问:
Get vector of Tuesdays, but if Tuesday falls on a holiday, then replace it with Wednesday in R
I would like to find all of the Tuesdays between two dates. But if the Tuesday falls on a user-defined list of holidays, then I would like Wednesday instead.

This code works in my tests, but it is pretty janky and I am afraid it will fail silently.

```<code>low.date <- "1996-01-01"
high.date <- "1997-01-01"
holidays = c("01-01", "07-04", "12-25")
tues <- seq(as.Date(low.date), as.Date(high.date), by = 1)
tues <- subset(tues, format(tues, "%a") == "Tue")
tues <- ifelse(format(tues, "%m-%d") %in% holidays, tues + 1, tues)
tues <- as.Date(tues, origin = "1970-01-01")
</code>```

Thanks! I see answers pointing to the timeDate package, but I only see methods for finding business days or holidays. Is there a cleaner/safer logic than what I'm using?

答:
POSIXlt in the base package gives you access to wday as a number, which is a little safer since names of days change from system to system.

```<code>low.date <- "1996-01-01"
high.date <- "1997-01-01"
holidays <- c("01-01", "07-04", "12-25")

all.days <- seq(as.Date(low.date), as.Date(high.date), by = "day")

# Tuesday is Day 2 of the week
all.tues <- all.days[as.POSIXlt(all.days)$wday == 2]
tues.holidays <- format(all.tues, "%m-%d") %in% holidays
all.tues[tues.holidays] <- all.tues[tues.holidays] + 1
</code>```

Body:
I would like to find all of the Tuesdays between two dates. But if the Tuesday falls on a user-defined list of holidays, then I would like Wednesday instead.

This code works in my tests, but it is pretty janky and I am afraid it will fail silently.

low.date <- "1996-01-01"
high.date <- "1997-01-01"
holidays = c("01-01", "07-04", "12-25")
tues <- seq(as.Date(low.date), as.Date(high.date), by = 1)
tues <- subset(tues, format(tues, "%a") == "Tue")
tues <- ifelse(format(tues, "%m-%d") %in% holidays, tues + 1, tues)
tues <- as.Date(tues, origin = "1970-01-01")

Thanks! I see answers pointing to the timeDate package, but I only see methods for finding business days or holidays. Is there a cleaner/safer logic than what I'm using?

Body:
POSIXlt in the base package gives you access to wday as a number, which is a little safer since names of days change from system to system.

low.date <- "1996-01-01"
high.date <- "1997-01-01"
holidays <- c("01-01", "07-04", "12-25")

all.days <- seq(as.Date(low.date), as.Date(high.date), by = "day")

# Tuesday is Day 2 of the week
all.tues <- all.days[as.POSIXlt(all.days)$wday == 2]
tues.holidays <- format(all.tues, "%m-%d") %in% holidays
all.tues[tues.holidays] <- all.tues[tues.holidays] + 1


来源: stackexchange

问:
Can I run a Azure function once on a specific date triggered by my asp.net mvc site?
I know I can create a scheduled Azure function to run on a schedule. But what I want is to be able to run a Azure function once given a specific date/time I pass it, along with some data parameters.

Ex. I'm scheduling classes in my site and I want to email out all students when the class is over. So when the class is created for Monday October 9th @ 4:00PM I want to send a message to trigger my Azure function on that same day, but like 1 hour later at 5:00PM. And I want to pass it some info like the class id or something. I also want to be able to remove this queued trigger if the class is canceled.

Is this possible in Azure and my ASP.Net MVC site?

答:
My classes might be scheduled upto 30 days ahead of the current date.

Per my understanding, you could also leverage the Scheduled messages from Azure Service Bus and set the ScheduledEnqueueTimeUtc property for your message. For more details about triggering the service bus queue message, you could follow Azure Functions Service Bus bindings. For sending the message, you could install the WindowsAzure.ServiceBus in your MVC application and leverage QueueClient.ScheduleMessageAsync for sending scheduled message and QueueClient.CancelScheduledMessageAsync for cancelling the scheduled message. Moreover, you could follow the code snippet in this issue.

ContentLicense: CC BY-SA 3.0


问:
Implementing an interface through a subset of its methods
I have a C++ interface with two methods. Any class implementing this interface need to implement at least one of the two methods but may define both. It is however not necessary to define both. What is the best pattern to use in such situation ?</p>

答:
Something like following:</p>

```<code>class MyInterface
{
public:
  virtual ~MyInterface() {}

  virtual void foo() = 0;
  virtual void bar() = 0;
};

class MyAbstractClass :  public MyInterface
{
public:
  virtual ~MyAbstractClass();

  // Provide implementation for foo or bar
  virtual void foo() override { }
  virtual void bar() override { }
};

class MyNewClass : public MyAbstractClass
{
   // Implement either of foo or bar or can be both
};
</code>```

Body:
Something like following:

class MyInterface
{
public:
  virtual ~MyInterface() {}

  virtual void foo() = 0;
  virtual void bar() = 0;
};

class MyAbstractClass :  public MyInterface
{
public:
  virtual ~MyAbstractClass();

  // Provide implementation for foo or bar
  virtual void foo() override { }
  virtual void bar() override { }
};

class MyNewClass : public MyAbstractClass
{
   // Implement either of foo or bar or can be both
};


问:
How to set keyboard shortcuts to jump to beginning/end of line?
I can see that Ctrl+left/right jumps to the beginning/end of line. How to change this to Cmd+left/right arrow?

答:
explained in https://aaronaddleman.com/articles/hexcodes-and-iterm/

you can use xxd -psd to get key hex code.

ContentLicense: CC BY-SA 4.0


问:
How the GNU builtin function `__builtin_unreachable ` works in this code snippet?
I have a code snippet in my project in which the __builtin_unreachable function has been used but I don't know why it is needed here.

And I read from GNU __builtin_unreachable, it seems that the __builtin_unreachable function is used to inform the compiler this line will never be reached during the CPU run time, so that a lot of complains in compilation can be prevented in advance. But I am not understood why this feature is needed in this code snippet, it seems nothing will happen by removing the __builtin_unreachable.

```<code># define ATHCONTAINERS_ASSUME(x) do { if (!(x)) __builtin_unreachable(); } while(0)

inline
void*
AuxVectorData::Cache::getDataArray (SG::auxid_t auxid,
                                    AuxVectorData& parent)
{
  // This function is important for performance.
  // Be careful when changing it.

  void* ptr = cachePtr (auxid);
  if (ATHCONTAINERS_UNLIKELY (ptr == 0)) {
    // We don't have the variable cached.
    // Call the out-of-line routine to get it cached.
    ptr = parent.getDataOol (auxid, false);

    // These inform the compiler of what the previous call did.
    // They tell the optimizer that it can now assume that this cache
    // entry is valid.
    ATHCONTAINERS_ASSUME (ptr != 0);
    ATHCONTAINERS_ASSUME (cachePtr (auxid) != 0);
    ATHCONTAINERS_ASSUME (cachePtr (auxid) == ptr);
  }
  return ptr;
}
</code>```

答:
ATHCONTAINERS_ASSUME tells the compiler that its argument x cannot be false.  This relieves the compiler from having to generate any code to accommodate the possibility that x is false.  For example, when the compiler sees ATHCONTAINERS_ASSUME (ptr != 0) it can assume ptr is not null, and any code which contradicts that assumption can be optimized away, as it would be undefined behavior.

For example, since getDataArray() is inline, the compiler can know at every call site that the returned pointer will never be null.  So if a caller does this:

```<code>if (void* p = cache.getDataArray(aux, parent))
    memcpy(p, "OK", 2);
</code>```

The compiler can generate code which directly writes "OK" without performing the null check.

Body:
I have a code snippet in my project in which the __builtin_unreachable function has been used but I don't know why it is needed here.

And I read from GNU __builtin_unreachable, it seems that the __builtin_unreachable function is used to inform the compiler this line will never be reached during the CPU run time, so that a lot of complains in compilation can be prevented in advance. But I am not understood why this feature is needed in this code snippet, it seems nothing will happen by removing the __builtin_unreachable.

# define ATHCONTAINERS_ASSUME(x) do { if (!(x)) __builtin_unreachable(); } while(0)

inline
void*
AuxVectorData::Cache::getDataArray (SG::auxid_t auxid,
                                    AuxVectorData& parent)
{
  // This function is important for performance.
  // Be careful when changing it.

  void* ptr = cachePtr (auxid);
  if (ATHCONTAINERS_UNLIKELY (ptr == 0)) {
    // We don't have the variable cached.
    // Call the out-of-line routine to get it cached.
    ptr = parent.getDataOol (auxid, false);

    // These inform the compiler of what the previous call did.
    // They tell the optimizer that it can now assume that this cache
    // entry is valid.
    ATHCONTAINERS_ASSUME (ptr != 0);
    ATHCONTAINERS_ASSUME (cachePtr (auxid) != 0);
    ATHCONTAINERS_ASSUME (cachePtr (auxid) == ptr);
  }
  return ptr;
}

Body:
ATHCONTAINERS_ASSUME tells the compiler that its argument x cannot be false.  This relieves the compiler from having to generate any code to accommodate the possibility that x is false.  For example, when the compiler sees ATHCONTAINERS_ASSUME (ptr != 0) it can assume ptr is not null, and any code which contradicts that assumption can be optimized away, as it would be undefined behavior.

For example, since getDataArray() is inline, the compiler can know at every call site that the returned pointer will never be null.  So if a caller does this:

if (void* p = cache.getDataArray(aux, parent))
    memcpy(p, "OK", 2);

The compiler can generate code which directly writes "OK" without performing the null check.


答:
You should transform the IN clauses to INNER JOIN clauses.

You can transform a query like this one:

```<code>SELECT  foo
FROM    bar
WHERE bar.stuff IN
       (SELECT  stuff FROM asdf)
</code>```

Into a query like this other one:

```<code>SELECT  b.foo
FROM    (
        SELECT  DISTINCT stuff
        FROM    asdf ) a
JOIN    bar b
ON      b.stuff = a.stuff
</code>```

You will gain a lot of performance.

As the php generate the query, try some kind of trick like a temporary table for the items inside the IN clause. Always try to avoid the IN clauses if you can, because they are very time consuming.

ContentLicense: CC BY-SA 2.5

Title: MySQL Query IN() Clause Slow on Indexed Column

Body:
I Have a MySQL query that is being generated by a PHP script, the query will look something like this:

