text:
Q: onclick on image passing dynamic parameters I'm creating a contextmenu in leaflet that is dynamically created according to the region of the map that was clicked (basically it displays the features next to the click). The menu is created using popup.
Question: I need to call a function passing "value" object as parameter when user clicks on image
My Code:

            proximos = queryFeatures(e.latlng, 1)

            var contentHtml = ''
            var tipo_icon = ''

            proximos.forEach(function (value, index) {

                contentHtml = contentHtml + "

"

                  **// call function with parameters on click this img:**

                contentHtml = contentHtml + "
"

                if (value.tipo == 'DMSCoord') {
                    tipo_icon = "{% static 'icons/icon-gps-location.svg'%}"
                }
                else if (value.tipo == 'airport') {
                    tipo_icon = "{% static 'icons/userpoint_Airport.svg'%}"
                } else if (value.tipo == 'waypoint') {
                    tipo_icon = "{% static 'icons/userpoint_waypoint.svg'%}"
                } else if (value.tipo == 'VOR') {
                    tipo_icon = "{% static 'icons/VOR.png'%}"
                }

                contentHtml = contentHtml + "

"

                contentHtml = contentHtml + "
" + value.txtname + "

"

            })

            var popup = L.popup()
                .setLatLng(e.latlng)
                .setContent(contentHtml)
                .openOn(map);
        });


text:
Q: Microsoft Ribbon´s RibbonWindow disables visual styles i just tried to use "RibbonWindow" to integrate my ribbon menu into the window.
But now, if i start the program, it looks like punched with a glitchy classic-style.
This is, how it should look like:
http://imageshack.us/photo/my-images/594/pfgok.png/
and this is how it looks like:
http://imageshack.us/photo/my-images/840/pfgfail.png/
Why is this so?
Thanks :)

A: Found the reason. This is a known defect in the pre .Net 4.5 release. Details can be found on connect.microsoft.com:
.NET 4.5 WPF RibbonWindow broken in VS2012
This should be fixed in the final release.

A: Try setting Window Class to RibbonWindow as in example

redpajama_set_name: RedPajamaStackExchange


text:
Q: const fns are an unstable feature when using AtomicUsize::new What is wrong with this code?
use std::sync::atomic::AtomicUsize;

static mut counter: AtomicUsize = AtomicUsize::new(0);

fn main() {}

I get this error:
error: const fns are an unstable feature
 --> src/main.rs:3:35
  |>
3 |> static mut counter: AtomicUsize = AtomicUsize::new(0);
  |>                                   ^^^^^^^^^^^^^^^^^^^
help: in Nightly builds, add `#![feature(const_fn)]` to the crate attributes to enable

The docs mention that other atomic int sizes are unstable, but AtomicUsize is apparently stable.
The purpose of this is to get an atomic per-process counter.

A: Yes, you cannot call functions outside of a function as of Rust 1.10. That requires a feature that is not yet stable: constant function evaluation.
You can initialize an atomic variable to zero using ATOMIC_USIZE_INIT (or the appropriate variant):
use std::sync::atomic::{AtomicUsize, ATOMIC_USIZE_INIT};

static COUNTER: AtomicUsize = ATOMIC_USIZE_INIT;

fn main() {}

As bluss points out, there's no need to make this mutable. And as the compiler points out, static and const values should be in SCREAMING_SNAKE_CASE.


text:
Q: It's running fine on my local pc but why it is causing error in Leetcode I can't understand? You are given two integer arrays nums1 and nums2, sorted in non-decreasing order, and two integers m and n, representing the number of elements in nums1 and nums2 respectively.
Merge nums1 and nums2 into a single array sorted in non-decreasing order.
The final sorted array should not be returned by the function, but instead be stored inside the array nums1. To accommodate this, nums1 has a length of m + n, where the first m elements denote the elements that should be merged, and the last n elements are set to 0 and should be ignored. nums2 has a length of n.
class Solution:
    def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
        """
        Do not return anything, modify nums1 in-place instead.
        """

        if len(nums1) == 0:
            for i in range(len(nums2)):
                nums1.append(nums2[i])

        i, j = 0, 0

        templist = []

        while i < m and j < n:
            if nums1[i] < nums2[j]:
                templist.append(nums1[i])
                i += 1
            else:
                templist.append(nums2[j])
                j += 1

        for k in range(len(nums1)):
            nums1[k] = templist[k]

        while i < m:
            nums1.append(nums1[i])
            i += 1
        while j < n:
            nums1.append(nums2[j])
            j += 1

Error:
IndexError: list index out of range
    nums1[k] = templist[k]
Line 24 in merge (Solution.py)
    ret = Solution().merge(param_1, param_2, param_3, param_4)
Line 66 in _driver (Solution.py)
    _driver()
