text:
Q: Getting services from the command class How can I get a service from the command class? I have been trying to use ContainerAwareCommand as the parent of my command class, and then just using $this->getContainer()->get('my_service'), but when I run the command in cli, I get the following error:
Call to undefined method Symfony\Component\Console\Application::getKernel()
inside the getContainer() method of the ContainerAwareCommand class.
The file through which I run the command is:
<?php

    require_once __DIR__.'/../vendor/autoload.php';
    require_once __DIR__.'/AppKernel.php';

    use AppBundle\Console\Command\ChangeEmailCommand;
    use Symfony\Component\Console\Application;
    use Symfony\Component\Console\Input\ArgvInput;
    use Symfony\Component\Debug\Debug;

    $input = new ArgvInput();
    $env = $input->getParameterOption(array('--env', '-e'), getenv('SYMFONY_ENV') ?: 'dev');
    $debug = getenv('SYMFONY_DEBUG') !== '0' && !$input->hasParameterOption(array('--no-debug', '')) && $env !== 'prod';

    if ($debug) {
        Debug::enable();
    }

    $kernel = new AppKernel($env, $debug);
    $application = new Application($kernel);
    $application->add(new ChangeEmailCommand());
    $application->run();

A: You have to use the Application of the FrameworkBundle instead of the Console component. This class extends the one in the Console component, but adds awareness of the Kernel and the Container. Your Application version doesn't have this awareness (as it's designed for standalone use, outside of the Symfony context), resulting in a "method getKernel() does not exists".
So change this:
use Symfony\Component\Console\Application;

To:
use Symfony\Bundle\FrameworkBundle\Console\Application;

Btw, normally you won't need to create this file yourself. You can just use app/console in the Standard Edition: https://github.com/symfony/symfony-standard/blob/2.7/app/console when you installed Symfony using the installer/composer create-project.


text:
Q: Does .net 4.0 still support asmx
*

*I Opened my .net 2.0 ASMX webservice in VS2010 and migrated to .net4.0. If i simply run my ASMX w/o changing te code to WCF format i can still run old asmx service under .net 4.0 ?? will this work as it is?

*My web.config file also has WSE settings what happens to this?

*WCF/net4.0 does not support attachments, do i need to change my asmx webmethod to return as dataset in the body and will this work?

*I tried running my existing asmx service using dataset as attachments in .net 4.0 and it worked?

*I can see asmx file can be added in the .net 2010? are they still supported?

A: ASMX Web Services would fall under the .NET framework lifecycle. The .NET framework 4.0 and 4.5 support ASMX web services. Microsoft recomends that no new code be created using ASMX as pointed in the earlier answers.

A: To quote Microsoft:

This topic is specific to a legacy technology. XML Web services and XML Web service clients should now be created using Windows Communication Foundation.

Decide on your own what that means to you.
WCF completely replaces ASMX web services. People who complain about the complexity of WCF aren't paying attention. Go create a new WCF service and look at the actual code in the "hello world" service that the template creates. That's only more complicated than what the ASMX template created  because it includes two operations not just one.
Make no mistake about WSE, however. It's simply obsolete. Stop using it as soon as possible, and do not develop any new code using WSE.
Don't let anybody convince you that nothing has changed. It has. ASMX has been replaced by something much better, much more powerful, and much more flexible.

A: Yes, you can use ASMX in .NET 4.0 also.

Quoting Dave Ward from his reply to a comment on his post at Encosia named ASMX and JSON – Common mistakes and misconceptions

I think WCF is great in situations
  where you can take advantage of its
  strengths, like when you can use the
  tcpBinding mode. However, WCF's
  complexity makes it hard to seriously
  consider for simple AJAX callback
  functionality where a better targeted,
  more mature solution already exists.
ASMX is by no means deprecated or
  obsolete, even in .NET 4. That's
  actually one of the misconceptions I'm
  going to cover in this series.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Wordpress overwrite contact form mail_2 body Currently I am facing a problem to overwrite the body content of the mail_2 in the hook wpcf7_before_send_mail.
I am trying to rewrite a wpcf7 shortcode to a more proper presentation of the content with some html modifications.
The problem is that I can't overwrite the mail body. After I rewrite the body and print directly the result it seems to be back as the default body. When I print my modification directly, I see the modifications as I want them to be.
Example of code:
add_action("wpcf7_before_send_mail", "cf7_wpcf7_custom", 99, 1);

# Before sending email
function cf7_wpcf7_custom($properties, $contact_form_obj) {
    $submission = WPCF7_Submission::get_instance();
    $wpcf7      = WPCF7_ContactForm::get_current();

    $wpcf7->mail_2['body'] = str_replace('[checkbox-1]', '..test..', $wpcf7->mail_2['body']);

    // No changes appearing
    var_dump($wpcf7->mail_2['body']);

    exit;
}

A: The wpcf7_before_send_mail hook is performed before the additional mail is set. So it will be overwritten.
We can modify the mail body by using the filter wpcf7_additional_mail.
For example:
add_filter('wpcf7_additional_mail', 'customize_mail_2', 10, 2);
function customize_mail_2($additional_mail, $contact_form) {
    $submission = WPCF7_Submission::get_instance();
    $wpcf7      = WPCF7_ContactForm::get_current();

    $additional_mail['mail_2']['body'] = '..do your replacement stuff';
    return $additional_mail;
}

A: I was able to change Email 1 and 2 with following code in functions.php and add some self inserted code:
add_action( 'wpcf7_before_send_mail', 'wpcf7_add_couponnr_to_mail_body' );

function wpcf7_add_couponnr_to_mail_body($contact_form){

  // get mail property
  $mail = $contact_form->prop( 'mail' ); // returns array with mail values
  $mail2 = $contact_form->prop( 'mail_2' ); // returns array with mail values

  $couponnr = ...some insert code...;

  // add date (or other content) to email body
  $mail['body'] = str_replace("%%%COUPONNR%%%", $couponnr, $mail['body']);
  $mail2['body'] = str_replace("%%%COUPONNR%%%", $couponnr, $mail2['body']);

  // set mail property with changed value(s)
  $contact_form->set_properties( array( 'mail' => $mail ) );
  $contact_form->set_properties( array( 'mail_2' => $mail2 ) );

}


text:
Q: Filtering by .docx in ios document picker What is the Uniform Type Identifer to provide to a UIDocumentMenuViewController to allow a user to select *.docx files?
The documentation in System-Declared Uniform Type Identifiers does not list a public UTType that allows filtering by .docx. An identifier exists for a standard *.doc file but not *.docx, is there instead an alternate UTType?
This is my current code:
var allowedDocumentTypes = new string[] {
    UTType.RTF,
    UTType.Text,
    UTType.PDF,
    UTType.UTF8PlainText,
    UTType.RTFD,
    UTType.UTF16ExternalPlainText,
    UTType.UTF16PlainText,
    UTType.UTF8PlainText,
    UTType.FlatRTFD,
    "com.microsoft.word.doc",
    "com.microsoft.word.docx" // An attempt to include docx filtering.
};

var pickerMenu = new UIDocumentMenuViewController(allowedDocumentTypes, UIDocumentPickerMode.Open);
pickerMenu.DidPickDocumentPicker += (sender, args) =>
{
    args.DocumentPicker.DidPickDocument += (sndr, pArgs) =>
    {
        var securityEnabled = pArgs.Url.StartAccessingSecurityScopedResource();

        FileInfo fi = new FileInfo(pArgs.Url.Path);

        var result = new SelectFileResult();
        result.FilePath = fi.FullName;
        result.FileName = fi.Name;

        NSUrlRequest urlReq = NSUrlRequest.FromUrl(pArgs.Url);
        NSUrlResponse response;
        NSError error;;
        var data = NSUrlConnection.SendSynchronousRequest(urlReq, out response, out error);

        result.MimeType = response.MimeType;

        Action onFileConsumeDone = () =>
        {
            pArgs.Url.StopAccessingSecurityScopedResource();
        };

        onFileSelected(result, onFileConsumeDone);

    };

    // Display the document picker
    AppDelegate.TopViewController.PresentViewController(args.DocumentPicker, true, null);
};

pickerMenu.ModalPresentationStyle = UIModalPresentationStyle.Popover;
AppDelegate.TopViewController.PresentViewController(pickerMenu, true, null);

I had a shot in the dark and included the identifier com.microsoft.word.docx but it does not trigger filtering by docx.
My current solution is C# but objective-c and swift solutions accepted.

A: Try org.openxmlformats.wordprocessingml.document

A: Try
let supportedTypes: [UTType] = [UTType.content]


text:
Q: Unbiased estimator for mu
I have to find an unbiased estimator for $\mu$ where $\bar{X} = \frac{1}{n}(X_1+X_2+...+X_n)$ is the mean for a $\mathcal{N}(\mu,1)$-distribution.

I know that unbiased requires $E[\bar{X}] = \mu$ in this case but I am not sure whether or not my calculations are correct:
$$
E[\bar{X}] = E[\frac{1}{n}(X_1+X_2+...+X_n)] = \frac{1}{n} E[X_1+X_2+...+X_n] = \frac{1}{n} E[X_i] = \frac{1}{n} \mu = \mu.
$$
Thus $E[\bar{X}] = \mu$ and therefore $\bar{X}$ must be an unbiased estimator for $\mu$. Is this correct?

Furthermore I need to calculate the MSE. Thus I need to find
$$
E[(\bar{X}-\mu)^2] = Var(\bar{X}-\mu) + (E[\bar{X} - \mu ])^2 = Var(\bar{X}) = Var(\frac{1}{n} ( x_1+x_2+...+x_n) = \frac{1}{n^2} \cdot Var(x_i) = \frac{1}{n} \cdot Var(x) \cdot n = \frac{1}{n} \cdot Var(x) = \frac{1}{n}.$$
Is this also correct?

I do not have answers to the above questions and I am currently studying for my exam in probability and statistics.
Thanks in advance everyone for your help.

A: You have dropped the sum in both calculations. You should have:
$$\frac{1}{n}\sum_{i=1}^n \mathbb{E}[X_i] = \frac{1}{n}\sum_{i=1}^n \mu = \mu$$
and
$$\frac{1}{n^2}\sum_{i=1}^n Var(X_i) =\frac{1}{n^2}\sum_{i=1}^n 1 = \frac{1}{n}.$$


text:
Q: How to get the id of selected radio button in android? I am working on quiz application in android. We have created Select.java page which displays the questions and options(with radio buttons) from sqlite database. Also we created a header.java file for displaying buttons i.e back and next buttons for the Select.java page.

Here we need to get the selected radio button id and need to send that to Header class. Because header class consists of the next button onclick action. Once the next button is clicked the selected radio button value has to be stored in arraylist. We created radio buttons in Select.java class. So my question is how to get the selected radio button id into that next button click action. Please help me regarding this.
Thanks in Advance.

A: Your layout xml file should be like this
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent">

    <RadioGroup
    android:orientation="vertical"
    android:id="@+id/radiogroup"
     android:layout_width="wrap_content"
  android:layout_height="wrap_content"
    >
    <RadioButton
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:id="@+id/option1"
       android:text="Option1"
    />
    <RadioButton
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:id="@+id/option2"
       android:text="Option2"
    />
    <RadioButton
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:id="@+id/option3"
       android:text="Option3"
    />
    <RadioButton
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:id="@+id/option4"
       android:text="Option4"
    />
    <RadioButton
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:id="@+id/option5"
       android:text="Option5"
    />
    </RadioGroup>
</LinearLayout>

Add the below ode in your Activity
RadioGroup radioGroup = (RadioGroup) findViewById(R.id.radiogroup);
        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId)
            {
                RadioButton checkedRadioButton = (RadioButton) findViewById(checkedId);
                String text = checkedRadioButton.getText().toString();
                Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show();
            }
        });

