Golden Globes 2020 nominations: The Irishman, Marriage Story and 1917 honoured
by Emma KellyThe Irishman and Once Upon A Time In Hollywood have dominated the nominations for the Golden Globes 2020.
The nominees for the first big movie and TV awards show of the season have been announced, and Martin Scorsese’s three-hour drama The Irishman is running away with the nods.
The Golden Globes take place on 5 January 2020.
Golden Globes 2020 nominations
FILM CATEGORIES
Best Motion Picture - Drama
1917
Marriage Story
Joker
The Two Popes
The Irishman
Best Motion Picture - Comedy/Musical
Dolemite Is My Name
Once Upon A Time In Hollywood
Best Performance by an Actor in a Motion Picture – Drama
Adam Driver (Marriage Story)
Joaquin Phoenix (Joker)
Jonathan Price
Best Performance by an Actress in a Motion Picture – Drama
Scarlett Johansson (Marriage Story)
Charlize Theron (Bombshell)
Renee Zellwegger (Judy)
Best Performance by an Actor in a Motion Picture – Musical or Comedy
Daniel Craig (Knives Out)
Roman Griffin Davis (Jojo Rabbit)
Leonardo DiCaprio (Once Upon A Time In Hollywood)
Taron Egerton (Rocketman)
Eddie Murphy (Dolemite Is My Name)
Best Performance by an Actress in a Motion Picture – Musical or Comedy
Ana de Armas (Knives Out)
Awkafina (The Farewell)
Cate Blanchett (Where'd You Go Bernadette)
Beanie Feldstein (Booksmart)
Emma Thompson (Late Night)
Best Performance by an Actor in a Supporting Role in Any Motion Picture
Tom Hanks (A Beautiful Day In The Neighbourhood)
Anthony Hopkins (The Two Popes)
Al Pacino (The Irishman)
Brad Pitt (Once Upon A Time In Hollywood)
Joe Pesci (The Irishman)
Best Performance by an Actress in a Supporting Role in Any Motion Picture
Kathy Bates
Annette Bening
Laura Dern (
Jennifer Lopez (Hustlers)
Margot Robbie (Bombshell)
Best Director – Motion Picture
Todd Phillips (Joker)
Martin Scorcese (The Irishman)
Quentin Tarantino (Once Upon A Time In Hollywood)
Bong Joon Ho (Parasite)
Sam Mendes (1917)
Best Screenplay – Motion Picture
Marriage Story
Parasite
The Two Popes
Once Upon A Time In Hollywood
The Irishman
Best Original Score – Motion Picture
Motherless Brooklyn
Little Women
Joker
1917
Marriage Story
Best Original Song – Motion Picture
Beautiful Ghosts (Cats)
I'm Gonna Love Me Again (Rocketman)
Into The Unknown (Frozen 2)
Spirit (The Lion King)
Stand Up (Harriet)
Best Animated Feature Film
Frozen 2
The Lion King
Missing Link
Toy Story 4
How To Train Your Dragon: The Hidden World
Best Foreign-Language Film
The Farewell
Les Miserables
Pain and Glory
Portrait of a Lady on Fire
Parasite
TV CATEGORIES
Best Television Series - Drama
Big Little Lies
The Crown
Killing Eve
Sucecssion
The Morning Show
Best Television Series - Musical or Comedy
Fleabag
The Komiskey Method
The Politician
Barry
The Marvellous Mrs Maisel
Best Miniseries or Television Film
Chernobyl
Catch 22
Fosse/Verdon
The Loudest Voice
Unbelievable
Best Actor - Television Series Drama
Kit Harington (Game Of Thrones)
Tobias Menzes (The Crown)
Billy Porter (Pose)
Brian Cox (Succession)
Rami Malek (Mr Robot)
Best Actor - Television Series Musical or Comedy
Best Actor - Miniseries or Television Film
Jared Harris (Chernobyl)
Chris Abbott
Sacha Baron Cohen (The Spy)
Russell Crowe (The Loudest Voice)
Sam Rockwell
Best Actress - Television Series Drama
Jennifer Aniston (The Morning Show)
Olivia Colman (The Crown)
Jodie Comer (Killing Eve)
Nicole Kidman (Big Little Lies)
Reese Witherspoon (The Morning Show)
Best Actress Television Series Musical or Comedy
Christina Applegate (Dead To Me)
Rachel Brosnahan (The Marvellous Mrs Maisel)
Kirsten Dunst (On Becoming A God in Central Florida)
Natasha Lyonne (Russian Doll)
Phoebe Waller-Bridge (Fleabag)
Best Actress - Miniseries or Television Film
Kaitlyn Dever (Unbelievable)
Joey King (The Act)
Helen Mirren (Catherine The Great)
Merrit Weaver (Unbelievable)
Michelle Williams (Fosse/Verdon)
Best Supporting Actor
Alan Arkin
Kieran Culkin
Andrew Scott
Henry Winkler
Stellan Skarsgaard
Best Supporting Actress
Patricia Arquette (The Act)
Helena Bonham Carter (The Crown)
Meryl Streep (
Emily Watson (Chernobyl)
Toni Collette (Unbelievable)
Got a showbiz story?
If you've got a celebrity story, video or pictures get in touch with the Metro.co.uk entertainment team by emailing us<EMAIL_ADDRESS>calling 020 3615 2145 or by visiting our Submit Stuff page - we'd love to hear from you.


The Indianapolis Ruby Users Group (Indy.rb) hosts a monthly hack night. Format is bring a problem and/or help someone solve a problem. I was lucky enough to work with @unixmonkey on the following refactor.
My rails application Team FBO has a rake task to purge stale database rows. A row of data shall be purged when it meets two conditions:
evaluation_code_id
greater than oneThe original rake task works correctly but requires two iterations to evaluate all rows. I need it to work in one iteration.
Here is the original code in app/lib/tasks/scrape.rake
:
@opportunities.each do |opportunity|
if (Date.today - opportunity.post_date).to_i > 5
if Evaluation.where(opportunity_id: opportunity.id).first
evaluations = Evaluation.where(opportunity_id: opportunity.id)
evaluations.each do |evaluation|
if evaluation.evaluation_code_id == 1 #purge only if team opportunity is not evaluated
evaluation.destroy
end
end
else #the opportunity is not part of any team's evaluation criteria
opportunity.destroy
end
end
end
These two lines mean the same thing. The evaluations.present?
is more expressive.
- if Evaluation.where(opportunity_id: opportunity.id).first
+ if opportunity.evaluations.present?
BTW, the +
and -
are change indicators from the git commit.
We extracted the methods out of .rake
and into a new file /app/models/concerns/purge_opportunities.rb
. During the extract, Dave asked me to explain what each block of code was doing. When I was able to articulate clearly, we named the method according to my verbal description. We also used a style convention of ?
for conditional methods (return true or false) and !
for methods that change data.
One block was eliminited in its entirity with a select statement:
- opportunities = Opportunity.all
- if (Date.today - opportunity.post_date).to_i > 5
+ Opportunity.where('post_date < ?', 5.days.ago)
Here is the refactored code in purge_opportunities.rb
. Much more expressive and easier to understand. And test.
class PurgeOpportunities
def purge_old_and_never_evaluated!
purge_never_evaluated!
purge_never_evaluated_opportunities!
end
# private
def old_opportunities
Opportunity.where('post_date < ?', 5.days.ago)
end
def purge_never_evaluated!
old_opportunities.each do |opportunity|
if has_team_evaluation?(opportunity)
opportunity.evaluations.each do |evaluation|
if evaluation_is_in_initial_state_of_not_evaluated?(evaluation)
evaluation.destroy
end
end
end
end
end
def purge_never_evaluated_opportunities!
old_opportunities.each do |opportunity|
unless has_team_evaluation?(opportunity)
opportunity.destroy
end
end
end
def has_team_evaluation?(opportunity)
opportunity.evaluations.present?
end
def evaluation_is_in_initial_state_of_not_evaluated?(evaluation)
evaluation.evaluation_code_id == 1 #purge only if team opportunity is not evaluated
end
end
We simplified the rake
task to create a PurgOpportunity object as follows:
task :clean => :environment do #heroku scheduler run this every 1 days
purger = PurgeOpportunities.new
purger.purge_old_and_never_evaluated!
end
Now that we had a properly structured object, we were able to write some tests in /app/tests/models/purge_opportunities_test.rb
.
require 'test_helper'
class PurgeOpportunitiesTest < ActiveSupport::TestCase
test "#purge_old_and_never_evaluated" do
old = Opportunity.create(opportunity: 'old', post_date: 6.days.ago)
bad = Opportunity.create(opportunity: 'bad', post_date: 4.weeks.ago)
bad.evaluations.create(evaluation_code_id: 1)
good = Opportunity.create(opportunity: 'good', post_date: Date.today)
good.evaluations.create(evaluation_code_id: 3)
old_good = Opportunity.create(opportunity: 'old_good', post_date: 1.month.ago)
old_good.evaluations.create(evaluation_code_id: 2)
purger = PurgeOpportunities.new
purger.purge_old_and_never_evaluated!
all = Opportunity.all
assert !all.include?(old), 'old is not gone :('
assert !all.include?(bad), 'bad is not gone :('
assert all.include?(good), 'good not here :('
assert all.include?(old_good), 'old_good not here :('
end
end
Dave took three hours out of his Tuesday evening to help a casual acquaintance write better code. Indy.rb’s culture of helping others get better should not surprise rubyists. But its a special thing. And its what make so ruby powerful.
I look forward to the day when I get to help someone else get better.


Haptic Games Bring Fun To The Visually Impaired
by Kristina PanosNo matter what your parents might say, games are good for us. They teach us to manage resources and give us dopamine rewards just like eating and mating do. Even if you’re no good at games in general, they are still a fun distraction from life.
There are so many games out there that could be enjoyed by the visually impaired, except that they rely on visuals. For example, you can play Yahtzee with nothing more than five dice, a cup, pencil and paper, and knowledge of the rules and scoring. The biggest obstacles are differentiating the dice from each other and keeping score.
One of our esteemed 2019 Hackaday Prize Top 20 Finalists is [JanThar]’s Haptic Games. [JanThar]’s growing collection of games uses 3D printing, vibration motors, and RFID to replace visual cues with sensory feedback. Yahtzee-wise, there’s a set of printed dice and scorecards. The scorecards use spherical magnets and an abacus layout. [JanThar] is also working on a Memory game to teach Braille, though it could be adapted to pure Braille for the visually impaired. Each game piece contains an RFID chip, so players can hold it up to a reader to check what they have.
Our favorite might be the PONG game that’s built on [JanThar]’s 2017 Hackaday Prize entry, the HaptiVision vest. Through the magic of a 16×8 field of vibration motors, players can track the ball’s movement across their torso and control the paddles with a sliders. There’s a brief demo of the games after the break.
The HackadayPrize2019 is Sponsored by:


Multiple Popup Forms
Contact Us
Send a Compliant Form
×
Contact Us
Message
Submit
×
Complaint form
Message
Submit


Tests that the 'kind' attribute is set properly and that cues are only visible when 'kind' is set to 'captions' or 'subtitles'.


{% extends 'base.html' %} {% block content %}
Please add a profile to aboard desired hood.
Contact: {{profile.email}}
Neighbourhood: {{profile.neighborhood.name}}


Nexus
Meet the Creator
Welcome to Nexus
Nexus is a powerfully simple web app that helps you organize your thoughts and keep track of tasks that you need to complete throughout the day.
Try It today!


Are you a host or organizer and we forgot about you? Haven't found some cool event below? Suggest it here!


Colors
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
public enum Colors
Color palette helper accessing colors and it’s variations.
-
red and it’s associated variations
Declaration
Swift
case red(RedSubType)
-
green and it’s associated variations
Declaration
Swift
case green(GreenSubType)
-
blue and it’s associated variations
Declaration
Swift
case blue(BlueSubType)
-
gray and it’s associated variations
Declaration
Swift
case gray(GraySubType)
-
teal color
Declaration
Swift
case teal
-
lavender color
Declaration
Swift
case lavendar
-
orange color
Declaration
Swift
case orange
-
black color
Declaration
Swift
case black
-
yellow and it’s associated variations
Declaration
Swift
case yellow(YellowSubType)
-
cyan color
Declaration
Swift
case cyan
-
ploar color
Declaration
Swift
case polar
-
Color palette for all gray variations
See moreDeclaration
Swift
public enum GraySubType
-
Color palette for all green variations
See moreDeclaration
Swift
public enum GreenSubType
-
Color palette for all blue variations
See moreDeclaration
Swift
public enum BlueSubType
-
Color palette for all yellow variations
See moreDeclaration
Swift
public enum YellowSubType
-
Color palette for all red variations
See moreDeclaration
Swift
public enum RedSubType
-
alias to
Color
Declaration
Swift
public typealias RawValue = Color
-
returns the desired color based on the switch case matching criteria
Declaration
Swift
public var rawValue: RawValue { get }


germination seed species (.) temperature seeds drought community desert Artemisia size stress Seed Venable, conditions water Baskin, response study {border-style Forb environmental px;} #ffffff;} Ecology, germinate large responses Ecology Westoby, different seedling Germination Perennial high mass Allium low percentage seasonal dormancy plant regime regimes seedlings temperatures variation (Figure Annual steppe time Bassia However, Moles, Plant climate important related small traits −., American China Kochia Therefore, change establishment fitness mean plants px; results structure {font-family ./j.-...x Academy Neopallasia correlated data emergence expected font-size germinated potentials prastrata, scoparia, stress. using Desert Effect Inner Liu, Mongolia Poschlod, Potentilla Sciences annua, annual dasyphylla, differ double; early effect environments evolutionary growth increased potential ramosum, risk significant species, species‐specific steppe. survival temperate tree winter (Baskin (a) Brown, Center Chinese Eriksson, Evolution, Fenner, Figure Mean Naturalist, Research Table Vegetation [], ability addition, border-color border-width does ecology effects environment evolution highest life niche regeneration relationships showing soil solid; tanacetifolia used variable {font-style {font-weight < (Leishman (b) /°C, Bohrer, Botany, Bu, Casas, Du, Falster, Furthermore, Heteropappus Kentucky Lagochilus New Phytologist, Plateau Prataculture, Research, Simons, Sonoran Species Thus, Willis, Wright, annuals annuals. bold comparative conditions. consistent courier; determined determining em; evidence growing hedging heterogeneous higher increase increasing length level, light pectinata percentages phylogenetic population precipitation predation predicting produce pt;} relationship relatively respectively. season shallow significantly size. species. spring strategies strategy study, suggest understanding varying width


Contents
WebOb is an extraction and refinement of pieces from Paste. It is under active development. Discussion should happen on the Paste mailing lists, and bugs can go on the Paste trac instance.
WebOb is released under an MIT-style license.
WebOb is in a Mercurial repository at http://bitbucket.org/ianb/webob/, and installable via easy_install webob==dev. You can check it out with:
$ hg clone http://bitbucket.org/ianb/webob
WebOb provides objects for HTTP requests and responses. Specifically it does this by wrapping the WSGI request environment and response status/headers/app_iter(body).
The request and response objects provide many conveniences for parsing HTTP request and forming HTTP responses. Both objects are read/write: as a result, WebOb is also a nice way to create HTTP requests and parse HTTP responses; however, we won’t cover that use case in this document. The reference documentation shows many examples of creating requests.
The request object is a wrapper around the WSGI environ dictionary. This dictionary contains keys for each header, keys that describe the request (including the path and query string), a file-like object for the request body, and a variety of custom keys. You can always access the environ with req.environ.
Some of the most important/interesting attributes of a request object:
Also, for standard HTTP request headers there are usually attributes, for instance: req.accept_language, req.content_length, req.user_agent, as an example. These properties expose the parsed form of each header, for whatever parsing makes sense. For instance, req.if_modified_since returns a datetime object (or None if the header is was not provided). Details are in the Request reference.
In addition to these attributes, there are several ways to get the URL of the request. I’ll show various values for an example URL http://localhost/app-root/doc?article_id=10, where the application is mounted at http://localhost/app-root.
There are several methods but only a few you’ll use often:
Many of the properties in the request object will return unicode values if the request encoding/charset is provided. The client can indicate the charset with something like Content-Type: application/x-www-form-urlencoded; charset=utf8, but browsers seldom set this. You can set the charset with req.charset = 'utf8', or during instantiation with Request(environ, charset='utf8'). If you subclass ``Request you can also set charset as a class-level attribute.
If it is set, then req.POST, req.GET, req.params, and req.cookies will contain unicode strings. Each has a corresponding req.str_* (like req.str_POST) that is always str and never unicode.
The response object looks a lot like the request object, though with some differences. The request object wraps a single environ object; the response object has three fundamental parts (based on WSGI):
Everything else in the object derives from this underlying state. Here’s the highlights:
Like the request, most HTTP response headers are available as properties. These are parsed, so you can do things like response.last_modified = os.path.getmtime(filename).
The details are available in the extracted Response documentation.
Of course most of the time you just want to make a response. Generally any attribute of the response can be passed in as a keyword argument to the class; e.g.:
response = Response(body='hello world!', content_type='text/plain')
The status defaults to '200 OK'. The content_type does not default to anything, though if you subclass Response and set default_content_type you can override this behavior.
To facilitate error responses like 404 Not Found, the module webob.exc contains classes for each kind of error response. These include boring but appropriate error bodies.
Each class is named webob.exc.HTTP*, where * is the reason for the error. For instance, webob.exc.HTTPNotFound. It subclasses Response, so you can manipulate the instances in the same way. A typical example is:
response = HTTPNotFound('There is no such resource')
# or:
response = HTTPMovedPermanently(location=new_url)
These are not exceptions unless you are using Python 2.5+, because they are new-style classes which are not allowed as exceptions until Python 2.5. To get an exception object use response.exception. You can use this like:
try:
... stuff ...
raise HTTPNotFound('No such resource').exception
except HTTPException, e:
return e(environ, start_response)
The exceptions are still WSGI applications, but you cannot set attributes like content_type, charset, etc. on these exception objects.
Several parts of WebOb use a “multidict”; this is a dictionary where a key can have multiple values. The quintessential example is a query string like ?pref=red&pref=blue; the pref variable has two values: red and blue.
In a multidict, when you do request.GET['pref'] you’ll get back only 'blue' (the last value of pref). Sometimes returning a string, and sometimes returning a list, is the cause of frequent exceptions. If you want all the values back, use request.GET.getall('pref'). If you want to be sure there is one and only one value, use request.GET.getone('pref'), which will raise an exception if there is zero or more than one value for pref.
When you use operations like request.GET.items() you’ll get back something like [('pref', 'red'), ('pref', 'blue')]. All the key/value pairs will show up. Similarly request.GET.keys() returns ['pref', 'pref']. Multidict is a view on a list of tuples; all the keys are ordered, and all the values are ordered.
I haven’t figured out the example I want to use here. The file-serving example shows how to do more advanced HTTP techniques, while the comment middleware example shows middleware. For applications it’s more reasonable to use WebOb in the context of a larger framework. Pylons uses WebOb in 0.9.7+.


Which of the following would you like to make your edit in?
Please choose a date to continue to edit its data.
Loading...Editing {{currentlyEditing}} data on {{silingTypeToEdit.data ? silingTypeToEdit.data.date : ""}} ({{silingTypeToEdit.entryId}}):


Starting this saturday we will have the first ROM builds come out in a long while. These builds will be based off of the latest version of Android [5.1.1] and Cyanogenmod 12.1. While these builds will be fairly feature light at first, more features are will be added in as time goes on.
The following devices should have builds by Saturday though one or two may not:
- Android One [Sprout]
- Samsung Galaxy S3 [I9300]
- Nexus 6 [Shamu]
- Moto X [Ghost]
- Sony Xperia SP [Huashan]
- Samsung Galaxy S4 [Jflte]
- Moto G 2013 [Falcon]
- Samsung Galaxy S4 [I9505]
Some of you may also want to know why we havent had any builds in a while. This is because some of us had exams and other personal maters that we had to attend to resulting in the builds being delayed to the summer which is now.
Anyway we should have the first builds coming out tomorrow so get ready to flash!


|
cds
1.5.0
|
Cuckoo hash set. More...
#include <cds/container/cuckoo_set.h>
Public Types | |
| typedef T | value_type |
| value type stored in the container | |
| typedef Traits | options |
| traits | |
| typedef options::hash | hash |
| hash functor tuple wrapped for internal use | |
| typedef base_class::hash_tuple_type | hash_tuple_type |
| Type of hash tuple. | |
| typedef base_class::mutex_policy | mutex_policy |
| Concurrent access policy, see cuckoo::type_traits::mutex_policy. | |
| typedef base_class::stat | stat |
| internal statistics type | |
| typedef base_class::key_equal_to | key_equal_to |
| Key equality functor; used only for unordered probe-set. | |
| typedef base_class::key_comparator | key_comparator |
| key comparing functor based on opt::compare and opt::less option setter. Used only for ordered probe set | |
| typedef base_class::allocator | allocator |
| allocator type used for internal bucket table allocations | |
|
typedef std::conditional < std::is_same< typename options::node_allocator, opt::none >::value, allocator, typename options::node_allocator > ::type | node_allocator |
| Node allocator type. | |
| typedef options::item_counter | item_counter |
| item counter type | |
Public Member Functions | |
| CuckooSet () | |
| Default constructor. More... | |
| CuckooSet (size_t nInitialSize, unsigned int nProbesetSize, unsigned int nProbesetThreshold=0) | |
| Constructs the set object with given probe set size and threshold. More... | |
| CuckooSet (hash_tuple_type const &h) | |
| Constructs the set object with given hash functor tuple. More... | |
| CuckooSet (size_t nInitialSize, unsigned int nProbesetSize, unsigned int nProbesetThreshold, hash_tuple_type const &h) | |
| Constructs the set object with given probe set properties and hash functor tuple. More... | |
| CuckooSet (hash_tuple_type &&h) | |
| Constructs the set object with given hash functor tuple (move semantics) More... | |
| CuckooSet (size_t nInitialSize, unsigned int nProbesetSize, unsigned int nProbesetThreshold, hash_tuple_type &&h) | |
| Constructs the set object with given probe set properties and hash functor tuple (move semantics) More... | |
| ~CuckooSet () | |
| Destructor clears the set. | |
| template<typename Q > | |
| bool | insert (Q const &val) |
| Inserts new node. More... | |
| template<typename Q , typename Func > | |
| bool | insert (Q const &val, Func f) |
| Inserts new node. More... | |
| template<typename... Args> | |
| bool | emplace (Args &&...args) |
Inserts data of type value_type constructed with std::forward<Args>(args)... More... | |
| template<typename Q , typename Func > | |
| std::pair< bool, bool > | ensure (Q const &val, Func func) |
Ensures that the val exists in the set. More... | |
| template<typename Q > | |
| bool | erase (Q const &key) |
Delete key from the set. More... | |
| template<typename Q , typename Predicate > | |
| bool | erase_with (Q const &key, Predicate pred) |
Deletes the item from the list using pred predicate for searching. More... | |
| template<typename Q , typename Func > | |
| bool | erase (Q const &key, Func f) |
Delete key from the set. More... | |
| template<typename Q , typename Predicate , typename Func > | |
| bool | erase_with (Q const &key, Predicate pred, Func f) |
Deletes the item from the list using pred predicate for searching. More... | |
| template<typename Q , typename Func > | |
| bool | find (Q &val, Func f) |
Find the key val . More... | |
| template<typename Q , typename Predicate , typename Func > | |
| bool | find_with (Q &val, Predicate pred, Func f) |
Find the key val using pred predicate for comparing. More... | |
| template<typename Q , typename Func > | |
| bool | find (Q const &val, Func f) |
Find the key val . More... | |
| template<typename Q , typename Predicate , typename Func > | |
| bool | find_with (Q const &val, Predicate pred, Func f) |
Find the key val using pred predicate for comparing. More... | |
| template<typename Q > | |
| bool | find (Q const &val) |
Find the key val . More... | |
| template<typename Q , typename Predicate > | |
| bool | find_with (Q const &val, Predicate pred) |
Find the key val using pred predicate for comparing. More... | |
| void | clear () |
| Clears the set. More... | |
| bool | empty () const |
| Checks if the set is empty. More... | |
| size_t | size () const |
| Returns item count in the set. | |
| size_t | bucket_count () const |
| Returns the size of hash table. More... | |
| size_t | lock_count () const |
| Returns lock array size. | |
| stat const & | statistics () const |
| Returns const reference to internal statistics. | |
|
mutex_policy::statistics_type const & | mutex_policy_statistics () const |
| Returns const reference to mutex policy internal statistics. | |
Static Public Attributes | |
| static bool const | c_isSorted = base_class::c_isSorted |
| whether the probe set should be ordered | |
| static size_t const | c_nArity = base_class::c_nArity |
| the arity of cuckoo hashing: the number of hash functors provided; minimum 2. | |
| static unsigned int const | c_nDefaultProbesetSize = base_class::c_nDefaultProbesetSize |
| default probeset size | |
| static size_t const | c_nDefaultInitialSize = base_class::c_nDefaultInitialSize |
| default initial size | |
| static unsigned int const | c_nRelocateLimit = base_class::c_nRelocateLimit |
| Count of attempts to relocate before giving up. | |
Additional Inherited Members | |
| Protected Types inherited from cds::intrusive::CuckooSet< T, Traits > | |
| typedef T | value_type |
| The value type stored in the set. | |
| typedef Traits | options |
| Set traits. | |
| typedef options::hook | hook |
| hook type | |
| typedef hook::node_type | node_type |
| node type | |
|
typedef get_node_traits < value_type, node_type, hook > ::type | node_traits |
| node traits | |
| typedef options::hash | hash |
| hash functor tuple wrapped for internal use | |
| typedef hash::hash_tuple_type | hash_tuple_type |
| Type of hash tuple. | |
| typedef options::stat | stat |
| internal statistics type | |
| typedef options::mutex_policy | original_mutex_policy |
| Concurrent access policy, see cuckoo::type_traits::mutex_policy. | |
| typedef original_mutex_policy::template rebind_statistics< typename std::conditional< std::is_same < stat, cuckoo::empty_stat > ::value,typename original_mutex_policy::empty_stat,typename original_mutex_policy::real_stat > ::type >::other | mutex_policy |
| Actual mutex policy. More... | |
|
typedef opt::details::make_equal_to < value_type, options,!c_isSorted > ::type | key_equal_to |
| Key equality functor; used only for unordered probe-set. | |
|
typedef opt::details::make_comparator < value_type, options >::type | key_comparator |
| key comparing functor based on opt::compare and opt::less option setter. Used only for ordered probe set | |
| typedef options::allocator | allocator |
| allocator type | |
| typedef options::item_counter | item_counter |
| item counter type | |
| typedef options::disposer | disposer |
| node disposer | |
| Protected Member Functions inherited from cds::intrusive::CuckooSet< T, Traits > | |
| CuckooSet () | |
| Default constructor. More... | |
| CuckooSet (size_t nInitialSize, unsigned int nProbesetSize, unsigned int nProbesetThreshold=0) | |
| Constructs the set object with given probe set size and threshold. More... | |
| CuckooSet (hash_tuple_type const &h) | |
| Constructs the set object with given hash functor tuple. More... | |
| CuckooSet (size_t nInitialSize, unsigned int nProbesetSize, unsigned int nProbesetThreshold, hash_tuple_type const &h) | |
| Constructs the set object with given probe set properties and hash functor tuple. More... | |
| CuckooSet (hash_tuple_type &&h) | |
| Constructs the set object with given hash functor tuple (move semantics) More... | |
| CuckooSet (size_t nInitialSize, unsigned int nProbesetSize, unsigned int nProbesetThreshold, hash_tuple_type &&h) | |
| Constructs the set object with given probe set properties and hash functor tuple (move semantics) More... | |
| ~CuckooSet () | |
| Destructor. | |
| bool | insert (value_type &val) |
| Inserts new node. More... | |
| template<typename Func > | |
| bool | insert (value_type &val, Func f) |
| Inserts new node. More... | |
| template<typename Func > | |
| std::pair< bool, bool > | ensure (value_type &val, Func func) |
Ensures that the val exists in the set. More... | |
| bool | unlink (value_type &val) |
Unlink the item val from the set. More... | |
| template<typename Q > | |
| value_type * | erase (Q const &val) |
| Deletes the item from the set. More... | |
| template<typename Q , typename Predicate > | |
| value_type * | erase_with (Q const &val, Predicate pred) |
Deletes the item from the set using pred predicate for searching. More... | |
| template<typename Q , typename Func > | |
| value_type * | erase (Q const &val, Func f) |
| Delete the item from the set. More... | |
| template<typename Q , typename Predicate , typename Func > | |
| value_type * | erase_with (Q const &val, Predicate pred, Func f) |
Deletes the item from the set using pred predicate for searching. More... | |
| template<typename Q , typename Func > | |
| bool | find (Q &val, Func f) |
Find the key val . More... | |
| template<typename Q , typename Predicate , typename Func > | |
| bool | find_with (Q &val, Predicate pred, Func f) |
Find the key val using pred predicate for comparing. More... | |
| template<typename Q , typename Func > | |
| bool | find (Q const &val, Func f) |
Find the key val . More... | |
| template<typename Q , typename Predicate , typename Func > | |
| bool | find_with (Q const &val, Predicate pred, Func f) |
Find the key val using pred predicate for comparing. More... | |
| template<typename Q > | |
| bool | find (Q const &val) |
Find the key val . More... | |
| template<typename Q , typename Predicate > | |
| bool | find_with (Q const &val, Predicate pred) |
Find the key val using pred predicate for comparing. More... | |
| void | clear () |
| Clears the set. More... | |
| template<typename Disposer > | |
| void | clear_and_dispose (Disposer oDisposer) |
Clears the set and calls disposer for each item. More... | |
| bool | empty () const |
| Checks if the set is empty. More... | |
| size_t | size () const |
| Returns item count in the set. | |
| size_t | bucket_count () const |
| Returns the size of hash table. More... | |
| size_t | lock_count () const |
| Returns lock array size. | |
| stat const & | statistics () const |
| Returns const reference to internal statistics. | |
|
mutex_policy::statistics_type const & | mutex_policy_statistics () const |
| Returns const reference to mutex policy internal statistics. | |
| Protected Attributes inherited from cds::intrusive::CuckooSet< T, Traits > | |
| bucket_entry * | m_BucketTable [c_nArity] |
| Bucket tables. | |
| size_t | m_nBucketMask |
| Hash bitmask; bucket table size minus 1. | |
| unsigned int const | m_nProbesetSize |
| Probe set size. | |
| unsigned int const | m_nProbesetThreshold |
| Probe set threshold. | |
| hash | m_Hash |
| Hash functor tuple. | |
| mutex_policy | m_MutexPolicy |
| concurrent access policy | |
| item_counter | m_ItemCounter |
| item counter | |
| stat | m_Stat |
| internal statistics | |
| Static Protected Attributes inherited from cds::intrusive::CuckooSet< T, Traits > | |
| static bool const | c_isSorted |
| whether the probe set should be ordered More... | |
| static size_t const | c_nArity = hash::size |
| the arity of cuckoo hashing: the number of hash functors provided; minimum 2. | |
| static unsigned int const | c_nDefaultProbesetSize = 4 |
| default probeset size | |
| static size_t const | c_nDefaultInitialSize = 16 |
| default initial size | |
| static unsigned int const | c_nRelocateLimit = c_nArity * 2 - 1 |
| Count of attempts to relocate before giving up. | |
Cuckoo hash set.
Source
About Cuckoo hashing
[From "The Art of Multiprocessor Programming"] Cuckoo hashing is a hashing algorithm in which a newly added item displaces any earlier item occupying the same slot. For brevity, a table is a k-entry array of items. For a hash set f size N = 2k we use a two-entry array of tables, and two independent hash functions, h0, h1: KeyRange -> 0,...,k-1
mapping the set of possible keys to entries in he array. To test whether a value x
is in the set, find(x)
tests whether either table[0][h0(x)]
or table[1][h1(x)]
is equal to x
. Similarly, erase(x)
checks whether x
is in either table[0][h0(x)]
or table[1][h1(x)]
, ad removes it if found.
The insert(x)
successively "kicks out" conflicting items until every key has a slot. To add x
, the method swaps x
with y
, the current occupant of table[0][h0(x)]
. If the prior value was NULL
, it is done. Otherwise, it swaps the newly nest-less value y
for the current occupant of table[1][h1(y)]
in the same way. As before, if the prior value was NULL
, it is done. Otherwise, the method continues swapping entries (alternating tables) until it finds an empty slot. We might not find an empty slot, either because the table is full, or because the sequence of displacement forms a cycle. We therefore need an upper limit on the number of successive displacements we are willing to undertake. When this limit is exceeded, we resize the hash table, choose new hash functions and start over.
For concurrent cuckoo hashing, rather than organizing the set as a two-dimensional table of items, we use two-dimensional table of probe sets, where a probe set is a constant-sized set of items with the same hash code. Each probe set holds at most PROBE_SIZE
items, but the algorithm tries to ensure that when the set is quiescent (i.e no method call in progress) each probe set holds no more than THRESHOLD < PROBE_SET
items. While method calls are in-flight, a probe set may temporarily hold more than THRESHOLD
but never more than PROBE_SET
items.
In current implementation, a probe set can be defined either as a (single-linked) list or as a fixed-sized vector, optionally ordered.
In description above two-table cuckoo hashing (k = 2
) has been considered. We can generalize this approach for k >= 2
when we have k
hash functions h[0], ... h[k-1]
and k
tables table[0], ... table[k-1]
.
The search in probe set is linear, the complexity is O(PROBE_SET)
. The probe set may be ordered or not. Ordered probe set can be a little better since the average search complexity is O(PROBE_SET/2)
. However, the overhead of sorting can eliminate a gain of ordered search.
The probe set is ordered if opt::compare or opt::less is specified in CuckooSet
declaration. Otherwise, the probe set is unordered and CuckooSet
must contain opt::equal_to option.
Template arguments:
T
- the type stored in the set.Traits
- type traits. See cuckoo::type_traits for explanation. It is possible to declare option-based set with cuckoo::make_traits metafunction result as Traits
template argument.Template argument list Options
... of cuckoo::make_traits metafunction are:
i,j: i != j => h[i](x) != h[j](x)
. The hash functors are passed as std::tuple< H1, H2, ... Hn >
. The number of hash functors specifies the number k
- the count of hash tables in cuckoo hashing. If the compiler supports variadic templates then k is unlimited, otherwise up to 10 different hash functors are supported.std::equal_to
. If this functor is defined then the probe-set will be unordered. If opt::compare or opt::less option is specified too, then the probe-set will be ordered and opt::equal_to will be ignored.std::less<T>
. If opt::compare or opt::less option is specified, then the probe-set will be ordered.CDS_DEFAULT_ALLOCATOR
false
.cuckoo::list
or cuckoo::vector<Capacity>
, Default is cuckoo::list
.Examples
Cuckoo-set with list-based unordered probe set and storing hash values
If we provide compare
function instead of equal_to
for my_data
we get as a result a cuckoo set with ordered probe set that may improve performance. Example for ordered vector-based probe-set:
|
inline |
Default constructor.
Initial size = c_nDefaultInitialSize
Probe set size:
probeset_type
is cuckoo::list
Capacity
if probeset_type
is cuckoo::vector<Capacity>
Probe set threshold = probe set size - 1
|
inline |
Constructs the set object with given probe set size and threshold.
If probe set type is cuckoo::vector<Capacity>
vector then nProbesetSize
should be equal to vector's Capacity
.
| nInitialSize | Initial set size; if 0 - use default initial size c_nDefaultInitialSize |
| nProbesetSize | probe set size |
| nProbesetThreshold | probe set threshold, nProbesetThreshold < nProbesetSize . If 0, nProbesetThreshold = nProbesetSize - 1 |
|
inline |
Constructs the set object with given hash functor tuple.
The probe set size and threshold are set as default, see CuckooSet()
| h | hash functor tuple of type std::tuple<H1, H2, ... Hn> where n == c_nArity |
|
inline |
Constructs the set object with given probe set properties and hash functor tuple.
If probe set type is cuckoo::vector<Capacity>
vector then nProbesetSize
should be equal to vector's Capacity
.
| nInitialSize | Initial set size; if 0 - use default initial size c_nDefaultInitialSize |
| nProbesetSize | probe set size |
| nProbesetThreshold | probe set threshold, nProbesetThreshold < nProbesetSize . If 0, nProbesetThreshold = nProbesetSize - 1 |
| h | hash functor tuple of type std::tuple<H1, H2, ... Hn> where n == c_nArity |
|
inline |
Constructs the set object with given hash functor tuple (move semantics)
The probe set size and threshold are set as default, see CuckooSet()
| h | hash functor tuple of type std::tuple<H1, H2, ... Hn> where n == c_nArity |
|
inline |
Constructs the set object with given probe set properties and hash functor tuple (move semantics)
If probe set type is cuckoo::vector<Capacity>
vector then nProbesetSize
should be equal to vector's Capacity
.
| nInitialSize | Initial set size; if 0 - use default initial size c_nDefaultInitialSize |
| nProbesetSize | probe set size |
| nProbesetThreshold | probe set threshold, nProbesetThreshold < nProbesetSize . If 0, nProbesetThreshold = nProbesetSize - 1 |
| h | hash functor tuple of type std::tuple<H1, H2, ... Hn> where n == c_nArity |
|
inline |
Returns the size of hash table.
The hash table size is non-constant and can be increased via resizing.
|
inline |
Clears the set.
The function erases all items from the set.
|
inline |
Inserts data of type value_type constructed with std::forward<Args>(args)...
Returns true
if inserting successful, false
otherwise.
This function is available only for compiler that supports variadic template and move semantics
|
inline |
Checks if the set is empty.
Emptiness is checked by item counting: if item count is zero then the set is empty.
|
inline |
Ensures that the val
exists in the set.
The operation performs inserting or changing data.
If the val
key not found in the set, then the new item created from val
is inserted into the set. Otherwise, the functor func
is called with the item found. The functor Func
should be a function with signature:
or a functor:
with arguments:
bNew
- true
if the item has been inserted, false
otherwiseitem
- item of the setval
- argument val
passed into the ensure
functionThe functor can change non-key fields of the item
.
You can pass func
argument by value or by reference using boost::ref
.
Returns std::pair<bool, bool>
where first
is true if operation is successfull, second
is true if new item has been added or false
if the item with val
key already exists.
|
inline |
Delete key
from the set.
Since the key of set's item type value_type is not explicitly specified, template parameter Q
defines the key type searching in the list. The set item comparator should be able to compare the type value_type
and the type Q
.
Return true
if key is found and deleted, false
otherwise
|
inline |
Delete key
from the set.
The function searches an item with key key
, calls f
functor and deletes the item. If key
is not found, the functor is not called.
The functor Func
interface is:
The functor can be passed by value or by reference using boost:ref
Return true
if key is found and deleted, false
otherwise
|
inline |
Deletes the item from the list using pred
predicate for searching.
The function is an analog of erase(Q const&) but pred
is used for key comparing. If cuckoo set is ordered, then Predicate
should have the interface and semantics like std::less
. If cuckoo set is unordered, then Predicate
should have the interface and semantics like std::equal_to
. Predicate
must imply the same element order as the comparator used for building the set.
|
inline |
Deletes the item from the list using pred
predicate for searching.
The function is an analog of erase(Q const&, Func) but pred
is used for key comparing. If you use ordered cuckoo set, then Predicate
should have the interface and semantics like std::less
. If you use unordered cuckoo set, then Predicate
should have the interface and semantics like std::equal_to
. Predicate
must imply the same element order as the comparator used for building the set.
|
inline |
Find the key val
.
The function searches the item with key equal to val
and calls the functor f
for item found. The interface of Func
functor is:
where item
is the item found, val
is the find
function argument.
You can pass f
argument by value or by reference using boost::ref
or cds::ref.
The functor can change non-key fields of item
. The val
argument is non-const since it can be used as f
functor destination i.e., the functor can modify both arguments.
The type Q
can differ from value_type of items storing in the container. Therefore, the value_type
should be comparable with type Q
.
The function returns true
if val
is found, false
otherwise.
|
inline |
Find the key val
.
The function searches the item with key equal to val
and calls the functor f
for item found. The interface of Func
functor is:
where item
is the item found, val
is the find
function argument.
You can pass f
argument by value or by reference using boost::ref
or cds::ref.
The functor can change non-key fields of item
.
The type Q
can differ from value_type of items storing in the container. Therefore, the value_type
should be comparable with type Q
.
The function returns true
if val
is found, false
otherwise.
|
inline |
Find the key val
.
The function searches the item with key equal to val
and returns true
if it is found, and false
otherwise.
Note the hash functor specified for class Traits
template parameter should accept a parameter of type Q
that can be not the same as value_type.
|
inline |
Find the key val
using pred
predicate for comparing.
The function is an analog of find(Q&, Func) but pred
is used for key comparison. If you use ordered cuckoo set, then Predicate
should have the interface and semantics like std::less
. If you use unordered cuckoo set, then Predicate
should have the interface and semantics like std::equal_to
. pred
must imply the same element order as the comparator used for building the set.
|
inline |
Find the key val
using pred
predicate for comparing.
The function is an analog of find(Q const&, Func) but pred
is used for key comparison. If you use ordered cuckoo set, then Predicate
should have the interface and semantics like std::less
. If you use unordered cuckoo set, then Predicate
should have the interface and semantics like std::equal_to
. pred
must imply the same element order as the comparator used for building the set.
|
inline |
Find the key val
using pred
predicate for comparing.
The function is an analog of find(Q const&) but pred
is used for key comparison. If you use ordered cuckoo set, then Predicate
should have the interface and semantics like std::less
. If you use unordered cuckoo set, then Predicate
should have the interface and semantics like std::equal_to
. pred
must imply the same element order as the comparator used for building the set.
|
inline |
Inserts new node.
The function creates a node with copy of val
value and then inserts the node created into the set.
The type Q
should contain as minimum the complete key for the node. The object of value_type should be constructible from a value of type Q
. In trivial case, Q
is equal to value_type.
Returns true
if val
is inserted into the set, false
otherwise.
|
inline |
Inserts new node.
The function allows to split creating of new item into two part:
f
functor to initialize value-field of new item .The functor signature is:
where item
is the item inserted.
The type Q
can differ from value_type of items storing in the set. Therefore, the value_type
should be constructible from type Q
.
The user-defined functor is called only if the inserting is success. It can be passed by reference using boost::ref


PB-F MAVS cells (Fig protein virus WSN expression influenza aggregation viruses []. HEKT mitochondrial proteins transfected Fig IFN type infected analysis hours, Influenza mitochondria blot effect lane performed degradation level activation antiviral {border-style Biology PB-F, Western innate signaling viral -well SDS-PAGE avian described harvested interaction plates production proteasomal px;} #ffffff;} Sendai Viral aggregates infection mRNA response MAVS. activity analyzed expressed suppression used Cell JC- PB-F. THP- cells. construct pathogens IFNβ SDD-AGE buffer levels lysosomal pathogenic similar total (HN) PB-F-Flag Pathogens RNA TRIM hours lanes reporter sciences treated using A). MAVS, Orthomyxoviruses TBK TRAF WSN, [], anti-Flag followed human results seen suppressive GAPDH However, K-polyubiquitination RIPA Sciences degradation. form immune interferon known recombinant suppressed vector C). Cells Immunol. Medical Microbial Virol. assay did early indicated life min. observed previously sample suppresses ubiquitin < (A) (B) Fig). Medicine Organisms RIG-I TRIM-MAVS Viruses adaptor amyloid anti-parallel attenuated experiments. highly hpi lysis membrane mouse replication sequence stained strain virus: (C) Mitotracker Mol Protein TRAF, acid affect anti-V clusters control data difference expressing extraction higher hpi, including independent leading min px; review target virulence viruses. {font-family –). ./JVI.- B). Biol. IKKε Life Microbiology [–]. aggregated co-transfected confocal consistent contrast, cytokine dye factor font-size formation high host ligase novel pEF-Bos-Flag-MAVS pairing panels presence pronounced required segments sequences staining ubiquitination vRNA virus. (Figs (I:C) ./jimmunol. FAF H-ΔF Hong MOI Notably, PB, RT-qPCR Red Research Suppression TNFα Virus aggregation. al.The amino anti-MAVS assay. bars cell construct. constructs double; energy induction interact mechanism mutants pandemic poly potential proinflammatory promoter promotes represent residue. sheet showed steady-state structure study subjected subtype-specific suppress –.e. CMXRos Cell. Fund IRF-D MDCK Nat PASTA PB-F-expressing Pathology Sci absence affected anti-Myc bafilomycin border-color border-width clustered co-immunoprecipitation colocalized constructs, cross cross-β dishes dual-luciferase essential features fluorescent function high-molecular-mass immunity inhibition intensity lower luciferase mRNA, marker minimally mitochondria. multiple pathogenicity plasmid probed prominent prone propensity putative reduced remained residues respiratory response. samples segment served shown solid; solubility species suggested targeting test transfection treatment unaggregated viruses: washed {font-style {font-weight ΔΨm μg/mL (D) (H) (IP: (S) (TIF) ./ncomms A), Acad CCCP Chem. Click Cruz), D). DF- EMBO Health LINK MAVS-TRIM MAVS-mediated Mitochondrial Natl PBS PaleseP. Paramyxoviruses: Proc Santa Thus, USA. VargaZT, activated additional aggregate aggregation-defective aggregation-prone al.MAVS analysis. antibody bold calculated centrifugation comparative compared constructs. counterpart courier; coverslips decrease degradation, destabilization destabilizing detected different disease distinct e./embj. em; enhanced extracted file. findings fissioned fixed genetic http://dx.doi.org/./Health humans, immunity. induced induces influence inhibitor inhibits knockout laboratory likely lines localization lysate mammalian means media molecular overexpressed pCAGEN-myc-MAVS pairings parallel pattern point potent predicted presented propagation properties proteasome proteolysis pt;} ratio relative reverse robust severe signal staining. triplicate verify


Input variables Patient age Gender Female Male Patient category NSND SD Continuance of risk habits following diagnosis Yes No Not applicable Previous malignancy Solid - Head and Neck Solid - Others Hematologic malignancy No malignancy Charlson comorbidity index Hypertension status Yes No Diabetes mellitus status Yes No Hyperlipidemia status Yes No Autoimmune disease status Yes No Viral hepatitis status Yes No Type of lesion Oral leukoplakia Oral lichenoid lesion Type of lichenoid lesion Reticular/Papular Erosive/Atrophic Plaque Not applicable Tongue involvement Yes No Buccal/labial mucosa involvement Yes No Retromolar area involvement Yes No Gingiva involvement Yes No Palate involvement Yes No Number of lesions 1 2 ≥3 Presence of ulcers or red form Yes No Presence of induration Yes No Treatment type Surgical intervention Pharmacological treatment No treatment Recurrence following surgical intervention No recurrence Recurrence Not applicable - No surgical intervention Number of recurrence Not applicable 1 2 3 >3 Oral epithelial dysplasia - diagnostic biopsy No dysplasia Mild dysplasia Moderate dysplasia Severe dysplasia Unknown - Patient refused biopsy Oral epithelial dysplasia - follow-up biopsy No dysplasia/No follow-up Mild dysplasia Moderate dysplasia Severe dysplasia Unknown - Patient refused biopsy during follow-up Select Model Random forest with class weights Decision tree with ADASYN resampling Predict Clear


Class QProcessor<TModel>
Abstract class representing a message processor.
Inheritance
Inherited Members
Namespace: AwsQueueBroker
Assembly: AwsQueueBroker.dll
Syntax
public abstract class QProcessor<TModel>
Type Parameters
| Name | Description |
|---|---|
| TModel | Type representing the content of the message body. |
Methods
| Improve this Doc View SourceError(Message, Exception, ILogger)
Method called if any other method in the processing chain threw an exception.
Declaration
public abstract Task Error(Message message, Exception exception, ILogger logger = null)
Parameters
| Type | Name | Description |
|---|---|---|
| Amazon.SQS.Model.Message | message | Copy of the Amazon.Sqs.Model.Message |
| System.Exception | exception | The exception thrown |
| Serilog.ILogger | logger | ILogger interface |
Returns
| Type | Description |
|---|---|
| System.Threading.Tasks.Task | Task |
Remarks
Provides the opportunity to conduct additional processing if an exception was thrown.
Process(Message, TModel, ILogger)
Method called after Validation.
Declaration
public abstract Task<QReply> Process(Message message, TModel model, ILogger logger = null)
Parameters
| Type | Name | Description |
|---|---|---|
| Amazon.SQS.Model.Message | message | Copy of the Amazon.Sqs.Model.Message |
| TModel | model | TModel returned by the Validate method |
| Serilog.ILogger | logger | ILogger interface |
Returns
| Type | Description |
|---|---|
| System.Threading.Tasks.Task<QReply> | Task<QMessage> |
Remarks
The primary processing logic for the message should occur within this method. If the message should trigger a reply, returning a QMessage will cause the broker to to automatically send a queue message to the specified queue url.
Received(Message, ILogger)
Method called when a message is first received.
Declaration
public abstract Task Received(Message message, ILogger logger = null)
Parameters
| Type | Name | Description |
|---|---|---|
| Amazon.SQS.Model.Message | message | Copy of the Amazon.Sqs.Model.Message |
| Serilog.ILogger | logger | ILogger interface |
Returns
| Type | Description |
|---|---|
| System.Threading.Tasks.Task | Task |
Validate(Message, TModel, ILogger)
Method called after Received.
Declaration
public abstract Task<object> Validate(Message message, TModel body, ILogger logger = null)
Parameters
| Type | Name | Description |
|---|---|---|
| Amazon.SQS.Model.Message | message | Copy of the Amazon.Sqs.Model.Message |
| TModel | body | The message body deserialized to TModel |
| Serilog.ILogger | logger | ILogger interface |
Returns
| Type | Description |
|---|---|
| System.Threading.Tasks.Task<System.Object> | Task<object>> |
Remarks
This method provides the opportunity to conduct additional validation on the deserialized message body. Modifications can be made to the TModel body within this function if necessary. The method should return TModel if validation is considered successful. The method should return null if validation has failed and processing should be halted for this message.


Paper Date Picker
This web component shows a calendar where dates can be picked.
Iron Data Table
This web component shows a table.
[[item.name.title]]
[[item.name.first]]
[[item.name.last]]
[[item.name.age]]
Google Map
This web component shows a map, based on the 'google map'.
The icons used on this website to display a female and two male persons are from the set
'Man by Eugen Belyakoff from the Noun Project'
https://thenounproject.com/eugen.belyakoff/collection/man/
Licenced under CC BY 3.0
https://creativecommons.org/licenses/by/3.0/legalcode


Configuring Mod Organizer 2
- Run ModOrganizer.exe
- From the pop-up called Choose Instance, select Portable
- From the pop-up called Please select the game to manage, select New Vegas
- If the option New Vegas does not appear, select Browse..., then navigate to the root folder and select FalloutNV.exe
- If there is a pop-up called INI file is read-only, select Yes
- From the pop-up called Show Tutorial?, select No
- From the pop-up called Register?, select Yes
- If all of the plugins in the right pane are not checked, right-click and select Enable all
- Change the order of the mods in the left pane to match the order of the plugins in the right pane
- If you have a GOG copy of the game, there may be a FalloutNV_lang.esp in the right pane
- If so, navigate to the Data folder and delete it
- Click the button on the toolbar of MO2
- Navigate to the Paths tab
- If you are on an SSD or an HDD with little space, set the Downloads path to a location on a drive with plenty of space
- In the Nexus tab, click the box that says Connect to Nexus
- MO2 should open a Nexus page in your browser
- Select Authorise
- Exit out of your browser and out of the settings menu in MO2
- MO2 may prompt you to restart, to which you should say yes
Optional: Configuring MO2's Looks
This section is optional only if you want to clean up MO2's interface a bit and change the theme. This is all up to personal preference, so feel free to configure it to your own liking
- Click the button on the toolbar of MO2
- In the General tab, you can select what style you want for MO2 in the drop-down right below the language selector
- Once you have selected a style, exit the settings menu
- Right-click in the header bar above the left pane where it says Mod Name
- Here you can choose to add or remove certain information MO2 will show about your mods
- I only leave Flags and Priority checked
- You can hide the background information box on the bottom of the window by hovering your mouse over the top of the box, holding left-click, and dragging down
- Right-click the toolbar of MO2 next to the button
- Here you can select what parts of the toolbar appear and how
I select Main Toolbar, Medium Icons, and Icons Only
Creating New Profiles in Mod Organizer 2
Mod Organizer 2's "Profiles" feature allows for easy switching between different mod configurations. In this step, we will setup a vanilla profile, a testing profile, and a main profile. The vanilla profile will stay completely untouched and act as a backup. The testing profile will be configured the same as the main profile for the guide, but will have all mods unchecked, allowing you to only activate certain mods for easy testing/troubleshooting. Profiles can be selected via the drop-down menu above the left pane
- Click the button on the toolbar of MO2
- Click on the Default profile and select Rename
- Input Vanilla for the new name
- With the Vanilla profile selected, select Copy
- Input Testing for the name and click OK
- Select the Testing folder and check both Use profile-specific Game INI Files and Automatic Archive Invalidation
- With the Testing profile selected, select Copy
- Input Viva New Vegas - Core for the name, click OK then Close
- You may get a pop-up about a missing modlist.txt. If that is the case, simply restart MO2 and select the Viva New Vegas - Core profile again
Setting up Tools in Mod Organizer 2
In order for programs to recognize MO2's virtual file system, the programs need to be ran directly through MO2. Programs can be selected via the drop-down menu in the top right, but first we have to add them.
- Switch to the Viva New Vegas profile
- Click the button on the toolbar of MO2
- Select the blue + sign at the top of the window
- In the right pane of the same window, input FNVEdit into the Title box
- Click the three dots to the right of the Binary box, and from the pop-up navigate to where FNVEdit is installed and select FNVEdit.exe
- Input -IKnowWhatImDoing in the Arguments box, then select Apply, then OK
- Back in the executables menu, select the blue + sign at the top of the window
- Input FNVEdit Cleaner into the Title box
- Click the three dots to the right of the Binary box, and from the pop-up navigate to where FNVEdit is installed and select FNVEditQuickAutoClean.exe, then click apply
- Select the blue + sign at the top of the window again and input FNVLODGen into the Title box
- Click the three dots to the right of the Binary box, and from the pop-up navigate to where FNVLODGen is installed and select xLODGenx64.exe
- Input -FNV into the Arguments box and select Apply
- Add zMerge and the GECK with the same method, but do not input anything into the Arguments box (GECK may have already been automatically added)
Mod Installation/Tracking
How to properly install mods from Nexus and track them so you get notified when they are updated:
- On the Nexus page, navigate to the Files tab
- For whatever files are listed in the guide, click the Mod Manager Download button to have it automatically download in MO2
- On the top of the mod page above the images and to the right of the statistics, click the Track button
- You will get a notification every time a tracked mod is updated on the toolbar on the top of the Nexus website
- MO2 also has a built system for updating mods that can be accessed by right-clicking in the left pane and selecting All Mods -> Check for updates. However, this system does not always fully work correctly
IMPORTANT: Mod Installation Advice in Mod Organizer 2
This is general advice to follow when installing mods in Mod Organizer 2
- When downloading multiple files from the same page, you will be prompted with a box in Mod Organizer 2 with the options Merge, Replace, and Rename
- For Main Files, Updates, and Hotfixes, select Merge. This will merge the mod files together into one mod in MO2
- If a mod has multiple Main Files, select Rename. Naming it something different will cause MO2 to install it as its own mod.
- For Optional Files, Miscellaneous Files, and Patches, select Rename. Naming it something different will cause MO2 to install it as its own mod.
- When updating from a previous version of a mod, select Replace. This will delete all the files from the old version of the mod and just install the ones from the new version
- If the guide says Install normally, just install the main file of the mod and use the Mod Manager Download button to install it through MO2
- If the guide says Hide the following:, do the following:
- Once the mod is installed, double-click it in the left pane of MO2
- Navigate to the Filetree tab
- Right-click on the listed file and select Hide
- If MO2 gives you a No game data on top level message while installing a mod:
- Expand the main folder
- Find the Data folder, right-click on it, and select Set data directory
- If there is no folder called Data, find the folder that contains the mod data (textures, meshes, and/or an .esp) and follow the same instructions as above
- If there is no Mod Manager Download button for a file, or if a file isn't hosted on Nexus, do the following:
- Click the Manual Download button (or whatever the download button is for the respective site)
- Click the button on the toolbar of MO2
- From the pop-up, navigate to where the file installed and double-click it
- Finish the install as you would any other mod


Working with the garage door opened
A way of working briefly described by Andy Matuschak here https://notes.andymatuschak.org/z21cgR9K3UcQ5a7yPsj2RUim3oM2TzdBByZu. If we apply this "working with the garage door open" idea to a scientific research endeavor I understand it as respecting the core concepts of open-science.
What is interesting is that in a garage you can peek in and get a sense of the tools, the dirt and a bunch of unrelated stuff and the object crafted in the workshop (furnitures, cars, computers, bombs, strange chemicals). You can see these objects in their final form but most of the time you will see them in their unfinished forms. The fact that people passing by are able to peek at the garage in the very early stages of the projects are of much interest and maybe still not very much adopted in science. I would like to experiment on this concept also. This second note of Andy explains this Anti-marketing concept nicely as https://notes.andymatuschak.org/z4bK6LaSBRetDzuYkeCs3A8mJ8DufTbK4o6FS
https://michaelnielsen.org/ https://quantum.country/qcvc cf vault/tools.mnemonics
Principles
Make the first draft deliberately bad. It’s hard to write something good from nothing. But it’s easy to look at something and say “I can at least do better than this idiot.”

Then be better. Then be better again...
-- (https://twitter.com/cahollenbeck/status/1327296301596352512)
A list of similar research endeavors
//TODO make a list of similar types of research strategies in academic or personal research
-
OSM The Open Source Malaria https://opensourcemalaria.org/. Hey they also have a fork for TB http://opensourcetb.org/
-
Have a look over there http://matt.might.net/. Also check the CRAPL license http://matt.might.net/articles/crapl/ (thanks to Adriano Rutz for fwd)
Daniel Mietchen github is a treasure trove for open science resources and actually a pretty good example of garage with an open door https://github.com/Daniel-Mietchen
It looks like Daniel has started to compile some information and examples. Here for the use of Commons in science https://github.com/Daniel-Mietchen/datascience/blob/master/commons.md
Links
https://galaxyproject.org/jxtx/
A community-centric approach https://app.jogl.io/


Context: Well established libraries typically have API documentation. However, they frequently lack examples and explanations, possibly making difficult their effective reuse. Stack Overflow is a question-and-answer website oriented to issues related to software development. Despite the increasing adoption of Stack Overflow, the information related to a particular topic (e.g., an API) is spread across the website. Thus, Stack Overflow still lacks organization of the crowd knowledge available on it.
Objective: Our target goal is to address the problem of the poor quality documentation for APIs by providing an alternative artifact to document them based on the crowd knowledge available on Stack Overflow, called crowd cookbook. A cookbook is a recipe-oriented book, and we refer to our cookbook as crowd cookbook since it contains content generated by a crowd. The cookbooks are meant to be used through an exploration process, i.e. browsing.
Method: In this paper, we present a semi-automatic approach that organizes the crowd knowledge available on Stack Overflow to build cookbooks for APIs. We have generated cookbooks for three APIs widely used by the software development community: SWT, LINQ and QT. We have also defined desired properties that crowd cookbooks must meet, and we conducted an evaluation of the cookbooks against these properties with human subjects.
Results: The results showed that the cookbooks built using our approach, in general, meet those properties. As a highlight, most of the recipes were considered appropriate to be in the cookbooks and have self-contained information.
Conclusions: We concluded that our approach is capable to produce adequate cookbooks automatically, which can be as useful as manually produced cookbooks. This opens an opportunity for API designers to enrich existent cookbooks with the different points of view from the crowd, or even to generate initial versions of new cookbooks.


ECLIPSE
Copyright (c) 2005 Michael Howe
This game is played on any empty square board (say 8x8):
- TURN - On each turn, each player drops a friendly stone on an empty cell adjacent to another empty cell or friendly stone.
- If it is adjacent to a friendly stone, then all enemy stones at horizontal or vertical adjacent lines change color (i.e., they become friendly stones).
- There is a swap option after the third drop, i.e., the second player may choose the adversary color and pass his turn.
- GOAL - When the board is full, wins the player with more stones.
An example White's turn. If he drops at the green dot, he will flip colors of all the marked black stones. He will not change the black stone at e5 since it is at a diagonal, not orthogonal adjacent line. Also, the three vertical black stones at column 'f' does not change since they are not adjacent to the cell where the drop is made.
White could also drop at the red spot, but then no captures would be made, since that cell is not adjacent to any friendly stone.
Eclipse can be seen as a game template with two arguments: (a) how to define adjacency, (b) how to define the range for color change. In the actual rules, these arguments are (a) chess King adjacency and (b) chess Rook move range. So, shortly, we can define this instance as Eclipse[King,Rook].
There are many other options, like Eclipse[Knight,Rook], Eclipse[Knight,King], Eclipse[Ferz+Alfil,Bishop], ... (check other move ranges at Piececlopedia). We can also consider pairs of arguments, like Eclipse[(Ferz,Rook) + (Dabbabah,King)]. This expands to thousands of possible variants (some better than others, of course).


str_replace
(PHP 4, PHP 5, PHP 7)
str_replace — 子字符串替换
说明
mixed str_replace ( mixed $search , mixed $replace , mixed $subject [, int &
$count ] )
该函数返回一个字符串或者数组。该字符串或数组是将 subject 中全部的 search 都被
replace 替换之后的结果。
如果没有一些特殊的替换需求（比如正则表达式），你应该使用该函数替换 ereg_replace
() 和 preg_replace()。
参数
如果 search 和 replace 为数组，那么 str_replace() 将对 subject 做二者的映射替换
。如果 replace 的值的个数少于 search 的个数，多余的替换将使用空字符串来进行。如
果 search 是一个数组而 replace 是一个字符串，那么 search 中每个元素的替换将始终
使用这个字符串。该转换不会改变大小写。
如果 search 和 replace 都是数组，它们的值将会被依次处理。
search
查找的目标值，也就是 needle。一个数组可以指定多个目标。
replace
search 的替换值。一个数组可以被用来指定多重替换。
subject
执行替换的数组或者字符串。也就是 haystack。
如果 subject 是一个数组，替换操作将遍历整个 subject，返回值也将是一个数组。
count
如果被指定，它的值将被设置为替换发生的次数。
返回值
该函数返回替换后的数组或者字符串。

// 由于从左到右依次替换，最终 E 被 F 替换
$search = array('A', 'B', 'C', 'D', 'E');
$replace = array('B', 'C', 'D', 'E', 'F');
$subject = 'A';
echo str_replace($search, $replace, $subject);
// 输出: apearpearle pear
// 由于上面提到的原因
$letters = array('a', 'p');
$fruit = array('apple', 'pear');
$text = 'a p';
$output = str_replace($letters, $fruit, $text);
echo $output;
?>
注释
Note: 此函数可安全用于二进制对象。
Caution
了解替换顺序
由于 str_replace() 的替换时从左到右依次进行的，进行多重替换的时候可能会替换掉之
前插入的值。参见该文档的范例。
Note:
该函数区分大小写。使用 str_ireplace() 可以进行不区分大小写的替换。
参见
• str_ireplace() - str_replace 的忽略大小写版本
• substr_replace() - 替换字符串的子串
• preg_replace() - 执行一个正则表达式的搜索和替换
• strtr() - 转换指定字符
User Contributed Notes 41 notes
===============================================================================
A faster way to replace the strings in multidimensional array is to json_encode
() it, do the str_replace() and then json_decode() it, like this:
This method is almost 3x faster (in 10000 runs.) than using recursive calling
and looping method, and 10x simpler in coding.
Compared to:
===============================================================================
jSON Turkish Characters Problem - (PHP < 5.4 for example)
===============================================================================
Feel free to optimize this using the while/for or anything else, but this is a
bit of code that allows you to replace strings found in an associative array.
For example:
'cat',
'apple' => 'orange'
'chevy' => 'ford'
);
$string = 'I like to eat an apple with my dog in my chevy';
echo str_replace_assoc($replace,$string);
// Echo: I like to eat an orange with my cat in my ford
?>
Here is the function:
[Jun 1st, 2010 - EDIT BY thiago AT php DOT net: Function has been replaced with
an updated version sent by ljelinek AT gmail DOT com]
===============================================================================
Be careful when replacing characters (or repeated patterns in the FROM and TO
arrays):
For example:
I would expect as result: "ZDDB"
However, this return: "ZDDD"
(Because B = D according to our array)
To make this work, use "strtr" instead:
"A","2" => "B","3" => "C","B" => "D");
$word = "ZBB2";
echo strtr($word,$arr);
?>
This returns: "ZDDB"
===============================================================================
Note that this does not replace strings that become part of replacement
strings. This may be a problem when you want to remove multiple instances of
the same repetative pattern, several times in a row.
If you want to remove all dashes but one from the string
'-aaa----b-c-----d--e---f' resulting in '-aaa-b-c-d-e-f', you cannot use
str_replace. Instead, use preg_replace:
';
echo preg_replace('/--+/', '-', $challenge).'
';
?>
This outputs the following:
-aaa--b-c---d-e--f
-aaa-b-c-d-e-f
===============================================================================
This strips out horrible MS word characters.
Just keep fine tuning it until you get what you need, you'll see ive commented
some out which caused problems for me.
There could be some that need adding in, but its a start to anyone who wishes
to make their own custom function.
', $str); // right single guillemet
// $str = str_replace(chr(156), 'oe', $str); // oe ligature
$str = str_replace(chr(159), 'Y', $str); // Y Dieresis
$str = str_replace('°C', '°C', $str); // Celcius is used quite a lot so
it makes sense to add this in
$str = str_replace('£', '£', $str);
$str = str_replace("'", "'", $str);
$str = str_replace('"', '"', $str);
$str = str_replace('–', '–', $str);
return $str;
}
?>
===============================================================================
Might be worth mentioning that a SIMPLE way to accomplish Example 2 (potential
gotchas) is to simply start your "replacements" in reverse.
So instead of starting from "A" and ending with "E":
So basically start from the "end" and put the replacements in an order where
the "replaced value" won't equal a value that exists later in the "search
array".
===============================================================================
I was working with MySQL and displaying the title to things on the web page.
I'd written a script to ensure single and double quotes were removed from the
title. I used
$title = str_replace( "'", "", $title );
and
$title = str_replace( '"', "", $title );
But still the single and double quotes continued. So I wrote a bit of code to
print out each character separated by a dash. Like so:
for( $i=0; $i\n";
This displayed:
m-y-c-o-m-p-a-n-y- b-b-&-#-3-9-;-s
Which made me go "Oh! I get it."
The MySQL function real_escape_string modifies the single quotes to be '
and double quotes as " These still show up as single and double quotes
under HTML and most importantly -
JAVASCRIPT sees the " and ' as actual single or double
quotes. So if you are passing arguments to a function you have
to get rid of them or else you will get an error on trying to call
a given function. Example:
becomes
Which then will give you an error because there is a single quote inside of the
single quoted string. HOWEVER, the
$title = str_replace( "'", "", $title );
WILL NOT FIND a single quote. Instead, you have to do this:
$title = str_replace( "'", "'", $title );
and
$title = str_relace( """, '"', $title );
(Or you could just get rid of them.)
So remember! If you are trying to remove single and double quotes and are
using MySQL and MySQL's real_escape_string() function that you might be having
single and double quotes hanging around which are defined as ' and "
but which show up as single and double quotes as well as causing problems in
your Javascripts.
===============================================================================
Here's a deep replace function allowing multi-dimensional arrays in $search,
$replace and $subject. The keys and other structure of $subject are preserved.
===============================================================================
===============================================================================
As an effort to remove those Word copy and paste smart quotes, I've found that
this works with UTF8 encoded strings (where $text in the following example is
UTF8). Also the elipsis and em and en dashes are replaced.
There is an "invisible" character after the â€ for the right side double smart
quote that doesn't seem to display here. It is chr(157).
===============================================================================
Maybe obvious to veteran PHP programmers but less so to novice PHP programmers
is the fact that this is invalid:
At a glance it appears to be a reasonable request, until you realize that the
fourth parameter must be a variable in order to be passed as a reference. A
replacement:
===============================================================================
In many countries the numeric format is 1.000,33 in english it is 1,000.33
This function converts numeric arguments always into the PHP confirm numeric
format. If only one seperator is into the numericstring so it is interpreted as
the decimalpoint.
function dp($zahl)
{
if ((strpos($zahl,".") > "-1") | (strpos($zahl,",") > "-1")) {
if ((strpos($zahl,".") > "-1") & (strpos($zahl,",") > "-1")) {
if (strpos($zahl,".") > strpos($zahl,",")){
return str_replace(",","",$zahl);
} else {
return str_replace(",",".",str_replace(".","",$zahl));
}
} else {
if (strpos($zahl,".") > "-1") {
if (strpos($zahl,".") == strrpos($zahl,".")) {
return $zahl;
} else {
return str_replace(".","",$zahl);
}
} else {
if (strpos($zahl,",") == strrpos($zahl,",")) {
return str_replace(",",".",$zahl);
} else {
return str_replace(",","",$zahl);
}
} }
} else {
return $zahl;
} }
===============================================================================
Be aware that if you use this for filtering & sanitizing some form of user
input, or remove ALL instances of a string, there's another gotcha to watch out
for:
// Remove all double characters
$string="1001011010";
$string=str_replace(array("11","00"),"",$string);
// Output: "110010"
$string="ml> Malicious code html> etc";
$string=str_replace(array("",""),"",$string);
// Output: " Malicious code etc"
===============================================================================
Insert space after comma.
If you have a form that stores results in a database field as comma separated
values, when you display this data you can use the following to insert a space
after each comma:
Notes:
1) To get round the Replacement Order Gotcha, the comma is also replaced with
its code equivalent: ,
2) You can adapt the $replace section to suit your needs: swap out the
code with
or replace comma and space with · etc.
===============================================================================
nikolaz dot tang at hotmail dot com's solution of using json_encode/decode is
interesting, but a couple of issues to be aware of with it.
json_decode will return objects, where arrays are probably expected. This is
easily remedied by adding 2nd parameter 'true' to json_decode.
$search and $replace could contain strings that match json encoding, which will
either change the structure returned by this method, or break the json.
ie:
'stuff']));
var_dump(str_replace_json('this":"', 'this" : "thing", "with":"', ['this' =>
'stuff']));
?>
===============================================================================
$myString = “It was the best of mine it was the worst of mine,”;
// Displays “It was the best of bananas, it was the worst of bananas,”
echo str_replace( “mine”, “bananas”, $myString );
If you want to know how many times the search string was replaced, pass in a
variable as an optional
fourth argument. After the function runs, this variable holds the number of
replacements:
$myString = “It was the best of mine, it was the worst of mine,”;
// Displays “It was the best of bananas, it was the worst of bananas,”
echo str_replace( “mine”, “bananas”, $myString, $num ) . “ < br/ > ”;
// Displays “The text was replaced 2 times.”
echo “The text was replaced $num times. < br/ > ”;
===============================================================================
I came across requirement to replace some occurrences of a letter with other
letter in a word:
===============================================================================
Before spending hours searching your application why it makes UTF-8 encoding
into some malformed something with str_replace, make sure you save your PHP
file in UTF-8 (NO BOM).
This was at least one of my problems.
===============================================================================
As previous commentators mentioned, when $search contains values that occur
earlier in $replace, str_replace will factor those previous replacements into
the process rather than operating solely on the original string. This may
produce unexpected output.
Example:
In the above code, the $search and $replace should replace each occurrence in
the $subject with the next letter in the alphabet. The expected output for
this sample is 'BCDEF'; however, the actual output is 'FFFFF'.
To more clearly illustrate this, consider the following example:
Since 'A' is the only letter in the $search array that appears in $subject, one
would expect the result to be 'B'; however, replacement number $n does *not*
operate on $subject, it operates on $subject after the previous $n-1
replacements have been completed.
The following function utilizes array_combine and strtr to produce the expected
output, and I believe it is the most efficient way to perform the desired
string replacement without prior replacements affecting the final result.
Some other examples:
===============================================================================
My input is MS Excel file but I want to save ‘,’,“,” as ',',",".
$badchr = array(
"\xc2", // prefix 1
"\x80", // prefix 2
"\x98", // single quote opening
"\x99", // single quote closing
"\x8c", // double quote opening
"\x9d" // double quote closing
);
$goodchr = array('', '', '\'', '\'', '"', '"');
str_replace($badchr, $goodchr, $strFromExcelFile);
Works for me.
===============================================================================
I found a pretty low tech solution to avoid the "gotcha" without worrying about
the array order of how things are replaced. I could not "order" the replacement
array easily because it was being read from a database table.
Anyway if you add an identifiable token to each replaced word, then just filter
this out at the very end, no nested search terms are found. I just dynamically
add the %% after the first char of each word before pumping it into the
str_ireplace function.
$find = array("as1", "as2", "as3", "flex");
$replace = array("A%%uto S%%entry R%%ev. A%%", "A%%uto S%%entry E%%xp", "A%%uto S%%entry
f%%lex", "f%%lex");
$text = str_ireplace($find, $replace, $text);
echo str_ireplace("%%", "", $text);
In this case I am using %% as my token as this is an unlikely char combo for
me.
===============================================================================
If we have a html template that contains placeholders in curly braces that need
to be replaced in runtime, the following function will do it using str_replace:
'one', "bc" => 'two');
$q = file_get_contents($filename);
foreach ($data as $key => $value) {
$q = str_replace('{'.$key.'}', $value, $q);
}
return $q;
}
?>
===============================================================================
"If search is an array and replace is a string, then this replacement string is
used for every value of search. The converse would not make sense, though. "
I think one important (and not at all vaguely theoretical) use-case is
completely ignored here. Take, for example, the way the PDO handles parameter
replacement.
If we have the following query:
"SELECT * FROM my_table WHERE (id = ? AND my_column = ? AND other_column = ?);"
The "?"s should be replaced by each successive variable in a $parameters array.
That is EXACTLY the use case for "search" being a value and "replace" being an
array.
Considering that this is not only a real-world example but also part of a core
PHP functionality I find it very strange that it's dismissed so easily here.
===============================================================================
I tried max at efoxdesigns dot com solution for str_replace_once but it didn't
work quite right so I came up with this solution (all params must be strings):
===============================================================================
To collapse multiple consecutive space characters to a single one, don't use
str_replace() inside a loop--use preg_replace() instead for clarity and better
performance:
===============================================================================
If you need to replace a string in another, but only once but still in all
possible combinations (f.e. to replace "a" with "x" in "aba" to get array
("xba", "abx")) you can use this function:
It may not be the best in performance, but it works.
===============================================================================
say you want every "a" replaced by "abba" and every "b" replaced by "baab" in
the string "ab" you do:
that results in "abaabbaababaab" and not the expected "abbabaab"
I wrote this little snippet to solve the replacements-in-replacement problem:
that results in the expected "abbabaab"
===============================================================================
Yet another deep replace function:
===============================================================================
With PHP 4.3.1, at least, str_replace works fine when working with single
arrays but mess it all with two or more dimension arrays.
You should eat that [1] => that [2] => and
that every day. )
echo "
";
$subject = array(array("first", "You should eat this")
,array("second","this")
,array("third", "and this every day."));
$search = "this";
$replace = "that";
$new = str_replace($search, $replace, $subject);
print_r($new); // Array ( [0] => Array [1] => Array [2] => Array )
?>
===============================================================================
$value) {
if (is_array($value)) {
recursive_array_replace($find, $replace, $data[$key]);
} else {
$data[$key] = str_replace($find, $replace, $value);
}
}
} else {
$data = str_replace($find, $replace, $data);
}
}
$a = array();
$a['a'] = "a";
$a['b']['a'] = "ba";
$a['b']['b'] = "bb";
$a['c'] = "c";
$a['d']['a'] = "da";
$a['d']['b'] = "db";
$a['d']['c'] = "dc";
$a['d']['d'] = "dd";
echo "Before Replaces";
print_r($a);
recursive_array_replace("a", "XXXX", $a);
echo "After Replaces";
print_r($a);
?>
===============================================================================
@moostende at gmail dot com
If you want to remove all dashes but one from the string
'-aaa----b-c-----d--e---f' resulting in '-aaa-b-c-d-e-f', you CAN use
str_replace !
0);
return $str;
}
echo foo("-aaa----b-c-----d--e---f");
?>
This outputs the following:
-aaa-b-c-d-e-f
===============================================================================
I was looking for a str_replace function supporting callbacks. As I didn't
found one I wrote one my own. Works exactly like str_replace, but the replace
parameter is a callback or an array of callbacks (instead of string/strings in
str_replace). The callback function accepts two arguments, the string that is
being replaced and the count of the replacement being done.
$callback) {
if (!is_callable($callback)) {
throw new Exception(sprintf('Unable to use %s (#%d) as a callback',
gettype($callback), $index));
}
}
// search and replace
$subjectIsString = is_string($subject);
$subject = (array) $subject;
foreach($subject as &$haystack) {
if (!is_string($haystack)) continue;
foreach($search as $key => $needle) {
if (!$len = strlen($needle))
continue;
$replaceSingle && $key = 0;
$pos = 0;
while(false !== $pos = strpos($haystack, $needle, $pos)) {
$replaceWith = isset($replace[$key]) ? call_user_func($replace[
$key], $needle, ++$replace_count) : '';
$haystack = substr_replace($haystack, $replaceWith, $pos, $len
);
}
}
}
unset($haystack);
return $subjectIsString ? reset($subject) : $subject;
}
?>
===============================================================================
'new word',
'was' => 'it',
'past' => 'future',
);
$originalText = "every old word was a thing of the past...";
$replacedText = str_replace(array_keys($replaceThis), $replaceThis,
$originalText);
echo $replacedText;
?>
===============================================================================
As mentioned earlier you should take the order into account when substituting
multiple values.
However it is worth noticing that str_replace doesn't seem to re-read the
string when doing single replacements. Take the following example.
You would expect the following.
First replacement '/a/a/' -> '/a/'
Second replacement '/a/'->'/'
This is not the case, the actual result will be '/a/'.
To fix this, you will have to put str_replace in a while-loop.
===============================================================================
This function implements $limit for str_replace(); is 100% backward compatible
with str_replace(); uses str_replace() whenever possible (for performance
reasons); supports arrays for $search, $replace, and $subject; and is fully
commented.
$this_subject){
// Skip values that are arrays
if(!is_array($this_subject)){
// Call this function again
$this_function = __FUNCTION__;
$subject[$key] = $this_function($search, $replace, $this_subject,
$this_count, $limit);
// Adjust $count
$count += $this_count;
// Adjust $limit
if($limit!=-1){
$limit -= $this_count;
}
// Reached $limit
if($limit===0){
return $subject;
}
}
}
return $subject;
} elseif(is_array($search)){
// Clear keys of $search
$search = array_values($search);
// Clear keys of $replace
if(is_array($replace)){
$replace = array_values($replace);
}
// Loop through $search
foreach($search as $key => $this_search){
// Don't support multi-dimensional arrays
$this_search = strval($this_search);
// If $replace is an array, use $replace[$key] if exists, else ''
if(is_array($replace)){
if(array_key_exists($key, $replace)){
$this_replace = strval($replace[$key]);
} else {
$this_replace = '';
}
} else {
$this_replace = strval($replace);
}
// Call this function again for
$this_function = __FUNCTION__;
$subject = $this_function($this_search, $this_replace, $subject, $this_count
, $limit);
// Adjust $count
$count += $this_count;
// Adjust $limit
if($limit!=-1){
$limit -= $this_count;
}
// Reached $limit
if($limit===0){
return $subject;
}
}
return $subject;
} else {
$search = strval($search);
$replace = strval($replace);
// Get position of first $search
$pos = strpos($subject, $search);
// Return $subject if $search cannot be found
if($pos===false){
return $subject;
}
// Get length of $search
$search_len = strlen($search);
// Loop until $search cannot be found or $limit is reached
for($i=0;(($i<$limit)||($limit===-1));$i++){
$subject = substr_replace($subject, $replace, $pos, $search_len);
// Increase $count
$count++;
// Get location of next $search
$pos = strpos($subject, $search);
// Break out of loop
if($pos===false){
break;
}
}
return $subject;
}
}
?>
===============================================================================
I have:
autocommit(TRUE);
return $db;
}
// dane do ramy pliku .xml
$kanalRSS = '';
$kanalRSS .= '';
$kanalRSS .= '';
// połaczenie z bazą danych
$db = lacz_bd();
//zapytanie określające dane ktore powinny byc pobrane z tabeli
// teraz pobierzmy wszystkie dane spelniajace warunek category_id=140
$zapytanie = "SELECT * FROM announcements WHERE category_id in
(140,141,142,143,144)";
$wynik = $db->query($zapytanie);
$ile_znalezionych = $wynik->num_rows;
for ($i=0; $i <$ile_znalezionych; $i++)
{
$wiersz = $wynik->fetch_assoc();
//usuwamy znaczniki html ze wszystkich danych z tabeli, polskie znaki,
duze litery
$string_title = $wiersz['annoucement_title'];
$string_url = $wiersz['annoucement_title'];
$pattern = array(' ', ',', '.', '/ą/', '/Ą/', '/ć/', '/Ć/', '/ę/', '/Ę/
', '/ł/', '/Ł/' ,'/ń/', '/Ń/', '/ó/', '/Ó/', '/ś/', '/Ś/', '/ź/', '/Ź/', '/ż/',
'/Ż/',);
$replacement = array('-', '', '', 'a', 'A', 'c', 'C', 'e', 'E', 'l'
, 'L', 'n', 'N', 'o', 'O', 's', 'S', 'z', 'Z', 'z', 'Z',);
$string_url = strtolower(str_replace($pattern, $replacement,
$string_url));
$wiersz['annoucement_content'] = strip_tags($wiersz[
'annoucement_content']);
//dodajemy nazwy rodzajow ogloszenia
$string_type = $wiersz['annoucement_type'];
$_type = array('1', '2', '3', '4');
$_new_type = array('Buy', 'Replace', 'For Rent', 'For Sale');
$wiersz['annoucement_type'] = str_replace($_type, $_new_type,
$string_type);
//tutaj generujemy zawartosc pliku .xml, ktora pobierana jest z tabeli
announcements
$kanalRSS .= '- ';
$kanalRSS .= '';
$kanalRSS .= '';
$kanalRSS .= '';
$kanalRSS .= '';
$kanalRSS .= '
content>';
$kanalRSS .= '
date>';
$kanalRSS .= '
';
}
$kanalRSS .= ' ';
$kanalRSS .= '';
//Zapisujemy wygenerowany kod XML do pliku moj_rss.xml
$fp = fopen('trovit_oglaszajtu.xml','w');
fwrite($fp,$kanalRSS);
fclose($fp);
?>
And one problem - ą,ó,ś, etc - don't delete
oglaszajtu.pl/moj_rss.php
oglaszajtu.pl/trovit_oglaszajtu.xml
:-(
Can anyone help me?
Thx
rel
===============================================================================
Fast function to replace new lines from a given string. This is interesting to
replace all new lines from e. g. a text formatted in HTML retrieved from
database and printing it without the unnecessary new lines. This results in
slightly faster rendering in the Web browser.
===============================================================================
For PHP 4 < 4.4.5 and PHP 5 < 5.2.1 you may occur (like me) in this bug:
http://www.php-security.org/MOPB/MOPB-39-2007.html
===============================================================================
If you wish to get around the 'gotcha', you could do something like this:
The idea here is that you first replace the items you want with unique
identifiers (that you are unlikely to find in the subject) and then search for
those identifiers and then replace them.
===============================================================================
Replacement for str_replace in which a multiarray of numerically keyed data can
be properly evaluated with the given template without having a search for 11 be
mistaken for two 1's next to each other
'yellow', 2=>'banana', 11=>'fruit'), array(1=>'green',
2=>'spinach', 11=>'vegetable'), array(1=>'pink', 2=>'salmon', 11=>'fish'));
print_r (data_template($input, '2: a 1, healthy 11'));
/*
Array
(
[0] => banana: a yellow, healthy fruit
[1] => spinach: a green, healthy vegetable
[2] => salmon: a pink, healthy fish
)
*/
// str_replace would have wanted to output 'banana: a yellow, healthy
yellowyellow
?>
Not sure if this will help anyone but I wrote it for my application and thought
I would share just in case


Files CCore/inc/TlsSlot.h CCore/src/TlsSlot.cpp
TlsSlot is designed to provide a thread local variables. It is integrated with the PlanInit subsystem.
class TlsSlot
{
....
public:
explicit TlsSlot(const char *tag);
~TlsSlot();
void set(void *value);
void * get();
};
Don't use objects of this class directly! Here is the pattern:
struct MySlot : TlsSlot { MySlot() : TlsSlot("MySlot") {} }; MySlot MySlotObject CCORE_INITPRI_1 ; PlanInitNode * GetPlanInitNode_MySlot() { return &MySlotObject; } void SomeFunc() { void *tls=MySlotObject->get(); }
TlsSlot value is a thread-specific, i.e. depends on the calling thread. Each thread has own private copy of this value. The initial value is 0. If the TlsSlot constructor is unable to allocate a TLS slot, it aborts execution.
You should avoid using TlsSlot, leave it to the CCore internals. There is a better way to define a thread-specific variable: when you start a thread, using the Task object and functions, you always can find the current task by the Task::GetCurrent() function. So just add a required thread context to the Task object. You can also use the PerTask tool.