Line 78 in <module> (Solution.py)```

it's running fine on my local pc then why the error in leetcode?

A: Your templist is not in general the same length as nums1 (it's shorter, that's why you need to extend it with nums1 or nums2 in the end to get the "whole" list merged).

A: Combine the two input lists. Sort them. Place result in the first of the input lists:
class Solution:
    def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
        nums1[:] = sorted(nums1[:m]+nums2[:n])


text:
Q: AWS-CloudWatch: InvalidSequenceTokenException I have a php worker where i log events to AWS could watch.
Unfortunately i got the following error when i try to submit it.

InvalidSequenceTokenException Error executing "PutLogEvents" on
  "https://logs.eu-west-1.amazonaws.com"; AWS HTTP error: Client error:
  POST https://logs.eu-west-1.amazonaws.com resulted in a 400 Bad
  Request response:
  {"__type":"InvalidSequenceTokenException","expectedSequenceToken":"999999999999990356407851919528174
  (truncated...)  InvalidSequenceTokenException (client): The given
  sequenceToken is invalid. The next expected sequenceToken is:
  495599999999988500356407851919528174642 -
  {"__type":"InvalidSequenceTokenException","expectedSequenceToken":"495573099999999900356407851919528174642","message":"The
  given sequenceToken is invalid. The next expected sequenceToken is:
  495579999999900356407851919528174642"}

and this is my code
 $date = new DateTime();
 $instance= = new CloudWatchLogsClient([
                'region' => 'eu-west-1',
                'version' => 'latest',
                'credentials' => [
                    'key' => 'XXX',
                    'secret' => 'XXXX'
                ]
            ]);
        $instance->putLogEvents([
                'logGroupName' => "WorkerLog",
                'logStreamName' => "log",
                'logEvents' => [
                    [
                        'timestamp' => $date->getTimestamp(),
                        'message' => "test log"
                    ]
                ]
            ]);

A: The DescribeLogStreams does not support the same volume call as PutLogEvent. You may got throttled if calling it frequently.
The recommended way to do it is calling the PutLogEvents directly and catch the InvalidSequenceTokenException. Then retry the PutLogEvents with Sequence Token in the InvalidSequenceTokenException message.
Correct sequence token can be found in the expectedSequenceToken field of InvalidSequenceTokenException
    try {
        $result = $client->describeLogStreams([
            'logGroupName' => $logGroupName,
            'logStreamNamePrefix' => $logStreamName,
        ]);

        $uploadSequenceToken = $logStreams[0]['uploadSequenceToken'];

        $client->putLogEvents([
            'logGroupName' => $logGroupName,
            'logStreamName' => $logStreamName,
            'logEvents' => [
                [
                    'timestamp' => $timestamp,
                    'message' => $message
                ],
            ],
            'sequenceToken' => $uploadSequenceToken,
        ]);
    } catch (\InvalidSequenceTokenException $e) {
        $client->putLogEvents([
            'logGroupName' => $logGroupName,
            'logStreamName' => $logStreamName,
            'logEvents' => [
                [
                    'timestamp' => $timestamp,
                    'message' => $message
                ],
            ],
            'sequenceToken' => $e->expectedSequenceToken,
        ]);
    }

A: http://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_PutLogEvents.html
You must include a sequence token with your request. If you don't have one you must use describeLogStreams (http://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_DescribeLogStreams.html) to get the stream sequence.
When you make a call to putLogEvents you will get the nextToken in the response. You also must be ready for the case in which someone else pushes to the stream and invalidates the nextToken. (in this case you need to describe the stream again to get an updated token).

A: This is my working solution: before send new putLogEvents you must take the last uploadSequenceToken.
    try {
        $client = \Aws\CloudWatchLogs\CloudWatchLogsClient::factory($configCloudWatch);

        $logStreamName = 'testLogStream';
        $logGroupName = 'testGroupName';

        $result = $client->describeLogStreams([
            'logGroupName' => $logGroupName,
            'logStreamNamePrefix' => $logStreamName,
        ]);
        $logStreams=$result->get('logStreams');
        if (!$logStreams)
            throw new \Exception('No log stream found');
        if (count($logStreams)!=1)
            throw new \Exception('Multiple log stream found');
        $uploadSequenceToken = $logStreams[0]['uploadSequenceToken'];

        $client->putLogEvents([
            'logGroupName' => $logGroupName,
            'logStreamName' => $logStreamName,
            'logEvents' => [
                [
                    'timestamp' => round(microtime(true) * 1000),
                    // message is required
                    'message' => json_encode([ ... ]
                    ),
                ],
            ],
            'sequenceToken' => $uploadSequenceToken,
        ]);
    } catch (\Exception $e) {
        \Log::error(__METHOD__, ['exception' => $e]);
    }


text:
Q: JQUERY & CSS DOWN MENU - Unable to keep background of
* highlighted when hovering over subitem(a div) I created a mega dropdown menu with the hoverintent plugin which works like a charm, except the li background color wont stay black when i put my mouse into the subdiv.  I know its probably a silly fix, but I can't figure it out. Please help...
Site:http://www.nestudiosonline.com/test.php
html:

DKE.ORG

ABOUT DKE
div content

ALUMNI

UNDERGRADUATES

EVENTS

MULTIMEDIA

SHOP DKE

CSS:
ul#menu
{
    display:block;
    list-style-type:none;
    margin:0;
    padding:0;
}

ul# menu li
{
    display:inline;
    position: relative;
    }

ul#menu div {
  display: none;
}

ul#menu li.mega div {
    position: absolute;
}

ul#menu li.hovering div {
  display: block;
}

#aboutdke
{
    display:block;
    color:#FFF;
    text-align:left;
    font-family:Verdana, Geneva, sans-serif;
    font-size:10px;
    background-color:#000;
    margin:0;
    padding-top:10px;
    padding-right:10px;
    padding-bottom:10px;
    padding-left:10px;
    border:0px;
    width:910px;
    height:280px;
    float:left;
    position:absolute;
    z-index:99999;
    top:164px;
    left:140px;
}

a.links:link
{
    display:block;
    width:120px;
    height:22px;
    padding-top:8px;
    padding-left:3px;
    padding-bottom:0px;
    color:#FFF;
    text-decoration:none;
    text-align:center;
    outline:none;
    float:left;
}

a.links:visited
    {
    display:block;
    width:120px;
    height:22px;
    padding-top:8px;
    padding-left:3px;
    padding-bottom:0px;
    color:#FFF;
    text-decoration:none;
    text-align:center;
    outline:none;
    float:left;
    }

/* mouse over link */

a.links:hover
    {
    display:block;
    width:120px;
    height:22px;
    padding-top:8px;
    padding-left:3px;
    padding-bottom:0px;
    color:#FFF;
    text-decoration:underline;
    text-align:center;
    outline:none;
    background-color:#000;
    float:left;
    }

/* selected link */

a.links:active
    {
    display:block;
    width:120px;
    height:22px;
    padding-top:8px;
    padding-left:3px;
    padding-bottom:0px;
    color:#FFF;
    text-decoration:underline;
    text-align:center;
    outline:none;
    background-color:#000;
    float:left;
    }

JQUERY:

A: ul#menu li.hovering {
  background-color:#000;
}

So the list item itself will have a black background, all child elements - with transparent backgrounds themselves - will also have that parent's black background.


text:
Q: How can I play Pixelmon? I am playing Minecraft and would love to play the Pokemon version, Pixelmon. The only problem is, I don't know how to get Pixelmon.
Is it just something you download in Minecraft, or is it gotten separately? Do you know?

A: PixelMon is a mod for minecraft. Mods are add-on files that change how minecraft is played or how it looks or usually both to some extent. They can be difficult to install if your not computer savvy, and sometimes they are difficult to install even if you are computer savvy, but usually it's not too big of a problem if you pay attention and follow the instructions properly. The instructions to install a mod are almost always included in the forum thread dedicated to the mod. (linked above) The forum thread is also where the download link for the mod can usually be found.
TL:DR: You play Pixelmon by downloading and installing it. You will find the install file and instructions to install it in its forum thread on the Minecraft Forums.


text:
Q: AcceptHeaderLocaleResolver - still unclear how to use it I tried to use the AcceptHeaderLocaleResolver in my application. I have made a lot of searches, but I still don't understand how to use it correctly. For the moment, the following code is the one that's working:
HeaderLocaleResolver class:
@Component
class HeaderLocaleResolver {

    private val acceptHeaderResolver = AcceptHeaderLocaleResolver()

    init {
        acceptHeaderResolver.defaultLocale = Locale.ENGLISH
    }

    fun getLocale(request: HttpServletRequest): Locale{
        return acceptHeaderResolver.resolveLocale(request)
    }
}

My rest controller class:
@RequestMapping("/rest/report")
@RestController
class PrinterController(private val printerService: PrinterService,
                        private val localeResolver: HeaderLocaleResolver) {

    @PostMapping("/{folder}/{templateName}")
    fun printReport(request: HttpServletRequest,
                    @PathVariable("folder") folder : String,
                    @PathVariable("templateName") templateName :String,
                    @RequestParam("doctype") doctype: DocumentType,
                    @RequestBody data: String) : ResponseEntity<InputStreamResource> {
        val locale = localeResolver.getLocale(request)
        val printedReport = printerService.printReport(folder, templateName, doctype, data, locale)
        return ResponseEntity.ok().contentType(printedReport.mediaType)
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; fileName=" + printedReport.filename)
                .body(InputStreamResource(ByteArrayInputStream(printedReport.content)))
    }

}

At the moment this is working fine, but what I don't understand is: do I really have to use the AcceptHeaderLocaleResolver class in this way? I read lots of posts that shows how to override default configuration of the LocalChangeInterceptor but to me it looks like that class needs a URL parameter that contains the "lang" parameter, and then he resolves using that parameter, but what I want to do it's to simply use the header. Is there a way to define an interceptor that reads only from headers the language and than allows you to access that value, maybe throught the LocaleContextHolder class?
All previous posts/questions seems to lack a bit of code, I tried almost all of them by I end up with non working code or exceptions.

A: Nevermind... I've simplyfied my controller in this way:
@RequestMapping("/rest/report")
@RestController
class PrinterController(private val printerService: PrinterService) {

    @PostMapping("/{folder}/{templateName}", consumes = [MediaType.APPLICATION_JSON_VALUE])
    fun printReport(@RequestHeader(name = "accept-language", defaultValue = "en") lang: String,
                    @PathVariable("folder") folder: String,
                    @PathVariable("templateName") templateName: String,
                    @RequestParam("doctype") doctype: DocumentType,
                    @RequestBody data: String): Mono<ResponseEntity<InputStreamResource>> {
            logger.debug{ "Payload to print: $data in language $lang" }
            return printerService.printReport(folder, templateName, doctype, data, lang)
                .map { report -> ResponseEntity.ok().contentType(report.mediaType)
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; fileName=${report.filename}")
                .body(InputStreamResource(ByteArrayInputStream(report.content))) }
    }

}


text:
Q: Longest Common Subsequence top-bottom #include <iostream>
#include <cstring>
using namespace std;

int LCS(string x, string y , int n , int m)
{
  int t[n+1][m+1];
  for(int i=0;i<=n+1;i++)
    for(int j=0;j<=m+1;j++)
    {
        if(i==0 || j==0)
            t[i][j]=0;
    }
  for(int i=1;i<=n+1;i++)
    for(int j=1;j<=m+1;j++)
    {
        if(x[i-1]==y[j-1])
            t[i][j]=1+t[i-1][j-1];
        else
            t[i][j]=max(t[i-1][j],t[i][j-1]);
    }
  return t[n][m];
}

int main()
{
    string x;
    string y;
    cin>>x>>y;
    LCS(x,y,x.length(),y.length());
    return 0;
}

o/p=Process returned 0 (0x0)   execution time : 3.342 s
Press any key to continue.
the o/p to the following code is always zero . idk why. plzz help . what wrong am I doing ?

A:
the o/p to the following code is always zero

because your main does :

...
LCS(x,y,x.length(),y.length());
return 0;

but you want :
...
return LCS(x,y,x.length(),y.length());

Out of that

 int t[n+1][m+1];

is a variable length array, do not use them (see Why aren't variable-length arrays part of the C++ standard?) but array dynamically allocated in the heap, because the size are not known at compile time you can use a std::vector<std::vector<int>> and for instance replace

 int t[n+1][m+1];
 for(int i=0;i<=n+1;i++)
   for(int j=0;j<=m+1;j++)
   {
       if(i==0 || j==0)
           t[i][j]=0;
   }

by
  std::vector<std::vector<int>> t(n+1);

  for (int i = 0; i <= n; ++i)
    t[i].resize(m+1);

BTW your loops are wrong because the right tests are i<=nand j<=m everywhere


text:
Q: How to let multiple web address (http) point to the smae webpage I want 3 or more web address (http) point to the smae webpage, how to do so
in python or html,css,javascript way

*

*http://192.168.0.206:8080/english/index.html

*http://192.168.0.206:8080/english/apple

*http://192.168.0.206:8080/english?fruit_ID=001
I have done the learning about flask, can command in web address, but still need a hand
is a concept question so that I don't post the code, I just need the key word for this idea, so that I can look it up too, or luckily if someone know ho to do, thanks

I have read through the discussion, the Http Redirection code 3XX in python requests was the closest, but that one not slove my problem


text:
Q: Unmount/detach/deactivate PostgreSQL database I manage a server that serves several web applications that use PostgreSQL as a data store.  Each web application has a separate role and database, and each database is stored exclusively on a dedicated tablespace on a different logical file system.
What I would like to be able to do is unmount a web app's file system without affecting postgres - if I do that at the moment CHECKPOINTs fail to run, so CREATE DATABASE, VACUUM, and other commands fail.
Is there a way to "deactivate" a database so that PostgreSQL won't try to checkpoint or autovacuum it?

A: This is not possible with PostgreSQL at this time.
What you're talking about is more like a "quiesce" or "stop" than a "detach". You don't seem to want to be able to move it from one PostgreSQL instance to another.
The issues are:

*

*Transaction IDs are global. Pg would have to stop all writes to the DB then VACUUM FREEZE it, which is quite expensive, to make sure there would be no txid wrap-around issues when it was re-enabled.

*Pg needs to be able to tell if a database contains objects that depend on a global object like a user, so when you DROP USER it can reject the attempt if it'd violate dependencies.

*... and probably more
I don't think it's impossible, theoretically, but it's not going to be trivial to impliment. It also won't be very useful - I don't see what you gain from this over simply leaving the DB unused, or at most forcing a VACUUM FREEZE. Checkpoint activity is insignificant to nil if there's no activity in the DB, same with autovacuum.


text:
Q: $concatArrays not working on existing multi array field I have this sample document with key values set to be array of arrays.
{ _id: 1, items: [ [1, 2, 3], [4, 5, 6] ] }

Here is my aggregate function
db.collection.aggregate([

   { $project: { items: { $concatArrays: "$items" } } }

])

Result should be:
{ _id: 1, items: [1, 2, 3, 4, 5, 6] }

However results are:
{ _id: 1, items: [ [1, 2, 3], [4, 5, 6] ] }

Is there is another way to achieve the required output? I know I that I could use lodash _.flattenDeep(items), but I'm looking for mongodb solution.
Here is my mongo Playground

A: I've seen you already got your answer but I'll briefly explain why this behaviour is happening for anyone curios.
This is actually a "feature" of Mongo, there is an open feature change request you can track. but first let's understand what's causing it:

There are a class of expressions which accept multiple arguments, expressed as an array. (In the code, these inherit from ExpressionNary.) For any such n-ary expression, which I will call $nary, the syntax {$nary: "$myArg"} is simply a shorthand for {$nary: ["$myArg"]}. These two expression are identical in meaning.

So this unique class of expressions include many operators, one of them is $concatArrays. Mongo's expression languages just parses any '$arg' as ['$arg'] for these operators.
This is why the 'unexpected' behaviour happens when you used the $dups expression but does not happen when you explicitly write the same values.

A: You can use below aggregation
db.collection.aggregate([
  { "$project": {
    "items": {
      "$reduce": {
        "input": "$items",
        "initialValue": [],
        "in": { "$concatArrays": ["$$this", "$$value"] }
      }
    }
  }}
])

MongoPlayground


text:
Q: EXCEL VBA: getting the integer value of mm in today's date novice programmer here and it's my first question here.
I'm interested in doing some invoicing using excel, and a part of that is generating invoice numbers, e.g. 1870001-1879999, referring to the year 2018, the month of July, and the 1st to 9999th invoice of this month.
To do this, I've written a bit of code:
Private Sub Workbook_Open()

Dim MValue As String
Dim XValue As Integer

MValue = Format(Date, "mm/dd/yy")
LValue = Left(MValue, 2)
XValue = CInt(LValue)
Range("K1").Value = XValue

End Sub

This would give me "7" as an integer in the cell K1, which I can then multiply by 10000 and add to 1800000 to give the baseline value of 1870000.
I have two questions:
1) what's a better way to do this problem? My method seems incredibly long. (dates are stored awkwardly in excel)
2) why is it that:
    Range("K1").Value = XValue * 10000
   causes an error?
Thanks.

A: Your problem is because Integer cannot handle the size of the number you are trying to pass. You will get an overflow error.
Declare as Long to avoid this.
Dim XValue As Long
CLng(LValue)

What you have written could be re-written as:
Range("K1").Value = Month(Date) * 10000

A: You can use Day and Month functions. Here's one of the possible solutions:
Sub G()
    Dim dt As Date, d, m, s
    dt = Now
    d = Day(dt): m = Month(dt)
    s = d & m & GenerateID()
End Sub
Function GenerateID()
    GenerateID = "SOMETHING"
End Function


text:
Q: TravisCI login with credentials return "Not Found", can't execute any travis TravisCI login with credentials return "Not Found", can't execute any Travis command because it asks to login --pro, which I suppose is API endpoint for a pro account, which I don't have.
I have installed ruby from the msi installer, and then Travis using gem install travis.
I installed ruby and then installed using chocolatey.
Report:
Username: ajfmo
Password for ajfmo: *********
Not Found
for a full error report, run travis report

ajfm@DESKTOP-FJTHL36 MINGW64 ~/Desktop/ideaProjects/ICRM-DevOrg (main)
$ travis report
System
Ruby:                     Ruby 3.0.0-p0
Operating System:         Windows
RubyGems:                 RubyGems 3.2.3

CLI
Version:                  1.10.0
Plugins:                  none
Auto-Completion:          yes
Last Version Check:       2021-02-04 14:00:04 -0500

Session
API Endpoint:             https://api.travis-ci.org/
Logged In:                no
Verify SSL:               yes
Enterprise:               no

Endpoints
org:                      https://api.travis-ci.org/ (current)
com:                      https://api.travis-ci.com/ ()

Last Exception
An error occurred running `travis login`:
    RuntimeError: Not Found
        from C:/tools/ruby30/lib/ruby/gems/3.0.0/gems/travis-1.10.0/lib/travis/tools/github.rb:212:in `rescue in basic_auth'
        from C:/tools/ruby30/lib/ruby/gems/3.0.0/gems/travis-1.10.0/lib/travis/tools/github.rb:208:in `basic_auth'
        from C:/tools/ruby30/lib/ruby/gems/3.0.0/gems/travis-1.10.0/lib/travis/tools/github.rb:216:in `login'
        from C:/tools/ruby30/lib/ruby/gems/3.0.0/gems/travis-1.10.0/lib/travis/tools/github.rb:81:in `possible_tokens'
        from C:/tools/ruby30/lib/ruby/gems/3.0.0/gems/travis-1.10.0/lib/travis/tools/github.rb:50:in `each_token'
        from C:/tools/ruby30/lib/ruby/gems/3.0.0/gems/travis-1.10.0/lib/travis/tools/github.rb:37:in `with_token'
        from C:/tools/ruby30/lib/ruby/gems/3.0.0/gems/travis-1.10.0/lib/travis/cli/login.rb:31:in `login'
        from C:/tools/ruby30/lib/ruby/gems/3.0.0/gems/travis-1.10.0/lib/travis/cli/login.rb:50:in `run'
        from C:/tools/ruby30/lib/ruby/gems/3.0.0/gems/travis-1.10.0/lib/travis/cli/command.rb:200:in `execute'
        from C:/tools/ruby30/lib/ruby/gems/3.0.0/gems/travis-1.10.0/lib/travis/cli.rb:64:in `run'
        from C:/tools/ruby30/lib/ruby/gems/3.0.0/gems/travis-1.10.0/bin/travis:18:in `<top (required)>'
        from C:/tools/ruby30/bin/travis:23:in `load'
        from C:/tools/ruby30/bin/travis:23:in `<main>'

