text:
Q: классы в javascript

class Button {
constructor ($element) {
  this.$element = $element;
  this.coords = {
    x: 0,
    y: 0,
 w: 0,
    h: 0
  }
}
}

Button.prototype.setCoords_but = function(x, y, w, h) {
  this.coords = {
    x: x,
    y: y,
 w: w,
    h: h
  }
   this.$element.offset({
    top: this.coords.x,
    left: this.coords.y
  });
  this.$element.css({height: this.coords.h, width: this.coords.w});
 }

var button_proverka = new Button($('#proverka'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>

  <button id="proverka">Проверка</button>
  <button id="delete">Очистить</button>
  <button id="table_ist"  >Построить</button>

</body>

Вопрос заключается в следующем: возможно ли описать класс в отдельном файле и вызвать его в другом файле? Если возможно такое, то каким образом! и следующее: как можно изменять стиль кнопки при наведении курсора мыши и нажатие на кнопку (все это должно быть описано в классе)

A:
Возможно ли описать класс в отдельном файле и вызвать его в другом файле?

Да, возможно, при этом файл с классом должен быть подключен раньше файла с его вызовом. Если вы конкатенируете файлы в один, код с классом должен быть в результате выше, т.к. его объявление не всплывает.

как можно изменять стиль кнопки при наведении курсора мыши и нажатие на кнопку (все это должно быть описано в классе)

Если вы не хотите/не можете делать это через CSS, вешайте на кнопку обработчики событий мыши:
class Button {

    constructor($element) {
        this.$element = $element;

        this.$element.addEventListener('mouseover', this.onMouseover);
        this.$element.addEventListener('mouseout', this.onMouseout);
        this.$element.addEventListener('click', this.onClick);
    }

    ...

    onMouseover(event) { /*код функции*/ }

    onMouseout(event) { /*код функции*/ }

    onClick(event) { /*код функции*/ }

   ...
}

p.s. Навешивать обработчики не обязательно в конструкторе. Можете поместить их в отдельную функцию и вызвать ее, когда вам будет удобнее.


text:
Q: 403(Forbidden), Invalid Key Error On Google Speech API I am trying to access speech api using following url and always getting 403(Forbidden) Error, Invalid Key.
https://www.google.com/speech-api/v2/recognize?output=json&lang=en-us&key={MyKey}
I have tried with both Server Key and Browser key as shown on this Keys image.
I am sending http request using .NET HTTP Client; Code snippet is given below:
Stream stream = null;
            StreamReader sr = null;
            WebResponse response = null;
            JSon.RecognizedItem result;
            try
            {
                WebRequest request = WebRequest.Create(Constants.GoogleRequestString);
                request.Method = "POST";
                request.ContentType = "audio/x-flac; rate=" + sampleRate;
                request.ContentLength = bytes.Length;

                stream = request.GetRequestStream();

                stream.Write(bytes, 0, bytes.Length);
                stream.Close();

                response = request.GetResponse();

                stream = response.GetResponseStream();
                if (stream == null)
                {
                    throw new Exception("Can't get a response from server. Response stream is null.");
                }
                sr = new StreamReader(stream);

                //Get response in JSON format
                string respFromServer = sr.ReadToEnd();

                var parsedResult = JSon.Parse(respFromServer);
                result =
                    parsedResult.hypotheses.Where(d => d.confidence == parsedResult.hypotheses.Max(p => p.confidence)).FirstOrDefault();
            }
            finally
            {
                if (stream != null)
                    stream.Close();

                if (sr != null)
                    sr.Close();

                if (response != null)
                    response.Close();
            }

            return result == null ? "" : result.utterance;

Can anybody please help me to identify the problem here.
Thanks,
Ab.

A: For that API endpoint, usage quota is no longer offered. And, apparently, it was an endpoint specific for community developers for the Chromium project.
Google's Speech API is the Cloud Speech API .
The keys you are referencing appear to be set up in your Google Cloud Project (GCP). GCP, implicitly those keys, can be linked to the Cloud Speech API, as pointed out here, not the https://www.google.com/speech-api/v2/ one.

redpajama_set_name: RedPajamaStackExchange


text:
Q: bash.bashrc not working for all users So I have 2 users on my PC when I add the line alias abc='echo Hello' in /etc/bash.bashrc file and log back in it only works for the first user. (the one that I changed the file) I even rebooted my PC and still didn't work.
Here's my bash.bashrc file (I know it's not necessary but just to give more info):
alias abc='echo Hi' # <<< Here's the line I've added

# System-wide .bashrc file for interactive bash(1) shells.

# To enable the settings / commands in this file for login shells as well,
# this file has to be sourced in /etc/profile.

# If not running interactively, don't do anything
[ -z "$PS1" ] && return

# check the window size after each command and, if necessary,
# update the values of LINES and COLUMNS.
shopt -s checkwinsize

# set variable identifying the chroot you work in (used in the prompt below)
if [ -z "${debian_chroot:-}" ] && [ -r /etc/debian_chroot ]; then
    debian_chroot=$(cat /etc/debian_chroot)
fi

# set a fancy prompt (non-color, overwrite the one in /etc/profile)
# but only if not SUDOing and have SUDO_PS1 set; then assume smart user.
if ! [ -n "${SUDO_USER}" -a -n "${SUDO_PS1}" ]; then
  PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w\$ '
fi

# Commented out, don't overwrite xterm -T "title" -n "icontitle" by default.
# If this is an xterm set the title to user@host:dir
#case "$TERM" in
#xterm*|rxvt*)
#    PROMPT_COMMAND='echo -ne "\033]0;${USER}@${HOSTNAME}: ${PWD}\007"'
#    ;;
#*)
#    ;;
#esac

# enable bash completion in interactive shells
#if ! shopt -oq posix; then
#  if [ -f /usr/share/bash-completion/bash_completion ]; then
#    . /usr/share/bash-completion/bash_completion
#  elif [ -f /etc/bash_completion ]; then
#    . /etc/bash_completion
#  fi
#fi

# sudo hint
if [ ! -e "$HOME/.sudo_as_admin_successful" ] && [ ! -e "$HOME/.hushlogin" ] ; then
    case " $(groups) " in *\ admin\ *|*\ sudo\ *)
    if [ -x /usr/bin/sudo ]; then
    cat <<-EOF
    To run a command as administrator (user "root"), use "sudo <command>".
    See "man sudo_root" for details.

    EOF
    fi
    esac
fi

# if the command-not-found package is installed, use it
if [ -x /usr/lib/command-not-found -o -x /usr/share/command-not-found/command-not-found ]; then
    function command_not_found_handle {
            # check because c-n-f could've been removed in the meantime
                if [ -x /usr/lib/command-not-found ]; then
           /usr/lib/command-not-found -- "$1"
                   return $?
                elif [ -x /usr/share/command-not-found/command-not-found ]; then
           /usr/share/command-not-found/command-not-found -- "$1"
                   return $?
        else
           printf "%s: command not found\n" "$1" >&2
           return 127
        fi
    }
fi

Also I'm running xubuntu 18.04.5 LTS.

A: The /etc/bash.bashrc is sourced from /etc/profile if the user's default shell is bash.  The default shell is set in the last field of the /etc/passwd file on that user's line. If another shell is used, like /usr/bin/sh, then the /etc/profile logic says skip the sourcing of the bash.bashrc.
Change the default shell to bash with usermod:
usermod -s /bin/bash USER2


text:
Q: accessing other users calendar in google apps by super admin As we know Super administrators also have full access to all users' calendars and calendar event details.
I found these API's
https://developers.google.com/google-apps/calendar/v3/reference/ which can be used to retrieve calendar's related to a user.
i read google docs api
for getting information about a current user we use default
https://docs.google.com/feeds/default/...
and for getting information about other user in the same domain
https://docs.google.com/feeds/user@yourdomain.com/...
we have to replace default with user's email address.
but in calendar's api for accessing list of current user's calendar's list
we use this url
https://www.googleapis.com/calendar/v3/users/me/calendarList
if current user is an administrator and i have to retrieve list of calendar of other user in the same domain then how to retrieve that list
i tried to call https://www.googleapis.com/calendar/v3/users/rashmi@riteshmehandiratta.com/calendarList
response is  Not Found.riteshmehandiratta.com is my domain and rashmi is a user so email address is rashmi@riteshmehandiratta.com i authorize my app by super administrator and successfully get access token and putting header
Authorization with OAuth anonymous_access_token so there is no problem with  authorization part of url.
can any one please help how to retrieve other user's calendar list in the same domain by super administrator via api call?plz.. plz.. help


text:
Q: Why is my syntax highlighting not working in my build.gradle file in intellij When I create a build.gradle file and open it with IntelliJ, it does not recognize the build.gradle file and a lightbulb appears suggesting that I correct my gradle syntax. See the picture on top. I can still run the gradle file successfully in intellij.
However, when I create a Gradle Project using the New Project option in IntelliJ, I get proper syntax highlighting.
What should I do to get syntax highlighting for my build.gradle file?

A: For an IDE to recognize build.gradle files as a Gradle build script instead of simple plain Groovy file it needs to be opened(imported) as a Gradel build file. You can do it from the file's context menu:


