text:
Q: Adding rules efficiently In background.js I am using rules but I am also using regex so many times. I have declarativeContent.ShowPageAction based on these rules.
new chrome.declarativeContent.PageStateMatcher({pageUrl: { urlMatches: 'https?:\/\/([a-z0-9]+[.])*microsoft.com'},}),
new chrome.declarativeContent.PageStateMatcher({pageUrl: { urlMatches: 'https?:\/\/([a-z0-9]+[.])*google.com'},}),
new chrome.declarativeContent.PageStateMatcher({pageUrl: { urlMatches: 'https?:\/\/([a-z0-9]+[.])*amazon.com'},}),

Is there a way to use regex only once and use it as in javascript
myRegexInstance.test(collectionOfURLs);

A: Don't use regexp. They're slow and you're duplicating the job already performed by the API: it already separated the URL into parts which you can test separately.
Use hostSuffix:
[
  '.microsoft.com',
  '.google.com',
  '.amazon.com',
].map(s => new chrome.declarativeContent.PageStateMatcher({pageUrl: {hostSuffix: s}}))

The leading dot will match both *://google.com/ and any subdomain e.g. *://www.google.com/


text:
Q: Python, Tkinter, Can not access StringVar() Object with the attached code i try to access the StringVar object in the widget object himself.
But unfortunately  it says 'AttributeError: 'str' object has no attribute 'set''
Any idea why? Thanks in advance..
import Tkinter as tk

class mainWindow:
    def __init__(self, master):
        self.master = master

        self.fieldList = {}

        f = tk.Entry(self.master, text='', width = 7)
        f.grid(column=0, row=0)
        self.addToFieldList(f, 'MyFieldA')

    def addToFieldList(self, fieldObj, fieldId):
        fieldObj.bind('<Return>', lambda event, temp=fieldObj :self.commitField(event, temp))

        t = tk.StringVar()
        fieldObj['textvariable'] = t
        setattr(fieldObj, 'fieldId', fieldId)
        self.fieldList[fieldId] = fieldObj

    def commitField(self, event, sender):
        newValue = sender.get()
        t = sender['textvariable']
        t.set('newValue')  # here comes the error

def main():
    root = tk.Tk()
    app = mainWindow(root)

    root.wm_geometry("500x180")
    root.mainloop()

if __name__ == '__main__':
    main()

A: Put self in front of the StringVar which will let you call it without an error. This is because it is not a global variable and so the function cannot access it. Also change t = sender['textvariable'] to sender['textvariable'] = t.

redpajama_set_name: RedPajamaStackExchange


