text:
Q: Typescript generator functions as paramter I have the following generator function
function* dispatchIncomingMessageImp(msg: string) {
  console.log(`dispatching incoming message = ${msg}`);
  yield put({ type: 'INCOMING_MESSAGE', messge: msg });
}

Now I'm passing this as a parameter to another function which has the following
function process(clientId: string, dispatchIncomingMessage: (msg: string) => void){
   dispatchIncomingMessage('test');
}

Now I'm calling process the following way
process('id1', dispatchIncomingMessageImp)

However the function dispatchIncomingMessageImp does not get invoked, if I remove the generator symbol then it works.


text:
Q: How can i call a dll that import another dll using NSIS system plugin I am newbie of NSIS installer. I gotta say NSIS deployment is awesome . but lately I am encountered a problem.
I am using NSIS script to call let's say A.dll which compiled using Visual C++ and export some C functions. and A.dll import B.dll. So I extract them (A.dll and B.dll) to $PLUGINSDIR at the very beginning of installation.
After that I call System::call to call let's say "test()" of A.dll. but it always return "error". I also did a test removing import of B.dll and "test()" works and returns the value of what I expected.
here is the code:
;extract dll file

InitPluginsDir

SetOutPath $PLUGINSDIR

File "A.dll"

File "B.dll"

...........
;call it
code:
System::Call "$PLUGINSDIR\A::test() i.r0"

$0 return "error"
after removing import of B.dll and re-compile A.dll. test() works fine.
Can anybody explain How can I call a dll that imports another dll using NSIS system plugin? Thanks in advance. sorry for the poor English. hope you guys understand what I mean.

A: The loader cannot find B.dll so LoadLibrary (called by system.dll) on A.dll is going to fail.
You can set the working directory:
Push $outdir ; Save current, not required
SetOutPath $pluginsdir
System::Call "$PLUGINSDIR\A::test() i.r0"
pop $outdir
SetOutPath $outdir ; Restore

or you can load B.dll yourself:
System::Call 'KERNEL32::LoadLibrary(t "$PLUGINSDIR\B.dll")i.s'
System::Call "$PLUGINSDIR\A::test() i.r0"
System::Call 'KERNEL32::FreeLibrary(is)'

redpajama_set_name: RedPajamaStackExchange


text:
Q: Loop in web Table I am new using python and I am trying to get some values from a table in a webpage, I need to get the values in yellow from the web page:

I have this code, it is getting all the values in the "Instruments" column but I don't know how to get the specific values:
body = soup.find_all("tr")
for Rows in body:
        RowValue = Rows.find_all('th')
        if len(RowValue) > 0:
            CellValue = RowValue[0]
            ThisWeekValues.append(CellValue.text)

any suggestion?

A: ids = driver.find_elements_by_xpath('//*[@id]')

if 'Your element id`  in ids:
    Do something

One of the ways could be this, since only id is different.


text:
Q: Set IME caret position in a c# control I have made a text editor control in C#, where I have inherited from Control.
Some of my users use an IME (Input Method Editor) for input, so I would like to add more support for it.
Normally, an IME will pop up where the caret is, but I can't figure out how to tell it where to show up. I assume there is some standard way of doing this, since there are some IME fields in the Control class.

A: I found a solution. The code here did it for me.
http://www.koders.com/csharp/fidEB8980C0605213D81D1D8364B00F09538F1DF83D.aspx


text:
Q: AngularJS ngModelController What is the correct way to check ngModelController validity?
I have a valid controller object inside of a directive. If I log the object to the console from inside the directive I get:
console.log(ctrl)
$dirty: false
$invalid: true
$modelValue: ""
$name: undefined
$pristine: true
$valid: false
$viewValue: ""
...

then, if I ask if( ctrl.$valid === true ) to log the object to the console again, it does with the exact same output.
console.log(ctrl); //ctrl.$valid is false
if(ctrl.$valid == true) {
    console.log(ctrl); //ctrl.$valid is false
}

additionally if I inspect the element I can see the the appropriate ng-invalid class is being applied.
I will try to make a plunkr to demonstrate but I can't imagine I would be able to duplicate this.
Update If I console.log(ctrl.$valid) is prints true. So now I get how it's passing the conditional but not why the object form shows $valid being false.
Also I made a plnkr that shows an example of what I am doing but it does not suffer from the same problem. example

A: Have you tried this:
console.log(JSON.stringify(ctrl));
if(ctrl.$valid == true) {
    console.log(JSON.stringify(ctrl));
}

or
console.log("$valid is ", ctrl.$valid);
if(ctrl.$valid == true) {
    console.log("$valid should be true and is actually ", ctrl.$valid);
}

It could be related to this (old) Chrome bug.  I believe the expected behavior is that when you expand the object in the console you get the value of the object at expansion time, not at log time, so you would need to print the object as a string or clone it when logging.
Edit - Some more details...
If you run this var obj = {a: 1, b: {}}; console.log(obj); obj['a'] = 2; console.log(obj); in the Chrome console you will see this being output:
> Object {a: 1, b: Object}
  a: 2
  b: Object
  __proto__: Object

> Object {a: 2, b: Object}
  a: 2
  b: Object
  __proto__: Object

Edit 2
Hopefully this will answer your question.  It appears that you may be adding a parser to the $parsers array after $setViewValue(...) has been called.  As a result, when your directive is first initialized any validations you have added will not have been executed.  You can manually execute them by calling something like ctrl.$setViewValue(ctrl.$viewValue); after your parser has been added.


text:
Q: open video file with opencv java so there is OpenCV for Java now...!
Can anyone tell me how to open Videofiles with it ?
I tryed and look all over the internet, but found nothing. The documentation of the VideoCapture class is not very helpfull, becaus it gives a C# example and show how to capture from a webcam.
the Q&A of OpenCV doesnt help either, because there is no (public) method to whom you can give a filename string.
BUT it should work as written in the API. But it doesn't
There is however a privte method in the VideoCapture class with a sting parameter.
please answer if have a solution, or even if you have the same problem.
garyee
UPDATE: (May 2017)
since Version 3.0.0 There is a constructor for the VideoCapture class that takes a string argument. So there is a easy solution to this Problem now!

A: To me its a mystery why the so called automatically generated java wrapper for opencv is lacking this functionality. I first created a new VideoCapture class with a VideoCapture(String filename) constructor and called the private native method. This lead to an an unsatisfied link error:
Exception in thread "main" java.lang.UnsatisfiedLinkError:       org.opencv.highgui.VideoCapture.n_VideoCapture(Ljava/lang/String;)J
    at org.opencv.highgui.VideoCapture.n_VideoCapture(Native Method)
    at org.opencv.highgui.VideoCapture.<init>(VideoCapture.java:90)
    at Tester.main(Tester.java:30)

This indicates that the corresponding JNIEXPORT is missing.
Luckily this can be fixed.
Surprisingly the needed c-constructor is already defined in opencv-2.4.6/modules/highgui/include/opencv2/highgui/highgui.cpp
CV_WRAP VideoCapture(const string& filename);

We add the constructor we long to the VideoCapture class in opencv-2.4.6/modules/java/generator/src/java/highgui+VideoCapture.java:
//
// C++: VideoCapture::VideoCapture(const string& filename)
//

// javadoc: VideoCapture::VideoCapture(String filename)
public VideoCapture(String filename)
{
    nativeObj = n_VideoCapture(filename);

    return;
}

The crucial and tricky step was to add the jni export. Especially finding the right method name for the JNICALL proved to be challenging, since the constructor is overloaded and takes a java class as argument. Additionally we need to convert the java sting into a c-string. The rest is copied from the other constructors.
In opencv-2.4.6/modules/java/generator/src/cpp/VideoCapture.cpp we add this new JNIEXPORT:
//
//   VideoCapture::VideoCapture(const string& filename)
//

JNIEXPORT jlong JNICALL Java_org_opencv_highgui_VideoCapture_n_1VideoCapture__Ljava_lang_String_2
(JNIEnv* env, jclass, jstring filename);

JNIEXPORT jlong JNICALL Java_org_opencv_highgui_VideoCapture_n_1VideoCapture__Ljava_lang_String_2
(JNIEnv* env, jclass, jstring filename)
{
    try {
        LOGD("highgui::VideoCapture_n_1VideoCapture__Ljava_lang_String_2()");
        const char* jnamestr = env->GetStringUTFChars(filename, NULL);
        string stdFileName(jnamestr);
        VideoCapture* _retval_ = new VideoCapture( jnamestr );

        return (jlong) _retval_;
    } catch(cv::Exception e) {
        LOGD("highgui::VideoCapture_n_1VideoCapture__Ljava_lang_String_2() catched cv::Exception: %s", e.what());
        jclass je = env->FindClass("org/opencv/core/CvException");
        if(!je) je = env->FindClass("java/lang/Exception");
        env->ThrowNew(je, e.what());
        return 0;
    } catch (...) {
        LOGD("highgui::VideoCapture_n_1VideoCapture__Ljava_lang_String_2() catched unknown exception (...)");
        jclass je = env->FindClass("java/lang/Exception");
        env->ThrowNew(je, "Unknown exception in JNI code {highgui::VideoCapture_n_1VideoCapture__Ljava_lang_String_2()}");
        return 0;
    }
}

Recompile OpenCV and it should work.