text:
Q: How to split a dataframe into multiple dataframe in pandas dynamically based on the column count? I am still a newbie in pandas. I have an excel file which contains more than 700 columns with 600 rows. I am trying to split it into multiple dataframes so I can insert it into sql table. The reason why I am trying to split is because I am getting an error saying The statement has been terminated. (3621); [42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Cannot create a row of size 8349 which is greater than the allowable maximum row size of 8060. I want to split it by 250 columns per dataframe and also take the first row so I can join it in the sql.
Another reason why I cannot specify the dataframe range is because, different excel files might have different number of columns. Lets say the excel file contains 800 columns, but I set it as 700: 850, it gives me an error saying iloc giving 'IndexError: single positional indexer is out-of-bounds'.
If there is a way to do it dynamically by splitting it by 250 rows, it would be great. Below is my code which is working but I need to specify the range of index:
 def sqlcol(dfparam):
     dtypedict = {}
     for i,j in zip(dfparam.columns, dfparam.dtypes):
        if "object" in str(j):
            dtypedict.update({i: sqla.types.NVARCHAR(length=255)})

        if "datetime" in str(j):
            dtypedict.update({i: sqla.types.DateTime()})

        if "float" in str(j):
           dtypedict.update({i: sqla.types.Float()})

        if "int" in str(j):
           dtypedict.update({i: sqla.types.BIGINT()})

        if "decimal" in str(j):
           dtypedict.update({i: sqla.types.DECIMAL()})

    return dtypedict

def import_varchar_to_hst03(db:str,tb_name:str,df):
    n= 1

    import pandas as pd
    import sqlalchemy as sqla
    import urllib
    import pyodbc
    t=sqlcol(df1)
    a=sqlcol(df2)
    c=sqlcol(df3)
    quoted = urllib.parse.quote_plus("DRIVER={ODBC Driver 17 for SQL Server};SERVER=localhost;DATABASE="+db+";Trusted_Connection=yes;")
engine = sqla.create_engine('mssql+pyodbc:///?odbc_connect={}'.format(quoted), fast_executemany = True)
    df1.to_sql(tb_name, schema='dbo', con = engine, index=False,dtype=t,if_exists='replace')
    df2.to_sql(tb_name + ( "A" * n), schema='dbo', con = engine, index=False,dtype=a,if_exists='replace')
    df3.to_sql(tb_name + ( "B" * n), schema='dbo', con = engine, index=False,dtype=c,if_exists='replace')

import pandas as pd
import numpy as np

Ex=pd.read_excel(r'C:\Users\sriram.ramasamy\Desktop\Testsriram.xlsx',sheet_name=None)

for sh,v in Ex.items():
    df=pd.DataFrame(v)
    df1 = df.iloc[:,:255]
    df2 = df.iloc[:,np.r_[0:1,256:500]]
    df3 = df.iloc[:,np.r_[0:1,501:700]]
    import_varchar_to_hst03('InsightMaster',sh,df)

print('data imported to database')


text:
Q: Imprimir Conteúdo que Tenha Vários Canvas Estou fazendo um site no qual se tem um quadro para colorir um desenho.
Depois de muita pesquisa consegui fazer um esquema de pintar uma determinada área do desenho do canvas.
Agora eu quero fazer uma função que imprima o desenho que eu fiz.
Estou tentando fazer assim:

<canvas style="z-index: 1;"></canvas>
<canvas style="z-index: 2;"></canvas>
<canvas style="z-index: 3;"></canvas>
<canvas style="z-index: 4;"></canvas>

Meu quadro tem todos estes canvas.
Quando eu faço um risco no quadro ele cria outro canvas e assim sucessivamente.
Quero imprimir o desenho, mas dessa forma não está indo. Quando abre a tela para imprimir aparece 5 folhas vazias.
O canvas não sai na impressão ?

A: Encontrei a resposta no SOen.
    $("#printImagem").on('click', function(e){
        e.preventDefault();

        var Can = new Array();
        $('canvas').each(function(index, el){
            Can[index] = $(el)[0].toDataURL('image/png');
        });

        var windowContent = '<!DOCTYPE html>';
        windowContent += '<title>Imprimir Desenho</title>';
        windowContent += '';

        for(var x = 0; x <= Can.length - 1; x++)
            windowContent += '';

        windowContent += '';
        windowContent += '';
        var printWin = window.open('', '', width = 340, height = 260);
        printWin.document.open();
        printWin.document.write(windowContent);
        printWin.document.close();
        printWin.focus();
        printWin.print();
    });

A única coisa que me serviu foi o toDataURL. Não sabia que tinha que fazer isso para transformar o canvas numa imagem. Na verdade ela é convertida em base64 e png, conforme defini no parâmetro da função toDataURL('image/png').
Mas pode ser que tenha mais de um canvas na área de desenho.
Então eu fiz um each pesquisando cada canvas e o convertendo em base64 e o colocando na mesma posição com absolute, top e left com valor 0.
Para isso usei um array. Não sei se existe maneiras melhor de fazer. Se existir, por favor postem a lógica. Me refiro ao array e ao each.


text:
Q: Sending multiple http requests with Apache Camel I am trying to send GET HTTP requests to a paginated endpoint. The challenge is I do not know the page size beforehand therefore I have to send a request to get page number and interate till the end. I have tried Camel HTTP but I was not able to make it send dynamic requests based on first (or previous) response. I am currently testing recipientList to generate HTTP URLs by sending the first request and use the simple method as processor. Since Camel is really new for me, I am not sure if this is the best way to do like this.
I would be really grateful if someone could show some direction on this. Thank you

A: When I understood your question correct, you have to make an initial request to get the first page.
In the response you probably get the number of pages and then you want to get all remaining pages.
You could give the Camel Loop EIP a try for the remaining pages.
Pseudo-Route:
.from("whatever triggers the page retrieval")
    .setHeader("currentPage", constant(1))
    .to("http:target/page/1")
    // dont know what you want to do with the pages
    ... continue processing of the first page
    .setHeader("numberOfPages", simple("extract the number of pages somehow"))
    .loopDoWhile(simple("${header.currentPage} <= ${header.numberOfPages}"))
        .toD("http:target/page/${header.currentPage}")
        // dont know what you want to do with the pages
        ... continue processing of the current page
    .end

It really depends on what you need to do with the pages you retrieve. For example if you have to aggregate them, I am not sure if you can access an aggregated result from inside the loop.


text:
Q: Изменение фона ListView Как сделать чтобы изменялся фон элемента ListView в ListActivity в зависимости от текстового содержания этого элемента(данные приходят из MySql).
Кто какие варианты предложит?

A: Создайте свой адаптер и в зависимости от данных задавайте необходимый цвет фона для каждого элемента ListView.

A: Для Вашей цели проще создать своего посредника между адаптером и списком. Он в святых письменах называется биндер (Binder). Это мы вставляем в метод "Создать" Окно (Activity):
    // создааем адаптер
    scAdapter = new SimpleCursorAdapter(this, R.layout.list_view, null,
            new String[]{"name", "archive"}, new int[]{R.id.textView_task, R.id.LinearLayout_task}, 0);
    // указываем адаптеру свой биндер
    scAdapter.setViewBinder(new ArchiveViewBinder());
    // создааем список
    li = (ListView) findViewById(R.id.task_edit_listView);
    //настраиваем список (соединяем с адаптером)
    li.setAdapter(scAdapter);

Обратите внимание, в Адаптере стоит ссылка на курсор null по той причине, что я использую курсор-загрузчик, вошедший в душу класса окна:
public class Task_edit extends AppCompatActivity implements LoaderManager.LoaderCallbacks<Cursor>

В Вашем случае там может быть ссылка на Курсор.
Далее за фигурными скобками метода создания окна отдельным вложенным классом создаем биндер:
class ArchiveViewBinder implements SimpleCursorAdapter.ViewBinder
{
    int i;
    @Override
    public boolean setViewValue(View view, Cursor cursor, int columnIndex)
    {
        switch (view.getId())
        {
            // меняем фон линейной разметки в случае архивной задачи
            case R.id.LinearLayout_task:
                i = cursor.getInt(columnIndex);
                // если нужно поменять фон
                if (i == 1) view.setBackgroundResource(R.drawable.button_stop);
                // если нужно оставить фон по умолчанию
                else  view.setBackgroundResource(R.drawable.button_task);
                return true;
        }
        return false;
    }
}

Я меняю фон не надписи, а линейной разметки под надписью. По этому методу Вы можете менять основной фон и для любого элемента.
САМОЕ ВАЖНОЕ.
Обязательно переустанавливайте цвет фона для объектов, которым Вы меняете его, для КАЖДОГО пункта списка, даже если там не надо менять его (т.е. он должен остаться по умолчанию). Андроидный бог слишком ленив, чтобы создавать задний фон для каждого элемента списка, а берет его с ушедшего из зоны видимости пункта для вновь появившегося. Поэтому при листании списка туда-сюда, элементы закрашиваются помимо Вашей грешной воли.
Я привел Вам свой полностью рабочий код. Вам остается понять логику работы посредника (Биндера), который берет значения из указанных в Адаптере данных "фром", и кладет в "ту". Для полей, которые требуется изменить - Вы указываете Биндеру работу, а после его работы возвращаете через голубя мира "ретерн" "тру". А там, где не надо менять данные, шлете весточку "ложь", и тогда адаптер сам вставляет данные. То есть, заставляйте биндер исполнить только Вашу задачу изменения фона, а работу по умолчанию пусть выполняет сам Адаптер.


text:
Q: Location still null after user enable location usage When I try to get the last known location of the user, right after the user has agreed to the use of his own location by the app, I have found that the location is still null.
Here is my code:
@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode){
            case REQUEST_LOCATION:
                switch (resultCode){
                    case Activity.RESULT_OK: {
                        getLastKnowLocation();
                        break;
                    }
                    case Activity.RESULT_CANCELED:{
                        Toast.makeText(MyActivity.this, "Location not enabled.", Toast.LENGTH_LONG).show();
                        break;
                    }
                    default:{
                        break;
                    }
                }
        }
    }

protected void getLastKnowLocation() {
        if (checkPermission(FINE_LOCATION) == DENIDED) {
            requestPermissionLocation(OBTAINGLASTKNOWLOCATION_REQUESTCODE);
            return;
        }
        flpc.getLastLocation().addOnSuccessListener(new OnSuccessListener<Location>() {
            @Override
            public void onSuccess(final Location location) {
                if (location != null && onSuccessListener != null) onSuccessListener.onSuccess(location);
                else {
                    displayLocationSettingsRequest(onSuccessListener);
                }
            }
        });
    }

There's anyway to force the app to get the user's location?
By the way, I'm not using any map here.


text:
Q: Data Nucleus error: Class "has application-identity and no objectid-class specified yet has 0 primary key fields" I am receiving an error when my JPA code is invoked and the EntityManagerFactory is being retrieved:
Caused by: org.datanucleus.metadata.InvalidClassMetaDataException: Class com.analytics.jpa.model.Providers has application-identity and no objectid-class specified yet has 0 primary key fields. Unable to use SingleFieldIdentity.
    at org.datanucleus.metadata.AbstractClassMetaData.determineObjectIdClass(AbstractClassMetaData.java:1415)
    at org.datanucleus.metadata.ClassMetaData.populate(ClassMetaData.java:209)
    at org.datanucleus.metadata.MetaDataManager$1.run(MetaDataManager.java:2806)
    at java.security.AccessController.doPrivileged(Native Method)
    at org.datanucleus.metadata.MetaDataManager.populateAbstractClassMetaData(MetaDataManager.java:2800)
    at org.datanucleus.metadata.MetaDataManager.populateFileMetaData(MetaDataManager.java:2623)
    at org.datanucleus.metadata.MetaDataManager.initialiseFileMetaDataForUse(MetaDataManager.java:1183)
    at org.datanucleus.metadata.MetaDataManager.loadPersistenceUnit(MetaDataManager.java:1046)
    at org.datanucleus.api.jpa.JPAEntityManagerFactory.initialiseNucleusContext(JPAEntityManagerFactory.java:855)
    at org.datanucleus.api.jpa.JPAEntityManagerFactory.initialise(JPAEntityManagerFactory.java:470)
    at org.datanucleus.api.jpa.JPAEntityManagerFactory.<init>(JPAEntityManagerFactory.java:428)
    at org.datanucleus.api.jpa.PersistenceProviderImpl.createEntityManagerFactory(PersistenceProviderImpl.java:116)
    at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:152)

My model class looks like this:
@Entity
@Table(name = "PROVIDERS")
@SequenceGenerator(name = "PROVIDERS_SEQ", sequenceName = "PROVIDERS_SEQ", allocationSize = 1)
public class Providers {

     @Id
     @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "PROVIDERS_SEQ")
     @Column(name = "PROVIDER_ID")
     private Long providerId;

     @Column(name = "PROVIDER_NAME", nullable = false, length = 1000)
     private String providerName;

     @OneToOne(optional = false, orphanRemoval = true, cascade = CascadeType.ALL,
             fetch = FetchType.EAGER, mappedBy = "provider", targetEntity = Maps.class)
     private Maps map;

     // ... Getters and Setters ...
 }