SELECT * FROM Recipe_Data WHERE 404_Without_200 = 0 AND Failures_Without_Success = 0 AND RHD_No IN (10, 24, 34, 41, 43, 51, 57, 59, 61, 67, 84, 90, 272, 324, 402, 405, 414, 498, 500, 501, 510, 559, 562, 595, 632, 634, 640, 643, 647, 651, 703, 714, 719, 762, 765, 776, 796, 812, 814, 815, 822, 848, 853, 855, 858, 866, 891, 920, 947, 956, 962, 968, 1049, 1054, 1064, 1065, 1070, 1100, 1113, 1119, 1130, 1262, 1287, 1292, 1313, 1320, 1327, 1332, 1333, 1335, 1340, 1343, 1344, 1346, 1349, 1352, 1358, 1362, 1365, 1482, 1495, 1532, 1533, 1537, 1549, 1550, 1569, 1571, 1573, 1574, 1596, 1628, 1691, 1714, 1720, 1735, 1755, 1759, 1829, 1837, 1844, 1881, 1919, 2005, 2022, 2034, 2035, 2039, 2054, 2076, 2079, 2087, 2088, 2089, 2090, 2091, 2092, 2154, 2155, 2156, 2157, 2160, 2162, 2164, 2166, 2169, 2171, 2174, 2176, 2178, 2179, 2183, 2185, 2186, 2187, 2201, 2234, 2236, 2244, 2245, 2250, 2255, 2260, 2272, 2280, 2281, 2282, 2291, 2329, 2357, 2375, 2444, 2451, 2452, 2453, 2454, 2456, 2457, 2460, 2462, 2464, 2465, 2467, 2468, 2469, 2470, 2473, 2474, 2481, 2485, 2487, 2510, 2516, 2519, 2525, 2540, 2545, 2547, 2553, 2571, 2579, 2580, 2587, 2589, 2597, 2602, 2611, 2629, 2660, 2662, 2700, 2756, 2825, 2833, 2835, 2858, 2958, 2963, 2964, 3009, 3090, 3117, 3118, 3120, 3121, 3122, 3123, 3126, 3127, 3129, 3130, 3133, 3135, 3137, 3138, 3139, 3141, 3142, 3145, 3146, 3147, 3151, 3152, 3155, 3193, 3201, 3204, 3219, 3221, 3222, 3223, 3224, 3225, 3226, 3227, 3228, 3229, 3231, 3232, 3233, 3234, 3235, 3237, 3239, 3246, 3250, 3253, 3259, 3261, 3291, 3315, 3328, 3377, 3381, 3383, 3384, 3385, 3387, 3388, 3389, 3390, 3396, 3436, 3463, 3465, 3467, 3470, 3471, 3484, 3507, 3515, 3554, 3572, 3641, 3672, 3683, 3689, 3690, 3692, 3693, 3694, 3697, 3698, 3705, 3711, 3713, 3715, 3716, 3717, 3719, 3720, 3722, 3726, 3727, 3732, 3737, 3763, 3767, 3770, 3771, 3772, 3773, 3803, 3810, 3812, 3816, 3846, 3847, 3848, 3851, 3874, 3882, 3902, 3903, 3906, 3908, 3916, 3924, 3967, 3987, 4006, 4030, 4043, 4045, 4047, 4058, 4067, 4107, 4108, 4114, 4115, 4131, 4132, 4133, 4137, 4138, 4139, 4140, 4141, 4142, 4146, 4150, 4151, 4152, 4153, 4157, 4158, 4160, 4163, 4166, 4167, 4171, 4179, 4183, 4221, 4225, 4242, 4257, 4435, 4437, 4438, 4443, 4446, 4449, 4450, 4451, 4452, 4454, 4460, 4550, 4557, 4618, 4731, 4775, 4804, 4972, 5025, 5026, 5039, 5042, 5294, 5578, 5580, 5599, 5602, 5649, 5726, 5779, 5783, 5931, 5934, 5936, 5939, 5940, 5941, 5978, 6044, 6056, 6113, 6116, 6118, 6122, 6123, 6125, 6127, 6128, 6129, 6130, 6131, 6135, 6141, 6145, 6147, 6150, 6152, 6153, 6154, 6160, 6166, 6169);

The column RHD_No is the primary key for this database, and there are about 400,000 rows total. The problem is, the query is extremely slow, it's often around 2 seconds, but I've seen it get as long as 10.

When I try to explain the query, everything seems like it should be fine:

+----+-------------+-------------+-------+---------------+---------+---------+------+------+-------------+
| id | select_type | table       | type  | possible_keys | key     | key_len | ref  | rows | Extra       |
+----+-------------+-------------+-------+---------------+---------+---------+------+------+-------------+
|  1 | SIMPLE      | Recipe_Data | range | PRIMARY       | PRIMARY | 4       | NULL |  420 | Using where |
+----+-------------+-------------+-------+---------------+---------+---------+------+------+-------------+

When I profile the query I get:

mysql> show profile;
+--------------------------------+----------+
| Status                         | Duration |
+--------------------------------+----------+
| starting                       | 0.000015 |
| checking query cache for query | 0.000266 |
| Opening tables                 | 0.000009 |
| System lock                    | 0.000004 |
| Table lock                     | 0.000006 |
| init                           | 0.000115 |
| optimizing                     | 0.000038 |
| statistics                     | 0.000797 |
| preparing                      | 0.000047 |
| executing                      | 0.000002 |
| Sending data                   | 2.675270 |
| end                            | 0.000007 |
| query end                      | 0.000003 |
| freeing items                  | 0.000071 |
| logging slow query             | 0.000002 |
| logging slow query             | 0.000058 |
| cleaning up                    | 0.000005 |
+--------------------------------+----------+

I've been working on this problem for a long time and I haven't been able to find a solution. Is there anything overtly wrong with this query? I don't see how looking at 420 rows should take 2+ seconds.

Body:
You should transform the IN clauses to INNER JOIN clauses.

You can transform a query like this one:

SELECT  foo
FROM    bar
WHERE bar.stuff IN
       (SELECT  stuff FROM asdf)

Into a query like this other one:

SELECT  b.foo
FROM    (
        SELECT  DISTINCT stuff
        FROM    asdf ) a
JOIN    bar b
ON      b.stuff = a.stuff

You will gain a lot of performance.

As the php generate the query, try some kind of trick like a temporary table for the items inside the IN clause. Always try to avoid the IN clauses if you can, because they are very time consuming.


问:
TM Package: Error in UseMethod("TermDocumentMatrix", x)
I want to plot a term-document matrix like Figure 6 in the JSS article on TM package
 1The article link: https://www.jstatsoft.org/article/view/v025i05

My corpus Speach-English.txt is in here:
https://github.com/yushu-liu/speach-english.git

The figure should look like as follow:

Here is my code:

```<code>library(tm)
library(stringr)
library(wordcloud)

text <- paste(readLines("D:/Rdata/speach-English.txt"), collapse = " ")
text_tidy <- gsub(pattern = "\\W",replace=" ",text)
text_tidy2 <- gsub(pattern = "\\d",replace=" ",text_tidy)

text_tidy2 <- tolower(text_tidy2)
text_tidy2 <- removeWords(text_tidy2,stopwords())
text_tidy2 <- gsub(pattern = "\\b[A-z]\\b{1}",replace=" ", text_tidy2 )
text_tidy2 <- stripWhitespace(text_tidy2)

textbag <- str_split(text_tidy2,pattern = "\\s+")
textbag <- unlist(textbag)

tdm <- TermDocumentMatrix(textbag, control = list(removePunctuation = TRUE,
                                                removeNumbers = TRUE,
                                                stopwords = TRUE))

plot(tdm, terms = findFreqTerms(tdm, lowfreq = 6)[1:25], corThreshold = 0.5)
</code>```

But one bug came out:

```<code>Error in UseMethod("TermDocumentMatrix", x) :
  no applicable method for 'TermDocumentMatrix' applied to an object of class "character"
</code>```

Why? Thanks!

答:
The problem is that you have not created an object of the Corpus class, which is the type of object you need to feed to TermDocumentMatrix(). See an example of how you could do that below.

Another point I would like to note is that in your line str_split(text_tidy2,pattern = "\\s+") you split your text into unigrams (individual terms). Hence, you only get documents of one term each. Creating a tdm from this structure does not make much sense. What is the intended purpose of this line? Maybe I can point you to what you want.

```<code>library(tm)
text <-  readLines("https://raw.githubusercontent.com/yushu-liu/speach-english/master/speach-English.txt")
#first define the type of source you want to use and how it shall be read
x <- VectorSource(text)
#create a corpus object
x <- VCorpus(x)
#feed it to tdm
tdm <- TermDocumentMatrix(x)
tdm
#<<TermDocumentMatrix (terms: 4159, documents: 573)>>
#Non-/sparse entries: 14481/2368626
#Sparsity           : 99%
#Maximal term length: 21
#Weighting          : term frequency (tf)
</code>```

Body:
I want to plot a term-document matrix like Figure 6 in the JSS article on TM package
 1The article link: https://www.jstatsoft.org/article/view/v025i05

My corpus Speach-English.txt is in here:
https://github.com/yushu-liu/speach-english.git

The figure should look like as follow:

Here is my code:

library(tm)
library(stringr)
library(wordcloud)

text <- paste(readLines("D:/Rdata/speach-English.txt"), collapse = " ")
text_tidy <- gsub(pattern = "\\W",replace=" ",text)
text_tidy2 <- gsub(pattern = "\\d",replace=" ",text_tidy)

text_tidy2 <- tolower(text_tidy2)
text_tidy2 <- removeWords(text_tidy2,stopwords())
text_tidy2 <- gsub(pattern = "\\b[A-z]\\b{1}",replace=" ", text_tidy2 )
text_tidy2 <- stripWhitespace(text_tidy2)

textbag <- str_split(text_tidy2,pattern = "\\s+")
textbag <- unlist(textbag)

tdm <- TermDocumentMatrix(textbag, control = list(removePunctuation = TRUE,
                                                removeNumbers = TRUE,
                                                stopwords = TRUE))

plot(tdm, terms = findFreqTerms(tdm, lowfreq = 6)[1:25], corThreshold = 0.5)

But one bug came out:

Error in UseMethod("TermDocumentMatrix", x) :
  no applicable method for 'TermDocumentMatrix' applied to an object of class "character"

Why? Thanks!

Body:
The problem is that you have not created an object of the Corpus class, which is the type of object you need to feed to TermDocumentMatrix(). See an example of how you could do that below.

Another point I would like to note is that in your line str_split(text_tidy2,pattern = "\\s+") you split your text into unigrams (individual terms). Hence, you only get documents of one term each. Creating a tdm from this structure does not make much sense. What is the intended purpose of this line? Maybe I can point you to what you want.

library(tm)
text <-  readLines("https://raw.githubusercontent.com/yushu-liu/speach-english/master/speach-English.txt")
#first define the type of source you want to use and how it shall be read
x <- VectorSource(text)
#create a corpus object
x <- VCorpus(x)
#feed it to tdm
tdm <- TermDocumentMatrix(x)
tdm
#<<TermDocumentMatrix (terms: 4159, documents: 573)>>
#Non-/sparse entries: 14481/2368626
#Sparsity           : 99%
#Maximal term length: 21
#Weighting          : term frequency (tf)


答:
That's pretty interesting, and new to me.

My best understanding, from the documentation you linked to which says:

If control flow reaches the point of the __builtin_unreachable(), the program is undefined.

So basically the macro reaches undefined behavior if the condition is false. Thus, the compiler is assumed to be able to optimize based on the assumption that that doesn't happen, i.e. the conditions are not false.

I'd be interested in comparing the result from building the code with and without those macros, to further understand what actual difference it makes.

Relying on this to get some kind of optimization to happen seems kind of "brittle" to me, since it assumes a lot about the internal functioning of the compiler.

Title: How the GNU builtin function `__builtin_unreachable ` works in this code snippet?