A: here is an example :
    public static void main(String[] args) {
    Mat frame = new Mat();
    VideoCapture camera = new VideoCapture("C:/Users/SAAD/Desktop/motion.mp4");
    JFrame jframe = new JFrame("Title");
    jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JLabel vidpanel = new JLabel();
    jframe.setContentPane(vidpanel);
    jframe.setVisible(true);

    while (true) {
        if (camera.read(frame)) {

            ImageIcon image = new ImageIcon(Mat2bufferedImage(frame));
            vidpanel.setIcon(image);
            vidpanel.repaint();

        }
    }
}`

if you are using Windows add C:\opencv\build\x86\vc11\bin to the Path variable

A: If you are using the new version of Java, this is how I got it to work.
import org.opencv.core.*;
import org.opencv.videoio.*;

import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;

import javax.swing.*;public class MainStruct {

public class MainStruct {

static {
    try {
    System.load("C:opencv\\build\\x64\\vc14\\bin\\opencv_ffmpeg320_64.dll");
    } catch (UnsatisfiedLinkError e) {
        System.err.println("Native code library failed to load.\n" + e);
        System.exit(1);
    }
}

public static void main(String[] args)
{
    System.loadLibrary(Core.NATIVE_LIBRARY_NAME);

    //Create new MAT object
    Mat frame = new Mat();

    //Create new VideoCapture object
    VideoCapture camera = new VideoCapture("C:\\**VideoFileLocation**");

    //Create new JFrame object
    JFrame jframe = new JFrame("Video Title);

    //Inform jframe what to do in the event that you close the program
    jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    //Create a new JLabel object vidpanel
    JLabel vidPanel = new JLabel();

    //assign vidPanel to jframe
    jframe.setContentPane(vidPanel);

    //set frame size
    jframe.setSize(2000, 4000);

    //make jframe visible
    jframe.setVisible(true);

    while (true) {
        //If next video frame is available
        if (camera.read(frame)) {
            //Create new image icon object and convert Mat to Buffered Image
            ImageIcon image = new ImageIcon(Mat2BufferedImage(frame));
            //Update the image in the vidPanel
            vidPanel.setIcon(image);
            //Update the vidPanel in the JFrame
            vidPanel.repaint();

        }
    }
}

public static BufferedImage Mat2BufferedImage(Mat m) {
    //Method converts a Mat to a Buffered Image
    int type = BufferedImage.TYPE_BYTE_GRAY;
     if ( m.channels() > 1 ) {
         type = BufferedImage.TYPE_3BYTE_BGR;
     }
     int bufferSize = m.channels()*m.cols()*m.rows();
     byte [] b = new byte[bufferSize];
     m.get(0,0,b); // get all the pixels
     BufferedImage image = new BufferedImage(m.cols(),m.rows(), type);
     final byte[] targetPixels = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();
     System.arraycopy(b, 0, targetPixels, 0, b.length);
     return image;
    }

}

A: Here is how it worked for me.

VideoCapture capture=new VideoCapture();
capture.open("Vid.mp4");
Mat frame=new Mat();

for(;;){
   capture.read(frame); //reads captured frame into the Mat image
   imshow("Display",frame);
   if(cvWaitKey(30) >= 0) break;
}


text:
Q: Why I don't have a /usr/lib/systemd/system folder? I am trying to use systemd for the first time after giving up on supervisord.
Following this documentation for airflow here, my understanding is that I need to move the .service files to /usr/lib/systemd/system, however such directory does not exist in my system (Ubuntu 18.04.2 LTS). Instead I have /usr/lib/systemd/system-environment-generators/.
Should I create this system folder myself or have I made a mistake somewhere which I need to fix otherwise?

A: In Ubuntu the folder that holds the .service files is /lib/systemd/system. This folder is intended to be used by .deb packages.
Best option to place systemd related files which are not provided by a Debian package would be /etc/systemd/system.


text:
Q: Silverlight 3 with WCF Service - I've got a SL3 app trying to connect to a WFC service. Both the app and the service are on different secure servers on the same domain.  The SL3 app lives here:
https://www-r.aetc.af.mil/fm/tools/batsnet/authenticated/modules/blah blah
When the SL app starts, it immediately connects to the service, but when it makes it's first call into the service, I get this exception:
An exception occurred during the operation, making the result invalid.  Check InnerException for exception details.
   at System.ComponentModel.AsyncCompletedEventArgs.RaiseExceptionIfNecessary()
   at FMDashboard2.FMDashSvc3Ref.GetMetricDataCompletedEventArgs.get_Result()
   at FMDashboard2.Objects.DataRetrieval.service_GetMetricDataCompleted(Object sender, GetMetricDataCompletedEventArgs e)
============
Inner exception: An error occurred while trying to make a request to URI 'https://bats.aetc.af.mil/fm/tools/FMDashSvc/FMDash3.svc'. This could be due to attempting to access a service in a cross-domain way without a proper cross-domain policy in place, or a policy that is unsuitable for SOAP services. You may need to contact the owner of the service to publish a cross-domain policy file and to ensure it allows SOAP-related HTTP headers to be sent. This error may also be caused by using internal types in the web service proxy without using the InternalsVisibleToAttribute attribute. Please see the inner exception for more details.
   at System.ServiceModel.AsyncResult.End[TAsyncResult](IAsyncResult result)
   at System.ServiceModel.Channels.ServiceChannel.SendAsyncResult.End(SendAsyncResult result)
   at System.ServiceModel.Channels.ServiceChannel.EndCall(String action, Object[] outs, IAsyncResult result)
   at System.ServiceModel.ClientBase`1.ChannelBase`1.EndInvoke(String methodName, Object[] args, IAsyncResult result)
   at FMDashboard2.FMDashSvc3Ref.FMDash3Client.FMDash3ClientChannel.EndGetMetricData(IAsyncResult result)
   at FMDashboard2.FMDashSvc3Ref.FMDash3Client.FMDashboard2.FMDashSvc3Ref.FMDash3.EndGetMetricData(IAsyncResult result)
   at FMDashboard2.FMDashSvc3Ref.FMDash3Client.OnEndGetMetricData(IAsyncResult result)
   at System.ServiceModel.ClientBase`1.OnAsyncCallCompleted(IAsyncResult result)
============
Inner exception:
   at System.Net.Browser.AsyncHelper.BeginOnUI(SendOrPostCallback beginMethod, Object state)
   at System.Net.Browser.BrowserHttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
   at System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelAsyncRequest.CompleteGetResponse(IAsyncResult result)
============
Inner exception: Security error.
   at System.Net.Browser.BrowserHttpWebRequest.InternalEndGetResponse(IAsyncResult asyncResult)
   at System.Net.Browser.BrowserHttpWebRequest.c__DisplayClass5.b__4(Object sendState)
   at System.Net.Browser.AsyncHelper.c__DisplayClass2.b__0(Object sendState)
Here's my ClientConfig:
<configuration>
    <system.serviceModel>
        <bindings>
            <customBinding>
                <binding name="SecureBinding_FMDashSvc">
                    <binaryMessageEncoding />
                    <httpsTransport maxReceivedMessageSize="2147483647" maxBufferSize="2147483647" />
                </binding>
                <binding name="LocalBinding_FMDashSvc">
                    <binaryMessageEncoding />
                    <httpTransport maxReceivedMessageSize="2147483647" maxBufferSize="2147483647" />
                </binding>
            </customBinding>
        </bindings>

        <client>
            <endpoint address="https://bats.aetc.af.mil/fm/tools/FMDashSvc/FMDash3.svc"
                      binding="customBinding"
                      bindingConfiguration="SecureBinding_FMDashSvc"
                      contract="FMDashSvc3Ref.FMDash3"
                      name="SecureEndPoint_FMDashSvc_GDIT_BATS" />
            <endpoint address="http://localhost:53519/FMDash3.svc"
                      binding="customBinding"
                      bindingConfiguration="LocalBinding_FMDashSvc"
                      contract="FMDashSvc3Ref.FMDash3"
                      name="LocalEndPoint_FMDashSvc" />
        </client>
    </system.serviceModel>
</configuration>
Here's my web config for the service:
<system.serviceModel>
    <behaviors>
        <serviceBehaviors>
            <behavior name="FMDashboardSvc3.StandardBehavior" >
                <serviceMetadata httpsGetEnabled="true" />
                <serviceDebug includeExceptionDetailInFaults="true" />
            </behavior>
        </serviceBehaviors>
    </behaviors>

    <bindings>
        <wsHttpBinding >
            <binding name="secureBinding">
                <security mode="Transport">
                    <transport clientCredentialType="Certificate" />
                </security>
            </binding>
        </wsHttpBinding>
    </bindings>

    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" />

    <services >
        <service name="FMDashboardSvc3.FMDash3" behaviorConfiguration="FMDashboardSvc3.StandardBehavior">
            <endpoint address="/"
                      binding="wsHttpBinding"
                      bindingConfiguration="secureBinding"
                      contract="FMDashboardSvc3.FMDash3"  />
        </service>
    </services>
</system.serviceModel>

And here's my ClientAccessPolicy.xml file:
<?xml version="1.0" encoding="utf-8" ?>
<access-policy>
    <cross-domain-access>
        <policy>
            <allow-from http-request-headers="SOAPAction">
                <domain uri ="http://*" />
                <domain uri ="https://*" />
            </allow-from>
            <grant-to>
                <resource path="/" include-subpaths="true"/>
            </grant-to>
        </policy>

        <policy>
            <allow-from https-request-headers="SOAPAction">
                <domain uri ="http://*" />
                <domain uri ="https://*" />
            </allow-from>
            <grant-to>
                <resource path="/" include-subpaths="true"/>
            </grant-to>
        </policy>
    </cross-domain-access>
</access-policy>

I've been working on this for WEEKS. I've hammer both Codeproject and the MSDN forums, and nobody's been able to come up with a solution for me. Help me, obi-wan-kenobi.

A: I think the problem may be related to the clientCredentialType on your server side. E.g.:
<security mode="Transport">
     <transport clientCredentialType="Certificate" />
</security>

I don't think Silverlight supports this kind of client credential at the transport level.

A: You exposed your service as a Ws Binding which Silverlight does not suppourt. If you use the same secuity settings with basicHttpBinding it should work however.


text:
Q: Como criar dois pontos y para um mesmo x? Olá, eu gostaria de criar uma rotina em python para criar "pontos duplos", onde um mesmo valor de x assumiria dois valores de y para qualquer situação. Usando a seguinte sequência de dados por exemplo:
1;5
2;2
3;4
4;10
5;6