The research that I've done says this error occurs if you do not have a Primary Key field specified, however, my code does.  What else am I missing?
EDIT
A few additional items from the DataNucleus.MetaData logs on DEBUG:

Class "com.analytics.jpa.model.Providers" has been specified with JPA annotations so using those.
Ignoring metadata for field com.analytics.jpa.model.Providers.providerId since we already have MetaData for the property com.analytics.jpa.model.Providers.providerId
Populating all MetaData ...
Class "com.analytics.jpa.model.Providers" : Populating Meta-Data
Class com.analytics.jpa.model.Providers has application-identity and no objectid-class specified yet has 0 primary key fields. Unable to use SingleFieldIdentity.

EDIT 2
I am using the following versions of Data Nucleus libraries:

*

*datanulceus-core: 3.2.5 4.0.0-release

*datanucleus-api-jpa: 3.2.4 4.0.0-release

*datanucleus-rdbms: 3.2.4 4.0.0-release

This is running in Jetty 7.6.7 on JDK 1.7.0_25 on Windows 7


text:
Q: How to create a temporary column + when + order by with Criteria Builder here is the sql statement I am trying to translate in jpa :
  select
        id,
        act_invalidation_id,
        last_modification_date,
        title,
        case when act_invalidation_id is null then 1 else 0 end as test
    from act order by test, last_modification_date desc

The actual translation
Root<Act> act = query.from(Act.class);

builder.selectCase()
                .when(builder.isNull(actRoot.get("actInvalidation")), 1)
                .otherwise(0).as(Integer.class);
Expression<?> actInvalidationPath = actRoot.get("actInvalidation");
Order byInvalidationOrder = builder.asc(actInvalidationPath);

Path<Date> publicationDate = actRoot.get("metadata").get("publicationDate");
Order byLastModificationDate = builder.desc(publicationDate);

query.select(act).orderBy(byInvalidationOrder, byLastModificationDate);
entityManager.createQuery(query).getResultList();

I try to create a temporary column (named test) of Integer type and orderby this column, then orderby lastmodificationdate. The content of this new column is determined by the value of actInvalidation field.
In short: How to create a temp column with integer values, then order by this temp column in jpa ?
Thank you

A: I didn't test this but it should work like this:
Root<Act> act = query.from(Act.class);

Expression<?> test = builder.selectCase()
                .when(builder.isNull(actRoot.get("actInvalidation")), 1)
                .otherwise(0).as(Integer.class);
Expression<?> actInvalidationPath = actRoot.get("actInvalidation");
Order byInvalidationOrder = builder.asc(actInvalidationPath);

Path<Date> publicationDate = actRoot.get("metadata").get("publicationDate");
Order byLastModificationDate = builder.desc(publicationDate);

Order byTest = builder.asc(test);

query.select(act).orderBy(byTest, byInvalidationOrder, byLastModificationDate);
entityManager.createQuery(query).getResultList();


text:
Q: Block serialization of database writes Is there a more elegant and reusable/general way to do the following.
I am writing this a lot, essentially on every write job as my data balloons to 100s of 1000s then 1,000,000s of records on table after table.
    .then(function(nodes){
            var job=Promise.resolve()
            var blocks=[]
            while (nodes.length){
                    blocks.push(nodes.splice(0,NODES_BLOCK_SIZE))
            }
            _.each(blocks,function(block){
                    job=job.then(function(){
                            return Node.bulkCreate(block)
                    })
            })
            return job
    })

I am about to factor that so I can pass Node.bulkCreate and NODES_BLOCK_SIZEto,
function block_op(data,func,blocksize){
    var job=Promise.resolve()
    var blocks=[]
    while (data.length){
        blocks.push(data.splice(0,blocksize))
    }
    _.each(blocks,function(block){
        job=job.then(function(){
            return func(block)
        })
      })
     return job
  }

but it still feels like 10 lines of code too much.
My real problems are not so much MySQL complaining when Sequelize fires over 64 megs at it, its the input, I cant read an arbitrarily large table into store, and thats harder than just reusing that block of code above.
I have sketched this piece of code UNTESTED,which reads blocks from one table, resolves the foreign keys in the target table and deletes the primary key, and writes. its not too bad and maybe this is the answer,but I it feels like way too common a pattern not to be better supported..
import events from "events"
test()
.then(function(){
    console.log("DONE")
})

function test(){
    blockster= new Blockster({
        read:stop_times.findAll,
        write:StopTimes.bulkCreate,
        transform:transform,
        block_size:1024*32,
        clause:{
            where:{
// read the whole table
//                trip_id:trip_id
            }
        },
        params:{
            DataSetId:DataSetId
        }
    })
    return blockster.promise
}

function transform(block){
    // resolve foreign keys on the target table
    var stop_ids=block.map(function(record){
        return record.stop_id
    })
    .filter(uniq)
    var trip_id=block.map(function(record){
        return record.trip_id
    })
    .filter(uniq)

    var StopId=[]
    var TripId=[]

    return Trips.findAll({
        where:{
            trip_id:{
                $in:trip_id
            },
            DataSetId:self.options.params.DataSetId
        }
    })
    .then(function(trips){
        trips.forEach((trip)=>{
            TripId[trip.source_id]=trip.id
        })
        return Stops.findAll({
            where:{
                stop_id:{
                    $in:stop_ids
                },
                DataSetId:self.options.params.DataSetId
            }
        })
    })
    .then(function(stops){
        stops.forEach((stop)=>{
            StopId[stop.source_id]=stop.id
        })

        block.forEach(function(record){
            record.source_id=record.id
            delete record.id
            record.StopId=StopId[record.stop_id]
            record.TripId=TripId[record.trip_id]
        })
    })
}

class Blockster extends events {
    constructor(options){
        super()
        var self=this
        this.options=options
        this.promise=new Promise(function(resolve,error){
            self.resolve=resolve
            self.error=error
        })
        this.block_number=0
        this.on('block',this.output)
        this.on('clear',this.input)
        this.on('end',this.resolve)
        this.trigger('clear')
        return this
    }

    input(){
        var self=this
        self.options.read(self.options.clause.extend(self.clause()))
        .then(function(block){
             if (!block)
                return self.trigger('end')
            self.block_number++
            self.trigger('block',block)
        })
    }

    output(block){
        var self=this
        self.options.transform(block)
        .then(function(block){
            return self.options.write(block)
        })
        .then(function(){
            self.trigger('clear')
        })
    }

    clause(){
        return {
            offset:this.block_number*this.options.block_size,
          limit:this.options.block_size
        }
    }
}

A: I wrote this.
const events =require( "events")
const spliceop =require( "./spliceop")
const _=require("underscore")
const sleep=require("sleep-promise")
const DEFAULT_BLOCK_SIZE_OUTPUT =1024*64
const DEFAULT_BLOCK_SIZE_INPUT =1024*65

class Blockster extends events {
    constructor(options){
        super()
        var self=this
        this.block_number=0
        this.options=options || {}
        this.options.block_size_input=this.options.block_size_input || DEFAULT_BLOCK_SIZE_INPUT
        this.options.block_size_transform=this.options.block_size_transform || DEFAULT_BLOCK_SIZE_INPUT
        this.options.block_size_output=this.options.block_size_output || DEFAULT_BLOCK_SIZE_OUTPUT
        this.promise=new Promise(function(resolve,error){
            self.resolve=resolve
            self.error=error
        })
        this.on('read',output.bind(this))
        this.on('clear',input.bind(this))
        this.on('end',this.resolve)
        return this
    }

    run(){
        this.emit('clear')
        return this.promise
    }

    input(){
        var self=this
        return self.options.read(_.extend(self.options.clause,self.clause()))
        .then(function(buffer){
             if (!buffer || !buffer.length)
                return self.emit('end')
            self.block_number++
            self.emit('read',buffer)
        })
    }

    output(buffer){
        var self=this
        return spliceop(buffer, self.options.transform,self.options.block_size_transform  )
        .then(function(buffer){
            if (self.options.write)
                return spliceop(buffer,self.options.write, self.options.block_size_output )
        })
        .then(()=>{
            if (self.options.sleeper)
                return sleep(self.options.sleeper)
        })
        .then(function(){
            if (self.options.read_once)
                self.emit('end')
            else
                self.emit('clear')
        })
    }

    clause(){
        return {
            offset:this.block_number*this.options.block_size_input,
            limit:this.options.block_size_input
        }
    }
}

function output(block){
    return this.output(block)
}

function input(){
    return this.input()
}

module.exports=Blockster

I do things like this with it. I have 10 of these phases, all involving potentially memory busting input streams. harnessing them all in this publication model has been very effective but I stil feel that I should be leveraging something other than events and promises.
class Normalizer {
    Normalizer(){
        var barg={

            read:this.sequelize.models.Stop.findAll.bind(this.sequelize.models.Stop),
            write:resolve_writer.bind(this),
            transform:resolve_transform.bind(this),
            clause:{
                where:{
                    $or:[
                        {
                            normalized:null
                        },
                        {
                            normalized:0
                        }
                    ]
                }
            },
            block_size_input:OVERPASS_BLOCK_SIZE
        }
        if (this.options.source)
            barg.clause.where.DataSetId=this.DataSetId

        var blockster= new Blockster(barg)
        return blockster.run()
    }
}
function resolve_transform(block){
   // do stuff
   return block // or other array of stuff for wtrite to handle
}
function resolve_write(block){
   // usually update stuff, if just blockCreate we can pass that to blockster
}


text:
Q: Error 10061: No connection could be made because the target machine actively refused it I have recently installed a (cross platform) client server application consisting of a web server backend and a thick (dumb) desktop client.
I have been able to connect to the server and run the Ubuntu desktop client successfully, however, when a colleague installed the client application on their Windows 10 laptop, the got the following error:

[Error 10061]: No connection could be made because the target machine
  actively refused it

I have SSH installed and running on the Linux server.
This is what I've done so far, to try and solve the problem:
1. run ps aux | grep ssh to make sure SSH is running on server:
root      4359  0.0  0.1  65520  6304 ?        Ss   Sep02   0:02 /usr/sbin/sshd -D
root     19148  0.0  0.1  95400  6704 ?        Ss   08:23   0:00 sshd: morpheous [priv]
morpheo+ 19166  0.0  0.0  95400  3380 ?        S    08:23   0:00 sshd: morpheous@pts/0