问:
Github SQL Server installation
I am new to github I understand it is aversion control repository for collaborative software development. I wish to however explore that can we also install software such as SQL Server or java in github repository so that it provides a complete platform. Actually I have developed a software tool that uses HTML5 D3 and SQL Server I want it to upload to a Github repository so that other can see a live demo. I'm not sure how to do this - please comment  </p>

答: Github will only host the source code itself and static html pages. Nothing is actually executed there. Basically a folder on a computer. Passive. You would need to use a cloud platform like gcp or aws to do what you are describing. </p>

Title: Github SQL Server installation


问:
Should I even check for a default value when calling IEnumerable<T>.FirstOrDefault where T: struct
I have a sequence of structs like so:

```<code>struct Foo { }

...

// somewhere else
var foos = GetListOfFoos();

...

// somewhere else
var foo = foos.FirstOrDefault();
</code>```

Now, should I just go ahead and use the foo I just retrieved without worrying about nullability, of course because structs are not nullable since they're value types.

It just feels a bit worrying.

I know this is a stupid question and the answer is, "Yes, just use it without any checks for null." But I don't know why I am asking this even or what the question here is.

I am not missing anything by not checking for nullability here, right? There cannot be an invalid state for structs put inside that IEnumerable<T>, right?

Of course, I understand that if Foo had uninitialized members because it declared a parameterized ctor that did not initialize each and every member, one or more members of the instance of Foo will be in an unsable state. But as such each instance of Foo in that list will amount to something and there's no need to check for nulls or anything as there is no such thing as default(Foo), right? Of course, just confirming.

答:
Even if value types are not null you should worry about this value being the default value if that was exceptional or not expected.

there is no such thing as default(Foo)

Sure, It will return an instance of this type where all members are nitialized to their default alues.

If you take f.e. struct Guid then default(Guid) returns an instance which is equal to Guid.Empty or new Guid().

So my advice is, don't compare with default(yourStruct) because that could lead to nasty bugs if the default struct could be a valid instance. Instead you could use Any:

```<code>bool containsAny = foos.Any();
if(containsAny)
{
    Foo firstFoo = foos.First();
}
</code>```

MSDN: default

returns null for reference types(class types and interface types)

zero for numeric value types

for user-defined structs, it returns the struct initialized to the zero bit pattern, which produces 0 or null for each member depending on whether that member is a value or reference type. For nullable value types, default returns a System.Nullable<T>, which is initialized like any struct.

Body:
I have a sequence of structs like so:

struct Foo { }

...

// somewhere else
var foos = GetListOfFoos();

...

// somewhere else
var foo = foos.FirstOrDefault();

Now, should I just go ahead and use the foo I just retrieved without worrying about nullability, of course because structs are not nullable since they're value types.

It just feels a bit worrying.

I know this is a stupid question and the answer is, "Yes, just use it without any checks for null." But I don't know why I am asking this even or what the question here is.

I am not missing anything by not checking for nullability here, right? There cannot be an invalid state for structs put inside that IEnumerable<T>, right?

Of course, I understand that if Foo had uninitialized members because it declared a parameterized ctor that did not initialize each and every member, one or more members of the instance of Foo will be in an unsable state. But as such each instance of Foo in that list will amount to something and there's no need to check for nulls or anything as there is no such thing as default(Foo), right? Of course, just confirming.

Body:
Even if value types are not null you should worry about this value being the default value if that was exceptional or not expected.

there is no such thing as default(Foo)

Sure, It will return an instance of this type where all members are nitialized to their default alues.

If you take f.e. struct Guid then default(Guid) returns an instance which is equal to Guid.Empty or new Guid().

So my advice is, don't compare with default(yourStruct) because that could lead to nasty bugs if the default struct could be a valid instance. Instead you could use Any:

bool containsAny = foos.Any();
if(containsAny)
{
    Foo firstFoo = foos.First();
}

MSDN: default

returns null for reference types(class types and interface types)

zero for numeric value types

for user-defined structs, it returns the struct initialized to the zero bit pattern, which produces 0 or null for each member depending on whether that member is a value or reference type. For nullable value types, default returns a System.Nullable<T>, which is initialized like any struct.


答:
If T is a struct, you can't check for null: it will never be null, and a real "zero" (equivalent) in the list/sequence will be indistinguishable from "no there weren't any values in the list/sequence".

No, you don't need to check for null here.

Title: Should I even check for a default value when calling IEnumerable<T>.FirstOrDefault where T: struct


问:
MySQL query not outputting result only heading
I am currently practicing PHP and AJAX and I am trying to create an application that allows a user to search a database for product stock in real time. When the user types in a letter within one of the entries the headings show up but not the data. I'm not sure if I am doing it wrong but I'll let you guys be the judge of that. Code below:

Results.php - Below

```<code> <!DOCTYPE html>
<html>
<head>
<title>Results</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>

<?php
$q = intval($_GET['q']);

$con = mysqli_connect("localhost", "username", "password", "databaseName");
//edited out for safety

if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}

mysqli_select_db($con,"jakeholc_ajaxtest");

$sql="SELECT * FROM stock WHERE name LIKE '%{$q}%'";
$result = mysqli_query($con,$sql);

echo "<table>
<tr>
<th>Product name</th>
<th>Description</th>
<th>Price</th>
<th>Quantity</th>
</tr>";

if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
echo "<tr>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['descr'] . "</td>";
echo "<td>" . $row['price'] . "</td>";
echo "<td>" . $row['quantity'] . "</td>";
echo "</tr>";
}
}

echo "</table>";
mysqli_close($con);
?>
</code>```

答:
you may try my code. I already tested this one. And everytime you entered a text, entered text will match some record from your database then if there's a record matched, then it will display the record matched on your entered text. Hope this helps :) Please note that the below code are the content of "ajax_search.php".</p>

```<code><!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#search").keyup(function() {
var name = $('#search').val();
if (name == "") {
$("#display").html("");
}
else {
$.ajax({
type: "POST",
url: "ajax_search.php",
data: {
search: name
},
success: function(html) {
$("#display").html(html).show();
}
});
}
});
});
</script>
</head>

<body>
<input type="text" id="search" placeholder="Search Product Here..." />
<?php
$con = mysqli_connect("localhost","username","password","databasename");
if (mysqli_connect_errno()) {
echo "Database Connection Failed: " . mysqli_connect_error();
}
?>
<?php
if (isset($_POST['search'])) {
$key = $_POST['search'];
$query = "SELECT * FROM stock  WHERE name LIKE '%$key%' OR descr LIKE '%$key%' OR price LIKE '%$key%' OR quantity LIKE '%$key%' ";
$execute_query = mysqli_query($con, $query);
echo "<table border='3px' cellpadding='3px' cellspacing='3px' bgcolor='skyblue' align='center'>";
echo "<tr>";
echo "<td>Product Name</td>";
echo "<td>Description</td>";
echo "<td>Price</td>";
echo "<td>Quantity</td>";
echo "</tr>";
while ($result = mysqli_fetch_array($execute_query)) {
echo "<tr>";
echo "<td>".$result['name']."</td>";
echo "<td>".$result['descr']."</td>";
echo "<td>".$result['price']."</td>";
echo "<td>".$result['quantity']."</td>";
echo "</tr>";
}}
mysqli_close($con);
?>
</table>
<div id="display">
<!-- Ouput will display here -->
</div>
</body>
</html>
</code>```

Body:
I am currently practicing PHP and AJAX and I am trying to create an application that allows a user to search a database for product stock in real time. When the user types in a letter within one of the entries the headings show up but not the data. I'm not sure if I am doing it wrong but I'll let you guys be the judge of that. Code below:

Results.php - Below

 <!DOCTYPE html>

<title>Results</title>
<link rel="stylesheet" type="text/css" href="style.css">

<?php
$q = intval($_GET['q']);

$con = mysqli_connect("localhost", "username", "password", "databaseName");
//edited out for safety

if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}

mysqli_select_db($con,"jakeholc_ajaxtest");

$sql="SELECT * FROM stock WHERE name LIKE '%{$q}%'";
$result = mysqli_query($con,$sql);

echo "

Product name
Description
Price
Quantity

";

if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
echo "
";
echo "" . $row['name'] . "	";
echo "" . $row['descr'] . "	";
echo "" . $row['price'] . "	";
echo "" . $row['quantity'] . "	";
echo "
";
}
}

echo "
";
mysqli_close($con);
?>

Body:
you may try my code. I already tested this one. And everytime you entered a text, entered text will match some record from your database then if there's a record matched, then it will display the record matched on your entered text. Hope this helps :) Please note that the below code are the content of "ajax_search.php".

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#search").keyup(function() {
var name = $('#search').val();
if (name == "") {
$("#display").html("");
}
else {
$.ajax({
type: "POST",
url: "ajax_search.php",
data: {
search: name
},
success: function(html) {
$("#display").html(html).show();
}
});
}
});
});
</script>
</head>

<body>
<input type="text" id="search" placeholder="Search Product Here..." />
<?php
$con = mysqli_connect("localhost","username","password","databasename");
if (mysqli_connect_errno()) {
echo "Database Connection Failed: " . mysqli_connect_error();
}
?>
<?php
if (isset($_POST['search'])) {
$key = $_POST['search'];
$query = "SELECT * FROM stock  WHERE name LIKE '%$key%' OR descr LIKE '%$key%' OR price LIKE '%$key%' OR quantity LIKE '%$key%' ";
$execute_query = mysqli_query($con, $query);
echo "<table border='3px' cellpadding='3px' cellspacing='3px' bgcolor='skyblue' align='center'>";
echo "<tr>";
echo "<td>Product Name</td>";
echo "<td>Description</td>";
echo "<td>Price</td>";
echo "<td>Quantity</td>";
echo "</tr>";
while ($result = mysqli_fetch_array($execute_query)) {
echo "<tr>";
echo "<td>".$result['name']."</td>";
echo "<td>".$result['descr']."</td>";
echo "<td>".$result['price']."</td>";
echo "<td>".$result['quantity']."</td>";
echo "</tr>";
}}
mysqli_close($con);
?>
</table>
<div id="display">
<!-- Ouput will display here -->
</div>
</body>
</html>


问:
Angularjs Progress circle not working on dynamic input
when I try to give input value to progress circle in Angular js, only the value(20%) is displayed and loader color is not shown. please refer the attached screenshot.

The Angular progress works fine if the input value(20%) is given directly given in HTML.
But when try to bind value{{count}} its showing only the value, but some css is missing and the progress color is not displayed.

$scope.count= 20;