Plotando esse gráfico como sendo a primeira coluna x e a segunda y, formaria uma linha reta.
O cenário que eu gostaria de chegar seria o seguinte:
1;5
1;2
2;2
2;4
3;4
3;10
4;10
4;6
5;6

E isso geraria um gráfico retangular. No caso, o valor de x possui o seu respectivo valor de y, porém esse mesmo valor de x também possui o valor de y referente ao seu "x+1", e assim sucessivamente.
Eu tentei criar algo como uma lista, porém sem suceso
arquivo = open('vazmed.out', 'rt')
arq = open('vazmed2.out', 'wt')
lista = []
valor_prev = 0
for linha in arquivo:
    campo = linha.split(';')
    i = (campo[0])
    valor = float(campo[1])
    lista.append(valor)
n = len(lista)
for i in range(n-1):
    lista.append([lista[i:][:i], lista[i:][:i+1]])
    arq.write('{};{}\n' .format(i, lista[i]))
arq.close

Eu sou novo no python e isso faz parte dos meus estudos, então se alguém conseguir me ajudar e puder explicar o como e o porque eu ficaria agradecido.
EDIT
Código para transformação dos valores positivos em 1 e negativos em -1.
arquivo = open('vazdif.out', 'rt')
lista = []
valor_prev = 0
for linha in arquivo:
    campo = linha.split(',')
    cont = int(campo[0])
    vazdif = float(campo[2])
    if vazdif * valor_prev < 0:
        lista.append([lista[-1][0], - lista[-1][1]])
    if vazdif < 0:
        lista.append([cont, -1])
    else:
        lista.append([cont, 1])
    valor_prev = vazdif
fou = open('res_id.out','wt')
for i in lista:
    fou.write('%4d,%8.4f\n' % (i[0],i[1]))
fou.close()

O arquivo de saída desse código é o seguinte:
   0, -1.0000
   1, -1.0000
   2, -1.0000
   3, -1.0000
   4, -1.0000
   5, -1.0000
   5,  1.0000
   6,  1.0000
   7,  1.0000
   8,  1.0000
   9,  1.0000
  10,  1.0000
  11,  1.0000
  12,  1.0000
  13,  1.0000
  14,  1.0000
  14, -1.0000
  15, -1.0000
  16, -1.0000
  17, -1.0000
  18, -1.0000
  19, -1.0000
  20, -1.0000

Como é possível ver, sempre que o valor muda de negativo para positivo, o i repete com o valor do i anterior. Porém o i não faz parte dos dados efetivamente, sendo apenas um índice.
Importante ressaltar que é apenas o índice que vai repetir, não o valor em sí.

A: Bom, o principal problema eh que vc ta usando o indice da lista pra 'guardar' o valor x, mas isso nao eh possivel quando vc tem dois elementos com o mesmo valor x, ja que a lista soh pode ter um valor y guardado naquele indice x.
O outro problema eh que vc ta adicionando todos os pontos originais na lista antes de comecar a adicionar os novos, o que te impede de ordenar os pontos da forma que vc colocou no exemplo.
O comando lista[i:][:i] tambem eh bastante estranho. O que vc esta fazendo aqui eh cortar todos os primeiros i-1 elementos da lista e, dada a lista resultante deste corte, manter apenas os primeiros i elementos. Em qualquer caso, essa operacao vai resultar em uma lista, o que nao parece ser oq vc quer ai. Recomendo ate vc fazer alguns experimentos dando print em diferentes valores de i como indice para entender melhor como listas funcionam.
Tenta fazer algo nesse sentido:
l = [[1,5], [2,2], [3,4], [4,10], [5,6]] # Troque pela leitura do arquivo...

m = []
for i in range(len(l)):
    m.append(l[i])

    if i < len(l)-1:
        m.append([l[i][0], l[i+1][1]])

# Escreva os elementos de m no arquivo...

Esse codigo resulta em m = [[1, 5], [1, 2], [2, 2], [2, 4], [3, 4], [3, 10], [4, 10], [4, 6], [5, 6]], que parece ser o resultado que vc espera.

A: A resposta do Leafar está correta, mas só irá funcionar se você tratar os dados corretamente.

Tratando os dados de um arquivo separado por linhas

texto = '''1;5
2;-2
3;4.5
4;10
5;6'''
# Para cada linha que tiver na string, gerar uma lista de valores separado por ;
lista = [i.split(';') for i in texto.splitlines()]
print(lista)
# [['1', '5'], ['2', '-2'], ['3', '4.5'], ['4', '10'], ['5', '6']]

Agora é só aplicar a lógica oferecida por Leafar e tratar as strings:

m = []
for i in range(len(lista)):
    # Primeiro valor registra como INT e segundo valor registra como FLOAT
    m.append([int(lista[i][0]), float(lista[i][1])])

    if i < len(lista)-1:
        m.append([int(lista[i][0]), float(lista[i+1][1])])
 print(m)
 # [[1, 5.0], [1, -2.0], [2, -2.0], [2, 4.5], [3, 4.5], [3, 10.0], [4, 10.0], [4, 6.0], [5, 6.0]]

E para puxar os dados:

for i in m:
    print(f'index = {i[0]}; valor = {i[1]}')


text:
Q: Time Series Forecast in R - Weekly Sparse Data with Variable Starting Point I am working on building a time series forecast model for a problem which involves dataset of manufacturers and their product offerings in a large retail outlet.
The problem is as follows:

*

*Lets say you have thousands of manufacturers. (M1 to Mn)

*There is a retail outlet who would take goods from these
manufacturers to sell.

*The manufacturers supply product offerings to the store on weekly
basis.(same product or new product with same price or different
price, but for simplicity lets say they supply new distinct
products) (from week W1 to Wn)

*Each manufacturer would have started working with the retail outlet
on different dates.(which can be anything in past)

*From the time they started working with the retail outlet, the
history suggests that some manufacturers have been constantly
supplying products weekly and some have been sparse.

In Dataset Below (N/A means they hadn't started doing business with
  the retail outlet e.g manufacturer M1 joined the retailer on Week3 in
  our time window with their first offering count to be 10)

       W1 -  W2 -  W3 -  W4 -  W5 - W6 - W7 - W8 - . - . - . - Wn
M1 - | N/A | N/A | 10  | 0   | 5  | 0  | 10 | 15 | 12 | . | . | 23 |
M2 - | 10  | 5   | 12  | 8   | 4  | 9  | 0  | 0  | 0  | . | . | 4  |
M3 - | 9   | N/A | 0   | 0   | 45 | 45 | 45 | 38 | 12 | . | . | 11 |
 . - | N/A | N/A | N/A | N/A | 12 | 0  | 10 | 15 | 12 | . | . | 28 |
 . - | N/A | N/A | N/A | 0   | 5  | 0  | 8  | 15 | 12 | . | . | 12 |
 . - | 5   | N/A | 60  | 0   | 5  | 0  | 40 | 67 | 23 | . | . | 46 |
 . - | N/A | N/A | 12  | 9   | 12 | 15 | 10 | 15 | 43 | . | . | 9  |
Mn - | 0   | N/A | 90  | 78  | 65 | 0  | 10 | 15 | 12 | . | . | 65 |

Now assuming that for all the manufacturers, I want to forecast, from the point Wn their next 8 weeks of supply they would do from this historical data ( i.e. from Wn for next 8 weeks i..e Wn+1 to Wn+8).
I am trying to forecast using the Auto ARIMA and seasonal naive models in R.
tsfull<- ts(tsdata, start=c(ts_series_strt_dt,weeknum_strt), freq=52)

tswindow<- window(tsdata, start=c(ts_series_strt_dt,weeknum_strt), end=c(ts_series_end_dt,weeknum_end))

SN<-snaive(tswindow, 8)
AR<-forecast.Arima(auto.arima(tswindow), h=8)
etsfr<-forecast(ets(tswindow), h=8)
stlffr<-forecast(stlf(tswindow), h=8)

Since the data contains a lot of Zeros, also since the starting point of the series for every manufacturer is totally different, also we have thousands of manufacturers and I see the RMSE error varies erratically since each series is unique. Also I have tried grouping the manufacturer based on their age with the outlet. I am not able to decide on the best forecast model that would fit this problem.
I am not an expert in this field. Any thoughts and opinion would be really helpful.


text:
Q: Rails why autocomplete association is not working I have a association between jobs and companies and i want to implement a autocomplete features
in my jobs.js.coffe file i have this code
jQuery ->
  $('#job_company_name').autocomplete
    source: $('#job_company_name').data('autocomplete-source')

and this is my Job form view

  <%= f.label :company_name %>

  <%= f.text_field :company_name, data: {autocomplete_source: companies_path} %>

  <%= f.label :job_title, "Intitulé du poste", class: "jobs-newtitles" %>

  <%= f.text_field :job_title, class: "form-control form-newjob"  %>

this is my job model
class Job < ActiveRecord::Base

    belongs_to :company

    extend FriendlyId
    friendly_id :job_title, use: :slugged

      def company_name
        company.try(:name)
      end

      def company_name=(name)
        self.company = Company.find_or_create_by_name(name) if name.present?
      end

end

I have also added this to my company controller
  def autocomplete
    @companies = Company.order(:name).where("name like ?", "%#{params[:term]}%")

    respond_to do |format|
      format.html
      format.json { render json: @companies.map(&:name) }
    end
  end

and this is my routes
  concern :autocompletable do
    get 'autocomplete', on: :collection
  end

resources :companies, concerns: :autocompletable

A: You specified autocomplete url "companies_path", while your autocomplete action is 'autocomplete'.
Check the correct autocomplete path, with this inspection:
  $ rake routes | grep autocomplete

I assumes, you need modify autocomplete_source to something like this:
  <%= f.text_field :company_name, data: {autocomplete_source: companies_autocomplete_path} %>


text:
Q: Underworld layer in Heroes of Might and Magic III Might and Magic has a great lore and HMM 2, MM6,  HMM3, and MM7 follow a great story line (Kreegans, Ancients etc.).
I wanted to ask about underground layers in Heroes of Might and Magic III. Is there any background story, why underground layer exists (I mean like realm of Minotaur etc.)? Or this feature of Heroes III does not have any background story and it is just for fun?


