Q: How does the connection manager discard unconsumed connection? I am trying to debug a connection leak issue in my app where the connection manager is using more connections than I would have wanted. One lead I have is the following:
According to Apache HttpClient quick start, if response content is not fully consumed for any reason, the pooling connection manager can not safely reuse the underlying connection and will discard it.
Can anyone point me to the code block that does the checking of unconsumed content in a connection and the discarding of the connection?
// Please note that if response content is not fully consumed the underlying
    // connection cannot be safely re-used and will be shut down and discarded
    // by the connection manager.
    try (CloseableHttpResponse response1 = httpclient.execute(httpGet)) {
        System.out.println(response1.getCode() + " " + response1.getReasonPhrase());
        HttpEntity entity1 = response1.getEntity();
        // do something useful with the response body
        // and ensure it is fully consumed
        EntityUtils.consume(entity1);
    }

A: HttpClient version 4.x and 5.x wrap HTTP response entity with a proxy that releases the underlying connection back to the pool upon reaching the end of the message stream. In all other cases HttpClient assumes the message has not been fully consumed and the underlying connection cannot be re-used.
https://github.com/apache/httpcomponents-client/blob/master/httpclient5/src/main/java/org/apache/hc/client5/http/impl/classic/ResponseEntityProxy.java


Q: Reading data from a BLE smartband failed with app inventor I have a smartband (DS-D6) that communicates values through AT commands with the use of two UUIDs (0000190b-0000-1000-8000-00805f9b34fb and  0000190a-0000-1000-8000-00805f9b34fb). I confirmed these two UUIDs are working using a Serial BLE Terminal App. However, only one of the UUID (0000190b-0000-1000-8000-00805f9b34fb) is working, with app inventor (using latest BLE extension). I don’t know what is going wrong. The device is connected but there is no response to AT commands when I use 0000190a-0000-1000-8000-00805f9b34fb service UUID, while everything works well using the other UUID. I double checked the UUID numbers carefully and also confirmed them using nRFconnect app. I tried to interchange characteristic UUID values, still it didn't work. I don't understand what is causing this behavior that only of the service UUIDs is working with app inventor while both of them are working with BLE serial APP. I attached here the relevant blocks from App inventor. Please note that I am using only of the service UUIDs at a time. More information about the smartband can be found in the following link
https://github.com/fanoush/ds-d6/wiki/Bracelet-commands