For issues with the command line tool, please visit https://github.com/travis-ci/travis.rb/issues.
For Travis CI in general, go to https://github.com/travis-ci/travis-ci/issues or email support@travis-ci.com.

A: For some reason login itself keeps failing, I was able to log in by creating a GitHub token for Travis following this document and using travis login --github-token


text:
Q: How to add records to the hasMany attribute of an Ember Model? I am using the latest Ember Data version 1.0.0-beta. I am trying to add objects to a hasMany relationship in local storage but  am having some problems.
I have two models:
App.Item = DS.Model.extend({
    description: DS.attr('string'),
});

App.Basket = DS.Model.extend({
  selectedItems: DS.hasMany('item'),
  name: DS.attr('string'),

})

I have an array called "Items_descriptions" that contains an array of description strings.
I am trying to insert items into a basket using the following manner:
var basket_record = App.Basket.store.createRecord('basket', { name: 'Test_record' });

var itemsarray = [];

Items_descriptions.forEach(function(description){

    var item  = App.Item.store.filter('item', function(record){return record.get('description') == description}).objectAt(0);
    itemsarray.push(item);
});

basket_record.get('selectedItems').pushObjects(itemsarray); // ***errors out here****

basket_record.save();

However I get the following error at this line basket_record.get('selectedItems').pushObjects(itemsarray);" :

Uncaught TypeError: Cannot read property 'typeKey' of undefined

I also tried using the App.Model.store.find method, however that also doesnt work:
var basket_record = App.Basket.store.createRecord('basket', { name: 'Test_record' });
var itemsarray = [];

Items_descriptions.forEach(function(description){

   App.Item.store.find('item', {'description': description}).then(function(item){

       itemsarray.push(item);
   });
});
basket_record.get('selectedItems').pushObjects(itemsarray);

basket_record.save();

The App.Mode.store.find method works but it doesnot add the data successfully into the selectedItems attribute. When I check localstorage, the name attribute in basket is correctly filled out, but the array for selected Items is empty.
From what I understand,  App.Model.store.find returns a promise and an App.Model.store.filter().objectAt(0) returns the object itself.
Any idea what I am doing wrong here? Any help is greatly appreciated. Thanks so much!

A: The way I resolved this was by changing my ember data to the online version. I was using a downloaded version of ember data (downloaded on 13th September). But in the past ten days, there have been several edits made to the ember-data js library. I am guessing the error was initially experienced due to bugs in the previous versions. After I updated to the latest online version of ember data, the hasMany relationship is getting updated now.
FYI: I am using the first method of App.Model.store.filter(..).objectAt(0) to get the objects and set it to the hasMany relationship.


text:
Q: iPhone 4 - no provisioned iphone os is connected I'm trying to install an app onto an iPhone 4 and I get:
no provisioned iphone os is connected
I am using:

*

*Xcode 3.2.3

*iTunes 9.2

*iPhone 4.0 with iOS 4.0 (8A293)

I have the development provisioning profile in XCode and in the phone.
The Organizer window shows the iPhone 4 with a green circle next to it.  I have the correct App ID in the bundle identifier in Info.plist.
I've tried powering on/off phone, stopping/re-starting Xcode and iTunes with no luck.
Any ideas what is wrong?

A: If the profile is installed, you are probably trying to install the app on the device with the build configuration set to "Distribution"... you need to set it to "Debug" or "Release" in the drop-down menu in XCode on the main window.
So, build options should be "Debug" and "Device"

A: Did you check the status of the Organizer?  From Xcode, go under Window->Organizer, and look under the DEVICES section on the left pane.  It should show the connected devices, and provide a more detailed explanation (e.g., device is not enabled for development, OS installed on phone is not supported by SDK, etc).
One possibility is that you are running 4.0.1 on your phone, but only have the 4.0 SDK installed.

A: Double check the provisioning profile is tied to the build you are doing: Right click-> Info on the project icon in Groups & Files then Build and scroll down to Code Signing.
There seem to be a million different things that can go wrong with getting the app to the iPhone, I never get it right the first time.
I've followed this before: http://adeem.me/blog/2009/04/24/tutorial-list-guideline-for-building-ad-hoc-application-for-iphone/
It's for Ad Hoc but most of the steps are the same.

A: I figured out what the problem was. I had the build set to iPad and I was trying to download to an iPhone! I hope this helps someone else.


text:
Q: Sort upcoming birthdays based on current date I have the following table of people and their birthdays:
name        birthday
----------------------
yannis      1979-06-29
natalia     1980-08-19
kostas      1983-10-27
christos    1979-07-22
kosmas      1978-04-28

and I have no idea how to sort the names on how closer the birthday is to today. So for NOW() = 2011-09-08 the sorted result should be:
kostas      1983-10-27
kosmas      1978-04-28
yannis      1979-06-29
christos    1979-07-22
natalia     1980-08-19

I'm looking for a quick hack, don't really care for performance (pet project - table will hold less than 1000 records), but of course every suggestion will be extremely appreciated.

A: SELECT name
     , birthday
FROM TableX
ORDER BY DAYOFYEAR(birthday) < DAYOFYEAR(CURDATE())
       , DAYOFYEAR(birthday)

No, the above may produce error results, due to years with 366 days. This is correct:
SELECT name
     , birthday
FROM
  ( SELECT name
         , birthday
         , MONTH(birthday) AS m
         , DAY(birthday) As d
    FROM TableX
  ) AS tmp
ORDER BY (m,d) < ( MONTH(CURDATE()), DAY(CURDATE()) )
       , m
       , d

If your table grows to more than a few thousands records, it will be real slow. If you want a fast query, add fields with the month and day and have an index on (bmonth,bday) or add them as one field, either Char (08-17 or 0817 for 17-Aug) or Int (817 for 17-Aug) and an index on that field.

A: Seems to be rather fast, no problems with leap years:
SELECT *
FROM `people`
ORDER BY CONCAT(SUBSTR(`birthday`,6) < SUBSTR(CURDATE(),6), SUBSTR(`birthday`,6))

Все гениальное -- просто! ;)

A: Not pretty, but works
SELECT *
,CASE WHEN BirthdayThisYear>=NOW() THEN BirthdayThisYear ELSE BirthdayThisYear + INTERVAL 1 YEAR END AS NextBirthday
FROM (
    SELECT *
    ,birthday - INTERVAL YEAR(birthday) YEAR + INTERVAL YEAR(NOW()) YEAR AS BirthdayThisYear
    FROM bd
) AS bdv
ORDER BY NextBirthday

A: Here is one way:

*

*Calculate current year - year of birth

*Add the resulting number of years to the date of birth

*You now have the birthday this year, if this date has passed then add one more year

*Sort the results by that date

SELECT
    name,
    birthday,
    birthday + INTERVAL (YEAR(CURRENT_DATE) - YEAR(birthday))     YEAR AS currbirthday,
    birthday + INTERVAL (YEAR(CURRENT_DATE) - YEAR(birthday)) + 1 YEAR AS nextbirthday
FROM birthdays
ORDER BY CASE
    WHEN currbirthday >= CURRENT_DATE THEN currbirthday
    ELSE nextbirthday
END

Notes:

*

*Today's birthdays appears first regardless of current time

*February 29 birthday is treated equal to February 28 birthday for common years e.g.

*

*On Jan/1/2019 both Feb 28 and Feb 29 birthdays (2019) are sorted equal

*On Mar/1/2019 Feb 28 and Feb 29 birthdays (2020) are sorted as expected

SQLFiddle