2. run netstat -l to make sure port 8000 is being listened to:
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State
tcp        0      0 *:ssh                   *:*                     LISTEN
tcp6       0      0 [::]:ssh                [::]:*                  LISTEN
tcp6       0      0 [::]:8000               [::]:*                  LISTEN
Active UNIX domain sockets (only servers)
Proto RefCnt Flags       Type       State         I-Node   Path
unix  2      [ ACC ]     STREAM     LISTENING     16673    /run/user/1000/systemd/private
unix  2      [ ACC ]     STREAM     LISTENING     11592    /var/run/dbus/system_bus_socket
unix  2      [ ACC ]     STREAM     LISTENING     11597    /var/run/docker.sock
unix  2      [ ACC ]     STREAM     LISTENING     11601    /run/uuidd/request
unix  2      [ ACC ]     STREAM     LISTENING     15199    /run/docker/libnetwork/c691c7be0884cd7e163479e2dca860cec5877a0dc01ed98a50e22d236d70b7e0.sock
unix  2      [ ACC ]     STREAM     LISTENING     9616     /run/systemd/private
unix  2      [ ACC ]     SEQPACKET  LISTENING     9623     /run/udev/control
unix  2      [ ACC ]     STREAM     LISTENING     9631     /run/systemd/fsck.progress
unix  2      [ ACC ]     STREAM     LISTENING     9644     /run/systemd/journal/stdout
unix  2      [ ACC ]     STREAM     LISTENING     15072    /var/run/docker/libcontainerd/docker-containerd.sock

3. Used putty from the Windows machine, to try to connect to the server. However, when presented with the Linux CLI and prompted to login, when I enter valid credentials, I get the error message: Access denied
4. I obtained the IP address of the windows machine, and then checked /var/log/auth.log on the server machine to see if the IP address of the windows machine was in there (to see if the machine had been refused connection as reported by the Tryton client app). THERE WAS NO RECORD OF THE IP ADDRESS IN THE LOG FILE!
Can someone help with the required steps needed to diagnose and fix this problem?
[[UPDATE]]
It turns out that my friend was using the wrong IP address on the Windows client!. However, as I have wasted an entire day trying to get to the bottom of this, my question is this:
ASSUMING THE CLIENT IS ATTEMPTING TO CONNECT TO THE CORRECT MACHINE (i.e. USING CORRECT IP ADDRESS), is there a way I can (on the server) view/record all HTTP and HTTPS requests coming to the server machine?
How can I do that?


text:
Q: Time difference between two values based on other column value in SQL I have some problems with counting a time passed between records in SQL.
Or as in my case, how long the item was not active.
Sample of data:
Item  Not_Active Active Created
A     0          1      2017-01-01 10:03:15
A     1          0      2017-01-01 12:05:55
A     0          1      2017-01-01 13:05:55
A     1          0      2017-02-03 12:05:55
A     0          1      2017-02-05 13:05:55
B     1          0      2017-01-10 04:05:20
B     0          1      2017-01-10 07:05:20

So the main goal is to sum all time between deactivation and activation for each item. Answer should be in seconds. What kind of query should I use?
Challenge two: to count not active time between certain dates. For example, for item A just between 2017-02-01 and 2017-02-28.
Challenge three: to count how much not active time was during the night, lets say between 0 am till 5 am.
I have no idea where should I start. Any suggestions?

A: I create a little sample how you can made this.
    create table #table (item char, not_active int, active int, created datetime)

    insert into #table values('A', 0, 1, '2017-01-01 10:03:15')
    insert into #table values('A', 1, 0, '2017-01-01 12:05:55')
    insert into #table values('A', 0, 1, '2017-01-01 13:05:55')
    insert into #table values('A', 1, 0, '2017-02-03 12:05:55')
    insert into #table values('A', 0, 1, '2017-02-05 13:05:55')
    insert into #table values('B', 1, 0, '2017-01-10 04:05:20')
    insert into #table values('B', 0, 1, '2017-01-10 07:05:20')

    declare @very_hard table (item char,
                          not_active int,
                          active int,
                          created datetime,
                          before datetime,
                          afters datetime,
                          days_diff_stoped int,
                          hourstoped int )

declare very_hard_challenge cursor Local
for

select
item,
active,
not_active,
created,
LAG(created,1,0)over(partition by item order by created) as before,
LEAD(created,1,0)over(partition by item order by created) as afters,
datediff(day,LAG(created,1,0)over(partition by item order by created),created) as days_diff_stoped
from #table
--where item = 'B'
order by created asc

declare @item char,
        @not_active int,
        @active int,
        @created datetime,
        @days_diff_stoped int,
        @before datetime,
        @afters datetime

open very_hard_challenge

fetch next from very_hard_challenge into @item, @not_active, @active, @created, @before, @afters, @days_diff_stoped

WHILE @@FETCH_STATUS=0
    begin
        declare @datebegin datetime = @before
        declare @hourstoped int = 0
        if @datebegin != '1900-01-01 00:00:00.000'
        begin
            while @datebegin < convert(datetime,@created)
                begin
                        if datepart(hour,@datebegin) in(0,1,2,3,4,5)
                            begin
                                set @hourstoped = @hourstoped+1
                            end

                            set @datebegin = DATEADD(hour,1,@datebegin)
                end
        end

        insert into @very_hard values (@item, @not_active, @active, @created, @before, @afters, @days_diff_stoped, @hourstoped)

        fetch next from very_hard_challenge into @item, @not_active, @active, @created, @before, @afters, @days_diff_stoped
    end

close very_hard_challenge
deallocate very_hard_challenge

select * from @very_hard

This code has simple, but you can make better. Anyone question about this code please tell me and I will do make a possible for answer.


text: Q: Looking for Proof of the Order of a quandle cohomology group for an n-fold dihedral Does anyone know where the proof that states that the order of a quandle cohomology group for an n-fold dihedral quandle is n is located? I have been told it can be found in one of Niebrzydowski-Przytycki's or Mochizuki's articles but I have yet to find the specific proof.


text:
Q: Need help in understanding flip flop I have problem with understanding the feedback part in flip flop. Consider a flip-flop circuit containing just two NAND gates as shown in the picture below:

Problem 1) Let A & S' be the inputs of 1st NAND gate and B & R' be the inputs of the 2nd NAND gate. What will be the values of A & B when both S' & R' are 0? (To find output we need to know the inputs, but here the inputs are depended upon the outputs of each other which makes me confused!)
Problem 2) If A & S' are 0, Q will become 1. Since Q=B, B will also become 1. Now let R'=0, then  Q' will become 1. Since Q'=A, A will change to 1 from 0. Is this analysis true?

A: No, your analysis is NOT true. Even when Q' → A goes high, since the S' input is still low, the Q output remains high.
And despite the comment by Ignacio Vazquez-Abrams, the both-inputs-low condition (and both outputs high) is NOT an "unstable state" in itself, but the state that the circuit ends up in depends on the order in which the inputs go high. If they go high "simultaneously" (not really possible in practice), it's impossible to predict the output state, and the outputs may even become metastable for a period of time.

A: Problem 1)
Basically start by saying S' is 0, this means that Q will be 1 (as the NAND gate is high when Either A or S' is low), therefore B will be 1. As B is one the inputs to the second gate are 1 and 0 therefore Q' is 1. So A will be 1. The inputs to the first gate will be 1 and 0 so Q will still be 1.
Problem 2)
A will change from a 0 to a 1 but Q will still be high as S' is still 0


text: Q: How to increase the font size of automatic created window I am using MMA 12.3.0 on Ubuntu 18.04. I changed a new screen and the font of the toolbar became very small compared to other applications and managed to solve that. But, the font in the automatic created window is still very small compared to notebook font and toolbar font, see red arrow in the below picture. How can I increase this font  size?


text:
Q: Parallel transform of a vector by Lie derivative I am new to differential geometry and I learn by myself. It seems that we need something extra called a connection to parallel transport a vector along a curve.
But, suppose we have a vector field $X $, the vector field induces some flow $\phi_t $ on the manifold, which in turn can be viewed as a diffeomorphism of the manifold. Therefore, we can push forward the vector! Can we consider this as a parallel transport of the initial vector?
If not, what is the drawback?


text:
Q: Microsoft Excel 2010: using array functions to generate boxplot data I have a table with four columns.  Three of which are settings for the trials, and the fourth is the value generated by the experiment.  Each row represents a trial, and multiple trials for each experiment configuration was performed.  I want to build a table for each of configuration that lists the five values (min, 25th percentile, median, 75th percentile, and max) for those trials.
I've built a separate table where each unique experiment configuration is listed once.  There are extra columns with the percentile values as the column headers.  I have the following formula set up to try to calculate the five values:
{=PERCENTILE.INC(IF(AND($B$2:$B$35341=$G2,$C$2:$C$35341=$H2,$D$2:$D$35341=$I2),$E$2:$E$35341),J$1)}

This is intended to compare the row's three settings to ensure that only the trials with that row's configuration return the readings for percentile evaluation.
However, this formula only returns zeroes.
How can I generate the data I need?

A: You generally can't use AND's or OR's in array functions as they don't return an array, just a single TRUE or FALSE.  This multiplies the conditions together and returns blanks for the array triplets that don't resolve to TRUE.  PERCENTILE ignores the blanks and solves for the remaining elements:
=PERCENTILE.INC(IF(($B$2:$B$35=G2)*($C$2:$C$35=H2)*($D$2:$D$35=I2)=0,"",
($B$2:$B$35=G2)*($C$2:$C$35=H2)*($D$2:$D$35=I2)*($E$2:$E$35)),J$1)


text:
Q: How does Ionic/Cordova generate hash key? I'm working on adding Facebook API integration with ionic/Cordova and am trying to find the debug hash key that is generated for my app when I do:
ionic build android

I know that it generates a new .keystore file at /userhomedir/.android/debug.keystore. But what does it set as the alias and password? And how can I retrieve this hash key after Cordova has created it for my app. I don't see the hash key being printed anywhere during the build process.
I need the generated hash key to give to Facebook API to use their sign on SDK

A: It seems Cordova use ~/android/debug.keystore with the password android
To get it :
keytool -exportcert -alias androiddebugkey -keystore ~/.android/debug.keystore | openssl sha1 -binary | openssl base64

With password : android

A: One answer that worked for me is this one:

*

*Copy the apkname.apk file you want to know the hash of to the 'Java\jdk1.7.0_79\bin' folder

*Run this command keytool -list -printcert -jarfile apkname.apk

*Copy the SHA1 value and convert it using this site

*Use the converted Keyhash value (ex. zaHqo1xcaPv6CmvlWnJk3SaNRIQ=)

A: keytool -genkey -v -keystore my-release-key.jks -keyalg RSA -keysize 2048 -validity 10000 -alias my-alias


text:
Q: Easy Digital Download Pagination 404 error - Wordpress Im facing issues with wordpress digital download website for pagination on homepage.
Below pages doesn't seem to work with pagination when I go navigate through pagination, it shows 404 page.
[www.domain.com/page/2/][1]
[www.domain.com/page/3/][1]
But when I edit the links e.g below it works:
[www.domain.com/downloads/page/2/][1]
[www.domain.com/downloads/page/3/][1]
Why it is happening, same homepage code works fine with archives/categories/tags but not for homepage, I have been searching for this from yesterday and I couldn't find any solution:
Below My code for homepage
Your help is much appreciated
<?php
$store_page_setting = (is_front_page() && is_page_template('edd-store-front.php') ? 'page' : 'paged' );
$current_page = get_query_var( $store_page_setting );
$per_page = intval( get_theme_mod( 'bwpy_store_front_count', 3 ) );
$offset = $current_page > 0 ? $per_page * ( $current_page-1 ) : 0;
$product_args = array(
    'post_type'     => 'download',
    'posts_per_page'    => $per_page,
    'offset'        => $offset
);
$products = new WP_Query( $product_args );