A: I know it's a old question but i don't see my answer in anywhere and i found it more simple than others..
so here we go:
int myRadioChecked;
if(radioGroup.getCheckedRadioButtonId() == findViewById(R.id.YOUR_RADIO_BUTTON).getId()) {
  /**Do Stuff*/
  //ex.: myRadioChecked = 1;
}

A: final RadioGroup radioGroup = (RadioGroup) findViewById(R.id.MyRadioGroup);

radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {

    @Override
    public void onCheckedChanged(RadioGroup arg0, int arg1) {
        int selectedId = radioGroup.getCheckedRadioButtonId();
        Log.i("ID", String.valueOf(selectedId));

    }
});

A: In RadioGroup Class you can use method getCheckedRadioButtonId();
RadioGroup rg = findViewById(R.id.radioGroup);
rg.getCheckedRadioButtonId();

Returns the identifier of the selected radio button in this group. Upon empty selection, the returned value is -1.

A: Hmmm, just add one more member variable in UserBO to store selected answer.
Class UserBO {

private int userID;
private String userName;
private String question;
private String option1;
private String option2;
private String option3;

private int answerID;

//create getter and setters for above member variables
}

then within onclick listener of Adapter class, do like as following
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(RadioGroup radioGroup,
                int radioButtonID) {
        switch(radioButtonID) {
                case R.id.option1:
                       listItem.setAnswerID(1);
            break;
        case R.id.option2:
                listItem.setAnswerID(2);
            break;

                 }
        }
    });

then change your header constructor to receive userarraylist (which contains user details with answer)
ArrayList<USerBO> userList;
Header(Context context, AttributeSet attrs, ArrayList<UserBO> userALt) {
userList = userAL;
}

//on next button click

onclick() {
    for(UserBO userObj: userList) {
        if (userObj.getAnswerID != 0)
         Log.d("AnswerID", userObj.getAnswerID);
    }
}

it just like sudo code.. i hope this will help u..

A: you can get the id of selected button by the following this.Here
int position = group.indexOfChild(radioButton);

will give you the id.Also you can to Toast to see id like this
 Toast.makeText(MainActivity.this,"Id of radio button"+position+, Toast.LENGTH_SHORT).show();

This will pop up - "Id of radio button you clicked is 0" if you clicked first button.

A: This is the best way:
RadioButton button = findViewById(v.getId());


text:
Q: Variable displaying as NaN I have a variable that keeps showing up as NaN. I can't figure out why it is doing this.
This doesn't show up as NaN, it displays the value it should (from a jQuery UI slider).
var gdHours = $("#gdhours").val();

But my next bit of code always displays as NaN, and it keeps the rest of the calculations in the function from working. Shown here:
var gdCost = $("#gdcost").val(gdHours*20);

I have tried using parseInt and parseFloat and it doesn't work. Any suggestions?

A: The setter val(NEW_VALUE) returns the jQuery object. You could write
var gdCost = $("#gdcost").val(gdHours*20).val();

instead.

A: When you pass a parameter to the val(...) function, it returns the object, not the value. So in the second example is equivalent to the following:
$("#gdcost").val(gdHours*20);
var gdCost = $("#gdcost");

So the jQuery object is returned, not the value of the element.
jQuery does this to support function call chaining.

A: you can cast an integer like
foo = parseInt($('#foo').val());

because input type="text" may return a string by using val() and you cant multiply a string


text:
Q: *.so library from included *.jar involves UnsatisfiedLinkError I've wrote android app with native shared library ( libnativeext.so ).
Inside java class in app I load libnativeext.so with
System.loadLibrary("nativeext").
All works great.
Native code compiles, and libnativeext.so places in /libs/armeabi/ folder.
So final first.apk file contains /lib/armeabi/libnativeext.so, installs on device and all work ok.
Then I export project in javaext.jar.
At this point javaext.jar contains libnativeext.so in /libs/armeabi/.
In the new project (second-proj) I include javaext.jar and add path to javaext.jar in java build path.
Project builds with only warning about native library in javaext.jar.
I disable warning in eclipse preferences.
But on device I got: java.lang.UnsatisfiedLinkError: Couldn't load nativeext: findLibrary returned null
Strange, because second.apk have /libs/armeabi/libnativeext.so inside. I go to phone and figure out than folder on phone /data/data/myapp/lib/ is EMPTY! And ofcourse System.loadLibrary can't find libnativeext.so.
I find solution for myself, but it looks very ugly, and I want to find better way.
I create inside existing  second-proj/libs/ folder armeabi and place libnativeext.so inside.
second-proj:
/libs/armeabi/libnativeext.so
/libs/javaext.jar
When I build project, I look inside second.apk:
/lib/armeabi/libnativeext.so   <--- new one
/libs/armeabi/libnativeext.so
And this version work perfect on the phone.
So I assume, that during installation libraries from /libs/armeabi/ is ignored, and only libraries from /lib/armeabi/ is installed on the phone.
So question is: How to force apk bulder to copy *.so from *.jar to right *.apk folder?

A: In case there are no way to pack *.so library from included *.jar into final *.apk I solve this problem for myself.
I write LibraryLoader, which:

*

*Tries to load library with System.loadLibrary().

*If it fails, loader search library in application storage, and if find loads it with System.load().

*If no library was found in the app storage, it find .apk file, serch there, and if loader find library - copies it to app storage, then loads it with System.load().
Post code here - may be it helps somebody.
    import java.io.BufferedOutputStream;
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.util.Enumeration;
    import java.util.zip.ZipEntry;
    import java.util.zip.ZipFile;

    import android.content.Context;
    import android.util.Log;

    public class SharedLibraryLoader
    {
        private static Context context;
        private static String libDir = "lib";
        private static String shortLibName;
        private static String fullLibName;

        static public boolean loadLibrary(String libName, Context ctx)
        {
    context = ctx;
    shortLibName = libName;
    fullLibName = "lib" + libName + ".so";

    try
    {
        Log.d("SharedLibraryLoader", "Trying to load library");
        System.loadLibrary(shortLibName);
        Log.d("SharedLibraryLoader", "Library was loaded from default location");
        return true;
    }
    catch(UnsatisfiedLinkError e)
    {
        Log.d("SharedLibraryLoader","Lib wasn't found at default location. Trying to find in application private storage");
        String path = null;
        path = findInAppStorage(fullLibName);
        if(path != null)
        {
            Log.d("SharedLibraryLoader","Lib was found in application private storage. Loading lib...");
            System.load(path);
            return true;
        }
        else
        {
            Log.d("SharedLibraryLoader","Lib was not found in application private storage. Trying to find in apk...");
            path = findInApkAndCopyToAppStorage(fullLibName);

            if(path != null)
            {
                Log.d("SharedLibraryLoader","Lib was found in apk and copied to application private storage. Loading lib...");
                System.load(path);
                return true;
            }
            else
            {
                Log.d("SharedLibraryLoader", "FAILED TO LOAD LIBRARY");
                return false;
            }
        }
    }
        }

        static private String findInAppStorage(String libName)
        {

    Log.d("SharedLibraryLoader","enter findInAppStorage()");
    String basePath = context.getApplicationInfo().dataDir;
    File dataDir = new File(basePath);

    String[] listFiles;
    String  lib = null;
    listFiles = dataDir.list();

    for(int i=0; i < listFiles.length; i++)
    {
        lib = findInStorage(basePath + "/" +listFiles[i], libName);

        if(lib != null)
        {
            return lib;
        }
            }

    Log.d("SharedLibraryLoader", "Lib wasn't found.");
    return null;
        }

        static private String findInStorage(String path, String nameOfLib)
        {
    File file = new File(path);
    if(file.isDirectory())
    {
        Log.d("SharedLibraryLoader","Strorage__dir: " + path + "/");
        String[]    list = file.list();
        String      target = null;
        for(int i = 0; i < list.length; i++)
        {
            target = findInStorage(path + "/" + list[i], nameOfLib);
            if(target != null)
            {
                return target;
            }
        }
    }
    else
    {
        Log.d("SharedLibraryLoader","Strorage_file: " + path);
        if(path.contains(nameOfLib))
        {
            Log.d("SharedLibraryLoader","Lib was found in: " + path);
            return path;
        }
    }
    return null;
        }

        static private String findInApkAndCopyToAppStorage(String libName)
        {
            Log.d("SharedLibraryLoader", "Enter findInApkAndCopyToStorage()");

            // ---------------- ZIP - find path to .so  inside .apk ------------------
    String apkPath = context.getPackageResourcePath();
    Log.d("SharedLibraryLoader", String.format("Path to Package resource is: %s", apkPath));

    try
    {
        ZipFile zf = new ZipFile(apkPath);

        Enumeration<ZipEntry> zipFiles = (Enumeration<ZipEntry>) zf.entries();
        ZipEntry    soZipEntry = null;
        ZipEntry    tempZipEntry;
        String      tmpString;
        for ( ; zipFiles.hasMoreElements();)
        {
            tempZipEntry = zipFiles.nextElement();
            tmpString = tempZipEntry.getName();

            if(tmpString.contains(libName))
            {
                Log.d("SharedLibraryLoader", "Library " + fullLibName + " was found in: " + tmpString);
                soZipEntry = tempZipEntry;
            }
        }

        //----------now copy library---------------
        Log.d("SharedLibraryLoader", "soZipEntry = " + soZipEntry.toString());

        if(soZipEntry != null)
        {
            InputStream soInputStream = zf.getInputStream(soZipEntry);

            File fileDir;
            File soFile;
            OutputStream outStream;
            fileDir = context.getApplicationContext().getDir(libDir, Context.MODE_PRIVATE); // but "app_lib" was created!
            String fullSoFilePath = fileDir.getAbsolutePath() + "/" + libName;
            Log.d("SharedLibraryLoader", "New libpath is "+ fullSoFilePath);
            soFile = new File(fullSoFilePath);

            Log.d("SharedLibraryLoader", "Is file already exists? - " + soFile.exists());

            outStream = new BufferedOutputStream(new FileOutputStream(soFile));

            Log.d("SharedLibraryLoader", "Start copying library...");
            byte[] byteArray = new byte[256];
            int copiedBytes = 0;

            while((copiedBytes = soInputStream.read(byteArray)) != -1)
            {
                outStream.write(byteArray, 0, copiedBytes);
            }

            Log.d("SharedLibraryLoader", "Finish copying library");
            outStream.close();

            soInputStream.close();
            return fullSoFilePath;
        }
        else
        {
            Log.d("SharedLibraryLoader", "Library not Found in APK");
            return null;
        }
    }
    catch (IOException e)
    {
        e.printStackTrace();
        return null;
    }
        }
            }


text:
Q: C++ Using Enum with Static Method new to QT5 only have done a little C++.  Mostly C#.  anyway, trying to make an enum and use it in a static method in a class.  the class file does not see the enum (compliler errors are "unknown Type name ActionNames.".  tried a few things, moving enum out of the class, using Gui:: in front of ViewNames in cpp file  etc.  I'm sure this is a pretty easy thing - but how can I do this? thank you.
Gui.h
#ifndef GUI_H
#define GUI_H