```<code>(function($) {
    $.fn.loading = function() {

        var backgroundColor = '#ccc';
        var progressColor = '#1abc9c';
        var percent = 90;
        var duration = 2000;

        var DEFAULTS = {
            backgroundColor : '#ccc',
            progressColor : '#1abc9c',
            percent : 90,
            duration : 2000
        };

        $(this)
                .each(
                        function() {
                            var $target = $(this);

                            var opts = {
                                backgroundColor : $target.data('color') ? $target
                                        .data('color').split(',')[0]
                                        : DEFAULTS.backgroundColor,
                                progressColor : $target.data('color') ? $target
                                        .data('color').split(',')[1]
                                        : DEFAULTS.progressColor,
                                percent : $target.data('percent') ? $target
                                        .data('percent') : DEFAULTS.percent,
                                duration : $target.data('duration') ? $target
                                        .data('duration') : DEFAULTS.duration
                            };
                            // console.log(opts);

                            $target
                                    .append('<div class="background"></div><div class="rotate"></div><div class="left"></div><div class="right"></div><div class=""><span>'
                                            + opts.percent + '%</span></div>');

                            $target.find('.background').css('background-color',
                                    opts.backgroundColor);
                            $target.find('.left').css('background-color',
                                    opts.backgroundColor);
                            $target.find('.rotate').css('background-color',
                                    opts.progressColor);
                            $target.find('.right').css('background-color',
                                    opts.progressColor);

                            var $rotate = $target.find('.rotate');
                            setTimeout(function() {
                                $rotate.css({
                                    'transition' : 'transform ' + opts.duration
                                            + 'ms linear',
                                    'transform' : 'rotate(' + opts.percent
                                            * 3.6 + 'deg)'
                                });
                            }, 1);

                            if (opts.percent > 50) {
                                var animationRight = 'toggle '
                                        + (opts.duration / opts.percent * 50)
                                        + 'ms step-end';
                                var animationLeft = 'toggle '
                                        + (opts.duration / opts.percent * 50)
                                        + 'ms step-start';
                                $target.find('.right').css({
                                    animation : animationRight,
                                    opacity : 1
                                });
                                $target.find('.left').css({
                                    animation : animationLeft,
                                    opacity : 0
                                });
                            }
                        });
    }
})(jQuery);
</code>```

.position {
  float: left;
  margin: 20px 0px;
}

.progress-bar-container {
  width: 100px;
  margin: 0 auto;
}

.pb-heading {
    border: 0px;
    margin-bottom: -10px;
}

.progress-bar {
  position: relative;
  height: 100px;
  color: #111;
  background-color: transparent;
  -webkit-box-shadow: inset 0 0px 0 rgba(0,0,0,.15);
  box-shadow: inset 0 0px 0 rgba(0,0,0,.15);
}

.progress-bar div {
  position: absolute;
  height: 100px;
  width: 100px;
  border-radius: 50%;
}

.progress-bar div span {
    position: absolute;
    font-family: Arial;
    font-size: 20px;
    line-height: 80px;
    height: 75px;
    width: 75px;
    left: 12.5px;
    top: 12.5px;
    text-align: center;
    border-radius: 50%;
    background-color: white;
}