if ( $products->have_posts() ) : ?>
<?php
    while ( $products->have_posts() ) : $products->the_post();
        //

endwhile;
?>

    <?php
        $big = 999999999;
        echo paginate_links( array(
            'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),
            'format' => '?paged=%#%',
            'current' => max( 1, $current_page ),
            'total' => $products->max_num_pages
        ) );
    ?>

<?php else : ?>

<?php endif; ?>


text:
Q: how to customize react-toastify I need to customize react-toastify.
I tried to follow the advice from the documentation and change the styles in the .scss file. unfortunately this didn't work. tell me what am I doing wrong?
I want notifications to look like on the picture how I want it to look

A: You can use this method in App.js :
   <ToastContainer
       position="bottom-right"
       autoClose={8000}
       pauseOnHover={true}
       draggable={true}
       theme="dark"
    />

here the toast appears on the bottom-right side, it is automatically closed after 8 seconds and its background theme is dark.

A: Add a style attribute like this:
     <ToastContainer
        position="bottom-right"
        autoClose={8000}
        pauseOnHover={true}
        draggable={true}
        theme="dark"
        style={{width: "100px"}}
      />


text:
Q: Independance of Sigma Algebras A book I'm reading gives the following defintion for independance.

Write $J \subset_f I$ if $J$ is a finite subset of $I$. A family $(S_i)_{i\in I}$ of $\sigma$-sub-algebras of $A$ is called independent, if for every $J \subset_f I$ and every choice $A_j \in S_j$ we have $P[\cap_{j\in J} A_j] = \prod_{j\in J} P[A_j]$. A family of sets $(A_i)_{i\in I}$ is called independent, if the $\sigma$-algebras $S_j = \{\emptyset, A_j, A^C_j, \Omega\}$ are independent.

Then they provide the following example:

Let $\Omega = \{1,2,3,4\}$ and consider the two $\sigma$-algebras $A=\{\emptyset,\{1,3\},\{2,4\},\Omega\}$ and $B=\{\emptyset,\{1,2\},\{3,4\},\Omega\}$. $A$ and $B$ are independent.

I don't see how the sigma algebras are independent. In particular, how are they making this assertion without a probability measure on $\Omega$. Do they mean that they are independent for any choice of probability measure? If so, how do I see that?
thanks!

A: My guess would be that the measure is defined as $\mathbb{P}(1)=\frac{1}{4}$ and similarly for $2,3,4$, i.e. a uniform distribution. Then independence is an easy check - e.g.
$$\mathbb{P}(\{1,2\}\bigcap\{1,3\})=\mathbb{P}(\{1\})=\frac{1}{4}=\mathbb{P}(\{1,2\})\mathbb{P}(\{1,3\})$$