#include <QObject>

class Gui
{
public:
    Gui();

    enum ViewNames
    {
    MAIN_VIEW,
    WORK_VIEW
    };

    enum ActionNames
    {
    BACK,
    HOME
    };
    static std::string GetViewStringFor(ViewNames view);
    static std::string GetActionStringFor(ActionNames view);
};

#endif // GUI_H

Gui.cpp
#ifndef GUI_H
#define GUI_H

#include <QObject>

#include "Gui.h"

class Gui
{
public:
    Gui();

    static std::string GetViewStringFor(ViewNames view)
    {
        return "";
    }
    static std::string GetActionStringFor(ActionNames view)
    {
        return "";
    }
};

#endif // GUI_H

A: You have declared the class twice slightly differently: once in gui.cpp and once in gui.h
The difference in the two classes is that the enum definitions aren't declared in the class in gui.cpp.
Your gui.cpp file defines the GUI_H symbol and then includes gui.h which checks for the GUI_H symbol.  Because it exists nothing in gui.h is included.
So that means the class in gui.cpp is the one that is used and the one in gui.h is ignored, but the enums aren't declared in the class in gui.cpp so the compiler can't find them.
To fix it, change gui.cpp like this:
#include <QObject>
#include "Gui.h"

Gui::Gui()
{
}
static std::string Gui::GetViewStringFor(Gui::ViewNames view)
{
    return "";
}
static std::string Gui::GetActionStringFor(Gui::ActionNames view)
{
    return "";
}

A: big oversight - the cpp file included class again... whoops... thanks everyone.
#include "Gui.h"

Gui::Gui()
{

}

static std::string GetViewStringFor(Gui::ViewNames view)
{
    return "";
}

static std::string GetActionStringFor(Gui::ActionNames view)
{
    return "";
}


text:
Q: Prevent pdflatex.ini repair when updating packages in miktex I've installed Miktex for the local user only so it is installed in C:\Users\~\AppData\Local\Programs\MiKTeX 2.9. I had to add save_size=80000 to pdflatex.ini in ..\miktex\config to avoid errors when compiling a large document.
However, each time I update packages with the package manager the pdflatex.ini is repaired to its original. Is there any way around this?

A: Run on the command line
 initexmf --edit-config-file pdflatex

This will open a local pdflatex.ini in which you can put your save-size setting


text:
Q: Can I temporarily hide indicators to reduce clutter?
Possible Duplicate:
Can I blacklist an appindicator?

I currently have 9 indicators (old-style and new-style appindicators) sitting in my Ubuntu taskbar. In time I'm sure some of them will migrate to a better location (for example, I presume both SpiderOak and Dropbox are supposed to be under the mail indicator, just like Ubuntu One). Until then, I want to reduce the clutter!
In Windows there is an option to hide (but not remove) system tray icons.[1] When you click on a reveal button, the hidden icons are revealed and you can use them as normal. Is there a similar function in Ubuntu?
[1] I could remove old-style non-appindicators from the systray-whitelist, but it would be a major hassle when I want to show them again.

A: Currently there is no such an option in Unity and as far as I've seen Ubuntu 11.10 doesn't have it either.


text:
Q: numpy.genfromtxt path value I would like to load a txt file with genformtxt(). the txt file is already in c:.
stock=np.genfromtxt('c:\09012017.txt',delimiter=' ',dtype=str,skip_header=1)

C:\Anaconda3\lib\site-packages\numpy\lib\npyio.py in genfromtxt(fname, dtype, comments, delimiter, skip_header, skip_footer, converters, missing_values, filling_values, usecols, names, excludelist, deletechars, replace_space, autostrip, case_sensitive, defaultfmt, unpack, usemask, loose, invalid_raise, max_rows)
   1549                 fhd = iter(np.lib._datasource.open(fname, 'rbU'))
   1550             else:
-> 1551                 fhd = iter(np.lib._datasource.open(fname, 'rb'))
   1552             own_fhd = True
   1553         else:

C:\Anaconda3\lib\site-packages\numpy\lib\_datasource.py in open(path, mode, destpath)
    149
    150     ds = DataSource(destpath)
--> 151     return ds.open(path, mode)
    152
    153

C:\Anaconda3\lib\site-packages\numpy\lib\_datasource.py in open(self, path, mode)
    492
    493         # NOTE: _findfile will fail on a new file opened for writing.
--> 494         found = self._findfile(path)
    495         if found:
    496             _fname, ext = self._splitzipext(found)

C:\Anaconda3\lib\site-packages\numpy\lib\_datasource.py in _findfile(self, path)
    335
    336         for name in filelist:
--> 337             if self.exists(name):
    338                 if self._isurl(name):
    339                     name = self._cache(name)

C:\Anaconda3\lib\site-packages\numpy\lib\_datasource.py in exists(self, path)
    440
    441         # Test local path
--> 442         if os.path.exists(path):
    443             return True
    444

C:\Anaconda3\lib\genericpath.py in exists(path)
     17     """Test whether a path exists.  Returns False for broken symbolic links"""
     18     try:
---> 19         os.stat(path)
     20     except OSError:
     21         return False

ValueError: stat: embedded null character in path

it looks like sth wrong in path .  I am 100% sure the txt is under disc c: path.
pls give some help. Thanks

A: You either have to use a forward slash, or a double backslash
stock=np.genfromtxt('c:/09012017.txt',delimiter=' ',dtype=str,skip_header=1)

or
stock=np.genfromtxt('c:\\09012017.txt',delimiter=' ',dtype=str,skip_header=1)

If you use just one backslash it will be seen as an escape command, which is not the thing you want to do there.
If you just call the filename and not the absolute path, the file has to be located in the working directory of the python process; this is the working directory of the shell, which started you python process.


text:
Q: Java/JVM (HotSpot): Is there a way to save JIT performance gains at compile time? When I measure the throughput of my Java application, I see a 50% performance increase over time:

*

*For the first 100K messages, I get ~3,000 messages per second

*For the second 100K messages, I get ~4,500 messages per second.

I believe the performance improves as JIT optimizes the execution path.
The reason given for not saving the JIT compilation is that "the optimizations that the JVM performs are not static, but rather dynamic, based on the data patterns as well as code patterns. It's likely that these data patterns will change during the application's lifetime, rendering the cached optimisations less than optimal."
However, I know for a fact that these data patterns won't change during my application's lifetime, or even over multiple application lifetimes. So how can I "save" these performance gains in the HotSpot JVM?
See also, the relevant question and discussion.

A: You could try adapting your app to run it with Nailgun. Instead of invoking your app against a fresh JVM each time you invoke it against a Nailgun server which is a long-lived JVM. The second time you invoke your app, the nailgun JVM will have optimized the paths in your classes and should therefore execute a lot faster than it would from fresh.

A: Use '-server' to do much more up front. Hotspot does not as far as I know allow for saving jit information between runs so -server is the simplest way to tell it what you want it to do.

A: Are you sure it is CPU related and not IO related? I have seen this behaviour a lot of times, when hitting a cold cache somewhere worsens performance.

A: Few more options to tune up the JIT.
1. Class Data sharing
http://publib.boulder.ibm.com/infocenter/javasdk/v6r0/index.jsp?topic=%2Fcom.ibm.java.doc.user.aix64.60%2Fuser%2Fclassdatasharing.html
2. Tiered Compilation
See details for flag -XX:+TieredCompilation
3. Custom CompileThreshold
Controls number of invocations of a function that would make it eligible for JIT compile.
See details for flag  -XX:CompileThreshold. Never make this to ZERO or ONE. Your tampering here may result in deterioration of performance. JVM gives you the option though. -server defaults this to 10000.


text:
Q: Setting jax-ws client timeout I've trouble setting jax-ws timeout. My code is:
@WebServiceClient(name = "VoipDBJDBCService", targetNamespace = "http://db.server.voipmeter.jextreme.eu/", wsdlLocation = "http://trace0.nyc.blinkmind.com:8080/voipdb?wsdl")
public class VoipDBJDBCService extends Service {
    public VoipDBJDBCService(URL wsdlLocation) {
        super(wsdlLocation, new QName("http://db.server.voipmeter.jextreme.eu/", "VoipDBJDBCService"));
    }

    @WebEndpoint(name = "VoipDBJDBCPort")
    public VoipDB getVoipDBJDBCPort() {
        return super.getPort(new QName("http://db.server.voipmeter.jextreme.eu/", "VoipDBJDBCPort"), VoipDB.class);
    }
}

And the usage:
VoipDB db = new VoipDBJDBCService(new URL(url)).getVoipDBJDBCPort();

How do i Hook in timeouts ? I've found "solution" here: https://jax-ws.dev.java.net/guide/HTTP_Timeouts.html but I don't know where I shall hook it in. How to obtain proxy ? When I call getPort client tries to connect and then hangs forever if server is not responding.
UPDATE:
This code is invoked from within applets init() method if that makes any difference.

A: With Metro/Glassfish...
//1 minute for connection
((BindingProvider) wsPort).getRequestContext().put("com.sun.xml.ws.connect.timeout", 1 * 60 * 1000);

//3 minutos for request
((BindingProvider) wsPort).getRequestContext().put("com.sun.xml.ws.request.timeout", 3 * 60 * 1000);

A: If you are using a Sun JRE, you can set the following system properties for default network connect and read timeouts (in milliseconds). I haven't tried these with the JAX-WS client, but they ought work there as well:
sun.net.client.defaultConnectTimeout
sun.net.client.defaultReadTimeout

Addition: I missed your last part of the question where you said that you are doing this in an applet. If the applet is running with default permissions, you are probably not allowed to set the system properties.

A: ProxyWs proxy = (ProxyWs) factory.create();
Client client = ClientProxy.getClient(proxy);
HTTPConduit http = (HTTPConduit) client.getConduit();
HTTPClientPolicy httpClientPolicy = new HTTPClientPolicy();
httpClientPolicy.setConnectionTimeout(0);
httpClientPolicy.setReceiveTimeout(0);
http.setClient(httpClientPolicy);

This worked for me.

A: You can cast your VoipDB object to BindingProvider. So in the example in the link you've given just replace proxy by db and you're good to go.

A: Here is one example
public void testConfigureTimeout() throws Exception
{
   //Set timeout until a connection is established
   ((BindingProvider)port).getRequestContext()
   .put("javax.xml.ws.client.connectionTimeout", "6000");

   //Set timeout until the response is received
   ((BindingProvider) port).getRequestContext()
   .put("javax.xml.ws.client.receiveTimeout", "1000");

    port.echo("testTimeout");
}


text:
Q: Which one is correct - "Committed to help .." or "Committed to helping .."? Consider "I'm committed to help somebody to do something/with something." vs. "I'm committed to helping somebody. to do something/with something."

A: I think the phrase should be:
I am committed to help somebody with something.
I have committed to helping somebody with something.


text:
Q: Display the value of a variable in itself I am doing a quine in Ruby that will display its own code in a new file. I'm trying to do like the following to print the variable itself in the new file:
$var = "Some Code%c$var = %c%s%c % [10,34,$var,34,10]%cSome Code" % [10,34,$var,34,10]

The $var variable is empty in the new file, and this is what I want:
Some Text
$var = "Some Code%c$var = %c%s%c % [10,34,$var,34,10]%cSome Code" % [10,34,$var,34,10]
Some Text

