text:
Q: my dvi-d port is not working for dual monitoring? I have two monitors. The first is an LG Flatron w1946sn and the second is an LG Flatron ezt710sh I am trying to connect them to my motherboard J&W Z77A-prox that supports dual monitoring. I am connecting the main display to the motherboard with a VGA cable and the second using a VGA cable and DVI-D adapter. It just detects the one that is connected to the VGA port, but it does not detect the one that is connected to the DVI-D port.
Can anyone help.

A: I've ran into this same issue. A DVI-D is digital only port and even though you have a DVI-D adapter, an analog monitor will not work with the dvi "digital" port on your computer. I assume it's not a DVI-I port on your PC? If not you will have to buy an analog/digital converter to get this to work. Also important is to know a DVI "adapter" is not the same as a "converter". The fact they make so many types of DVI plugs makes this an easy mistake to make.


text:
Q: Composite Component is not updating outside autocomplete I know it seems like a duplicate question (and I found a lot of questions like mine, but none could solve my problem). In fact, as long as it can be a lack of attention of mine, yes it can be a duplicate. Here it is: I have two updates not working well: the most important is one, concerning a button inside a composite component (a p:dialog with its own h:form inside) trying to update a p:autoComplete in another h:form. The composite also receive a listener as a parameter and, in the listener, it updates a property of the bean: this is one of the problems - this property is bound to the value attribute of the p:autoComplete and I was not able to update it after the listener change its value.
The other problem is a p:inputReset which is apparently doing nothing (it should clear up the input fields in the same composite above).
I've already checked out the updates attributes values with the browser development tool, and they're correct.
One more information: the problem started after I put the dialog inside a composite. It used to work fine before it.
[EDITED]: These are some of the topics I've researched:

*

*How to update a composite component form from another composite component?: The composite component already had an update attribute in the cc:interface section and it's not helping with this problem. @stg said it's a bad design to put a form inside a composite component, but would it prevent it from updating other components? [EDITED 2]: Anyway, I moved the form out of the composite (and moved the component into a form). The problem remains.

*How to find out client ID of component for ajax update/render? Cannot find component with expression "foo" referenced from "bar": Very detailed @BalusC answer. I already checked  the paths to the component being updated and they seem to be correct (actually, cc.parent.namingContainer.clientId and other syntactic sugar is not getting the clientId, maybe some of them are deprecated - the answer was wrote in 2011). Anyway, all the working approaches pointed there result in the same path I put in the example bellow.

*Updating a component outside of the  component's context: I've tried with and without the leading ":". Made no difference.

There are other questions about this topic all over the Internet, but they are variations of this problem and most of them could be solved with the same things pointed by @BalusC in the link above.
In my case the behavior occured in a structure like this (simplified):
A template:
...
<h:body>
    <h:form id="dlgTemplateForm">
        <p:tabView id="tbvMain">
            <ui:insert name="tabs" />
        </p:tabView>
    </h:form>
    <ui:insert name="outsideDlgTemplateForm" />
</h:body>

I also have a composite component (dlgComp.xhtml) that looks like:
<cc:interface>
    <cc:attribute name="returnListener" method-signature="void listener()" />
    <cc:attribute name="bean" type="com.foo.BeanClass" />
    <cc:attribute name="widgetVar" />
    <cc:attribute name="update" />
</cc:interface>
<cc:implementation>
    <div id="#{cc.clientId}">
        <p:dialog id="dlg" widgetVar="#{cc.attrs.widgetVar}">
            <h:form id="dlgForm">
                <p:inputText id="ipm" value="#{cc.attrs.bean.obj}" />
                <!--here is the componentn with the update which doesn't work-->
                <p:commandButton id="btnSave"
                                 actionListener="#{cc.attrs.returnListener}"
                                 value="Gravar"
                                 update="#{cc.attrs.update}"
                                 oncomplete="PF('#{cc.attrs.widgetVar}').hide()"/>
            </h:form>
        </p:dialog>
    </div>
</cc:implementation>

Then, I build myPage.xhtml, based on the template above. Inside it:
<ui:define name="tabs">
    <p:tab id="tabInfo">
        <ui:include src="myTab.xhtml" />
    </p:tab>
</ui:define>
<ui:define name="outsideDlgTemplateForm">
    <myComp:dlgComp id="dlgId"
                    widgetVar="dlgIdWGV" bean="#{myPageBean.myPageManagedProperty}"
                    returnListener="#{myPageBean.returnFromDialog}"
                    update=":dlgTemplateForm:tbvMain:acpTest" />
</ui:define>

In myTab.xhmtl (to be included in myPage.xhtml), I have this:
<p:autoComplete id="acpTest" value="#{myPageBean.prop}"
                completeMethod="#{myPageBean.acpCompleteText}" />
<p:commandButton actionListener="#{myPage.listener}"
                oncomplete="PF('dlgIdWGV').show();"
                update=":dlgId:dlgForm" process="@this">
    <p:resetInput target=":dlgId:dlgForm" /> <!--this doesn't work too-->
</p:commandButton>

In myPageBean.java
@ManagedProperty(value = "beanClass")
private com.foo.BeanClass myPageManagedProperty;
private Object prop;

//getters and setters

public void returnFromDialog(void) {
    this.prop = myPageManagedProperty.getObj();
}

And, finally, in com.foo.BeanClass
private Object obj;
//getter and setter

redpajama_set_name: RedPajamaStackExchange


