text:
Q: Postgres json_agg order by I have multiple tables in a json_agg for psql:
SELECT json_agg(t) FROM (SELECT *,
    ( SELECT row_to_json(b) FROM ( SELECT * from (SELECT *, ( (3959 * acos( cos( radians(6.414478) ) * cos( radians( lat ) ) * cos( radians( lng ) - radians(12.466646) ) + sin( radians(6.414478) ) * sin( radians( lat ) ) ) ) * 1.609344 ) AS distance
    from farm_location ) al WHERE farm_location_id=supply_forecast.farm_location_id and distance < 100 ) b) as farm_location,
    ( SELECT json_agg(c) FROM ( SELECT *
    FROM supply_forecast_status_history WHERE supply_forecast_id=supply_forecast.supply_forecast_id) c) as supply_forecast_status
FROM supply_forecast WHERE delete = B'0' ORDER BY farm_location.distance desc) t;

I'm trying to calculate the distance from a farm location.  The issue is I'm trying to sort the data by "distance" but it's throwing an error:

ERROR:  missing FROM-clause entry for table "farm_location"
      LINE 6: ...FROM supply_forecast WHERE delete = B'0' ORDER BY farm_locat...
                                                               ^
********** Error **********

ERROR: missing FROM-clause entry for table "farm_location"
SQL state: 42P01
Character: 642

If I remove the ORDER BY farm_location.distance desc the query works but the data is not sorted by distance.  Any idea on how to go about this?

A: json_agg function can support order by parameter.
SELECT json_agg(t.* ORDER BY distance desc) FROM
    (SELECT *,
        (SELECT row_to_json(b) FROM
            (SELECT * from
                (SELECT *
                    , ((3959 * acos( cos( radians(6.414478)) * cos( radians( lat )) * cos(radians( lng )
                        - radians(12.466646) ) + sin( radians(6.414478) ) * sin( radians( lat ) ) ) ) * 1.609344 ) as distance
                from farm_location) al
            where farm_location_id=supply_forecast.farm_location_id and distance < 100
            ) b
        ) as farm_location
        , (select json_agg(c)
            from (SELECT * FROM supply_forecast_status_history
                WHERE supply_forecast_id=supply_forecast.supply_forecast_id) c
            )as supply_forecast_status
    FROM supply_forecast WHERE delete = B'0'
) t;

A: I apply ORDER BY inside function json_agg() and itś work OK
select
    jsonb_agg(jsonb_build_object('toma_parada', app51.app51_tomas__toma_parada)|| jsonb_build_object('lado', app51.app51_tomas__lado)|| jsonb_build_object('existen_tomas_paradas', app51.app51_tomas__existen_tomas_paradas)|| jsonb_build_object('b', app51.app51_tomas__b)|| jsonb_build_object('a', app51.app51_tomas__a)|| jsonb_build_object('m', app51.app51_tomas__m)|| jsonb_build_object('nombre', app51.app51_tomas__nombre, 'id_publico', app51.app51_tomas__id_publico , 'id', app51.app51_tomas__id )
    order by app51.app51_tomas__id desc) as app51_tomas,
    app51.fecha_modificacion,
    app51.fecha_creacion,
    app51.id_cliente,
    app51.id_rumas,
    app51.id_usuario,
    app51.id,
    app51.id_publico,
    app51.habilitado,
    app51.borrado,
    app51.produccion_fin,
    app51.produccion_inicio
from
    (
    select
        distinct app51.id_cliente,
        app51.id_rumas,
        app51.id_usuario,
        app51.id,
        app51.id_publico,
        app51.habilitado,
        app51.borrado,
        app51.atributos ->> 'produccion_fin' as produccion_fin,
        app51.atributos ->> 'produccion_inicio' as produccion_inicio,
        app51_tomas.atributos ->> 'toma_parada' as app51_tomas__toma_parada,
        app51_tomas.atributos ->> 'lado' as app51_tomas__lado,
        app51_tomas.atributos ->> 'existen_tomas_paradas' as app51_tomas__existen_tomas_paradas,
        app51_tomas.atributos ->> 'b' as app51_tomas__b,
        app51_tomas.atributos ->> 'a' as app51_tomas__a,
        app51_tomas.atributos ->> 'm' as app51_tomas__m,
        app51_tomas.atributos ->> 'nombre' as app51_tomas__nombre,
        app51_tomas.id as app51_tomas__id ,
        app51_tomas.id_publico as app51_tomas__id_publico ,
        jsonb_build_object() as id_usuario_creacion,
        jsonb_build_object() as id_usuario_modificacion,
        (
        select
            TO_CHAR(app51.fecha_creacion::timestamptz at time zone 'GMT' , 'YYYY-MM-DD"T"HH24:MI:SS.ss0"Z"')) as fecha_creacion ,
        (
        select
            TO_CHAR(app51.fecha_modificacion::timestamptz at time zone 'GMT' , 'YYYY-MM-DD"T"HH24:MI:SS.ss0"Z"')) as fecha_modificacion
    from
        app51
    left join app51_app51_tomas on
        app51_app51_tomas.id_app51 = app51.id
    left join app51_tomas on
        app51_app51_tomas.id_app51_tomas = app51_tomas.id
        and ((app51_tomas.habilitado = true
        and app51_tomas.borrado = false)
        or app51_tomas is null )
    where
        (app51.habilitado = true
        and app51.borrado = false)
    order by
        app51_tomas.id desc) as app51
group by
    app51.fecha_modificacion,
    app51.fecha_creacion,
    app51.id_cliente,
    app51.id_rumas,
    app51.id_usuario,
    app51.id,
    app51.id_publico,
    app51.habilitado,
    app51.borrado,
    app51.produccion_fin,
    app51.produccion_inicio


text:
Q: React Navigation Is there a way to refer to a navigator from the parent component? I understand that navigation and route props are automatically passed to the target screen when you navigate. So you can access navigation when you're in that screen, say screen B.
What I want to do is in Screen A, where the navigator is defined, I'd like to be able to setParams every so often. How can I refer to the navigator in this case?
For example, I would like to do this:
navigator.screen('posts').setParams({videoData: stuff});
A.js
const A = () => {
  const Tab = createMaterialTopTabNavigator();
  const navigator =   <Tab.Navigator>
  <Tab.Screen name="posts" component={FeedList} />
  </Tab.Navigator>;

  useEffect(()=> {
    fetchStuff((stuff)=> {
      navigator.screen('posts').setParams({videoData: dataState});
    });
  },[]);

  return <>{navigator}</>;
}

Inside the useEffect, I ideally would be able to dynamically set the route params of the target screen.
I tried using initialParams and a state, but the initialParams doesn't seem to update in the target screen when the state changes. (So, I would accept that as an answer too, if you know why that's not working.)
not working initialParams example:

const A = () => {
  const [dataState, setDataState] = useState(null);
  const Tab = createMaterialTopTabNavigator();

  useEffect(()=> {
    fetchStuff((stuff)=> {
      setDataState(stuff);  // this doesn't seem to update initialParams
    });
  },[]);

  return <Tab.Navigator>
  <Tab.Screen name="posts" component={FeedList} initialParams={{videoData: dataState}} />
  </Tab.Navigator>;
}

A: You can use setParams function.
Here is the code of updating of the state of a nested tab's screen after 3 seconds.
import React, {useContext, useState, createContext, useEffect} from 'react';
import {View, Text, StyleSheet} from 'react-native';
import {NavigationContainer} from '@react-navigation/native';
import {createBottomTabNavigator} from '@react-navigation/bottom-tabs';
import {createStackNavigator} from '@react-navigation/stack';
import {CommonActions} from '@react-navigation/native';

const Stack = createStackNavigator();
const KeyContext = createContext();
const DELAY_TIME = 3000;

const KeyContextProvider = (props) => {
  const [routeKey, setRouteKey] = useState(null);
  return (
    <KeyContext.Provider
      value={{key: routeKey, setKey: (value) => setRouteKey(value)}}>
      {props.children}
    </KeyContext.Provider>
  );
};

const AScreen = ({navigation}) => {
  const Tab = createBottomTabNavigator();
  const {key} = useContext(KeyContext);
  React.useEffect(() => {
    if (key) {
      setTimeout(() => {
        navigation.dispatch({
          ...CommonActions.setParams({value: 'Updated state'}),
          source: key,
        });
      }, DELAY_TIME);
    }
  }, [navigation, key]);

  return (
    <Tab.Navigator>
      <Tab.Screen
        name="screen B"
        component={BScreen}
        initialParams={{value: 'Initial state'}}
      />
      <Tab.Screen name="screen C" component={CScreen} />
    </Tab.Navigator>
  );
};

const BScreen = ({route}) => {
  const val = route.params?.value || null;
  const {setKey} = useContext(KeyContext);

  useEffect(() => {
    setKey(route.key);
  }, [route, setKey]);

  return (
    <View style={styles.screen}>
      <Text>Screen B</Text>
      <Text>{val}</Text>
    </View>
  );
};

const CScreen = () => {
  return (
    <View style={styles.screen}>
      <Text>Screen C</Text>
    </View>
  );
};

export default function App() {
  return (
    <KeyContextProvider>
      <NavigationContainer>
        <Stack.Navigator>
          <Stack.Screen name="Screen A" component={AScreen} />
        </Stack.Navigator>
      </NavigationContainer>
    </KeyContextProvider>
  );
}

const styles = StyleSheet.create({
  screen: {flex: 1, justifyContent: 'center', alignItems: 'center'},
});

redpajama_set_name: RedPajamaStackExchange


text:
Q: Unable to run query in Presto I am installing presto for first time. I created a single ubuntu instance in amazon ec2 and installed all the dependences required to install presto. I followed https://github.com/facebook/presto .
I did git clone and got the source code then I ran $mvn clean install as per instruction. Then I ran $presto-cli/target/presto-cli-*-executable.jar. while executing query it is showing an error as shown in image below

Please help me in solving this. The same I want to try in cluster containing master and slaves.

A: while working with ec2 make sure that you have your own AMI, Keypair and security group.

A: It seems, your server is not running or is hosted on another port number.
Have you started the server using
./presto-server-x.x/bin/launcher.py start


text:
Q: Как поддерживать SSH тунель активным Есть компьютер с ubuntu 16 у которого серый IP, и есть vps - хочу как-то держать постоянно активным ssh тунель от vps до компьютера.
Сейчас, для простоты персонала, на компьютере bash скрипт который который создает туннель от себя до сервера, но для его запуска нужно что-бы кто-то запустил скрипт. Можно поставить в автозапуск скрипт, но если пропадет интернет, то и соединение прервется.
Можно в теории написать срипт, который будет раз в минуту смотреть активные соединения, и если ssh не будет то скрипт будет перезапускать скрипт, который создает тунель. Или как правильно сделать так что бы было активное соединение по ssh с vps, и чтобы если соединение прервано, то создавалась занова?
Может есть кикие-то готовые решения? Программы по типу AnyDesk не подходят, из-за того что я буду забирать у персонала управление над компьютером.