When I launch it, I get this in the new file:
Some Code
$var = "" % [10,$var,10]
Some Code

Help please.

A: You need to escape the percent sign (%%) located within the string and also wrap the $var assignment expression in parentheses so it's available for the following interpolation like so:
($var = "Some Code%c($var = %c%s%c) %% [10,34,$var,34,10]%cSome Code") % [10,34,$var,34,10]

This should result in the following:
>> ($var = "Some Code%c($var = %c%s%c) %% [10,34,$var,34,10]%cSome Code") % [10,34,$var,34,10]
=> "Some Code\n($var = \"Some Code%c($var = %c%s%c) %% [10,34,$var,34,10]%cSome Code\") % [10,34,$var,34,10]\nSome Code"


text:
Q: how to echo specific value from array in another array i am using this code to export 3 currency info from coinmarketcap api ↓ :
<?php
$url = 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest';
$parameters = [
  'start' => '1',
  'limit' => '3',
  'convert' => 'USD'
];

$headers = [
  'Accepts: application/json',
  'X-CMC_PRO_API_KEY: my_own_key'
];
$qs = http_build_query($parameters); // query string encode the parameters
$request = "{$url}?{$qs}"; // create the request URL

$curl = curl_init(); // Get cURL resource
// Set cURL options
curl_setopt_array($curl, array(
  CURLOPT_URL => $request,            // set the request URL
  CURLOPT_HTTPHEADER => $headers,     // set the headers
  CURLOPT_RETURNTRANSFER => 1         // ask for raw response instead of bool
));
header('Content-Type: application/json');
$response = curl_exec($curl); // Send the request, save the response
print_r(json_decode($response)); // print json decoded response
echo $response[1]->name;
curl_close($curl); // Close request
?>
-------------

result is ↓:

---------------
stdClass Object
(
    [status] => stdClass Object
        (
            [timestamp] => 2021-06-05T17:35:04.344Z
            [error_code] => 0
            [error_message] =>
            [elapsed] => 12
            [credit_count] => 1
            [notice] =>
            [total_count] => 5530
        )

    [data] => Array
        (
            [0] => stdClass Object
                (
                    [id] => 1
                    [name] => Bitcoin
                    [symbol] => BTC
                    [slug] => bitcoin
                    [num_market_pairs] => 9702
                    [date_added] => 2013-04-28T00:00:00.000Z
                    [tags] => Array
                        (
                            [0] => mineable
                            [1] => pow
                            [2] => sha-256
                            [3] => store-of-value
                            [4] => state-channels
                            [5] => coinbase-ventures-portfolio
                            [6] => three-arrows-capital-portfolio
                            [7] => polychain-capital-portfolio
                            [8] => binance-labs-portfolio
                            [9] => arrington-xrp-capital
                            [10] => blockchain-capital-portfolio
                            [11] => boostvc-portfolio
                            [12] => cms-holdings-portfolio
                            [13] => dcg-portfolio
                            [14] => dragonfly-capital-portfolio
                            [15] => electric-capital-portfolio
                            [16] => fabric-ventures-portfolio
                            [17] => framework-ventures
                            [18] => galaxy-digital-portfolio
                            [19] => huobi-capital
                            [20] => alameda-research-portfolio
                            [21] => a16z-portfolio
                            [22] => 1confirmation-portfolio
                            [23] => winklevoss-capital
                            [24] => usv-portfolio
                            [25] => placeholder-ventures-portfolio
                            [26] => pantera-capital-portfolio
                            [27] => multicoin-capital-portfolio
                            [28] => paradigm-xzy-screener
                        )

                    [max_supply] => 21000000
                    [circulating_supply] => 18727431
                    [total_supply] => 18727431
                    [platform] =>
                    [cmc_rank] => 1
                    [last_updated] => 2021-06-05T17:34:02.000Z
                    [quote] => stdClass Object
                        (
                            [USD] => stdClass Object
                                (
                                    [price] => 36108.810885716
                                    [volume_24h] => 34482634689.161
                                    [percent_change_1h] => -0.22000049
                                    [percent_change_24h] => -2.95972194
                                    [percent_change_7d] => 5.12257226
                                    [percent_change_30d] => -36.74685465
                                    [percent_change_60d] => -38.11198041
                                    [percent_change_90d] => -29.1772556
                                    [market_cap] => 676225264354.3
                                    [last_updated] => 2021-06-05T17:34:02.000Z
                                )

                        )

                )

            [1] => stdClass Object
                (
                    [id] => 1027
                    [name] => Ethereum
                    [symbol] => ETH
                    [slug] => ethereum
                    [num_market_pairs] => 6019
                    [date_added] => 2015-08-07T00:00:00.000Z
                    [tags] => Array
                        (
                            [0] => mineable
                            [1] => pow
                            [2] => smart-contracts
                            [3] => ethereum
                            [4] => coinbase-ventures-portfolio
                            [5] => three-arrows-capital-portfolio
                            [6] => polychain-capital-portfolio
                            [7] => binance-labs-portfolio
                            [8] => arrington-xrp-capital
                            [9] => blockchain-capital-portfolio
                            [10] => boostvc-portfolio
                            [11] => cms-holdings-portfolio
                            [12] => dcg-portfolio
                            [13] => dragonfly-capital-portfolio
                            [14] => electric-capital-portfolio
                            [15] => fabric-ventures-portfolio
                            [16] => framework-ventures
                            [17] => hashkey-capital-portfolio
                            [18] => kinetic-capital
                            [19] => huobi-capital
                            [20] => alameda-research-portfolio
                            [21] => a16z-portfolio
                            [22] => 1confirmation-portfolio
                            [23] => winklevoss-capital
                            [24] => usv-portfolio
                            [25] => placeholder-ventures-portfolio
                            [26] => pantera-capital-portfolio
                            [27] => multicoin-capital-portfolio
                            [28] => paradigm-xzy-screener
                        )

                    [max_supply] =>
                    [circulating_supply] => 116168370.374
                    [total_supply] => 116168370.374
                    [platform] =>
                    [cmc_rank] => 2
                    [last_updated] => 2021-06-05T17:34:02.000Z
                    [quote] => stdClass Object
                        (
                            [USD] => stdClass Object
                                (
                                    [price] => 2623.0501255974
                                    [volume_24h] => 29873289567.151
                                    [percent_change_1h] => -0.77281419
                                    [percent_change_24h] => -3.22775583
                                    [percent_change_7d] => 13.22095983
                                    [percent_change_30d] => -26.86990803
                                    [percent_change_60d] => 23.92154062
                                    [percent_change_90d] => 56.91903203
                                    [market_cap] => 304715458499.97
                                    [last_updated] => 2021-06-05T17:34:02.000Z
                                )

                        )

                )

            [2] => stdClass Object
                (
                    [id] => 825
                    [name] => Tether
                    [symbol] => USDT
                    [slug] => tether
                    [num_market_pairs] => 13422
                    [date_added] => 2015-02-25T00:00:00.000Z
                    [tags] => Array
                        (
                            [0] => store-of-value
                            [1] => payments
                            [2] => stablecoin
                            [3] => stablecoin-asset-backed
                            [4] => solana-ecosystem
                        )

                    [max_supply] =>
                    [circulating_supply] => 62209255385.452
                    [total_supply] => 64476291004.33
                    [platform] => stdClass Object
                        (
                            [id] => 1027
                            [name] => Ethereum
                            [symbol] => ETH
                            [slug] => ethereum
                            [token_address] => 0xdac17f958d2ee523a2206206994597c13d831ec7
                        )

                    [cmc_rank] => 3
                    [last_updated] => 2021-06-05T17:34:08.000Z
                    [quote] => stdClass Object
                        (
                            [USD] => stdClass Object
                                (
                                    [price] => 1.0004588605114
                                    [volume_24h] => 73072076028.18
                                    [percent_change_1h] => 0.01364608
                                    [percent_change_24h] => -0.08415844
                                    [percent_change_7d] => -0.01154942
                                    [percent_change_30d] => 0.03709874
                                    [percent_change_60d] => -0.09232759
                                    [percent_change_90d] => 0.00764482
                                    [market_cap] => 62237800756.194
                                    [last_updated] => 2021-06-05T17:34:08.000Z
                                )

                        )

                )

        )

)

this result is array in another array in another array ...
i cant understand for example:
how to echo 'price' of each 'id'

A: $json=json_decode($response,true);
echo $json['data']['0']['name'];
finally i lost time but finally found answer.


text:
Q: run vbscript mhta i want to run vbscript from mhta

A: mshta "vbscript:window.close(msgbox("test"))"

WScript or CScript script hosts are not able to run a script if it is not stored in a file. But you can use mshta and the vbscript: protocol to run simple commands.
Anyway, for this case, it is easier to use
msg console "test"