text:
Q: Transform Jquery function Hey there i am using this little jquery:
$("area.imagefield[data-name='" + searchText + "']").each(function() {

to check if the value of the attribute "data-name" matches exactly the variable "searchText".
But i need to check if the value of the attribute "data-name" is index of the variable "searchText", so using the
.indexOf

What i tried:
$("area.imagefield[data-name=]").each(function() {
    if ($(this).attr("data-name").indexOf(searchText) != -1) {
        console.log("match");
    } else {
        console.log("no match");
    }

But there is no log in the console... :/ any idea´s ?

A: Actually your code looks good except one typo.
Remove the equal sign after data-name otherwise it's an invalid css selector:
So area.imagefield[data-name=] should be area.imagefield[data-name]

A: Try this way:
$("#imagefieldID").each(function() {
    if ($(this).attr("data-name").indexOf(searchText) != -1) {
        console.log("match");
    } else {
        console.log("no match");
});

A: jQuery data()
Is the normal way of working withdata attributes in jQuery, and probably what you would want to use.
$('area.imagefield').each(function (i) {
    if ($(this).data('name')===searchText) {
        console.log('match '+i);
    } else { console.log('no match '+i); }
});

made a fiddle: http://jsfiddle.net/filever10/mau93/


text:
Q: Simply multi touch programming for Android I've scoured the internets trying to find an answer for this, but all the tutorials I've read seem to significantly over complicate my little problem.  Basically, I have a ship on the left side of the screen that moves up and down if you drag your finger up and down on the left side of the screen, and fires a missile if you touch anywhere on the right side of the screen.
public boolean onTouchEvent(MotionEvent event)
{
    if (event.getX() < getWidth()/2)
    {
        if (shipY < event.getY())
            shipY = shipY + 10;
        if(shipY > event.getY())
            shipY = shipY - 10;
    }

    if (event.getX() >= getWidth()/2)
    {
        if(!missile)
        {
            missile = true;
            missileY = shipY;
            missileX = shipX;
        }
    }
    return true;
}

Right now I can only fire the missile if I stop moving the ship.  Thank you much!

A: I contributed to an explanation of this problem yesterday: Touch more one button at once
TL;DR - You can't touch two Views at the same time. You need to combine them into a custom ViewGroup and dispatch the touch events yourself if you want to accomplish concurrent touches on multiple View objects.

A: If your ship and missile happen to be in the same View, then you can add an onTouchListener to that view which will handle multiple touch. (It would be your own class, which implements View.onTouchListener)
Here's a skeleton of the method you'll need to override in the onTouchListener:
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        switch(event.getAction() & MotionEvent.ACTION_MASK) {

        case MotionEvent.ACTION_DOWN:
            //first finger went down
            break;

        case MotionEvent.ACTION_MOVE:
            //a touch placement has changed
            break;

        case MotionEvent.ACTION_UP:
            //first finger went up
            break;

        case MotionEvent.ACTION_CANCEL:
            //gesture aborted (I think this means the finger was dragged outside of the touchscreen)
            break;

        case MotionEvent.ACTION_POINTER_DOWN:
            //second finger (or third, or more) went down.
            break;

        case MotionEvent.ACTION_POINTER_UP:
            //second finger (or more) went up.
            break;

            default: break;
        }
        return true;
    }

You can get more detail on these cases (and others you might want to use) at http://developer.android.com/reference/android/view/MotionEvent.html .
About how you handle your logic - in the case of sane play, your ACTION_DOWN, or "first finger" would probably correspond to the player touching the ship, and the ACTION_POINTER_DOWN where they want to shoot a missile. But remember to handle cases where the player may touch the "missile side" of the screen first, and then touch the ship to move it afterwards.


text:
Q: Custom font in iphone not being displayed properly I installed a custom font called "modern no. 20" (already installed in my mac) into my iphone project .
I copied the modernno20.ttf into my resources.
Now in my app-info.plist i added this font name in "Fonts provided by application".
Then i added
   cell.textLabel.font=[UIFont fontWithName:@"modernno20.ttf" size:14.0];

in my tableviewcode .
i dont know why but this font is not properly displayed.is there any thing i missed?

A: In order to call the font in your fontWithName call, the string should be the name of the font as it is displayed in the Mac's 'Font Book' app, and not the actual filename of the referenced font file.

A: There hasn't been an easy way to add custom fonts to your iPhone applications. As of iOS 4 it has become very easy to do. there could be  possibility you would have missed some of the step to get custom font work.
Here is what you need to do in order to add custom fonts,
Check  How to include ttf fonts to iOS app


text:
Q: Make use of google calendar into my website? I have a website that has some register users, now I want to provide calendar service for them. I am considering using google calendar to ease my development work, the requirement should be:
1) Google calendar needs to support non google users, because my website users are not google users
2) Support provision from my website, that means my website can create calendar account for my users.
...
For simplicity, my objective is create one account for all the registered users, and manupulate the data in the calendar on behave of my user.
Is it possible?

A: You're looking for Google Apps for Business, which has a provisioning API.


text:
Q: Match based on a field only with non-empty array I am trying to do a filter on something. Here is a simplified layout of my Order model:
{
    merchant: <Reference to the merchant>,
    date: <Date Object>
    name: "Some order name",
    ingredients: [{
        ingredient: {data: "some data"}
        otherData: "some data"
    }]
}

I want to query the documents based on the ingredients that they contain.  I have an array of items to search through "objectifiedIngredients". If it has ingredients in it, then I want to search for orders that contain that ingredient. If the array is empty, then I want to not do the query and just get all orders.  "objectifiedIngredients" is a list of ObjectId's. Here is what I have so far:
      Order.aggregate([
            {$match:{
                merchant: new ObjectId(req.session.user),
                date: {
                    $gte: from,
                    $lt: to
                },
                ingredients: {
                    $elemMatch: {
                        ingredient: {
                            $in: objectifiedIngredients
                        }
                    }
                }
            }}
        ])

How can I run the $match on ingredients only if the array has elements in it? I have tried using $cond, but either it doesn't work here or I didn't use it right.

A: Try this
Order.aggregate([
            {$match:{
                merchant: new ObjectId(req.session.user),
                date: {
                    $gte: from,
                    $lt: to
                },
                ingredients: {
                    $ne: false
                }
            }}
        ])

You can check for more details here

A: I figured this one out after some time.  I didn't use Mongoose to solve it.  What I did was to create JavaScript variables to store the queries that I wanted.  So I used an if statement to set what query was stored.
let query = {};
if(objectifiedIngredients.length === 0){
    query = {$exists: true};
}else{
    query = {
        $elemMatch: {
            ingredient: {
                $in: objectifiedIngredients
            }
        }
    }
}

Order.aggregate([
    {$match:{
        merchant: new ObjectId(req.session.user),
        date: {
            $gte: from,
            $lt: to
        },
        ingredients: query
])

NOTE: the {$exists: true} part assumes that the ingredient array exists on the order.  If it doesn't then it won't return that order.


text:
Q: Ошибка при повторном запуске Здравствуйте.
Вот этот кусок кода (дан ниже) при повторном запуске программы выдает ошибку:

terminate called after throwing an
instance of 'std::ios_base::failure'
what(): basic_ios::clear

Я так понимаю, нужно очистить буфер ошибок, что я и делаю: content.clear(); pageHead.clear();, но тем не менее ошибка все равно остаётся. Это моя первая программа, так что готов к любой критике. Собирается под виндой minGW32, curl+ssl+zlib также собран под виндой. Все библиотеки и заголовки закинуты в папку MinGW, в общем, все вроде бы как нужно.
Это кусок кода, в котором проблема (элемент данные и функция мейн с вызовом я упустил,  так как несущественно):
curl_handle = curl_easy_init();

        // задаем адрес страницы
        curl_easy_setopt(curl_handle, CURLOPT_URL, url_prime.c_str() );

        content.clear(); //предварительная очистка переменной-буфера
        //  сохраняем html код cтраницы в строку content
        curl_easy_setopt(curl_handle, CURLOPT_WRITEFUNCTION, write_data);
        curl_easy_setopt(curl_handle, CURLOPT_WRITEDATA,     &content);

        pageHead.clear(); //предварительная очистка переменной-буфера
        // Загловок ответа сервера выводим в pageHead
        curl_easy_setopt(curl_handle, CURLOPT_HEADERFUNCTION, write_head);
        curl_easy_setopt(curl_handle, CURLOPT_WRITEHEADER,    &pageHead);

        curl_easy_setopt(curl_handle, CURLOPT_USERAGENT,"Mozilla/5.0 (Windows NT 6.1; rv:16.0) Gecko/20100101 Firefox/16.0");
        curl_easy_setopt(curl_handle, CURLOPT_AUTOREFERER,1);// автоматически заполняет поле referer

        // разрешаем авто перенаправление
        curl_easy_setopt(curl_handle, CURLOPT_FOLLOWLOCATION, 1);
        // max 5-ть перенаправлений
        curl_easy_setopt(curl_handle, CURLOPT_MAXREDIRS, 5);
        // разрешаем использовать куки
        curl_easy_setopt(curl_handle, CURLOPT_COOKIEFILE,"");

        //Выполняет отправку запроса на сервер и возвращает CURLE_OK в случае успеха, в противном случае код ошибки
        resData = curl_easy_perform(curl_handle);

        if (resData != CURLE_OK)
        {
            printf( "curl_easy_perform() failed: %s\n", curl_easy_strerror(resData) );
            resData = curl_easy_perform(curl_handle);
        }

Есть подозрение, что ошибка связанна с функцией записи в буфер.
На просторах Интернета искал разные варианты реализации этой функции, но все, что нашел, также вылетает с ошибкой при повторном запуске.
 static size_t write_data(char *ptr, size_t size, size_t nmemb, std::string* data)
{
    if (data)
     {
         data->append(ptr, size*nmemb);
         return size*nmemb;
     }
    else return 0;  // будет ошибка
}


text:
Q: Часть буфера обмена обрезается при вставке в консольное приложение Вставка в произвольный текстовый файл вставляет буфер целиком (примерно 2000 символов) в консольное приложение c# пролезает всего около сотни почему-то. Можно ли как-то увеличить этот объем?

A: таки нашел как задать длину буфера
byte[] inputBuffer = new byte[4096];
Stream inputStream = Console.OpenStandardInput(inputBuffer.Length);
Console.SetIn(new StreamReader(inputStream, Console.InputEncoding, false, inputBuffer.Length));


text:
Q: Firestone documents create dinamycally with python script I have a .csv file.
For example:
record-1a, record-1b, record-1c, document-name-1
record-2a, record-2b, record-2c, document-name-2

I would like to solve that after running my python script, it will create 2 document (depends on the number of the lines from the .csv) with the document-name-N names.
This is my code now:
import firebase_admin
from firebase_admin import credentials
from firebase_admin import firestore
from array import array
import csv

cred = credentials.Certificate('firebase-sdk.json')

with open('foo/bar/file.csv', 'r', newline='', encoding="utf8") as file:
    reader = csv.reader(file)
    data = []
    for row in reader:
        data.append(row)

firebase_admin.initialize_app(cred)
db = firestore.client()

doc_ref = db.collection('collectionname').document(row[3])

for item in data:
    doc_ref.set({
        'someArray': [],
        'column1': item[0],
        'column2': item[1],
        'column3': item[2]
})

I've already checked this doc: https://firebase.google.com/docs/firestore/manage-data/transactions
but it didn't help me to find my solution.

A: In the first code sample, you were using doc_ref inside the for loop, so I guess the result after running your script was that only one document was generated with the data from the last row of your json file. The actual behavior was that you immediately overwrote the document with each row of that file. In the second sample, you are creating a new reference for each row, so it is producing different documents for each of them.

A: I found the solution:
import firebase_admin
from firebase_admin import credentials
from firebase_admin import firestore
from array import array
import csv

cred = credentials.Certificate('firebase-sdk.json')

with open('foo/bar/file.csv', 'r', newline='', encoding="utf8") as file:
    reader = csv.reader(file)
    data = []

    firebase_admin.initialize_app(cred)
    db = firestore.client()

    for row in reader:
        print(row)
        data.append(row)

        content = ({
            'someArray': [],
            'column1': item[0],
            'column2': item[1],
            'column3': item[2]
        })
        db.collection('collectionname').document(row[5]).set(content)

I am a little beginner with the python so I barely know what was the problem.
If somebody can write some lines about the problem, I would be very glad.


text:
Q: Is the "mobile" subdomain popular practice in non-English websites as well (e.g. móvil, mobiel)? For example, there is mobile.twitter.com, mobile.facebook.com... So I'm wondering if that practice is common in other languages, like, móvil.popularSpanishSite.com or mobiel.popularDutchSite.com, etc...Is another similar word used, like célula.popularSpanishSite.com (célula = cell)?
Being an English-only speaker, I'm not sure how I would research this. Any suggestions?

A: The most popular ones are: mobile.yoursite.com and m.yoursite.com
I have encountered some others like "lajt.yoursite.com" (Polish site), but there are only few of them and they're not recognizable among common users.


text:
Q: How to make object appear when a certain torso is called using C# in Unity This is the code I used for a tutorial
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Trial_Changer : MonoBehaviour
{

        [Header("Sprite To Change")]
        public SpriteRenderer bodyPart;

        [Header("Sprites to Cycle Through")]
        public List<Sprite> options = new List<Sprite>();

    public static int currentTorsoOption = 0;

    public void NextOption ()
    {
        currentTorsoOption++;
        if (currentTorsoOption >= options.Count)
        { currentTorsoOption = 0; }

        bodyPart.sprite = options[currentTorsoOption];

    }

    public void PreviousOption()
    {
        currentTorsoOption--;
        if (currentTorsoOption <= 0)
        { currentTorsoOption = options.Count - 1; }

        bodyPart.sprite = options[currentTorsoOption];

    }
}

**This is the code I am using to try to say "if torso 2 is called, create object"
**
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SpeechAppears : MonoBehaviour
{
    public GameObject speechBubbleTOSpawn;
    private int Torso = Trial_Changer.currentTorsoOption;

    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        if (Torso == 2)
        {
            Instantiate(speechBubbleTOSpawn);
        }

    }
}

Except the torso just appears always.
What do I do to fix this?
I want an object to appear when torso 2 is on the screen but instead the object is just always present. What do I do ?

A: The culprit is this line :
private int Torso = Trial_Changer.currentTorsoOption;

Since you assign value Torso only once at the start of the game, its value always be the same.
Try this :
private int Torso => Trial_Changer.currentTorsoOption;

This change Torso from a field to a property, and when Torso is used, it will read the current value of Trial_Changer.currentTorsoOption.


text:
Q: Is there a sequence container with external allocation of elements (in the STL)? I would like to use a sequence container type like std::forward_list but with external allocation of the contained elements. This requirement is in order to gain more control over the allocation.
Such elements would probably have to use a class template which contains the necessary members for linking the (list) elements.
It can be implemented, but I wonder if there is already a proven in use solution? I am bound to C++17 or older.
By external allocation of the element I mean that the definition, allocation and initialization is done outside the control of the container type. That object is then manually added to the container.

A: Considering that you want fine-grained control over the list elements, to the level how they are joined, Boost.Intrusive could be an option.
Boost.Intrusive provides an intrusive slist class: https://www.boost.org/doc/libs/1_73_0/doc/html/intrusive/slist.html

A: The definition of a forward list is :
template<class T, class Allocator = std::allocator<T>> class forward_list;

this is so that you can specify whichever allocator you want to use, with
forward_list<int, MyAllocator> my_list;

It's not the most trivial part of C++, but you can then read up on writing a custom allocator.
Alternatively, as @NathanOliver suggest,
forward_list<shared_ptr<Type>> myList;
forward_list<unique_ptr<Type>> myList;

might fit your needs as allocation will happen outside.


text:
Q: How to make infinite loop to keep the clock showing continuously for 8086? Following is the code that I have written but it shows the time once i want it to be in the loop to keep updating. I have tried .while loop and simple loops but they are not helping.
MAIN PROC

L1:
     mov cx, 100
     push cx

     MOV AX, @DATA                ; initialize DS
     MOV DS, AX

     mov BX,offset time           ; BX=offset address of string TIME

     CALL GET_TIME                ; call the procedure GET_TIME

     CALL clrscr

     MOV DX,offset time           ; DX=offset address of string PROMPT
     MOV AH, 09H                  ; print the string PROMPT
     INT 21H

     MOV AH, 4CH                  ; return control to DOS
     INT 21H

     pop cx
     inc cx

     loop L1

MAIN ENDP


text:
Q: Hive SQL: Both left and right aliases encountered in JOIN I have this valid T-SQL query:
select t1.*
    ,case when s1.period is not null then 'Y' else 'N' end as flag_cur
    ,case when s2.period is not null then 'Y' else 'N' end as flag_prev
    ,s1.cutoff_date as cutoff_date_cur ,s1.cutoff_dtkey as cutoff_dtkey_cur
    ,s2.cutoff_date as cutoff_date_prev ,s2.cutoff_dtkey as cutoff_dtkey_prev
into #tmp_leads2
from #tmp_leads t1
left join #param s1 on s1.period = '(a) Current' and s1.begin_date <= t1.CreatedDate and t1.CreatedDate < s1.end_date
left join #param s2 on s2.period = '(b) Previous' and s2.begin_date <= t1.CreatedDate and t1.CreatedDate < s2.end_date

I tried to re-write it for Hive (v0.13) as:
create table tmp_leads2 as
select t1.*
    ,case when s1.period is not null then 'Y' else 'N' end as flag_cur
    ,case when s2.period is not null then 'Y' else 'N' end as flag_prev
    ,s1.cutoff_date as cutoff_date_cur ,s1.cutoff_dtkey as cutoff_dtkey_cur
    ,s2.cutoff_date as cutoff_date_prev ,s2.cutoff_dtkey as cutoff_dtkey_prev
from tmp_leads t1
left join param s1 on s1.period = '(a) Current'  and s1.begin_date <= t1.CreatedDate and t1.CreatedDate < s1.end_date
left join param s2 on s2.period = '(b) Previous' and s2.begin_date <= t1.CreatedDate and t1.CreatedDate < s2.end_date ;

But I get the error:
Error occurred executing hive query: OK FAILED: SemanticException [Error 10017]: Line 8:53 Both left and right aliases encountered in JOIN 'CreatedDate'

I see the fields it's talking about, but I'm not sure how to re-write this while keeping the query results identical.

A: The problem comes from the inequality conditions in the joins.  This poses a problem.  The following is probably sufficient for your purposes:
create table tmp_leads2 as
    select t1.*,
           (case when s1.period is not null then 'Y' else 'N' end) as flag_cur,
           (case when s2.period is not null then 'Y' else 'N' end) as flag_prev,
           s1.cutoff_date as cutoff_date_cur, s1.cutoff_dtkey as cutoff_dtkey_cur ,
           s2.cutoff_date as cutoff_date_prev, s2.cutoff_dtkey as cutoff_dtkey_prev
    from tmp_leads t1 left join
         param s1
         on s1.period = '(a) Current' left join
         param s2
         on s2.period = '(b) Previous'
    where (s1.begin_date is null or s1.begin_date <= t1.CreatedDate and t1.CreatedDate < s1.end_date) or
          (s2.begin_date is null or s2.begin_date <= t1.CreatedDate and t1.CreatedDate < s2.end_date);

This is not exactly equivalent.  It makes the assumption that if a parameter is in the table, then it is in the table for all dates.  That might be a reasonable assumption.  If not, then a more complex query would be needed.

A: Here is something which would not cause inner join or alias issue and give you the expected results in Hive
   create table tmp_leads2 as
   select final.*
       ,case when s1period is not null then 'Y' else 'N' end as flag_cur
       ,case when s2period is not null then 'Y' else 'N' end as flag_prev

    from
    (select t1.*,
       max(case when  s1.begin_date <= t1.CreatedDate and t1.CreatedDate < s1.end_date then s1.peroid else null end) as s1period,
       max(case when  s1.begin_date <= t1.CreatedDate and t1.CreatedDate < s1.end_date then s1.cutoff_date else null end) as cutoff_date_cur,
       max(case when  s1.begin_date <= t1.CreatedDate and t1.CreatedDate < s1.end_date then s1.cutoff_dtkey else null end) as cutoff_dtkey_cur,

       max(case when  s2.begin_date <= t1.CreatedDate and t1.CreatedDate < s2.end_date then s2.peroid else null end) as s2period,
       max(case when  s2.begin_date <= t1.CreatedDate and t1.CreatedDate < s2.end_date then s2.cutoff_date else null end) as cutoff_date_prev,
       max(case when  s2.begin_date <= t1.CreatedDate and t1.CreatedDate < s2.end_date then s2.cutoff_dtkey else null end) as cutoff_dtkey_prev,

   from tmp_leads t1
   left join param s1 on s1.period = '(a) Current'
   left join param s2 on s2.period = '(b) Previous'
   group by t1.* /* type all column names required from t1*/
   ) final ;


text:
Q: AWS Lambda executed successfully with SQS event trigger but not with SQS test case This is my code:
        const aws = require('aws-sdk');
        const dynamodb = new aws.DynamoDB();
        const sqs = new aws.SQS();
        var item;
        var orderName;
        var orderPrice;
        exports.handler = function(event, context) {

          event.Records.forEach(record => {
            const { body } = record;
           item = JSON.parse(body);
            });
            console.log(item);

             var orderName = item.OrderName;
             var orderPrice = item.OrderPrice;

          var dynamoParams = {
              Item: {
                "OrderName": {
                    S: orderName
                },
                "OrderPrice": {
                  S: orderPrice
                }
              },
          ReturnConsumedCapacity: "TOTAL",
          TableName: "Orders"
          };

          dynamodb.putItem(dynamoParams, function(err, data) {
          if (err) console.log(err, err.stack); // an error occurred
          else     console.log(data);           // successful response
          });
};

SQS Input Message which triggers this Lambda Function: { "OrderName": "Laptop", "OrderPrice": "40000" }
My Question is Lambda Executed successfully with SQS event trigger but, if I am going to invoke the function with Test It is giving me following error:
{
  "errorType": "SyntaxError",
  "errorMessage": "Unexpected token o in JSON at position 1",
  "trace": [
    "SyntaxError: Unexpected token o in JSON at position 1",
    "    at JSON.parse (<anonymous>)",
    "    at /var/task/index.js:15:16",
    "    at Array.forEach (<anonymous>)",
    "    at Runtime.exports.handler (/var/task/index.js:13:17)",
    "    at Runtime.handleOnce (/var/runtime/Runtime.js:66:25)"
  ]
}

Successful SQS Event trigger logs:


text:
Q: pandas - How to save only selected columns of a DataFrame to HDF5 I'm reading a csv sample file and store it on .h5 database. The .csv is structured as follows:
User_ID;Longitude;Latitude;Year;Month;String
267261661;-3.86580025;40.32170825;2013;12;hello world
171255468;-3.83879575;40.05035005;2013;12;hello world
343588169;-3.70759531;40.4055946;2014;2;hello world
908779052;-3.8356385;40.1249459;2013;8;hello world
289540518;-3.6723114;40.3801642;2013;11;hello world
635876313;-3.8323166;40.3379393;2012;10;hello world
175160914;-3.53687933;40.35101274;2013;12;hello world
155029860;-3.68555076;40.47688417;2013;11;hello world

I've putting it on a .h5 store with the pandas to_hdf, selecting to pass to the .h5 only a couple of columns:
import pandas as pd

df = pd.read_csv(filename + '.csv', sep=';')

df.to_hdf('test.h5','key1',format='table',data_columns=['User_ID','Year'])

I've obtained different results in the columns stored in the .h5 file using HDFStore and read_hdf, in particular:
store = pd.HDFStore('test.h5')
>>> store
>>> <class 'pandas.io.pytables.HDFStore'>
File path: /test.h5
/key1            frame_table  (typ->appendable,nrows->8,ncols->6,indexers->[index],dc->[User_ID,Year])

which is what I expect (only the 'User_ID' and 'Year' columns stored in the database), althought the ncols->6 means that actually all the columns have been stored in the .h5 file.
If I try reading the file with pd.read_hdf:
hdf = pd.read_hdf('test.h5','key1')

and asking for the keys:
hdf.keys()
>>> Index([u'User_ID', u'Longitude', u'Latitude', u'Year', u'Month', u'String'], dtype='object')

which is not what I'm expected since all columns of the original .csv file are still in the .h5 database. How can I store only a selection of columns in the .h5 in order to reduce the size of the database?
Thanks for your help.

A: just select out the columns as you write to the file.
cols_to_keep = ['User_ID', 'Year']
df.loc[:, cols_to_keep].to_hdf(...)


text: Q: Envoy access log stream to Logstash Envoy can stream access log out via gRPC. I'm trying to route Envoy access log to Logstash. I found a protobuf plugin here (https://www.elastic.co/guide/en/logstash/current/plugins-codecs-protobuf.html) for Logstash. In it's config, it requires class_name and the files of pb.rb definitions. Look like to me that this is the proto file to use https://github.com/envoyproxy/envoy/blob/3e63182c3e74e0d517d2f0d1fc2ee950bbfe21e1/api/envoy/data/accesslog/v2/accesslog.proto.? Apparently it depends on other definition files, e.g. envoy.api.v2.core.Address and some others. It's a deep dependency tree there. I'm not able to grep all the necessary proto files and compile them to Ruby. Anyone has such kind of experience connecting Envoy and Logstash?


text:
Q: The radius of convergence Given the following series: $\sum_{n\geq 1}\left(\frac{x}{\sin n}\right)^{n}$
How to find the radius of convergence?
I tried to use Cauchy–Hadamard theorem and got
$R^{-1} = \lim_{n\rightarrow \infty} \left|\frac{x}{\sin n}\right|$
What should I do next?

A: The limit $\lim_{n\to\infty}\frac{|x|}{|\sin n|}$ does not exist. However, $\limsup_{n\to\infty}\frac{|x|}{|\sin n|}=+\infty$, since $\liminf_{n\to\infty}|\sin n|=0$. Therefore, the radius of convergence of your series is $0$.


text:
Q: how to fix this undefined variable On a Previous page the user enters in a number in the textbox, when that form is submitted, the number is posted on this page as $_SESSION['sessionNum']. Now I want to store this number on the top as $sessionMinus showing the same number except difference is that everytime this form is submitted to it self, the number counts down by 1 everytime the form is submitted. Problem is that it is giving me an undefined variable $sessionMinus. How can this be fixed?
  <?php
session_start();
//validate the post data if necessary
if (isset($_POST['sessionNum'])) {

$_SESSION['sessionNum'] = $_POST['sessionNum'];
}else{
        $_SESSION['sessionNum']--;
}

$sessionMinus = $_SESSION['sessionNum'];

?>

    <?php echo $sessionMinus; ?>

      <form id="enter"
                action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>"
                method="post"
                onsubmit="return validateForm(this);" >

            <input id="submitBtn" name="submitDetails" type="submit" value="Submit Details" />

      </form>

      <?php

      $outputDetails = "";
      $outputDetails .= "

      Number of Sessions:
      {$_SESSION['sessionNum']}

";
      $outputDetails .= "
";

      echo $outputDetails;

      ?>

A: Your $sessionMinus is never initialized.
When you do isset($sessionMinus) you're checking if the variable has been declared, and since it hasn't, it will of course be undefined. If you want variables to be carried across each submit, you have to store it in a $_SESSION variable, not a local variable.
You can learn about variable scope here and about session variables here.

You're using $_POST
You're using $_POST but you're not sending a variable named sessionNum in your form.

Keep it clean
You should also try to keep your html as "clean" as possible, by separating PHP processing and PHP outputting.
This is how your setup should look like
<?php
    session_start();

    if(!isset($_SESSION['my_counter'])){
        if(isset($_POST['my_count'])){
            //Declare my counter for the first time
            $_SESSION['initial_count'] = $_POST['my_count'];
            $_SESSION['my_counter'] = $_POST['my_count'];
        }
    }else{
        //Decrement my counter
        $_SESSION['my_counter']--;
    }

    $actionurl = htmlentities($_SERVER['PHP_SELF']);

    if($_SESSION['my_counter'] <= 0)
        $number_of_sessions = "No sessions left!";
    else
        $number_of_sessions = $_SESSION['my_counter'];

    $started_with_sessions = $_SESSION['initial_count'];
?>

<!DOCTYPE html>

    <form id="enter" action="<?php echo $actionurl; ?>" method="post" onsubmit="return validateForm(this);" >
        <input type='hidden' name='my_count' value='5' />
        <input id="submitBtn" name="submitDetails" type="submit" value="Submit Details" />
    </form>

            Number of sessions:
            <?php echo $number_of_sessions; ?>

            Started with:
            <?php echo $started_with_sessions; ?> sessions

A: if $sessionMinus is not set, you are never setting it. Perhaps you should be checking if it's not set before you set it?
if (!isset($sessionMinus)) {
  $sessionMinus = "";
  $sessionMinus .= $_POST['sessionNum']--;

}


text: Q: How to protect user data in mongoDB using Azure Active Directory So I'm building a flask app using AAD B2C based off the QuickStart code from Microsoft. All that is fine and is working with no issues but how do I secure individual user data in a backend database (Mongo DB API on Cosmos DB)? I've read a lot about RBAC but to create a new role Every time a new user registers isn't really scalable. Because if you secure data via the mongo db secret key users can still modify data. I've thought about maybe adding a "user_id" of some kind to the documents in mongodb and pass along the user_id but in my head it seems that can be easily spoofed. So how do I ensure Users can only modify their own data? Is there a new DB user created for each user of the app that gets mapped to each other? Really I just want to secure user data in the DB with AAD or some kind of Kerberos method. Thank you!


text:
Q: Morse function with indices of only $0$ and $n$ Q1: If a Morse function on a smooth closed $n$-manifold $X$ has critical points of only index $0$ and $n$, does it follow that $X\approx \mathbb{S}^n\coprod\ldots\coprod\mathbb{S}^n$?
I think the following question is essential in regard to the one above:
Q2: If $f$ is a Morse function on a closed connected smooth $n$-manifold $X$ that has critical points of only index $0$ and $n$ and $f(X)\!=\![a,b]$, can a critical point of index $0$ or $n$ be mapped into $(a,b)$?

A: As Matt mentioned, a Morse function gives you a handle decomposition.
In the connected case when $n>1$, Poincare duality forces you to have exactly two critical points. The handle decomposition then means that you can form your smooth manifold by taking two $n$-discs and gluing them together along their boundary.
As a result, the actual answer to your question depends on what you mean by $\approx$.
If you mean homeomorphism, the answer is yes.  To pull out a heavy hammer, the Poincare conjecture tells you that the resulting topological manifold has to be the $n$-sphere $S^n$, because it's $(n-1)$-connected.
If you mean diffeomorphism, then I suspect that the answer is no.  After all, this procedure of taking two discs and gluing them together along a diffeomorphism of their boundaries, which is what the handle decomposition gives you, is also how Milnor originally produced exotic spheres.

A: Say $M$ has $j$ connected components and you only have critical points of index 0 and $n$, then you must have $j$ of each index.  You can probably also get this from the Morse inequalities but a very easy way to see this is because the homology of $M$ can be computed from the complex whose $k$th degree group is the free $\mathbb Z$ module generated by the critical points of index $k$.  Then since the chain complex is zero in degrees $n-1$ or $n+1$, the $n$th homology must be $\mathbb Z^m$ where $m$ is the number of critical points of index $n$.  But an $n$-manifold with $j$ components must have $\mathbb Z^j$ for $n$th homology.  Similarly using Poincare duality (i.e. replacing $f$ by $-f$), shows that there must be $j$ critical points of index 0 as well.
Now $f$ restricted to each connected component has exactly two critical points and it is a theorem of Reeb that any such manifold must be homeomorphic to $S^n$.  An easy proof of this is in Milnor's Morse Theory.


text:
Q: configure: error: Python interpreter is too old I am trying to Build and Install the Apache Thrift compiler and libraries
As shown in instructions run ./configure && make
And I get this error configure: error: Python interpreter is too old
I have python 2.7.12
checking for a BSD-compatible install... /usr/bin/install -c
checking whether build environment is sane... yes
checking for a thread-safe mkdir -p... /usr/bin/mkdir -p
checking for gawk... gawk
checking whether make sets $(MAKE)... yes
checking whether make supports nested variables... yes
checking whether UID '197608' is supported by ustar format... yes
checking whether GID '197121' is supported by ustar format... yes
checking how to create a ustar tar archive... gnutar
checking for pkg-config... /usr/bin/pkg-config
checking pkg-config is at least version 0.9.0... yes
checking for gcc... gcc
checking whether the C compiler works... yes
checking for C compiler default output file name... a.exe
checking for suffix of executables... .exe
checking whether we are cross compiling... no
checking for suffix of object files... o
checking whether we are using the GNU C compiler... yes
checking whether gcc accepts -g... yes
checking for gcc option to accept ISO C89... none needed
checking whether gcc understands -c and -o together... yes
checking for style of include used by make... GNU
checking dependency style of gcc... gcc3
checking how to run the C preprocessor... gcc -E
checking for g++... g++
checking whether we are using the GNU C++ compiler... yes
checking whether g++ accepts -g... yes
checking dependency style of g++... gcc3
checking build system type... x86_64-pc-msys
checking host system type... x86_64-pc-msys
checking how to print strings... printf
checking for a sed that does not truncate output... /usr/bin/sed
checking for grep that handles long lines and -e... /usr/bin/grep
checking for egrep... /usr/bin/grep -E
checking for fgrep... /usr/bin/grep -F
checking for ld used by gcc... c:/mingw/mingw32/bin/ld.exe
checking if the linker (c:/mingw/mingw32/bin/ld.exe) is GNU ld... yes
checking for BSD- or MS-compatible name lister (nm)... /c/MinGW/bin/nm
checking the name lister (/c/MinGW/bin/nm) interface... BSD nm
checking whether ln -s works... no, using cp -pR
checking the maximum length of command line arguments... 24000
checking whether the shell understands some XSI constructs... yes
checking whether the shell understands "+="... yes
checking how to convert x86_64-pc-msys file names to x86_64-pc-msys format... func_convert_file_noop
checking how to convert x86_64-pc-msys file names to toolchain format... func_convert_file_noop
checking for c:/mingw/mingw32/bin/ld.exe option to reload object files... -r
checking for objdump... objdump
checking how to recognize dependent libraries... unknown
checking for dlltool... dlltool
checking how to associate runtime and link libraries... printf %s\n
checking for ar... ar
checking for archiver @FILE support... @
checking for strip... strip
checking for ranlib... ranlib
checking command to parse /c/MinGW/bin/nm output from gcc object... ok
checking for sysroot... no
checking for mt... no
checking if : is a manifest tool... no
checking for ANSI C header files... yes
checking for sys/types.h... yes
checking for sys/stat.h... yes
checking for stdlib.h... yes
checking for string.h... yes
checking for memory.h... yes
checking for strings.h... yes
checking for inttypes.h... yes
checking for stdint.h... yes
checking for unistd.h... yes
checking for dlfcn.h... yes
checking for objdir... .libs
checking if gcc supports -fno-rtti -fno-exceptions... no
checking for gcc option to produce PIC... -fPIC -DPIC
checking if gcc PIC flag -fPIC -DPIC works... no
checking if gcc static flag -static works... yes
checking if gcc supports -c -o file.o... yes
checking if gcc supports -c -o file.o... (cached) yes
checking whether the gcc linker (c:/mingw/mingw32/bin/ld.exe) supports shared libraries... yes
checking whether -lc should be explicitly linked in... yes
checking dynamic linker characteristics... no
checking how to hardcode library paths into programs... immediate
checking whether stripping libraries is possible... yes
checking if libtool supports shared libraries... no
checking whether to build shared libraries... no
checking whether to build static libraries... yes
checking how to run the C++ preprocessor... g++ -E
checking for ld used by g++... c:/mingw/mingw32/bin/ld.exe
checking if the linker (c:/mingw/mingw32/bin/ld.exe) is GNU ld... yes
checking whether the g++ linker (c:/mingw/mingw32/bin/ld.exe) supports shared libraries... no
checking for g++ option to produce PIC... -fPIC -DPIC
checking if g++ PIC flag -fPIC -DPIC works... no
checking if g++ static flag -static works... yes
checking if g++ supports -c -o file.o... yes
checking if g++ supports -c -o file.o... (cached) yes
checking whether the g++ linker (c:/mingw/mingw32/bin/ld.exe) supports shared libraries... no
checking dynamic linker characteristics... no
checking how to hardcode library paths into programs... immediate
checking whether make sets $(MAKE)... (cached) yes
checking for bison... yes
checking for bison version >= 2.5... yes
checking for bison... bison -y
checking for flex... flex
checking lex output file root... lex.yy
checking lex library... none needed
checking whether yytext is a pointer... no
checking whether ln -s works... no, using cp -pR
checking for gawk... (cached) gawk
checking for ranlib... (cached) ranlib
checking whether g++ supports C++11 features by default... no
checking whether g++ supports C++11 features with -std=c++11... yes
checking for boostlib >= 1.53.0... configure: We could not detect the boost libraries (version 1.53 or higher). If you have a staged boost library (still not installed) please specify $BOOST_ROOT in your environment and do not give a PATH to --with-boost option.  If you are sure you have boost installed, then check your version number looking in <boost/version.hpp>. See http://randspringer.de/boost for more documentation.
checking for pkg-config... /usr/bin/pkg-config
checking for openssl/ssl.h in /usr/local/ssl... no
checking for openssl/ssl.h in /usr/lib/ssl... no
checking for openssl/ssl.h in /usr/ssl... no
checking for openssl/ssl.h in /usr/pkg... no
checking for openssl/ssl.h in /usr/local... no
checking for openssl/ssl.h in /usr... no
checking whether compiling and linking against OpenSSL works... no
checking for libevent >= 1.0... no
checking for zlib >= 1.2.3... no
checking for QT... no
checking for QT5... no
checking for GLIB... no
checking for GOBJECT... no
checking for MONO... no
checking for MONO... no
checking for MONO... no
checking for javac and java... yes
checking for ant... no
checking for ant version > 1.7... expr: syntax error
no
checking for erl... no
checking for erlc... no
checking for nodejs... no
checking for node... no
checking for npm... no
checking for a Lua interpreter with version >= 5.2... none
checking for trial... no
checking whether C:\Python27\Lib version is >= 2.4... no

Couldn't find in documentation of Apache Thrift which python interpreter I should have on my pc.
Thanks in advance!

A: I just built Apache Thrift here, version 0.9.3. Check the PYTHON environment variable, as it should point to a valid Python interpreter that fits the version requirement >= 2.4. It could be that ./configure is looking for the Python interpreter using an invalid path.
Here's an example of what I did, and worked.
PYTHON="/usr/bin/python2.7" ./configure

But this, using an invalid, non-existing Python interpreter, gave me the error you mentioned:
PYTHON="/usr/bin/nonexisting-python-interpreter" ./configure
configure: error: Python interpreter is too old


text:
Q: TYPO3 - HTML RTE frontend rendering is not working I have the latest version of TYPO3, and the data I entered in the RTE is not rendered properly in the frond end (in site).
So for example
asdf
 will show as it is in frond end.
I googled it and tried with some RTE default configuration changes, but that did not work well.

A: Please try with some basic testing first.

*

*Create a new site on root level (directly below the globe). Create one content element with all text and styles you want to test.

*Create a new Typoscript template for this site and put the following in the setup section:
page = PAGE
page.10 < styles.content.get
Make sure to include CSS Styled content inside the static template section.
Now watch your page page in frontend. Does it work?
Otherwise try step 0. and create a new (admin) backend user first.
Most likely you have either a strange transformation rule inside your RTE config in backend (UserTS or PageTS) or you have some kind of htmlspecialchar definition for your frontend rendering.

A: Please post something of the following basic Typo3 configuration settings and/or tell us if you use something of that:
You Upgraded from an older Typo3 version? Than it could be, that some configuration is missing.
Root Template or Site Template inside Typo3 Backend you can create or edit one, when you click in the most left menu on "Template"
If you choose "Create Template for new site" button the most basic Typo3 Typoscript * is automatically created
# Default PAGE object:
page = PAGE
page.10 = TEXT
page.10.value = HELLO WORLD!

Do you have such an TS (= Typoscript) tested? TEST IT and tell us if it works!!!
Does this work for you?

*

*(Typo3's own configuration language - both a blessing and a curse - can be so easy and so painful - most laughful description i ever read, you can found on  hatetypo3.blogspot.de "spaghetti code festival")

Don't miss include "CSS styled content" (it's in the form "edit whole template -> Includes)
But if you don't have include this, normally no site content is displayed in the frontend.
Another way is to include basic TS configuration in one or mor separate files. To get the files working, you have to referce them by this snippet in a Site Template in the BE
   <INCLUDE_TYPOSCRIPT: source="FILE: yourfile">
   # BTW I saw that it is common to place the file in a dir like
   /fileadmin/ts/yourtyposcriptfile.ts

So give us this info or ask for more, if i miss something.


text:
Q: How can I print while evalexpression with c in perl program? Trying to pipe the output of varnishlog to perl inside C language.
Code as below:
How can I display the information of evalExpression?
e.g.
      evalExpression("open(my $file,'varnishlog -u -c -i ReqStart,RxURL,RxHeader |') or die $!; \
                      while (<$file>) {$data = $_;}; \
                      close $file; \
                      ");

      printf("data = %s\n", SvPV(perl_get_sv("data", FALSE), length));

the above data will only display after while is ran... so that means it will never be displayed if while is running...
help appreciated. thanks
#include <stdio.h>
#include <EXTERN.h>
#include <perl.h>

static PerlInterpreter *my_perl;

    int evalExpression(char *evaluatedString)
    {
      char *argv[2];
      argv[0] = evaluatedString;
      argv[1] = NULL;
      perl_call_argv("_eval_", 0, argv);
    }

 main (int argc, char **argv, char **env)
 {

      char *codeToUse[] = { "", "-e", "sub _eval_ { eval $_[0] }" };
      STRLEN length;

      my_perl = perl_alloc();
      perl_construct( my_perl );

      perl_parse(my_perl, NULL, 3, codeToUse, env);

      evalExpression("open(my $file,'varnishlog -u -c -i ReqStart,RxURL,RxHeader |') or die $!; \
                      while (<$file>) {$data = $_;}; \
                      close $file; \
                      ");

      printf("data = %s\n", SvPV(perl_get_sv("data", FALSE), length));

      perl_destruct(my_perl);
      perl_free(my_perl);
 }


text:
Q: how to use ajax to search in paginated pages I created a simple js script that will filter names in a list. The issue I'm facing now, is if the list paginates I can't pull up the names without refreshing.
Is there any thing I can do with ajax to look into the other pages, and populate them, without paginating?
The URL looks like this www.mysite.com/my_slug?page=1
Any help would be great. Thanks!
$(document).ready(function(){
  $("#filter-search").on("keyup", function() {
    var value = $(this).val().toLowerCase();
    $(".filter-data").filter(function() {
      $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
    });
  });
});

A: I'm assuming that if you're doing the filtering on the client side JS code that all of the names are available in the JS code (whether they are on another page or not)? If so, then you need to find out where the object or array is that stores ALL names and not just the ones on the current page. This is usually known as the "data source". Once you find this, then you can call the filter function on the data source instead. If you don't have a data source yet, then you need to create one in order for this to be possible.
Alternatively, you can handle this logic on the server side instead. Depending on what kind of app you're building this might be a better approach so that all of the names, filtering, etc. are all maintained on the server side and the client only cares about displaying the names on the current page.


text:
Q: How to cache some temp data in MongoDB? I have some client-server application. And as one of its part, I need to implement a paginal approach on client side. I am making data footprint from db (I'm using MongoDB with 10gen's driver) on server-side and then give part of the footprint on client's request.
I have a problem with storing the footprint. I can't store it on server as local variable, because it simply don't save any data after completing method. I figured out that the footprint data can be stored as a MongoDB cache. But I don't know how it works.
Googling didn't made any progress for me. So can anybody explain me how to implement this MongoDB caching in C#?

A: According to Sergio's and Craig's answers in comments to my question I assume that easiest way "to cache" some data in MongoDB is to create separate collection for storing data. Or (if it's not an option, as in my case) to use built-in ASP.NET cache.


text:
Q: Wordpress Job Manager - Show URL structure as /[listing-category]/[listing-child-category] I am trying to change the standard permalink structure of the job listing feature from Wordpress' Job Manager.
The aim is to stop it having "listing-category" in the URL and changing it to the actual parent category name.
The current URL structure outputs:
/listing-category/marketing-executives

I would like this to be:
/marketing-roles/marketing-executives

for example. "marketing executives" is the child category of "marketing roles" (the parent category).
I have tried threads such as Wordpress - Show parent category AND subcategory name in subcategory archive URL and scoured through Wordpress' developers pages such as https://wordpress.org/plugins/wp-no-category-base/ with no success.
I have also taken a punt on making the custom permalink structure with strings such as:
/%listing-category%/%listing-child%/

again with no success. (It was a very big punt!)
Can anyone guide me as to where I will find the documentation to achieve this, or have any suggestions on what changes I need to make? No doubt it will require custom PHP development which I can happily make with some guidance.
Thanks in advance


text:
Q: Collapse multiple rows based on time values I'm trying to collapse rows with consecutive timeline within the same day into one row but having an issue because of gap in time. For example, my dataset looks like this.
Date            StartTime     EndTime      ID
2017-12-1       09:00:00      11:00:00    12345
2017-12-1       11:00:00      13:00:00    12345
2018-09-08      09:00:00      10:00:00    78465
2018-09-08      10:00:00      12:00:00    78465
2018-09-08      15:00:00      16:00:00    78465
2018-09-08      16:00:00      18:00:00    78465

As up can see, the first two rows can just be combined together without any issue because there's no time gap within that day. However. for the entries on 2019-09-08, there is a gap between 12:00 and 15:00. And I'd like to merge these four records into two different rows like this:
Date            StartTime     EndTime      ID
2017-12-1       09:00:00      13:00:00    12345
2018-09-08      09:00:00      12:00:00    78465
2018-09-08      15:00:00      18:00:00    78465

In other words, I only want to collapse the rows only when the time variables are consecutive within the same day for the same ID.
Could anyone please help me with this? I tried to generate unique group using LAG and LEAD functions but it didn't work.

A: You can use a recursive cte. Group it as same group if the EndTime is same as next StartTime. And then find the MIN() and MAX()
with cte as
(
    select  rn = row_number() over (partition by [ID], [Date] order by [StartTime]),
            *
    from    tbl
),
rcte as
(
    -- anchor member
    select  rn, [ID], [Date], [StartTime], [EndTime], grp = 1
    from    cte
    where   rn  = 1

    union all

    -- recursive member
    select  c.rn, c.[ID], c.[Date], c.[StartTime], c.[EndTime],
            grp = case  when    r.[EndTime] = c.[StartTime]
                        then    r.grp
                        else    r.grp + 1
                        end
    from    rcte r
            inner join cte c    on  r.[ID]      = c.[ID]
                               and  r.[Date]    = c.[Date]
                               and  r.rn        = c.rn - 1
)
select  [ID], [Date],
        min([StartTime]) as StartTime,
        max([EndTime]) as EndTime
from    rcte
group by [ID], [Date], grp

db<>fiddle demo

A: Unless you have a particular objection to collapsing non-consecutive rows, which are consecutive for that ID, you can just use GROUP BY:
SELECT
    Date,
    StartTime = MIN(StartTime),
    EndTime = MAX(EndTime),
    ID
FROM table
GROUP BY ID, Date

Otherwise you can use a solution based on ROW_NUMBER:
SELECT
    Date,
    StartTime,
    EndTime,
    ID
FROM (
    SELECT *,
        rn = ROW_NUMBER() OVER (PARTITION BY Date, ID ORDER BY StartTime)
    FROM table
) t
WHERE rn = 1

A: This is an example of a gaps-and-islands problem -- actually a pretty simple example.  The idea is to assign an "island" grouping to each row specifying that they should be combined because they overlap.  Then aggregate.
How do you assign the island?  In this case, look at the previous endtime and if it is different from the starttime, then the row starts a new island.  Voila!  A cumulative sum of the the start flag identifies each island.
As SQL:
select id, date, min(starttime), max(endtime)
from (select t.*,
             sum(case when prev_endtime = starttime then 0 else 1 end) over (partition by id, date order by starttime) as grp
      from (select t.*,
                   lag(endtime) over (partition by id, date order by starttime) as prev_endtime
            from t
           ) t
     ) t
group by id, date, grp;

Here is a db<>fiddle.
Note:  This assumes that the time periods never span multiple days.  The code can be very easily modified to handle that . . . but with a caveat.  The start and end times should be stored as datetime (or a related timestamp) rather than separating the date and times into different columns.  Why?  SQL Server doesn't support '24:00:00' as a valid time.


text:
Q: composer error "minimum-stability" setting I am trying to install this package
ExeuAmazonECSBundle
"require": {
    "php": ">=5.3.3",
    .
    .
    .
    "exeu/amazon-ecs-bundle": "dev-master"

},

then
sudo php composer.phar update exeu/amazon-ecs-bundle

However it indicates two error potential, I have confirmed it is not type.
my setting is
"minimum-stability": "alpha",

and I can install other bundle as 'dev-master'
How can I slove this?
  Problem 1
    - Installation request for exeu/amazon-ecs-bundle dev-master -> satisfiable by exeu/amazon-ecs-bundle[dev-master].
    - exeu/amazon-ecs-bundle dev-master requires exeu/amazon-ecs-php dev-master -> no matching package found.
  Problem 2
    - exeu/amazon-ecs-bundle dev-master requires exeu/amazon-ecs-php dev-master -> no matching package found.
    - symfony/framework-standard-edition 2.2.x-dev requires exeu/amazon-ecs-bundle dev-master -> satisfiable by exeu/amazon-ecs-bundle[dev-master].
    - Installation request for symfony/framework-standard-edition 2.2.x-dev -> satisfiable by symfony/framework-standard-edition[2.2.x-dev].

Potential causes:
 - A typo in the package name
 - The package is not available in a stable-enough version according to your minimum-stability setting
   see <https://groups.google.com/d/topic/composer-dev/_g3ASeIFlrc/discussion> for more details.

Read <http://getcomposer.org/doc/articles/troubleshooting.md> for further common problems.

A: The error message is quite clear about what the problem is.
You need to contact the guy wrote that library and ask him to also publish the library 'exeu/amazon-ecs-php' which apparently 'exeu/amazon-ecs-bundle' is dependent on.
The package amazon-ecs-php isn't available in any stability, which is why composer is failing.


text:
Q: ng-repeat array of strings into seperate
* elements not working I have an array of objects. Inside each object is an array of strings. What I'd like to accomplish is iterate over the objects with an ng-repeat but inside of that ng-repeat have another repeat to iterate over the array of strings. I would like each string to be it's own ul li element. I've read over several stackoverflow posts and my closest solution seems to iterate over the array of strings but puts them all in one 'li' element. Moving the ng-repeat from the 'li' element to the 'a' tag didn't solve this issue. Will someone look over this and tell me the correct way to get these strings to separate into different 'li' elements.
Picture of issue

Array of Objects (accessed from controller with $ctrl.websites)
[
  {
    id:'someID',
    title: 'First title',
    listOfTechnologies: ['KeystoneJS', 'ExpressJS', 'MongoDB']
  },
  {
    id:'anotherID',
    title: 'Second Title',
    listOfTechnologies: ['MongoDB', 'ExpressJS', 'AngularJS', 'NodeJS']
  }
]

HTML

Marigold Box

Web Projects

 ...

 ...

...

...

...

                 View on the Web

                 View on Github

                {{website.listOfTechnologies[$index]}}

A: if you have defined your scope through $scope.<property> you dont need to reference it with $ctrl.
created a simple Codepen illustrating how it can work

      {{one.id}}

          {{two}}

angular.module("myapp", [])
    .controller("ctlr", function($scope){
  $scope.web = [
  {
    id:'someID',
    title: 'First title',
    listOfTechnologies: ['KeystoneJS', 'ExpressJS', 'MongoDB']
  },
  {
    id:'anotherID',
    title: 'Second Title',
    listOfTechnologies: ['MongoDB', 'ExpressJS', 'AngularJS', 'NodeJS']
  }
];
})


text:
Q: RXJS Share state between merge streams I need to make API call for get/set method. But these Service need previous state to make a next call.
In this pattern, in state prop I wanted to maintain previous state of this stream so that when I make next get/set call I can pass the previous state to service. And once I receive the response from service it will update state for next iteration.
But problem is this merge state is executing get$ and set$ map even before sending value with next.
Can someone please suggest what am I missing here?
const { Subject, merge} = require('rxjs');
const { map,switchMap,scan } = require('rxjs/operators');

function stream(){

  const get$= new Subject()
  const set$= new Subject()

  const store$=merge(
    get$.pipe(
      map(options=>{
        return acc=>{

          return {
            state:{…acc.state},
            service:state=>{
              return getCall(options,state)
            }
          }
        }

      })
    ),
    set$.pipe(
      map(options=>{
        return acc=>{

          return {
            state:{…acc.state},
            service:state=>{
              return setCall(options,state)
            }
          }
        }

      })
    )

  ).pipe(
    scan((acc,update)=>{
      return update(acc)
    },{state:{},service:()=>{}}),
    switchMap(
      ({state,service})=>{
        return service(state)
      }
    )
  )

  return {
    get:options=>{
      get$.next(options)
      return store$
    },
    set:options=>{
      set$.next(options)
      return store$
    }
  }
}
const{get,set}=stream()
get({prop:1}).subscribe(console.log)
set({prop:2}).subscribe(console.log)


text:
Q: Reset Entire Web Page To Original State I have written some javascript that enlivens otherwise boring webpages by replacing all embedded images with better images of Marty Feldman. However, in order to mitigate the obliteration of functionality this usually causes, I would like to have the webpage reset back to its original state after a few seconds. What is my best bet?
My first thought was to save document.body.innerHTML in the variable savedPage and set a timer to set document.body.innerHTML=savedPage, but this seems to throw off some events; no dynamically loaded images will load after this happens, and one page (Citizen's Bank login) grays out and displays a permanent "Please Wait" gif (probably some weird security measure).
I am also genuinely curious if there is a way to make this work.


text:
Q: J stat problem, GMM I have recently performed a GMM estimations, my problem is that all the J-stats are 0.0000. It means that the IV are overrefined right or the model is not well specified. I used one-period lags of the independent variables as interments. Should I just report that the GMM model is misspecified or even if the J stat is 0.0000, i can make some inferences about the coefficients.?

A: If the $J$-stat is 0, then you have a ridiculously good model. If the $p$ value is 0 you have a ridiculously bad model. Say you're estimating moment restrictions
$$ \operatorname{E}[\,g(X_i,\theta)\,]=0$$
with $X$ being the data and $\theta$ being the true parameter value. You have an estimate $\hat{\theta}$, and an estimate of the inverse variance covariance matrix of moments $\hat W$. The $J$-stat is:
$$ N\,\, \bigg(\frac{1}{N}\sum_{i=1}^N g(X_i,\hat\theta)\bigg)' \hat{W} \bigg(\frac{1}{N}\sum_{t=1}^N g(X_i,\hat\theta)\bigg)\ $$
If your model correctly describes the data (and your estimation routine is working okay) then $\frac{1}{N}\sum_{t=1}^Ng(X_i,\hat\theta)$ will be very close to 0, and this statistic will be extremely low. It will in fact be asymptotically $\chi^2$ distributed (degrees of freedom = #moments - #parameters) under the null of a correctly identified model. For a 5% significance compare this statistic to the 0.95 quantile of the distribution - so you need to be careful what this $p$ value corresponds to. Higher $J$-stats should lead to higher rejections. I'm assuming that you're using a package for this which calculates the $p$-value for you, in which case everything should be correct and low $p$-values will mean a rejected model. I also assume your $p$-value is 0, because I have never seen a $J$-stat that low, although who knows?
What does it mean if your $J$ stat is extremely far away from zero? You have a bad model, but again what does that mean? The $J$-stat is a test of over-identifying restrictions - your model places enough restrictions that you can check to make sure that they are all consistent. If your model were completely correct, it should be possible to satisfy all the moment restrictions simultaneously, even though there are more equations there than unknowns. You could imagine a situation where you have five correct moments, and add one incorrect moment restriction into a model. The $J$-stat will reject the model. That tells you the last restriction is inconsistent with the parameters necessary to satisfy the others. If this is the case you should not use the parameters. With a more complicated model they may still be of interest for telling you something about the model and moments themselves, what kind of restrictions they place on your parameters and why the moments might be impossible to consistently satisfy. It still answers the question "what parameters give us the best this model can do to explain the data?" But you should not really carry these estimates over to other applications.
In an IV model, your moment restrictions are really exclusion restrictions, $E[z_i^\prime(y_i-x_i\beta)]=0$ (plus the model itself, $x_i\beta$). A $J$ test can never tell you whether every one of your individual IV exclusion restrictions are correct or incorrect - there's no really good way to determine that. Instead, if you don't reject the null it tells you that given some of your exclusion restrictions/model are correct, it seems the rest of the restrictions can be satisfied by the same parameter values. In other words, it can't tell you about the validity of your instruments, just about their consistency. You should check to see whether there are particular instruments whose exclusion restrictions are giving you problems, but don't rely on a $J$-test to validate your underlying exogeneity assumptions.


text:
Q: Join two tables with OR logic in PowerQuery As the title states, I am trying to do a merge of 2 tables. I want a nested joint where the values from the first table are always there and rows matching the second table are added to the first. I believe this is known as the nested join.
Unfortunately, it only allows for 1 key to 1 key matching where as I need it for 1 key in table 1 to 2 keys in table 2
Here is an example
Table1:

Group
..
..
Time
Date

Table2:

Group 1
Group 2
..
..
..
Other Info

What I want is where "Group = Group 1 OR Group = Group 2" and display the matching row from table 2 nested into Table 1
I looked at the following example but I must be confused by the syntax because it doesn't seem to be working for me.
How to join two tables in PowerQuery with one of many columns matching?

A: So after further investigation of the answer post I linked earlier, I will add an explanation of it here:
Table.AddColumn(Source, "Name_of_Column",
    (Q1) => Table.SelectRows(Query2,
                each Q1[Col_from_q1] = [Col_from_q2] or Q1[Col_from_q1] = [2_Col_from_q2]
            )
)

So this did work for me and it adds an extra column that needs to be expanded to get all the values from the table. What i would add is that I don't know / haven't tested if there are multiple matches and how it treats it, based on nestedjoin, I would assume that it will duplicate rows in the first table.


text:
Q: Run a function inside two v-for loop in vue js I have two v-for loops like so:

{{data.name}}

The first v-for iterates through an array of ids stored inside data().
On the second v-for it iterates through the result returned by the function getData().
The axios call does return an array of result including the name per ids, however the
 tag doesnt display the names.

A: I think this is the problem:
when v-for calls your method it doesn't wait for axios call to resolve and since there is no array immediately available for it to iterate on, it can't show anything (there isn't anything to show), on the other hand when axios call does resolve there is no way for v-for to get notified and therefore update the template. so situation is something like this:

*

*v-for runs your method

*method doesn't return an array immediately and v-for can't wait

*there is nothing to show here and it moves on

so here is what you can do:

*

*bind the v-for to an array in data object

*use axios result to update the said array

and it should work fine, your code might be like this for example:
// template

{{data.name}}

//script


text:
Q: I've got FairlyLocal, but I need it for a project in VB but the function _() is not supported I've found this nice library to make localization in a .NET application. Problem is, this FairlyLocal is build in C#. Now I downloaded a convertor to make it happen in VB.NET.
But it seems my project is using the FairlyLocal.dll which is a binary and uses _() where '_' is the name of the function.
All I want is to change the '_' to 't' so it would work with the VB.NET application too.
How is this possible. I'm a greeny to VB.NET and .NET overall so please don't be rude.
Edit:
For example I got a login page with a h1:
<ASP:CONTENT ID="content2" CONTENTPLACEHOLDERID="heading" RUNAT="server">
    <% _("This is a heading") %>
</ASP:CONTENT>

Problem I get is at the '_': Identifier expected
I also tried what Justin said (with the brackets []) but that doesn't work eiter.

A: Since only the source is distributed, assuming this is where you got it from, just change the method name from _ to t in your InternationalPage and InternationalMaster classes. Then, build the library and use it in your VB.NET application.

A: I'm not sure if it will work, but you may be able to call the function named _ from VB.NET by enclosing it in square brackets.  This is more often used when an identifier has the same name as a VB.NET keyword -- it may not work with all symbols.  Something like:
result = obj.[_]()

A: Don't convert it. Just build it in C# and add it as a reference in your project. From there you'll be able to use it as if it was written in vb.net


text:
Q: Custom "let" expression in Scala I'd love to have let construct similar to the one in Haskell in Scala. I tried a few ways, but none seems to be good. Here's some code:
object CustomLet extends App {
  val data = for (i <- 1 to 1024; j <- 1 to 512) yield (i % j) * i * (i + 1) - 1

  def heavyCalc() = { println("heavyCalc called"); data.sum }

  def doSomethingWithRes(res: Int) = {
    println(s"${res * res}")
    1
  }

  def cond(value: Int): Boolean = value > 256

  // not really usable, even though it's an expression (2x heavyCalc calls)
  def withoutLet() = if (cond(heavyCalc())) doSomethingWithRes(heavyCalc()) else 0

  // not an expression
  def letWithVal(): Int = {
    val res = heavyCalc()
    if (cond(res)) doSomethingWithRes(res)
    else 0
  }

  // a lot of code to simulate "let", at least it is an expression
  def letWithMatch(): Int = heavyCalc() match {
    case res => if (cond(res)) doSomethingWithRes(res) else 0
  }

  // not perfect solution from
  // http://stackoverflow.com/questions/3241101/with-statement-equivalent-for-scala/3241249#3241249
  def let[A, B](param: A)(body: A => B): B = body(param)

  // not bad, but I'm not sure if it could handle more bindings at once
  def letWithApp(): Int = let(heavyCalc()) {res => if (cond(res)) doSomethingWithRes(res) else 0}

  List[(String, () => Int)](
    ("withoutLet", withoutLet),
    ("letWithVal", letWithVal),
    ("letWithMatch", letWithMatch),
    ("letWithApp", letWithApp)
  ).foreach(
    item => item match {
      case (title, func) => {
        println(s"executing $title")
        val ret = func()
        println(s"$title finished with $ret")
        println()
      }
    }
  )
}

This is the ideal look of it (with only one binding, more could be separated by ,; not sure about the in keyword):
  // desired look
  def letTest(): Int =
    let res = heavyCalc() in
      if (cond(res)) doSomethingWithRes(res) else 0

I'm not sure if it's possible, but I have no experience with most of advanced Scala stuff like macros, so I can't really tell.
EDIT1: To be clear, the main things I'm expecting from it are: being expression and relatively simple syntax (like the one outlined above).

A: You could use a forward pipe:
object ForwardPipeContainer {
  implicit class ForwardPipe[A](val value: A) extends AnyVal {
    def |>[B](f: A => B): B = f(value)
  }
}

to be used like this:
import ForwardPipeContainer._

def f(i: Int) = i * i

println( f(3) |> (x => x * x) )

You can put multiple arguments in a tuple:
println( (f(2), f(3)) |> (x => x._1 * x._2) )

which looks better if combined with partial function synatx:
println( (f(2), f(3)) |> { case (x, y) => x * y } )

This answer is a variation of What is a good way of reusing function result in Scala, and both are based on Cache an intermediate variable in an one-liner where I got the initial idea from.

A: def letTest(): Int =
    let res = heavyCalc() in
      if (cond(res)) doSomethingWithRes(res) else 0

I would write this:
def letTest(): Int = {
  val res = heavyCalc()
  if (cond(res)) doSomethingWithRes(res) else 0
}

Ignoring laziness, let is just a construct that introduces a lexical scope, binds some terms to some names then returns an expression. So in Scala you would do
{ // new lexical scope
  // bind terms section
  val a = f()
  def b = a + g() // may be I don't want g to be evaluated unless b is needed
  val c = h()
  // result expression
  if (c) b else a
}

Macros should be able to enforce this syntactic layout if you want to ensure that there is nothing else going on in the block. There is actually a SIP (Scala Improvement Process) proposal called Spores that would enforce some of the same constraints (and an additional one: that you don't capture a reference of an enclosing object unknowingly).
Note that blocks in Scala are expressions that evaluate to the last expression in the block. So let me take a random let example from Haskell:
aaa = let y = 1+2
          z = 4+6
          in let f = 3
                 e = 3
             in e+f

This translates to:
val aaa = {
  val y = 1 + 2
  val z = 4 + 6
  val u = {
    val f = 3
    val e = 3
    e + f
  }
  u
}

As you can see the block statement can be used as an expression.


text:
Q: Label se movendo como letreiro digital Olá, gostaria de saber como que faço em Swift uma frase ficar passando da direita pra esquerda e quando toda frase passar ela ficar fazendo o mesmo procedimento eternamente, como um letreiro digital.

A: Para criar esse efeito da label se movendo (chamado efeito Marquee) você pode usar essa biblioteca: https://github.com/cbpowell/MarqueeLabel-Swift
Se estiver usando cocoapods é só adicionar pod 'MarqueeLabel-Swift' no seu podfile, ou caso queira adicionar manualmente é só colocar a classe MarqueeLabel.swift para dentro do seu projeto.
Agora basta criar uma label no no seu storyboard e colocar a classe dela como custom do tipo MarqueeLabel e conectar com seu @IBOutlet:
  @IBOutlet weak var marqueeLabel: MarqueeLabel!

  override func viewDidLoad() {
    super.viewDidLoad()

    marqueeLabel.type = .Continuous
    marqueeLabel.scrollDuration = 5.0
    marqueeLabel.animationCurve = .EaseInOut
    marqueeLabel.fadeLength = 10.0
    marqueeLabel.leadingBuffer = 30.0
    marqueeLabel.trailingBuffer = 20.0
  }


text:
Q: Tkinter - Storing folder directory in function and calling it to change directory I am trying to develop a GUI with tkinter. I have created a function (as a button) to browse for a directory folder ('input folder'). I have a routine linked to another button ('execute') that needs the path from 'input folder'.
I am getting errors when I try to pass the path from 'input folder' into os.chdir inside 'execute'. Example is as follows:
import sys
import os
from tkinter import filedialog
from tkinter import *

window = Tk()

def Input():
    filename = filedialog.askdirectory()
    global filename

def Extraction():
    in_loc = filename
    os.chdir(in_loc)

btn = Button(window, text="Extract", bg="black", fg="white", command=Extraction)
btn.pack()

btn2 = Button(text="Input", command=Input).pack()

window.mainloop()

Can anyone reproduce this and tell me what I am doing wrong here?
Thanks :)

A: Try this:
import sys
import os
from tkinter import filedialog
from tkinter import *

filename = ''

def input_function():
    global filename

    filename = filedialog.askdirectory()

def extraction():
    global filename

    in_loc = filename
    os.chdir(in_loc)

window = Tk()

btn = Button(window, text="Extract", bg="black", fg="white", command=extraction)
btn.pack()

btn2 = Button(text="Input", command=input_function).pack()

window.mainloop()


text:
Q: Is there any open source GWT widget that serves a function of "Item list" Is there any open source GWT widget/component that serves a function of a "Item List" that supports pagination, like page1, page2, PREV, NEXT buttons.

A: GWT CellList is not an option? GWT CellTable with one column?

A: Check the following links:
http://code.google.com/p/gwt-table/
http://code.google.com/p/gwt-table/wiki/PagingTableWidget
The offer step-by-step tutorial for pagination


text:
Q: How do I get the frequency totals for each bar in a barplot in R? I have the following code to generate a dataset in R.  However, I want the actual precise values for each x value in the chart and cant figure out how to generate these values.  Here is the code I have:
x <- c("CF", "CH", "CJ", "CE", "CN", "EC", "EN", "EJ", "AB", "BA", "KO", "OD", "DL", "HG")
px = c(0.08, 0.10, 0.06, 0.20, 0.04, 0.15, 0.02, 0.10, 0.025, 0.025, 0.05, 0.05, 0.05, 0.05)
draws = sample(x, size = 1000, replace = TRUE, prob = px)
barplot(height=table(draws))

How can I get the precise frequencies for each of the x values (i.e. CF, CH, CE, etc.)?

A: The function 'table' provides counts of each factor
Try:
    table(draws)

A: Here is one way:
sapply(lapply(x, '==', draws), sum)


text:
Q: Scrolling Background creating a gap between images - Swift I've created an infinite scrolling background out of 2 images.  As the scrolling speed increases, a gap begins to appear between the images.  Here is my code:
 override func update(currentTime: CFTimeInterval) {

    var fallingSpeed = 4 + speedIncrease

    background.position.y = background.position.y - fallingSpeed
    background2.position.y = background2.position.y - fallingSpeed

    if background.position.y <= 0 {
        background.position.y = size.height*2 - (fallingSpeed)

    }
    if background2.position.y <= 0 {
        background2.position.y = size.height*2 - (fallingSpeed)

    }
}

speedIncrease increases by +.1 every time the user taps the screen because I want the background to move faster as the game goes on.
Both backgrounds are the same image and size.
The gap only occurs as speedIncrease increases.  speedIncrease is initially set to 0 and the background scrolls smoothly with no gap.  When I start tapping the screen and increasing speedIncrease, then the gap appears.
Any suggestion as to how I can remove the gap?  I'm still very new to Swift and Obj-C so any advice for a beginner would be very appreciated.

A: I have had a similar issue, and managed to fix it by setting my position to a CGPoint with whole pixel (Integer) values. My assumption is that your problem is similar, and is caused because your background is drawn at fractions of a pixel.
Since you are only changing the position.y, you need a CGFloat, so you could simply round the number: background.position.y = round(some_CGFloat)
For Retina (@2x) screens, the pixels are actually on each 0.5 of the position.y. In this case you could do this: background.position.y = round(some_CGFloat * 2.0) / 2.0
Try the following code (assuming Retina display):
override func update(currentTime: CFTimeInterval) {

  var fallingSpeed = 4 + speedIncrease

  background.position.y = round((background.position.y - fallingSpeed) * 2.0) / 2.0
  background2.position.y = round((background2.position.y - fallingSpeed) * 2.0) / 2.0

  if background.position.y <= 0 {
    background.position.y = round((size.height * 2 - fallingSpeed) * 2.0) / 2.0
  }
  if background2.position.y <= 0 {
    background2.position.y = round((size.height * 2 - fallingSpeed) * 2.0) / 2.0
  }
}

I do realize this is an older question, but I hope it can help people with similar issues.


text:
Q: SetInterval Collides When Calling a jQuery Plugin More than Once I'm working on a custom jQuery plugin that makes use of SetInterval, but it breaks when it's called more than once.
I have something sort of like this:
(function($){
    $.fn.myplugin = function(options) {

        var defaults = {};
        var options = $.extend(defaults, options);
    var interval;

        this.each(function() {
            //etc.
            interval = setInterval(function(){ doMyOtherFunc(options); }, 1000);
        });

        function doMyOtherFunc(options) {
            //etc
        }

    }
})(jQuery);

Functionality works as expected if I call it once, but if I call it again on a second element it breaks.
$('#myelement').myplugin({'option1', 'option2'});
$('#myotherelement').myplugin({'option1', 'option2'});

Somehow, the interval in the second instance overrides the one on the previous element, data and all. (But the styling passed doesn't get screwed up.) Is this a weird limitation of setInterval, or am I doing something wrong?

A: You have to make the interval handle private to each element. For this, you could use $.data:
    this.each(function() {
        var interval = setInterval(function(){ doMyOtherFunc(options); }, 1000);
        $(this).data('myplugin-interval', interval);
    });

And you could retrieve the interval this way:
$(this).data('myplugin-interval');


text:
Q: Should I say "Using support" or "Using supported" Android version? Should I say "Using support Android version: You can do something" or "Using supported Android version: You can do something" ?
I want to mean if you have the current version, you can do this thing.

A: A range of system versions is typically supported by a developer, otherwise either the market is limited, or people are forced to upgrade with every new version.
So for example you can say

Using supported Android versions, you can do XXX.

or

Using supported versions of Android, you can do XXX.

or

You can do XXX using supported versions of Android.

There are currently three supported Android versions: Nougat, Oreo and Pie. There is a beta release of the next Android Q version, so to say "current version" isn't very specific.


text:
Q: Open id connect access token expiration We are using Open id connect authentication code flow to get refresh token and access token from external authorization server. I am thinking on using IdentityModel library to retrieve the tokens from the code.
https://github.com/IdentityModel/IdentityModel2/blob/dev/README.md
Tokens would be stored in database with the expiration date.
I would like to know the best practice to check if the access token is expired. I understand that one of the following ways would be helpful to achieve so. Would like to know if there is cleaner and better approach.

*

*Access the protected service using the expired token. Guess it would throw an exception

*Compare the expiration date with the today date.

*Is there a way in IdentityModel library to check for the expiration of access token?

Any other better approach?

A: I do it like this. First get the access token with the code
        _tokenClient = new TokenClient(_options.Authority);
        var response = await _tokenClient.RequestAuthorizationCodeAsync("CODE", "http://myuri");
        var token = response.AccessToken;
        var validUntil = DateTime.Now.AddSeconds(response.ExpiresIn);

Later I can use this value to check if the token is still valid. You can store the valid until value in the database or attach it to your users session.
        if(DateTime.Now >= validUntil)
        {
            // token expired
        }

I usually subtract a couple of minutes from this value - so I don't have to wait until the last minute before refreshing the token.


text:
Q: How do you use a custom comparator with SingleColumnValueFilter on HBase? I am trying to filter rows from a HBase table using two SingleColumnValueFilter objects to bring back all records that fall within a range of long values for the column. According to the documentation for the SingleColumnValueFilter, it does a lexicographic compare of the column value unless you pass it your own comparator. The api shows the SingleColumnValueFilter taking a WritableByteArrayComparable as a way to accomplish this.
I wrote a class extending the WritableByteArrayComparable and overwriting the compare method.
    public class LongWritableComparable extends WritableByteArrayComparable {

    public LongWritableComparable() {
        super();
    }

    public LongWritableComparable(byte[] value) {
        super(value);
    }

    public LongWritableComparable(Long value) {
        super(Bytes.toBytes(value));
    }

    @Override
    public int compareTo(byte[] otherValue) {
        byte[] thisValue = this.getValue();
        long thisLong = Bytes.toLong(thisValue);
        long otherLong = Bytes.toLong(otherValue);

        if (thisLong == otherLong) {
            return 0;
        }
        if (thisLong < otherLong) {
            return -1;
        }
        return 1;
    }
}

I am settting up the filter using:
SingleColumnValueFilter lowerBoundAddressResourceFilter = new SingleColumnValueFilter(
                    graphTable.getResource().getName(),
                    Bytes.toBytes(HBaseProperties.getInstance().getQualifierIpAdressLongRepresentation()),
                    CompareFilter.CompareOp.GREATER_OR_EQUAL,
                    new LongWritableComparable(lowerRangeValue));

but am seeing the following exception:
2010-08-25 14:24:10,034 ERROR org.apache.hadoop.hbase.regionserver.HRegionServer:
org.apache.hadoop.hbase.UnknownScannerException: Name: -1
        at org.apache.hadoop.hbase.regionserver.HRegionServer.next(HRegionServer.java:1880)
        at sun.reflect.GeneratedMethodAccessor5.invoke(Unknown Source)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
        at java.lang.reflect.Method.invoke(Method.java:597)
        at org.apache.hadoop.hbase.ipc.HBaseRPC$Server.call(HBaseRPC.java:657)
        at org.apache.hadoop.hbase.ipc.HBaseServer$Handler.run(HBaseServer.java:915)
2010-08-25 14:24:10,052 INFO org.apache.hadoop.ipc.HBaseServer: IPC Server handler 0 on 60020, call next(-1, 1000) from 172.16.32.215:53206: error: org.apache.hadoop.hbase.UnknownScannerException: Name: -1
org.apache.hadoop.hbase.UnknownScannerException: Name: -1
        at org.apache.hadoop.hbase.regionserver.HRegionServer.next(HRegionServer.java:1880)
        at sun.reflect.GeneratedMethodAccessor5.invoke(Unknown Source)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
        at java.lang.reflect.Method.invoke(Method.java:597)
        at org.apache.hadoop.hbase.ipc.HBaseRPC$Server.call(HBaseRPC.java:657)
        at org.apache.hadoop.hbase.ipc.HBaseServer$Handler.run(HBaseServer.java:915)

Looking on the web the consensus for the cause of this execption is that the code accessing the resultScanner.next() is taking too long causing the lease to the regionServer to timeout, but this exception is getting thrown before
ResultScanner resultScanner = table.getScanner(scan);

returns with a ResultScanner that I can iterate through.
Does anyone have or know of an example of using a custom comparator with SingleColumnValueFilter that works or any insight into what I am doing wrong?

A: It appears that the jar with your custom comparator needs to be placed on the region server(s) where the table you are querying reside in the $HBASE_HOME/lib folder. After placing the jar restart your cluster and the query should work.


text:
Q: Defining an equivalent measure starting from a continuous local Martingale Suppose we have continuous local martingal $L$ given. We define $Z=\mathcal{E}(L)$, the stochastic exponential of $L$. I am interested in finding some condition such that $Z$ defines a density, i.e. I can define an equivalent measure $Q$ by setting $dQ:=Z_\infty dP$.
First of all: $Z$ is again a continuous local martingale, positive hence a supermartingale and $>0$ on $[0,\infty)$. Hence $Z_\infty$ exists. Now I need two assumption, such that everything works out nicely

*

*$E[Z_\infty]=1$, which is equivalent to the property that $Z$ is a $P$-martingale on $[0,\infty]$, hence uniformly integrable.

*I have to guarantee that $Z_\infty>0$ $P$-a.s.

For $2.$ we have $Z_\infty =e^{L_\infty -\frac{1}{2}\langle L\rangle_\infty}$. Therefore $L_\infty -\frac{1}{2}\langle L\rangle_\infty \not= -\infty$. Since the bracket process is increasing, we must have $\langle L\rangle_\infty <\infty$. The question is:

Can it happen that $\langle L\rangle_\infty <\infty$ but $L_\infty = -\infty$. If so, are there conditions which excludes $L_\infty=-\infty$ and $\langle L\rangle_\infty =\infty$?

A: Let $L$ be a continuous local martingale with initial value zero. Define
$$
F = \{\omega\in\Omega\mid L_t \textrm{ converges as }t\to\infty\}\\
G = \{\omega\in\Omega\mid \langle L\rangle_t \textrm{ converges as }t\to\infty\}.
$$
It then holds that $F$ and $G$ are $P$-almost surely equal, in the sense that $P(F\setminus G)=P(G\setminus F)=0$. This implies that almost surely, it cannot happen that $\langle L\rangle_\infty<\infty$ but $L_\infty=-\infty.$
The proof of the above claim is not completely straightforward. You can find a detailed proof as the solution to Exercise 2.3 (in the appendix) in the following:
http://alexandersokol.dk/StochInt/ContinuousStochasticIntegration.pdf


text:
Q: Can I create an application or object from an existing XML file I have a couple of XML files that are used to control unattended installations of sharepoint. I need to create a simple desktop application that will create / modify these xml files.
Before i go through and create a load of stuff manually is there any way i can automate some of the process. I.E. can i generate my objects from an XML file?
Could i even create the starting of a GUI from the XML file or object?
I am using c# and can use visual studio 2008 or 2010 and up to .NET 4

A: You can create a XSD file based on the xml files and with the xsd compiler you can create classes based on the XSD files.
create a XSD from XML use like this
xsd myFile.xml /outputdir:myOutputDir

and create classes from XSD like this
xsd schema.xsd /classes

and loading in code like this
StreamReader str = new StreamReader("schema.xml");
XmlSerializer xSerializer = new XmlSerializer(typeof(myGeneratedClass));

myGeneratedClass myCdCatalogue = (myGeneratedClass)xSerializer.Deserialize(str);

regards

A: I've just found this post which describes how to...

read in XML from a file using HTTPService, put the data in an XMLListCollection, and then iterate through the data, creating UI elements.

It might provide you with a starting point for your application.

A: Another option would be to use InfoPath, creating xml-files are the whole purpose of that Office product


text:
Q: Внедрение в контекстное меню android телефона Здравствуйте, подскажите пожалуйста есть ли возможность внедрить в меню "Копировать вставить" свой пункт? При нажатие на который мы бы переходили с собственное приложение.

A: Есть такая возможность через setCustomSelectionActionModeCallback


text:
Q: Source not found on array This is what I am meant to do:
This class extends
JPanel, like the others. The constructor has two parameters: the controller and the number of tracks. You should not store these in member variables All of this is in the constructor:
Set the layout to null.
Store numTracks SoundNameBox instances in a member variable array, where numTracks is the number of tracks. This means you need to have a loop, and each time through the loop create one more SoundNameBox instance. The track number will range from 0 to numTracks -1. Make sure that there is a Tracks.GAP_SIZE sized gap between them. Set the size of this SoundBank so that it just contains the SoundNameBox instances.
I had to create a similar class before and it worked fine, however this one does not display the boxes it is supposed to and when I try to debug it it says that there is a source not found when I assign the array to the member variable.
Here is my code:
package view;

import javax.swing.JPanel;

import controller.Controller;

public class SoundBank extends JPanel {

    public SoundNameBox[] _track;

    public SoundBank(Controller controller, int numTracks) {
        setLayout(null);
        _track = new SoundNameBox[numTracks];
        int y = 0;
        for(int i = 0; i < numTracks; i++) {
            _track[i] = new SoundNameBox(controller, i);
            _track[i].setLocation(0,y);
            y = y + Tracks.GAP_SIZE;
        }
        this.setSize(Tracks.GAP_SIZE*numTracks, Tracks.GAP_SIZE*numTracks);
    }

    public void setSoundName(int numTrack, String name) {
        _track[numTrack].setText(name);
    }
}

A: You also need to add the SoundNameBox object to the JPanel after instantiation.
Put this in the constructor's for loop
this.add(_track[i]);

Good luck


text:
Q: Is the sign of the discriminant of a polynomial important? The discriminant of a polynomial is a very useful quantity but I have never seen the sign of a discriminant be useful. I know that the generalization of a discriminant from number fields over $\Bbb Q$ is other number fields is an ideal defined over the base field and clearly, in this generalized case, the sign cannot matter.
However, perhaps the sign is important elsewhere?

A: The sign of the discriminant of a monic polynomial $f(X) \in \mathbb R[X]$ is
$$(-1)^{r}$$
where $r$ is half the number of non-real roots of $f$.
Consider for instance a cubic monic polynomial $f(X)$ with roots $a, b, c$. Since non-real roots appear in complex conjugate pairs there are two possibilities: either all of $a, b, c$ are real, or one is real and the other two are complex conjugates.
The discriminant is
$$(a-b)^2(a-c)^2(b-c)^2.$$
This is clearly positive if all of $a,b,c$ are real. In the case where $a$ and $b$ are complex conjugate and $c$ is real, then $a-c$ and $b-c$ are complex conjugate so $(a-c)^2(b-c)^2$ is a positive real number, and on the other hand $(a-b)^2$ is the square of a purely imaginary number and is therefore negative, so the discriminant is negative.
(By the way, this is cool because you can calculate the discriminant of $f$ from its coefficients, and thus you have an easy and direct way to check whether a cubic polynomial has $3$ real roots or only $1$ real root.)


text:
Q: VSCode - TSLint Error ENOTDIR invalid cwd I'm using VSCode with TSLint (v5.11.0).
I set up the VSCode to:
"tslint.autoFixOnSave": true
However, whenever I open any ts files I get this TS error on the output:
[Info  - 14:52:31] vscode-tslint: Status is OK
[Info  - 14:52:31] vscode-tslint: Cannot read tslint configuration - 'ENOTDIR invalid cwd /Users/batman/project/Command.ts'

Because of this error vscode does not automatically fix the TS issues in my tslint.json file.
It is not just this one file it is any typescript files I open. Please let me know how to fix this.
Thanks.

A: It looks like you don't have a tsconfig.json file.
If you DO have one, it's not on the root folder of your project (aka cwd).
Please, refer to the documentation: https://www.typescriptlang.org/docs/handbook/tsconfig-json.html