A: С опцией ServerAliveInterval=5 клиент будет посылать каждые 5 секунд сообщения поддержания сессии, и если сообщение не доходит, то сессия обрывается сразу.
Скрипт запуска приведи к виду, например:
while true
do
  ssh 203.0.113.2 -l root -N -R 0.0.0.0:0:127.0.0.1:22 -o ServerAliveInterval=5
done

При обрыве связи ssh будет обрываться и переподключаться в вечном цикле

A: Добавлю свои 5 копеек.
Для устойчивой работы через соединение SSH можно использовать mosh.
Mosh — программа для удалённого подключения с клиентского компьютера к серверу через Интернет. Предоставляет доступ к текстовому терминалу. Mosh аналогичен приложению SSH, но имеет дополнительные функции, предназначенные для повышения удобства работы мобильных пользователей.
Основные задачи, которые решает mosh:

*

*Возможность роуминга ssh-соединений. Переключайтесь между wi-fi
сетями, не бойтесь смены IP в мобильных сетях — соединение не
разорвется. От себя замечу, можно закрыть ноутбук на работе и открыть уже дома, vim открыт с курсором в том же месте, где вы делали последнее редактирование, как будто соединение не пропадало вовсе.

*Уменьшение лагов насколько это возможно, за счет использования UDP и
умного predictive echo.

*Оптимизация использования сети — протокол mosh позволяет передавать только то, что должно быть отображено. В итоге Сtrl-C работает мгновенно, даже если вы выплюнули в консоль содержимое 500GB файла.

*Максимальная обратная совместимость — от  пользователя требуется минимум телодвижений и знаний, чтобы начать использовать mosh.

Как правило, remote-shell протоколы исповедуют подход «сервер отправляет все данные клиенту, а клиент уже разбирается, как их отображать». Mosh идет другим путем и хранит состояние экрана на клиенте и сервере, и эти два состояния постоянно синхронизирует — собственно, протокол так и называется — State Synchronization Protocol. Протокол позволяет контролировать частоту синхронизации, в зависимости от качества сетевого соединения.
Источник


text:
Q: sharepoint designer 2010 email notification with multiples conditions I'm a newbie and am trying create a SPD 2010 designer workflow that will send email notification when conditions were met.
Given:

*

*Column Name | Type

