text:
Q: Python 3 Tkinter - How to Enforce a default format I am writing my first Python tkinter application.
The Application itself is an xml editor. It will look for 2 elements, and update the text value of the the element. The code below is proof-of-concept, and does not actually update anything yet.
#!/usr/bin/env python

from tkinter import *
from tkinter import messagebox
import xml.etree.ElementTree as ET

class NameDropper(Frame):

    def __init__(self,fp=None):
        self.fp = fp
        #Create the Mainframe
        root = Tk()
        root.config(bg="red")
        root.title("NameDropper")
        mainframe = Frame(root, colormap="new")
        #mainframe.config(width=200,height=200,bg="green")

        # place and configure
        mainframe.grid(column=0,row=0,sticky=(N,W,E,S)) #makes Frame appear on screen
        #mainframe.columnconfigure(0, weight=1)
        #mainframe.rowconfigure(0, weight=1)

        self.mainframe = mainframe
        self.createVariables()
        self.createWidgets()
        self.gridWidgets()
        #self.mainframe.pack(fill=BOTH, expand=YES)

    def createVariables(self):
        self.start = StringVar()
        self.duration = StringVar()

    def createWidgets(self):
        self.mainframe.startLabel = Label(self.mainframe,text="Start",font=("Helvetica", 16))
        self.mainframe.startEntry = Entry(self.mainframe,textvariable=self.start,font=("Helvetica", 16))
        # self.mainframe.startLabel.pack(side="left", fill=None, expand=False)
        self.mainframe.durLabel = Label(self.mainframe,text="Duration",font=("Helvetica", 16))
        # self.mainframe.durLabel.pack(side="left", fill=None, expand=False)
        self.mainframe.durEntry =  Entry(self.mainframe,textvariable=self.duration,font=("Helvetica", 16))
        self.mainframe.saveButton = Button(self.mainframe, text='Save', command=self.save)
        self.mainframe.quitButton = Button(self.mainframe,text='Quit',command=self.mainframe.quit)

    def gridWidgets(self):
        self.mainframe.startLabel.grid(column=0,row=0,sticky=(N,W))
        # self.mainframe.startLabel.config(bg="red")
        self.mainframe.startEntry.grid(column=1,row=0,sticky=(N,W))
        # self.mainframe.startEntry.config(bg="black")
        self.mainframe.durLabel.grid(column=0,row=1,sticky=(N,W))
        self.mainframe.durEntry.grid(column=1,row=1,sticky=(N,W))
        self.mainframe.saveButton.grid(column=0,row=3,sticky=SW)
        self.mainframe.quitButton.grid(column=2,row=3,sticky=SE)

    def save(self):
        root = ET.parse(fp).getroot()
        generic_anc_enable = root.findall('GenericANCEnable')
        for item in generic_anc_enable:
            start_element = item.find('StartTimecode')
            duration_element = item.find('DurationTimecode')
            start_element.text = str(self.mainframe.startEntry.get())
            duration_element.text = str(self.mainframe.durEntry.get())

            messagebox.showwarning(start_element.text)

if __name__ == '__main__' :
    fp = "C:\\Users\\206420055\\Documents\\VancInsertionLabelTdyShwCrwlTC.xml"
    app = NameDropper(fp)

    app.mainframe.mainloop()

The question I have, is there any way to mask the Entry Fields so that they automatically and consistently abide by a certain format?

The Goal would be to have both labels Automatically follow the format xx:yy:zz;nn
I have previously built this application in Java a year ago, but new requirements cause me to get off Java.
The original question from Last August about the Java version is here
Java - Enforce TextField Format - UX - 00:00:00;00
I havent yet been able to find any documentation on enforcing the format

A: There is nothing built-in to the entry widget to do that. All of the basic building blocks are available to do it, but you'll have to do most of the work yourself.
A simple solution is to use four entry widgets (for xx, yy, zz and nn) with three labels (for the colons). To get fancier you can set up custom bindings to automatically insert the colons as the user types.
You can also use the entry widget validation feature to simply reject any characters that don't result in a string in the proper format.

A: In Flask-wtforms, there is a validation idea that would be applicable here; which is to use regex to check that the input matches certain criteria. If the inputed data doesn't match a given format of your choosing, simply reject the submition with a helpful message to the user.
import re

start_time = re.compile(r'^(([01]\d|2[0-3]):([0-5]\d)|24:00)$')
duration = re.compile('[0-9]{2}:[0-9]{2}:[0-9]{2};[0-5]{1}[0-9]{1}')

if start_time.match(user_input_var):
    add_well_formatted_data()
else:
    print('please format the data accordingly:  xx,yy,zz,nn')

if duration.match(user_input_var):
    add_well_formatted_data()
else:
    print('please format the data accordingly:  xx,yy,zz,nn')

Alternatively, you shouldn't need regex for this, as there are format validators in the datetime class.


text:
Q: Conemu - how to add a command "npm start" when tab opens? I have following bash startup script in Conemu console:

-new_console:d:C:\git\AgentReporting\src\AgentReporting.Client\agent-reporting-client set "PATH=%ConEmuDir%..\Git\usr\bin;%PATH%" & %ConEmuDir%..\Git\git-cmd.exe --no-cd --command=%ConEmuBaseDirShort%\conemu-msys2-64.exe /usr/bin/bash.exe -l -i -new_console:s20V

How to add "npm start" command to this?

A: Ok, I managed to do that... But hell, it was hard to find any examples on the Internet.

-new_console:d:C:\git\AgentReporting\src\AgentReporting.Client\agent-reporting-client set "PATH=%ConEmuDir%..\Git\usr\bin;%PATH%" & %ConEmuDir%..\Git\git-cmd.exe --no-cd --command=%ConEmuBaseDirShort%\conemu-msys2-64.exe /usr/bin/bash.exe -l -i -new_console:s20Vt:"Ng Serve" -c "npm start"

Above script runs the bash console.
-new_console:d:C:\git\AgentReporting\src\AgentReporting.Client\agent-reporting-client - starting directory
s20Vt - it will open only in 20% of the window size, vertically, on the bottom.
t:"Ng Serve" - with the tab name "Ng Serve"
-c "npm start" - runs the command "npm start"

redpajama_set_name: RedPajamaStackExchange


text:
Q: Setting TreeView.DataContext doesn't refresh the tree I have a List that I've bound to a TreeView. Setting TreeView.DataContext works - everything displays correctly. I then change the list (add an item to it) and set TreeView.DataContext again (to the same value) but the tree does not refresh with the new items. How do I get the treeview to refresh?
This is basically my code:
public class xItemCollection : ObservableCollection<xItem>
{
}

public class xItem : INotifyPropertyChanged
{
    xItemCollection _Items;
    string m_Text;

    public xItem()
    {
        _Items = new xItemCollection();
    }

    public xItemCollection Items {get{return _Items;}}
    public string Text {get{return m_Text;} set{m_Text=value;}}
}

class MyProgram
{
    xItem m_RootItem;

    void UpdateTree()
    {
        this.RootItem = new xItem();
        treeView.DataContext = this;
    }

    public xItem RootItem
    {
        get { return m_RootItem;}
        set { m_RootItem = value;}
    }
}

The xaml is:
<TreeView Name="Tree" ItemsSource="{Binding Path=RootItem.Items}" >

<TreeView.ItemTemplate>
    <HierarchicalDataTemplate ItemsSource="{Binding Items}">
        <StackPanel Orientation="Horizontal">
            <TextBlock Text="{Binding Text}" />
        </StackPanel>
    </HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>

Adding items to the list works until the tree is rendered for the first time. After it is rendered, adding/removing items does not refresh the tree.

A: if you assign the same object to a datacontext, I guess it will not fire the datacontext as being changed.
you have some options here:

*

*assign null to the datacontext and reassign your list, or call any other "refreshing command" that gets your datacontext refreshed, which is actually a pretty bad idea as your whole tree has to be regenerated.

*use an ObservableCollection as your list. This automatically triggers a CollectionChanged event if you add an item, that WPF uses to update only the ChangedParts of the list.
I would definatly recommend using the second approach!

A: I needed to implement INotifyPropertyChanged and then fire PropertyChanged when RootItem changed. My code was creating a new list of items then assigning the complete list to RootItem. Without PropertyChanged the TreeView never knew that RootItem had changed.


text:
Q: Long Click event firing on the Button Click in Android I have heard that we can create the click event of the Button by holding it for a few moments in Android.
I want to use that functionality in my application.
Can anyone please tell me how to do that?
Thanks,
david

A: Look at View.OnLongClickListener.
public class MyActivity extends Activity {
   protected void onCreate(Bundle icicle) {
     super.onCreate(icicle);

     setContentView(R.layout.content_layout_id);

     final Button button = (Button) findViewById(R.id.button_id);
     button.setOnLongClickListener(new View.OnLongClickListener() {
         public boolean onLongClick(View v) {
             // Perform action on click
             return true;
         }
     });
   }
}


text:
Q: Mercurial - How to disable push I am trying to find if there is an easy way to make a mercurial repository read-only. The user should be able to clone, but no pushes should be allowed. I need to do this for all my repositories which is more than 100.

A: You can do this like this in .hg/hgrc:
[hooks]
prechangegroup = false

A: This depends on how you're publishing your repositories but here's a few things you can try, depending on this:

*

*If you're publishing your repositories on network shares or mounted volumes, simply set access rights on the mercurial folder in such a way that they only have read access to the folder and its files

*If you're publishing your repositories using any of the available http server options, like hg serve or any of the 3rd party websites you can install, make sure you set up users that doesn't have write/push access

*If you're publishing your repositories using any of the online cloud-based solutions, like bitbucket, kiln, etc. then simply don't hand out push access to anyone that shouldn't have it, again you can set up users and access specifically

A: Make them available over http only (hg serve, kallithea,...) and don't give them login credentials.

A: You have a lot of repos, their URLs are known and have already been used to clone them, and you just decided you want to turn off push access to them. Is this about right?
If the repos are accessed over ssh, you can do it by simply reassigning ownership of the repo files to a new account, with free read access but no write access by other users. The file locations stay the same, the current access credentials remain valid, but pushing to the repos is no longer possible.
If you're on a unix system, you can probably do everything in bash with a for loop  and chown -R. If you're not... good luck. Give us more information about your configuration, and one of the approaches proposed in the answers will fit best.

A: For disabling push over http or https, you can try one of the following in your hgrc file. Note, this doesn't disable pushing over the filesystem.
allow_push
Whether to allow pushing to the repository. If empty or not set, push is not allowed. If the special value * is used, any remote user can push, including unauthenticated users. Otherwise, the remote user must have been authenticated, and the authenticated user name must be present in this list (separated by whitespace or ","). The contents of the allow_push list are examined after the deny_push list.
[web]
allow_push =

deny_push
Whether to deny pushing to the repository. If empty or not set, push is not denied. If the special value *, all remote users are denied push. Otherwise, unauthenticated users are all denied, and any authenticated user name present in this list (separated by whitespace or ",") is also denied. The contents of the deny_push list are examined before the allow_push list.
[web]
deny_push = *


text:
Q: how to make '=' overloading work on the other side of the '=' I have made this little c++ program as part of my homework. I"m not allowed to change the main.
I managed  to make
board1[{1, 1}] = 'X';

but now I"m not able to make
char c = board1[{1, 2}];