text:
Q: Calculating total value for a given financial period results in an 'list' object has no attribute 'sum' error My code
tperiod = list(df.groupby(['Period']),['Val.in rep.cur.'].sum())

Error Msg

AttributeError: 'list' object has no attribute 'sum'

What I'm trying to do
Using Pandas Groupby to calculate the total value for a given financial period on a spreadsheet. Period and "Val.in rep.cur." are both headings for an excel column.
Does anyone know if I'd made a syntax error? Thanks for your help.
George Ng

A: If you want to find the sum of all the numbers in a list, you do sum(list), not list.sum().


text:
Q: Force to download .ics file I think my question is very particular. What I'm doing right now is creating a simple list of events where you can click each of them an add to your calendar (iCal, Google Calendar, Live Calendar, etc.). To achieve this i'm using addToCalentar but there is something acting weird in this code.
When I select iCal it's suppose to download an ics file but the plugin open a new browser tab showing the file itself. All the other options are working very good, because their needs to open in a new window. But muy question is. Where can I modify the source code in order to only download the file if the user selects "iCal" option?
This is my HTML:

01/04/2015

This is my Plugin Configuration:
$('.addtocal').AddToCal({
      icalEnabled:true,
      vcalEnabled:false,

      getEventDetails: function( element ) {
        var
          dtstart_element = element.find('.dtstart'), start,
          dtend_element = element.find('.dtend'), end,
          title_element = element.find('.summary'), title,
          details_element = element.find('.description'), details,
          ics_element = element.find('.ics'), ics;

        start = dtstart_element.length ? dtstart_element.attr('title') : new Date();

        if(dtend_element.length) {
          end = dtend_element.attr('title');

        } else {

          end = new Date();
          end.setTime(end.getTime() + 60 * 60 * 1000);

        }

        title = title_element.length ? title_element.html() : element.attr('id');
        details = details_element.length ? details_element.html() : element.html();

        ics = ics_element.attr('title');

        // return the required event structure
        return {
          webcalurl: null,
          icalurl: ics,
          vcalurl: null,
          start: start,
          end: end,
          title: title,
          details: details,
          location: null,
          url: null
          };
      },
    });

This is the referenced plugin:
https://github.com/tardate/jquery.addtocalendar/blob/master/jquery.addtocal.js
What I was working on is changing this method to determine if the item.label is iCal I can add ...</> but is not working.
_renderItem: function( ul, item) {

      return $( "

" )
        .data( "item.addtocal", item )
        .append( $( "" ).text( item.label ) )
        .appendTo( ul );
    },

A: To force your browser to download a file instead of reading it, you can give it a FileType header that will force it to download.
If you do not have a .htaccess file yet, make one in your webroot folder, and add this:
AddType application/octet-stream .ics
That will force browsers to download *.ics files instead of showing them.


text:
Q: MS Excel - Consolidate and sum from columns with data validation list and dependent list I have an excel sheet consist with 3 columns: Price, Category1, Category2.
Category1 is a select-drop down using data validation list from predefined name (from another sheet).
Category2 is also a drop down list from defined names but with dependency of Category1 using the INDIRECT function.
I would like to create cells with data of a the total amount (Sum Prices) for Category1 and Category2.
For Example:

So I would get the sum: A 350, B 400, A1 200 and so on...
Consolidate column Category1/Category2 did not work for me (got a message: no data was consolidate), Pivote table wizard also did not work (got a pivot table with all data messed up)
Any Ideas?

A: A simple pivot table should give the correct numbers, even if they aren't the numbers you want:


text:
Q: Mobile version of my website only loads correctly after refresh I created a responsive website with media queries for the mobile version but it doesn't load part of the css for the links on the homepage but then corrects itself after being refreshed. Can someone help me understand what's wrong and why it does that?

@media only screen and (max-width: 600px) {

    .Design-projects {
    padding-left: 8%;
    font-size: 30px;
    padding-bottom: 5%;
  }

    .design-projects-level-1 {
    padding-left: 8%;
    font-size: 20px;
  }

    .design-projects-level-2 {
    padding-left: 8%;
    font-size: 20px;
    padding-top: 15%;
  }

    .design-projects-level-3 {
    padding-left: 8%;
    font-size: 20px;
    padding-top: 15%;
    }

    .eventsgeneral {
      text-align: right;
    }

    .Events {
      font-size: 30px;
      padding-left: 55%;
      margin-right: 0;
      padding-bottom: 5%;
    }

    .design-projects-level-4 {
      font-size: 20px;
      padding-right: 64%;
      padding-left: 0;
    }

    .design-projects-level-5 {
      font-size: 20px;
      padding-left: 5%;
      padding-right: 64%;
      padding-top: 15%;
    }

    .design-projects-level-6 {
      font-size: 20px;
      padding-left: 0;
      padding-right: 64%;
      padding-top: 15%;
    }
}

DESIGN PROJECTS

 <Link to="/Soundcloudredesign">01. Redesigning Soundcloud </Link>

        <Link to="/ramenshop">02. The Ramen Shop</Link>

        <Link to="/otts">03. Ott's Exotic Plants</Link>

EVENTS

        <Link to="/westhollywood">01. West Hollywood EDITION</Link>

        <Link to="/noblepanacea">02. Noble Panacea Global Brand Launch</Link>

        <Link to="/ellenvonunwerth">03. Ellen von Unwerth at Fotografiska</Link>

When it first loads, the links look like this:

But it should look like this (however, it only looks like this after I refresh the page):

A: Sorry, but first, you should improve your coding. You don't need to create a new CSS class for each of your item, especially if it is exactly the same.
You encounter that issue because your CSS code is not useful.
Below, you will find the code that you are looking for:

@media only screen and (max-width: 600px) {

.Design-projects {
    font-size: 30px;
    padding-bottom: 5%;
    padding-left: 8%;
}

.design-projects-item{

    padding-left: 8%;
    padding-bottom: 5%;
    font-size: 20px;
}

.eventsgeneral {
    text-align: right;
    padding-right: 8%;
}

.Events {
    font-size: 30px;
    padding-bottom: 5%;
}

.events-item {
    font-size: 20px;
    padding-bottom: 5%;
}
}

DESIGN PROJECTS

  <Link to="/Soundcloudredesign">01. Redesigning Soundcloud </Link>

  <Link to="/ramenshop">02. The Ramen Shop</Link>

  <Link to="/otts">03. Ott's Exotic Plants</Link>

EVENTS

    <Link to="/westhollywood">01. West Hollywood EDITION</Link>

    <Link to="/noblepanacea">02. Noble Panacea Global Brand Launch</Link>

    <Link to="/ellenvonunwerth">03. Ellen von Unwerth at Fotografiska</Link>


text:
Q: CMD prompt can't display Unicode characters that are stored in oracle database correctly I've been meddling with charset/encoding problems of Oracle database, PL/SQL developer and JDBC and these are what I want to achieve:

*

*Input Unicode characters from a browser into the database

*Display Unicode characters that are retrieved from the database correctly in the browser, CMD prompt, and PL/SQL developer

And these are what I've done:

*

*Change the server charset to AL32UTF8 by following the steps:
SQL>SHUTDOWN IMMEDIATE
SQL>STARTUP MOUNT;
SQL>ALTER SYSTEM ENABLE RESTRICTED SESSION;
SQL>ALTER SYSTEM SET JOB_QUEUE_PROCESSES=0;
SQL>ALTER SYSTEM SET AQ_TM_PROCESSES=0;
SQL>ALTER DATABASE OPEN;
SQL>ALTER DATABASE CHARACTER SET INTERNAL_USE AL32UTF8;
SQL>ALTER DATABASE NATIONAL CHARACTER SET INTERNAL_USE AL32UTF8;
SQL>update props$ set VALUE$='UTF8' where NAME='NLS_NCHAR_CHARACTERSET';
SQL>ALTER SYSTEM DISABLE RESTRICTED SESSION;
SQL>SHUTDOWN IMMEDIATE;
SQL>STARTUP

*Change the client charset to AL32UTF8 by adding system environment variable NLS_LANG with value AMERICAN_AMERICA.AL32UTF8and changing the value of NLS_LANG to AMERICAN_AMERICA.AL32UTF8 under HKEY_LOCAL_MACHINE>SOFTWARE>ORACLE>KEY_OraDB12Home1 in regedit

*Check "Always UTF8" under Tool>Preferences>Files>Format>Encoding in P/SD

Eventually if I added the Unicode characters to the database from either the browser or P/SD they can be displayed properly in the browser and P/SD but not in the CMD prompt. If they are added to the database from the CMD prompt they can be displayed correctly everywhere. For now I'm sure that the characters input from the browser and P/SD are Unicode characters, but not for the CMD input, which is also supposed to be Unicode since both the server and client charsets have been set to AL32UTF8. Here's an example of a correct display and an incorrect one:
In P/SD: (Correct)
SQL> select title from posts where id=134;
TITLE
--------------------------------------------------------------------------------
测试

SQL> SELECT DUMP(title, 1016) FROM posts where id=134;
DUMP(TITLE,1016)
--------------------------------------------------------------------------------
Typ=1 Len=6 CharacterSet=AL32UTF8: e6,b5,8b,e8,af,95

In command prompt: (Incorrect)
SQL> select title from posts where id=134;

TITLE
--------------------------------------------------------------------------------
娴嬭瘯

SQL> SELECT DUMP(title, 1016) FROM posts where id=134;

DUMP(TITLE,1016)
--------------------------------------------------------------------------------
Typ=1 Len=6 CharacterSet=AL32UTF8: e6,b5,8b,e8,af,95

SQL>

A: Most likely you corrupted your database and you should consider to make a full restore from backup.
ALTER DATABASE CHARACTER SET ... was supported till Oracle version 9 and worked only at certain conditions.
Never use clause INTERNAL_USE or make any updates on Oracle system tables unless you are advised by Oracle Support. If you like to change the character set on an existing database, follow this instruction: Character Set Migration
Perhaps you had good luck, because you changed only WHERE NAME='NLS_NCHAR_CHARACTERSET'. National character set are hardly used nowadays, perhaps you did not destroy everything.
Anyway, items 2.) and 3.) are correct. In case of 32 bit check also registry key HKEY_LOCAL_MACHINE>SOFTWARE>Wow6432Node>ORACLE>KEY_OraDB12Home1
In order to verify if your data is really stored in UTF-8 run
SELECT DUMP(YOUR_COLUMN, 1016) FROM YOUR_TABLE;