A: I guess it should say (maybe it does somewhere) that $P$ is defined in such a way that $P({n})=\frac14$ for $n\in\{1,2,3,4\}$ (or put in other way $P(A)=\frac{\#A}4$).
So you have to prove that for every pair $(E_A,E_B)\in A\times B$ (*), you have
$$P(E_A\cap E_B)=P(E_A)\cdot P(E_B).$$
If one of $E_A$ and $E_B$ or both are empty sets, then both sides equal $0$. If $E_A=\Omega$ then both equal $P(E_B)$ and viceversa.
Finally, in other case, you have $\#E_A=\#E_B=2$ and $\#(E_A\cap E_B)=1$, so the left side equals $\frac14$ and the right side equals $\frac12\cdot\frac12=\frac14$.
If you choose a $P$ such that, for instance, $p_1=\frac12$, $p_2=\frac14$ and $p_3=p_4=\frac18$ (where $p_i=P(\{i\})$, $1\le i \le 4$, then it is easy to see that, for instance $P(\{1,3\}\cap\{1,2\})\neq P(\{1,3\})\cdot P(\{1,2\})$.

(*) Going back to the definition, this would actually be the case $J=I$, and here $\#I=2$. Technically there are three other cases which are all fairly trivial: two of them correspond to $\#J=1$ —that is, taking only events in $A$ and taking only events in $B$, which makes the equality evident since it is of the form $P(E)=P(E)$— and the other one is for $J=\emptyset$ which involves an empty intersection and an empty product which conventionally are interpreted as $\Omega$ and $1$, respectively. Of course, you never need to check these trivial cases, but it is interesting to see that they are somehow included in the definition.


text:
Q: How to inactive other dropdown while I am clicking another one [![

  Dashboard

  <button class="dropdown-btn" style="width: 100%;">Admin

          </button>

    Admin Profile
    Change Password

  <button class="dropdown-btn" style="width: 100%;">Doctors

          </button>

    Doctors List
    Doctors Appointments
    Doctors Requests
    Add a Doctor

  <button class="dropdown-btn" style="width: 100%;">Patients

          </button>

    Patient List
    Patients Appointments
    Patient Requests
    Add a Patient

]1]1Here I wanted to inactive toggle like if I click on doctors and then click to admin, doctor's toggle will be converted to inactive automatically . I have no idea how to do this.

A: *

*Use jQuery to listen dropdown-btn event. Activate all buttons and disable the clicked button.

Like this code:

$('.dropdown-btn').on('click', function(){
        $(".dropdown-btn").attr("disabled", false);
        $(this).attr("disabled", true);
});

  Dashboard

  <button class="dropdown-btn" style="width: 100%;">Admin

          </button>

    Admin Profile
    Change Password

  <button class="dropdown-btn" style="width: 100%;">Doctors

          </button>

    Doctors List
    Doctors Appointments
    Doctors Requests
    Add a Doctor

  <button class="dropdown-btn" style="width: 100%;">Patients

          </button>

    Patient List
    Patients Appointments
    Patient Requests
    Add a Patient


text:
Q: onclick event in Slim not working - converting ' to ' I'm trying to set up a Google Analytics goal - an event to be recorded whenever someone clicks on a certain link on my site. I'm using the Slim templating language and Rails.
The Javascript snippet I need to insert is:
onClick="_gaq.push(['_trackEvent', 'Category', 'Action']);"

The code I have is:
= link_to "A Link", link_path, :title => "A Link", :onclick => "_gaq.push(['_trackEvent', 'Category', 'Action']);"

But clicks on this aren't registering (looking at the console), and the view-source shows this:
onclick="_gaq.push(['_trackEvent', 'Category', 'Action']);"

Somehow the ' is getting converted. How can I stop this? I've tried using a pipe | but I don't think you can nest on link_tos.
Thanks for any help! I've searched Google and StackOverflow and couldn't find anything on my own. This is frustrating and I know the fix will be simple!

A: Use html_safe
= link_to "A Link", link_path, :title => "A Link", :onclick => "_gaq.push(['_trackEvent', 'Category', 'Action']);".html_safe


text:
Q: two digit year as primary key in sql server I have a table with these columns:
ID int,
d date

Now what I need is to define the primary key in such a way that ID would be unique for each year; meaning that there can not be two same IDs in 2004, but it is possible to have two same IDs in two different years.
Like:
insert into myTable values(1, '1-1-2004'), (1, '1-1-2005')

but not like:
insert into myTable values(1, '3-1-2005'), (1, '1-1-2005')

I tried this:
primary key(ID, datepart(YY, d))

but I get syntax error.

A: One way of doing this, if you can alter the table structure, is to add a persisted computed column for the year part, and then add a primary key for (id, computer_col), like this:
CREATE TABLE myTable (
    id INT NOT NULL,
    d DATE NOT NULL,
    y AS DATEPART(YEAR,d) PERSISTED NOT NULL,
    PRIMARY KEY(id,y)
    )

I'm not saying this is a good solution in any way, but it should work. Using a trigger on insert or a check constraint might be better.
Using your test data this will allow the first insert statement, but disallow the second as it violates the primary key constraint.


text:
Q: Query with FK=PK condition but showing rows without FK too I need help writting a query that has a condition like this in the WHERE clause
Select a.field, b.field
From Table1 a, Table2 b
Where a.FK = b.PK

But I also want the select to return rows that has no FK reference in the field a.FK, in this case the b.field should return some empty or null value.
Thanks

A: User Left Outer JOIN. Try the following:
SELECT a.field, b.field
FROM Table1 a LEFT JOIN Table2 b
ON a.FK = b.PK

This is a good read how LEFT JOIN works

A: Use Left Join. This should give you what you are looking for.
Select a.field, b.field
From Table1 a
LEFT JOIN Table2 b on a.FK = b.PK


text:
Q: Pass parameter to select dataframe spark I want to pass the column to be selected in a dataframe as a parameter as I change each time for the moment I have done this. It actually works
object PCA extends App{
val spark = SparkSession.builder.master("local").appName("my-spark-app").getOrCreate()
 val strPath="C:/Users/mhattabi/Desktop/testBis2.txt"
val intial_Data=spark.read.option("header",true).csv(strPath)
val inputData=intial_Data.select("col1","col2").show
}

I want to pass a parameter to the select so I did this
     object PCA extends App{
            val spark = SparkSession.builder.master("local").appName("my-spark-app").getOrCreate()
             val strPath="C:/Users/mhattabi/Desktop/testBis2.txt"
             val columns="col1","col2"
            val intial_Data=spark.read.option("header",true).csv(strPath)
           val listcolu=intial_Data.columns
foreach(string s in listcolu)
{create the list insert the column name
}
        }

It hasn't even accepted what it should do. The aim is to pass it each time as parameter.

A: You can do something like this.
import org.apache.spark.sql.functions.col
val colsList = List(col("col1"),col("col2"))
intial_Data.select(colsList:_*).show


text:
Q: tinymce stand alone version suddenly not working A while back I downloaded the tinymce Developer Package 4.6.6 from https://www.tinymce.com/download/.  I installed it, configured it and it worked like a dream (with a bit of tinkering).  All of a sudden, it has stopped working. I can still enter text into the textarea, but I am unable to format it AT ALL.  When I submit the Form and dump the content of the textarea, there is nothing there.  I didn't change any code, so I am wondering if I have breached some sort of Licence limit. Has anyone got any ideas?  The Code is dead simple:
JS:
<script src="tinymce/js/tinymce/tinymce.min.js"></script>
<script>
tinymce.init({
selector:'textarea.theme1',
branding: false,
statusbar: false,
menubar : false,
height: 500,
plugins: 'table,lists,fullscreen,textcolor',
table_default_styles: { width: '90%' },
toolbar: 'table,lists,fullscreen,textcolor',
toolbar1: 'undo redo | fontselect fontsizeselect',
toolbar2: 'bold italic underline forecolor',
toolbar3: 'alignleft alignright aligncenter indent outdent bullist numlist',
toolbar4: 'table | fullscreen '
});
</script>

HTML:
<textarea class="theme1" name="message"></textarea>

A: Sorry, forgot to add:
if I replace the local js file:
<script src="tinymce/js/tinymce/tinymce.min.js"></script>

with the Cloud js file:
<script src="https://cloud.tinymce.com/stable/tinymce.min.js"></script>

it works again.
Go figure.


text:
Q: When set proxy, facebook opens slowly When I use proxy, my, several web pages (etc. facebook) loads very slowly. This is script:

import random import time

 import os import sys from selenium import webdriver

 chromedriver = "chromedriver.exe"

 os.environ["webdriver.chrome.driver"] = chromedriver

 from selenium.webdriver.common.by import By from
 selenium.webdriver.common.keys import Keys from
 selenium.webdriver.support.ui import Select from
 selenium.common.exceptions import NoSuchElementException from
 selenium.common.exceptions import NoAlertPresentException import
 unittest from time import gmtime, strftime from datetime import
 datetime from random import randint

 PROXY = "114.77.67.32:22" # IP:PORT or HOST:PORT

 chrome_options = webdriver.ChromeOptions()
 chrome_options.add_argument('--proxy-server=http://%s' % PROXY)

 driver = webdriver.Chrome(chrome_options=chrome_options)
 driver.get("http://web.facebook.com")

Is it good method to visit pages with another IP ?

A: Are you using -trustAllSSLCertificates parameter when launching Webdriver? It helped with this resolved problem.
Otherwise you should try some other proxy or connect to launch tests from another host, there's no other simple way around this.


text:
Q: Kattis Issue, Texture Analysis. Java I'm having issues with debugging the texture analysis on Kattis. I'm able to finish every test case i can imagine but yet the last test case fails.
Does anyone have any idea what might be causing the last test case to fail?
Link to the kattis problem
public static void main(String[] args) throws Exception {
    BufferedReader sc = new BufferedReader(new InputStreamReader(System.in));
    BufferedWriter dc = new BufferedWriter(new OutputStreamWriter(System.out));

    int numOfLines = 1;

    for (;;) {
        String inputLine = sc.readLine();
        if (inputLine.equals("END"))
            break;
        else if (!inputLine.contains(".")) {
            dc.write(numOfLines++ + " EVEN\n");
        } else {
            //Next two lines creates an array out of the characters in a single line
            String[] tempArray = inputLine.split("");
            ArrayList<String> charArray = new ArrayList<String>(Arrays.asList(tempArray));
            //Next block of code finds all elements where an asterix has been found and puts them in the allIndexes array
            //If the code is even, the elements will for example be on 0, 2, 4, 6
            //If the code is uneven, the elements will for example be on 0, 1, 5, 8
            String str = "*";
            List<Integer> allIndexes =
                    IntStream.range(0, charArray.size()).boxed()
                            .filter(j -> charArray.get(j).equals(str))
                            .collect(Collectors.toList());

            ArrayList<Integer> duplicateList = new ArrayList<>();
            //For-loop, is used to normalize numbers
            //An even array of 0,2,4,6 turns into 2,2,2,2
            //An uneven array of 0,2,6,8 turns into 2,4,2,2
            //This means we can easily see where the uneven number is
            for (int j = 0; j < allIndexes.size(); j++) {
                if(j < allIndexes.size() - 1)
                    duplicateList.add(allIndexes.get(j + 1) - allIndexes.get(j));
            }
            Boolean isArrayUneven = false;
            //Here we check for uneven numbers in the array
            //If one is found then isArrayUneven turns true.
            for (int i = 1; i < duplicateList.size();i++) {
                if (duplicateList.get(0) != duplicateList.get(i)) {
                    isArrayUneven = true;
                }
            }
            if (isArrayUneven ==true ) {
                dc.write(numOfLines++ + " NOT EVEN" + "\n");
            }
            else{
                dc.write(numOfLines++ + " EVEN" + "\n");
            }
        }
    }
    dc.close();
    sc.close();
}

A: Although the solution seems a bit overengineered to me, I coded a working solution which was accepted by Kattis, then compared it against yours with a script on a variety of tests and couldn't find any differences. There's a slight chance it's a Java version behavior or platform issue of some sort, but I can't imagine what. Here's my solution and testing script in case it helps:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

public class TextureAnalysis {
    public static void main(String[] args) throws java.io.IOException {
        var sc = new BufferedReader(new InputStreamReader(System.in));
        var dc = new BufferedWriter(new OutputStreamWriter(System.out));

        for (int i = 1;; i++) {
            String s = sc.readLine();

            if (s.equals("END")) {
                break;
            }

            var a = s.split("\\*", -1);
            boolean allSameLength = true;

            for (int j = 2; j < a.length - 1; j++) {
                if (a[j].length() != a[1].length()) {
                    allSameLength = false;
                    break;
                }
            }

            dc.write(i + (allSameLength ? " EVEN\n" : " NOT EVEN\n"));
        }

        dc.close();
        sc.close();
    }
}

Testing script:
import random
import sys
from subprocess import Popen, PIPE

def start(cmd):
    return Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE)

def read(process):
    return process.stdout.read().decode("utf-8")

def write(process, s):
    process.stdin.write(f"{s}\n".encode("utf-8"))
    process.stdin.flush()

def terminate(process):
    process.stdin.close()
    process.terminate()
    process.wait(timeout=0.2)

def main():
    # even tests
    for i in range(100):
        good = start(["java", "TextureAnalysis"])
        bad = start(["java", "TextureAnalysisBad"])

        for j in range(100):
            chunk = "*".join(["." * i for _ in range(j)])
            test = "*" + chunk + "*"
            write(good, test)
            write(bad, test)

        write(good, "END")
        write(bad, "END")
        g = read(good)
        b = read(bad)

        if g != b:
            print("FAIL:", test)
            sys.exit(0)

    # random tests, mostly uneven
    for _ in range(1000000):
        good = start(["java", "TextureAnalysis"])
        bad = start(["java", "TextureAnalysisBad"])

        for j in range(100):
            chunk = "".join(
                [random.choice(".*") for _ in range(random.randint(10, 150))]
            )
            test = "*" + chunk + "*"
            write(good, test)
            write(bad, test)

        write(good, "END")
        write(bad, "END")
        g = read(good)
        b = read(bad)

        if g != b:
            print("FAIL:", test)
            sys.exit(0)

if __name__ == "__main__":
    main()

(credit to this post for subprocess code)


text:
Q: Issue to getting flickr contact list I want to get flickr friends list on my iPhone app. I read documentation and I found the URL for it. But in this URL I do not understand how to pass api_sig tht name parameter. The URL is given below. Can any body help me?
http://api.flickr.com/services/rest/?method=flickr.contacts.getList&api_key=b201806ce09c404a786288dbd1840b2b&format=json&nojsoncallback=1&auth_token=72157629827571110-752bbff651a7654c&api_sig=a8c18f235e27220db724ac97d3216b1a

A: Flickr has updated its authentication protocols recently, so perhaps the information linked by @Nikunj R. Jadav (dated 28 July 2009) is in need of updating.  Flickr's instructions on how to sign an API call read:

Currently, Flickr only supports HMAC-SHA1 signature encryption.
First, you must create a base string from your request. The base string is constructed by concatenating the HTTP verb, the request URL, and all request parameters sorted by name, using lexicograhpical byte value ordering, separated by an '&'.
Use the base string as the text and the key is the concatenated values of the Consumer Secret and Token Secret, separated by an '&'.

You then hash the base string and pass it as the &api_sign query string parameter.
Beyond just signing the API call, you will need to authenticate.  The documentation for the flickr.contacts.getList API says that it requires authentication with OAuth.  OAuth authentication (also documented) is a little tricky; it helps to have a library to manage some of the work for you.  You can find a directory of libraries for OAuth support in Objective-C at the OAuth site.


text:
Q: MonoGame Problem with renderize Texture2D on camera movement First, sorry for my bad English, English is not my native language.
I have a problem when I draw a Texture2D in screen. When I move a Texture in screen,
colors in border of the texture flickers. This is my code:
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using SharpDX.Direct2D1.Effects;
using System;
using System.Collections.Generic;

namespace PixelTest
{
    public class Drawable
    {
        public Texture2D Image;
        public Point Position;
        public Point Size;
        public Rectangle Source;
    }

    public class MainGame : Game
    {
        //PRIVATE READ-ONLY VARIABLES
        private readonly GraphicsDeviceManager _graphics;
        private readonly List<Drawable> _sprites;

        //VARIABLES
        private Texture2D _screen;
        private Texture2D _tiles;
        private SpriteBatch _spriteBatch;
        private Point _camera;
        private Point _scale;
        private bool _byRect;
        private KeyboardState _previousKeyState;
        private BlendState _state;
        private RasterizerState _rState;

        //CONSTRUCTOR
        public MainGame()
        {
            _graphics = new GraphicsDeviceManager(this);
            _sprites = new List<Drawable>();

            _tiles = null;
            _spriteBatch = null;
            _camera = Point.Zero;
            _scale = new Point(1, 1);

            Content.RootDirectory = "Content";
            IsMouseVisible = true;
            IsFixedTimeStep = true;
            //_graphics.PreferHalfPixelOffset = true;
            _graphics.PreferMultiSampling= true;
            //_graphics.SynchronizeWithVerticalRetrace = false;
            _state = new BlendState()
            {
                AlphaBlendFunction = BlendFunction.Add,
                AlphaSourceBlend = Microsoft.Xna.Framework.Graphics.Blend.Zero,
                AlphaDestinationBlend = Microsoft.Xna.Framework.Graphics.Blend.Zero,

                ColorBlendFunction= BlendFunction.Add,
                ColorDestinationBlend = Microsoft.Xna.Framework.Graphics.Blend.Zero,
                ColorSourceBlend = Microsoft.Xna.Framework.Graphics.Blend.One,

            };
            _rState = new RasterizerState()
            {
                MultiSampleAntiAlias = false
            };
        }

        protected override void Initialize()
        {
            base.Initialize();

            _sprites.Add(new Drawable
            {
                Image = _tiles,
                Position = new Point(32, 64),
                Size = new Point(8, 8),
                Source = new Rectangle(0, 0, 8, 8)
            });
        }

        protected override void LoadContent()
        {
            _spriteBatch = new SpriteBatch(GraphicsDevice);

            _tiles = Content.Load<Texture2D>("i001_tiles");
            _screen = new Texture2D(GraphicsDevice, _graphics.PreferredBackBufferWidth, _graphics.PreferredBackBufferHeight);

            var colors = new Color[_graphics.PreferredBackBufferWidth * _graphics.PreferredBackBufferHeight];

            for (var i = 0; i < _graphics.PreferredBackBufferWidth * _graphics.PreferredBackBufferHeight; i++)
                colors[i] = Color.Black;

            _screen.SetData(colors);
        }

        protected override void UnloadContent()
        {
            base.UnloadContent();

            _tiles.Dispose();
            _screen.Dispose();
        }

        protected override void Update(GameTime gameTime)
        {
            base.Update(gameTime);

            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
                Exit();

            var sKey = Keyboard.GetState();
            var translateUnit = Point.Zero;
            var scaleUnit = 0;

            if (sKey.IsKeyDown(Keys.A))
                translateUnit.X = -1;
            else if (sKey.IsKeyDown(Keys.D))
                translateUnit.X = 1;
            else
                translateUnit.X = 0;

            if (sKey.IsKeyDown(Keys.W))
                translateUnit.Y = -1;
            else if (sKey.IsKeyDown(Keys.S))
                translateUnit.Y = 1;
            else
                translateUnit.Y = 0;

            if (sKey.IsKeyDown(Keys.F))
                scaleUnit = -1;
            else if (sKey.IsKeyDown(Keys.G))
                scaleUnit = 1;
            else
                scaleUnit = 0;

            if (sKey.IsKeyDown(Keys.U) && _previousKeyState.IsKeyUp(Keys.U))
                _byRect = !_byRect;

            var speed = translateUnit;// * 1;

            _camera += speed;// RoundVec(speed);
            _scale = new Point(4, 4);
            _previousKeyState = sKey;
        }

        protected override void Draw(GameTime gameTime)
        {
            base.Draw(gameTime);
            GraphicsDevice.Clear(Color.Blue);

            _spriteBatch.Begin(SpriteSortMode.Deferred, _state, SamplerState.PointClamp, null, _rState, null, null);
            //_spriteBatch.Draw(_screen, Vector2.Zero, Color.White);

            foreach (var item in _sprites)
            {
                if (true)
                {
                    var pos = item.Position;
                    var size = item.Size;

                    pos += _camera;
                    pos *= _scale;
                    size *= _scale;

                    var rect = new Rectangle(
                        (int)pos.X,
                        (int)pos.Y,
                        (int)size.X,
                        (int)size.Y);

                    _spriteBatch.Draw(
                        item.Image,
                        rect,
                        item.Source,
                        Color.White,
                        0F,
                        Vector2.Zero,
                        SpriteEffects.None,
                        0F);
                }
                else
                {
                    var pos = item.Position;

                    //pos = RoundVec(pos * _scale) / _scale;
                    pos += _camera;
                    pos *= _scale;

                    _spriteBatch.Draw(
                        item.Image,
                        pos.ToVector2(),
                        item.Source,
                        Color.White,
                        0F,
                        Vector2.Zero,
                        _scale.ToVector2(),
                        SpriteEffects.None,
                        0F);
                }
            }

            _spriteBatch.End();
        }

    }
}

I dont use floats values for camera position in this test and the flickers continue to happens. I dont know what is happen.
I tried various things, but nothing work.
Resources:
i001_tiles.png (no alpha values)

PrintScreens:

Maybe is just a ottical illusion, or a monitor problem, but the green part of texture merge with the blue background on camera movement, i dont know why.
In Movement Up:

This only occour with the colors different of white, when i movement camera to right, only the one pixel in green in the right merge with blue background.


text:
Q: Entity Framework optimistic concurrency exceptions occur when multi SaveChanges I using Entity Framework 6. After calling SaveChanges method twice in my code, after DeleteObject, a ConcurrencyException occurred:
entities.DeleteObject(pu);

// First time
entities.Context.SaveChanges(SaveOptions.None);

// everything is ok

// Second Time
entities.Context.SaveChanges(SaveOptions.None);

// Concurrency exception

But with using AddObject this exception did not occur !
Exception message is:

Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. Handling optimistic concurrency exceptions.

How I can control multiple SaveChanges calls before AcceptAllChanges without a concurrency exception?

A: Are you calling the AcceptAllChanges() method before the second save? My understanding is that if you use SaveOptions.None, the context keeps the changes so they can be resubmitted to the database. If the first SaveChanges() succeeds, than the rowversion is updated in the db, but in the context, everything is kept as it was, so the second time it causes the conflict on the rowversion.

A: You can use transaction

var yourContext = ((IObjectContextAdapter)db).ObjectContext;

try {
    yourContext.Connection.Open();
    using (var transaction = new TransactionScope()) {

        //you can implement entities.DeleteObject(pu) here

        db.SaveChanges();

        // Do something else

        db.SaveChanges();

        transaction.Complete();
    }
} finally {
    yourContext.Connection.Close();
}


text:
Q: Getting log4j error when setting up kafka docker compose I had a docker compose file that allowed me to set up kafka running on docker. Now I'm trying to add kafka-connect to it but I'm getting this error:

My docker compose up file is the following, which I adapted from examples I found online:
version: '2.1'
services:
  kafka:
    image: wurstmeister/kafka
    container_name: kafka
    ports:
      - 9092:9092
    environment:
      KAFKA_ADVERTISED_HOST_NAME: localhost
      KAFKA_ZOOKEEPER_CONNECT: zookeeper:2181
      KAFKA_ADVERTISED_PORT: 9092
      KAFKA_AUTO_CREATE_TOPICS_ENABLE: 'true'
      KAFKA_DELETE_TOPIC_ENABLE: 'true'
      KAFKA_CREATE_TOPICS: "TOPIC:3:1"
  zookeeper:
    image: wurstmeister/zookeeper
    ports:
      - 2181:2181
  connect:
    image: confluentinc/cp-kafka-connect
    hostname: localhost
    depends_on:
      - zookeeper
      - kafka
    ports:
      - 8083:8083
    environment:
      CONNECT_BOOTSTRAP_SERVERS: kafka:9092
      CONNECT_REST_ADVERTISED_HOST_NAME: localhost
      CONNECT_REST_PORT: 8083
      CONNECT_GROUP_ID: compose-connect-group
      CONNECT_CONFIG_STORAGE_TOPIC: docker-connect-configs
      CONNECT_CONFIG_STORAGE_REPLICATION_FACTOR: 1
      CONNECT_OFFSET_FLUSH_INTERVAL_MS: 10000
      CONNECT_OFFSET_STORAGE_TOPIC: docker-connect-offsets
      CONNECT_OFFSET_STORAGE_REPLICATION_FACTOR: 1
      CONNECT_STATUS_STORAGE_TOPIC: docker-connect-status
      CONNECT_STATUS_STORAGE_REPLICATION_FACTOR: 1
      CONNECT_KEY_CONVERTER: org.apache.kafka.connect.storage.StringConverter
      CONNECT_VALUE_CONVERTER: org.apache.kafka.connect.json.JsonConverter
      CONNECT_ZOOKEEPER_CONNECT: zookeeper:2181

I have no idea how to set up the log4j configuration. I have added an example config file in the directory of the docker compose, but no luck.
Any ideas? Thanks!

A:
how to set up the log4j configuration

Add another variable. (Copied from existing Confluent Docker-Compose stack)
CONNECT_LOG4J_LOGGERS: org.apache.zookeeper=ERROR,org.I0Itec.zkclient=ERROR,org.reflections=ERROR

Also, you have an error in your Kafka image. You should be using KAFKA_ADVERTISED_HOST_NAME: kafka. Otherwise, Connect will not work.


text:
Q: JQuery Mobile - select onchange breaks tabbing to next field When using Jquery mobile, When you select an option from a select with the keyboard, you cannot tab to the next input in the DOM. If you take out the jquery mobile bits, things work as expected.
I have the following html:

<input type='text' id='starter' />

<select id='sel'>
    <option value=''></option>
    <option value='1'>One</option>
    <option value='2'>Two</option>
</select>

<input type='text' id='ender' />

I have set this up on fiddler with jquery and jquery mobile below:
http://jsfiddle.net/58jkj1wa/ - raw jquery works as expected.
http://jsfiddle.net/a5reojmo/4/ - jquery mobile broken select.
To reproduce the issue perform the following:

*

*The cursor starts in the first input

*press 'tab' to move to the select

*press down arrow to activate the options

*press down arrow to select the first option

*press return to accept the change (non mobile - focus is now correctly on the select)

*press tab

In the non-mobile version the cursor is now in the second input as expected. In the mobile version it's someplace else... and I don't know where. You have tab a lot for the focus to move to the first input again... then through the inputs to the field you want after the select you just used.
Personally I reckon this is a bug, so the most interfering I felt prepared to do was to try the on change trigger to try and set the focus back to the select like this:
$("#sel").on("change", function (e) {
    $("#sel").focus();
});

But this does not work. If you do the focus call anywhere else, it works as expected, highlighting correctly and tabbing off if you do not change the value. but as soon as you change the value the focus is someplace else.
I can set the focus to the next item however:
$("#sel").on("change", function (e) {
    $("#ender").focus();
});

But I'd rather not do this as this means I can't do some of the dynamic hiding of inputs I'm doing and have to programmatically mirror the flow handling in the form.
I've tried updating some of wrapper stuff that JQM adds and I've tried setting focus on another input and then back again, and then optionally doing a selectmenu refresh, but the mobile still can't tab out to the next input. I've also tried various blur() and focus() calls all to no avail.
I did see this answer doing something similar by adding a keydown handler, but since I don't know where the focus is after a value change I don't know where to add the keydown handler... besides this sounds like a JQuery Mobile bug doesn't it??
Do you know how I can make tab and focus-highlight work correctly after a select change in JQuery Mobile?
Is this a bug I should report?


text:
Q: Can I take a DISTINCT set of a COALESCE'd set of data? I have the following bit of code, and it works so far:
SELECT
    [id],
    COALESCE ([Company], [LastName] + ', ' + [FirstName]) as Customer
FROM [some_database].[dbo].[some_table]
ORDER BY Customer

However, I'd like to use the DISTINCT keyword to eliminate duplicate "Customer" entries.  Is this possible?  I've tried it a few different ways, but to no avail.

A: If you have multiple customer entries with the same name, you have to pick one ID for a given name. Here's an example of picking the most recently created (ie max()), but you may want the first created (ie min()):
SELECT
    Max([id]) as id,
    COALESCE ([Company], [LastName] + ', ' + [FirstName]) as Customer
FROM [some_database].[dbo].[some_table]
GROUP BY 2
ORDER BY Customer

EDITED: Sorry... GROUP BY 2, not 1


text:
Q: Hierarchical Clustering related I have a question concerning hierarchical clustering using R Language. I am trying to find out what values does the argument dist.metric takes of the function hclust. I wonder whether this is the same as in Python's "metric", but apparently I tried to use "cosine" there and the result was an error. So what values does this argument accept? If possible with an example provided.

A: You can use different metrics in the hclust function:

the agglomeration method to be used. This should be (an unambiguous
abbreviation of) one of "ward.D", "ward.D2", "single", "complete",
"average" (= UPGMA), "mcquitty" (= WPGMA), "median" (= WPGMC) or
"centroid" (= UPGMC).

This means you can use for example average. Here is an example:
data <- matrix(rnorm(100), nrow=3)
d_m = dist(data, method="maximum")
hclust(d_m, method="average")

Call:
hclust(d = d_m, method = "average")

Cluster method   : average
Distance         : maximum
Number of objects: 3

As you can see the cosine is not available.
When using dist.metric in hclust:
hclust(d_m, method="average", dist.metric = "cosine")
Error in hclust(d_m, method = "average", dist.metric = "cosine") :
  unused argument (dist.metric = "cosine")

So there is no argument called dist.metric.


text:
Q: Capturing group does not work with NSRegularExpression I'm trying to make NSRegularExpression working with capturing group pattern. I've got string abc{=2} and regular expression pattern {(.+)} to get =2 string but every attempt to create NSRegularExpression instance ends with
Optional(Error Domain=NSCocoaErrorDomain Code=2048 "The operation couldn't be completed. (Cocoa error 2048.)" UserInfo=0x7fad7253cb40 {NSInvalidValue={(.+)}})

Code:
var error: NSError?
let regexp = NSRegularExpression(pattern: "{(.+)}", options: .CaseInsensitive, error: &error)
println("error = \(error)")

I cannot find what's wrong with this pattern. I am using regex101.com page and it works there.
Thank you in advance!
Edit
I see that escaping curly brackets (\\{(.+)\\}) solves problem with error but then I've got {=2} instead of =2.

A: This is a peculiarity of NSRegularExpression and perhaps more so NSTextCheckingResult. Your captured range is actually the range at index 1 of your NSTextCheckingResult result instance.
An example:
let rx = NSRegularExpression(pattern: "\\{(.+?)\\}", options: .CaseInsensitive, error: nil)!
let str = "abc{=2}"
let strRange = NSMakeRange(0, count(str))

rx.enumerateMatchesInString(str, options: nil, range: strRange, usingBlock: { result, flags, stop in
    if let range0 = result?.range {
        println( (str as NSString).substringWithRange(range0) ) // "{=2}"
    }
    if let range1 = result?.rangeAtIndex(1) {
        println( (str as NSString).substringWithRange(range1) ) // "=2" <-- this is what you want!
    }
})

For each NSTextCheckingResult instance, the range at index 0 is a range representing the capture of your entire pattern (the range property is a shortcut for index 0). Your captures groups' ranges are held at indexes 1 and beyond. From the NSTextCheckingResult docs rangeAtIndex: method:

A result must have at least one range, but may optionally have more (for example, to represent regular expression capture groups).

The simplest way of understanding this is to imagine you provided a regex pattern with no capture groups. What would matched and represented by an NSTextCheckingResult instance? The entire matched pattern!
It would be good practice to use NSTextCheckingResult's numberOfRanges property to make sure you have more than 1 range captured before you try to access your capture group's range. If you are using one capture group, you should expect numberOfRanges to be 2 if your capture group finds a match.
Finally, although this was not necessary, I added the ? modifier to your capture group (.+) to make (.+?). Your pattern was originally greedy inside the capture group, and the ? makes the pattern non-greedy. I find non-greedy to be more predictable in general when working with regular expressions.

I should also mention the reason your solution works (with the result at index 0). By using the lookahead/lookbehind, you have effectively excluded the {} braces from your pattern completely. If you check your result, you should see that your capture group result actually exists at index 1 (but gives the same result as index 0).

A: I fixed this using different pattern. I don't know now if regex101.com matches it wrongly and correct match for my pattern is {=2} instead of '=2'.
I used positive lookbehind and positive lookahead to match this. This is the pattern:
(?<=\\{)(.+)(?=\\})


text:
Q: Expression Language in JSP not working I am new to JSP and using Expression language. I am using Eclipse Galileo with version 2.5 and Tomcat 6 server . I just want to ask that my simple Expression Language is not printing the vale like if i write ${1>2} which suppose to give false but it is displaying  ${1>2} only when it renders the page. But when i am using <c:out value="${1>2}"/> it is printing false correctly. I think there is an issue with tag library. Please kindly suggest me the reason for this i am giving a sample code for this so that you can understand where I am going wrong:-
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                                 "http://www.w3.org/TR/html4/loose.dtd">

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Expression Language Example</title>
</head>
<body>

Is 1 greater than 2 using cout  :<c:out value="${1>2}"/>

Is 1 greater than 2 without using cout: ${1>2}
</body>
</html>

Update as per the answers, here is more information:
I am showing my web.xml how it looks like:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:jsp="http://java.sun.com/xml/ns/javaee/jsp" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>ScriptLessJsp</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>

  <servlet>
    <description></description>
    <display-name>ElServlet</display-name>
    <servlet-name>ElServlet</servlet-name>
    <servlet-class>com.servlet.El.ElServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>ElServlet</servlet-name>
    <url-pattern>/ElServlet</url-pattern>
  </servlet-mapping>
  <servlet>
    <description></description>
    <display-name>Collections</display-name>
    <servlet-name>Collections</servlet-name>
    <servlet-class>com.servlet.El.Collections</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>Collections</servlet-name>
    <url-pattern>/go</url-pattern>
  </servlet-mapping>
</web-app>

And in my lib folder I have added only jstl.jar so that i can make use of <c:out> tag to display but my EL for template text is not working.

A: I'm quoting from an answer I provided before to the problem of EL not working:

With other words, the EL expression doesn't get evaluated? That can have one or more of the following causes:

*

*Application server in question doesn't support JSP 2.0.

*The web.xml is not declared as Servlet 2.4 or higher.

*The @page is configured with isELIgnored=true.

*The web.xml is configured with <el-ignored>true</el-ignored> in <jsp-config>.

In your particular case, EL works in taglibs, but not in template text, so I suspect it's caused by point 2. Ensure that your web.xml is declared as at least Servlet 2.4. As Tomcat 6.0 supports Servlet 2.5, I would recommend to declare your web.xml as Servlet 2.5:
<web-app
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    id="Your_WebApp_ID"
    version="2.5">

    <!-- Here you go. -->

</web-app>

Another rare cause I've seen on this is that there's a collision with EL JAR's in the classpath. Ensure that you have not copied any appserver-specific JAR files into your webapp's WEB-INF/lib or, more worse, the JRE/lib.
As you're already using Eclipse and Tomcat, I would review the development steps you used for this all. Ensure that you're using "Eclipse for Java EE developers" and that you've integrated the Tomcat instance in Eclipse's Servers view and that you've created a Dynamic Web Project set to "Servlet 2.5" which makes use of the Tomcat instance. This way everything should go automagically (Eclipse will take appserver's libraries in the build path itself and autogenerate a Servlet 2.5 compliant web.xml).
Update: as per your update: those com.servlet.El servlets look suspicious. What exactly do they do? Parsing EL? Remove them and retry.

A: BalusC covers it, but I'll add these comments:
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

The JSTL TLD namespace should include a "jsp" (as above). Given this namespace error may be due to following old instructions, check the most recent documentation to ensure you haven't included any obsolete libraries in WEB-INF/lib. A number of technologies that used to be separate are now included in the container (the EL language being one).
As an aside, I would generally use keywords like gt instead of > and lt instead of < - this is friendlier to XML and its ilk.

A: Setting <%@ page isELIgnored="false" %> at the top of the page helped to me. Don't know why it was the root of the problem in my case. not clear why yet

A:
In my case, I generated a webapp by maven archetype generator, I use maven-archetype-webapp. I need to change two things:

*

*in web.xml, change the head to:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns="http://java.sun.com/xml/ns/javaee"
  xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
  xsi:schemaLocation="http://java.sun.com/xml/ns/javaee  http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
  version="2.5">

*by default, eclipse generated jsp file with head:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

Just remove it.

A: I've had the problem that with the line <!DOCTYPE html> in my JSP, the tomcat started with eclipse didn't interpret the EL correctly. Using the war and copying it to the webapps folder and then starting tomcat with the commandline did the job.
So obviously eclipse tomcat plugin has a problem with <!DOCTYPE html>?!


text:
Q: Can't access Nginx outside home network So, I set up a Nginx server on a Ubuntu system, I can access directly from my LAN.
I then bought a domain and linked it with my public ip address.
I port forwarded port 80 on my router.
So, this is the weird part, I can access my server by typing my domain in my home network.
But, i've been trying to access it outside my network (my phone's lte) and it does not work.
I know i can connect, because my FTP server works directly fine.
I temporarily disable my local firewall to make sure it wasn't an exceptrion problem, but it was not that.
I don't know what else to try?
my server config file
listen 80;
listen [::]:80;