I understand it is not working because c is char type and I"m returning "CellValue" to it. But I cann't understand how to make '=' to work the other way and make it return the value as char when i want it to be on the right side of the '='.
the whole code:

#include <iostream>
using namespace std;

class CellValue {
public:
    char value;

    void operator=(char charToAdd) {
        if (charToAdd == 'X' || charToAdd == 'O' || charToAdd == '.') {
            value = charToAdd;;
        }
        else {
            cout << "ERROR!" << endl;
        }
    }

    friend ostream& operator<<(ostream& os, const CellValue &CellToPrint) {       //prints matrix
        cout << CellToPrint.value << endl;
        os << CellToPrint.value;
        os << endl;
        return os;
    }
};

class Cell
{
public:
    int row; int col;
};

class Board {
private:
    int size;
    CellValue** matrix = nullptr;

public:

    Board(int sizeToSet) {                       //constructor with size
        size = sizeToSet;

        matrix = new CellValue*[size];                 //creates a matrix
        for (int i = 0; i < size; i++)
            matrix[i] = new CellValue[size];

        for (int i = 0; i < size; i++) {          //makes every cell in matix '.'
            for (int j = 0; j < size; j++) {
                matrix[i][j].value = '.';
            }
        }
    }

    ~Board() {                                    //destructor
        for (int i = 0; i < size; i++)
            delete[] matrix[i];
        delete[] matrix;
    }

    CellValue& operator[](const Cell& cellToChange) {
        if (cellToChange.row < size && cellToChange.col < size) {
            return { matrix[cellToChange.row][cellToChange.col] };
        }
        else
            cout << "ERROR!" << endl;
    }

};

int main() {
    Board board1{ 4 };  // Initializes a 4x4 board
    board1[{1, 1}] = 'X';
    board1[{1, 2}] = 't';
    cout << board1[{1, 1}] << endl;
    cout << board1[{1, 2}] << endl;
    char c = board1[{1, 2}];

    return 0;
}

I"m just starting to program on c++ so I"m now allowed to use something too smart. I would like to get some help from you. Thanks!

A: If an instance of your class is the right-hand side of an assignment, and the left-hand is not of the same type, then a user-defined conversion must be provided in order for this to work.
There are two ways this can work with assignment. The first is that the left-hand object can provide an assignment operator or conversion constructor that takes an object of the type of the right-hand side. This is what you have done with CellValue::operator=(), but cannot work when the LHS is char, as you cannot modify built-in types.
The second way is that the right-hand object provided a conversion operator to the type of the left-hand side (or something else that can be assigned to it). This is done by adding operator char() to your CellValue class:
class CellValue{
public:
  operator char() const{
    return value;
  }
// rest as before
};

This can be a const member function because it only reads the data.


text:
Q: How to use S3 with signature V2 In Laravel I have a project in Laravel 7 and I want to use a compatible storage S3 who accept only version 2 of signature. I tried to install flysystem/flysystem-aws-s3-v2 but there are more conflict with Symfony and Guzzle. Is there a method for use flysystem/flysystem-aws-s3-v3 with signature v2?
Thanks


text:
Q: Package Pathing Errors in Python So I am working on implementing a file structure to my Python and am having an error with doing imports.  The file structure looks something like this:
Dirs(Folder)
   ╘ run.py
     Vers(Folder)
        ╘ __init__.py
          1_1(Folder)
             ╘ Main.py
               secondary.py
               __init__.py
          1_2(Folder)
             ╘ Main.py
               secondary.py
               __init__.py

This is the contents of run.py
import importlib
print("This is the main module")
A = importlib.import_module(str("Vers.1_1.Main"))
A.start()
B = importlib.import_module(str("Vers.1_2.Main"))
B.start()

Each Main.py and secondary.py contain code that is the same except for the version number in the print statements, which is changed depending on the version number of the folder they are in.
Main.py

import secondary
class start():
    def __init__(self):
        print("This is version 1.2 main")
        secondary.start()

secondary.py

class start():
    def __init__(self):
        print("This is version 1.1 secondary")

This is the output I get when I execute run.py
This is the main module
Traceback (most recent call last):
  File "Python\Python36-32\lib\importlib\__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 978, in _gcd_import
  File "<frozen importlib._bootstrap>", line 961, in _find_and_load
  File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 655, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 678, in exec_module
  File "<frozen importlib._bootstrap>", line 205, in _call_with_frames_removed
  File "Dirs\Vers\1_1\Main.py", line 1, in <module>
import secondary
ModuleNotFoundError: No module named 'secondary'

So from my understanding, run.py is able to successfully find and attempt to import Main.py from the 1_1 Folder.  However, when executing the Main.py file, it is unable to see that secondary.py is in the same directory to import it.  I've tried looking for how to fix this problem, but I really don't know what my issue is.  Is how I am attempting to set up packages wrong?  If so what do I need to change in order to make it work properly?

A: Short answer: Use
from . import secondary

Longer version: It looks like you assume Python 2 relative import semantics, when this is Python 3 with absolute import semantics. Have a look e.g. here for a more detailed explanation.
If you do
import secondary

this is an absolute import, and thus is not resolved relative to the current package, but rather from sys.path.
When you execute run.py as a Python script (not as a module with -m), the directory the script resides in gets added to sys.path automatically, which is why importing Vers.1_1.Main works, but import secondary does not.

A: After the import your code is executing under Dirs, where there is no secondary module to import
Change
import secondary

in Main.py
to
import Vers.1_1.secondary

and to
import Vers.1_2.secondary

in the other Main.py


text:
Q: Checking PoDSecurityPolicy status in a GKE Cluster How to check if PoDSecurityPolicy is enabled on a GKE cluster  or not ? Using gcloud container clusters describe <clustername>, I could not find anything.
If I enable it on a cluster where this plugin is already enabled, it displays that the plugin has been enabled so there is no way actually to know that if plugin is already enabled on a cluster
 $ gcloud beta container clusters update mycluster --enable-pod-security-policy --zone us-east1-c
 Updating podsecpolicy-poc...done.
 Updated [https://container.googleapis.com/v1beta1/projects/<project>/zones/us-east1-c/clusters/mycluster].

A: Since PodSecurityPolicy is still a beta feature in GKE, it can only be accessed by GKE beta API. To check if PodSecurityPolicy controller is enabled on your GKE cluster, run:
$ gcloud beta container clusters describe <cluster-name> --zone=<zone> --format json | jq '.podSecurityPolicyConfig'

Sample command with its result:
$ gcloud beta container clusters describe my-gke-cluster --zone=europe-west4-c --format json | jq '.podSecurityPolicyConfig'
{
  "enabled": true
}

Update:
When PodSecurityPolicy is not enabled on GKE cluster, the above query returns:
null

as there is no podSecurityPolicyConfig section available. You can also serch for it with grep. If PodSecurityPolicy is enabled, the result will look as follows:
$ gcloud beta container clusters describe my-gke-cluster --zone=europe-west4-c | grep -iA 1 podsecuritypolicy
podSecurityPolicyConfig:
  enabled: true

If it is not, you won't find this section at all.


text:
Q: Novel where a genius child secretly makes clones of himself I'm trying to find the name of a novel that was (what I'll call) light horror sci-fi. It was probably published in the early 90s.
As best as I can remember, the plot goes something like:

*

*a child is genetically engineered (prenatally) to be smart

*when he's very young, his intelligence tests off the charts

*as he grows up, his intelligence goes back down to normal

*a bunch of clones are found and (plot twist) it turns out he was faking not being a genius and he's been incubating clones for years

I think there was something malicious about the boy... like maybe he was plotting a new world order.

A: This is probably Robin Cook's Mutation.

Victor Frank, and his wife Marsha, are unable to have a second child due to Marsha's infertility. They turn to surrogacy as an alternate method of conception. Victor, an obstetrician-gynaecologist and owner of the biochemical company Chimera Inc., injects the egg implanted in his wife with an agent called Nerve Growth Factor (NGF) into chromosome six, which causes the baby to grow more neurons than usual, as a result making them super intelligent. Their son, VJ, is born a genius. He is able to talk in six months and read in thirteen.
Several years later, VJ's brother, David, and nanny, Janice, both die of an unexplainable rare form of liver cancer. At about three, VJ experiences a drop in intelligence, leading Victor to think his experiment is a failure...

....

One year later, a mother brings in her teenage daughter and her daughter's child to her office. Marsha surmises from the fact that the 18-month child is reading a medical journal, something VJ did, and his ice blue eyes, a trait VJ had, that this child is the "failed" zygote. She decides she will have to go through another VJ-like experience, "with Joe's help and end forever the nightmare her husband had begun".


text:
Q: How to add custom hooks to controllers in ASP.NET MVC2 I've just started a new project in ASP.net 4.0 with MVC 2.
What I need to be able to do is have a custom hook at the start and end of each action of the controller.
e.g.
public void Index() {
    *** call to the start custom hook to externalfile.cs (is empty so does nothing)

    ViewData["welcomeMessage"] = "Hello World";

    *** call to the end custom hook to externalfile.cs (changes "Hello World!" to "Hi World")

    return View();
}

The View then see welcomeMessage as "Hi World" after being changed in the custom hook.
The custom hook would need to be in an external file and not change the "core" compiled code. This causes a problem as with my limited knowledge ASP.net MVC has to be compiled.
Does anyone have any advice on how this can be achieved?
Thanks

A: You create your own class based on the ActionFilterAttribute. It has the following hooks.

*

*OnActionExecuted

*OnActionExecuting

*OnResultExecuted

*OnResultExecuting

For example,
public class MyFilterAttribute : ActionFilterAttribute
{
    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        var controller = filterContext.Controller;

        controller.ViewData["welcomeMessage"] = "Hi World!";
        controller.TempData["Access_My_TempData"] = "Some Value";

        base.OnActionExecuted(filterContext);
    }
}

You can also check what type of [Action] the Action method is performing.
if ((filterContext.Result is RedirectResult) || (filterContext.Result is RedirectToRouteResult))
{
    // do something only if we are redirecting to a different action
}
else if (filterContext.Result is ViewResult)
{
    // this is just a normal View action
}

Oh I forgot to show how to use the attribute.
You just decorate on top of your Action Method.
[MyFilterAttribute]
public ActionResult MyActionMethod()
{
    return View();
}

A: An event based plugin system where you can dynamically call script code. So creating (for example) iron python scripts that get called when events are raised by the controller.
Doesn't have to be iron python, but that would make the most sense that I can see.

A: How about override OnActionExecuting/OnActionExecuted and use MEF(Import,Export other assembly code)?


text:
Q: Groovy - group and sort list My orginal list is:
[[string: firstString, id: 2],
[string: secondString, id: 1],
[string: secondString, id: 3],
[string: firstString, id: 1],
[string: firstString, id: 3],
[string: secondString, id: 2]]

I want to group it by string and sort it by id just like this:
[[string: firstString, id: 1],
[string: firstString, id: 2],
[string: firstString, id: 3],
[string: secondString, id: 1],
[string: secondString, id: 2],
[string: secondString, id: 3]]

A: def firstString = 'first'

def secondString = 'second'

def source =
[[string: firstString, id: 2],
[string: secondString, id: 1],
[string: secondString, id: 3],
[string: firstString, id: 1],
[string: firstString, id: 3],
[string: secondString, id: 2]]