And check the binary values. For comparison you can use page Unicode code converter to get UTF-8 binary values (field "UTF-8 code units") of arbitrary strings.

A: Your code page is 936 (Chinese). When you start SQL"Plus then this code page is inherited from CMD.
Usually you have two possibilities:

*

*Set NLS_LANG according to your code page (either as Environment Variable or in Registry). Example set NLS_LANG=.WE8MSWIN1252 for a PC in Central Europe, the language and territory information do not matter for character sets.
In your case this solution seems to be not possible, according this list of Character Sets there is no Oracle character set for code page 936. But have a look at this Wikipedia article Code page 1386. Perhaps you can use "GB 18030", which would be set NLS_LANG=.ZHS32GB18030 or "GB 2312", which would be set NLS_LANG=.ZHS16CGB231280

*Second solution is to switch th code page at CMD before you launch SQL*Plus. Use chcp 65001 in order to set the code page to UTF-8. However, you may face some problems when you use UTF-8 on CMD, see this discussion.
For more information have also a look at this answer.


text:
Q: Why do we use log probability in deep learning? I got curious while reading the paper 'Sequence to Sequence Learning with Neural Networks'.
In fact, not only this paper but also many other papers use log probabilities, is there a reason for that?
Please check the attached photo.

A: Two reasons -

*

*Theoretical - Probabilities of two independent events A and B co-occurring together is given by P(A).P(B). This easily gets mapped to a sum if we use log, i.e. log(P(A)) + log(P(B)). It is thus easier to address the neuron firing 'events' as a linear function.

*Practical - The probability values are in [0, 1]. Hence multiplying two or more such small numbers could easily lead to an underflow in a floating point precision arithmetic (e.g. consider multiplying 0.0001*0.00001). A practical solution is to use the logs to get rid of the underflow.

A: For any given problem we need to optimise the likelihood of parameters. But optimising the product require all data at once and requires huge computation.
We know that a sum is a lot easier to optimise as the derivative of a sum is the sum of derivatives. So, taking log convert it to sum and makes computation faster.
Refer this


text:
Q: How can I print the number of steps forward, backward, and total? Here's my code:
import math
import random

while True:
    fwd= random.randint(2,20)
    bkwd= random.randint(2,fwd)
    total=random.randint(10,85)
    f= 0
    b = 0
    t= 0

    if bkwd > fwd:
        break

    while total > 0:
        f = 0

        while fwd > f:
            if total > 0:
                print("F", end="")
                f=f+1
                t=t+1
                total=total-1

            else:
               f = fwd

        b = 0

        while bkwd > b:
            if total > 0:
                print("B", end="")
                t=t-1
                b=b+1
                total=total-1
            else:
                b = bkwd
    if f > total:
        break

print(" ",t, "steps from the start")
#I need help here printing the right amount of total steps
print("Forward:", f, "Backward:", b, "Total:", )

My instructions are:
A person walks a random amount of steps forward, and then a different random number of steps backwards.
The random steps are anywhere between 2 and 20
The number of steps forward is always greater than the number of steps backwards
That motion of forward / backward random steps repeats itself again and again
The motion is consistent (the number of forward steps stays the same throughout the motion, and the number of backwards steps stays the same throughout the motion)
After making a specific amount of total steps the person is told to stop and will be a certain amount of steps forward from where they started.
The total number of steps is generated randomly and will be between 10 and 85
You are writing a program to simulate the motion taken by the person.
Display that motion and the number of steps he ends away from where he started.
For Example:
If the program generated the forward steps to be 4, and the backward steps to be 2, and the total number of steps to be 13, your program would display:
FFFFBBFFFFBBF = 5 Steps from the start
If the program generated the forward steps to be 5, and the backward steps to be 3, and the total steps to be 16, your program would display
FFFFFBBBFFFFFBBB = 4 Steps from the start

A: For one thing, bkwd = random.randint(2,fwd) will generate a number between 2<=n<=fwd, when instead you want 2<=n<=fwd-1.
To answer your question, you just need to add a new variable to keep track of total steps taken. Maybe call it steps_taken? You should increment this counter once for every step taken.


text:
Q: Angular form submit event firing twice between parent and child components I have a strange problem where by the form submit event of my child form is firing twice on my parent form.
child.component.html
<form [formGroup]="childForm" (ngSubmit)="childFormSubmit()">
  ...
</form>

child.component.ts
@Component({
  selector: 'child-form',
  templateUrl: 'login.component.html',
})

export class ChildComponent {
  @Output() submit = new EventEmitter<any>();

  public childForm: FormGroup;

  childFormSubmit() {
    if (this.childForm.valid) {
      console.log('Child Form Submit')
      this.submit.emit(this.childForm.value);
    }
  }
}

parent.component.html
<child-form (submit)="parentSubmit($event)"></child-form>

parent.component.ts
@Component({
  selector: 'parent',
  templateUrl: 'parent.component.html',
})

export class ParentComponent {

  constructor() {
  }

  parentSubmit(event: any) {
    console.log('Parent Submit');
  }
}

Submitting the child form results in the following in the console output:
Child Form Submit
Parent Submit
Parent Submit

A: You have used a reserved word 'submit' on child component as decorator function and attribute. So if you have a form in a parent component, (submit) (which is equivalent of (ngSubmit))  is fired at the same time as the event from the child.
Change it for something else, like this:
<child-form (childSubmit)="parentSubmit($event)"></child-form>

and in child component:
 @Output() childSubmit = new EventEmitter<any>();
 ...
 childFormSubmit() {
   if (this.childForm.valid) {
         console.log('Child Form Submit')
         this.childSubmit.emit();
   }
 }

Here is a working DEMO


text:
Q: Azure Function: Could not load file or assembly WebJobs.Host I have an error saying

Error: The function runtime is unable to start. mscorlib: Could not
  load file or assembly 'Microsoft.Azure.WebJobs.Host, Version=3.0.0.0,
  Culture=neutral, PublicKeyToken=null' or one of its dependencies. The
  system cannot find the file specified.

Do I need to setup anything in the azure portal? I can run it on my local machine. After I published the function to azure and tried to run the function it gave me this error.

A: I ran into this same issue locally and solved it by clearing my local nuget cache. See How to clear NuGet package cache using command line?

A: If you are running Functions V2 you need to ensure that the Function App's "FUNCTIONS_EXTENSION_VERSION" Application Setting on Azure is set to a value of "~2". It seems to default to "~1" - you can modify the value manually or through your automated release process (CD).
HTH

A: I removed the azure function created previously and create a new one from Visual Studio by creating a azure function project and publish from there.