Reminder Status | Choice (Open,Close)
ExpirationCountdown | Calc value = ([Date of expiration] - Today())
MOD30 | Calc value = (INT(MOD([Exp_countdown],30)
MOD10 | Calc value = (INT(MOD([Exp_countdown],10)

*

*Conditions:

Condition a: if Reminder Status = 'Open'
Condition b: ExpirationCountdown = 120,90,60,30,20,10
Condition c: if Reminder Status = 'Close' stop workflow and log "Closed"
My research led me to the workflow below.
 If Current Item:Reminder Status equal OPEN
and Current Item:ExpirationCountdown is less that or equal to 120
and Current Item:ExpirationCountdown equals Current Item: MOD30
or Current Item:ExpirationCountdown is less that or equal to 30
and Current Item:ExpirationCountdown equals Current Item: MOD30
email Current Item:Person to Notify
then pause until Current Item:Reminder Status equals 'Closed'
Else if Current Item:Reminder Status equals 'Closed'
stop the workflow and log Closed | Document Submission Completed
Any help would be much appreciated.
Thank you so much.

A: I suppose you want the email triggers on the mentioned countdown days.
With this workflow, the email will be triggered only once and then it would wait until the Reminder Status is changed to closed and then log the status.
A loop is not possible using 2010. It would be suggested to maintain a field and trigger the workflow on item update and use this field value to check to trigger emails.


text:
Q: git push only moved some files So, I'm a bit of a git noob, but I've been able to get it working for me most of the time.  I've recently encountered a problem that has me stumped. I set up a git repo for a staging site and a production site.  My post-receive file looks something like this:
#!/bin/sh
GIT_WORK_TREE=/var/www/site_name.com/public_html git checkout -f master

The only difference in my staging post-receive is it goes to /staging.  I did git init on my local machine, set up the remotes and pushed to staging.  When I was done, I could go to myDomain.com/staging and bam, page loads.  Then I go and push to live and look, and roughly 1/3 of the files are there.
When I load myDomain.com it shows up as a directory.  When I check the files, the index and several directories never made the move.  When I try to do
git add .
git commit -m "some message"
git push production master

It gives me the message "Everything up-to-date" even though it's clear that it's not.
I've looked at:
git status --ignore

The only files the come up are the .DS_Store files in each directory.
Any help would be much appreciated.  I'm very stuck.

A: You might have a .gitignore that makes git ignore certain files.

A: When you add the files, which folder are you in? If you're not in the base directory, try:
git add -A :/


text:
Q: No me lee los \n o /r o algunos de esos en python Que hago? El la consola los caracteres de \n, \t, /r.. en vez de interpretarse como salto delinea o como sea se leen literalmente como literalmente "\n" por ejemplo que hago???? Aqui dejo el codigo...
# -*- coding: utf-8 -*-
import socket
import os

host = socket.gethostname()                                             #Nos da la IP de la maquina
port = 8056                                                             #Puerto del server
BUFFER_SIZE = 4096                                                      #Es el tamaño del que vamos a recibir los paquetes de informacion

socketS = socket.socket(socket.AF_INET, socket.SOCK_STREAM)             #Crea el server con protocolo TCP

socketS.bind((host, port))                                              #Vinculamos el server con un puerto y host
print("[INFO] Esperando conexion...")
socketS.listen(5)                                                       #Esperamos la conexion del cliente...
conn, addr = socketS.accept()                                           #Establecemos conexion con el cliente
with conn:
    print("[INFO] Conexion establecida")
    while True:
        print("----------------------------------")
        print("----------------------------------")
        dataEnv = input("Comando que quieres poner: ")
        print("----------------------------------")
        print("----------------------------------")
        if dataEnv != "" or dataEnv != " ":
            conn.send(dataEnv.encode('utf-8'))
        try:
            data = conn.recv(BUFFER_SIZE)                               #Recibimos datos del cliente
            dataDecode = data.decode('utf-8')                           #Decodificamos los datos recibimos
                                                                        #Comprobamos si hemos recibido datos
            if data:
                print(repr("Resultado: /n {}".format(dataDecode)))      #Mostramos lo recibido
        except:
            input("[ERROR] El cliente no esta conectado")
            break

A: Se debe a que para que interprete las secuencias de escape, todos deben de estar con la denominada barra invertida o backslash (\), ya que si se pone con la barra normal (/) lo toma como un carácter que se debe de imprimir:
print("Salto de  \n línea con barra invertida")
print("Salto de  /n línea con barra normal")

Resultado:

En tu caso en la siguiente línea es donde veo que utilizas este tipo de caracter:
print(repr("Resultado: /n {}".format(dataDecode)))

En cual sale con la barra normal, y debería de ser con barra invertida tal que así:
print(repr("Resultado: \n {}".format(dataDecode)))

Además repr también estaría ayudando a que la línea no se visualice correctamente, para ello es necesario eliminar repr también.
Ya que repr es una función que devuelve una cadena en su formato imprimible, es decir, no resuelve las secuencias de escape.
El siguiente código que también puedes visualizar en el siguiente enlace, gentileza del usuario insolor muestra como repr afecta.
dataDecode = 111

print(repr("Resultado: \n {}".format(dataDecode)))
print("Resultado: \n {}".format(dataDecode))

Resultado
'Resultado: \n 111'
Resultado:
 111

El código resultante en tu caso debería ser, sin repr y con barra invertida (\):
print("Resultado: \n {}".format(dataDecode))


text:
Q: Find an equivalent to the function $f(x) = \frac 1 { \sqrt { 1 - x^2 } }$ Find an asymptotically equivalent equivalent to the function $$f(x) = \frac 1 { \sqrt { 1 - x^2 } }$$
around $1$, where for asymptotically equivalent function $f$ of a given function $g$ at a point $a$ I mean a function such that
$$
f\sim_a g\iff \lim_{x\to a}\frac{f(x)}{g(x)}=1
$$
I'm searching for that because I saw that $$ x \cdot f(x) = \frac x { \sqrt { 1 - x^2 } }$$ diverges in $1^-$. I don't understand why this should be true, on an analytical level.

A: The domain of $f$ is $(-1,1)$.
$$f(x)=\frac{1}{\sqrt{1-x^2}}$$
$$=\frac{1}{\sqrt{(1+x)(1-x)}}$$
$$\sim \frac{1}{\sqrt{2(1-x)}}\;\;\; (x\to 1^-)$$
because $1+x\sim 2 \;\; (x\to 1)$.

A: Another approach:
By your definition we want to have $\lim_{x \to 1}  \frac{f(x)} {g(x)} = 1$. Because domain of $f(x)$ is $(-1,1)$, the only possibility is $x \to1^{-}$. Using the L'Hôpital's rule, we get $\lim_{x \to 1^{-}}  \frac{f'(x)} {g'(x)} = 1$. So $\lim_{x \to 1^{-}}  \frac{x(1-x^2)^{-3/2}} {g'(x)} = 1$. If $g'(x) = (1-x^2)^{-3/2}$ then we are done. Therefore we calculate $\int(1-x^2)^{-3/2}dx$. By the $x = \sin\theta$ substitution, answer is $\frac{x}{\sqrt{1-x^2}} + c$. I think it's possible to obtain other functions in this fashion.


text:
Q: Software packaging for RedHat similar to Ubuntu I'm currently helping a professor who is having trouble installing a particular software onto the school's server which runs on Red Hat/Fedora. The professor thinks that the software was packaged for Ubuntu which distributes files together rather than into multiple folders which apparently is what Red Hat/Fedora does (correct me if I'm wrong!).
Is there a way to distribute software on Red Hat/Fedora in a similar fashion as Ubuntu?

A: I think you are mixing things called tar-balls (when referring to multiple folders), with regular installation packages (files ending in .deb on Debian/Ubuntu and in .rpm on Red Hat/Fedora/SuSE).
The former is "only" a, often compressed, directory structure with some instruction (in the form of scripts, Makefiles, configuration files) to get the files installed to the right directories on your system after unpacking. This has the disadvantage that it is often difficult to reverse such an installation.
Installation packages (.deb, .rpm) have, broadly speaking, additional information on where what files are installed, so they can be deinstalled (there are also post- an pre-install and deinstall scripts for additional actions etc.).
The packagings can proceed directly from source, but is often based on the "more primitive" tar balls. There are often similarities that for a large subset of packages in one form, they can be converted to the other using the program alien


text:
Q: jquery on('click') event firing twice when resizing I'm having an issue trying to fix my mobile navigation when I tried resizing my browser. Basically whenever I try resizing the browser the slideUp and slideDown fires at the same time by a click event. How can I resolve this

            INICIO

            BUSCAR ÓPTICA

            QUIÉNES SOMOS

            SERVICIOS

                    Cómo funciona

                    Seguro

                    Formas de pago

                    Reclamaciones

                    Garantía

                    Preguntas frecuentes

    reformat : function() {
        this.winWidth = $(window).width();

        if (Global.winWidth <= 768) {

            $('.fa-bars').addClass('active').removeClass('inactive');

            $('.menu--main li.menu-item--expanded').unbind('mouseenter mouseleave');

            $('.menu--main li.menu-item--expanded').on('click touchstart', function(e) {

                e.preventDefault();

                $('> a', this).removeAttr('href');

                var item = $('ul.menu', this);

                if (!item.hasClass('active')) {
                    // Global.hideSubMenu();
                    setTimeout(function(){
                        item.stop(true).slideDown();
                        item.addClass('active');
                    },100);
                } else {
                    // Global.hideSubMenu();
                    item.stop(true).slideUp();
                    item.removeClass('active');
                }
            });

            if ($('.fa-times').hasClass('active')){
                $('.fa-bars').addClass('inactive');
            }

        } else {
            Global.hideMobileMenu();

            $('.fa-bars').removeClass('active').addClass('inactive');

            $('.menu--main li.menu-item--expanded').unbind('click');

            $('.menu--main li.menu-item--expanded').hover(function() {
                $('ul.menu', this).stop(true).slideDown();
            }, function() {
                $('ul.menu', this).stop(true).slideUp();
            });
        }
    }

}


text:
Q: Terminate python based on printed output In here, Limit tweepy stream to a specific number, I tried to stop a streaming script using tweepy but kept getting an error. I tried fixing the error as some people may have suggested but no luck.
I thought of another method of possibly terminating the script based on a the number of printed outputs. What I did is take the previous code and put into a function:
def streamer(location):
    ## same code here ##
    twitterStream.filter(locations=[\location) ## changed to match function##

Then I would call the function (i.e. streamer(LA)) where LA is predefined with a set of coordinates.
My question: Is it possible to terminate the function streamer based on the number it outputs without changing the function itself (due to persisting error)?

A: you could use quit() but that also terminates the whole session.
You also need to add your streamdata to a variable somewhere.
If I am correct you will get a constant stream of Json items, so just add them to a list and then use the length of the list. Then use twitterstream.disconnect() if you got your amount of outputs.


text:
Q: Override the bookmark shortcut (Ctrl+D) function in Chrome Is it possible to override the Ctrl+D? I want to, for example console.log or something, and not add the links to the bookmarks.

A: It's not necessary to use chrome.commands -- you can use a content script to trap the keydown event, call preventDefault and stopPropagation on it, and handle it however you want. Example snippet that should work as part of a content script:
document.addEventListener('keydown', function(event) {
  if (event.ctrlKey && String.fromCharCode(event.keyCode) === 'D') {
    console.log("you pressed ctrl-D");
    event.preventDefault();
    event.stopPropagation();
  }
}, true);

The only things you can't override this way are window-handling commands, like ctrl-N and ctrl-<tab>.

A: Alternative Solution:
Type chrome:extensions into your browser's address bar. This will pull up the Chrome Extensions page.
Click on Keyboard Shortcuts in the top left menu ("Menu/Burger Button")
Assign Ctrl-D to a plugin that does not alter your Bookmarks.
This will solve the problem that an bookmark is created directly when you accidentally press Ctrl-D, instead the other Addon will pop up in that case.

A: Shortcuts can be overridden using the chrome.commands API. An extension can suggest a default shortcut (eg. Ctrl+D) in the manifest file, but users are free to override this at chrome://extensions/, as seen below:

Usage
This API is still under development and only available at the Beta and Dev channels, and the Canary builds More info. It will probably available to everyone starting at Chrome 24.
If you want to test the API in Chrome 23 or lower, add the "experimental" permission to the manifest file, and use chrome.experimental.commands instead of chrome.commands. Also visit chrome://flags/ and enable "Experimental Extension APIs", or start Chrome with the --enable-experimental-extension-apis flag.
manifest.json
{
    "name": "Remap shortcut",
    "version": "1",
    "manifest_version": 2,
    "background": {
        "scripts": ["background.js"]
    },
    "permissions": [
        "tabs"
    ],
    "commands": {
        "test-shortcut": {
            "suggested_key": {
                "default": "Ctrl+D",
                "mac": "Command+D",
                "linux": "Ctrl+D"
            },
            "description": "Whatever you want"
        }
    }
}

background.js
// Chrome 24+. Use chrome.experimental.commands in Chrome 23-
chrome.commands.onCommand.addListener(function(command) {
    if (command === 'test-shortcut') {
         // Do whatever you want, for instance console.log in the tab:
         chrome.tabs.query({active:true}, function(tabs) {
             var tabId = tabs[0].id;
             var code = 'console.log("Intercepted Ctrl+D!");';
             chrome.tabs.executeScript(tabId, {code: code});
         });
    }
});

Documentation

*

*chrome.commands

*chrome.tabs (methods query and executeScript)


text:
Q: Android Lollipop becoming device admininistrator doesn't work I'm following this guide on how to have my app request to become a device administrator.
This works great on any 4.x android versions with any phone, but doesn't work on Lollipop (I've tried on a Nexus 5 and on a Nexus 7).
Logcat shoes the following error:
 *11-02 07:37:09.649: W/DeviceAdminAdd(10020): Cannot start ADD_DEVICE_ADMIN as a new task*

Has anyone else come across this problem with Lollipop? What can be the cause?
I've gone over all parts of the guide and made sure my XML, menifest, receiver, etc. are all as they should be (and again, it does work on any other version of OS or phone I've tried).
If it matters, I'm compiling my app with target API=17 and min API=14 for compatibility reasons.

Adding the manifest file:
<?xml version='1.0' encoding='utf-8'?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.my.package"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="14"
        android:targetSdkVersion="17" />

     <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.WRITE_SYNC_SETTINGS" />
    <uses-permission android:name="com.mycompany.permission.NFProvider_WRITE" />
    <uses-permission android:name="com.mycompany.permission.NFProvider_READ" />
    <uses-permission android:name="android.permission.READ_LOGS" />

    <application
        android:name="com.mycompany.myapp.Application"
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >

        <receiver
            android:name="com.mycompany.myapp.NFAdminReceiver"
            android:permission="android.permission.BIND_DEVICE_ADMIN">
            <meta-data
                android:name="android.app.device_admin"
                android:resource="@xml/admin"/>
            <intent-filter>
                <action android:name="android.app.action.DEVICE_ADMIN_ENABLED"/>
            </intent-filter>
        </receiver>

        <activity
            android:name="com.mycompany.myapp.ConnectMainActivity"
            android:label="@string/title_activity_connect_main"
            android:process="com.mycompany.ui"
            android:launchMode="singleInstance"
            android:screenOrientation="portrait" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <service
            android:name="com.mycompany.myapp.MainService"
            android:enabled="true" />

        <meta-data android:name="applicationVersion" android:value="1.2.0.213" />

    </application>
</manifest>

Code creating the Intent:
ComponentName mComponentName = new ComponentName(activity, NFAdminReceiver.class);
Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, mComponentName);
intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION, ADMIN_REQUEST_TITLE);
activity.startActivityForResult(intent, ADMIN_INTENT);

The variable activity is an instance of ConnectMainActivity

A: Seems it was the singleInstance launchMode option that caused the problem, I'm still interested to know why it causes the problem on Lollipop and not on other versions.
For now, setting launchMode to singleTask solves the issue, and seems to still fit with the design of the app's flow.

A: The root cause of this error message is in DeviceAdminAdd.java. There is this check:
if ((getIntent().getFlags()&Intent.FLAG_ACTIVITY_NEW_TASK) != 0) {
         Log.w(TAG, "Cannot start ADD_DEVICE_ADMIN as a new task");
         finish();
         return;
}

This check was already there in 4.0.1 : API level 14 !
The Intent subject of this check is the Intent triggering the action : DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN.
From the docs :

A "singleInstance" activity permits no other activities to be part of its task.

It don't explain the difference between API 21 and API<21 , but it explain why the FLAG_ACTIVITY_NEW_TASK is set.


text:
Q: Diameter of the Symmetric group If $G$ is a finite group and $A \subseteq G$ a set of generators, the diameter $diam(G,A)$ is the least integer $d$ such that $A^d=G$.
Now consider the symmetric group $S_n$ and the subset $A_n = \{(12...n), (12) \}$. It is known that $diam(S_n,A_n) \asymp n^2$.
There exist a set of generators $A_n$ of bounded cardinality such that $diam(S_n,A_n) \ll n \log n$?

A: If $\lvert A_n\rvert=m$, then we have $\lvert A_n^n\rvert\le m^n$. But if $m$ is bounded, this grows more slowly than $n!$.
Edit: The question has changed.  $n\log n$ is attainable, with $\lvert A_n\rvert=3$. The idea is to consider the set of $n$ points being moved as $\mathbb{Z}_{n-1}\cup\{\infty\}$. Then you define two linear transformations $\sigma_0,\sigma_1$ on $\mathbb{Z}_{n-1}$ such that you can go from $0$ to any other $m\in\mathbb{Z}_{n-1}$ in $\log n$ steps. The third generator is the transposition $(0,\infty)$.
Then you can get any transposition $(m,\infty)$ in $\log n$ steps, and since $(m,n)=(m,\infty)(n,\infty)(m,\infty)$, and you can write any permutation with $n$ transpositions, the diameter is $n\log n$.
The source for this is the paper On the diameter of finite groups (PDF), section 4.


text:
Q: How to centre an HTML snippet within the browser? An app I'm working on receives HTML from an API and needs to add some simple formatting to it for rendering in a browser. The content received is typically just an  wrapped in an  - very simple.
Example HTML received:

I need to format that received HTML using inline styles (in tags I add around it) that will centre the content within the browser's document area, both horizontally and vertically. I cannot alter the snippet itself, so I need to build an HTML container that will correctly centre whatever snippet is provided.
Here's where I'm at:

I couldn't get the page to do what I needed with styles, so to clarify this what I need here is a (working) solution implemented using tables. I'd much prefer to do it with styles.

A: Seeing as you know the width of the image, you may be able to position it absolutely, and center it that way.
img { /* Assuming a size of 300 by 500, as in your example */
    position:absolute;
    top:50%;
    left:50%;
    margin:-250px 0 0 -150px;  }

See fiddle: http://jsfiddle.net/TheNix/W4cPw/3/

UPDATE
In the case where you don't know the content or the surrounding markup at all, the only way to do this (without Javascript hacks) is with tables (gasp!).
HTML

CSS
html, body, table {
    width:100%;
    height:100%; }

td {
    vertical-align:middle;
    text-align:center; }

See fiddle:
http://jsfiddle.net/TheNix/W4cPw/4/


text:
Q: \mkbibquote used referencing title of a paper is "paper". How about 'paper'? How to make the title of the paper from:
NoiseSpeech, a noise of living bodies : towards Attali's "Composition"

to
NoiseSpeech, a noise of living bodies : towards Attali's 'Composition'

I am using:
  title={NoiseSpeech, a noise of living bodies: towards Attali's \mkbibquote{Composition}},

My MWE:
% \documentclass[12pt,oneside]{book}  % Remove draft option to show figures (for final draft), otherwise keep for faster production
\documentclass{article}
\usepackage{enumitem} % macros to modify appearance of 'itemize' environments

\usepackage{xpatch}

\usepackage[backend=biber,
% style=authoryear,
 style=authoryear-comp,
% citestyle=authoryear,
dashed=false,
maxcitenames=2,
maxbibnames=99,
giveninits,
uniquename=init]{biblatex}

\DeclareNameAlias{sortname}{family-given} %for second and third author name

\renewcommand{\labelnamepunct}{\space} %to delete . after (1997)

\DeclareFieldFormat[article, incollection, unpublished]{title}{#1}

\DeclareFieldFormat*{title}{#1} %for conference title delete ".."
\DeclareFieldFormat[incollection]{title}{\mkbibemph{#1}} %for incollecion title italic ONLY
\DeclareFieldFormat[thesis]{title}{\mkbibemph{#1}} %for phdthesis title italic ONLY

\renewbibmacro{in:}{%
  \ifentrytype{article}{}{\printtext{\bibstring{in}\intitlepunct}}}

\newcommand*{\volnumdelim}{}
\DeclareFieldFormat[article,periodical]{number}{\mkbibparens{#1}}

\renewbibmacro*{volume+number+eid}{%
  \printfield{volume}%
  \setunit*{\volnumdelim}%
  \printfield{number}%
  \setunit{\addcomma\space}%
  \printfield{eid}}

\newcommand*{\jourvoldelim}{\addcomma\space}
\newcommand*{\jourserdelim}{\newunitpunct}
\newcommand*{\servoldelim}{\jourvoldelim}
\newcommand*{\volnumdatedelim}{\addspace}

\renewbibmacro*{journal+issuetitle}{%
  \usebibmacro{journal}%
  \setunit*{\jourvoldelim}%
  \iffieldundef{series}
    {}
    {\setunit*{\jourserdelim}%
     \printfield{series}%
     \setunit{\servoldelim}}%
  \usebibmacro{volume+number+eid}%
  \setunit{\volnumdatedelim}%
  \usebibmacro{issue+date}%
  \setunit{\addcolon\space}%
  \usebibmacro{issue}%
  \newunit}
% to make volume (number), eg. 4(2)

% for delete comma after Author A and Aurhor b
\DefineBibliographyExtras{english}{%
   \let\finalandcomma\empty
   \let\finalandsemicolon\empty
 }

\renewcommand{\compcitedelim}{\addsemicolon\space}
\DeclareNameAlias{editorin}{given-family}

\newbibmacro*{byeditor:in}{%
  \ifnameundef{editor}
    {}
    {\printnames[editorin]{editor}%
     \setunit{\addcomma\space}%
     \usebibmacro{editorstrg}%
     \clearname{editor}}}

\xpatchbibdriver{inbook}
  {\usebibmacro{in:}%
   \usebibmacro{bybookauthor}%
   \newunit\newblock
   \usebibmacro{maintitle+booktitle}%
   \newunit\newblock
   \usebibmacro{byeditor+others}}
  {\usebibmacro{in:}%
   \usebibmacro{bybookauthor}%
   \newunit\newblock
   \usebibmacro{byeditor:in}%
   \newunit\newblock
   \usebibmacro{maintitle+booktitle}%
   \newunit\newblock
   \usebibmacro{byeditor+others}}
  {}{}

% \usepackage{parskip}

\usepackage[hypcap=false]{caption}

\usepackage{csquotes}

\usepackage[unicode,colorlinks,citecolor=blue]{hyperref}

\usepackage{filecontents}
\begin{filecontents*}{\jobname.bib}

@article{dean2005noisespeech,
  title={NoiseSpeech, a noise of living bodies: towards Attali's \mkbibquote{Composition}},
  author={Dean, Roger T},
  journal={NMEDIAC: Journal of New Media \& Culture},
  year={2005},
  number={1},
  volume={3}
}

\end{filecontents*}
\addbibresource{\jobname.bib}

\begin{document}
\nocite{*}

 in \textcite{dean2005noisespeech}

\printbibliography
\end{document}

A: There are a few different ways you can do this:
You can change your language to british (or australian) which uses single quotation marks for outer marks. i.e.,
\usepackage[british]{babel}
\usepackage{csquotes}
\usepackage{biblatex}

Bear in mind that this will also change other language related things like date formats.
The other option is to specify the quotation style directly with csquotes. i.e.,
\usepackage[english]{babel}
\usepackage[style=british]{csquotes}
\usepackage{biblatex}

This will use British style single quotation marks for outer quotation marks, but keep other language settings to babel's default for english (basically American English).


text:
Q: Sass pre-processing using Webpack Encore: how to add sass options? I'm trying to configure Webpack Encore to integrate Foundation into our project. At this page, it is said that Sass options can be passed into Encore using something like:
Encore
    // ...
    .enableSassLoader(function(sassOptions) {
        // https://github.com/sass/node-sass#options
        // options.includePaths = [...]
    });
;

How to pass Sass options such as the following (ie, the path to the scss folder of Foundation) in my config?
var sassOptions = {
    includePaths: 'node_modules/foundation-sites/scss'
};

I'm new to Sass & Webpack. I'm probably missing smthg obvious.

A: I think the key is that includePaths should be an array. If you do this, it should work:
var sassOptions = {
    includePaths: ['node_modules/foundation-sites/scss']
};
Encore
    // ...
    .enableSassLoader(function(sassOptions) {
        // https://github.com/sass/node-sass#options
        // options.includePaths = [...]
    });
;

A: Have you tried this already?
.enableSassLoader(function(sassOptions) {
    options.includePaths = ['node_modules/foundation-sites/scss'];
});

OR
.enableSassLoader(function(sassOptions) {
   sassOptions.includePaths = ['node_modules/foundation-sites/scss'];
});


text:
Q: Declaring parameters. What is the correct way to declare parameters that will be iterated? I am new to Latex Templates and outputting Rmarkdown
This is what my tex file looks like
\documentclass{article}
\usepackage{eso-pic,graphicx}
\usepackage[top=2cm, bottom=2cm, outer=0cm, inner=0cm]{geometry}
\usepackage[absolute,overlay]{textpos}
\usepackage{fontspec}
% Set Font------------------------------------------------
\setmainfont{Segoe UI Symbol}
% Begin Document
\begin{document}
\begin{textblock*}{5cm}(11.6cm,2cm) % {block width} (coords)
\fontsize{40}{12}\selectfont
 $district_name$
\end{textblock*}
\begin{textblock*}{5cm}(9cm,3cm) % {block width} (coords)
\fontsize{24}{12}\selectfont
  $total_membership$ %Param One
\end{textblock*}
\begin{textblock*}{18.6cm}(1cm,8.0cm) % {block width} (coords)
\fontsize{18}{12}\selectfont
  $lob_one$% Param two
\end{textblock*}
\begin{textblock*}{18.6cm}(1cm,13.0cm) % {block width} (coords)
\fontsize{18}{12}\selectfont
  $lob_two$% Param three
\end{textblock*}
\begin{textblock*}{18.6cm}(1cm,17.5cm) % {block width} (coords)
\fontsize{18}{12}\selectfont
  $lob_three$% Param Four
\end{textblock*}
\begin{textblock*}{18.6cm}(1cm,21cm) % {block width} (coords)
\fontsize{18}{12}\selectfont
  $lob_four$% Param Five
\end{textblock*}

\AddToShipoutPictureBG*{\includegraphics[width=\paperwidth,height=\paperheight]{test.png}};
\end{document}

When I write my yaml in Rmarkdown like this, I get the output I want in PDF.
---
title: "Example"
author: "N N"
date: \today

output:
    pdf_document:
        latex_engine: xelatex
        template: test.tex

district_name: "Bob"
lob_one: "Billy B"
lob_two: "Membership 2"
lob_three: "Membership 3"
lob_four: "Membership 4"

---

Fair enough, but in the end goal is to be able to call this rmarkdown and iterate something like this.
renderMyDocument <- function(region, start) {
  rmarkdown::render("MyDocument.Rmd", params = list(
    district_name = something1,
    lob_one = something2
  ))
}

I tried this setup but I did not get the same output as before, in fact none of the params actually appear.
title: "Example"
author: "N N"
date: \today

output:
    pdf_document:
        latex_engine: xelatex
        template: test.tex
params:
  district_name: "Bob"
  lob_one: "Billy B"
  lob_two: "Membership 2"
  lob_three: "Membership 3"
  lob_four: "Membership 4"

What I'm missing here?


text:
Q: I want to implement progressbar while sending image I want to send the image through socket and while the sending process going on the progress bar must be displayed and it should be updating when the image is being sending but when i tried this code the progressbar is not been displayed and the image is being send.
  try {
        //image send
        client = new Socket(ServerIP,4444);

        File file = new File(path);
        byte[] mybytearray = new byte[(int) file.length()];
        FileInputStream fis = new FileInputStream(file);
        BufferedInputStream bis = new BufferedInputStream(fis);
        bis.read(mybytearray, 0, mybytearray.length);
        OutputStream os = client.getOutputStream();
        DataOutputStream dos = new DataOutputStream(os);
                dos.writeUTF(file.getName());
                    int bytesread=0;

        ProgressDialog pd = new ProgressDialog(c);
        pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        pd.setMessage("Sending...");
        pd.setCancelable(false);
        pd.setProgress(0);
        pd.show();

            while((bytesread=fis.read(mybytearray))>0)
                os.write(mybytearray, 0, mybytearray.length);
                int old_value=pd.getProgress();
                     int new_read=(int)( ((float)file.length()/bytesread));
                int value= new_read+old_value;
                pd.setProgress(value);
                pd.dismiss();
        os.write(mybytearray, 0, mybytearray.length);
        os.flush();
        bis.close();
        fis.close();
        client.close();

    } catch (UnknownHostException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

A: You have to look at AsyncTask for this type of task. try this following code and use for your requirement
public class UploadImage extends AsyncTask<String, String, String> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(ShowFullImageShare.this);
        pDialog.setMessage("Updating to twitter...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();
    }

    @Override
    protected String doInBackground(String... args) {

        // write your code here for sending image
        return null;
    }

    @Override
    protected void onPostExecute(String file_url) {
        pDialog.dismiss();

    }
}

call this AsyncTask like this
new UploadImage().execute();

A: public class UploadImage extends AsyncTask<Void, Integer, Void> {

@Override
protected void onPreExecute() {
    super.onPreExecute();
    pDialog = new ProgressDialog(ShowFullImageShare.this);
    pDialog.setMessage("Sending...");
    pDialog.setIndeterminate(false);
    pDialog.setCancelable(false);
    pDialog.show();
}

@Override
protected Void doInBackground(Void... args) {

while((bytesread=fis.read(mybytearray))>0)
os.write(mybytearray, 0, mybytearray.length);
int old_value=pd.getProgress();
int new_read=(int)( ((float)file.length()/bytesread));
int value= new_read+old_value;
os.write(mybytearray, 0, mybytearray.length);
os.flush();
bis.close();
fis.close();
client.close();

publishProgress(value);
return null;
}

@Override
protected void onProgressUpdate(Integer progress) {
    pDialog.setProgress(progress);

}

@Override
protected void onPostExecute(Void value) {
    pDialog.dismiss();

}
}


text:
Q: what is the best way to update component color/font globally in `materia-ui`? I am using material-ui for my react project and I found material-ui uses makeStyles to create the style object. Then inject the styles object as classes into each component. It seems styles is bind with each component. My question is how I can define some globally used styles like font, color etc. In css / scss, I can define some global variables and I can change them in the css files which will apply to all other components. What is the best way to do that in material-ui styles?
...

const useStyles = makeStyles({
  root: {
    background: 'linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)',
    border: 0,
    borderRadius: 3,
    boxShadow: '0 3px 5px 2px rgba(255, 105, 135, .3)',
    color: 'white',
    height: 48,
    padding: '0 30px',
  },
});

return (
      <div className={classes.root}>
 ...

A: Check the customization of Theme


text:
Q: Manually sending missing values to Amazon Forecast I am trying to use Amazon forecast for the first time.
After reading the documentation, I want to manually fill the missing values in my dataset. I want to make sure that Amazon understands well what I am sending.
My missing values are mainly divided into two categories:

*

*Days when an item was in stock and was not sold (real 0)

*Days when an item was out of stock and was not sold (NaN according to Amazon docs)

So in my dataset, I made this:
+---------+------------+--------+
| item_id | timestamp  | demand |
+---------+------------+--------+
|     299 | 2020-01-01 | 0      |
|     320 | 2020-01-01 | NaN    |
+---------+------------+--------+

Does Amazon is going to understand the string NaN that I've included in the dataset? I can't understand from the documentation if NaN is just a method that Amazon can use to automatically fill missing values or if I can actually include those values in my dataset.
Thank you for your help

A: NaN should not be a string, it should be a true NaN object.  Then be sure to adjust the filling logic, like so:
{
    "AttributeName": "target_value",
    "FeaturizationPipeline": [
         {
             "FeaturizationMethodName": "filling",
             "FeaturizationMethodParameters": {
                 "aggregation": "sum",
                 "middlefill": "nan",
                 "backfill": "nan"
             }
         }
     ]
 }


text:
Q: How to compare stored strings with inputted strings-MIPS I'm writing a program that asks the user which temperature they have and then takes that input and converts and outputs all four temperatures. I need help getting my user's input read-in so that it will work in my branch, beq. I can't get it to recogize the input 'f' as equal to the stored version.
.data
temptype: .asciiz "Enter temperature type i.e. f, c, k, r: "
tempdegree: .asciiz "\n Enter degrees: "
space: .space 2
tempx: .asciiz "Your temperature in celsius is: "
tempc: .asciiz "\nYour temperature in celsius is: "
tempf: .asciiz "\nYour temperature in fahrenheit is: "
tempk: .asciiz "\nYour temperature in kelvin is: "
tempr: .asciiz "\nYour temperature in rankine is: :"
kr: .float 459.67

.globl main

.text
    main:

        li $v0, 4
        la $a0, temptype
        syscall

        li $v0, 8
        la $a0, space
        #li $a1, 2
        move $t0, $a0
        syscall

        li $t1, 102
        #li $t1, 99
        #li $t1, 107
        #li $t1, 114
        syscall

        beq $t0, $t1, fahrenheit
        #beq $t0, $t1, celsius
        #beq $t0, $t1, kelvin
        #beq $t0, $t1, rankine
        syscall

        li $v0,10
        syscall

    fahrenheit:

        li $v0, 4
        la $a0, tempdegree
        syscall

        li $v0, 5
        syscall

        move $t0, $v0

        li $v0, 4
        la $a0, tempf
        syscall

        move $a0, $t0
        li $v0, 1
        syscall

A: MIPS CPU (and none of any other common one) has no "compare strings" instruction, string is not native type of CPU and the instructions deal only with native types, like words and bytes.
"String" is certain amount (either defined somewhere, or using terminator character at end of data) of consecutive characters. What is "one character" depends on used encoding, in your case (MARS simulator, and simple practice of asm programming) you can stick with the old ASCII encoding, where single character is exactly one single byte. (JFYI: with modern SW you will mostly work in UTF8 encoding, like this web page does, where single character can have different amount of bytes, depending on which glyph you encode, which makes programming any string algorithm over UTF8 encoded string lot more fun than your current task. Quite often too much fun.)
Now as the CPU registers are of "word" size, that means they are 32 bits "wide", i.e. they can hold at most 4 ASCII characters at once (4 bytes), so using registers to store whole string would allow only for very sho. str. and_ noth else. You can do that, but it's not practical (except the beq would work, because you can compare word value 0x30303030 = "0000" against 0x31313131 = "1111" with beq).
Thus most of the time while programming in MIPS beginners assembly the "strings" are following pattern: some register contains memory address pointing to the first letter of string (first byte of string), and the very last "character" of string is not any letter, but value zero, the so called "null terminator".
When you want to compare strings then, you create loop, which starts with two pointers (to the two strings = to the two first letters). Load byte from both addresses into some temporary register (i.e. loading first letter of both), compare that, against, if they differ, the strings differ. If equal, check for zero (both strings ended = they are equal). If not zero, advance both addresses by one, so they will point to the next letter, and loop to the beginning.
But in your case the user can enter only single letter, and you want to compare only single letter, so writing whole loop is sort of abundant effort, you can just load that single letter and compare that.
So reading your source from top, these lines will get my comments:
#li $a1, 2

is commented out why? You should use that to limit the syscall (I think without setting anything the default value may be zero, so no input happens). Also you may be interested into syscall(v0=12) "read character" instead of "read string", but I'm not sure how that is presented toward user in MARS (user experience related), but let's stick with service v0=8 "read string" and 2 byte long buffer.
Now after syscall returns (user did enter the letter "f"), the memory at address space will contain two bytes set by syscall: 102, 0.
li $t1, 102

Looks familiar, but difficult to read for other programmer, with MARS assembler you can use also this way of writing that number: li $t1, 'f' - the simple apostrophes tells assembler you want value of single ASCII character ('ab' is error in MARS, only single char can be used, some other assemblers may translate the 'ab' as two byte value)
Next uncommented instruction is:
syscall

And here you are asking for which MARS service? You didn't set any value in v0, nor you need any service, so if you would single step over your code in debugger, this should make no sense to you, if you reason what is going happen with each instruction.
Then comes beq $t0, $t1, fahrenheit.
At that point the t1 is equal to 'f', and t0 is equal to address of first byte of that buffer, also aliased as space symbol during compilation, which is equal to some 32 bit value, probably similar to something like 0x100000c. The values 0x100000c vs 102 certainly doesn't equal, so that beq will never jump to label fahrenheit.
To compare that first letter inside buffer, first fetch its value from memory, like lb $t2, ($t0), that loads byte value from address in t0  (advanced info: lb will sign-extend the 8 bit value to 32 bit value. Basic printable characters of ASCII are all smaller than 128, so you will not need to deal with negative values, but if letter 'f' would encode as 140, using lb to load that value into t2 would produce 32 bit value -116, not 140 ... as I wrote, basic ASCII is only 7 bit, so only positive values, which work as expected, 102 is loaded as 102).
Then you can have more success with beq $t2, $t1, fahrenheit, as now it will compare ASCII character against ASCII character.
You can also use MARS MIPS assembly pseudo instruction beq $t2, 'f', fahrenheit. MARS will compile that as two native instructions:
addi $at, $zero, 102 # 102 = 'f', $at = $1, $zero = $0
beq  $at, $t2, fahrenheit

Saving you some typing, which is good in programming, as long as it makes sense while reading (once you will start to shorten your source code just for the purpose of short writing, you are doing it wrong, in programming the source code is written to be being read, the writing cost is negligible compared to the reading costs). In this case beq $t2, 'f', label looks quite readable to me, so I would prefer that.
And that should be enough to answer both your questions, the explicit one (how to compare strings = in a loop, character by character), and the implicit one (how to compare that single letter from user against 'f').


text:
Q: How to store python script data into Django model I've already written a script that parses JSON data from a particular url and stores them into a list. After that I'm able to pass that as an argument to be displayed in my template.
My end goal is to display a table on the template from this JSON data (of which I have currently included only one parameter), for which I believe I need to pass that list into a Django Model.
def index(request):
    is_cached = ('raw_json' in request.session)
    print(is_cached)

if not is_cached:
    # g = {'starttime': '2014-01-01', 'endtime': '2014-01-02', 'minmagnitude': '5'}
    g=''
    url1 = ul.urlencode(g)
    # print(url1)
    main_api = 'https://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&'
    final_url = main_api + url1
    # print(final_url)
    raw_json = requests.get(final_url).json()
    string_json = json.dumps(raw_json)
    # print(raw_json)
    with open('test.txt', 'w') as file:
        file.write(string_json)

count = raw_json['metadata']['count']
print('Count: ' + str(count))

maglist = []
placelist = []
for cou in range(0, count):
    mag = (raw_json['features'][cou]['properties']['mag'])
    maglist.append(mag)
    # magdict = dict(list(enumerate(maglist)))
    place = (raw_json['features'][cou]['properties']['place'])
    placelist.append(place)
    # placedict = dict(list(enumerate(placelist)))
    # print(placedict)

with open('test2.txt', 'w+') as t1:
    for features in raw_json['features']:
        coordinates = (features['geometry']['coordinates'])
        id = (features['id'])
        t1.write("id: %s \n" % (id))
        t1.write("coordinates: %s \n" % (coordinates))
        # print(singfeature)
        for properties, value in features['properties'].items():
            t1.write("%s : %s \n" % (properties, value))
        # t1.write("\n")
# print (maglist)
args = {'magni': maglist}
print (args)
return render(request, 'earthquake/index.html', args)

The template receives this data with a simple for loop as follows:
{% block content %}
    {% for item in magni %}
        <p>{{ item }}</p>
    {% endfor %}
{% endblock %}

To which the result shows up as follows:

As mentioned previously, I need to display a filterable/sortable table with this parameter (along with other parameters too), so that the end-user may view the data as needed.
I'm quite new to Django.


text:
Q: Initializing shared_ptr member variable, new vs make_shared? When initializing a shared_ptr member variable:
// .h
class Customer
{
public:
  Customer();

private:
  std::shared_ptr<OtherClass> something_;
}

// .cpp
Customer():
  something_(new OtherClass())
{
}

vs.
Customer():
  something_(std::make_shared<OtherClass>())
{
}

Is the make_shared version allowed?  I always seem to see the first version, which is preferred?

A: In this case, using make_shared is not just allowed, but it is better to use it. If you use new, it will allocate memory for your Customer somewhere and then memory for your shared_ptr somewhere else, storing both strong and weak references (for weak pointers and shared pointers). If you use the make_shared you would have only one place in memory with everything and therefore only one new.
I'm not sure that I was really clear, this was the purpose of the GotW #89, read it, it is well explained there.

A: The only times when make_shared is not allowed are:

*

*If you're getting a naked pointer allocated by someone else and storing it in shared_ptr. This is often the case when interfacing with C APIs.

*If the constructor you want to call is not public (make_shared can only call public constructors). This can happen with factory functions, where you want to force users to create the object from the factory.
However, there are ways to get around this. Instead of having a private constructor, have a public constructor. But make the constructor take a type with can only be constructed by those with private access to the class. That way, the only people who can call make_shared with that object type are those with private access to the class.
So yes, you can do this.


text:
Q: Пользователи proftpd в ubuntu Есть ubuntu сервер с про фтпд. В /etc/proftpd/ftpd.passwd есть строчка:    share:$1$2kOvNsNz$ov/E2j033xsusDDYTwZNE.:33:33::/home/username/share:/bin/false.
Мне надо создать нового пользователя на папку, чтобы юзер конектился к ней по фтп.
Я правильно понял, что в этом файле надо прописать нового юзера (новую строчку)?
Что значит каждый пункт, разделенный двоеточием?    юзер:пароль:33:33::путь к домашней папке?
Если да, то есть вопросы:

*

*Пароль - это его хэш, а что за хэш? на мд5 не похоже,как мне вбить пароль?

*Что такое 33? Что они значат?

A: Разобрался по мануалу этому: установка и настройка FTP сервера ProFTPD в Ubuntu. Надо было выполнить эту команду: sudo ftpasswd --passwd --name=user --home=/home/ftp --shell=/bin/false --uid=1003 --file /etc/proftpd/ftpd.passwd
A: 33 - uid, 33 - gid, файлы будут создаваться с таким владельцем. Хэш - это хэш собственно пароля, ftpasswd его сам генерирует.


text:
Q: Perl: Match specific elements from arrays between two files and print desired elements from the file I want to match the elements from arrays between two files. The first file consists of six elements and second file consists of seven elements.
The first six elements in the first file matches with the six elements in the second file.The two lines are identical except for that final element in the second file.
I have to print the entire line from the second file, if the line matches with first file.
First File - errep.txt
 XYZ432345  Ethiopia    2567    89  ABC P   28-Apr-14
 XYZ432345  Poland      2567    98  ABC P   28-Apr-14

Second File - rep.txt
XYZ432345   Ethiopia    2567    89  ABC P   28-Apr-14   No Issue
XYZ432345   Philippines 2467    92  ADC P   28-Apr-14   No Issue

Desired Output
XYZ432345   Ethiopia    2567    89  ABC P   28-Apr-14   No Issue

Below is the code which I am trying
use strict;
use warnings;

open(OUT,"> Final Error Report.txt");

open(IN, "rep.txt");
my @values = <IN>;
close IN;
$flag=0;
$count=0;

open(IN, "errep.txt");
my @verify = <IN>;
close IN;

for my $ver (@verify) {
chomp $ver;
@elements= split("\t",$ver);
 for my $rep (@values) {
 chomp $rep;
 @report = split("\t",$rep);

$newstring1="@elements[0 .. 5]";
$newstring2="@report[0 .. 5]";

if ($newstring1 =~/$newstring2/) {
    ++$count;
    $flag=1;
}

if($flag==1){
$flag=0;
print OUT "$rep\n";
            }
    }
}
print OUT "Total Count:$count";

If any one can improve this code much appreciated. Thanks for suggestions..

A: *

*Logical AND is && not & in Perl (and most languages)

*If you want to test for string equality, use e.g. $code eq $code1 (not $code =~ $code1, which does regex matching)

*Using a nested loop is a slow way of doing things, but it might be fast enough if one or both of your input files is fairly small.  But for it to work, you will need to load all the lines from REPORT into an array before you start.  Currently, on the second iteration of the outer loop, <REPORT> will return undef immediately because you have already read everything from this file.  (Alternatively you could rewind the file pointer with seek().)

*Instead of a nested loop you could either use a hashtable, or sort both inputs -- but only bother with doing this if it takes too long.

A: What do you mean match. The two lines don't entirely match. Do you mean if the first six elements in the first file match the six elements in the second file? Are the lines identical except for that final element in the seventh file?
Whenever you say "I have to find a match", you think first of using hashes. If your files are very large, you need to think about using an external database.
I'm also going to use more modern Perl. This includes use strict and use warnings. This means declaring variables with my. This catches many of the programming errors that you run into.
I create a hash called %file_hash. The key to this hash will be the file with the fields separated by colons instead of spaces. This way, I don't have to worry about space differences between the two files since the fields will be in the same order.
The data of this hash will be the line itself. For example:
$file_hash{XYZ432345:Ethiopia:2567:89:ABC:P:28-Apr-14} =
   "XYZ432345   Ethiopia    2567    89  ABC P   28-Apr-14   No Issue"

Now, if I do the same for the second file, I can see if that key exists in %file_hash. If it does, I know I've seen that line before in File #1, and I'll print out that data.
By using a hash, I only have to go through each file once instead of matching each line against each other. If file #1 contains 100 lines, and file #2 contains 200 lines, I'm going through 300 iterations. In your way, you're looping 100 * 200 times, or 2000 iterations.
use strict;
use warnings;
use autodie;  # Will kill my program if file doens't open
use feature qw(say);

use constant {
    file_1  => 'rep.txt',
    file_2  => 'errep.txt',
};

#
# Open file #1 and build the hash index
#
open my $fh_1, '<', file_1;

my %file_hash;
while ( my $line = <$fh_1> ) {
    chomp $line;
    my $key = substr( $line, 0, 53);
    $key =~ s/\s+/:/g;
    $file_hash{$key} = $line;
}
close $fh_1;

#
# Open file #2 and compare the lines against that hash index
#
open my $fh_2, '<', file_2;
while ( my $line = <$fh_2> ) {
    chomp $line;
    my $key = $line;
    $key =~ s/\s+/:/g;
    if ( $file_hash{$key} ) {
        say "$file_hash{$key};"
    }
}

A: I suggest you use something like this. Note the following

*

*use strict and use warnings, and the declaration of all variables with my

*Meaningful variable names

*Lexical file handles instead of global ones (my $rep_fh instead of INFILE) etc.

*I have copied the contents of rep.txt into the array @rep, to save reopening the file multiple times

*I have left the fields in their arrays, and used the all function from List::Util to check whether all of the first six fields match. There is no need to copy the values to their own scalar variables if you're not using them separately.

#!/usr/bin/perl

use strict;
use warnings;

use List::Util 'all';

open my $rep_fh,  '<', 'rep.txt' or die qq{Unable to open "rep.txt" for input: $!};
my @rep = <$rep_fh>;
chomp @rep;
close $rep_fh;

open my $errep_fh, '<', 'errep.txt' or die qq{Unable to open "errep.txt" for input: $!};

while (my $errep_record = <$errep_fh>) {

  chomp $errep_record;
  my @errep_record = split /\t/, $errep_record;

  for my $rep_record (@rep) {

    my @rep_record = split /\t/, $rep_record;

    if ( all { $rep_record[$_] eq $errep_record[$_] } 0 .. 5 ) {
      print "$rep_record\n";
    }
  }
}


text:
Q: Quitar cifras en conversión de decimal a binario en Python Tengo el siguiente programa que pasa un número a binario.
#34. Plantee e implemente un programa para convertir un número entero a binario.
if __name__=="__main__":
    n=int(input("Introduce el entero positivo que quieras a binario: "))
    cociente=None
    resto=0
    while cociente !=0:
        resto=str(resto)+str((n%2)) #Concatenamos los restos, ya que es el numero en binario
        #Tenemos que convertir los restos a str ya que si no, al ser números, se suman.
        cociente=n//2 #Evaluamos el conciente hasta que sea 0 porque es la condición del bucle
        n=n//2 #Actualizamos el valor de n para volver a hacer la división nuevamente
    print (f'{resto}')

El problema es que siempre me genera un 0 al principio porque tengo declarado resto=0 al principio del código. ¿Hay alguna función de python que permita visualizar un número a partir de la segunda posición?
Introduce el entero positivo que quieras a binario: 25
010011

A: Hay 2 problemas:
(1) Estás inicializando un acumulador tipo cadena en 0, obviamente str(0) será '0' por lo que ese valor será incluído en la cadena.
(2) En la conversión binaria, el primer valor obtenido será el último y viceversa. Para corregirlo solo hay que invertir el orden de esta operación: str(resto) + str((n%2))
Con esas correcciones, el código quedará:
if __name__=="__main__":
    n = int(input("Introduce el entero positivo que quieras a binario: "))
    cociente = None
    resto = ''
    while cociente != 0:
        resto = str(n%2) + resto # Concatenamos los restos, ya que es el numero en binario
        cociente = n // 2 # Evaluamos el cociente hasta ser 0, porque es la condición del bucle
        n = cociente # Actualizamos el valor de n para hacer la división nuevamente
    print (f'{resto}')

Prueba:
Introduce el entero positivo que quieras a binario: 157
10011101


text:
Q: python 2.7 imaplib error I tried to connect to my mail server via imaplib and got an error in constructor:
My code:
import imaplib
imaplib.IMAP4_SSL('my_host.com', 1234)

Error:
Traceback (most recent call last)

/home/username/www/site/<ipython console> in <module>()

/usr/lib/python2.7/imaplib.py in __init__(self, host, port, keyfile, certfile)
   1163             self.keyfile = keyfile
   1164             self.certfile = certfile
-> 1165             IMAP4.__init__(self, host, port)
   1166
   1167

/usr/lib/python2.7/imaplib.py in __init__(self, host, port)
    197             self.state = 'NONAUTH'
    198         else:
--> 199             raise self.error(self.welcome)
    200
    201         typ, dat = self.capability()

error: None

Python recieved response from server and then raise an error, but it's a normal continuation response.
Response from server:
+OK my_host.com POP3 MDaemon 12.5.6 ready <MDAEMON-F201406061147.AA472534MD1387@my_host.com>

What I should do to recieve my mails from my server?

A: Demon point that he using protocol POP3. You are trying to communicate whit him using IMAP protocol. Change lib to poplib or change port to communicate via IMAP protocol(default is 143).


text:
Q: Summarize using dplyr and shiny I currently have an app setup where it lets the user input which variable they want to plot and visualize. I am running into an issue when I am trying to pass off the shiny input variable into summarize.
testData <- plotData %>%
        summarize(means=mean(input$selectedMetric, na.rm=TRUE)) %>%
        summarize(sd=sd(input$selectedMetric, na.rm=TRUE))

The error I get is the following:
Warning in mean.default(input$selectedMetric, na.rm = TRUE) :
argument is not numeric or logical: returning NA

How am I supposed to set it up so that it takes the mean and standard deviation of whatever selected column the user decides?

A: There a few things can go wrong here:

*

*You are not checking for null when using input$selectedMetric

*You improperly using reactives. You should access the reactives by using () at the end as they are functions that return something.
Below Im assuming that your plotData variable isn't a reactive and its a declared object
testData <- reactive({
  if(is.null(input$selectedMetric)){
    return()
  }
  plotData %>%
    summarize(means=mean(input$selectedMetric, na.rm=TRUE)) %>%
    summarize(sd=sd(input$selectedMetric, na.rm=TRUE))
})

testData()

You can access the summary, like so: testData()


text:
Q: Removing PAGELATCH with randomized ID instead of GUID We have two tables which receive 1 million+ insertions per minute. This table is heavily indexed, which also can't be removed to support business requirements. Due to such high volume of insertions, we are seeing PAGELATCH_EX and PAGELATCH_SH. These locks further slowdown insertions.
A commonly accepted solution is to change the identity column to GUID so that insertions are written on random page every time. We can do this but changing IDs will trigger a need for the development cycle of migration scripts so that existing production data can be changed.
I tried another approach which seems to be working well in our load tests. Instead of changing to GUID, We are now generating IDs in a randomized pattern using following logic
SELECT @ModValue = (DATEPART(NANOSECOND, GETDATE()) % 14);
INSERT xxx(id)
SELECT NEXT VALUE FOR Sequence * (@ModValue + IIF(@ModValue IN (0,1,2,3,4,5,6), 100000000000,-100000000000))

It has eliminated PAGELATCH_EX and PAGELATCH_SH locks and our insertions are quite fast now. I also think GUID as PK of such a critical table is less efficient then a bigint ID column.
However, some of team members are sceptical on this as IDs with negative values that too generated on random basis is not a common solution. Also, there is argument that support team may struggle due to large negative IDs. A common habit of writing select * from table order by 1 will need to be changed.
I am wondering what the community's take on this solution. If you could please point any disadvantage of approach suggested, that will be highly appreciated.

A:
However, some of team members are skeptical on this as IDs with negative values that too generated on random basis is not a common solution

You have an uncommon problem, and so uncommon solutions might need to be entertained.

Also, there is argument that support team may struggle due to large negative IDs. A common habit of writing select * from table order by 1 will need to be changed.

Sure. The system as it exists now has a high (but not perfect) correlation between IDs and time. That is, in general a higher ID for a row means that it was created after one with a lower ID. So it's convenient to order by IDs as a stand-in for ordering by time. If that's something that they need to do (i.e. order the data by time), give them a way to do that in the new proposal. Conversely, play out the hypothetical scenario where you're explaining to your CTO why you didn't fix performance on this table for your end users. Would "so that our support personnel don't have to change the way they do things" be an acceptable answer? I know that it wouldn't be for me but maybe the needs of support outweigh the needs of end users in your system. Only you (and your CTO) can answer that question.


text:
Q: How kerberos authentication works? I've tried to figure out how kerberos authentication works, the information which I found was always missing something as if a part of it was taken for granted. I am aware of the process in general but missing some details.
Getting TGT:

*

*First a user should get a TGT (Ticket Granting Tickets) from the KDC - the user sends a request with only it's user name (UPN) and without it's password. Some extra information is given to prevent a resent of the request such as ip address and a timestamp. If preauthentication is required then the time is hashed with the user's password.

*The KDC is sending the user back the following:
A. TGT - with a timestamp, user name, ip address and a session key - the TGT is encrypted with a secret only the KDC knows and therefore cannot be changed by anyone.
B. Session key for the user and the KDC to be used in later communication.
Those things are encrypted using the users password (a basic shared secret amongst the KDC and the user). In case a preauthentication was used the server will check if the timestamp was valid before sending the information back.

*The users receive the information and decrypt it using it's password - and then stores it in it's memory (kerberos tray).
Getting TGS:

*

*When the user is requested to authenticate itself from a service he sends a request to the KDC for a TGS (Ticket Granting Service), the request contains the TGT, UPN and the SPN (Service Principal Name - say, the URI of a webpage).

*The KDC then decrypts the TGT and validate it's authenticity, that it is corresponds with the UPN, from the same IP address and still valid (the ticket has an effective time period).

*The KDC sends a TGS to the user encrypted with the service password.

*The user presents the TGS to the service - which decrypts it using it's own password.

*The authentication is complete since the service counts on the fact that it's password is only shared between it and the KDC so it trusts that the KDC authenticated the user earlier.
A few questions:

*

*Am I missing something or that's it?

*When does the user and the KDC ever use the session key? At what point? Why is it necessary? Why does the user password isn't enough?

*There should also be a session key between the user and the service (to the best of my knowledge) - when and why is it used (same as the last question)?

*Kerberos has a 5 minute gap limitation between all parties - I understand why keeping the time in sync is important since it is used as something that we encrypt and decrypt so how come any gap is OK? Why 5 minutes?
I'll be glad for any corrections if you have.
Thanks in advance, Tomer

A: 1) that seems pretty thorough, I'm not sure about all the details.
2) The user's password isn't enough because it would have to be shared between two parties, and the only two parties that share it are the KDC and the client. If you're going to send something over the wire, even encrypted, it's better if it doesn't have a long useful life. So the session key is used by the client to request the service ticket (I think). And, the KDC generates service tickets with session keys, so when a client gets a ticket for say an LDAP or HTTP service, the KDC generates a session key. That session key is in the service ticket, and also the service ticket contains an encrypted message to the service providing agent (the LDAP or HTTP server) which also includes the session key. So, now the client and the server both share an ephemeral secret that the KDC told to both of them. This key is used when there is a protocol in place to use it. So perhaps say a telnet server could encrypt traffic over the wire if it's kerberos enabled for example.
4) Including the time, and a 5 minute leeway is a way to ensure that clocks don't have to be exactly synchronized down to the millisecond, you can tolerate any normal levels of network delay or brief outages, and yet you can't replay a request later. It's no good to go get a ticket, have it snooped down the wire by the NSA and then days/weeks/years later after brute-forcing your password or decrypting using fancy mathematical attacks discovered at a later time, they go and use the ticket again. Ensuring that the ticket is recent prevents that kind of issue.
The session key isn't used all the time. For example if you connect to an https website using kerberos authentication, typically you'd use kerberos for the authentication, but the session key is negotiated using standard https methods (ie. SSL/TLS)


text:
Q: How to modify Android app UI via java when I created it using main.xml file? This is my first post here. Have done hundreds of posts, mostly answers, in linuxquestions.org, but nothing here yet.
I'm starting to develop using android SDK 1.2, and struggle to understand something.
I've used a basic source that uses xml to define a UI and gets it displayed using setContentView(R.layout.main);.
Now in my Java program I'd like to add some code to modify some of the objects I defined in my xml file.
I understand Java, the object concept, methods, etc ... but I don't know which exact syntax to use, and which id my object actually is.
My xml code includes:
<EditText android:layout_width="match_parent" android:id="@+id/editText1" android:layout_height="wrap_content" android:text="@string/saisie">
    <requestFocus></requestFocus>
</EditText>

my .java includes:
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.main);
}

My question is: how do I modify the .java code to make the EditText object display "hello" instead of what is statically defined in my strings file?
I know there is not a big practical use in the example code I am doing, but it will help me do lots of other more interesting things.

A: In your onCreate() or another function, add:
 EditText et = (EditText)findViewById(R.id.editText1);
 et.setText("some text");

A: Change to this (delete the android:text=@string/..)
<EditText
 android:layout_width="match_parent"
 android:id="@+id/editText1"
 android:layout_height="wrap_content"
 <requestFocus></requestFocus>
</EditText>

And add the following in onCreate()
 EditText text = (EditText)findViewById(R.id.editText1);
 text.setText("some text");


text:
Q: Match partially or completely type parameter pack I want to check if the type parameter pack are matching partially or completely with another parameter pack.
So far, I'm trying this:
template<typename... Arguments>
struct VariadicArguments
{
    template<typename... AnotherArguments>
    struct IsSame: std::bool_constant<sizeof...(AnotherArguments)==0> {};
};

template<typename Arg, typename... Arguments>
struct VariadicArguments<Arg, Arguments...>
{
    template<typename... Args>
    struct IsSame: std::false_type{};

    template<typename AnotherArg, typename... AnotherArguments>
    struct IsSame<AnotherArg, AnotherArguments...>:
        std::bool_constant<
            std::is_same<Arg, AnotherArg>::value &&
            VariadicArguments<Arguments...>::IsSame<AnotherArguments...>::value> { };

    template<>
    struct IsSame<> : std::true_type{};
};

template<>
struct VariadicArguments<>
{
    template<typename... Args>
    struct IsSame : std::false_type {};

    template<>
    struct IsSame<> : std::true_type {};
};

I predicted that
VariadicArguments<int, float, double>::IsSame<int, float>::value // true because (int, float, double) partially matches (int, float)
VariadicArguments<int, float, double>::IsSame<int, double>::value // false because (int, float, double) doesn't partially matches (int, double) it should be in serial
VariadicArguments<int, float, double>::IsSame<int, float, double>::value // true because they are all same in serial
VariadicArguments<int, float, double>::IsSame<>::value // true because no arguments matches every parameter pack.

But I'm getting some compile-time errors

1>signal.hpp(25): error C2210:
  '_Val': pack expansions cannot be used as arguments to non-packed
  parameters in alias templates
1>signal.hpp(25): note: see
  reference to class template instantiation
  'VariadicArguments::IsSame'
  being compiled 1>d:\dell\source\repos\mimg\mimg-base\signal.hpp(29):
  note: see reference to class template instantiation
  'VariadicArguments' being compiled
1>signal.hpp(25): error C3770:
  'unknown-type': is not a valid base class
1>signal.hpp(25): warning C4346:
  'VariadicArguments::IsSame': dependent name is not a
  type 1>d:\dell\source\repos\mimg\mimg-base\signal.hpp(25): note:
  prefix with 'typename' to indicate a type
1>signal.hpp(25): error C2143:
  syntax error: missing ',' before '::'
1>signal.hpp(25): error C2039:
  'value': is not a member of '`global namespace''
1>signal.hpp(25): error C2143:
  syntax error: missing ',' before '>'
1>signal.hpp(41): error C3769:
  'VariadicArguments': a nested class cannot have the same name as the
  immediately enclosing class
1>signal.hpp(57): error C2953:
  'VariadicArguments<>::VariadicArguments': class
  template has already been defined
1>signal.hpp(16): note: see
  declaration of
  'VariadicArguments<>::VariadicArguments'
1>signal.hpp(67): error C3412:
  'VariadicArguments<>': cannot specialize template in current scope

A: I propose a simpler VariadicArguments (renamed VarArgs to make it shorter)
template <typename...>
struct VarArgs;

template <typename A0, typename ... As>
struct VarArgs<A0, As...>
 {
   template <typename ... Bs>
   struct IsSame  : std::integral_constant<bool, sizeof...(Bs)==0>
    { };

   template <typename ... Bs>
   struct IsSame<A0, Bs...> : VarArgs<As...>::template IsSame<Bs...>
    { };
 };

template <>
struct VarArgs<>
 {
   template <typename ... Bs>
   struct IsSame : std::integral_constant<bool, sizeof...(Bs)==0>
    { };
 };

Now you can write
int main ()
 {
   using ifd = VarArgs<int, float, double>;

   static_assert(  true == ifd::IsSame<int, float>::value, "1!" );
   static_assert( false == ifd::IsSame<int, double>::value, "2!" );
   static_assert(  true == ifd::IsSame<int, float, double>::value, "3!" );
   static_assert(  true == ifd::IsSame<>::value, "4!" );
 }

Observe that using std::integral_constant<bool, BoolValue> instead of std::bool_constant<BoolValue>, this solution works also for C++11 and C++14, not only for C++17.


text:
Q: Send JSON data to PHP SERVER (Localhost to Hosting Site) I'm trying to send a JSON data to Server(Localhost to Hosting Site), unfortunately it does not work.
I have this code which I found on this site while searching for a solution and modified it a bit.
proto.html
This is the button to initiate the function
<button onclick="proto_test();">Test Button</button>

This is the code for the function that I'm having a problem with.
function proto_test() {
var data = {},
data['abc'] = [];
data['abc'].push('some info');
data['abc'].push('some more info');
json_data = JSON.stringify(data);

$.post("proto2.php", {'updateValues': json_data}, function(data) {
alert(data);
});

}

proto2.php
Here is the code for the php file which that I'm echoing it.
<?php
echo $_POST['updateValues'];
?>

This is what it looks like after you clicked the button. It alerts the result.
(LOCALHOST TO LOCALHOST) In other words, I'm using XAMPP.

Then if I changed the url to pass the data. Which I'm passing it to a SERVER (Hosting Site)
It does not work.
$.post("http://www.mysite.com/proto2.php", {'updateValues': json_data}, function(data){
alert(data);
});

Any ideas how to fix this problem? I would be glad if someone helps me.
Thanks in advance.

A: Read the additional note in jQuery.post() API. AJAX requests are subject to the same origin policy. That's why you can't perform ajax post to different domain.
If you have control over the target server, you can enable cross-origin resource sharing. Check out this answer on how to enable CORS. Note: CORS is not supported in all browsers. See CORS browser support.


text:
Q: jQuery Autosearch is not showing fetched data on textbox using codeigniter3 I am working with Codeigniter3 "autosearch" feature...I want to fetch Customer Name with autoserach on a Bootstrap modal...I got the output through Network, but it doesnot show on UI...You can download my output in following link "https://ibb.co/D98gwnP"
This Bootstrap modal I used in jQuery Full Calendar to add an event into the Database
Controller.php:
public function get_customer()
{
    if(isset($_GET['term']))
    {
        $result = $this->Calendar_model->search_customer($_GET['term']);
        if(count($result)>0)
        {
            foreach($result as $row)
                $arr_result[]=$row;

        }
        echo json_encode($arr_result);
    }
}

Model.php:
 public function search_customer($customer)
 {
    $MainDB = $this->load->database('default', TRUE);

    $MainDB->select('Name');
    $MainDB->where('IsCustomer','Y');
    $MainDB->like('Name', $customer, 'both');
    $MainDB->order_by('Name','Asc');
    $MainDB->limit(10);

    return $MainDB->get('PartyDetail')->result();
   }

View.php:
<input type="text" class="form-control" name="customer" id="customer"
  placeholder="Customer Name">

jQueryCode:
    $('#customer').autocomplete({
      source : "<?php echo site_url('Calendar/get_customer');?>"

    });

I want to populate data into Textbox using "Autosearch" feature from database table... Thank You Sir....

A: try this code
Controller.php
public function get_customer()
{
    if(isset($_GET['term']))
    {
        $result = $this->Calendar_model->search_customer($_GET['term']);
        if(count($result)>0)
        {
            foreach($result as $row)
                $arr_result[]=$row->Name;

             echo json_encode($arr_result);
        }

    }
}


text:
Q: cannot create resource "namespaces" in API group "" This is my ClusterRoleBinding and ClusterRole defination
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: my-namespaces
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: bootstrap
subjects:
- kind: ServiceAccount
  name: executors
  namespace: bootstrap
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: bootstrap
rules:
- apiGroups:
  - '*'
  resources:
  - namespaces
  verbs:
  - get
  - list
  - watch
  - create
  - update
  - patch
  - delete

The service account
[node1 ~]$ kubectl  get sa executors  -n bootstrap -o yaml
apiVersion: v1
kind: ServiceAccount
metadata:
  creationTimestamp: "2022-08-30T19:51:17Z"
  name: executors
  namespace: bootstrap
  resourceVersion: "2209"
  uid: 488f5a2d-c44d-4db1-8d18-11a4f0206952
secrets:
- name: executors-token-2b2wl

The test Config
[node1 ~]$ kubectl create namespace test  --as=executors
Error from server (Forbidden): namespaces is forbidden: User "executors" cannot create resource "namespaces" in API group "" at the cluster scope
[no

[node1 ~]$ kubectl auth can-i create namespace --as=executors
Warning: resource 'namespaces' is not namespace scoped
no

Why I'm getting the above error I did follow the k8's doc of ClusterRoleBinding here

A: Try this and let me know how it goes.
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: my-namespaces
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: bootstrap
subjects:
- kind: ServiceAccount
  name: executors
  namespace: bootstrap
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: bootstrap
rules:
- apiGroups:
  - ''
  resources:
  - namespaces
  verbs:
  - get
  - list
  - watch
  - create
  - update
  - patch
  - delete

I see that in my cluster ClusterRole system:controller:namespace-controller have apiGroups of '' instead of '*' seen in your original ClusterRole.

A: You're not creating clusterrole correctly, please use the following:
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: bootstrap
rules:
  - apiGroups: [""]
    resources:
      - namespaces
    verbs:
      - get
      - list
      - watch
      - create
      - update
      - patch
      - delete

Either use
apiGroups: [""]
OR
- apiGroups:
  - ''

Refer to documentation for more details:
https://kubernetes.io/docs/reference/access-authn-authz/rbac/


text:
Q: How to get a value in a dictionary inside a list in python and further index a value from it I had challenge problem that I got to solve, this is what the data looks like,
data = [{'Clay':[x for x in range(2, 3)]},
        {'George':[x for x in range(7)]},
        {'Buddy':[x for x in range(5, 8)]},
        {'Mark':[x for x in range(7, 11)]},
        {'John':[x for x in range(1, 10)]}]

The Challenge Question was to find a value in data say "Buddy" and further index a number/value from it  say 6, this is what I came up with so far but I got stuck here-
data = [{'Clay':[x for x in range(2, 3)]},
        {'George':[x for x in range(7)]},
        {'Buddy':[x for x in range(5, 8)]},
        {'Mark':[x for x in range(7, 11)]},
        {'John':[x for x in range(1, 10)]}]

def find_usr(usr, val):
    if usr in data:
        print("True")
    else:
        print("False")

find_usr(usr="Buddy", val=6)

It returns False I'm not sure what is going wrong here I did a few searches on a topic but coudn't find a possible solution.Any further debugging details are welcome!

A: If I understood what you asked correctly, I hope this block of code may help:
def find_usr(usr, val):
    for dictionary in data:
        # Checking each dictionary in the list
        if usr in dictionary.keys():
            # Only if the user in the current dictionary
            if val in dictionary[usr]:
                # If the value in the list of the user
                return True
            # If the value is not in the list of the user
            break  # We can stop the loop becuase we have found the user
    return False

By the way, if you are using a list of dictionaries that have only one key and one value, it will be better to use a dictionary instead of a list:
data = {'Clay':[x for x in range(2, 3)],
        'George':[x for x in range(7)],
        'Buddy':[x for x in range(5, 8)],
        'Mark':[x for x in range(7, 11)],
        'John':[x for x in range(1, 10)]}

So the code will be more efficient:
def find_usr(usr, val):
    if usr in data.keys():
        # Only if the user in the current dictionary
        if val in data[usr]:
            # If the value in the list of the user
            return True
        # If the value is not in the list of the user
        break  # We can stop the loop becuase we have found the user
    return False


text:
Q: How to get npm to update without having to re-build? I'm trying to get get it so that I don't have to re-build with npm every time I make changes.  I'm working with Vue.js as my front-end framework, and Python-Flask for my MT.
When I was first working with Vue, I was just messing around and had no MT code.  I had the following in my package.json:
"scripts": {
"dev": "cross-env NODE_ENV=development webpack-dev-server --host 127.0.0.1 --port 5000 --open --hot",
"build": "cross-env NODE_ENV=production webpack --progress --hide-modules"
},

Running:
npm run dev

Would open up a browser window with the hosted Vue application, and would automatically update anytime I made changes.
Now that I've added Flask to the mix, I already have the application hosted with Flask, and I just want my Vue application to auto-refresh as I'm working on it.  Currently, the only thing that works is to build after every change, which is quite tedious.
I don't really know npm very well, and I can't seem to find any documentation on this.  Any help would be much appreciated!


text:
Q: typescript Iterable return type incorrect in "for of" context Here is my code
interface A  {
    Id: string,
    Level: number,
    IA1: string,
    IA2: string,
    IA3: string,
    IA4: string,
}
interface B  {
    Id: string,
    Level: number,
    IA1: string,
    IA2: string,
    IA3: string,
}
interface C {
    Id: string,
    Level: number,
}
type Player = {
    A: Iterable<[A, number]>,
    B: Iterable<[B, number]>,
    C: Iterable<[C, number]>,
}
function find<T extends "A" | "B" | "C">(player: Player, type: T) {
    for(const [obj1] of player[type]){
    }
    let t1 : "A" | "B" | "C" = type as any
    for(const [obj2] of player[t1]){
    }
}

Here's playground link Playground
type obj1 obj1
type obj2 obj2
I thought the type of obj1 should be A | B | C, just like obj2, so where is it wrong?
Just don't understand, i want to know why


text:
Q: cy.origin is not a function error displayed I am trying to use the new origin function and I got this error:

No commands were issued in this test.
TypeError
The following error originated from your test code, not from Cypress.
cy.origin is not a function

The code is really basic:
cy.origin('https://www.acme.com', () => {
    cy.visit('/history/founder')
    cy.get('h1').contains('About our Founder, Marvin Acme')
})

Thanks a lot!

A: Two things to check

*

*have you added experimentalSessionAndOrigin: true to cypress.json?

*are you using Cypres v9.6.0+


text:
Q: Markov chain on letter scale and random text I would like to generate a random text using letter frequencies from a book in a .txt file, so that each new character (string.lowercase + ' ') depends on the previous one.
How do I use Markov chains to do so? Or is it simpler to use 27 arrays with conditional frequencies for each letter?

A:
I would like to generate a random text using letter frequencies from a
  book in a txt file

Consider using collections.Counter to build-up the frequencies when looping over the text file two letters at a time.

How do I use markov chains to do so? Or is it simpler to use 27 arrays
  with conditional frequencies for each letter?

The two statements are equivalent.  The Markov chain is what you're doing.  The 27 arrays with conditional frequencies is how you're doing it.
Here is some dictionary based code to get you started:
from collections import defaultdict, Counter
from itertools import ifilter
from random import choice, randrange

def pairwise(iterable):
    it = iter(iterable)
    last = next(it)
    for curr in it:
        yield last, curr
        last = curr

valid = set('abcdefghijklmnopqrstuvwxyz ')

def valid_pair((last, curr)):
    return last in valid and curr in valid

def make_markov(text):
    markov = defaultdict(Counter)
    lowercased = (c.lower() for c in text)
    for p, q in ifilter(valid_pair, pairwise(lowercased)):
        markov[p][q] += 1
    return markov

def genrandom(model, n):
    curr = choice(list(model))
    for i in xrange(n):
        yield curr
        if curr not in model:   # handle case where there is no known successor
            curr = choice(list(model))
        d = model[curr]
        target = randrange(sum(d.values()))
        cumulative = 0
        for curr, cnt in d.items():
            cumulative += cnt
            if cumulative > target:
                break

model = make_markov('The qui_.ck brown fox')
print ''.join(genrandom(model, 20))

A: If each character only depends on the previous character, you could just compute the probabilities for all 27^2 pairs of characters.