Your stated expected result:
def expected =
[[string: firstString, id: 1],
[string: firstString, id: 2],
[string: firstString, id: 3],
[string: secondString, id: 1],
[string: secondString, id: 2],
[string: secondString, id: 3]]

def result = source.sort { [it.string, it.id] }
assert result == expected

IDs reversly ordered:
def expected =
[[string: firstString, id: 3],
[string: firstString, id: 2],
[string: firstString, id: 1],
[string: secondString, id: 3],
[string: secondString, id: 2],
[string: secondString, id: 1]]

def result = source.sort { [it.string, -it.id] }
assert result == expected

Really grouped, not only sorted by string:
def expected =
[(firstString):
  [[string: firstString, id: 1],
  [string: firstString, id: 2],
  [string: firstString, id: 3]],
(secondString):
  [[string: secondString, id: 1],
  [string: secondString, id: 2],
  [string: secondString, id: 3]]]

def result = source.groupBy { it.string }
result.each { it.value.sort { it.id } }
assert result == expected

Really grouped, not only sorted by string, IDs reversely ordered:
def expected =
[(firstString):
  [[string: firstString, id: 3],
  [string: firstString, id: 2],
  [string: firstString, id: 1]],
(secondString):
  [[string: secondString, id: 3],
  [string: secondString, id: 2],
  [string: secondString, id: 1]]]

def result = source.groupBy { it.string }
result.each { it.value = it.value.sort { it.id }.reverse() }
assert result == expected

Really grouped and IDs flattened out:
def expected =
[(firstString): [1, 2, 3],
(secondString): [1, 2, 3]]

def result = source.groupBy { it.string }
result.each { it.value = it.value.collect { it.id }.sort() }
assert result == expected

Really grouped and IDs flattened out, IDs reversely ordered:
def expected =
[(firstString): [3, 2, 1],
(secondString): [3, 2, 1]]

def result = source.groupBy { it.string }
result.each { it.value = it.value.collect { it.id }.sort().reverse() }
assert result == expected


text:
Q: How do we modify docker0 mtu in my k8s cluster? I want to modify docker0 mtu to 1400 byifconfig docker0 mtu 1400 and it is successed.
but after a while, the mtu goes back to 1500. please help, how to modify docker0 in my k8s cluster.

A: MTU in Kubernetes can be configured from the CNI plugin.
Here is the documentation for Calico https://docs.projectcalico.org/v3.5/usage/configuration/mtu


text:
Q: congruent number problem I am studying the congruent number problem
and I heard that there is a paper by Kazuma Morita
which claims to solve this problem from my colleague.
I saw the paper on his homepage but it is very short
and I cannot belive it is true because it is too short.
While I try to find his mistakes, I don't have the knowledge
about the Hodge-Tate weight (p,q). Although there is an explanation
on the Hodge-Tate weight (p,q), he writes that it is based on the
Japanese article by T.Yoshida. I know the notion about Hodge-Tate
weight p but not Hodge-Tate weight(p,q) well. So, let me know the
litaratures in English on Hodge-Tate weight (p,q).