text:
Q: Trying to implement Drag and Drop gmail attachment from chrome I have been trying to implement drag and drop a gmail attachment from chrome into my application.
Its possible to drag the file from the email to the desktop and it create the attachment there so I know this must be possible.
I have been able to get it to read the file name, but when I read FileContents from the data object I get an internet shortcut with a link to the file.
Has anyone got this working before? the code at the moment is hard coded for a .txt file
My main DataObjectWrapper class is as follows:
there are too many characters to post all of it but the main method is:
public object GetDataNative(string format, bool autoConvert)
{
    switch (format)
    {
        case CFSTR_FILEDESCRIPTOR_A:

            IntPtr fileGroupDescriptorAPointer = IntPtr.Zero;
            try
            {
                //use the underlying IDataObject to get the FileGroupDescriptor as a MemoryStream
                MemoryStream fileGroupDescriptorStream = (MemoryStream)this.underlyingDataObject.GetData(CFSTR_FILEDESCRIPTOR_A, autoConvert);
                byte[] fileGroupDescriptorBytes = new byte[fileGroupDescriptorStream.Length];
                fileGroupDescriptorStream.Read(fileGroupDescriptorBytes, 0, fileGroupDescriptorBytes.Length);
                fileGroupDescriptorStream.Close();

                //copy the file group descriptor into unmanaged memory
                fileGroupDescriptorAPointer = Marshal.AllocHGlobal(fileGroupDescriptorBytes.Length);
                Marshal.Copy(fileGroupDescriptorBytes, 0, fileGroupDescriptorAPointer, fileGroupDescriptorBytes.Length);

                //marshal the unmanaged memory to to FILEGROUPDESCRIPTORA struct
                object fileGroupDescriptorObject = Marshal.PtrToStructure(fileGroupDescriptorAPointer, typeof(NativeMethods.FILEGROUPDESCRIPTORA));
                NativeMethods.FILEGROUPDESCRIPTORA fileGroupDescriptor = (NativeMethods.FILEGROUPDESCRIPTORA)fileGroupDescriptorObject;

                //get the pointer to the first file descriptor
                IntPtr fileDescriptorPointer = (IntPtr)((int)fileGroupDescriptorAPointer + Marshal.SizeOf(fileGroupDescriptor.cItems));

                NativeMethods.FILEDESCRIPTORA[] fileDescriptors = new NativeMethods.FILEDESCRIPTORA[fileGroupDescriptor.cItems];

                //loop for the number of files acording to the file group descriptor
                for (int fileDescriptorIndex = 0; fileDescriptorIndex < fileGroupDescriptor.cItems; fileDescriptorIndex++)
                {

                    //marshal the pointer top the file descriptor as a FILEDESCRIPTORA struct and get the file name
                    NativeMethods.FILEDESCRIPTORA fileDescriptor = (NativeMethods.FILEDESCRIPTORA)Marshal.PtrToStructure(fileDescriptorPointer, typeof(NativeMethods.FILEDESCRIPTORA));
                    fileDescriptors[fileDescriptorIndex] = fileDescriptor;

                    //move the file descriptor pointer to the next file descriptor
                    fileDescriptorPointer = (IntPtr)((int)fileDescriptorPointer + Marshal.SizeOf(fileDescriptor));
                }

                fileGroupDescriptor.fgd = fileDescriptors;

                //return the array of filenames
                return fileGroupDescriptor;
            }
            finally
            {
                //free unmanaged memory pointer
                Marshal.FreeHGlobal(fileGroupDescriptorAPointer);
            }

        case CFSTR_FILEDESCRIPTOR_W:

            IntPtr fileGroupDescriptorWPointer = IntPtr.Zero;
            try
            {
                //use the underlying IDataObject to get the FileGroupDescriptorW as a MemoryStream
                MemoryStream fileGroupDescriptorStream = (MemoryStream)this.underlyingDataObject.GetData(CFSTR_FILEDESCRIPTOR_W);
                byte[] fileGroupDescriptorBytes = new byte[fileGroupDescriptorStream.Length];
                fileGroupDescriptorStream.Read(fileGroupDescriptorBytes, 0, fileGroupDescriptorBytes.Length);
                fileGroupDescriptorStream.Close();

                //copy the file group descriptor into unmanaged memory
                fileGroupDescriptorWPointer = Marshal.AllocHGlobal(fileGroupDescriptorBytes.Length);
                Marshal.Copy(fileGroupDescriptorBytes, 0, fileGroupDescriptorWPointer, fileGroupDescriptorBytes.Length);

                //marshal the unmanaged memory to to FILEGROUPDESCRIPTORW struct
                object fileGroupDescriptorObject = Marshal.PtrToStructure(fileGroupDescriptorWPointer, typeof(NativeMethods.FILEGROUPDESCRIPTORW));
                NativeMethods.FILEGROUPDESCRIPTORW fileGroupDescriptor = (NativeMethods.FILEGROUPDESCRIPTORW)fileGroupDescriptorObject;

                //get the pointer to the first file descriptor
                IntPtr fileDescriptorPointer = (IntPtr)((int)fileGroupDescriptorWPointer + Marshal.SizeOf(fileGroupDescriptor.cItems));

                NativeMethods.FILEDESCRIPTORW[] fileDescriptiors = new NativeMethods.FILEDESCRIPTORW[fileGroupDescriptor.cItems];

                //loop for the number of files acording to the file group descriptor
                for (int fileDescriptorIndex = 0; fileDescriptorIndex < fileGroupDescriptor.cItems; fileDescriptorIndex++)
                {
                    //marshal the pointer top the file descriptor as a FILEDESCRIPTORW struct and get the file name
                    NativeMethods.FILEDESCRIPTORW fileDescriptor = (NativeMethods.FILEDESCRIPTORW)Marshal.PtrToStructure(fileDescriptorPointer, typeof(NativeMethods.FILEDESCRIPTORW));
                    fileDescriptiors[fileDescriptorIndex] = fileDescriptor;

                    //move the file descriptor pointer to the next file descriptor
                    fileDescriptorPointer = (IntPtr)((int)fileDescriptorPointer + Marshal.SizeOf(fileDescriptor));
                }

                fileGroupDescriptor.fgd = fileDescriptiors;

                //return the array of filenames
                return fileGroupDescriptor;
            }
            finally
            {
                //free unmanaged memory pointer
                Marshal.FreeHGlobal(fileGroupDescriptorWPointer);
            }

        case CFSTR_FILECONTENTS:

            //override the default handling of FileContents which returns the
            //contents of the first file as a memory stream and instead return
            //a array of MemoryStreams containing the data to each file dropped

            //get the array of filenames which lets us know how many file contents exist
            string[] fileContentNames = (string[])this.GetData(CFSTR_FILEDESCRIPTOR_W);

            //create a MemoryStream array to store the file contents
            MemoryStream[] fileContents = new MemoryStream[fileContentNames.Length];

            //loop for the number of files acording to the file names
            for (int fileIndex = 0; fileIndex < fileContentNames.Length; fileIndex++)
            {
                //get the data at the file index and store in array
                fileContents[fileIndex] = this.GetData(format, fileIndex);
            }

            //return array of MemoryStreams containing file contents
            return fileContents;

        case CFSTR_INETURL_A:

            //use the underlying IDataObject to get the FileGroupDescriptorW as a MemoryStream
            MemoryStream UniformResourceLocatorStream = (MemoryStream)this.underlyingDataObject.GetData(CFSTR_INETURL_A);
            byte[] UniformResourceLocatorBytes = new byte[UniformResourceLocatorStream.Length];
            UniformResourceLocatorStream.Read(UniformResourceLocatorBytes, 0, UniformResourceLocatorBytes.Length);
            UniformResourceLocatorStream.Close();

            string url = null;

            if (UniformResourceLocatorBytes[1] == 0)
                url = Encoding.Unicode.GetString(UniformResourceLocatorBytes);
            else
                url = Encoding.ASCII.GetString(UniformResourceLocatorBytes);

            return url;

        case CFSTR_INETURL_W:

            //use the underlying IDataObject to get the FileGroupDescriptorW as a MemoryStream
            MemoryStream UniformResourceLocatorWStream = (MemoryStream)this.underlyingDataObject.GetData(CFSTR_INETURL_W);
            byte[] UniformResourceLocatorWBytes = new byte[UniformResourceLocatorWStream.Length];
            UniformResourceLocatorWStream.Read(UniformResourceLocatorWBytes, 0, UniformResourceLocatorWBytes.Length);
            UniformResourceLocatorWStream.Close();

            string urlW = null;

            if (UniformResourceLocatorWBytes[1] == 0)
                urlW = Encoding.Unicode.GetString(UniformResourceLocatorWBytes);
            else
                urlW = Encoding.ASCII.GetString(UniformResourceLocatorWBytes);

            return urlW;

        case TEXT_X_MOZ_URL:

            //use the underlying IDataObject to get the FileGroupDescriptorW as a MemoryStream
            MemoryStream textMozStream = (MemoryStream)this.underlyingDataObject.GetData(TEXT_X_MOZ_URL);
            byte[] textMozBytes = new byte[textMozStream.Length];
            textMozStream.Read(textMozBytes, 0, textMozBytes.Length);
            textMozStream.Close();

            string urlText = null;

            if (textMozBytes[1] == 0)
                urlText = Encoding.Unicode.GetString(textMozBytes);
            else
                urlText = Encoding.ASCII.GetString(textMozBytes);

            return urlText;

        case "text/html":

            //use the underlying IDataObject to get the FileGroupDescriptorW as a MemoryStream
            MemoryStream dataFormatStream = (MemoryStream)this.underlyingDataObject.GetData("text/html");
            byte[] dataFormatBytes = new byte[dataFormatStream.Length];
            dataFormatStream.Read(dataFormatBytes, 0, dataFormatBytes.Length);
            dataFormatStream.Close();

            string formatText = null;

            if (dataFormatBytes[1] == 0)
                formatText = Encoding.Unicode.GetString(dataFormatBytes);
            else
                formatText = Encoding.ASCII.GetString(dataFormatBytes);

            return formatText;
    }

    //use underlying IDataObject to handle getting of data
    return this.underlyingDataObject.GetData(format, autoConvert);
}

I can get quite a bit of data out of it, but just not in the same was as if it was dropped on the desktop:
private void Form1_DragDrop(object sender, DragEventArgs e)
{
    string[] dataFormats = e.Data.GetFormats();

    Dictionary<string, object> dataDictionary = new Dictionary<string, object>();

    foreach (string dataFormat in dataFormats)
    {
        dataDictionary.Add(dataFormat, e.Data.GetData(dataFormat));

        Debug.WriteLine(
            String.Format("Data Format: {0}     Has data: {1}       Data: {2}",
                dataFormat,
                dataDictionary[dataFormat] != null ? "Yes" : "No",
                dataDictionary[dataFormat] != null ? dataDictionary[dataFormat] : string.Empty));
    }

    DataObjectWrapper dataWrapper = new DragDropTest.DataObjectWrapper(e.Data);

    DataObjectWrapper.NativeMethods.FILEGROUPDESCRIPTORW fileGroupDescriptorW = dataWrapper.GetFileGroupDescriptorW();

    string url = dataWrapper.GetUniformResourceLocatorA();
    string urlw = dataWrapper.GetUniformResourceLocatorW();
    string mozUrl = dataWrapper.GetTextMozURL();
    string textHTML = dataWrapper.GetTExtHtml();

    Stream[] streams = dataWrapper.GetFileContents();

    byte[] buffer = new byte[1024];

    int received = 0;

    FileStream fileStream = File.OpenWrite(@"c:\temp\hello.txt");
    using (Stream input = streams[0])
    {
        int size = input.Read(buffer, 0, buffer.Length);
        while (size > 0)
        {
            fileStream.Write(buffer, 0, size);
            received += size;

            size = input.Read(buffer, 0, buffer.Length);
        }
    }

    fileStream.Flush();
    fileStream.Close();

    return;
}