.progress-bar .background { background-color: #b3cef6; }

.progress-bar .rotate {
  color: red;
  clip: rect(0 50px 200px 0);
  background-color: #4b86db;
}

.progress-bar .left {
  clip: rect(0 50px 200px 0);
  opacity: 1;
  background-color: #b3cef6;
}

.progress-bar .right {
  clip: rect(0 50px 200px 0);
  transform: rotate(180deg);
  opacity: 0;
  background-color: #4b86db;
}
 @keyframes
toggle {  0% {
 opacity: 0;
}
 100% {
 opacity: 1;
}
}
```

<pre class="lang-html prettyprint-override"><code><div class="col-md-3">
     <div class="panel db-panel">
                        <div class="panel-heading pb-heading">
                            Total Uploaded this Week
                        </div>
                        <!-- /.panel-heading -->
                        <div class="panel-body progress-bar-container" >
                        <div class="progress-bar position"  ng-class="rotate"  data-percent={{count}} data-duration="1000" data-color="#ccc,#f39c12"></div>
                        </div>
    </div>
    <div class="panel db-panel">
                        <div class="panel-heading pb-heading">
                            Successfully Uploaded
                        </div>
                        <!-- /.panel-heading -->
                        <div class="panel-body progress-bar-container">
                        <div class="progress-bar position" data-percent="20" data-duration="1000" data-color="#ccc,#f39c12"></div>
                        </div>
    </div>

</div>
</code>```

答:
I believe that changing your progress-bar data-percent={{count}} to have quotes around will fix your issue:

```<code><div class="progress-bar position"  ng-class="rotate"  data-percent="{{count}}" data-duration="1000" data-color="#ccc,#f39c12"></div>
</code>```

Also I'm not sure about your logic since you didn't post any of you angularjs code, remove ng-class="rotate" and put just  class="rotate" ng-class will take expression so it will think that rotate is some property on $scope and you would need to set it up like:

$scope.rotate='rotate'

but using:

```<code>class="rotate"
</code>```

should work fine.

Because all of this is just a workaround and messy approach, I would advise to check this and work it out AngularJS way:

http://jtblin.github.io/angular-chart.js/

Body:
when I try to give input value to progress circle in Angular js, only the value(20%) is displayed and loader color is not shown. please refer the attached screenshot.

The Angular progress works fine if the input value(20%) is given directly given in HTML.
But when try to bind value{{count}} its showing only the value, but some css is missing and the progress color is not displayed.

$scope.count= 20;

(function($) {
    $.fn.loading = function() {

        var backgroundColor = '#ccc';
        var progressColor = '#1abc9c';
        var percent = 90;
        var duration = 2000;

        var DEFAULTS = {
            backgroundColor : '#ccc',
            progressColor : '#1abc9c',
            percent : 90,
            duration : 2000
        };

        $(this)
                .each(
                        function() {
                            var $target = $(this);

                            var opts = {
                                backgroundColor : $target.data('color') ? $target
                                        .data('color').split(',')[0]
                                        : DEFAULTS.backgroundColor,
                                progressColor : $target.data('color') ? $target
                                        .data('color').split(',')[1]
                                        : DEFAULTS.progressColor,
                                percent : $target.data('percent') ? $target
                                        .data('percent') : DEFAULTS.percent,
                                duration : $target.data('duration') ? $target
                                        .data('duration') : DEFAULTS.duration
                            };
                            // console.log(opts);

                            $target
                                    .append('

'
                                            + opts.percent + '%
');

                            $target.find('.background').css('background-color',
                                    opts.backgroundColor);
                            $target.find('.left').css('background-color',
                                    opts.backgroundColor);
                            $target.find('.rotate').css('background-color',
                                    opts.progressColor);
                            $target.find('.right').css('background-color',
                                    opts.progressColor);

                            var $rotate = $target.find('.rotate');
                            setTimeout(function() {
                                $rotate.css({
                                    'transition' : 'transform ' + opts.duration
                                            + 'ms linear',
                                    'transform' : 'rotate(' + opts.percent
                                            * 3.6 + 'deg)'
                                });
                            }, 1);

                            if (opts.percent > 50) {
                                var animationRight = 'toggle '
                                        + (opts.duration / opts.percent * 50)
                                        + 'ms step-end';
                                var animationLeft = 'toggle '
                                        + (opts.duration / opts.percent * 50)
                                        + 'ms step-start';
                                $target.find('.right').css({
                                    animation : animationRight,
                                    opacity : 1
                                });
                                $target.find('.left').css({
                                    animation : animationLeft,
                                    opacity : 0
                                });
                            }
                        });
    }
})(jQuery);

.position {
  float: left;
  margin: 20px 0px;
}

.progress-bar-container {
  width: 100px;
  margin: 0 auto;
}

.pb-heading {
    border: 0px;
    margin-bottom: -10px;
}

.progress-bar {
  position: relative;
  height: 100px;
  color: #111;
  background-color: transparent;
  -webkit-box-shadow: inset 0 0px 0 rgba(0,0,0,.15);
  box-shadow: inset 0 0px 0 rgba(0,0,0,.15);
}

.progress-bar div {
  position: absolute;
  height: 100px;
  width: 100px;
  border-radius: 50%;
}

.progress-bar div span {
    position: absolute;
    font-family: Arial;
    font-size: 20px;
    line-height: 80px;
    height: 75px;
    width: 75px;
    left: 12.5px;
    top: 12.5px;
    text-align: center;
    border-radius: 50%;
    background-color: white;
}

.progress-bar .background { background-color: #b3cef6; }

.progress-bar .rotate {
  color: red;
  clip: rect(0 50px 200px 0);
  background-color: #4b86db;
}

.progress-bar .left {
  clip: rect(0 50px 200px 0);
  opacity: 1;
  background-color: #b3cef6;
}

.progress-bar .right {
  clip: rect(0 50px 200px 0);
  transform: rotate(180deg);
  opacity: 0;
  background-color: #4b86db;
}
 @keyframes
toggle {  0% {
 opacity: 0;
}
 100% {
 opacity: 1;
}
}

                            Total Uploaded this Week

                            Successfully Uploaded

Body:
I believe that changing your progress-bar data-percent={{count}} to have quotes around will fix your issue:

<div class="progress-bar position"  ng-class="rotate"  data-percent="{{count}}" data-duration="1000" data-color="#ccc,#f39c12"></div>

Also I'm not sure about your logic since you didn't post any of you angularjs code, remove ng-class="rotate" and put just  class="rotate" ng-class will take expression so it will think that rotate is some property on $scope and you would need to set it up like:

$scope.rotate='rotate'

but using:

class="rotate"

should work fine.

Because all of this is just a workaround and messy approach, I would advise to check this and work it out AngularJS way:

http://jtblin.github.io/angular-chart.js/


问:
negative index in array of pointers in C
```<code>#include<stdio.h>
int main(){
  int a1[]={6,7,8,18,34,67};
  int a2[]={23,56,28,24};
  int a3[]={-12,27,-31};
  int *y[]={a1,a2,a3};
  int **a= y;

  printf("%d\n",a[0][2]);
  printf("%d\n",*a[2]);
  printf("%d\n",*(++a[0]));
  printf("%d\n",*(++a)[0]);
  printf("%d\n",a[-1][1]);
  return 0;
}
</code>```

When I run the above code output is 8,-12,7,23,8. But if i change the last 3 lines to

```<code>printf("%d\n",*(++a[2]));
printf("%d\n",*(++a)[1]);
printf("%d\n",a[-1][1]);
</code>```

output is 8,-12,27,27,7. I'm unable to understand last printf statement. How does a[-1][something] is calculated ? And according to me *(++a)[1] should print 56 instead of 27 !

答:
Pointers and array bases are in fact addresses in virtual memory. In C, they can be calculated into new addresses. Since the compiler knows the size of memory the pointer points to (e.g. int * points to 4 Bytes), a pointer +/- 1 means the address +/- the size (e.g. 4 Bytes for int).

The operator * means to get the value stored in the specified address.

Another trick here is the priorities of the operators. [] is calculated before ++.

If you understand what I mean above, your problem should be resolved.

Body:
#include<stdio.h>
int main(){
  int a1[]={6,7,8,18,34,67};
  int a2[]={23,56,28,24};
  int a3[]={-12,27,-31};
  int *y[]={a1,a2,a3};
  int **a= y;

  printf("%d\n",a[0][2]);
  printf("%d\n",*a[2]);
  printf("%d\n",*(++a[0]));
  printf("%d\n",*(++a)[0]);
  printf("%d\n",a[-1][1]);
  return 0;
}

When I run the above code output is 8,-12,7,23,8. But if i change the last 3 lines to

printf("%d\n",*(++a[2]));
printf("%d\n",*(++a)[1]);
printf("%d\n",a[-1][1]);

output is 8,-12,27,27,7. I'm unable to understand last printf statement. How does a[-1][something] is calculated ? And according to me *(++a)[1] should print 56 instead of 27 !


问:
Cordova encrypt source code
I have project in Phonegap / Cordova and i need secrecy in source-code. Is there any way to encrypt my source code for anyone don't extract the APK file in android?

I saw a plugin Cordova crypt file plugin, but it does not work, it is out of date and not have suport, and, when i installed, my javascript code does not work.

I need an efficient alternative solution. What is recommended?

答:
I found a nice workaround here

Encrypt Source Files

All you need to do is add:
cordova plugin add cordova-plugin-crypt-file

and as soon as you run:

cordova build android

or

cordova build android --prod --release

it will be encrypted.

To verify, try extracting the apk file using any archive utility tool and open the source file, you will see it encrypted

Hope this helps.

Title: Cordova encrypt source code


问:
Android global variable
How can I create global variable keep remain values around the life cycle of the application regardless which activity running.</p>

答:
Technically this does not answer the question, but I would recommend using the Room database instead of any global variable.
https://developer.android.com/topic/libraries/architecture/room.html
Even if you are 'only' needing to store a global variable and it's no big deal and what not, but using the Room database is the most elegant, native and well supported way of keeping values around the life cycle of the activity.
It will help to prevent many issues, especially integrity of data.
I understand that database and global variable are different but please use Room for the sake of code maintenance, app stability and data integrity. </p>

Title: Android global variable


问:
Custom fields with spaces in Workfront issues
Please, can you help me create/update items from custom fields that have space within their name?

We have a project with a custom field Contact phone. This field can be used correctly from the browser. https://github.com/Workfront/workfront-api-examples-csharp didn't help. I was able to add the data within the details of the issue. I would like to add it within the specific custom field (create/update).

```<code>var client = new AtTaskRestClient(_url); // from the example
...
var description = $"Contact phone: {item.ContactPhone}";
client.Create(ObjCode.ISSUE, new { name = item.Name,
    description = description,
    projectID = _projectID });
</code>```

client.Create has an object as final parameter. We use an anonymous type that can't contain "DE:Contact phone" = item.ContactPhone within the constructor. How can we write this field?

Reading DE:Contact phone works correctly if we insert the value from the browser:

```<code>JToken issues = client.Search(ObjCode.ISSUE, new { projectID = _projectID });
foreach (var issue in issues["data"].Children()) {
    var name = issue.Value<string>("name"); // correct
    var id = issue.Value<string>("ID"); // correct
    var fields = client.Get(ObjCode.ISSUE, id, new[] { "description", "DE:Contact phone"}); // correct
</code>```

答:
https://github.com/Workfront/workfront-api-examples-csharp/blob/master/AtTaskRestExample/AtTaskRestClient.cs

```<code>public JToken Create(ObjCode objcode, object parameters) {
    VerifySignedIn();
    string[] p = parameterObjectToStringArray(parameters, "sessionID=" + SessionID);
    JToken json = client.DoPost(string.Format("/{0}", objcode), p);
    return json;
}
</code>```

I wrote a new function CreateEx, that receives a string array

```<code>public JToken Create(ObjCode objcode, string[] parameters) {
    VerifySignedIn();
    JToken json = client.DoPost(string.Format("/{0}", objcode), parameters);
    return json;
}
</code>```

It is accessed as follows:

```<code>var client = new AtTaskRestClient(_url); // from the example
...
string[] parameteres =
    {
        $"name={issueName}",
        $"description={description}",
        $"projectID={_projectID}",
        $"sessionID={client.SessionID}",
        $"DE:Contact phone={contactPhone}"
    };
client.CreateEx(ObjCode.ISSUE, parameteres);
</code>```

Body:
Please, can you help me create/update items from custom fields that have space within their name?

We have a project with a custom field Contact phone. This field can be used correctly from the browser. https://github.com/Workfront/workfront-api-examples-csharp didn't help. I was able to add the data within the details of the issue. I would like to add it within the specific custom field (create/update).

var client = new AtTaskRestClient(_url); // from the example
...
var description = $"Contact phone: {item.ContactPhone}";
client.Create(ObjCode.ISSUE, new { name = item.Name,
    description = description,
    projectID = _projectID });

client.Create has an object as final parameter. We use an anonymous type that can't contain "DE:Contact phone" = item.ContactPhone within the constructor. How can we write this field?

Reading DE:Contact phone works correctly if we insert the value from the browser:

JToken issues = client.Search(ObjCode.ISSUE, new { projectID = _projectID });
foreach (var issue in issues["data"].Children()) {
    var name = issue.Value<string>("name"); // correct
    var id = issue.Value<string>("ID"); // correct
    var fields = client.Get(ObjCode.ISSUE, id, new[] { "description", "DE:Contact phone"}); // correct

Body:
https://github.com/Workfront/workfront-api-examples-csharp/blob/master/AtTaskRestExample/AtTaskRestClient.cs

public JToken Create(ObjCode objcode, object parameters) {
    VerifySignedIn();
    string[] p = parameterObjectToStringArray(parameters, "sessionID=" + SessionID);
    JToken json = client.DoPost(string.Format("/{0}", objcode), p);
    return json;
}

I wrote a new function CreateEx, that receives a string array

public JToken Create(ObjCode objcode, string[] parameters) {
    VerifySignedIn();
    JToken json = client.DoPost(string.Format("/{0}", objcode), parameters);
    return json;
}

It is accessed as follows:

var client = new AtTaskRestClient(_url); // from the example
...
string[] parameteres =
    {
        $"name={issueName}",
        $"description={description}",
        $"projectID={_projectID}",
        $"sessionID={client.SessionID}",
        $"DE:Contact phone={contactPhone}"
    };
client.CreateEx(ObjCode.ISSUE, parameteres);


问:
Laravel: Check if record exists Before Insertion
I have two tables: assignments table(columns assignment_id, Staff Name, asset_id, department, date, status), and an assets table (columns asset_id, tag_name, serial_number, model_number, color). The asset table columns are linked with the assignments table. I want to perform an insertion into the assignments table but before the insertion, i want to check if the asset_id already exists in the assignments table & if it's status = 'Active' then the insertion should throw an error/shouldn't happen.

AssignmentsController

```<code>class AssignmentController extends Controller
{

public function assignment(){
    $assignments = Assignment::all();
    return view('assignment/index', ['assignments' => $assignments]);
}

  public function add(Request $request){

    $this->validate($request, [
        'assignment_id' => '',
        'staff_name' => 'required',
        'asset_id' => 'required',
        'department' => 'required',
        'date' => 'required',
        'status' => 'required'
    ]);
    $assignments =  new Assignment;
    $assignments  ->assignment_id = $request->input('assignment_id');
    $assignments  ->staff_id  = $request->input('staff_id');
    $assignments  ->asset_id = $request->input('asset_id');
    $assignments  ->department_id = $request->input('department_id');
    $assignments  ->date  = $request->input('date');
    $assignments  ->status = $request->input('status');

$count = Assignment::where('status', '=' ,'Active' )->
    where('asset_id', '=' ,$assignments->asset_id)->
    count();
    if($count) {
        abort(405, 'Trying to assign an already assigned asset');
    }

    $assignments  ->save();
    return redirect('/assignment/index') ->with('info', 'New Assignment Saved Successfully!');
}
</code>```

Assginment.php

```<code>class Assignment extends Model
{
    protected $primaryKey = 'assignment_id';

    public function asset()
    {
        return $this->belongsTo('App\Asset', 'asset_id');
    }
}
</code>```

The below variable and if statement in the AssignmentsController always throws the error in the if statement whether it's true or not and the insertion doesn't happen but when the whole statement is cleared, the insertion happens.

```<code>$count = Assignment::where('status', '=' ,'Active' )->
        where('asset_id', '=' ,$assignments->asset_id)->
        count();
        if($count) {
            abort(405, 'Trying to assign an already assigned asset');
        }
</code>```

So i want a way to check if the the record to be inserted already exists  with conditions as if asset_id exists then check for it's status if it's ='Active' then throw an error but if not then insertion happens. Please help if you understand it. Thanks in advance.

答:
You can just do:</p>

```<code>public function add(Request $request){
    $this->validate($request, [
        'assignment_id' => '',
        'staff_name' => 'required',
        'asset_id' => 'required',
        'department' => 'required',
        'date' => 'required',
        'status' => 'required'
    ]);
    $assignment = Assignment::firstOrNew([
           "status" => "Active",
           "asset_id" => $assignments->asset_id
    ], $request->all());
    abort_if($assignment->exists(), 405, 'Trying to assign an already assigned asset');
    $assignment->save();
    return redirect('/assignment/index')
          ->with('info', 'New Assignment Saved Successfully!');
}
</code>```

Body:
I have two tables: assignments table(columns assignment_id, Staff Name, asset_id, department, date, status), and an assets table (columns asset_id, tag_name, serial_number, model_number, color). The asset table columns are linked with the assignments table. I want to perform an insertion into the assignments table but before the insertion, i want to check if the asset_id already exists in the assignments table & if it's status = 'Active' then the insertion should throw an error/shouldn't happen.

AssignmentsController

class AssignmentController extends Controller
{

public function assignment(){
    $assignments = Assignment::all();
    return view('assignment/index', ['assignments' => $assignments]);
}

  public function add(Request $request){

    $this->validate($request, [
        'assignment_id' => '',
        'staff_name' => 'required',
        'asset_id' => 'required',
        'department' => 'required',
        'date' => 'required',
        'status' => 'required'
    ]);
    $assignments =  new Assignment;
    $assignments  ->assignment_id = $request->input('assignment_id');
    $assignments  ->staff_id  = $request->input('staff_id');
    $assignments  ->asset_id = $request->input('asset_id');
    $assignments  ->department_id = $request->input('department_id');
    $assignments  ->date  = $request->input('date');
    $assignments  ->status = $request->input('status');

$count = Assignment::where('status', '=' ,'Active' )->
    where('asset_id', '=' ,$assignments->asset_id)->
    count();
    if($count) {
        abort(405, 'Trying to assign an already assigned asset');
    }

    $assignments  ->save();
    return redirect('/assignment/index') ->with('info', 'New Assignment Saved Successfully!');
}

Assginment.php

class Assignment extends Model
{
    protected $primaryKey = 'assignment_id';

    public function asset()
    {
        return $this->belongsTo('App\Asset', 'asset_id');
    }
}

The below variable and if statement in the AssignmentsController always throws the error in the if statement whether it's true or not and the insertion doesn't happen but when the whole statement is cleared, the insertion happens.

$count = Assignment::where('status', '=' ,'Active' )->
        where('asset_id', '=' ,$assignments->asset_id)->
        count();
        if($count) {
            abort(405, 'Trying to assign an already assigned asset');
        }

So i want a way to check if the the record to be inserted already exists  with conditions as if asset_id exists then check for it's status if it's ='Active' then throw an error but if not then insertion happens. Please help if you understand it. Thanks in advance.

Body:
You can just do:

public function add(Request $request){
    $this->validate($request, [
        'assignment_id' => '',
        'staff_name' => 'required',
        'asset_id' => 'required',
        'department' => 'required',
        'date' => 'required',
        'status' => 'required'
    ]);
    $assignment = Assignment::firstOrNew([
           "status" => "Active",
           "asset_id" => $assignments->asset_id
    ], $request->all());
    abort_if($assignment->exists(), 405, 'Trying to assign an already assigned asset');
    $assignment->save();
    return redirect('/assignment/index')
          ->with('info', 'New Assignment Saved Successfully!');
}


问:
Is this an optimisation bug?
Here is some output from my compiler in assembler. It's the MPLAB C30 C compiler, based on GCC v3.23, for a dsPIC33FJ128GP802, a 16-bit moderately high speed DSP/MCU.

```<code>212:               inline uint16_t ror_16(uint16_t word, int num)
213:               {
 078C4  608270     and.w w1,#16,w4
 078C6  DE0204     lsr w0,w4,w4
 078C8  780101     mov.w w1,w2
 078CA  EA8102     com.w w2,w2
 078CC  EA8183     com.w w3,w3
 078CE  610170     and.w w2,#16,w2
 078D0  DD0002     sl w0,w2,w0
 078D2  700004     ior.w w0,w4,w0
214:                num &= 16; // limit to 16 shifts
215:                return (word >> num) | (word << (16 - num));
216:               }
 078D4  060000     return
</code>```

In particular I'm interested in the following:

```<code>and.w w1,#16,w4         AND W1 with 16, storing result in W4
lsr w0,w4,w4            Logical shift right W0 by W4 times storing result in W4
mov.w w1,w2             Move W1 to W2
com.w w2,w2             Logical complement of W2 stored in W2
com.w w3,w3             Logical complement of W3 stored in W3   <-- This line is confusing me
and.w w2,#16,w2         AND W2 with 16, storing result in W2
sl w0,w2,w0             (Logical) shift left W0 left by W2 times storing result in W0
ior.w w0,w4,w0          Inclusive OR of W0 and W4 stored in W0
return                  Return from function
</code>```

W0..W15 are an array of sixteen on chip 16-bit registers.

Effectively this simplifies to (in a primitive RTL):

```<code>W4 := W1 & 16
W4 := W0 LSR W4
W1 := W2
W2 := COM W2
W3 := COM W3
W2 := W2 & 16
W0 := W0 SL W2
W0 := W0 | W4
return
</code>```

Now I'm confused at why it is computing the complement of W3 when there are only two passed arguments (W0 and W1 - it uses the W array for passing arguments to functions for functions with smaller arguments.) W3 is never used in the calculation, and is never returned. In fact it doesn't even appear to have data in it: nothing is stored in it by the function, and only the callee will have some data in it (although functions are not required to preserve W0..W7 so the callee should not be relying on it.) Why is it included in the code? Is it just a compiler glitch or error, or am I missing something?

And it's not just this code - I'm seeing the very same oddness in other parts of code. Even code designed to calculate things like complements of a 16-bit variable always seem to use two registers. It has me lost!

答:
The function is not coded to limit the count to 16 (which I suspect you mean 0 to 16) but limits it to 0 or 16.

Instead of

```<code>num &= 16
</code>```

you perhaps want

```<code>num > 16 ? (num & 15) : num
</code>```

Re: the question, since the function is inlined, it can only be answered by looking at where it is used. Perhaps W3 is used for something in the surrounding code. Or it could be a "bug," but one that only has performance, not correctness, impact.

If num can be only 0 or 16 (as in your code) then (16 - num) can also only be 16 or 0, which is why C30 can do the "subtract" with a complement and mask.

FYI, when I don't inline, in C30 I get:

```<code>34:                uint16_t ror_16(uint16_t word, int num)
35:                {
 05AF4  608170     and.w 0x0002,#16,0x0004
 05AF6  DE0102     lsr 0x0000,0x0004,0x0004
 05AF8  EA8081     com.w 0x0002,0x0002
 05AFA  6080F0     and.w 0x0002,#16,0x0002
 05AFC  DD0001     sl 0x0000,0x0002,0x0000
 05AFE  700002     ior.w 0x0000,0x0004,0x0000
36:                    num &= 16; // limit to 16 shifts
37:                    return (word >> num) | (word << (16 - num));
38:                }
 05B00  060000     return
</code>```

I might code this as

```<code>34:                uint16_t ror_16(uint16_t word, int num)
35:                {
 05AF4  780100     mov.w 0x0000,0x0004
36:                    num &= 15; // mod 16
 05AF6  60806F     and.w 0x0002,#15,0x0000
37:                    return (num == 0) ? word : ((word >> num) | (word << (16 - num)));
 05AF8  320004     bra z, 0x005b02
 05AFA  DE1080     lsr 0x0004,0x0000,0x0002
 05AFC  100070     subr.w 0x0000,#16,0x0000
 05AFE  DD1000     sl 0x0004,0x0000,0x0000
 05B00  708100     ior.w 0x0002,0x0000,0x0004
38:                }
 05B02  780002     mov.w 0x0004,0x0000
 05B04  060000     return
</code>```

Title: Is this an optimisation bug?

Body:
Here is some output from my compiler in assembler. It's the MPLAB C30 C compiler, based on GCC v3.23, for a dsPIC33FJ128GP802, a 16-bit moderately high speed DSP/MCU.

212:               inline uint16_t ror_16(uint16_t word, int num)
213:               {
 078C4  608270     and.w w1,#16,w4
 078C6  DE0204     lsr w0,w4,w4
 078C8  780101     mov.w w1,w2
 078CA  EA8102     com.w w2,w2
 078CC  EA8183     com.w w3,w3
 078CE  610170     and.w w2,#16,w2
 078D0  DD0002     sl w0,w2,w0
 078D2  700004     ior.w w0,w4,w0
214:                num &= 16; // limit to 16 shifts
215:                return (word >> num) | (word << (16 - num));
216:               }
 078D4  060000     return

In particular I'm interested in the following:

and.w w1,#16,w4         AND W1 with 16, storing result in W4
lsr w0,w4,w4            Logical shift right W0 by W4 times storing result in W4
mov.w w1,w2             Move W1 to W2
com.w w2,w2             Logical complement of W2 stored in W2
com.w w3,w3             Logical complement of W3 stored in W3   <-- This line is confusing me
and.w w2,#16,w2         AND W2 with 16, storing result in W2
sl w0,w2,w0             (Logical) shift left W0 left by W2 times storing result in W0
ior.w w0,w4,w0          Inclusive OR of W0 and W4 stored in W0
return                  Return from function

W0..W15 are an array of sixteen on chip 16-bit registers.

Effectively this simplifies to (in a primitive RTL):

W4 := W1 & 16
W4 := W0 LSR W4
W1 := W2
W2 := COM W2
W3 := COM W3
W2 := W2 & 16
W0 := W0 SL W2
W0 := W0 | W4
return

Now I'm confused at why it is computing the complement of W3 when there are only two passed arguments (W0 and W1 - it uses the W array for passing arguments to functions for functions with smaller arguments.) W3 is never used in the calculation, and is never returned. In fact it doesn't even appear to have data in it: nothing is stored in it by the function, and only the callee will have some data in it (although functions are not required to preserve W0..W7 so the callee should not be relying on it.) Why is it included in the code? Is it just a compiler glitch or error, or am I missing something?

And it's not just this code - I'm seeing the very same oddness in other parts of code. Even code designed to calculate things like complements of a 16-bit variable always seem to use two registers. It has me lost!

Body:
The function is not coded to limit the count to 16 (which I suspect you mean 0 to 16) but limits it to 0 or 16.

Instead of

num &= 16

you perhaps want

num > 16 ? (num & 15) : num

Re: the question, since the function is inlined, it can only be answered by looking at where it is used. Perhaps W3 is used for something in the surrounding code. Or it could be a "bug," but one that only has performance, not correctness, impact.

If num can be only 0 or 16 (as in your code) then (16 - num) can also only be 16 or 0, which is why C30 can do the "subtract" with a complement and mask.

FYI, when I don't inline, in C30 I get:

34:                uint16_t ror_16(uint16_t word, int num)
35:                {
 05AF4  608170     and.w 0x0002,#16,0x0004
 05AF6  DE0102     lsr 0x0000,0x0004,0x0004
 05AF8  EA8081     com.w 0x0002,0x0002
 05AFA  6080F0     and.w 0x0002,#16,0x0002
 05AFC  DD0001     sl 0x0000,0x0002,0x0000
 05AFE  700002     ior.w 0x0000,0x0004,0x0000
36:                    num &= 16; // limit to 16 shifts
37:                    return (word >> num) | (word << (16 - num));
38:                }
 05B00  060000     return

I might code this as

34:                uint16_t ror_16(uint16_t word, int num)
35:                {
 05AF4  780100     mov.w 0x0000,0x0004
36:                    num &= 15; // mod 16
 05AF6  60806F     and.w 0x0002,#15,0x0000
37:                    return (num == 0) ? word : ((word >> num) | (word << (16 - num)));
 05AF8  320004     bra z, 0x005b02
 05AFA  DE1080     lsr 0x0004,0x0000,0x0002
 05AFC  100070     subr.w 0x0000,#16,0x0000
 05AFE  DD1000     sl 0x0004,0x0000,0x0000
 05B00  708100     ior.w 0x0002,0x0000,0x0004
38:                }
 05B02  780002     mov.w 0x0004,0x0000
 05B04  060000     return


问:
Total all matching integer elements in an array
I was looking over some basic questions that might be asked in an interview. Using basic for loops (No hash maps etc)I want to sum up all the matching elements in an array.For example, 6 matching elements will result in (Matched: 6) and a total of 36 in the example below.An example of this could be rolling dice, and the score is the total of all the dice that match.

```<code>public static void main(String[] args) {

    int arr[] = {6,6,6,6,6,6};
    int matched = 1;
    int value = 0;
    int total = 0;
    for(int i=0;i<arr.length;i++){
        for(int j=(i+1);j<arr.length;j++){
            if(ar[i] == ar[j]){
                matched++;
                value = ar[i];
                break;
            }
        }
        total = (matched * value);
    } // End for loop
    System.out.println("Matched:"+(matched)+"");
    System.out.println("Total:"+total);
}
</code>```

But, if the array was for example...

```<code>int arr[] = {6,1,1,6,6,6};
</code>```

The output I get will be (Matched:5) and an a total of 30.Can could I store the matching pair of 1's and add them to the total using as little basic code as possible?

答:
If the range of your integers is limited, the easiest way to do this would be to create a histogram (i.e. create an array, where under index i you store the number of occurrences of the number i).
From that, it's easy to find elements that occur more than once, and sum them up. This solution has a complexity of O(n+k), where k is the range of your integers.

Another solution is to sort the array,then the matching numbers will be next to each other, and it's easy to count them. This has O(nlogn) complexity.

If these methods are not allowed, here is a solution in O(n^2) that only uses for loops:

Sum up the whole array

With a double loop, find all elements that are unique, subtract them from the sum, and count their number.

The remaining sum is the sum of all elements occurring more than once, and the count of unique elements subtracted from the length of the array gives the number of matching element.

Body:
I was looking over some basic questions that might be asked in an interview. Using basic for loops (No hash maps etc)I want to sum up all the matching elements in an array.For example, 6 matching elements will result in (Matched: 6) and a total of 36 in the example below.An example of this could be rolling dice, and the score is the total of all the dice that match.

public static void main(String[] args) {

    int arr[] = {6,6,6,6,6,6};
    int matched = 1;
    int value = 0;
    int total = 0;
    for(int i=0;i<arr.length;i++){
        for(int j=(i+1);j<arr.length;j++){
            if(ar[i] == ar[j]){
                matched++;
                value = ar[i];
                break;
            }
        }
        total = (matched * value);
    } // End for loop
    System.out.println("Matched:"+(matched)+"");
    System.out.println("Total:"+total);
}

But, if the array was for example...

int arr[] = {6,1,1,6,6,6};

The output I get will be (Matched:5) and an a total of 30.Can could I store the matching pair of 1's and add them to the total using as little basic code as possible?


问:
Java:Transforming multiple XML file on single XSL file to generate single output XMLfile
I am in need to transform multiple input XML files into a single output XML using single XSL.
I am able to transform single XML on single XSL file using java JAXP. Below is the code I used, but I have no idea how to pass multiple input XML files to single XSL file</p>

```<code>        TransformerFactory factory = TransformerFactory.newInstance();
        StreamSource xslStream = new StreamSource("Transform_LineSequenceNumber1.xsl");

        StreamSource in = new StreamSource("Transform_LineSequenceNumber1-Source.xml");
        StreamResult out = new StreamResult("Output.xml");

        try {
            Transformer transformer = factory.newTransformer(xslStream);
            transformer.transform(in, out);

        } catch (Exception e) {
            e.printStackTrace();
        }
</code>```

答:
Besides the collection function XSLT has the standard function document to load additional xml in a stylesheet.

For example you can store it in a varablie then apply templates to that variable

```<code><xsl:variabe name='another_file' select='document("foo.xml")/' />
</code>```

A detailed example taken from the o'reilly XSLT book.

Body:
I am in need to transform multiple input XML files into a single output XML using single XSL.
I am able to transform single XML on single XSL file using java JAXP. Below is the code I used, but I have no idea how to pass multiple input XML files to single XSL file

        TransformerFactory factory = TransformerFactory.newInstance();
        StreamSource xslStream = new StreamSource("Transform_LineSequenceNumber1.xsl");

        StreamSource in = new StreamSource("Transform_LineSequenceNumber1-Source.xml");
        StreamResult out = new StreamResult("Output.xml");

        try {
            Transformer transformer = factory.newTransformer(xslStream);
            transformer.transform(in, out);

        } catch (Exception e) {
            e.printStackTrace();
        }

Body:
Besides the collection function XSLT has the standard function document to load additional xml in a stylesheet.

For example you can store it in a varablie then apply templates to that variable

<xsl:variabe name='another_file' select='document("foo.xml")/' />

A detailed example taken from the o'reilly XSLT book.


问:
xamarin ios rightbarbuttonitem uialertcontroller not showing in correct spot
I have created a rightbarbutton that brings up a memnu. It brings up my menu but at the bottom, I want it to appear under the rightbarbutton. From the xamarin users doc it says I need to set menu.PopoverPresentationController.BarButtonItem  to a button which I do, but it always return null for that line. Am I missing something/doimng it wrong?</p>

```<code>        var customBtn = new UIBarButtonItem();
        customBtn.Image = UIImage.FromFile("images/hamburger.png");
        _button = customBtn;
        customBtn.Clicked += (object sender, EventArgs e) =>
        {
            NavActionMenu(sender);
        };

        NavigationItem.RightBarButtonItem = customBtn;

    private void NavActionMenu(object sender)
    {
        UIAlertController menu = UIAlertController.Create("Menu", null, UIAlertControllerStyle.ActionSheet);

        UIAlertAction actionMail = (UIAlertAction.Create("Mail", UIAlertActionStyle.Default, (Action) =>
        {
            try
            {
                appD.type = "Mail";
                appD.user = _user;
                UIStoryboard sb = UIStoryboard.FromName("Main", null);
                var view = sb.InstantiateViewController("MailViewController") as MailViewController;
                appD.navCtrl.PushViewController(view, true);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.InnerException.Message);
            }
        }));

        UIAlertAction actionUserEdit = (UIAlertAction.Create("User", UIAlertActionStyle.Default, (Action) =>
        {
            try
            {
                appD.type = "Edit";
                appD.user = _user;
                UIStoryboard sb = UIStoryboard.FromName("Main", null);
                var view = sb.InstantiateViewController("SignupViewController") as SignupViewController;
                appD.navCtrl.PushViewController(view, true);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.InnerException.Message);
            }
        }));

        UIAlertAction actionLogout = (UIAlertAction.Create("Logout", UIAlertActionStyle.Default, (Action) =>
        {
            try
            {
                appD.user = null;
                UIStoryboard sb = UIStoryboard.FromName("Main", null);
                var view = sb.InstantiateViewController("ViewController") as ViewController;
                appD.navCtrl.PushViewController(view, true);
            }
           catch (Exception e)
            {
                Console.WriteLine(e.InnerException.Message);
            }
        }));

        menu.AddAction(actionMail);
        menu.AddAction(actionUserEdit);
        menu.AddAction(actionLogout);
        //menu.PopoverPresentationController.BarButtonItem = _button;

        this.PresentViewController(menu, true, null);

    }
</code>```

答:
First, you are doing it correctly.

UIPopoverPresentationController can be used in iPhone.

But UIPopoverPresentationController + UIAlertViewController seems not available in iPhone , However we can access it in iPad.

In my test ,menu.PopoverPresentationController always comes to null ,but it works perfectly in iPad.

Test:

Body:
I have created a rightbarbutton that brings up a memnu. It brings up my menu but at the bottom, I want it to appear under the rightbarbutton. From the xamarin users doc it says I need to set menu.PopoverPresentationController.BarButtonItem  to a button which I do, but it always return null for that line. Am I missing something/doimng it wrong?

        var customBtn = new UIBarButtonItem();
        customBtn.Image = UIImage.FromFile("images/hamburger.png");
        _button = customBtn;
        customBtn.Clicked += (object sender, EventArgs e) =>
        {
            NavActionMenu(sender);
        };

        NavigationItem.RightBarButtonItem = customBtn;

    private void NavActionMenu(object sender)
    {
        UIAlertController menu = UIAlertController.Create("Menu", null, UIAlertControllerStyle.ActionSheet);

        UIAlertAction actionMail = (UIAlertAction.Create("Mail", UIAlertActionStyle.Default, (Action) =>
        {
            try
            {
                appD.type = "Mail";
                appD.user = _user;
                UIStoryboard sb = UIStoryboard.FromName("Main", null);
                var view = sb.InstantiateViewController("MailViewController") as MailViewController;
                appD.navCtrl.PushViewController(view, true);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.InnerException.Message);
            }
        }));

        UIAlertAction actionUserEdit = (UIAlertAction.Create("User", UIAlertActionStyle.Default, (Action) =>
        {
            try
            {
                appD.type = "Edit";
                appD.user = _user;
                UIStoryboard sb = UIStoryboard.FromName("Main", null);
                var view = sb.InstantiateViewController("SignupViewController") as SignupViewController;
                appD.navCtrl.PushViewController(view, true);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.InnerException.Message);
            }
        }));

        UIAlertAction actionLogout = (UIAlertAction.Create("Logout", UIAlertActionStyle.Default, (Action) =>
        {
            try
            {
                appD.user = null;
                UIStoryboard sb = UIStoryboard.FromName("Main", null);
                var view = sb.InstantiateViewController("ViewController") as ViewController;
                appD.navCtrl.PushViewController(view, true);
            }
           catch (Exception e)
            {
                Console.WriteLine(e.InnerException.Message);
            }
        }));

        menu.AddAction(actionMail);
        menu.AddAction(actionUserEdit);
        menu.AddAction(actionLogout);
        //menu.PopoverPresentationController.BarButtonItem = _button;

        this.PresentViewController(menu, true, null);

    }


答:
I don't completely understand your question, but based from what I understood, you want to get the sum of all matched numbers if its greater than 1? In that case there is a O(n) solution that you could use.

Create an empty Map then iterate over the array, and if the current number is not within the map add it to the map with value 1, if the current element is already existing in the map then just increment it's value (val++), at the end you will have a map and for each key (each distinct number) you will have the number of matched numbers from the array as the value. All you need to do is iterate over the pairs of key,val multiply each key*val then sum up the multiplied values and you get your correct total. And if you need just the number of matched, you can in another variable sum up just the vals.

So for lets say array [1,1,5,1,5,2,2,5,1], your map will something like:

{1:4, 2:2, 5:3},

and your totals:

total matches: 9

total: 23

I hope this helps!

Title: Total all matching integer elements in an array


问:
Correcting the double summation formula written in pseudo-code

I have to implement the formula above in python, but I am having a difficulty fully understanding it. I wrote a pseudo code for doing this and I really need someone to correct it.

Given Info

So, I am running this code in a parallel corpus for Machine translation that consists of S sentence pairs (f
(s), e(s)), where 1 ≤ s ≤ S. So f(s) and e(s) represents s'th sentence in the corpus in f:foreign language and e: english. e_x is the x'th words in the sentence e(s)

I understood this formula as the following pseudo-code:

```<code>for a fixed english word e_x in all sentences:
    for all foreign word f_y in the sentence where f_y and e_x appears together:
        Z += apply the count in <.. I have the function for calculating this..>
</code>```

Am I understanding this formula correctly?

答:
It seems like Z_{e_x} is the computation of Z for whatever e_x is. So the formula you have is just for a single english word e_x. So you'd probably need a vector/map for each word.

Might look something like this

```<code>Z = {x: 0 for x in all_english_words}
for x in Z.keys():
    for y in all_foreign_words:
        for s in S:
            Z[x] += <your_function>
</code>```

Body:
I have to implement the formula above in python, but I am having a difficulty fully understanding it. I wrote a pseudo code for doing this and I really need someone to correct it.

Given Info

So, I am running this code in a parallel corpus for Machine translation that consists of S sentence pairs (f
(s), e(s)), where 1 ≤ s ≤ S. So f(s) and e(s) represents s'th sentence in the corpus in f:foreign language and e: english. e_x is the x'th words in the sentence e(s)

I understood this formula as the following pseudo-code:

for a fixed english word e_x in all sentences:
    for all foreign word f_y in the sentence where f_y and e_x appears together:
        Z += apply the count in <.. I have the function for calculating this..>

Am I understanding this formula correctly?

Body:
It seems like Z_{e_x} is the computation of Z for whatever e_x is. So the formula you have is just for a single english word e_x. So you'd probably need a vector/map for each word.

Might look something like this

Z = {x: 0 for x in all_english_words}
for x in Z.keys():
    for y in all_foreign_words:
        for s in S:
            Z[x] += <your_function>


问:
Perl: Parentheses vs Brackets for array definition, why is one considered a scalar?
I was following this tutorial on the HTML::Template module for Perl. Here's the template:

```<code><!--template2.tmpl-->
<html>
<body>
<table>
  <tr>
    <th>Language</th>
    <th>Description</th>
  </tr>
  <tmpl_loop name="language">
  <tr>
    <td><tmpl_var name="language_name"></td>
    <td><tmpl_var name="description"></td>
  </tr>
  </tmpl_loop>
</table>
</body>
</html>
</code>```

And here's the CGI test program:

```<code>#!"C:\Strawberry\perl\bin\perl.exe" -wT
use CGI qw(:all);
use CGI::Carp qw(fatalsToBrowser);
use HTML::Template;

my @rows = (
  {
    language_name => 'C#',
    description   => 'Created by Microsoft'
  },
  {
    language_name => 'PHP',
    description   => 'Hypertext Preprocessor'
  },
  {
    language_name => 'Haskell',
    description   => 'Functional language'
  },
);

print header;
my $template=HTML::Template->new(filename=>'template2.tmpl');
$template->param(language => @rows);
print $template->output();
</code>```

This fails with the following error: HTML::Template::param() : attempt to set parameter 'language' with a scalar - parameter is not a TMPL_VAR!

However, when I change the definition of @rows from using parenthesis to using square brackets(from my @rows=(...) to my @rows = [...]) the code works fine; it displays a table with the data.

As I understood from reading this article, the first form is an array defined from a list and the second one is a reference to an anonymous array. It's still not clear to me why the first form doesn't work. I'd appreciate you clarifying this for me.

答:
The param() method in HTML::Template takes pairs of arguments. The first value in the pair is the name of a template variable that you want to set and the second is the value that you want to set that variable to.

So you can make a call that sets a single variable:

```<code>$template->param(foo => 1);
</code>```

Or you can set multiple variables in one call:

```<code>$template->param(foo => 1, bar => 2, baz => 3);
</code>```

For reasons that should be obvious, the variable names given in your call to param() should all be variables that are defined in your template (either as standard tmpl_var variables or as looping tmpl_loop variables).

If you're setting a tmpl_loop  variable (as you are in this case) then the associated value needs to be a reference to an array containing your values. There is some attempt to explain this in the documentation for param(), but I can see how it might be unclear as it just does it by showing examples in square (array reference constructor) brackets rather than actually explaining the requirement.

The reason for this is that the list of parameters passed to a subroutine in Perl is "flattened" - so an array is broken up into its individual elements. This means that when you pass:

```<code>$template->param(languages => @rows);
</code>```

Perl sees it as:

```<code>$template->param(languages => $row[0], $row[1] => $row[2]);
</code>```

The elements of your array are hash references. This means that $row[1] will be interpreted as a stringified hash reference (something like "HASH(0x12345678)") which definitely isn't the name of one of the variables in your template.

So how do we fix this? Well, there are a few alternatives. You have stumbled over a bad one. You have used code like this:

```<code>@rows = [ ... ];
</code>```

This creates @rows an array with a single element which is a reference to your real array. This means that:

```<code>$template->param(language => @rows);
</code>```

is interpreted as:

```<code>$template->param(language => $rows[0]);
</code>```

And as $rows[0] is a reference to your array, it all works.

Far better would be to explicitly pass a reference to @rows.

```<code>@rows = ( ... ); # your original version

$template->param(language => \@rows);
</code>```

Or to create an array reference, stored in a scalar.

```<code>$rows = [ ... ];

$template->param(language => $rows);
</code>```

There's really nothing to choose between these two options.

However, I would ask you to consider why you are spending time teaching yourself HTML::Template. It has been many years since I have seen it being used. The Template Toolkit seems to have become the de-facto standard Perl templating engine.

Body:
I was following this tutorial on the HTML::Template module for Perl. Here's the template:

    Language
    Description

  <tmpl_loop name="language">

    <tmpl_var name="language_name">
    <tmpl_var name="description">

  </tmpl_loop>

And here's the CGI test program:

#!"C:\Strawberry\perl\bin\perl.exe" -wT
use CGI qw(:all);
use CGI::Carp qw(fatalsToBrowser);
use HTML::Template;

my @rows = (
  {
    language_name => 'C#',
    description   => 'Created by Microsoft'
  },
  {
    language_name => 'PHP',
    description   => 'Hypertext Preprocessor'
  },
  {
    language_name => 'Haskell',
    description   => 'Functional language'
  },
);

print header;
my $template=HTML::Template->new(filename=>'template2.tmpl');
$template->param(language => @rows);
print $template->output();

This fails with the following error: HTML::Template::param() : attempt to set parameter 'language' with a scalar - parameter is not a TMPL_VAR!

However, when I change the definition of @rows from using parenthesis to using square brackets(from my @rows=(...) to my @rows = [...]) the code works fine; it displays a table with the data.

As I understood from reading this article, the first form is an array defined from a list and the second one is a reference to an anonymous array. It's still not clear to me why the first form doesn't work. I'd appreciate you clarifying this for me.

Body:
The param() method in HTML::Template takes pairs of arguments. The first value in the pair is the name of a template variable that you want to set and the second is the value that you want to set that variable to.

So you can make a call that sets a single variable:

$template->param(foo => 1);

Or you can set multiple variables in one call:

$template->param(foo => 1, bar => 2, baz => 3);

For reasons that should be obvious, the variable names given in your call to param() should all be variables that are defined in your template (either as standard tmpl_var variables or as looping tmpl_loop variables).

If you're setting a tmpl_loop  variable (as you are in this case) then the associated value needs to be a reference to an array containing your values. There is some attempt to explain this in the documentation for param(), but I can see how it might be unclear as it just does it by showing examples in square (array reference constructor) brackets rather than actually explaining the requirement.

The reason for this is that the list of parameters passed to a subroutine in Perl is "flattened" - so an array is broken up into its individual elements. This means that when you pass:

$template->param(languages => @rows);

Perl sees it as:

$template->param(languages => $row[0], $row[1] => $row[2]);

The elements of your array are hash references. This means that $row[1] will be interpreted as a stringified hash reference (something like "HASH(0x12345678)") which definitely isn't the name of one of the variables in your template.

So how do we fix this? Well, there are a few alternatives. You have stumbled over a bad one. You have used code like this:

@rows = [ ... ];

This creates @rows an array with a single element which is a reference to your real array. This means that:

$template->param(language => @rows);

is interpreted as:

$template->param(language => $rows[0]);

And as $rows[0] is a reference to your array, it all works.

Far better would be to explicitly pass a reference to @rows.

@rows = ( ... ); # your original version

$template->param(language => \@rows);

Or to create an array reference, stored in a scalar.

$rows = [ ... ];

$template->param(language => $rows);

There's really nothing to choose between these two options.

However, I would ask you to consider why you are spending time teaching yourself HTML::Template. It has been many years since I have seen it being used. The Template Toolkit seems to have become the de-facto standard Perl templating engine.


问:
PHP filter library or class
I need a filter function for a project I'm working on.
I am thinking about using HTML purifier. However I concerned about it performance.

Does any of you guys used or using HTML purifier. Or do you suggest another library or class with similar functionality.

The most important issues are:

utf-8 support

xss security

答:
If you are looking for validation as well as filter options for variables then go with below library.

https://github.com/Wixel/GUMP

```<code># Note that filters and validators are separate rule sets and method calls. There is a good reason for this.

require "gump.class.php";

$gump = new GUMP();

$_POST = $gump->sanitize($_POST); // You don't have to sanitize, but it's safest to do so.

$gump->validation_rules(array(
    'username'    => 'required|alpha_numeric|max_len,100|min_len,6',
    'password'    => 'required|max_len,100|min_len,6',
    'email'       => 'required|valid_email',
    'gender'      => 'required|exact_len,1|contains,m f',
    'credit_card' => 'required|valid_cc'
));

$gump->filter_rules(array(
    'username' => 'trim|sanitize_string',
    'password' => 'trim',
    'email'    => 'trim|sanitize_email',
    'gender'   => 'trim',
    'bio'      => 'noise_words'
));

$validated_data = $gump->run($_POST);

if($validated_data === false) {
    echo $gump->get_readable_errors(true);
} else {
    print_r($validated_data); // validation successful
}
</code>```

Title: PHP filter library or class

Body:
If you are looking for validation as well as filter options for variables then go with below library.

https://github.com/Wixel/GUMP

# Note that filters and validators are separate rule sets and method calls. There is a good reason for this.

require "gump.class.php";

$gump = new GUMP();

$_POST = $gump->sanitize($_POST); // You don't have to sanitize, but it's safest to do so.

$gump->validation_rules(array(
    'username'    => 'required|alpha_numeric|max_len,100|min_len,6',
    'password'    => 'required|max_len,100|min_len,6',
    'email'       => 'required|valid_email',
    'gender'      => 'required|exact_len,1|contains,m f',
    'credit_card' => 'required|valid_cc'
));

$gump->filter_rules(array(
    'username' => 'trim|sanitize_string',
    'password' => 'trim',
    'email'    => 'trim|sanitize_email',
    'gender'   => 'trim',
    'bio'      => 'noise_words'
));

$validated_data = $gump->run($_POST);

if($validated_data === false) {
    echo $gump->get_readable_errors(true);
} else {
    print_r($validated_data); // validation successful
}


问:
What is the fastest way to get a random MPMediaItem
guys :) Can you please share some ideas how to get one or more random MPMediaItems from user's iPod Library. Any call to [MPMediaQuery songsQuery].items is waaaaay too slow - for a library of just 800 songs it takes about 19 seconds on my iPod Touch 2G to execute the query. I don't want to cache the entire iPod library, because I don't think it's worth the effort. Any thoughts will be greatly appreciated. Thank you :)</p>

答:
I wrote this method to retrieve a random track from the music collection for my iPad Jukebox application called My Jukebox, hopefully you can use it too. Its fast, even on big music collections and if you retain the MediaQuery object (store it as a property of the class) then the second call is almost instant. I hope it helps.</p>

```<code>-(MPMediaItem*) getRandomTrack
{
    // Check if we can re-use an MPMediaQuery
    if (self.mediaQuery == nil)
    {
        MPMediaQuery *everything = [[MPMediaQuery alloc] init];
        [self setMediaQuery:everything];
        [everything release];
    }
    // Get all Media Items into an Array (Fast)
    NSArray *allTracks = [mediaQuery items];
    // Check we have enough Tracks for a Random Choice
    if ([allTracks count] < 20)
    {
        return nil;
    }
    // Pick Random Track
    int trackNumber = arc4random() % [allTracks count];
    MPMediaItem *item = [allTracks objectAtIndex:trackNumber];
    // Display and Return
    return item;
}
</code>```

Body:
I wrote this method to retrieve a random track from the music collection for my iPad Jukebox application called My Jukebox, hopefully you can use it too. Its fast, even on big music collections and if you retain the MediaQuery object (store it as a property of the class) then the second call is almost instant. I hope it helps.

-(MPMediaItem*) getRandomTrack
{
    // Check if we can re-use an MPMediaQuery
    if (self.mediaQuery == nil)
    {
        MPMediaQuery *everything = [[MPMediaQuery alloc] init];
        [self setMediaQuery:everything];
        [everything release];
    }
    // Get all Media Items into an Array (Fast)
    NSArray *allTracks = [mediaQuery items];
    // Check we have enough Tracks for a Random Choice
    if ([allTracks count] < 20)
    {
        return nil;
    }
    // Pick Random Track
    int trackNumber = arc4random() % [allTracks count];
    MPMediaItem *item = [allTracks objectAtIndex:trackNumber];
    // Display and Return
    return item;
}