A: The fatal error in the reasoning in the paper "L-functions and rational points on a CM elliptic curve via the classical number theory" at the top of the list of papers at
http://kazuma-morita.jimdo.com
occurs near the top of page 3 (when "proving" a statement near the bottom of page 2 that we'll see is false); it comes down to an elementary but unfixable blunder in $p$-adic Hodge theory.
The phrase "weight $(a, b)$" refers to the fact that for a quadratic field $K$ and rational prime $p$ split in $K$, a continuous Galois character $G_K \rightarrow \mathbf{Q}_p^{\times}$ arising from algebraic geometry over $K$ (e.g., inside the $p$-adic Tate module of an abelian variety over $K$, or in the geometric $p$-adic etale cohomology of a smooth projective $K$-scheme) has two Hodge--Tate weights: weight $a$ at one place and weight $b$ at the other (when restricting such a global character to the decomposition groups at the two places of $K$ over $p$).  So this indexing is a notion which comes up in the global theory, not the purely local theory.
To explain the context for the error (including what I guess is the author's motivating idea), say $E$ is an elliptic curve over $\mathbf{Q}$ such that for an imaginary quadratic field $K$ we have ${\rm{End}}^0(E_K) = K$ (e.g., the key cases of interest $E_n: y^2 = x^3 - n^2 x$ with $K = \mathbf{Q}(\sqrt{-n})$ for a non-square positive integers $n$).
By the CM theory of elliptic curves, upon choosing an inclusion $\iota:K \rightarrow \mathbf{C}$ ("CM type") we have $L(E/K,s) = L(s, \chi)L(s,\overline{\chi})$ for the algebraic Hecke character $\chi: \mathbf{A}_K^{\times} \rightarrow K^{\times}$ attached to $(E, \iota)$; this $\chi$ is unramified at all good places for $E$ over $K$.
Suppose $p$ is an ordinary good prime for $E$, so $p$ splits in $K$; i.e., $K$ embeds in $\mathbf{Q}_p$ and precomposing with complex conjugation on $K$ swaps the two such embeddings. Let $j:K \rightarrow \mathbf{Q}_p$ be one such embedding (so $x \mapsto j(\overline{x})$ is the other). For a good place $v$ away from $p$, the (unramified) action of ${\rm{Frob}}_v$ on $V_p(E)$ has eigenvalues in $\mathbf{Q}_p$ given by $j(\chi(\pi_v))$ and $j(\overline{\chi(\pi_v)})$ for any local uniformizer $\pi_v$ at $v$ (using suitable class field theory conventions).
The author's idea seems to be to recover the $L$-functions attached to $\chi$ and $\overline{\chi}$ with a well-known (and quite simple) $p$-adic construction in the case of ordinary $p$, and then (the big "idea") prove a strong $p$-adic Hodge theory property of this $p$-adic construction from which striking consequences follow for those $L$-functions (and hence for $L(E/K,s)$). But the proof of the strong $p$-adic Hodge theory property is flawed, and more specifically the asserted property is false.

Here is the well-known $p$-adic construction. Consider the $p$-adic representation $V_p(E)$ of $G_K$ for any prime $p$. This $V_p(E)$ is a free module of rank 1 over $K_p := K \otimes_{\mathbf{Q}} \mathbf{Q}_p$ with $G_K$ acting $K_p$-linearly, so if $p$ is ordinary then the $\mathbf{Q}_p$-algebra decomposition $K_p = \mathbf{Q}_p \times \mathbf{Q}_p$ correspondingly decomposes the $K_p[G_K]$-module $V_p(E)$ as a direct sum of two $G_K$-stable $\mathbf{Q}_p$-lines $V^{(1)}$ and $V^{(2)}$ on which the $G_K$-action is through respective continuous characters $\sigma^{(1)}, \sigma^{(2)}: G_K^{\rm{ab}} \rightrightarrows \mathbf{Q}_p^{\times}$. Up to here there is nothing to intrinsically distinguish these two characters from each other (apart from that each is attached to one of the two factor fields of the $\mathbf{Q}_p$-algebra $K_p$, so each character is attached to one of the places of $K$ over $p$ based on the factor field of $K_p$ "corresponding" to each character).
The author claims near the start of 2.1 that there is an intrinsic way (in terms of $p$-adic Hodge theory) to distinguish $\sigma^{(1)}$ from $\sigma^{(2)}$ in a manner that very different from the elementary bijection defined above between this set of two characters and the set of two places of $K$ over $p$.  This proposed alternative way to
break the symmetry will turn out to not be compatible with the effect on this pair of characters by the action of complex conjugation on $G_K^{\rm{ab}}$ (or equivalently on $\mathbf{A}_K^{\times}/K^{\times}$).  So let's first see why that is really bad news for the author (and then see what the author's incorrect proposed way is), by showing that as characters on $\mathbf{A}_K^{\times}/K^{\times}$ (via global class field theory) these $\sigma^{(i)}$'s are swapped by the effect of complex conjugation (how could it be otherwise?).
Since the effect of complex conjugation on the $\mathbf{Q}_p$-algebra $K_p$ swaps its two factor fields, and the $\sigma^{(i)}$ are defined intrinsically in terms of the $K_p[G_K]$-module $V_p(E)$, this swapping claim amounts to showing that  the abelian character $\psi_p:\mathbf{A}_K^{\times}/K^{\times} \rightarrow K_p^{\times}$ encoding the $K_p$-linear $G_K$-action on $V_p(E)$ is equivariant for the effect of complex conjugation. Since $\psi_p$ is the "$p$-adic avatar" of $\chi$ (concretely, at good places $v$ of $K$ the local restriction of $\psi_p$ is unramified and carries a local uniformizer to the element of $K^{\times}$ giving the effect of the Frobenius endomorphism of the reduction of $E$ at $v$), by regarding the complex conjugation isomorphism $K \simeq K$ as an inclusion of number fields (i.e., overlook that the source and target fields happen to be the same) this is just expressing the "general nonsense" fact that the formation of the algebraic Hecke character attached to a CM abelian variety equipped with CM type on the CM field is compatible with ground field extension.

OK, now finally we come to the error. Consider $p$ that is good ordinary for $E$ (hence split in $K$), with places $\{v, v'\}$ over it in $K$. It is an elementary fact via the connected-etale sequence for $p$-divisible groups (or even just finite flat group schemes) over $O_{K_v}$ that among the two local characters
$\sigma^{(1)}_v, \sigma^{(2)}_v: G_{K_v} \rightrightarrows \mathbf{Q}_p^{\times}$ exactly one is unramified, so the other is $p$-adic cyclotimic times unramified; the same goes for $v'$.  Then one is led to the question: is the unique character among $\{\sigma^{(1)}, \sigma^{(2)}\}$ that is unramified at the place $v$ over $p$ also the unique one that is unramified at the other place $v'$ over $p$?  This is exactly what the author is asserting at the start of 2.1 (i.e., that one of these has "Hodge-Tate weights" $(0,0)$ and the other has weights $(1,1)$).  But it is wrong!
Indeed, we saw above the combined effect of complex conjugations on $G_K^{\rm{ab}}$ and $K_p$ swap $\sigma^{(1)}$ and $\sigma^{(2)}$, and clearly also swap the decomposition groups at $v$ and $v'$, so for whichever one is unramified at $v$ we see that the other must be unramified at $v'$. In other words, indexing Hodge-Tate weights by the two embeddings of $K$ into $\mathbf{Q}_p$, one of these $\sigma^{(i)}$'s has weights $(0,1)$ and the other has weights $(1,0)$.
(Not that it matters, but this labeling of the HT-weights as $(0,1)$ and $(1,0)$ to break the symmetry can be made more explicit: for a given $\sigma^{(i)}$ the place over $p$ at which it is unramified -- i.e., has HT-weight 0 rather than 1 -- is the one corresponding to the factor field of $K_p$ that underlies the initial definition of the character.)
One cannot point to the error in the "proof" of the false statement because in the proof the author is initially analyzing each local place on its own and just boldly asserts without any reason that the weight which occurs for a given $\sigma^{(i)}$ at one $p$-adic place must be the same at the other place.  Maybe the author is misled by the equalities $K_v = \mathbf{Q}_p = K_{v'}$ and didn't notice how exchanging these two incarnations of $\mathbf{Q}_p$ requires interacting with complex conjugation and that complex conjugation swaps the two $\sigma^{(i)}$'s in the way that is explained above.

A: Objection to nfdc23. Sorry if it is wrong!
His $p$-adic avatar carries the uniformizer to Frob
and one gets the equality of L-functions but
this is related just by $\chi=\iota\circ \sigma\circ Art$ which
is not a continuous character in general because of a field isomorphism $\iota:\bar{Q}_{p}\simeq C$. He looked at only the finite components but not infinite or $p$-adic components. So, I think that
his proof is incomplete. The effect of the complex conjugation does
not necessarily swap two Galois characters (as a continuous character).
On the other hand, as I wrote in the comment, Morita takes care of this issue.


text:
Q: Java: printing file doesn't work I use Java 1.6 (JDK), Windows 7 and a virtual image printer driver.
I try to print some documents.
Here is my code
try {

   System.out.println(" PrintServiceOverseer printFileToDefaultPrinter start "+
      fileName);

   PrintService printService = PrintServiceLookup.lookupDefaultPrintService();

   System.out.println(" default Printer " + printService.getName());

   FileInputStream inputStream = new FileInputStream(new File(fileName));

   DocFlavor docFlavor = DocFlavor.INPUT_STREAM.AUTOSENSE;

   Doc printDoc = new SimpleDoc(inputStream, docFlavor, null);

   PrintRequestAttributeSet  pras = new HashPrintRequestAttributeSet();
   pras.add(new Copies(1));

   DocPrintJob printJob = printService.createPrintJob();

   printJob.print(printDoc, pras);

   inputStream.close();

   System.out.println(" PrintServiceOverseer printFileToDefaultPrinter end ");
} catch (Exception ex) {
        ex.printStackTrace();
}

But it doesn't work. It prints nothing and no exception is thrown. The code compiles and runs smoothly, but there is no output.
Can you give me some guidance?

A: I got the same problem, I solved it by updating my printer's driver, I think you didn't install the proper driver, you may installed a driver which works for your printer but not the proper one.


text:
Q: How to get the MS Band region setting I am displaying numbers and currency values on a Band custom tile. How can I get the current region setting of Band so I can format the numbers correctly?
The Band region can be set via MS Health app: Preferences, choose your region (Format for date, time, etc on your Band).

A: Getting the region setting of the band from the Microsoft Band SDK is not currently supported.
But it seems like you have a good use case, so it is something you might want to add to the Microsoft Band/Health User Voice:
https://microsofthealth.uservoice.com/forums/283636-microsoft-health-and-microsoft-band

A: While you cannot get the exact set region from the Band itself, you may be able to use the "preferred locale" information of the user's Microsoft Health profile, obtained via the Microsoft Health (Preview) Cloud API.


text:
Q: Populate the column by comparing if the value from the list is in string I appreciate the help.
I have two data sets:
models = pd.DataFrame({"manufacturer":['Nokia', 'Samsung', 'Motorola', 'Nokia', 'Alcatel', 'Nokia 5'],
               "model":['3310', 'S4', 'Moto G', 'N1', 'Pixy', 'Nokia 5']})

data = pd.DataFrame({"title":["Brand New Nokia 3310", "Old Samsung S4", "Cool Motorola Moto G", 'New Alcatel', 'Old Nokia 5'],
                "manufacturer":['Nokia', "Samsung", "Motorola", 'Alcatel', 'Nokia'],
                "model":["placeholder", "placeholder", "placeholder", "placeholder", "placeholder"]})

I need to populate model value in data['model'] by condition that the string in title contains model string, otherwise the value in that column should remain placeholder.
I tried to do it by using a list comprehension but it's not working.
mod = models["model"].tolist()
title = data['title']
data['model'] = pd.Series([m for m in mod for t in title if m in]

I also tried by using "str.contains" which is pandas method:
for m in mod:
    if title.str.contains(m):
        data['model'] = m

But that also is not working as i expected. Is there a way to do it?
Thanks in advance.

A: mod = models["model"]
data["model"] = data["title"].map(lambda s: next((m for m in mod if m in s), "placeholder"))


text:
Q: Embedded form render wrong input type To allow customisation of the registration form, some form fields are generated from database informations and the form in embedded into the registration form.
While each fields of the embedded form is typed, for some reason, when I render them using twig, some types like url or number are rendered as text type input.
Yet, all fields form the main form (nom, prenom, email, plainPassword) are rendered with the assigned type.
As you can see in the code fragments, I'm properly using form_widget and form_widget to render each input, thus type handling is done by Symfony.
When I dump each formView for each field, within field.vars.block_prefixes (array), I can find the type of the input as it should be.
As example, this is the content of a text input :
"block_prefixes" => array:3 [▼
  0 => "form"
  1 => "text"
  2 => "_security_extraDataCollection_datum-30"
]

The content of a url input :
"block_prefixes" => array:4 [▼
  0 => "form"
  1 => "text"
  2 => "url"
  3 => "_security_extraDataCollection_datum-31"
]

And the content of a number input :
"block_prefixes" => array:3 [▼
  0 => "form"
  1 => "number"
  2 => "_security_extraDataCollection_datum-33"
]

At first, I thought that was because I was using material-component-web, but even without CSS, this problem occur.
Any idea as to why url and number type are turned to text type when I render them from enbedded form?
Registration form
public function buildForm(FormBuilderInterface $builder, array $options) {
    /** @var array $extraData */
    $extraData=$options['extra_data'];

    $builder->add('nom')
            ->add('prenom')
            ->add('email', EmailType::class)
            ->add('plainPassword', PasswordType::class, array(
                'mapped'=>false,
                'constraints'=>array(
                    new NotBlank(array(
                        'message'=>'Please enter a password',
                    )),
                    new Length(array(
                        'min'=>6,
                        'max'=>4096,
                    )),
                ),
            ));

    if($extraData !== null && is_array($extraData) && count($extraData)) {
        $builder->add('extraDataCollection', UnmappedMixedType::class, array(
            'mapped'=>false,
            'data'=>$extraData,
        ));
    }
}

UnmappedMixedType form
public function buildForm(FormBuilderInterface $builder, array $options) {
    /** @var array $extraData */
    $extraData=$options['data'];

    /** @var ExtraData $extraDatum */
    foreach($extraData as $extraDatum) {
        if($extraDatum->getType() == 'text') {
            $builder->add('datum-'.$extraDatum->getId(), TextType::class, array(
                'mapped'=>false,
                'required'=>$extraDatum->getIsObligatoire(),
                'label'=>$extraDatum->getLabel(),
            ));
        } elseif($extraDatum->getType() == 'url') {
            $builder->add('datum-'.$extraDatum->getId(), UrlType::class, array(
                'mapped'=>false,
                'required'=>$extraDatum->getIsObligatoire(),
                'label'=>$extraDatum->getLabel(),
            ));
        } elseif($extraDatum->getType() == 'number') {
            $builder->add('datum-'.$extraDatum->getId(), NumberType::class, array(
                'mapped'=>false,
                'required'=>$extraDatum->getIsObligatoire(),
                'label'=>$extraDatum->getLabel(),
            ));
        } elseif($extraDatum->getType() == 'checkbox') {
            $builder->add('datum-'.$extraDatum->getId(), CheckboxType::class, array(
                'mapped'=>false,
                'required'=>$extraDatum->getIsObligatoire(),
                'label'=>$extraDatum->getLabel(),
            ));
        } elseif($extraDatum->getType() == 'choice' && $extraDatum->getChoix() !== null && count($extraDatum->getChoix()) >= 1) {
            $builder->add('datum-'.$extraDatum->getId(), ChoiceType::class, array(
                'mapped'=>false,
                'required'=>$extraDatum->getIsObligatoire(),
                'label'=>$extraDatum->getLabel(),
                'multiple'=>$extraDatum->getIsChoixMultipleUtilisateur(),
                'choices'=>array_combine($extraDatum->getChoix(), $extraDatum->getChoix()),
            ));
        }
    }
}

Twig view
{% if form.extraDataForm is defined %}

                {% for field in form.extraDataForm %}
                    {{ dump(field) }}
                    {% if field.vars.block_prefixes[1] == 'text' or field.vars.block_prefixes[1] == 'number' %}

                            {{ form_widget(field, {'attr': {'class': 'mdc-text-field__input'}}) }}

                                    {{ form_label(field, null, {'label_attr': {'class': 'mdc-floating-label'}}) }}

                    {% elseif field.vars.block_prefixes[1] == 'checkbox' %}

                                {{ form_widget(field, {'attr': {'class': 'mdc-checkbox__native-control'}}) }}

                                    <svg class="mdc-checkbox__checkmark" viewBox="0 0 24 24">
                                        <path class="mdc-checkbox__checkmark-path" fill="none" d="M1.73,12.91 8.1,19.28 22.79,4.59"></path>
                                    </svg>

                            {{ form_label(field, null, {'label_attr': {'class': 'app-txt-light-emphasis'}}) }}

                    {% elseif field.vars.block_prefixes[1] == 'choice' %}

{{ form_widget(field) }}

                    {% endif %}
                {% endfor %}

{% endif %}

A: UrlType Field as the documentations says:

The UrlType field is a text field that prepends the submitted value with a given protocol (e.g. http://) if the submitted value doesn't already have a protocol.

If you would like an input with url type create your own Form Field Type like that:
class MyUrlType extends AbstractType {

    /**
     * {@inheritdoc}
     */
    public function buildView(FormView $view, FormInterface $form, array $options)
    {
        $view->vars['type'] = 'url';
    }

    /**
     * {@inheritdoc}
     */
    public function getParent()
    {
        return __NAMESPACE__.'\TextType';
    }
}

From here https://symfony.com/doc/current/form/create_custom_field_type.html


text:
Q: MainActivity.java: uses or overrides a deprecated API I get a compilation error after I add implementation 'com.google.firebase:firebase-inappmessaging-display:19.0.2' under dependencies in build.grandle app. It's working fine when the project is syncing, but it fails while I try to compile the app.
This is the error I've got:
AndroidStudioProjects/Pari365/app/src/main/java/com/maunexus/MainActivity.java:
uses or overrides a deprecated API.
Recompile with -Xlint:deprecation for details.

This is the MainActivity.java file:
package com.maunexus;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Build;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.webkit.CookieManager;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    private WebView webView;
    Activity activity;
    private ProgressDialog progDailog;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        activity = this;

        progDailog = ProgressDialog.show(activity, "Loading", "Please wait...", true);
        progDailog.setCancelable(false);

        webView = (WebView) findViewById(R.id.webviewid);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            CookieManager.getInstance().setAcceptThirdPartyCookies(webView, true);
        }
        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(false);
        webView.getSettings().setSupportMultipleWindows(false);
        webView.getSettings().setSupportZoom(false);
        webView.setVerticalScrollBarEnabled(false);
        webView.setHorizontalScrollBarEnabled(false);
        webView.getSettings().setLoadWithOverviewMode(true);
        webView.getSettings().setUseWideViewPort(true);
        webView.setWebViewClient(new WebViewClient() {

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                progDailog.show();
                view.loadUrl(url);

                return true;
            }

            @Override
            public void onPageFinished(WebView view, final String url) {
                progDailog.dismiss();
            }
        });

        webView.loadUrl("https://pari365.mg");

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater menuInflater = getMenuInflater();
        menuInflater.inflate(R.menu.super_menu, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
            case R.id.menu_back:
                onBackPressed();
                break;

            case R.id.menu_forward:
                onForwardPressed();
                break;

            case R.id.menu_refresh:
                webView.reload();
                Toast.makeText(this, "Reloading... Please Wait!", Toast.LENGTH_SHORT).show();
                break;

        }
        return super.onOptionsItemSelected(item);
    }

    private void onForwardPressed() {
        if (webView.canGoForward()) {
            webView.goForward();
        } else {
            Toast.makeText(this, "Already there! ;)", Toast.LENGTH_SHORT).show();
        }
    }

    public void onBackPressed() {
        if (webView.canGoBack()) {
            webView.goBack();
        }
    }
}

And, this is the AndroidManifest.xml file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.maunexus">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

Please help me to fix the error. Thank You ;)
UPDATE: I replaced the ProgressDialog with ProgressBar, but the error still persists.
com/maunexus/MainActivity.java
uses or overrides a deprecated API.
com.android.tools.r8.CompilationFailedException: Compilation failed to complete
com.android.tools.r8.utils.AbortException: Error: null, Cannot fit requested classes in a single dex file (# methods: 100707 > 65536)
null
Cannot fit requested classes in a single dex file (# methods: 100707 > 65536)

A: This is a warning, and the deprecated class is ProgressDialog, from the docs:

This class was deprecated in API level 26.
ProgressDialog is a modal dialog, which prevents the user from interacting with the app. Instead of using this class, you should use a progress indicator like ProgressBar, which can be embedded in your app's UI. Alternatively, you can use a notification to inform the user of the task's progress.

https://developer.android.com/reference/android/app/ProgressDialog
You can use the ProgressBar instead of ProgressDialog.


text:
Q: Why do I no longer have the question and answer editing privilege? Recently I've noticed that in Stack Overflow I no longer am allowed to edit questions and answers. This seems to be disabled.
Can anyone please tell me why that might have happened?

A: Too many of your recent suggested edits have been rejected, and you have been banned (temporarily, one week) from suggesting any more.
Reviewing the recent rejected suggestions, we find:

*

*February 27

*

*You need to do more than just fix the formatting and remove 'thank you'. You left many other problems in place. It was thus rejected as Too Minor.

*

*February 27

*

*'JavaScript', 'JSF' and 'API' are not code (or variable names). Don't use backticks for
those, only use that for code and names taken from code (class names, variables, etc.).

*

*February 27

*

*Just adding backticks to JPanel is too minor; adding the ticks doesn't really add anything to the quality of that post.

*

*February 26

*

*'firefox', 'chrome' and 'internet explorer' are not code (or variable names). Don't use backticks for
those, only use that for code and names taken from code (class names, variables, etc.).

*

*February 25

*

*'javascript' is not code (or a variable name). Don't use backticks for
those, only use that for code and names taken from code (class names, variables, etc.).

*

*February 22

*

*'Worker Threads and SwingWorker' is not code (or a variable name). Don't use backticks for
those, only use that for code and names taken from code (class names, variables, etc.).

These two were editing conflicts (suggested edits always lose to a regular edit submitted at the same time):

*

*February 25

*February 25
The rest are older.
Your ban will automatically be lifted after 1 week, but its purpose has been served. You took a breather from suggesting edits and instead took the time to find out why you were blocked. Thank you!


text:
Q: Cardinality of Reals and Turing Machines I'm a math hobbyist, so forgive me if what I ask is silly.
I just learned that the cardinality of Reals is greater than the Naturals.
So, because of that, there can be no turing machines which generate all real numbers (ignore the fact that the turing machine would never halt).
In particular, there can be no algorithm which sequentially generates all real numbers, because, since turing machines operates sequentially, we could put them into correspondence with the Naturals, which would be a contradiction of the Cantor Theorem.
Is my thinking correct?
Could you imagine what other implications would this have?
Thanks for the time.

A: You are correct. Another way to say this is that the set of computable reals is countable, so cannot be all the reals. In fact, in the measure-theoretic sense almost all reals are not computable.


text:
Q: FileNotFoundError: while converting .py to exe file I'm trying to convert my py file to exe after when I run the exe file it always shows the same error on console windows
Traceback (most recent call last):
  File "njlispendens.py", line 482, in <module>
  File "selenium_stealth\__init__.py", line 45, in stealth
  File "selenium_stealth\utils.py", line 8, in with_utils
  File "pathlib.py", line 1132, in read_text
  File "pathlib.py", line 1117, in open
FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\alium\\AppData\\Local\\Temp\\_MEI93442\\selenium_stealth\\js\\utils.js'
[9744] Failed to execute script 'njlispendens' due to unhandled exception!
[10772:940:0102/104425.600:ERROR:chrome_browser_main_extra_parts_metrics.cc(226)] crbug.com/1216328: Checking Bluetooth availability started. Please report if there is no report that this ends.
[10772:6564:0102/104425.600:ERROR:device_event_log_impl.cc(214)] [10:44:25.611] USB: usb_device_handle_win.cc:1048 Failed to read descriptor from node connection: A device attached to the system is not functioning. (0x1F)
[10772:940:0102/104425.616:ERROR:chrome_browser_main_extra_parts_metrics.cc(229)] crbug.com/1216328: Checking Bluetooth availability ended.
[10772:940:0102/104425.616:ERROR:chrome_browser_main_extra_parts_metrics.cc(232)] crbug.com/1216328: Checking default browser status started. Please report if there is no report that this ends.
[10772:940:0102/104425.709:ERROR:chrome_browser_main_extra_parts_metrics.cc(236)] crbug.com/1216328: Checking default browser status ended.

Here is what I did to deal with the error

*

*tried uninstalling packages and installing them again and then converting it into exe

*tried Pyinstaller single and multiple file

*adding python to path

*tried using auto-py-to-exe to for conversion

*tried uninstalling python, removing from path, installing python again

please help


text:
Q: Does React rerender child components if they become null via ternary operation? If we have a state called, show, which determines whether to display <Child /> component. Does <Child /> component re-render if its parent re-renders and show is still false?
{ show === true ? <Child /> : null }

A: Consider the following piece of code
{ condition ? <Component /> : null }

Can be interpreted as:
If a given condition asserts to true then render Component else render null.
Something will always be rendered, either null or an instance of Component. Now this one:
{ condition && <Component /> }

Doesn't render anything cause the interpreter will just stop when the first part of the logical operator (&&) returns false (cause you don't even need to check what comes after). So in this case nothing is rendered, not even null. It's worth mentioning that performance wise both are pretty much the same


text:
Q: "factoring" subordinate clauses with verbs that require indicative and subjunctive clauses For some verbs a subjunctive form is used in the subordinate clause, and I would write

I demand that he read the appendices.

Other verbs demand that you use an indicative form, for example

I expect that he will read the appendices.

So how do I terminate the sentence

You cannot demand nor expect that he...

I know that you can always avoid that sort of construction, but I was just wondering about the grammatical rule in this case.

A: Fortunately, English has an auxiliary verb that goes with both demand and expect:

You cannot demand or expect that he should read the appendices.

But this doesn't answer the question for general pairs of verbs.

A: I know of no absolute rule, and so would depend upon the proximity principle to produce something that hopefully read well:

You cannot demand nor expect that he will read the appendices.
You cannot expect nor demand that he read the appendices.

The proximity principle is more an observation than a rule - in cases where there is a conflict of agreement because of two or more words being joined by a conjunction that would require a different number, mood, etc. in what follows, then make the agreement happen with those words that are closer to each other and it will tend to sound correct whether it is or not!
However, if what was added could be read as a parenthetical clause, then I would treat it as if it could be omitted:

You cannot demand, nor expect, that he read the appendices.
You cannot expect, nor demand, that he will read the appendices.

Again though, I know of no absolute rule.

A: In general, when we factor out into a list, we make the common factor agree with the closest member of the list.  For example:

There was a cat and two dogs.
There were two dogs and a cat.
You can neither demand, nor expect that he will read the appendices.
You can neither expect, nor demand that he read the appendices.

A: The difficulty arises from the different constructions that can follow the two verbs demand and expect. You can demand that someone do something, but you can't expect that someone do something.  It follows that it is not grammatically coherent to say either 'You cannot demand nor expect that he read the appendices' or 'You cannot demand nor expect that he reads the appendices' or 'You cannot demand nor expect that he will read the appendices' is.
Not only can you avoid that sort of construction, as you suggest, but you must, if you want to make life easy for the reader. A possible alternative is 'You cannot demand that he read the appendices, and you cannot expect him to either.'


text:
Q: php mysql multiple OR statements I am trying to run a simple mysql query,but it returns nothing everytime. For some reason it seems having multiple "OR" statements is the reason. why?
returns null
mysql_query("SELECT * FROM table WHERE lower(Name)='arabic' or lower(Sub Name)='arabic' or lower(Language)='arabic'");

returns results
mysql_query("SELECT * FROM table WHERE lower(Name)='arabic'");

A: your column name has space you should surround column name with ` symbol
mysql_query("SELECT * FROM table WHERE lower(`Name`)='arabic' or lower(`Sub Name`)='arabic' or lower(`Language`)='arabic'");


text:
Q: How do I get Eclipse Galileo to stop restarting an external Tomcat run configuration? I don't even have any servers setup except as an External Tool Configuration > Program. I'm using the JPDA connector, and yet when I do certain things like have Eclipse auto generate a serialVersionUID it automatically restarts Tomcat. I can't find where this might be configured in the project properties or the window preferences. I don't want Eclipse to do anything with Tomcat unless I'm starting or stopping. Thanks!

A: Well, months after giving up, I was having a discussion with a co-worker about my Tomcat context, and finally realized what it was. I had reloadable = "true" in the context node, and it had nothing to do with Eclipse. In this scenario, all Eclipse does is communicate with Tomcat, and display console output. Tomcat was being notified in certain scenarios that files had changed, and it was restarting automatically. I set reloadable = "false", and this is no longer a problem.

A: Does the server show up in the Servers view?
If so, double-click the server in that view, expand the "Publishing" area, and select the "Never publish automatically" radio option. Save the server, and (re)start it.


text:
Q: How to return and write data into a file using apache camel? After a rest call, I am trying to set me camel route to return the data and write it into a cvs file. Problem is that I can get it to do only one of the two.
from("direct:select")
                .setBody(constant("select * from animal")).to("jdbc:dataSource").marshal().csv()
                .to("file:///tmp?fileName=MY_TEST_FILE.csv");

In the current version it writes into the file correctly but the rest response is just a bunch of numbers. Though if I change the order of functions like:
from("direct:select")
                .setBody(constant("select * from animal"))
                .to("file:///tmp?fileName=MY_TEST_FILE.csv").marshal().csv().to("jdbc:dataSource");

I get the correct rest response but in the file I get:
select * from applicant

Is there a way to do both from a single camel route?

A: Camel just executes the routing/transformation instructions in the order that you define them.
Your first attempt makes some sense: you run the select query, get the list of rows out of the JDBC call, convert it to CSV, then write it to file and return it as reply of your route.
That last part is important to understand: the reply from your route will be whatever your exchange body contains at the end of the (synchronous) processing.
Given that you're not happy with this first attempt, I will go and assume that the CSV format is not what you intend to return as reply.
Now looking at your second attempt, you say that it returns the expected reply but that is surprising to me: you're trying to convert the literal string "select * from animal" to CSV, which is throwing an exception on my end:

org.apache.camel.NoTypeConversionAvailableException: No type converter available to convert from type: java.lang.String to the required type: java.util.List with value select * from animal

Now if you remove the .marshal().csv(), the route is working. It writes "select * from animal" to file as you've observed (but that's exactly what the route is instructing to do) and it returns as reply the content of the exchange body at the end of the route, meaning the List that results from the JDBC call. I will thus make another assumption that this list is in fact what you're intending to return (you probably want to return JSON, so List does indeed fit the bill for seamless JSON conversion).
With all this in mind, let's try to find you a route that does what you want. However, we hit a bit of a wall with your requirement to "do both from a single camel route". Let's hope that you didn't mean to exclude the usage of sub-routes linked by direct: endpoints (I don't see any good reason why you'd want to avoid that).
Here's a first solution that does everything synchronously (JDBC call + writing to file both done by the originating thread):
from("direct:select")
    .setBody(constant("select * from animal"))
    .to("jdbc:dataSource")
    .enrich("direct:file", new UseOriginalAggregationStrategy());

from("direct:file")
    .marshal().csv()
    .to("file:///tmp?fileName=MY_TEST_FILE.csv");

See Camel Enrich EIP for more details.
And here's one that will write to file asynchronously (i.e. in a separate thread), meaning that your REST call should be a bit faster to respond:
from("direct:select")
    .setBody(constant("select * from animal"))
    .to("jdbc:dataSource")
    .wireTap("direct:file");

from("direct:file")
    .marshal().csv()
    .to("file:///tmp?fileName=MY_TEST_FILE.csv");

See Camel Wire Tap EIP for more details.


text:
Q: Problemas para abrir ventana modal de boostrap en pagina con Frames Estoy desarrollando una página en jsp y mysql , la cual se compone de 3 frames
uno para la barra superior, otro para la barra central y otro para un mena a la izquierda.
En la barra superior hay un link, para desconectarse de la aplicación, que abre un modal con un formulario que envía la petición al servidor para desconectarse. El problema es que esta ventana modal se muestra detrás del frame central.
aquí la imagen.

Aquí el código del modal.

Log out

<button type="button" class="close" data-dismiss="modal" aria-label="Close">
×
</button>

<form action="logoutServlet.do">

Estas seguro que deseas salir?

<button type="button" class="btn btn-secondary" data-dismiss="modal">Cancelar</button>
<button type="submit" class="btn btn-primary" formtarget="_top">Salir</button>

</form>

Este modal se crea en la página "frame superior" osea en la barra superior y lo llamó desde el botón "Salir", pero en vez de mostrarse afuera de todos los frames, se muestra detrás.
Si alguien me pudiese ayudar seria genial, gracias.
probé usando style:"z-index: 999;" en el div del modal pero solo me oscurece la pagina de la barra superior y el modal sigue visualizandose detras del frame central.
aqui la primera linea del modal con el style z-index 999

A: El principal problema que estás sufriendo es que cada marco tiene asignada un área de la ventana del navegador de la que no puede salir, es imposible escapar de ella ni aún modificando parámetros como z-index.
Para poder solucionar esta limitación, podemos aumentar el área de visualización desde el marco hijo, accediendo al marco padre mediante window.parent:
console.log('Marco padre:', parent);

Para empezar facilitaremos la localización del juego de marcos en el HTML del padre para facilitar el código:
<frameset id="marcos" rows="100,*">
  <frame src="superior.html">
  <frame src="inferior.html">
</frameset>

En el ejemplo la parte superior tendrá una altura de 100 pixeles y la parte inferior será del resto de la ventana (100,*).
Ahora, para poder mostrar el mensaje modal a pantalla completa jugaremos con los eventos del modal:

show.bs.modal
Este evento se dispara inmediatamente en cuanto se llama al método de instancia para mostrar. Si fue causado por un clic, el elemento que fue pulsado estará disponible en la propiedad relatedTarget del evento.
hidden.bs.modal
Este evento será disparado cuando el modal finalice su efecto de ocultación al usuario (esperará a que se complete la transición CSS).

De modo que localizaremos el juego de marcos del padre para cambiar la definición del atributo rows por uno en el que el marco inferior sólo ocupe 1 pixel y el superior el resto de la ventana (*,1) y restablecemos el original cuando se oculte:
/* Aumentamos el marco superior cuando se muestre el modal */
$('#exampleModalCenter').on('show.bs.modal', function (e) {
  parent.document.getElementById('marcos').rows = '*,1';
})
/* Restablecemos el tamaño original cuando se oculte */
$('#exampleModalCenter').on('hidden.bs.modal', function (e) {
  parent.document.getElementById('marcos').rows = '100,*';
})

Tienes un ejemplo online disponible aquí.


text:
Q: Click() action is not working with firefox in selenium webdriver
*

*Below code not working for click action.

*I have tried it on chrome but not working on Firefox.
    package SeleniumCase;
    import org.openqa.selenium.By;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.WebElement;
    import org.openqa.selenium.firefox.FirefoxDriver;

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

     {

       WebDriver driver;
       System.setProperty("webdriver.gecko.driver","E:\\Librar\\geckodriver.exe");
       driver = new FirefoxDriver();
       driver.get("my company url hide for security reason");
       driver.findElement(By.id("UserName")).sendKeys("admin@school.com");
       driver.findElement(By.id("next")).click();
       driver.findElement(By.id("Password")).sendKeys("passw0rd");
       driver.findElement(By.id("submit")).click();
     }
}

A: Are you getting any error?Please share the exception or error
try this
JavascriptExecutor js = (JavascriptExecutor) driver;
            js.executeScript("var evt = document.createEvent('MouseEvents');" + "evt.initMouseEvent('click',true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0,null);" + "arguments[0].dispatchEvent(evt);",  webElement);


text:
Q: Looping many one-sided ANOVA in R I would like to run 100 ANOVA for different numeric vectors.
My numeric vectors are (ruy, fjr, akf....) from my data.frame
aa=aov(data.frame$ruy~data.frame$Group)
anova(aa)
ab=aov(data.frame$fjr~data.frame$Group)
anova(ab)
ac=aov(data.frame$akf~data.frame$Group)
anova(ac)
.....
.....

My looping skills are poor so please be nice.

A: Since aov is based on lm you can cbind dependent variables on the LHS, which results in seperate models being run:
formula <- as.formula(paste0("cbind(", paste(names(iris)[-5], collapse = ","), ") ~ Species"))

fit <- aov(formula, data=iris)
summary(fit)
# Response Sepal.Length :
#             Df Sum Sq Mean Sq F value    Pr(>F)
#Species       2 63.212  31.606  119.26 < 2.2e-16 ***
#Residuals   147 38.956   0.265
#---
#Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
#
# Response Sepal.Width :
#             Df Sum Sq Mean Sq F value    Pr(>F)
#Species       2 11.345  5.6725   49.16 < 2.2e-16 ***
#Residuals   147 16.962  0.1154
#---
#Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
#
#</snip>

A: Alternatively, you can loop over the responses to create a list where each eleemnt corresponds to one model instead of the excellent answer from Roland which generates a 'single' model with multiple responses. This could be usefule if you want (in a later step) work with the generated models seperately:
responseList <- names(iris)[-5]
modelList    <- lapply(responseList, function(resp) {
                           mF <- formula(paste(resp, " ~ Species"))
                           aov(mF, data = iris)
                })

Then you could use lapply again to run the summary on the aov models:
lapply(modelList, summary)

As mentioned, the solution from Roland gives you a multiple responses model (class(fit)) whereas the solution above gives you a list of (single) response models. Whatever you prefer mainly depends on how you want to work with the result.


text:
Q: how do you add a home button and tabs to custom written web browser in ubuntu how do you code in a home button for a web browser?
im creating a web browser in ubuntu for use in ubuntu.  I am using a mix of Glade, Python, quickly, WebKit and WebView
i have got nearly everything done and thought a home button would be a nice touch.  I already have the home button in place just need to know how to get it to work.
for the tabbed buttons i have done this:
        self.webview = WebKit.WebView()
    self.scrolledwindow1.add(self, webview)
    self.scrolledwindow2.add(self, webview)
    self.scrolledwindow3.add(self, webview)
    self.webview.show()

the way i have set that tabbed windows and the scrolledwindow out in glade is like this:
tab1 holds scrolledwindow1
tab2 holds scrolledwindow2
tab3 holds scrolledwindow3
when i do "quickly run" i get this error message:
/usr/lib/python2.7/dist-packages/gi/overrides/Gtk.py:391: Warning: g_object_set_property: construct property "type" for object `Window' can't be set after construction

Gtk.Window.init(self, type=type, **kwds)
Traceback (most recent call last):
  File "bin/dm-test", line 33, in
    dm_test.main()
  File "/home/matty/dm-test/dm_test/init.py", line 33, in main
    window = DmTestWindow.DmTestWindow()
  File "/home/matty/dm-test/dm_test_lib/Window.py", line 35, in new
    new_object.finish_initializing(builder)
  File "/home/matty/dm-test/dm_test/DmTestWindow.py", line 55, in finish_initializing
    self.scrolledwindow1.add(self, webview)
AttributeError: 'DmTestWindow' object has no attribute 'scrolledwindow1'
now im not sure if im actually calling the tab's and the scrolledwindow in the right way or not.  Below is the full code that i have written for this to work (was working before tabbed window idea)
# Code for other initialization actions should be added here.

#this builds the tool back and all the buttons(defines)

    self.toolbar = self.builder.get_object("toolbar")
    self.backbutton = self.builder.get_object("backbutton")
    self.forwardbutton = self.builder.get_object("forwardbutton")
    self.refreshbutton = self.builder.get_object("refreshbutton")
    self.stopbutton = self.builder.get_object("stopbutton")
    self.homebutton = self.builder.get_object("homebutton")
    self.urlentry = self.builder.get_object("urlentry")
    self.webview = WebKit.WebView()
    self.scrolledwindow1.add(self, webview)
    self.scrolledwindow2.add(self, webview)
    self.scrolledwindow3.add(self, webview)
    self.webview.show()

#This sets the buttons in tool bar to work

def on_backbutton_clicked(self, widget):
    self.webview.go_back()

def on_forwardbutton_clicked(self, widget):
    self.webview.go_forward()

def on_refreshbutton_clicked(self, widget):
    self.webview.reload()

def on_stopbutton_clicked(self, widget):
    self.webview.stop_loading()

def on_homebutton_clicked(self, widget):
    self.webview.open(DEFAULT_URL)

def on_url_entry_activate(self, widget):
    url = widget.get_text()
    self.webview.open("http://" + url)
    print url

has anyone got any ideas how i can properly set the tabbed windows (want it to look abit like chromium) the code to set it would also be helpful or a sample of the code i would need to use and a explanation on how to use it if possible.
many thanks in advance

A: A home button is very simple, considering you already have the button and handler created through Glade:
# You'll probably have this laying around somewhere already
DEFAULT_URL = "http://www.ubuntu.com"

# class
    # init etc

    def on_home_clicked(self, widget):
        self.web_view.open(DEFAULT_URL)

Making your browser tabbed is a bit more work. You should created a GtkNotebook inside your window and pack each browserview into a seperate page.


text:
Q: Xamarin web api and other platforms time problems i created an api by .NET, webform and xamarin mobile.. when i check token expire time i saw different times but all of them are workin same computer. what is the problem and how can i solve these problem.
When i check with Fidler i saw time which is .issued=Sun, 24 May 2020 20:38:34 GMT and my computer time is 23:58 how it can be.. both of them are running  on same compuer
WEB API Time on Computer and Computer Time
OAuthAuthorizationServerOptions oAuthAuthorizationServerOptions = new
OAuthAuthorizationServerOptions()
        {
            TokenEndpointPath = new Microsoft.Owin.PathString("/token"),
            AccessTokenExpireTimeSpan = TimeSpan.FromHours(1),
            AllowInsecureHttp = true,
            Provider = new Saglayici() //
        };


text:
Q: Putting existing versions and branches of a project under version control I am the only developer of a software project. I did not use any version control until now. I know I can put the last version of the project under version control. The question is whether it is possible to put older versions and branches of the project under version control. If it is possible, how ?
which version control software should I use ? (I am using Visual Studio 2008)
Edit: I have almost all previous versions.

A: You could do it, assuming you have copies of the older revisions that you want to put into source control (you can't magically make them appear, of course).
What I would do is take the oldest version, put it somewhere, and commit the folder to your source control (this would become Revision 1). Then, take the second-oldest version, overwrite the first version on your hard drive with that, then check in again (this becomes Revision 2 in source control). Repeat, overwriting with the next-newest revision each time until all of the versions you want are checked in.
There are good, free version control systems available. I use SVN (with the TortoiseSVN shell add-on), and I'm quite happy with it. CVS is alright too, but gets very slow as projects get large.

A: Which VCS you should use is really up to you.  I'd recommend Mercurial as it is a very good distributed VCS and runs rather well under Windows.  I don't know what VS support but you may want to use a supported VCS (which probably means Subversion I guess).  There is TortoiseHg available there as well.
If you have all previous versions, you can import them manually, one after the other to get to the last one then work from that.


text:
Q: Mail function has stopped working on server my mail script is on online server. was working fine. but not now. I am confused why it has stopped sending mail. It shows the message that email sent, but no email is received in inbox. here is my php script:
$useremail = $_POST['myemail'];

    $friendemail = $_POST['friendemail'];

        $name = "support";

        $email = "support@example.com";

        $rec = $friendemail;

        $sub = "support Invitation";

        $body = 'the user '.$useremail.' has sent you message';

        $header="Content-type: text/html\n";

        $header .= "From: $name < ". $email ." >";

        $success_mail = mail($rec,$sub,$body,$header);
        if($success_mail){ echo "success0";} else { echo "Not sent";}

please help me !

A: IME most issues relating to sending mail from PHP are problems with the MTA and nothing to do with PHP. If the system has stopped sending mail but your PHP has not changed then that's probably the case here too.
You've provided no information about what OS this is running on, nor how PHP is configured to use mail - this is very different on different operating systems.

but no email is received in inbox

There's a whole lot of things which hapen in between sending an email and it arriving at it's destination. Typically it is queued for sending by the MTA at the sending end, passed to the MTA at the receiving end (optionally through intermediate MTAs), policy checks applied at the receiving end, passed on to the imap/pop service at the receiving end (possibly with further policy checks), retrieved by your mail client (again with further policy checks).
You need to look at each step of the process to find out where it is failing.

mysql_real_escape_string($_POST['friendemail']);

WTF? this is just wrong.

$header="Content-type: text/html\n";

You're not doing yourself any favours by trying to force non 7-bit ascii through SMTP. These days,  that shouldn't be a big problem, and is unlikely to be the cause of the error - but try sending plain text messages and see what happens.
oh...and looking at your code again I see that you are sending plain text so WTF is the html header for?
If you want any assurance of deliverability, then fix the encoding of your emails regardless if this is not the cause of the problem in this case.


text:
Q: Change folder name using batch file I have two sets of data that I need to be able to rotate between. In order to use the data it needs to be in a folder C:\Data so I was trying to create short script that would check which data set was in use (TX or CA) and rotate which folder set was using the "data" label, but it won't read the second line of either IF/ELSE clause. Is there syntax or something else I am missing?
IF EXIST C:\data_TX (
  ren "C:\data" "data_CA"
  ren "C:\data_TX" "data" )
ELSE (
  ren "C:\data" "data_TX"
  ren "C:\data_CA" "data" )

A: Use IF /? to find out how this works. cmd.exe is not a free-form language. This is what the others are saying.
IF EXIST C:\data_TX (
  ren "C:\data" "data_CA"
  ren "C:\data_TX" "data"
) ELSE (
  ren "C:\data" "data_TX"
  ren "C:\data_CA" "data"
)


text:
Q: How to make UITabBarItem be an image from unicode? I can create an image with a "png" file.
UITabBarItem *tabBarItem1 = [[UITabBarItem alloc] initWithTitle:@"Operation"
                              image:[UIImage imageNamed:@"plus.png"] tag:0 ];

But I would like to use unicode image (721) or character val, ie:
UITabBarItem *tabBarItem1 = [[UITabBarItem alloc] initWithTitle:@"Operation"
                              image: {unicode: 721 }];

How would I do this?  thx

A: I've created a little helper method that creates a small image from an NSString that usually contains a single Unicode character.
+ (UIImage *)characterImage:(NSString *)ch {
    UIFont *font = [UIFont boldSystemFontOfSize:12];
    CGSize chsize = [ch sizeWithAttributes:@{ NSFontAttributeName : font }];
    CGSize imgsize = CGSizeMake(16, 16);
    UIGraphicsBeginImageContextWithOptions(imgsize, NO, [UIScreen mainScreen].scale);

    CGRect rect = CGRectMake((imgsize.width - chsize.width) / 2.0, (imgsize.height - chsize.height) / 2.0, chsize.width, chsize.height);
    NSMutableParagraphStyle *pStyle = [[NSMutableParagraphStyle alloc] init];
    pStyle.alignment = NSTextAlignmentCenter;
    pStyle.lineBreakMode = NSLineBreakByClipping;
    NSDictionary *attrs = @{ NSFontAttributeName : font, NSParagraphStyleAttributeName : pStyle };
    [ch drawInRect:rect withAttributes:attrs];

    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    return newImage;
}

Adjust the font size and image size to suit your needs.
Then you can do something like this:
NSString *tabChar = @"✚"; // Unicode U+271A
UIImage *tabImg = [SomeHelperClass characterImage:tabChar];

Adjust the call to characterImage: based on where you add the method.


text:
Q: basic question about php multiple FOREACH loops I have few FOREACH loops in php;
$c1 = 1;
$c2 = 1;
$c3 = 1;

foreach ($someArray as $a){
    echo $a;
    if (sizeof($someArray != $c1){
        echo " / ";
    }
    $c1++;
}

foreach ($otherArray as $b){
    echo $b;
    if (sizeof($otherArray != $c2){
        echo ", ";
    }
    $c2++;
}

// etc.

This seems somehow stupid, of course =) Is there any way to avoid declaring variables with same values and to use them in many FOREACH loops?
Thanks in advance for any help!

A: It appears you are trying to do what the following code does much better:
$line = implode(' / ', $someArray);
echo $line;

$line = implode(', ', $otherArray);
echo $line;


text:
Q: How to make sure a daily time trigger runs? I setup two sets of scripts. One that checks conditions in a google-sheet every hour, and sends me an email if a value is above a limit. (The sheet is updated every hour through Supermetrics).
The second script resets a column I use to "timeout" a row from sending me an email again, if it already has done so this day. This script runs only once a day.
My problem is that now and then the scripts don't run. After some testing it seems to be about 20% of the times, it does'nt run.
This is not a big deal for the hour-by-hour check. But I need my daily check to run once a day (the specific time doesn't matter all that much, but I really need it to rune some time during the day).
Does anyone know of a way to make sure of this? Alternatively, do you know of a better way to "timeout" the email so it won't spam me?
Thank you.


text:
Q: Empty white screen while trying to compile and run ionic2 I am trying to create a simple HTTP post service for my login page.
For some weird reasons, i encountered errors in my app.bundle.js:

TypeError: Cannot read property 'toString' of undefined
Uncaught TypeError: Cannot read property 'getOptional' of undefined

Using ionic2 tutorial sample project, I have done the following:
In my app.js (so my service would be accessible globally)
import {HttpService} from './services/httpService';
@App({
  templateUrl: 'build/app.html',
  config: {} ,// http://ionicframework.com/docs/v2/api/config/Config/
  providers: [HttpService]
})

and set the rootPage to my login page
this.rootPage = LoginPage;

In my log-in.html
 <button  class="button button-block" (click)="loginSuccess()" style="width:70%;">
   Log In
 </button>

In my log-in.js
import {App, Page, Platform, IonicApp, NavParams, NavController} from 'ionic-angular';
import {HttpService} from '../../services/httpService';

@Page({
  templateUrl: 'build/pages/log-in/log-in.html'
})

export class LoginPage {

  constructor(nav,app,httpService) {
    this.nav = nav;
    this.app = app;
    this.httpService = httpService;
  }

  loginSuccess() {
    console.log("Invoked Method!");

       this.httpService.loginService(event.target.value).subscribe(
         data => {this.httpService = data.results; console.log(data);},
         err => this.logError(err),
         () => console.log('Invoked Login Service Complete')
       );
  }
}

httpService.JS
import { Inject } from 'angular2/core';
import { Http } from 'angular2/http';
import 'rxjs/add/operator/map';

export class httpService {
    static get parameters() {
        return [[Http]];
    }

    constructor(http) {
        this.http = http
    }

    loginService(httpService) {
      console.log("Service Function Variable: "+httpService);

    //  var body = "username=" + username + "&password=" + password+" &ipAddress="+ip;
      var body = "username=" + "admin" + "&password=" + "admin" +" &ipAddress="+"127.0.0.1";
      var headers = new Headers();
      headers.append('Content-Type', 'application/x-www-form-urlencoded');

      var url = 'http://localhost/WS/Login.asmx/Login';
      return this.http.post(url,body, {headers: headers}).map(res => res.json());

    }

}

As you can see, I'm just trying to get my services up. All I am presented is a blank white screen and errors from app.bundle.js (which is generated at compile time), yet I do not have any compile errors while compiling.

And the app.bundle.js code which have errors are:
exports.isJsObject = isJsObject;
function print(obj) {
    console.log(obj);
}

and
var inits = injector.getOptional(application_tokens_1.APP_INITIALIZER);

which I have no idea as this is generated automatically. I apologise for the code dump(I have tried to remove unnecessary stuff) as I do not know which part of it went wrong.
My ionic version is : 2.0.0-beta.25 if that helps.
Any help would be deeply appreciated.

A: Had a look at your code. I could see that you have used Headers but haven't imported them in your code. In the httpService.js file modify the import statement as shown below.
import { Http, Headers } from 'angular2/http';

app.bundle.js is simply a bundle of modules generated by webpack which is popular module loader used by Ionic.
P.S: If you are trying to implement an authentication system in your Ionic 2 application, I recommend you to have a look here.
Hope this helped you. Thanks.

A: I don't see the decorator @Injectable on your service...
export class httpService {
should be (i think, I´m using v24, maybe in v25 is different?)
import {Injectable, Inject} from "angular2/core";
@Injectable
export class httpService {


text:
Q: Firefox notificationbox onclose? How can I detect when a firefox xul notificationbox element I created is closed?
Thanks,
Ash

A: Looks like this is what you want: Either the notificationsHidden property or the events that are right below it.

A: The only way you can be sure is to create a derived binding for your notification in which case your destructor will run when the notification is closed. See for instance http://hg.mozilla.org/comm-central/annotate/edc24697f35e/suite/common/bindings/notification.xml#l1616


text:
Q: Can you make `table` behave as it was a generic function? Suppose I have an object x from class foo (representing some intervals):
x <- c("0;100", "0;20", "10;40", "10;40")
attr(x, "class") <- "foo"

table(x) orders the elements of x alphabetically:
0;100  0;20 10;40
    1     1     2

but I as default, would prefer to order x according to the length of the intervals. I expected that
table.foo <- function(x, ...) table(unclass(x), ...)[c(2, 3, 1)]
# or the sake of simplicity the way to find the ordering is not shown

leading to
table.foo(x)
0;20 10;40 0;100
   1     2     1

would do the job. Unfortunately, as far as I see it, table isn't a generic function (in contrast to e.g. plot), so running table(x) would not call table.foo(x). Is there a way to make table generic or more general: to make a function that will be called instead of table? I tried setGeneric("table", table.foo) but it seems not to be what I want: firstly, it produces infinite recursion, as table.foo will be called in every case, even if the object passed to table is not of class foo and secondly, it seems to be a local effect (on the computer running the code) for table, but not a general effect for table.foo, which shall be distributed by a package.

A: The first link to an answer on a different question, both (link and answer) provided by @duckmayr, solved the issue. So here is the hardly modified code from @duckmayr's answer:
#' My new table function
#'
#' My new table function able to handle objects of class foo.
#'
#' @param x an object
#' @param ... other arguments
#'
#' @rdname table
#' @export
table <- function(x, ...) {
    UseMethod('table', x)
}

#' @rdname table
#' @export
table.foo <- function(x, ...) {
    table(unclass(x), ...)[c(2, 3, 1)]
}

#' @rdname table
#' @export
table.default <- function(x, ...) {
    return(base::table(x, ...))
}


text:
Q: How to install magento2 sample module? How can I install sample-module-payment-gateway (https://github.com/magento/magento2-samples/tree/master/sample-module-payment-gateway) using composer?
I'm getting error "Your requirements could not be resolved to an installable set of packages.", apparently the package name is not recognised.
The documentation only says, that the component should be included in composer, but the how-to is missing?
To clarify: I'm not interested in sample data, but a sample module.

A: For now, sample modules doesn't allow to be installed via composer.
But new documentation describes how you can install it with git cloning.


text:
Q: Maximum limit for 'find / -name 'file' -o -iname 'file2' -o -iname 'file3'..." etc I am trying to organize a massive amount of files based on file extension.
My code is as follows (sorry for the length):
sudo find /malon/tyler/Desktop/test/all/ -iname '*.doc' -o -iname '*.docx' -o -iname '*.log' -o -iname '*.msg' -o -iname '*.odt' -o -iname '*.pages' -o -iname '*.rtf' -o -iname '*.tex' -o -iname '*.txt' -o -iname '*.wpd' -o -iname '*.wps' -o -iname '*.csv' -o -iname '*.dat' -o -iname '*.gbr' -o -iname '*.ged' -o -iname '*.ibooks' -o -iname '*.key' -o -iname '*.keychain' -o -iname '*.pps' -o -iname '*.ppt' -o -iname '*.pptx' -o -iname '*.sdf' -o -iname '*.tar' -o -iname '*.tax' -o -iname '*.vcf' -o -iname '*.xml' -o -iname '*.aif' -o -iname '*.iff' -o -iname '*.m3u' -o -iname '*.m4a' -o -iname '*.mid' -o -iname '*.midi' -o -iname '*.mp3' -o -iname '*.mpa' -o -iname '*.ra' -o -iname '*.wav' -o -iname '*.wma' -o -iname '*.3g2' -o -iname '*.3gp' -o -iname '*.asf' -o -iname '*.asx' -o -iname '*.avi' -o -iname '*.flv' -o -iname '*.m4v' -o -iname '*.mov' -o -iname '*.mp4' -o -iname '*.mpg' -o -iname '*.mpeg' -o -iname '*.rm' -o -iname '*.srt' -o -iname '*.swf' -o -iname '*.vob' -o -iname '*.wmv' -o -iname '*.3dm' -o -iname '*.3ds' -o -iname '*.max' -o -iname '*.obj' -o -iname '*.bmp' -o -iname '*.dds' -o -iname '*.gif' -o -iname '*.jpg' -o -iname '*.jpeg' -o -iname '*.png' -o -iname '*.psd' -o -iname '*.pspimage' -o -iname '*.tga' -o -iname '*.thm' -o -iname '*.tif' -o -iname '*.tiff' -o -iname '*.yuv' -o -iname '*.ai' -o -iname '*.eps' -o -iname '*.ps' -o -iname '*.svg' -o -iname '*.indd' -o -iname '*.pct' -o -iname '*.pdf' -o -iname '*.xlr' -o -iname '*.xls' -o -iname '*.xlsx' -o -iname '*.accdb' -o -iname '*.db' -o -iname '*.dbf' -o -iname '*.mdb' -o -iname '*.pdb' -o -iname '*.sql' -o -iname '*.apk' -o -iname '*.app' -o -iname '*.bat' -o -iname '*.cgi' -o -iname '*.com' -o -iname '*.exe' -o -iname '*.gadget' -o -iname '*.jar' -o -iname '*.pif' -o -iname '*.vb' -o -iname '*.wsf' -o -iname '*.dem' -o -iname '*.gam' -o -iname '*.nes' -o -iname '*.rom' -o -iname '*.sav' -o -iname '*.dwg' -o -iname '*.dxf' -o -iname '*.gpx' -o -iname '*.kml' -o -iname '*.kmz' -o -iname '*.asp' -o -iname '*.aspx' -o -iname '*.cer' -o -iname '*.cfm' -o -iname '*.csr' -o -iname '*.css' -o -iname '*.htm' -o -iname '*.html' -o -iname '*.js' -o -iname '*.jsp' -o -iname '*.php' -o -iname '*.rss' -o -iname '*.xhtml' -o -iname '*.crx' -o -iname '*.plugin' -o -iname '*.fnt' -o -iname '*.fon' -o -iname '*.otf' -o -iname '*.ttf' -o -iname '*.cab' -o -iname '*.cpl' -o -iname '*.cur' -o -iname '*.deskthemepack' -o -iname '*.dll' -o -iname '*.dmp' -o -iname '*.drv' -o -iname '*.icns' -o -iname '*.ico' -o -iname '*.lnk' -o -iname '*.sys' -o -iname '*.cfg' -o -iname '*.ini' -o -iname '*.prf' -o -iname '*.hqx' -o -iname '*.mim' -o -iname '*.uue' -o -iname '*.7z' -o -iname '*.cbr' -o -iname '*.deb' -o -iname '*.gz' -o -iname '*.pkg' -o -iname '*.rar' -o -iname '*.rpm' -o -iname '*.sitx' -o -iname '*.tarr' -o -iname '*.zip' -o -iname '*.zipx' -o -iname '*.bin' -o -iname '*.cue' -o -iname '*.dmg' -o -iname '*.iso' -o -iname '*.mdf' -o -iname '*.toast' -o -iname '*.vcd' -o -iname '*.c' -o -iname '*.class' -o -iname '*.cpp' -o -iname '*.cs' -o -iname '*.dtd' -o -iname '*.fla' -o -iname '*.h' -o -iname '*.java' -o -iname '*.lua' -o -iname '*.m' -o -iname '*.pl' -o -iname '*.py' -o -iname '*.sh' -o -iname '*.sln' -o -iname '*.vcxproj' -o -iname '*.xcodeproj' -o -iname '*.bak' -o -iname '*.tmp' -o -iname '*.crdownload' -o -iname '*.ics' -o -iname '*.msi' -o -iname '*.part' -o -iname '*.torrent' -o -iname '*.raw' -exec mv {} /home/malon/Desktop/test/ \;

If I leave out the -exec portion at the end of the find command, the find command works as expected. This leads me to believe it's something to do with exec, not the find part.
What this code is supposed to do:
Move any detected file up one level from ~/Desktop/test/all/ to ~/Desktop/test/
What this code actually does:
Nothing at all. No error. Looks successful, but the files are never moved.
Are you certain there's no typos?
Pretty certain, seeing as it works with a smaller number of arguments. I also build that command using a loop, lessening the chance of typos.
How did I build this command?
I wrote a bash script here: http://pastebin.com/MeQgH74X
Why have such a huge find command?
Because the actual folder I'm trying to get organized comes from a backup drive that has hundreds of thousands of folders (incremental backups) and iterating through it more than once is painfully long. I'd like to iterate the backup drive once, find the files I need as I go, move them all into a single folder, then iterate that single folder (now holding all the file types I want) and then place the files into folders based on filetype. I hope that makes sense.
Thanks guys!

A: Logical and has a higher precedence than logical or in find.
find ... \( ... -o ..... \) -exec ...


text:
Q: php object oriented overloading I came across the following code and could not figure out why the output of the script came out in a non-intuitive sequence using php's get and set magic methods.
class Magic
{
    public $a = "A";
    protected $b = array("a" => "A", "b" => "B", "c" => "C");
    protected $c = array(1,2,3);

    public function __get($v)
    {
        echo "$v";
        return $this->b[$v];
    }
    public function __set($var, $val)
    {
        echo "$var: $val";
        $this->$var = $val;
    }
}
$m = new Magic();
echo $m->a . "," . $m->b . "," . $m->c . ",";
$m->c = "CC";
echo $m->a . "," . $m->b . "," . $m->c;

Out put was:
bcA,B,C,c
CCbcA,B,C

First of all why is it no outputting A as the first thing? The sequence of output doesn't make sense.

A: Somebody is studying for their Zend certification ;-)
The reason is that magic methods are only triggered when the property is inaccessible.
So, for the first echo, it fetches $m->a this is an accessible property, so it is not echo'd from __get and is simply returned. After this, both $b and $c are inaccessible, so they are echo'd and then returned.
So the output from the first echo is:
b // echo'd by __get
c // echo'd by __get
A // simply returned, and echo'd in the concatenated string
B // (As above)
C // (As above)

A: The reason is quite simple. You do string concatenation so PHP has to prepare complete string before outputs one. It means that it executes everything that needs to be concatenated. When it executes getter (__get method will be called only for inaccessible members) there's echo that is executed first and then returned value.
If you echo them out separately everything will be on its place.

A: echo $m->a . "," . $m->b . "," . $m->c . ",";

When this line gets called, it is first resolving variable names before the concatenation takes place.
So it looks up $m->a, then $m->b, then $m->c.
Since $m->a resolves to your public property a, it doesn't trigger your _get, thus that echo in there doesn't get sent right away. However, $m->b does trigger it, which causes it to get echoed.
Finally, once the variables are resolved, the whole concatenated string gets output.