I have read and tried the below links already:
http://dlaa.me/blog/post/9913083
Drag and Drop large virtual files with IStream using VirtualFileDataObject
Drag and drop large virtual files from C# to Windows Explorer
https://msdn.microsoft.com/en-us/library/windows/desktop/bb776902(v=vs.85).aspx#CFSTR_FILECONTENTS
https://msdn.microsoft.com/en-us/library/windows/desktop/bb776904(v=vs.85).aspx
https://dlaa.me/blog/post/9923072
Drag and drop virtual files using IStream
https://blogs.msdn.microsoft.com/adamroot/2008/02/19/shell-style-drag-and-drop-in-net-wpf-and-winforms/
Implementing drag-drop from Chrome on my .NET Windows form
https://blogs.msdn.microsoft.com/adamroot/2008/02/19/shell-style-drag-and-drop-in-net-part-3/
https://blogs.msdn.microsoft.com/adamroot/2008/02/19/shell-style-drag-and-drop-in-net-wpf-and-winforms/
https://blogs.msdn.microsoft.com/adamroot/2008/02/19/shell-style-drag-and-drop-in-net-part-2/
https://blogs.msdn.microsoft.com/adamroot/2008/02/02/dragdroplib-cs/
https://www.codeproject.com/reference/1091137/windows-clipboard-formats
http://dlaa.me/blog/post/9923072
Drag and drop virtual files using IStream
http://www.ookii.org/Blog/opening_files_via_idroptarget_in_net
https://www.codeproject.com/Articles/28209/Outlook-Drag-and-Drop-in-C

A: You should be able to drag & drop embedded images with your code. But attachments like zip or pdf files are transfered as "FileDrop" format from Chrome. Unfortunately it uses the asynchronous drag & drop interface which is not natively supported by DotNet. That's why GetData("FileDrop") will always return null.
You need to use the interface IDataObjectAsyncCapability to trigger the download. But first it is necessary to pick apart the DataObject to get to the underlying COM-DataObject:
using System;
using System.Collections.Specialized;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.ComTypes;
using System.Threading.Tasks;

namespace Dummy
{
    public class FileDrop
    {
        [ComImport]
        [Guid("3D8B0590-F691-11d2-8EA9-006097DF5BD4")]
        [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
        public interface IDataObjectAsyncCapability
        {
            void SetAsyncMode([In] Int32 fDoOpAsync);
            void GetAsyncMode([Out] out Int32 pfIsOpAsync);
            void StartOperation([In] IBindCtx pbcReserved);
            void InOperation([Out] out Int32 pfInAsyncOp);
            void EndOperation([In] Int32 hResult, [In] IBindCtx pbcReserved, [In] UInt32 dwEffects);
        }

        public static async Task<StringCollection> GetFileDrop(System.Windows.Forms.DataObject dataobject)
        {
            if (dataobject.ContainsFileDropList())
            {
                var files = dataobject.GetFileDropList();
                if (files.Count == 0)
                {
                    // try async version
                    if (await ProcessFileDropAsync(dataobject))
                    {
                        files = dataobject.GetFileDropList();
                    }
                }

                return files;
            }

            // return empty collection
            return new StringCollection();
        }

        private static async Task<bool> ProcessFileDropAsync(System.Windows.Forms.DataObject dataobject)
        {
            // get the internal ole dataobject
            FieldInfo innerDataField = dataobject.GetType().GetField("innerData", BindingFlags.NonPublic | BindingFlags.Instance);
            var oledataobject = (System.Windows.Forms.IDataObject)innerDataField.GetValue(dataobject);

            var type = oledataobject.GetType();
            if (type.Name == "OleConverter")
            {
                // get the COM-object from the OleConverter
                FieldInfo innerDataField2 = type.GetField("innerData", BindingFlags.NonPublic | BindingFlags.Instance);
                var item = innerDataField2.GetValue(oledataobject);

                var asyncitem = item as IDataObjectAsyncCapability;

                if (asyncitem != null)
                {
                    var isasync = 0;
                    asyncitem.GetAsyncMode(out isasync);
                    if (isasync != 0)
                    {
                        var task = Task.Run(() =>
                        {
                            asyncitem.StartOperation(null);

                            // calling GetData after StartOperation will trigger the download in Chrome
                            // subsequent calls to GetData return cached data
                            // files are downloaded to something like c:\temp\chrome_drag1234_123456789\yourfilename.here
                            var result = dataobject.GetData("FileDrop");

                            asyncitem.EndOperation(0, null, 1); // DROPEFFECT_COPY = 1
                        });

                        await task;

                        return true;
                    }
                }
            }

            return false;
        }
    }
}

Call it from your drop handler and files should contain the path to your attachment:
    private async void panel_DragDrop(object sender, DragEventArgs e)
    {
        var files = await FileDrop.GetFileDrop(e.Data as System.Windows.Forms.DataObject);

        foreach (var file in files)
        {
            Console.WriteLine(file);
        }
    }


text:
Q: dig - answer section has list of server names this is the answer section of : dig supl.nokia.com
;; ANSWER SECTION:
supl.nokia.com.     82858   IN  CNAME   nokia.supl.svc.ovi.com.
nokia.supl.svc.ovi.com. 58  IN  CNAME   nokia.supl.svc.ovi.com.glb.as1248.net.
nokia.supl.svc.ovi.com.glb.as1248.net. 300 IN CNAME geo3.nokia.supl.svc.ovi.com.glb.as1248.net.
geo3.nokia.supl.svc.ovi.com.glb.as1248.net. 60 IN CNAME supl.nokia.us-east-1.pos.here.com.
supl.nokia.us-east-1.pos.here.com. 100 IN CNAME pra-suplnokia-516311011.us-east-1.elb.amazonaws.com.
pra-suplnokia-516311011.us-east-1.elb.amazonaws.com. 60 IN A 52.3.37.45
pra-suplnokia-516311011.us-east-1.elb.amazonaws.com. 60 IN A 52.22.201.16

I was expecting an IP address like what I got for : dig supl.google.com
;; ANSWER SECTION:
supl.google.com.    300 IN  A   74.125.195.192

What is this list of servers I got for nokia?

A: It's a chain of CNAME pointers. If you look at the names on the right-hand side of the lines with "CNAME" in them, they are the same as the left-hand name on the following line, until you get to the final step where the right-hand name leads to two A records (which then hold the IP addresses you wanted).

A: Are this names of different servers? Or same one?
Also, some other DNS server returns in its answer only 3 CNAMEs (and not this whole list) and I see in wireshark for the 3rd CMANE :
nokia.supl.svc.ovi.com.glb.as1248.net: type A, class IN, addr 127.0.0.1
(So i get localhost as my query result and can not establish connection)
How can that be? Why does it return only 3 and not the whole list, like i got when i did 'dig' command?
Thanks


text:
Q: Create table using rows from another table as columns I have a table with the following structure :
TableNo1
Field1
row1
row2
row3
row4
row5
...
...
...
row n
Now I need to create a new table with the following schema:
TableNo2
Field1(row1 of Table1)   Field2(row2 of Table1)   Field3(row3 of table1) Fieldn(row n of table1)
I read about this but only thing i was able to find is the into clause which doesnt work.
Can anyone please help?

A: You can use dynamic SQL
DECLARE @TableNo1 TABLE(Field varchar(128),DataType varchar(128))
DECLARE @s nvarchar(max)='CREATE TABLE dbo.TableNo2('
INSERT INTO @TableNo1
VALUES
('Field1','nvarchar(max)'),
('Field2','int')

SELECT  @s+=T.Field+' '+T.DataType+',' FROM   @TableNo1 T
SET @s=LEFT(@s,LEN(@s)-1)+')'
EXECUTE(@s)


text:
Q: Передача элемента символьного массива в функцию с изменением значения Допустим есть символьный массив и функция:
void function(char a) {
    strcpy_s(a, "Something");
}

int main () {
    char mass[30];
    function();
    return 0;
}

Как мне передать символьный массив mass[30] в функцию, чтобы при вызове функции function() в массиве находилось слово "Something"?

A: Во-первых, вам надо изменить тип параметра функции:
function (char* a)
или
function (char a[])
Потом при вызове функции передавайте массив в неё вот так:
void function(char a[]) {
    strcpy_s(a, "Something");
}

int main () {
    char mass[30];
    function(mass);
    return 0;
}

Пояснение
Добавление к типу * делает этот тип указателем. Советую просто найти литературу или просто поискать в гугле про "указатели в C++".
Но если вкратце - char a это тип "символ", а char* a это тип "указатель на символ" или "адрес ячейки в памяти, в которой лежит символ".
Когда мы работаем с массивами в Си и C++, мы можем указывать вместо char* char[]. Квадратные скобки семантически говорят программисту, что это не просто указатель, а указатель на начало массива. Со стороны программы запись char* и char[] совершенно одинакова. Проще говоря - это синтаксический сахар для лучшей читаемости программ.
Именно поэтому, когда нужно сделать функцию, которая что-то делает с переменной или массивом снаружи (то есть пришедшем в параметре), надо всегда делать тип параметра этой функции указателем или ссылкой.
Про ссылки расписывать не буду, ищи-читай на просторах интернета.


text:
Q: Получить значение ячейки Exel и вывести на экран Нашел в интернете примеры кода. Пытался совместить, чтобы получать значение ячейки и выводить на экран. Но что-то пошло не так... Кто может помочь решить эту проблему? Заранее благодарен
<?php
require_once 'PHPExel/Classes/PHPExcel.php';
$pExcel = PHPExcel_IOFactory::load('test.xlsx');

foreach ($pExcel->getWorksheetIterator() as $worksheet) {
    $tables[] = $worksheet->toArray();
}
$pExcel->setActiveSheetIndex(1);
$aSheet = $pExcel->getActiveSheet();
$test = $pExcel->getActiveSheet()->getCellValue('B2')
echo "| $test |";
?>


text:
Q: Container Managed Transaction in EJB If I mark an EJB to use Container Managed Transaction and from a method of that EJB I do not explicitly use setRollBackOnly() (when an Exception occurs), will that transaction still be flagged for rollback automatically?

A: It depends whether or not the exception is an application exception (commit by default) or a system exception (rollback always).  Application exceptions are most commonly checked exceptions declared on the throws clause, but they can also be declared via the @ApplicationException annotation (or corresponding <application-exception> element in the ejb-jar.xml).

A: If the thrown exception extends from RuntimeException then the transaction will roll back. If extends from Exception (and not is a RuntimeException) the transaction will commit.
Since ejb 3.0, you can change this behavior using the @AnnotationException (or the application-exception deployment descriptor element in ejb-jar.xml file)
Regardless of what class the exception extends, if you marked the class with @AnnotationException(rollback=true) the transaction will never commit, the oposite applies if you marke the exception with @AnnotationException(rollback=false).
Notice that if your code throws an exception, but you catch it before the container can intercept it, the exception will not affect the transaction state.


text:
Q: Allow customers add embed code to pleers I have a dating site project and I need to provide to customers possibility to upload embed code with pleer from 3rd part services like:
https://soundcloud.com/
http://joxi.ru/EA4zBRLsDloDzm

http://pleer.com/
http://joxi.ru/L21zEK6s6kR8RA
<object width="578" height="31"><param name="movie" value="http://embed.pleer.com/small/track?id=B2nq55Bgri8xfBumq&t=grey"></param><embed src="http://embed.pleer.com/small/track?id=B2nq55Bgri8xfBumq&t=grey" type="application/x-shockwave-flash" width="578" height="31"></embed></object>
 Cкачать Linkin Park - Numb бесплатно на pleer.com

e.t.c.
So any customer should be able to add embed pleer code from any(or most) 3rd part sound services. Now question - how can I create it secure way?
Or maybe someone can provide solution with validation for most popular services?
So customer fill some code and I need some way to validate is it real sound and is this code protected from injections.
Thanks!


text:
Q: How to group the rows and add a number I need sequential number on this group of items of students in Excel
enter image description here

A: Not really sure what you are trying to do but i think you can use COUNTIF formula:
In example if you want calculate Number 1  Adam students:
=COUNTIFS(A:A;"Adam";B:B;"1")

A: Enter the formula in cell B2 and drag down to get the numbers in sequence,
=IF(A1=A2,B1,MAX($B$1:$B1)+1)

Note:- Your student names in column A has to be sorted order as in image, or this formula would'nt work


text:
Q: Send message to Kafka when SessionWindows was started and ended I want to send a message to the Kafka topic when new SessionWindow was created and when was ended. I have the following code
stream
    .filter(user -> user.isAdmin)
    .keyBy(user -> user.username)
    .window(ProcessingTimeSessionWindows.withGap(Time.seconds(10)))
//what now? Trigger?

Now I want to send message when new session was started (with some metadata like web browser and timestamps, these informations are available in each element of stream) and send message to Kafka when session was ended (in this example 10 seconds after last element I think) with number of total requests.
It's possible in Flink? I think I should use some trigger but I don't know how and I can't find any example.

A: If You want to do this when the window is processed, then You can simply use the WindowProcessFunction, basically what You need to do is to add .process(new MyProcessFunction() to Your code. In the ProcessFunction You can have access to the whole window including its first (start) and last (end) element. You can simply use the Side output to just output the beginning and the end of the given window. You can then create a stream from side output and sink it to Kafka. More on Side outputs can be found here.

A: You can write a custom window trigger.

*

*How to tell a new session is started?
You can create a ValueState with the default value to null, so in case the state value is null, it is a session start.

*When the session ended?
Just before TriggerResult.FIRE.
Here is a demo based on ProcessingTimeTrigger of Flink, I only put the question-related logics here, you can check other details from the source code.
public class MyProcessingTimeTrigger extends Trigger<Object, TimeWindow> {
    // a state which keeps a session start.
    private final ValueStateDescriptor<Long> stateDescriptor = new ValueStateDescriptor<Long>("session-start", Long.class);

    @Override
    public TriggerResult onElement(Object element, long timestamp, TimeWindow window, TriggerContext ctx) throws Exception {
        ValueState<Long> state = ctx.getPartitionedState(stateDescriptor);
        if(state.value() == null) {
            // if value is null, it's a session start.
            state.update(window.getStart());
        }

        ctx.registerProcessingTimeTimer(window.maxTimestamp());
        return TriggerResult.CONTINUE;
    }

    @Override
    public TriggerResult onProcessingTime(long time, TimeWindow window, TriggerContext ctx) {
        // here is a session end.
        return TriggerResult.FIRE;
    }

    @Override
    public void clear(TimeWindow window, TriggerContext ctx) throws Exception {
        ctx.getPartitionedState(stateDescriptor).clear();
        ctx.deleteProcessingTimeTimer(window.maxTimestamp());
    }
}


text:
Q: Assignee for issue not set on creation I create a issue on GitLab like this(Python 3):
    user_id = int(11)

    gl_issue = requests.post(
        GITLAB_URL + '/api/v4/projects/%s/issues' % GITLAB_PROJECT_ID,
        headers={'PRIVATE-TOKEN': GITLAB_TOKEN,'SUDO': GITLAB_USER_NAMES.get(reporter, reporter)},
        verify=VERIFY_SSL_CERTIFICATE,
        data={
            'title': issue['fields']['summary'],
            'description': issue['fields']['description'],
            'created_at': issue['fields']['created'],
            'assignee_ids' : [user_id],
        })

Issue created but the assignee is not set. What am I doing wrong?

A: I used python-gitlab:
gl_issue = gl_issue.json()['iid']

project = gitlab.projects.get(GITLAB_PROJECT_ID)
issue = project.issues.get(gl_issue)
issue.assignee_id = user_id
issue.save()


text:
Q: AngularJs dynamic table performance issues I'm working on a project that requires a table to be dynamically constructed from an array of header objects:
[{ field: "name", show: true, title: "Name"},
 { field: "id", show: true, title: "ID"},
 { field: "time", show: true, title: "Time"}]

and an array of data objects that is updated at an interval:
[{ name: "Abc", id: 123, time: "300" },
 { name: "Def", id: 456, time: "10" }]

My template looks something like this:

      {{::header.title}}

        {{::row[col.field]}}

Please note that this is a simplified version but it holds the important bits.
As of now, rendering a table with 10 cols and 20 rows takes around 200ms (which creates a noticeable lag in scrolling and other page animations).
As you can see, I've tried to use one-time biding but that hasn't improved the performance noticeably.
Another thing I've tried was to 'track by' row.id, but this caused the data to stop updating altogether (The initial DOM object is reused even though some columns have changed).
So my question is, what measures should I take in order to optimize this configuration?
Any help would be greatly appreciated.
Thanks :)


text:
Q: How do I make a callback to get current position I have a function getLocation like this in my map.ts:
let location = this.geocoderService.getLocation(this.callbackPosition);

//Here do I want to wait for the location to use it in the setView method
if (location.length) {
    this.map.setView(location, 14);

    let toast = this.toastCtrl.create({
        message: 'Location was change successfully',
        duration: 3000,
        position: 'bottom',
        closeButtonText: 'OK',
        showCloseButton: true
    });
    toast.present();
}

And in the geoCoderService I have the getLocation method:
getLocation(callback) {
    let position = [
        this.lat,
        this.lng
    ]

    callback(position);
}

But how do I use the callback to return the position so the initializing of the map wait for the position


text:
Q: can I variate number in '{}' of [ '{:.3}'.format(i)) for i in mylist]? I have function that prints list in more comfortable way for me.
def pr(mylist):
    print ( [float('{:.3}'.format(i)) for i in mylist])