root /var/www/ahtpo.host/html;
index index.html index.htm index.nginx-debain.html;

server_name ahtpo.host www.ahtpo.host;

access_log /var/log/nginx/ahtpo.host.access.log;
error_log /var/log/nginx/ahtpo.host.error.log;

location / {
    try_files $uri $uri/ =404;
}

my access.log shows access only from my home's public ip and nothing else. all other attempts fail. My error.log is empty
OpenPortCheckTool says that port 80 is closed, even though i've allowed on my firewall and my router

A: I figured it out. My ISP (Cox) does not allow port 80 traffic on a residential address, so I just changed the port number. Thanks for the help. I know it wasn't a programming question, sorry.


text:
Q: Simple Phone gap/jquery project got an error I'm new of phonegap and jquery
In the log cat i got this error:
03-09 18:46:56.170: D/CordovaLog(10139): http://code.jquery.com/jquery-1.11.1.min.js: Line 2 : Uncaught Error: cannot call methods on page prior to initialization; attempted to call method 'bindRemove'
this is my js:
$(document).ready(function() {
    app.initialize();
});

var app = {
    initialize: function() {
        this.bind();
    },

    bind: function() {

        document.addEventListener('deviceready', this.deviceready, false);
        $(".buttonConferma").on("tap", selezione.conferma);
    },

    deviceready: function() {
        app.start();
    },

    start: function() {

        }
    }
};

    var selezione = {
         conferma: function() {

             navigator.notification.alert("Confermato!");
            }
    }