A: i would try it like this (but this isn't tested):
SELECT
  name,
  birthday
FROM
  birthdays
ORDER BY
  ABS( DAYOFYEAR(birthday) - (DAYOFYEAR(CURDATE()) ) ASC

EDIT:
changed ordering from DESC to ASC because you want to get the farthest first, not the closest.


text:
Q: Plugin Using get_the_content Causing Issues With  Tag I'm testing out the Woothemes "Our Team" plugin to see how it works for future project purposes.
The plugin uses at CPT for Team Members as well as a shortcode to allow users to display members on a page.
The issue that I'm bumping into is that the content that is output by the shortcode is not honoring the <!--more--> tag.  I'm assuming it's because in the woothemes-our-team-template.php file on line 196 it's using get_the_content as shown below:
$content = apply_filters( 'woothemes_our_team_content', wpautop( get_the_content() ), $post );
It appears that there is also a filter that should be able to be hooked into called "woothemes_our_team_content" but no matter what I try to add into my functions.php I can't get it to recognize that there is a <!--more--> tag.  All my efforts have only managed to remove all the content.
Essentially I'd like to hook into the filter, have it recognize the <!--more--> tag, and then change "Read More" to say "Read Full Bio...".
Doe anyone have any suggestions on the best way to achieve this?
Thanks in advance!

A: The logical fork between displaying full content and teaser (that's what part from start of post to more tag is called) is ruled by $more global variable. Which depends on other global stuff and so on, important point being it's not set to 0 when you want it to be. Likely because you are running this in context when it wouldn't be set to zero for normal loop either.
Something like this should work:
add_filter( 'woothemes_our_team_content', function () {
    global $more;
    $real_more = $more;
    $more      = 0;
    $output    = wpautop( get_the_content() );
    $more      = $real_more;

    return $output;
} );

You can just work with link there, or hook into the_content_more_link to customize it.


text:
Q: Check during runtime which persistence provider a Java EE server is using? I am not looking to find out whether or not a class has been loaded using low-level Reflection API. This question has been posted here and has some answers. I want to use "clean code", preferably using an API as specified in a Java EE  specification (for example, JPA 2.1).
My real problem is that I need to write a patch that applies only for Hibernate.

A: See the Java Persistence 2.1 specification, section "9.3 Determining the Available Persistence Providers".
Example
PersistenceProviderResolver resolver = PersistenceProviderResolverHolder.getPersistenceProviderResolver();
List<PersistenceProvider> providers = resolver.getPersistenceProviders();

Note that there exists a Persistence.PERSISTENCE_PROVIDER (String) and a Persistence.providers (Set) but these fields has been deprecated according to their JavaDoc.
The PersistenceProvider interface doesn't say much. But the class behind the interface reveals the provider.
In GlassFish 4.0.1-b08-m1 that bundles EclipseLink 2.5.2, only one provider is returned: org.eclipse.persistence.jpa.PersistenceProvider.
In WildFly 8.1.0 that bundles Hibernate 4.3.5, two providers are returned. The second provider's class is org.hibernate.ejb.HibernatePersistence (order may be machine dependent?). According to the class JavaDoc, it has been deprecated in favor of the first provider in the List: org.hibernate.jpa.HibernatePersistenceProvider.
Note that the JPA specification emphasize that it might not be safe to cache this information:

In dynamic environments (e.g., OSGi-based environments, containers
  based on dynamic kernels, etc.), the list of persistence providers may
  change.

Note also that PersistenceProviderResolver.getPersistenceProviders() is used to " determine the list of available persistence providers". I have not yet understood how to determine the persistence provider in use. For example, in WildFly I would like to get hold of just one provider, not two.
Java 1.8 Solution
// "providers" is the variable declared in the example at the beginning
boolean usingHibernate = providers.stream()
        .map(Object::getClass)
        .map(Class::getName)
        .anyMatch(str -> str.startsWith("org.hibernate"));

Java 1.7 Solution
boolean usingHibernate = false;

for (PersistenceProvider p : providers) {
    if (p.getClass().getName().startsWith("org.hibernate")) {
        usingHibernate = true;
        break;
    }
}


text:
Q: In PHP how can I get the count of each instance in a mySQL table column? To clarify, I am trying to get a table to output that displays my MySQL database table in a certain way.  The table is populated with names, birth-years, and zodiac animals.
What I want to do is have a table row that says something like "cat zodiac signs" and then a heading of "name" and "birth year". Under that I want each persons' name and year they were born. I want this done for each zodiac animal.
The issue I am having is that the heading for is displaying each instance of the zodiac column. I know my code is wrong, I am just not sure what to do next!  Please help! Here is my code
$TableName = "zodiacshared";
        $SQLstring = "SELECT * FROM $TableName GROUP BY sign, birthyear";
        $QueryResult = @mysql_query($SQLstring, $DBConnect);
        if (mysql_num_rows($QueryResult) == 0){
            echo "
 There are no entries in the chinese zodiac gallery!
";
        }
        else{
            echo "
";
            while ($row=mysql_fetch_array($QueryResult)){
                    echo ""; echo $row['sign']; echo " zodiac signs	";
                    echo "
Name	Birth Year
";
                    echo "
";
                    echo ""; echo $row['name']; echo "	";
                    echo ""; echo $row['birthyear']; echo "	";
                    echo "
";

            }
            echo "
";
            mysql_free_result($QueryResult);
        }

Edit:  Right that may be helpful
My hopeful output is something like this (this is a rough draft made on Excel, but gets point across):

edit 2:  Solution was:
$current_zodiac= '';
            while ($row=mysql_fetch_array($QueryResult)){
                    if ($row['sign']!=$current_zodiac){
                        echo ""; echo $row['sign']; echo " zodiac signs	";
                        echo "
Name	Birth Year
";
                    }else{
                        //echo the other rows
                    }
                        echo "
";
                        echo ""; echo $row['name']; echo "	";
                        echo ""; echo $row['birthyear']; echo "	";
                        echo "
";
                    $current_zodiac = $row['sign']; //assign new zodiac to current zodiac variable

            }

A: You can have one variable to store current zodiac name in your while loop. So every time the zodiac name is unique which means new zodiac found in the while loop, you can print new header for it.
For example, the flow could be like this.
$current_zodiac = '';
while ($row=mysql_fetch_array($QueryResult)){
if ($row['sign']!=$current_zodiac){
 echo ""; echo $row['sign']; echo " zodiac signs	";
}else{
//echo the other rows
}
$current_zodiac = $row['sign']; //assign new zodiac to current zodiac variable

}


text:
Q: Kendo - Display dropdown over-top parent div I'm using the Kendo Ext library (https://github.com/jsExtensions/kendoui-extended-api) to render a Treeview inside of a Dropdown List. The problem I'm having is that the control get's hidden underneath the parent div. However when compared to the normal Kendo Dropdown List, that control does not suffer the same problem.
This is the example I have so far:
https://jsfiddle.net/6xxau9d4/1/
HTML

  <input id="sample1" value="1" style="width: 150;" />
  <input id="sample2" value="1" style="width: 150x;" />

JS
var dropDownTreeView = $("#dropDownTreeView").kendoExtDropDownTreeView({
  treeview: {
    dataSource: new kendo.data.HierarchicalDataSource({
      data: [{
        text: "Furniture",
        items: [{
          text: "Tables & Chairs"
        }, {
          text: "Sofas"
        }, {
          text: "Occasional Furniture"
        }]
      }, {
        text: "Decor",
        items: [{
          text: "Bed Linen"
        }, {
          text: "Curtains & Blinds"
        }, {
          text: "Carpets"
        }]
      }]
    })
  }
}).data("kendoExtDropDownTreeView");

dropDownTreeView.dropDownList().text("Dropdown Treeview")

$(document).ready(function() {

  $("#sample1").kendoDropDownList({
    dataTextField: "text",
    dataValueField: "value",
    dataSource: [{
      text: "Sample1",
      value: null
    }],
    template: "
test
",
    height: 400,
    open: function(e) {
      var elm = e.sender.list.find("#myfancyid");
      var dropDownTreeView = $(elm).kendoTreeView({
        dataSource: new kendo.data.HierarchicalDataSource({
          data: [{
            text: "Furniture",
            items: [{
              text: "Tables & Chairs"
            }, {
              text: "Sofas"
            }, {
              text: "Occasional Furniture"
            }]
          }, {
            text: "Decor",
            items: [{
              text: "Bed Linen"
            }, {
              text: "Curtains & Blinds"
            }, {
              text: "Carpets"
            }]
          }]
        })
      });

    }
  });
  $("#sample2").kendoDropDownList({
    dataTextField: "text",
    dataValueField: "value",
    dataSource: [{
      text: "Sample2",
      value: null
    }],
    template: "
test
",
    height: 400,
    open: function(e) {
      var elm = e.sender.list.find("#myfancyid");
      var dropDownTreeView = $(elm).kendoTreeView({
        dataSource: new kendo.data.HierarchicalDataSource({
          data: [{
            text: "Furniture",
            items: [{
              text: "Tables & Chairs"
            }, {
              text: "Sofas"
            }, {
              text: "Occasional Furniture"
            }]
          }, {
            text: "Decor",
            items: [{
              text: "Bed Linen"
            }, {
              text: "Curtains & Blinds"
            }, {
              text: "Carpets"
            }]
          }]
        })
      });

    }
  });

});

CSS
.elm1 {
  width: 400px;
  height: 100px;
  background-color: grey;
  position: relative;
  overflow: scroll;
}

#customers-list .k-item {
  line-height: 1em;
  min-width: 300px;
  background-color: white;
  display: inline-block;

Where Sample1 and Sample2 perform how I would like, but Dropdown Treeview does not. I've been pouring over the source trying to understand what makes Sample1 and Sample2 work, but I have yet to come to a realization. Any help in the right direction is much appreciated.

A: By default, the Kendo UI DropDownLists, ComboBoxes, DatePickers and similar widgets, use a detached popup, which is a child of the  element. This ensures that these popups (or dropdowns, if you prefer) will be able to stay on top of the other page content and not be restricted by fixed-height or scrollable containers.
On the other hand, the ExtDropDownTreeView widget renders its dropdown in the same place, where the original widget element is placed. Since the widget element is located inside a fixed height scrollable container in your case, this causes the observed problem.


text:
Q: EC2 instance web server site as a subdomain of a Squarespace site? I have a website on Squarespace: www.example.com
Squarespace doesn't allow custom code, so I developed a web app with advanced functionality on an EC2 instance that currently has an elastic IP address: 12.34.56.78.
Is it possible to connect the two in that the web app at 12.34.56.78 can be displayed when users visit webapp.example.com? Is that a subdomain?
Any help is appreciated.


text:
Q: How to fix TextView font fallback? I have a program that is localized into multiple languages. It works well on Android 4.x but has a font rendering issue Android 2.3.x.  Here is a small example that reproduces it. Any help will be greatly appreciated.
Main activity layout. Nothing special here. Just two TextView views:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="10dp" >

    <TextView
        android:id="@+id/text_view1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="80dp"
        tools:context=".MainActivity" />

    <TextView
        android:id="@+id/text_view2"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="80dp"
        tools:context=".MainActivity" />

</LinearLayout>

Main activity:
package com.font_test;

import android.app.Activity;
import android.graphics.Typeface;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends Activity {

    private static final String TEXT =
            "\u0440\u0443\u0441\u0441\u043A\u0438\u0439" +
            "\n" +
            "pyccknn";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Set textview 1
        final Typeface typeface1 = Typeface
                .createFromAsset(getAssets(), "fonts/chelsea.ttf");
        final TextView tv1 = (TextView) findViewById(R.id.text_view1);
        tv1.setTypeface(typeface1);
        tv1.setTextSize(40);
        tv1.setBackgroundColor(0x280000ff);
        tv1.setText(TEXT);

        // Set textview 2
        final Typeface typeface2 = Typeface.SANS_SERIF;
        final TextView tv2 = (TextView) findViewById(R.id.text_view2);
        tv2.setTypeface(typeface2);
        tv2.setTextSize(40);
        tv2.setBackgroundColor(0x280000ff);
        tv2.setText(TEXT);
    }
}

The custom font chelsea.ttf is from here http://www.dafont.com/chelsea.font . Nothing special about it, I can reproduce it with other fonts as well.
The TEXT string contains two lines, the first line with unicode characters that are not in the chelsea font and the second lines with characters that are in the font. The first text view is rendered with the custom font and the second with the stock san serif fonts (which contains all the unicode characters of TEXT).
Android 4.x renders it correctly, failing over to stock font when needed:

However, Android 2.3.x, does not render it correctly. It does fall back to the stock fonts (good) but uses strange metrics that resulted in way too large characters spacing:

Any suggestion how to fix it? I am open for ugly workarounds, if needed.


text:
Q: How to insert delay into onkeyup event How would insert the delay into this snippet of code so that it won't fire till after the user is done typing?
JS
gridContainer = $('#shuffleContainer');
var sizer = gridContainer.find('.col-md-4');

$('.js-shuffle-search').on('keyup change', function () {
    var val = this.value.toLowerCase();
    gridContainer.shuffle('shuffle', function ($el, shuffle) {

        // Only search elements in the current group
        if (shuffle.group !== 'all' && $.inArray(shuffle.group, $el.data('groups')) === -1) {
            return false;
        }

        var text = $.trim($el.find('.picture-item__title').text()).toLowerCase();
        return text.indexOf(val) !== -1;
    });
});

JS DELAY
var delay = (function(){
    var timer = 0;
    return function(callback, ms){
        clearTimeout (timer);
        timer = setTimeout(callback, ms);
    };
})();

$('input').keyup(function() {
    delay(function(){
        alert('Time elapsed!');
    }, 1000 );
});


text:
Q: Duplicate Values in SQL I'm using this query and have used the Select Distinct code to enusre no duplicates are pulled from the database.
However on my QTD colum the number is sometimes X2 the proper amount?
This is probably an error with the server or would my query be incorrect?
SELECT DISTINCT ad.eid, MAX(u1.email) as ops,MAX(u2.email) as rep,
    (SUM(ad.cost)) as qtd_spend,
    Sum(case when day < current_date AND day >='2015-01-01' then cost else 0 end) as MTD,
    AVG(case when day < current_date AND day >= current_date-7 then cost else null end) as weekly_spend
    FROM adcube as ad
    inner JOIN advertisables as a on ad.eid = a.eid
    LEFT JOIN organizations as o on o.id = a.id
    LEFT outer JOIN users as u1 on o.ops_organization_id = u1.organization_id
    LEFT outer JOIN users as u2 on o.sales_organization_id = u2.organization_id
    WHERE day >='2015-01-01' and day < current_date
    GROUP BY eid

A: You must have GROUP BY if you have aggregate functions (such as SUM or MAX).
What is likely the problem is in you JOINs.
I am not familiar with your data structure, but I am assuming that in your advertisables table, it contains (or CAN contain) more than one entry of the same "eid" - is this correct? Or do you have a constraint?
If this is correct, then when you join even if you have only ONE entry in the "adcube" table, once it JOINs with the multiple entries in the "advertisables" table then it pulls up TWO records (or however many match) and then the aggregate results at the select level of the statement then sum BOTH (or more) columsn.
So you should take the duplicates out of hte joining tables or factor that into account.
EDIT:
Ok, well glad to know that is the problem. You will not fix it by INNER JOINING either. You will have to do an inline select statement.
The best way to solve this, from what I understand you are trying to do, is do the following:
SELECT ad.eid
     , (
         select max(u1.email)
    from JOIN advertisables as a
         LEFT JOIN organizations as o on o.id = a.id
         LEFT outer JOIN users as u1 on o.ops_organization_id = u1.organization_id
         LEFT outer JOIN users as u2 on o.sales_organization_id = u2.organization_id
     where a.eid = ad.eid
       ) as ops
     , (
         select max(u2.email)
    from JOIN advertisables as a
         LEFT JOIN organizations as o on o.id = a.id
         LEFT outer JOIN users as u1 on o.ops_organization_id = u1.organization_id
         LEFT outer JOIN users as u2 on o.sales_organization_id = u2.organization_id
     where a.eid = ad.eid
       ) as rep
     , (SUM(ad.cost)) as qtd_spend
     , Sum(case when day < current_date AND day >='2015-01-01' then cost else 0 end) as MTD
     , AVG(case when day < current_date AND day >= current_date-7 then cost else null end) as weekly_spend
FROM adcube as ad
    WHERE day >='2015-01-01' and day < current_date
    GROUP BY eid


text:
Q: CABasicAnimation - Infinite scrolling of an image on retina device is garbled In a similar post, I found a solution to animating a scrolling image infinitely:
Animate infinite scrolling of an image in a seamless loop
While this solution works beautifully, there seems to be an issue when running on a retina device.  In particular, I am running this project on an iPad only.  A non-retina iPad 2 scrolls the image without any problems.  But run on a retina iPad 3 or 4 the image is a mess!  It's difficult to describe, but the best I can say is that it is garbled. Pixels are stretched every which way.  It resembles a Jackson Pollak painting.
Screen shot:
http://imgur.com/Q7n08kv
I tested this using a non-retina image (non 2x) and a retina version (@2x).  The image is large - full screen (landscape) and is 4 panels wide (4096 x 768).  I played around with smaller images but with the same result.
Is there a limitation with the scrolling functionality of CABasicAnimation that would affect retina devices?  Here is the code I am using (as contributed by rob mayoff):
UIImage *crawlImage = [UIImage imageNamed:@"CrawlBackground.png"];
UIColor *crawlPattern = [UIColor colorWithPatternImage:crawlImage];
self.crawlLayer = [CALayer layer];
self.crawlLayer.backgroundColor = crawlPattern.CGColor;

self.crawlLayer.transform = CATransform3DMakeScale(1, -1, 1);
self.crawlLayer.anchorPoint = CGPointMake(0, 1);

self.crawlLayer.frame = CGRectMake(0, 0, crawlImage.size.width + 1024, crawlImage.size.height);

[self.backgroundCrawl.layer addSublayer:self.crawlLayer];
self.backgroundCrawl.layer.zPosition = 0;

CGPoint startPoint = CGPointZero;
CGPoint endPoint = CGPointMake(-crawlImage.size.width, 0);

self.crawlLayerAnimation = [CABasicAnimation animationWithKeyPath:@"position"];
self.crawlLayerAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
self.crawlLayerAnimation.fromValue = [NSValue valueWithCGPoint:startPoint];
self.crawlLayerAnimation.toValue = [NSValue valueWithCGPoint:endPoint];
self.crawlLayerAnimation.repeatCount = HUGE_VALF;
self.crawlLayerAnimation.duration = 30;   // nn seconds to complete the cycle

A: self.crawlLayer.contents = (id)crawlImage.CGImage;
or:
self.crawlLayer.contents = (__bridge id)([crawlImage CGImage]);

This should fix it. Allowing large images to scroll correctly.

A: self.crawlLayer = [CALayer layer];

As soon as you make a layer you should set its contentsScale:
self.crawlLayer.contentsScale = [[UIScreen mainScreen] scale];

Otherwise it may not display correctly on double-resolution screens.


text:
Q: Perl exec command failing I'm trying to execute a shell command via a perl script that looks as follows
 $cmd = 'cat <(ssh -o \"StrictHostKeyChecking no\" dev-adm1 \'sudo cat /etc/httpd/conf/httpd.conf\')';
 exec $cmd;

This is throwing an error
sh: -c: line 0: syntax error near unexpected token `('
sh: -c: line 0: `cat <(ssh -o \"StrictHostKeyChecking no\" dev-adm1 'sudo cat /etc/httpd/conf/httpd.conf')'

The command works directly on the shell but not like this. What am i missing?

A: which shell did you use to test this command?
my first guess is that you used bash or ksh, while sh (used by perl exec) doesn't know the '(' syntax


text:
Q: Using regular expressions to compare numbers So this is an obvious case of "you're doing it wrong".  I don't actually intend on doing this, but a conversation at work spurred this question:

Can you generate a regular expression to determine if an integer is less than an arbitrary value.

For some values this is easy.  For integers less than 1000, \d{1,3} should do the trick.  For integers < 500, it's a bit trickier, but not that bad, as you can use [0-4]{0,1}\d{1,2}.
Once you get to arbitrary values it gets a lot tricker.  For example, all numbers less than 255 would be something like \d{1,2} | [0-1]\d{2}|[2][0-4]\d | [2][5][0-4].
Is there a single regular expression that works here?  Or do you have to programatically generate the regex?
(And again, let me point out that I have no intention of actually doing this.  Obviously using "foo < bar" in your favorite programming language is far more efficient and easy to read.)

A: This is quite easy.
#!/usr/bin/env perl
use strict;
use warnings;
use Regexp::Assemble;

for my $n (@ARGV)  {
    my $asm = new Regexp::Assemble;
    for (1 .. $n) { $asm->add($_) }
    for ($asm->re){
        s/\)$/\$/;
        s/^[^:]*:/^/;
        print "$n => /$_/\n";
    }
}

Now run it to find the pattern that matches integers between 1 and that number:
$ perl /tmp/ra 5 15 153 401 1144
5 => /^[12345]$/
15 => /^(?:[23456789]|1[012345]?)$/
153 => /^(?:1(?:[6789]|5[0123]?|0\d?|1\d?|2\d?|3\d?|4\d?)?|2\d?|3\d?|4\d?|5\d?|6\d?|7\d?|8\d?|9\d?)$/
401 => /^(?:1(?:0\d?|1\d?|2\d?|3\d?|4\d?|5\d?|6\d?|7\d?|8\d?|9\d?)?|2(?:0\d?|1\d?|2\d?|3\d?|4\d?|5\d?|6\d?|7\d?|8\d?|9\d?)?|3(?:0\d?|1\d?|2\d?|3\d?|4\d?|5\d?|6\d?|7\d?|8\d?|9\d?)?|4(?:[123456789]|0[01]?)?|5\d?|6\d?|7\d?|8\d?|9\d?)$/
1144 => /^(?:1(?:0(?:0\d?|1\d?|2\d?|3\d?|4\d?|5\d?|6\d?|7\d?|8\d?|9\d?)?|1(?:[56789]|4[01234]?|0\d?|1\d?|2\d?|3\d?)?|2\d?|3\d?|4\d?|5\d?|6\d?|7\d?|8\d?|9\d?)?|2(?:0\d?|1\d?|2\d?|3\d?|4\d?|5\d?|6\d?|7\d?|8\d?|9\d?)?|3(?:0\d?|1\d?|2\d?|3\d?|4\d?|5\d?|6\d?|7\d?|8\d?|9\d?)?|4(?:0\d?|1\d?|2\d?|3\d?|4\d?|5\d?|6\d?|7\d?|8\d?|9\d?)?|5(?:0\d?|1\d?|2\d?|3\d?|4\d?|5\d?|6\d?|7\d?|8\d?|9\d?)?|6(?:0\d?|1\d?|2\d?|3\d?|4\d?|5\d?|6\d?|7\d?|8\d?|9\d?)?|7(?:0\d?|1\d?|2\d?|3\d?|4\d?|5\d?|6\d?|7\d?|8\d?|9\d?)?|8(?:0\d?|1\d?|2\d?|3\d?|4\d?|5\d?|6\d?|7\d?|8\d?|9\d?)?|9(?:0\d?|1\d?|2\d?|3\d?|4\d?|5\d?|6\d?|7\d?|8\d?|9\d?)?)$/

A: You're going to need to generate the expression for each bounding number.  Let's say there were a regular expression that would do the job.  Then that regular expression would have to be able to take as input some sequence of characters.  However, we know that regular expressions and finite state automata are equivalent, so this is the same as saying we can construct an FSM since the possible number is unbounded, that would require an unbounded number of states, which contradicts the definition of FSA.


text:
Q: Image becomes white instead of Transparent in IE8 Opacity is not working in Ie8.. Image becomes white instead of transparent...
But it works fine in chrome....
-ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=50)";
filter: alpha(opacity=00);
-moz-opacity:0.5;
opacity: 0.0;

I'm using this... Please help me in Ie8

A: filter: alpha(opacity=X); is the filter for IE8 and earlier versions. if you set it to 00 value so you will not see anything in IE8 and earlier versions, if you want it to be 0.5 value so change it to filter: alpha(opacity=50);


text:
Q: File History keeps backing up entire user profile I recently upgraded from Windows 8.1 Pro to Windows 10 Pro and noticed that File History, which previously had been configured to only back up my OneDrive folder, now backs up my entire user profile (except hidden folders like AppData). This is undesirable because it includes several large folders that I either back up manually (e.g. VMs) or don't need to back up at all (e.g. Downloads).
However, I cannot seem to configure File History to exclude those folders, to make it behave the way it did previously in Windows 8.1. Here's what I've tried:

*

*I tried changing the list of folders to back up in the classic control panel (under "System and Security" → "File History"). I seem to recall that option was there in Windows 8.1, but it's not in Windows 10. It simply says it copies files from "Libraries, Desktop, Contacts, Favourites and OneDrive (only files available offline)", with no visible way to change it.

*Still in the classic control panel, I tried adding all folders in my user profile to the list of excluded folders. This doesn't work - if I hit "Save changes", then go back to the list of excluded folders, the ones I just added simply aren't there.

*I tried the same things in the new Settings app (under "Update & security" → "Backup") - removing the undesirable folders from "Back up these folders" or adding them to "Exclude these folders". While it seems to work at first, both lists magically reset as soon as File History starts backing up files.

*I tried manually editing the configuration files, both at the File History target location as well as in %LocalAppData%, but those changes also reset.
How can I fix this? Is there any other place that the configuration files are cached? Or is File History in Windows 10 hard-coded to back up the entire user profile folder?
I've searched online, but haven't found any solutions (at least not any that are applicable to Windows 10), only a few reports of others having the same issue.


text:
Q: Solve a system of M equations without specifying M I am trying to write my game-theoretic model in Wolfram Language. There is only one remaining step and I am not sure if it is within reach of Wolfram Language (or Mathematica). I describe a simplified version of my problem below.
Cournot game
There are $M$ firms. Each firm $i$ can produce some output $q_i\geq0$ at a cost of $c_i$ per unit. Once the firms have (simultaneously) decided on their outputs, the price is set in the market according to an inverse demand function $P(Q)=\alpha-Q$, where $Q=q_1+\ldots+q_M$ is the aggregate output and $\alpha>0$ is market size parameter. Firm $i$'s profits are $q_iP(Q)-q_ic_i=q_i(\alpha-q_1-\ldots-q_M-c_i)$. Each firm maximizes its profits taking outputs of the opponents as given. By differentiating the profit function with respect to $q_i$ and imposing the necessary condition for maximizing a function, I obtain the equilibrium outputs:
$$q_i^*=\frac{1}{2}\left(\alpha-\sum_{k\neq i}q_k^*-c_k\right) \text{ for } i=\{1,\ldots,M\}.$$
A quick derivation on the piece of paper gives me the explicit solution:
$$q_i^*=\frac{1}{M+1}\left(\alpha-Mc_i+\sum_{k\neq i}c_k\right)$$
Here's the thing: I would like to obtain exactly this result (the above equation) in Mathematica. Is it possible? Note: I don't want to substitute any numbers for $M, c_1, \ldots, c_M$ or $\alpha$. They are general, exogenous parameters.
In other words, the above problem boils down to inverting a $M\times M$ matrix of the form:
$$\left[\begin{array}{cccc}
2 & 1 & \ldots & 1\\
1 & 2 & \ldots & 1\\
\vdots & \vdots & \ddots & \vdots \\
1 & 1 & \ldots & 2
\end{array}\right].$$
Can one do this without specifying $M$?

A: You can invert the matrix
$$\left[\begin{array}{cccc}
2 & 1 & \ldots & 1\\
1 & 2 & \ldots & 1\\
\vdots & \vdots & \ddots & \vdots \\
1 & 1 & \ldots & 2
\end{array}\right].$$
(for general m) using the Woodbury matrix identity. First, let one be the m-vector of all ones. Then the matrix you want to invert is expressible as
mat = IdentityMatrix[m] + Outer[Times, one, one];

To use the matrix inversion lemma (with the notation from the wikipedia article), let A = IdentityMatrix[m], U=one, V=Transpose[one], C=A; and the lemma says the inverse is:
matInv= IdentityMatrix[m] - Outer[Times, one, one]/(m + 1);

This holds for all m. We can check this for an specific m like so:
m = 5;
one = ConstantArray[1, m];
eye = IdentityMatrix[m];
mat = eye + Outer[Times, one, one];
matInv = eye - Outer[Times, one, one]/(m + 1);
mat.matInv == matInv.mat == eye

to which the response is True. To do this truly within Mathematica, one approach would be to incorporate knowledge of the inversion lemma.

A: Maybe something like this:
cournotEq[m_] := (IdentityMatrix[m] -
    1/(m + 1) ConstantArray[1, m]).Array[\[Alpha] - Subscript[c, #] &,  m]
cournotEq[2]//FullSimplify

$\left\{\frac{1}{3} \left(\alpha -2 c_1+c_2\right),\frac{1}{3} \left(\alpha +c_1-2
   c_2\right)\right\}$
cournotEq[3]//FullSimplify

$\left\{\frac{1}{4} \left(\alpha -3 c_1+c_2+c_3\right),\frac{1}{4} \left(\alpha +c_1-3
   c_2+c_3\right),\frac{1}{4} \left(\alpha +c_1+c_2-3 c_3\right)\right\} $


text:
Q: How to 'kitchen login' with user different from root our main cookbook disables root login via ssh, but we want to be able to execute kitchen login to play with the test machine (yes, we can do it with ssh machine, but I want to know if it is possible to configure test-kitchen to use a custom user).
My question is 'Is it possible to configure test-kitchen to use the user steve instead of the root one when executing kitchen login?' I can't find anything about this in the net or the already asked questions.

A: I do not believe this is supported.  According to the kitchen docs, the only supported option is for setting the log level, not the user.  If this is something you need, I'd recommend filing a feature request.


text:
Q: Make div expand to a certain size I have a div on my page, and I want to make it expand to a certain size and then stop. Right now I have...
div {height:300px; width:700px; overflow:auto;}

The overflow attribute makes it scroll, but until then, I would like it to expand with the content. I have a text box below this and it looks bad with a text box floating down part of the page. Is there a way to have both of these attributes? All of the hits I found on Google were about making it expand to fit the content. Thanks!

A: Try using max-height.
This will allow you to specify the maximum height the box can be and once it reaches this height it will scroll as you've specified.

A: Did you mean you want the div to have its height variable, depending on the size of content? Then just give height: auto instead of giving a fixed height of 300px. height: auto will adjust the height of the div based on the content size. Also define max-height property if you want to limit the maximum height the div can extend to.


text:
Q: ReactJs - Uncaught TypeError: Cannot read property 'string' of undefined My 2 files:
APP:
import React, { Component } from 'react';
import { NICE, SUPER_NICE } from './colors';
import Counter from './counter';

export class App extends Component {
  render() {
    return (

        <Counter increment={ 1 } color={ NICE } />
        <Counter increment={ 5 } color={ SUPER_NICE } />

    );
  }
}

Counter:
import React, { Component } from 'react';

class Counter extends Component {
  constructor(props) {
    super(props);
    this.state = { counter: 0 };
    this.interval = setInterval(() => this.tick(), 1000);
  }

  tick() {
    this.setState({
      counter: this.state.counter + this.props.increment
    });
  }

  componentWillUnmount() {
    clearInterval(this.interval);
  }

  render() {
    return (

        Counter ( { this.props.increment } ): { this.state.counter }

    );
  }
}

Counter.defaultProps = {
  increment: 0,
  color: null
};

Counter.propTypes = {
  increment: React.PropTypes.number.isRequired,
  color: React.propTypes.string.isRequired
};

module.exports = Counter;

I am using:
"react": "^0.14.0-rc1",
"eslint": "^1.3.1",
"eslint-config-airbnb": "^0.1.0",
"eslint-loader": "^1.0.0",
"eslint-plugin-react": "^3.0.0"

I need the declare the propTypes to satisfy eslint, but I am receiving a run-error:
"Uncaught TypeError: Cannot read property 'string' of undefined".
Does anyone see my error?
Many Thanks !

A: I faced similar problem with React.PropTypes, as I am using React-16 I found out that React.PropTypes is not supported.
So you need to install "prop-types": "^15.6.0" using
npm install prop-types --save

and then import it as shown below
import PropType from 'prop-types'

I made a mistake while importing, instead of prop-types I imported prop-type and that was the issue for me.
Posting as an answer so others can get idea about newer package and how to install etc.

A: On the counter propTypes, the "color" React.PropTypes should be capitalized.
Counter.propTypes = {
  increment: React.PropTypes.number.isRequired,
  color: React.PropTypes.string.isRequired
};


text:
Q: Is there any way to make the HTML underline thicker? I have a centered div with a nested h1 inside. Is there any way to underline it with a thicker line than the html default?

A: No, there isn't. The thickness of the underline is browser-dependent and cannot be affected in CSS (or HTML).
There was once a text-underline-width property suggested in the CSS3 Text draft. But there was insufficient interest in it, and it was removed from the draft in 2005. It was probably never implemented.
The usual workaround is to use a bottom border instead of an underline. However, note that it is a different thing. The bottom border is below the line box, whereas an underline is normally on the baseline of text and therefore cuts descenders of letters. Generally, a bottom border is better for legibility than an underline, but it deviates from typographic tradition.
The following example demonstrates the differences.

jgq
jgq
jgq

A: I am not recommending inline CSS but have used it here for brevity:

A: This will give you control over the U tag's underline:

In this case the underline will be four pixels.

A: You may be able to achieve the same visual effect with border-bottom-width;
h2
{
  border-bottom-color:black;
  border-bottom-style:solid;
  border-bottom-width:15px;
}

A: Since you don't always want border-bottom (eg, item may have padding and it will appear too far away), this method works best:
h1:after {
    content: '';
    height: 1px;
    background: black;
    display:block;
}

If you want a thicker underline, add more height
If you want more or less space between the text and the underline, add a margin-top:
h1:after {
    content: '';
    height: 2px;
    background: black;
    display:block;
    margin-top: 2px;
}


text:
Q: Aggregate error 'invalid type (closure) for variable 'paste' For this question @SimonO101 suggested aggregate solution in comments, as below:
#dataframe
df <- data.frame(id=c(101,102,102,103,104,104,104),
                 calmonth=c('01','01','01','01','01','01','02'),
                 product=c('apple','apple','htc','htc','apple','htc','nokia'),
                 bb=sample(1:20,7))

#aggregate - SimonO101's solution:
aggregate(product~id+calmonth, data=df, FUN=paste, collapse=" & ")

#Error

Error in model.frame.default(formula = ~product + paste, data = list(id = c(101,  :
  invalid type (closure) for variable 'paste'

Can't figure out the cause of this error?
Version:
Windows 7 Enterprise SP1, 64bit OS, "R version 3.0.1 (2013-05-16)", RStudio

Update: Opened new RStudio session, no error, still would like to find out the cause.
Update: dput:
dput(df123)
structure(list(id = c(101, 102, 102, 103, 104, 104, 104), calmonth = structure(c(1L,
1L, 1L, 1L, 1L, 1L, 2L), .Label = c("01", "02"), class = "factor"),
    product = structure(c(1L, 1L, 2L, 2L, 1L, 2L, 3L), .Label = c("apple",
    "htc", "nokia"), class = "factor"), bb = c(19L, 17L, 5L,
    15L, 16L, 4L, 9L)), .Names = c("id", "calmonth", "product",
"bb"), row.names = c(NA, -7L), class = "data.frame")

Update: conflicts
conflicts()
 [1] "dbCallProc"        "dbClearResult"     "dbColumnInfo"      "dbCommit"
 [5] "dbConnect"         "dbDataType"        "dbDisconnect"      "dbExistsTable"
 [9] "dbGetException"    "dbGetInfo"         "dbGetQuery"        "dbGetRowCount"
[13] "dbGetRowsAffected" "dbGetStatement"    "dbHasCompleted"    "dbListConnections"
[17] "dbListFields"      "dbListResults"     "dbListTables"      "dbReadTable"
[21] "dbRemoveTable"     "dbRollback"        "dbSendQuery"       "dbUnloadDriver"
[25] "dbWriteTable"      "fetch"             "isSQLKeyword"      "make.db.names"
[29] "SQLKeywords"       "summary"           "fillin"            "recode"
[33] "untangle.specials" "%nin%"             "codebook"          "coerce"
[37] "initialize"        "recode"            "rename"            "show"
[41] "summary"           "dotplot"           "contr.sum"         "contr.treatment"
[45] "contrasts"         "contrasts<-"       "Arith"             "coerce"
[49] "Compare"           "initialize"        "Math"              "Math2"
[53] "show"              "Summary"           "%in%"              "as.array"
[57] "as.factor"         "as.ordered"        "as.vector"         "body<-"
[61] "format"            "format.pval"       "kronecker"         "labels"
[65] "print"             "round.POSIXt"      "row.names"         "sample"
[69] "subset"            "summary"           "trunc.POSIXt"      "unique"
[73] "units"             "within"

A: It works for me...
> df <- data.frame(id=c(101,102,102,103,104,104,104),
+                  calmonth=c('01','01','01','01','01','01','02'),
+                  product=c('apple','apple','htc','htc','apple','htc','nokia'),
+                  bb=sample(1:20,7))
>
> #aggregate - SimonO101's solution:
> aggregate(product~id+calmonth, data=df, FUN=paste, collapse=" & ")
   id calmonth     product
1 101       01       apple
2 102       01 apple & htc
3 103       01         htc
4 104       01 apple & htc
5 104       02       nokia
>

Try conflicts() to see if you are masking something ...


text:
Q: Links with WWW in Wordpress redirect to home page I've recently updated a website I work on to Wordpress 3.0. Something strange has started happening, where now the www. has dissapeared from the URLs, and if you add the www. to the URL (a good portion of the existing hardcoded links have it) then it redirects you to the home page URL.
Any ideas what could be causing this?
My .htaccess looks like the default for Wordpress 3.0 Multi-User
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]

# uploaded files
RewriteRule ^([_0-9a-zA-Z-]+/)?files/(.+) wp-includes/ms-files.php?file=$2 [L]

# add a trailing slash to /wp-admin
RewriteRule ^([_0-9a-zA-Z-]+/)?wp-admin$ $1wp-admin/ [R=301,L]

RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]
RewriteRule  ^([_0-9a-zA-Z-]+/)?(wp-(content|admin|includes).*) $2 [L]
RewriteRule  ^([_0-9a-zA-Z-]+/)?(.*\.php)$ $2 [L]
RewriteRule . index.php [L]

The settings in my wp-config.php related to the multi-user are
/** Multi User */
define('WP_ALLOW_MULTISITE', true);

define( 'MULTISITE', true );
define( 'SUBDOMAIN_INSTALL', false );
$base = '/';
define( 'DOMAIN_CURRENT_SITE', 'xxxx.ca' );
define( 'PATH_CURRENT_SITE', '/' );
define( 'SITE_ID_CURRENT_SITE', 1 );
define( 'BLOG_ID_CURRENT_SITE', 1 );

The URL settings for my domain is just the xxxx.ca, theres no www. infront of it.

A: What's in your .htaccess? Anything like this?:
RewriteEngine On
RewriteCond %{HTTP_HOST} ^www.domain.com$ [NC]
RewriteRule ^(.*)$ http://domain.com/$1 [R=301,L]

That redirect block strips the www from all URLs.
And what are the site URL settings in Dashboard/Settings/General? Do they have the www? And do you have site URLs configured in wp-config.php?


text:
Q: Can't install Nokogiri gem, "libxml/parser.h" not found, but its there, why? I tried to install Nokogiri but I always get an compiling error:
checking for libxml/parser.h... *** extconf.rb failed ***

but, I've installed it and all other dependencies.
I try to give the installer hints like this:
%> gem install nokogiri -- --with-xml2-lib=/usr/lib/ --with-xml2-include=/usr/include/libxml2/

...

checking for libxml/parser.h... *** extconf.rb failed ***

...

but it still doesn't install:
%> find /usr/include/ -name "parser.h"
/usr/include/libxml2/libxml/parser.h
...

I'm on Ubuntu 11.10.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Output of:
"dpkg-query -l | grep xml" and "dpkg-query -l | grep xslt"
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The failure seem to be on the side of GCC:
%> cat hello.c
#include <stdio.h>

main()
{
   printf("Hello World \n");
}

%> gcc hello.c
/usr/lib/gcc/x86_64-linux-gnu/4.6.1/../../../x86_64-linux-gnu/crt1.o: In function `_start':
(.text+0x12): undefined reference to `__libc_csu_fini'
/usr/lib/gcc/x86_64-linux-gnu/4.6.1/../../../x86_64-linux-gnu/crt1.o: In function `_start':
(.text+0x19): undefined reference to `__libc_csu_init'
collect2: ld gab 1 als Ende-Status zurück

A: This will work.
sudo apt-get install libxslt-dev libxml2-dev
gem install nokogiri

A: I just faced the same issue on (cat /etc/centos-release:) CentOS release 6.6 (Final).
sudo yum install -y rubygem-nokogiri

…fixed that problem.
(see: http://www.nokogiri.org/tutorials/installing_nokogiri.html#red_hat___centos)


text:
Q: Using UIPageViewController with swift and multiple view controllers I'm trying to utilize a UIPageViewController in a Swift app with multiple view controllers. I have 2 view controllers on my storyboard (firstViewController and secondViewController) that are both embedded in their own navigation controllers. They have storyboard identifiers "FirstViewController" and "SecondViewController". I also have a page view controller on my storyboard with identifierPageView controller and set the navigation to horizontal and transition style to scroll in the attributes inspector. FirstViewController is the root view controller of the app
I want firstViewController to be the first page of the page view controller so I have written its class like so:
import Foundation
import UIKit

class FirsttViewController: UITableViewController, UIPageViewControllerDataSource, UIPageViewControllerDelegate  {

    override func viewDidLoad() {

        let pageViewController: PageViewController = self.storyboard.instantiateViewControllerWithIdentifier("PageViewController") as PageViewController

        pageViewController.delegate = self

        var viewControllers: [UIViewController] = [self]

        pageViewController.setViewControllers(viewControllers, direction: UIPageViewControllerNavigationDirection.Forward, animated: false, completion: nil)
        pageViewController.view.frame = CGRectMake(0, 0, self.view.frame.width, self.view.frame.height)

        self.addChildViewController(pageViewController)
        self.view.addSubview(pageViewController.view)
        pageViewController.didMoveToParentViewController(self)

    }
    func pageViewController(pageViewController: UIPageViewController!, viewControllerAfterViewController viewController: UIViewController!) -> UIViewController! {

        let secondViewController: SecondViewController = self.storyboard.instantiateViewControllerWithIdentifier("SecondViewController") as SecondViewController

        return secondViewController
    }

    func pageViewController(pageViewController: UIPageViewController!, viewControllerBeforeViewController viewController: UIViewController!) -> UIViewController! {

        return nil
    }

    func presentationCountForPageViewController(pageViewController: UIPageViewController!) -> Int {
        return 2
    }

    func presentationIndexForPageViewController(pageViewController: UIPageViewController!) -> Int {
        return 0
    }
}

the file for SecondViewController looks like this:
import Foundation
import UIKit

class SecondViewController: UITableViewController, UIPageViewControllerDataSource {

    func pageViewController(pageViewController: UIPageViewController!, viewControllerAfterViewController viewController: UIViewController!) -> UIViewController! {

        return nil
    }

    func pageViewController(pageViewController: UIPageViewController!, viewControllerBeforeViewController viewController: UIViewController!) -> UIViewController! {

        let firstViewController: FirstViewController = self.storyboard.instantiateViewControllerWithIdentifier("FirstViewController") as FirstViewController
        return firstViewController
    }

}

However, when I run my app it doesn't seem to have a page view controller. It just shows firstViewController and that's it. No dots, no pages, etc. Anyone know whats wrong? I've found a couple of Objective-C tutorials but they all cover using one view controller for all the pages and have a root view controller that is not a page in the pageView so they weren't too much help. I was hoping it was going to be like using a tabBarController where you just click and drag to the view controllers but thats not the case unfortunately. like I said I've not worked with one of these before so I'm sort of lost.
update:
following iiFreeman's suggestion, I subclassed UIPageViewController and made it the root in my storyboard file. below is the subclass
import Foundation
import UIKit
class PageViewController: UIPageViewController {

    override func viewDidLoad() {

        let startingViewController = self.storyboard.instantiateViewControllerWithIdentifier("FirstViewController") as FirstViewController

        self.dataSource = startingViewController
        var viewControllers: [UIViewController] = [startingViewController]

        self.setViewControllers(viewControllers, direction: UIPageViewControllerNavigationDirection.Forward, animated: false, completion: nil)

    }

}

However now the app just hangs on a black screen and eventually Xcode loses connection to the simulator. I'm not really sure what's up.

A: OK, I got it figured out. since I needed the page view controller to be the root and handle everything, I subclassed UIPageViewControlleras iiFreeman suggested and conformed to the delegate and data source protocols. I then set up the controller in viewDidLoad, and implemented the delegate and data source methods. I added a property store an array of storyboard identifiers as well as one to keep track of the current index of that array. I also added a helper method to return the correct view controller given an index. I didn't need anything in my other tableView controller subclasses since my page view controller was handling everything. One thing I did realize is since my tableViewControllers were embedded in navigation controllers, my page view controller actually needed to show the navigation controllers, not the tableView controllers.  below is my implementation:
import Foundation
import UIKit

class PageViewController: UIPageViewController, UIPageViewControllerDataSource, UIPageViewControllerDelegate {

    var index = 0
    var identifiers: NSArray = ["FirstNavigationController", "SecondNavigationController"]
    override func viewDidLoad() {

        self.dataSource = self
        self.delegate = self

        let startingViewController = self.viewControllerAtIndex(self.index)
        let viewControllers: NSArray = [startingViewController]
        self.setViewControllers(viewControllers, direction: UIPageViewControllerNavigationDirection.Forward, animated: false, completion: nil)

    }

    func viewControllerAtIndex(index: Int) -> UINavigationController! {

        //first view controller = firstViewControllers navigation controller
        if index == 0 {

            return self.storyboard.instantiateViewControllerWithIdentifier("FirstNavigationController") as UINavigationController

        }

        //second view controller = secondViewController's navigation controller
        if index == 1 {

            return self.storyboard.instantiateViewControllerWithIdentifier("SecondNavigationController") as UINavigationController
        }

        return nil
    }
    func pageViewController(pageViewController: UIPageViewController!, viewControllerAfterViewController viewController: UIViewController!) -> UIViewController! {

        let identifier = viewController.restorationIdentifier
        let index = self.identifiers.indexOfObject(identifier)

        //if the index is the end of the array, return nil since we dont want a view controller after the last one
        if index == identifiers.count - 1 {

            return nil
        }

        //increment the index to get the viewController after the current index
        self.index = self.index + 1
        return self.viewControllerAtIndex(self.index)

    }

    func pageViewController(pageViewController: UIPageViewController!, viewControllerBeforeViewController viewController: UIViewController!) -> UIViewController! {

        let identifier = viewController.restorationIdentifier
        let index = self.identifiers.indexOfObject(identifier)

        //if the index is 0, return nil since we dont want a view controller before the first one
        if index == 0 {

            return nil
        }

        //decrement the index to get the viewController before the current one
        self.index = self.index - 1
        return self.viewControllerAtIndex(self.index)

    }

    func presentationCountForPageViewController(pageViewController: UIPageViewController!) -> Int {
        return self.identifiers.count
    }

    func presentationIndexForPageViewController(pageViewController: UIPageViewController!) -> Int {
        return 0
    }

}

this post helped me out a lot

A: sure cause FirstViewController - initial view controller in your storyboard
add a custom UIPageViewController subclass into your storyboard, mark it as initial and do all work inside, instantiate page controller members by storyboardIDs in your UIPageViewController subclass, do the same thing just inside another class

A: Please be aware that this code will only work with two ViewController. If you are planning on using more you have to change the line:
self.index = self.index + 1

Found at the before and after call, to:
self.index = index + 1

To call the current ViewController index.


text:
Q: Java FX Controller not recognized Today when I was working on Windows, there was no problem at all. After transferring to my Mac at home, trouble started.
I have the following path in the FXML (BorderPane):
fx:controller="application.controllers.DashboardController"

The directory structure looks like this:

Eclipse keeps saying that 'the controller has no field XXX'.

It seems to me quite clear that they are there!

The interface gets properly loaded when run, I'm quite sure the path is correct.
However, the controller is not recognised, and 'test' doesn't get printed.
Any hints?

A: FXML loader and IDEs (e.g. Eclipse) use reflection to retrieve information about the controller. In your case you seem to have an inner class PleaseProvideControllerClassName where the annotated fields are. Hence, from reflection's perspective the DashboardController class itself does not contain any fields at all.
It's worth noting that nested classes should not be used in controllers.


text:
Q: PdfBook Extension - MediaWiki - Fullurl parser function link automatically to every category page I am able to display a download link in category to download all the pages of that category.
In the below link, it is written as
In order to include this parser function link automatically to every category page, add it to the Mediawiki:Categoryarticlecount page.
Rather than adding the download link manually to all categories, i tried the above. That is, added the download link in Mediawiki:Categoryarticlecount page to automatically include the fullurl parser function link to every category page. But it didnt work.
 Parser function link : [{{fullurl:{{FULLPAGENAME}}|action=pdfbook}} | Download]

How to achieve this?
Any help is appreciated.

A: You have two typos in there:

*

*The system message is at MediaWiki:Category-article-count (note the camel-case in MediaWiki)

*The external link syntax is [url text], not [url | text], so it should be [{{fullurl:{{FULLPAGENAME}}|action=pdfbook}} Download]
Other than that, your code looks fine.


text:
Q: Derivative formula for L2 fourier transform It is well known that if $f(x),f'(x) \in L_{PC}^1\left( { - \infty ,\infty }
\right)$ then $F\left\{ {f'(x)} \right\} = i\omega F\left\{ {f(x)} \right\}$.
The proof itself is rather straightforward using integration by parts.
How would one go about proving that if $f(x),f'(x) \in L_{PC}^2\left( { - \infty ,\infty } \right)$ then the same formula takes hold (in the $L2$ sense) ?


text:
Q: Specify max and min for Random.nextInt()?
Possible Duplicate:
Java: generating random number in a range

I want to generate a random int in a logical range. So, say for example, I'm writing a program to "roll" a dice with a specified number of sides.
public int rollDice() {
     Random generator = new Random();
     return generator.nextInt(sides);
}
Now the problem becomes that this will return values between sides and zero, inclusive, which makes no sense because most dice go from 1 to 6, 9, etc. So how can I specify that nextInt should work between 1 and the number of sides?

A: To generate a random int value (uniform distribution) between from and to (inclusive) use:
from + rndGenerator.nextInt(to - from + 1)

In your case (1..sides):
1 + rndGenerator.nextInt(sides)


text:
Q: Checking for syllables, python So I am trying to write the code that will do the following:
r""" (list of str, poetry pattern, pronunciation dictionary) -> list of str

Precondition: len(poem_lines) == len(pattern[0])

Return a list of lines from poem_lines that do not have the right number of
syllables for the poetry pattern according to the pronunciation dictionary.
If all lines have the right number of syllables, return the empty list.

>>> poem_lines = ['The first line leads off,', 'With a gap before the next.', 'Then the poem ends.']
>>> pattern = ([5, 5, 4], ['*', '*', '*'])
>>> word_to_phonemes = {'NEXT': ['N', 'EH1', 'K', 'S', 'T'],
...                     'GAP': ['G', 'AE1', 'P'],
...                     'BEFORE': ['B', 'IH0', 'F', 'AO1', 'R'],
...                     'LEADS': ['L', 'IY1', 'D', 'Z'],
...                     'WITH': ['W', 'IH1', 'DH'],
...                     'LINE': ['L', 'AY1', 'N'],
...                     'THEN': ['DH', 'EH1', 'N'],
...                     'THE': ['DH', 'AH0'],
...                     'A': ['AH0'],
...                     'FIRST': ['F', 'ER1', 'S', 'T'],
...                     'ENDS': ['EH1', 'N', 'D', 'Z'],
...                     'POEM': ['P', 'OW1', 'AH0', 'M'],
...                     'OFF': ['AO1', 'F']}
>>> check_syllables(poem_lines, pattern, word_to_phonemes)
['With a gap before the next.', 'Then the poem ends.']
>>> poem_lines = ['The first line leads off,']
>>> check_syllables(poem_lines, ([0], ['*']), word_to_phonemes)
[]
"""

I do not understand how exactly it suppose to work, since every string in list has more syllables than it is given. ex: the first has 7 syllables but the pattern is 5, the second has 8 but 5 is given again, and so on.
I have no clear idea what to start with and what my code should do, so far I have this:
def check_syllables(poem_lines, pattern, word_to_phonemes):
   if  len(poem_lines) == len(pattern[0]):
        for k in word_to_phonemes:
            for v in poem_lines:
                if k is in v:
                   k , v = v, k

A: Here's how the question breaks down:
(1) the signature of the required function:
r""" (list of str, poetry pattern, pronunciation dictionary) -> list of str

(2) a guarantee about the structure of the inputs:
Precondition: len(poem_lines) == len(pattern[0])

(3) specification of the returm value:
Return a list of lines from poem_lines that do not have the right number of
syllables for the poetry pattern according to the pronunciation dictionary.
If all lines have the right number of syllables, return the empty list.

(4) sample input - first argument [list of str]:
>>> poem_lines = ['The first line leads off,', 'With a gap before the next.', 'Then the poem ends.']

(5) sample input - second argument [poetry pattern]:
>>> pattern = ([5, 5, 4], ['*', '*', '*'])

(6) sample input - third argument [pronunciation dictionary]:
>>> word_to_phonemes = {'NEXT': ['N', 'EH1', 'K', 'S', 'T'],
...                     'GAP': ['G', 'AE1', 'P'],
...                     'BEFORE': ['B', 'IH0', 'F', 'AO1', 'R'],
...                     'LEADS': ['L', 'IY1', 'D', 'Z'],
...                     'WITH': ['W', 'IH1', 'DH'],
...                     'LINE': ['L', 'AY1', 'N'],
...                     'THEN': ['DH', 'EH1', 'N'],
...                     'THE': ['DH', 'AH0'],
...                     'A': ['AH0'],
...                     'FIRST': ['F', 'ER1', 'S', 'T'],
...                     'ENDS': ['EH1', 'N', 'D', 'Z'],
...                     'POEM': ['P', 'OW1', 'AH0', 'M'],
...                     'OFF': ['AO1', 'F']}

(7) first sample output - return value [list of str]:
>>> check_syllables(poem_lines, pattern, word_to_phonemes)
['With a gap before the next.', 'Then the poem ends.']

(8) second sample output - return value [list of str]:
>>> poem_lines = ['The first line leads off,']
>>> check_syllables(poem_lines, ([0], ['*']), word_to_phonemes)
[]
"""

The first sample output (7) shows the expected return value for input lines (5) which do not match the pattern (6). That is, the three input lines have the pattern [5, 7, 5], which does not match the pattern [5, 5, 4] in the last two elements, and so the corresponding lines are returned by the function.
The second sample input (8) shows what the output should be when the input lines (5) do match the pattern (6) - i.e. an empty list should be returned.
PS:
It looks like there is a in error in (8). The sample code should probably be:
>>> check_syllables(poem_lines, ([5], ['*']), word_to_phonemes)


text:
Q: How to optimize code if ViewState turned off?         protected void Page_Init(object sender, EventArgs e)
         { }
        protected void Page_Load(object sender, EventArgs e)
        {
              if (!IsPostBack)
              {
                 DropDownList1.DataSource = SomeObject.GetData();
                 DropDownList1.DataBind();
                } }

    protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
    {
    var selvalue = DropDownList1.SelectedValue;
    DoSomething(selvalue);
}

Please some body help me to make works properly this code if ViewState turned off.

A: If you turn the viewstate off, then you need to rebind the data on every trip to the server and before the page initializes.
Example of a dropdownlist without viewstate


text:
Q: BlockingQueue - one producer multiple consumers I have three threads. Thread 1 (T1) is the producer, which generates data. Threads 2 an 3 (T2, T3 respectively) each wait on T1's data to process in separate loops. I'm thinking of sharing a BlockingQueue between the threads and having T2 and T3 wait by calling "take".
The docs for java.util.concurrent.BlockingQueue say it can "safely be used with multiple producers and multiple consumers". Trying out the example from the docs, it seems as though the behaviour is to allow one consumer to "take" the "put" object instead of all of them receiving it. So, either T2 or T3 gets the data and it appears as though they alternate. I'd like both of them to get the same data when T1 puts some data.
My question is, is BlockingQueue the right way to go? Should I be thinking about this problem differently?

A: Sounds like Publish-Subscribe, you publish data to a topic and all registered consumers receive a copy of the message. In contrast, a queue delivers a message to a single registered consumer only. I recommend you reconsider the desin of that component.
The BlockingQueue, essentailly a Queue implementation, as the name suggests, is a queue which allows to add and examine objects. These operations are thread-safe, which means that for example no two threads receive the same object when examining.


text:
Q: Generating time series for everyday's am9:00 to pm2:00 I want to generatie time series from am9:00 to pm2:00 everyday
My current time series generated from min(ticktime) to max(ticktime)
But I want to scope the series to everyday's am8:59 to pm3:00
how to do it ?
I  tried to generate time between 1:11 ~ 1:15, But it didn't stop by  1:15
      SELECT generate_series
      (
        date_trunc('second', min(ticktime)) ,
        date_trunc('second', max(ticktime)) ,
        interval '1 sec'
      ) AS ticktime FROM czces
        WHERE
        (date_part('hour', ticktime) >= 1 AND  date_part('minute', ticktime) > 10  )
        AND  (date_part('hour', ticktime) <= 1 AND  date_part('minute', ticktime) <= 15 )

I tried another solution but the outputed generating series still not under the BETWEEN interval.
Please check the result the series not stopped by 1:01 am
      SELECT generate_series
      (
        min(ticktime)::timestamp,
        max(ticktime)::timestamp,
         '1 minute'::interval
      ) AS ticktime FROM czces
      where ticktime::time between '00:01 am'::time AND '1:01 am'::time

      ~~~~

A: You need to add the appropriate where clause.
Examples of the syntax to use:
select dt
from generate_series(
  now()::date - interval '1 day',
  now()::date + interval '1 day',
  '1 hour'
) as dt
where dt::time between '9:00 am'::time and '2:00 pm'::time;

select t
from generate_series(
  now()::timestamptz(0) - interval '1 day',
  now()::timestamptz(0) + interval '1 day',
  '1 hour'
) as t
where t::time between '9:00 am'::time and '2:00 pm'::time;


text:
Q: Easy way to get date from UTC to PST in python 2.7.x I have this:
>>> import datetime
>>> today = str(datetime.date.today())
>>> print today
2017-06-07

The machine is in UTC time. I would like to know if there is easy/simple way to get same kind of output for PST (without changing machine time zone).

A: import datetime
import pytz

def tz2ntz(date_obj, tz, ntz):

    # date_obj: datetime object
    # tz: old timezone
    # ntz: new timezone

    if isinstance(date_obj, datetime.date) and tz and ntz:
       date_obj = date_obj.replace(tzinfo=pytz.timezone(tz))
       return date_obj.astimezone(pytz.timezone(ntz))
    return False

print tz2ntz(datetime.datetime.utcnow(), 'UTC', 'US/Pacific')