Can I also variate number of digits after decimal point? Something like that
def pr(mylist,r):
    print ( [float('{:.r}'.format(i)) for i in mylist])

For example
mylist = [-3.141592653589793, -2.5132741228718345, -1.8849555921538759]
pr(mylist,3) - [-3.14, -2.51, -1.88]

A: Yes, see Format Specification Mini-Language:
def pr(mylist,r):
    print ( [float('{:.{}}'.format(i,r)) for i in mylist])

pr([1.234567], 3)
# [1.23]


text:
Q: In GIMP 2.0 can you set new layers to be created at the bottom of the image instead of the top? Currently, when I create a new layer, it's at the very top of a rather tall canvas. All of my new layers need to be at the bottom (to make use of the "growth chart" background layer).
Is there a way to have them be created at the bottom of the canvas instead of the top, or is the only option to drag them all the way down manually?

A: Layers are created just above the current layer. If you want to consistently create layers at the bottom of the stack, add a transparent placeholder layer at the bottom of the stack and make it active just before creating a new layer.


text:
Q: String comparison with a don't care (ignore) character I have two lists, a golden strings list and a measured strings list. I have to compare these lists element by element.
The strings have exactly the same length. There are characters in the golden strings which are marked with 'X', and these should not considered in the comparison.
For example:
Golden = [
    '023XX1FD', 'FEBFF1B6', 'XXXXXXXX', '????????', '00000XXX',
    '00000000', '00000000', '00000000', '00000800'
]

Measured = [
    '0236C1FD', 'FEBFF1B6', '00F1FC3F', '????????', '00000000',
    '00000000', '00000000', '00000000', '00000800'
]

and comparison of '023XX1FD' with '0236C1FD' should return true since we should only be comparing the parts that are not equal to 'X' in the golden string.
For this example, the output is True for every string.

A: You can define your own string comparison function to go through the characters one by one and compare them, as long as the golden character is not the "Don't Care" value:
def myStringCompare(golden, measured, dont_care="X"):
    return (
        (len(golden) == len(measured)) and
        all(g == m for g, m in zip(golden, measured) if g != dont_care)
    )

Then use this function in a list comprehension:
print([myStringCompare(a, b) for a, b in zip(Golden, Measured)])
#[True, True, True, True, True, True, True, True, True]

A: You can use
[all(char1 == 'X' or char1 == char2 for char1, char2 in zip(str1, str2)) for str1, str2 in zip(list1, list2)]

A: I've been able to come up with the following list comprehension:
result_list = [
    all(
        [
            symbol == b[list_index][symbol_index]
            for symbol_index, symbol in enumerate(item)
            if symbol != "X"
        ]
    )
    for list_index, item in enumerate(a)
]

> [True, True, True, True, True, True, True, True, True]


text:
Q: how to disable symlinks in apache I tried to disable symlinks in apache so I updated apache2.conf (on ubuntu) to:
<Directory />
  Options -FollowSymLinks
  AllowOverride None
  Require all denied
</Directory>

but still symlinks continue to be followed for cgi-bin, from the browser.  Is there a different way to accomplish this?