and this is my html head imports:
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css">
<script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
<script type="text/javascript" src="js/dettagliEvento.js"></script>
<script type="text/javascript" src="cordova.js"></script>

Any advice to resolve the error? other similar question had not helped
I forgot to say I get the error when I press on confirm button (.buttonConferma)


text:
Q: Block specific ipad apps from Internet using a Hotspot locked down with UFW My goal is to be able to use an Apple ipad online but block specific apps from network connections. I want to create proprietary products with these apps and don't want this content stored on their cloud.
One online solution was to go into ipad settings and block cellular for any specific app but many of us do not have cellular on the ipad and must use wifi for internet access. And, there is no wifi blocking equivalent feature per app.
Another proposed solution is Apple approved vpn firewall apps. The problem with this is you have to buy a service and all your content truly isn't blocked it's still sent to the vpn unnecessarily.
Another proposed solution I found suggests to use Screen Time to disable apps. Apps are disabled, but not their network connections. Wireshark proved to me that Screen Time Apps (although disabled from use when launched) still start making network connections after a blocked launch attempt.
Another proposed solution I found was that I should turn off iCloud storage but some apps are not using iCloud so this is not a complete solution.
So, I'm trying to do it by customizing a hotspot with ufw firewall rules where these rules will block these apps.
What steps do I take to do get an app specific rule set for ufw?
Should I block hosts by putting them in /etc/hosts file? If so, how do I get all the hosts?
Should I block by ip address? How do I get all the ip addresses so I can form this rules?
My tools of disposal at this time are: wireshark, ufw, and a computer for a hotspot.
I prefer to use ufw and the hotspot, but if not through hotspot with ufw how about some other way that has the same end goal?

A: Enroll the devices in a mobile device management system. Whitelist and blacklist apps as desired.
Probably there exist firewalls that can do application identification sufficient for this purpose. However, I don't know how to do so with UFW. The real trick is identifying different apps that all use the same public clouds.