edited to adapt to comments
i've being testing. vbscript parser in the mshta url has to face a lot of limitations. And problems with spaces, concatenation of commands with :, problems with procedure calling as a function but you can not use call keyword as a space is required, ....
The only stable, "easy" way of doing it is to prepare the vbscript to execute as a string, with no spaces inside it, and use the execute method to run it
mshta "vbscript:window.close(execute("msgbox"&chr(32)&"""test"":msgbox"&chr(32)&"""this"&chr(32)&"should"&chr(32)&"work"""))"
mshta "vbscript:window.close(execute("server=CreateObject(""WScript.Shell"").RegRead(""HKEY_CURRENT_USER\Volatile"&chr(32)&"Environment\LOGONSERVER""):For"&chr(32)&"i=1"&chr(32)&"to"&chr(32)&"3:msgbox"&chr(32)&"i"&chr(38)&"server:next"))"


text:
Q: Make ExtJS member variable private Ext.define("rgpd.user.Profile", {

    config: {
        id: -1,
        role: 0,
        token: '',
        corps_metier: [],
    },

    constructor: function(config) {
        this.initConfig(config);
        this.callParent(arguments);
    }
});

I have this class definition. I need to have a global access to this and the object values (using getters and setters) but the member variables (id, token, role etc.) have to be unreachable from console. I tried using private property but it didn't work
edit:
from the example given
Ext.application({ name : 'Fiddle',

launch : function() {
    Ext.Msg.alert('Fiddle', 'Welcome to Sencha Fiddle!');
}

});

Ext.define('MyWindow', (function (){
    var isWindow = true;

    var isPrivateProp = true;

   return {
       isWindow: isWindow
   };
})());

var myWindow = new MyWindow();
console.log('object: ', MyWindow);
console.log('isWindow: ', myWindow.isWindow);
console.log('isPrivateProp: ', myWindow.isPrivateProp);

myWindow.isPrivateProp = false;
console.log('isPrivateProp: ', myWindow.isPrivateProp);

if i do this isPrivateProp value is reset to false. I want the property to be accessible ONLY using my getters function and i want to be able to change the property value ONLY using my setters

A: A basic example of a pattern which can be applied with ExtJs to have private members:
Ext.define('MyButton', (function(){
  function privateStaticMethod() {
    console.log('static method');
  }

  function privateMethod(me) {
    console.log(me.getText());
  };

  function privateMethod2() {
    console.log(this.getText());
  }

  return {
    extends: 'Ext.button.Button',
    text: 'Click me',

    // will be called when the button was clicked
     handler: function() {
      privateStaticMethod();
      privateMethod(this);
      privateMethod2.apply(this);
    }
};

})()
);

Source:
http://flexblog.faratasystems.com/index.php/private-methods-in-ext-js/
Edit:
Go to https://fiddle.sencha.com/#view/editor
paste this code observe console:
Ext.application({
    name : 'Fiddle',

    launch : function() {
        Ext.Msg.alert('Fiddle', 'Welcome to Sencha Fiddle!');
    }
});

    Ext.define('MyWindow', (function (){
        var isWindow = true;

        var isPrivateProp = true;

       return {
           isWindow: function () { return isWindow }
       };
    })());

    var myWindow = new MyWindow();
    console.log('object: ', MyWindow);
    console.log('isWindow: ', myWindow.isWindow);
    console.log('isPrivateProp: ', myWindow.isPrivateProp);


text:
Q: USB Audio Device Loopback Through Speakers I have a USB turntable which when plugged in to my Ubuntu 10.10 machine appears in the audio settings as an input device (USB PnP Audio Device Analog Stereo) like a microphone.
What I'd like to be able to do is have the sound for that audio device played back through the audio output (speaker or whatever). I'm not too worried if there's a slight delay between the audio coming in and it being played out through the speakers.
As far as I'm aware this is refereed to as software loopback. I can achieve exactly what I want if I open Audacity, enable software loopback and press record. Obvious this isn't ideal as I don't really want it recording what I'm playing all the time.
I know this is possible because of the Audacity example however I'd like to know if there's a way to do it without it recording. I've search around for a while for a piece of software that does this, however I couldn't get anything even close.
Any help would be greatly appreciated.

A: Just a warning: This answer is theoretical, because i don't own such hardware...
AFAIK you have to enable a loopback-device for pulseaudio:
pactl load-module module-loopback

After that you should see a new application under audio-settings.
If it works well, you may add a line to the pulse-audio-config to make this persistent:
sudo sh -c ' echo "load-module module-loopback" >>  /etc/pulse/default.pa '

Good luck!
Additional info from matto1990:

You only need to do this if you want to loopback from a device other than the microphone or line in (the default ones). Go to software center and install "PulseAudio Volume Control". Open it up and go to the recording tab. In the show dropdown select "all". In the "loopback from internal audio" section (or whatever the output device you want is) select the input device you want to loopback from (in my case the USB one).


text:
Q: Writing parsers with Text.ParserCombinators In class, we wrote parsers by defining our own Parser type and this gave us a lot of flexibility. For example, if we wanted to make code and parse out "[at]" as '@', we could write
atParser = Parser $ \s ->
    case s of
        w:x:y:z:zs ->
            | (w:x:y:z:[]) == "[at]" = ['@',zs]
            | otherwise = []
        zs -> []

However, I cannot figure out how to implement this sort of parser using Text.ParserCombinators. Is it possible?
Thanks

A: I believe you're looking for the string combinator.
λ> :set -package parsec
package flags have changed, resetting and loading new packages...

λ> import Text.Parsec

λ> :t string
string :: Stream s m Char => String -> ParsecT s u m String

λ> parse (string "[at]") "" "[at]"
Right "[at]"

λ> parse (string "[at]") "" "[at"
Left (line 1, column 1):
unexpected end of input
expecting "[at]"

λ> parse ('@' <$ string "[at]") "" "[at]"
Right '@'


text:
Q: Extract specific word I have this list of objects:
  dput(head(annotations))
    structure(list(X1 = c("KQ415659.1", "KQ415659.1", "KQ415659.1",
    "KQ415659.1", "KQ415659.1", "KQ415659.1"), X2 = c("Genbank",
    "Genbank", "Genbank", "Genbank", "Genbank", "Genbank"), X3 = c("exon",
    "exon", "exon", "exon", "exon", "exon"), X4 = c(2986, 8779, 12123,
    14982, 15303, 15780), X5 = c(3040, 8886, 12182, 15050, 15387,
    15844), X6 = c(".", ".", ".", ".", ".", "."), X7 = c("+", "+",
    "+", "+", "+", "+"), X8 = c(".", ".", ".", ".", ".", "."), X9 = c("transcript_id \"rna0\"; gene_id \"gene0\"; gene_name \"ICBIM_22028242mg\";",
    "transcript_id \"rna0\"; gene_id \"gene0\"; gene_name \"ICBIM_22028243mg\";",
    "transcript_id \"rna0\"; gene_id \"gene0\"; gene_name \"ICBIM_22028244mg\";",
    "transcript_id \"rna0\"; gene_id \"gene0\"; gene_name \"ICBIM_22028245mg\";",
    "transcript_id \"rna0\"; gene_id \"gene0\"; gene_name \"ICBIM_22028246mg\";",
    "transcript_id \"rna0\"; gene_id \"gene0\"; gene_name \"ICBIM_22028247mg\";"
    )), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA,
    -6L))

I want to extract the  word that starts with "ICBIM" and ends with "mg" from all the strings.
# A tibble: 6 x 1
  X9
<chr>
        1 "transcript_id \"rna0\"; gene_id \"gene0\"; gene_name \"ICBIM_22028241mg\";"
        2 "transcript_id \"rna0\"; gene_id \"gene0\"; gene_name \"ICBIM_22028242mg\";"
        3 "transcript_id \"rna0\"; gene_id \"gene0\"; gene_name \"ICBIM_22028243mg\";"
        4 "transcript_id \"rna0\"; gene_id \"gene0\"; gene_name \"ICBIM_22028244mg\";"
        5 "transcript_id \"rna0\"; gene_id \"gene0\"; gene_name \"ICBIM_22028245mg\";"
        6 "transcript_id \"rna0\"; gene_id \"gene0\"; gene_name \"ICBIM_22028246mg\";"

A: Regex matching in R is a bit weird. You have a 6 functions (grep, grepl, sub, gsub, regexpr, gregepr, regexec) doing related things, but none of them returns the actual string. The closest thing you can get is a list of match positions and lengths from (for example) regexpr that can be passed to  regmatches to get the strings.
So here is how I would do it:
your_data = c("transcript_id \"rna0\"; gene_id \"gene0\"; gene_name \"ICBIM_22028241mg\";", "transcript_id \"rna0\"; gene_id \"gene0\"; gene_name \"ICBIM_22028242mg\";")
matches = regexpr("ICBIM.*mg", your_data)
regmatches(your_data, matches)
[1] "ICBIM_22028241mg" "ICBIM_22028242mg"

A: You can use this regex in sub:
sub(".*\\b(ICBIM.+mg)\\b.*", "\\1", annotations$X9)
# [1] "ICBIM_22028242mg" "ICBIM_22028243mg" "ICBIM_22028244mg" "ICBIM_22028245mg"
# [5] "ICBIM_22028246mg" "ICBIM_22028247mg"

Here, \\b indicates a word border.

A:
starts with "ICBIM" and ends with "mg"

ICBIM.+?mg

See the regex demo

A: Assuming format of rows are the same, without regex:
substring(annotations$X9, 51, 66)
# [1] "ICBIM_22028242mg" "ICBIM_22028243mg" "ICBIM_22028244mg" "ICBIM_22028245mg" "ICBIM_22028246mg" "ICBIM_22028247mg"

read.fwf(textConnection(annotations$X9), widths = c(50, 16), stringsAsFactors = FALSE)[, 2]
# [1] "ICBIM_22028242mg" "ICBIM_22028243mg" "ICBIM_22028244mg" "ICBIM_22028245mg" "ICBIM_22028246mg" "ICBIM_22028247mg"


text:
Q: Using a Dynamic Named Range inside a Sum Formula =SUM(IF(('Old Data'!$A$2:$A$10000=Tracking!A9)*('Old Data'!$B$2:$B$10000=$E$7)*('Old Data'!$D$2:$D$10000>$B$5)*('Old Data'!$D$2:$D$10000<$C$5),IF('Old Data'!$E$2:$E$10000-'Old Data'!$D$2:$D$10000<"4:00"+0,0.5,NETWORKDAYS('Old Data'!$D$2:$D$10000+0,'Old Data'!$E$2:$E$10000+0))))

is my current code.  I created a defined name Total
Total = =COUNTA('Old Data'!$C:$C)
Everywhere that I have 10,000 I'd like to return the value of Total. I've tried simply replacing 10000 with Total, tryed using the + built in formula creator. I can't figure how to insert the value into my formula.
Any Ideas?

A: This seems like a formula question to me?
You can use INDIRECT See this example
If I have =Sum(A1:A10000) then in such a case I can use
=SUM(INDIRECT("A1:A"&total))

In my example total has been defined as =COUNTA('Old Data'!$A:$A)
Let me know if you still want a VBA solution.
SNAPSHOT
The best way to check it is to highlight the relevant section in the formula and click F9 to see how the values are calculated.


text:
Q: Logistic Regression with a Time Factor for Forecasting I have a general question with regards to modelling the chance that domestic flights within the U.S. are cancelled or not using logistic regression (which I'm relatively new to).
I have used 'R' to fit a logistic regression model to a vast data set comprising of millions of flights over the past five years (2014 - 2018) using the following factors:

*

*Year

*Month

*Day of the week

*Origin airport

*Destination airport

Now, the output of the GLM analysis shows that all of these factors are significant.
In particular, the Year variable is likely key as it may give insight into the 'severity of weather' in that year, or 'mix of flights' in that year.
However, my issue now is that I want to use these results to predict the chance that a given flight (if I know the date of departure, and origin / destination) will be cancelled.
I want to do this for flights occurring in 2019.
Of course, the 'Year' factor is now no use to me, as it is only used to predict cancellations for historic years. And i'm not sure how to interpret the factors given that I am saying that a significant factor is now of no use.
Perhaps one option is to assume that 2019 will 'behave like 2018' and hence, when using the GLM for forecasting, I ignore the year variable, but assume that the '2018' factor is the correct factor to use? And 'leave' all other factor values as they are?
Or, perhaps a better option is to completely ignore the Year factor from my GLM, and run it again without the Year variable?
(But then, i'm not sure if the new factors for the other variables will adjust in a way that makes sense for forecasting 2019)?
Sorry if that's a little broad and vague, but any insight into this problem and general thought processes on how best to model this would be greatly appreciated.


text:
Q: Passing a Typescript class to a SharedWorker to create the worker When creating SharedWorkers you would pass the JS file inside the SharedWorker constructor such as
var worker = new SharedWorker('some_worker_file.js');

That file will contain a line that gets executed right away as its not inside any function. That line would be something like -
this.addEventlistener('connect', function(e) { ... handler code ... } );

Now how do you do something similar with Typescript?  You aren't calling new XXX so placing the code inside a constructor is pointless.
What's the best way to create a class with Typescript to do this - is it possible?
I'm wondering if the only way to do this is to create a simple JS file with the connect listener to set up the worker and also have that simple JS file load in the transpiled TS files as imports.


text:
Q: How to delete rows in a tensor with tensorflow? For example, I have :
X=tf.constant([9,5,3,7,2,4,7,8,1])
And I would like to delete all the values greater than 5 :
Y=tf.constant([3,2,4,1])
How could I do this?

A: Use the tensorflow boolean_mask operation:
import tensorflow as tf

a = tf.constant([1,9,2,8,3,7,4,6,5])
b = tf.boolean_mask(a,tf.greater(5,a))
with tf.Session() as sess:
    print(sess.run(b)) #[1,2,3,4]


text:
Q: Calulating The derivative of an fbm function and applying I'm creating a 2D mesh based off of an fbm function in unity. I know a good thing to implement is using the derivative of the function to smooth the side of steeper mountains and hills accordingly for more realistic effects.
My question is given my current FBM function

*

*How would I get the derivate of the function?

*How would I apply this derivative to my noise (eg. addition, multiplication, etc.)

float Customfbm(Vector2 x, Vector2 location, int octs = 5, float lacunarity = 1, float gain = 1)
    {
        float freq = 1, amp = 1;
        float sum = 0;
        for(int Octave = 0; Octave < octs; Octave++)
        {
            float value = Mathf.PerlinNoise(freq * (x.x + (location.x * 240)) / 240, freq * (x.y + (location.y * 240)) / 240) * 10;
            sum += value * amp;
            freq *= lacunarity;
            amp *= gain;
        }
        return sum;
    }

I have tried looking up the answer and it's not very clear due to most of the sources I could find are using Shaders. I'm really new to shaders and I haven't really learned the language. A lot of the examples out there are coded in open GL or open CV, Meaning while I can almost make out what they are doing it can still lead to being very vague on actual implementation details.
A lot of times where I have my "PerlinNoise" function, people replace that with a "PerlinDeriv" function. What does this function do and how? my guess is that it finds the derivative of the Perlin value to the layered noise, but if that were true wouldn't we only be using derivative to calculate the final height of the point? Also don't we want to calculate to the derivative of the point's height to the derivative of the finalized height which is a combination of the octaves?
Two sites that I found helpful are:
https://www.iquilezles.org/www/articles/morenoise/morenoise.htm
https://youtu.be/C9RyEiEzMiU?t=1958


text:
Q: Performing the same calculation over multiple dataframes with a for loop or function I am trying to figure out how to perform the same calculation in a dataframe for multiple dataframes at the same time. I am working with 56 different dataframes with all the same column names, deriving from multiple data sources.
I want to do a very simple column calculation, like this one underneath.
df1 <- data.frame( EF = c(1, 3, 5, 2, 5), FF = c(0.5, 0.7, 0.4, 1, 0.8))

df2 <- data.frame( EF = c(1, 1, 5, 7, 6), FF = c(0.4, 0.2, 0.1, 0.9, 0.2))

df1$CF <- df1$EF * df1$FF

df2$CF <- df2$EF * df2$FF

Now, I have to do this for df1 to df56, just this simple multiplication of these two columns.
To do this manually, it takes a lot of time and I am quite sure to be able to do this for multiple dataframes at the same time with a for loop or a function command, but I cannot manage to find a clear instruction. Hopefully one of you can help me out!

A: IF there are multiple datasets, place them in a list and then do the calculation in the list by looping over the list
lst1 <- lapply(list(df1, df2), transform, CF = EF * FF)

Placing them in the list can be easy if the object names created have a pattern i.e. df1, df2, ...df56 with mget and paste or with mget and ls(pattern = '^df\\d+$')
lst1 <- lapply(mget(paste0('df', 1:56)), transform, CF = EF * FF)


text:
Q: Show News Item creator or owner full name in Plone I'm trying to show the full name for each news item in a list. For the moment I have only the user id (nickname).
Is there a simple way (in existing .pt file) to show the full name of creator or owner instead of a nickname?
The page must work for anonymous users, too. I mean - the page must be public.
Some details:

    <tal:items tal:repeat="news_item batch">

      <div class="row news-item"
           tal:define="news_object python:news_item.getObject();
                       news_date python:news_object.getField('modification_date').getAccessor(news_object)();
                       news_title python:news_object.getField('title').getAccessor(news_object)();
                       news_description python:news_object.getField('description').getAccessor(news_object)();
                       news_image python:news_object.getField('image').getAccessor(news_object)();
                       news_url python:news_object.absolute_url();
                       news_creators python:news_object.getField('creators').getAccessor(news_object)(); .... ...

A: <tal:fullname define="membership context/portal_membership;
                      info python:membership.getMemberInfo(user.getId());
                      fullname info/fullname">
    You are are
</tal:fullname>

This example is taken from the  plone documentation

A: You can get inspired a lot by this code:

*

*https://github.com/collective/Products.Scrawl/blob/1021047c4ef6c2655d104e8b345a24140da9e4aa/Products/Scrawl/browser/blogentry_view.pt#L32
    <tal:name tal:condition="item_creator"
        tal:define="author python:context.portal_membership.getMemberInfo(item_creator)">
      Posted by

        Bob Dobalina

    </tal:name>

Mind the possible performance issues.
A cached view method may work a lot better, e.g.:
@memoize
def userid2fullname(self, userid):
     pm = api.portal.get_tool('portal_membership')
     memberinfo = pm.getMemberInfo(userid)
     return memberinfo and memberinfo['fullname'] or userid


text:
Q: list problem in Python I have 2 lists: first is list that I need to work with and the second is list of -1.
First of all I need to find the remainder of the divison of the number (number is len(lst)) and put it to the position (remainder of the divisor) in the list of -1. If there is already element, then to the next position in the list (if the next position is not empty, to the next and so on until it finds a position). How to realize the part that is in bold?
# -*- coding: utf-8 -*-
def fun(lst):
    count = [-1] * (len(lst) + 1)
    jar = []
    for i in range(len(lst)):
        jar.append(lst[i]%(len(lst) + 1))
        if count[jar[i]] == -1:
            count[jar[i]] = jar[i]
        else:
            arv[jar[i] + 1] = jar[i] # problem starts here
    print jar

lst = [26, 53, 12, 65, 39, 6]
lst = fun(lst)

A: You introduce arv, but you never assigned it a dict. Since it is a dict, assign arv as:
arv = {}

I would also use:
for i,elem in enumerate(lst):

You can now iterate over lst, while also knowing its position.

A: The line you indicated with a comment refers to a list that does not exist (arv) and I cannot tell what you mean by that.


text:
Q: Autohotkey make a window on top of fullscreen games how can I make a window on top of full screen applications using an Autohotkey script? Any window, if possible, or at least a window created by the script.

A: Andrius,
One that seems to work with many full screen games is the following:
SoundBeep 1000 , 1000 ; Alert the users
SplashTextOn, 300, 30, Homework, Start your homework NOW!
WinMove, Homework,, 0,0 ; Move the alert screen away from the center
Sleep, 4000 ; wait 4 seconds
SplashTextOff ; remove the text
Return

If you want to make this interactive, you could use something like:
!Esc::
SplashTextOn, 250,200,Power Options,S = Sleep`n`rR = Reboot`n`rP = Power down`n`rW = Wait`n`rEsc = keep working`n`r`n`rPC will automatically go to sleep after 10 seconds if no key is pressed!
SetTimer, GoToSleep, Off
Input, CI_KeyVar, I L1 T10
SplashTextOff
if ErrorLevel = Timeout
{
Run C:\Windows\System32\rundll32.exe powrprof.dll`,SetSuspendState 0`,1`,0
return
}
if (CI_KeyVar = "q")
{
  Return
}
if (CI_KeyVar = "s")
{
  Run C:\Windows\System32\rundll32.exe powrprof.dll`,SetSuspendState 0`,1`,0
  Return
}
if (CI_KeyVar = "r")
{
  run, Shutdown.exe /r /t 1 ; Reboot PC
  Return
}
if (CI_KeyVar = "p")
{
  run, Shutdown.exe /s /t 0 ; Shutdown PC
  Return
}
if (CI_KeyVar = "w")
{
SleepTime+=1
inputbox, Sleeptime, Minutes,,,400,110,,,,,%Sleeptime%
Sleeptimer+=%Sleeptime%
MySleeptimer:=Sleeptimer * 60000 ; 60`000 = 1 minute
if MySleeptimer = 0
{
  Return
}
TrayTip, Count Down,`n`nSleeping in %Sleeptimer% minutes`n`nPress Alt + Esc to cancel,10,1
SetTimer, GoToSleep, %Mysleeptimer%
}
Return

GoToSleep:
SetTimer, GoToSleep, Off
TrayTip, Sleep, Started
Sleep, 1000
run C:\Windows\System32\rundll32.exe powrprof.dll`,SetSuspendState 0`,1`,0
return

Success

A: If SplashTextOn or SplashImage doesn't work, nor a game specific child-parent setting by Wicked here, nor the library GPF , than according to this, nothing will or no-one has managed yet.
EDIT: I managed to get the child-parent method above for any fullscreen application (and not just a specific game) as follows, but there is still something wrong with the Gui then:
WinGet, WinHND, ID, A   ;Get Handle of current fullscreen app
Gui,Vol:+0x40000000 -0x80000000 +Owner%WinHND%  ;MAke fullscreen app own our gui


text:
Q: When would a queue consider a task is completed? In the following code, when would queueT (serial queue) consider "task A" is completed?
The moment when aNetworkRequest  switched to another thread?
Or in the doneInAnotherQueue block? ( commented // 1)
In another word, when would "task B" be executed?
let queueT = DispatchQueue(label: "com.test.a")
queueT.async { // task A
    aNetworkRequest.doneInAnotherQueue() { // completed in another thread possibly
        // 1
    }
}

queueT.async { // task B
    print("It's my turn")
}

It would much better if you could explain the mechanism how a queue consider a task is completed.
Thanks in advance.

A: In short, the first example starts an asynchronous network request, so the async call "finishes" as soon as that network request is submitted (but does not wait for that network request to finish).
I am assuming that the real question is that you want to know when the network request is done. Bottom line, GCD is not well suited for managing dependencies between tasks that are, themselves, asynchronous requests. The dispatching the initiation of a network request to a serial queue is undoubtedly not going to achieve what you want. (And before someone suggests using semaphores or dispatch groups to wait for the asynchronous request to finish, note that can solve the tactical issue, but it is a pattern to be avoided because it is inefficient use of resources and, in edge cases, can introduce deadlocks.)
One pattern is to use completion handlers:
func performRequestA(completion: @escaping () -> Void) { // task A
    aNetworkRequest.doneInAnotherQueue() { object in
        ...
        completion()
    }
}

Now, in practice, we would generally use the completion handler with a parameter, perhaps even a Result type:
func performRequestA(completion: @escaping (Result<Foo, Error>) -> Void) { // task A
    aNetworkRequest.doneInAnotherQueue() { result in
        guard ... else {
            completion(.failure(error))
            return
        }
        let foo = ...
        completion(.success(foo))
    }
}

Then you can use the completion handler pattern, to process the results, update models, and perhaps initiate subsequent requests that are dependent upon the results of this request. For example:
performRequestA { result in
    switch result {
    case .failure(let error):
        print(error)

    case .success(let foo):
        // update models or initiate next step in the process here
    }
}

If you are really asking how to manage dependencies between asynchronous tasks, there are a number of other, elegant patterns (e.g., Combine, custom asynchronous Operation subclass, the forthcoming async/await pattern contemplated in SE-0296 and SE-0303, etc.). All of these are elegant solutions for managing dependencies between asynchronous tasks, controlling the degree of concurrency, etc.
We probably would need to better understand the nature of your broader needs before we made any specific recommendations. You have asked the question about a single dispatch, but the question probably is best viewed from a broader context of what you are trying to achieve. For example, I'm assuming you are asking because you have multiple asynchronous requests to initiate: Do you really need to make sure that they happen sequentially and lose all the performance benefits of concurrency? Or can you allow them to run concurrently and you just need to know when all of the concurrent requests are done and how to get the results in the correct order? And might you have so many concurrent requests that you might need to constrain the degree of concurrency?
The answers to those questions will probably influence our recommendation of how to best manage your multiple asynchronous requests. But the answer is almost certainly is not a GCD queue.

A: You can do a simple check
    let queueT = DispatchQueue(label: "com.test.a")
    queueT.async { // task A

        DispatchQueue(label: "com.test2.a").async { // create another queue inside
            for i in 0..<6 {
                print(i)
            }
        }

    }

    queueT.async { // task B
        for i in 10..<20 {
            print(i)
        }
    }

}

you'll get different output each run this means yes when you switch thread the task is considered done

A: A GCD work item is complete when the closure you pass returns. So for your example, I'm going to rewrite it to make the function calls and parameters more explicit (rather than using trailing closure syntax).
queueT.async(execute: {
    // This is a function call that takes a closure parameter. Whether this
    // function returns, then this closure will continue. Whether that is before or
    // after running completionHandler is an internal detail of doneInAnotherQueue.
    aNetworkRequest.doneInAnotherQueue(closureParameter: { ... })

    // At this point, the closure is complete. What doneInAnotherQueue() does with
    // its closure is its business.
})

Assuming that doneInAnotherQueue() executes its closure parameter "sometime in the future", then your task B will likely run before that closure runs (it may not; it's really a race at that point, but probably). If the doneInAnotherQueue() blocks on its closure before returning, then closureParameter will definitely run before task B.
There is absolutely no magic here. The system has no idea what doneInAnotherQueue does with its parameter. It may never run it. It may run it immediately. It may run it sometime in the future. The system just calls doneInAnotherQueue() and passes it a closure.
I rewrote async in normal "function with parameters" syntax to make it even more clear that async() is just a function, and it takes a closure parameter. It also isn't magic. It's not part of the language. It's just a normal function in the Dispatch framework. All it does it take its parameter, put it on a dispatch queue, and return. It doesn't execute anything. There's just closures that get put on queues, scheduled, and executed.
Swift is in the process of adding structured concurrency, which will add more language-level concurrency features that will allow you to express much more advanced things than the simple primitives provided by GCD.

A: Your task A returns straight away. Dispatching work to another queue is synchronous. Think of the block (the trailing closure) after 'doneInAnotherQueue' as just an argument to the doneInAnotherQueue function, no different to passing an Int or a String.  You pass that block along and then you return immediately with the closing brace from task A.


text:
Q: Alternative to Cloud SCORM API I am looking for a alternative to the Cloud SCORM API? it's too expensive to implement so i was thinking if there is an alternative or a source code that i can use to start developing a SCORM Api.
Thank you in advance !

A: You may want to look at Moodle.
(Full disclosure I work for Rustici Software who own SCORM Cloud.)

A: You may take a look to this commercial solution that is an alternative to scorm cloud:
https://www.scormnext.es
It lets you distribute your SCORM contents remotely to external LMS by using SCORM connectors (dispatchers).
This solution has a more commercial look and has a lot of features that enterprises usually need.

A: Another option is the open source ilias project.  It supports scorm, and you can modify the css of the launch, and so use it as the backend engine for scorm.  you can do some curl requests to post content to it, and you could add some callbacks in the code to forward completions to somewhere else.  This way you could turn it into a scorm cloud alternative.   Or you could try to dig out the specific scorm related tables/code and see what it takes to actually support scorm.

A: You can tinker on my https://angular.scobot.net.  I put that in beta this year.  Mainly uses both same and cross domain implementations to showcase my SCOBot Runtime API if your planning on building your own platform and want SCORM support.
This mainly uses a self-signup strategy with AWS Amplify.
More info on https://cybercussion.com


text:
Q: Installing GitLab on Ubuntu: "Could not resolve host: packages.gitlab.com" This is my system (fresh install):
Distributor ID: Ubuntu
Description:    Ubuntu 16.04.6 LTS
Release:    16.04
Codename:   xenial

I've already installed OpenSSH and Postfix and added the GitLab repository, but when I try installing GitLab, this is what I get:
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following NEW packages will be installed:
  gitlab-ce
0 upgraded, 1 newly installed, 0 to remove and 4 not upgraded.
Need to get 743 MB of archives.
After this operation, 1,961 MB of additional disk space will be used.
Err:1 https://packages.gitlab.com/gitlab/gitlab-ce/ubuntu xenial/main amd64 gitlab-ce amd64 12.8.1-ce.0
  Could not resolve host: packages.gitlab.com
E: Failed to fetch https://packages.gitlab.com/gitlab/gitlab-ce/ubuntu/pool/xenial/main/g/gitlab-ce/gitlab-ce_12.8.1-ce.0_amd64.deb  Could not resolve host: packages.gitlab.com

E: Unable to fetch some archives, maybe run apt-get update or try with --fix-missing?

I tried both recommendations and even tried changing networks, hoping it was the school Wi-Fi.

A: Try and access first https://packages.gitlab.com/gitlab/gitlab-ce in a browser.
If that fails as well, it might be the case the domain is blocked by a firewall.


text:
Q: In Visual Studio 2019, can I set my local source control repository to somewhere other than in my solution folder? Visual Studio 2019 Community, Win10 Pro 64
I'm new to VS 2017 and 2019 and not all that familiar with git, but I have been able to set up a git repository and commit my solution to all the way to the remote server, using VS.  If I understand this correctly, the files are first stored into a repository that exists on my local machine, and then I commit it to the repository on the git server.
While this all works just fine, I can't figure out how to place that local repository somewhere other than in my solution folder.  When I click on File->Add to Source Control in VS, it always adds it in a .git folder in my solution folder, and I can't figure out a way to put it somewhere else.
The reason I want to do this is that I do my development on an SSD for speed, but I want my local repository on an HDD so it doesn't consume space on the SSD.
Is there any way to set this up with Visual Studio 2019?

A: You can do nothing from VS but you can do it by relying on the command line. Once it is set, you could you VS normally without problems.
There is a way to set the '.git' folder in another directory when you init or clone a repository. See: https://stackoverflow.com/a/19548676/717372
But you could also easily achieve what you want using the 'git worktree' feature.
Do the steps :

*

*Verify that all the files are committed or stashed (you have a clean working directory)

*move all the folder on your hdd.

*From inside the new hdd directory, checkout a revision (the one you wish, but not a branch, to avoid a limitation due to use the 'worktree' feature) with git checkout SHA1_OF_HEAD or git checkout $(git rev-parse HEAD)

*Create and use a worktree on your ssd with git worktree add c:\path\to\ssd master

*Now you can work in the ssd folder from VS


text:
Q: Woes using urllib.request.urlretrieve. Saves as HTML file? New (newb) python user here! Quick question, hopefully basic level, working with
urllib.request.urlretrieve. I can't figure out why the below code returns an HTML file (saved as a .zip) instead of an actual zip file. Any help would be extremely appreciated!!!
import os
import zipfile
import urllib.request, urllib.parse, urllib.error

DOWNLOAD_ROOT = "https://www.kaggle.com/annavictoria/speed-dating-experiment/downloads/"
SPEED_PATH = "datasets/speed"
SPEED_URL =  DOWNLOAD_ROOT + "speed-dating-experiment.zip"

def fetch_speed_data(speed_url=SPEED_URL, speed_path=SPEED_PATH):
        if not os.path.isdir(speed_path):
            os.makedirs(speed_path)
        zip_path = os.path.join(speed_path, "speed.zip")
        urllib.request.urlretrieve(speed_url, zip_path)
        speed_zip = zipfile.ZipFile(zip_path, 'a')
        speed_zip.extractall(path=speed_path)
        speed_zip.close()

fetch_speed_data()


text:
Q: Rake tasks, "warning: already initialized constant STATS_DIRECTORIES" when executing the rake tasks, it issues this message:
warning: already initialized constant STATS_DIRECTORIES
¿how can I load it, using rails 4?.
thanks for you help.


text:
Q: how to transpose a table by a column with group by pandas I have a table that I need to transpose, and it looks like this:

| User ID| Week | clicks | days|
|------- |------| -------|-----|
| x      | 1    | 1      | 1   |
| x      | 2    | 2      | 3   |
| y      | 1    | 3      | 2   |
| y      | 2    | 3      | 2   |
| y      | 3    | 4      | 3   |

The output I need looks like this:
| User ID| clicks week 1| clicks week 2| clicks week 3| days week 1| days week 2| days week 3|
|--------|--------------| -------------|------------- |------------| -----------|------------|
| x      | 1            | 2            | 0            | 1          | 3          | 0          |
| y      | 3            | 3            | 4            | 2          | 2          | 3          |

For each user I need a single row and for each category I need a column for each week (if there's no activity for user in a week, write 0).
Any idea how to do it?
Thanks!

A: You can use .pivot() with .fillna():
df.pivot(index="User ID", columns="Week", values=["clicks", "days"]).fillna(0)

This outputs:
          clicks                    days
Week       1        2        3     1     2     3
User ID
x        1        2              0  1     3        0
y        3        3        4        2     2     3

A: You can try pandas pivot method:
testing.pivot(index="User ID",columns=["Week"],values=["clicks","days"]).fillna(0)

         clicks         days
Week    1   2   3   1   2   3
User ID
x       1.0 2.0 0.0 1.0 3.0 0.0
y       3.0 3.0 4.0 2.0 2.0 3.0

A: You can do it multiple ways.
no 1. You can use .pivot and assign index='User ID', columns='Week', values=['clicks', "days"]
df.pivot(index='User ID', columns='Week', values=['clicks', "days"])

no 2. You can use groupby + unstack, if aggregations is required. groupby method is used to group the data by columns, and the unstack is used to pivot the data.
df.groupby(['User ID', 'Week'], sort=False).sum().unstack()

No 3 Another solution is using set_index + unstack
df.set_index(['User ID', 'Week']).unstack()


text:
Q: PHP Fatal error: Uncaught Error: Cannot access property started with '\\0' So I'm using Timber v0.22.5. I have it currently running on my local and a dev environment right now. Everything is running great no issues. Both environments are running PHP 5.5.9.
I just migrated it to my production server which is running PHP 7.0. I am now getting the following error from Timber.

Fatal error: Uncaught Error: Cannot access property started with '\0'
  in
  /var/www/html/wp-content/plugins/timber-library/lib/timber-core.php:67

I'm not sure what exactly else is different between the environments other than different versions of PHP. I cannot update to Timber v1 because well the guide seems to suggest not doing that because of some backwards compatibility issues.
I'm going to try installing PHP 5.5.9 and see if that does the trick but was wondering if anyone else was having this issue.
Thanks!

A: This is an issue with Timber 0.* and PHP 7. You should be able to fix it by replacing Timber/Core::import with the current version:
https://github.com/timber/timber/blob/master/lib/Core.php#L59-L75

A: This will be happened if you use the latest version of "Better Search and Replace" plugin too. You should be able to fix by trimming the key:
https://github.com/deliciousbrains/better-search-replace/issues/71


text:
Q: Open url method not called in app delegate using "https" as url schema in deep linking swift 4 Open URL method not called in app delegate using "https" as URL schema in deep linking swift 4
I will attach plist screenshot.

A: when you want to call deeplink use this from any browser
like safari type yourdeeplink:// or for your deeplink type http://


text:
Q: How to detect whether a solenoid is actually attached to a MOSFET? An injector is usually switched to ground to turn it on using a an N channel Mosfet. But how does the MCU knows when this is disconnected?

I'm trying to drive a solenoid, but if the solenoid is disconnected, I'd like my MCU to know that.

A: The thing you're asking and what you're trying to do a very different things.
So, a modern ECU is a complex device with literally hundreds of actors and sensors attached. Especially, there will be sensors that observe whether the explosion in the cyclinder happens, there will be gasoline flow sensors, exhaust gas sensors… plenty of data from which an ECU can infer something went wrong during operation of the motor, and quite possibly also specifically that an injector doesn't work. Whether it knows why that injector doesn't work is a different question; I don't think it needs to!
What you're trying to do is a slight bit easier. You're not observing a complete car's drive. You're observing a solenoid.
So, simplest solution I could think of without actually just sensing the current with a shunt resistor, which brings isolation problems:

simulate this circuit – Schematic created using CircuitLab
In non-operation, the digital input will be reliably high. But the switching on and: especially the switching off impulse as seen through the capacitor will be very different whether there is a solenoid attached or not; you should be able to register that.
Notice that all the component values are examples only; you probably want a smaller C1 if your solenoid is large, and lower-valued resistors. Maybe a pair of TVS diodes might be a good thing, too, to protect your microcontroller – but that really depends on your microcontroller, switching speed, the solenoid, and your ability to detect short pulses. Most microcontrollers can be programmed to register a sudden edge on an input – be it as an interrupt, or as a counter increase – but if yours doesn't, you'll need to poll that input, so that you might miss very short pulses.

A: First: ask yourself what failure are you trying to guard against. That is what problem you are tying to solve.
If the problem you want to detect is a wiring error during manufacturing then just testing that the solenoid is connected is a good solution.
If you want to detect that the MCU is causing some mechanical action, then consider sensing the mechanical activation. For example you could use a Hall sensor to detect movement of the rod in the solenoid. A second coil can give a transient response as the rod moves. Electro-mechanical components are typically more failure prone than solid-state electronics.
The solenoid has some wire resistance. In fact a coil (in relays for sure) is typically wound to have a resistance that will produce more than the activation current when the specified voltage is applied. So you can model the solenoid as an inductor and a resistor in series.
Depending on the system, solenoid current may make a significant change in the current drawn from the power supply. Maybe this is easy to measure.
Place a resistor in series with the coil. Make sure the resistance is small enough that it won't reduce coil current enough to prevent activation. If the solenoid is in the circuit there will be current flow and hence a voltage across this resistor.
Other current sensing methods that maybe easier to interface direct to an MCU are Hall sensors, current transformers (transient response).
As suggested in the other post you can put a small sense resistor between the MOSFET source and ground. An op-amp can be used to gain this small signal up to a voltage that is easily measured bu the MCU.
Now that I know the Solenoid could use up to 210 W. I think you could just amplify the Vds of the MOSFET. Even a large FET will some measureable voltage across its drain to source with thus much current flow. Another idea is if you have a wiring harness of any kind for this you could use wire resistance as a sense resistor for the solenoid current. The advantage of using a sense resistor is that you can digitize the voltage across it when no current flows before activating the solenoid and use that to subtract  the offset and improve your measurement.  You could apply this technique to a very low resistance say 0.1 mOhms or less.


text:
Q: How to listen for HTTP call in front end JS I am working on a site, which uses a 3rd party library to launch a pop up to collect users email addresses.
After the user submits the email address, the 3rd party API is called, following the format https://<API-URL>/collectemail?email=test%40test.com
I want to run a function when that API is called and pass it the email param. How can I listen for that event and then trigger my function?

A: The best way would be to fork the library and modify it so that, when the API is called, the library code itself calls the code on your site with the email parameter.
If that's not possible, your only other option is to monkeypatch XMLHttpRequest so as to intercept requests, such as with:

// Your code, make sure this runs first:
const origXHR = window.XMLHttpRequest;
window.XMLHttpRequest = function() {
  const xhr = new origXHR();
  xhr.open = (method, url) => {
    origXHR.prototype.open.call(xhr, method, url);
    console.log('Connection just opened to:', url);
  }
  return xhr;
};

// Library code:
const xhr = new XMLHttpRequest();
xhr.open('POST', 'https://example.com/?email=test%40test.com');
xhr.send();


text:
Q: Pick row with key GROUP_FILENAME and add a new column with column name I have a data frame which looks like this
GROUP_FIELD_NAME:BKR_ID
GROUP_FIELD_VALUE:T80
GROUP_FIELD_NAME:GROUP_OFFSET
GROUP_FIELD_VALUE:0
GROUP_FIELD_NAME:GROUP_LENGTH
GROUP_FIELD_VALUE:0
GROUP_FIELD_NAME:FIRM_ID
GROUP_FIELD_VALUE:KIZEM
GROUP_FILENAME:000000018.pdf
GROUP_FIELD_NAME:BKR_ID
GROUP_FIELD_VALUE:T80
GROUP_FIELD_VALUE:P
GROUP_FIELD_NAME:FI_ID
GROUP_FIELD_VALUE:
GROUP_FIELD_NAME:RUN_DTE
GROUP_FIELD_VALUE:20220208
GROUP_FIELD_NAME:FIRM_ID
GROUP_FIELD_VALUE:KIZEM
GROUP_FILENAME:000000019.pdf

It has three keys Group field ,group field value and group file name,i want to create a dataframe like this
I am expecting a data frame with three column group_field_name,group_field_value and group_file name.

A: You can use:
(df['col'].str.extract('GROUP_FILENAME:(.*)|([^:]+):(.*)')
 .set_axis(['GROUP_FILENAME', 'var', 'val'], axis=1)
 .assign(GROUP_FILENAME=lambda d: d['GROUP_FILENAME'].bfill(),
         n=lambda d: d.groupby(['GROUP_FILENAME', 'var']).cumcount()
        )
 .dropna(subset=['var'])
 .pivot(index=['GROUP_FILENAME', 'n'], columns='var', values='val')
 .droplevel(1).rename_axis(columns=None)
 .reset_index('GROUP_FILENAME')
 )

Output:
  GROUP_FILENAME GROUP_FIELD_NAME GROUP_FIELD_VALUE
0  000000018.pdf           BKR_ID              T80
1  000000018.pdf     GROUP_OFFSET                 0
2  000000018.pdf     GROUP_LENGTH                 0
3  000000018.pdf          FIRM_ID             KIZEM
4  000000019.pdf           BKR_ID               T80
5  000000019.pdf            FI_ID                 P
6  000000019.pdf          RUN_DTE
7  000000019.pdf          FIRM_ID          20220208
8  000000019.pdf              NaN             KIZEM

Used input:
                              col
0         GROUP_FIELD_NAME:BKR_ID
1          GROUP_FIELD_VALUE:T80
2   GROUP_FIELD_NAME:GROUP_OFFSET
3             GROUP_FIELD_VALUE:0
4   GROUP_FIELD_NAME:GROUP_LENGTH
5             GROUP_FIELD_VALUE:0
6        GROUP_FIELD_NAME:FIRM_ID
7         GROUP_FIELD_VALUE:KIZEM
8    GROUP_FILENAME:000000018.pdf
9         GROUP_FIELD_NAME:BKR_ID
10          GROUP_FIELD_VALUE:T80
11            GROUP_FIELD_VALUE:P
12         GROUP_FIELD_NAME:FI_ID
13             GROUP_FIELD_VALUE:
14       GROUP_FIELD_NAME:RUN_DTE
15     GROUP_FIELD_VALUE:20220208
16       GROUP_FIELD_NAME:FIRM_ID
17        GROUP_FIELD_VALUE:KIZEM
18   GROUP_FILENAME:000000019.pdf


text:
Q: Fix MS-DOS MBR Without DOS Boot Disk How can I restore the MBR for MS-DOS without having an MS-DOS boot disk or floppy drive. Ideally, I would like to be able to do this from a Windows 7 Win PE disk. The only solutions I've found online say to use fdisk or fixmbr but neither of those seem to come with Win PE.

A: fdisk /mbr is not documented but works also in MS-DOS 5.00 (http://support.microsoft.com/kb/69013)
Tried today, and yes me too I have some DOS machines in production.
Other tools @ http://www.bootdisk.com/bootdisk.htm .

A: Naturally, things can go even more haywire: the first thing you should do is make sure any critical data is backed up.  If this is a production machine, then it should be worth making a disk image if needed (of the hard drive).  Mucking with boot stuff can easily result in disasters, like looking the partition table, which can be much more difficult to fix.
That's not to say that I'm lacking confidence in my advice.  I could follow it without problem.  But tools that muck with this part of the disk are often tools that are capable of causing major data loss if they are used improperly.  Backups should be done anyway for critical  business data, on a regular basis.  Well, that's even more important before trying any programs like what I am about to suggest, or other software that I've seen other people suggest in this SuperUser question.
If using Windows PE is causing too much aggravation, you can forget about using tools that come with Windows.  There are other options available for you.
If you need to boot DOS, all you need is an MBR that can load DOS.
Boot managers can also do what you seek, and they may be installable from different operating systems (or even different computers).  Consider using any operating system to make a disk (CD, or floppy) that uses GAG, and then GAG can boot DOS.  Also, GAG can install itself onto the hard drive, so then the machine can directly boot the DOS machine.  GAG doesn't come with Windows PE or any other operating system; it doe snot use Windows PE or any other operating system.  It's meant to be started from the MBR, and it will take care of what you're describing you want to do.
Or use XFDisk which is available separately but also comes with FreeDOS.  That has a boot manager that will fit entirely within the MBR.  Ranish Partition Boot Manager may be another option.

A: DOS MBR work same as WIN7 MBR. MS MBR have only one task- find Active partiotion and "chainload" it BootSector. You need fix BootSector by DOS, as I know you need SYS command


text:
Q: which data structure to use for specific text editor Some text editor needs to perform the following operations:

*

*insert one character

*delete one character

Linked list example:
Insert(3,"x"):

   before:  [a]-[b]-[c]-[d]-...
   after:   [a]-[b]-[x]-[c]-[d]-...

Delete(3):

   before:  [a]-[b]-[x]-[c]-[d]-...
   after:   [a]-[b]-[c]-[d]-...

Which would be the optimal data structure to implement this behavior? (my gut feeling: red-black tree)


text:
Q: Is "look at him in that..." natural?
Guy 1: "Where is Mike?"
Guy 2: "There he is! Hahaha! Look at him in that ugly shirt!"

Would the emboldened part be natural in the context for a native speaker? (With 'him' referring to Mike.)


text:
Q: How to pass character strings to R from IML Studio If I define a function in IML:
start func(a);
  submit a / R;
   print(&a);
  endsubmit;
finish;

and run it:
run func("character string");

I get the error message: object 'character string' does not exist.
So R or IML is evaluating the character string into an object.  I want R to output "character string."  How do I do this?

A: I haven't used the new R/IML interface functionality, but from reading the help it looks like submit foo does text substitution. That is, if the IML variable foo contains the value x, then any occurrence of &foo in the submit block is replaced with x. When R is involved, IML generates R code to treat x as a symbol rather plain text. With that in mind, see if
start func(a);
  submit a / R;
    print("&a");
  endsubmit;
finish;

does what you want. Alternatively, you could use the ExportMatrixToR module to send the data to R:
start func(a);
   run ExportMatrixToR(a, "a");
   submit / R;
     print(a);
   endsubmit;
finish;

Caveat: untested code.