text:
Q: (AndroidTouchGallery) How to start with 2,3,4.. image. How to set position I`m trying to implement ImageGallery on Android. I use AndroidTouchGallery library. In MainActyvity I have list of images and by clicking on them open AndroidTouchGallery. Everything work, but when open the image gallery starts with the first one.
There need to set the image position, in which to start. In this stage I have a problem. Maybe someone how to make it.
int pos ; //Picture Position

UrlPagerAdapter pagerAdapter = new UrlPagerAdapter(Full_Image_Activity.this, ArrayImgBig);
mViewPager = (GalleryViewPager)findViewById(R.id.viewer);
mViewPager.setOffscreenPageLimit(3);
mViewPager.setAdapter(pagerAdapter);

The code of UrlPageAdapter. I try to set the position in setPrimaryItem, but it still open the first image.
/**
 Class wraps URLs to adapter, then it instantiates {@link UrlTouchImageView} objects to paging up through them.
 */
public class UrlPagerAdapter extends BasePagerAdapter {

    public UrlPagerAdapter(Context context, List<String> resources)
    {
        super(context, resources);
    }
    @Override
    public void setPrimaryItem(ViewGroup container, int position, Object object) {
        super.setPrimaryItem(container, position, object);
        ((GalleryViewPager)container).mCurrentView = ((UrlTouchImageView)object).getImageView();
    }

    @Override
    public Object instantiateItem(ViewGroup collection, int position){
        final UrlTouchImageView iv = new UrlTouchImageView(mContext);
        iv.setUrl(mResources.get(position));
        iv.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));

        collection.addView(iv, 0);
        return iv;
    }
}

BasePagerAdapter
/**
 Class wraps URLs to adapter, then it instantiates <b>UrlTouchImageView</b> objects to paging up through them.
 */
public class BasePagerAdapter extends PagerAdapter {

    protected final List<String> mResources;
    protected final Context mContext;
    protected int mCurrentPosition = -1;
    protected OnItemChangeListener mOnItemChangeListener;
    public BasePagerAdapter()
    {
        mResources = null;
        mContext = null;
    }
    public BasePagerAdapter(Context context, List<String> resources)
    {
        this.mResources = resources;
        this.mContext = context;
    }
    @Override
    public void setPrimaryItem(ViewGroup container, int position, Object object) {
        super.setPrimaryItem(container, position, object);
        if (mCurrentPosition == position) return;
        GalleryViewPager galleryContainer = ((GalleryViewPager)container);
        if (galleryContainer.mCurrentView != null) galleryContainer.mCurrentView.resetScale();

        mCurrentPosition = position;
        if (mOnItemChangeListener != null) mOnItemChangeListener.onItemChange(mCurrentPosition);
    }

    @Override
    public void destroyItem(ViewGroup collection, int position, Object view){
        collection.removeView((View) view);
    }

    @Override
    public int getCount()
    {
        return mResources.size();
    }

    @Override
    public boolean isViewFromObject(View view, Object object){
        return view.equals(object);
    }

    @Override
    public void finishUpdate(ViewGroup arg0){
    }

    @Override
    public void restoreState(Parcelable arg0, ClassLoader arg1){
    }

    @Override
    public Parcelable saveState(){
        return null;
    }

    @Override
    public void startUpdate(ViewGroup arg0) { }

    public int getCurrentPosition() { return mCurrentPosition; }

    public void setOnItemChangeListener(OnItemChangeListener listener) { mOnItemChangeListener = listener; }

    public static interface OnItemChangeListener
    {
        public void onItemChange(int currentPosition);
    }
}

Olso I have some other queston.
*is the "setPrimaryItem" set up the main Item(Image) witch is open first?
*is the "instantiateItem" initialise every item from the array, whitch is shows?

A: I made it by this:
            mViewPager = (GalleryViewPager)findViewById(R.id.viewer);
            mViewPager.setOffscreenPageLimit(3);
            mViewPager.setAdapter(pagerAdapter);

            //set position
            mViewPager.setCurrentItem(pos);


text:
Q: How to set [DataMember] on all class members I have a class with countless members.
I want to use DataContract serialization/deserialization and so the class has the [DataContract] attribute. If I put the [DataMember] attribute that works otherwise it doesn't.
Am I to put [DataMember] on all of them? Isn't there a way to automatically set ALL of them as datamembers?
Thanks
--EDIT--
The solution in Set DataContract and DataMember Without All the Attributes is not working.
public Test()
{
  if (false)
  {

    MyClass theclass = new MyClass();

    var serializer = new DataContractSerializer(typeof(MyClass));

    using (Stream fileStream = File.Open("aaa.bin", FileMode.Create))
    {
      XmlDictionaryWriter binaryDictionaryWriter = XmlDictionaryWriter.CreateBinaryWriter(fileStream);
      serializer.WriteObject(binaryDictionaryWriter, theclass);
      binaryDictionaryWriter.Flush();
    }
  }
  else
  {
    MyClass theclass;
    var serializer = new DataContractSerializer(typeof(MyClass));

    using (Stream fileStream = File.Open("aaa.bin", FileMode.Open))
    {
      XmlDictionaryReaderQuotas xq = new XmlDictionaryReaderQuotas();
      XmlDictionaryReader binaryDictionarReader = XmlDictionaryReader.CreateBinaryReader(fileStream, xq);
      theclass = (MyClass)serializer.ReadObject(binaryDictionarReader);

    }
  }

}

}
[DataContract(IsReference = true)]
public class MyClass
{
  // need a parameterless constructor for serialization
  public MyClass()
  {
    MyDictionary = new Dictionary<string, string>() { { "AAA", "BBB" } , {"CCC", "DDD"} };
  }
  public Dictionary<string, string> MyDictionary { get; set; }<----no attribute
  public int aaaa = 3;<----no attribute

}


text:
Q: How to find status of producer using consumer I am reading a large sized file like approximately 2 GB. But I am not aware of whether the writer has written the file completely. Is there any way to check whether the file is written completely from reader side?

A: Without any code, it's going to be hard to make any concrete suggestions but why not just extend whatever class you're using as a writer and add a simple CountDownLatch to it (I'm assuming that reader and writer are running in two different threads) and call countDown() once writing is done? On the reader side, you simply use the latch's await method.

A: AFAIK, there isn't a portable way to do it.  However on Linux you can test if some other process has a file open by running the lsof command and processing its output.
For example:
lsof /home/fred/someFile

will output the pids for the process or processes that have that file open.  If you can assume that the process that is writing the file closes it once it has finished writing (and doesn't reopen it), you can use the lsof output to test if the file has been fully written.
You can run the lsof command from Java using Process / ProcessBuilder.


text:
Q: Adding OnHint-like functionality to a third party component Due to cosmetic reasons the app I'm maintaining uses an ancient component from DevExpress that pre-dated their current grid controls (TdxMasterView if you're interested). What I want to be able to do is to have a tooltip that displays the current cell's text, however this component does not have an OnHint event exposed.
I have been able to get the functionality that I need using the MouseMove event, however as the code requires it to translate the mouse cursor into a cell and then retrieve the contents I think this is too much code for an event that is fired so frequently (although it doesn't feel TOO laggy in operation).
The component itself is derived from TCustomControl, so has the basic Hint and ShowHint properties, however what I think I want is to be able to either expose or add an event that will fire only when the hint bubble will be shown (i.e. the OnHint event or equivalent). All I need to get the correct text is the X and Y coordinates of the mouse. This appears to be tied up in TControlAction, however I'm not entirely sure how this works as it's not immediately clear from a first glance at the code and it's not exposed by the component.
Does anyone have any example code where they have achieved something similar? I have access to the underlying source, so can modify it a bit if needed (DevExpress will never release an update to this code, so normal risks of doing this don't really apply), but I'd prefer to work by helper function, windows message or some sort of decorator if possible.
I suppose the other option is to have a timer to enable/disable the event, but that seems a bit of a sucky (if simple) solution.

A: Implement procedure CMHintShow(var Message: TCMHintShow); message CM_HINTSHOW; in your code.
procedure TMyComponent.CMHintShow(var Message: TCMHintShow);
var
  CellIdx: Integer;
  Handled: Boolean;
  HintStr: string;
  LHintInfo: PHintInfo;
begin
  Message.Result := 1; // Don't show the hint
  if Message.HintInfo.HintControl = Self then
  begin
    with Message.HintInfo.CursorPos do
    begin
      CellIdx := ImageAtPos(X, Y);
    end;

    Handled := False;
    HintStr := '';
    if Assigned(FOnGetHint) then
      FOnGetHint(Self, CellIdx, HintStr, Handled);
    LHintInfo := Message.HintInfo;
    if (CellIdx <> -1) then
    begin
      if not Handled then
        HintStr := Hint;
      LHintInfo.CursorRect := GetCellRect(CellIdx);
      Handled := True;
    end;
    if Handled then
    begin
      LHintInfo.HintStr := HintStr;
      Message.Result := 0; // Show the hint
    end;
  end;
end;


text:
Q: How to select an individual cell in a SWT Tree with a TreeCursor First I was surprised that TreeCursor.setSelection(TreeItem row, int column) didn't select anything. Then I looked into the source of this method and found that they call Tree.indexOf(). Of course it won't find the tree item if it isn't direct child of the tree.
Don't I understand something about the usage of this class? Is it possible to select a tree item which is not direct child of the tree? I hardly believe that the selection functionality is so limited. I mean a tree is a tree and has usually one root and deep hierarchy...
import org.eclipse.debug.internal.ui.viewers.model.TreeCursor;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeColumn;
import org.eclipse.swt.widgets.TreeItem;

public class Test {

    /**
     * @param args
     */
    public static void main(String[] args) {
        Display display = new Display();
        Shell shell = new Shell(display);
        shell.setLayout(new FillLayout());

        Tree tree = new Tree(shell, SWT.V_SCROLL | SWT.H_SCROLL | SWT.BORDER | SWT.SINGLE | SWT.FULL_SELECTION);

        tree.setHeaderVisible(true);
        TreeColumn column1 = new TreeColumn(tree, SWT.LEFT);
        column1.setText("Column 1");
        column1.setWidth(200);
        TreeColumn column2 = new TreeColumn(tree, SWT.CENTER);
        column2.setText("Column 2");
        column2.setWidth(200);
        TreeColumn column3 = new TreeColumn(tree, SWT.RIGHT);
        column3.setText("Column 3");
        column3.setWidth(200);
        TreeColumn column4 = new TreeColumn(tree, SWT.RIGHT);
        column4.setText("Column 4");
        column4.setWidth(200);

        TreeItem root = new TreeItem(tree, SWT.NONE);
        root.setText(new String[] { "root", "a1", "b1", "c1" });

        TreeItem rootChild1 = new TreeItem(root, SWT.NONE);
        rootChild1.setText(new String[] { "rootChild1", "a2", "b2", "c2" });

        TreeItem rootChild2 = new TreeItem(root, SWT.NONE);
        rootChild2.setText(new String[] { "rootChild2", "a2", "b2", "c2" });

        TreeCursor cursor = new TreeCursor(tree, SWT.NONE);
//      cursor.setSelection(root, 2);
        cursor.setSelection(rootChild1, 2);

        shell.open();
        while (!shell.isDisposed()) {
            if (!display.readAndDispatch()) {
                display.sleep();
            }
        }
        display.dispose();
    }
}

If you uncomment the line 'cursor.setSelection(root, 2);' you will see that the selection works as expected.

A: I'm not quite sure I understand your problem, but this code works for me and selects a TreeItem that is not a direct child of the root:
public static void main(String[] args)
{
    Display display = Display.getDefault();
    final Shell shell = new Shell(display);
    shell.setText("StackOverflow");
    shell.setLayout(new FillLayout());

    Tree tree = new Tree(shell, SWT.NONE);

    TreeItem parent = new TreeItem(tree, SWT.NONE);
    parent.setText("root");

    for(int i = 0; i < 10; i++)
    {
        TreeItem child = new TreeItem(parent, SWT.NONE);
        child.setText("child " + i);

        parent = child;
    }

    tree.setSelection(parent);

    shell.pack();
    shell.open();
    while (!shell.isDisposed())
    {
        if (!display.readAndDispatch())
            display.sleep();
    }
    display.dispose();
}

It looks like this when running:

A: Ok, I found the solution. I switched from org.eclipse.debug.internal.ui.viewers.model.TreeCursor to org.eclipse.swt.custom.TreeCursor (which exists since Eclipse 3.8) and the issue was resolved.


text:
Q: Element#getAttribute not returning default value when attribute isn't present I have the following XML file:
<el id="el1">content</el>

The part of my file which defines the element above is as follows:
<xsd:element name="el" type="myns:el" />

<xsd:simpleType name="state">
    <xsd:restriction base="xsd:string">
        <xsd:enumeration value="enabled" />
        <xsd:enumeration value="disabled" />
    </xsd:restriction>
</xsd:simpleType>

<xsd:complexType name="el">
    <xsd:attribute name="id" type="xsd:string" use="required" />
    <xsd:attribute name="state" type="myns:state"
        default="enabled" />
</xsd:complexType>

My Java code which is supposed to obtain the default value for state looks like the following:
Element e = (Element) ns.getElementsByTagName("el").item(0);
System.out.println(e.getAttribute("state"));

The code above always prints an empty string if I don't set the state attribute in the XML file. Why is that the case? According to the Java documentation, getAttribute returns

The Attr value as a string, or the empty string if that attribute does
  not have a specified or default value.

My question is: why doesn't getAttribute return the default value when a value is not specified?


text:
Q: Can not read excel file in javafx when it converted to JAR I am using Apache POI for reading excel file (in xls and xlsx format).
It runs fine in IDE (I am using IntelliJ), but when I make the project to JAR, it can't read the excel file. I tried by giving full path of excel file, but not working.
File name spelling is right, file is not protected or read only format. Everything is good until I run JAR.
java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(Unknown Source)
    at com.sun.javafx.application.LauncherImpl.launchApplication(Unknown Source)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at sun.launcher.LauncherHelper$FXHelper.main(Unknown Source)
Caused by: java.lang.NoClassDefFoundError: org/apache/poi/hssf/usermodel/HSSFWorkbook
    at TakeInput.Take(TakeInput.java:25)
    at MainGUI.main(MainGUI.java:53)
    ... 11 more
Caused by: java.lang.ClassNotFoundException: org.apache.poi.hssf.usermodel.HSSFWorkbook
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    ... 13 more
Exception running application MainGUI

Here is my TakeInput Class:
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import java.io.*;
import java.util.Arrays;
import java.util.Comparator;
import java.util.StringTokenizer;

public class TakeInput {

public void Take() throws Exception{
    System.out.println("Inside TakeInput class..");

    File f = new File("courses.xls");
    FileInputStream fs = new FileInputStream(f);
    HSSFWorkbook wb = new HSSFWorkbook(fs);
    HSSFSheet sheet = wb.getSheetAt(0);

    int CSECourseCounter=0;

    for(int i=0;i<=sheet.getLastRowNum();i++){
        String tempCode = sheet.getRow(i).getCell(0).getStringCellValue();
        StringTokenizer tok = new StringTokenizer(tempCode);

        String codeTok=tok.nextToken();

        if(codeTok.equals("CSE") || codeTok.equals("CSI")) {
            CSECourseCounter++;
        }

    }

    CourseInfo[] courses = new CourseInfo[CSECourseCounter];
    for(int i=0;i<CSECourseCounter;i++)
        courses[i]=new CourseInfo();

    System.out.println(sheet.getLastRowNum());

    for(int i=0,j=0;i<=sheet.getLastRowNum();i++){
        String tempCode = sheet.getRow(i).getCell(0).getStringCellValue();
        StringTokenizer tok = new StringTokenizer(tempCode);

        String codeTok=tok.nextToken();

        if(codeTok.equals("CSE") || codeTok.equals("CSI")) {
            courses[j].code = sheet.getRow(i).getCell(0).getStringCellValue();
            courses[j].title = sheet.getRow(i).getCell(1).getStringCellValue();
            courses[j].section = sheet.getRow(i).getCell(2).getStringCellValue();
            courses[j].day = sheet.getRow(i).getCell(4).getStringCellValue();
            courses[j].time = sheet.getRow(i).getCell(5).getStringCellValue();
            //courses[i].room = sheet.getRow(i).getCell(6).getNumericCellValue();
            //System.out.println(courses[j].code);
            j++;
            //CSECourseCounter++;
        }
    }

    Arrays.sort(courses, new Comparator<CourseInfo>() {
        @Override
        public int compare(CourseInfo o1, CourseInfo o2) {
            return o1.title.compareTo(o2.title);
        }
    });

    System.out.println("CSE courses = "+CSECourseCounter);

    for(int i=0;i<CSECourseCounter;i++){
        courses[i].setCampus();
        courses[i].setLabCLassAndTimeSlot();
        courses[i].setDay();
    }

    //***************************** CourseInfo to a linked list ******************

    for(int i=0;i<courses.length;i++){

        CourseToLinkedList temp = AddSearchCourse.searchCourse(courses[i].code);

        if(temp==null) {
            AddSearchCourse.addCourse(courses[i].title,courses[i].code,courses[i].islabClass);
            CourseToLinkedList temp1 = AddSearchCourse.searchCourse(courses[i].code);
            temp1.addSections(courses[i].code,courses[i].title,courses[i].section,courses[i].day,courses[i].time,
                    courses[i].timeStart,courses[i].timeEnd,courses[i].room,
                    courses[i].faculty,courses[i].credit,courses[i].assigned,
                    courses[i].campus,courses[i].dept,courses[i].islabClass,
                    courses[i].timeSlot,courses[i].labTimeSlot,courses[i].day1,courses[i].day2
            );
        }
        else{
            CourseToLinkedList temp1 = AddSearchCourse.searchCourse(courses[i].code);
            temp1.addSections(courses[i].code,courses[i].title,courses[i].section,courses[i].day,courses[i].time,
                    courses[i].timeStart,courses[i].timeEnd,courses[i].room,
                    courses[i].faculty,courses[i].credit,courses[i].assigned,
                    courses[i].campus,courses[i].dept,courses[i].islabClass,
                    courses[i].timeSlot,courses[i].labTimeSlot,courses[i].day1,courses[i].day2
            );
        }
    }

    System.out.println("outside try catch..");
}
}

I put a copy of this excel file which is in the project folder to that folder where JAR file situated. No problem with location.

A: As I can see the logs, this issue may happen because of dependency jars for your code. try to add the jar(may be 'jakarta-poi-version.jar') having class 'HSSFWorkbook' into your class path and then try to run it again.


text:
Q: Are dialogs supported in jquery-ui Version 1.11.0? I'm looking at legacy javascript code and am attempting to add a popup dialog to a webpage.
I added the dialog html/script to the page. At runtime, I get the following error:

Uncaught TypeError: $(...).dialog is not a function

The client is using the following:

jquery-ui version 1.11.0 (circa 2014).
jquery version 2.1.4

Were dialogs not supported back in jquery-ui 1.11.0?
Before I upgrade everything here to the latest versions of jquery/jquery-ui,
I want to be sure that this a version issue before I initiate of upgrading.

A: Yes.  As can be found by going to the jquery ui website and navigating to the older documentation (found on the bottom left), you can find the api documentation for 1.11 containing the Dialog widget.
https://api.jqueryui.com/1.11/category/widgets/
https://api.jqueryui.com/1.11/dialog/


text:
Q: Why are member functions passed differently than local functions to a std::thread? I'm trying to understand how std::thread is used.
The header looks as follows:
template< class Function, class... Args >
explicit thread( Function&& f, Args&&... args );

*

*How does one identify whether f is a universal ref or rvalue? From what I found online:

"If T is getting deduced and variable / parameter type is unqualified T&& , then only it's a Universal Reference."

what does unqualified T&& refer to? auto or template?

*

*If I have a function foo, I could call use it like std::thread(foo). Does that mean foo is being used as an lvalue reference because it doesn't qualify for rvalue reference?

*Why does the way a function is passed differ from in the case of member functions? if foo was a part of the class, you won't be able to use it like std::thread(obj.foo) - instead std::thread(&Class::foo, &obj) works. What's the logical reasoning behind it?

*How does one pass a local variable/vector to a thread? I tried the following but in the function itself, I can't access any vector elements even though vector.size() does output correctly.
void Class::foo(vector<int>v)
{
   std::cout<<v[0]; // prints nothing
}

int main(void)
{
    std::vector<int>v = {12,3};

    Class obj;

    std::thread t1(&Class::foo, &obj, v);

    t1.join();

}

A:
what does unqualified T&& refer to?

It refers to the function parameter of the function template. f and args... are the parameters. They satifsy the described requirment of being forwarding references (as long as the template type argument isn't passed explicitly inn which case the type would not be deduced from the function argument).

Why does the way a function is passed differ from in the case of member functions?

Because non static member functions have an implicit instance parameter, and because they don't implicitly decay to pointer to member function.

How does one pass a local variable/vector to a thread?

Depends on context. Copying is usually simplest.


text:
Q: Confused as to the procedure to install a java application New to Ubuntu, using 18.04.
I'm trying to work out the best procedure for installing jwildfire flame fractal software. If you're interested go here http://jwildfire.org/
The install is just a bunch of files in a .zip file that just need to be unpacked into a directory. The app is launched by executing the j-wildfire-launcher.jar
Question 1 - Where should this be unpacked to, and why?
Question 2 - How to do this?
I've trawled through a bunch of forums and there seems to be no clear consensus as to where things should be installed. Many people say 'just let the installer choose the right place' but this has no installer, it's just a zip file with a java executable.  When I try to use the Archive manager to unpack it into /opt or some such it throws a permissions error.
Any help appreciated

A: Question 1:
There is no definite answers of where to install, but if you want suggestion, I recommend place it to /home/<user>/j-wild-fire (replace <user> to your username) rather than /opt, since /opt require sudo permission to write, this is the reason why you can't create file inside /opt. If you want more about what sudo is, you can read this.
Question 2:

*

*

*

*open the terminal by press ctrl+alt+t

*

*install unzip and java if necessary, by enter the following command in terminal

sudo apt install unzip
sudo apt install default-jre

*

*

*unzip the file

unzip <location_of_your_zip_file> -d /home/<user>/j-wild-fire

*

*

*run the program

java -jar /home/<user>/j-wild-fire/j-wildfire-launcher.jar

*

*

*If you want to create launcher, you can follow this, and use the command in step.4


text:
Q: Display ñ on a C# .NET application I have a localization issue.
One of my industrious coworkers has replaced all the strings throughout our application with constants that are contained in a dictionary.  That dictionary gets various strings placed in it once the user selects a language (English by default, but target languages are German, Spanish, French, Portuguese, Mandarin, and Thai).
For our test of this functionality, we wanted to change a button to include text which has a ñ character, which appears both in Spanish and in the Arial Unicode MS font (which we're using throughout the application).
Problem is, the ñ is appearing as a square block, as if the program did not know how to display it.  When I debug into that particular string being read from disk, the debugger reports that character as a square block as well.
So where is the failure?  I think it could be in a few places:
1) Notepad may not be unicode aware, so the ñ displayed there is not the same as what vs2008 expects, and so the program interprets the character as a square (EDIT: notepad shows the same characters as vs; ie, they both show the ñ.  In the same place.).
2) vs2008 can't handle ñ.  I find that very, very hard to believe.
3) The text is read in properly, but the default font for vs2008 can't display it, which is why the debugger shows a square.
4) The text is not read in properly, and I should use something other than a regular StreamReader to get strings.
5) The text is read in properly, but the default String class in C# doesn't handle ñ well.  I find that very, very hard to believe.
6) The version of Arial Unicode MS I have doesn't have ñ, despite it being listed as one of the 50k characters by http://www.fileinfo.info.
Anything else I could have left out?
Thanks for any help!

A: I would say that most certainly Notepad is the culprit.  Notepad does not deal well with unicode characters.  If you want to hand edit this file, use something like Notepad++ which can handle unicode, and make sure you save the file as UTF-8. You can probably just use VS to edit the file, and just forget about notepad or Notepad++ completely.  .Net and Visual studio are actaully very good at handling accented characters. All strings are UTF-8 by default, so the problem almost certainly lies with Notepad.

A: How are you reading the strings?
Have you tried to read the text file like this (with the encoding on set to UTF8):
using(StreamReader sr = new StreamReader(File.Open("file.txt", FileMode.Open), Encoding.UTF8))
{
// add your string to dictionary
}

A: I have a very short guide to debugging Unicode problems. It's targeted at fetching text from databases, but the same principles apply in general.
The most important starting point IMO is to know what's actually in your string when it just shows a box. Dump the contents to the console, with code like this:
static void DumpString (string value)
{
    foreach (char c in value)
    {
        Console.Write ("{0:x4} ", (int)c);
    }
    Console.WriteLine();
}

Then look up the character in the code charts on unicode.org. I suspect you want U+00F1, but there may be another similar character with a different code point - I've been fooled by that before.

A: I was having a similar problem just the other day - see Unicode characters not showing in System.Windows.Forms.TextBox.  I was able to fix by changing a TextBox to a RichTextBox.

A: Have you tried using String.Format when assigning the button.Text property, and providing the proper IFormatProvider with a spanish CultureInfo object?
I don't know if that would have an effect, but could help.

A: Have you checked that your source file encoding is really utf-8? May not be applicable to default vs2008 install but IDE may detect your OS' default locale (or filesystem encoding) and set the matching non-utf-8 encoding for all your files. You might want to try with the doubly encoded mess (which you often come across on the web) "ñ" without changing anything in your setup to test your encoding mismatches.
I have bitten by this thing when I get to work on a coworker's god-knows-what-editor-in-what-encoding code.
I'm quite sure and assume all your api calls are utf-8 aware so all your text is interpreted as utf-8 even if it is not.

A: To read correctly spanish characters (ñ, á, é, etc) you can try the Codepage 1252 for the Encoding.


text:
Q: Second XSLT in SAXTransform chain does not seem to do anything Before I go into the specific details, I tried this before with Oracle's parser.v2 XSLT libraries and ran into the same problem (see my first question).  However, it works fine when I use C#.
// from the example I see everywhere on the internet
SAXTransformerFactory stf = (SAXTransformerFactory)TransformerFactory.newInstance();

Templates t_cctagstrip = stf.newTemplates(new StreamSource(new FileInputStream("C:\\path\\to\\first.xsl")));
Templates t_cctable = stf.newTemplates(new StreamSource(new FileInputStream("C:\\path\\to\\second.xsl")));

TransformerHandler th1 = stf.newTransformerHandler(t_cctagstrip);
TransformerHandler th2 = stf.newTransformerHandler(t_cctable);

// transform 1 pipes into transform 2
th1.setResult(new SAXResult(th2));

// transform 2 pipes to System.out
th2.setResult(new StreamResult(System.out));

Transformer t = stf.newTransformer();
t.transform(new StreamSource(new FileInputStream("C:\\path\\to\\source.xml")), new SAXResult(th1));

I'm thinking that maybe the problem lies in the fact that the output from the first transform is a fragment with text at the root level?
text at root level
<tag> ... tags that need extra processing ... </tag>
more text at root level

Is there something different about how C# processes the transforms?  It's not failing or giving me any warnings that I can tell.  It's just not changing anything.

A: You didn't in your first question mention the actual problems you're running into, e.g., providing any log messages, etc. so it was impossible to know why your XSLT transformations are failing. But in this second question you clearly reveal why things are failing.
In general, XSLT transformations require all parsed content to be at very least well-formed XML. If your source document isn't wrapped with a "root" element (actually called a document element) then it's not well-formed XML, therefore not by definition XML, and therefore not suitable for XML processing.
As a solution, if you can wrap the output from the first transform in a document element you could then continue to parse it as XML. You could then strip it off later via a non-XML process.
There won't be any difference between Java or C# in this regard. If the output from the first transformation is not well-formed XML then C# shouldn't be accepting it as XML. I can't explain why it might be doing so — C#'s XML processor would be non-compliant if it accepted non-well-formed XML. I imagine the reason you're not getting any output is that the transformation is simply failing due to the non-XML source. In order to find out what's actually going on you might set an javax.xml.transform.ErrorListener on your Transformer, and in your ErrorListener dump everything to a log.
(As a bit of a tangent, you also state you're required to use Oracle's XSL processor. Really? I'll assume there must be some features in Oracle's implementation that aren't available in Xalan or Saxon, as you'd be tying your code to an implementation rather than using the JAXP API, which is certainly not recommended practice. It's probably better to debug problems when coding to the API to be sure that they're not implementation-dependent, since you aren't able to change the internal code of an implementation and it's better to only be debugging your own defects, not Oracle's. But given your example code above seems to be using the JAXP API I'll assume the problems you have aren't actually tied to Oracle's XSLProcessor.)


text:
Q: Where can I find deleted packages from debian main pool? I'm in need for an older version of debootstrap(1.0.93 to be specific). I can't find it in the pool. The newer version(0.97) is giving some issues. The older one worked fine. I'm pretty sure that I downloded 0.93 from the main pool. Don't they keep a copy of every version? I can't find them here. Any other place to look for?

A: You can get debootstrap v1.0.93 from snapshot.debian.org, but be warned that the site does not support encryption so you should verify your downloads.
http://snapshot.debian.org/package/debootstrap/1.0.93%2Bnmu3/
If the site goes down (which it does occasionally), check the Internet Archive's Wayback Machine for a cached version of its contents.


text:
Q: Show that (X,d) is complete Suppose $(X,d)$ is a metric space and for all sequences $ \{x_n\} $, if $\sum d(x_n,x_{n+1})< \infty $ then  $ \{x_n\} $ converges. Prove that $(X,d)$ is complete.
Question: I can show that if $\sum d(x_n,x_{n+1})< \infty $ then the sequence is Cauchy, but what if there is a Cauchy sequence that does not satisfy the condition $\sum d(x_n,x_{n+1})< \infty $, how can I prove that the space is complete?

A: An obvious counterexample is $\mathbb R$. However, if you meant '$(X,d)$ is complete' instead of '$(X,d)$ is compact' then the result is true. Given any Cauchy sequence $\{x_n\}$ find  a subsequence $\{x_{n_{k}}\}$ such that $\sum d(x_{n_{k}},x_{n_{k+1}})<\infty$, conclude that $\{x_{n_{k}}\}$ converges. If  a subseqeunce of a Cauchy sequence converges the whole sequence converges.


text:
Q: How to built scatter plot in Tableau with only 2 measures? I am trying to built scatter plot in Tableau using https://raw.githubusercontent.com/mwaskom/seaborn-data/master/iris.csv
I want all points to be plotted but Tableau is aggregating(summing) and plotting 1 point. How can I do this? I am able to get required scatter plot in seaborn/python but want to do it in Tableau


text:
Q: SCSS (SASS) Efficiency Assistance I was just wondering if anyone knew anyway i could make the below code anymore efficient or dynamic, I have already achieved the desired result i would just like to know if it can be made to work better.
 The Script
Any answer would be greatly appreciated,
Cheers,
Jackson Redmond

A: I suggest you to have a look compass. It provides a lot of useful mixins (e.g. box-shadow or border-radius) for Scss or Sass. They are working on an animation module, so have a look at this commit to see how they are implementing this.


text:
Q: SwiftUI: WebView reloads if ActionSheet presented I have a WebView on my UI that I only load during instantiation. But if I present an action sheet it loads it's content again. Any idea why?
struct DetailView: View {

    let url: URL
    private let NC = NotificationCenter.default
    @State private var showingSheet = false
    @Environment(\.presentationMode) private var presentationMode
    var webView: WebView

    init(url: URL){
        self.url = url
        webView = WebView(url: url)
    }

    var body: some View {

        ZStack{
         ShakableViewRepresentable().allowsHitTesting(false).onAppear(){
         self.NC.addObserver(forName: Constants.shakeNotification, object: nil, queue: nil, using: self.shakeDetected)
         }

        webView
            .padding( .bottom, -40.0)
            .padding(.top , -45.0)
            .frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity, alignment: .topLeading)
            .edgesIgnoringSafeArea(.all)

            .actionSheet(isPresented: $showingSheet) {
                ActionSheet(title: Text("What do you want to do?"), message: Text("There's only one choice..."), buttons: [.default(Text("Restart")), .default(Text("Exit"), action: {
                    self.presentationMode.wrappedValue.dismiss()
                }), .cancel()])
            }

        }
        .hideNavigationAndStatusBar()

    }

    func shakeDetected(_ notification: Notification) {
        showingSheet = true
    }

}

Some notes: With ShakableViewRepresentable I detect a shake gesture. If this is detected I present the action sheet. hideNavigationAndStatusBar() does what it is called.
Edit:
Here is my WebView:
struct WebView: UIViewRepresentable{

    var url: URL

    func makeUIView(context: UIViewRepresentableContext<WebView>) -> WKWebView {
        return WKWebView()
    }

    func updateUIView(_ uiView: WKWebView, context: UIViewRepresentableContext<WebView>) {
        let request = URLRequest(url: url)
        uiView.load(request)
    }

}


text:
Q: Unable to transfer token to another account due toTypeError: Cannot read property 'toString' of undefined I am trying to transfer the token to another account using the Solana rust program. I am currently using the Anchor framework. I have created the program for it.
Now, I am trying to execute the test case to check the transfer functionality. But I am getting an error as TypeError: Cannot read property 'toString' of undefined
I am not able to get the cause of the error.
Please take a look at my code.
use anchor_lang::prelude::*;
use anchor_spl::token::{ Token, TokenAccount, Transfer, Mint, self };

pub fn transfer_sol(ctx:Context<TransferInfo>) -> Result<()>{
    let amt: u64 = 1000000;
    msg!("Lamport: {}",amt);
    msg!("Starting Tokens: {}",ctx.accounts.sender.amount);
    let cpi_ctx = CpiContext::new(
        ctx.accounts.token_program.to_account_info(),
        Transfer{
            from:ctx.accounts.sender.to_account_info(),
            to:ctx.accounts.receiver.to_account_info(),
            authority:ctx.accounts.authority.to_account_info(),
        }
    );
    token::transfer(cpi_ctx,amt)?;
    ctx.accounts.sender.reload()?;
    Ok(())
}

#[derive(Accounts)]
pub struct TransferInfo<'info>{
    #[account(mut)]
    pub sender: Box<Account<'info, TokenAccount>>,
    #[account(mut)]
    pub receiver: Box<Account<'info, TokenAccount>>,
    pub authority: Signer<'info>,
    pub mint: Box<Account<'info, Mint>>,
    pub token_program: Program<'info, Token>,
}

it("Is transfer!", async () =>{
      //let amount = new anchor.BN(1000000);
      //let amount = new anchor.web3.BN(LAMPORTS_PER_SOL);

      await program.methods.transfera()
        .accounts({
          sender:provider.wallet.publicKey,
          receiver:receiver_token.publicKey,
          authority:provider.wallet.publicKey,
          mint: mint.publicKey,
          tokenProgram:TOKEN_PROGRAM_ID
        })
        .signers([sender_token.publicKey])
        .rpc();

      let tokenbal = await provider.connection.getTokenAccountBalance(sender_token.publicKey);
      console.log("tokenbal ",tokenbal);

      let tokenbalm = await provider.connection.getTokenAccountBalance(receiver_token.publicKey);
      console.log("tokenbalm ",tokenbalm);

  });

Below is the error occured while running testcase.
Is transfer!:
     TypeError: Cannot read property 'toString' of undefined
      at Transaction.partialSign (node_modules/@solana/web3.js/src/transaction/legacy.ts:642:36)
      at /opt/projects/demo/rust-demo/second/node_modules/@project-serum/anchor/src/provider.ts:142:10
      at Array.forEach (<anonymous>)
      at AnchorProvider.sendAndConfirm (node_modules/@project-serum/anchor/src/provider.ts:141:21)
      at processTicksAndRejections (internal/process/task_queues.js:95:5)
      at MethodsBuilder.rpc [as _rpcFn] (node_modules/@project-serum/anchor/src/program/namespace/rpc.ts:29:16)

Please suggest any solution for it.


text:
Q: Changing the background image of  with jQuery not working I know it's possible to change the background image for body or div tags, but is it possible to add or change the background image for the html tag?
I tried the following, but it didn't work:
$("html").css('background', 'url(../images/myImage.jpg)');

Is there another way?

A: Try $('body').parent().css('background', 'url(imagePath)'). It should work.

A: This method is perfec
var id_of_div ="contenedor";
document.getElementById(id_of_div).style.backgroundImage='http://conectica.com.mx/wp-content/uploads/2013/08/youtube-ios.png';

that's all


text:
Q: 2 errors in libsvm matlab "Model does not support probabiliy estimates and Subscripted assignment dimension mismatch" I want to classify a list of 5 test images using the library LIBSVM with a strategy 'one against all' in order to obtain probabilities for each class. the used code is bellow :
load('D:\xapp.mat');
load('D:\xtest.mat');
load('D:\yapp.mat');%% matrix contains true class of images yapp=[641;645;1001;1010;1100]
load('D:\ytest.mat');%% matrix contains unlabeled class of test set  ytest=[1;2;3;4;5]
numLabels=max(yapp);
numTest=size(ytest,1);
%# train one-against-all models
model = cell(numLabels,1);
for k=1:numLabels
   model{k} = svmtrain(double(yapp==k),xapp, ['-c 1000 -g 10 -b 1 ']);
end
%# get probability estimates of test instances using each model
prob = zeros(numTest,numLabels);
for k=1:numLabels
   [~,~,p] = svmpredict(double(ytest==k), xtest, model{k}, '-b 1');
   prob(:,k) = p(:,model{k}.Label==1);    %# probability of class==k
end
%# predict the class with the highest probability
[~,pred] = max(prob,[],2);
acc = sum(pred == ytest) ./ numel(ytest)    %# accuracy

I obtain this error :

Model does not support probabiliy estimates
  Subscripted assignment dimension mismatch.
     Error in comp (line 98)
     prob(:,k) = p(:,model{k}.Label==1);    %# probability of class==k

please, help me to solve this error and thanks in advance

A: What you're trying to do is to use a code snippet that evaluates a SVM classifier performances whereas your goal is to properly estimate the labels for your test set.
I assume your five labels are [641;645;1001;1010;1100] (as in yapp). First thing you have to do is delete ytest, because you don't know any labels for the test set. It is pointless to fill ytest with some dummy values: the SVMs will return our predicted labels.
The first error, as already pointed out in the comments is in
numLabels=max(yapp);

you must change max() with length() in order to gather the number of classes.
The training stage is almost correct.
Given the fact that k goes from 1 to 5 whereas yapp has the range above, you should consider changing double(yapp==k) into double(yapp==yapp(k)): in this manner we mark as positive the k-th value in yapp. Given the fact that k goes from 1 to 5, then yapp(k) will go from 641 to 1100.
And now the prediction stage.
The first input for svmpredict() should be the test labels but now we don't know them so we can fill it with a vector of zeros (there will be as many zeros as there are patterns in the test set). That is because svmpredict() automatically returns the accuracy as well if the test labels are known, but that's not the case. So you must change the second for-loop to
for k=1:numLabels
   [~,~,p] = svmpredict(zeros(size(xtest,1),1), xtest, model{k}, '-b 1');
   prob(:,k) = p(:,model{k}.Label==1);    %# probability of class==k
end

and finally predict the labels with
[~,pred] = max(prob,[],2);

and pred contains the predicted labels.
Note 1: in this method, however, you cannot measure accuracy and/or other parameters because what we called the test set actually is not a test set. A test set is a labelled set and we pretend we don't know its labels in order to let the SVM predict them and then match the predicted labels with the actual labels in order to measure its accuracy.
Note 2: predicted labels in pred will most likely have values in range 1 to 5 due to the second for-loop. However, since your labels have different values, you can map back taking into account that 1 is 641, 2 is 645, 3 is 1001, 4 is 1010, 5 is 1100.


text:
Q: String and EditText function issues in Android i'm trying to trigger a conditional by checking the user input in an EditText field.  when i print the String from the EditText to logcat, i can see the data change, but the String functions that check against the values always return false.
if(((EditText)findViewById(R.id.drv_in)).getText().toString().equals("")) {
    TX_FAIL_TEXT = "Missing Driver ID!";
}
Log.e("SMSDRVERR", ((EditText)findViewById(R.id.drv_in)).getText().toString());

this code always displays "Missing Driver ID!".  i have tried these other conditionals, with no success:
(((EditText)findViewById(R.id.drv_in)).getText().toString().isEmpty())  //does not compile, says cannot find symbol, but the function is in the Android documentation
(((EditText)findViewById(R.id.drv_in)).getText().toString().length() < 1) //returns false, even for strings of length > 1

i can confirm that the data is, indeed, no null by looking at logcat and seeing my data show up in the logs.  what's wrong with the conditional?
it doesn't fail if you insert no data in the first transmit. if the first transmit fails, all subsequent transmissions fail, regardless of whether you change the data or not. furthermore, if it passes the first transmission, it will pass all subsequent transmissions.
additionally, there are other conditionals, posted in the full code below, which also evaluate only on the first click of the button.
transmit.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
        //data validation
        ///////////////////////
        boolean valid = true;
        if(((EditText)findViewById(R.id.drv_in)).getText().toString().equals("")) {
            TX_FAIL_TEXT = "Missing Driver ID!";
            showDialog(DIALOG_FAIL);
            TX_FAIL_TEXT = "Transmission Failed!"; //reset the dialog fail text to default
            valid = false;
        }
        Log.e("SMSDRVERR", ((EditText)findViewById(R.id.drv_in)).getText().toString());
        if(custSpn.getSelectedItemPosition() == 0) {
            TX_FAIL_TEXT = "Missing Customer Selection!";
            showDialog(DIALOG_FAIL);
            TX_FAIL_TEXT = "Transmission Failed!"; //reset the dialog fail text to default
            valid = false;
        }
        if(prdSpn.getSelectedItemPosition() == 0) {
            TX_FAIL_TEXT = "Missing Product Selection!";
            showDialog(DIALOG_FAIL);
            TX_FAIL_TEXT = "Transmission Failed!"; //reset the dialog fail text to default
            valid = false;
        }
        if(((Cursor)prdSpn.getItemAtPosition(prdSpn.getSelectedItemPosition())).getString(prdSpn.getSelectedItemPosition()).contains("CAR") ||
                ((Cursor)prdSpn.getItemAtPosition(prdSpn.getSelectedItemPosition())).getString(prdSpn.getSelectedItemPosition()).contains("AUTO") ||
                ((Cursor)prdSpn.getItemAtPosition(prdSpn.getSelectedItemPosition())).getString(prdSpn.getSelectedItemPosition()).contains("TRUCK")
            ) {
            //must have make, license# and 1vin
            if(((EditText)findViewById(R.id.make_in)).getText().toString().equals("")) {
                TX_FAIL_TEXT = "Vehicle Entry:\n Missing Make/Model!";
                showDialog(DIALOG_FAIL);
                TX_FAIL_TEXT = "Transmission Failed!"; //reset the dialog fail text to default
                valid = false;
            }
            if(((EditText)findViewById(R.id.tag_in)).getText().toString().equals("")) {
                TX_FAIL_TEXT = "Vehicle Entry:\n Missing Tag Number!";
                showDialog(DIALOG_FAIL);
                TX_FAIL_TEXT = "Transmission Failed!"; //reset the dialog fail text to default
                valid = false;
            }
            if(((EditText)findViewById(R.id.vin1_in)).getText().toString().equals("") ||
                    ((EditText)findViewById(R.id.vin2_in)).getText().toString().equals("") ||
                    ((EditText)findViewById(R.id.vin3_in)).getText().toString().equals("") ||
                    ((EditText)findViewById(R.id.vin4_in)).getText().toString().equals("") ||
                    ((EditText)findViewById(R.id.vin5_in)).getText().toString().equals("") ||
                    ((EditText)findViewById(R.id.vin6_in)).getText().toString().equals("") ||
                    ((EditText)findViewById(R.id.vin7_in)).getText().toString().equals("") ||
                    ((EditText)findViewById(R.id.vin8_in)).getText().toString().equals("")
                ) {
                TX_FAIL_TEXT = "Vehicle Entry:\n Missing VIN Number!";
                showDialog(DIALOG_FAIL);
                TX_FAIL_TEXT = "Transmission Failed!"; //reset the dialog fail text to default
                valid = false;
            }
        }
        //Log.e("smsDRVERR",((EditText)smsActivity.this.findViewById(R.id.drv_in)).getText().toString());
        //begin transmission
        ///////////////////////
        if(valid) {
            showDialog(DIALOG_TX_PROGRESS);
            Thread t = new Thread(txRunnable);
            t.start();
        } else {
            //do things if needed

        }
    }

A: I'd post this as a comment, but it'd be too long...
I don't think the problem is what you think it is. However, I can't say what the problem is, because you haven't been clear about how you're detecting success and/or failure.
Let's start by clarifying the diagnostic code, to remove any possible ambiguities. I'd suggest you change this:
if(((EditText)findViewById(R.id.drv_in)).getText().toString().equals("")) {
    TX_FAIL_TEXT = "Missing Driver ID!";
}
Log.e("SMSDRVERR", ((EditText)findViewById(R.id.drv_in)).getText().toString());

to:
final String drv = (EditText)findViewById(R.id.drv_in)).getText().toString();
if(drv.equals("") {
    TX_FAIL_TEXT = "Missing Driver ID!";
    Log.e("SMSDRVERR", "Missing ID " + drv);
}
else {
    Log.e("SMSDRVERR", "Found ID" + drv);
}

This will eliminate any possible ambiguity in the log about whether the text really was missing. (It also makes for more readable code.)

A: the problem was actually with the Dialog objects.  the conditional is fine.  at the beginning of the onClick method, i added a call to:
 removeDialog(DIALOG_FAIL);

this forces Android to rebuild the Dialog the next time it is called.
EDIT: for future reference, there is a more elegant way to do this using onPrepareDialog(), but this solution was easier for me.


text:
Q: How is this ground fault circuit working? I am having a difficult time understanding a few things in regards to the ground fault detection circuit below. I have found this circuit while investigating ground fault detection. I intend to build my own circuit for use in my system and am using this as a starting point.
Note the circuit below is to be matched with this CT.

Now, my questions are...

*

*I assume the intent of D1 is to provide over voltage protection. However, I don't see how that works with this particular diode. These are standard Shottky diodes which don't conduct when reversed biased. Why not just use a TVS for this sort of thing? I must be missing something here. I feel silly asking...

*R17 becomes the burden of the CT and develops a voltage proportional to the current. This particular circuit uses a value of 330 ohms. If I understand the CT datasheet correctly that yields a voltage around 6.5V at the rated current which doesn't seem like a good choice. However, I am not sure I read the datasheet correctly. Is Te turns ratio? How do I chose the value R for a GFI situation? The data sheet recommends choosing R such that V < .8 Vl but they fail to specify what Vl is (or perhaps I should know this).

*The threshold for tripping is set by R15 and R14. C14 would add some delay. R16 and R20 act to amplify the current reading. How would appropriate values be determined here? In other words, what's safe or customary?

Note that this is a one off design which wouldn't necessarily have to conform to any regulations but I'd still like to get a handle on this.
EDIT:
The AC leads (hot, hot, ground) will enter the enclosure and run to relay contacts. The leads then run from the relay contacts and exit the enclosure. I was planning only to run the two hot legs through the CT right where they enter the enclosure.

A: The circuit is just a peak detector, that has a gain of 100 with a little bandwidth limiting Low Pass Filter, followed by a comparator that compares the output of the peak detector with 0.8V.
C14 is not for a delay, its there to set the peak hold time.  It's charged through the diode, D3, but has no discharge path so holds the highest voltage it sees. Normally there would be a parallel large value resistor to make this hold time more predictable, currently it's set by the comparator opamps input resistance and it's own leakage.
As the current in the CT increases (because of a fault) the voltage across R17 increases, this is clipped by D1. The peak detector amplifies negative signals better than positive ones (because it's inverting and the output can't go below zero), so it smooths out the bumps in the negative AC, as well as (for a short time) capturing the peak voltage of the negative cycle.  If this peak exceeds 0.8V the output goes high.
The circuit is missing a latch to capture the fault signal, so as it is it would oscillate.  When the load is remove by the detector circuit, the current would drop to zero and after a short time the fault output would be de-assert, turning back on the load.


text:
Q: How to install Python Modules I want to install pyserial for python, but I don't know how. I have tried stuff like pip, but it doesn't recognise the install command. How do I install it?

A: First you have to install pip  follow this link .Then you can use pip install pyserial
Or you can download pyserial from gituhub and run python setup.py install

A: How about your python version? The default version of python is 2.x. If you want to use python 3 then install it with pyenv to control your python version.
I think it would be easier for you to solve this problem if you are using windows. Simple install python3 and pip is automatically there. All you need to do is
pip install pyserial

or
pip3 install pyserial

About how to install python3 on windows:
install python3 on windows
Good luck!

A: in terminal use python -m pip install 'packagename'
in python shell try
import pip
pip.main(['install','pyserial'])

or download the module and use python setup.py pyserial
( How to manually install a pypi module without pip/easy_install? )


text:
Q: HTTP patch not supported as a method I am trying to integrate with a third party service, while trying to make a http request , i want to send PATCH as a method,I have looked for two solutions mentioned here in this questionHow can I make a PATCH HTTP Callout from Apex?
In both the solution , i get the exact same error like the one when i tried without the workarounds.The requested resource was not found, or a disallowed method was used.
The service is expecting PATCH as method ,not PUT nor POST and these workarounds are not overriding httpmethod as PATCH.
public class CRMOppUpdate{

public static void performUpdateOnOpportunity(){
    String strToken='';
    string scope='crm';
    strToken = BCDBJWToken.getBearerToken(scope);// Fetching Token
    system.debug('strToken '+strToken );
    Doc_Generator_Settings__c docGenSettings = Doc_Generator_Settings__c.getOrgDefaults(); // Custom Settings
    String apiKey =docGenSettings.Client_Id__c;
    STring SiebelEndpoint = docGenSettings.Endpoint_c;
    String requestBody= JSONGeneratorCRM.createJSON();
    system.debug('requestBody'+requestBody);
    HttpRequest req = new HttpRequest();
    Http http = new Http();
    HTTPResponse responseString;
    string strEndpoint =SiebelEndpoint +'/opportunities/1-2DJLY2S?_HttpMethod=PATCH';

    system.debug('strEndpoint'+strEndpoint);
    req.setEndPoint(strEndpoint);
    String authorizationHeader = 'Bearer '+ strToken;
    req.setHeader('Authorization', authorizationHeader);
    req.setHeader('Accept','application/json');
    req.setHeader('Content-Type','application/json');
    system.debug('authorizationHeader'+authorizationHeader);
    req.setHeader('API-Key',apiKey);
    req.setHeader('ApplicationId','CREDITS');
    req.setHeader('Cache-Control','no-cache');
    //req.setMethod('POST');
    PostMethod m = new PostMethod(strEndpoint+ '?_HttpMethod=PATCH');
    //req.setHeader('X-HTTP-Method-Override', 'PATCH');
    req.setBody(requestBody);
    req.setClientCertificateName('ABServices');

    req.setTimeout(120000);
    responseString = http.send(req);
    system.debug('responseString'+responseString.getBody());

}

}


text:
Q: Sending html Email in CakePHP I want to send emails to my users after they get registered in my site. Its like an account-activation mail. I have tried this, but its not working(its my own function from where I am trying to send mails) :
public function send_mail($from,$to,$subject,$msg,$value,$template){
    $Email=new CakeEmail('smtp');
    $Email->template('template','default')
          ->viewVars(array('value'=>$value))
          ->emailFormat('html')
          ->to($to)
          ->subject($subject)
          ->from(array($from=>'My Site'))
          ->send();
}

This is my email.php file's code :
<?php
    class EmailConfig{
        public $smtp=array(
           'transport'=>'Smtp',
           'from'=>array('notification@domain.com'=>'My Site'),
           'host'=>HOST,
           'port'=>PORT,
           'timeout'=>30,
           'username'=>'notification@domain.com',
           'password'=>PASSWORD,
           'client'=>null,
           'log'=>false,
           //'charset' => 'utf-8',
           //'headerCharset' => 'utf-8',
       );
    }

Please help me. Is there anything wrong in my code, or, I have to do something else ?
Thanks.

A: I don't know if you replaced it with dummy data for security's sake, but all those fields in email.php need to contain valid information for an SMTP server. It won't ever work with blatantly false information like "notification@domain.com" as a username.
Not trying to be snarky; just not clear if you understood the default values need to be changed.


text:
Q: TCL script to find a script and add new text before searched string with number Below is the partial content of my input file:
   xyz
   abc
   MainContent(abc_dt) {
      sc: it;
    }
    MainContent(xyz_cnt) {
      sc : it;
    }
    MainContent(asd_zxc) {
      sc : it;
    }

Here, I want to search "MainContent" line and want to add new line before it ... this new line should have "Sb (text which is inside bracket in MainContent_1)"... this should also add opening bracket and closing bracket before next Sb occurance:
Expected output from the script:
   xyz
   abc
   Sb(abc_dt_sb1) {
   MainContent(abc_dt) {
      sc: it;
    }
   }
   Sb(xyz_cnt_sb2) {
    MainContent(xyz_cnt) {
      sc : it;
    }
   }
   Sb(asd_zxc_sb3) {
      MainContent(asd_zxc) {
      sc : it;
    }
   }

Can someone please help to me create a TCL script for this?

A: This code will take your text to be processed on standard input and produce the results on standard output. Redirect it as required.
set counter 0
set expectBrace false
while {[gets stdin line] >= 0} {
    if {!$expectBrace && [regexp {^\s*MainContent\s*\((\w+)\)} $line -> bits]} {
        puts [format "Sb(%s_sb%d) \{" $bits [incr counter]]
        set expectBrace true
    }
    puts $line
    if {$expectBrace && [regexp {^\s*\}\s*$} $line]} {
        puts "\}"
        set expectBrace false
    }
}

Using regular expressions to do the matching of the triggers for state changes in a little state machine (two states, governed by expectBrace) is pretty conventional parsing. I've used format to do the substitutions into the Sb(…) line; these are simple enough that you could use direct substitutions instead if you prefer.
I've not done anything about adding indentation.


text:
Q: How do I cause vertical two-finger swipe behavior to cause a horizontal slider to move left or right? I have a horizontal slider in my app, and I want to make it so that if you have the slider selected, you can do the two-fingered swipe up or down gesture from anywhere on the screen (The scroll up or down gesture) to move the slider left or right. I haven't been able to find anything through google about how to change vertical swipe behavior for Talkback and was wondering if there was in fact a way to change this.

A: I'd really suggest not doing this, it isn't how Android works so it will confuse your users, and be a big source of bugs as any behavior like this can cause touch errors on completely separate views.  I just fixed a problem on something similar in my company's app.
But if you really want to do this-  your root ViewGroup needs to intercept touch events if there are two fingers down and it moves far enough to qualify.  Read https://developer.android.com/training/gestures/viewgroup#intercept for an explanation of how a parent view group can steal touch events from the child.  This is the same way ScrollView works to scroll its contents.  In fact, looking up the AOSP implementation of ScrollView would give you good example code.


text:
Q: Get all string in 1 file text start with character I have a text file. In the text file I have a string like below:
r=[{"\u7ec4ID",dataIndex:"id",key:"id"},{"\u7ec4\u540d\u79f0",dataIndex:"name",key:"name"}...

I want to get \u7ec4ID, \u7ec4\u540d\u79f0 from that text file and put it in a string array.
I have the idea that this string usually starts with the character "\u and ends with " but I don't know how to parse it.
Can you help me?

A: Load the text in your file into a string variable and use Regular expression and LINQ
string filePath = "..."; // Name of your file

var str = File.ReadAllText(filePath);

var values = Regex
    .Matches(str, @"{""[\\a-zA-Z0-9]+""")
    .Cast<Match>()
    .Select(m => m.Value)
    .Select(s => s.Substring(2, s.Length - 3))
    .ToList();

values contains the values you wanted to retrieve.

var values = Regex
    .Matches(str, @"""\\u[\\a-zA-Z0-9]+""")
    .Cast<Match>()
    .Select(m => m.Value)
    .Select(s => s.Substring(1, s.Length - 2))
    .ToList();

A: One option is parse as a Json but you need do some changes before deserialize. If you have this in your file:
r=[{"\u7ec4ID",dataIndex:"id",key:"id"},{"\u7ec4\u540d\u79f0",dataIndex:"name",key:"name"}]

We want this:
r=[{"id":"\u7ec4ID",dataIndex:"id",key:"id"},{"id":"\u7ec4\u540d\u79f0",dataIndex:"name",key:"name"}]

Basically, we do that your "\u... texts become the value part in the json. We create an artificial id property. Then, you can simply deserialize.
Create a class for your items:
public class Item
{
    public string id { get; set; }
    public string dataIndex { get; set; }
    public string key { get; set; }
}

NOTE: If you only need the id, you can remove the other properties.
And deserialize (you need the Newtonsoft nuget package):
// Read the file and "inject" the id property
var content = File.ReadAllText(...);
content = content.Replace("\"\\u", "\"id\":\"\\u");

// Remove the "r=" part to have only the array
var index = content.IndexOf('[');
content = content.Substring(index);

var items = JsonConvert.DeserializeObject<List<Item>>(content);
var ids = items.Select(i => i.id);


text:
Q: Property, iVar, accessor method...? I have a couple of classes that I set up properties in.
e.g. a class called MyDetailCell that subclassed UITableViewCell.
In it I had a property something like...
@property SomeClass *someValue;

Initially I was using it and storing it within the setter function...
- (void)setSomeValue:(SomeClass*)someValue
{
    _somValue = someValue;

    //do something with the _someValue object like changing text or something...
}

Anyway, I decided that I didn't actually need to store the value that was sent in so I was just doing this...
- (void)setSomeValue:(SomeClass*)someValue
{
    //do something with the _someValue object like changing text or something...
}

And then I changed to where I was just passing the setter forward to a subview.  Like this...
- (void)setSomeValue:(SomeClass*)someValue
{
    self.someSubView.someValue = someValue;
}

So now I'm not sure what to use.  I'm not actually saving the property at all now so I guess I don't really need it.  I don't need to access it to get the value either I just need to set it.
At the moment I've left the property in there as it is.

*

*Is that OK?

*Is that bad practise?

*Should I change it for just a setter method instead?

*What are the benefits of doing that?

A:
Is that OK?

No.

Is it bad practice?

Yes.

Should I change it for a just a setter method instead? What are the benefits of doing that?

I don't see what you mean by this. You wrote 'just a setter method' and you also did some processing in the setter method, which is fine, but you did other things wrong. One is that you don't retain a non-delegate object - you should. You don't provide a getter - that's also a broken concept. There can be readonly and readwrite properties, but not write only properties.


text:
Q: How to replace PageParameters constructor (String) in Wicket 6? I'm doing a migration from wicket 1.4 -> 1.5 -> 6. When I was upgrading to 6 I encounter the following compile error:

The constructor PageParameters(String) is undefined

When I looked into the sources of Wicket 1.4, I noticed that this constructor is deprecated but still there (probably that's why I didn't notice it in the migration to Wicket 1.5).
Example of using it in my code:
cancelButton = new AjaxButton("cancelButton", new I18nModel("Common.Cancel"), groupForm) {
    private static final long serialVersionUID = -6267601642356425767L;
    public void onSubmit(AjaxRequestTarget target, Form<?> form) {
        String paramsString = "mode=" + DISPLAY.toString() +
            (groupId == null ? "" : ",id=" + groupId);
        PageParameters params = new PageParameters(paramsString);
        UiUtils.redirect(GroupPage.class, params);
    }
};

What should I use instead? In Wicket 6 I only see two constructors:
PageParameters()
PageParameters(final PageParameters copy)

A: You have to use the add method:
PageParameters pp = new PageParameters();
pp.add("mode",value);

After that redirect as usual.


text:
Q: DataTable checking if null returns an error but not on variable declaration I have this weird error.
On this code, as you can, I have a query on database, return it as DataTable and explicitly declared it null. Now I have a condition to check this if this is null and pass it to a string variable. Everything works fine. I receive an empty string. No exception found.
DataTable dtDateUploaded = _BL.GetRecordByDataTableResults();
dtDateUploaded = null;
string strUploadedDate = dtDateUploaded == null ? string.Empty :
                                        dtDateUploaded.Rows[0].IsNull(0) ? string.Empty :
                                        dtDateUploaded.Rows[0][0].ToString();

But when I used the same condition and pass it directly to a Label control for example (and not use a string variable), I get an object reference error. I wonder why do I get an object reference error if I just used the same code on my string variable above?
LblRecordCount.Text = "Record Uploaded last: " + dtDateUploaded == null ? string.Empty :
                                        dtDateUploaded.Rows[0].IsNull(0) ? string.Empty :
                                        dtDateUploaded.Rows[0][0].ToString();

And the weird part is that this works:
LblRecordCount.Text = "Record Uploaded last: " + strUploadedDate;

A: You get this error because, in the second example, the + operator has precedence over the == operator so you are trying to concatenate the "Record Uploaded last" string to a null variable.
Instead, in the first example, the = operator has lower precedence than the == operator and no error occurs because the ternary operators are evaluated before the assignment.
You should use brackets to group the ternary operators logic together
LblRecordCount.Text = "Record Uploaded last: " + (dtDateUploaded == null ? string.Empty :
                                        dtDateUploaded.Rows[0].IsNull(0) ? string.Empty :
                                        dtDateUploaded.Rows[0][0].ToString());

See MSDN on C# Operators


text:
Q: Did Mad-Eye Moody practice his magical skills in the time between being freed from his magical trunk and the battle in the Department of Mysteries? In the Goblet of Fire, it was said that he was beaten by Barty Crouch Jr. and Wormtail combined, just because he got rusty in his duelling skills.  However, did he manage to defeat any Death Eaters during the Battle of Department of Mysteries?  If so, did he manage to restore his magical skills that he possessed when he fought against Death Eaters during the first wizarding war, by the time he fought against the Death Eaters in the Battle of Mysteries?

A: Moody didn't win in battle at the Ministry.
Though it's possible Moody was still a skilled duelist despite his defeat by Barty Crouch Jr. and Wormtail, Moody wasn't seen actually defeating any of the Death Eaters at the Department of Mysteries, and from what we do see, he doesn't seem to have been very successful in that battle. The first time he's mentioned in the battle is when he and the other Order members arrive through the doors.

"Then, high above them, two more doors burst open and five more people sprinted into the room: Sirius, Lupin, Moody, Tonks and Kingsley." - Harry Potter and the Order of the Phoenix, Chapter 35 (Beyond the Veil)

The next time Moody is mentioned, he's been defeated himself by a Death Eater - he's bleeding from the head and his magical eye came out of its socket and roll away.

"For a moment he thought he had dropped the prophecy, but then he saw Moody's magical eye spinning away across the floor.
Its owner was lying on his side, bleeding from the head, and his attacker was now bearing down upon Harry and Neville: Dolohov, his long pale face twisted with glee." - Harry Potter and the Order of the Phoenix, Chapter 35 (Beyond the Veil)

After that, the next time Moody is seen, he's crawling along the floor to revive Tonks, while Dumbledore immobilized the majority of the Death Eaters who were left.

"Dumbledore had most of the remaining Death Eaters grouped in the middle of the room, seemingly immobilised by invisible ropes; Mad-Eye Moody had crawled across the room to where Tonks lay, and was attempting to revive her; behind the dais there were still flashes of light, grunts and cries – Kingsley had run forward to continue Sirius's duel with Bellatrix." - Harry Potter and the Order of the Phoenix, Chapter 36 (The Only One He Ever Feared)

Therefore, it doesn't seem like Moody defeated any Death Eaters at the Department of Mysteries - he seems to have been quickly dispatched and rendered fairly ineffective by Dolohov, as he was unable to get back up and continue fighting.

A: As Bellatrix mentioned, Moody did not fare so well in the Department of Mysteries. However, that does not mean that he was rusty and hadn't practiced his skills. As I argued in this answer to another of your questions, citing my answer to still another of your questions, Moody was probably subdued by Crouch Jr. and Wormtail because it was a surprise 2-on-1 attack and not because he was rusty. Moreover, as you can see there, I provided examples of virtually all the other Order members also getting defeated at some point, so the fact that Moody lost a duel is not indicative of a significant loss of skills. And finally, as mentioned in both of those answers, even in the beginning of  Deathly Hallows Moody was considered the most powerful member:

"You-Know-Who acted exactly as Mad-Eye expected him to," sniffed Tonks. "Mad-Eye said he'd expect the real Harry to be with the toughest, most skilled Aurors. He chased Mad-Eye first, and when Mundungus gave them away he switched to Kingsley...."


text:
Q: RAM upgrade compatibility for HP Elite 8300 Desktop I have a HP Elite 8300 PC.
https://support.hp.com/us-en/product/hp-compaq-elite-8300-ultra-slim-pc/5232866/document/c03345460
It already has an 4GB x 2 RAM installed. The specification of the RAM already installed are
4GB 1Rx8 PC3L-12800U-11-12-A1  from Kingston
I want to upgrade the RAM on the machine. I have an 8GB RAM  and a 4GB RAM with me with the following specification.
8GB DDR3L-1600 UDIMM 1.35V CL11 from Crucial by Micron
4GB 2Rx8 PC3-10600U-09-11-B1 from Samsung.
I tried inserting both of these.It didn't work. I message that I got was something like, RAM error - The size of the RAM during the last reboot was different and it didn't boot up.
I want to know if the 8GB RAM is compatible with my HP Desktop

A: The
HP Compaq Business PC Maintenance and Service Guide Elite 8300 Series
specifies these memory sticks:

And has these warnings:

Therefore DDR3L is not supported, and also PC3-10600U.
Your two RAM sticks are just not compatible.
If you are buying Crucial RAM, use their
scanner tool
to find guaranteed compatible RAM.


text:
Q: Twisted setup Mac OS compiles forever I enter 'pip install Twisted'. Then I get the message
Running setup.py bdist_wheel for Twisted ... \
and the \ simply doesn't move.
ps -ef tells me that it tries to compile raiser.c
And there it spent the last hour. I went to gymn and it is still there.
It is a clang compiler. I got it from xcode install. It is version 4.2 (clang-425.0.28).


text:
Q: Using user CSS sheet in a template I'm using Django to display user uploaded static HTML and CSS files. The HTML isn't a problem, however I can't get Django to actually render using the uploaded CSS.
Project structure is the following:
my_project
    main_app
    display_app
    my_project
    media
        user
            whatever.html
            whatver.css

My main url.py contains:
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^html_uploads/', include('display_app.urls')),
url(r'^', include('main_app.urls')),] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

display_app urls.py is:
urlpatterns = [
url(r'^(?P<requested>(?:[\w]+\/?)+)$', views.readhtml, name='requested'),]

The relevant part of the view is:
def read_html(request, file_name):
    title = 'html_file_title'
    body = get_body(file_name)
    css_source = 'user/whatever.css'
    return render(request, "display_app/base.html",
            {'title': title,
            'body': body,
            'css_source': css_source,
            'media_url': settings.MEDIA_URL,}
            )

The CSS simply contains:
body {
background-color: #FFCC66
}

And the template looks like:
<head>
    <title>{{ title }}</title>
<link rel="stylesheet" href="{{ media_url }}{{ css_source }}" type="text/css" />
</head>
<body>
{% autoescape off %}
    {{ body }}
{% endautoescape %}
</body>

With this, I get a 404 as Django fails to find /media/user/whatever.css.
If I change the CSS location to:
<link rel="stylesheet" href="/{{ media_url }}{{ css_source }}" type="text/css" />

The 404 warning disappears, the HTML still loads, however the CSS is silently ignored.
The HTML is passed through several functions and heavily modified, therefore passing it as a string made sense, however the CSS should be used directly and I was hoping to load it from the template instead.
What's going on there? Does not getting a 404 warning mean Django is locating the CSS file correctly? If it is, why is it not used?


text:
Q: How can I get weekly total? I am new to SAS and I am having some problems. I have tried several things myself but I keep getting weird results and I don't think I am doing it right.
I have attached a picture of the data. The data shows us birthdays and times.  Provsti is just the place and not relevant. B is dummy variable which is 1 because we have a birth. And then we have year, month, hour, minut and second of the birth. I had to write up a date variable and a date-time variable. I have managed to do this.
Now the problem is that I need to get weekly totals. So how many births occur each week, if we are missing data for a day then that means that a birth did not occur.
My approach was to sum the dummy variable with interval=week. This did not work and I tried to google but could not find a solution.
Best Husky
DATA

A: One way to do it is using SQL, which SAS can process. First, create a computed column for week number:
data table;
set table;
week_num = WEEK(date);
run;

Then, summarize your table:
proc sql;
select week_num
    ,sum(b) as birthCount
from table
group by week_num;
quit;

To save the proc sql table to a table, add the statement create table tableName as before the select statement.

A: Use PROC means and format your date variable with a week format.
Proc means data=have;
Class date;
 Format date weeku7.;
VAR analysis_var;
Run;

Look at the different week formats to see what meets your needs.


text:
Q: R (xlsx) - Write Multiple Excel Files From DF Based on Column Values I have a dataframe with many rows (>300,000) which I would like to write to multiple Excel files using xlsx package.
Sample data -
myData <- data.frame(Letter=c("A","B","C","D","E","F","G","H","I","J"),
                 Fruit = c("Apples", "Pears", "Oranges",
                           "Carrots", "Mangoes", "Potatoes",
                           "Bananas", "Plums","Grapes",
                           "Broccoli"),
                 Country = c("Scotland", "Scotland", "Scotland",
                             "England", "England", "England",
                             "Wales", "Wales", "Wales",
                             "Ireland"))

So, from the sample data I would like to split my Excel workbooks by the 'Country' column.  There would be 4 Excel files with the country name as the filename and I would like them to look like below -
Letter  Fruit    Country
------------------------
A       Apples   Scotland
B       Pears    Scotland
C       Oranges  Scotland

Taking the 'Country' column out of the dataset would be a bonus.
I've figured out how to split these into multiple dataframes using a For loop, and then I could write a 'write.xlsx' line for each country.  But my list of countries is dynamic.  See below example -
for (i in unique(myData$Country)) {
  test <- paste0("excel", i)
  assign(test, myData[myData$Country == i,])
}

I've struggled to fit the write.xlsx function into that loop, but perhaps there's a better way.
Could anybody help please?

A: I would just split them into a list, then use an lapply for the write.xlsx. I'd suggest lapply over a for-loop.
myDatalist <- split(myData, myData$Country)
lapply(1:length(myDatalist), function(x) write.xlsx(myDatalist[[x]],
file = paste0(names(myDatalist[x]), ".xlsx"), row.names = FALSE))

All this does is apply a function to a list.

A: Using the For Loop method...
List <- list()

for (i in unique(myData$Country)) {
  test <- paste0("excel", i)
  testlist<-list(assign(test, myData[myData$Country == i,]))
  List[[test]]<-testlist
}

And as @Anonymous coward showed, simply apply the function to the list
lapply(1:length(List), function(x) write.xlsx(List[[x]],
       file = paste0(names(List[x]), ".xlsx"), row.names = FALSE))


text:
Q: ¿Cómo corregir el error Process exited with code 3221226505? He intentado Este enlace que les comparto y no se si lo modifique bien (Posible Solucion pero a mi no me vale)
El problema comienza al iniciar mi terminal de windows con ubuntu. Se demora unos 3 a 5 minutos en cargar la terminal y sale

[Process exited with code 3221226505].

Tambien yo descarge mi ubuntu y terminal de la store por eso tal vez sea el problema, pero bueno sea lo que sea debe haber solucion por que paso de la nada y en las demas terminales como CMP no se ejecuta ningun comando de wsl y aparte de eso se demora mucho.
Les dejo un pantallazo.

Aqui tambien les dejo mi configuracion que recomiendan en el enlace que les comparti y si alguien sabe como solucionarlo y por que sucedio eso les agradeceria.Este problema parece ser uno nuevo por lo que veo que no hay mucha informacion. Con todo muchas gracias.

Miren gente si alguien sabe tambien le pasa esto a ubuntu voy a buscar informacion de lo que me sale pero si alguin por aqui sabe les agradecere les dejo una imagen de lo que pasa con el.La verdad soy nuevo en esto y me da un dolor de cabeza esto pero poco a poco voy asiendo cosas que me parece que ya mismo encuentro la solucion.

Cuando la encuentre va a estar en los comentarios de momento les agradesco por la ayuda y no duden en dejar su comentario si saben que es,!Gracias¡.

A: Señores, para la gente que tenga el mismo problema, acabo de areglarlo.
Verán primero actualicen su sistema windows y reinicien (Esto viene de esta publicacion: Información de ubuntu).
Despues abran la terminal y el problema cambia (sale otro) les dejo el enlace : Nuevo error y al final de esto su problema con la terminal se habrá solucionado. Bueno, eso espero, de momento a mi me sirvió, espero les sirva a ustedes también.
les dejo la imagen de mi terminal areglada.


text:
Q: bitbucket: fork vs clone? Using Mercurial with a private repository hosted at bitbucket.  I need to add some new features to an application that will potentially end up being serious changes.  I've been debating between creating a named branch or cloning the repository.  I think cloning makes a little more sense for my case as it's almost a new project that will borrow heavily from the current one.
So my plan was to create a brand new repository on bitbucket and the push my local repository to this new repository.
Now I go on bitbucket and I noticed a fork feature.  This seems to clone the repository server side, but also remembers the original repository it was forked from and has tools for showing the difference between them.
What are the pros/cons for this?  Should I just use fork or is there any catch?

A: There are no catches. Forks are just regular clones.
Sometimes I first clone a project from Bitbucket to use and study. And when I have a patch I fork it on bitbucket, push to my new fork and do a pull-request.
So this means you don't have to fork it now. Just clone it locally and decide later that you may want to fork on Bitbucket.


text:
Q: Erro ao usar condicional If Estou tentando analisar os dados da seguinte tabela. Isso é uma registro de trades só para deixar claro.
DATAFRAME:

def lista_preco():

    #ainda falta resolver os trades depois de 19h

    lista_dias = df['DATE'].unique().tolist()
    lista = df['pair'].unique().tolist()
    lista_buy = []
    lista_sell = []

    for dias in lista_dias:
        for tickers in lista:
            if (df['pair']== tickers and df['type'] == 'sell'):

                mask1 = (df['pair']== tickers and df['type'] == 'sell')

                df2 = df[mask1]
                df2['price_vol'] = df2['price'] * df2['vol']
                preco = df2['price_vol'].sum(axis = 0) / df2['vol'].sum(axis = 0)
                lista_sell.append([dias,tickers,preco,"LONG"])

            if (df['pair']== tickers and df['type'] == 'buy'):

                mask2 = df['pair']== tickers and df['type'] == 'buy'

                df2 = df[mask2]
                df2['price_vol'] = df2['price'] * df2['vol']
                preco = df2['price_vol'].sum(axis = 0) / df2['vol'].sum(axis = 0)
                lista_buy.append([dias, tickers, preco, "SHORT"])

    return lista_buy, lista_sell

ERRO:

ValueError                                Traceback (most recent call last)
<ipython-input-16-d301c71c9e88> in <module>
----> 1 lista_preco()

<ipython-input-15-8ac3ff545e1d> in lista_preco()
     12     for dias in lista_dias:
     13         for tickers in lista:
---> 14             if (df['pair']== tickers and df['type'] == 'sell'):
     15
     16                 mask1 = (df['pair']== tickers and df['type'] == 'sell')

~\anaconda3\lib\site-packages\pandas\core\generic.py in __nonzero__(self)
   1477     def __nonzero__(self):
   1478         raise ValueError(
-> 1479             f"The truth value of a {type(self).__name__} is ambiguous. "
   1480             "Use a.empty, a.bool(), a.item(), a.any() or a.all()."
   1481         )

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

A: Acho que estás a complicar mais do que realmente é necessário.
Tendo:
import pandas as pd
from io import StringIO

csv = StringIO("""DATE;time;pair;type;ordertype;price;cost;fee;vol;margin;misc
30/12/2020;15:11:05;ABEV3;buy;market;10;1000;12;300;0;0
30/12/2020;15:11:05;ABEV3;sell;market;15;1000;12;300;0;0
30/12/2020;15:10:08;MRV3;buy;limit;20;15500;9;200;0;0
31/12/2020;15:09:11;PETR4;sell;limit;30;4516;8;100;0;0
30/12/2020;13:46:53;ABEV3;buy;market;40;45415;10;500;0;0
31/12/2020;13:20:07;TAEE11;buy;limit;10;5465;13;600;0;0
31/12/2020;13:20:07;TAEE11;sell;limit;10;5465;13;600;0;0
""")

df = pd.read_csv(csv, sep=";")

Acresentar a coluna total_price:
df['total_price'] = df['price'] * df['vol']

df:
         DATE      time    pair  type ordertype  price   cost  fee  vol  margin  misc  total_price
0  30/12/2020  15:11:05   ABEV3   buy    market     10   1000   12  300       0     0         3000
1  30/12/2020  15:11:05   ABEV3  sell    market     15   1000   12  300       0     0         4500
2  30/12/2020  15:10:08    MRV3   buy     limit     20  15500    9  200       0     0         4000
3  31/12/2020  15:09:11   PETR4  sell     limit     30   4516    8  100       0     0         3000
4  30/12/2020  13:46:53   ABEV3   buy    market     40  45415   10  500       0     0        20000
5  31/12/2020  13:20:07  TAEE11   buy     limit     10   5465   13  600       0     0         6000
6  31/12/2020  13:20:07  TAEE11  sell     limit     10   5465   13  600       0     0         6000

Podemos começar por agrupar e calcular o preço médio por ativo por type e dia, presumindo que 'activo' é o pair, e fazer um sum() do total_price e vol e calcular a média.
df_tmp = df.groupby(['pair','type', 'DATE'], as_index=False).agg({'total_price': 'sum', 'vol': 'sum'})
df_tmp['mean_price'] = df_tmp['total_price'] / df_tmp['vol']
df_tmp.drop(['vol', 'total_price'], axis=1, inplace=True) # drop das colunas visto que ja nao precisamos

df_tmp:
     pair  type        DATE  mean_price
0   ABEV3   buy  30/12/2020       28.75
1   ABEV3  sell  30/12/2020       15.00
2    MRV3   buy  30/12/2020       20.00
3   PETR4  sell  31/12/2020       30.00
4  TAEE11   buy  31/12/2020       10.00
5  TAEE11  sell  31/12/2020       10.00

Quanto ao segundo tema comentado podemos mudar os valores da coluna type, já que não os vamos usar para neste problema, com "SHORT" ou "LONG" consoante a condição pedida:
df_tmp['type'] = df_tmp['type'].apply(lambda t: "SHORT" if t == 'sell' else 'LONG')

df_tmp:
     pair   type        DATE  mean_price
0   ABEV3   LONG  30/12/2020       28.75
1   ABEV3  SHORT  30/12/2020       15.00
2    MRV3   LONG  30/12/2020       20.00
3   PETR4  SHORT  31/12/2020       30.00
4  TAEE11   LONG  31/12/2020       10.00
5  TAEE11  SHORT  31/12/2020       10.00

E por fim, convertê-las para a lista de listas pedida:
lista = df_tmp.values.tolist()

lista:
[['ABEV3', 'LONG', '30/12/2020', 28.75], ['ABEV3', 'SHORT', '30/12/2020', 15.0], ['MRV3', 'LONG', '30/12/2020', 20.0], ['PETR4', 'SHORT', '31/12/2020', 30.0], ['TAEE11', 'LONG', '31/12/2020', 10.0], ['TAEE11', 'SHORT', '31/12/2020', 10.0]]


text:
Q: Ubuntu samba on virtualbox shared folder premissions I have an ubuntu 16.04.2 server on my virtualbox and want to share the folders from ubuntu to my windows 10 host os. the sharing works fine but here is my problem.
I have one user on ubuntu lets call it "John" that is my login user on ubuntu. I also have a John user on my Windows 10 that is my main login user and it is administrator.
when I share for example /var/www/html on ubuntu, I can access it from windows by typing the ubuntu ip like \\192.168.56.1 in windows explorer and can visit the files and folders in that directory.
The problem is I cant create a file in that directory.
so I changed the ownership of the directory to John user and forced the samba shared folder to that user by adding force user = John in smb.conf on samba.
at this point I can add files and folders to the shared folder from windows BUT
if I create another folder in this directory (like mkdir /var/www/html/NewFolder) from ubuntu John user, I cant write or create a file in that NewFolder from windows, but I can do so in its parent (/var/www/html) directory that the user is its owner.
so short version of My question is:
How can add full permission to a samba shared folder for its current AND future files and folders to a user or user group or all users that access it on the network.
there is a apache server on this ubuntu that should access the files and folders with full permissions like 777 or 755 too. so I can't do this just for a single user I should be able to do it for any user i want.
so thats it! please help. I am a totally new user to ubuntu and want to learn this kind of things.
any helpful advice or solutions would be highly appreciated.

A: The strategy I use to deal with this, is to use SetGID on the shared directory, so that all new subdirectories will have the same owner-group as the parent.

*

*Create a group that both John and your service user (wwwdata?) belong to.

*Change the owner-group on the shared folder and all subs to your new group

*Set your permissions to 277X on the folder and all subs, where X is the current "Other" permission value.
From then on, you want your access to be evaluated by the Group permission value, not the Owner (which is why we set it to 7, just like the owner). Newly created folders will automatically take on the owner-group of their parent, so you will be able to add files or additional sub-directories.


text:
Q: Chrome - assign hotkey to enter text into current text field I want a specific text to be entered into the currently focused field in the web page. This is mainly for templates etc. For example, Ctrl-H to enter "if blah then { ... } else { ... }". Is this possible ? Or one has to develop a new chrome extension ?

A: AutohotKey can do this for you.
SetTitleMatchMode, RegEx

#IfWinActive, - Google Chrome$

!V:: SendRaw "if blah then {...} else {...}"

return

Here Alt+V will enter the text you want to in any text filed of Chrome.
You have to assign shortcut for per template as you want, and its drawback is this that you have to run every script to use it anytime which need the RAM.


text:
Q: Created date of onenote page is not converted to local date by microsoft graph api I am a little confused about the created date meta when creating onenote page by microsoft graph api. According to the doc, the date has to be a ISO 8601 standard time stamp, I first copied the date (2013-06-11T06:30:00-08:00) in the example to my code, and my onenote shows the creation date is Tuesday, June 11, 2013 6:30 AM, which is not what I expected, because the timezone of my city is +8:00, the date should be Tuesday, June 11, 2013 22:30 PM.
I tried to change date to 2013-06-11T06:30:00-10:00, but my onenote still shows Tuesday, June 11, 2013 6:30 AM, it seems the timezone offset doesn't work.
The doc also mentions that we can use a timezone offset without date and time, so I tried +00:00, but it's also not converted to local date. At last, I tried +08:00, and it works fine.
Is the timezone offset ignored by graph api? Can I use an utc date in server side or do I have to get timezone in client side first?
Here is my function to create a page:
def create_page(section_id):
    page = request.json
    created_at = '2013-06-11T06:30:00-08:00'
    content = '''
        <!DOCTYPE html>
        <html>
            <head>
                <title>{0}</title>
                <meta name="created" content="{1}" />
            </head>
            <body>
                {2}
            </body>
        </html>
    '''.format(page['title'], created_at, MARKDOWN_FILE_OBJECT_HTML)
    files = {
        'Presentation': ('', io.StringIO(content), 'text/html'),
        'markdown': ('markdown.md', io.StringIO(''), 'text/markdown')
    }

    oauth_client = oauth.microsoft_graph
    response = oauth_client.post(
        'me/onenote/sections/{0}/pages'.format(section_id), files=files).json()

    return jsonify(response)

And the request body:
--0971a31c3b8a4c79985d91774720e44b
Content-Disposition: form-data; name="Presentation"; filename=""
Content-Type: text/html
<!DOCTYPE html>
    <html>
        <head>
            <title>Untitled Page</title>
            <meta name="created" content="2013-06-11T06:30:00-08:00" />
        </head>
        <body>
            <object data-id="markdown-file" data-attachment="markdown.md" data="name:markdown" type="text/markdown" />
        </body>
    </html>
--0971a31c3b8a4c79985d91774720e44b
Content-Disposition: form-data; name="markdown"; filename="markdown.md"
Content-Type: text/markdown
--0971a31c3b8a4c79985d91774720e44b--


text:
Q: Jquery Zebra list odd even display after filtering data. I have a problem displaying "zebra" list after filtering results.
I have a zebra list which display perfect here is the code:
$('ul li:odd').addClass('zebra_odd');
$('ul li:even').addClass('zebra_even');

The problem comes when I filter that list an input like this:
  $('input').keyup(function() {
    var textboxVal = $(this).val().toLowerCase();
    $('ul li').each(function() {
    var listVal = $(this).text().toLowerCase();
      if(listVal.indexOf(textboxVal) >= 0) {
        $(this).show();
      } else {
        $(this).hide();
      }

i.e. on the list I have this values: a1, b1, a2, b2, a3, b3. The list display the values on zebra rows perfect, but if I filter the data i.e. "a" it will show me a1, a2, a3 all in white background, it kept the old odd, even values. Thanks

A: You can write a function to Update odd,even classes after filtering the elements like this
function setOddEven() {
    $('li:visible:odd').removeClass('odd even').addClass('odd');
    $('li:visible:even').removeClass('odd even').addClass('even');
}
$(function() {
    setOddEven();
    $('input').keyup(function() {
        var textboxVal = $(this).val().toLowerCase();
        $('ul li').each(function() {
            $this = $(this); // cache the object for better performance
            var listVal = $this.text().toLowerCase();
            if (listVal.indexOf(textboxVal) >= 0) {
                $this.show();
            } else {
                $this.hide();
            }
        });
        setOddEven();
    });
});

Working Fiddle
Dont forget the :visible selector, or it will take hidden elements into account and hence wont work properly.


text:
Q: Space after attribute in html5 I have heard before that for xhtml, there ought to be a space between any attributes and the closing bracket of a tag. E.g.  instead of . Is this true for html5 (and for that matter was it true for xhtml)?

A: In this case it is not a self-closing tag and both forms are equivalent, valid syntax in both HTML (at least 4+) and XML (including XHTML). The similar question linked in the comments is about /> constructs, which have historically been "icky".
If a resource said "ought to be", then they are merely talking about a convention as XML (and thus XHTML) doesn't care. Now, self-closing tags can be a different can of worms (that is mostly "fixed" with HTML5 rules), but they are unrelated to this particular syntax construct.

A: It doesn't really make a difference. Pretty much all browsers will read it correctly. I can't think of any that would read it incorrectly.