Q: Detect faces in python with MTCNN, Opencv and multithreading I'm here because I'm really stuck on my project. At the beginning of my project, it was just a simple face detection that worked pretty well using Python, Opencv, and the MTCNN model. The problem was that the program was pretty slow and I tried to make it faster.  My research then, unfortunately, led me to multithreading and I didn't really know what I was getting into.
In my program, I'm using
1 function: process_frame()
2 variables: frame and frame_buffer
The purpose of this program is therefore to have both image processing and simultaneous playback of video streams in order to gain performance. The problem is that imshow() of my function "process_frame" works very well,  I have pictures with a face detected. However, as soon as I enter my main loop, I have a simple video stream without detection. I was just wondering if my problem would not come from a problem with the synchronization of my threads.
I know that adding multithreading can slow down my program more than anything else but you have to practice to understand ahah
I would be pleased to have a little help because I admit to being stuck for a long time
Below is the code:
    import cv2
    import numpy as np
    from mtcnn import MTCNN
    import threading
    import time
    import tensorflow as tf
    from threading import Lock
    #import pdb

    #pdb.set_trace()
    lock = Lock()
    cap = cv2.VideoCapture(0)
    frame_buffer = []
    frame = None

    def process_frame():
        global frame_buffer, stop_event, lock, frame
        while not stop_event.is_set():
            try:
                lock.acquire()
                if frame is None:
                    print("frame vide")
                    continue
                print ("frame copié avec succes")
                frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
                frame = cv2.resize(frame, (320,240))
                frame = frame_buffer
            except Exception as e:
                print("Une exception a été levée lors du traitement de l'image :", e)
                continue
            finally :
                lock.release()

            try:
                model = MTCNN(min_face_size=10)
                predictions = model.detect_faces(frame)
                print(f"{len(predictions)} visages détectés")
            except Exception as e:
                print("Une exception a été levée lors de la détection des visages :", e)

            try:
                predictions = [prediction for prediction in predictions if prediction['confidence'] > 0.5]
                print(f"{len(predictions)} visages filtrés")
            except Exception as e:
                print("Une exception a été levée lors de la filtration des prédictions :", e)

            for face in predictions:
                try:
                    x, y, w, h = face['box']
                    with lock :
                        cv2.rectangle(frame, (x,y), (x+w, y+h), (255, 0, 0), 2)
                        cv2.imwrite("parth/image_traitee_process_frame.jpg", frame_buffer,     [cv2.IMWRITE_JPEG_QUALITY, 100])
                except Exception as e:
                    print("Une exception a été levée lors de l'ajout de l'annotation du rectangle :", e)
            print ("frame mis a jour avec succes")
            #frame_buffer = frame
            print ("Copie de la liste de frame : ", frame, "dans frame_buffer : ", frame_buffer)
            time.sleep(0.01)

    stop_event = threading.Event()
    thread = threading.Thread(target=process_frame)
    thread.daemon = True
    thread.start()

    start_time = time.perf_counter()
    frame_count = 0

    def stop_thread():
        stop_event.set()
        thread.join()

    while True:

        ret, frame = cap.read()
        if ret:
            frame_buffer = frame.copy()
        else :
            frame = frame_buffer
        frame = frame_buffer
        print ("valeur de frame_buffer après cap.read : ", frame_buffer)
        print (cap.get(cv2.CAP_PROP_FRAME_WIDTH))
        print (cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
        cv2.imwrite("parth/image_traitee_boucle_while.jpg", frame_buffer, [cv2.IMWRITE_JPEG_QUALITY, 50])

        if not ret:
            break
        lock.acquire()
        #frame_buffer = frame
        lock.release()
        frame_count += 1
        elapsed_time = time.perf_counter() - start_time
        if elapsed_time > 1.0:
            print("Frames par seconde : ", frame_count / elapsed_time)
            start_time = time.perf_counter()
            frame_count = 0
        lock.acquire()
        #print(frame_buffer.shape)
        cv2.imshow("Output", frame_buffer)
        lock.release()
        key = cv2.waitKey(1) & 0xFF
        if key == ord("q"):
            break

    cap.release()
    cv2.destroyAllWindows()
    stop_thread()

I tried a lot of things like catching some exceptions with try-except but I have nothing.
with some print statements, ret is set to true, frame in my loop got the position in cap.read() but I don't know where is the problem.


Q: Probability that at least 1 person from a group of N people will be in the top M places out of K total people? Imagine you have a group of N people that each make a submission. There are K submissions total. What is the probability that at least 1 person from the group of N people will be in one of the top M places assuming each place has an equal probability.
For example, a group of 10 people each make a submission. There are 100 submissions total. What the is the probability that at least 1 of the 10 people will be in the top 3 places assuming that each person has an equal probability to be in each place and only 1 person can be in each place.


Q: Когда нужно использовать ООП? Добрый день! Интересно было бы услышать мнения о том, когда нужно использовать ООП в delphi, какие-то примеры. Поделитесь своими соображениями и опытом!
A: Старайтесь почитать документацию по платформе/языку, прежде чем задавать вопросы. Используйте процедурное программирование там, где это уместно, и ООП там, где этого требует сам язык, соглашения о коде и прочее. Если язык позволяет писать код и тем, и другим способом, исходите из опыта других людей или из своего собственного.
ООП - это не панацея, если интересно, то почитайте что-нибудь вроде Почему объектно-ориентированное программирование провалилось?
В любом случае, возможности языка лучше использовать максимально, это поможет в освоении других платформ и языков.
A: Дык, приехали...
Весь VCL в делфях - сплошное ООП. Каждая форма, фрейм, компонент - объекты.
Тоесть, ответ - практически всегда. Кроме консольных приложений, там иногда можно обойтись и без ООП.
A: Я советую использовать ООП, когда программа работает с моделями реальных объектов.
Например, Приемная Комиссия в ВУЗе. Тут можно выделить такие реальные объекты, как абитуриенты и специальности, например. То есть создать 2 класса - абитуриент и специальность.
Ну, это может и не самый подходящий пример, но мне кажется, так проще всего, и понятнее на мой взгляд...


Q: Using Insert Iterators when reading from file can you use Insert Iterators while reading from a file to put the data into STL container?
for example:
FILE *stream;
fread(back_inserter(std::list), sizeof(int), 1, stream);

A: C++ streams are not compatible with C stdio streams.  In other words, you can't use C++ iterators with FILE* or fread.  However, if you use the C++ std::fstream facilities along with istream_iterator, you can use an insertion iterator to insert into a C++ container.
Assuming you have an input file "input.txt" which contains ASCII text numbers separated by whitespace, you can do:
#include <iostream>
#include <fstream>
#include <vector>
#include <iterator>

int main()
{
 std::ifstream ifs("input.txt");
 std::vector<int> vec;
    // read in the numbers from disk
 std::copy(std::istream_iterator<int>(ifs), std::istream_iterator<int>(), std::back_inserter(vec));
    // now output the integers
 std::copy(vec.begin(), vec.end(), std::ostream_iterator<int>(std::cout, "\n"));
}

A: no you can't. And it's fundamentally not-portable to store int like that. Your code will break if you write your file with a big-endian machine and try to read it with a little-endian machine.
But nobody prevents you to. Just define your own forward iterator that reads binary from a istream. You will likely want to stop using FILE and fread/fopen/fclose function as they are from C era.
then you will be able to write :
std::copy_n(your_custom_forward_iterator, count, back_inserter<std::list<....> >);


Q: Get the most value from another column I want to get data historical and  the production. My stored procedure is as follows:
ALTER PROCEDURE [dbo].[pCaRptACInactivas](
                    @CodAsesor      VARCHAR(15),
                    @CodOficina     VARCHAR(4))

    AS
    SET NOCOUNT ON

    DECLARE @CodArbolConta VARCHAR(25)

    IF @CodOficina = '%'
        SET @CodArbolConta = '%'
    ELSE
        SELECT @CodArbolConta = CodArbolConta + '%'     FROM   tClOficinas  WHERE  CodOficina LIKE @CodOficina

    SELECT
        tabACInactivas.CodOficina,
        tabACInactivas.NomOficina,
        tabACInactivas.NomAsesor,
        MAX(tabACInactivas.CodPrestamo) CodPrestamo,
        tabACInactivas.CodAsociacion,
        tabACInactivas.NombreAsociacion,
        MAX(tabACInactivas.Ciclo) AS Ciclo,
        COUNT(DISTINCT tabACInactivas.CodUsuario) AS CantSocias,
        MAX(tabACInactivas.FechaEstado) AS FechaCancelacion--,

    FROM (      SELECT          tClOficinas.CodOficina,             tClOficinas.NomOficina,             tCaClAsesores.CodAsesor,                        tCaClAsesores.NomAsesor,            tCaPrestamos.CodPrestamo,           tCaAsociacion.CodAsociacion,            tCaAsociacion.NombreAsociacion,             tCaPrestamos.Ciclo,             tCaPrCliente.CodUsuario,            tCaPrestamos.FechaEstado,           tClParametros.FechaProceso      FROM            tCaPrestamos WITH(NOLOCK)           INNER JOIN tCaProducto WITH(NOLOCK) ON tCaProducto.CodProducto = tCaPrestamos.CodProducto           INNER JOIN tClOficinas WITH(NOLOCK) ON tClOficinas.CodOficina = tCaPrestamos.CodOficina             INNER JOIN tCaAsociacion WITH(NOLOCK) ON tCaAsociacion.CodAsociacion = tCaPrestamos.CodAsociacion           INNER JOIN tCaPrCliente WITH(NOLOCK) ON tCaPrCliente.CodPrestamo = tCaPrestamos.CodPrestamo             INNER JOIN tClParametros WITH(NOLOCK) ON tClParametros.CodOficina = tClOficinas.CodOficina          INNER JOIN tCaClAsesores ON tCaClAsesores.CodAsesor = tCaAsociacion.CodAsesor       WHERE           tCaPrestamos.Estado = 'CANCELADO'           AND DATEDIFF(DAY, tCaPrestamos.FechaEstado, tClParametros.FechaProceso) > 30            AND NOT EXISTS(SELECT 1
                           FROM tCaPrestamos Pr
                           INNER JOIN tCaPrCliente PrCl ON PrCl.CodPrestamo = Pr.CodPrestamo
                           WHERE Pr.Estado NOT IN ('TRAMITE', 'APROBADO')
                           AND Pr.FechaDesembolso >= tCaPrestamos.FechaEstado
                           AND Pr.CodAsociacion = tCaPrestamos.CodAsociacion
                          )             AND tCaProducto.Tecnologia = 3          AND tCaPrestamos.CodAsesor LIKE @CodAsesor              AND tCaPrestamos.CodOficina IN (SELECT CodOficina FROM tClOficinas WHERE CodArbolConta LIKE @CodArbolConta)

        UNION ALL

        SELECT          tClOficinas.CodOficina,             tClOficinas.NomOficina,             tCaClAsesores.CodAsesor,            tCaClAsesores.NomAsesor,            tCaHPrestamos.CodPrestamo,          tCaAsociacion.CodAsociacion,            tCaAsociacion.NombreAsociacion,             tCaHPrestamos.Ciclo,            tCaHPrCliente.CodUsuario,           tCaHPrestamos.FechaEstado,          tClParametros.FechaProceso          FROM            tCaHPrestamos WITH(NOLOCK)          INNER JOIN tCaProducto WITH(NOLOCK) ON tCaProducto.CodProducto = tCaHPrestamos.CodProducto          INNER JOIN tClOficinas WITH(NOLOCK) ON tClOficinas.CodOficina = tCaHPrestamos.CodOficina            INNER JOIN tCaAsociacion WITH(NOLOCK) ON tCaAsociacion.CodAsociacion = tCaHPrestamos.CodAsociacion          INNER JOIN tCaHPrCliente WITH(NOLOCK) ON tCaHPrCliente.CodPrestamo = tCaHPrestamos.CodPrestamo          INNER JOIN tClParametros WITH(NOLOCK) ON tClParametros.CodOficina = tClOficinas.CodOficina          INNER JOIN tCaClAsesores ON tCaClAsesores.CodAsesor = tCaAsociacion.CodAsesor       WHERE           tCaHPrestamos.Estado = 'CANCELADO'          AND DATEDIFF(DAY, tCaHPrestamos.FechaEstado, tClParametros.FechaProceso) > 30           AND NOT EXISTS(SELECT 1
                           FROM tCaHPrestamos Pr
                           INNER JOIN tCaHPrCliente PrCl ON PrCl.CodPrestamo = Pr.CodPrestamo
                           WHERE Pr.Estado NOT IN ('TRAMITE', 'APROBADO')
                           AND Pr.FechaDesembolso >= tCaHPrestamos.FechaEstado
                           AND Pr.CodAsociacion = tCaHPrestamos.CodAsociacion
                          )             AND tCaProducto.Tecnologia = 3          AND tCaHPrestamos.CodAsesor LIKE @CodAsesor             AND tCaHPrestamos.CodOficina    IN (SELECT CodOficina FROM tClOficinas WHERE CodArbolConta LIKE @CodArbolConta)

    )tabACInactivas
    GROUP BY            tabACInactivas.CodAsociacion,           tabACInactivas.NombreAsociacion,            tabACInactivas.NomOficina,          tabACInactivas.CodOficina,          tabACInactivas.NomAsesor

I want the CantSocias column takes the most value of the Ciclo column, but not working

A: That stored procedure that you have posted up is way too large and blocky to even try to interpret and understand.  So I will go off of your last sentence:

I want the CantSocias column takes the most value of the Ciclo column,
  but not working

Basically if you want to set a specific column to that, you can do something like this:
update YourTable
set CantSocias =
(
  select max(Ciclo)
  from YourOtherTable
)
-- here is where you can put a conditional WHERE clause

A: You may need to create a sub query to get the most value of Ciclo and join back to your query.
An example of what I mean is here:
create table #Product
(
    ID int,
    ProductName varchar(20)
)

insert into #Product(ID, ProductName)
    select 1,'ProductOne'
    union
    select 2,'ProductTwo'

create table #ProductSale
(
    ProductID int,
    Number int,
    SalesRegion varchar(20)
)

insert into #ProductSale(ProductID,Number,SalesRegion)
    select 1,1500,'North'
    union
    select 1, 1200, 'South'
    union
    select 2,2500,'North'
    union
    select 2, 3200, 'South'

--select product sales region with the most sales
select * from #Product p

select ProductId, Max(Number) as Bestsale   from #ProductSale ps group by ProductID

--combining
select
    p.ID,
    p.ProductName,
    tp.Bestsale,
    ps.SalesRegion
from
    #Product p
inner join
    (select ProductId, Max(Number) as Bestsale   from #ProductSale ps group by ProductID) as tp on p.ID = tp.ProductID
inner join
    #ProductSale ps on p.ID = ps.ProductID and tp.Bestsale = ps.Number


Q: How to pair a Windows 10 phone with PC for debugging? I get a code on my phone - but where do I enter it?
I tried connecting by usb, entering the wifi url into my PC's browser ("insecure connection"),...

A: Edited (May2016):
With later Win10 mobile its now possible to debug a phone running Windows 10 Mobile via WIFI.
Follow the guidance here: https://msdn.microsoft.com/en-us/windows/uwp/debug-test-perf/device-portal-mobile


Q: Combo box automatically assigns a value, when not wanted. C# Windows Forms I'm having this issue with ComboBox controls. I select a value for the combo box (Already pre-setted) and it AUTOMATICALLY assigns the same value to another ComboBox next to it. Despite their data source is the same List, I want to select two different values (from that same list) for those two combo boxes.
cmbEmpresas.DataSource = Empresa.listaDeEmpresas;
cmbEmpresas.DisplayMember = "NombreEmpresa"; //This works OK

cmbLlegada.DataSource = Locacion.listaDeLocaciones;
cmbLlegada.DisplayMember = "Ciudad";

//These two represent a starting and arriving location for a trip
//they both have objects of the type "Locación"

cmbSalida.DataSource = Locacion.listaDeLocaciones;
cmbSalida.DisplayMember = "Ciudad";

As it is shown in the previous image, both cmbLlegada and cmbSalida have the same value, I did not want this to happen, I just selected cmbSalida's value and it automatically changed cmbLlegada's value.


Q: Xamarin form: How display activityindicator instantly while in async task?     public async Task ShowIndicator(Func<Task> action)
    {
        actionEnabled = false;
        IndicatorVisibility = true;
        await Task.Delay(5000);
        await action.Invoke();
        IndicatorVisibility = false;
        actionEnabled = true;
    }

I am using the above code to run some Task while showing the indicator by setting the viewmodel properties of the IndicatorVisibility. If I placed the Task.Delay, it will ok but will slow down the code. If I am not placed it, the indicator won't show straightaway coz it will set to second to last indicator visibility to false.
Is it possible to wait the indicator displayed itself before execute the action from the above code?

A: I had the same issue. This has the exact problem, the activity indicator never appers or appears too late:
async void GoDetail(object obj)
{
    Busy = true;

    DetailsViewModel.Initialize(_items, this.SelectedItem);

    await App.Current.MainPage.Navigation.PushAsync(new xxxPage());

    Busy = false;

}

This fixes it, activity indicator appears instantly...:
async void GoDetail(object obj)
{
    Busy = true;
    Device.BeginInvokeOnMainThread(async () =>
    {
        DetailsViewModel.Initialize(_items, this.SelectedItem);

        await App.Current.MainPage.Navigation.PushAsync(new xxxPage());

        Busy = false;
    });

}

A: Try this code
 public Task ShowIndicator(Func<Task> action)
    {
        actionEnabled = false;
        IndicatorVisibility = true;

        Device.BeginInvokeOnMainThread(async () =>
        {
            await action.Invoke();
            IndicatorVisibility = false;
            actionEnabled = true;
        });
    }


Q: Get Join table data as a result of ActiveRecord:Relation I am using rails 5 and oracle as a database. My query look like this..
DefaultConfig.where("role_id = ?","1001").joins(:config_param)

Now i want to get the result object as a config_param object not a default_config..
is it possible to do? Thanks for any help
class DefaultConfig < ApplicationRecord
    self.table_name = "default_config"
    belongs_to :role
    belongs_to :config_param
end

class ConfigParam < ApplicationRecord
    self.table_name = "config_param"
    has_many :default_configs, foreign_key: "param_id"
end

A: ConfigParam.joins(:default_configs).where(default_config: { role_id: 1001 })


Q: Single Click reply to Approval Emails Currently, to approve any salesforce record through email, you have to reply to approval email using Approved/Yes and it gets approve.
I just want to skip the step of writing "Approved/Yes" for approving records. Instead of this, I would like to create a HTML template and provide some button or link into that. When user will click the button or link, then it should approve that salesforce record ( make sure that button or link doesn't open a new salesforce window).
I don't know whether it's achievable or not, but I would like some positive response for this problem. Can anyone please suggest something ?

A: A solution to this would be to publishing a Visualforce page on Salesforce Sites with the call to the API ro approve :
http://www.salesforce.com/us/developer/docs/api/Content/sforce_api_calls_process.htm
The email link would open this page which will have an auto-init action call the approval.
To work without authentication, this could only be done on a custom object.
I hope this helps,
Rup

A: If you mean to not leave the mail message you're looking at and just have some sort of spinner that does all the work in the background; then that is very likely impossible in the most email clients (imagine the security impacts if mails could execute code).
You might be able to make a button in the HTML mail like
Approve

which opens a new email with the YES added to the subject? That saves a little typing, but I actually don't know if you can get hold of that response ID (or even response address) you need...
Otherwise, @altius_rup 's answer should work fine. The page can close itself once the approval is successful.


Q: XAML adding text based on a trigger <dxg:GridControl Grid.Row="1" Grid.Column="0" Grid.ColumnSpan="2" ItemsSource="{Binding Notes}" AutoGenerateColumns="None" ColumnGeneratorTemplateSelector="{StaticResource ColumnTemplateSelector}" dependencyProperties:BestFitColumn.IsEnabled="True" SelectedItem="{Binding SelectedRow}">
            <dxg:GridControl.Columns>
                <dxg:GridColumn FieldName="Priority" Header="{x:Static meta:MetaCommon.Importance}">
                    <dxg:GridColumn.CellTemplate>
                        <DataTemplate>
                            <Image>
                                <Image.Style>
                                    <Style BasedOn="{StaticResource SmallIcon}" TargetType="Image">
                                        <Style.Triggers>
                                            <DataTrigger Binding="{Binding RowData.Row.Priority}" Value="H">
                                                <Setter Property="Source" Value="{x:Static helper:IconHelper.HighImportance}" />
                                                <Setter Property="ToolTip" Value="{x:Static meta:MetaCommon.High}" />
                                            </DataTrigger>
                                    </Style.Triggers>
                                </Style>
                            </Image.Style>
                        </Image>
                    </DataTemplate>

I'm wondering if it's possible to add text in the case where RowData.Row.Priority=H. I can't seem to find any way myself and was wondering if I just missed something or if have to create a work around and do something outside of this statement.

A: You can move your DataTrigger under DataTemplate.Triggers.
Have it set the Visibility for a new TextBlock with the text you want.
<DataTemplate>
<Grid>
<Image/>
<TextBlock Visibility="Collapsed"/>
</Grid>
<DataTemplate.Triggers>
</DataTemplate.Triggers>
</DataTemplate>


Q: Magento 2 Rest Ajax call appends weird number as parameter I implemented a custom Rest Api in my module. Until now everythhing works fine. Jquery Ajax is used to call the api. The JS Code is below:
                $("#p").click(function(){
                      $.ajax({
                         url: "http://127.0.0.1/rest/V1/ajax/l/-100/b/0-300/fo/a/fa/a/p/100-/cat/a",
                         type: "GET",
                         beforeSend: function(xhr){
                               xhr.setRequestHeader('content-type', 'application/json');
                               xhr.setRequestHeader('cache-control', 'no-cache');
                                                                                },
                         success: function(response) { $('#b').html(response);}
                      });
                }); //close onclick

When inspecting the Ajax call in Browser, the following is shown:

Everything works fine and I receive the correct response. But I am asking myself why this number (see red arrow) is automatically appended in the request?
How can I prevent that behavior ?

A: This parameter is added by jQuery to circumvent an Internet Explorer behavior. It is only applied to GET requests and only if cache is false.
Specify cache: true in your ajax request to get rid of it.
See jQuery Docs


Q: Facebook Login Invalid Key Hash After First Login I have added the key hash logged by this call (plus an equals sign) to the settings for my app on the Facebook developer site.
Log.d("MyApp", FacebookSdk.getApplicationSignature(this));
I can repeat the following steps indefinitely. Facebook login works the first time, but fails on all subsequent attempts.
Facebook App (v91.0.0.17.68)
Facebook Android SDK (v4.15.0)

*

*Revoke Facebook Login at https://www.facebook.com/settings?tab=applications

*Login with Facebook

*

*Success

*Login with Facebook

*

*Invalid key hash. The key hash KEY_HASH does not match any stored key hashes. Configure your app key hashes at http://developers.facebook.com/apps/FACEBOOK_APP_ID

The KEY_HASH in the error messages exactly matches one of the key hashes I have saved to the app on the Facebook developer site (at the link listed in the error message).
This only happens when the Facebook app is installed on the device. Facebook login succeeds multiple times in a row using the fallback web login.
I've found this and this question that have a combined single answer of "revoke Facebook Login manually in the app before trying to log in again" which seems like a hacky workaround to me.
Why do you have to revoke Facebook Login before logging in again? With the web fallback login it just says "you've already authorized this app". I would expect the same behavior here.
Edit: This only happens with a debug build. I can login repeatedly with the Facebook app installed if I use a release build (minify disabled just to reduce the changes).

A: Same thing happened to me and I had generated hash from debugkey for debugging in dev enviroment but when building it for Google Play the problem was appearing. You need to generate hash with the certificate and alias that you will sign the app for publishing in Google Play.
Edit: You need to add key hash for both debug key and release key.


Q: Cannot insert the value NULL into column 'X', table 'DB139.dbo.Y'; column does not allow nulls. INSERT fails I'm working on a SQL Server.
I have created the following table:
CREATE TABLE Payment(
    Cust_ID                 CHAR(4),
    Credit_Card_Number      CHAR(16),
    Payment_Number          INTEGER,
    Date                    DATE,
    Fee                     MONEY,
    PRIMARY KEY (Cust_ID, Credit_card_number, Payment_number))

ALTER TABLE Payment
    ADD CONSTRAINT FK_CustPays
        FOREIGN KEY (Cust_ID)
        REFERENCES Customer(Cust_ID) ON DELETE CASCADE
;

ALTER TABLE Payment
    ADD CONSTRAINT FK_CardPayment
        FOREIGN KEY (Credit_Card_Number)
        REFERENCES Credit_card(Credit_card_number) ON DELETE CASCADE
;

As you can probably tell, this is a weak entity. I suspect this is the reason why I can't insert values into it with the INSERT INTO statement, like this:
Insert into Payment(Payment_number,Date,Fee) Values ('918702','2016-08-12',93);

I get the error

Cannot insert the value NULL into column 'Cust_ID', table 'DB139.dbo.Payment'; column does not allow nulls. INSERT fails.

I have successfully inserted data into all of my other tables this way. The only 2 tables that have also been affected by this are the other 2 weak entities (the tables Savings_account and Checking_account). As you can tell, I haven't included any NULL values, so I'm not sure what this error is about.
Here are the 2 other weak entities, for reference (after the "Account" table):
CREATE TABLE  Account(
   Account_number           CHAR(10),
   Balance                  MONEY,
   Name_of_bank             VARCHAR(50),
   Date_of_creation         DATE,
   PRIMARY KEY  (Account_number))

ALTER TABLE Account
    ADD Account_number CHAR(16)
    CONSTRAINT FK_AccountNumberDouble
        FOREIGN KEY (Credit_card_number)
        REFERENCES Credit_card(Credit_card_number) ON DELETE CASCADE
;

ALTER TABLE Account
    ADD Cust_ID CHAR(4)
    CONSTRAINT FK_CustIDTriple
        FOREIGN KEY (Cust_ID)
        REFERENCES Customer(Cust_ID)
;

CREATE TABLE Savings_account(
  Account_number      CHAR(10),
  Interest_rate       INTEGER,
  PRIMARY KEY  (Account_number))

ALTER TABLE Savings_account
    ADD CONSTRAINT FK_SavingsAccount
        FOREIGN KEY (Account_number)
        REFERENCES Account(Account_number)
;

CREATE TABLE Checking_account(
  Account_number        CHAR(10),
  Overdraft_limit       MONEY,
  PRIMARY KEY  (Account_number))

ALTER TABLE Checking_account
    ADD CONSTRAINT FK_CheckingAccount
        FOREIGN KEY (Account_number)
        REFERENCES Account(Account_number)
;

Any help is appreciated.

A: you should be insert value for Cust_ID because it not identity and it primary key..
or you alter Cust_ID to identity


Q: About punctuation: why did the author use double apostrophe in can't? EDUCATION CAN"T WAIT
I have come across the aforementioned title somewhere on a newspaper. Why did the author use double apostrophe  (") in can't...

A: There is no such thing as a "double apostrophe". What you saw was a printer's error, or as Jasper suggests, an attempt at humour.


Q: ThreadStart, field initializer cannot reference the non-static field I am trying to use Threads in my app but i get a error. I searched a solution at MSDN and other forums but i didn't get it.
public class ClickingThread
    {
        private const int MOUSEEVENTF_LEFTDOWN = 0x0002;
        private const int MOUSEEVENTF_LEFTUP = 0x0004;

        [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
        public static extern void mouse_event(int dwFlags, int dx, int dy, int cButtons, int dwExtraInfo);

        public ClickingThread()
        {
        }

        public void MouseClicking()
        {
            int X = Cursor.Position.X;
            int Y = Cursor.Position.Y;
            Thread.Sleep(100);
            mouse_event(MOUSEEVENTF_LEFTUP, X, Y, 0, 0);
            mouse_event(MOUSEEVENTF_LEFTDOWN, X, Y, 0, 0);
        }

        public void Click()
        {
            while (true)
            {
                MouseClicking();
            }
        }
    }

And when i try to use method from this class like this
ClickingThread clicker = new ClickingThread();
Thread click = new Thread(new ThreadStart(clicker.Click));

I get an error (second line -> clicker.Click)"A field initializer cannot reference the non-static field, method etc."
Thanks for advices.


Q: Web Scraping an Image I was thinking about the applications of web scraping (still quite new to it) and came up with a question.  Can you get an image from a page if there are advertisements on the page (like can you avoid advertisements and only look for the correct image content on the page)?  Also, if the image is also a link to another page, can you say go to the next page and get that image (and then go from there until you either reach a certain amount or get all of the images)?  This would mean avoiding going to the advertisements pages.

A: Absolutely. If you use a tool like kimonolabs.com this can be relatively easy. You click the data that you want on the page, so instead of getting all images including advertisements, Kimono uses the CSS selectors of the data you clicked to know which data to scrape.
You can use Kimono to scrape data within links as well. It's actually a very common use. Here's a break-down of that strategy: https://help.kimonolabs.com/hc/en-us/articles/203438300-Source-URLs-to-crawl-from-another-kimono-API
This might be a helpful solution for you, especially if you're not a programmer because it doesn't require coding experience. It's a pretty powerful tool.

A: I think if you are ok with PHP programming then give a look into php simple html dome parser. I have used it a lot and scrapped number of websites.


Q: setBackgroundResource on ImageView return null I'm using ListFragment in my android project. I decided to make a listView, each listview item consist of music frequency imageView. I will try to animate the imageView of music frequency. Each listView has a button called play, once the play is clicked, the music frequency start to animate.
public View onCreateView(LayoutInflater inflater,
         ViewGroup container,  Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.fragmentmusiclist, container, false);
    lv = (ListView) v.findViewById(R.id.list);

    mp = new MediaPlayer();
    mp = null;

    Song s1 = new Song("Love Story",(float) 2.5, onMusicPlayListener);
    Song s2 = new Song("Sad Story",(float) 1.0, onMusicPlayListener);
    Song s3 = new Song("Breakup Story",(float) 3.5, onMusicPlayListener);

    songs = new ArrayList<Song>();
    songs.add(s1);
    songs.add(s2);
    songs.add(s3);

    adapter = new MusicListAdapter(getActivity(),songs);
    setListAdapter(adapter);

    return super.onCreateView(inflater, container, savedInstanceState);
}

OnClickListener onMusicPlayListener = new OnClickListener() {

@Override
public void onClick(View v) {
  final int position = getListView().getPositionForView((LinearLayout)v.getParent());
  animMusicFreq = (ImageView) v.findViewById(R.id.music_anim);
  animMusicFreq.setBackgroundResource(R.anim.anim_music);
  animMusicFreq.post(new Runnable() {

    @Override
    public void run() {
        AnimationDrawable frameAnimation =
            (AnimationDrawable) animMusicFreq.getBackground();
                    frameAnimation.start();
    }

});

A: You are inflating your view inside onCreateView, but you don't pass it to the system. Instead you tell it to inflate its own (you return super). It doesn't make any sense.
You should return your v view like so:
public View onCreateView(LayoutInflater inflater,
                         ViewGroup container,  Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.fragmentmusiclist, container, false);
    // ...
    return v;
}


Q: Silverlight Multithreading; Need to Synchronize? I have a Silverlight app where I've implemented the M-V-VM pattern so my actual UI elements (Views) are separated from the data (Models).  Anyways, at one point after the user has gone and done some selections and possible other input, I'd like to asyncronously go though the model and scan it and compile a list of optiions that the user has changed (different from the default), and eventually update that on the UI as a summary, but that would be a final step.
My question is that if I use a background worker to do this, up until I actually want to do the UI updates, I just want to read current values in one of my models, I don't have to synchronize access to the model right?  I'm not modifying data just reading current values...
There are Lists (ObservableCollections), so I will have to call methods of those collections like "_ABCCollection.GetSelectedItems()" but again I'm just reading, I'm not making changes. Since they are not primitives, will I have to synchronize access to them for just reads, or does that not matter?
I assume I'll have to sychronize my final step as it will cause PropertyChanged events to fire and eventually the Views will request the new data through the bindings...
Thanks in advance for any and all advice.

A: You are correct. You can read from your Model objects and ObservableCollections on a worker thread without having a cross-thread violation. Getting or setting the value of a property on a UI element (more specifically, an object that derives from DispatcherObject) must be done on the UI thread (more specifically, the thread on which the DispatcherObject subclass instance was created). For more info about this, see here.


Q: How to set the background color for specified row in datagridview? I want to set the background color for specified Row in datagridview ..
My need is i have a for loop (i=0;i<10;i++) .Inside this for loop i write the logic
as
if(i=1)
{
//Want to Set Color For This Specified Row..
dataGridView1.SelectedRows[1].DefaultCellStyle.SelectionBackColor = Color.Yellow;
}

if(i=1)
{
//Want to Set Color For This Specified Row..
dataGridView1.SelectedRows[2].DefaultCellStyle.SelectionBackColor = Color.Blue;
}

if(i=1)
{
//Want to Set Color For This Specified Row..
dataGridView1.SelectedRows[3].DefaultCellStyle.SelectionBackColor = Color.Red;
}

But i didn't get the expected o/p . I hope U understand My need . Please Help Me.

A: Instead of using SelectedRows property of the DataGridview you can use as follows
dataGridView1.Rows[1].DefaultCellStyle.ForeColor = Color.Red;

Because SelectedRows property will return rows when row(s) has been selected by the User only, if no rows are selected then your code will throw exception.
EDIT :
For your doubt here am providing a sample code, hope it will help you.
for (int i = 0; i < 10; i++)
 {
   if (dataGridView1.Rows.Count > i)
    {
      if (i == 1)
         dataGridView1.Rows[i].DefaultCellStyle.ForeColor = Color.Red;
      else if (i == 2)
         dataGridView1.Rows[i].DefaultCellStyle.ForeColor = Color.Blue;
      else
         dataGridView1.Rows[i].DefaultCellStyle.ForeColor = Color.Green;
     }
 }

A: You may handle different events of your datagrid and set cell style
Here is example from related question
private void dgvStatus_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
    if (e.ColumnIndex != color.Index)
        return;

    e.CellStyle.BackColor = Color.Red;
}


Q: Spring Boot Mail send email using acces token I have simple mail sending functionality in project which configured in one bean.
@Bean
public JavaMailSender javaMailSender() {
    JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl();

    Properties properties = new Properties();
    properties.setProperty("mail.smtp.auth", "false");
    properties.setProperty("mail.smtp.socketFactory.port", "465");
    properties.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    properties.setProperty("smtp.socketFactory.fallback", "false");
    properties.setProperty("mail.smtp.starttls.enable", "true");
    properties.setProperty("mail.smtp.starttls.required", "true");

    javaMailSender.setHost("smtp.gmail.com");
    javaMailSender.setProtocol("smtp");
    javaMailSender.setUsername("username");
    javaMailSender.setPassword("password");
    javaMailSender.setJavaMailProperties(properties);

    return javaMailSender;
}

and it works great.
Now I want to add functionality for sending emails via accessToken/refreshToken of specific email.
How to do it? What should I extend in my bean or add another bean for sending with token? I couldn't find some example which is full explained. As I understand I should add setFrom() and in setPassword() put accessToken

A: The use of OAUTH2 with JavaMail is explained on the JavaMail project page.
Also, you should fix these common mistakes in your code.


Q: What does "counted with multiplicity" mean in this proposition regarding roots of polynomials? I may have come to understand it as I was writing this; reasoning in the last paragraph

The proposition is as follows:

Given any nonconstant polynomial $f \in \mathbb{F}[x]$, the number of roots of $f$, counted with multiplicity, is at most $\deg(f)$

I'm just getting hung up on the phrase "counted with multiplicity." I believe I understand the rest of the proposition. Using an example of a quadratic polynomial it's obvious to me that, vis a vis the quadratic formula, at most we could find $2$ roots.
What I understand about multiplicity is that, analogous to the prime factorization theorem for the integers, there is a theorem for polynomials that says that any nonconstant polynomial $f \in \mathbb{F}[x]$ can be factored as $$f = ap_{1} \cdots p_{k}$$ Where $a \in \mathbb{F}\ \text{and}\ p_1,...,p_k \in \mathbb{F}[x]$ are monic, irreducible polynomials. The multiplicity of $\alpha$ (a root of $f$) is then the number of times $(x - \alpha)$ shows up in the factorization. In other words it's the number of monic, irreducible polynomials $p_i$ that take the form above. Correct?

With that said, "counted with multiplicity", does that phrase simply suggest that the way we determined that at most  the number of roots can be $n$ for $\deg(f) = n$ is because $(x-\alpha)$ is a linear polynomial and linear polynomials are the lowest degree polynomial that can be irreducible so given the fact that $\deg(p_{1} \cdots p_{k}) = \deg(p_1) + \cdots \deg(p_k)$ the most we could potentially get is $n$ linear polynomials and thus $n$ polynomials of the form $(x-\alpha)$ and hence $n$ roots? Is that correct thinking?

A: When you factor a polynomial over a field each root corresponds to a linear factor. Some linear factors may repeat. So for example if
$$
p(x) = (x - \alpha)^2(x-\beta)q(x)
$$
and $q$ has no roots in the field then $p$ has three roots: $\alpha$ with multiplicity two and $\beta$ (with multiplicity one).
Counting the number of linear factors counts the roots with multiplicity. Clearly the number of linear factors can't exceed the degree of $p$.
Note: that the coefficients come from a field is important. In the ring $\mathbb{Z}_8[x]$ the polynomial $x^2-1$ has four roots, since every odd square is congruent to $1$ modulo $8$.
It factors as
$$
x^2 - 1 = (x-1)(x-7) = (x-3)(x-5).
$$

A: A few different ways of looking at it:

Admitting Copies:
You can think of it as meaning "a polynomial of degree $n$ has $n$ roots, when we allow for copies". For instance, in $\newcommand{\R}{\mathbb{R}}
\newcommand{\F}{\mathbb{F}}
\R[x]$,
$$f(x) = x^2 - 2x + 1 = (x-1)^2$$
We count that $1$ twice, since its linear factor is squared. We could also write
$$f(x) = (x-1)(x-1)$$
for instance. And we know it is a root "twice" since $1$ is still a root of $f(x)/(x-1)$, which leads into another framing...

Multisets:
Consider defining a multiset. (A set will exclude repeat entries, i.e. $\{1,1\}=\{1\}$, but a multiset does not.) Define, given $f \in \F[x]$,
$$
S_f := \left\{ (r,m) \in \F \times \mathbb{Z}_{\ge 1} \,\middle|\, \frac{f(r)}{(x-r)^{m-1} } = 0 \right\}
$$
Then this theorem says that $|S_f| \le \deg(f)$. ($r$ corresponds to roots, and $m$ to multiplicity.)
To see how this works, consider the example
$$f(x) = (x-2)^3 (x-1)^2 (x+1) \in \R[x]$$
Then

*

*$f(x) = 0$ when $x=2$

*$f(x)/(x-2) = 0$ when $x=2$

*$f(x)/(x-2)^2 = 0$ when $x=2$

*$f(x) = 0$ when $x=1$

*$f(x)/(x-1) = 0$ when $x=1$

*$f(x) = 0$ when $x=-1$
but

*

*$f(x)/(x-2)^3 \ne 0$ for $x = 2$

*$f(x)/(x-1)^2 \ne 0$ for $x = 1$

*$f(x)/(x+1) \ne 0$ for $x = -1$
so
$$S_f = \{(2,1),(2,2),(2,3),(1,1),(1,2),(-1,1)\}$$
and $\deg(f) = 6 = |S_f|$.

Factorization:
Perhaps the most explicit: how would we write this out? Given the factorization of $f \in \F[x]$, we can write (for some $a \in \F$ and $r_i \in \F$ the roots with multiplicities $m_i \in \mathbb{Z}$),
$$
f(x) = a \prod_i (x - r_i)^{m_i}
$$
Then the theorem says that $\displaystyle \deg(f) \ge \sum_i m_i$

Addendum: "At Most"
Not every $f \in \F[x]$ need factor into linear factors for given $f,\F$. Sometimes they do (in what we call an algebraically closed field; $\mathbb{C}$ is an example of one). In the above examples, for simplicity, they did, but it might not hold in $\R[x]$ in general. For instance, $f(x) = x^2 + 1$ has zero roots in $\R$, hence the "at most".
Possibly already known to you but I wanted to address the possible contrived-ness of the examples.

The multiplicity of $\alpha$ (a root of $f$) is then the number of times $(x - \alpha)$ shows up in the factorization. In other words it's the number of monic, irreducible polynomials $p_i$ that take the form above. Correct?

Yes, if you only allow powers of $1$ and write
$$f(x) = a \prod_{i=1}^{\deg(f)} (x - r_i) = a \prod_{i=1}^{\deg(f)} p_i(x)$$
(for $r_i$ roots and $p_i(x) := x-r_i$), then the number of times $p_i$ appears in that product is the multiplicity of the root $r_i$. (Though I feel somewhat adverse to this framing since then you have a bunch of root-multiplicity pairs that themselves are not distinct, but I suppose as long as it's not taken as a rigorous definition, all is fine.)

does that phrase simply suggest that the way we determined that at most  the number of roots can be $n$ for $deg(f) = n$ is because $(x-\alpha)$ is a linear polynomial and linear polynomials are the lowest degree polynomial that can be irreducible so given the fact that $deg(p_{1} \cdots p_{k}) = deg(p_1) + \cdots deg(p_k)$ the most we could potentially get is $n$ linear polynomials and thus $n$ polynomials of the form $(x-\alpha)$ and hence $n$ roots?

Depends on how you look at it.
Are you suggesting this might be the proof? If so, I wouldn't be convinced.
As a heuristic? Yeah, sure, I suppose.


Q: Rxjs synchronous? I recently started working on a new project and I have seen this twice now, am I crazy or will never work under any circumstance?
protected get reportView(): any {
    let convertedView = null;
    this.store
      .pipe(select(fromStore.getTransferOrderConverted), rxjs.take(1))
      .subscribe((convertedOrder) => (convertedView = convertedOrder));
    return convertedView;
  }

A:
am I crazy or will never work under any circumstance?

Q) Are you crazy?
A) Yes. Absolutely. That looks bonkers!
Q) Will this never work under any circumstance?
A) Oh, there are times this will work. Some observables are synchronous.
For example, this will always log a 2, so this works as expected.
let convertedView = null;

of(1).pipe(
    map(v => v + 1)
).subscribe(convertedOrder => convertedView = convertedOrder);

console.log(convertedView);

That's because of(1) is a synchronous observable.

This, however, will never work
let convertedView = null;

of(1).pipe(
    delay(0),
    map(v => v + 1)
).subscribe(convertedOrder => convertedView = convertedOrder);

console.log(convertedView);

This will print null. Even though delay(0) conceptually takes no time, it still uses JSs event loop and therefore doesn't get executed until the current code completes.

I think it's best practise to assume all observables are asynchronous. Any code that assume otherwise is likely to be brittle.

A: Your store.subscribe is asynchronous and the rest of your code is not.
You can resolve it with a Promise like the example below.
protected get reportView(): Promise < any > {
    return new Promise((resolve, reject) => {
        this.store
            .pipe(select(fromStore.getTransferOrderConverted), rxjs.take(1))
            .subscribe((convertedOrder) => resolve(convertedOrder));
    });
}

reportView.then(convertedOrder => {
    // do your stuff
});

Also you can get the convertedOrder with Async/Await. But remember, the parent function must be async.
const convertedOrder = await reportView();

A: Convert a stream to synchronous isn't a good ideal.
However, you can use method toPromise of a subject (subscription) for convert it to a promise and await for resolve.

A: Rxjs take(1), first() operator should work absolutely fine
These 2 operators takes the latest value from store selector or BehaviourSubject in synchronous way.


Q: java.util.NoSuchElementException when run with Semaphore I have a Queue containing 10 elements, and I start 100 threads of which 6 may run concurrently, controlled by a Semaphore.  When each thread runs, it takes the head element then adds it to the tail.   But sometimes I get this exception:
java.util.NoSuchElementException
 at java.util.LinkedList.removeFirst(LinkedList.java:270)
 at java.util.LinkedList.remove(LinkedList.java:685)
 at IBM.SemApp$1.run(SemApp.java:27)
 at java.lang.Thread.run(Thread.java:745)

import java.util.LinkedList;
import java.util.Queue;
import java.util.Random;
import java.util.concurrent.Semaphore;

public class SemApp {
public static void main(String[] args) {

    Queue queueB = new LinkedList<>();
    for (int i = 0; i < 10; i++) {
        queueB.add("Object " + i);
    }

    Runnable limitedCall = new Runnable() {
        final Random rand = new Random();
        final Semaphore available = new Semaphore(6);
        int count = 0;

        public void run() {
            int time = rand.nextInt(15);

            try {
                available.acquire();
                String A = (String) queueB.remove();
                queueB.add(A);
                available.release();
                count++;
                System.out.println(count);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    };

    for (int i = 0; i < 100; i++) {
        new Thread(limitedCall).start();
    }
}
}

What am I doing wrong?

A: The problem is that LinkedList is not a thread-safe structure.
Therefore, it should not be shared and modified by multiple concurrent threads as the changes on queueB might not be properly "communicated" to other threads.
Try using a LinkedBlockingQueue instead.
Also, use an AtomicLong for count for the same reason: it is shared in between several threads and you want to avoid race conditions.

A: The fact that up to six threads may be operating on the queue concurrently means that modifications are not safe.


Q: How to pass context to AdMob InterstitialAd in LibGDX Does smb knows how to pass a context to InterstitialAd in LibGDX?
In Android it is simply
InterstitialAd interstitial = new InterstitialAd(this);

My class extended from Screen. or I can intialize it in class extended Game.. Or how to pass the context in this case?
And if smb knows any problem related to this, I'll be very thankfull to any advice!

A: To show ads from inside other classes not from the main activity you need to use a facade. Basically, you make use of a listener to load/display the ads.
Follow this libgdx official tutorial guide. It covers both banner and interstitial ads and it isn't outdated. It uses the new admob via the google play services


Q: Sending mail by unattended upgrade Some people had met some similar problems but nothing solves my problem;
my log file
# tail -f /var/log/unattended-upgrades/unattended-upgrades.log
2018-02-18 13:25:37,656 DEBUG No conffiles in deb
'/var/cache/apt/archives/libgfortran3_4.9.2-10+deb8u1_amd64.deb' (There
is no member named 'conffiles')
2018-02-18 13:25:37,657 DEBUG blacklist: []
2018-02-18 13:25:37,658 DEBUG whitelist: []
2018-02-18 13:25:37,658 DEBUG InstCount=23 DelCount=0 BrokenCount=0
2018-02-18 13:25:37,660 INFO Packages that will be upgraded: cpp-4.9
g++-4.9 gcc-4.9 gcc-4.9-base gcc-4.9-base:i386 libasan1 libatomic1
libcilkrts5 libgcc-4.9-dev libgcc1 libgcc1:i386 libgfortran3 libgomp1
libitm1 liblsan0 libobjc-4.9-dev libobjc4 libquadmath0 libstdc++-4.9-dev
libstdc++6 libstdc++6:i386 libtsan0 libubsan0
2018-02-18 13:25:37,662 INFO Writing dpkg log to '/var/log/unattended-
upgrades/unattended-upgrades-dpkg.log'
2018-02-18 13:27:02,483 INFO All upgrades installed
2018-02-18 13:27:02,485 DEBUG Extracting content from
'/var/log/unattended-upgrades/unattended-upgrades-dpkg.log' since '2018-
02-18 13:25:37.661632'
2018-02-18 13:27:02,511 DEBUG Sending mail to 'xxxyyyy@gmail.com'
2018-02-18 13:27:02,713 DEBUG mail returned: 0

# cat /etc/apt/listchanges.conf
[apt]
frontend=pager
email_address=xxxyyyy@gmail.com
confirm=0
save_seen=/var/lib/apt/listchanges.db
which=news

But the message doesn't go to my email address.
Of course mailx makes the job:
$ echo "Just testing mailx" | mail -s "Yooo woot" xxxyyyy@gmail.com

and I receive my message...
I'm using smtp configuration in my .mailrc file
So what can I do?
thanks for your helps

A: Have you got a system-wide MTA configured for off-site mail delivery? Unattended-upgrades does not run in your name, so it won't read your ~/.mailrc. If you're running with Debian defaults, you probably have Exim installed (check with apt-cache policy exim4). Run dpkg-reconfigure exim4-config to configure remote delivery either via smarthost or by direct MX depending on your connection (basically, transfer the settings from your ~/.mailrc). This will also make your personal SMTP settings unnecessary. Check /var/log/exim4/mainlog* for clues if it still does not work.


Q: What is the best variable scope I should use in servlet operation I am working on workflow management system.
Have one separate java class which contains logic method. One of this is:
public static in get_nxt_stg(int current_stg,int action)
{
}

and define static variable cur_stg and nxt_stg. used in servlet. call this method.
When multiple users log in and do some action these variables get not proper value. It seems like it is shared between all user requests.
What is best way to use variable in servlet, which is remain specific for that request?

A: You should not use static in such a way. If you need to share state, consider using the singleton pattern; but try to avoid static. Unwise use of "static" can turn into a nightmare (for example regarding unit testing).
In addition: it seems that you are a beginner with the Java language. But creating servlets is definitely a "advanced" java topic. I really recommend you to start learning more about Java as preparation for working on servlets. Otherwise the user of your server might have many unpleasant experiences ...

A: What you are doing is wrong. You should use Servlets only for the purpose of reading request parameters and sending responses. What you are trying to do, should be implemented in the Business layer of your application and if you have it implemented with EJBs, then your problem can easily be solved with an Stateful EJB.


Q: Parametric asymptotic test for Poisson Distributed random sample I am exercising for my stochastic course and cannot find an answer to this question.
We suppose the number of car crashes in a city is poisson distributed with parameter $\lambda > 0$. In the last couple of years the mean number of car crashes per year was 15. Last year the mean number of car crashes was only 10. Test if its legal to say the car crash rate sank. Test for the level $\alpha = 0.05$ die zero Hypothesis $H_0 \; : \; \lambda \ge 15$ to the alternative $h_1 : \lambda < 15$ using an asymptotic test.
I tried applying samples from our course script but that didnt work. I am confused about the null hypothesis not being in the form $\lambda = 15$ that means its a composite hypothesis so i tried to estimate to get a test working for all $\lambda \in H_0$, but couldnt come to a good result.
I fruther know by the central strong limit theorem and theorem of slutsky, for any given set of iid random var $(X-1,\dots,X_n)$, $X_i \tilde{ } Poi(\lambda)$ we have
$$\sqrt{n} \frac{\bar{X}_n-\lambda}{\sqrt{X_n}} \to_{d} N(0,1)$$
Please tell me how to do this or hint me the right way.

A: If $X \sim POIS(15),$ then $P(X \le 10) = 0.118.$ Hardly, astonishing.
Not significant at the 5% level.
 ppois(10, 15)
 ## 0.1184644

A normal approximation to Poisson with such a small mean seems
a bit risky. Especially, when there is no need for an approximation.
In any case, if you're (correctly) assuming $\lambda = 15$ for the null
distribution, then $\sigma = \sqrt{15}$
in the denominator; no need to estimate it as $\sqrt{\bar X}.$
Note: If you insist on the normal approximation, then the P-value is about 10%, still not significant.
 pnorm(10, 15, sqrt(15))
 ## 0.0983528

Closer to correct with continuity correction, about 12.3%:
 pnorm(10.5, 15, sqrt(15))
 ## 0.1226391

Below: Blue bars for POIS(15).  Maroon curve: approximating normal density.


Q: Load XML into mxml (Flex AS3) I am trying to display content of an xml file in a textarea (using Flex 4.7).
But I am getting errors and I am not sure why.
This is my code:
<?xml version="1.0" encoding="utf-8"?>
<s:WindowedApplication xmlns:fx="http://ns.adobe.com/mxml/2009"
                       xmlns:s="library://ns.adobe.com/flex/spark"
                       xmlns:mx="library://ns.adobe.com/flex/mx">
    <fx:Declarations>
        <!-- Place non-visual elements (e.g., services, value objects) here -->
    </fx:Declarations>
    <fx:Script>
        <![CDATA[

            var xmlLoader:URLLoader = new URLLoader();
            xmlLoader.addEventListener(Event.COMPLETE, loadXML); // 1st error here
            xmlLoader.load(new URLRequest("books.xml")); // 2nd error here

            var xmlData:XML = new XML();

            function loadXML(e:Event):void{
                xmlData = new XML (e.target.data);
            }
        ]]>
    </fx:Script>

    <s:VGroup>
        <s:TextArea id="txtArea">
        </s:TextArea>
    </s:VGroup>

</s:WindowedApplication>

Here are my errors:

Multiple markets at this line:
-1120: Access of undefined propertyloadXML (1st error)
-1120: Access of undefined property xmlLoader (2nd error)

This is the app structure:

Tester
- src
-- (default package)
--- Tester.mxml
-- books.xml
-- Tester-app.xml

I am not sure what I am doing wrong. Could anyone please get me on the right track?
Thank you!

A: Most of your ActionScript code must go inside a method; and you have code that must be put in a method.  Variable definitions are okay.  Import statements are okay.  I think some directives, such as include are okay. But, other code must be in a method.
This is your annotated code:
<fx:Script>
    <![CDATA[

        // this is a variable definition so it is good
        var xmlLoader:URLLoader = new URLLoader();

        // these two lines are code that executes; so they must be put inside a method; something you did not do.  Comment them out
        //xmlLoader.addEventListener(Event.COMPLETE, loadXML); // 1st error here
        //xmlLoader.load(new URLRequest("books.xml")); // 2nd error here

        // this is a variable definition so it is okay
        var xmlData:XML = new XML();

        // this is a function definition so it is okay
        function loadXML(e:Event):void{
            xmlData = new XML (e.target.data);
        }

        // move your executing code into a method
        public function load():void{
         xmlLoader.addEventListener(Event.COMPLETE, loadXML);
         xmlLoader.load(new URLRequest("books.xml"));
        }
    ]]>
</fx:Script>

I bet that removes your errors.  However, you'll also want to / need to do something to execute that load method.  When you do this depends on how the data is used in your app and the current component.  But, I'd probably add a preinitialize event listener:
<s:WindowedApplication xmlns:fx="http://ns.adobe.com/mxml/2009"
                       xmlns:s="library://ns.adobe.com/flex/spark"
                       xmlns:mx="library://ns.adobe.com/flex/mx"
                       preinitialize="load()">

If preinitialize doesn't work; I'd move the code to the initialize event.  If that doesn't work; I'd go to the creationComplete event.


Q: Where is the tail position in my Clojure loop? Clojure is saying that I can't call recur from a non-tail-position.
Is this not the tail position?
What is the tail position in my loop then?
(loop [i 20]
    (for [x (range 1 21)]
      (if (zero? (rem i x))
        i
        (recur (+ i 1)))))

A: for does not do what you think it does; it is not an imperative loop. It is a list comprehension, or sequence-generator. Therefore, there is not a return or iterate call at its end, so you cannot place recur there.
It would seem you probably do not need either loop or recur in this expression at all; the for is all you need to build a sequence, but it's not clear to me exactly what sequence you wish to build.

A: Further to @JohnBaker's answer, any recur refers to the (nearest) enclosing loop or fn (which may be dressed as a letfn or a defn). There is no such thing in your snippet. So there is nothing for the recur to be in tail position to.
But just replace the for with loop, and you get
(loop [i 20]
  (loop [x 1]
    (if (zero? (rem i x))
      i
      (recur (+ i 1)))))

... which evaluates to 20,no doubt what you intended.
However, the outer loop is never recurred to, so might at well be a let:
(let [i 20]
  (loop [x 1]
    (if (zero? (rem i x))
      i
      (recur (+ i 1)))))

The recur is in tail position because there is nothing left to do in that control path through the loop form: the recur form is the returned value. Both arms of an if have their own tail position.
There are some other disguised ifs that have their own tail position: ors and ands are such.


Q: How can I zero pad a 4 character string in C# I am using the following class method to create a Base36 string from a number:
private const string CharList = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";

public static String Encode(long input) {
    if (input < 0) throw new ArgumentOutOfRangeException("input", input, "input cannot be negative");
        char[] clistarr = CharList.ToCharArray();
        var result = new Stack<char>();
        while (input != 0)
        {
            result.Push(clistarr[input % 36]);
            input /= 36;
        }
        return new string(result.ToArray());
    }

One of the requirements is that the string should always be padded with zero's and should be a maximum of four digits. Can anyone suggest a way that I can code the leading zero's and also limit the function so it will never return more than "ZZZZ" ? Is there some function in C# that can do this. Sorry about the indentation on this code. I am not sure why it's not indenting properly.

A: ZZZZ in base 36 is 1679615 in base 10 (36^4 - 1). So you can simply test if the number is greater than this and reject it.
To pad you can use String.PadLeft.

A: If there are always going to be exactly four digits, it's really easy:
const long MaxBase36Value = (36L * 36L * 36L * 36L) - 1L;

public static string EncodeBase36(long input)
{
    if (input < 0L || input > MaxBase36Value)
    {
        throw new ArgumentOutOfRangeException();
    }
    char[] chars = new char[4];
    chars[3] = CharList[(int) (input % 36)];
    chars[2] = CharList[(int) ((input / 36) % 36)];
    chars[1] = CharList[(int) ((input / (36 * 36)) % 36)];
    chars[0] = CharList[(int) ((input / (36 * 36 * 36)) % 36)];
    return new string(chars);
}

Or using a loop:
const long MaxBase36Value = (36L * 36L * 36L * 36L) - 1L;

public static string EncodeBase36(long input)
{
    if (input < 0L || input > MaxBase36Value)
    {
        throw new ArgumentOutOfRangeException();
    }
    char[] chars = new char[4];
    for (int i = 3; i >= 0; i--)
    {
        chars[i] = CharList[(int) (input % 36)];
        input = input / 36;
    }
    return new string(chars);
}


Q: Protractor test picking up edge browser instead of chrome after reboot I was trying to get a server installed with headless chrome, selenium webdriver and protractor for automating tests.
I setup my environment with these instructions:
# JDK 8
sudo add-apt-repository ppa:openjdk-r/ppa
sudo apt-get update && sudo apt-get install openjdk-8-jdk

# Node JS
curl -sL https://deb.nodesource.com/setup_6.x | sudo bash -
sudo apt-get install -y nodejs

# NPM modules
sudo npm install protractor -g
sudo npm install chromedriver -g

# Google Chrome
echo "deb http://dl.google.com/linux/chrome/deb/ stable main" | sudo tee -a /etc/apt/sources.list
wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | sudo apt-key add -
sudo apt-get update
sudo apt-get -y install libxpm4 libxrender1 libgtk2.0-0 libnss3 libgconf-2-4
sudo apt-get -y install google-chrome-stable
sudo apt-get -y install xvfb gtk2-engines-pixbuf
sudo apt-get -y install xfonts-cyrillic xfonts-100dpi xfonts-75dpi xfonts-base xfonts-scalable
sudo apt-get -y install imagemagick x11-apps
Xvfb -ac :99 -screen 0 1280x1024x16 &
disown $1
export DISPLAY=:99

The issue is that when I run my protractor test for the first time, it works great and the tests run perfectly. But when there is a server reboot or something, I cant seem to run it again. Now this is because when I am do a webdriver-manager start, this is my output:
yeshwanthvshenoy@node-3:~$ sudo webdriver-manager start
[02:59:54] I/start - java -Djava.security.egd=file:///dev/./urandom -Dwebdriver.chrome.driver=/usr/lib/node_modules/protractor/node_modules/webdriver-manager/selenium/chromedriver_2.29 -Dwebdriver.gecko.driver=/usr/lib/node_modules/protractor/node_modules/webdriver-manager/selenium/geckodriver-v0.16.1 -jar /usr/lib/node_modules/protractor/node_modules/webdriver-manager/selenium/selenium-server-standalone-3.4.0.jar -port 4444
[02:59:54] I/start - seleniumProcess.pid: 2239
02:59:54.729 INFO - Selenium build info: version: '3.4.0', revision: 'unknown'
02:59:54.730 INFO - Launching a standalone Selenium Server
2017-06-07 02:59:54.758:INFO::main: Logging initialized @329ms to org.seleniumhq.jetty9.util.log.StdErrLog
02:59:54.832 INFO - Driver provider org.openqa.selenium.ie.InternetExplorerDriver registration is skipped:
 registration capabilities Capabilities [{ensureCleanSession=true, browserName=internet explorer, version=, platform=WINDOWS}] does not match the current platform LINUX
02:59:54.833 INFO - Driver provider org.openqa.selenium.edge.EdgeDriver registration is skipped:
 registration capabilities Capabilities [{browserName=MicrosoftEdge, version=, platform=WINDOWS}] does not match the current platform LINUX
02:59:54.833 INFO - Driver class not found: com.opera.core.systems.OperaDriver
02:59:54.833 INFO - Driver provider com.opera.core.systems.OperaDriver registration is skipped:
Unable to create new instances on this machine.
02:59:54.837 INFO - Driver class not found: com.opera.core.systems.OperaDriver
02:59:54.837 INFO - Driver provider com.opera.core.systems.OperaDriver is not registered
02:59:54.842 INFO - Driver provider org.openqa.selenium.safari.SafariDriver registration is skipped:
 registration capabilities Capabilities [{browserName=safari, version=, platform=MAC}] does not match the current platform LINUX
2017-06-07 02:59:54.892:INFO:osjs.Server:main: jetty-9.4.3.v20170317
2017-06-07 02:59:54.942:INFO:osjsh.ContextHandler:main: Started o.s.j.s.ServletContextHandler@523884b2{/,null,AVAILABLE}
2017-06-07 02:59:54.968:INFO:osjs.AbstractConnector:main: Started ServerConnector@2d653761{HTTP/1.1,[http/1.1]}{0.0.0.0:4444}
2017-06-07 02:59:54.969:INFO:osjs.Server:main: Started @541ms
02:59:54.969 INFO - Selenium Server is up and running

As you can see, it shows the edge browser instead of chrome. Why is that it is being switched back? Is there a way to store this permanently or should I do some other command to specify that I need to use chrome?

A: I see that IE, Edge, Safari, and Opera are skipped (which is to be expected). After starting the WebDriver manager, go to http://localhost:4444/grid/console and check what has been registered.
Check out Setting Up the Browser for Protractor.


Q: Use of XML / XML Attributes in Flex I am new to XML and XML attributes. I have read in some XML documentation that XML can be represented in 2 ways:
Method-1
<?xml version="1.0" encoding="UTF-8"?>
<CATALOG>
 <CD>
        <TITLE>Empire Burlesque</TITLE>
        <ARTIST>Bob Dylan</ARTIST>
        <COUNTRY>USA</COUNTRY>
        <COMPANY>Columbia</COMPANY>
        <PRICE>10.90</PRICE>
        <YEAR>1985</YEAR>
    </CD>
    <CD>
        <TITLE>Hide your heart</TITLE>
        <ARTIST>Bonnie Tyler</ARTIST>
        <COUNTRY>UK</COUNTRY>
        <COMPANY>CBS Records</COMPANY>
        <PRICE>8.90</PRICE>
        <YEAR>1988</YEAR>
    </CD>
</CATALOG>

Method - 2
<?xml version="1.0" encoding="UTF-8"?>
<CATALOG>
    <CD TITLE="Empire Burlesque" ARTIST="Bob Dylan" COUNTRY="USA" COMPANY="Columbia" PRICE="10.90" YEAR="1985"/>
    <CD TITLE="Hide your heart" ARTIST="Bonnie Tyler" COUNTRY="UK" COMPANY="CBS Records" PRICE="8.90" YEAR="1988"/>
 </CATALOG>

But for example when I am using this function to filter where price >=9 and display the data in a grid.
    When using XML Way 1, it works fine, but when I use XML Way 2, the datagrid is empty. Also note that I am using @ Binding at the datafield of each DatagridColumn. My filter function is as such:
private function myFilter(xml:XML):Boolean
            {
                return Number(xml.PRICE) >= 9;
            }

Thanks

A: In way number 2, the price is an atribute and not a subtag so it should be accessed with the @ symobl.
So for way 2, your filter function should be:
private function myFilter(xml:XML):Boolean
            {
                return Number(xml.@PRICE) >= 9;
            }

Notice the @ before PRICE.


Q: Create SQL query for the following tables A database is composed of 4 tables: Table1, table2, table3 and table4.

For a given query Q. If Q = Name_1. I want to select all the fields in tables 1, 2, 3 and 4 and save them in an array using python.

create Tables:
Create Table table1 (ID1 INT PRIMARY KEY NOT NULL, NAME VARCHAR(100));
Create table table2 (ID2 INT PRIMARY KEY NOT NULL, NAME VARCHAR(100),ID_T1 INT, Foreign Key(ID_T1) references table1(ID1));
Create table table3 (ID3 INT PRIMARY KEY NOT NULL, NAME VARCHAR(100),ID_T1 INT, Foreign Key(ID_T1) references table1(ID1));
Create table table4 (ID4 INT PRIMARY KEY NOT NULL, NAME VARCHAR(100),ID_T2 INT, Foreign Key(ID_T2) references table2(ID2));

Insert Data in tables:
insert into table1 (ID1,NAME) values ("1", "john");
insert into table2 (ID2,NAME,ID_T1) values ("1", "math","1");
insert into table3 (ID3,NAME,ID_T1) values ("1", "physics","1");
insert into table4 (ID4,NAME,ID_T2) values ("1", "friend of","1");

A: Here is the query:
 SELECT * FROM Table1 AS t1
    JOIN table3 as t3 ON t1.ID_table1 = t3.ID_table1
    JOIN table2 as t2 ON t1.ID_table1 = t2.ID_table1
    JOIN table4 as t4 ON t2.ID_table2 = t4.ID_table2


Q: How to sticky section using "position: sticky;" css?
*

*I try to sticky full section using css but i cant sticky section

*when i try with div it's working fine but when i try with section it's not working.

*I try to sticky pizza section. i already sticky inner div but not sticky full section.

Please view in full screen.

*

*I try to sticky full section using css but i cant sticky section

*when i try with div it's working fine but when i try with section it's not working.

*I try to sticky pizza section. i already sticky inner div but not sticky full section.

Here is my code

$(document).ready(function(){
  // Add smooth scrolling to all links
  $("a").on('click', function(event) {

    // Make sure this.hash has a value before overriding default behavior
    if (this.hash !== "") {
      // Prevent default anchor click behavior
      event.preventDefault();

      // Store hash
      var hash = this.hash;

      // Using jQuery's animate() method to add smooth page scroll
      // The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area
      $('html, body').animate({
        scrollTop: $(hash).offset().top
      }, 600, function(){

        // Add hash (#) to URL when done scrolling (default click behavior)
        window.location.hash = hash;
      });
    } // End if
  });
});

$(window).scroll(function() {
        var scrollDistance = $(window).scrollTop();

        // Show/hide menu on scroll
        //if (scrollDistance >= 850) {
        //      $('nav').fadeIn("fast");
        //} else {
        //      $('nav').fadeOut("fast");
        //}

        // Assign active class to nav links while scolling
        $('.page-section').each(function(i) {
                if ($(this).position().top <= scrollDistance) {
                        $('.navigation a.active').removeClass('active');
                        $('.navigation a').eq(i).addClass('active');
                }
        });
}).scroll();
.page-section {
          height: 480px;
          width: 100%;
          padding: 3em;
          background: linear-gradient(45deg, #43cea2 10%, #185a9d 90%);
          color: white;
          box-shadow: 0px 3px 10px 0px rgba(0, 0, 0, 0.5);
        }

        .navigation {
          position: sticky;
          width: 100%;
          top: 0px;
          background-color: #999;
          color: #fff;
        }
        .all-menu-item{
            position: sticky;
          width: 100%;
          top: 0px;
        }
        .navigation__link {
          display: block;
          color: #ddd;
          text-decoration: none;
          padding: 1em;
          font-weight: 400;
        }
        .navigation__link:hover {
          background-color: #aaa;
        }
        .navigation__link.active {
          color: white;
          background-color: rgba(0, 0, 0, 0.1);
        }
        .menu-title{
            position: sticky;
            top: 0px;
            padding: 20px;
            background: #fff;
        }

        .menu-fix{
            position: sticky;
            top: 0px;
        }

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet"/>

Content...

Scroll down to see the Navbar stick

Sriracha biodiesel taxidermy organic post-ironic, Intelligentsia salvia mustache 90's code editing brunch. Butcher polaroid VHS art party, hashtag Brooklyn deep v PBR narwhal sustainable mixtape swag wolf squid tote bag. Tote bag cronut semiotics,
                    raw denim deep v taxidermy messenger bag. Tofu YOLO Etsy, direct trade ethical Odd Future jean shorts paleo. Forage Shoreditch tousled aesthetic irony, street art organic Bushwick artisan cliche semiotics ugh synth chillwave meditation.
                    Shabby chic lomo plaid vinyl chambray Vice. Vice sustainable cardigan, Williamsburg master cleanse hella DIY 90's blog.

Ethical Kickstarter PBR asymmetrical lo-fi. Dreamcatcher street art Carles, stumptown gluten-free Kickstarter artisan Wes Anderson wolf pug. Godard sustainable you probably haven't heard of them, vegan farm-to-table Williamsburg slow-carb
                    readymade disrupt deep v. Meggings seitan Wes Anderson semiotics, cliche American Apparel whatever. Helvetica cray plaid, vegan brunch Banksy leggings +1 direct trade. Wayfarers codeply PBR selfies. Banh mi McSweeney's Shoreditch selfies,
                    forage fingerstache food truck occupy YOLO Pitchfork fixie iPhone fanny pack art party Portland.

Ethical Kickstarter PBR asymmetrical lo-fi. Dreamcatcher street art Carles, stumptown gluten-free Kickstarter artisan Wes Anderson wolf pug. Godard sustainable you probably haven't heard of them, vegan farm-to-table Williamsburg slow-carb
                    readymade disrupt deep v. Meggings seitan Wes Anderson semiotics, cliche American Apparel whatever. Helvetica cray plaid, vegan brunch Banksy leggings +1 direct trade. Wayfarers codeply PBR selfies. Banh mi McSweeney's Shoreditch selfies,
                    forage fingerstache food truck occupy YOLO Pitchfork fixie iPhone fanny pack art party Portland.

Pizza section

                    Section 1
                    Section 2
                    Section 3
                    Section 4
                        Section 5
                        Section 6
                        Section 7

Pizza

Smooth scroll, fixed jump menu with active class

Section Two

Section Three

Section Four

Section Five

Section Six

Section Seven

Content...

Scroll down to see the Navbar stick

Sriracha biodiesel taxidermy organic post-ironic, Intelligentsia salvia mustache 90's code editing brunch. Butcher polaroid VHS art party, hashtag Brooklyn deep v PBR narwhal sustainable mixtape swag wolf squid tote bag. Tote bag cronut semiotics,
                        raw denim deep v taxidermy messenger bag. Tofu YOLO Etsy, direct trade ethical Odd Future jean shorts paleo. Forage Shoreditch tousled aesthetic irony, street art organic Bushwick artisan cliche semiotics ugh synth chillwave meditation.
                        Shabby chic lomo plaid vinyl chambray Vice. Vice sustainable cardigan, Williamsburg master cleanse hella DIY 90's blog.

Ethical Kickstarter PBR asymmetrical lo-fi. Dreamcatcher street art Carles, stumptown gluten-free Kickstarter artisan Wes Anderson wolf pug. Godard sustainable you probably haven't heard of them, vegan farm-to-table Williamsburg slow-carb
                        readymade disrupt deep v. Meggings seitan Wes Anderson semiotics, cliche American Apparel whatever. Helvetica cray plaid, vegan brunch Banksy leggings +1 direct trade. Wayfarers codeply PBR selfies. Banh mi McSweeney's Shoreditch selfies,
                        forage fingerstache food truck occupy YOLO Pitchfork fixie iPhone fanny pack art party Portland.

Ethical Kickstarter PBR asymmetrical lo-fi. Dreamcatcher street art Carles, stumptown gluten-free Kickstarter artisan Wes Anderson wolf pug. Godard sustainable you probably haven't heard of them, vegan farm-to-table Williamsburg slow-carb
                        readymade disrupt deep v. Meggings seitan Wes Anderson semiotics, cliche American Apparel whatever. Helvetica cray plaid, vegan brunch Banksy leggings +1 direct trade. Wayfarers codeply PBR selfies. Banh mi McSweeney's Shoreditch selfies,
                        forage fingerstache food truck occupy YOLO Pitchfork fixie iPhone fanny pack art party Portland.

Ethical Kickstarter PBR asymmetrical lo-fi. Dreamcatcher street art Carles, stumptown gluten-free Kickstarter artisan Wes Anderson wolf pug. Godard sustainable you probably haven't heard of them, vegan farm-to-table Williamsburg slow-carb
                        readymade disrupt deep v. Meggings seitan Wes Anderson semiotics, cliche American Apparel whatever. Helvetica cray plaid, vegan brunch Banksy leggings +1 direct trade. Wayfarers codeply PBR selfies. Banh mi McSweeney's Shoreditch selfies,
                        forage fingerstache food truck occupy YOLO Pitchfork fixie iPhone fanny pack art party Portland.

A: add position: relative to parent element
.parent{
position: relative;
}
.child{
position: sticky;
top: 0
}


Q: Как изменять размер TextView в зависимости от его содержимого? Как растягивать textview в зависимости от того сколько там текста?

A: Создайте constraints сверху, справа и слева. Высоту оставьте динамической, отключите функцию Scrolling Enable.

Решение второй ситуации.

*

*Создаете ScrollView (растягивает по всему основному View).

*На ScrollView наносите UIView (дальше по тексту contentView) и так же растягиваете по всему экрану.

*Выставляете ширину contentView она должна быть равна ширине основного вью.

*Раскидываете элементы в contentView. TextView используете так, как я описал выше. Важно чтобы была взаимосвязь всех элементов в contentView по высоте. Так как его высота будет динамическая.


Q: Magento 2 : how make Burger menu in 768px Magento 2 : how make Burger menu in 768px
I want make burger menu in mediaquery 768px, because I have 11 category menu in nav so if already 768px, it's look messy, any body have exprience make burger menu in 768px?


Q: Can superlatives only be used when comparing more than two items? I was reading the comments on an opinion piece in the Guardian where someone claimed that "...offering you the smallest half" was an "ungrammatical oxymoron in the first paragraph".
Seeing what other people were saying, one person gave the reason for the phrase to be ungrammatical as:

Smaller is the comparator of two. Smallest is the superlative of more than two. So no, you can't have the superlative of two. It's the smaller piece. Hope this helps.

Is this really the case? In my native language I wouldn't think twice about using superlatives when comparing two items, and I think I could very easily have done so when writing in English as well.
If this is not a grammatical mistake, is there something else wrong with the phrase? I realise that going to the comment section to learn about proper English is fraught with peril, but it seems that quite a few people agreed with the comment.

A: Although it's not uncommon to hear people using superlatives to compare two things, many people like me consider it bad grammar and it makes us wince, so you should avoid it. Nobody will think you've made a mistake if you use the comparative.
From this Google Ngrams graph, you can see that "the smaller half" is overwhelmingly preferred over "the smallest half", and the difference is increasing.

A: There are two points buried in the item you reproduce from Styggron.  I agree with one of them:  if you have divided something into two halves, then by definition they both are equal.  If they are unequal, then they aren't halves.  But honestly, who can be that exact when dividing a piece of pie?  However, I think this point accounts for his use of the word oxymoron.
As for the ungrammatical point, I do not agree:  it's very common in English to use a superlative even when there are only two things.  So referring to the smallest of two pieces is not ungrammatical.  It would be equally acceptable to refer to the smaller of two pieces.


Q: Printing PDF files using VBS I am new to coding with VBS. This is my unfinished code to print documents in a folder containing documents with 3 distinct headers, "DN" "INV" and "PO". I've been searching around for the code/method to print out PDF documents. I tried using the invokeverb "&print" function but it doesn't seem to work. Can someone please teach me how to print it out? Thank you very much :)
"DN" needs to printed out once, " INV" needs to be printed out 6 times, "PO" needs to be printed out 2 times.
P.S. Thank you @kajkrow for solving this same problem using VBA. Reposting as I found out I was using VBS. Previous question can be found here. *EDIT : attached link solves my problem in both VBA and VBS and uses InvokeVerbEx to print files.
'' To set the path to the current folder

set shApp = CreateObject("shell.application")

currentPath = CreateObject("Scripting.FileSystemObject").GetAbsolutePathName(".")

set shFolder = shApp.NameSpace( currentPath )

'' To set the items in the current folder as "files"

set files = shFolder.Items()

''Start of code''

'msgbox("Starting Script")

for each files in files

        ' If name contains "DN" '
        if inStr(files, "DN") then
            'print out 1 time'
        end if
        ' if name contains "INV" '
        if inStr(files, "INV") then
            'print out 6 times'
        end if
        ' if name contains "PO" '
        if inStr(files, "PO") then
            'print out 2 times'
        end if
next
MsgBox("completed")

A: According to documentation (https://www.adobe.com/content/dam/acom/en/devnet/acrobat/pdfs/Acrobat_SDK_developer_faq.pdf) you could send a command to print a file, but there is no parameter for the number of copies.

You can display and print a PDF file with Acrobat and Adobe Reader
  from the command line. These commands are unsupported, but have worked
  for some developers. There is no documentation for these commands
  other than what is listed below.
Note: All examples below use Adobe
  Reader, but apply to Acrobat as well. If you are using Acrobat,
  substitute Acrobat.exe in place of AcroRd32.exe on the command line.
  AcroRd32.exe pathname — Start Adobe Reader and display the file. The
  full path must be provided. This command can accept the following
  options.

/n Start a separate instance of Acrobat or Adobe Reader, even if one is currently open.
/s Suppress the splash screen.
/o Suppress the open file dialog box.
/h Start Acrobat or Adobe Reader in a minimized window.

AcroRd32.exe /p pathname — Start Adobe Reader and display the Print dialog box.
AcroRd32.exe /t path "printername" "drivername" "portname" — Start Adobe Reader
and print a file while suppressing the Print dialog box. The path must be fully specified.
The four parameters of the /t option evaluate to path, printername, drivername, and portname (all
strings).
printername — The name of your printer.
drivername — Your printer driver’s name, as it appears in your printer’s properties.
portname — The printer’s port. portname cannot contain any "/" characters; if it does, output is
routed to the default port for that printer

For multiple copies of each pdf, you could use a loop.
Something like this:
    set shApp = CreateObject("shell.application")

currentPath = CreateObject("Scripting.FileSystemObject").GetAbsolutePathName(".")

set shFolder = shApp.NameSpace( currentPath )

set files = shFolder.Items()

set oWsh = CreateObject ("Wscript.Shell")
dn = 1
inv = 6
po = 2

for each files in files
    msgbox(files)

    if inStr(files, "DN") then
        for x = 1 to dn
          oWsh.run """AcroRd32.exe"" /t /n /h /o /s" &files,,true

        next
    end if

    if inStr(files, "INV") then
        for x = 1 to inv
          oWsh.run """AcroRd32.exe"" /t /n /h /o /s" &files,,true
        next
    end if

    if inStr(files, "PO") then
        for x = 1 to po
          oWsh.run """AcroRd32.exe"" /t /n /h /o /s" &files,,true
        next
    end if

next
MsgBox("completed")

Note: tested only with XPS Document writer


Q: Showing the formal identity $(1-x+x^2)(1-x^2+x^4)(1-x^4+x^8)\cdots =\frac{1}{1+x+x^2}$
How to show this formal identity (or you can assume $|x|<1$)?
$$(1-x+x^2)(1-x^2+x^4)(1-x^4+x^8)\cdots =\frac{1}{1+x+x^2}$$

I can show that the latter is $$=1-x+x^3-x^4+x^6-x^7+\cdots$$ but how to show this is equal to the infinite product. I think it has something to do with residue of the exponent modulo $3$.

A: Notice that $$(1+x^n+x^{2n})(1-x^n+x^{2n}) = 1+x^{2n}+x^{4n}$$

Now if  $p_n$ is product of first $n$ brackets on LHS then $$p_n ={1+x^{2^n}+x^{2^{n+1}}\over 1+x+x^2}$$
Taking $\displaystyle \lim _{n\to \infty}p_n$ for $|x|<1$ we get the desired.

A: Notice that $(1+x+x^2)(1-x+x^2)=(x^2+1)^2-x^2=1+x^2+x^4$. So: multiply both sides by $1+x+x^2$:
$$\begin{array}{rcl}(1+x+x^2)\cdot(\text{LHS})&\equiv&(1+x+x^2)(1-x+x^2)(1-x^2+x^4)(1-x^4+x^8)\cdots\\&=&(1+x^2+x^4)(1-x^2+x^4)(1-x^4+x^8)\cdots\\&=&(1+x^4+x^8)(1-x^4+x^8)\cdots\\&&\vdots\end{array}$$
The second row shows that the formal product on the left has no (nonzero) odd terms. The third row shows that it doesn't even have the terms $x^2, x^6$ etc. i.e. all the (nonzero) terms are of the form $x^{4k}$, then in the next step all the (nonzero) terms will actually be of the form $x^{8k}$ etc. - so by using induction (or otherwise) you can easily see that the formal product does not have any nonzero terms (except for the constant, which is obviously $1$). Thus, this formal product is $1$.


Q: How to show in a custom QGIS form the feature and/or geometry info? I need to show point coordinates on the from dialog used to edit the attributes of a point..
I see that in the formOpen the dialog receives a layerId and a featureId, but no iface object, so how can get a provider to use the selectatId() and reach feature informations?
def formOpen(dialog,layerid,featureid):
...omissis...

(see here for a more detailed explanation of custom qgis forms)

A: never mind.
I was fooled by the function declaration used in the example.
Actually, it should be:
def formOpen(dialog,layer,feature):
    ...omissis...
    geometry = feature.geometry()
    wktString = geometry.exportToWkt()

That is: the function is receiving the ACTUAL object, not it's id.
So I can access the geometry by direct function call.


Q: How can I reset a ComboBox when the underlying list changes? I'm currently working on a WinForms graphical interface in C#. The form has a ComboBox that is displaying the contents of a custom class I wrote. This class implements the IList interface so that it can be used as the DataSource for that ComboBox.
The issue is that when I add or remove items to/from the underlying object, the ComboBox does not visually reflect this.
I have tried reassigning the list to the DataSource property whenever the contents change, but that doesn't seem to make a difference.
Most of the answers on this site that deal with this issue or similar seem to require a number of extra classes, or editing XAML documents, in order to achieve this.
Is there a simpler method to achieving this? If it makes a difference, the ComboBox will not be visible at the point where changes are made to the IList sourcing it. The only idea I've had so far is to possibly delete the ComboBox and replace it with a new one when needed, but I'm not sure if this is possible to do at runtime, and is obviously not very elegant either way.


Q: Override PLIST file for iOS builds using VS2015 TACO to work around CB-10493 [iOS] Missing icon.png I am using VS2015 TACO to build a cordova application using Cordova 6.0 and Cordova-ios 4.0.1.
There is a registered issue CB-10493 [iOS] Missing icon.png
https://issues.apache.org/jira/browse/CB-10493
The work around for the issue requires you to update the PLIST file to remove a particular keyed entry from the PLIST file.  Unfortunately, because of the way that VS2015 TACO rebuilds the Cordova project on build, any manual edits to the files in the platforms folder is overwritten.
Directions on how to update the file was discussed here:
https://taco.visualstudio.com/en-us/docs/configure-app/#VisualAssets
However upon putting the file in place, it seems to be ignored.  I copied the PLIST file in the platforms folder to: res/native/ios/myapp/myapp-Info.plist and removed the requisite entries.  I then removed the platforms folder and rebuilt the application.  This made no impact on the contents of the PLIST file in the platforms folder.
I could rollback versions for Cordova, however as this would involve also rolling back a number of plugins with fixes that I want to keep, I would prefer not to do this.
I would really appreciate if I could get clear working directions on how to implement an effective work-around to removing the offending entries from the PLIST file within a VS2015 TACO project.
Thanks in advance.

A: Okay - discovered that despite the fact that the PLIST file in the platforms folder is not being overwritten, the use of a PLIST file in the native folder is still effective in working around the issue.
Discovered this when syntax errors entered my file and my build broke, despite the platforms copy of the PLIST still being exactly the same as the original.


Q: Compile errors after adding V8 to my project (C2143, C2059, ..) i've recently added Google's V8 to a MSVC2005 project which is also using Qt and i haven't been able to compile it since.
The defines are giving me a lot of problems, for example
in V8's token.h there is
#define T(name, string, precedence) name,
enum Value {
TOKEN_LIST(T, T)
NUM_TOKENS
};

The line TOKEN_LIST(T, T) yields an error C2143 ('}' missing before '{'), also error C2059 (syntax error '{'), also C2334 (token before '{'; visible function text is skipped). This repeats itself a couple of times.
I have searched through SO and through Microsoft's database and tested various things, for example using /clr, which broke Qt. I also used #undef before including the "v8.h" file for possibly existing definitions to be removed.
Can anyone help with this? Is there a standard procedure to fix errors like this?
Thanks.

A: You can find the conflicting macro definitions by searching for differences between the preprocessed code generated for token.h with and without the #include <windows.h>.
For example, for "token.h", the errors occur at the definition of the enum Value so you have to look at the preprocessed definition of that enum in both cases. So with
    #include <windows.h>
    #include <token.h>

you get:
enum Value {
    ...
    INSTANCEOF, , NOT, BIT_NOT, (0x00010000L), TYPEOF, void, BREAK,
    ...
    SWITCH, void, THROW,
    ...
    FUTURE_STRICT_RESERVED_WORD, const, EXPORT,
    ...
};

instead of:
enum Value {
    ...
    INSTANCEOF, IN, NOT, BIT_NOT, DELETE, TYPEOF, VOID, BREAK,
    ...
    SWITCH, THIS, THROW,
    ...
    FUTURE_STRICT_RESERVED_WORD, CONST, EXPORT,
    ...
};

with only #include <token.h>.