qid
int64
1
74.7M
question
stringlengths
0
58.3k
date
stringlengths
10
10
metadata
sequence
response_j
stringlengths
2
48.3k
response_k
stringlengths
2
40.5k
51,786
I got excited about Calc's power as an embedded mode. Define some variables in natural inline notation and then do operations on them. But the execution seems a bit messy: you got a separate key bindings when you're in CalcEmbed mode and mistakes are easy to make. Can the mode be tamed so that the following org-mode buffer: ``` * Calc test embed! Let $foo := 342$ and $bar := 2.2$. Now $foo*bar => $! ``` Could be evaluated to ``` * Calc test embed! Let $foo := 342$ and $bar := 2.2$. Now $foo*bar => 752.4$! ``` With a single key stroke, all the while remaining in org-mode?
2019/07/23
[ "https://emacs.stackexchange.com/questions/51786", "https://emacs.stackexchange.com", "https://emacs.stackexchange.com/users/318/" ]
Maybe not a single keystroke but you could *activate* embedded mode via `C-x * a` and then (while point is in, say, the first expression) *update* all calc expressions with `C-x * u`. I use embedded mode all the time and it's one of the most understated features of Emacs!
To expand on @éric's answer: you can avoid having to activate the formulas explicitly with `C-x * a` by including these lines: ``` --- Local Variables: --- --- eval:(calc-embedded-activate) --- --- End: --- ``` In an org-mode file, using just `#` instead of `---` is probably better though. Also notice that this and `C-x * a` doesn't actually *activate* embedded mode, but just activates the formulas for embedded mode, so you stay in org-mode. (See [doc for `calc-embedded-activate`](https://www.gnu.org/software/emacs/manual/html_node/calc/Assignments-in-Embedded-Mode.html#index-C_002dx-_002a-a) for reference.) Also, you can call `C-x * u` with a numeric prefix, which will update all activated `=>` formulas, so you don't need to move the point into a formula first (e.g. `C-- C-x * u` but not `C-u C-x * u` which will only update formulas in the current region). In itself, `C-x * u` will only update formulas which are dependent on the current formula (i.e. where the point is pointing at). (See [doc for `calc-embedded-update-formula`](https://www.gnu.org/software/emacs/manual/html_node/calc/Assignments-in-Embedded-Mode.html#index-calc_002dembedded_002dupdate_002dformula) for reference.)
28,640,427
I have table in mysqli database now i want to get 1 result random This is code mysql ``` $cid = $_GET['id']; $ans = $db->query("select * from result where cat_id='$cid' limit 1"); $rowans = $ans->fetch_object(); echo" <h4>".$rowans->title."</h4><br> <img src='".$rowans->img."' style='width:400px;height:300;' /> <p>".$rowans->desc."</p>"; ``` in this code i get 1 result but not random always gives me the same result
2015/02/21
[ "https://Stackoverflow.com/questions/28640427", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
SQL: ``` SELECT * FROM result ORDER BY rand() LIMIT 1 ```
`LIMIT` orders the rows by the primary key of the table, so you always get the same one (the "first" row according to that key). Try: ``` SELECT * FROM result WHERE cat_id='$cid' ORDER BY RAND() LIMIT 0,1; ``` You can think of it this way: it first orders the results by a random order, then picks the first one.
7,674,955
I am developing an asp.net application where i have a dataset having 3 tables i.e. `ds.Tables[0], Tables[1] and Tables[2]` I need to find minimum number and maximum number out of all the 3 tables of dataset. How to do that? I found similar question in SO [here](https://stackoverflow.com/questions/2442525/how-to-select-min-and-max-values-of-a-column-in-a-datatable) but not sure how that would help me getting my way? **UPDATED:** ``` double minValue = double.MinValue; double maxValue = double.MaxValue; foreach (DataRow dr in dtSMPS.Rows) { double actualValue = dr.Field<double>("TOTAL_SUM"); // This fails specifying type cast error minValue = Math.Min(minValue, actualValue); maxValue = Math.Max(maxValue, actualValue); } ``` Please guide! Thanks.
2011/10/06
[ "https://Stackoverflow.com/questions/7674955", "https://Stackoverflow.com", "https://Stackoverflow.com/users/224636/" ]
Do it on `IOrganisation`(and have `IPeople` as the return type). Something like this: ``` interface IOrganisation { IList<IPeople> GetPeople(); } ``` This is because the people of an organisation is a property of the organisation, not of the people.
That sounds like it should be on `IOrganization` - that's what you'll call it on, after all. What you *have* is the organization, you *want* the list of people - you can't *start* fromt the list of people, so it *must* be part of the `IOrganization` interface. I find it strange to have *plural* interface names to start with - I'd expect `IOrganization` for a single organization, and `IPerson` for a single person. ``` public interface IOrganization { IList<IPerson> GetPeople(); } ```
7,674,955
I am developing an asp.net application where i have a dataset having 3 tables i.e. `ds.Tables[0], Tables[1] and Tables[2]` I need to find minimum number and maximum number out of all the 3 tables of dataset. How to do that? I found similar question in SO [here](https://stackoverflow.com/questions/2442525/how-to-select-min-and-max-values-of-a-column-in-a-datatable) but not sure how that would help me getting my way? **UPDATED:** ``` double minValue = double.MinValue; double maxValue = double.MaxValue; foreach (DataRow dr in dtSMPS.Rows) { double actualValue = dr.Field<double>("TOTAL_SUM"); // This fails specifying type cast error minValue = Math.Min(minValue, actualValue); maxValue = Math.Max(maxValue, actualValue); } ``` Please guide! Thanks.
2011/10/06
[ "https://Stackoverflow.com/questions/7674955", "https://Stackoverflow.com", "https://Stackoverflow.com/users/224636/" ]
Do it on `IOrganisation`(and have `IPeople` as the return type). Something like this: ``` interface IOrganisation { IList<IPeople> GetPeople(); } ``` This is because the people of an organisation is a property of the organisation, not of the people.
Which belongs to which? It seems to me that `iOrganisation.People` would be a list of people ( is your "IPeople" interface representing a list of people or a single person? ) belonging to the organisation. Likewise you might have an `IPeople.Organisations` that lists all organisations that a person belongs to. Both will probably have a different underlying mechanism - maybe calling the same lookup table - it doesn't matter to the person calling the code.
7,674,955
I am developing an asp.net application where i have a dataset having 3 tables i.e. `ds.Tables[0], Tables[1] and Tables[2]` I need to find minimum number and maximum number out of all the 3 tables of dataset. How to do that? I found similar question in SO [here](https://stackoverflow.com/questions/2442525/how-to-select-min-and-max-values-of-a-column-in-a-datatable) but not sure how that would help me getting my way? **UPDATED:** ``` double minValue = double.MinValue; double maxValue = double.MaxValue; foreach (DataRow dr in dtSMPS.Rows) { double actualValue = dr.Field<double>("TOTAL_SUM"); // This fails specifying type cast error minValue = Math.Min(minValue, actualValue); maxValue = Math.Max(maxValue, actualValue); } ``` Please guide! Thanks.
2011/10/06
[ "https://Stackoverflow.com/questions/7674955", "https://Stackoverflow.com", "https://Stackoverflow.com/users/224636/" ]
Do it on `IOrganisation`(and have `IPeople` as the return type). Something like this: ``` interface IOrganisation { IList<IPeople> GetPeople(); } ``` This is because the people of an organisation is a property of the organisation, not of the people.
First of all, your should probably not have pluralized interface names. So call them IOrganization and IPerson and then on your `IOrganisation` interface you might have a method called: ``` IEnumerable<IPerson> GetPeople() ```
7,674,955
I am developing an asp.net application where i have a dataset having 3 tables i.e. `ds.Tables[0], Tables[1] and Tables[2]` I need to find minimum number and maximum number out of all the 3 tables of dataset. How to do that? I found similar question in SO [here](https://stackoverflow.com/questions/2442525/how-to-select-min-and-max-values-of-a-column-in-a-datatable) but not sure how that would help me getting my way? **UPDATED:** ``` double minValue = double.MinValue; double maxValue = double.MaxValue; foreach (DataRow dr in dtSMPS.Rows) { double actualValue = dr.Field<double>("TOTAL_SUM"); // This fails specifying type cast error minValue = Math.Min(minValue, actualValue); maxValue = Math.Max(maxValue, actualValue); } ``` Please guide! Thanks.
2011/10/06
[ "https://Stackoverflow.com/questions/7674955", "https://Stackoverflow.com", "https://Stackoverflow.com/users/224636/" ]
Do it on `IOrganisation`(and have `IPeople` as the return type). Something like this: ``` interface IOrganisation { IList<IPeople> GetPeople(); } ``` This is because the people of an organisation is a property of the organisation, not of the people.
If you think of an organization as a collection containing people, then it's intuitive to put that in `IOrganization`. It would look like this: ``` interface IOrganization { IList<IPeople> Members { get; } } ```
7,674,955
I am developing an asp.net application where i have a dataset having 3 tables i.e. `ds.Tables[0], Tables[1] and Tables[2]` I need to find minimum number and maximum number out of all the 3 tables of dataset. How to do that? I found similar question in SO [here](https://stackoverflow.com/questions/2442525/how-to-select-min-and-max-values-of-a-column-in-a-datatable) but not sure how that would help me getting my way? **UPDATED:** ``` double minValue = double.MinValue; double maxValue = double.MaxValue; foreach (DataRow dr in dtSMPS.Rows) { double actualValue = dr.Field<double>("TOTAL_SUM"); // This fails specifying type cast error minValue = Math.Min(minValue, actualValue); maxValue = Math.Max(maxValue, actualValue); } ``` Please guide! Thanks.
2011/10/06
[ "https://Stackoverflow.com/questions/7674955", "https://Stackoverflow.com", "https://Stackoverflow.com/users/224636/" ]
That sounds like it should be on `IOrganization` - that's what you'll call it on, after all. What you *have* is the organization, you *want* the list of people - you can't *start* fromt the list of people, so it *must* be part of the `IOrganization` interface. I find it strange to have *plural* interface names to start with - I'd expect `IOrganization` for a single organization, and `IPerson` for a single person. ``` public interface IOrganization { IList<IPerson> GetPeople(); } ```
Which belongs to which? It seems to me that `iOrganisation.People` would be a list of people ( is your "IPeople" interface representing a list of people or a single person? ) belonging to the organisation. Likewise you might have an `IPeople.Organisations` that lists all organisations that a person belongs to. Both will probably have a different underlying mechanism - maybe calling the same lookup table - it doesn't matter to the person calling the code.
7,674,955
I am developing an asp.net application where i have a dataset having 3 tables i.e. `ds.Tables[0], Tables[1] and Tables[2]` I need to find minimum number and maximum number out of all the 3 tables of dataset. How to do that? I found similar question in SO [here](https://stackoverflow.com/questions/2442525/how-to-select-min-and-max-values-of-a-column-in-a-datatable) but not sure how that would help me getting my way? **UPDATED:** ``` double minValue = double.MinValue; double maxValue = double.MaxValue; foreach (DataRow dr in dtSMPS.Rows) { double actualValue = dr.Field<double>("TOTAL_SUM"); // This fails specifying type cast error minValue = Math.Min(minValue, actualValue); maxValue = Math.Max(maxValue, actualValue); } ``` Please guide! Thanks.
2011/10/06
[ "https://Stackoverflow.com/questions/7674955", "https://Stackoverflow.com", "https://Stackoverflow.com/users/224636/" ]
That sounds like it should be on `IOrganization` - that's what you'll call it on, after all. What you *have* is the organization, you *want* the list of people - you can't *start* fromt the list of people, so it *must* be part of the `IOrganization` interface. I find it strange to have *plural* interface names to start with - I'd expect `IOrganization` for a single organization, and `IPerson` for a single person. ``` public interface IOrganization { IList<IPerson> GetPeople(); } ```
First of all, your should probably not have pluralized interface names. So call them IOrganization and IPerson and then on your `IOrganisation` interface you might have a method called: ``` IEnumerable<IPerson> GetPeople() ```
7,674,955
I am developing an asp.net application where i have a dataset having 3 tables i.e. `ds.Tables[0], Tables[1] and Tables[2]` I need to find minimum number and maximum number out of all the 3 tables of dataset. How to do that? I found similar question in SO [here](https://stackoverflow.com/questions/2442525/how-to-select-min-and-max-values-of-a-column-in-a-datatable) but not sure how that would help me getting my way? **UPDATED:** ``` double minValue = double.MinValue; double maxValue = double.MaxValue; foreach (DataRow dr in dtSMPS.Rows) { double actualValue = dr.Field<double>("TOTAL_SUM"); // This fails specifying type cast error minValue = Math.Min(minValue, actualValue); maxValue = Math.Max(maxValue, actualValue); } ``` Please guide! Thanks.
2011/10/06
[ "https://Stackoverflow.com/questions/7674955", "https://Stackoverflow.com", "https://Stackoverflow.com/users/224636/" ]
That sounds like it should be on `IOrganization` - that's what you'll call it on, after all. What you *have* is the organization, you *want* the list of people - you can't *start* fromt the list of people, so it *must* be part of the `IOrganization` interface. I find it strange to have *plural* interface names to start with - I'd expect `IOrganization` for a single organization, and `IPerson` for a single person. ``` public interface IOrganization { IList<IPerson> GetPeople(); } ```
If you think of an organization as a collection containing people, then it's intuitive to put that in `IOrganization`. It would look like this: ``` interface IOrganization { IList<IPeople> Members { get; } } ```
7,674,955
I am developing an asp.net application where i have a dataset having 3 tables i.e. `ds.Tables[0], Tables[1] and Tables[2]` I need to find minimum number and maximum number out of all the 3 tables of dataset. How to do that? I found similar question in SO [here](https://stackoverflow.com/questions/2442525/how-to-select-min-and-max-values-of-a-column-in-a-datatable) but not sure how that would help me getting my way? **UPDATED:** ``` double minValue = double.MinValue; double maxValue = double.MaxValue; foreach (DataRow dr in dtSMPS.Rows) { double actualValue = dr.Field<double>("TOTAL_SUM"); // This fails specifying type cast error minValue = Math.Min(minValue, actualValue); maxValue = Math.Max(maxValue, actualValue); } ``` Please guide! Thanks.
2011/10/06
[ "https://Stackoverflow.com/questions/7674955", "https://Stackoverflow.com", "https://Stackoverflow.com/users/224636/" ]
First of all, your should probably not have pluralized interface names. So call them IOrganization and IPerson and then on your `IOrganisation` interface you might have a method called: ``` IEnumerable<IPerson> GetPeople() ```
Which belongs to which? It seems to me that `iOrganisation.People` would be a list of people ( is your "IPeople" interface representing a list of people or a single person? ) belonging to the organisation. Likewise you might have an `IPeople.Organisations` that lists all organisations that a person belongs to. Both will probably have a different underlying mechanism - maybe calling the same lookup table - it doesn't matter to the person calling the code.
7,674,955
I am developing an asp.net application where i have a dataset having 3 tables i.e. `ds.Tables[0], Tables[1] and Tables[2]` I need to find minimum number and maximum number out of all the 3 tables of dataset. How to do that? I found similar question in SO [here](https://stackoverflow.com/questions/2442525/how-to-select-min-and-max-values-of-a-column-in-a-datatable) but not sure how that would help me getting my way? **UPDATED:** ``` double minValue = double.MinValue; double maxValue = double.MaxValue; foreach (DataRow dr in dtSMPS.Rows) { double actualValue = dr.Field<double>("TOTAL_SUM"); // This fails specifying type cast error minValue = Math.Min(minValue, actualValue); maxValue = Math.Max(maxValue, actualValue); } ``` Please guide! Thanks.
2011/10/06
[ "https://Stackoverflow.com/questions/7674955", "https://Stackoverflow.com", "https://Stackoverflow.com/users/224636/" ]
First of all, your should probably not have pluralized interface names. So call them IOrganization and IPerson and then on your `IOrganisation` interface you might have a method called: ``` IEnumerable<IPerson> GetPeople() ```
If you think of an organization as a collection containing people, then it's intuitive to put that in `IOrganization`. It would look like this: ``` interface IOrganization { IList<IPeople> Members { get; } } ```
34,399,423
I've got some problems with my Connection string. Seached the web for some mistakes but didn't got any further. Is there something changed between SQL Server versions? ``` <?xml version="1.0" encoding="utf-8" ?> <configuration> <configSections> </configSections> <connectionStrings> <add name="BeursTD.Properties.Settings.sdtcaptConnectionString" connectionString="Data Source=localhost\SQLEXPRESS,1433;Initial Catalog=sdtcapt;User ID=XXXX;Password=XXXX" providerName="System.Data.SqlClient" /> </connectionStrings> </configuration> ```
2015/12/21
[ "https://Stackoverflow.com/questions/34399423", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4159130/" ]
There are at least two reasons why this issue (`Client Error: Remaining data too small for BSON object`) appears: **1. PHP MongoDB driver is not compatible with MongoDB installed on the machine.** (originally mentioned in the [first answer](https://stackoverflow.com/a/34646148/309031)). Examine PHP driver version set up on your machine on `<?php phpinfo();` page: [![enter image description here](https://i.stack.imgur.com/oaB0u.jpg)](https://i.stack.imgur.com/oaB0u.jpg) Retrieve MongoDB version in use with: ``` mongod --version\ # db version v3.2.0 ``` Use [compatibility table on MongoDB website](https://docs.mongodb.org/ecosystem/drivers/php/#compatibility) to see whether examined PHP MongoDB driver version is compatible with MongoDB version: [![enter image description here](https://i.stack.imgur.com/8uMyC.jpg)](https://i.stack.imgur.com/8uMyC.jpg) If versions are not compatible, it is required to uninstall one of the existing parts and install compatible version. From my own experience, it is much easier to change PHP MongoDB driver, since only different `.so` extension file is required. **2. Two PHP MongoDB drivers are installed on the machine.** Since [`MongoClient`](http://php.net/manual/en/class.mongoclient.php) is deprecated, many tutorials and articles online (including [official mongo-php-driver repository on Github](https://github.com/mongodb/mongo-php-driver#installation)) now guides to install `mongodb`, not `mongo` PHP driver. Year+ before, everyone was pointing at `mongo` extension, however. Because of this change from `mongo` to `mongodb`, we might get both extensions defined in `php.ini` file. *Just make sure, only one extension is defined under "Dynamic Extension" section*: [![enter image description here](https://i.stack.imgur.com/4lPG6.jpg)](https://i.stack.imgur.com/4lPG6.jpg) --- Hope somebody gets this answer useful when looking for a solution to fix "Remaining data too small for BSON object" error working with MongoDB through PHP MongoDB driver.
The issue was that Laravel was unable to communicate with MongoDB because I was using the mongodb-1.1 php driver and MongoDB 3.2 together. According to the table found on this page: <https://docs.mongodb.org/ecosystem/drivers/php/>, these two versions are not compatible. I uninstalled MongoDB 3.2 and installed MongoDB 3.O, and the problem was solved.
64,569,792
These are my haves: ``` vec <- seq(1, 3, by = 1) df <- data.frame(x1 = c("a1", "a2")) ``` and this is my wants: ``` x1 x2 1 a1 1 2 a2 1 3 a1 2 4 a2 2 5 a1 3 6 a2 3 ``` I basically want to replicate the data frame according to the values in the vector vec. This is my working (possibly inefficient approach): ``` vec <- seq(1, 3, by = 1) df <- data.frame(x1 = c("a1", "a2")) results <- NULL for (v in vec) { results <- rbind(results, cbind(df, x2=v)) } results ``` Maybe there is a better way? Sorry this is more like a code review. Thanks! PS: Thanks for all your great answers. Sorry should have thought about some myself but it is early here. I will have to accept one. Sorry no hard feelings!
2020/10/28
[ "https://Stackoverflow.com/questions/64569792", "https://Stackoverflow.com", "https://Stackoverflow.com/users/283538/" ]
You can use `crossing` : ``` tidyr::crossing(df, vec) %>% dplyr::arrange(vec) # x1 vec # <chr> <dbl> #1 a1 1 #2 a2 1 #3 a1 2 #4 a2 2 #5 a1 3 #6 a2 3 ``` Also, ``` tidyr::expand_grid(df, vec) %>% dplyr::arrange(vec) ```
One option could be: ``` data.frame(x1 = df, x2 = rep(vec, each = nrow(df))) x1 x2 1 a1 1 2 a2 1 3 a1 2 4 a2 2 5 a1 3 6 a2 3 ```
64,569,792
These are my haves: ``` vec <- seq(1, 3, by = 1) df <- data.frame(x1 = c("a1", "a2")) ``` and this is my wants: ``` x1 x2 1 a1 1 2 a2 1 3 a1 2 4 a2 2 5 a1 3 6 a2 3 ``` I basically want to replicate the data frame according to the values in the vector vec. This is my working (possibly inefficient approach): ``` vec <- seq(1, 3, by = 1) df <- data.frame(x1 = c("a1", "a2")) results <- NULL for (v in vec) { results <- rbind(results, cbind(df, x2=v)) } results ``` Maybe there is a better way? Sorry this is more like a code review. Thanks! PS: Thanks for all your great answers. Sorry should have thought about some myself but it is early here. I will have to accept one. Sorry no hard feelings!
2020/10/28
[ "https://Stackoverflow.com/questions/64569792", "https://Stackoverflow.com", "https://Stackoverflow.com/users/283538/" ]
You can use `crossing` : ``` tidyr::crossing(df, vec) %>% dplyr::arrange(vec) # x1 vec # <chr> <dbl> #1 a1 1 #2 a2 1 #3 a1 2 #4 a2 2 #5 a1 3 #6 a2 3 ``` Also, ``` tidyr::expand_grid(df, vec) %>% dplyr::arrange(vec) ```
`expand.grid` can give all combinations of two vectors. ``` expand.grid(x1 = df$x1, vec = vec) #> x1 vec #> 1 a1 1 #> 2 a2 1 #> 3 a1 2 #> 4 a2 2 #> 5 a1 3 #> 6 a2 3 ```
60,351,355
I am trying to make my nav bar sit parallel with my logo but I'm having difficulty doing this. First of all, when I enter the code for the image, the image afterwards doesn't display at the top of the page. Instead, it sits about 40px below the page. I have tried using floats, but have had no luck. I have created a negative value of -20px for the logo to sit further at the top of the page but would like to know if that is normal practice in CSS I have tried looking at youtube videos but the code they share doesn't seem to work on my project. I'm just wondering whether the image may be a bit too big for the header ![](https://i.stack.imgur.com/ep89u.png)
2020/02/22
[ "https://Stackoverflow.com/questions/60351355", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12943430/" ]
"To maintain the integrity of the data dictionary, tables in the SYS schema are manipulated only by the database. They should never be modified by any user or database administrator. You must not create any tables in the SYS schema." <https://docs.oracle.com/database/121/ADMQS/GUID-CF1CD853-AF15-41EC-BC80-61918C73FDB5.htm#ADMQS12003>
Try to put in this order: ``` ALTER TABLE table_name DROP COLUMN column_name; ``` If the table has data it doesn't work.
187,493
Input ----- A single hex 6-digit colour code, capital letter, without `#`. Can also be a 24-bit integer if you prefer. Output ------ The closest HTML color *name* (e.g `red`, or `dark-salmon`, as defined as <https://www.w3schools.com/colors/colors_names.asp> or see below). Distance is defined by summing the difference in red, green and blue channels. Examples -------- > > `FF04FE`: `magenta` > > > `FFFFFF`: `white` > > > `457CCB` (halfway between `steelblue` and `darkslateblue`): `steelblue` (round **up**) > > > Rules ----- * Standard loopholes apply. * Standard I/O applies * Round up to the color with the higher channel sum if halfway between two colors. If two colours have the same channel sum, output the one which is higher as a hex code: e.g `red` = `#FF0000` = 16711680 > `blue` = `#0000FF` = 256 * If one hex code has two names (e.g. `grey` and `gray`), output either. * Outputs can be capitalised and hyphenated how you like * Trailing/preceding spaces/newlines are fine * You must output the names in full. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins. Colors ------ As per suggestion in the comments, here are all of the color names with respective hex values in CSV format: ``` Color Name,HEX Black,#000000 Navy,#000080 DarkBlue,#00008B MediumBlue,#0000CD Blue,#0000FF DarkGreen,#006400 Green,#008000 Teal,#008080 DarkCyan,#008B8B DeepSkyBlue,#00BFFF DarkTurquoise,#00CED1 MediumSpringGreen,#00FA9A Lime,#00FF00 SpringGreen,#00FF7F Aqua,#00FFFF Cyan,#00FFFF MidnightBlue,#191970 DodgerBlue,#1E90FF LightSeaGreen,#20B2AA ForestGreen,#228B22 SeaGreen,#2E8B57 DarkSlateGray,#2F4F4F DarkSlateGrey,#2F4F4F LimeGreen,#32CD32 MediumSeaGreen,#3CB371 Turquoise,#40E0D0 RoyalBlue,#4169E1 SteelBlue,#4682B4 DarkSlateBlue,#483D8B MediumTurquoise,#48D1CC Indigo,#4B0082 DarkOliveGreen,#556B2F CadetBlue,#5F9EA0 CornflowerBlue,#6495ED RebeccaPurple,#663399 MediumAquaMarine,#66CDAA DimGray,#696969 DimGrey,#696969 SlateBlue,#6A5ACD OliveDrab,#6B8E23 SlateGray,#708090 SlateGrey,#708090 LightSlateGray,#778899 LightSlateGrey,#778899 MediumSlateBlue,#7B68EE LawnGreen,#7CFC00 Chartreuse,#7FFF00 Aquamarine,#7FFFD4 Maroon,#800000 Purple,#800080 Olive,#808000 Gray,#808080 Grey,#808080 SkyBlue,#87CEEB LightSkyBlue,#87CEFA BlueViolet,#8A2BE2 DarkRed,#8B0000 DarkMagenta,#8B008B SaddleBrown,#8B4513 DarkSeaGreen,#8FBC8F LightGreen,#90EE90 MediumPurple,#9370DB DarkViolet,#9400D3 PaleGreen,#98FB98 DarkOrchid,#9932CC YellowGreen,#9ACD32 Sienna,#A0522D Brown,#A52A2A DarkGray,#A9A9A9 DarkGrey,#A9A9A9 LightBlue,#ADD8E6 GreenYellow,#ADFF2F PaleTurquoise,#AFEEEE LightSteelBlue,#B0C4DE PowderBlue,#B0E0E6 FireBrick,#B22222 DarkGoldenRod,#B8860B MediumOrchid,#BA55D3 RosyBrown,#BC8F8F DarkKhaki,#BDB76B Silver,#C0C0C0 MediumVioletRed,#C71585 IndianRed,#CD5C5C Peru,#CD853F Chocolate,#D2691E Tan,#D2B48C LightGray,#D3D3D3 LightGrey,#D3D3D3 Thistle,#D8BFD8 Orchid,#DA70D6 GoldenRod,#DAA520 PaleVioletRed,#DB7093 Crimson,#DC143C Gainsboro,#DCDCDC Plum,#DDA0DD BurlyWood,#DEB887 LightCyan,#E0FFFF Lavender,#E6E6FA DarkSalmon,#E9967A Violet,#EE82EE PaleGoldenRod,#EEE8AA LightCoral,#F08080 Khaki,#F0E68C AliceBlue,#F0F8FF HoneyDew,#F0FFF0 Azure,#F0FFFF SandyBrown,#F4A460 Wheat,#F5DEB3 Beige,#F5F5DC WhiteSmoke,#F5F5F5 MintCream,#F5FFFA GhostWhite,#F8F8FF Salmon,#FA8072 AntiqueWhite,#FAEBD7 Linen,#FAF0E6 LightGoldenRodYellow,#FAFAD2 OldLace,#FDF5E6 Red,#FF0000 Fuchsia,#FF00FF Magenta,#FF00FF DeepPink,#FF1493 OrangeRed,#FF4500 Tomato,#FF6347 HotPink,#FF69B4 Coral,#FF7F50 DarkOrange,#FF8C00 LightSalmon,#FFA07A Orange,#FFA500 LightPink,#FFB6C1 Pink,#FFC0CB Gold,#FFD700 PeachPuff,#FFDAB9 NavajoWhite,#FFDEAD Moccasin,#FFE4B5 Bisque,#FFE4C4 MistyRose,#FFE4E1 BlanchedAlmond,#FFEBCD PapayaWhip,#FFEFD5 LavenderBlush,#FFF0F5 SeaShell,#FFF5EE Cornsilk,#FFF8DC LemonChiffon,#FFFACD FloralWhite,#FFFAF0 Snow,#FFFAFA Yellow,#FFFF00 LightYellow,#FFFFE0 Ivory,#FFFFF0 White,#FFFFFF ```
2019/06/30
[ "https://codegolf.stackexchange.com/questions/187493", "https://codegolf.stackexchange.com", "https://codegolf.stackexchange.com/users/85546/" ]
[Jelly](https://github.com/DennisMitchell/jelly), ~~1015~~ 914 bytes ==================================================================== ``` “¥.⁻ḲU3ŒẆȯ§.eḊC¤ŀ"}Ʋ59£Uŀ'⁶ɠıṇȥLcṆɓ?^¢Ỵɠ.ȮẆẆḊqʠu½ỊƑfĠ⁴ µ¥ɓƭÑUC½ṁUĿẆṃ⁹S/÷Ɓɗ>ṭ"»Ḳ33r64¤,Ọy“µṂFŀƲOḌẇȤạ2œxṾk,E.LẸpḄ2s⁵Ṛç¦ṆkAẋ=çw©ḌĊẒƤm`;ṄȧṄİɦbṠṆṛ⁴Ḟ[CƊėQẏƑ<:⁾Þḍ?çⱮ3ƈṗ¬!7Hẏywœ⁽Ẉ¤ṾƈpHṗ(⁾ƲḢdƲḃ'¦ṇ9ẏP¡ċ⁻ȤẒṬf§®ṬẒpJÞẒẸṪÄƊhḊḃ7ʠ%ƈėc+ġȦı©ḄO⁸ṗ:WṠß@Ä|ż_g¹Ʋ®[*ẹ5¡Ẹßė¶~[ȷ'ȧẊṖZẋ¦ẉ7Ġ⁽ė⁽ƁLP`²¶⁶* Ġv|$ṭⱮẋ_ƭø¦Ẇ-*ɓɼhCUṙƭƭƓS7Ø⁵¤³¢Ʋẉ!§ḟƇṣḟṛḳṠƬ4ẓḢTḌZżƇȦQxw}ḃçṣȮv⁷ȤĊẏyNỵʠÄ⁸hLġị³TİọȧfÞȤTO&ṡ°⁼`WẹạẇḂvðFmż]ɦo½ƓṂḟȯ#Æ⁺T)ṃç=ḣṆø⁽Wpʂqṫ&⁷¶S®¢ð:\ṚMĖḌ½⁽_ạ⁵]Xlȷg¿£⁺x0ṁo8ẒṛżøuɲẈ®§Bṡr:ċ³ḷb|Mku¬V°ḟƲ!ɦɠ4¬>ḷ^XḶɼ5[ṇƑȮ.XȮƙẎbḊÐþFæṁoOṗ⁺mṪ-&ƊṅƑḋ$!`€ɓḥƤ¡ɗbH⁻ḃÄ⁵!Ñėḅƈḳm⁴ḳcÐⱮ⁷ỤḍġḷȥṀSĖ»Ḳ “⁸¢!İƝ\8¢[V⁸¢Ñ"ĠƙḶ-Æ⁷⁾Æ⁵¢⁸¢ƙhLṂS×®Ẓ©Aḅ¦ṚÆ&nj£ÇØ¿waþM=ÆḂḌ¢³(Ñḷx¦DẊ¢Aẓ©ḋ¬!ƁV ṾÐẉœ¦2Ä¢⁼C®⁶ẇ£ḋṀ¤çẠÐȧIæḌH€5ẋ¥®⁹µ⁻£⁴⁸¢AƇ¢⁸¢£*ç-Ụz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c6TcO9@NT/fu4Iybc3bqcl5B4UXTzaas2FnruxkcvzJGB2fQEOsXXJ1dbHkQL8OktLMA7WEjeRf9YQb78VWoCkVLXI57AcoBSFLSgzR6zYkfaKUMl0wSiw6yl@Lb0vJz1WWAmTnVB@LtwHntFMUP/Zew0elm2CQvjcgRJrfaT5aMnkVHbIyPbKGxBjHPcdXmOO4vNcx3rLSotHz0TEkXVjruRebDePPoPw "Jelly – Try It Online") Thanks to @Arnauld for a suggestion that saved 41 bytes! Full program. Takes colour as 24-bit integer as its argument and returns the colour name. Explanation ----------- ### Helper link Colour names. Stored using compressed string, but with common words replaced by single ASCII characters in range 33 to 64 ``` “¥...» | Compressed string "blue brown coral..." Ḳ | Split at spaces 33r64¤, | Pair the numbers 33 to 64 with these words [[33,34,35,...],["blue","brown","coral",...]] Ọ | Convert the numbers to Unicode characters [["!",'"',"#",...],["blue","brown","coral",...]] y“µ...» | Translate the compressed string "black navy %! ..." using the mapping generated above Ḳ | Split at spaces ``` ### Main link Stage 1: Start generating list of colour numbers. The increments between colour numbers are stored as between 1 and 3 base 249 digits. The increment has been multiplied by 3, converted to base 249 and then the number of digits minus 1 has been added to the least significant digit, before reversing the order of digits. ``` “⁸...‘© | Copy compressed integers 136,1,33,198,... to register ṛ | Right value (will yield value of the following): ¤®Ð¿ | - While the register is non-empty, do the following, collecting values as we go: ®Ḣ¤ | - Take the first value from the list held in the register, popping it from the list, x %¡3 | - Repeat the following (x mod 3 times) ⁺;$ | - Concatenate the first value from the list held in the register, popping it from the list Ḋ | Remove the first item (will be 'None') ``` Stage 2: Finish generating colour numbers and look up the input ``` ḅ249 | Convert from base 249 to integer :3 | Integer divide by 3 Ä | Cumulative sum: 128,139,205,255,25600,... Ż | Prepend zero , | Pair with input b⁹ | Convert to base 256: [[0],[128],[139],[205],[255],[100,0],...], [input in base 256] U | Reverse order of innermost lists (so RGB becomes BGR, GB becomes BG and B remains as B); this is because colours with no red component will be a list with only two members, and colours with only blue will just have one member ʋ@€/ | Reduce using the following as a dyad for each; effectively calls the following once for each colour with the reversed base-256 colour as left argument and the reversed base-256 input as right ạ | - Absolute difference of the colour and the output of stage 1 N | Negate , | - Pair with the colour § | - Sum each of these M | Indices of maximum Ṫ | Tail (will be the index of the largest colour value) ị¢ | Index into helper link ``` Colours are reversed before comparing because colours with no red component (for example) will end up as a 2 component list. TIO link generates 10 random colours and shows the output so will be different each time.
Wolfram Language (Mathematica), 164 bytes ========================================= *Note:* This only works in Mathematica 12.0 due to a bug in previous versions. This also means there is no TIO link. ```mma g[c_]:=Last@Keys@SortBy[Round[255List@@@<|"HTML"~ColorData~"ColorRules"~Join~{"RebeccaPurple"->RGBColor@"#639"}|>],{-Total@Abs[IntegerDigits[c,256,3]-#]&,Total,#&}] ``` Defines the function `g`, which takes an integer as input. Test cases: ```mma AssociationMap[g, {327581, 3483113, 2820178, 4358965, 2058772, 13569770, 8698378, 2897368, 3896382, 12856883}] (* <| 327581 -> "MediumSpringGreen", 3483113 -> "RoyalBlue", 2820178 -> "MidnightBlue", 4358965 -> "DarkOliveGreen", 2058772 -> "ForestGreen", 13569770 -> "Magenta", 8698378 -> "Olive", 2897368 -> "RoyalBlue", 3896382 -> "DarkOliveGreen", 12856883 -> "Brown" |> *) ``` Unfortunately, quite a few bytes are wasted on adding "RebeccaPurple" to the built-in list of colors, which is missing for some reason. The rest is pretty straightforward, we just sort the colors by their distance to the input, breaking ties with the sum of channel values and then the absolute ordering.
187,493
Input ----- A single hex 6-digit colour code, capital letter, without `#`. Can also be a 24-bit integer if you prefer. Output ------ The closest HTML color *name* (e.g `red`, or `dark-salmon`, as defined as <https://www.w3schools.com/colors/colors_names.asp> or see below). Distance is defined by summing the difference in red, green and blue channels. Examples -------- > > `FF04FE`: `magenta` > > > `FFFFFF`: `white` > > > `457CCB` (halfway between `steelblue` and `darkslateblue`): `steelblue` (round **up**) > > > Rules ----- * Standard loopholes apply. * Standard I/O applies * Round up to the color with the higher channel sum if halfway between two colors. If two colours have the same channel sum, output the one which is higher as a hex code: e.g `red` = `#FF0000` = 16711680 > `blue` = `#0000FF` = 256 * If one hex code has two names (e.g. `grey` and `gray`), output either. * Outputs can be capitalised and hyphenated how you like * Trailing/preceding spaces/newlines are fine * You must output the names in full. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins. Colors ------ As per suggestion in the comments, here are all of the color names with respective hex values in CSV format: ``` Color Name,HEX Black,#000000 Navy,#000080 DarkBlue,#00008B MediumBlue,#0000CD Blue,#0000FF DarkGreen,#006400 Green,#008000 Teal,#008080 DarkCyan,#008B8B DeepSkyBlue,#00BFFF DarkTurquoise,#00CED1 MediumSpringGreen,#00FA9A Lime,#00FF00 SpringGreen,#00FF7F Aqua,#00FFFF Cyan,#00FFFF MidnightBlue,#191970 DodgerBlue,#1E90FF LightSeaGreen,#20B2AA ForestGreen,#228B22 SeaGreen,#2E8B57 DarkSlateGray,#2F4F4F DarkSlateGrey,#2F4F4F LimeGreen,#32CD32 MediumSeaGreen,#3CB371 Turquoise,#40E0D0 RoyalBlue,#4169E1 SteelBlue,#4682B4 DarkSlateBlue,#483D8B MediumTurquoise,#48D1CC Indigo,#4B0082 DarkOliveGreen,#556B2F CadetBlue,#5F9EA0 CornflowerBlue,#6495ED RebeccaPurple,#663399 MediumAquaMarine,#66CDAA DimGray,#696969 DimGrey,#696969 SlateBlue,#6A5ACD OliveDrab,#6B8E23 SlateGray,#708090 SlateGrey,#708090 LightSlateGray,#778899 LightSlateGrey,#778899 MediumSlateBlue,#7B68EE LawnGreen,#7CFC00 Chartreuse,#7FFF00 Aquamarine,#7FFFD4 Maroon,#800000 Purple,#800080 Olive,#808000 Gray,#808080 Grey,#808080 SkyBlue,#87CEEB LightSkyBlue,#87CEFA BlueViolet,#8A2BE2 DarkRed,#8B0000 DarkMagenta,#8B008B SaddleBrown,#8B4513 DarkSeaGreen,#8FBC8F LightGreen,#90EE90 MediumPurple,#9370DB DarkViolet,#9400D3 PaleGreen,#98FB98 DarkOrchid,#9932CC YellowGreen,#9ACD32 Sienna,#A0522D Brown,#A52A2A DarkGray,#A9A9A9 DarkGrey,#A9A9A9 LightBlue,#ADD8E6 GreenYellow,#ADFF2F PaleTurquoise,#AFEEEE LightSteelBlue,#B0C4DE PowderBlue,#B0E0E6 FireBrick,#B22222 DarkGoldenRod,#B8860B MediumOrchid,#BA55D3 RosyBrown,#BC8F8F DarkKhaki,#BDB76B Silver,#C0C0C0 MediumVioletRed,#C71585 IndianRed,#CD5C5C Peru,#CD853F Chocolate,#D2691E Tan,#D2B48C LightGray,#D3D3D3 LightGrey,#D3D3D3 Thistle,#D8BFD8 Orchid,#DA70D6 GoldenRod,#DAA520 PaleVioletRed,#DB7093 Crimson,#DC143C Gainsboro,#DCDCDC Plum,#DDA0DD BurlyWood,#DEB887 LightCyan,#E0FFFF Lavender,#E6E6FA DarkSalmon,#E9967A Violet,#EE82EE PaleGoldenRod,#EEE8AA LightCoral,#F08080 Khaki,#F0E68C AliceBlue,#F0F8FF HoneyDew,#F0FFF0 Azure,#F0FFFF SandyBrown,#F4A460 Wheat,#F5DEB3 Beige,#F5F5DC WhiteSmoke,#F5F5F5 MintCream,#F5FFFA GhostWhite,#F8F8FF Salmon,#FA8072 AntiqueWhite,#FAEBD7 Linen,#FAF0E6 LightGoldenRodYellow,#FAFAD2 OldLace,#FDF5E6 Red,#FF0000 Fuchsia,#FF00FF Magenta,#FF00FF DeepPink,#FF1493 OrangeRed,#FF4500 Tomato,#FF6347 HotPink,#FF69B4 Coral,#FF7F50 DarkOrange,#FF8C00 LightSalmon,#FFA07A Orange,#FFA500 LightPink,#FFB6C1 Pink,#FFC0CB Gold,#FFD700 PeachPuff,#FFDAB9 NavajoWhite,#FFDEAD Moccasin,#FFE4B5 Bisque,#FFE4C4 MistyRose,#FFE4E1 BlanchedAlmond,#FFEBCD PapayaWhip,#FFEFD5 LavenderBlush,#FFF0F5 SeaShell,#FFF5EE Cornsilk,#FFF8DC LemonChiffon,#FFFACD FloralWhite,#FFFAF0 Snow,#FFFAFA Yellow,#FFFF00 LightYellow,#FFFFE0 Ivory,#FFFFF0 White,#FFFFFF ```
2019/06/30
[ "https://codegolf.stackexchange.com/questions/187493", "https://codegolf.stackexchange.com", "https://codegolf.stackexchange.com/users/85546/" ]
[C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 231+21=252 bytes ======================================================================================================================== ```cs s=>Color.FromArgb(Convert.ToInt32(s,16));f=s=>Enum.GetNames(typeof(KnownColor)).Select(x=>Color.FromName(x)).Where(x=>!x.IsSystemColor&x.A>254).OrderBy(x=>Math.Abs(x.R-C(s).R)+Math.Abs(x.G-C(s).G)+Math.Abs(x.B-C(s).B)).First().Name ``` Explanation: ```cs using System.Drawing; //System library that handles Colors in C# C=s=>Color.FromArgb(Convert.ToInt32(s,16)); //helper method. receives a hex string and returns it's Color f=s=>Enum.GetNames(typeof(KnownColor)) //collection of color names from the System.Drawing.KnownColor enum .Select(x=>Color.FromName(x)) //convert the color names to Colors .Where(x=>!x.IsSystemColor&x.A>254) //filter out unwanted colors .OrderBy(x=>Math.Abs(x.R-C(s).R) //order by increasing distance +Math.Abs(x.G-C(s).G) +Math.Abs(x.B-C(s).B)) .First().Name //return the closest color's name ``` For some reason, Tio complains that the namespace 'Drawing' does not exist in the namespace 'System', despite the source project [Mono](https://www.mono-project.com/docs/gui/drawing/) stating it's compatible. It works fine in VisualStudio though. EDIT: apparently it [hasn't been implemented](https://github.com/TryItOnline/cs-mono/blob/master/README.md) into Tio yet! [Try it online!](https://tio.run/##bc9Li8IwEAfwu5@i62FJWA2aah@4FpL0gewLdMFz7aZasMmSxLV@@m5rL0o9hfnNn5lJpseZLuqTLsTe2ly04SUKVXpuysUgPonsVRvVFCOrewMrv3cmj1IFFrOWtV4G1wrFSpZE7XeASfHHlUHfciWMjYEeTR0IF/myiUbiVKKEm8@05BqYyy@XOXgT8iyuQyBEG37kmQHV7dg2DaqmuT1wxdveU4VWurv8GnuuEAnwfAbRl/rhil7a0EdqDojsNKjQesyAhmgNX24w6TC5Q9ohbbbFhdIGQNSurxeDrSoMfy8EBzkYxrbvUG/Y/OveGaHuBPc9xFOX0b4T3w8j1veZEzqO23fbo9iPHuzFrj0nfXcp8WeTvseTcO49mONTHNl26/U/ "C# (Visual C# Interactive Compiler) – Try It Online")
Wolfram Language (Mathematica), 164 bytes ========================================= *Note:* This only works in Mathematica 12.0 due to a bug in previous versions. This also means there is no TIO link. ```mma g[c_]:=Last@Keys@SortBy[Round[255List@@@<|"HTML"~ColorData~"ColorRules"~Join~{"RebeccaPurple"->RGBColor@"#639"}|>],{-Total@Abs[IntegerDigits[c,256,3]-#]&,Total,#&}] ``` Defines the function `g`, which takes an integer as input. Test cases: ```mma AssociationMap[g, {327581, 3483113, 2820178, 4358965, 2058772, 13569770, 8698378, 2897368, 3896382, 12856883}] (* <| 327581 -> "MediumSpringGreen", 3483113 -> "RoyalBlue", 2820178 -> "MidnightBlue", 4358965 -> "DarkOliveGreen", 2058772 -> "ForestGreen", 13569770 -> "Magenta", 8698378 -> "Olive", 2897368 -> "RoyalBlue", 3896382 -> "DarkOliveGreen", 12856883 -> "Brown" |> *) ``` Unfortunately, quite a few bytes are wasted on adding "RebeccaPurple" to the built-in list of colors, which is missing for some reason. The rest is pretty straightforward, we just sort the colors by their distance to the input, breaking ties with the sum of channel values and then the absolute ordering.
187,493
Input ----- A single hex 6-digit colour code, capital letter, without `#`. Can also be a 24-bit integer if you prefer. Output ------ The closest HTML color *name* (e.g `red`, or `dark-salmon`, as defined as <https://www.w3schools.com/colors/colors_names.asp> or see below). Distance is defined by summing the difference in red, green and blue channels. Examples -------- > > `FF04FE`: `magenta` > > > `FFFFFF`: `white` > > > `457CCB` (halfway between `steelblue` and `darkslateblue`): `steelblue` (round **up**) > > > Rules ----- * Standard loopholes apply. * Standard I/O applies * Round up to the color with the higher channel sum if halfway between two colors. If two colours have the same channel sum, output the one which is higher as a hex code: e.g `red` = `#FF0000` = 16711680 > `blue` = `#0000FF` = 256 * If one hex code has two names (e.g. `grey` and `gray`), output either. * Outputs can be capitalised and hyphenated how you like * Trailing/preceding spaces/newlines are fine * You must output the names in full. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins. Colors ------ As per suggestion in the comments, here are all of the color names with respective hex values in CSV format: ``` Color Name,HEX Black,#000000 Navy,#000080 DarkBlue,#00008B MediumBlue,#0000CD Blue,#0000FF DarkGreen,#006400 Green,#008000 Teal,#008080 DarkCyan,#008B8B DeepSkyBlue,#00BFFF DarkTurquoise,#00CED1 MediumSpringGreen,#00FA9A Lime,#00FF00 SpringGreen,#00FF7F Aqua,#00FFFF Cyan,#00FFFF MidnightBlue,#191970 DodgerBlue,#1E90FF LightSeaGreen,#20B2AA ForestGreen,#228B22 SeaGreen,#2E8B57 DarkSlateGray,#2F4F4F DarkSlateGrey,#2F4F4F LimeGreen,#32CD32 MediumSeaGreen,#3CB371 Turquoise,#40E0D0 RoyalBlue,#4169E1 SteelBlue,#4682B4 DarkSlateBlue,#483D8B MediumTurquoise,#48D1CC Indigo,#4B0082 DarkOliveGreen,#556B2F CadetBlue,#5F9EA0 CornflowerBlue,#6495ED RebeccaPurple,#663399 MediumAquaMarine,#66CDAA DimGray,#696969 DimGrey,#696969 SlateBlue,#6A5ACD OliveDrab,#6B8E23 SlateGray,#708090 SlateGrey,#708090 LightSlateGray,#778899 LightSlateGrey,#778899 MediumSlateBlue,#7B68EE LawnGreen,#7CFC00 Chartreuse,#7FFF00 Aquamarine,#7FFFD4 Maroon,#800000 Purple,#800080 Olive,#808000 Gray,#808080 Grey,#808080 SkyBlue,#87CEEB LightSkyBlue,#87CEFA BlueViolet,#8A2BE2 DarkRed,#8B0000 DarkMagenta,#8B008B SaddleBrown,#8B4513 DarkSeaGreen,#8FBC8F LightGreen,#90EE90 MediumPurple,#9370DB DarkViolet,#9400D3 PaleGreen,#98FB98 DarkOrchid,#9932CC YellowGreen,#9ACD32 Sienna,#A0522D Brown,#A52A2A DarkGray,#A9A9A9 DarkGrey,#A9A9A9 LightBlue,#ADD8E6 GreenYellow,#ADFF2F PaleTurquoise,#AFEEEE LightSteelBlue,#B0C4DE PowderBlue,#B0E0E6 FireBrick,#B22222 DarkGoldenRod,#B8860B MediumOrchid,#BA55D3 RosyBrown,#BC8F8F DarkKhaki,#BDB76B Silver,#C0C0C0 MediumVioletRed,#C71585 IndianRed,#CD5C5C Peru,#CD853F Chocolate,#D2691E Tan,#D2B48C LightGray,#D3D3D3 LightGrey,#D3D3D3 Thistle,#D8BFD8 Orchid,#DA70D6 GoldenRod,#DAA520 PaleVioletRed,#DB7093 Crimson,#DC143C Gainsboro,#DCDCDC Plum,#DDA0DD BurlyWood,#DEB887 LightCyan,#E0FFFF Lavender,#E6E6FA DarkSalmon,#E9967A Violet,#EE82EE PaleGoldenRod,#EEE8AA LightCoral,#F08080 Khaki,#F0E68C AliceBlue,#F0F8FF HoneyDew,#F0FFF0 Azure,#F0FFFF SandyBrown,#F4A460 Wheat,#F5DEB3 Beige,#F5F5DC WhiteSmoke,#F5F5F5 MintCream,#F5FFFA GhostWhite,#F8F8FF Salmon,#FA8072 AntiqueWhite,#FAEBD7 Linen,#FAF0E6 LightGoldenRodYellow,#FAFAD2 OldLace,#FDF5E6 Red,#FF0000 Fuchsia,#FF00FF Magenta,#FF00FF DeepPink,#FF1493 OrangeRed,#FF4500 Tomato,#FF6347 HotPink,#FF69B4 Coral,#FF7F50 DarkOrange,#FF8C00 LightSalmon,#FFA07A Orange,#FFA500 LightPink,#FFB6C1 Pink,#FFC0CB Gold,#FFD700 PeachPuff,#FFDAB9 NavajoWhite,#FFDEAD Moccasin,#FFE4B5 Bisque,#FFE4C4 MistyRose,#FFE4E1 BlanchedAlmond,#FFEBCD PapayaWhip,#FFEFD5 LavenderBlush,#FFF0F5 SeaShell,#FFF5EE Cornsilk,#FFF8DC LemonChiffon,#FFFACD FloralWhite,#FFFAF0 Snow,#FFFAFA Yellow,#FFFF00 LightYellow,#FFFFE0 Ivory,#FFFFF0 White,#FFFFFF ```
2019/06/30
[ "https://codegolf.stackexchange.com/questions/187493", "https://codegolf.stackexchange.com", "https://codegolf.stackexchange.com/users/85546/" ]
[C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 231+21=252 bytes ======================================================================================================================== ```cs s=>Color.FromArgb(Convert.ToInt32(s,16));f=s=>Enum.GetNames(typeof(KnownColor)).Select(x=>Color.FromName(x)).Where(x=>!x.IsSystemColor&x.A>254).OrderBy(x=>Math.Abs(x.R-C(s).R)+Math.Abs(x.G-C(s).G)+Math.Abs(x.B-C(s).B)).First().Name ``` Explanation: ```cs using System.Drawing; //System library that handles Colors in C# C=s=>Color.FromArgb(Convert.ToInt32(s,16)); //helper method. receives a hex string and returns it's Color f=s=>Enum.GetNames(typeof(KnownColor)) //collection of color names from the System.Drawing.KnownColor enum .Select(x=>Color.FromName(x)) //convert the color names to Colors .Where(x=>!x.IsSystemColor&x.A>254) //filter out unwanted colors .OrderBy(x=>Math.Abs(x.R-C(s).R) //order by increasing distance +Math.Abs(x.G-C(s).G) +Math.Abs(x.B-C(s).B)) .First().Name //return the closest color's name ``` For some reason, Tio complains that the namespace 'Drawing' does not exist in the namespace 'System', despite the source project [Mono](https://www.mono-project.com/docs/gui/drawing/) stating it's compatible. It works fine in VisualStudio though. EDIT: apparently it [hasn't been implemented](https://github.com/TryItOnline/cs-mono/blob/master/README.md) into Tio yet! [Try it online!](https://tio.run/##bc9Li8IwEAfwu5@i62FJWA2aah@4FpL0gewLdMFz7aZasMmSxLV@@m5rL0o9hfnNn5lJpseZLuqTLsTe2ly04SUKVXpuysUgPonsVRvVFCOrewMrv3cmj1IFFrOWtV4G1wrFSpZE7XeASfHHlUHfciWMjYEeTR0IF/myiUbiVKKEm8@05BqYyy@XOXgT8iyuQyBEG37kmQHV7dg2DaqmuT1wxdveU4VWurv8GnuuEAnwfAbRl/rhil7a0EdqDojsNKjQesyAhmgNX24w6TC5Q9ohbbbFhdIGQNSurxeDrSoMfy8EBzkYxrbvUG/Y/OveGaHuBPc9xFOX0b4T3w8j1veZEzqO23fbo9iPHuzFrj0nfXcp8WeTvseTcO49mONTHNl26/U/ "C# (Visual C# Interactive Compiler) – Try It Online")
[Jelly](https://github.com/DennisMitchell/jelly), ~~1015~~ 914 bytes ==================================================================== ``` “¥.⁻ḲU3ŒẆȯ§.eḊC¤ŀ"}Ʋ59£Uŀ'⁶ɠıṇȥLcṆɓ?^¢Ỵɠ.ȮẆẆḊqʠu½ỊƑfĠ⁴ µ¥ɓƭÑUC½ṁUĿẆṃ⁹S/÷Ɓɗ>ṭ"»Ḳ33r64¤,Ọy“µṂFŀƲOḌẇȤạ2œxṾk,E.LẸpḄ2s⁵Ṛç¦ṆkAẋ=çw©ḌĊẒƤm`;ṄȧṄİɦbṠṆṛ⁴Ḟ[CƊėQẏƑ<:⁾Þḍ?çⱮ3ƈṗ¬!7Hẏywœ⁽Ẉ¤ṾƈpHṗ(⁾ƲḢdƲḃ'¦ṇ9ẏP¡ċ⁻ȤẒṬf§®ṬẒpJÞẒẸṪÄƊhḊḃ7ʠ%ƈėc+ġȦı©ḄO⁸ṗ:WṠß@Ä|ż_g¹Ʋ®[*ẹ5¡Ẹßė¶~[ȷ'ȧẊṖZẋ¦ẉ7Ġ⁽ė⁽ƁLP`²¶⁶* Ġv|$ṭⱮẋ_ƭø¦Ẇ-*ɓɼhCUṙƭƭƓS7Ø⁵¤³¢Ʋẉ!§ḟƇṣḟṛḳṠƬ4ẓḢTḌZżƇȦQxw}ḃçṣȮv⁷ȤĊẏyNỵʠÄ⁸hLġị³TİọȧfÞȤTO&ṡ°⁼`WẹạẇḂvðFmż]ɦo½ƓṂḟȯ#Æ⁺T)ṃç=ḣṆø⁽Wpʂqṫ&⁷¶S®¢ð:\ṚMĖḌ½⁽_ạ⁵]Xlȷg¿£⁺x0ṁo8ẒṛżøuɲẈ®§Bṡr:ċ³ḷb|Mku¬V°ḟƲ!ɦɠ4¬>ḷ^XḶɼ5[ṇƑȮ.XȮƙẎbḊÐþFæṁoOṗ⁺mṪ-&ƊṅƑḋ$!`€ɓḥƤ¡ɗbH⁻ḃÄ⁵!Ñėḅƈḳm⁴ḳcÐⱮ⁷ỤḍġḷȥṀSĖ»Ḳ “⁸¢!İƝ\8¢[V⁸¢Ñ"ĠƙḶ-Æ⁷⁾Æ⁵¢⁸¢ƙhLṂS×®Ẓ©Aḅ¦ṚÆ&nj£ÇØ¿waþM=ÆḂḌ¢³(Ñḷx¦DẊ¢Aẓ©ḋ¬!ƁV ṾÐẉœ¦2Ä¢⁼C®⁶ẇ£ḋṀ¤çẠÐȧIæḌH€5ẋ¥®⁹µ⁻£⁴⁸¢AƇ¢⁸¢£*ç-Ụz¬>ƈ£ʋ¢^ạṭ(ÇṪĠ¤Çŀ¬ÇḞ¢ṪĠÐCȥṖÞ¦ø}×⁹YÐƬAÇ×CÆævÇ#©ḥƙ£sVṀṙ¤ỊAÞtỤ¦AǬ⁶ʠ¤⁼ƈµ£ŒÞ¿§Œ÷~2~Ðɲċ×⁻¤SƤÐ}Z¦Fƙ°¹£Ḣ©£Ṁx£⁹j£Ƒs¤ɓ8¬_ḶØz°®ʂƬÐḢ@¢ẉ€¦ỴA¢Ä8gß-Ė⁸¿zṛ¤mGKÄœ>jµ\ạ¥>R¢ƤÐƤœⱮpµỴI¤Œ¤a<[Ɱa]ṠŒɲB"'(?ŀÆȦ6ȯœ|Dy¿1€ƤØ-WXßm€v¤Uнµẋ¦iœg€Ḥ£0-‘©ṛ®Ḣ¤⁺;$%¡3¤®Ð¿Ḋḅ249:3ÄŻ,b⁹UạN,§ʋ@€/MṪị¢ ``` [Try it online!](https://tio.run/##LVV9UxNHGP/fTwFogaJB5EUQFEUsxRZEy6uigliFqlTUyosDToKRINEayAwBrRCSIxltiBBecnfhZebZu507vsXeF6G/zXRgbudun93n97abRw@ePBk7OnLc/9BqsePJCDXVXmbOCX3K@k7x4gdCnaknxXT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TEppI7RZyMAkPUqxK8gmRXBQgzLdfhwu7unIycGBYgGkygxSrJR5ZbvdegKFHdhNSJgf6ElBhPQwC1jxq1BMfd8IXSpkyldlqUbb0EWatpUFW8d9/8OmaBGLuyDGKxjCpyl66KfIXZklba2QIcLfjDA295luSuBVXcIlJ7@xQL2UbZ4tUYypEwzuaDdZgCfqwDNUz6ZYbJj5jksmq3yRoi86gBJnBhdEZqaOLf2FlhRDMSXA5BA9QAv9tylqzmHTA4pjTL8ufc0CdsrwywYZUlq5wgITtyjWgE3XSZP8I/QVg@Yelfw0KM1nX5BiB6so0QO32MIrVCYPJ3kCOqqRS2Cgv4M8MCezVQdjvVX9bNllzEtBDl4hy6QM/vwr85rB2ke0fRti0Grtb7AYvbmCq24jOYSLOLN1FT8Lc6TcO9@NT/fu4Iybc3bqcl5B4UXTzaas2FnruxkcvzJGB2fQEOsXXJ1dbHkQL8OktLMA7WEjeRf9YQb78VWoCkVLXI57AcoBSFLSgzR6zYkfaKUMl0wSiw6yl@Lb0vJz1WWAmTnVB@LtwHntFMUP/Zew0elm2CQvjcgRJrfaT5aMnkVHbIyPbKGxBjHPcdXmOO4vNcx3rLSotHz0TEkXVjruRebDePPoPw "Jelly – Try It Online") Thanks to @Arnauld for a suggestion that saved 41 bytes! Full program. Takes colour as 24-bit integer as its argument and returns the colour name. Explanation ----------- ### Helper link Colour names. Stored using compressed string, but with common words replaced by single ASCII characters in range 33 to 64 ``` “¥...» | Compressed string "blue brown coral..." Ḳ | Split at spaces 33r64¤, | Pair the numbers 33 to 64 with these words [[33,34,35,...],["blue","brown","coral",...]] Ọ | Convert the numbers to Unicode characters [["!",'"',"#",...],["blue","brown","coral",...]] y“µ...» | Translate the compressed string "black navy %! ..." using the mapping generated above Ḳ | Split at spaces ``` ### Main link Stage 1: Start generating list of colour numbers. The increments between colour numbers are stored as between 1 and 3 base 249 digits. The increment has been multiplied by 3, converted to base 249 and then the number of digits minus 1 has been added to the least significant digit, before reversing the order of digits. ``` “⁸...‘© | Copy compressed integers 136,1,33,198,... to register ṛ | Right value (will yield value of the following): ¤®Ð¿ | - While the register is non-empty, do the following, collecting values as we go: ®Ḣ¤ | - Take the first value from the list held in the register, popping it from the list, x %¡3 | - Repeat the following (x mod 3 times) ⁺;$ | - Concatenate the first value from the list held in the register, popping it from the list Ḋ | Remove the first item (will be 'None') ``` Stage 2: Finish generating colour numbers and look up the input ``` ḅ249 | Convert from base 249 to integer :3 | Integer divide by 3 Ä | Cumulative sum: 128,139,205,255,25600,... Ż | Prepend zero , | Pair with input b⁹ | Convert to base 256: [[0],[128],[139],[205],[255],[100,0],...], [input in base 256] U | Reverse order of innermost lists (so RGB becomes BGR, GB becomes BG and B remains as B); this is because colours with no red component will be a list with only two members, and colours with only blue will just have one member ʋ@€/ | Reduce using the following as a dyad for each; effectively calls the following once for each colour with the reversed base-256 colour as left argument and the reversed base-256 input as right ạ | - Absolute difference of the colour and the output of stage 1 N | Negate , | - Pair with the colour § | - Sum each of these M | Indices of maximum Ṫ | Tail (will be the index of the largest colour value) ị¢ | Index into helper link ``` Colours are reversed before comparing because colours with no red component (for example) will end up as a 2 component list. TIO link generates 10 random colours and shows the output so will be different each time.
187,493
Input ----- A single hex 6-digit colour code, capital letter, without `#`. Can also be a 24-bit integer if you prefer. Output ------ The closest HTML color *name* (e.g `red`, or `dark-salmon`, as defined as <https://www.w3schools.com/colors/colors_names.asp> or see below). Distance is defined by summing the difference in red, green and blue channels. Examples -------- > > `FF04FE`: `magenta` > > > `FFFFFF`: `white` > > > `457CCB` (halfway between `steelblue` and `darkslateblue`): `steelblue` (round **up**) > > > Rules ----- * Standard loopholes apply. * Standard I/O applies * Round up to the color with the higher channel sum if halfway between two colors. If two colours have the same channel sum, output the one which is higher as a hex code: e.g `red` = `#FF0000` = 16711680 > `blue` = `#0000FF` = 256 * If one hex code has two names (e.g. `grey` and `gray`), output either. * Outputs can be capitalised and hyphenated how you like * Trailing/preceding spaces/newlines are fine * You must output the names in full. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins. Colors ------ As per suggestion in the comments, here are all of the color names with respective hex values in CSV format: ``` Color Name,HEX Black,#000000 Navy,#000080 DarkBlue,#00008B MediumBlue,#0000CD Blue,#0000FF DarkGreen,#006400 Green,#008000 Teal,#008080 DarkCyan,#008B8B DeepSkyBlue,#00BFFF DarkTurquoise,#00CED1 MediumSpringGreen,#00FA9A Lime,#00FF00 SpringGreen,#00FF7F Aqua,#00FFFF Cyan,#00FFFF MidnightBlue,#191970 DodgerBlue,#1E90FF LightSeaGreen,#20B2AA ForestGreen,#228B22 SeaGreen,#2E8B57 DarkSlateGray,#2F4F4F DarkSlateGrey,#2F4F4F LimeGreen,#32CD32 MediumSeaGreen,#3CB371 Turquoise,#40E0D0 RoyalBlue,#4169E1 SteelBlue,#4682B4 DarkSlateBlue,#483D8B MediumTurquoise,#48D1CC Indigo,#4B0082 DarkOliveGreen,#556B2F CadetBlue,#5F9EA0 CornflowerBlue,#6495ED RebeccaPurple,#663399 MediumAquaMarine,#66CDAA DimGray,#696969 DimGrey,#696969 SlateBlue,#6A5ACD OliveDrab,#6B8E23 SlateGray,#708090 SlateGrey,#708090 LightSlateGray,#778899 LightSlateGrey,#778899 MediumSlateBlue,#7B68EE LawnGreen,#7CFC00 Chartreuse,#7FFF00 Aquamarine,#7FFFD4 Maroon,#800000 Purple,#800080 Olive,#808000 Gray,#808080 Grey,#808080 SkyBlue,#87CEEB LightSkyBlue,#87CEFA BlueViolet,#8A2BE2 DarkRed,#8B0000 DarkMagenta,#8B008B SaddleBrown,#8B4513 DarkSeaGreen,#8FBC8F LightGreen,#90EE90 MediumPurple,#9370DB DarkViolet,#9400D3 PaleGreen,#98FB98 DarkOrchid,#9932CC YellowGreen,#9ACD32 Sienna,#A0522D Brown,#A52A2A DarkGray,#A9A9A9 DarkGrey,#A9A9A9 LightBlue,#ADD8E6 GreenYellow,#ADFF2F PaleTurquoise,#AFEEEE LightSteelBlue,#B0C4DE PowderBlue,#B0E0E6 FireBrick,#B22222 DarkGoldenRod,#B8860B MediumOrchid,#BA55D3 RosyBrown,#BC8F8F DarkKhaki,#BDB76B Silver,#C0C0C0 MediumVioletRed,#C71585 IndianRed,#CD5C5C Peru,#CD853F Chocolate,#D2691E Tan,#D2B48C LightGray,#D3D3D3 LightGrey,#D3D3D3 Thistle,#D8BFD8 Orchid,#DA70D6 GoldenRod,#DAA520 PaleVioletRed,#DB7093 Crimson,#DC143C Gainsboro,#DCDCDC Plum,#DDA0DD BurlyWood,#DEB887 LightCyan,#E0FFFF Lavender,#E6E6FA DarkSalmon,#E9967A Violet,#EE82EE PaleGoldenRod,#EEE8AA LightCoral,#F08080 Khaki,#F0E68C AliceBlue,#F0F8FF HoneyDew,#F0FFF0 Azure,#F0FFFF SandyBrown,#F4A460 Wheat,#F5DEB3 Beige,#F5F5DC WhiteSmoke,#F5F5F5 MintCream,#F5FFFA GhostWhite,#F8F8FF Salmon,#FA8072 AntiqueWhite,#FAEBD7 Linen,#FAF0E6 LightGoldenRodYellow,#FAFAD2 OldLace,#FDF5E6 Red,#FF0000 Fuchsia,#FF00FF Magenta,#FF00FF DeepPink,#FF1493 OrangeRed,#FF4500 Tomato,#FF6347 HotPink,#FF69B4 Coral,#FF7F50 DarkOrange,#FF8C00 LightSalmon,#FFA07A Orange,#FFA500 LightPink,#FFB6C1 Pink,#FFC0CB Gold,#FFD700 PeachPuff,#FFDAB9 NavajoWhite,#FFDEAD Moccasin,#FFE4B5 Bisque,#FFE4C4 MistyRose,#FFE4E1 BlanchedAlmond,#FFEBCD PapayaWhip,#FFEFD5 LavenderBlush,#FFF0F5 SeaShell,#FFF5EE Cornsilk,#FFF8DC LemonChiffon,#FFFACD FloralWhite,#FFFAF0 Snow,#FFFAFA Yellow,#FFFF00 LightYellow,#FFFFE0 Ivory,#FFFFF0 White,#FFFFFF ```
2019/06/30
[ "https://codegolf.stackexchange.com/questions/187493", "https://codegolf.stackexchange.com", "https://codegolf.stackexchange.com/users/85546/" ]
[Node.js](https://nodejs.org), 1488 bytes ========================================= Takes input as a 24-bit integer. Outputs in lower case. ```javascript v=>(require('zlib').inflateRawSync(Buffer('TVRbm6o4EPxLE27CowziDOiIV+bwFkkrWUPCBBg/9tdvLurZFzGX7uqqrs6Z4fr2xvHv5OYEy9uZjRC3QOjY6r/oaH4X+ugqAXiWI/P1M28AzGxQPWHuBBkB6PrbpCPmyZs+GEb5Mwrag/O9sEn7TlJ+NSnCr4TRFk7z/+25mc7l5i0lnF6bQef6Pn6tiCBXkHo12yxTpo96wCbEqfbxRUjoB7tcxfvn0fJ4POgyeoYHuEo8IafINaY59co8exT1uJ+Uq/hVsn8KUykmzDTqzin6AcD8n/nb3Sur3nDSD9cmegUf5hHlhF6F6ySOviwY/bWwi/UO1ZiA4baIj1EtJL8wcbf8gspLJJyhrnE3yo6BExUbmx3/jLjFSis4pitCW83I/SrTVyEo3uQGiEh8Rpvi80U8+OMXVrXnTnTKowf7Z7i/fFsxfOdWx9l6XjdYDhLGHrxwvvkL75fqKwRHoS3RtahFsDEl5U8TRMudBbXrVP/8UsFgcOMP4xwJBPmlsVeLr8AH7J56TAiDsxR3nmTvRulHf4LotDQJzQptlsgyeFTxeUr1bYuwT/cdZlbyoDog0wRZN5TMy3wCpgS3PCNn0VPgHM927smgBvvvwhpeCRc/7GYEOq0KE2TjZ3mkIf6avPiOLd+nVVAQvXfiTmxr/ez9QlVvJa1vaLc01K6CEeBSkLDyfcvGVulk6zcp+slU5HrZUt++NfhG0Tote8p+QXpRVtgYy1mpGZb+h3Ye5npxWKQdyDF0dnUjaqEbHZzmswHzRbl4KKmmIt+ehob2A4OgLP0HfpI5r+Lm8VEzfaEgL9jVkra94GV8uGLK+7OQArnrTcfGVo3Z4TxKNt2FICgLtwbKTPYs8hj+Ba4kCedLO0eYtYK7u31p8wdlFZrWPdFz13ZdDQpmTpgHRobc32BGa+Nc92vWCA4TgTtKEvzvKCHtMSdWPd8LonsDeEBbd3YGegUvL+4NHaBvx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TXpAa/AvR8wfPcz8C78g5UNQCpnza/Q7gkietfoB/KO1Q38NEUSfUbtMZ5gSJ/ht6Vd2gAaVp0MQQg/wWb/fnhQ1RAJJ@sJvifk3zyeUJ8X1F0Nvnnw2TSPvUf7YdeHhYZMpv8McF7Av9hk69P5hn0c0KEmHz@PCHp51k7e62LUw2TPEYI5vvGKksA@edgILPXKk2e80DMnsVO/191O3tW9O@3/wI "JavaScript (Node.js) – Try It Online") ### How? The compressed string is 1683 characters long and looks like that: ```javascript "black0navy3KdarkblueBmediumblue1Ublue1EdarkgreenJK1green5J4(…)lightyellow68ivoryGwhiteF" ``` The colors are ordered from lowest to highest value. Each color is encoded as its name in lower case followed by the difference between its value and the previous value in base-36 and in upper case: ``` black[0] | 0x000000 + 0 --> 0x000000 navy[3K] | 0x000000 + 128 --> 0x000080 darkblue[B] | 0x000080 + 11 --> 0x00008B mediumblue[1U] | 0x00008B + 66 --> 0x0000CD blue[1E] | 0x0000CD + 50 --> 0x0000FF darkgreen[JK1] | 0x0000FF + 25345 --> 0x006400 green[5J4] | 0x006400 + 7168 --> 0x008000 ... | ... lightyellow[68] | 0xFFFF00 + 224 --> 0xFFFFE0 ivory[G] | 0xFFFFE0 + 16 --> 0xFFFFF0 white[F] | 0xFFFFF0 + 15 --> 0xFFFFFF ``` ### Commented ```javascript v => // v = input ( require('zlib') // using zlib, .inflateRawSync( // inflate the Buffer( // buffer obtained by 'TVRbm(…)Pw', // converting this string 'base64' // encoded in base-64 ) // ) + '' // and coerce it back to a string ).replace( // on which we invoke replace(): m = // initialize m to a non-numeric value /([a-z]+)([^a-z]+)/g, // for each color encoded as ... (_, s, d) => // ... s = name, d = delta in base-36: [e = 0, 8, 16] // using x = 0 for blue, 8 for green and 16 for red, .map(x => // compute the error e: e += // add to e: Math.abs( // the absolute value of the difference between (v >> x & 255) - // the component of the target color (t >> x & 255) // and the component of the current color ), // t += parseInt(d, 36) // start by adding the delta to t ) | e > m || // end of map(); if e is less than or equal to m: (o = s, m = e), // update o to s and m to e t = 0 // start with t = 0 ) && o // end of replace(); return o ```
JavaScript (Firefox), 1050 bytes ================================ ``` c=>(b=document.body,_.match(/.[a-z]*/g).map(t=>getComputedStyle(b,b.style.color=t).color.match(/\d+/g).map((v,i)=>s+=Math.abs((c>>16-8*i&255)-v),s=0)|m>=s&&(m=s,r=t),r=m=c),r) _='BlackNavy}~x~B2e}|G^ETeU}cy@Deeps,}t`xs*LimeS*Cy@Midnight~Dodg9~{s:GFo^1|S:|}s]JLime|xs:|T`RoyU~Steel~}s]~xt`Indigo}o6|Cadet~C?nfl59~Rebeccap<xa;DimJS]~O6drabS]J{s]Jxs]~Lawn|Chart^useA;Maro4P<O6GrayG^yS,{s,B2ev[}0}m+Saddleb>}s:|{|xp<}v[7|}?/YZ|SiEnaB>}J{~G^EyZ7t`{1eel~P5d9~Fi^brick}g_x?/Rosyb>}khakiSilv9xv[0Indi@0P9uChoco]T@{JT81leOr/G_7v[0Crims4GaQsb?oP2mBurlywood{cy@3}s=V[7g_{c?UKhakiAlice~H4eydewAzu^S@dyb>Wh:tBeigeWXsmokeMQtc^amGho1wXS=AntiquewXLQE{g_yZOldlaceRedM+Deep.Or-0TomatoHot.C?U}?-{s=Or-{.PQkGoldP:chpuffNavaj5XMoccasQBisqueMi1yroseBl@ched=dPapayaw8p3b2shS:shellC?nsilkLem4c8ff4Fl?UwXSn5YZ{yZIv?yWX~b2e}Dark|g^E{LightxMedium`urquoise_oldErod^re]late[ioletZell5X8teUalQinJg^yEen@an?or>r5n=Um4<urple;quamarQe:ea9er8hi7PUe6live5ow4on3LavEd92lu1st0^d/c8d.pQk-@ge,ky~+agEta*prQg|';for(i of'*+,-./0123456789:;<=>?@EJQUXZ[]^_`x{|}~')with(_.split(i))_=join(pop()) ``` ```js f = c=>(b=document.body,_.match(/.[a-z]*/g).map(t=>getComputedStyle(b,b.style.color=t).color.match(/\d+/g).map((v,i)=>s+=Math.abs((c>>16-8*i&255)-v),s=0)|m>=s&&(m=s,r=t),r=m=c),r) _='BlackNavy}~x~B2e}|G^ETeU}cy@Deeps,}t`xs*LimeS*Cy@Midnight~Dodg9~{s:GFo^1|S:|}s]JLime|xs:|T`RoyU~Steel~}s]~xt`Indigo}o6|Cadet~C?nfl59~Rebeccap<xa;DimJS]~O6drabS]J{s]Jxs]~Lawn|Chart^useA;Maro4P<O6GrayG^yS,{s,B2ev[}0}m+Saddleb>}s:|{|xp<}v[7|}?/YZ|SiEnaB>}J{~G^EyZ7t`{1eel~P5d9~Fi^brick}g_x?/Rosyb>}khakiSilv9xv[0Indi@0P9uChoco]T@{JT81leOr/G_7v[0Crims4GaQsb?oP2mBurlywood{cy@3}s=V[7g_{c?UKhakiAlice~H4eydewAzu^S@dyb>Wh:tBeigeWXsmokeMQtc^amGho1wXS=AntiquewXLQE{g_yZOldlaceRedM+Deep.Or-0TomatoHot.C?U}?-{s=Or-{.PQkGoldP:chpuffNavaj5XMoccasQBisqueMi1yroseBl@ched=dPapayaw8p3b2shS:shellC?nsilkLem4c8ff4Fl?UwXSn5YZ{yZIv?yWX~b2e}Dark|g^E{LightxMedium`urquoise_oldErod^re]late[ioletZell5X8teUalQinJg^yEen@an?or>r5n=Um4<urple;quamarQe:ea9er8hi7PUe6live5ow4on3LavEd92lu1st0^d/c8d.pQk-@ge,ky~+agEta*prQg|';for(i of'*+,-./0123456789:;<=>?@EJQUXZ[]^_`x{|}~')with(_.split(i))_=join(pop()) console.log(f(0xFF04FE)); console.log(f(0xFFFFFF)); console.log(f(0x457CCB)); document.body.style.color = 'black'; ``` Third JavaScript language in this question now... [`getComputedStyle`](https://developer.mozilla.org/en-US/docs/Web/API/Window/getComputedStyle) always returns colors in `rgb(x, y, z)` form if `alpha == 1` on Firefox. `_` variable holds the string with all color names in the form `BlackNavyDarkblueMediumblueBlueDarkgreen...White`. Save 11 bytes thanks to Kevin Cruijssen by removing unnecessary colors. Save ~350 bytes thanks to Arnauld by introducing some strange packing algorithm.
187,493
Input ----- A single hex 6-digit colour code, capital letter, without `#`. Can also be a 24-bit integer if you prefer. Output ------ The closest HTML color *name* (e.g `red`, or `dark-salmon`, as defined as <https://www.w3schools.com/colors/colors_names.asp> or see below). Distance is defined by summing the difference in red, green and blue channels. Examples -------- > > `FF04FE`: `magenta` > > > `FFFFFF`: `white` > > > `457CCB` (halfway between `steelblue` and `darkslateblue`): `steelblue` (round **up**) > > > Rules ----- * Standard loopholes apply. * Standard I/O applies * Round up to the color with the higher channel sum if halfway between two colors. If two colours have the same channel sum, output the one which is higher as a hex code: e.g `red` = `#FF0000` = 16711680 > `blue` = `#0000FF` = 256 * If one hex code has two names (e.g. `grey` and `gray`), output either. * Outputs can be capitalised and hyphenated how you like * Trailing/preceding spaces/newlines are fine * You must output the names in full. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins. Colors ------ As per suggestion in the comments, here are all of the color names with respective hex values in CSV format: ``` Color Name,HEX Black,#000000 Navy,#000080 DarkBlue,#00008B MediumBlue,#0000CD Blue,#0000FF DarkGreen,#006400 Green,#008000 Teal,#008080 DarkCyan,#008B8B DeepSkyBlue,#00BFFF DarkTurquoise,#00CED1 MediumSpringGreen,#00FA9A Lime,#00FF00 SpringGreen,#00FF7F Aqua,#00FFFF Cyan,#00FFFF MidnightBlue,#191970 DodgerBlue,#1E90FF LightSeaGreen,#20B2AA ForestGreen,#228B22 SeaGreen,#2E8B57 DarkSlateGray,#2F4F4F DarkSlateGrey,#2F4F4F LimeGreen,#32CD32 MediumSeaGreen,#3CB371 Turquoise,#40E0D0 RoyalBlue,#4169E1 SteelBlue,#4682B4 DarkSlateBlue,#483D8B MediumTurquoise,#48D1CC Indigo,#4B0082 DarkOliveGreen,#556B2F CadetBlue,#5F9EA0 CornflowerBlue,#6495ED RebeccaPurple,#663399 MediumAquaMarine,#66CDAA DimGray,#696969 DimGrey,#696969 SlateBlue,#6A5ACD OliveDrab,#6B8E23 SlateGray,#708090 SlateGrey,#708090 LightSlateGray,#778899 LightSlateGrey,#778899 MediumSlateBlue,#7B68EE LawnGreen,#7CFC00 Chartreuse,#7FFF00 Aquamarine,#7FFFD4 Maroon,#800000 Purple,#800080 Olive,#808000 Gray,#808080 Grey,#808080 SkyBlue,#87CEEB LightSkyBlue,#87CEFA BlueViolet,#8A2BE2 DarkRed,#8B0000 DarkMagenta,#8B008B SaddleBrown,#8B4513 DarkSeaGreen,#8FBC8F LightGreen,#90EE90 MediumPurple,#9370DB DarkViolet,#9400D3 PaleGreen,#98FB98 DarkOrchid,#9932CC YellowGreen,#9ACD32 Sienna,#A0522D Brown,#A52A2A DarkGray,#A9A9A9 DarkGrey,#A9A9A9 LightBlue,#ADD8E6 GreenYellow,#ADFF2F PaleTurquoise,#AFEEEE LightSteelBlue,#B0C4DE PowderBlue,#B0E0E6 FireBrick,#B22222 DarkGoldenRod,#B8860B MediumOrchid,#BA55D3 RosyBrown,#BC8F8F DarkKhaki,#BDB76B Silver,#C0C0C0 MediumVioletRed,#C71585 IndianRed,#CD5C5C Peru,#CD853F Chocolate,#D2691E Tan,#D2B48C LightGray,#D3D3D3 LightGrey,#D3D3D3 Thistle,#D8BFD8 Orchid,#DA70D6 GoldenRod,#DAA520 PaleVioletRed,#DB7093 Crimson,#DC143C Gainsboro,#DCDCDC Plum,#DDA0DD BurlyWood,#DEB887 LightCyan,#E0FFFF Lavender,#E6E6FA DarkSalmon,#E9967A Violet,#EE82EE PaleGoldenRod,#EEE8AA LightCoral,#F08080 Khaki,#F0E68C AliceBlue,#F0F8FF HoneyDew,#F0FFF0 Azure,#F0FFFF SandyBrown,#F4A460 Wheat,#F5DEB3 Beige,#F5F5DC WhiteSmoke,#F5F5F5 MintCream,#F5FFFA GhostWhite,#F8F8FF Salmon,#FA8072 AntiqueWhite,#FAEBD7 Linen,#FAF0E6 LightGoldenRodYellow,#FAFAD2 OldLace,#FDF5E6 Red,#FF0000 Fuchsia,#FF00FF Magenta,#FF00FF DeepPink,#FF1493 OrangeRed,#FF4500 Tomato,#FF6347 HotPink,#FF69B4 Coral,#FF7F50 DarkOrange,#FF8C00 LightSalmon,#FFA07A Orange,#FFA500 LightPink,#FFB6C1 Pink,#FFC0CB Gold,#FFD700 PeachPuff,#FFDAB9 NavajoWhite,#FFDEAD Moccasin,#FFE4B5 Bisque,#FFE4C4 MistyRose,#FFE4E1 BlanchedAlmond,#FFEBCD PapayaWhip,#FFEFD5 LavenderBlush,#FFF0F5 SeaShell,#FFF5EE Cornsilk,#FFF8DC LemonChiffon,#FFFACD FloralWhite,#FFFAF0 Snow,#FFFAFA Yellow,#FFFF00 LightYellow,#FFFFE0 Ivory,#FFFFF0 White,#FFFFFF ```
2019/06/30
[ "https://codegolf.stackexchange.com/questions/187493", "https://codegolf.stackexchange.com", "https://codegolf.stackexchange.com/users/85546/" ]
[C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 231+21=252 bytes ======================================================================================================================== ```cs s=>Color.FromArgb(Convert.ToInt32(s,16));f=s=>Enum.GetNames(typeof(KnownColor)).Select(x=>Color.FromName(x)).Where(x=>!x.IsSystemColor&x.A>254).OrderBy(x=>Math.Abs(x.R-C(s).R)+Math.Abs(x.G-C(s).G)+Math.Abs(x.B-C(s).B)).First().Name ``` Explanation: ```cs using System.Drawing; //System library that handles Colors in C# C=s=>Color.FromArgb(Convert.ToInt32(s,16)); //helper method. receives a hex string and returns it's Color f=s=>Enum.GetNames(typeof(KnownColor)) //collection of color names from the System.Drawing.KnownColor enum .Select(x=>Color.FromName(x)) //convert the color names to Colors .Where(x=>!x.IsSystemColor&x.A>254) //filter out unwanted colors .OrderBy(x=>Math.Abs(x.R-C(s).R) //order by increasing distance +Math.Abs(x.G-C(s).G) +Math.Abs(x.B-C(s).B)) .First().Name //return the closest color's name ``` For some reason, Tio complains that the namespace 'Drawing' does not exist in the namespace 'System', despite the source project [Mono](https://www.mono-project.com/docs/gui/drawing/) stating it's compatible. It works fine in VisualStudio though. EDIT: apparently it [hasn't been implemented](https://github.com/TryItOnline/cs-mono/blob/master/README.md) into Tio yet! [Try it online!](https://tio.run/##bc9Li8IwEAfwu5@i62FJWA2aah@4FpL0gewLdMFz7aZasMmSxLV@@m5rL0o9hfnNn5lJpseZLuqTLsTe2ly04SUKVXpuysUgPonsVRvVFCOrewMrv3cmj1IFFrOWtV4G1wrFSpZE7XeASfHHlUHfciWMjYEeTR0IF/myiUbiVKKEm8@05BqYyy@XOXgT8iyuQyBEG37kmQHV7dg2DaqmuT1wxdveU4VWurv8GnuuEAnwfAbRl/rhil7a0EdqDojsNKjQesyAhmgNX24w6TC5Q9ohbbbFhdIGQNSurxeDrSoMfy8EBzkYxrbvUG/Y/OveGaHuBPc9xFOX0b4T3w8j1veZEzqO23fbo9iPHuzFrj0nfXcp8WeTvseTcO49mONTHNl26/U/ "C# (Visual C# Interactive Compiler) – Try It Online")
[05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 1175 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ============================================================================================================================== ``` .•ŒRǝJÖ¤|DÕGø∊ŸγÜuÕפJÓΩaĀhºΔè₆ìkh¥ù§¸β?|"qтy¥Œ›ιM?z*Ω3¿ƒLò·¡ËÌóñD#Ë‰в††α½ÅÎëLpÄäÍEáyø‡§*ßtÓñ7тÜöãô±‘§—ÄGfΔ½~10'–ßaÔ´?ç"&$&¾¬ÍTʒ}M‰8βÔŽÙûQ[мvαн'YW:ΘÌiнœ+ĀβWŬŽø%ð°¤]γθγçkÌã©Ð:8• #`“ƒÏª©–°0‡—–í0‡—‡—–°0ˆ¨ˆ¨¤Æl–°ÿ•³0¤Ð0‡—–°ÿ–í0Ž¹0ˆ¨ë¿Ž¹0ˆ¨Ü„Àš0‡—·¡r0‡—‡Ž0í™0ˆ¨ï×0ˆ¨í™0ˆ¨–°s0Ž¦0°¯ë¿0ˆ¨–í0í™0ˆ¨ ÿïˆ0‡—–Í0‡—–°s0Ž¦0‡—–íÿ ÿ–°0Ê£0ˆ¨ ÿ0‡—ÃÅ0žç0‡—Ôî0´Ò–í0Ü„0›Ðæá0°¯ s0Ž¦0‡—Ê£ÿ s0Ž¦0°¯¦º0Ž¦0°¯–ís0Ž¦0‡—į0ˆ¨œëre0€ÅÜ„0›Ð ÿ´ÒÊ£°¯¤Ð0‡—‡Ž0¤Ð0‡—‡—ÿ–°0†¾–°m0î±a»Ïÿ0ŽÌ–°0í™0ˆ¨‡Ž0ˆ¨–í0´Ò–°ÿæ§0ˆ¨–°ÿŠÛ0ˆ¨ ÿŽÌ–°0°¯‡Ž0‡—ˆ¨0ŠÛæ§ÿ‡Ž0–Í0‡—¼ì0‡—ŠÄ0Ñ´–°0ž®0»³–íÿ ÿ0ŽÌ–°ÿ‹ß–íÿ0†¾•‹0†¾¾ç¨ËÇ⇎0°¯€Œÿ ÿž®0»³æ§ÿ0†¾ ÿÆŠÿ ÿ ÿ0–œ‡Žÿ ÿ–°0ÇÝ ÿæ§0ž®0»³‡Ž0Í€ ÿ¿í0‡—Æàÿ ÿǨ0ŽÌÍÍ ÿ„¸0³«¼Õ0¥â·ä0„¸ÇÝ°Š0„¸ƒ£n‡Ž0ž®0»³0ŠÛ„Ï0ÕÚ†¾ m0î±a•³0™Å›È0†¾æž…ß0™ÅÍ€–°0›È‡Ž0ÇݛȇŽ0™Å™Åˆ° p0‚Ìÿ ÿ0„¸ ÿ ÿ ÿ0šÓ ÿ ÿ ÿí™0¬•ÃÅ0»»ËÃÿÄ‚0„¸œÒŠÛ‡Ž0ŠÛ؉„¸“„0 K#•zÑĪåð≠K¯&u+UhĆõ;Éðf.ã₂=нH,ª@O¶ü˜ˆ₂Ɔ¥2Œ’Ktθu1Sнdw΀(#ç¹ü‹U¹³αh+8R∍±æ”ÇKë₆ßõk₃¿θòĀηú¿ζвî!Vs©₂™CÖ.∍JнαθWÀhzαÐé3¾¯|ë¡×°'βâá—P‘Å_uë_§₃P∊%ý/=i]¥5óO₃^E‘[∞₆ć:βU=J€¦†˜X'Žāìd4Ā’δ‹a°∊›ÊÐƶoÂö mвæÁƵ¨¼Yü“à §‚₂¾¤н7Þ9úÂuœ¿®jF™SΛ¬ìr½ƒxßU‘Lβ7≠°oι—ĀÅýÆgBÐγö™α₆©vÝeEXεò₁Uт3ÈĀ(wº4{ºö쾫 åUøò${J#₃O<!øN”;GÑéÈfm ½™×γäJǝõ¥àÐι)λÓ:α–ù?6¦¨·ã™ζÙ4ÍHd›-Iž|ï¦{Ö9ÊàÛ§¥–Σÿ%ć8ùćYáþǝC±;••O褕в.¥εI‚₄S₁β+₁∦`αO}Wkè ``` That took quite a while.. 139 colors to create a string of.. >.> Takes input as a 24-bit integers to save 1 byte. [Try it online](https://tio.run/##VVZrU1NXFP3ur4iiYqWl14oFsQ4d0WpBi9VSdByrOGqx1GpVtCp2rpcQ8BHFBN@8EpIAJkIeEJPATWb2ysWZMnMm/oX7R@g@9@blTBLOY5@119p7n324cr373KUL64c61@tN1W94jn0cb8MLCvTvx/ODSJnDD42USGCsD8/xkgJt8Iq57rzaQxkxillTcyHS20NBpGmGUiLe0r/p70/abQoaHlPNiPSRljvbxdxOyq16DiNOH8iHR3iMBGL7a/DIVKOFuKlO8UfESMcgniB8@CqcCMB9AL7bTED10cx2TN6AF7HGTxrGkMQ0Filmqq9oxlRH4Tx4UYyS/u8OpdZUvZjsxigttmBm09bNWylLEbh/@c9z7wg7axJxjBo6XmP551OFlZsiVtBrT3Y1i1d4fKmgG966vCriXRikCFultiBKUQqcFgkhYzDTy8ynaQ4jzU0cqw01Z011bNWDp/SO5tgzRRVmy4wki/flcXGFd9dcNCu/FIDrT2sJOQaihMIrI0qVqVyXGIZOaesYwpSrTMZMdQKq4SsekWG9VvFn6Arem06/bbuAl/agvGR5uC6xQwrrW5DYpQ32WTF0IIeFNVeVKnc1ySJElWbkHBZz1oqHNF0CKZpgAIOKkcVMaT6KeYUW4Sn6lap4K4MRhOCzqDk@8yEx2UUVdQpRpjKzcD4/4aQFi4XhRfjaBcXUIlxkFUdMThKQwBZcdRpkHD9fkI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rU@Zs00Mzf5kedh0aMRVX65nE3e6tST@XX/OeckoxKCpn2BSHoMoRCmLS3DG47hQIG@UUsOOCqYkhvjiPYet1Nn3LCnLBYWrW3VipPnh3Z2ZBEeNPGzeJGa9xLvp5Z4AhzLNc5x5ThaFM1MhrbnzGHncrUfjW1mKGuIvnfDneI4Cw/nCqlZb295S2d2VcWDmMhwhfLsOMrihHsqljh@j9d220ivWtsS0Xr2VcQnqgQnT4N623tHhP@els6uIdPGXxB4q5RBJY55pppwTFtEhXae0pfdhNEQR1eRxDrVgQr8YkVrp1pZ/SWhxR7rofkeTxajaKxT0/3@R@qigs146XZXy4JZvSIlq8A3LXXS3C/YFflA1a6uPO5eNXKVzCfX0aojRO8quAwQs9WLjAj4PSf5IfsH1IfXPkynkKVCPWxmu/ONjonD48wTwyQ/VatP1IC1Mn5je1NXamRE1lHiB0sSojs0CNL06ik8KMI3L4CCObq9egYNV6lbkG8WBzhRv6@lkheQz9VvEkvWXyzM@fTdkwUYcklB7VS2la/MPJmk5r7/hNCt2g1KbnH0y2M5njWtTGWaDwNS3BIjIyl1IKrt@bMMLvziof0iJMluZvY/yS44y2gqiuPGj/rFRiOCMfuEPJqnuU5IcxxG4XoFgQaAfHde@9lmIW3PbtHsR/4OgfPspZn8fw5atWSokSfMXw/pZP41jhuzLF3hJfaWvw1rM7bgKJhhpusHN8hWYEhVW8qYL72EWOw9ffqxt94PZ7Dy/rOChcZ/z@B/iQxh16X2aoFonM0Fn4sPFp3E6Rw0YbmW7LxsnPf7PRMgpoK2eMUA2cZi1atJS/@Z8BkYdftUjb/Y5uzG0f2q6qttntTRanU6pyOixVktPpaLQ0SvbmygpeFB@LZHwsFTVSY7nNUldub66otNTUVVTaqy32SqezttJS52isqKuxVFTbmmuqLY5mW1NTnaXRYatqqvkf). (Both are slightly modified to take Hexadecimal strings as input instead, since it's easier to test.) **Explanation:** First we generate all the color-strings: ```python .•ŒRǝJÖ¤|DÕGø∊ŸγÜuÕפJÓΩaĀhºΔè₆ìkh¥ù§¸β?|"qтy¥Œ›ιM?z*Ω3¿ƒLò·¡ËÌóñD#Ë‰в††α½ÅÎëLpÄäÍEáyø‡§*ßtÓñ7тÜöãô±‘§—ÄGfΔ½~10'–ßaÔ´?ç"&$&¾¬ÍTʒ}M‰8βÔŽÙûQ[мvαн'YW:ΘÌiнœ+ĀβWŬŽø%ð°¤]γθγçkÌã©Ð:8• '# Push compressed string "chiffon lavenderblush papayawhip blanchedalmond misty bisque moccasin navajo puff beige azure dew khaki violet lavender cyan burly plum boro crimson violet orchid tle violet khaki rosy orchid turquoise sienna orchid violet dle violet maroon drab cadet indigo turquoise turquoise cyan turquoise steelblue" # # Split this string on spaces ` # Push each string separately to the stack “ƒÏª©–°0‡—–í0‡—‡—–°0ˆ¨ˆ¨¤Æl–°ÿ•³0¤Ð0‡—–°ÿ–í0Ž¹0ˆ¨ë¿Ž¹0ˆ¨Ü„Àš0‡—·¡r0‡—‡Ž0í™0ˆ¨ï×0ˆ¨í™0ˆ¨–°s0Ž¦0°¯ë¿0ˆ¨–í0í™0ˆ¨ ÿïˆ0‡—–Í0‡—–°s0Ž¦0‡—–íÿ ÿ–°0Ê£0ˆ¨ ÿ0‡—ÃÅ0žç0‡—Ôî0´Ò–í0Ü„0›Ðæá0°¯ s0Ž¦0‡—Ê£ÿ s0Ž¦0°¯¦º0Ž¦0°¯–ís0Ž¦0‡—į0ˆ¨œëre0€ÅÜ„0›Ð ÿ´ÒÊ£°¯¤Ð0‡—‡Ž0¤Ð0‡—‡—ÿ–°0†¾–°m0î±a»Ïÿ0ŽÌ–°0í™0ˆ¨‡Ž0ˆ¨–í0´Ò–°ÿæ§0ˆ¨–°ÿŠÛ0ˆ¨ ÿŽÌ–°0°¯‡Ž0‡—ˆ¨0ŠÛæ§ÿ‡Ž0–Í0‡—¼ì0‡—ŠÄ0Ñ´–°0ž®0»³–íÿ ÿ0ŽÌ–°ÿ‹ß–íÿ0†¾•‹0†¾¾ç¨ËÇ⇎0°¯€Œÿ ÿž®0»³æ§ÿ0†¾ ÿÆŠÿ ÿ ÿ0–œ‡Žÿ ÿ–°0ÇÝ ÿæ§0ž®0»³‡Ž0Í€ ÿ¿í0‡—Æàÿ ÿǨ0ŽÌÍÍ ÿ„¸0³«¼Õ0¥â·ä0„¸ÇÝ°Š0„¸ƒ£n‡Ž0ž®0»³0ŠÛ„Ï0ÕÚ†¾ m0î±a•³0™Å›È0†¾æž…ß0™ÅÍ€–°0›È‡Ž0ÇݛȇŽ0™Å™Åˆ° p0‚Ìÿ ÿ0„¸ ÿ ÿ ÿ0šÓ ÿ ÿ ÿí™0¬•ÃÅ0»»ËÃÿÄ‚0„¸œÒŠÛ‡Ž0ŠÛ؉„¸“ # Push dictionary string "black navy dark0 blue medium0 blue blue dark0 green green teal darkÿ deep0 sky0 blue darkÿ medium0 spring0 green lime spring0 green aqua midnight0 blue dodger0 blue light0 sea0 green forest0 green sea0 green darks0 late0 grey lime0 green medium0 sea0 green ÿ royal0 blue steel0 blue darks0 late0 blue mediumÿ ÿ dark0 olive0 green ÿ0 blue corn0 flower0 blue rebecca0 purple medium0 aqua0 marine dim0 grey s0 late0 blue oliveÿ s0 late0 grey lights0 late0 grey mediums0 late0 blue lawn0 green chartre0 use aqua0 marine ÿ purple olive grey sky0 blue light0 sky0 blue blueÿ dark0 red darkm0 agenta sadÿ0 brown dark0 sea0 green light0 green medium0 purple darkÿ pale0 green darkÿ yellow0 green ÿ brown dark0 grey light0 blue green0 yellow paleÿ light0 steel0 blue powder0 blue fire0 brick dark0 golden0 rod mediumÿ ÿ0 brown darkÿ silver mediumÿ0 red indian0 red peru chocolate tan light0 grey thisÿ ÿ golden0 rod paleÿ0 red ÿ gainsÿ ÿ ÿ0 wood lightÿ ÿ dark0 salmon ÿ pale0 golden0 rod light0 coral ÿ alice0 blue honeyÿ ÿ sandy0 brown wheat ÿ white0 smoke mint0 cream ghost0 white salmon antique0 white linen light0 golden0 rod0 yellow old0 lace red m0 agenta deep0 pink orange0 red tomato hot0 pink coral dark0 orange light0 salmon orange light0 pink pink gold p0 eachÿ ÿ0 white ÿ ÿ ÿ0 rose ÿ ÿ ÿ sea0 shell corn0 silk lemonÿ floral0 white snow yellow light0 yellow ivory white" # Where all `ÿ` are automatically filled with the strings on the stack „0 K # Remove all "0 " from this string # # Split the colors on spaces ``` Then we generate a list of forward differences (deltas) between each integer value of the colors: ```python •zÑĪåð≠K¯&u+UhĆõ;Éðf.ã₂=нH,ª@O¶ü˜ˆ₂Ɔ¥2Œ’Ktθu1Sнdw΀(#ç¹ü‹U¹³αh+8R∍±æ”ÇKë₆ßõk₃¿θòĀηú¿ζвî!Vs©₂™CÖ.∍JнαθWÀhzαÐé3¾¯|ë¡×°'βâá—P‘Å_uë_§₃P∊%ý/=i]¥5óO₃^E‘[∞₆ć:βU=J€¦†˜X'Žāìd4Ā’δ‹a°∊›ÊÐƶoÂö mвæÁƵ¨¼Yü“à §‚₂¾¤н7Þ9úÂuœ¿®jF™SΛ¬ìr½ƒxßU‘Lβ7≠°oι—ĀÅýÆgBÐγö™α₆©vÝeEXεò₁Uт3ÈĀ(wº4{ºö쾫 åUøò${J#₃O<!øN”;GÑéÈfm ½™×γäJǝõ¥àÐι)λÓ:α–ù?6¦¨·ã™ζÙ4ÍHd›-Iž|ï¦{Ö9ÊàÛ§¥–Σÿ%ć8ùćYáþǝC±;• # Push compressed integer 199435987809271424589508700952987345999804200072375133628254343692108407476588500135573281889031649216370100759626064238727072489415325130552011943231372407222964404763401980843968947657212497212027480199840300219769136432328209307347145119976644138878553798683794751309798787883572249589074597119540397124774131357786254535108429605287982569524294490533853150008626425797260994727581899181000813165364870780739754491720041566206327597753141661846275821649635815830948299823383964329384068145070200611196756567681968774265025511020508722510627341700584849057763591073777679021648285012447092662591008342199952284925672007531443930335828262810273697784303468071652124201899153101970895280421720006686387730894329535589566680885995478455871002071758051626349351150223272343920758114226776399859623393233070539000599481915926111317851112136858026586181791 •O褕 # Push compressed integer 1579378 в # Convert the larger integer to Base-1579378 as list: [128,11,66,50,25345,7168,128,2827,13428,3794,11209,1126,127,128,1579377,358287,139691,120952,786485,50168,228835,648767,273759,35089,334035,113367,37953,143030,682669,668529,325453,105900,39441,170943,61796,78678,324205,460809,254037,103186,197376,212,44,128,32640,128,478827,15,154856,54302,139,17544,292732,78337,164427,36856,326341,14132,105062,361723,317437,294783,274237,9801,126911,54768,7176,82236,418793,118728,145852,75740,198997,414917,411351,10467,320479,19310,73543,322565,110846,13386,52083,41897,51360,50177,71594,149368,386811,176000,322676,26044,104406,26124,4723,1777,15,238689,80467,5929,25,2565,194821,100211,27493,1295,2540,195348,68122,255,5012,12397,7751,1645,5532,3248,5242,1158,4545,2570,5685,953,1012,1544,15,29,1772,1032,288,1273,750,497,35,10,1030,224,16,15] .¥ # Undelta this list: [0,128,139,205,255,25600,32768,32896,35723,49151,52945,64154,65280,65407,65535,1644912,2003199,2142890,2263842,3050327,3100495,3329330,3978097,4251856,4286945,4620980,4734347,4772300,4915330,5597999,6266528,6591981,6697881,6737322,6908265,6970061,7048739,7372944,7833753,8087790,8190976,8388352,8388564,8388608,8388736,8421376,8421504,8900331,8900346,9055202,9109504,9109643,9127187,9419919,9498256,9662683,9699539,10025880,10040012,10145074,10506797,10824234,11119017,11393254,11403055,11529966,11584734,11591910,11674146,12092939,12211667,12357519,12433259,12632256,13047173,13458524,13468991,13789470,13808780,13882323,14204888,14315734,14329120,14381203,14423100,14474460,14524637,14596231,14745599,15132410,15308410,15631086,15657130,15761536,15787660,15792383,15794160,15794175,16032864,16113331,16119260,16119285,16121850,16316671,16416882,16444375,16445670,16448210,16643558,16711680,16711935,16716947,16729344,16737095,16738740,16744272,16747520,16752762,16753920,16758465,16761035,16766720,16767673,16768685,16770229,16770244,16770273,16772045,16773077,16773365,16774638,16775388,16775885,16775920,16775930,16776960,16777184,16777200,16777215] ``` Then we determine the index of the value closest to the input (in terms of absolute differences between each RGB color - and here I thought I could use builtin `.x`..), determine the index of this closest integer in the list, and use that to index into the color-strings we created earlier: ```python ε # Map each integer to: I‚ # Pair it with the input-integer ₄S # Push 1000, split to digits: [1,0,0,0] ₁β # Converted from base-256 to an integer: 16777216 + # Add that to both integers in the pair ₁в # Convert both integers to base-256 as list (we now have [1,R,G,B]) €¦ # Remove the leading 1 ` # Push both lists to the stack α # Get the absolute difference between the lists (at the same indices) O # Sum these differences }W # After the map: get the minimum (without popping the list itself) k # Get the index of this minimum in the list è # And use it to index into the string-color list # (after which the result is output implicitly) ``` [See this 05AB1E tip of mine (all four sections)](https://codegolf.stackexchange.com/a/166851/52210) to understand why: * `.•ŒRǝ...Ð:8•` is `"chiffon lavenderblush papayawhip ... cyan turquoise steelblue"` * `“ƒÏª©–°0‡—...‡Ž0ŠÛ؉„¸“` is `"black navy dark0 blue ... light0 yellow ivory white"` * `•zÑÄ...C±;•` is `199...791` * `•O褕` is `1579378` * `•zÑÄ...C±;••O褕в` is `[128,11,66,...,224,16,15]`
187,493
Input ----- A single hex 6-digit colour code, capital letter, without `#`. Can also be a 24-bit integer if you prefer. Output ------ The closest HTML color *name* (e.g `red`, or `dark-salmon`, as defined as <https://www.w3schools.com/colors/colors_names.asp> or see below). Distance is defined by summing the difference in red, green and blue channels. Examples -------- > > `FF04FE`: `magenta` > > > `FFFFFF`: `white` > > > `457CCB` (halfway between `steelblue` and `darkslateblue`): `steelblue` (round **up**) > > > Rules ----- * Standard loopholes apply. * Standard I/O applies * Round up to the color with the higher channel sum if halfway between two colors. If two colours have the same channel sum, output the one which is higher as a hex code: e.g `red` = `#FF0000` = 16711680 > `blue` = `#0000FF` = 256 * If one hex code has two names (e.g. `grey` and `gray`), output either. * Outputs can be capitalised and hyphenated how you like * Trailing/preceding spaces/newlines are fine * You must output the names in full. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins. Colors ------ As per suggestion in the comments, here are all of the color names with respective hex values in CSV format: ``` Color Name,HEX Black,#000000 Navy,#000080 DarkBlue,#00008B MediumBlue,#0000CD Blue,#0000FF DarkGreen,#006400 Green,#008000 Teal,#008080 DarkCyan,#008B8B DeepSkyBlue,#00BFFF DarkTurquoise,#00CED1 MediumSpringGreen,#00FA9A Lime,#00FF00 SpringGreen,#00FF7F Aqua,#00FFFF Cyan,#00FFFF MidnightBlue,#191970 DodgerBlue,#1E90FF LightSeaGreen,#20B2AA ForestGreen,#228B22 SeaGreen,#2E8B57 DarkSlateGray,#2F4F4F DarkSlateGrey,#2F4F4F LimeGreen,#32CD32 MediumSeaGreen,#3CB371 Turquoise,#40E0D0 RoyalBlue,#4169E1 SteelBlue,#4682B4 DarkSlateBlue,#483D8B MediumTurquoise,#48D1CC Indigo,#4B0082 DarkOliveGreen,#556B2F CadetBlue,#5F9EA0 CornflowerBlue,#6495ED RebeccaPurple,#663399 MediumAquaMarine,#66CDAA DimGray,#696969 DimGrey,#696969 SlateBlue,#6A5ACD OliveDrab,#6B8E23 SlateGray,#708090 SlateGrey,#708090 LightSlateGray,#778899 LightSlateGrey,#778899 MediumSlateBlue,#7B68EE LawnGreen,#7CFC00 Chartreuse,#7FFF00 Aquamarine,#7FFFD4 Maroon,#800000 Purple,#800080 Olive,#808000 Gray,#808080 Grey,#808080 SkyBlue,#87CEEB LightSkyBlue,#87CEFA BlueViolet,#8A2BE2 DarkRed,#8B0000 DarkMagenta,#8B008B SaddleBrown,#8B4513 DarkSeaGreen,#8FBC8F LightGreen,#90EE90 MediumPurple,#9370DB DarkViolet,#9400D3 PaleGreen,#98FB98 DarkOrchid,#9932CC YellowGreen,#9ACD32 Sienna,#A0522D Brown,#A52A2A DarkGray,#A9A9A9 DarkGrey,#A9A9A9 LightBlue,#ADD8E6 GreenYellow,#ADFF2F PaleTurquoise,#AFEEEE LightSteelBlue,#B0C4DE PowderBlue,#B0E0E6 FireBrick,#B22222 DarkGoldenRod,#B8860B MediumOrchid,#BA55D3 RosyBrown,#BC8F8F DarkKhaki,#BDB76B Silver,#C0C0C0 MediumVioletRed,#C71585 IndianRed,#CD5C5C Peru,#CD853F Chocolate,#D2691E Tan,#D2B48C LightGray,#D3D3D3 LightGrey,#D3D3D3 Thistle,#D8BFD8 Orchid,#DA70D6 GoldenRod,#DAA520 PaleVioletRed,#DB7093 Crimson,#DC143C Gainsboro,#DCDCDC Plum,#DDA0DD BurlyWood,#DEB887 LightCyan,#E0FFFF Lavender,#E6E6FA DarkSalmon,#E9967A Violet,#EE82EE PaleGoldenRod,#EEE8AA LightCoral,#F08080 Khaki,#F0E68C AliceBlue,#F0F8FF HoneyDew,#F0FFF0 Azure,#F0FFFF SandyBrown,#F4A460 Wheat,#F5DEB3 Beige,#F5F5DC WhiteSmoke,#F5F5F5 MintCream,#F5FFFA GhostWhite,#F8F8FF Salmon,#FA8072 AntiqueWhite,#FAEBD7 Linen,#FAF0E6 LightGoldenRodYellow,#FAFAD2 OldLace,#FDF5E6 Red,#FF0000 Fuchsia,#FF00FF Magenta,#FF00FF DeepPink,#FF1493 OrangeRed,#FF4500 Tomato,#FF6347 HotPink,#FF69B4 Coral,#FF7F50 DarkOrange,#FF8C00 LightSalmon,#FFA07A Orange,#FFA500 LightPink,#FFB6C1 Pink,#FFC0CB Gold,#FFD700 PeachPuff,#FFDAB9 NavajoWhite,#FFDEAD Moccasin,#FFE4B5 Bisque,#FFE4C4 MistyRose,#FFE4E1 BlanchedAlmond,#FFEBCD PapayaWhip,#FFEFD5 LavenderBlush,#FFF0F5 SeaShell,#FFF5EE Cornsilk,#FFF8DC LemonChiffon,#FFFACD FloralWhite,#FFFAF0 Snow,#FFFAFA Yellow,#FFFF00 LightYellow,#FFFFE0 Ivory,#FFFFF0 White,#FFFFFF ```
2019/06/30
[ "https://codegolf.stackexchange.com/questions/187493", "https://codegolf.stackexchange.com", "https://codegolf.stackexchange.com/users/85546/" ]
Wolfram Language (Mathematica), 164 bytes ========================================= *Note:* This only works in Mathematica 12.0 due to a bug in previous versions. This also means there is no TIO link. ```mma g[c_]:=Last@Keys@SortBy[Round[255List@@@<|"HTML"~ColorData~"ColorRules"~Join~{"RebeccaPurple"->RGBColor@"#639"}|>],{-Total@Abs[IntegerDigits[c,256,3]-#]&,Total,#&}] ``` Defines the function `g`, which takes an integer as input. Test cases: ```mma AssociationMap[g, {327581, 3483113, 2820178, 4358965, 2058772, 13569770, 8698378, 2897368, 3896382, 12856883}] (* <| 327581 -> "MediumSpringGreen", 3483113 -> "RoyalBlue", 2820178 -> "MidnightBlue", 4358965 -> "DarkOliveGreen", 2058772 -> "ForestGreen", 13569770 -> "Magenta", 8698378 -> "Olive", 2897368 -> "RoyalBlue", 3896382 -> "DarkOliveGreen", 12856883 -> "Brown" |> *) ``` Unfortunately, quite a few bytes are wasted on adding "RebeccaPurple" to the built-in list of colors, which is missing for some reason. The rest is pretty straightforward, we just sort the colors by their distance to the input, breaking ties with the sum of channel values and then the absolute ordering.
[05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 1175 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ============================================================================================================================== ``` .•ŒRǝJÖ¤|DÕGø∊ŸγÜuÕפJÓΩaĀhºΔè₆ìkh¥ù§¸β?|"qтy¥Œ›ιM?z*Ω3¿ƒLò·¡ËÌóñD#Ë‰в††α½ÅÎëLpÄäÍEáyø‡§*ßtÓñ7тÜöãô±‘§—ÄGfΔ½~10'–ßaÔ´?ç"&$&¾¬ÍTʒ}M‰8βÔŽÙûQ[мvαн'YW:ΘÌiнœ+ĀβWŬŽø%ð°¤]γθγçkÌã©Ð:8• #`“ƒÏª©–°0‡—–í0‡—‡—–°0ˆ¨ˆ¨¤Æl–°ÿ•³0¤Ð0‡—–°ÿ–í0Ž¹0ˆ¨ë¿Ž¹0ˆ¨Ü„Àš0‡—·¡r0‡—‡Ž0í™0ˆ¨ï×0ˆ¨í™0ˆ¨–°s0Ž¦0°¯ë¿0ˆ¨–í0í™0ˆ¨ ÿïˆ0‡—–Í0‡—–°s0Ž¦0‡—–íÿ ÿ–°0Ê£0ˆ¨ ÿ0‡—ÃÅ0žç0‡—Ôî0´Ò–í0Ü„0›Ðæá0°¯ s0Ž¦0‡—Ê£ÿ s0Ž¦0°¯¦º0Ž¦0°¯–ís0Ž¦0‡—į0ˆ¨œëre0€ÅÜ„0›Ð ÿ´ÒÊ£°¯¤Ð0‡—‡Ž0¤Ð0‡—‡—ÿ–°0†¾–°m0î±a»Ïÿ0ŽÌ–°0í™0ˆ¨‡Ž0ˆ¨–í0´Ò–°ÿæ§0ˆ¨–°ÿŠÛ0ˆ¨ ÿŽÌ–°0°¯‡Ž0‡—ˆ¨0ŠÛæ§ÿ‡Ž0–Í0‡—¼ì0‡—ŠÄ0Ñ´–°0ž®0»³–íÿ ÿ0ŽÌ–°ÿ‹ß–íÿ0†¾•‹0†¾¾ç¨ËÇ⇎0°¯€Œÿ ÿž®0»³æ§ÿ0†¾ ÿÆŠÿ ÿ ÿ0–œ‡Žÿ ÿ–°0ÇÝ ÿæ§0ž®0»³‡Ž0Í€ ÿ¿í0‡—Æàÿ ÿǨ0ŽÌÍÍ ÿ„¸0³«¼Õ0¥â·ä0„¸ÇÝ°Š0„¸ƒ£n‡Ž0ž®0»³0ŠÛ„Ï0ÕÚ†¾ m0î±a•³0™Å›È0†¾æž…ß0™ÅÍ€–°0›È‡Ž0ÇݛȇŽ0™Å™Åˆ° p0‚Ìÿ ÿ0„¸ ÿ ÿ ÿ0šÓ ÿ ÿ ÿí™0¬•ÃÅ0»»ËÃÿÄ‚0„¸œÒŠÛ‡Ž0ŠÛ؉„¸“„0 K#•zÑĪåð≠K¯&u+UhĆõ;Éðf.ã₂=нH,ª@O¶ü˜ˆ₂Ɔ¥2Œ’Ktθu1Sнdw΀(#ç¹ü‹U¹³αh+8R∍±æ”ÇKë₆ßõk₃¿θòĀηú¿ζвî!Vs©₂™CÖ.∍JнαθWÀhzαÐé3¾¯|ë¡×°'βâá—P‘Å_uë_§₃P∊%ý/=i]¥5óO₃^E‘[∞₆ć:βU=J€¦†˜X'Žāìd4Ā’δ‹a°∊›ÊÐƶoÂö mвæÁƵ¨¼Yü“à §‚₂¾¤н7Þ9úÂuœ¿®jF™SΛ¬ìr½ƒxßU‘Lβ7≠°oι—ĀÅýÆgBÐγö™α₆©vÝeEXεò₁Uт3ÈĀ(wº4{ºö쾫 åUøò${J#₃O<!øN”;GÑéÈfm ½™×γäJǝõ¥àÐι)λÓ:α–ù?6¦¨·ã™ζÙ4ÍHd›-Iž|ï¦{Ö9ÊàÛ§¥–Σÿ%ć8ùćYáþǝC±;••O褕в.¥εI‚₄S₁β+₁∦`αO}Wkè ``` That took quite a while.. 139 colors to create a string of.. >.> Takes input as a 24-bit integers to save 1 byte. [Try it online](https://tio.run/##VVZrU1NXFP3ur4iiYqWl14oFsQ4d0WpBi9VSdByrOGqx1GpVtCp2rpcQ8BHFBN@8EpIAJkIeEJPATWb2ysWZMnMm/oX7R@g@9@blTBLOY5@119p7n324cr373KUL64c61@tN1W94jn0cb8MLCvTvx/ODSJnDD42USGCsD8/xkgJt8Iq57rzaQxkxillTcyHS20NBpGmGUiLe0r/p70/abQoaHlPNiPSRljvbxdxOyq16DiNOH8iHR3iMBGL7a/DIVKOFuKlO8UfESMcgniB8@CqcCMB9AL7bTED10cx2TN6AF7HGTxrGkMQ0Filmqq9oxlRH4Tx4UYyS/u8OpdZUvZjsxigttmBm09bNWylLEbh/@c9z7wg7axJxjBo6XmP551OFlZsiVtBrT3Y1i1d4fKmgG966vCriXRikCFultiBKUQqcFgkhYzDTy8ynaQ4jzU0cqw01Z011bNWDp/SO5tgzRRVmy4wki/flcXGFd9dcNCu/FIDrT2sJOQaihMIrI0qVqVyXGIZOaesYwpSrTMZMdQKq4SsekWG9VvFn6Arem06/bbuAl/agvGR5uC6xQwrrW5DYpQ32WTF0IIeFNVeVKnc1ySJElWbkHBZz1oqHNF0CKZpgAIOKkcVMaT6KeYUW4Sn6lap4K4MRhOCzqDk@8yEx2UUVdQpRpjKzcD4/4aQFi4XhRfjaBcXUIlxkFUdMThKQwBZcdRpkHD9fkIC5UqKnKGsNLyuYp1g3LeM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65nE3e6tST@XX/OeckoxKCpn2BSHoMoRCmLS3DG47hQIG@UUsOOCqYkhvjiPYet1Nn3LCnLBYWrW3VipPnh3Z2ZBEeNPGzeJGa9xLvp5Z4AhzLNc5x5ThaFM1MhrbnzGHncrUfjW1mKGuIvnfDneI4Cw/nCqlZb295S2d2VcWDmMhwhfLsOMrihHsqljh@j9d220ivWtsS0Xr2VcQnqgQnT4N623tHhP@els6uIdPGXxB4q5RBJY55pppwTFtEhXae0pfdhNEQR1eRxDrVgQr8YkVrp1pZ/SWhxR7rofkeTxajaKxT0/3@R@qigs146XZXy4JZvSIlq8A3LXXS3C/YFflA1a6uPO5eNXKVzCfX0aojRO8quAwQs9WLjAj4PSf5IfsH1IfXPkynkKVCPWxmu/ONjonD48wTwyQ/VatP1IC1Mn5je1NXamRE1lHiB0sSojs0CNL06ik8KMI3L4CCObq9egYNV6lbkG8WBzhRv6@lkheQz9VvEkvWXyzM@fTdkwUYcklB7VS2la/MPJmk5r7/hNCt2g1KbnH0y2M5njWtTGWaDwNS3BIjIyl1IKrt@bMMLvziof0iJMluZvY/yS44y2gqiuPGj/rFRiOCMfuEPJqnuU5IcxxG4XoFgQaAfHde@9lmIW3PbtHsR/4OgfPspZn8fw5atWSokSfMXw/pZP41jhuzLF3hJfaWvw1rM7bgKJhhpusHN8hWYEhVW8qYL72EWOw9ffqxt94PZ7Dy/rOChcZ/z@B/iQxh16X2aoFonM0Fn4sPFp3E6Rw0YbmW7LxsnPf7PRMgpoK2eMUA2cZi1atJS/@Z8BkYdftUjb/Y5uzG0f2q6qttntTRanU6pyOixVktPpaLQ0SvbmygpeFB@LZHwsFTVSY7nNUldub66otNTUVVTaqy32SqezttJS52isqKuxVFTbmmuqLY5mW1NTnaXRYatqqvkf). (Both are slightly modified to take Hexadecimal strings as input instead, since it's easier to test.) **Explanation:** First we generate all the color-strings: ```python .•ŒRǝJÖ¤|DÕGø∊ŸγÜuÕפJÓΩaĀhºΔè₆ìkh¥ù§¸β?|"qтy¥Œ›ιM?z*Ω3¿ƒLò·¡ËÌóñD#Ë‰в††α½ÅÎëLpÄäÍEáyø‡§*ßtÓñ7тÜöãô±‘§—ÄGfΔ½~10'–ßaÔ´?ç"&$&¾¬ÍTʒ}M‰8βÔŽÙûQ[мvαн'YW:ΘÌiнœ+ĀβWŬŽø%ð°¤]γθγçkÌã©Ð:8• '# Push compressed string "chiffon lavenderblush papayawhip blanchedalmond misty bisque moccasin navajo puff beige azure dew khaki violet lavender cyan burly plum boro crimson violet orchid tle violet khaki rosy orchid turquoise sienna orchid violet dle violet maroon drab cadet indigo turquoise turquoise cyan turquoise steelblue" # # Split this string on spaces ` # Push each string separately to the stack “ƒÏª©–°0‡—–í0‡—‡—–°0ˆ¨ˆ¨¤Æl–°ÿ•³0¤Ð0‡—–°ÿ–í0Ž¹0ˆ¨ë¿Ž¹0ˆ¨Ü„Àš0‡—·¡r0‡—‡Ž0í™0ˆ¨ï×0ˆ¨í™0ˆ¨–°s0Ž¦0°¯ë¿0ˆ¨–í0í™0ˆ¨ ÿïˆ0‡—–Í0‡—–°s0Ž¦0‡—–íÿ ÿ–°0Ê£0ˆ¨ ÿ0‡—ÃÅ0žç0‡—Ôî0´Ò–í0Ü„0›Ðæá0°¯ s0Ž¦0‡—Ê£ÿ s0Ž¦0°¯¦º0Ž¦0°¯–ís0Ž¦0‡—į0ˆ¨œëre0€ÅÜ„0›Ð ÿ´ÒÊ£°¯¤Ð0‡—‡Ž0¤Ð0‡—‡—ÿ–°0†¾–°m0î±a»Ïÿ0ŽÌ–°0í™0ˆ¨‡Ž0ˆ¨–í0´Ò–°ÿæ§0ˆ¨–°ÿŠÛ0ˆ¨ ÿŽÌ–°0°¯‡Ž0‡—ˆ¨0ŠÛæ§ÿ‡Ž0–Í0‡—¼ì0‡—ŠÄ0Ñ´–°0ž®0»³–íÿ ÿ0ŽÌ–°ÿ‹ß–íÿ0†¾•‹0†¾¾ç¨ËÇ⇎0°¯€Œÿ ÿž®0»³æ§ÿ0†¾ ÿÆŠÿ ÿ ÿ0–œ‡Žÿ ÿ–°0ÇÝ ÿæ§0ž®0»³‡Ž0Í€ ÿ¿í0‡—Æàÿ ÿǨ0ŽÌÍÍ ÿ„¸0³«¼Õ0¥â·ä0„¸ÇÝ°Š0„¸ƒ£n‡Ž0ž®0»³0ŠÛ„Ï0ÕÚ†¾ m0î±a•³0™Å›È0†¾æž…ß0™ÅÍ€–°0›È‡Ž0ÇݛȇŽ0™Å™Åˆ° p0‚Ìÿ ÿ0„¸ ÿ ÿ ÿ0šÓ ÿ ÿ ÿí™0¬•ÃÅ0»»ËÃÿÄ‚0„¸œÒŠÛ‡Ž0ŠÛ؉„¸“ # Push dictionary string "black navy dark0 blue medium0 blue blue dark0 green green teal darkÿ deep0 sky0 blue darkÿ medium0 spring0 green lime spring0 green aqua midnight0 blue dodger0 blue light0 sea0 green forest0 green sea0 green darks0 late0 grey lime0 green medium0 sea0 green ÿ royal0 blue steel0 blue darks0 late0 blue mediumÿ ÿ dark0 olive0 green ÿ0 blue corn0 flower0 blue rebecca0 purple medium0 aqua0 marine dim0 grey s0 late0 blue oliveÿ s0 late0 grey lights0 late0 grey mediums0 late0 blue lawn0 green chartre0 use aqua0 marine ÿ purple olive grey sky0 blue light0 sky0 blue blueÿ dark0 red darkm0 agenta sadÿ0 brown dark0 sea0 green light0 green medium0 purple darkÿ pale0 green darkÿ yellow0 green ÿ brown dark0 grey light0 blue green0 yellow paleÿ light0 steel0 blue powder0 blue fire0 brick dark0 golden0 rod mediumÿ ÿ0 brown darkÿ silver mediumÿ0 red indian0 red peru chocolate tan light0 grey thisÿ ÿ golden0 rod paleÿ0 red ÿ gainsÿ ÿ ÿ0 wood lightÿ ÿ dark0 salmon ÿ pale0 golden0 rod light0 coral ÿ alice0 blue honeyÿ ÿ sandy0 brown wheat ÿ white0 smoke mint0 cream ghost0 white salmon antique0 white linen light0 golden0 rod0 yellow old0 lace red m0 agenta deep0 pink orange0 red tomato hot0 pink coral dark0 orange light0 salmon orange light0 pink pink gold p0 eachÿ ÿ0 white ÿ ÿ ÿ0 rose ÿ ÿ ÿ sea0 shell corn0 silk lemonÿ floral0 white snow yellow light0 yellow ivory white" # Where all `ÿ` are automatically filled with the strings on the stack „0 K # Remove all "0 " from this string # # Split the colors on spaces ``` Then we generate a list of forward differences (deltas) between each integer value of the colors: ```python •zÑĪåð≠K¯&u+UhĆõ;Éðf.ã₂=нH,ª@O¶ü˜ˆ₂Ɔ¥2Œ’Ktθu1Sнdw΀(#ç¹ü‹U¹³αh+8R∍±æ”ÇKë₆ßõk₃¿θòĀηú¿ζвî!Vs©₂™CÖ.∍JнαθWÀhzαÐé3¾¯|ë¡×°'βâá—P‘Å_uë_§₃P∊%ý/=i]¥5óO₃^E‘[∞₆ć:βU=J€¦†˜X'Žāìd4Ā’δ‹a°∊›ÊÐƶoÂö mвæÁƵ¨¼Yü“à §‚₂¾¤н7Þ9úÂuœ¿®jF™SΛ¬ìr½ƒxßU‘Lβ7≠°oι—ĀÅýÆgBÐγö™α₆©vÝeEXεò₁Uт3ÈĀ(wº4{ºö쾫 åUøò${J#₃O<!øN”;GÑéÈfm ½™×γäJǝõ¥àÐι)λÓ:α–ù?6¦¨·ã™ζÙ4ÍHd›-Iž|ï¦{Ö9ÊàÛ§¥–Σÿ%ć8ùćYáþǝC±;• # Push compressed integer 199435987809271424589508700952987345999804200072375133628254343692108407476588500135573281889031649216370100759626064238727072489415325130552011943231372407222964404763401980843968947657212497212027480199840300219769136432328209307347145119976644138878553798683794751309798787883572249589074597119540397124774131357786254535108429605287982569524294490533853150008626425797260994727581899181000813165364870780739754491720041566206327597753141661846275821649635815830948299823383964329384068145070200611196756567681968774265025511020508722510627341700584849057763591073777679021648285012447092662591008342199952284925672007531443930335828262810273697784303468071652124201899153101970895280421720006686387730894329535589566680885995478455871002071758051626349351150223272343920758114226776399859623393233070539000599481915926111317851112136858026586181791 •O褕 # Push compressed integer 1579378 в # Convert the larger integer to Base-1579378 as list: [128,11,66,50,25345,7168,128,2827,13428,3794,11209,1126,127,128,1579377,358287,139691,120952,786485,50168,228835,648767,273759,35089,334035,113367,37953,143030,682669,668529,325453,105900,39441,170943,61796,78678,324205,460809,254037,103186,197376,212,44,128,32640,128,478827,15,154856,54302,139,17544,292732,78337,164427,36856,326341,14132,105062,361723,317437,294783,274237,9801,126911,54768,7176,82236,418793,118728,145852,75740,198997,414917,411351,10467,320479,19310,73543,322565,110846,13386,52083,41897,51360,50177,71594,149368,386811,176000,322676,26044,104406,26124,4723,1777,15,238689,80467,5929,25,2565,194821,100211,27493,1295,2540,195348,68122,255,5012,12397,7751,1645,5532,3248,5242,1158,4545,2570,5685,953,1012,1544,15,29,1772,1032,288,1273,750,497,35,10,1030,224,16,15] .¥ # Undelta this list: [0,128,139,205,255,25600,32768,32896,35723,49151,52945,64154,65280,65407,65535,1644912,2003199,2142890,2263842,3050327,3100495,3329330,3978097,4251856,4286945,4620980,4734347,4772300,4915330,5597999,6266528,6591981,6697881,6737322,6908265,6970061,7048739,7372944,7833753,8087790,8190976,8388352,8388564,8388608,8388736,8421376,8421504,8900331,8900346,9055202,9109504,9109643,9127187,9419919,9498256,9662683,9699539,10025880,10040012,10145074,10506797,10824234,11119017,11393254,11403055,11529966,11584734,11591910,11674146,12092939,12211667,12357519,12433259,12632256,13047173,13458524,13468991,13789470,13808780,13882323,14204888,14315734,14329120,14381203,14423100,14474460,14524637,14596231,14745599,15132410,15308410,15631086,15657130,15761536,15787660,15792383,15794160,15794175,16032864,16113331,16119260,16119285,16121850,16316671,16416882,16444375,16445670,16448210,16643558,16711680,16711935,16716947,16729344,16737095,16738740,16744272,16747520,16752762,16753920,16758465,16761035,16766720,16767673,16768685,16770229,16770244,16770273,16772045,16773077,16773365,16774638,16775388,16775885,16775920,16775930,16776960,16777184,16777200,16777215] ``` Then we determine the index of the value closest to the input (in terms of absolute differences between each RGB color - and here I thought I could use builtin `.x`..), determine the index of this closest integer in the list, and use that to index into the color-strings we created earlier: ```python ε # Map each integer to: I‚ # Pair it with the input-integer ₄S # Push 1000, split to digits: [1,0,0,0] ₁β # Converted from base-256 to an integer: 16777216 + # Add that to both integers in the pair ₁в # Convert both integers to base-256 as list (we now have [1,R,G,B]) €¦ # Remove the leading 1 ` # Push both lists to the stack α # Get the absolute difference between the lists (at the same indices) O # Sum these differences }W # After the map: get the minimum (without popping the list itself) k # Get the index of this minimum in the list è # And use it to index into the string-color list # (after which the result is output implicitly) ``` [See this 05AB1E tip of mine (all four sections)](https://codegolf.stackexchange.com/a/166851/52210) to understand why: * `.•ŒRǝ...Ð:8•` is `"chiffon lavenderblush papayawhip ... cyan turquoise steelblue"` * `“ƒÏª©–°0‡—...‡Ž0ŠÛ؉„¸“` is `"black navy dark0 blue ... light0 yellow ivory white"` * `•zÑÄ...C±;•` is `199...791` * `•O褕` is `1579378` * `•zÑÄ...C±;••O褕в` is `[128,11,66,...,224,16,15]`
187,493
Input ----- A single hex 6-digit colour code, capital letter, without `#`. Can also be a 24-bit integer if you prefer. Output ------ The closest HTML color *name* (e.g `red`, or `dark-salmon`, as defined as <https://www.w3schools.com/colors/colors_names.asp> or see below). Distance is defined by summing the difference in red, green and blue channels. Examples -------- > > `FF04FE`: `magenta` > > > `FFFFFF`: `white` > > > `457CCB` (halfway between `steelblue` and `darkslateblue`): `steelblue` (round **up**) > > > Rules ----- * Standard loopholes apply. * Standard I/O applies * Round up to the color with the higher channel sum if halfway between two colors. If two colours have the same channel sum, output the one which is higher as a hex code: e.g `red` = `#FF0000` = 16711680 > `blue` = `#0000FF` = 256 * If one hex code has two names (e.g. `grey` and `gray`), output either. * Outputs can be capitalised and hyphenated how you like * Trailing/preceding spaces/newlines are fine * You must output the names in full. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins. Colors ------ As per suggestion in the comments, here are all of the color names with respective hex values in CSV format: ``` Color Name,HEX Black,#000000 Navy,#000080 DarkBlue,#00008B MediumBlue,#0000CD Blue,#0000FF DarkGreen,#006400 Green,#008000 Teal,#008080 DarkCyan,#008B8B DeepSkyBlue,#00BFFF DarkTurquoise,#00CED1 MediumSpringGreen,#00FA9A Lime,#00FF00 SpringGreen,#00FF7F Aqua,#00FFFF Cyan,#00FFFF MidnightBlue,#191970 DodgerBlue,#1E90FF LightSeaGreen,#20B2AA ForestGreen,#228B22 SeaGreen,#2E8B57 DarkSlateGray,#2F4F4F DarkSlateGrey,#2F4F4F LimeGreen,#32CD32 MediumSeaGreen,#3CB371 Turquoise,#40E0D0 RoyalBlue,#4169E1 SteelBlue,#4682B4 DarkSlateBlue,#483D8B MediumTurquoise,#48D1CC Indigo,#4B0082 DarkOliveGreen,#556B2F CadetBlue,#5F9EA0 CornflowerBlue,#6495ED RebeccaPurple,#663399 MediumAquaMarine,#66CDAA DimGray,#696969 DimGrey,#696969 SlateBlue,#6A5ACD OliveDrab,#6B8E23 SlateGray,#708090 SlateGrey,#708090 LightSlateGray,#778899 LightSlateGrey,#778899 MediumSlateBlue,#7B68EE LawnGreen,#7CFC00 Chartreuse,#7FFF00 Aquamarine,#7FFFD4 Maroon,#800000 Purple,#800080 Olive,#808000 Gray,#808080 Grey,#808080 SkyBlue,#87CEEB LightSkyBlue,#87CEFA BlueViolet,#8A2BE2 DarkRed,#8B0000 DarkMagenta,#8B008B SaddleBrown,#8B4513 DarkSeaGreen,#8FBC8F LightGreen,#90EE90 MediumPurple,#9370DB DarkViolet,#9400D3 PaleGreen,#98FB98 DarkOrchid,#9932CC YellowGreen,#9ACD32 Sienna,#A0522D Brown,#A52A2A DarkGray,#A9A9A9 DarkGrey,#A9A9A9 LightBlue,#ADD8E6 GreenYellow,#ADFF2F PaleTurquoise,#AFEEEE LightSteelBlue,#B0C4DE PowderBlue,#B0E0E6 FireBrick,#B22222 DarkGoldenRod,#B8860B MediumOrchid,#BA55D3 RosyBrown,#BC8F8F DarkKhaki,#BDB76B Silver,#C0C0C0 MediumVioletRed,#C71585 IndianRed,#CD5C5C Peru,#CD853F Chocolate,#D2691E Tan,#D2B48C LightGray,#D3D3D3 LightGrey,#D3D3D3 Thistle,#D8BFD8 Orchid,#DA70D6 GoldenRod,#DAA520 PaleVioletRed,#DB7093 Crimson,#DC143C Gainsboro,#DCDCDC Plum,#DDA0DD BurlyWood,#DEB887 LightCyan,#E0FFFF Lavender,#E6E6FA DarkSalmon,#E9967A Violet,#EE82EE PaleGoldenRod,#EEE8AA LightCoral,#F08080 Khaki,#F0E68C AliceBlue,#F0F8FF HoneyDew,#F0FFF0 Azure,#F0FFFF SandyBrown,#F4A460 Wheat,#F5DEB3 Beige,#F5F5DC WhiteSmoke,#F5F5F5 MintCream,#F5FFFA GhostWhite,#F8F8FF Salmon,#FA8072 AntiqueWhite,#FAEBD7 Linen,#FAF0E6 LightGoldenRodYellow,#FAFAD2 OldLace,#FDF5E6 Red,#FF0000 Fuchsia,#FF00FF Magenta,#FF00FF DeepPink,#FF1493 OrangeRed,#FF4500 Tomato,#FF6347 HotPink,#FF69B4 Coral,#FF7F50 DarkOrange,#FF8C00 LightSalmon,#FFA07A Orange,#FFA500 LightPink,#FFB6C1 Pink,#FFC0CB Gold,#FFD700 PeachPuff,#FFDAB9 NavajoWhite,#FFDEAD Moccasin,#FFE4B5 Bisque,#FFE4C4 MistyRose,#FFE4E1 BlanchedAlmond,#FFEBCD PapayaWhip,#FFEFD5 LavenderBlush,#FFF0F5 SeaShell,#FFF5EE Cornsilk,#FFF8DC LemonChiffon,#FFFACD FloralWhite,#FFFAF0 Snow,#FFFAFA Yellow,#FFFF00 LightYellow,#FFFFE0 Ivory,#FFFFF0 White,#FFFFFF ```
2019/06/30
[ "https://codegolf.stackexchange.com/questions/187493", "https://codegolf.stackexchange.com", "https://codegolf.stackexchange.com/users/85546/" ]
[Node.js](https://nodejs.org), 1488 bytes ========================================= Takes input as a 24-bit integer. Outputs in lower case. ```javascript v=>(require('zlib').inflateRawSync(Buffer('TVRbm6o4EPxLE27CowziDOiIV+bwFkkrWUPCBBg/9tdvLurZFzGX7uqqrs6Z4fr2xvHv5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0KEmHz@PCHp51k7e62LUw2TPEYI5vvGKksA@edgILPXKk2e80DMnsVO/191O3tW9O@3/wI "JavaScript (Node.js) – Try It Online") ### How? The compressed string is 1683 characters long and looks like that: ```javascript "black0navy3KdarkblueBmediumblue1Ublue1EdarkgreenJK1green5J4(…)lightyellow68ivoryGwhiteF" ``` The colors are ordered from lowest to highest value. Each color is encoded as its name in lower case followed by the difference between its value and the previous value in base-36 and in upper case: ``` black[0] | 0x000000 + 0 --> 0x000000 navy[3K] | 0x000000 + 128 --> 0x000080 darkblue[B] | 0x000080 + 11 --> 0x00008B mediumblue[1U] | 0x00008B + 66 --> 0x0000CD blue[1E] | 0x0000CD + 50 --> 0x0000FF darkgreen[JK1] | 0x0000FF + 25345 --> 0x006400 green[5J4] | 0x006400 + 7168 --> 0x008000 ... | ... lightyellow[68] | 0xFFFF00 + 224 --> 0xFFFFE0 ivory[G] | 0xFFFFE0 + 16 --> 0xFFFFF0 white[F] | 0xFFFFF0 + 15 --> 0xFFFFFF ``` ### Commented ```javascript v => // v = input ( require('zlib') // using zlib, .inflateRawSync( // inflate the Buffer( // buffer obtained by 'TVRbm(…)Pw', // converting this string 'base64' // encoded in base-64 ) // ) + '' // and coerce it back to a string ).replace( // on which we invoke replace(): m = // initialize m to a non-numeric value /([a-z]+)([^a-z]+)/g, // for each color encoded as ... (_, s, d) => // ... s = name, d = delta in base-36: [e = 0, 8, 16] // using x = 0 for blue, 8 for green and 16 for red, .map(x => // compute the error e: e += // add to e: Math.abs( // the absolute value of the difference between (v >> x & 255) - // the component of the target color (t >> x & 255) // and the component of the current color ), // t += parseInt(d, 36) // start by adding the delta to t ) | e > m || // end of map(); if e is less than or equal to m: (o = s, m = e), // update o to s and m to e t = 0 // start with t = 0 ) && o // end of replace(); return o ```
[05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 1175 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ============================================================================================================================== ``` .•ŒRǝJÖ¤|DÕGø∊ŸγÜuÕפJÓΩaĀhºΔè₆ìkh¥ù§¸β?|"qтy¥Œ›ιM?z*Ω3¿ƒLò·¡ËÌóñD#Ë‰в††α½ÅÎëLpÄäÍEáyø‡§*ßtÓñ7тÜöãô±‘§—ÄGfΔ½~10'–ßaÔ´?ç"&$&¾¬ÍTʒ}M‰8βÔŽÙûQ[мvαн'YW:ΘÌiнœ+ĀβWŬŽø%ð°¤]γθγçkÌã©Ð:8• #`“ƒÏª©–°0‡—–í0‡—‡—–°0ˆ¨ˆ¨¤Æl–°ÿ•³0¤Ð0‡—–°ÿ–í0Ž¹0ˆ¨ë¿Ž¹0ˆ¨Ü„Àš0‡—·¡r0‡—‡Ž0í™0ˆ¨ï×0ˆ¨í™0ˆ¨–°s0Ž¦0°¯ë¿0ˆ¨–í0í™0ˆ¨ ÿïˆ0‡—–Í0‡—–°s0Ž¦0‡—–íÿ ÿ–°0Ê£0ˆ¨ ÿ0‡—ÃÅ0žç0‡—Ôî0´Ò–í0Ü„0›Ðæá0°¯ s0Ž¦0‡—Ê£ÿ s0Ž¦0°¯¦º0Ž¦0°¯–ís0Ž¦0‡—į0ˆ¨œëre0€ÅÜ„0›Ð ÿ´ÒÊ£°¯¤Ð0‡—‡Ž0¤Ð0‡—‡—ÿ–°0†¾–°m0î±a»Ïÿ0ŽÌ–°0í™0ˆ¨‡Ž0ˆ¨–í0´Ò–°ÿæ§0ˆ¨–°ÿŠÛ0ˆ¨ ÿŽÌ–°0°¯‡Ž0‡—ˆ¨0ŠÛæ§ÿ‡Ž0–Í0‡—¼ì0‡—ŠÄ0Ñ´–°0ž®0»³–íÿ ÿ0ŽÌ–°ÿ‹ß–íÿ0†¾•‹0†¾¾ç¨ËÇ⇎0°¯€Œÿ ÿž®0»³æ§ÿ0†¾ ÿÆŠÿ ÿ ÿ0–œ‡Žÿ ÿ–°0ÇÝ ÿæ§0ž®0»³‡Ž0Í€ ÿ¿í0‡—Æàÿ ÿǨ0ŽÌÍÍ ÿ„¸0³«¼Õ0¥â·ä0„¸ÇÝ°Š0„¸ƒ£n‡Ž0ž®0»³0ŠÛ„Ï0ÕÚ†¾ m0î±a•³0™Å›È0†¾æž…ß0™ÅÍ€–°0›È‡Ž0ÇݛȇŽ0™Å™Åˆ° p0‚Ìÿ ÿ0„¸ ÿ ÿ ÿ0šÓ ÿ ÿ ÿí™0¬•ÃÅ0»»ËÃÿÄ‚0„¸œÒŠÛ‡Ž0ŠÛ؉„¸“„0 K#•zÑĪåð≠K¯&u+UhĆõ;Éðf.ã₂=нH,ª@O¶ü˜ˆ₂Ɔ¥2Œ’Ktθu1Sнdw΀(#ç¹ü‹U¹³αh+8R∍±æ”ÇKë₆ßõk₃¿θòĀηú¿ζвî!Vs©₂™CÖ.∍JнαθWÀhzαÐé3¾¯|ë¡×°'βâá—P‘Å_uë_§₃P∊%ý/=i]¥5óO₃^E‘[∞₆ć:βU=J€¦†˜X'Žāìd4Ā’δ‹a°∊›ÊÐƶoÂö mвæÁƵ¨¼Yü“à §‚₂¾¤н7Þ9úÂuœ¿®jF™SΛ¬ìr½ƒxßU‘Lβ7≠°oι—ĀÅýÆgBÐγö™α₆©vÝeEXεò₁Uт3ÈĀ(wº4{ºö쾫 åUøò${J#₃O<!øN”;GÑéÈfm ½™×γäJǝõ¥àÐι)λÓ:α–ù?6¦¨·ã™ζÙ4ÍHd›-Iž|ï¦{Ö9ÊàÛ§¥–Σÿ%ć8ùćYáþǝC±;••O褕в.¥εI‚₄S₁β+₁∦`αO}Wkè ``` That took quite a while.. 139 colors to create a string of.. >.> Takes input as a 24-bit integers to save 1 byte. [Try it online](https://tio.run/##VVZrU1NXFP3ur4iiYqWl14oFsQ4d0WpBi9VSdByrOGqx1GpVtCp2rpcQ8BHFBN@8EpIAJkIeEJPATWb2ysWZMnMm/oX7R@g@9@blTBLOY5@119p7n324cr373KUL64c61@tN1W94jn0cb8MLCvTvx/ODSJnDD42USGCsD8/xkgJt8Iq57rzaQxkxillTcyHS20NBpGmGUiLe0r/p70/abQoaHlP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TGWaDwNS3BIjIyl1IKrt@bMMLvziof0iJMluZvY/yS44y2gqiuPGj/rFRiOCMfuEPJqnuU5IcxxG4XoFgQaAfHde@9lmIW3PbtHsR/4OgfPspZn8fw5atWSokSfMXw/pZP41jhuzLF3hJfaWvw1rM7bgKJhhpusHN8hWYEhVW8qYL72EWOw9ffqxt94PZ7Dy/rOChcZ/z@B/iQxh16X2aoFonM0Fn4sPFp3E6Rw0YbmW7LxsnPf7PRMgpoK2eMUA2cZi1atJS/@Z8BkYdftUjb/Y5uzG0f2q6qttntTRanU6pyOixVktPpaLQ0SvbmygpeFB@LZHwsFTVSY7nNUldub66otNTUVVTaqy32SqezttJS52isqKuxVFTbmmuqLY5mW1NTnaXRYatqqvkf). (Both are slightly modified to take Hexadecimal strings as input instead, since it's easier to test.) **Explanation:** First we generate all the color-strings: ```python .•ŒRǝJÖ¤|DÕGø∊ŸγÜuÕפJÓΩaĀhºΔè₆ìkh¥ù§¸β?|"qтy¥Œ›ιM?z*Ω3¿ƒLò·¡ËÌóñD#Ë‰в††α½ÅÎëLpÄäÍEáyø‡§*ßtÓñ7тÜöãô±‘§—ÄGfΔ½~10'–ßaÔ´?ç"&$&¾¬ÍTʒ}M‰8βÔŽÙûQ[мvαн'YW:ΘÌiнœ+ĀβWŬŽø%ð°¤]γθγçkÌã©Ð:8• '# Push compressed string "chiffon lavenderblush papayawhip blanchedalmond misty bisque moccasin navajo puff beige azure dew khaki violet lavender cyan burly plum boro crimson violet orchid tle violet khaki rosy orchid turquoise sienna orchid violet dle violet maroon drab cadet indigo turquoise turquoise cyan turquoise steelblue" # # Split this string on spaces ` # Push each string separately to the stack “ƒÏª©–°0‡—–í0‡—‡—–°0ˆ¨ˆ¨¤Æl–°ÿ•³0¤Ð0‡—–°ÿ–í0Ž¹0ˆ¨ë¿Ž¹0ˆ¨Ü„Àš0‡—·¡r0‡—‡Ž0í™0ˆ¨ï×0ˆ¨í™0ˆ¨–°s0Ž¦0°¯ë¿0ˆ¨–í0í™0ˆ¨ ÿïˆ0‡—–Í0‡—–°s0Ž¦0‡—–íÿ ÿ–°0Ê£0ˆ¨ ÿ0‡—ÃÅ0žç0‡—Ôî0´Ò–í0Ü„0›Ðæá0°¯ s0Ž¦0‡—Ê£ÿ s0Ž¦0°¯¦º0Ž¦0°¯–ís0Ž¦0‡—į0ˆ¨œëre0€ÅÜ„0›Ð ÿ´ÒÊ£°¯¤Ð0‡—‡Ž0¤Ð0‡—‡—ÿ–°0†¾–°m0î±a»Ïÿ0ŽÌ–°0í™0ˆ¨‡Ž0ˆ¨–í0´Ò–°ÿæ§0ˆ¨–°ÿŠÛ0ˆ¨ ÿŽÌ–°0°¯‡Ž0‡—ˆ¨0ŠÛæ§ÿ‡Ž0–Í0‡—¼ì0‡—ŠÄ0Ñ´–°0ž®0»³–íÿ ÿ0ŽÌ–°ÿ‹ß–íÿ0†¾•‹0†¾¾ç¨ËÇ⇎0°¯€Œÿ ÿž®0»³æ§ÿ0†¾ ÿÆŠÿ ÿ ÿ0–œ‡Žÿ ÿ–°0ÇÝ ÿæ§0ž®0»³‡Ž0Í€ ÿ¿í0‡—Æàÿ ÿǨ0ŽÌÍÍ ÿ„¸0³«¼Õ0¥â·ä0„¸ÇÝ°Š0„¸ƒ£n‡Ž0ž®0»³0ŠÛ„Ï0ÕÚ†¾ m0î±a•³0™Å›È0†¾æž…ß0™ÅÍ€–°0›È‡Ž0ÇݛȇŽ0™Å™Åˆ° p0‚Ìÿ ÿ0„¸ ÿ ÿ ÿ0šÓ ÿ ÿ ÿí™0¬•ÃÅ0»»ËÃÿÄ‚0„¸œÒŠÛ‡Ž0ŠÛ؉„¸“ # Push dictionary string "black navy dark0 blue medium0 blue blue dark0 green green teal darkÿ deep0 sky0 blue darkÿ medium0 spring0 green lime spring0 green aqua midnight0 blue dodger0 blue light0 sea0 green forest0 green sea0 green darks0 late0 grey lime0 green medium0 sea0 green ÿ royal0 blue steel0 blue darks0 late0 blue mediumÿ ÿ dark0 olive0 green ÿ0 blue corn0 flower0 blue rebecca0 purple medium0 aqua0 marine dim0 grey s0 late0 blue oliveÿ s0 late0 grey lights0 late0 grey mediums0 late0 blue lawn0 green chartre0 use aqua0 marine ÿ purple olive grey sky0 blue light0 sky0 blue blueÿ dark0 red darkm0 agenta sadÿ0 brown dark0 sea0 green light0 green medium0 purple darkÿ pale0 green darkÿ yellow0 green ÿ brown dark0 grey light0 blue green0 yellow paleÿ light0 steel0 blue powder0 blue fire0 brick dark0 golden0 rod mediumÿ ÿ0 brown darkÿ silver mediumÿ0 red indian0 red peru chocolate tan light0 grey thisÿ ÿ golden0 rod paleÿ0 red ÿ gainsÿ ÿ ÿ0 wood lightÿ ÿ dark0 salmon ÿ pale0 golden0 rod light0 coral ÿ alice0 blue honeyÿ ÿ sandy0 brown wheat ÿ white0 smoke mint0 cream ghost0 white salmon antique0 white linen light0 golden0 rod0 yellow old0 lace red m0 agenta deep0 pink orange0 red tomato hot0 pink coral dark0 orange light0 salmon orange light0 pink pink gold p0 eachÿ ÿ0 white ÿ ÿ ÿ0 rose ÿ ÿ ÿ sea0 shell corn0 silk lemonÿ floral0 white snow yellow light0 yellow ivory white" # Where all `ÿ` are automatically filled with the strings on the stack „0 K # Remove all "0 " from this string # # Split the colors on spaces ``` Then we generate a list of forward differences (deltas) between each integer value of the colors: ```python •zÑĪåð≠K¯&u+UhĆõ;Éðf.ã₂=нH,ª@O¶ü˜ˆ₂Ɔ¥2Œ’Ktθu1Sнdw΀(#ç¹ü‹U¹³αh+8R∍±æ”ÇKë₆ßõk₃¿θòĀηú¿ζвî!Vs©₂™CÖ.∍JнαθWÀhzαÐé3¾¯|ë¡×°'βâá—P‘Å_uë_§₃P∊%ý/=i]¥5óO₃^E‘[∞₆ć:βU=J€¦†˜X'Žāìd4Ā’δ‹a°∊›ÊÐƶoÂö mвæÁƵ¨¼Yü“à §‚₂¾¤н7Þ9úÂuœ¿®jF™SΛ¬ìr½ƒxßU‘Lβ7≠°oι—ĀÅýÆgBÐγö™α₆©vÝeEXεò₁Uт3ÈĀ(wº4{ºö쾫 åUøò${J#₃O<!øN”;GÑéÈfm ½™×γäJǝõ¥àÐι)λÓ:α–ù?6¦¨·ã™ζÙ4ÍHd›-Iž|ï¦{Ö9ÊàÛ§¥–Σÿ%ć8ùćYáþǝC±;• # Push compressed integer 199435987809271424589508700952987345999804200072375133628254343692108407476588500135573281889031649216370100759626064238727072489415325130552011943231372407222964404763401980843968947657212497212027480199840300219769136432328209307347145119976644138878553798683794751309798787883572249589074597119540397124774131357786254535108429605287982569524294490533853150008626425797260994727581899181000813165364870780739754491720041566206327597753141661846275821649635815830948299823383964329384068145070200611196756567681968774265025511020508722510627341700584849057763591073777679021648285012447092662591008342199952284925672007531443930335828262810273697784303468071652124201899153101970895280421720006686387730894329535589566680885995478455871002071758051626349351150223272343920758114226776399859623393233070539000599481915926111317851112136858026586181791 •O褕 # Push compressed integer 1579378 в # Convert the larger integer to Base-1579378 as list: [128,11,66,50,25345,7168,128,2827,13428,3794,11209,1126,127,128,1579377,358287,139691,120952,786485,50168,228835,648767,273759,35089,334035,113367,37953,143030,682669,668529,325453,105900,39441,170943,61796,78678,324205,460809,254037,103186,197376,212,44,128,32640,128,478827,15,154856,54302,139,17544,292732,78337,164427,36856,326341,14132,105062,361723,317437,294783,274237,9801,126911,54768,7176,82236,418793,118728,145852,75740,198997,414917,411351,10467,320479,19310,73543,322565,110846,13386,52083,41897,51360,50177,71594,149368,386811,176000,322676,26044,104406,26124,4723,1777,15,238689,80467,5929,25,2565,194821,100211,27493,1295,2540,195348,68122,255,5012,12397,7751,1645,5532,3248,5242,1158,4545,2570,5685,953,1012,1544,15,29,1772,1032,288,1273,750,497,35,10,1030,224,16,15] .¥ # Undelta this list: [0,128,139,205,255,25600,32768,32896,35723,49151,52945,64154,65280,65407,65535,1644912,2003199,2142890,2263842,3050327,3100495,3329330,3978097,4251856,4286945,4620980,4734347,4772300,4915330,5597999,6266528,6591981,6697881,6737322,6908265,6970061,7048739,7372944,7833753,8087790,8190976,8388352,8388564,8388608,8388736,8421376,8421504,8900331,8900346,9055202,9109504,9109643,9127187,9419919,9498256,9662683,9699539,10025880,10040012,10145074,10506797,10824234,11119017,11393254,11403055,11529966,11584734,11591910,11674146,12092939,12211667,12357519,12433259,12632256,13047173,13458524,13468991,13789470,13808780,13882323,14204888,14315734,14329120,14381203,14423100,14474460,14524637,14596231,14745599,15132410,15308410,15631086,15657130,15761536,15787660,15792383,15794160,15794175,16032864,16113331,16119260,16119285,16121850,16316671,16416882,16444375,16445670,16448210,16643558,16711680,16711935,16716947,16729344,16737095,16738740,16744272,16747520,16752762,16753920,16758465,16761035,16766720,16767673,16768685,16770229,16770244,16770273,16772045,16773077,16773365,16774638,16775388,16775885,16775920,16775930,16776960,16777184,16777200,16777215] ``` Then we determine the index of the value closest to the input (in terms of absolute differences between each RGB color - and here I thought I could use builtin `.x`..), determine the index of this closest integer in the list, and use that to index into the color-strings we created earlier: ```python ε # Map each integer to: I‚ # Pair it with the input-integer ₄S # Push 1000, split to digits: [1,0,0,0] ₁β # Converted from base-256 to an integer: 16777216 + # Add that to both integers in the pair ₁в # Convert both integers to base-256 as list (we now have [1,R,G,B]) €¦ # Remove the leading 1 ` # Push both lists to the stack α # Get the absolute difference between the lists (at the same indices) O # Sum these differences }W # After the map: get the minimum (without popping the list itself) k # Get the index of this minimum in the list è # And use it to index into the string-color list # (after which the result is output implicitly) ``` [See this 05AB1E tip of mine (all four sections)](https://codegolf.stackexchange.com/a/166851/52210) to understand why: * `.•ŒRǝ...Ð:8•` is `"chiffon lavenderblush papayawhip ... cyan turquoise steelblue"` * `“ƒÏª©–°0‡—...‡Ž0ŠÛ؉„¸“` is `"black navy dark0 blue ... light0 yellow ivory white"` * `•zÑÄ...C±;•` is `199...791` * `•O褕` is `1579378` * `•zÑÄ...C±;••O褕в` is `[128,11,66,...,224,16,15]`
187,493
Input ----- A single hex 6-digit colour code, capital letter, without `#`. Can also be a 24-bit integer if you prefer. Output ------ The closest HTML color *name* (e.g `red`, or `dark-salmon`, as defined as <https://www.w3schools.com/colors/colors_names.asp> or see below). Distance is defined by summing the difference in red, green and blue channels. Examples -------- > > `FF04FE`: `magenta` > > > `FFFFFF`: `white` > > > `457CCB` (halfway between `steelblue` and `darkslateblue`): `steelblue` (round **up**) > > > Rules ----- * Standard loopholes apply. * Standard I/O applies * Round up to the color with the higher channel sum if halfway between two colors. If two colours have the same channel sum, output the one which is higher as a hex code: e.g `red` = `#FF0000` = 16711680 > `blue` = `#0000FF` = 256 * If one hex code has two names (e.g. `grey` and `gray`), output either. * Outputs can be capitalised and hyphenated how you like * Trailing/preceding spaces/newlines are fine * You must output the names in full. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins. Colors ------ As per suggestion in the comments, here are all of the color names with respective hex values in CSV format: ``` Color Name,HEX Black,#000000 Navy,#000080 DarkBlue,#00008B MediumBlue,#0000CD Blue,#0000FF DarkGreen,#006400 Green,#008000 Teal,#008080 DarkCyan,#008B8B DeepSkyBlue,#00BFFF DarkTurquoise,#00CED1 MediumSpringGreen,#00FA9A Lime,#00FF00 SpringGreen,#00FF7F Aqua,#00FFFF Cyan,#00FFFF MidnightBlue,#191970 DodgerBlue,#1E90FF LightSeaGreen,#20B2AA ForestGreen,#228B22 SeaGreen,#2E8B57 DarkSlateGray,#2F4F4F DarkSlateGrey,#2F4F4F LimeGreen,#32CD32 MediumSeaGreen,#3CB371 Turquoise,#40E0D0 RoyalBlue,#4169E1 SteelBlue,#4682B4 DarkSlateBlue,#483D8B MediumTurquoise,#48D1CC Indigo,#4B0082 DarkOliveGreen,#556B2F CadetBlue,#5F9EA0 CornflowerBlue,#6495ED RebeccaPurple,#663399 MediumAquaMarine,#66CDAA DimGray,#696969 DimGrey,#696969 SlateBlue,#6A5ACD OliveDrab,#6B8E23 SlateGray,#708090 SlateGrey,#708090 LightSlateGray,#778899 LightSlateGrey,#778899 MediumSlateBlue,#7B68EE LawnGreen,#7CFC00 Chartreuse,#7FFF00 Aquamarine,#7FFFD4 Maroon,#800000 Purple,#800080 Olive,#808000 Gray,#808080 Grey,#808080 SkyBlue,#87CEEB LightSkyBlue,#87CEFA BlueViolet,#8A2BE2 DarkRed,#8B0000 DarkMagenta,#8B008B SaddleBrown,#8B4513 DarkSeaGreen,#8FBC8F LightGreen,#90EE90 MediumPurple,#9370DB DarkViolet,#9400D3 PaleGreen,#98FB98 DarkOrchid,#9932CC YellowGreen,#9ACD32 Sienna,#A0522D Brown,#A52A2A DarkGray,#A9A9A9 DarkGrey,#A9A9A9 LightBlue,#ADD8E6 GreenYellow,#ADFF2F PaleTurquoise,#AFEEEE LightSteelBlue,#B0C4DE PowderBlue,#B0E0E6 FireBrick,#B22222 DarkGoldenRod,#B8860B MediumOrchid,#BA55D3 RosyBrown,#BC8F8F DarkKhaki,#BDB76B Silver,#C0C0C0 MediumVioletRed,#C71585 IndianRed,#CD5C5C Peru,#CD853F Chocolate,#D2691E Tan,#D2B48C LightGray,#D3D3D3 LightGrey,#D3D3D3 Thistle,#D8BFD8 Orchid,#DA70D6 GoldenRod,#DAA520 PaleVioletRed,#DB7093 Crimson,#DC143C Gainsboro,#DCDCDC Plum,#DDA0DD BurlyWood,#DEB887 LightCyan,#E0FFFF Lavender,#E6E6FA DarkSalmon,#E9967A Violet,#EE82EE PaleGoldenRod,#EEE8AA LightCoral,#F08080 Khaki,#F0E68C AliceBlue,#F0F8FF HoneyDew,#F0FFF0 Azure,#F0FFFF SandyBrown,#F4A460 Wheat,#F5DEB3 Beige,#F5F5DC WhiteSmoke,#F5F5F5 MintCream,#F5FFFA GhostWhite,#F8F8FF Salmon,#FA8072 AntiqueWhite,#FAEBD7 Linen,#FAF0E6 LightGoldenRodYellow,#FAFAD2 OldLace,#FDF5E6 Red,#FF0000 Fuchsia,#FF00FF Magenta,#FF00FF DeepPink,#FF1493 OrangeRed,#FF4500 Tomato,#FF6347 HotPink,#FF69B4 Coral,#FF7F50 DarkOrange,#FF8C00 LightSalmon,#FFA07A Orange,#FFA500 LightPink,#FFB6C1 Pink,#FFC0CB Gold,#FFD700 PeachPuff,#FFDAB9 NavajoWhite,#FFDEAD Moccasin,#FFE4B5 Bisque,#FFE4C4 MistyRose,#FFE4E1 BlanchedAlmond,#FFEBCD PapayaWhip,#FFEFD5 LavenderBlush,#FFF0F5 SeaShell,#FFF5EE Cornsilk,#FFF8DC LemonChiffon,#FFFACD FloralWhite,#FFFAF0 Snow,#FFFAFA Yellow,#FFFF00 LightYellow,#FFFFE0 Ivory,#FFFFF0 White,#FFFFFF ```
2019/06/30
[ "https://codegolf.stackexchange.com/questions/187493", "https://codegolf.stackexchange.com", "https://codegolf.stackexchange.com/users/85546/" ]
[C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 231+21=252 bytes ======================================================================================================================== ```cs s=>Color.FromArgb(Convert.ToInt32(s,16));f=s=>Enum.GetNames(typeof(KnownColor)).Select(x=>Color.FromName(x)).Where(x=>!x.IsSystemColor&x.A>254).OrderBy(x=>Math.Abs(x.R-C(s).R)+Math.Abs(x.G-C(s).G)+Math.Abs(x.B-C(s).B)).First().Name ``` Explanation: ```cs using System.Drawing; //System library that handles Colors in C# C=s=>Color.FromArgb(Convert.ToInt32(s,16)); //helper method. receives a hex string and returns it's Color f=s=>Enum.GetNames(typeof(KnownColor)) //collection of color names from the System.Drawing.KnownColor enum .Select(x=>Color.FromName(x)) //convert the color names to Colors .Where(x=>!x.IsSystemColor&x.A>254) //filter out unwanted colors .OrderBy(x=>Math.Abs(x.R-C(s).R) //order by increasing distance +Math.Abs(x.G-C(s).G) +Math.Abs(x.B-C(s).B)) .First().Name //return the closest color's name ``` For some reason, Tio complains that the namespace 'Drawing' does not exist in the namespace 'System', despite the source project [Mono](https://www.mono-project.com/docs/gui/drawing/) stating it's compatible. It works fine in VisualStudio though. EDIT: apparently it [hasn't been implemented](https://github.com/TryItOnline/cs-mono/blob/master/README.md) into Tio yet! [Try it online!](https://tio.run/##bc9Li8IwEAfwu5@i62FJWA2aah@4FpL0gewLdMFz7aZasMmSxLV@@m5rL0o9hfnNn5lJpseZLuqTLsTe2ly04SUKVXpuysUgPonsVRvVFCOrewMrv3cmj1IFFrOWtV4G1wrFSpZE7XeASfHHlUHfciWMjYEeTR0IF/myiUbiVKKEm8@05BqYyy@XOXgT8iyuQyBEG37kmQHV7dg2DaqmuT1wxdveU4VWurv8GnuuEAnwfAbRl/rhil7a0EdqDojsNKjQesyAhmgNX24w6TC5Q9ohbbbFhdIGQNSurxeDrSoMfy8EBzkYxrbvUG/Y/OveGaHuBPc9xFOX0b4T3w8j1veZEzqO23fbo9iPHuzFrj0nfXcp8WeTvseTcO49mONTHNl26/U/ "C# (Visual C# Interactive Compiler) – Try It Online")
[JavaScript (Node.js)](https://nodejs.org) + `color-name` package, 259 ~~279~~ ~~284~~ ~~259~~ ~~278~~ ~~282~~ ~~299~~ ~~312~~ ~~364~~ bytes ============================================================================================================================================ ```javascript c=>{w=[] K=Object.keys for(x in d=require('color-name')){(w[W=(p=i=>Math.abs(d[x][2-i]-(255&("0x"+c)>>8*i)))(2)+p(1)+p(0)]=w[W]||[]).push(x)}S=[] for(s of r=w[K(w)[0]]){(S[z=(W=d[s])[0]+W[1]+W[2]]=S[z]||[]).push([d[s],s])}return S[K(S).pop()].sort().pop()[1]} ``` [Try it online!](https://tio.run/##fVjbbts4EH3PVwh92NibNBAp67aF8wPFYh/y0AfDCGiJttXIpCLJcdzLt3c5vI6ctEBMODrD28yZMyN/ZS9sqPqmGz8KWfNfPX8@Nj1/rGQr@8fHR8EO/DFaRt@jqyhibVPxTXvk/0SriC7iWzUUakjTaH0LuBib5yM/7ZvRmKRgkqRqIM7k@cgAivU0PFcBB9Y3Qs8kNHcGhFqDb8cebTyZvOHNzmLwWA80tlgzPNsT6zlUnZiUmQVbVj3Z88CffyqqPa9Ze5CiDlP1TWK3p/WDmRmOoh6/NLLlo75HonZbJLCt27GXJ6GhTK22oPCxyLFvzycpzYZUIaRYq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ruwzhXqneOrvKhiut/NE29xRl2fkxElEKpft5MS1@g7OumuaSr5GKl7tjFkgVBC4@0a68teKgvkNpBTe0Ch2fOgI5ApaYYeNhIda/m07IEKUSMFMbLxUgWaTFMIVEoDPgk4ydNbt1ARbCbxploA4Cy@oelYx85MObxD7zKaFdbfHWfVvjtut6h664ilDu@Pvt4R6AszN3MilKUmpIPaoyGQJl@mOwnLgE6eavQ6kWshWqBYosyz6e9JoPojruiFLCD7jd8SZ1JjUbFrKsKew9uXbVpR59rLM/MKmbnC70k9sLpueVgAHKg7/9LhoST4AujYMDBRh80pVCWSqcG9h2IZWWS2ZytyDw57pcyovKeIAUPDhTAvE@BkKFau8qs3shfTOujQuMGC75YflxRT0QKoxBJ6UZiou7Crshc16S0uJnUGtzTvCaF5J7U4rmS56bFQgzbaLoOYh6iVGrlpUN60J@NeCVpr34wz1@4TG5tRHtgo/WFBTnPL40lyQjwNi2O7bngDMS2Iad8seNpzNgaBNfpXOmza4eNeSWPDQT5d/uDhgv5eEY8xhCRngcr11c9PV9vlr2p5//20XK2vPi//23zl1Xj3xM/DlXqxmL2q/jaql@/@RjT/Pjutvixn3bJZ3v/Lxv0d2wyzevW6XtGPzfrjTJ3jr9mH@PXDTTW/vy/@bubz@YzOb7oZgSGer5dqgfWPH6v1/K5T3ezsdf7zAQ4CWw@R3Ea9svg8O81X8Xqt9ntYfVvOvizr1bCGRzdfVgQGul4vFYRXWoHNrTL72YOgiuhBrfOgQNnN5uu7QfbjzP6n1vj5Szl4HKJltLpOSE7S8vo2uk5TlRsFfNuyIqH6Wc1ZvdnCN1WW6g2Fb7zYVtviev0Jzh3NXlgfaUfBBfS6c/W/GBQz7lq5mxnsJrqOPt6r4Sbamkfz@adf/wM "JavaScript (Node.js) – Try It Online") Commented: ```javascript c=>{w=[] // build dict of arrays of names, by color distance: K=Object.keys for(x in d=require('color-name')){ (w[W= (p=i=>Math.abs(d[x][2-i]-(255&("0x"+c)>>8*i)))(2) + p(1) +p(0) ] = w[W]||[]).push(x) }S=[] // distances were ordered by Object.keys() for(s of r=w[K(w)[0]]){ // build dict of [[RGB, name]+] by channel sum for distance ties: (S[ z= (W=d[s])[0] + W[1] + W[2] ]= S[z]||[]).push([d[s],s]) } return S[ K(S).pop() // highest channel sum ].sort().pop()[1]} // [name of] highest RGB ``` I had to ```javascript npm install color-name ``` for the require() to work. I don't think I can npm install on TIO, so I hardcoded the dictionary in the header. This package contains the same 148 entries as the w3schools page, names are lowercase. I have no idea who created it and when, I just found it while googling. There is a [Debian package](https://packages.debian.org/sid/node-color-name) for it, so I assume it's older than this question. **[Edit: third size reduction / major overhaul]** [Edit 5th/correction: that version had 282 bytes but was missing the tiebreak by RGB value. I don't think I can fix that one and then golf it smaller than this one, so I removed that code from the post.] This time, I rewrote most of the code. I feel that it's so different from before, it doesn't make sense to keep history in the post. @Shaggy saved me 4 bytes from the last version by omitting parentheses around single arrow function parameters. Now, there are 6 of those, so basically I owe 12 bytes of thanks. I switched from constructing dicts/lists manually to using `map` and `filter` everywhere, which enabled/prompted a lot of restructuring. I also found some more situations where I could assign variables later. **[Edit: 4th shrinking, return to the roots]** Within a minute of dismissing history (above), I realized my mistake in saying that. I applied the lessons learned so far to the old code, and I saw that the second sort() was pointless. So right now, that code is ahead by 4 bytes. [Edit: 4.1th: DUH! all sorts were pointless. -19 more bytes] **[Edit: 5th iteration, growing but now (hopefully) correct]** @Lukas Lang pointed out that my code wasn't correct in cases where the channel sum was tied. I had the wrong impression that this never occurs. To fix it, I needed to fill the arrays in `S` with [RGBarray, name] pairs instead of just names. This way, default array sorting completes the job. **[Edit: 6th reduction - gift from a higher realm]** @Shaggy gets all the credit for this round. `.reverse()[0]` is `.pop()`. Obviously... Also, implicit type conversion makes `('0x'+c)` work instead of `parseInt(c,16)`. And if you get the parantheses right, EVERY variable can be assigned at first use. This time, that was `W` and `p`.
187,493
Input ----- A single hex 6-digit colour code, capital letter, without `#`. Can also be a 24-bit integer if you prefer. Output ------ The closest HTML color *name* (e.g `red`, or `dark-salmon`, as defined as <https://www.w3schools.com/colors/colors_names.asp> or see below). Distance is defined by summing the difference in red, green and blue channels. Examples -------- > > `FF04FE`: `magenta` > > > `FFFFFF`: `white` > > > `457CCB` (halfway between `steelblue` and `darkslateblue`): `steelblue` (round **up**) > > > Rules ----- * Standard loopholes apply. * Standard I/O applies * Round up to the color with the higher channel sum if halfway between two colors. If two colours have the same channel sum, output the one which is higher as a hex code: e.g `red` = `#FF0000` = 16711680 > `blue` = `#0000FF` = 256 * If one hex code has two names (e.g. `grey` and `gray`), output either. * Outputs can be capitalised and hyphenated how you like * Trailing/preceding spaces/newlines are fine * You must output the names in full. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins. Colors ------ As per suggestion in the comments, here are all of the color names with respective hex values in CSV format: ``` Color Name,HEX Black,#000000 Navy,#000080 DarkBlue,#00008B MediumBlue,#0000CD Blue,#0000FF DarkGreen,#006400 Green,#008000 Teal,#008080 DarkCyan,#008B8B DeepSkyBlue,#00BFFF DarkTurquoise,#00CED1 MediumSpringGreen,#00FA9A Lime,#00FF00 SpringGreen,#00FF7F Aqua,#00FFFF Cyan,#00FFFF MidnightBlue,#191970 DodgerBlue,#1E90FF LightSeaGreen,#20B2AA ForestGreen,#228B22 SeaGreen,#2E8B57 DarkSlateGray,#2F4F4F DarkSlateGrey,#2F4F4F LimeGreen,#32CD32 MediumSeaGreen,#3CB371 Turquoise,#40E0D0 RoyalBlue,#4169E1 SteelBlue,#4682B4 DarkSlateBlue,#483D8B MediumTurquoise,#48D1CC Indigo,#4B0082 DarkOliveGreen,#556B2F CadetBlue,#5F9EA0 CornflowerBlue,#6495ED RebeccaPurple,#663399 MediumAquaMarine,#66CDAA DimGray,#696969 DimGrey,#696969 SlateBlue,#6A5ACD OliveDrab,#6B8E23 SlateGray,#708090 SlateGrey,#708090 LightSlateGray,#778899 LightSlateGrey,#778899 MediumSlateBlue,#7B68EE LawnGreen,#7CFC00 Chartreuse,#7FFF00 Aquamarine,#7FFFD4 Maroon,#800000 Purple,#800080 Olive,#808000 Gray,#808080 Grey,#808080 SkyBlue,#87CEEB LightSkyBlue,#87CEFA BlueViolet,#8A2BE2 DarkRed,#8B0000 DarkMagenta,#8B008B SaddleBrown,#8B4513 DarkSeaGreen,#8FBC8F LightGreen,#90EE90 MediumPurple,#9370DB DarkViolet,#9400D3 PaleGreen,#98FB98 DarkOrchid,#9932CC YellowGreen,#9ACD32 Sienna,#A0522D Brown,#A52A2A DarkGray,#A9A9A9 DarkGrey,#A9A9A9 LightBlue,#ADD8E6 GreenYellow,#ADFF2F PaleTurquoise,#AFEEEE LightSteelBlue,#B0C4DE PowderBlue,#B0E0E6 FireBrick,#B22222 DarkGoldenRod,#B8860B MediumOrchid,#BA55D3 RosyBrown,#BC8F8F DarkKhaki,#BDB76B Silver,#C0C0C0 MediumVioletRed,#C71585 IndianRed,#CD5C5C Peru,#CD853F Chocolate,#D2691E Tan,#D2B48C LightGray,#D3D3D3 LightGrey,#D3D3D3 Thistle,#D8BFD8 Orchid,#DA70D6 GoldenRod,#DAA520 PaleVioletRed,#DB7093 Crimson,#DC143C Gainsboro,#DCDCDC Plum,#DDA0DD BurlyWood,#DEB887 LightCyan,#E0FFFF Lavender,#E6E6FA DarkSalmon,#E9967A Violet,#EE82EE PaleGoldenRod,#EEE8AA LightCoral,#F08080 Khaki,#F0E68C AliceBlue,#F0F8FF HoneyDew,#F0FFF0 Azure,#F0FFFF SandyBrown,#F4A460 Wheat,#F5DEB3 Beige,#F5F5DC WhiteSmoke,#F5F5F5 MintCream,#F5FFFA GhostWhite,#F8F8FF Salmon,#FA8072 AntiqueWhite,#FAEBD7 Linen,#FAF0E6 LightGoldenRodYellow,#FAFAD2 OldLace,#FDF5E6 Red,#FF0000 Fuchsia,#FF00FF Magenta,#FF00FF DeepPink,#FF1493 OrangeRed,#FF4500 Tomato,#FF6347 HotPink,#FF69B4 Coral,#FF7F50 DarkOrange,#FF8C00 LightSalmon,#FFA07A Orange,#FFA500 LightPink,#FFB6C1 Pink,#FFC0CB Gold,#FFD700 PeachPuff,#FFDAB9 NavajoWhite,#FFDEAD Moccasin,#FFE4B5 Bisque,#FFE4C4 MistyRose,#FFE4E1 BlanchedAlmond,#FFEBCD PapayaWhip,#FFEFD5 LavenderBlush,#FFF0F5 SeaShell,#FFF5EE Cornsilk,#FFF8DC LemonChiffon,#FFFACD FloralWhite,#FFFAF0 Snow,#FFFAFA Yellow,#FFFF00 LightYellow,#FFFFE0 Ivory,#FFFFF0 White,#FFFFFF ```
2019/06/30
[ "https://codegolf.stackexchange.com/questions/187493", "https://codegolf.stackexchange.com", "https://codegolf.stackexchange.com/users/85546/" ]
[Node.js](https://nodejs.org), 1488 bytes ========================================= Takes input as a 24-bit integer. Outputs in lower case. ```javascript v=>(require('zlib').inflateRawSync(Buffer('TVRbm6o4EPxLE27CowziDOiIV+bwFkkrWUPCBBg/9tdvLurZFzGX7uqqrs6Z4fr2xvHv5OYEy9uZjRC3QOjY6r/oaH4X+ugqAXiWI/P1M28AzGxQPWHuBBkB6PrbpCPmyZs+GEb5Mwrag/O9sEn7TlJ+NSnCr4TRFk7z/+25mc7l5i0lnF6bQef6Pn6tiCBXkHo12yxTpo96wCbEqfbxRUjoB7tcxfvn0fJ4POgyeoYHuEo8IafINaY59co8exT1uJ+Uq/hVsn8KUykmzDTqzin6AcD8n/nb3Sur3nDSD9cmegUf5hHlhF6F6ySOviwY/bWwi/UO1ZiA4baIj1EtJL8wcbf8gspLJJyhrnE3yo6BExUbmx3/jLjFSis4pitCW83I/SrTVyEo3uQGiEh8Rpvi80U8+OMXVrXnTnTKowf7Z7i/fFsxfOdWx9l6XjdYDhLGHrxwvvkL75fqKwRHoS3RtahFsDEl5U8TRMudBbXrVP/8UsFgcOMP4xwJBPmlsVeLr8AH7J56TAiDsxR3nmTvRulHf4LotDQJzQptlsgyeFTxeUr1bYuwT/cdZlbyoDog0wRZN5TMy3wCpgS3PCNn0VPgHM927smgBvvvwhpeC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2eyTlpra0pWqOd2W46bXkb3A7IqNUk@Ng4zlEhx9jfHcsSmjQxwwOGwYDpqs/Qpqi3cYb1blRK7XYkqqSPt/fIAqScqxDtdjmHHYeFIPe1M1j3uzR@tQ2hBIWTVwKKH@716NH4Xo3fZn6XgUYejqbodPnrwlBmXoBQLIVhnzxPo1/oTPky3/eHSx@Qf5@qV7C2ertC1jhL@wLwfz1mnkl0q/eALrae/X11fMrBGnf3vqP5Hw@@4TU/3NnLzW6Kj1YgW1eI@ELxcxmX8Fb9vUrUqyql2wFnhErfPbxY/EteF51kYLXtIiRqSThtCROVm@T6QSdRAjevyuz2QTDJpkXg7z2PvyGfLdfke/2jnTXpAa/AvR8wfPcz8C78g5UNQCpnza/Q7gkietfoB/KO1Q38NEUSfUbtMZ5gSJ/ht6Vd2gAaVp0MQQg/wWb/fnhQ1RAJJ@sJvifk3zyeUJ8X1F0Nvnnw2TSPvUf7YdeHhYZMpv8McF7Av9hk69P5hn0c0KEmHz@PCHp51k7e62LUw2TPEYI5vvGKksA@edgILPXKk2e80DMnsVO/191O3tW9O@3/wI "JavaScript (Node.js) – Try It Online") ### How? The compressed string is 1683 characters long and looks like that: ```javascript "black0navy3KdarkblueBmediumblue1Ublue1EdarkgreenJK1green5J4(…)lightyellow68ivoryGwhiteF" ``` The colors are ordered from lowest to highest value. Each color is encoded as its name in lower case followed by the difference between its value and the previous value in base-36 and in upper case: ``` black[0] | 0x000000 + 0 --> 0x000000 navy[3K] | 0x000000 + 128 --> 0x000080 darkblue[B] | 0x000080 + 11 --> 0x00008B mediumblue[1U] | 0x00008B + 66 --> 0x0000CD blue[1E] | 0x0000CD + 50 --> 0x0000FF darkgreen[JK1] | 0x0000FF + 25345 --> 0x006400 green[5J4] | 0x006400 + 7168 --> 0x008000 ... | ... lightyellow[68] | 0xFFFF00 + 224 --> 0xFFFFE0 ivory[G] | 0xFFFFE0 + 16 --> 0xFFFFF0 white[F] | 0xFFFFF0 + 15 --> 0xFFFFFF ``` ### Commented ```javascript v => // v = input ( require('zlib') // using zlib, .inflateRawSync( // inflate the Buffer( // buffer obtained by 'TVRbm(…)Pw', // converting this string 'base64' // encoded in base-64 ) // ) + '' // and coerce it back to a string ).replace( // on which we invoke replace(): m = // initialize m to a non-numeric value /([a-z]+)([^a-z]+)/g, // for each color encoded as ... (_, s, d) => // ... s = name, d = delta in base-36: [e = 0, 8, 16] // using x = 0 for blue, 8 for green and 16 for red, .map(x => // compute the error e: e += // add to e: Math.abs( // the absolute value of the difference between (v >> x & 255) - // the component of the target color (t >> x & 255) // and the component of the current color ), // t += parseInt(d, 36) // start by adding the delta to t ) | e > m || // end of map(); if e is less than or equal to m: (o = s, m = e), // update o to s and m to e t = 0 // start with t = 0 ) && o // end of replace(); return o ```
Wolfram Language (Mathematica), 164 bytes ========================================= *Note:* This only works in Mathematica 12.0 due to a bug in previous versions. This also means there is no TIO link. ```mma g[c_]:=Last@Keys@SortBy[Round[255List@@@<|"HTML"~ColorData~"ColorRules"~Join~{"RebeccaPurple"->RGBColor@"#639"}|>],{-Total@Abs[IntegerDigits[c,256,3]-#]&,Total,#&}] ``` Defines the function `g`, which takes an integer as input. Test cases: ```mma AssociationMap[g, {327581, 3483113, 2820178, 4358965, 2058772, 13569770, 8698378, 2897368, 3896382, 12856883}] (* <| 327581 -> "MediumSpringGreen", 3483113 -> "RoyalBlue", 2820178 -> "MidnightBlue", 4358965 -> "DarkOliveGreen", 2058772 -> "ForestGreen", 13569770 -> "Magenta", 8698378 -> "Olive", 2897368 -> "RoyalBlue", 3896382 -> "DarkOliveGreen", 12856883 -> "Brown" |> *) ``` Unfortunately, quite a few bytes are wasted on adding "RebeccaPurple" to the built-in list of colors, which is missing for some reason. The rest is pretty straightforward, we just sort the colors by their distance to the input, breaking ties with the sum of channel values and then the absolute ordering.
187,493
Input ----- A single hex 6-digit colour code, capital letter, without `#`. Can also be a 24-bit integer if you prefer. Output ------ The closest HTML color *name* (e.g `red`, or `dark-salmon`, as defined as <https://www.w3schools.com/colors/colors_names.asp> or see below). Distance is defined by summing the difference in red, green and blue channels. Examples -------- > > `FF04FE`: `magenta` > > > `FFFFFF`: `white` > > > `457CCB` (halfway between `steelblue` and `darkslateblue`): `steelblue` (round **up**) > > > Rules ----- * Standard loopholes apply. * Standard I/O applies * Round up to the color with the higher channel sum if halfway between two colors. If two colours have the same channel sum, output the one which is higher as a hex code: e.g `red` = `#FF0000` = 16711680 > `blue` = `#0000FF` = 256 * If one hex code has two names (e.g. `grey` and `gray`), output either. * Outputs can be capitalised and hyphenated how you like * Trailing/preceding spaces/newlines are fine * You must output the names in full. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins. Colors ------ As per suggestion in the comments, here are all of the color names with respective hex values in CSV format: ``` Color Name,HEX Black,#000000 Navy,#000080 DarkBlue,#00008B MediumBlue,#0000CD Blue,#0000FF DarkGreen,#006400 Green,#008000 Teal,#008080 DarkCyan,#008B8B DeepSkyBlue,#00BFFF DarkTurquoise,#00CED1 MediumSpringGreen,#00FA9A Lime,#00FF00 SpringGreen,#00FF7F Aqua,#00FFFF Cyan,#00FFFF MidnightBlue,#191970 DodgerBlue,#1E90FF LightSeaGreen,#20B2AA ForestGreen,#228B22 SeaGreen,#2E8B57 DarkSlateGray,#2F4F4F DarkSlateGrey,#2F4F4F LimeGreen,#32CD32 MediumSeaGreen,#3CB371 Turquoise,#40E0D0 RoyalBlue,#4169E1 SteelBlue,#4682B4 DarkSlateBlue,#483D8B MediumTurquoise,#48D1CC Indigo,#4B0082 DarkOliveGreen,#556B2F CadetBlue,#5F9EA0 CornflowerBlue,#6495ED RebeccaPurple,#663399 MediumAquaMarine,#66CDAA DimGray,#696969 DimGrey,#696969 SlateBlue,#6A5ACD OliveDrab,#6B8E23 SlateGray,#708090 SlateGrey,#708090 LightSlateGray,#778899 LightSlateGrey,#778899 MediumSlateBlue,#7B68EE LawnGreen,#7CFC00 Chartreuse,#7FFF00 Aquamarine,#7FFFD4 Maroon,#800000 Purple,#800080 Olive,#808000 Gray,#808080 Grey,#808080 SkyBlue,#87CEEB LightSkyBlue,#87CEFA BlueViolet,#8A2BE2 DarkRed,#8B0000 DarkMagenta,#8B008B SaddleBrown,#8B4513 DarkSeaGreen,#8FBC8F LightGreen,#90EE90 MediumPurple,#9370DB DarkViolet,#9400D3 PaleGreen,#98FB98 DarkOrchid,#9932CC YellowGreen,#9ACD32 Sienna,#A0522D Brown,#A52A2A DarkGray,#A9A9A9 DarkGrey,#A9A9A9 LightBlue,#ADD8E6 GreenYellow,#ADFF2F PaleTurquoise,#AFEEEE LightSteelBlue,#B0C4DE PowderBlue,#B0E0E6 FireBrick,#B22222 DarkGoldenRod,#B8860B MediumOrchid,#BA55D3 RosyBrown,#BC8F8F DarkKhaki,#BDB76B Silver,#C0C0C0 MediumVioletRed,#C71585 IndianRed,#CD5C5C Peru,#CD853F Chocolate,#D2691E Tan,#D2B48C LightGray,#D3D3D3 LightGrey,#D3D3D3 Thistle,#D8BFD8 Orchid,#DA70D6 GoldenRod,#DAA520 PaleVioletRed,#DB7093 Crimson,#DC143C Gainsboro,#DCDCDC Plum,#DDA0DD BurlyWood,#DEB887 LightCyan,#E0FFFF Lavender,#E6E6FA DarkSalmon,#E9967A Violet,#EE82EE PaleGoldenRod,#EEE8AA LightCoral,#F08080 Khaki,#F0E68C AliceBlue,#F0F8FF HoneyDew,#F0FFF0 Azure,#F0FFFF SandyBrown,#F4A460 Wheat,#F5DEB3 Beige,#F5F5DC WhiteSmoke,#F5F5F5 MintCream,#F5FFFA GhostWhite,#F8F8FF Salmon,#FA8072 AntiqueWhite,#FAEBD7 Linen,#FAF0E6 LightGoldenRodYellow,#FAFAD2 OldLace,#FDF5E6 Red,#FF0000 Fuchsia,#FF00FF Magenta,#FF00FF DeepPink,#FF1493 OrangeRed,#FF4500 Tomato,#FF6347 HotPink,#FF69B4 Coral,#FF7F50 DarkOrange,#FF8C00 LightSalmon,#FFA07A Orange,#FFA500 LightPink,#FFB6C1 Pink,#FFC0CB Gold,#FFD700 PeachPuff,#FFDAB9 NavajoWhite,#FFDEAD Moccasin,#FFE4B5 Bisque,#FFE4C4 MistyRose,#FFE4E1 BlanchedAlmond,#FFEBCD PapayaWhip,#FFEFD5 LavenderBlush,#FFF0F5 SeaShell,#FFF5EE Cornsilk,#FFF8DC LemonChiffon,#FFFACD FloralWhite,#FFFAF0 Snow,#FFFAFA Yellow,#FFFF00 LightYellow,#FFFFE0 Ivory,#FFFFF0 White,#FFFFFF ```
2019/06/30
[ "https://codegolf.stackexchange.com/questions/187493", "https://codegolf.stackexchange.com", "https://codegolf.stackexchange.com/users/85546/" ]
[Jelly](https://github.com/DennisMitchell/jelly), ~~1015~~ 914 bytes ==================================================================== ``` “¥.⁻ḲU3ŒẆȯ§.eḊC¤ŀ"}Ʋ59£Uŀ'⁶ɠıṇȥLcṆɓ?^¢Ỵɠ.ȮẆẆḊqʠu½ỊƑfĠ⁴ µ¥ɓƭÑUC½ṁUĿẆṃ⁹S/÷Ɓɗ>ṭ"»Ḳ33r64¤,Ọy“µṂFŀƲOḌẇȤạ2œxṾk,E.LẸpḄ2s⁵Ṛç¦ṆkAẋ=çw©ḌĊẒƤm`;ṄȧṄİɦbṠṆṛ⁴Ḟ[CƊėQẏƑ<:⁾Þḍ?çⱮ3ƈṗ¬!7Hẏywœ⁽Ẉ¤ṾƈpHṗ(⁾ƲḢdƲḃ'¦ṇ9ẏP¡ċ⁻ȤẒṬf§®ṬẒpJÞẒẸṪÄƊhḊḃ7ʠ%ƈėc+ġȦı©ḄO⁸ṗ:WṠß@Ä|ż_g¹Ʋ®[*ẹ5¡Ẹßė¶~[ȷ'ȧẊṖZẋ¦ẉ7Ġ⁽ė⁽ƁLP`²¶⁶* Ġv|$ṭⱮẋ_ƭø¦Ẇ-*ɓɼhCUṙƭƭƓS7Ø⁵¤³¢Ʋẉ!§ḟƇṣḟṛḳṠƬ4ẓḢTḌZżƇȦQxw}ḃçṣȮv⁷ȤĊẏyNỵʠÄ⁸hLġị³TİọȧfÞȤTO&ṡ°⁼`WẹạẇḂvðFmż]ɦo½ƓṂḟȯ#Æ⁺T)ṃç=ḣṆø⁽Wpʂqṫ&⁷¶S®¢ð:\ṚMĖḌ½⁽_ạ⁵]Xlȷg¿£⁺x0ṁo8ẒṛżøuɲẈ®§Bṡr:ċ³ḷb|Mku¬V°ḟƲ!ɦɠ4¬>ḷ^XḶɼ5[ṇƑȮ.XȮƙẎbḊÐþFæṁoOṗ⁺mṪ-&ƊṅƑḋ$!`€ɓḥƤ¡ɗbH⁻ḃÄ⁵!Ñėḅƈḳm⁴ḳcÐⱮ⁷ỤḍġḷȥṀSĖ»Ḳ “⁸¢!İƝ\8¢[V⁸¢Ñ"ĠƙḶ-Æ⁷⁾Æ⁵¢⁸¢ƙhLṂS×®Ẓ©Aḅ¦ṚÆ&nj£ÇØ¿waþM=ÆḂḌ¢³(Ñḷx¦DẊ¢Aẓ©ḋ¬!ƁV ṾÐẉœ¦2Ä¢⁼C®⁶ẇ£ḋṀ¤çẠÐȧIæḌH€5ẋ¥®⁹µ⁻£⁴⁸¢AƇ¢⁸¢£*ç-Ụz¬>ƈ£ʋ¢^ạṭ(ÇṪĠ¤Çŀ¬ÇḞ¢ṪĠÐCȥṖÞ¦ø}×⁹YÐƬAÇ×CÆævÇ#©ḥƙ£sVṀṙ¤ỊAÞtỤ¦AǬ⁶ʠ¤⁼ƈµ£ŒÞ¿§Œ÷~2~Ðɲċ×⁻¤SƤÐ}Z¦Fƙ°¹£Ḣ©£Ṁx£⁹j£Ƒs¤ɓ8¬_ḶØz°®ʂƬÐḢ@¢ẉ€¦ỴA¢Ä8gß-Ė⁸¿zṛ¤mGKÄœ>jµ\ạ¥>R¢ƤÐƤœⱮpµỴI¤Œ¤a<[Ɱa]ṠŒɲB"'(?ŀÆȦ6ȯœ|Dy¿1€ƤØ-WXßm€v¤Uнµẋ¦iœg€Ḥ£0-‘©ṛ®Ḣ¤⁺;$%¡3¤®Ð¿Ḋḅ249:3ÄŻ,b⁹UạN,§ʋ@€/MṪị¢ ``` [Try it online!](https://tio.run/##LVV9UxNHGP/fTwFogaJB5EUQFEUsxRZEy6uigliFqlTUyosDToKRINEayAwBrRCSIxltiBBecnfhZebZu507vsXeF6G/zXRgbudun93n97abRw@ePBk7OnLc/9BqsePJCDXVXmbOCX3K@k7x4gdCnaknxXTnTfBUxTmKtpvuAsezY4eNDaH5rNWm@0KbsoMX71JEZLbscLGVxFr5r848Owy/pD2RmeGzD42w49nKoW1atYN8jc2212NG87QbB7JWe@N4tNbTLM09dqhWaGt5JJGUlT0/W07KKZF5PyYRbgttssF081SLUN8L3WcpQl8pNYOjQtt/fOqn4iahq0NC9Za@cDyo/cTiFAO8x3VC919g8RH6inXGjNDnuDLYWyM0rxXHw1i3Y31CC6NUaJ@BU6hL3fV8xgjdEPpHPnu@2vHssyWhfrjI4s5GsoxPCy1EidzKRsyPjZhBx7Mn9GlSgINPDzVithBLeEqokd/l802BBOI7h/LrtGL4IbTEPie0xEOKUxIj3oZ@QRN81FWhfWNePjMAEbG48jD8A582QvdPGitWzNiQNLwtjgdloepOAGfLl5h33Nzt6SeNpyjZXSR0rYJWsBNbNkK087rbSheAqz4jtPlbUANw9HeV0pQ9I4QH9zRd76UU7cDbohwjPDx@Ai6AK2p74JcqF0y5iuygvTtQ3y60Rb6Gv2BrJVuA1qTQJkXAVH@XS3GhLnOf0KIYoadQNwGRJ8qFHoQebbDglrnLfVbsxujIBOgxeBC1ksOOJ20p0p2PY9dEZvswzLzgONBkrIiMnzbbjHWR@WDFH7IlS2lryRfaCq07nt3eTpBFDpAHoU4Os/WGQXP3jh17Sns8iMAAhfX9OJtyPHrbj0gai18QahReMxXEO4cOJ58J7d98dKedVkpShK1X30Z4mo15QKU9FPVge7C80/XESvfTAUWx12gJ4vu0KmviZ3OXqS/tlMxAkuKXAe15tQHMQk33jTc/fkmJDlqXsqRy7ZgdLqdELabudgl1x96t6EY0@KyVLO6yknxR6H/3wXcWYPsNLCabtMBndBxEKlz5HBa@5bNC9Z/I7XUmEzZEXeUKrdihvsbsAX4jddvOZbNGSKhvkVV1czAb6s37LABLwVRkFKQZwqppa1Vo7lZjPnvgjuGUQXOK5Brr/MvtKop0d2Tf2WyeEQY2dccllUzLAzEljY9kp/niQBOkbmUhZFmfo6916Cwj/4lN5f/5iKLMxxboYOQe22@@wHA3TEppI7RZyMAkPUqxK8gmRXBQgzLdfhwu7unIycGBYgGkygxSrJR5ZbvdegKFHdhNSJgf6ElBhPQwC1jxq1BMfd8IXSpkyldlqUbb0EWatpUFW8d9/8OmaBGLuyDGKxjCpyl66KfIXZklba2QIcLfjDA295luSuBVXcIlJ7@xQL2UbZ4tUYypEwzuaDdZgCfqwDNUz6ZYbJj5jksmq3yRoi86gBJnBhdEZqaOLf2FlhRDMSXA5BA9QAv9tylqzmHTA4pjTL8ufc0CdsrwywYZUlq5wgITtyjWgE3XSZP8I/QVg@Yelfw0KM1nX5BiB6so0QO32MIrVCYPJ3kCOqqRS2Cgv4M8MCezVQdjvVX9bNllzEtBDl4hy6QM/vwr85rB2ke0fRti0Grtb7AYvbmCq24jOYSLOLN1FT8Lc6TcO9@NT/fu4Iybc3bqcl5B4UXTzaas2FnruxkcvzJGB2fQEOsXXJ1dbHkQL8OktLMA7WEjeRf9YQb78VWoCkVLXI57AcoBSFLSgzR6zYkfaKUMl0wSiw6yl@Lb0vJz1WWAmTnVB@LtwHntFMUP/Zew0elm2CQvjcgRJrfaT5aMnkVHbIyPbKGxBjHPcdXmOO4vNcx3rLSotHz0TEkXVjruRebDePPoPw "Jelly – Try It Online") Thanks to @Arnauld for a suggestion that saved 41 bytes! Full program. Takes colour as 24-bit integer as its argument and returns the colour name. Explanation ----------- ### Helper link Colour names. Stored using compressed string, but with common words replaced by single ASCII characters in range 33 to 64 ``` “¥...» | Compressed string "blue brown coral..." Ḳ | Split at spaces 33r64¤, | Pair the numbers 33 to 64 with these words [[33,34,35,...],["blue","brown","coral",...]] Ọ | Convert the numbers to Unicode characters [["!",'"',"#",...],["blue","brown","coral",...]] y“µ...» | Translate the compressed string "black navy %! ..." using the mapping generated above Ḳ | Split at spaces ``` ### Main link Stage 1: Start generating list of colour numbers. The increments between colour numbers are stored as between 1 and 3 base 249 digits. The increment has been multiplied by 3, converted to base 249 and then the number of digits minus 1 has been added to the least significant digit, before reversing the order of digits. ``` “⁸...‘© | Copy compressed integers 136,1,33,198,... to register ṛ | Right value (will yield value of the following): ¤®Ð¿ | - While the register is non-empty, do the following, collecting values as we go: ®Ḣ¤ | - Take the first value from the list held in the register, popping it from the list, x %¡3 | - Repeat the following (x mod 3 times) ⁺;$ | - Concatenate the first value from the list held in the register, popping it from the list Ḋ | Remove the first item (will be 'None') ``` Stage 2: Finish generating colour numbers and look up the input ``` ḅ249 | Convert from base 249 to integer :3 | Integer divide by 3 Ä | Cumulative sum: 128,139,205,255,25600,... Ż | Prepend zero , | Pair with input b⁹ | Convert to base 256: [[0],[128],[139],[205],[255],[100,0],...], [input in base 256] U | Reverse order of innermost lists (so RGB becomes BGR, GB becomes BG and B remains as B); this is because colours with no red component will be a list with only two members, and colours with only blue will just have one member ʋ@€/ | Reduce using the following as a dyad for each; effectively calls the following once for each colour with the reversed base-256 colour as left argument and the reversed base-256 input as right ạ | - Absolute difference of the colour and the output of stage 1 N | Negate , | - Pair with the colour § | - Sum each of these M | Indices of maximum Ṫ | Tail (will be the index of the largest colour value) ị¢ | Index into helper link ``` Colours are reversed before comparing because colours with no red component (for example) will end up as a 2 component list. TIO link generates 10 random colours and shows the output so will be different each time.
[05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 1175 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ============================================================================================================================== ``` .•ŒRǝJÖ¤|DÕGø∊ŸγÜuÕפJÓΩaĀhºΔè₆ìkh¥ù§¸β?|"qтy¥Œ›ιM?z*Ω3¿ƒLò·¡ËÌóñD#Ë‰в††α½ÅÎëLpÄäÍEáyø‡§*ßtÓñ7тÜöãô±‘§—ÄGfΔ½~10'–ßaÔ´?ç"&$&¾¬ÍTʒ}M‰8βÔŽÙûQ[мvαн'YW:ΘÌiнœ+ĀβWŬŽø%ð°¤]γθγçkÌã©Ð:8• #`“ƒÏª©–°0‡—–í0‡—‡—–°0ˆ¨ˆ¨¤Æl–°ÿ•³0¤Ð0‡—–°ÿ–í0Ž¹0ˆ¨ë¿Ž¹0ˆ¨Ü„Àš0‡—·¡r0‡—‡Ž0í™0ˆ¨ï×0ˆ¨í™0ˆ¨–°s0Ž¦0°¯ë¿0ˆ¨–í0í™0ˆ¨ ÿïˆ0‡—–Í0‡—–°s0Ž¦0‡—–íÿ ÿ–°0Ê£0ˆ¨ ÿ0‡—ÃÅ0žç0‡—Ôî0´Ò–í0Ü„0›Ðæá0°¯ s0Ž¦0‡—Ê£ÿ s0Ž¦0°¯¦º0Ž¦0°¯–ís0Ž¦0‡—į0ˆ¨œëre0€ÅÜ„0›Ð ÿ´ÒÊ£°¯¤Ð0‡—‡Ž0¤Ð0‡—‡—ÿ–°0†¾–°m0î±a»Ïÿ0ŽÌ–°0í™0ˆ¨‡Ž0ˆ¨–í0´Ò–°ÿæ§0ˆ¨–°ÿŠÛ0ˆ¨ ÿŽÌ–°0°¯‡Ž0‡—ˆ¨0ŠÛæ§ÿ‡Ž0–Í0‡—¼ì0‡—ŠÄ0Ñ´–°0ž®0»³–íÿ ÿ0ŽÌ–°ÿ‹ß–íÿ0†¾•‹0†¾¾ç¨ËÇ⇎0°¯€Œÿ ÿž®0»³æ§ÿ0†¾ ÿÆŠÿ ÿ ÿ0–œ‡Žÿ ÿ–°0ÇÝ ÿæ§0ž®0»³‡Ž0Í€ ÿ¿í0‡—Æàÿ ÿǨ0ŽÌÍÍ ÿ„¸0³«¼Õ0¥â·ä0„¸ÇÝ°Š0„¸ƒ£n‡Ž0ž®0»³0ŠÛ„Ï0ÕÚ†¾ m0î±a•³0™Å›È0†¾æž…ß0™ÅÍ€–°0›È‡Ž0ÇݛȇŽ0™Å™Åˆ° p0‚Ìÿ ÿ0„¸ ÿ ÿ ÿ0šÓ ÿ ÿ ÿí™0¬•ÃÅ0»»ËÃÿÄ‚0„¸œÒŠÛ‡Ž0ŠÛ؉„¸“„0 K#•zÑĪåð≠K¯&u+UhĆõ;Éðf.ã₂=нH,ª@O¶ü˜ˆ₂Ɔ¥2Œ’Ktθu1Sнdw΀(#ç¹ü‹U¹³αh+8R∍±æ”ÇKë₆ßõk₃¿θòĀηú¿ζвî!Vs©₂™CÖ.∍JнαθWÀhzαÐé3¾¯|ë¡×°'βâá—P‘Å_uë_§₃P∊%ý/=i]¥5óO₃^E‘[∞₆ć:βU=J€¦†˜X'Žāìd4Ā’δ‹a°∊›ÊÐƶoÂö mвæÁƵ¨¼Yü“à §‚₂¾¤н7Þ9úÂuœ¿®jF™SΛ¬ìr½ƒxßU‘Lβ7≠°oι—ĀÅýÆgBÐγö™α₆©vÝeEXεò₁Uт3ÈĀ(wº4{ºö쾫 åUøò${J#₃O<!øN”;GÑéÈfm ½™×γäJǝõ¥àÐι)λÓ:α–ù?6¦¨·ã™ζÙ4ÍHd›-Iž|ï¦{Ö9ÊàÛ§¥–Σÿ%ć8ùćYáþǝC±;••O褕в.¥εI‚₄S₁β+₁∦`αO}Wkè ``` That took quite a while.. 139 colors to create a string of.. >.> Takes input as a 24-bit integers to save 1 byte. [Try it online](https://tio.run/##VVZrU1NXFP3ur4iiYqWl14oFsQ4d0WpBi9VSdByrOGqx1GpVtCp2rpcQ8BHFBN@8EpIAJkIeEJPATWb2ysWZMnMm/oX7R@g@9@blTBLOY5@119p7n324cr373KUL64c61@tN1W94jn0cb8MLCvTvx/ODSJnDD42USGCsD8/xkgJt8Iq57rzaQxkxillTcyHS20NBpGmGUiLe0r/p70/abQoaHlPNiPSRljvbxdxOyq16DiNOH8iHR3iMBGL7a/DIVKOFuKlO8UfESMcgniB8@CqcCMB9AL7bTED10cx2TN6AF7HGTxrGkMQ0Filmqq9oxlRH4Tx4UYyS/u8OpdZUvZjsxigttmBm09b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F3hJfaWvw1rM7bgKJhhpusHN8hWYEhVW8qYL72EWOw9ffqxt94PZ7Dy/rOChcZ/z@B/iQxh16X2aoFonM0Fn4sPFp3E6Rw0YbmW7LxsnPf7PRMgpoK2eMUA2cZi1atJS/@Z8BkYdftUjb/Y5uzG0f2q6qttntTRanU6pyOixVktPpaLQ0SvbmygpeFB@LZHwsFTVSY7nNUldub66otNTUVVTaqy32SqezttJS52isqKuxVFTbmmuqLY5mW1NTnaXRYatqqvkf). (Both are slightly modified to take Hexadecimal strings as input instead, since it's easier to test.) **Explanation:** First we generate all the color-strings: ```python .•ŒRǝJÖ¤|DÕGø∊ŸγÜuÕפJÓΩaĀhºΔè₆ìkh¥ù§¸β?|"qтy¥Œ›ιM?z*Ω3¿ƒLò·¡ËÌóñD#Ë‰в††α½ÅÎëLpÄäÍEáyø‡§*ßtÓñ7тÜöãô±‘§—ÄGfΔ½~10'–ßaÔ´?ç"&$&¾¬ÍTʒ}M‰8βÔŽÙûQ[мvαн'YW:ΘÌiнœ+ĀβWŬŽø%ð°¤]γθγçkÌã©Ð:8• '# Push compressed string "chiffon lavenderblush papayawhip blanchedalmond misty bisque moccasin navajo puff beige azure dew khaki violet lavender cyan burly plum boro crimson violet orchid tle violet khaki rosy orchid turquoise sienna orchid violet dle violet maroon drab cadet indigo turquoise turquoise cyan turquoise steelblue" # # Split this string on spaces ` # Push each string separately to the stack “ƒÏª©–°0‡—–í0‡—‡—–°0ˆ¨ˆ¨¤Æl–°ÿ•³0¤Ð0‡—–°ÿ–í0Ž¹0ˆ¨ë¿Ž¹0ˆ¨Ü„Àš0‡—·¡r0‡—‡Ž0í™0ˆ¨ï×0ˆ¨í™0ˆ¨–°s0Ž¦0°¯ë¿0ˆ¨–í0í™0ˆ¨ ÿïˆ0‡—–Í0‡—–°s0Ž¦0‡—–íÿ ÿ–°0Ê£0ˆ¨ ÿ0‡—ÃÅ0žç0‡—Ôî0´Ò–í0Ü„0›Ðæá0°¯ s0Ž¦0‡—Ê£ÿ s0Ž¦0°¯¦º0Ž¦0°¯–ís0Ž¦0‡—į0ˆ¨œëre0€ÅÜ„0›Ð ÿ´ÒÊ£°¯¤Ð0‡—‡Ž0¤Ð0‡—‡—ÿ–°0†¾–°m0î±a»Ïÿ0ŽÌ–°0í™0ˆ¨‡Ž0ˆ¨–í0´Ò–°ÿæ§0ˆ¨–°ÿŠÛ0ˆ¨ ÿŽÌ–°0°¯‡Ž0‡—ˆ¨0ŠÛæ§ÿ‡Ž0–Í0‡—¼ì0‡—ŠÄ0Ñ´–°0ž®0»³–íÿ ÿ0ŽÌ–°ÿ‹ß–íÿ0†¾•‹0†¾¾ç¨ËÇ⇎0°¯€Œÿ ÿž®0»³æ§ÿ0†¾ ÿÆŠÿ ÿ ÿ0–œ‡Žÿ ÿ–°0ÇÝ ÿæ§0ž®0»³‡Ž0Í€ ÿ¿í0‡—Æàÿ ÿǨ0ŽÌÍÍ ÿ„¸0³«¼Õ0¥â·ä0„¸ÇÝ°Š0„¸ƒ£n‡Ž0ž®0»³0ŠÛ„Ï0ÕÚ†¾ m0î±a•³0™Å›È0†¾æž…ß0™ÅÍ€–°0›È‡Ž0ÇݛȇŽ0™Å™Åˆ° p0‚Ìÿ ÿ0„¸ ÿ ÿ ÿ0šÓ ÿ ÿ ÿí™0¬•ÃÅ0»»ËÃÿÄ‚0„¸œÒŠÛ‡Ž0ŠÛ؉„¸“ # Push dictionary string "black navy dark0 blue medium0 blue blue dark0 green green teal darkÿ deep0 sky0 blue darkÿ medium0 spring0 green lime spring0 green aqua midnight0 blue dodger0 blue light0 sea0 green forest0 green sea0 green darks0 late0 grey lime0 green medium0 sea0 green ÿ royal0 blue steel0 blue darks0 late0 blue mediumÿ ÿ dark0 olive0 green ÿ0 blue corn0 flower0 blue rebecca0 purple medium0 aqua0 marine dim0 grey s0 late0 blue oliveÿ s0 late0 grey lights0 late0 grey mediums0 late0 blue lawn0 green chartre0 use aqua0 marine ÿ purple olive grey sky0 blue light0 sky0 blue blueÿ dark0 red darkm0 agenta sadÿ0 brown dark0 sea0 green light0 green medium0 purple darkÿ pale0 green darkÿ yellow0 green ÿ brown dark0 grey light0 blue green0 yellow paleÿ light0 steel0 blue powder0 blue fire0 brick dark0 golden0 rod mediumÿ ÿ0 brown darkÿ silver mediumÿ0 red indian0 red peru chocolate tan light0 grey thisÿ ÿ golden0 rod paleÿ0 red ÿ gainsÿ ÿ ÿ0 wood lightÿ ÿ dark0 salmon ÿ pale0 golden0 rod light0 coral ÿ alice0 blue honeyÿ ÿ sandy0 brown wheat ÿ white0 smoke mint0 cream ghost0 white salmon antique0 white linen light0 golden0 rod0 yellow old0 lace red m0 agenta deep0 pink orange0 red tomato hot0 pink coral dark0 orange light0 salmon orange light0 pink pink gold p0 eachÿ ÿ0 white ÿ ÿ ÿ0 rose ÿ ÿ ÿ sea0 shell corn0 silk lemonÿ floral0 white snow yellow light0 yellow ivory white" # Where all `ÿ` are automatically filled with the strings on the stack „0 K # Remove all "0 " from this string # # Split the colors on spaces ``` Then we generate a list of forward differences (deltas) between each integer value of the colors: ```python •zÑĪåð≠K¯&u+UhĆõ;Éðf.ã₂=нH,ª@O¶ü˜ˆ₂Ɔ¥2Œ’Ktθu1Sнdw΀(#ç¹ü‹U¹³αh+8R∍±æ”ÇKë₆ßõk₃¿θòĀηú¿ζвî!Vs©₂™CÖ.∍JнαθWÀhzαÐé3¾¯|ë¡×°'βâá—P‘Å_uë_§₃P∊%ý/=i]¥5óO₃^E‘[∞₆ć:βU=J€¦†˜X'Žāìd4Ā’δ‹a°∊›ÊÐƶoÂö mвæÁƵ¨¼Yü“à §‚₂¾¤н7Þ9úÂuœ¿®jF™SΛ¬ìr½ƒxßU‘Lβ7≠°oι—ĀÅýÆgBÐγö™α₆©vÝeEXεò₁Uт3ÈĀ(wº4{ºö쾫 åUøò${J#₃O<!øN”;GÑéÈfm ½™×γäJǝõ¥àÐι)λÓ:α–ù?6¦¨·ã™ζÙ4ÍHd›-Iž|ï¦{Ö9ÊàÛ§¥–Σÿ%ć8ùćYáþǝC±;• # Push compressed integer 199435987809271424589508700952987345999804200072375133628254343692108407476588500135573281889031649216370100759626064238727072489415325130552011943231372407222964404763401980843968947657212497212027480199840300219769136432328209307347145119976644138878553798683794751309798787883572249589074597119540397124774131357786254535108429605287982569524294490533853150008626425797260994727581899181000813165364870780739754491720041566206327597753141661846275821649635815830948299823383964329384068145070200611196756567681968774265025511020508722510627341700584849057763591073777679021648285012447092662591008342199952284925672007531443930335828262810273697784303468071652124201899153101970895280421720006686387730894329535589566680885995478455871002071758051626349351150223272343920758114226776399859623393233070539000599481915926111317851112136858026586181791 •O褕 # Push compressed integer 1579378 в # Convert the larger integer to Base-1579378 as list: [128,11,66,50,25345,7168,128,2827,13428,3794,11209,1126,127,128,1579377,358287,139691,120952,786485,50168,228835,648767,273759,35089,334035,113367,37953,143030,682669,668529,325453,105900,39441,170943,61796,78678,324205,460809,254037,103186,197376,212,44,128,32640,128,478827,15,154856,54302,139,17544,292732,78337,164427,36856,326341,14132,105062,361723,317437,294783,274237,9801,126911,54768,7176,82236,418793,118728,145852,75740,198997,414917,411351,10467,320479,19310,73543,322565,110846,13386,52083,41897,51360,50177,71594,149368,386811,176000,322676,26044,104406,26124,4723,1777,15,238689,80467,5929,25,2565,194821,100211,27493,1295,2540,195348,68122,255,5012,12397,7751,1645,5532,3248,5242,1158,4545,2570,5685,953,1012,1544,15,29,1772,1032,288,1273,750,497,35,10,1030,224,16,15] .¥ # Undelta this list: [0,128,139,205,255,25600,32768,32896,35723,49151,52945,64154,65280,65407,65535,1644912,2003199,2142890,2263842,3050327,3100495,3329330,3978097,4251856,4286945,4620980,4734347,4772300,4915330,5597999,6266528,6591981,6697881,6737322,6908265,6970061,7048739,7372944,7833753,8087790,8190976,8388352,8388564,8388608,8388736,8421376,8421504,8900331,8900346,9055202,9109504,9109643,9127187,9419919,9498256,9662683,9699539,10025880,10040012,10145074,10506797,10824234,11119017,11393254,11403055,11529966,11584734,11591910,11674146,12092939,12211667,12357519,12433259,12632256,13047173,13458524,13468991,13789470,13808780,13882323,14204888,14315734,14329120,14381203,14423100,14474460,14524637,14596231,14745599,15132410,15308410,15631086,15657130,15761536,15787660,15792383,15794160,15794175,16032864,16113331,16119260,16119285,16121850,16316671,16416882,16444375,16445670,16448210,16643558,16711680,16711935,16716947,16729344,16737095,16738740,16744272,16747520,16752762,16753920,16758465,16761035,16766720,16767673,16768685,16770229,16770244,16770273,16772045,16773077,16773365,16774638,16775388,16775885,16775920,16775930,16776960,16777184,16777200,16777215] ``` Then we determine the index of the value closest to the input (in terms of absolute differences between each RGB color - and here I thought I could use builtin `.x`..), determine the index of this closest integer in the list, and use that to index into the color-strings we created earlier: ```python ε # Map each integer to: I‚ # Pair it with the input-integer ₄S # Push 1000, split to digits: [1,0,0,0] ₁β # Converted from base-256 to an integer: 16777216 + # Add that to both integers in the pair ₁в # Convert both integers to base-256 as list (we now have [1,R,G,B]) €¦ # Remove the leading 1 ` # Push both lists to the stack α # Get the absolute difference between the lists (at the same indices) O # Sum these differences }W # After the map: get the minimum (without popping the list itself) k # Get the index of this minimum in the list è # And use it to index into the string-color list # (after which the result is output implicitly) ``` [See this 05AB1E tip of mine (all four sections)](https://codegolf.stackexchange.com/a/166851/52210) to understand why: * `.•ŒRǝ...Ð:8•` is `"chiffon lavenderblush papayawhip ... cyan turquoise steelblue"` * `“ƒÏª©–°0‡—...‡Ž0ŠÛ؉„¸“` is `"black navy dark0 blue ... light0 yellow ivory white"` * `•zÑÄ...C±;•` is `199...791` * `•O褕` is `1579378` * `•zÑÄ...C±;••O褕в` is `[128,11,66,...,224,16,15]`
44,409
Bonjour, Normalement, on ne met pas d'article devant un nom de métier. > > Je suis professeur. Je suis boulanger. > > > Mais imaginons le dialogue suivant : > > A : Es-tu boulanger ? > > > B : Non, je suis (**un**) maçon. > > > Dans ce cas, faut-il mettre l'article indéfini devant *maçon*, ceci parce que la phrase de B sous-entend *Non, je ne suis pas (**un**) boulanger, je suis (**un**) maçon* ?
2021/01/28
[ "https://french.stackexchange.com/questions/44409", "https://french.stackexchange.com", "https://french.stackexchange.com/users/26093/" ]
Je ne vois pas de nécessité d'ajouter un article indéfini, ni dans un cas, ni dans l'autre : > > A : Es-tu boulanger ? > > B : Non, je suis maçon. > > A : Mais on m'a bien dit que tu étais un boulanger… > > B : Oui, c'est mon nom de famille, je suis bien un Boulanger. Et toi ? > > A : Oh, pardon ! C'est amusant, car moi qui suis boulanger, je suis un Masson. > > > Évidemment, à l'écrit, tout de suite, ça saute aux yeux. À l'oral, par contre, la différence vient de l'article ; mais ça reste une source de quiproquos pour les inattentifs :-). Une petite remarque : je n'ai jamais rencontré la graphie Maçon en nom de famille, et fr.Wikipédia n'en cite aucun. NB: la forme « **je suis un·e** /*nomDeFamille*/ » n'est typiquement utilisé que dans un contexte de zones géographiques où ces noms de famille sont courants, ce qui n'est pas rare dans les villages en régions rurales. Sinon, on utilisera plutôt le classique « **je m'appelle** ». En fait, on retrouve la même nuance qu'entre « *je suis française* » et « *je suis **une** française* », ou leur variante masculine : la première forme est un qualificatif, alors que la seconde réfère incidemment à un groupe spécifique, et éventuellement insiste sur l'appartenance à ce groupe. Du coup, on peut très bien imaginer une situation où l'article indéfini prend sens devant un nom de métier. Par exemple :   « *Je suis boulanger. Mais ne vous méprenez pas, je ne suis pas juste un pétrisseur et un cuiseur. Nous, les boulangers, avons bien plus en tête qu'une simple recette d'assemblage et de manipulation qu'on reproduirait chaque jour, chaque nuit. Selon le météo, selon la saison, et selon les envies du moment de la clientèle, nous savons composer. C'est pour ça que n'importe quelle échoppe qui vend /du pain/, ne peut pas marquer « boulangerie » sur sa vitrine ; boulanger est un titre, et un métier, reconnu : oui, je suis bien un boulanger.* »
Il est habituel de ne pas utiliser d'article dans ce contexte, mais l'utiliser ne résulte pas en une faute; si ce n'est pas usuel, il n'y a quand même pas de principe contradictoire qui empêche d'utiliser l'article. En fait de nombreux cas d'utilisation de l'article se trouvent dans la littérature. Les noms associés à cet usage, noms de métier ou noms assimilés à des noms de métiers, sont les suivants : soldat, balayeur, écrivain, guide, cowboy, flic, ingénieur, archéologue, ouvrier, artisan, coureur de vitesse, acteur tragique, berger, directeur commercial, homme de lettres, travailleur, metteur en scène d'action, homme politique, poète, écrivain public, médecin. On ne trouve des exemples que pour la première personne du singulier. ([réf.](https://books.google.fr/books?id=gU-JAQAAQBAJ&pg=PT2&dq=%22non+je+suis+un%22&hl=en&sa=X&ved=2ahUKEwjD0bD5tL7uAhWF3oUKHbWOATYQ6AEwAHoECAYQAg#v=onepage&q=%22non%20je%20suis%20un%22&f=false)) Mais non : je suis un Soldat. Chargé, entraîné, conditionné depuis l'enfance pour la défense de Ter, mon pays. ([réf;](https://books.google.fr/books?id=xSALBgAAQBAJ&pg=PA18&dq=%22non+je+suis+un%22&hl=en&sa=X&ved=2ahUKEwjD0bD5tL7uAhWF3oUKHbWOATYQ6AEwD3oECC8QAg#v=onepage&q=%22non%20je%20suis%20un%22&f=false)) Euh non, je suis un balayeur plutôt. Je suis un balayeur magicien, euh, un magicien balayeur. ([réf.](https://books.google.fr/books?id=_E9d43aoickC&pg=PP44&dq=%22non+je+suis+un%22&hl=en&sa=X&ved=2ahUKEwjD0bD5tL7uAhWF3oUKHbWOATYQ6AEwE3oECDcQAg#v=onepage&q=%22non%20je%20suis%20un%22&f=false)) " Bien sûr que non . Je suis un écrivain . J'arrange les choses , je les embellis . ([réf.](https://books.google.fr/books?id=eQ1hqHzSMnwC&pg=PA464&dq=%22non+je+suis+un%22&hl=en&sa=X&ved=2ahUKEwjD0bD5tL7uAhWF3oUKHbWOATYQ6AEwGHoECD4QAg#v=onepage&q=%22non%20je%20suis%20un%22&f=false)) « Ca alors, je te vois ! Mais tu n'es pas sous forme de corps spirituel ? -Non, je suis un guide ... ([réf.](https://books.google.fr/books?id=X2ZZBAAAQBAJ&pg=PT106&dq=%22non+je+suis+un%22&hl=en&sa=X&ved=2ahUKEwjD0bD5tL7uAhWF3oUKHbWOATYQ6AEwGnoECEEQAg#v=onepage&q=%22non%20je%20suis%20un%22&f=false)) — Vous dealez de la drogue, Ach ? — Non, je suis un cowboy, un genre de shérif, répondit Acheron en démarrant. ([réf.](https://books.google.fr/books?id=EX0cBwAAQBAJ&pg=PT49&dq=%22non+je+suis+un%22&hl=en&sa=X&ved=2ahUKEwjD0bD5tL7uAhWF3oUKHbWOATYQ6AEwG3oECEUQAg#v=onepage&q=%22non%20je%20suis%20un%22&f=false)) Non, je suis un flic. Ou du moins c'est ce que je serais si on me laissait faire mon métier. » ([réf](https://books.google.fr/books?id=eWGJAQAAQBAJ&pg=PT313&dq=%22non+je+suis+un%22&hl=en&sa=X&ved=2ahUKEwjD0bD5tL7uAhWF3oUKHbWOATYQ6AEwV3oECBIQAg#v=onepage&q=%22non%20je%20suis%20un%22&f=false)) Non, je suis un ingénieur, pas un archéologue. Je vous laisse volontiers toute la gloire et la célébrité. ([réf.](https://books.google.fr/books?id=mOFdAgAAQBAJ&pg=PT303&dq=%22non+je+suis+un%22&hl=en&sa=X&ved=2ahUKEwjD0bD5tL7uAhWF3oUKHbWOATYQ6AEwWHoECCcQAg#v=onepage&q=%22non%20je%20suis%20un%22&f=false)) Non, je suis un prêtre diocésain, mais je peux dire la messe en latin. ([réf.](https://books.google.fr/books?id=_9oYCwAAQBAJ&pg=PA53&dq=%22je+suis+un%22&hl=en&sa=X&ved=2ahUKEwiz8sKzu77uAhWR0eAKHfYcDM4Q6AEwAXoECE4QAg#v=onepage&q=%22je%20suis%20un%22&f=false)) Je ne suis pas forcément ce que j'écris. Mais j'écris. Ça, je le suis. Je suis un écrivain. C'est joli, au village ? Oui. ([réf.](https://books.google.fr/books?id=hATvPAAACAAJ&dq=%22je+suis+un%22&hl=en&sa=X&ved=2ahUKEwiz8sKzu77uAhWR0eAKHfYcDM4Q6AEwNnoECGIQAQ)) Je suis un écrivain: guide de l'auteur professionnel ([réf.](https://books.google.fr/books?id=uAlBAQAAIAAJ&q=%22je+suis+un%22&dq=%22je+suis+un%22&hl=en&sa=X&ved=2ahUKEwi8h6CUvr7uAhVRExoKHUjcBrY4yAEQ6AEwAXoECE0QAg)) Je suis mécanicien , je suis un ouvrier , pas plus . - Je le suis aussi , dit Bernier . ([réf.](https://books.google.fr/books?id=JpZNAQAAIAAJ&q=%22je+suis+un%22&dq=%22je+suis+un%22&hl=en&sa=X&ved=2ahUKEwi8h6CUvr7uAhVRExoKHUjcBrY4yAEQ6AEwMnoECFwQAg)) j'aide Simenon à lutter contre ses doutes, ses remords, à repousser tous les spectres qui encombrent sa vie. « Je suis un artisan » ([réf.](https://books.google.fr/books?id=FLqxk81W7fgC&pg=PT12&dq=%22je+suis+devenu+un%22&hl=en&sa=X&ved=2ahUKEwjDjYLswr7uAhVmyoUKHcnVC0wQ6AEwHHoECEUQAg#v=onepage&q=%22je%20suis%20devenu%20un%22&f=false)) Comment je suis devenu un flic. ([réf.](https://books.google.fr/books?id=4c26KO_-acQC&pg=PA20&dq=%22je+suis+devenu+un%22&hl=en&sa=X&ved=2ahUKEwjDjYLswr7uAhVmyoUKHcnVC0wQ6AEwJHoECFAQAg#v=onepage&q=%22je%20suis%20devenu%20un%22&f=false)) Peu à peu, sur le plan sportif, j'ai émergé du lot et je suis devenu un coureur de vitesse. C'était un refuge, qui me permettait d'être accepté par les autres. J'allais faire des championnats qui me rapportaient, avec la victoire, des titres et ([réf.](https://books.google.fr/books?id=QUdFoIlIPzwC&pg=PT87&dq=%22je+suis+devenu+un%22&hl=en&sa=X&ved=2ahUKEwjDjYLswr7uAhVmyoUKHcnVC0wQ6AEwJXoECFIQAg#v=onepage&q=%22je%20suis%20devenu%20un%22&f=false)) Moi, je ne voulais pas faire du « boulevard », entout cas pas que, alors je suis devenu un acteur tragique. ([réf.](https://books.google.fr/books?id=LcIFAAAAQAAJ&pg=PA7&dq=%22je+suis+devenu+un%22&hl=en&sa=X&ved=2ahUKEwjDjYLswr7uAhVmyoUKHcnVC0wQ6AEwNHoECFMQAg#v=onepage&q=%22je%20suis%20devenu%20un%22&f=false)) je suis devenu un Berger ([réf.](https://books.google.fr/books?id=8DMZxAvUJaEC&pg=PT96&dq=%22je+suis+devenu+un%22&hl=en&sa=X&ved=2ahUKEwjDjYLswr7uAhVmyoUKHcnVC0wQ6AEwOHoECEYQAg#v=onepage&q=%22je%20suis%20devenu%20un%22&f=false)) Et comble du comble, je suis devenu un commercial. Un directeur commercial. ([réf.](https://books.google.fr/books?id=gJvTaK99nwkC&pg=PT9&dq=%22je+suis+devenu+un%22&hl=en&sa=X&ved=2ahUKEwjo5fmrxr7uAhVpxoUKHZTZDIg4ZBDoATApegQISBAC#v=onepage&q=%22je%20suis%20devenu%20un%22&f=false)) à l'aune de ce que je suis devenu: un écrivain,un type qui revient sur ses pas, ([réf.](https://books.google.fr/books?id=Bcb_rwEytEIC&pg=PT113&dq=%22je+suis+devenu+un%22&hl=en&sa=X&ved=2ahUKEwjo5fmrxr7uAhVpxoUKHZTZDIg4ZBDoATAtegQITxAC#v=onepage&q=%22je%20suis%20devenu%20un%22&f=false)) Je suis devenu un homme de lettres. » Léon ne manie pas la langue de Bloy. L'exaspération de son style, ([réf.](https://books.google.fr/books?id=GU3jAAAAMAAJ&q=%22je+suis+devenu+un%22&dq=%22je+suis+devenu+un%22&hl=en&sa=X&ved=2ahUKEwiW3vuByb7uAhUNxIUKHdPYBIw4rAIQ6AEwAXoECEwQAg)) je suis devenu un homme quand je suis devenu un travailleur , ([réf.](https://books.google.fr/books?id=IXxZAAAAMAAJ&q=%22je+suis+devenu+un%22&dq=%22je+suis+devenu+un%22&hl=en&sa=X&ved=2ahUKEwiW3vuByb7uAhUNxIUKHdPYBIw4rAIQ6AEwAnoECF0QAg)) Je suis devenu un metteur en scène d'action par accident ; c'est une absurdité . Je ne connais pas d'escrocs . . . je veux dire que je ne les connais pas en tant qu ' escrocs ([réf.](https://books.google.fr/books?id=EfvxAAAAMAAJ&q=%22je+suis+devenu+un%22&dq=%22je+suis+devenu+un%22&hl=en&sa=X&ved=2ahUKEwiW3vuByb7uAhUNxIUKHdPYBIw4rAIQ6AEwCnoECCIQAQ)) Bref de dire comment, mol qui n'ai même pas le certificat d'études primaires, je suis devenu un écrivain. ([réf.](https://books.google.fr/books?id=n5oQAAAAYAAJ&q=%22je+suis+devenu+un%22&dq=%22je+suis+devenu+un%22&hl=en&sa=X&ved=2ahUKEwiW3vuByb7uAhUNxIUKHdPYBIw4rAIQ6AEwD3oECC8QAg)) Je ne prends pas cela très au sérieux . time car après tout , si je suis devenu un homme politique : C'est une manière de parler ([réf.](https://books.google.fr/books?id=7vsaAAAAYAAJ&pg=PP339&dq=%22il+est+devenu+un%22&hl=en&sa=X&ved=2ahUKEwjui6m9zb7uAhVP9IUKHSKQAG0Q6AEwG3oECFIQAg#v=onepage&q=%22il%20est%20devenu%20un%22&f=false)) car il serait devenu un bon peintre avec la nature pour modèle , comme il est devenu un poète en faisant de la ([réf.](https://books.google.fr/books?id=7sVfVHBd7tYC&pg=PA34&dq=%22il+est+devenu+un%22&hl=en&sa=X&ved=2ahUKEwi-vJn6zr7uAhXB3oUKHaQoAuQ4ZBDoATAVegQIKRAC#v=onepage&q=%22il%20est%20devenu%20un%22&f=false)) 'estrade: elle incarne cette figure que l'écrivain rencontre partout où il va lorsqu'il est devenu... un écrivain public. ([réf.](https://books.google.fr/books?id=M1piAAAAMAAJ&q=%22il+est+devenu+un%22&dq=%22il+est+devenu+un%22&hl=en&sa=X&ved=2ahUKEwihg8Cf0L7uAhUInhQKHcS0BtE4yAEQ6AEwRHoECCkQAg)) Ainsi , à la limite , Paul n ' est plus médecin , mais - sans contradiction - il est resté un médecin ; ou encore , Paul était déjà médecin , mais c ' est maintenant qu ' il est devenu un médecin .
14,489,876
I have a table `HRTC` in SQL Server. I want to import data which is in Excel into this table. But my Excel file does not have all the columns which match the `HRTC` table. Is there anyway I can do this? I am thinking something like in the import wizard ``` Insert into SQLServerTable Select * FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0', 'Excel 8.0;Database=D:\testing.xls;HDR=YES', 'SELECT * FROM [SheetName$]') select column1, column2 from HRTC ```
2013/01/23
[ "https://Stackoverflow.com/questions/14489876", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1723572/" ]
Try this Create a temp table ``` Select * INTO TmpTable FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0', 'Excel 8.0;Database=D:\testing.xls;HDR=YES', 'SELECT * FROM [SheetName$]') ``` Then to insert row into hrtc using temptable, any missing columns will have null ``` INSERT INTO hrtc(column1, column2) select col1, col2 from TmpTable ```
One simple approach is to script your excel file into a collection of insert statement, then run it on SQL Server. Also if you can export your excel file into CSV file, this is often useful. Tool like SQL Server Management Studio should have some kind of import wizard where you can load the CSV, choose column mapping etc.
14,489,876
I have a table `HRTC` in SQL Server. I want to import data which is in Excel into this table. But my Excel file does not have all the columns which match the `HRTC` table. Is there anyway I can do this? I am thinking something like in the import wizard ``` Insert into SQLServerTable Select * FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0', 'Excel 8.0;Database=D:\testing.xls;HDR=YES', 'SELECT * FROM [SheetName$]') select column1, column2 from HRTC ```
2013/01/23
[ "https://Stackoverflow.com/questions/14489876", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1723572/" ]
Try this Create a temp table ``` Select * INTO TmpTable FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0', 'Excel 8.0;Database=D:\testing.xls;HDR=YES', 'SELECT * FROM [SheetName$]') ``` Then to insert row into hrtc using temptable, any missing columns will have null ``` INSERT INTO hrtc(column1, column2) select col1, col2 from TmpTable ```
What I often end up doing in these situations is to do some code completion using excel's CONCATENATE function. Let's say you have: ``` A B 1 foo bar 2 test2 bar2 3 test3 bar 3 ``` If you needed to insert those into a table. In column C you can write: ``` =CONCATENATE("INSERT INTO HRTC(col, col2) VALUES('", A1, "','", B1, "')") ```
14,489,876
I have a table `HRTC` in SQL Server. I want to import data which is in Excel into this table. But my Excel file does not have all the columns which match the `HRTC` table. Is there anyway I can do this? I am thinking something like in the import wizard ``` Insert into SQLServerTable Select * FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0', 'Excel 8.0;Database=D:\testing.xls;HDR=YES', 'SELECT * FROM [SheetName$]') select column1, column2 from HRTC ```
2013/01/23
[ "https://Stackoverflow.com/questions/14489876", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1723572/" ]
One simple approach is to script your excel file into a collection of insert statement, then run it on SQL Server. Also if you can export your excel file into CSV file, this is often useful. Tool like SQL Server Management Studio should have some kind of import wizard where you can load the CSV, choose column mapping etc.
What I often end up doing in these situations is to do some code completion using excel's CONCATENATE function. Let's say you have: ``` A B 1 foo bar 2 test2 bar2 3 test3 bar 3 ``` If you needed to insert those into a table. In column C you can write: ``` =CONCATENATE("INSERT INTO HRTC(col, col2) VALUES('", A1, "','", B1, "')") ```
19,034,871
Hi I was wondering whether someone would be able to help me with a query. I am trying to select from an EAV type table where the value is not multiple values. Using the example below I am trying to retrieve rows where tag\_id != 1 and tag\_id != 2. So based on the data I want to return just the row containing contact\_id 3 ``` Tags Table: contact_id tag_id 1 1 1 2 2 1 2 4 3 4 ``` The desire result is to return a single row: ``` contact_id -> 3 ``` I have tried the following queries which don't return what I am looking for so are obviously are not correct: ``` select `contact_id` from `contact_tags` where tag_id !=1 and tag_id != 2 select `contact_id` from `contact_tags` where tag_id NOT IN(1,2) ``` Any help on this. Or just a pointer in the right direction would be great.
2013/09/26
[ "https://Stackoverflow.com/questions/19034871", "https://Stackoverflow.com", "https://Stackoverflow.com/users/460824/" ]
You can use `NOT EXISTS()` in which the statement inside selects all records where it has tags of `1` or `2`. ``` SELECT contact_id FROM contact_tags a WHERE NOT EXISTS ( SELECT 1 FROM contact_tags b WHERE tag_id IN (1, 2) AND a.contact_id = b.contact_id ) GROUP BY contact_id ``` * [SQLFiddle Demo](http://sqlfiddle.com/#!2/b2b11/5) Another alternative is to use `LEFT JOIN` ``` SELECT a.contact_id FROM contact_tags a LEFT JOIN contact_tags b ON a.contact_id = b.contact_id AND b.tag_id IN (1, 2) WHERE b.contact_id IS NULL ``` * [SQLFiddle Demo](http://sqlfiddle.com/#!2/b2b11/13)
Stealing from @491243 fiddle here is a modification which returns contacts\_id which lack both tags\_id <http://sqlfiddle.com/#!2/b2b11/19>
19,034,871
Hi I was wondering whether someone would be able to help me with a query. I am trying to select from an EAV type table where the value is not multiple values. Using the example below I am trying to retrieve rows where tag\_id != 1 and tag\_id != 2. So based on the data I want to return just the row containing contact\_id 3 ``` Tags Table: contact_id tag_id 1 1 1 2 2 1 2 4 3 4 ``` The desire result is to return a single row: ``` contact_id -> 3 ``` I have tried the following queries which don't return what I am looking for so are obviously are not correct: ``` select `contact_id` from `contact_tags` where tag_id !=1 and tag_id != 2 select `contact_id` from `contact_tags` where tag_id NOT IN(1,2) ``` Any help on this. Or just a pointer in the right direction would be great.
2013/09/26
[ "https://Stackoverflow.com/questions/19034871", "https://Stackoverflow.com", "https://Stackoverflow.com/users/460824/" ]
may be this is what you want ``` select contact_id from contact_tags where contact_id not in ( select contact_id from contact_tags where tag_id in (1,2) ) tmp ```
Stealing from @491243 fiddle here is a modification which returns contacts\_id which lack both tags\_id <http://sqlfiddle.com/#!2/b2b11/19>
9,941,898
I'm new in Ruby/Rails, so, my question: what is the perfect way to upload file and save filename in database with rails? Are there any Gem? Or maybe there are good build-in feature?
2012/03/30
[ "https://Stackoverflow.com/questions/9941898", "https://Stackoverflow.com", "https://Stackoverflow.com/users/630189/" ]
Also try [carrierwave](https://github.com/jnicklas/carrierwave), Ryan has a good screencast about this [gem](http://railscasts.com/episodes/253-carrierwave-file-uploads)
Most people use the [Paperclip Gem](https://github.com/thoughtbot/paperclip).
9,941,898
I'm new in Ruby/Rails, so, my question: what is the perfect way to upload file and save filename in database with rails? Are there any Gem? Or maybe there are good build-in feature?
2012/03/30
[ "https://Stackoverflow.com/questions/9941898", "https://Stackoverflow.com", "https://Stackoverflow.com/users/630189/" ]
You can try Paperclip.It is most popular gem in rails community... ``` https://github.com/thoughtbot/paperclip ``` these lines do the all stuff ``` class User < ActiveRecord::Base has_attached_file :avatar, :styles => { :medium => "300x300>", :thumb => "100x100>" } end ``` Try it......
Most people use the [Paperclip Gem](https://github.com/thoughtbot/paperclip).
9,941,898
I'm new in Ruby/Rails, so, my question: what is the perfect way to upload file and save filename in database with rails? Are there any Gem? Or maybe there are good build-in feature?
2012/03/30
[ "https://Stackoverflow.com/questions/9941898", "https://Stackoverflow.com", "https://Stackoverflow.com/users/630189/" ]
Just take a look on the links to choose between paperClip & carrierwave : [Rails 3 paperclip vs carrierwave vs dragonfly vs attachment\_fu](https://stackoverflow.com/questions/7419731/rails-3-paperclip-vs-carrierwave-vs-dragonfly-vs-attachment-fu) And <http://bcjordan.github.com/posts/rails-image-uploading-framework-comparison/>
Most people use the [Paperclip Gem](https://github.com/thoughtbot/paperclip).
9,941,898
I'm new in Ruby/Rails, so, my question: what is the perfect way to upload file and save filename in database with rails? Are there any Gem? Or maybe there are good build-in feature?
2012/03/30
[ "https://Stackoverflow.com/questions/9941898", "https://Stackoverflow.com", "https://Stackoverflow.com/users/630189/" ]
Also try [carrierwave](https://github.com/jnicklas/carrierwave), Ryan has a good screencast about this [gem](http://railscasts.com/episodes/253-carrierwave-file-uploads)
Just take a look on the links to choose between paperClip & carrierwave : [Rails 3 paperclip vs carrierwave vs dragonfly vs attachment\_fu](https://stackoverflow.com/questions/7419731/rails-3-paperclip-vs-carrierwave-vs-dragonfly-vs-attachment-fu) And <http://bcjordan.github.com/posts/rails-image-uploading-framework-comparison/>
9,941,898
I'm new in Ruby/Rails, so, my question: what is the perfect way to upload file and save filename in database with rails? Are there any Gem? Or maybe there are good build-in feature?
2012/03/30
[ "https://Stackoverflow.com/questions/9941898", "https://Stackoverflow.com", "https://Stackoverflow.com/users/630189/" ]
You can try Paperclip.It is most popular gem in rails community... ``` https://github.com/thoughtbot/paperclip ``` these lines do the all stuff ``` class User < ActiveRecord::Base has_attached_file :avatar, :styles => { :medium => "300x300>", :thumb => "100x100>" } end ``` Try it......
Just take a look on the links to choose between paperClip & carrierwave : [Rails 3 paperclip vs carrierwave vs dragonfly vs attachment\_fu](https://stackoverflow.com/questions/7419731/rails-3-paperclip-vs-carrierwave-vs-dragonfly-vs-attachment-fu) And <http://bcjordan.github.com/posts/rails-image-uploading-framework-comparison/>
48,411,072
The following query matches userID's to eachother based off of total score difference. I have two tables, survey & users. I need to join this to the users table that I have that has usernames/photo links. The columns I need displayed are users.name & users.photo. All tables currently have a unique userID, which is users.id, and survey.id that helps match users across DB's. Could anyone give me a hand as how I could get this done? I've been having a lot of trouble figuring this out, thanks in advance. ``` select a.id yourId, b.id matchId, abs(a.q1 - b.q1) + abs(a.q2 - b.q2) + abs(a.q3 - b.q3)+ abs(a.q4 - b.q4)+ abs(a.q5 - b.q5)+ abs(a.q6 - b.q6)+ abs(a.q7 - b.q7)+ abs(a.q8 - b.q8)+ abs(a.q9 - b.q9)+ abs(a.q10 - b.q10) scorediff from surveys as a inner join surveys as b on a.id != b.id WHERE a.id=1 order by scorediff asc ``` Currently this is the results of that query: ``` | yourID| matchID| scoreDiff| ---------------------------- | 5 | 2 | 14 | | 5 | 3 | 25 | | 5 | 1 | 33 | | 5 | 6 | 34 | ``` I would like this as the result: ``` | yourID| matchID| scoreDiff| name | photo | ---------------------------------------------- | 5 | 2 | 14 | john | url | 5 | 3 | 25 | steve| url | 5 | 1 | 33 | jane | url | 5 | 6 | 34 | kelly| url ``` matchID can be matched to the users.ID column, as they are all unique to the user.
2018/01/23
[ "https://Stackoverflow.com/questions/48411072", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8534513/" ]
I would just add a filter to exclude undefined events on the initial subscription: ``` ngOnInit() { this.dataService.getEvents() .filter(events => events && events.length > 0) .subscribe( (events) => { this.events = events; console.log(events); // when I try to get this is no problem it prints log to console (probably because event is var so it is not defined) console.log(events[0].name); // it didn't see that property so I'm getting ERROR TypeError: Cannot read property 'name' of undefined }); } ```
Instead of using a BehaviorSubject you can try using a Subject, the Subject won't have the empty array in the first place which triggers the initial subscription call. If you need to use a BehaviorSubject, you can instead do a check for null and has length before working with it, so ``` .subscribe(events => { if(events && events instanceof Array && events.length > 0){ this.events = events; this.eventChanged.next(events); } }); ```
44,215,132
I have a Oracle query ``` SELECT to_timestamp('29-03-17 03:58:34.312000000 PM','DD-MM-RR HH12:MI:SS.FF AM') FROM DUAL ``` I want to convert to SQL Server where I need to retain the Oracle date string i.e `'29-03-17 03:58:34.312000000 PM'`: ``` SELECT CONVERT(DATETIME, REPLACE(REPLACE('29-03-2017 03:58:34.312000000 PM','-', '/'),'000000 ', ''), 131) ``` I tried the above query, as 131 format closely matches '29-03-17 03:58:34.312000000 PM' format 'dd/mm/yyyy hh:mi:ss:mmmAM' but only difference is with the year. In Oracle year is 17 and SQL Server the year is 2017. I need to prefix 20 to the year to make it 2017. This query converts into Hijri datetime. I need it in Gregorian datetime format. This is the documentation. <https://learn.microsoft.com/en-us/sql/t-sql/functions/cast-and-convert-transact-sql> I need to convert the date which is in string in Oracle format to SQL Server equivalent. Is there any way where the format like 'dd/mm/yyyy hh:mi:ss:mmmAM' can be mentioned instead of mentioning the date format code like 131, 101, 102 in the convert function.
2017/05/27
[ "https://Stackoverflow.com/questions/44215132", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2550324/" ]
You might try it like this: ``` DECLARE @oracleDT VARCHAR(100)='29-03-17 03:58:34.312000000 PM'; SELECT CAST('<x>' + @oracleDT + '</x>' AS XML).value(N'(/x/text())[1]','datetime'); ``` It seems, that XML is implicitly able to do this correctly... EDIT: The above is culture related! ----------------------------------- It worked on my (german) system, but if you set the correct dateformat you can force this (be aware of side effects for the current job!) Try this and then remove the `--` to try alternative date formats. Or try with `GERMAN`: ``` SET LANGUAGE ENGLISH; SET DATEFORMAT mdy; --SET DATEFORMAT ymd; --SET DATEFORMAT dmy; DECLARE @oracleDT VARCHAR(100)='01-02-03 03:58:34.312000000 PM'; SELECT CAST('<x>' + @oracleDT + '</x>' AS XML).value(N'(/x/text())[1]','datetime'); ``` Another approach ---------------- You might split the string in all parts and build a convertible format like this: ``` DECLARE @oracleDT VARCHAR(100)='29-03-17 03:58:34.312000000 PM'; WITH AllParts(Casted) AS ( SELECT CAST('<x>' + REPLACE(REPLACE(REPLACE(REPLACE(@oracleDT,'.','-'),' ','-'),':','-'),'-','</x><x>') + '</x>' AS XML) ) SELECT CONVERT (DATETIME, DATENAME(MONTH,'2000'+Casted.value(N'x[2]/text()[1]','nvarchar(max)')+'01') + ' ' + Casted.value(N'x[1]/text()[1]','nvarchar(max)') + ' ' + N'20' + Casted.value(N'x[3]/text()[1]','nvarchar(max)') + ' ' + Casted.value(N'x[4]/text()[1]','nvarchar(max)') + ':' + Casted.value(N'x[5]/text()[1]','nvarchar(max)') + ':' + Casted.value(N'x[6]/text()[1]','nvarchar(max)') + ':' + LEFT(Casted.value(N'x[7]/text()[1]','nvarchar(max)'),3) + Casted.value(N'x[8]/text()[1]','nvarchar(max)'),109) FROM AllParts ```
Although I don't really understand the need to use a string format that does not suit conversion, but you could divide the string into parts then build it up by adding the parts to each other. The foundation part if the first 8 characters converted to datetime2 using format style 5. ``` select t , convert(varchar, converted ,121) converted from ( select '29-03-17 03:58:34.312000000 PM' as t ) t cross apply ( select convert(datetime2,substring(t,1,8),5) dt2 , case when right(t,2) = 'PM' then convert(smallint,substring(t,10,2)) + 12 else convert(smallint,substring(t,10,2)) end hh , convert(smallint,substring(t,13,2)) mi , convert(smallint,substring(t,16,2)) ss , convert(int,substring(t,19,9)) ns ) ca cross apply ( select dateadd(hh,hh,dateadd(mi,mi,dateadd(ss,ss,dateadd(ns,ns,dt2)))) as converted ) ca2 ; ``` Note I am able to use the column aliases of the first cross apply (dt1, hh, mi, ss, ns) in the second cross apply to form the converted datetime2 value. ``` +--------------------------------+-----------------------------+ | t | converted | +--------------------------------+-----------------------------+ | 29-03-17 03:58:34.312000000 PM | 2017-03-29 15:58:34.3120000 | +--------------------------------+-----------------------------+ ``` see: <http://rextester.com/DZJ42703>
13,440,602
lick() is a private method of Cat. Unfortunately, Cat's this.paw is not accessible in lick(). Is there a simple way to create a private method that has access to the member variables of its containing class? ``` <!doctype html> <html> <head> <meta charset="utf-8"> </head> <body> <p id="catStatus">???</p> <script> function Cat() { this.paw; var lick = function() { alert(this.paw); if(this.paw == "sticky") { alert("meow"); document.getElementById("catStatus").innerHTML = "*Slurp*"; } }; this.beCat = function() { this.paw = "sticky"; lick(); } } var kitty = new Cat(); kitty.beCat(); </script> </body> </html> ``` ![Result](https://i.stack.imgur.com/cIpgr.png)
2012/11/18
[ "https://Stackoverflow.com/questions/13440602", "https://Stackoverflow.com", "https://Stackoverflow.com/users/724752/" ]
The value of `this` depends on how you call the method. Since you're not calling the method on the object instance, `this` becomes the global object. Instead, you need to save `this` in a variable: ``` function Cat() { this.paw = ...; var me = this; var lick = function() { alert(me.paw); if(me.paw == "sticky") { alert("meow"); document.getElementById("catStatus").innerHTML = "*Slurp*"; } }; this.beCat = function() { this.paw = "sticky"; lick(); } } ```
There are a couple ways to solve this. The problem is that the context inside of lick is not the instance of cat. You can either: Use the call method to set the context ``` this.beCat = function() { this.paw = "sticky"; lick.call(this); }; ``` or use closure ``` var instance = this; var lick = function() { alert(instance.paw); if(instance.paw == "sticky") { alert("meow"); document.getElementById("catStatus").innerHTML = "*Slurp*"; } }; ```
13,440,602
lick() is a private method of Cat. Unfortunately, Cat's this.paw is not accessible in lick(). Is there a simple way to create a private method that has access to the member variables of its containing class? ``` <!doctype html> <html> <head> <meta charset="utf-8"> </head> <body> <p id="catStatus">???</p> <script> function Cat() { this.paw; var lick = function() { alert(this.paw); if(this.paw == "sticky") { alert("meow"); document.getElementById("catStatus").innerHTML = "*Slurp*"; } }; this.beCat = function() { this.paw = "sticky"; lick(); } } var kitty = new Cat(); kitty.beCat(); </script> </body> </html> ``` ![Result](https://i.stack.imgur.com/cIpgr.png)
2012/11/18
[ "https://Stackoverflow.com/questions/13440602", "https://Stackoverflow.com", "https://Stackoverflow.com/users/724752/" ]
The value of `this` depends on how you call the method. Since you're not calling the method on the object instance, `this` becomes the global object. Instead, you need to save `this` in a variable: ``` function Cat() { this.paw = ...; var me = this; var lick = function() { alert(me.paw); if(me.paw == "sticky") { alert("meow"); document.getElementById("catStatus").innerHTML = "*Slurp*"; } }; this.beCat = function() { this.paw = "sticky"; lick(); } } ```
The context of this depends upon who called the function. In this case it is beCat. You can however explicitly specify the this scope by using call. In your case: ``` this.beCat = function () { this.paw = "sticky"; lick.call(this); } ``` Or you can store the this in a variable. You can read more about the this scope/how it works [here](http://unschooled.org/2012/03/understanding-javascript-this/).
65,492,424
I'm working with [AI-Thermometer](https://github.com/tomek-l/ai-thermometer) project using Nvidia Jeton Nano. The project is using Pi camera v2 for video capturing. Here's the command of showing video streams using Pi camera v2. ```sh gst-launch-1.0 nvarguscamerasrc sensor_mode=0 ! 'video/x-raw(memory:NVMM),width=3264, height=2464, framerate=21/1, format=NV12' ! nvvidconv flip-method=2 ! 'video/x-raw,width=960, height=720' ! nvvidconv ! nvegltransform ! nveglglessink -e ``` I want to use the normal USB webcam (such as Logitech c930) instead of Pi camera v2. To do so, I need to stream the USB webcam data using GStreamer in the same way as above pipeline commands. I installed `v4l-utils` on Ubuntu of Jetson Nano. And tried like this, ```sh gst-launch-1.0 v4l2src device="/dev/video0" ! 'video/x-raw(memory:NVMM),width= ... ``` , but it gave a warning and didn't work. How can I show video streams from webcam?
2020/12/29
[ "https://Stackoverflow.com/questions/65492424", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12570573/" ]
There should not quotes around the device parameter i.e. `device=/dev/video0`. If the error persists, then its probably something else.
```none gst-launch-1.0 v4l2src device="/dev/video0" ! \ "video/x-raw, width=640, height=480, format=(string)YUY2" ! \ xvimagesink -e ```
1,749,232
What naming conventions do you use for everyday code? I'm pondering this because I currently have a project in Python that contains 3 packages, each with a unique purpose. Now, I've been putting general-purpose, 'utility' methods into the first package I created for the project, however I'm contemplating moving these methods to a separate package. The question is what would I call it? Utility, Collection, Assorted? Is there any standard naming conventions you swear by, and if so can you please provide links? I'm aware each language has it's own naming conventions, however is there any particular one that you find the most useful, that you'd recommend I'd start using?
2009/11/17
[ "https://Stackoverflow.com/questions/1749232", "https://Stackoverflow.com", "https://Stackoverflow.com/users/154280/" ]
In general, you should follow the naming convention of the language you're using. It doesn't matter if you like or prefer the standards of another language. Consistency within the context of the language helps make your code more readable, maintainable, and usable by others. In Python, that means you use [PEP 8](http://www.python.org/dev/peps/pep-0008/). Using a personal example: In Python, I'd call the package "utils" -- or if I intended on redistribution, "coryutils" or something similar to avoid namespace collisions. In Java or ActionScript, I'd call the package "net.petosky.utils", regardless of whether I intended on redistribution or not.
Unless you have some good reason not to, you should follow the guidelines presented in [PEP 8](http://www.python.org/dev/peps/pep-0008/). See, in particular, "Prescriptive: Naming Conventions".
30,779,774
I have a table like this: ``` CREATE TABLE mytable ( user_id int, device_id ascii, record_time timestamp, timestamp timeuuid, info_1 text, info_2 int, PRIMARY KEY (user_id, device_id, record_time, timestamp) ); ``` When I ask Cassandra to delete a record (an entry in the columnfamily) like this: ``` DELETE from my_table where user_id = X and device_id = Y and record_time = Z and timestamp = XX; ``` it returns without an error, but when I query again the record is still there. Now if I try to delete a whole row like this: ``` DELETE from my_table where user_id = X ``` It works and removes the whole row, and querying again immediately doesn't return any more data from that row. What I am doing wrong? How you can remove a record in Cassandra? Thanks
2015/06/11
[ "https://Stackoverflow.com/questions/30779774", "https://Stackoverflow.com", "https://Stackoverflow.com/users/697716/" ]
Ok, here is my theory as to what is going on. You have to be careful with timestamps, because they will *store* data down to the millisecond. But, they will only *display* data to the second. Take this sample table for example: ``` aploetz@cqlsh:stackoverflow> SELECT id, datetime FROM data; id | datetime --------+-------------------------- B25881 | 2015-02-16 12:00:03-0600 B26354 | 2015-02-16 12:00:03-0600 (2 rows) ``` The `datetime`s (of type timestamp) are equal, right? Nope: ``` aploetz@cqlsh:stackoverflow> SELECT id, blobAsBigint(timestampAsBlob(datetime)), datetime FROM data; id | blobAsBigint(timestampAsBlob(datetime)) | datetime --------+-----------------------------------------+-------------------------- B25881 | 1424109603000 | 2015-02-16 12:00:03-0600 B26354 | 1424109603234 | 2015-02-16 12:00:03-0600 (2 rows) ``` As you are finding out, this becomes problematic when you use timestamps as part of your PRIMARY KEY. It is possible that your timestamp is storing more precision than it is showing you. And thus, you will need to provide that hidden precision if you will be successful in deleting that single row. Anyway, you have a couple of options here. One, find a way to ensure that you are not entering more precision than necessary into your `record_time`. Or, you could define `record_time` as a timeuuid. Again, it's a theory. I could be totally wrong, but I have seen people do this a few times. Usually it happens when they insert timestamp data using `dateof(now())` like this: ``` INSERT INTO table (key, time, data) VALUES (1,dateof(now()),'blah blah'); ```
``` CREATE TABLE worker_login_table ( worker_id text, logged_in_time timestamp, PRIMARY KEY (worker_id, logged_in_time) ); INSERT INTO worker_login_table (worker_id, logged_in_time) VALUES ("worker_1",toTimestamp(now())); ``` after 1 hour executed the above insert statement once again ``` select * from worker_login_table; worker_id| logged_in_time ----------+-------------------------- worker_1 | 2019-10-23 12:00:03+0000 worker_1 | 2015-10-23 13:00:03+0000 (2 rows) ``` Query the table to get absolute timestamp ``` select worker_id, blobAsBigint(timestampAsBlob(logged_in_time )), logged_in_time from worker_login_table; worker_id | blobAsBigint(timestampAsBlob(logged_in_time)) | logged_in_time --------+-----------------------------------------+-------------------------- worker_1 | 1524109603000 | 2019-10-23 12:00:03+0000 worker_1 | 1524209403234 | 2019-10-23 13:00:03+0000 (2 rows) ``` The below command **will not delete** the entry from Cassandra as the precise value of timestamp is required to delete the entry ``` DELETE from worker_login_table where worker_id='worker_1' and logged_in_time ='2019-10-23 12:00:03+0000'; ``` By using the timestamp from blob **we can delete** the entry from Cassandra ``` DELETE from worker_login_table where worker_id='worker_1' and logged_in_time ='1524209403234'; ```
3,508,624
Got a table with 1200 rows. Added a new column which will contain incremental values - Candidate1 Candidate2 Candidate3 . . . Candidate1200 What is the best way to insert these values , non manual way. I am using SQL Server 2008
2010/08/18
[ "https://Stackoverflow.com/questions/3508624", "https://Stackoverflow.com", "https://Stackoverflow.com/users/416465/" ]
Simple: ``` $post_title = sanitize_title_with_dashes($post_title); ``` But WordPress does this for you already. I assume you need it for something different?
Some solution might be found at <http://postedpost.com/2008/06/23/ultimate-wordpress-post-name-url-sanitize-solution/> Also, you might want to do it as follows: ``` $special_chars = array("?", "[", "]", "/", "\\", "=", "<", ">", ":", ";", ",", "'", "\"", "&", "$", "#", "*", "(", ")", "|", "~", "`", "!", "{", "}"); $post_name = str_replace(' ', '-', str_replace($special_chars, '', strtolower($post_name))); ```
3,508,624
Got a table with 1200 rows. Added a new column which will contain incremental values - Candidate1 Candidate2 Candidate3 . . . Candidate1200 What is the best way to insert these values , non manual way. I am using SQL Server 2008
2010/08/18
[ "https://Stackoverflow.com/questions/3508624", "https://Stackoverflow.com", "https://Stackoverflow.com/users/416465/" ]
I'm guessing you're sanitizing by direct SQL insertion. Instead, consider using wp\_post\_insert() in your insertion script. ``` $new_post_id = wp_insert_post(array( 'post_title' => "This <open_tag insane title thing<b>LOL!;drop table `bobby`;" )); ``` At this point, you just worry about your title - and not the slug, post name, etc. WP will take care of the rest and (at least security) sanitization. The slug, as demonstrated in the screenshot, becomes fairly usable. ![alt text](https://i.stack.imgur.com/PgVau.jpg) This function can be used by simply doing `include( "wp-config.php" );` and going about your business without any other PHP overhead. If you are dealing with some funky titles to begin with, a simple strip\_tags(trim()) might do the trick. Otherwise, you've got other problems to deal with ;-)
Some solution might be found at <http://postedpost.com/2008/06/23/ultimate-wordpress-post-name-url-sanitize-solution/> Also, you might want to do it as follows: ``` $special_chars = array("?", "[", "]", "/", "\\", "=", "<", ">", ":", ";", ",", "'", "\"", "&", "$", "#", "*", "(", ")", "|", "~", "`", "!", "{", "}"); $post_name = str_replace(' ', '-', str_replace($special_chars, '', strtolower($post_name))); ```
3,508,624
Got a table with 1200 rows. Added a new column which will contain incremental values - Candidate1 Candidate2 Candidate3 . . . Candidate1200 What is the best way to insert these values , non manual way. I am using SQL Server 2008
2010/08/18
[ "https://Stackoverflow.com/questions/3508624", "https://Stackoverflow.com", "https://Stackoverflow.com/users/416465/" ]
Simple: ``` $post_title = sanitize_title_with_dashes($post_title); ``` But WordPress does this for you already. I assume you need it for something different?
I'm guessing you're sanitizing by direct SQL insertion. Instead, consider using wp\_post\_insert() in your insertion script. ``` $new_post_id = wp_insert_post(array( 'post_title' => "This <open_tag insane title thing<b>LOL!;drop table `bobby`;" )); ``` At this point, you just worry about your title - and not the slug, post name, etc. WP will take care of the rest and (at least security) sanitization. The slug, as demonstrated in the screenshot, becomes fairly usable. ![alt text](https://i.stack.imgur.com/PgVau.jpg) This function can be used by simply doing `include( "wp-config.php" );` and going about your business without any other PHP overhead. If you are dealing with some funky titles to begin with, a simple strip\_tags(trim()) might do the trick. Otherwise, you've got other problems to deal with ;-)
521
Has anyone seen this site? <http://answermagento.com/> I know this subject has been briefly discussed but this isn't another site using a StackExchange-clone platform. This site consists entirely of scraped content from Magento SE. [Frequently linked-to site ripping off Magento Stack Exchange](https://magento.meta.stackexchange.com/questions/495/frequently-linked-to-site-ripping-off-magento-stack-exchange)
2015/02/23
[ "https://magento.meta.stackexchange.com/questions/521", "https://magento.meta.stackexchange.com", "https://magento.meta.stackexchange.com/users/324/" ]
The content is CC share-alike, but this site isn't properly crediting the origin. Not important though because the domain name infringes our mark. I've sent a note to our legal team to C&D the owner.
Thats a common problem with stackoverflow/stackexchange content. Usually you dont find it on google anymore, as the duplicate content restrictions are good enough to recognize them. If you still see such things, you can report them to the StackExchange Team via one of the communication ways. I for example sent a mail 3 Years ago about one case. It took some days, but they answered and forwarded the case. They have dedicated persons for this kind of Issue. So, just report it directly to StackExchange, they will forward it to the person responsible for this.
521
Has anyone seen this site? <http://answermagento.com/> I know this subject has been briefly discussed but this isn't another site using a StackExchange-clone platform. This site consists entirely of scraped content from Magento SE. [Frequently linked-to site ripping off Magento Stack Exchange](https://magento.meta.stackexchange.com/questions/495/frequently-linked-to-site-ripping-off-magento-stack-exchange)
2015/02/23
[ "https://magento.meta.stackexchange.com/questions/521", "https://magento.meta.stackexchange.com", "https://magento.meta.stackexchange.com/users/324/" ]
The content is CC share-alike, but this site isn't properly crediting the origin. Not important though because the domain name infringes our mark. I've sent a note to our legal team to C&D the owner.
**Meet "Alan Storm"** ![Alan Storm](https://i.stack.imgur.com/xB5cM.png) This is another website ripping Magento SE, compare this: * Ours: [Inline translate Chrome Bug?](https://magento.stackexchange.com/q/6435/3326) * Theirs: <http://worldofcoder.com/question/12459/how-to-inline-translate-chrome-bug.html> They left out the poster's names and replaced the pics, hence the good looking "Alan Storm"... ;)
521
Has anyone seen this site? <http://answermagento.com/> I know this subject has been briefly discussed but this isn't another site using a StackExchange-clone platform. This site consists entirely of scraped content from Magento SE. [Frequently linked-to site ripping off Magento Stack Exchange](https://magento.meta.stackexchange.com/questions/495/frequently-linked-to-site-ripping-off-magento-stack-exchange)
2015/02/23
[ "https://magento.meta.stackexchange.com/questions/521", "https://magento.meta.stackexchange.com", "https://magento.meta.stackexchange.com/users/324/" ]
Thats a common problem with stackoverflow/stackexchange content. Usually you dont find it on google anymore, as the duplicate content restrictions are good enough to recognize them. If you still see such things, you can report them to the StackExchange Team via one of the communication ways. I for example sent a mail 3 Years ago about one case. It took some days, but they answered and forwarded the case. They have dedicated persons for this kind of Issue. So, just report it directly to StackExchange, they will forward it to the person responsible for this.
**Meet "Alan Storm"** ![Alan Storm](https://i.stack.imgur.com/xB5cM.png) This is another website ripping Magento SE, compare this: * Ours: [Inline translate Chrome Bug?](https://magento.stackexchange.com/q/6435/3326) * Theirs: <http://worldofcoder.com/question/12459/how-to-inline-translate-chrome-bug.html> They left out the poster's names and replaced the pics, hence the good looking "Alan Storm"... ;)
50,327,168
I need to create perforce clients from my jenkins build scripts, and this needs to be done unattended. This is mainly because jenkins jobs run in unique folders, Perforce insists that each client has a unique root target folder, and we create new jenkins jobs all the time based on need. Right now each time I create a unique jenkins job, I have to manually create a perforce client for that job - I can do this from the command line, but Perforce also insists on pausing the client creation to show me the specification settings file, which I need to manually close before the client is created. To create the client I'm using ``` p4 -u myuser -P mypassword client -S //mydepo/mystream someclientname ``` and I'm using this awful hack to simultaneously kill notepad ``` p4 -u myuser -P mypassword client -S //mydepo/mystream someclientname | taskkill /IM notepad.exe /F ``` This sort of works, but it doesn't feel right. Is there an official/better way I can force p4 to silently force create a client?
2018/05/14
[ "https://Stackoverflow.com/questions/50327168", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1216792/" ]
You can position an absolute View over the RNCamera view, and put all of your content into that absolute view. For example: ```js import { RNCamera } from 'react-native-camera'; class TakePicture extends Component { takePicture = async () => { try { const data = await this.camera.takePictureAsync(); console.log('Path to image: ' + data.uri); } catch (err) { // console.log('err: ', err); } }; render() { return ( <View style={styles.container}> <RNCamera ref={cam => { this.camera = cam; }} style={styles.preview} > <View style={styles.captureContainer}> <TouchableOpacity style={styles.captureBtn} onPress={this.takePicture}> <Icon style={styles.iconCamera}>camera</Icon> <Text>Take Photo</Text> </TouchableOpacity> </View> </RNCamera> <View style={styles.space} /> </View> ); } } const styles = StyleSheet.create({ container: { position: 'relative' }, captueContainer: { position: 'absolute' bottom: 0, }, captureBtn: { backgroundColor: 'red' } }); ``` This is just an example. You will have to play with css properties to reach the desired layout.
simply add this to your code, remember it should be placed inside, it will make a stylish button with shadow. `<RNCamera> </RNCamera>` ``` <RNCamera> <View style={{position: 'absolute', bottom: "50%", right: "30%",}}> <TouchableOpacity style={{ borderWidth:1, borderColor:'#4f83cc', alignItems:'center', justifyContent:'center', width:"180%", height:"180%", backgroundColor:'#fff', borderRadius:100, shadowOpacity:1, shadowRadius:1, shadowColor:"#414685", shadowOffset: { width: 1, height: 5.5, }, elevation: 6, }} onPress={()=>{Alert.alert('hellowworld')}} > <Text>hello World</Text> </TouchableOpacity> </View> </RNCamera> ``` here you can see the output, it will be on the top of the camera. [![enter image description here](https://i.stack.imgur.com/FuftO.png)](https://i.stack.imgur.com/FuftO.png)
3,959,078
I have a model called a `Statement` that belongs to a `Member`. Given an array of members, I want to create a query that will return the **most recent** statement for each of those members (preferably in one nice clean query). I thought I might be able to achieve this using `group` and `order` - something like: ``` # @members is already in an array @statements = Statement.all( :conditions => ["member_id IN(?)", @members.collect{|m| m.id}], :group => :member_id, :order => "created_at DESC" ) ``` But unfortunately the above always returns the *oldest* statement for each member. I've tried swapping the order option round, but alas it always returns the oldest statement of the group rather than the most recent. I'm guessing `group_by` isn't the way to achieve this - so how do I achieve it? PS - any non Ruby/Rails people reading this, if you know how to achieve this in raw MySQL, then fire away.
2010/10/18
[ "https://Stackoverflow.com/questions/3959078", "https://Stackoverflow.com", "https://Stackoverflow.com/users/151409/" ]
In MySQL directly, you need a sub-query that returns the maximum `created_at` value for each member, which can then be joined back to the `Statement` table to retrieve the rest of the row. ``` SELECT * FROM Statement s JOIN (SELECT member_id, MAX(created_at) max_created_at FROM Statement GROUP BY member_id ) latest ON s.member_id = latest.member_id AND s.created_at = latest.max_created_at ```
If you are using Rails 3 I would recommend taking a look at the new ActiveRecord query syntax. There is an overview at <http://guides.rubyonrails.org/active_record_querying.html> I am pretty certain you could do what you are trying to do here without writing any SQL. There is an example in the "Grouping" section on that page which looks similar to what you are trying to do.
5,032,968
When an EXE raised an exception message like "access violation at address XXXXXXXX...", the address XXXXXXXX is a hex value, and we can get the source code line number that caused the exception, by looking at the map file. Details below ([by madshi at EE](http://www.experts-exchange.com/Programming/Languages/Pascal/Delphi/Q_21201209.html#a12542996)): > > you need to substract the image base, > which is most probably $400000. > Furthermore you need to substract the > "base of code" address, which is > stored in the image nt headers of each > module (exe/dll). It's usually $1000. > You can check which value it has by > using the freeware tool "PEProwse > Pro". It's the field "Base Of Code" in > the "Details" of the "Optional > Header". You'll also find the image > base address there. > > > **My question is**: How to get the source line number for a **DLL**? Does the same calculation apply? Thanks! Note 1: the map file is generated by Delphi and I'm not sure if this matters. Note 2: I've been using JCL DEBUG but it couldn't catch the exception which seems occurred at the startup of the DLL (an Office add-in, actually).
2011/02/17
[ "https://Stackoverflow.com/questions/5032968", "https://Stackoverflow.com", "https://Stackoverflow.com/users/133516/" ]
Same calculations apply, with the following note: instead of image base address of EXE you'll need to take actual address where DLL had been loaded. Base of code for a DLL should taken in the same manner as for EXE (stored in PE's `IMAGE_OPTIONAL_HEADER`). Btw, EXE and DLL are actually the same thing from the point of view of PE format.
Two binaries can not be loaded at the same address. So the image base address stored in the DLL/EXE is only a suggestion for which the binary is optimized. Where the binary actually gets loaded into memory depends on many factors, like other binaries loaded in the process first, Windows version, injected 3rd party dlls, etc. As suggested you can use a debugger or a tool like Process Explorer to find out at what address the DLL is loaded at that time. Or if you want to know from code you can by getting the HInstance or HModule from the DLL [since both are the same](https://blogs.msdn.com/b/oldnewthing/archive/2004/06/14/155107.aspx) and are the address in memory the DLL is loaded at. Delphi gets you the HModule for other DLL's through the GetModuleHandle method. Newer Delphi versions also have other methods to find HInstance.
52,332,409
I converted the png file to SVG and got it from <http://inloop.github.io/svg2android/> to find the vector path information. I have been trying to support from api level 21 to get the right resolution for all screen sizes by using vector drawables. (My app`s minSdk is 21) The problem is that the text is white and the background color is transparent, but I am trying to change it using the fillColor attribute or strokeColor, but somehow not working well. how do I achieve this? I want text`s color is white and other background is transparent. ``` <?xml version="1.0" encoding="utf-8"?> <vector xmlns:android="http://schemas.android.com/apk/res/android" android:width="386.000000dp" android:height="149.000000dp" android:viewportWidth="386.000000" android:viewportHeight="149.000000" > <group android:translateY="149.000000" android:scaleX="0.100000" android:scaleY="-0.100000" > <path android:strokeColor="#FFFFFF" android:strokeWidth="3" android:pathData="M0 745 l0 -745 1930 0 1930 0 0 432 0 432 -45 -72 c-85 -138 -151 -202 -209 -202 -65 0 -85 40 -87 175 -2 140 -18 161 -77 97 -46 -50 -153 -224 -155 -252 -1 -18 -7 -20 -37 -18 l-35 3 2 80 c2 44 5 91 9 105 5 24 5 23 -17 -5 -44 -60 -135 -147 -171 -166 -49 -25 -112 -25 -138 1 -29 29 -33 61 -17 138 l14 70 -60 -44 c-32 -24 -63 -44 -68 -44 -5 0 -6 -19 -3 -42 11 -86 -57 -158 -148 -158 -39 0 -54 5 -73 25 -14 13 -25 31 -25 39 0 24 48 74 100 103 l48 27 -31 57 -31 56 -54 -44 c-30 -25 -65 -50 -78 -55 -20 -10 -23 -16 -18 -52 10 -84 -58 -156 -148 -156 -39 0 -54 5 -73 25 -14 13 -25 31 -25 39 0 24 48 74 100 103 l49 27 -26 46 -26 46 -81 -81 c-99 -100 -170 -138 -266 -143 -55 -3 -70 0 -100 20 -96 65 -67 247 51 325 33 22 56 28 110 31 63 4 70 2 95 -23 22 -22 25 -32 21 -62 -11 -64 -79 -113 -184 -134 -70 -13 -79 -28 -44 -70 16 -20 28 -24 68 -23 67 1 142 43 229 129 59 59 72 78 78 114 7 48 52 101 84 101 27 0 55 -34 48 -58 -4 -10 -17 -29 -31 -42 l-24 -23 32 -58 c18 -32 34 -59 37 -59 3 0 36 23 73 51 55 40 73 61 92 104 35 79 83 106 119 66 21 -23 15 -49 -19 -81 l-25 -23 32 -56 c17 -31 33 -58 34 -60 2 -2 33 18 69 43 67 48 101 88 91 104 -7 11 60 26 74 17 15 -9 12 -70 -7 -163 -16 -75 -16 -83 -1 -98 21 -21 45 -13 106 35 64 51 160 179 158 211 -1 18 6 27 25 34 15 5 35 6 44 2 16 -6 17 -16 11 -99 l-7 -92 49 75 c65 101 114 142 166 138 62 -5 77 -33 83 -164 5 -106 14 -144 33 -144 20 0 78 62 130 139 47 69 58 80 78 76 l22 -5 0 310 0 310 -1930 0 -1930 0 0 -745z m499 358 c-30 -38 -44 -42 -145 -43 l-101 0 -12 -62 c-7 -35 -15 -74 -18 -87 l-6 -24 79 6 c44 3 88 9 97 13 23 8 21 -8 -4 -40 -19 -24 -26 -26 -99 -26 l-79 0 -12 -57 c-20 -98 -18 -115 16 -132 24 -12 42 -12 100 -3 38 6 80 14 93 18 13 4 22 2 22 -4 0 -6 -10 -22 -22 -36 -26 -29 -94 -46 -189 -46 -122 0 -138 23 -111 163 l19 98 -23 -5 c-12 -3 -30 -9 -40 -13 -17 -6 -16 -4 2 28 13 22 29 35 46 37 23 3 27 10 38 65 6 34 14 73 17 86 5 22 4 23 -28 16 -19 -4 -47 -14 -62 -22 -16 -8 -31 -12 -34 -10 -6 7 24 64 39 74 7 4 90 11 183 14 94 3 187 6 209 7 35 2 37 1 25 -15z m2587 -21 c-18 -34 -91 -92 -117 -92 -40 0 -31 56 10 65 15 3 47 19 71 35 24 16 46 28 48 26 2 -2 -3 -18 -12 -34z m-2037 -47 c25 3 57 9 70 12 23 6 24 5 17 -42 -4 -26 -10 -54 -13 -62 -4 -10 6 -8 36 8 51 26 129 23 162 -7 98 -87 40 -283 -101 -342 -22 -9 -57 -13 -101 -10 l-67 4 -17 -84 c-9 -46 -15 -98 -13 -115 3 -31 2 -32 -37 -32 -39 0 -40 1 -43 35 -2 20 11 100 28 179 16 79 30 147 30 150 0 3 -14 -11 -31 -32 -86 -104 -211 -116 -282 -26 l-24 31 -25 -44 c-14 -23 -31 -61 -39 -83 -7 -22 -17 -44 -21 -49 -11 -14 -48 24 -48 49 0 23 67 132 95 155 13 10 12 17 -4 48 -10 21 -27 63 -37 96 l-18 58 23 19 c34 27 61 25 61 -6 0 -31 39 -135 50 -135 15 0 61 67 75 107 10 30 19 39 40 41 63 8 50 -45 -35 -141 -28 -30 -50 -59 -50 -64 0 -5 10 -19 23 -30 60 -55 102 -53 172 9 60 53 100 113 109 163 4 22 9 48 12 58 4 14 -1 17 -35 17 -37 0 -71 19 -71 40 0 5 -3 15 -6 24 -5 13 0 13 32 5 20 -6 58 -8 83 -4z m769 -95 c2 -17 -6 -34 -22 -49 -25 -23 -27 -24 -45 -7 -18 16 -21 16 -50 1 -44 -22 -115 -116 -162 -212 -37 -76 -43 -83 -70 -83 -18 0 -32 6 -36 16 -3 8 4 65 17 126 12 61 22 132 23 157 1 25 6 49 12 53 17 13 65 9 71 -6 3 -8 -1 -50 -9 -93 -8 -43 -14 -79 -12 -81 1 -2 13 14 26 35 31 50 106 131 144 155 19 12 44 17 70 16 34 -3 40 -6 43 -28z" /> <path android:strokeColor="#FFFFFF" android:strokeWidth="1" android:pathData="M1163 894 c-48 -24 -59 -42 -77 -134 -21 -112 -22 -109 20 -126 88 -37 184 44 184 156 0 52 -24 98 -56 110 -32 13 -33 13 -71 -6z" /> <path android:strokeColor="#FFFFFF" android:strokeWidth="1" android:pathData="M1995 930 c-32 -13 -75 -65 -90 -106 -7 -22 -10 -40 -5 -42 22 -8 93 22 125 52 60 57 39 125 -30 96z" /> <path android:strokeColor="#FFFFFF" android:strokeWidth="1" android:pathData="M2329 656 c-41 -28 -53 -48 -36 -65 28 -28 86 5 90 53 3 38 -11 41 -54 12z" /> <path android:strokeColor="#FFFFFF" android:strokeWidth="1" android:pathData="M2639 656 c-41 -28 -53 -48 -36 -65 28 -28 86 5 90 53 3 38 -11 41 -54 12z" /> </group> </vector> ``` Thanks in advance for any help!
2018/09/14
[ "https://Stackoverflow.com/questions/52332409", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10363717/" ]
Use this class ``` private class VectorDrawableUtils { Drawable getDrawable(Context context, int drawableResId) { return VectorDrawableCompat.create(context.getResources(), drawableResId, context.getTheme()); } Drawable getDrawable(Context context, int drawableResId, int colorFilter) { Drawable drawable = getDrawable(context, drawableResId); drawable.setColorFilter(ContextCompat.getColor(context, colorFilter), PorterDuff.Mode.SRC_IN); return drawable; } } ``` And call it like this ``` new VectorDrawableUtils().getDrawable(mContext,R.drawable.x,R.color.black); ```
It's possible to make it so, however, you have to manually change your vector. Currently, first `path` contains all letters and rectangle background. To make all letter white you can use should extract letter in separate `path` and set `fillColor` for it. And so on. BTW, why don't you use custom font for the purpose of text drawing? I think it is much more flexible and better in terms of performance.
52,332,409
I converted the png file to SVG and got it from <http://inloop.github.io/svg2android/> to find the vector path information. I have been trying to support from api level 21 to get the right resolution for all screen sizes by using vector drawables. (My app`s minSdk is 21) The problem is that the text is white and the background color is transparent, but I am trying to change it using the fillColor attribute or strokeColor, but somehow not working well. how do I achieve this? I want text`s color is white and other background is transparent. ``` <?xml version="1.0" encoding="utf-8"?> <vector xmlns:android="http://schemas.android.com/apk/res/android" android:width="386.000000dp" android:height="149.000000dp" android:viewportWidth="386.000000" android:viewportHeight="149.000000" > <group android:translateY="149.000000" android:scaleX="0.100000" android:scaleY="-0.100000" > <path android:strokeColor="#FFFFFF" android:strokeWidth="3" android:pathData="M0 745 l0 -745 1930 0 1930 0 0 432 0 432 -45 -72 c-85 -138 -151 -202 -209 -202 -65 0 -85 40 -87 175 -2 140 -18 161 -77 97 -46 -50 -153 -224 -155 -252 -1 -18 -7 -20 -37 -18 l-35 3 2 80 c2 44 5 91 9 105 5 24 5 23 -17 -5 -44 -60 -135 -147 -171 -166 -49 -25 -112 -25 -138 1 -29 29 -33 61 -17 138 l14 70 -60 -44 c-32 -24 -63 -44 -68 -44 -5 0 -6 -19 -3 -42 11 -86 -57 -158 -148 -158 -39 0 -54 5 -73 25 -14 13 -25 31 -25 39 0 24 48 74 100 103 l48 27 -31 57 -31 56 -54 -44 c-30 -25 -65 -50 -78 -55 -20 -10 -23 -16 -18 -52 10 -84 -58 -156 -148 -156 -39 0 -54 5 -73 25 -14 13 -25 31 -25 39 0 24 48 74 100 103 l49 27 -26 46 -26 46 -81 -81 c-99 -100 -170 -138 -266 -143 -55 -3 -70 0 -100 20 -96 65 -67 247 51 325 33 22 56 28 110 31 63 4 70 2 95 -23 22 -22 25 -32 21 -62 -11 -64 -79 -113 -184 -134 -70 -13 -79 -28 -44 -70 16 -20 28 -24 68 -23 67 1 142 43 229 129 59 59 72 78 78 114 7 48 52 101 84 101 27 0 55 -34 48 -58 -4 -10 -17 -29 -31 -42 l-24 -23 32 -58 c18 -32 34 -59 37 -59 3 0 36 23 73 51 55 40 73 61 92 104 35 79 83 106 119 66 21 -23 15 -49 -19 -81 l-25 -23 32 -56 c17 -31 33 -58 34 -60 2 -2 33 18 69 43 67 48 101 88 91 104 -7 11 60 26 74 17 15 -9 12 -70 -7 -163 -16 -75 -16 -83 -1 -98 21 -21 45 -13 106 35 64 51 160 179 158 211 -1 18 6 27 25 34 15 5 35 6 44 2 16 -6 17 -16 11 -99 l-7 -92 49 75 c65 101 114 142 166 138 62 -5 77 -33 83 -164 5 -106 14 -144 33 -144 20 0 78 62 130 139 47 69 58 80 78 76 l22 -5 0 310 0 310 -1930 0 -1930 0 0 -745z m499 358 c-30 -38 -44 -42 -145 -43 l-101 0 -12 -62 c-7 -35 -15 -74 -18 -87 l-6 -24 79 6 c44 3 88 9 97 13 23 8 21 -8 -4 -40 -19 -24 -26 -26 -99 -26 l-79 0 -12 -57 c-20 -98 -18 -115 16 -132 24 -12 42 -12 100 -3 38 6 80 14 93 18 13 4 22 2 22 -4 0 -6 -10 -22 -22 -36 -26 -29 -94 -46 -189 -46 -122 0 -138 23 -111 163 l19 98 -23 -5 c-12 -3 -30 -9 -40 -13 -17 -6 -16 -4 2 28 13 22 29 35 46 37 23 3 27 10 38 65 6 34 14 73 17 86 5 22 4 23 -28 16 -19 -4 -47 -14 -62 -22 -16 -8 -31 -12 -34 -10 -6 7 24 64 39 74 7 4 90 11 183 14 94 3 187 6 209 7 35 2 37 1 25 -15z m2587 -21 c-18 -34 -91 -92 -117 -92 -40 0 -31 56 10 65 15 3 47 19 71 35 24 16 46 28 48 26 2 -2 -3 -18 -12 -34z m-2037 -47 c25 3 57 9 70 12 23 6 24 5 17 -42 -4 -26 -10 -54 -13 -62 -4 -10 6 -8 36 8 51 26 129 23 162 -7 98 -87 40 -283 -101 -342 -22 -9 -57 -13 -101 -10 l-67 4 -17 -84 c-9 -46 -15 -98 -13 -115 3 -31 2 -32 -37 -32 -39 0 -40 1 -43 35 -2 20 11 100 28 179 16 79 30 147 30 150 0 3 -14 -11 -31 -32 -86 -104 -211 -116 -282 -26 l-24 31 -25 -44 c-14 -23 -31 -61 -39 -83 -7 -22 -17 -44 -21 -49 -11 -14 -48 24 -48 49 0 23 67 132 95 155 13 10 12 17 -4 48 -10 21 -27 63 -37 96 l-18 58 23 19 c34 27 61 25 61 -6 0 -31 39 -135 50 -135 15 0 61 67 75 107 10 30 19 39 40 41 63 8 50 -45 -35 -141 -28 -30 -50 -59 -50 -64 0 -5 10 -19 23 -30 60 -55 102 -53 172 9 60 53 100 113 109 163 4 22 9 48 12 58 4 14 -1 17 -35 17 -37 0 -71 19 -71 40 0 5 -3 15 -6 24 -5 13 0 13 32 5 20 -6 58 -8 83 -4z m769 -95 c2 -17 -6 -34 -22 -49 -25 -23 -27 -24 -45 -7 -18 16 -21 16 -50 1 -44 -22 -115 -116 -162 -212 -37 -76 -43 -83 -70 -83 -18 0 -32 6 -36 16 -3 8 4 65 17 126 12 61 22 132 23 157 1 25 6 49 12 53 17 13 65 9 71 -6 3 -8 -1 -50 -9 -93 -8 -43 -14 -79 -12 -81 1 -2 13 14 26 35 31 50 106 131 144 155 19 12 44 17 70 16 34 -3 40 -6 43 -28z" /> <path android:strokeColor="#FFFFFF" android:strokeWidth="1" android:pathData="M1163 894 c-48 -24 -59 -42 -77 -134 -21 -112 -22 -109 20 -126 88 -37 184 44 184 156 0 52 -24 98 -56 110 -32 13 -33 13 -71 -6z" /> <path android:strokeColor="#FFFFFF" android:strokeWidth="1" android:pathData="M1995 930 c-32 -13 -75 -65 -90 -106 -7 -22 -10 -40 -5 -42 22 -8 93 22 125 52 60 57 39 125 -30 96z" /> <path android:strokeColor="#FFFFFF" android:strokeWidth="1" android:pathData="M2329 656 c-41 -28 -53 -48 -36 -65 28 -28 86 5 90 53 3 38 -11 41 -54 12z" /> <path android:strokeColor="#FFFFFF" android:strokeWidth="1" android:pathData="M2639 656 c-41 -28 -53 -48 -36 -65 28 -28 86 5 90 53 3 38 -11 41 -54 12z" /> </group> </vector> ``` Thanks in advance for any help!
2018/09/14
[ "https://Stackoverflow.com/questions/52332409", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10363717/" ]
Use this class ``` private class VectorDrawableUtils { Drawable getDrawable(Context context, int drawableResId) { return VectorDrawableCompat.create(context.getResources(), drawableResId, context.getTheme()); } Drawable getDrawable(Context context, int drawableResId, int colorFilter) { Drawable drawable = getDrawable(context, drawableResId); drawable.setColorFilter(ContextCompat.getColor(context, colorFilter), PorterDuff.Mode.SRC_IN); return drawable; } } ``` And call it like this ``` new VectorDrawableUtils().getDrawable(mContext,R.drawable.x,R.color.black); ```
Change Fill color if you want to change inside color If you want change stroke color then change it's color
52,260,366
I am looking for a textbox control that suggests words as the user types, similar to SuggestAppend for textboxes in winforms, except for WPF. I have looked around on the WPFToolkit and haven't really found anything that fits my needs. Thanks.
2018/09/10
[ "https://Stackoverflow.com/questions/52260366", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6635930/" ]
Declare an enum AutoCompleteMode too with value(Append, None,SuggestAppend,Suggest) ``` public enum AutoCompleteMode ``` Create an custom UserControl with TextBox and ItemControls. Handle the **KeyDown** event of TextBox. Popup an custom List to show the suggestion list(ItemControls in here). Then Handle the selection of the ItemControls. Can custom the style of hte ItemControls's ItemTemplate. Apply the AutoCOmpleteMode in this UserControl and handle the Enum changed in the code behind.
WpfToolkit contains [AutoCompleteBox](https://github.com/dotnetprojects/WpfToolkit/blob/master/WpfToolkit/Input/AutoCompleteBox/System/Windows/Controls/AutoCompleteBox.cs) that you can use for auto suggest feature. You will have to define a collection for items to suggest (SuggestionItems) and set it as ItemsSource on AutoCompleteBox control. ``` <someNamespaceAlias:AutoCompleteBox ItemsSource="{Binding SuggestionItems}" SelectedItem="{Binding SelectedItem, Mode=TwoWay}" /> ```
5,788,258
Hey I have a .NET .aspx page that I would like to run every hour or so whats the best way to do this ? I assume it will have to open a browser window to do so and if possible that it closes the window after. EDIT : I have access over all features on the server
2011/04/26
[ "https://Stackoverflow.com/questions/5788258", "https://Stackoverflow.com", "https://Stackoverflow.com/users/215541/" ]
**Option 1**: The cleanest solution would be to write a Windows application that does the work (instead of an aspx page) and schedule this application on the server using the Windows Task Scheduler. This has a few advantages over the aspx approach: * You can use the features of the Windows Task Scheduler (event log entries if the task could not be started, see the time of the last run, run the task in the context of a specific user, etc.). * You don't need to "simulate" a web browser call. * Your page cannot be "accidentally" called by a web user or a search engine. * It's conceptually cleaner: The main purpose of a web page is to provide information to the client, not to trigger an action on the server. Of course, there are drawbacks as well: * You have two Visual Studio projects instead of one. * You might need to factor common code into a shared class library. (This can also be seen as an advantage.) * Your system becomes more complex and, thus, potentially harder to maintain. --- **Option 2**: If you need to stick to an aspx page, the easiest solution is probably to call the page via a command-line web client in a scheduled task. Since Windows does not provide any built-in command-line web clients, you'd have to download one such as `wget` or [`curl`](http://curl.haxx.se/). This related SO question contains the necessary command-line syntax: * [Scheduled Tasks for ASP.NET](https://stackoverflow.com/questions/2927330/scheduled-tasks-for-asp-net/2927375#2927375)
use this sample to schedule a task in asp.net : [enter link description here](http://www.codeproject.com/KB/aspnet/ASPNETService.aspx) then you need to create `Hit.aspx` page witch will do what you want. then you should call that page every time (using `WebClient` class) the task execution time elapsed!
5,788,258
Hey I have a .NET .aspx page that I would like to run every hour or so whats the best way to do this ? I assume it will have to open a browser window to do so and if possible that it closes the window after. EDIT : I have access over all features on the server
2011/04/26
[ "https://Stackoverflow.com/questions/5788258", "https://Stackoverflow.com", "https://Stackoverflow.com/users/215541/" ]
**Option 1**: The cleanest solution would be to write a Windows application that does the work (instead of an aspx page) and schedule this application on the server using the Windows Task Scheduler. This has a few advantages over the aspx approach: * You can use the features of the Windows Task Scheduler (event log entries if the task could not be started, see the time of the last run, run the task in the context of a specific user, etc.). * You don't need to "simulate" a web browser call. * Your page cannot be "accidentally" called by a web user or a search engine. * It's conceptually cleaner: The main purpose of a web page is to provide information to the client, not to trigger an action on the server. Of course, there are drawbacks as well: * You have two Visual Studio projects instead of one. * You might need to factor common code into a shared class library. (This can also be seen as an advantage.) * Your system becomes more complex and, thus, potentially harder to maintain. --- **Option 2**: If you need to stick to an aspx page, the easiest solution is probably to call the page via a command-line web client in a scheduled task. Since Windows does not provide any built-in command-line web clients, you'd have to download one such as `wget` or [`curl`](http://curl.haxx.se/). This related SO question contains the necessary command-line syntax: * [Scheduled Tasks for ASP.NET](https://stackoverflow.com/questions/2927330/scheduled-tasks-for-asp-net/2927375#2927375)
You can use <http://quartznet.sourceforge.net/> Quartz Job Scheduler. With Quartz.net you can write a job which will request your web page with interval you choose. or alternatively you can write an windows service which will request that web page.
29,776,576
I can create a [Guava `ImmutableList`](https://google.github.io/guava/releases/23.0/api/docs/com/google/common/collect/ImmutableList.html) with the `of` method, and will get the correct generic type based on the passed objects: ``` Foo foo = new Foo(); ImmutableList.of(foo); ``` However, [the `of` method with no parameters](https://google.github.io/guava/releases/23.0/api/docs/com/google/common/collect/ImmutableList.html#of--) cannot infer the generic type and creates an `ImmutableList<Object>`. How can I create an empty `ImmutableList` to satisfy `List<Foo>`?
2015/04/21
[ "https://Stackoverflow.com/questions/29776576", "https://Stackoverflow.com", "https://Stackoverflow.com/users/722332/" ]
If you assign the created list to a variable, you don't have to do anything: ``` ImmutableList<Foo> list = ImmutableList.of(); ``` In other cases where the type can't be inferred, you have to write `ImmutableList.<Foo>of()` as @zigg says.
`ImmutableList.<Foo>of()` will create an empty `ImmutableList` with generic type `Foo`. Though [the compiler can infer the generic type](https://stackoverflow.com/a/29776623/722332) in some circumstances, like assignment to a variable, you'll need to use this format (as I did) when you're providing the value for a function argument.
29,776,576
I can create a [Guava `ImmutableList`](https://google.github.io/guava/releases/23.0/api/docs/com/google/common/collect/ImmutableList.html) with the `of` method, and will get the correct generic type based on the passed objects: ``` Foo foo = new Foo(); ImmutableList.of(foo); ``` However, [the `of` method with no parameters](https://google.github.io/guava/releases/23.0/api/docs/com/google/common/collect/ImmutableList.html#of--) cannot infer the generic type and creates an `ImmutableList<Object>`. How can I create an empty `ImmutableList` to satisfy `List<Foo>`?
2015/04/21
[ "https://Stackoverflow.com/questions/29776576", "https://Stackoverflow.com", "https://Stackoverflow.com/users/722332/" ]
`ImmutableList.<Foo>of()` will create an empty `ImmutableList` with generic type `Foo`. Though [the compiler can infer the generic type](https://stackoverflow.com/a/29776623/722332) in some circumstances, like assignment to a variable, you'll need to use this format (as I did) when you're providing the value for a function argument.
Since Java 8 the compiler is much more clever and can figure out the type parameters parameters in more situations. Example: ``` void test(List<String> l) { ... } // Type checks in Java 8 but not in Java 7 test(ImmutableList.of()); ``` ### Explanation The new thing in Java 8 is that the [target type](https://docs.oracle.com/javase/tutorial/java/generics/genTypeInference.html#target_types) of an expression will be used to infer type parameters of its sub-expressions. Before Java 8 only arguments to methods where used for type parameter inference. (Most of the time, one exception is assignments.) In this case the parameter type of `test` will be the target type for `of()`, and the return value type of `of` will get chosen to match that argument type.
29,776,576
I can create a [Guava `ImmutableList`](https://google.github.io/guava/releases/23.0/api/docs/com/google/common/collect/ImmutableList.html) with the `of` method, and will get the correct generic type based on the passed objects: ``` Foo foo = new Foo(); ImmutableList.of(foo); ``` However, [the `of` method with no parameters](https://google.github.io/guava/releases/23.0/api/docs/com/google/common/collect/ImmutableList.html#of--) cannot infer the generic type and creates an `ImmutableList<Object>`. How can I create an empty `ImmutableList` to satisfy `List<Foo>`?
2015/04/21
[ "https://Stackoverflow.com/questions/29776576", "https://Stackoverflow.com", "https://Stackoverflow.com/users/722332/" ]
If you assign the created list to a variable, you don't have to do anything: ``` ImmutableList<Foo> list = ImmutableList.of(); ``` In other cases where the type can't be inferred, you have to write `ImmutableList.<Foo>of()` as @zigg says.
Since Java 8 the compiler is much more clever and can figure out the type parameters parameters in more situations. Example: ``` void test(List<String> l) { ... } // Type checks in Java 8 but not in Java 7 test(ImmutableList.of()); ``` ### Explanation The new thing in Java 8 is that the [target type](https://docs.oracle.com/javase/tutorial/java/generics/genTypeInference.html#target_types) of an expression will be used to infer type parameters of its sub-expressions. Before Java 8 only arguments to methods where used for type parameter inference. (Most of the time, one exception is assignments.) In this case the parameter type of `test` will be the target type for `of()`, and the return value type of `of` will get chosen to match that argument type.
1,990,579
I am using "ExuberantCtags" also known as "ctags -e", also known as just "etags" and I am trying to understand the TAGS file format which is generated by the etags command, in particular I want to understand line #2 of the TAGS file. [Wikipedia says](http://en.wikipedia.org/wiki/Ctags#Etags_2) that line #2 is described like this: ``` {src_file},{size_of_tag_definition_data_in_bytes} ``` In practical terms though TAGS file line:2 for "foo.c" looks like this ``` foo.c,1683 ``` My quandary is how exactly does it find this number: 1683 I know it is the size of the "tag\_definition" so what I want to know is what is the "tag\_definition"? I have tried looking through the [ctags source code](http://ctags.sourceforge.net/), but perhaps someone better at C than me will have more success figuring this out. Thanks! EDIT #2: ``` ^L^J hello.c,79^J float foo (float x) {^?foo^A3,20^J float bar () {^?bar^A7,59^J int main() {^?main^A11,91^J ``` Alright, so if I understand correctly, "79" refers to the number of bytes in the TAGS file from after 79 down to and including "91^J". Makes perfect sense. Now the numbers 20, 59, 91 in this example wikipedia says refer to the {byte\_offset} What is the {byte\_offset} offset from? Thanks for all the help Ken!
2010/01/02
[ "https://Stackoverflow.com/questions/1990579", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2085667/" ]
You can probably use [mcrypt](http://de3.php.net/manual/en/ref.mcrypt.php). But may I ask why you're encrypting with ECB mode at all? Remember the [known problems](http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Electronic_codebook_.28ECB.29) with that?
``` mcrypt_decrypt('rijndael-128', $key, $data, 'ecb'); ``` You will have to manually remove [the padding](http://en.wikipedia.org/wiki/Padding_%28cryptography%29#Byte_padding).
31,208,835
``` firstLetter = word.charAt(0); lastLetter = word.charAt((word.length()) - 1); noFirstLetter = word.substring(1); newWord = noFirstLetter + firstLetter; if(word.equalsIgnoreCase(newWord)) ``` So im trying to take the first letter of the word and if I take the first letter of the word away and move it to the end it should be equal to the same word. My code here isn't working. For example if the user entered "dresser" if you move the "d" to the end of the word you get the word "dresser" again. That is what im trying to check
2015/07/03
[ "https://Stackoverflow.com/questions/31208835", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5078138/" ]
I think what you are trying to do is to remove the first character, and then check if rest of the characters are symmetrical around the center of the word.(OK even it is complicated for me) EG: dresser => (drop d) => resser => (add d to the right) => resserd (read from right to left and it is dresser again). after you drop the first letter: resser (there are even number of letters in the word) ``` r e s s e r |_| |_____| |_________| ``` since they are symmetrical, you can say that that word would be Palindromic if you move D from left to right (or vice versa). The whole thing above could be horribly wrong if I misunderstood your question at the first place. But I assumed, your question was NOT a simple substring question. Cheers.
If you move 'd' to the end of the word "dresser" you get "resserd" which is not equal to "dresser". If you move 'd' to the end and then **reverse** the word then they are equal. So, assuming you consider strings equals even if they are reversed, the code you want would be : ``` boolean testPass = false; if ( word.length()==0 ) testPass = true; else { firstLetter = word.charAt(0); noFirstLetter = word.substring(1); newWord = noFirstLetter + firstLetter; reversed = new StringBuilder(newWord).reverse().toString() if (word.equalsIgnoreCase(newWord) || word.equalsIgnoreCase(reversed)) testPass = true; } if ( testPass ) // Do something ``` Take notice of the important check of word having lenght 0. Otherwise word.charAt(0) will throw an exception.
31,208,835
``` firstLetter = word.charAt(0); lastLetter = word.charAt((word.length()) - 1); noFirstLetter = word.substring(1); newWord = noFirstLetter + firstLetter; if(word.equalsIgnoreCase(newWord)) ``` So im trying to take the first letter of the word and if I take the first letter of the word away and move it to the end it should be equal to the same word. My code here isn't working. For example if the user entered "dresser" if you move the "d" to the end of the word you get the word "dresser" again. That is what im trying to check
2015/07/03
[ "https://Stackoverflow.com/questions/31208835", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5078138/" ]
Okay, so I'm presuming that you want to take a `string`, move it's first index to the end and then reverse the `string`. If you do this to a word such as 'dresser' then you end up with the same value. Something like this could work, currently untested: ``` public StringBuilder reverseWord(String word){ firstLetter = word.charAt(0); //find the first letter noFirstLetter = word.substring(1); //removing the first index newWord = noFirstLetter + firstLetter; //move first index to end return new StringBuilder(newWord).reverse().toString(); //reverse } if(reverseWord("dresser").equals("dresser")){ //do something } ``` Edit: As Jose has pointed out, it is important to check the length of the actual parameter by invoking `length()` on `word`.
If you move 'd' to the end of the word "dresser" you get "resserd" which is not equal to "dresser". If you move 'd' to the end and then **reverse** the word then they are equal. So, assuming you consider strings equals even if they are reversed, the code you want would be : ``` boolean testPass = false; if ( word.length()==0 ) testPass = true; else { firstLetter = word.charAt(0); noFirstLetter = word.substring(1); newWord = noFirstLetter + firstLetter; reversed = new StringBuilder(newWord).reverse().toString() if (word.equalsIgnoreCase(newWord) || word.equalsIgnoreCase(reversed)) testPass = true; } if ( testPass ) // Do something ``` Take notice of the important check of word having lenght 0. Otherwise word.charAt(0) will throw an exception.
17,426,311
I have list of Active Directory Users's Guid, I need to load a set of properties of those users for a specific reporting. To do this, if we make a bind for each Guid, then it will be a costly one. Whether with DirectorySearcher, can we provide multiple Guid(say 1000) as filter and load the properties?.
2013/07/02
[ "https://Stackoverflow.com/questions/17426311", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2376887/" ]
``` In [9]: pd.Series(df.Letter.values,index=df.Position).to_dict() Out[9]: {1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e'} ``` Speed comparion (using Wouter's method) ``` In [6]: df = pd.DataFrame(randint(0,10,10000).reshape(5000,2),columns=list('AB')) In [7]: %timeit dict(zip(df.A,df.B)) 1000 loops, best of 3: 1.27 ms per loop In [8]: %timeit pd.Series(df.A.values,index=df.B).to_dict() 1000 loops, best of 3: 987 us per loop ```
I like the Wouter method, however the behaviour with duplicate values might not be what is expected and this scenario is not discussed one way or the other by the OP unfortunately. Wouter, will always choose the last value for each key encountered. So in other words, it will keep overwriting the value for each key. The expected behavior in my mind would be more like [Create a dict using two columns from dataframe with duplicates in one column](https://stackoverflow.com/questions/60085490) where a list is kept for each key. So for the case of keeping duplicates, let me submit `df.groupby('Position')['Letter'].apply(list).to_dict()` (Or perhaps even a set instead of a list)
17,426,311
I have list of Active Directory Users's Guid, I need to load a set of properties of those users for a specific reporting. To do this, if we make a bind for each Guid, then it will be a costly one. Whether with DirectorySearcher, can we provide multiple Guid(say 1000) as filter and load the properties?.
2013/07/02
[ "https://Stackoverflow.com/questions/17426311", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2376887/" ]
``` dict (zip(data['position'], data['letter'])) ``` this will give you: ``` {1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e'} ```
I like the Wouter method, however the behaviour with duplicate values might not be what is expected and this scenario is not discussed one way or the other by the OP unfortunately. Wouter, will always choose the last value for each key encountered. So in other words, it will keep overwriting the value for each key. The expected behavior in my mind would be more like [Create a dict using two columns from dataframe with duplicates in one column](https://stackoverflow.com/questions/60085490) where a list is kept for each key. So for the case of keeping duplicates, let me submit `df.groupby('Position')['Letter'].apply(list).to_dict()` (Or perhaps even a set instead of a list)
17,426,311
I have list of Active Directory Users's Guid, I need to load a set of properties of those users for a specific reporting. To do this, if we make a bind for each Guid, then it will be a costly one. Whether with DirectorySearcher, can we provide multiple Guid(say 1000) as filter and load the properties?.
2013/07/02
[ "https://Stackoverflow.com/questions/17426311", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2376887/" ]
In Python 3.6 the fastest way is still the WouterOvermeire one. Kikohs' proposal is slower than the other two options. ``` import timeit setup = ''' import pandas as pd import numpy as np df = pd.DataFrame(np.random.randint(32, 120, 100000).reshape(50000,2),columns=list('AB')) df['A'] = df['A'].apply(chr) ''' timeit.Timer('dict(zip(df.A,df.B))', setup=setup).repeat(7,500) timeit.Timer('pd.Series(df.A.values,index=df.B).to_dict()', setup=setup).repeat(7,500) timeit.Timer('df.set_index("A").to_dict()["B"]', setup=setup).repeat(7,500) ``` Results: ``` 1.1214002349999777 s # WouterOvermeire 1.1922008498571748 s # Jeff 1.7034366211428602 s # Kikohs ```
I like the Wouter method, however the behaviour with duplicate values might not be what is expected and this scenario is not discussed one way or the other by the OP unfortunately. Wouter, will always choose the last value for each key encountered. So in other words, it will keep overwriting the value for each key. The expected behavior in my mind would be more like [Create a dict using two columns from dataframe with duplicates in one column](https://stackoverflow.com/questions/60085490) where a list is kept for each key. So for the case of keeping duplicates, let me submit `df.groupby('Position')['Letter'].apply(list).to_dict()` (Or perhaps even a set instead of a list)
17,426,311
I have list of Active Directory Users's Guid, I need to load a set of properties of those users for a specific reporting. To do this, if we make a bind for each Guid, then it will be a costly one. Whether with DirectorySearcher, can we provide multiple Guid(say 1000) as filter and load the properties?.
2013/07/02
[ "https://Stackoverflow.com/questions/17426311", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2376887/" ]
``` dict (zip(data['position'], data['letter'])) ``` this will give you: ``` {1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e'} ```
Here are two other ways tested with the following df. ``` df = pd.DataFrame(np.random.randint(0,10,10000).reshape(5000,2),columns=list('AB')) ``` using `to_records()` ``` dict(df.to_records(index=False)) ``` using `MultiIndex.from_frame()` ``` dict(pd.MultiIndex.from_frame(df)) ``` Time of each. ``` 24.6 ms ± 847 µs per loop (mean ± std. dev. of 7 runs, 10 loops each) 1.86 ms ± 11.6 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) ```
17,426,311
I have list of Active Directory Users's Guid, I need to load a set of properties of those users for a specific reporting. To do this, if we make a bind for each Guid, then it will be a costly one. Whether with DirectorySearcher, can we provide multiple Guid(say 1000) as filter and load the properties?.
2013/07/02
[ "https://Stackoverflow.com/questions/17426311", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2376887/" ]
``` In [9]: pd.Series(df.Letter.values,index=df.Position).to_dict() Out[9]: {1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e'} ``` Speed comparion (using Wouter's method) ``` In [6]: df = pd.DataFrame(randint(0,10,10000).reshape(5000,2),columns=list('AB')) In [7]: %timeit dict(zip(df.A,df.B)) 1000 loops, best of 3: 1.27 ms per loop In [8]: %timeit pd.Series(df.A.values,index=df.B).to_dict() 1000 loops, best of 3: 987 us per loop ```
In Python 3.6 the fastest way is still the WouterOvermeire one. Kikohs' proposal is slower than the other two options. ``` import timeit setup = ''' import pandas as pd import numpy as np df = pd.DataFrame(np.random.randint(32, 120, 100000).reshape(50000,2),columns=list('AB')) df['A'] = df['A'].apply(chr) ''' timeit.Timer('dict(zip(df.A,df.B))', setup=setup).repeat(7,500) timeit.Timer('pd.Series(df.A.values,index=df.B).to_dict()', setup=setup).repeat(7,500) timeit.Timer('df.set_index("A").to_dict()["B"]', setup=setup).repeat(7,500) ``` Results: ``` 1.1214002349999777 s # WouterOvermeire 1.1922008498571748 s # Jeff 1.7034366211428602 s # Kikohs ```
17,426,311
I have list of Active Directory Users's Guid, I need to load a set of properties of those users for a specific reporting. To do this, if we make a bind for each Guid, then it will be a costly one. Whether with DirectorySearcher, can we provide multiple Guid(say 1000) as filter and load the properties?.
2013/07/02
[ "https://Stackoverflow.com/questions/17426311", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2376887/" ]
I found a faster way to solve the problem, at least on realistically large datasets using: `df.set_index(KEY).to_dict()[VALUE]` Proof on 50,000 rows: ``` df = pd.DataFrame(np.random.randint(32, 120, 100000).reshape(50000,2),columns=list('AB')) df['A'] = df['A'].apply(chr) %timeit dict(zip(df.A,df.B)) %timeit pd.Series(df.A.values,index=df.B).to_dict() %timeit df.set_index('A').to_dict()['B'] ``` Output: ``` 100 loops, best of 3: 7.04 ms per loop # WouterOvermeire 100 loops, best of 3: 9.83 ms per loop # Jeff 100 loops, best of 3: 4.28 ms per loop # Kikohs (me) ```
TL;DR ===== ``` >>> import pandas as pd >>> df = pd.DataFrame({'Position':[1,2,3,4,5], 'Letter':['a', 'b', 'c', 'd', 'e']}) >>> dict(sorted(df.values.tolist())) # Sort of sorted... {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5} >>> from collections import OrderedDict >>> OrderedDict(df.values.tolist()) OrderedDict([('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5)]) ``` In Long ======= Explaining solution: `dict(sorted(df.values.tolist()))` Given: ``` df = pd.DataFrame({'Position':[1,2,3,4,5], 'Letter':['a', 'b', 'c', 'd', 'e']}) ``` [out]: ``` Letter Position 0 a 1 1 b 2 2 c 3 3 d 4 4 e 5 ``` Try: ``` # Get the values out to a 2-D numpy array, df.values ``` [out]: ``` array([['a', 1], ['b', 2], ['c', 3], ['d', 4], ['e', 5]], dtype=object) ``` Then optionally: ``` # Dump it into a list so that you can sort it using `sorted()` sorted(df.values.tolist()) # Sort by key ``` Or: ``` # Sort by value: from operator import itemgetter sorted(df.values.tolist(), key=itemgetter(1)) ``` [out]: ``` [['a', 1], ['b', 2], ['c', 3], ['d', 4], ['e', 5]] ``` Lastly, cast the list of list of 2 elements into a dict. ``` dict(sorted(df.values.tolist())) ``` [out]: ``` {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5} ``` --- Related ======= Answering @sbradbio comment: If there are multiple values for a specific key and you would like to keep all of them, it's the not the most efficient but the most intuitive way is: ``` from collections import defaultdict import pandas as pd multivalue_dict = defaultdict(list) df = pd.DataFrame({'Position':[1,2,4,4,4], 'Letter':['a', 'b', 'd', 'e', 'f']}) for idx,row in df.iterrows(): multivalue_dict[row['Position']].append(row['Letter']) ``` [out]: ``` >>> print(multivalue_dict) defaultdict(list, {1: ['a'], 2: ['b'], 4: ['d', 'e', 'f']}) ```
17,426,311
I have list of Active Directory Users's Guid, I need to load a set of properties of those users for a specific reporting. To do this, if we make a bind for each Guid, then it will be a costly one. Whether with DirectorySearcher, can we provide multiple Guid(say 1000) as filter and load the properties?.
2013/07/02
[ "https://Stackoverflow.com/questions/17426311", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2376887/" ]
I found a faster way to solve the problem, at least on realistically large datasets using: `df.set_index(KEY).to_dict()[VALUE]` Proof on 50,000 rows: ``` df = pd.DataFrame(np.random.randint(32, 120, 100000).reshape(50000,2),columns=list('AB')) df['A'] = df['A'].apply(chr) %timeit dict(zip(df.A,df.B)) %timeit pd.Series(df.A.values,index=df.B).to_dict() %timeit df.set_index('A').to_dict()['B'] ``` Output: ``` 100 loops, best of 3: 7.04 ms per loop # WouterOvermeire 100 loops, best of 3: 9.83 ms per loop # Jeff 100 loops, best of 3: 4.28 ms per loop # Kikohs (me) ```
In Python 3.6 the fastest way is still the WouterOvermeire one. Kikohs' proposal is slower than the other two options. ``` import timeit setup = ''' import pandas as pd import numpy as np df = pd.DataFrame(np.random.randint(32, 120, 100000).reshape(50000,2),columns=list('AB')) df['A'] = df['A'].apply(chr) ''' timeit.Timer('dict(zip(df.A,df.B))', setup=setup).repeat(7,500) timeit.Timer('pd.Series(df.A.values,index=df.B).to_dict()', setup=setup).repeat(7,500) timeit.Timer('df.set_index("A").to_dict()["B"]', setup=setup).repeat(7,500) ``` Results: ``` 1.1214002349999777 s # WouterOvermeire 1.1922008498571748 s # Jeff 1.7034366211428602 s # Kikohs ```
17,426,311
I have list of Active Directory Users's Guid, I need to load a set of properties of those users for a specific reporting. To do this, if we make a bind for each Guid, then it will be a costly one. Whether with DirectorySearcher, can we provide multiple Guid(say 1000) as filter and load the properties?.
2013/07/02
[ "https://Stackoverflow.com/questions/17426311", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2376887/" ]
``` In [9]: pd.Series(df.Letter.values,index=df.Position).to_dict() Out[9]: {1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e'} ``` Speed comparion (using Wouter's method) ``` In [6]: df = pd.DataFrame(randint(0,10,10000).reshape(5000,2),columns=list('AB')) In [7]: %timeit dict(zip(df.A,df.B)) 1000 loops, best of 3: 1.27 ms per loop In [8]: %timeit pd.Series(df.A.values,index=df.B).to_dict() 1000 loops, best of 3: 987 us per loop ```
Here are two other ways tested with the following df. ``` df = pd.DataFrame(np.random.randint(0,10,10000).reshape(5000,2),columns=list('AB')) ``` using `to_records()` ``` dict(df.to_records(index=False)) ``` using `MultiIndex.from_frame()` ``` dict(pd.MultiIndex.from_frame(df)) ``` Time of each. ``` 24.6 ms ± 847 µs per loop (mean ± std. dev. of 7 runs, 10 loops each) 1.86 ms ± 11.6 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) ```
17,426,311
I have list of Active Directory Users's Guid, I need to load a set of properties of those users for a specific reporting. To do this, if we make a bind for each Guid, then it will be a costly one. Whether with DirectorySearcher, can we provide multiple Guid(say 1000) as filter and load the properties?.
2013/07/02
[ "https://Stackoverflow.com/questions/17426311", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2376887/" ]
TL;DR ===== ``` >>> import pandas as pd >>> df = pd.DataFrame({'Position':[1,2,3,4,5], 'Letter':['a', 'b', 'c', 'd', 'e']}) >>> dict(sorted(df.values.tolist())) # Sort of sorted... {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5} >>> from collections import OrderedDict >>> OrderedDict(df.values.tolist()) OrderedDict([('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5)]) ``` In Long ======= Explaining solution: `dict(sorted(df.values.tolist()))` Given: ``` df = pd.DataFrame({'Position':[1,2,3,4,5], 'Letter':['a', 'b', 'c', 'd', 'e']}) ``` [out]: ``` Letter Position 0 a 1 1 b 2 2 c 3 3 d 4 4 e 5 ``` Try: ``` # Get the values out to a 2-D numpy array, df.values ``` [out]: ``` array([['a', 1], ['b', 2], ['c', 3], ['d', 4], ['e', 5]], dtype=object) ``` Then optionally: ``` # Dump it into a list so that you can sort it using `sorted()` sorted(df.values.tolist()) # Sort by key ``` Or: ``` # Sort by value: from operator import itemgetter sorted(df.values.tolist(), key=itemgetter(1)) ``` [out]: ``` [['a', 1], ['b', 2], ['c', 3], ['d', 4], ['e', 5]] ``` Lastly, cast the list of list of 2 elements into a dict. ``` dict(sorted(df.values.tolist())) ``` [out]: ``` {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5} ``` --- Related ======= Answering @sbradbio comment: If there are multiple values for a specific key and you would like to keep all of them, it's the not the most efficient but the most intuitive way is: ``` from collections import defaultdict import pandas as pd multivalue_dict = defaultdict(list) df = pd.DataFrame({'Position':[1,2,4,4,4], 'Letter':['a', 'b', 'd', 'e', 'f']}) for idx,row in df.iterrows(): multivalue_dict[row['Position']].append(row['Letter']) ``` [out]: ``` >>> print(multivalue_dict) defaultdict(list, {1: ['a'], 2: ['b'], 4: ['d', 'e', 'f']}) ```
Here are two other ways tested with the following df. ``` df = pd.DataFrame(np.random.randint(0,10,10000).reshape(5000,2),columns=list('AB')) ``` using `to_records()` ``` dict(df.to_records(index=False)) ``` using `MultiIndex.from_frame()` ``` dict(pd.MultiIndex.from_frame(df)) ``` Time of each. ``` 24.6 ms ± 847 µs per loop (mean ± std. dev. of 7 runs, 10 loops each) 1.86 ms ± 11.6 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) ```
17,426,311
I have list of Active Directory Users's Guid, I need to load a set of properties of those users for a specific reporting. To do this, if we make a bind for each Guid, then it will be a costly one. Whether with DirectorySearcher, can we provide multiple Guid(say 1000) as filter and load the properties?.
2013/07/02
[ "https://Stackoverflow.com/questions/17426311", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2376887/" ]
I found a faster way to solve the problem, at least on realistically large datasets using: `df.set_index(KEY).to_dict()[VALUE]` Proof on 50,000 rows: ``` df = pd.DataFrame(np.random.randint(32, 120, 100000).reshape(50000,2),columns=list('AB')) df['A'] = df['A'].apply(chr) %timeit dict(zip(df.A,df.B)) %timeit pd.Series(df.A.values,index=df.B).to_dict() %timeit df.set_index('A').to_dict()['B'] ``` Output: ``` 100 loops, best of 3: 7.04 ms per loop # WouterOvermeire 100 loops, best of 3: 9.83 ms per loop # Jeff 100 loops, best of 3: 4.28 ms per loop # Kikohs (me) ```
``` dict (zip(data['position'], data['letter'])) ``` this will give you: ``` {1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e'} ```
19,966,453
I'm trying to select a node's value from XML in a table in MySQL/MariaDB Acoording to the MySQL docs, `following-sibling` is not supported as an XPath axis in MySQL. Is there an alternative? Docs: <http://dev.mysql.com/doc/refman/5.1/en/xml-functions.html#function_extractvalue> My XML structure looks something like: ``` <fields> <record> <id>10</id> <value>Foo</value> </record> <record> <id>20</id> <value>Bar</value> </record> </fields> ``` I need to find the record with ID 10, and get the text in `<value></value>`. Valid XPath would be `/fields/record/id[text()=10]/following-sibling::value/text()` which would return `Foo` What are my options? Thanks!
2013/11/13
[ "https://Stackoverflow.com/questions/19966453", "https://Stackoverflow.com", "https://Stackoverflow.com/users/565626/" ]
In this simple case you do not need the `following-sibling`. Try this instead: ``` /fields/record[id[text()=10]]/value/text() ``` Using the tag `id` inside the brackets leaves your context at `record` so that the following slash descends to the corresponding sibling of `id` (having the same parent as `id`).
I have this XML: ``` <List> <Attribute> <Id>Name</Id> <Value>JOHN</Value> </Attribute> </List> ``` Below is query: > > SELECT EXTRACTVALUE(xml, > "List/Attribute[Id[text()='NAME']]/Value") > FROM xx; > > > But getting error as Unknown column 'List/Attribute[Id[text()='COUNTRY']]/Value' in 'field list'
2,621,549
Actually, I know that $\int\_0^n \lfloor t \rfloor dt$ is $\frac{n(n-1)}{2}$. But I can't solve this simple problem. Can anybody help me? P.S. I'm seventeen, I'm studying in last year of high school, and I'm preparing for the national exams.
2018/01/26
[ "https://math.stackexchange.com/questions/2621549", "https://math.stackexchange.com", "https://math.stackexchange.com/users/427758/" ]
\begin{eqnarray\*} \int\_0^n 2x \lfloor x \rfloor dx = \sum\_{i=0}^{n-1} i \underbrace{\int\_{i}^{i+1} 2x \,dx}\_{x^2 \mid\_i^{i+1}=2i+1} = \underbrace{\sum\_{i=0}^{n-1} i (2i+1)}\_{\text{using} \sum\_{i=0}^{n-1} i^2=\frac{n(n-1)(2n-1)}{6} } = \frac{(n-1)n(n+1)}{3}. \end{eqnarray\*}
**hint:** $\displaystyle \int\_{0}^n = \displaystyle \int\_{0}^1 +\displaystyle \int\_{1}^2 +...+\displaystyle \int\_{n-1}^n$
273,520
If $\sum\_{n=1}^{\infty}a\_n$ converge, then $\sum\_{n=1}^{\infty}\sqrt[4]{a\_{n}^{5}}=\underset{n=1}{\overset{\infty}{\sum}}a\_{n}^{\frac{5}{4}}$ converge? Please verify answer below.
2013/01/09
[ "https://math.stackexchange.com/questions/273520", "https://math.stackexchange.com", "https://math.stackexchange.com/users/55682/" ]
Yes. Because $\sum a\_n$ converges, we know that the limit $\lim a\_n = 0$, by the Divergence Test. This means that $\exists N, \forall n > N, a\_n <1 $. It stands to reason then that $a\_n^{5/4} \le a\_n$ for all such $n>N$. By Direct Comparison, then, $\sum a\_n^{5/4}$ also converges. We cannot say $\sum a\_n^{5/4} < \sum a\_n$. Someone said that but it is untrue. It all depends on the front-end behavior. If for the first $N$ terms $a\_n^{5/4}$ is sufficiently larger than $a\_n$ then the inequality of the actual sum may be reversed. --- It doesnt matter if for any terms $a\_n<0$. If a term is odd then $a\_n^5$ is still odd. And the principle fourth root $a\_n^{5/4}$ is going to be a complex number where $a\_n^{5/4} = |a\_n|^{5/4} \frac{\sqrt{2}+i\sqrt{2}}{2}$ for all negative $a\_n$ The principle fourth root $a\_n^{5/4}$ for positive $a\_n$ is still positive and real. Simply break the series apart into two separate series of positive and negative $a\_n$ terms. We know that $\sum\_{a\_n>0} a\_n^{5/4}$ is going to converge as per the first part of this proof. It has fewer terms and therefore converges to a smaller sum. For the series $\sum\_{a\_n<0} a\_n^{5/4}$ we get the final sum $\frac{\sqrt{2}+i\sqrt{2}}{2} \sum\_{a\_n<0} |a\_n|^{5/4} $. Notice the sum is still going to be convergent as per the first part of this proof, but there is a complex scalar that was factored out. Thus, even for a series containing negative $a\_n$ terms, the sum $\sum a\_n^{5/4}$ is simply going to be the sum $\left(\sum\_{a\_n>0} a\_n^{5/4}\right) + \left(\frac{\sqrt{2}+i\sqrt{2}}{2} \sum\_{a\_n<0} |a\_n|^{5/4}\right) $ Each individual series is now a series of positive terms, each containing fewer terms than the original series and therefore each converges to a smaller sum. --- **Disclaimer** Im no expert in infinite series. They are not exactly intuitive. The problem is infinitely more complicated if you let $a\_n$ take any complex value.
Because $\sum\_{n=1}^{\infty}a\_{n}$ converge, then $a\_n\rightarrow0$, so for big $n$: $a\_{n}<1$, which implies $$\sum\_{n=1}^{\infty}a\_{n}^{\frac{5}{4}}<\sum\_{n=0}^{\infty}a\_{n}$$ so it's also converge
39,193,733
It is my developed project with target API 23. Now I'm using Studio 2.1.3 When I am trying to open this project the error show me like `Error:failed to find Build Tools revision 24.0.0 rc2 Install Build Tools 24.0.0 rc2 and sync project` But when I try to install, then a error message shown. It was a big project, I have to run it. How can I sync it and run it properly? Please help me, Thanks in advance.. Screenshot 1: this is the error message [![enter image description here](https://i.stack.imgur.com/29uSF.png)](https://i.stack.imgur.com/29uSF.png) Screenshot 2: when i click to install and sync then this error message has appeared [![enter image description here](https://i.stack.imgur.com/OFx3n.png)](https://i.stack.imgur.com/OFx3n.png)
2016/08/28
[ "https://Stackoverflow.com/questions/39193733", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5032484/" ]
Update the `android-sdk` tools to the newest version: `24.0.2` Change your Android Support libraries version like `appcompat` from `23.x.x` version to `24.2.0` If you would any problem with updating dependencies, check: <https://developer.android.com/studio/intro/update.html#sdk-manager> **Tip:** Try to avoid use in your project `alpha`,`preview` or `beta` versions of project dependencies. Hope it will help
Check your connection to google servers.Some countries like Iran should use VPN to connect. Hop it work
39,193,733
It is my developed project with target API 23. Now I'm using Studio 2.1.3 When I am trying to open this project the error show me like `Error:failed to find Build Tools revision 24.0.0 rc2 Install Build Tools 24.0.0 rc2 and sync project` But when I try to install, then a error message shown. It was a big project, I have to run it. How can I sync it and run it properly? Please help me, Thanks in advance.. Screenshot 1: this is the error message [![enter image description here](https://i.stack.imgur.com/29uSF.png)](https://i.stack.imgur.com/29uSF.png) Screenshot 2: when i click to install and sync then this error message has appeared [![enter image description here](https://i.stack.imgur.com/OFx3n.png)](https://i.stack.imgur.com/OFx3n.png)
2016/08/28
[ "https://Stackoverflow.com/questions/39193733", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5032484/" ]
Update the `android-sdk` tools to the newest version: `24.0.2` Change your Android Support libraries version like `appcompat` from `23.x.x` version to `24.2.0` If you would any problem with updating dependencies, check: <https://developer.android.com/studio/intro/update.html#sdk-manager> **Tip:** Try to avoid use in your project `alpha`,`preview` or `beta` versions of project dependencies. Hope it will help
Go to build.gradle(Module:app) and update the `buildToolsVersion '24.0.0 rc2'` to `buildToolsVersion '24.0.0'` or to the latest version
39,193,733
It is my developed project with target API 23. Now I'm using Studio 2.1.3 When I am trying to open this project the error show me like `Error:failed to find Build Tools revision 24.0.0 rc2 Install Build Tools 24.0.0 rc2 and sync project` But when I try to install, then a error message shown. It was a big project, I have to run it. How can I sync it and run it properly? Please help me, Thanks in advance.. Screenshot 1: this is the error message [![enter image description here](https://i.stack.imgur.com/29uSF.png)](https://i.stack.imgur.com/29uSF.png) Screenshot 2: when i click to install and sync then this error message has appeared [![enter image description here](https://i.stack.imgur.com/OFx3n.png)](https://i.stack.imgur.com/OFx3n.png)
2016/08/28
[ "https://Stackoverflow.com/questions/39193733", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5032484/" ]
At the top of your *module's* `build.gradle` file there's a specification which build tools the module uses. Fix it to latest. ``` buildToolsVersion "24.0.2" ```
Check your connection to google servers.Some countries like Iran should use VPN to connect. Hop it work
39,193,733
It is my developed project with target API 23. Now I'm using Studio 2.1.3 When I am trying to open this project the error show me like `Error:failed to find Build Tools revision 24.0.0 rc2 Install Build Tools 24.0.0 rc2 and sync project` But when I try to install, then a error message shown. It was a big project, I have to run it. How can I sync it and run it properly? Please help me, Thanks in advance.. Screenshot 1: this is the error message [![enter image description here](https://i.stack.imgur.com/29uSF.png)](https://i.stack.imgur.com/29uSF.png) Screenshot 2: when i click to install and sync then this error message has appeared [![enter image description here](https://i.stack.imgur.com/OFx3n.png)](https://i.stack.imgur.com/OFx3n.png)
2016/08/28
[ "https://Stackoverflow.com/questions/39193733", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5032484/" ]
At the top of your *module's* `build.gradle` file there's a specification which build tools the module uses. Fix it to latest. ``` buildToolsVersion "24.0.2" ```
Go to build.gradle(Module:app) and update the `buildToolsVersion '24.0.0 rc2'` to `buildToolsVersion '24.0.0'` or to the latest version
1,613,692
The way I understand the definition of a combination of a set is that, without repetition,for example, the combination of the set $\{1,2\}$ would be $(1,2)$, and not $(1,1)$, $(1,2)$ and $(2,2)$ because I thought I read that each element has to be unique. Is this the case? Also, What is the combination of a set that has only one element? like $\{2\}$ ? the empty set? or is it $(2,2)$ which would to violate the unique property, if uniqueness actually is a constraint. I'm not sure if it is or not because the web doesn't cover the topic well in a 'non mathematician can understand it' way.
2016/01/15
[ "https://math.stackexchange.com/questions/1613692", "https://math.stackexchange.com", "https://math.stackexchange.com/users/-1/" ]
$$\int\frac{u}{\left(a^2+u^2\right)^{\frac{3}{2}}}\space\text{d}u=$$ --- Substitute $s=a^2+u^2$ and $\text{d}s=2u\space\text{d}u$: --- $$\frac{1}{2}\int\frac{1}{s^{\frac{3}{2}}}\space\text{d}s=\frac{1}{2}\int s^{-\frac{3}{2}}\space\text{d}s=\frac{1}{2}\cdot-\frac{2}{\sqrt{s}}+\text{C}=-\frac{1}{\sqrt{a^2+u^2}}+\text{C}$$
Let $w=$ some function of $u$ for which $dw = u\,du$.
1,613,692
The way I understand the definition of a combination of a set is that, without repetition,for example, the combination of the set $\{1,2\}$ would be $(1,2)$, and not $(1,1)$, $(1,2)$ and $(2,2)$ because I thought I read that each element has to be unique. Is this the case? Also, What is the combination of a set that has only one element? like $\{2\}$ ? the empty set? or is it $(2,2)$ which would to violate the unique property, if uniqueness actually is a constraint. I'm not sure if it is or not because the web doesn't cover the topic well in a 'non mathematician can understand it' way.
2016/01/15
[ "https://math.stackexchange.com/questions/1613692", "https://math.stackexchange.com", "https://math.stackexchange.com/users/-1/" ]
Let $w=$ some function of $u$ for which $dw = u\,du$.
Besides the other answers, I would like to expose another way of doing it: $$\int \dfrac{x}{(a^2+x^2)^{3/2}} dx=-2\int \dfrac{1}{(a^2+x^2)^{1/4}}\cdot \dfrac {\dfrac{-x}{2} (a^2+x^2)^{-3/4}}{(a^2+x^2)^{1/2}} \, dx$$ We realise now that the second factor is the derivative of the first, so we use $f(x)=x$ and $g(x)=\dfrac{1}{(a^2+x^2)^{1/4}}$, to get $\int u$ $du= \dfrac{u^2}{2}$. Don't forget to multiply by the -2, by which we get $-u^2=-\dfrac{1}{(a^2+x^2)^{1/2}}$. Although I think this way to proceed is more intrincate than the other answers, it has the advantage of being generalizable: If $R, l \in \mathbb{R}$, $$\int \dfrac{x}{(R+x^2)^l} \, dx=\int \dfrac{1}{(R+x^2)^p}\cdot \dfrac{x}{(R+x^2)^{p+1}} \, dx$$ (here $p=\dfrac{l-1}{2}$) $$=\dfrac{-1}{2p} \int \dfrac{1}{(R+x^2)^{p}} \cdot \dfrac{-2px(R+x^2)^{p-1}}{(R+x^2)^{2p}} \, dx =\dfrac{-1}{2p} \cdot \dfrac{u^2}{2}=\dfrac{-1}{4p (R+x^2)^{2p}}$$ Recalling that $l=2p+1$, we finally get: $\dfrac{1}{(2-2l)(R+x^2)^{l-1}} + \text{Constant}$. Edit: I changed the $u$ of the OP by $x$ only for a matter of comfort.
1,613,692
The way I understand the definition of a combination of a set is that, without repetition,for example, the combination of the set $\{1,2\}$ would be $(1,2)$, and not $(1,1)$, $(1,2)$ and $(2,2)$ because I thought I read that each element has to be unique. Is this the case? Also, What is the combination of a set that has only one element? like $\{2\}$ ? the empty set? or is it $(2,2)$ which would to violate the unique property, if uniqueness actually is a constraint. I'm not sure if it is or not because the web doesn't cover the topic well in a 'non mathematician can understand it' way.
2016/01/15
[ "https://math.stackexchange.com/questions/1613692", "https://math.stackexchange.com", "https://math.stackexchange.com/users/-1/" ]
Let $w=$ some function of $u$ for which $dw = u\,du$.
You can take the solution as I've presented [here](https://math.stackexchange.com/questions/3057298/solving-used-real-based-methods-int-0x-fractk-lefttn-a-rightm-d): \begin{equation} \int\_0^x \frac{t^k}{\left(t^n + a\right)^m}\:dt= \frac{1}{n}a^{\frac{k + 1}{n} - m} \left[B\left(m - \frac{k + 1}{n}, \frac{k + 1}{n}\right) - B\left(m - \frac{k + 1}{n}, \frac{k + 1}{n}, \frac{1}{1 + ax^n} \right)\right] \end{equation} Here $a$ is $a^2$, $k = 1$, $m = \frac{3}{2}$, thus: \begin{align} \int\_0^x \frac{t}{\left(t^{2} + a^{2}\right)^{\frac{3}{2}}}\:dt &= \frac{1}{2}\left(a^2\right)^{\frac{1 + 1}{2} - \frac{3}{2}} \left[B\left(\frac{3}{2} - \frac{1 + 1}{2}, \frac{1 + 1}{2}\right) - B\left(\frac{3}{2} - \frac{1 + 1}{2}, \frac{1 + 1}{2}, \frac{1}{1 + a^2x^2} \right)\right] \\ &= \frac{1}{\left|a\right|}\left[B\left(\frac{1}{2}, 1\right) - B\left(\frac{1}{2},1, \frac{1}{1 + a^2x^2} \right) \right] \end{align} Using the relationship between the [Beta and the Gamma function](https://en.wikipedia.org/wiki/Beta_function#Relationship_between_gamma_function_and_beta_function) we find that: \begin{equation} B\left(\frac{1}{2},1 \right) = \frac{\Gamma\left(\frac{1}{2} \right)\Gamma(1)}{\Gamma\left(1 + \frac{3}{2}\right)} = \frac{\Gamma\left(\frac{1}{2} \right)\Gamma(1)}{\frac{1}{2}\Gamma\left(\frac{1}{2}\right)} = 2\Gamma(1) = 2 \end{equation} Thus, \begin{equation} \int\_0^x \frac{t}{\left(t^{2} + a^{2}\right)^{\frac{3}{2}}}\:dt = \frac{1}{\left|a\right|}\left[2 - B\left(\frac{1}{2},1, \frac{1}{1 + a^2x^2} \right) \right] \end{equation}
1,613,692
The way I understand the definition of a combination of a set is that, without repetition,for example, the combination of the set $\{1,2\}$ would be $(1,2)$, and not $(1,1)$, $(1,2)$ and $(2,2)$ because I thought I read that each element has to be unique. Is this the case? Also, What is the combination of a set that has only one element? like $\{2\}$ ? the empty set? or is it $(2,2)$ which would to violate the unique property, if uniqueness actually is a constraint. I'm not sure if it is or not because the web doesn't cover the topic well in a 'non mathematician can understand it' way.
2016/01/15
[ "https://math.stackexchange.com/questions/1613692", "https://math.stackexchange.com", "https://math.stackexchange.com/users/-1/" ]
$$\int\frac{u}{\left(a^2+u^2\right)^{\frac{3}{2}}}\space\text{d}u=$$ --- Substitute $s=a^2+u^2$ and $\text{d}s=2u\space\text{d}u$: --- $$\frac{1}{2}\int\frac{1}{s^{\frac{3}{2}}}\space\text{d}s=\frac{1}{2}\int s^{-\frac{3}{2}}\space\text{d}s=\frac{1}{2}\cdot-\frac{2}{\sqrt{s}}+\text{C}=-\frac{1}{\sqrt{a^2+u^2}}+\text{C}$$
Besides the other answers, I would like to expose another way of doing it: $$\int \dfrac{x}{(a^2+x^2)^{3/2}} dx=-2\int \dfrac{1}{(a^2+x^2)^{1/4}}\cdot \dfrac {\dfrac{-x}{2} (a^2+x^2)^{-3/4}}{(a^2+x^2)^{1/2}} \, dx$$ We realise now that the second factor is the derivative of the first, so we use $f(x)=x$ and $g(x)=\dfrac{1}{(a^2+x^2)^{1/4}}$, to get $\int u$ $du= \dfrac{u^2}{2}$. Don't forget to multiply by the -2, by which we get $-u^2=-\dfrac{1}{(a^2+x^2)^{1/2}}$. Although I think this way to proceed is more intrincate than the other answers, it has the advantage of being generalizable: If $R, l \in \mathbb{R}$, $$\int \dfrac{x}{(R+x^2)^l} \, dx=\int \dfrac{1}{(R+x^2)^p}\cdot \dfrac{x}{(R+x^2)^{p+1}} \, dx$$ (here $p=\dfrac{l-1}{2}$) $$=\dfrac{-1}{2p} \int \dfrac{1}{(R+x^2)^{p}} \cdot \dfrac{-2px(R+x^2)^{p-1}}{(R+x^2)^{2p}} \, dx =\dfrac{-1}{2p} \cdot \dfrac{u^2}{2}=\dfrac{-1}{4p (R+x^2)^{2p}}$$ Recalling that $l=2p+1$, we finally get: $\dfrac{1}{(2-2l)(R+x^2)^{l-1}} + \text{Constant}$. Edit: I changed the $u$ of the OP by $x$ only for a matter of comfort.
1,613,692
The way I understand the definition of a combination of a set is that, without repetition,for example, the combination of the set $\{1,2\}$ would be $(1,2)$, and not $(1,1)$, $(1,2)$ and $(2,2)$ because I thought I read that each element has to be unique. Is this the case? Also, What is the combination of a set that has only one element? like $\{2\}$ ? the empty set? or is it $(2,2)$ which would to violate the unique property, if uniqueness actually is a constraint. I'm not sure if it is or not because the web doesn't cover the topic well in a 'non mathematician can understand it' way.
2016/01/15
[ "https://math.stackexchange.com/questions/1613692", "https://math.stackexchange.com", "https://math.stackexchange.com/users/-1/" ]
$$\int\frac{u}{\left(a^2+u^2\right)^{\frac{3}{2}}}\space\text{d}u=$$ --- Substitute $s=a^2+u^2$ and $\text{d}s=2u\space\text{d}u$: --- $$\frac{1}{2}\int\frac{1}{s^{\frac{3}{2}}}\space\text{d}s=\frac{1}{2}\int s^{-\frac{3}{2}}\space\text{d}s=\frac{1}{2}\cdot-\frac{2}{\sqrt{s}}+\text{C}=-\frac{1}{\sqrt{a^2+u^2}}+\text{C}$$
You can take the solution as I've presented [here](https://math.stackexchange.com/questions/3057298/solving-used-real-based-methods-int-0x-fractk-lefttn-a-rightm-d): \begin{equation} \int\_0^x \frac{t^k}{\left(t^n + a\right)^m}\:dt= \frac{1}{n}a^{\frac{k + 1}{n} - m} \left[B\left(m - \frac{k + 1}{n}, \frac{k + 1}{n}\right) - B\left(m - \frac{k + 1}{n}, \frac{k + 1}{n}, \frac{1}{1 + ax^n} \right)\right] \end{equation} Here $a$ is $a^2$, $k = 1$, $m = \frac{3}{2}$, thus: \begin{align} \int\_0^x \frac{t}{\left(t^{2} + a^{2}\right)^{\frac{3}{2}}}\:dt &= \frac{1}{2}\left(a^2\right)^{\frac{1 + 1}{2} - \frac{3}{2}} \left[B\left(\frac{3}{2} - \frac{1 + 1}{2}, \frac{1 + 1}{2}\right) - B\left(\frac{3}{2} - \frac{1 + 1}{2}, \frac{1 + 1}{2}, \frac{1}{1 + a^2x^2} \right)\right] \\ &= \frac{1}{\left|a\right|}\left[B\left(\frac{1}{2}, 1\right) - B\left(\frac{1}{2},1, \frac{1}{1 + a^2x^2} \right) \right] \end{align} Using the relationship between the [Beta and the Gamma function](https://en.wikipedia.org/wiki/Beta_function#Relationship_between_gamma_function_and_beta_function) we find that: \begin{equation} B\left(\frac{1}{2},1 \right) = \frac{\Gamma\left(\frac{1}{2} \right)\Gamma(1)}{\Gamma\left(1 + \frac{3}{2}\right)} = \frac{\Gamma\left(\frac{1}{2} \right)\Gamma(1)}{\frac{1}{2}\Gamma\left(\frac{1}{2}\right)} = 2\Gamma(1) = 2 \end{equation} Thus, \begin{equation} \int\_0^x \frac{t}{\left(t^{2} + a^{2}\right)^{\frac{3}{2}}}\:dt = \frac{1}{\left|a\right|}\left[2 - B\left(\frac{1}{2},1, \frac{1}{1 + a^2x^2} \right) \right] \end{equation}
42,048,152
I have the data given below with other lines of data in a huge file to be more specific this is a .json file, I have stripped the whole file except for this one catch. **Data:** * ,"value":["ABC-DE","XYZ-MN"] * ,"value":["MNO-RS"],"sub\_id":01 * "value":"[\"NEW-XYZ\"]"," * ,"value":["ABC-DE","XYZ-MN","MNO-BE","FRS-ND"] I want the data to look like this * ,"value":["ABC-DE,XYZ-MN"]-Changed * ,"value":["MNO-RS"],"sub\_id":01-Unchanged * "value":"[\"NEW-XYZ\"]","-Unchnaged * ,"value":["ABC-DE,XYZ-MN,MNO-BE,FRS-ND"]-Changed So far I have this piece of code however it seems to be replacing the whole files "," with , and not the ones just within [] ``` sed 's/\(\[\|\","\|\]\)/\,/g' testfile_1.txt >testfile_2.txt ``` Any help would be great \*\*Note: Edited fourth condition Cheers.
2017/02/05
[ "https://Stackoverflow.com/questions/42048152", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2102955/" ]
That's tougher without the non-greedy matching perl regex offers, but this seems to do it. ``` sed -e 's/\([^\[]*\"[A-Z\-]*\)\",\"\(.*\)/\1,\2/' ```
Thank you for your contributions @clearlight Here is my solution to the problem with multiple occurrences; ``` sed -e ': a' -e 's/\(\[[^]]*\)","/\1,/' -e 't a' testfile_1.txt >testfile_2.txt ``` Using label 'a' till end of label 'a' pseudocode: ``` while (not end of line){ replace "," with ' } ```
26,781,785
I'm trying to create a batch file which asks a user a question with multiple (four) options. The options that the user chooses should trigger the batch file to ignore one of the four options. Lets say that the commands that I would normally want to run is ECHO "A", ECHO "B", ECHO "C", ECHO "D". If the person puts A in, I would want them to still run all the other commands except ECHO "A". Currently the solution i have come up with is the following ``` @echo off set /p choice="Do you want not to do: A, B, C or D? [A/B/C/D] " [A/B/C/D] if %choice%==A ( ECHO "B" ECHO "C" ECHO "D" EXIT /b ) else if %choice%==B ( ECHO "A" ECHO "C" ECHO "D" EXIT /b ) else if %choice%==C ( ECHO "A" ECHO "B" ECHO "D" EXIT /b ) else if %choice%==D ( ECHO "A" ECHO "B" ECHO "C" EXIT /b ) ELSE ( ECHO Please select A, B, C or D! EXIT /b ) ``` However as you can imagine, i am using the echo commands as an example/abstraction. The actual commands are longer. It seems more efficient to define the commands under A, B, C and D once and then tell the batch file not to doA, B, C or D depending the users choice. Maybe it's because I started working early today but I cannot think of an easier way to do this right now. So I hope to hear your ideas on how to make this batch script less clogged up.
2014/11/06
[ "https://Stackoverflow.com/questions/26781785", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Something like this : ``` @echo off setlocal enabledelayedexpansion set "$Command=A B C D" set /p "$choice=Do you want not to do: A, B, C or D? " set "$Command=!$Command:%$choice%=!" for %%a in (!$command!) do echo %%a ```
This should do the trick. After a "CALL" the batch "jumps back" and will do the next step: ``` @echo off set /p choice="Do you want not to do: A, B, C or D? [A/B/C/D] " [A/B/C/D] if %choice%==A ( CALL :B CALL :C CALL :D EXIT /b ) else if %choice%==B ( CALL :A CALL :C CALL :D EXIT /b ) else if %choice%==C ( CALL :A CALL :B CALL :D EXIT /b ) else if %choice%==D ( CALL :A CALL :B CALL :C EXIT /b ) ELSE ( ECHO Please select A, B, C or D! EXIT /b ) :A <Function here> GOTO :EOF :B <Function here> GOTO :EOF :C <Function here> GOTO :EOF :D <Function here> GOTO :EOF ```
26,781,785
I'm trying to create a batch file which asks a user a question with multiple (four) options. The options that the user chooses should trigger the batch file to ignore one of the four options. Lets say that the commands that I would normally want to run is ECHO "A", ECHO "B", ECHO "C", ECHO "D". If the person puts A in, I would want them to still run all the other commands except ECHO "A". Currently the solution i have come up with is the following ``` @echo off set /p choice="Do you want not to do: A, B, C or D? [A/B/C/D] " [A/B/C/D] if %choice%==A ( ECHO "B" ECHO "C" ECHO "D" EXIT /b ) else if %choice%==B ( ECHO "A" ECHO "C" ECHO "D" EXIT /b ) else if %choice%==C ( ECHO "A" ECHO "B" ECHO "D" EXIT /b ) else if %choice%==D ( ECHO "A" ECHO "B" ECHO "C" EXIT /b ) ELSE ( ECHO Please select A, B, C or D! EXIT /b ) ``` However as you can imagine, i am using the echo commands as an example/abstraction. The actual commands are longer. It seems more efficient to define the commands under A, B, C and D once and then tell the batch file not to doA, B, C or D depending the users choice. Maybe it's because I started working early today but I cannot think of an easier way to do this right now. So I hope to hear your ideas on how to make this batch script less clogged up.
2014/11/06
[ "https://Stackoverflow.com/questions/26781785", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
The idea in this code is that it only skips the one that you choose. ``` @echo off set /p choice="Do you want not to do: A, B, C or D? [A/B/C/D] " [A/B/C/D] if "%choice%"=="" ( ECHO Please select A, B, C or D! EXIT /b ) if not %choice%==A ( ECHO "A" ) if not %choice%==B ( ECHO "B" ) if not %choice%==C ( ECHO "C" ) if not %choice%==D ( ECHO "D" ) exit /b ```
Something like this : ``` @echo off setlocal enabledelayedexpansion set "$Command=A B C D" set /p "$choice=Do you want not to do: A, B, C or D? " set "$Command=!$Command:%$choice%=!" for %%a in (!$command!) do echo %%a ```
26,781,785
I'm trying to create a batch file which asks a user a question with multiple (four) options. The options that the user chooses should trigger the batch file to ignore one of the four options. Lets say that the commands that I would normally want to run is ECHO "A", ECHO "B", ECHO "C", ECHO "D". If the person puts A in, I would want them to still run all the other commands except ECHO "A". Currently the solution i have come up with is the following ``` @echo off set /p choice="Do you want not to do: A, B, C or D? [A/B/C/D] " [A/B/C/D] if %choice%==A ( ECHO "B" ECHO "C" ECHO "D" EXIT /b ) else if %choice%==B ( ECHO "A" ECHO "C" ECHO "D" EXIT /b ) else if %choice%==C ( ECHO "A" ECHO "B" ECHO "D" EXIT /b ) else if %choice%==D ( ECHO "A" ECHO "B" ECHO "C" EXIT /b ) ELSE ( ECHO Please select A, B, C or D! EXIT /b ) ``` However as you can imagine, i am using the echo commands as an example/abstraction. The actual commands are longer. It seems more efficient to define the commands under A, B, C and D once and then tell the batch file not to doA, B, C or D depending the users choice. Maybe it's because I started working early today but I cannot think of an easier way to do this right now. So I hope to hear your ideas on how to make this batch script less clogged up.
2014/11/06
[ "https://Stackoverflow.com/questions/26781785", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Something like this : ``` @echo off setlocal enabledelayedexpansion set "$Command=A B C D" set /p "$choice=Do you want not to do: A, B, C or D? " set "$Command=!$Command:%$choice%=!" for %%a in (!$command!) do echo %%a ```
This type of problems may be easily solved using an [array](https://stackoverflow.com/questions/10166386/arrays-linked-lists-and-other-data-structures-in-cmd-exe-batch-script/10167990#10167990); the code is clearer and more flexible. I also suggest you to use `choice` command instead of `set /P` in order to achieve this type of selections. ``` @echo off setlocal EnableDelayedExpansion rem Define all the options/commands set option[1]=ECHO "A" set option[2]=ECHO "B" set option[3]=ECHO "C" set option[4]=ECHO "D" choice /C ABCD /M "Do you want not to do: A, B, C or D" rem Eliminate the not wanted option set "option[%errorlevel%]=" rem Execute the remaining options for /F "tokens=1* delims==" %%a in ('set option[') do %%b ```
26,781,785
I'm trying to create a batch file which asks a user a question with multiple (four) options. The options that the user chooses should trigger the batch file to ignore one of the four options. Lets say that the commands that I would normally want to run is ECHO "A", ECHO "B", ECHO "C", ECHO "D". If the person puts A in, I would want them to still run all the other commands except ECHO "A". Currently the solution i have come up with is the following ``` @echo off set /p choice="Do you want not to do: A, B, C or D? [A/B/C/D] " [A/B/C/D] if %choice%==A ( ECHO "B" ECHO "C" ECHO "D" EXIT /b ) else if %choice%==B ( ECHO "A" ECHO "C" ECHO "D" EXIT /b ) else if %choice%==C ( ECHO "A" ECHO "B" ECHO "D" EXIT /b ) else if %choice%==D ( ECHO "A" ECHO "B" ECHO "C" EXIT /b ) ELSE ( ECHO Please select A, B, C or D! EXIT /b ) ``` However as you can imagine, i am using the echo commands as an example/abstraction. The actual commands are longer. It seems more efficient to define the commands under A, B, C and D once and then tell the batch file not to doA, B, C or D depending the users choice. Maybe it's because I started working early today but I cannot think of an easier way to do this right now. So I hope to hear your ideas on how to make this batch script less clogged up.
2014/11/06
[ "https://Stackoverflow.com/questions/26781785", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
The idea in this code is that it only skips the one that you choose. ``` @echo off set /p choice="Do you want not to do: A, B, C or D? [A/B/C/D] " [A/B/C/D] if "%choice%"=="" ( ECHO Please select A, B, C or D! EXIT /b ) if not %choice%==A ( ECHO "A" ) if not %choice%==B ( ECHO "B" ) if not %choice%==C ( ECHO "C" ) if not %choice%==D ( ECHO "D" ) exit /b ```
This should do the trick. After a "CALL" the batch "jumps back" and will do the next step: ``` @echo off set /p choice="Do you want not to do: A, B, C or D? [A/B/C/D] " [A/B/C/D] if %choice%==A ( CALL :B CALL :C CALL :D EXIT /b ) else if %choice%==B ( CALL :A CALL :C CALL :D EXIT /b ) else if %choice%==C ( CALL :A CALL :B CALL :D EXIT /b ) else if %choice%==D ( CALL :A CALL :B CALL :C EXIT /b ) ELSE ( ECHO Please select A, B, C or D! EXIT /b ) :A <Function here> GOTO :EOF :B <Function here> GOTO :EOF :C <Function here> GOTO :EOF :D <Function here> GOTO :EOF ```
26,781,785
I'm trying to create a batch file which asks a user a question with multiple (four) options. The options that the user chooses should trigger the batch file to ignore one of the four options. Lets say that the commands that I would normally want to run is ECHO "A", ECHO "B", ECHO "C", ECHO "D". If the person puts A in, I would want them to still run all the other commands except ECHO "A". Currently the solution i have come up with is the following ``` @echo off set /p choice="Do you want not to do: A, B, C or D? [A/B/C/D] " [A/B/C/D] if %choice%==A ( ECHO "B" ECHO "C" ECHO "D" EXIT /b ) else if %choice%==B ( ECHO "A" ECHO "C" ECHO "D" EXIT /b ) else if %choice%==C ( ECHO "A" ECHO "B" ECHO "D" EXIT /b ) else if %choice%==D ( ECHO "A" ECHO "B" ECHO "C" EXIT /b ) ELSE ( ECHO Please select A, B, C or D! EXIT /b ) ``` However as you can imagine, i am using the echo commands as an example/abstraction. The actual commands are longer. It seems more efficient to define the commands under A, B, C and D once and then tell the batch file not to doA, B, C or D depending the users choice. Maybe it's because I started working early today but I cannot think of an easier way to do this right now. So I hope to hear your ideas on how to make this batch script less clogged up.
2014/11/06
[ "https://Stackoverflow.com/questions/26781785", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
The idea in this code is that it only skips the one that you choose. ``` @echo off set /p choice="Do you want not to do: A, B, C or D? [A/B/C/D] " [A/B/C/D] if "%choice%"=="" ( ECHO Please select A, B, C or D! EXIT /b ) if not %choice%==A ( ECHO "A" ) if not %choice%==B ( ECHO "B" ) if not %choice%==C ( ECHO "C" ) if not %choice%==D ( ECHO "D" ) exit /b ```
This type of problems may be easily solved using an [array](https://stackoverflow.com/questions/10166386/arrays-linked-lists-and-other-data-structures-in-cmd-exe-batch-script/10167990#10167990); the code is clearer and more flexible. I also suggest you to use `choice` command instead of `set /P` in order to achieve this type of selections. ``` @echo off setlocal EnableDelayedExpansion rem Define all the options/commands set option[1]=ECHO "A" set option[2]=ECHO "B" set option[3]=ECHO "C" set option[4]=ECHO "D" choice /C ABCD /M "Do you want not to do: A, B, C or D" rem Eliminate the not wanted option set "option[%errorlevel%]=" rem Execute the remaining options for /F "tokens=1* delims==" %%a in ('set option[') do %%b ```
18,258,755
This feels like it should be simple but it's been driving me crazy. I've got a function `indent-or-expand` that I'd like to remap to `tab` but I simply can't get it to work (Emacs v24, OS X). The only help I've been able to get from Emacs itself is: > > error "To bind the key TAB, use \"\\t\", not [TAB]" > > > Doing `(global-set-key [\"\\t\"] 'indent-or-expand)` binds the function to `<"\t">` apparently (whatever that is), and every combination I've tried of `\`, `"`, `[``]`, and `(``)` has failed. I DID manage to bind the function to `t`, though...
2013/08/15
[ "https://Stackoverflow.com/questions/18258755", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2521092/" ]
In addition to what others have told you: 1. The Emacs error message you cite told you to use "\t", and if you use that you should be OK: (global-set-key "\t" 'indent-or-expand) 2. Be aware also that `TAB` is one thing and `<tab>` might be another thing. IOW, it depends what code your physical keyboard `Tab` key actually sends to Emacs. `TAB` is the tab character, and it i the same as ACSCII control character `C-i`, that is, `Control` + `i`, which has decimal integer value 9. `<tab>` is (in Emacs) a pseudo function key. (Most likely `TAB` is what you want. Use `C-h k` to see what your physical `Tab` key does.)
Use the `kbd` function, i.e.: ``` (global-set-key (kbd "TAB") ...) ```
47,343,419
So I am having trouble implementing this scenario: From the backend server, I am receving an html string, something along like this: ``` <ul><li><strong>Title1</strong> <br/> <a class=\"title1" href="title1-link">Title 1</a></li><li><strong>Title2</strong> <a class="title2" href="/title2-link">Title 2</a> ``` Normally, that would be fine when just using `dangerouslySetInnerHTML`. However, around the `a href` tags in the html, I need to wrap those in component like so: ``` <ModalLink href={'title'}> {Title} </ModalLink> ``` This is because when wrapping the `a` tags, the component essentially adds functionality on creating a new child window. I figured this is something you would need to implement on Regex, but I dont have the slightest idea where to begin.
2017/11/17
[ "https://Stackoverflow.com/questions/47343419", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4927657/" ]
You can deconstruct and extract the necessary values from your html string with regex and then use JSX instead of dangerouslySetInnerHtml. This component shows how to render your sample html string. ``` import React, { Component } from 'react' export default class App extends Component { render() { const html = `<ul><li><strong>Title1</strong><br/><a class="title1" href="/title1-link">Title 1</a></li><li><strong>Title2</strong><br/><a class="title2" href="/title2-link">Title 2</a></li></ul>` return ( <div> <ul> {html.match(/(<li>.*?<\/li>)/g).map( li => { const title = li.match(/<strong>(.*?)<\/strong>/)[1] const aTag = li.match(/<a.*?\/a>/)[0] const aClass = aTag.match(/class="(.*?)"/)[1] const href = aTag.match(/href="(.*?)"/)[1] const aText = aTag.match(/>(.*?)</)[1] return ( <li> <strong>{title}</strong> <br/> <a className={aClass} href={href}>{aText}</a> </li> ) })} </ul> </div> ) } } ``` From there you can simply wrap the a tag in your ModalLink component. I'm not sure this is exactly how you want to do that, but here is an example. ``` return ( <li> <strong>{title}</strong> <br/> <ModalLink href={href}> <a className={aClass} href={href}>{aText}</a> </ModalLink> </li> ) ``` `html.match(/(<li>.*?<\/li>)/g)` matches each `<li>...</li>` within the html string in an array, which can then be mapped. Then I extract the title, href, etc. out of each `<li>...</li>` using captures (the part within parentheses), which can then be used in JSX. [This answer](https://stackoverflow.com/questions/7124778/how-to-match-anything-up-until-this-sequence-of-characters-in-a-regular-expres) provides more detail on the regular expressions used.
Unfortunately I've never really used JavaScript which is why my answer will focus solely on the regex part of this question. (I've added an attempt a the bottom, though!) If I understand it correctly you want to replace the `<a href="someLink">someTitle</a>` tags with a `<ModalLink href={'someLink'}>someTitle</ModalLink>` in a way that the `someLink` and `someTitle` will be in the ModalLink tag, too - please do correct me if I'm understanding this in a wrong way Now look at this regex pattern here ``` <a [^<]+?href\s*=\s*("|')(.*?)\1>(.*?)<\/a> ``` it will match with any tag starting with `<a` and matches all characters until it finds an `href` (with any number of whitespaces between the href and the equation mark). Then it will search for a string between either `''` or `""` quotation marks and capture it in order to be used later on. It again matches until it finds the end of the tag `>` and captures whatever is between that end and the closing tag `<\a>`. If you now use some method for replacing the matched regex in the given string (*I'm sorry that I'm unfamiliar with how this would work in JavaScript*) and replace it with this pattern ``` <ModalLink href={'$2'}> {$3} </ModalLink> ``` You will get a result like this for the example html string you're receiving: ``` <ul><li><strong>Title1</strong> <br/> <ModalLink href={'title1-link'}> {Title 1} </ModalLink></li><li><strong>Title2</strong> <ModalLink href={'/title2-link'}> {Title 2} </ModalLink> ``` The $2 and $3 part of the replacing pattern are placeholders for the before mentioned captured parts which will just be replaced with them as you can see. *(They are capturing group 2 and 3 instead of starting with 1 simply because I've captured the quotation marks as capturing group 1 already)* You can try the pattern I've provided [here](https://regexr.com/3h73j). *While you can see and edit the regex and the string input on the upper part of the window, the replace pattern and its result can be found in the lower part.* --- EDIT: I've now tried my best with an online compiler to use JavaScript methods for replacing the tags with the tags and it seems to just work fine when using this method with the above mentioned regex: ``` var regexMatch = html.replace(/<a [^<>]+?href\s*=\s*("|')(.*?)\1[^<>]*?>(.*?)<\/a>/g, "<ModalLink href={'$2'}> {$3} </ModalLink>"); ``` In this case the `html` should of course be the html string in which you want to replace the `<a>` tags. You can also try [this online here](https://tio.run/##Xc/RTsMgFAbg@z7FCVlCW13J6qWUvoC7885qggzbbseyAC4mc89eod3UeQHJnwMfP1t5kE7Zfu@Xg9nocTxIC51/R6iA8g8UHHvBnbdmaMVj71GvODtH4K@WhV2CQulc1RA/HSDQWf1WndMS@2FH5rsQLkvBWTT/u@Uf9yLORHkB2RyvxDKKNIm1rW7151p61YXy8Q@F1XuUSqcsiE8vXDzf1FFqXF6FlZIvmqVFXmfNaprmtZgib4LJ2lsgfG02Eh/Ce3OFI12U9CTguLg7AWc/U0Gy@yRRZnAGdYGmTX/LZOP4DQ).
20
In French, some nouns are considered male and some female (le/la). Is there a way which can help me understand which grammatical gender to use with which noun?
2016/04/05
[ "https://languagelearning.stackexchange.com/questions/20", "https://languagelearning.stackexchange.com", "https://languagelearning.stackexchange.com/users/41/" ]
You can't, really ----------------- As I was learning French (English is my first language) the idea of gender of objects can be difficult to grasp. Genders are pretty much arbitrary and is something you just have to remember with each word (this means remembering it as *"une fenêtre"* rather than *"fenêtre"*). You can also always listen for a [*liaison*](https://en.wikipedia.org/wiki/Liaison_(French)). But usually when speaking with a fluent speaker this can be quite subtle, and difficult to listen to. General Rules ------------- That said, they are *some general* patterns which can be used to distinguish the gender of a noun but these **are not rules**, and are only generally followed: * Things originating in France *tend* to be feminine. e.g. `une crêpe`, or `une pizza` * Things originating in America *tend* to be masculine e.g. `Un burger` **BIG DISCLAIMER:** These **are not rules at all**, these are just observations I have made. --- ### Spelling Nouns ending in the following tend to be masculine: * `ge` * `le` (that aren't `-lle`, `-ole`, `-ale`, or `-ule`) * `me` * `re` (that isn't `-ure`) * `phe` * `age` source: @bleh Nouns ending in the following tend to be feminine: * `on` * `é` * `eur` [[source]](http://www.languageguide.org/french/grammar/gender/rule.html) Feminine nouns tend to have `e` at the end too but *many* masculine nouns also have `e` at the end --- While some genders *tend* to have certain endings, there isn't any definite cut and dry to determine the gender of a word without memorizing it. You *can* memorize some common endings though to make better guesses. [This question on French.SE](https://french.stackexchange.com/q/2616/7385) might provide more information on this.
### Yes; rules exist, but they predict gender mostly with at least 80% (but not 100%) accuracy.To see what the rules are, please see the Linguistics papers below. [The other answer here](https://languagelearning.stackexchange.com/a/45/90) troubles me because it does not state all the detailed rules discovered in the Linguistics papers below, and so may discourage French learners from benefitting from rules discovered by linguists by possibly misleading them into losing hope and relying on only memorisation. May I repeat my answer to [a similar question on FSE](https://french.stackexchange.com/a/16778/1995): See * [*Predictability in French gender attribution: A corpus analysis* by Roy Lyster](http://personnel.mcgill.ca/files/roy.lyster/Lyster2006_JFLS.pdf) I quote from the last paragraph (from p 22 of the PDF of 24 pages above) which answers your question more optimistically: > >   Gender attribution rules based on noun endings, given their reliability and > systematicity, are worthy of more attention in French reference books and French > L2 > classrooms. The foregoing corpus-based study confirmed that predictive rules for > gender attribution do exist and apply to as many as > 80 > per cent of the nearly > 10,000 > nouns included in the analysis. More importantly, classroom studies have demonstrated that gender attribution rules are both teachable and learnable. Regardless of > age, L2 > learners can benefit from form-focused instructional activities that promote > awareness of gender attribution rules and that provide opportunities for practice > in associating grammatical gender with orthographic representations of constituent > rhymes of literally thousands of nouns—both animate and inanimate alike. > > > * [*Adult L2 Acquisition of French Grammatical Gender: investigating sensitivity to phonological and morphological gender cues*](http://www.cs.cmu.edu/%7Ecsisso/docs/honoursThesis.pdf)
20
In French, some nouns are considered male and some female (le/la). Is there a way which can help me understand which grammatical gender to use with which noun?
2016/04/05
[ "https://languagelearning.stackexchange.com/questions/20", "https://languagelearning.stackexchange.com", "https://languagelearning.stackexchange.com/users/41/" ]
You can't, really ----------------- As I was learning French (English is my first language) the idea of gender of objects can be difficult to grasp. Genders are pretty much arbitrary and is something you just have to remember with each word (this means remembering it as *"une fenêtre"* rather than *"fenêtre"*). You can also always listen for a [*liaison*](https://en.wikipedia.org/wiki/Liaison_(French)). But usually when speaking with a fluent speaker this can be quite subtle, and difficult to listen to. General Rules ------------- That said, they are *some general* patterns which can be used to distinguish the gender of a noun but these **are not rules**, and are only generally followed: * Things originating in France *tend* to be feminine. e.g. `une crêpe`, or `une pizza` * Things originating in America *tend* to be masculine e.g. `Un burger` **BIG DISCLAIMER:** These **are not rules at all**, these are just observations I have made. --- ### Spelling Nouns ending in the following tend to be masculine: * `ge` * `le` (that aren't `-lle`, `-ole`, `-ale`, or `-ule`) * `me` * `re` (that isn't `-ure`) * `phe` * `age` source: @bleh Nouns ending in the following tend to be feminine: * `on` * `é` * `eur` [[source]](http://www.languageguide.org/french/grammar/gender/rule.html) Feminine nouns tend to have `e` at the end too but *many* masculine nouns also have `e` at the end --- While some genders *tend* to have certain endings, there isn't any definite cut and dry to determine the gender of a word without memorizing it. You *can* memorize some common endings though to make better guesses. [This question on French.SE](https://french.stackexchange.com/q/2616/7385) might provide more information on this.
Grammatical gender in French is pretty much arbitrary. There's not much to understand. Sorry. The usual tip when learning a language with (mostly) arbitrary grammatical gender like French or German is to **always learn the article with the noun**. When you learn the word for *car*, learn “la voiture” or “une voiture”. I think I the definite article is taught more often, but it has a downside of hiding the gender if the word starts with a vowel sound: better learn “un arbre” than “l'arbre”. Make sure you understand the pronunciation of the indefinite article though: “une arme” and “un arbre” only differ by the vowel sound (and the noun itself), since the E in *une* is silent and the N in *un* is sounded due to the *liaison* with the following vowel. Nouns that specifically designate male people (or animals) are masculine. Ditto for females and feminine nouns. (There are a few exceptions with professions that are traditionally gendered.) These nouns usually come in pairs, e.g. “père/mère” (father/mother), “acteur/actrice” (actor/actress), “chat/chatte” (male/female cat). With such pairs, apart from a few common words, the male and female forms differ only by a suffix, the female suffix always ends with `-e`, and the suffixes mostly follow the same patterns as for adjectives. Apart from that, you can't rely on the meaning of the word. Even if two nouns are synonyms, that doesn't make it more likely that they have the same gender. You can **sometimes** rely on the **ending** of the word. [Many word endings are strongly gendered](https://french.stackexchange.com/questions/2616/is-there-any-general-rule-to-determine-the-gender-of-a-noun-based-on-its-spellin/16781#16781). You may want to learn the most common ones, but I'm not convinced of the effectiveness of this approach: that's one more arbitrary classification to learn, and most classes have exceptions that you'd need to learn anyway. I think (but I have no data or personal experience to support it) that it would be more effective to learn nouns on an individual basis. Once you know a critical mass of nouns, you can start looking for patterns: if you're unsure about the gender of a noun, try to think of a few words with the same ending; if they all have the same gender then chances are that the noun you're wondering about has the same gender. What works better than endings is **suffixes**. Many suffixes have a single gender. If a word is built from a stem and a suffix, then once you recognize the suffix, you know the gender of the noun. For example, *-tion* is exclusively a feminine suffix, so any word built with that suffix is feminine, e.g. you don't need to learn words like *vasoconstriction* or *mobilisation* to know their gender. But there are a couple of words that just happen to end with those letters (e.g. *cation* is not *ca-* + *-tion*, *gestion* is not *ges-* + *-tion*), and they can be of either gender. (In this case, recognizing the suffix also tells you the pronunciation of the word: the suffix *-tion* is pronounced [sjɔ̃], but the letters “tion” are otherwise pronounced [tjɔ̃].)
20
In French, some nouns are considered male and some female (le/la). Is there a way which can help me understand which grammatical gender to use with which noun?
2016/04/05
[ "https://languagelearning.stackexchange.com/questions/20", "https://languagelearning.stackexchange.com", "https://languagelearning.stackexchange.com/users/41/" ]
You can't, really ----------------- As I was learning French (English is my first language) the idea of gender of objects can be difficult to grasp. Genders are pretty much arbitrary and is something you just have to remember with each word (this means remembering it as *"une fenêtre"* rather than *"fenêtre"*). You can also always listen for a [*liaison*](https://en.wikipedia.org/wiki/Liaison_(French)). But usually when speaking with a fluent speaker this can be quite subtle, and difficult to listen to. General Rules ------------- That said, they are *some general* patterns which can be used to distinguish the gender of a noun but these **are not rules**, and are only generally followed: * Things originating in France *tend* to be feminine. e.g. `une crêpe`, or `une pizza` * Things originating in America *tend* to be masculine e.g. `Un burger` **BIG DISCLAIMER:** These **are not rules at all**, these are just observations I have made. --- ### Spelling Nouns ending in the following tend to be masculine: * `ge` * `le` (that aren't `-lle`, `-ole`, `-ale`, or `-ule`) * `me` * `re` (that isn't `-ure`) * `phe` * `age` source: @bleh Nouns ending in the following tend to be feminine: * `on` * `é` * `eur` [[source]](http://www.languageguide.org/french/grammar/gender/rule.html) Feminine nouns tend to have `e` at the end too but *many* masculine nouns also have `e` at the end --- While some genders *tend* to have certain endings, there isn't any definite cut and dry to determine the gender of a word without memorizing it. You *can* memorize some common endings though to make better guesses. [This question on French.SE](https://french.stackexchange.com/q/2616/7385) might provide more information on this.
On a more practical note, [here](https://drive.google.com/file/d/0B5iHCwiV-v7RLVRLVVZxX0xQQnM/view?pref=2&pli=1) is a cheat sheet for french gender, and [the accompanying article](http://www.languagecrawler.com/2015/06/cheat-sheet-for-learning-gender-of.html) suggests that *"glancing at this seven-page chart every once in a while helped solidify things"*.
20
In French, some nouns are considered male and some female (le/la). Is there a way which can help me understand which grammatical gender to use with which noun?
2016/04/05
[ "https://languagelearning.stackexchange.com/questions/20", "https://languagelearning.stackexchange.com", "https://languagelearning.stackexchange.com/users/41/" ]
You can't, really ----------------- As I was learning French (English is my first language) the idea of gender of objects can be difficult to grasp. Genders are pretty much arbitrary and is something you just have to remember with each word (this means remembering it as *"une fenêtre"* rather than *"fenêtre"*). You can also always listen for a [*liaison*](https://en.wikipedia.org/wiki/Liaison_(French)). But usually when speaking with a fluent speaker this can be quite subtle, and difficult to listen to. General Rules ------------- That said, they are *some general* patterns which can be used to distinguish the gender of a noun but these **are not rules**, and are only generally followed: * Things originating in France *tend* to be feminine. e.g. `une crêpe`, or `une pizza` * Things originating in America *tend* to be masculine e.g. `Un burger` **BIG DISCLAIMER:** These **are not rules at all**, these are just observations I have made. --- ### Spelling Nouns ending in the following tend to be masculine: * `ge` * `le` (that aren't `-lle`, `-ole`, `-ale`, or `-ule`) * `me` * `re` (that isn't `-ure`) * `phe` * `age` source: @bleh Nouns ending in the following tend to be feminine: * `on` * `é` * `eur` [[source]](http://www.languageguide.org/french/grammar/gender/rule.html) Feminine nouns tend to have `e` at the end too but *many* masculine nouns also have `e` at the end --- While some genders *tend* to have certain endings, there isn't any definite cut and dry to determine the gender of a word without memorizing it. You *can* memorize some common endings though to make better guesses. [This question on French.SE](https://french.stackexchange.com/q/2616/7385) might provide more information on this.
The best way to learn the grammatical gender is by practice and by using a French dictionary where *nf* refers to "nom féminin" (feminine noun) and *nm* refers to "nom musculin" (masculine noun). Please note that the grammatical gender is sometimes confusing. I speak French and Arabic (native language), and there are some objects which are feminine in Arabic and masculine in French e.g. airplane, and vice versa e.g. chair.
20
In French, some nouns are considered male and some female (le/la). Is there a way which can help me understand which grammatical gender to use with which noun?
2016/04/05
[ "https://languagelearning.stackexchange.com/questions/20", "https://languagelearning.stackexchange.com", "https://languagelearning.stackexchange.com/users/41/" ]
### Yes; rules exist, but they predict gender mostly with at least 80% (but not 100%) accuracy.To see what the rules are, please see the Linguistics papers below. [The other answer here](https://languagelearning.stackexchange.com/a/45/90) troubles me because it does not state all the detailed rules discovered in the Linguistics papers below, and so may discourage French learners from benefitting from rules discovered by linguists by possibly misleading them into losing hope and relying on only memorisation. May I repeat my answer to [a similar question on FSE](https://french.stackexchange.com/a/16778/1995): See * [*Predictability in French gender attribution: A corpus analysis* by Roy Lyster](http://personnel.mcgill.ca/files/roy.lyster/Lyster2006_JFLS.pdf) I quote from the last paragraph (from p 22 of the PDF of 24 pages above) which answers your question more optimistically: > >   Gender attribution rules based on noun endings, given their reliability and > systematicity, are worthy of more attention in French reference books and French > L2 > classrooms. The foregoing corpus-based study confirmed that predictive rules for > gender attribution do exist and apply to as many as > 80 > per cent of the nearly > 10,000 > nouns included in the analysis. More importantly, classroom studies have demonstrated that gender attribution rules are both teachable and learnable. Regardless of > age, L2 > learners can benefit from form-focused instructional activities that promote > awareness of gender attribution rules and that provide opportunities for practice > in associating grammatical gender with orthographic representations of constituent > rhymes of literally thousands of nouns—both animate and inanimate alike. > > > * [*Adult L2 Acquisition of French Grammatical Gender: investigating sensitivity to phonological and morphological gender cues*](http://www.cs.cmu.edu/%7Ecsisso/docs/honoursThesis.pdf)
On a more practical note, [here](https://drive.google.com/file/d/0B5iHCwiV-v7RLVRLVVZxX0xQQnM/view?pref=2&pli=1) is a cheat sheet for french gender, and [the accompanying article](http://www.languagecrawler.com/2015/06/cheat-sheet-for-learning-gender-of.html) suggests that *"glancing at this seven-page chart every once in a while helped solidify things"*.
20
In French, some nouns are considered male and some female (le/la). Is there a way which can help me understand which grammatical gender to use with which noun?
2016/04/05
[ "https://languagelearning.stackexchange.com/questions/20", "https://languagelearning.stackexchange.com", "https://languagelearning.stackexchange.com/users/41/" ]
### Yes; rules exist, but they predict gender mostly with at least 80% (but not 100%) accuracy.To see what the rules are, please see the Linguistics papers below. [The other answer here](https://languagelearning.stackexchange.com/a/45/90) troubles me because it does not state all the detailed rules discovered in the Linguistics papers below, and so may discourage French learners from benefitting from rules discovered by linguists by possibly misleading them into losing hope and relying on only memorisation. May I repeat my answer to [a similar question on FSE](https://french.stackexchange.com/a/16778/1995): See * [*Predictability in French gender attribution: A corpus analysis* by Roy Lyster](http://personnel.mcgill.ca/files/roy.lyster/Lyster2006_JFLS.pdf) I quote from the last paragraph (from p 22 of the PDF of 24 pages above) which answers your question more optimistically: > >   Gender attribution rules based on noun endings, given their reliability and > systematicity, are worthy of more attention in French reference books and French > L2 > classrooms. The foregoing corpus-based study confirmed that predictive rules for > gender attribution do exist and apply to as many as > 80 > per cent of the nearly > 10,000 > nouns included in the analysis. More importantly, classroom studies have demonstrated that gender attribution rules are both teachable and learnable. Regardless of > age, L2 > learners can benefit from form-focused instructional activities that promote > awareness of gender attribution rules and that provide opportunities for practice > in associating grammatical gender with orthographic representations of constituent > rhymes of literally thousands of nouns—both animate and inanimate alike. > > > * [*Adult L2 Acquisition of French Grammatical Gender: investigating sensitivity to phonological and morphological gender cues*](http://www.cs.cmu.edu/%7Ecsisso/docs/honoursThesis.pdf)
The best way to learn the grammatical gender is by practice and by using a French dictionary where *nf* refers to "nom féminin" (feminine noun) and *nm* refers to "nom musculin" (masculine noun). Please note that the grammatical gender is sometimes confusing. I speak French and Arabic (native language), and there are some objects which are feminine in Arabic and masculine in French e.g. airplane, and vice versa e.g. chair.
20
In French, some nouns are considered male and some female (le/la). Is there a way which can help me understand which grammatical gender to use with which noun?
2016/04/05
[ "https://languagelearning.stackexchange.com/questions/20", "https://languagelearning.stackexchange.com", "https://languagelearning.stackexchange.com/users/41/" ]
Grammatical gender in French is pretty much arbitrary. There's not much to understand. Sorry. The usual tip when learning a language with (mostly) arbitrary grammatical gender like French or German is to **always learn the article with the noun**. When you learn the word for *car*, learn “la voiture” or “une voiture”. I think I the definite article is taught more often, but it has a downside of hiding the gender if the word starts with a vowel sound: better learn “un arbre” than “l'arbre”. Make sure you understand the pronunciation of the indefinite article though: “une arme” and “un arbre” only differ by the vowel sound (and the noun itself), since the E in *une* is silent and the N in *un* is sounded due to the *liaison* with the following vowel. Nouns that specifically designate male people (or animals) are masculine. Ditto for females and feminine nouns. (There are a few exceptions with professions that are traditionally gendered.) These nouns usually come in pairs, e.g. “père/mère” (father/mother), “acteur/actrice” (actor/actress), “chat/chatte” (male/female cat). With such pairs, apart from a few common words, the male and female forms differ only by a suffix, the female suffix always ends with `-e`, and the suffixes mostly follow the same patterns as for adjectives. Apart from that, you can't rely on the meaning of the word. Even if two nouns are synonyms, that doesn't make it more likely that they have the same gender. You can **sometimes** rely on the **ending** of the word. [Many word endings are strongly gendered](https://french.stackexchange.com/questions/2616/is-there-any-general-rule-to-determine-the-gender-of-a-noun-based-on-its-spellin/16781#16781). You may want to learn the most common ones, but I'm not convinced of the effectiveness of this approach: that's one more arbitrary classification to learn, and most classes have exceptions that you'd need to learn anyway. I think (but I have no data or personal experience to support it) that it would be more effective to learn nouns on an individual basis. Once you know a critical mass of nouns, you can start looking for patterns: if you're unsure about the gender of a noun, try to think of a few words with the same ending; if they all have the same gender then chances are that the noun you're wondering about has the same gender. What works better than endings is **suffixes**. Many suffixes have a single gender. If a word is built from a stem and a suffix, then once you recognize the suffix, you know the gender of the noun. For example, *-tion* is exclusively a feminine suffix, so any word built with that suffix is feminine, e.g. you don't need to learn words like *vasoconstriction* or *mobilisation* to know their gender. But there are a couple of words that just happen to end with those letters (e.g. *cation* is not *ca-* + *-tion*, *gestion* is not *ges-* + *-tion*), and they can be of either gender. (In this case, recognizing the suffix also tells you the pronunciation of the word: the suffix *-tion* is pronounced [sjɔ̃], but the letters “tion” are otherwise pronounced [tjɔ̃].)
On a more practical note, [here](https://drive.google.com/file/d/0B5iHCwiV-v7RLVRLVVZxX0xQQnM/view?pref=2&pli=1) is a cheat sheet for french gender, and [the accompanying article](http://www.languagecrawler.com/2015/06/cheat-sheet-for-learning-gender-of.html) suggests that *"glancing at this seven-page chart every once in a while helped solidify things"*.