text:
Q: How to do a long press in Swift? I'm trying to implement a long press on a mapView in Swift (to achieve this)
I don't get any compiler errors but when I do the longpress in the simulator the app crashes with "unrecognized selector sent to instance"
I suspect it's something to do with selectors (similar to this) but every combination I've tried fails
I have this in viewDidLoad:
var lpgr = UILongPressGestureRecognizer(target: self, action: "action")

lpgr.minimumPressDuration = 2.0;

mapView.addGestureRecognizer(lpgr)

and this in the ViewController class:
func action(gestureRecognizer:UIGestureRecognizer) {

println("long press")

}

A: The method signature of the method:
func action(gestureRecognizer:UIGestureRecognizer) { }

Needs to include a colon for its parameter. You should be using this.
var lpgr = UILongPressGestureRecognizer(target: self, action: "action:")


text:
Q: regular expr question i'v got such string <>1 <>2 <>3
i want remove all '<>' and symbols after '<>' i want replace with such expression like www.test.com/1.jpg, www.test.com/2.jpg, www.test.com/3.jpg
is it possible to do with regex? i only know to find '/<>.?/'

A: str_replace('<>', 'www.test.com/', $input);

// pseudo code
pre_replace_all('~<>([0-9]+)~', 'www.test.com/$1.jpg', $input);

A:    preg_replace('/<>(\d+)/g', 'www.test.com/bla/$1.jpg', $input);

(assuming your replaced elements are just numbers. If they are more general, you'll need to replace '\d+' by something else).

A: Based on your example, I don't think you need regex at all.
$str = '<>1 <>2 <>3';
print_r(str_replace('<>', 'www.test.com/', $str));

A: $string = '<>1 <>2 <>3';

$temp = explode(' ',preg_replace('/<>(\d)/','www.test.com/\1.jpg',$string));
$newString = implode(', ',$temp);

echo $newString;

A: Regex's allow you to manipulate a string in any fashion you desire, to modify the string in the fashion you desire you would use the following regex:
<>(\d)
and you would use regex back referencing to keep the values you have captured in your grouping brackets, in this case a single digit. The back reference is typically signified by the $ symbol and then the number of the group you are referencing. As follows:
www.test.com/$1
this would be used in a regex replace scenario which would be implemented in different ways depending on the language you are implementing your regex replace method in.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can I pass a python function as a function pointer to a function bound through Boost.Python? So if I have a function:
void foo(void(*fn)()) {
  fn();
}

Which I've added to my Boost.Python module:
boost::python::def(&foo);

Is there any way I can make something like this work in my python script:
def my_fn():
  print 'hello'

foo(my_fn)


text:
Q: Label grow from right to left I have a label on my form which is on the right of the form. This label loads a dynamic text.
Sometimes the text that it loads is too long and the text crosses the border of the form, that is some of the text is out of the form.
I want to make the label to grow from right to left instead of left to right. How do I achieve this?

A: I solved this by setting the label
AutoSize property to false,
TextAlign to MiddleRight,
an Anchor to the right.
Notice that the label size itself is not growing with the text, but you can handle it by giving it enough width to fit the content. The visual effect is the same.

A: You can't make it "grow from right to left", but you can assign it's Left property so that it won't go out of the form:
label1.Text = "some dynamic text here...";
if (label1.Right > this.Width)
    label1.Left = this.Width - label1.Width;

If the design allows it, you can also double its height so that the text will span two lines.

A: You can use the TableLayoutPanel or other compatible container control, but instead setting RightToLeft property for the container set Dock="Right" for the label
Setting RightToLeft property does not always give the expected results as for some string formats the string is modified changing the order of the words.

A: My problem here was that my label was in a panel, and anything I did wasn't working.
What I did was to place the label in a TableLayoutPanel control and set the TableLayoutPanel's RightToLeft property to True; this did the trick.

A: you can Write it:
    public enum Leftorright { left,right}
    private Leftorright _LeftToRight = Leftorright.left;
    public Leftorright LeftToRight
    {
        get { return _LeftToRight; }
        set { _LeftToRight = value; }
    }

    protected override void OnTextChanged(EventArgs e)
    {
        int oldWidth;
        oldWidth = this.Width;
        base.OnTextChanged(e);
        if (LeftToRight == Leftorright.right && this.Width != oldWidth)
        {
            this.Left = this.Left - this.Width + oldWidth;
        }
    }

A: using System.Windows.Forms;

/// <summary>
/// The position of myLabel to the left of the otherControl component when entering
/// text "s".
/// You must set myLabel.AutoSize = true
/// </summary>
/// <param name="s">text</param>
void WriteText(string s)
{
    int len = TextRenderer.MeasureText ( s, myLabel.Font ).Width;
    myLabel.Left = otherControl.Left - 5 - len;
    myLabel.Text = s;
}

A: Wrap the label inside a FlowLayoutPanel and set the following properties in the panel:

*

*Anchor to right;

*AutoSize to GrowAndShrink;

*FlowDirection to RightToLeft


text:
Q: How to create dynamic *ngFor in angular2 I would like to create a table component. The table component needs data which is processed by *ngFor to display the rows of data. But the problem I am facing is how to send dynamic *ngFor query via input.
The reason for this is I am using the pagination filter for one table which is not used by some tables.
So when building table with pagination, ngFor would be
*ngFor="let report of reports | paginate: config"

without pagination *ngFor would be
*ngFor="let report of reports"
Any help is appreciated. I believe it could be done via *ngIf , but I believe this could be done in a more effective way?


text:
Q: Google sign in Firebase auth, show "choose account" Hello I'm using firebase and google sign in. Everything works fine, but I don't know how to show "choose account" dialog. It doesn't appear when user isn't in firebase auth users and when it is. I would like to show this dialog. This is how I create auth (it is in fragment)
    gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestIdToken(getActivity().getResources().getString(R.string.key))
            .requestEmail()
            .build();

    mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
            .enableAutoManage(((AppCompatActivity)getActivity()), this)
            .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
            .build();
  // and start activity

  Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
    startActivityForResult(signInIntent, RC_SIGN_IN);

A: That's because you didn't sign out your google account (not Firebase). Try to sign out your google account:
signOutButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        firebaseAuth.signOut();
        signInClient.signOut();        //here

        nameTextView.setText("Google Account Name");

        Toast.makeText(view.getContext(), "Sign out successfully", Toast.LENGTH_SHORT).show();
    }
});

A: This dialog appears automaticly when there are different accounts set in the device.


text:
Q: Can't access fields of a Javascript Object The following Javascript function returns a JS object:
function getCookies() {
    var result = {};
    var cookie = {};
    var cookies = document.cookie.split(';');
    for (var i = 0; i < cookies.length; i++) {
        cookie = cookies[i].split('=');
        result[cookie[0]] = cookie[1];
    }
    return result;
}

When I tried to access its fields the "easy" way, all I got was "undefined", eg:
var c = getCookies();
alert(c.a_cookie_name);
alert(c['a_cookie_name']);

The only way I could access the keys and values was iterating through the fields, eg:
for(cookieName in c){
  alert(c[cookieName]);
}

The question is how to access the fields without iterating?
Thank you.
P.S. The keys and values do exist, I can see the object fields with console.log(getCookies()) in Chrome.

A: You are properly accessing fields the problem is that hte fields you're accessing don't exist.  It' looks like the property named a_cookie_name simply doesn't exist on the object.
EDIT
Given that the Chrome console shows the properties as existing, one possibility to consider is there is white space in the names of the properties.  This could explain the difference as the white space would be hard to see in the console.  To test that out try the following.  It will make the spaces a bit more visible if they are there
for (var cookieName in c) {
  alert('"' + cookieName + '"="' + c[cookieName] + '"');
}


text:
Q: Get domain home / base address from url with IP and Port in shell script Have inputs like
url1='http://10.25.225.123:32782/actuator/health'
url2='http://10.25.225.321:12345/myappmanagement/health' and so on.
How to get only http://10.25.225.123:32782/ and http://10.25.225.321:12345 for url1 and url2 respectively using the same command?

A: url='http://10.25.225.123:32782/actuator/health'
awk -F'/' 'BEGIN{OFS=FS="/"} {print $1,$2,$3}' <<< "$url"
http://10.25.225.123:32782

or simply:
cut -d/ -f-3 <<< "$url"
http://10.25.225.123:32782


text:
Q: how to fix 'The type or namespace name 'PlayerManager' could not be found (are you missing a using directive or an assembly reference? í am trying to access the playermanager from ThirdPersonUserControl but it is not working and giving ther error
I have tried referencing but still no good
class 1
public class PlayerManager : MonoBehaviour{}
class 2
public PlayerManager manager;
    private void Start()
    {

        manager = gameObject.GetComponent<PlayerManager>();
    }

A: It is hard to tell with so little information. Ideally a compilable piece of code that people can drop into a blank project.
Do both classes/files use the same namespace? To use classes in another namespace, the file must contain a "using directive", e.g. using System; or you must use the complete name, e.g. System.Console.Write("Test"); for the Console class in the System namespace.
Are they both in the same project? Classes in different projects, or external DLLs will also need an assembly reference, in Visual Studio you can see these in the "Solution Explorer", if you expand your project and then "References", which will be at the top of the project.
Usually with Visual Studio (or other IDEs) for things like this it will underline the error in red, and can provide some hints on how to also fix it. In the case of Visual Studio, right click "Quick Actions and Refactorings..." or with the default shortcut Ctrl + . it may offer to add an using directive or an assembly reference for you automatically.


text:
Q: Running a DHCP server without conflict I have a single chip computer running ubuntu on it and I want to run a dhcp server on it to give addresses to any machine connected directly to it. Since it is a portable computer, I regularly connect it to multiple networks.
The problem is, when I connect it to a network already running a DHCP server, it results in conflict and messes up my network.
Is there any way to have the dhcp server running without it affecting the external network?
Any tips or alternative methods will be greatly appreciated!
PS: My chip doesn't support usbnet.

A: I used to catch programmers who did that on my corporate world.
Having a rogue DHCP server can really mess things up. Think, the CEO is angry and missed an important meeting with some investors, because he got on the wrong DHCP segment.
If you are lucky you can just get away with having your Port or MAC address disabled. Worst case the IT guy told the CEO exactly who was responsible for him missing his meeting, or you get slapped with a security violation.
You can get a USB ethernet stick, set the DHCP server to only give out addresses for that interface, plug in the interface when you need it. It's always good to go with the physical world.
Most of my developer would misconfigure virtual hosts, or plug in a router as a switch.
Hope this helps

A: As a network engineer, what I can tell you is that it's not your duty to protect the destination network. A healthy network should be able to prevent the unauthorized DHCP server from messing up the existing DHCP services. For example cisco has a feature called DHCP snooping.

DHCP snooping is a security feature that acts like a firewall between
  untrusted hosts and trusted DHCP servers. The DHCP snooping feature
  performs the following activities:
•Validates DHCP messages received from untrusted sources and filters
  out invalid messages.
•Rate-limits DHCP traffic from trusted and untrusted sources.
•Builds and maintains the DHCP snooping binding database, which
  contains information about untrusted hosts with leased IP addresses.
•Utilizes the DHCP snooping binding database to validate subsequent
  requests from untrusted hosts.

For detailed information, please check this link
Besides, if the destination network is using a hub which doesn't provide any security feature, your only solution might be disabling the DHCP service.


text:
Q: R: force reinstallation of package's dependencies My system installation of R is controlled by administrators, who make changes upon request from multiple users without coordination.  This causes problems for me because some packages installed in my user library interact badly with upgraded packages in the system library.  This breaks cron jobs and I have to spend time maintaining it.
When running install.packages or an equivalent, is there a way to make R ignore system-installed packages, and install all transitive dependencies in my user library?  For example, I tried running R_LIBS=/path/to/lib R but the system install is still on .libPaths(), and dependencies of my package are still not installed in my user library.

A: Oh! It looks like renv is just what I want.


text:
Q: Android Studio code doesn't work on Android Version P 9.0 Please My Android App works well in any android app version but dont work on android 9.0 ?? there is no errors display when run the code from android studio on emulator, and the problem is that the AutoCompleteTextView doesn't work, but on the other versions higher and lower work well.my code is:
AutoCompleteTextView srch_txt=(AutoCompleteTextView) findViewById(R.id.srch_txt);
        DBConnection db = new DBConnection(this);
        //SQLiteDatabase dbb = db.getWritableDatabase();//connect to MyDB
        SQLiteDatabase dbb = db.getReadableDatabase();//connect to MyDB
        final String [] mydata;
        //Inside the method you've read the cursor, loop through it and add those item to array
        String sql="SELECT * FROM revuesC";
        //execute SQL
        Cursor cr= dbb.rawQuery(sql, null);
        mydata = new String[cr.getCount()];//create array string based on numbers of row
        int i=0;
        while (cr.moveToNext()) {
            mydata[i]= cr.getString(1);
            i++;
        }
        cr.moveToFirst();
        ArrayAdapter<String> adapter = new ArrayAdapter<String>
                (this,android.R.layout.select_dialog_item,mydata);
        //Getting the instance of AutoCompleteTextView
        //AutoCompleteTextView actv =  (AutoCompleteTextView)findViewById(R.id.autoCompleteTextView);
        srch_txt.setThreshold(1);//will start working from first character
        srch_txt.setAdapter(adapter);//setting the adapter data into the AutoCompleteTextView
        cr.close();

> Blockquote

A: I resolve this issues by adding this @override method in my DBConnectionHelper:
@Override
    public void onOpen(SQLiteDatabase db) {
        super.onOpen(db);
        db.disableWriteAheadLogging();
    }


text:
Q: How can I simulate multiple specified calculation times in a multi-threaded environment? I want to simulate hundreds of calculations of let's say 100ms each in a multi-threaded environment.
Say 400 calculations of 100ms on a quad core processor (i5-3570K) should take 10s. (400/4) * 100ms.
First attempt is of course Thread.Sleep(100), but in a multi-threaded environment, this gives opportunity to other threads to do their work (which is just sleeping). But I want to keep the processor busy for 100ms, without this passing opportunity.
Second attempt was to put a lock on the current thread before doing the sleep, but that seems not to work either. Calculation time is still only 3 seconds.
I have created a test class to simulate this, but apparently I need something better than the lock on the current thread, and still I would like to specify the calculation time. Any suggestions? Can I expect desired results from different locking mechanisms?
Or should I have different expectations? CPU Utilization is low, but I don't mind/did expect that.
Here's the source code for a unit test class that I used as prototype.
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace CalculationTimeSimulator
{
    [TestClass]
    public class CalculationTimeTests
    {
        public int CalculateMeaningOfTheUniverse()
        {
            var thread = Thread.CurrentThread;

            lock (thread)
            {
                Thread.Sleep(100);
            }

            return 42;
        }

        [TestMethod]
        public void SubtleDouglasAdamsReferenceTest()
        {
            var theAnswerTo = CalculateMeaningOfTheUniverse();

            Assert.AreEqual(42, theAnswerTo);
            // Takes 103 ms, as expected with small overhead.
        }

        [TestMethod]
        public void TryIt400Times()
        {
            var items = Enumerable.Range(1, 400);

            Parallel.ForEach<int>(items, item =>
            {
                var theAnswerTo = CalculateMeaningOfTheUniverse();

                Assert.AreEqual(42, theAnswerTo);
            });
            // Took 3 sec, but I expected 10 sec on quad core processor.
        }
    }
}


text:
Q: How to load a different file than index.html in FastAPI root path? Here is a simple static FastAPI app. With this setup even though the root path is expected to return a FileResponse of custom.html, the app still returns index.html. How can I get the root path work and render custom.html?
from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles
from fastapi.responses import FileResponse

app = FastAPI()

app.mount(
    "/",
    StaticFiles(directory="static", html=True),
    name="static",
)

@app.get("/")
async def index() -> FileResponse:
    return FileResponse("custom.html", media_type="html")

A: As per Starlette documentation:

StaticFiles
Signature: StaticFiles(directory=None, packages=None, check_dir=True)

*

*html - Run in HTML mode. Automatically loads index.html for    directories if such file exists.

In addtion, as shown from the code snippet you provided, you have mounted StaticFiles to the root directory (i.e., '/'), instead of, for example, /static (or some other path name), as shown below:
from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles

app = FastAPI()

app.mount('/static', StaticFiles(directory='static'), name='static')

As per FastAPI documentation:

"Mounting" means adding a complete "independent" application in a
specific path, that then takes care of handling all the sub-paths.

Hence,  any path that starts with '/' will be handled by that StaticFiles application, and due to specifying html=True in the arguments, index.html will be automatically loaded; regardless of creating a separate endpoint pointing to the root path / and trying to return something else, as demonstrated in the example given in your question.
Important
If, for example, you moved app.mount("/",StaticFiles(... line after defining your @app.get("/") endpoint, you would see that order matters and index.html would not be automatically loaded anymore, as endpoints are evaluated in order. Note that, in your case, you might get an Internal Server Error, as your @app.get("/") endpoint would be called and attempt to find custom.html, but if this file exists under 'static' directory (as shown from your code) and not under '/', you would then get a File does not exist error, and you should instead return FileResponse('static/custom.html').
Even if you removed html=True, but keep StaticFiles mounted to the root directory (and defined before your '/' endpoint), you would get a {"detail":"Not Found"} error response when attempting to access http://localhost:8000/. This is because that request is still handled by that application (as mentioned earlier) and you should now need to specify the file that you would like to access, e.g., http://localhost:8000/index.html. Even if you defined other endpoints in your code (e.g., /register, /login, /hello)—as long as StaticFiles is mounted to the root directory (i.e., '/') and defined in your code before all other endpoints—all requests to those routes would be handled by StaticFiles application and lead to a {"detail":"Not Found"} error response.
The html=True simply provides an easy way to serve a directory of web content with just one line of code. If you only need to serve static files, such as package docs directory, then this is the way to go. If, however, you need to serve different HTML files that will get dynamically updated, as well as you wish to create additional routes/endpoints, you should have a look at Templates (not FileResponse), as well as mount your StaticFiles to a different directory (e.g., /static), rather than root directory (and without using html=True).


text:
Q: List all folders and subfolders in cmd, but not the files New to using cmd, just wanted to know is there a way to list all folders their subfolders, if any, but not the files.
e.g.D:\Movies\ dir /s /b gives me list of all files and folders located in Movies, and also its subfolders e.g. D:\Movies\Watched.
I would like to display only folders its subfolders, not their files. Is it possible?

A: Yes, this is possible as it can be read on running in a command prompt window dir /? which outputs the help for command DIR.
dir D:\Movies\* /AD /B /ON /S

This command outputs

*

*only directories because of /AD (attribute directory) including those with hidden attribute set,

*with only the names of the directories because of /B (bare format),

*with all subdirectories in a directory sorted by name because of /ON (order by name)

*of specified directory D:\Movies and all subdirectories because of /S and

*with full path of each directory also because of /S.

A small modification of the command line is needed to ignore directories with hidden attribute set:
dir D:\Movies\* /AD-H /B /ON /S

-H after /AD results in ignoring hidden directories.
See also:

*

*Microsoft's command-line reference

*SS64.com - A-Z index of the Windows CMD command line


text:
Q: Undefined array key "subject" in contact.php on line 18 I would like to send to my email the details of the users, but its not submitting the information to my mail box. How must I code it?
I tried to fix the local server, but its still failing to send, please help me on this. Thank you very much.
How can I fix the submit button?
if (!defined("PHP_EOL")) define("PHP_EOL", "\r\n");

$first_name     = $_POST['first_name'];
$last_name     = $_POST['last_name'];
$email    = $_POST['email'];
$phone   = $_POST['phone'];
$select_price   = $_POST['select_price'];
$select_service   = $_POST['select_service'];
$subject  = $_POST['subject'];
$comments = $_POST['comments'];
$verify   = $_POST['verify'];

if(trim($first_name) == '') {
    echo '
Attention! You must enter your name.
';
    exit();
}  else if(trim($email) == '') {
    echo '
Attention! Please enter a valid email address.
';
    exit();
} else if(!isEmail($email)) {
    echo '
Attention! You have enter an invalid e-mail address, try again.
';
    exit();
}

if(trim($comments) == '') {
    echo '
Attention! Please enter your message.
';
    exit();
}

if(get_magic_quotes_gpc()) {
    $comments = stripslashes($comments);
}

A: I suppose you stripped the code, so the error on line 18 refers to
$subject  = $_POST['subject'];

Double check that you do have an input named 'subject' on your page.


text:
Q: Django password field input showing up as plaintext despite forms.PasswordInput declaration Django password field input showing up as plaintext despite widget=forms.PasswordInput declaration:
forms.py
from django.contrib.auth.models import User
class LoginForm(forms.ModelForm):
    # specify password type so that passwords show up as *******, not plaintext
    # but this doesn't work if placeholder = ''
    password = forms.CharField(widget=forms.PasswordInput)

    class Meta:
        model = User
        fields = ["username", "password"]

    def __init__(self, *args, **kwargs):
        # first call the 'real' __init__()
        super(LoginForm, self).__init__(*args, **kwargs)
        # then do extra stuff:
        self.fields['username'].help_text = ''
        self.fields['password'].widget = forms.TextInput(attrs={'placeholder': ''})
        self.fields['password'].widget.attrs['class'] = 'form-control'

So interestingly, when I surface this form in a template, the password value shows up as plaintext instead of '******' text. But only if I add the 'placeholder': '' line. I inspected the form element and figured out that when I added the  'placeholder': '' line, type='password' was being changed to type='text' in the <input type='FOO'></input>element in the rendered HTML.
--> How do I keep this from happening, so passwords continue to show up as plaintext, without removing my 'placeholder': '' line?

A: You should not be using forms.TextInput for your password field. Django provides a PasswordInput widget that is more appropriate. Try this:
class Meta:
    model = User
    fields = ["username", "password"]

def __init__(self, *args, **kwargs):
    # first call the 'real' __init__()
    super(LoginForm, self).__init__(*args, **kwargs)
    # then do extra stuff:
    self.fields['username'].help_text = ''
    self.fields['password'].widget = forms.PasswordInput(attrs={'placeholder': ''})
    self.fields['password'].widget.attrs['class'] = 'form-control'

While you can edit the type of the field manually, it's better convention to use the widget.


text:
Q: Geckodriver in WSL stuck in readyState of 'interactive' I've recently switched computers and I have a script to scrape a site that I'm trying to port over, but it's not working. I'm running Mozilla Firefox 93.0, geckodriver 0.30.0 (d372710b98a6 2021-09-16 10:29 +0300) with Python 3.8.10 on Windows Subsystem for Linux
geckodriver.log is the following:
1635724994219   geckodriver INFO    Listening on 127.0.0.1:34993
1635724994224   mozrunner::runner   INFO    Running command: "/usr/bin/firefox" "--marionette" "--headless" "--remote-debugging-port" "45483" "-no-remote" "-profile" "/tmp/rust_mozprofileKcEU8P"
*** You are running in headless mode.
1635724994420   Marionette  INFO    Marionette enabled
[GFX1-]: RenderCompositorSWGL failed mapping default framebuffer, no dt
console.warn: SearchSettings: "get: No settings file exists, new profile?" (new NotFoundError("Could not open the file at /tmp/rust_mozprofileKcEU8P/search.json.mozlz4", (void 0)))
DevTools listening on ws://localhost:45483/devtools/browser/ef680f3f-d655-4d3d-86be-7287f5731e16
1635724995327   Marionette  INFO    Listening on port 38833
JavaScript error: resource://services-settings/Attachments.jsm, line 391: TypeError: / is not a valid URL.
1635724995445   RemoteAgent WARN    TLS certificate errors will be ignored for this session
1635724995448   RemoteAgent INFO    Proxy settings initialised: {"proxyType":"manual","httpProxy":"127.0.0.1:46485","sslProxy":"127.0.0.1:46485"}
1635724996122   Marionette  WARN    Ignoring event 'pageshow' because document has an invalid readyState of 'interactive'.
1635725002780   Marionette  WARN    Ignoring event 'pageshow' because document has an invalid readyState of 'interactive'.
[GFX1-]: Receive IPC close with reason=AbnormalShutdown
Exiting due to channel error.
Exiting due to channel error.
Exiting due to channel error.

while the program is repeatedly throwing the following error up on the command line.
refresh_site() 482 https://www.xkcd.com/
Message: Reached error page: about:neterror?e=nssFailure2&u=https%3A//www.xkcd.com/&c=UTF-8&d=The%20connection%20to%20the%20server%20was%20reset%20while%20the%20page%20was%20loading.
Stacktrace:
WebDriverError@chrome://remote/content/shared/webdriver/Errors.jsm:181:5
UnknownError@chrome://remote/content/shared/webdriver/Errors.jsm:488:5
checkReadyState@chrome://remote/content/marionette/navigate.js:64:24
onNavigation@chrome://remote/content/marionette/navigate.js:312:39
emit@resource://gre/modules/EventEmitter.jsm:160:20
receiveMessage@chrome://remote/content/marionette/actors/MarionetteEventsParent.jsm:42:25

I'm familiar with a fair amount of geckodriver errors from previous experience and have usually been able to fix them by reinstalling firefox and geckodriver with matching versions, but this is a new one for me and I don't know what I should do to proceed. Thoughts?
Edit:
For the record, I can initialize the webdriver without error, but when I uncomment out the lin self.driver.get(self.user_site) that resuts in an error being thrown every time.
Edit 2:
I suspect it has something to do with the commands to firefox, since on the computer where it works, the log show that it's sending the command as "/usr/bin/firefox" "--marionette" "--headless" "-foreground" "-no-remote" "-profile" "/tmp/rust_mozprofiledAb1T0" which is different from what my new computer is doing, but I don't know enough Selenium to fix that off the top of my head.
Edit 3:
I think this is a security certificate issue. I ran the following as a python script and it worked fine.
from selenium import webdriver

driver = webdriver.Firefox()
driver.get("https://dev.to")

driver.find_element_by_id("nav-search").send_keys("Selenium")

It still works when I swap in the url that I actually care for, but I get security errors when trying to open in it non-headless mode with my production code.
Edit4:
This code replicates the issue and shows that it can be fixed by changing seleniumwire to selenium
from seleniumwire import webdriver

class Foo:

    def __init__(self):
        self.web_options = webdriver.FirefoxOptions()
        self.driver = webdriver.Firefox(options=self.web_options)

    def bar(self):
        self.driver.get("https://xkcd.com")
        print(self.driver.current_url)

Foo().bar()

The actual error that's stopping seleniumwire is a AttributeError: module 'lib' has no attribute 'SSL_CTX_get0_param' error, which is caused by https://pypi.org/project/cryptography/#history being installed as version 2.8 which is two years out of date. This seems like the ultimate answer which I am working on now.

A: Turns out my cryptography package was out-of-date. I ran pip install pyopenssl which fixed the issue.


text:
Q: Highcharts incorrect pertange calculation My Highcharts Pie Chart is calculating a percentage incorrectly and I've no idea how/why.
These are the values I am passing to it (Spend vs Budget):
budget: 34319326.40
spent: 10000000.00
The correct percentage is supposed to be: 29.14% even though my chart display 22.56% as spent.
See screenshot here:

As you can see, my system's calculated percentage is correct but the one calculated by Highcharts is lower and incorrect. Below is how I pass the series data the pie chart:
series: [{
   name: 'Brands',
   colorByPoint: true,
   data: [{
       name: 'Budget',
       color: '#1e80c1',
       y: parseFloat( budget )
   }, {
      name: 'Spend',
      color: '#fdc942',
      y: parseFloat( spent )
  }]
}]

I was suspecting that maybe my parseFloat is affecting the accuracy though if I do the calculation on firebug console I get the correct result:

Does anyone know what could be causing this issue? Thanks in advance

A: It calculate base on total value

console.log((10000000.00/(34319326.40+10000000.00)*100).toFixed(2))
console.log((34319326.40/(34319326.40+10000000.00)*100).toFixed(2))


text:
Q: What is the most efficient way to sort hashes in ruby? I am trying to sort about 20 hashes in ruby based on one of the attributes of the array.  I want to only return the top 3 hash keys, but I don't want to have to compare each one.
Here is an example below of something similar to what I am trying to sort.  I want to sort based on powerrank.
["green", {:price=>24.88, :numreviews=>822, :avgStarsRank=>41.0, :reviewsrank=>28, :powerrank=>73.976}]

["steve", {:price=>14.96, :numreviews=>3, :avgStarsRank=>40.0, :reviewsrank=>0, :powerrank=>42.992000000000004}]

["joey", {:price=>40.27, :numreviews=>814, :avgStarsRank=>44.0, :reviewsrank=>28, :powerrank=>80.054}]

["board", {:price=>14.96, :numreviews=>3, :avgStarsRank=>40.0, :reviewsrank=>0, :powerrank=>47}]

["john", {:price=>40.27, :numreviews=>814, :avgStarsRank=>44.0, :reviewsrank=>28, :powerrank=>16}]

For this, all  I would want back would an array with ["joey", "green", "board"].  Any suggestions on how to tackle this issue?
Edit: Here is the example in the original hash form:
powerrankings =
    {
        "green"=>{:price=>24.88, :numreviews=>822, :avgStarsRank=>41.0, :reviewsrank=>28, :powerrank=>73.976},
        "steve"=>{:price=>14.96, :numreviews=>3, :avgStarsRank=>40.0, :reviewsrank=>0, :powerrank=>42.992000000000004},
        "joey"=>{:price=>40.27, :numreviews=>814, :avgStarsRank=>44.0, :reviewsrank=>28, :powerrank=>80.054}}
        "board"=>{:price=>14.96, :numreviews=>3, :avgStarsRank=>40.0, :reviewsrank=>0, :powerrank=>47},
        "john"=>{:price=>40.27, :numreviews=>814, :avgStarsRank=>44.0, :reviewsrank=>28, :powerrank=>16}
    }

A: Assuming that powerrankings is not as you showed but is rather,
powerrankings = {
  "green" => {:price=>24.88, :numreviews=>822, :avgStarsRank=>41.0, :reviewsrank=>28, :powerrank=>73.976},
  "steve" => {:price=>14.96, :numreviews=>3, :avgStarsRank=>40.0, :reviewsrank=>0, :powerrank=>42.992000000000004},
  "joey" => {:price=>40.27, :numreviews=>814, :avgStarsRank=>44.0, :reviewsrank=>28, :powerrank=>80.054},
  "board" => {:price=>14.96, :numreviews=>3, :avgStarsRank=>40.0, :reviewsrank=>0, :powerrank=>47},
  "john" => {:price=>40.27, :numreviews=>814, :avgStarsRank=>44.0, :reviewsrank=>28, :powerrank=>16}
}

then,
powerrankings.sort_by{|_, h| h[:powerrank]}.reverse.first(3).map(&:first)
# => ["joey", "green", "board"]


text:
Q: Invalid Argument Running Google Go Binary in Linux I've written a very small application in Go, and configured an AWS Linux AMI to host. The application is a very simple web server. I've installed Go on the Linux VM by following the instructions in the official documentation to the letter. My application runs as expected when invoked with the "go run main.go" command.
However, I receive an "Invalid argument" error when I attempt to manually launch the binary file generated as a result of running "go install". Instead, if I run "go build" (which I understand to be essentially the same thing, with a few exceptions) and then invoke the resulting binary, the application launches as expected.
I'm invoking the file from within the $GOPATH/bin/ folder as follows:
./myapp

I've also added $GOPATH/bin to the $PATH variable.
I have also moved the binary from $GOPATH/bin/ to the src folder, and successfully run it from there.
The Linux instance is a 64-bit instance, and I have installed the corresponding Go 64-bit installation.

A: go build builds everything (that is, all dependent packages), then produces the resulting executable files and then discards the intermediate results (see this for an alternative take; also consider carefully reading outputs of go help build and go help install).
go install, on the contrary, uses precompiled versions of the dependent packages, if it finds them; otherwise it builds them as well, and installs under $PATH/pkg. Hence I might suggest that go install sees some outdated packages which screw the resulting build.
Consider running go install ./... in your $GOPATH/src.
Or may be just selective go install uri/of/the/package for each dependent package, and then retry building the executable.


text:
Q: Cannot do functional test with sender address in service or environment While it is possible to create an environment variable SENDER_ADDRESS and access that in a controller, the address is not available in a functional test. This is due to the \tests directory being at the same level as \src. In an environment service EnvService:
use Symfony\Component\Dotenv\Dotenv;

class EnvService
{
    public function mailSender() {
        $dotenv = new Dotenv();
        $dotenv->load('../.env');
        $sender = getenv('SENDER_ADDRESS');

        return $sender;
    }
}

then in a controller:
    public function invite(Request $request, \Swift_Mailer $mailer, EnvService $env)
    {
        $invite = new Invitation();
        $form = $this->createForm(InvitationType::class, $invite);
        $form->handleRequest($request);
        if ($form->isSubmitted() && $form->isValid()) {
            $invitation = $request->request->get('invitation');
//            $sender = $this->get('mailer.sender_address');
            $sender = $env->mailSender();
...

the email will be sent.
But in a functional test this error occurs:

Unable to read the "../.env" environment file

If instead swiftmailer.yaml is modified to includesender_address: 'admin@bogus.info' the error

Service "swiftmailer.sender_address" not found: the container inside
  "App\Controller\RegistrationController" is a smaller service locator

I've tried multiple variations on the theme of adding a SwiftMailer service in services.yaml without success. The most recent iteration is:
swiftmailer:
    class: 'Swift_Mailer\Swift\Mailer'
    sender_address: 'admin@bogus.info'
    public: true


text:
Q: Possibility to get content of urls with headers and write it to a file (python 3.7) I have multiple urls that differ in query strings parameters, maily in days, for instance:
urls = [f'https://example.com?query=from-{x+1}d+TO+-{x}d%data' for x in range(10)]
I want to write the content of all these urls to just one file. I tried with urllib.requests:
import urllib.request

key = "some value"
requests = urllib.request.Request([url for url in urls], headers={"key":key})
<urllib.request.Request object at 0x7f48e8381490>

but the first pitfall is that 'Request' object is not iterable
responses = urllib.request.urlopen([request for request in requests])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'Request' object is not iterable

Ideally the result could go to a file as below:
data = open('file_name', 'a')
data.write([response.read() for response in responses])

I also tried with requests lib
import requests
test = requests.Session()
r = test.get([url for url in urls], headers={"key":key})

but this fails with
    raise InvalidSchema("No connection adapters were found for '%s'" % url)
requests.exceptions.InvalidSchema: No connection adapters were found for <list of urls>

Is there a way to get the content of these urls with headers and to send it to a file?

A: I suppose you might want to do something like this:
import urllib.request

with open("file_name", "a") as data:
    for url in urls:
        req = urllib.request.Request(url, headers={"key": "key"})
        with urllib.request.urlopen(req) as response:
            html = response.read()
            data.write(html)


text:
Q: An elementary question on Markov chain We consider the Markov chain $\left(X_{n}\right)_{n\geq0}$
  on $\left\{ 1,2,3,4,5\right\}$
  with transition matrix
$P=\left(\begin{array}{ccccc}
1/2 & 1/2 & 0 & 0 & 0\\
1/2 & 1/2 & 0 & 0 & 0\\
0 & 0 & 1 & 0 & 0\\
0 & 0 & 1/2 & 1/2 & 0\\
1/2 & 0 & 0 & 0 & 1/2
\end{array}\right)$
Set $\tau:=\textrm{inf}\left\{ n\geq1\left|X_{n}=1\right.\right\} $
 . Compute $\mathbb{P}_{5}\left[\tau=n\right]$
  and $\mathbb{E}_{5}\left(\tau\right)$
 .
EDIT: We have $\mathbb{P}_{5}\left[\tau=1\right]=\mathbb{P}_{5}\left[X_{1}=1\right]=1/2$ so by induction we get $\mathbb{P}_{5}\left[\tau=n\right]=\mathbb{P}_{5}\left[X_{n}=1,X_i \neq1 \forall i=1,...,n-1\right]=(1/2)^n$. But how to compute $\mathbb{E}_{5}\left(\tau\right)$?
I'm a freshmen of this subject. Help me. Thanks a lot.

A: $$\mathbb{P}_{5}\left[\tau=1\right]=\mathbb{P}_{5}\left[X_{1}=1\right]=1/2$$
$$\mathbb{P}_{5}\left[\tau=n\right]=\mathbb{P}_{5}\left[X_{n}=1,X_{i}\neq1\forall i=1,...,n-1\right]=(1/2)^{n}$$
Since $$\sum_{n=1}^{\infty}nx^{n}=\frac{x}{\left(1-x\right)^{2}}$$
  we get that
$$\mathbb{E}_{5}\left(\tau\right)={\displaystyle \sum_{i=1}^{+\infty}i}\mathbb{P}_{5}\left[\tau=i\right]={\displaystyle \sum_{i=1}^{+\infty}i}\left(\dfrac{1}{2}\right)^{i}=\dfrac{1/2}{\left(1-1/2\right)^{2}}=2$$


text:
Q: Select function and table columns on a single SQLAlchemy query I did some searching but couldn't find any examples.
Is there a way to query multiple columns from both tables and a function call while using SQLAlchemy Core?
This is the query I want to achieve:
SELECT
    t.id, t.field_1, t.field_2,
    some_function(t.field_2, t.field_3).*
FROM my_table t

Where some_function is a function that returns a 3-tuple, say calc_field_1, calc_field_2 and calc_field_3
The resulting set should be a table like so:

id
field_1
field_2
calc_field_1
calc_field_2
calc_field_3

1
...
...
...
...
...

2
...
...
...
...
...

3
...
...
...
...
...

A: If it is possible to change original SQL to this
SELECT
    t.id, t.field_1, t.field_2,
    calc_field_1, calc_field_2, calc_field_3
FROM my_table t, some_function(t.field_2, t.field_3);

then it's possible to express on Sqlalchemy Core
stmt = (
    select([
        my_table.c.id,
        my_table.c.field_1,
        my_table.c.field_2,
        column('calc_field_1'),
        column('calc_field_2'),
        column('calc_field_3')
    ])
    .select_from(my_table)
    .select_from(func.some_function(my_table.c.field_2, my_table.c.field_3))
)

Currently (as of Sqlalchemy 1.3) docs suggest that here. Sqlalchemy 1.4 (in beta) should provide table valued functions

If you can't move the function to the FROM-clause, then..
from sqlalchemy import literal_column
from sqlalchemy.sql.expression import Grouping
stmt = (
    select([
        my_table.c.id,
        my_table.c.field_1,
        my_table.c.field_2,
        Grouping(
            func.some_function(my_table.c.field_2, my_table.c.field_3)
        ).op('.')(literal_column('calc_field_1')).label('calc_field_1'),
        Grouping(
            func.some_function(my_table.c.field_2, my_table.c.field_3)
        ).op('.')(literal_column('calc_field_2')).label('calc_field_2'),
        Grouping(
            func.some_function(my_table.c.field_2, my_table.c.field_3)
        ).op('.')(literal_column('calc_field_3')).label('calc_field_3'),
    ])
    .select_from(my_table)
)

it will produce the following SQL
SELECT t.id, t.field_1, t.field_2,
  (some_function(t.field_2, t.field_3)) . calc_field_1 AS calc_field_1,
  (some_function(t.field_2, t.field_3)) . calc_field_2 AS calc_field_2,
  (some_function(t.field_2, t.field_3)) . calc_field_3 AS calc_field_3
FROM my_table t

And a shorthand operation:
from sqlalchemy.sql import functions

class some_function(functions.GenericFunction):
    def __getitem__(self, key):
        return Grouping(self).op('.')(column(key, String))

stmt = (
    select([
        my_table.c.id,
        my_table.c.field_1,
        my_table.c.field_2,
        some_function(my_table.c.field_1, my_table.c.field_2)['calc_field_1'].label('calc_field_1'),
        some_function(my_table.c.field_1, my_table.c.field_2)['calc_field_2'].label('calc_field_2'),
        some_function(my_table.c.field_1, my_table.c.field_2)['calc_field_3'].label('calc_field_3'),
    ])
    .select_from(my_table)
)

Solution is taken from here, checked with postgresql


text:
Q: Use vodafone easy-box umts-stick slot for usb network drive I own a Vodafone DSL-EasyBox 602 as router for my home wlan. This device includes a USB-UMTS-Stick Slot for mobile internet. I don't use this USB slot and was wondering, if I could use this USB Slot for running a network HD. In the extras section of my routers page, it says, that this slot is for use of an USB-UMTS-Stick, but I guess it should somehow be possible to access the file system as well?
Has anyone already experience with this or something similar? If not, could someone briefly outline, why it is most likely not possible?


text:
Q: signed applet blocked on webbrowser with reverse Proxy ('Unknown Source') I'm having problems to deploy a signed applet (certificate from a trusted CA) on a new webserver. It is running fine on my old webserver, but when I transfer it to the new host, it is blocked by Java security settings.
I deploy it like this in my html file:

my MANIFEST file contains the following lines:
Manifest-Version: 1.0
Application-Name: Example Name
Permissions: sandbox
Caller-Allowable-Codebase: *.example.com http://ab123.wwwdns.example.com http://other.example.com
Codebase: *.example.com http://ab123.wwwdns.example.com http://other.example.com
Application-Library-Allowable-Codebase: *.example.com http://ab123.wwwdns.example.com http://other.example.com
Entry-Point: db.main.ExApplet

(previously I tried it with only specifying *.example.com but this did not work either)
I guess the problem is related to the fact that the applet can now be accessed by two different URLs (ab123.wwwdns.example.com and other.example.com)?
Here is an excerpt from the Java Console (Java 8 Update 71 build 15 Plugin on Firefox):
java.lang.reflect.InvocationTargetException
...
Caused by: com.sun.deploy.security.BlockedException: Your security settings have blocked an untrusted application from running
    at com.sun.deploy.security.BlockedDialog.show(Unknown Source)
    at com.sun.deploy.security.SandboxSecurity.checkRunUntrusted(Unknown Source)
    at
com.sun.deploy.security.SandboxSecurity.checkUnsignedSandboxSecurity(Unknown Source)
...

Any hints are welcome!

A: I finally resolved my problems; I found out that the 'Unknown Source' Error was due to the fact that external libraries I use could not be found. This is weird, as I used the exact same architecture for accessing the external libraries as I did on the old server, but on the new server this did not work for some (to me unknown) reason.
Here a list of changes that I made to make the Applet work during my research and now it's running perfectly fine, hopefully this will help others who have problems with deploying their applets as well:

*

*I removed the codebase attribute from my html file

*I used the wildcard *.example.com in my MANIFEST file

*I moved all external libraries to the same folder as ExampleApplet.jar and additionally did not add them to the ExampleApplet.jar file anymore

*previously I had a dot (.) in my Class-Path attribute, which I also removed

html file

MANIFEST file
Manifest-Version: 1.0
Application-Name: Example Name
Permissions: sandbox
Caller-Allowable-Codebase: *.example.com
Codebase: *.example.com
Application-Library-Allowable-Codebase: *.example.com
Class-Path: external1.jar external2.jar
Entry-Point: db.main.ExApplet

(previously the Class-Path had looked like this and the external libraries where located under lib/ and additionally within ExampleApplet.jar):
Class-Path: . lib/external1.jar lib/external2.jar


text:
Q: How to get out of edit mode in CircuitMaker? When I edit a PCB in CircuitMaker, I start laying out tracks on both upper and bottom layer.
So far so good. Sometimes, I want to stop, and press Escape. Mostly this works, sometimes, I have to press twice, or three times.
When selecting an item, sometimes trace mode is still enabled, sometimes not.
But I had already twice in a few hours, that I cannot get out of a mode that keeps creating tracks. I cannot get even out of the black screen (see below). I cannot reach the menu, the left pane, or the window below. It just keeps scrolling.
Actually, as I'm writing this (using Alt-Tab I had to change application), it is still scrolling, and it will do so until I with TaskManager kill the application and lose (again) some work.
How can I get out of edit mode when the Escape key does not work?
(If I keep getting problems with CircuitMaker, my next question might be: how to convert a CircuitMaker to KiCad?.)

A: Right-click on an empty area. Right-clicking is a sort of way to exit either placing a trace, or the currently selected tool in both CircuitMaker and Altium Designer.

A: In Altium Designer it is the right mouse button, but I'm not sure about CircuitMaker. They switched around a lot of the basic controls for no well-explained reason. The Esc key is always my go-to for cases like this - it is mostly universal and doesn't require clicking on just the right area with the mouse pointer.


text:
Q: Expand child elements height outside parents I am trying to expand three divs with fixed heights outside of a parent div that spans full-width. But I want them to expand outside the parent's height, not width.
Similar to the picture below:

What would be the best way to do this?
Here is the basic HTML for it.

1

2

3

A: Here is one approach.
Apply transform: scaleY(1.2) to the .container element, and displace the scaling by adding transform: scaleY(0.8) to the children elements.
Example Here

.background {
    background: #000;
    height: 100px;
    margin: 1em 0;
}
.container {
    transform: scaleY(1.2);
    height: inherit;
}
.container > div {
    width: 28%;
    height: 100%;
    background: #f88;
    margin: 0 2.6666667%;
    float: left;
    text-align: center;
    font-size: 4em;
    line-height: 100px;
    color: #fff;
}
.container > div > .inner {
    transform: scaleY(0.8);
}

1

2

3

A: if I understand what you are asking correctly, you can just do something as to:
.container{
      overflow-y:visible;
      overflow-x:hidden;
}


text:
Q: Div hide not working I am trying to hide code when email checkbox is not checked.

{{ _('Email setup') }}

<form class="form-horizontal" id="enclosure_settings_email">

            <input id="enableemail" type="checkbox" data-bind="click: $parent.emailUI()">  {{ _('Email Enable') }}

            {{ _('Email From') }}

                <input type="text" class="input-block-level" data-bind="value: emailFrom">
                The addeess the email will come from

            {{ _('To Email') }}

                <input type="text" class="input-block-level" data-bind="value: emailTo">
                The addeess the email will sent to

            {{ _('CC Email') }}

                <input type="text" class="input-block-level" data-bind="value: emailCC">
                The addeess the email send copy to

            {{ _('SMTP Server') }}

                <input type="text" class="input-block-level" data-bind="value: emailServer">
                The SMTP server to send email to:

            {{ _('SMTP Server Port') }}

                <input type="text" class="input-block-level" data-bind="value: emailPort">
                The SMTP server Port

            {{ _('Send Image') }}

                <input type="checkbox" data-bind="checked: include_snapshot">{{ _('Send Image') }}
                To send image at the end of print job

            {{ _('SMTP SSL') }}

                <input id="emailSSL" type="checkbox" data-bind="click: $parent.emailsslUI()">  {{ _('Enable SSL') }}
                The Enable SSL

                {{ _('SMTP User Name') }}

                    <input type="text" class="input-block-level" data-bind="value: emailUser">
                    Name to login SMTP

                {{ _('SMTP Password') }}

                    <input type="password" class="input-block-level" data-bind="value: emailPassword">
                    Password to login SMTP

        {{ _('Send Test Email') }}

            <button data-bind="click: eventEmail">Test Email</button>

            Send test email ckeck your email

I have the button out of 1st div as can see/call the function or how do I call the function?
I have tried adding settings.plugins.enclosure etc did not
     /**********************************************
    emailsslUI
    ***********************************************/
    self.emailsslUI = function(){
      if($('#emailSSL').is(':checked')){
         $('#isSSLEmailEnabled').show("blind");
      }else{
        $('#isSSLEmailEnabled').hide("blind");
      }
    };
    /**********************************************
    eventEmail
    ***********************************************/
    self.eventEmail = function(data,event) {
        $.ajax({
            type: "GET",
            url: "/plugin/enclosure/getEnclosureEmail",
            async: false
        });
    }
    /**********************************************

How do I get this to work?

A: I found the answer removed div so a part min and added $root.
<button data-bind="click: $root.eventEmail">Test Email</button>

How working OK


text:
Q: call a method of object from another class I have three classes, the first class makes a box on screen and there is a method to screen capture the contents of the box. In the second class several boxes are instantiated and in the third class there is a jframe with a button. When the button is pressed I want to call the captureComponent method but just for one  specific box which has been created. I am new to Java and I have been really struggling to see how I can achieve this. I have been staring at this code for several days. I think that it will be something simple. All the individual classes work fine and ideally the class arrangement should stay as it is.
I have created the following code to demonstrate the issue I am having. It is a simplified representation of my actual code, as otherwise it would be too big to put on SO. The line I am having trouble with is Box.a.captureComponent(); in the Button class.  What is the correct way to call the method of one particular object from a different class?
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;

public class Box {

    public Box() {
        // Code to displays a transparent box on screen with a border
    }

    public void captureComponent()  {
       // This method screen captures whats displayed in the box
    }
}

public class Object_Instantiate {

      // In this class two boxes are created a & b

        Box a = new Box();
        Box b  = new Box();

}

public class Button {

    /*In this class there is a button. When I press it I want to call
    the captureComponent method but just for box a*/

    public static void main(String[] args) {
        // Code to create JFrame with button would go here

        btnSnap.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent event) {
                JButton clickedButton = (JButton) event.getSource();
                if (clickedButton == btnSnap) {

                    //CaptureComponent method of just Box a
                    Box.a.captureComponent();

                }
            }
        });
    }

}

A: Box doesn't have any static a of type Box, so you can't use Box.a.captureComponent();.
you need to create an instance of Box then call captureComponent(), since it is a instance method.
ex :
Box b  =new Box();
b.captureComponent();

A: Ok, first of all you need only one main function, that's the point where your program starts. Then you can create objects with Box BoxName = new Box(); in the main. After that you can handle the object with BoxName.captureComponent();
Maybe it's helpful to read some stuff about classes.


text:
Q: Applying increment to ternary operator in C I thought that the ternary operator returns either a value on the left side or the right side of : depending on the condition. Why does this following piece of code print 1?
#include <stdio.h>

int main(int argc, char const *argv[]) {
  int c = 0;
  (c?c:0)++;
  printf("%i", c);
  return 0;
}

A: You would appear to have a compiler bug, or perhaps a language extension, since this is not valid C.  You need an lvalue in order to apply the ++ operator, and (c?c:0) is not an lvalue.

A: I've just run across some oddness related to this, too.  It seems that the result of a ternary conditional can be treated as an lvalue in gcc 3.3.2, but not in gcc 4.6 (I haven't got more versions ready to hand to narrow it down further).  In fact it's not possible to compile gcc 3.3.2 using gcc 4.6 precisely because gcc 4.6 is much pickier about what constitutes an lvalue.
Another example from the gcc 3.3.2 source that doesn't compile with gcc 4.6:
char *x = ...;
*((void**)x)++ = ...;

gcc 4.6 could treat the result of a cast as an lvalue and increment it, but gcc 4.6 will not.
I also don't have the relevant standards to hand to find out of this is something that changed in the official standard or just something that gcc allowed at some stage.
Note also that C++ allows the ternary operator to return an lvalue, though you still can't increment 0.  So this is valid C++ but not valid C:
int c = 0, d = 0;
(c?c:d)++;

A: Simply because you are doing
(c?c:0)++;

If you don't let "++" happen, you will get what you want.
#include <stdio.h>

int main(int argc, char const *argv[]) {
  int c = 0;
  /*  (c?c:0)++;  */
  printf("%i \n", (c?c:0)++ );
  return 0;
}

output is:
$ gcc -o ternary ternary.c
$ ./ternary
0

gcc version 4.4.3 (Ubuntu 4.4.3-4ubuntu5)


text:
Q: Is this always true about symmetric relations? Statement : If $R_1$ and $R_2$ are both symmetric, then $R_1 \cap R_2$ is
symmetric.
Is this always true? As far as I could understand this with an example, suppose I have a set $A = \{1,2,3\}$
And $R_1$ and $R_2$ be symmetric relations
where,
$R_1$ = $\{(1,2),(2,1)\}$ and $R_2$ = $\{(1,3),(3,1)\}$, then the statement turns out to be false. Am I right?

A: A relation, say $R_1$ or $R_2$, is symmetric if for any ordered pair $(x,y)$ in that relation, then (what?).
Take any point $(x,y)$ in $R_1\cap R_2$.   When given that $R_1, R_2$ are symmetric, can you show that (what?)?

 In the case where the intersection is empty, this is vacuously true.


text:
Q: How to set the 'where' clause on a field with comma-seperated values? I have a db table with a field with values stored in the value1,value2,value3,value4 format.
I want to find all the rows where this field contains a defined value, eg. value3.
How can I perform a query to search a value in a field like this one?

A: use FIND_IN_SET()
SELECT  *
FROM    tableName
WHERE   FIND_IN_SET('value3', 'comma separated value here') > 0

*

*SQLFiddle Demo
SOURCE

*

*MySQL FIND_IN_SET
Description from MySQL Docs:

Returns a value in the range of 1 to N if the string str is in the
  string list strlist consisting of N substrings. A string list is a
  string composed of substrings separated by "," characters. If the
  first argument is a constant string and the second is a column of type
  SET, the FIND_IN_SET() function is optimized to use bit arithmetic.
  Returns 0 if str is not in strlist or if strlist is the empty string.
  Returns NULL if either argument is NULL.

A: You can do this using like:
where concat(',', field, ',') like '%,value3,%'

A: SELECT  *
FROM tableName
WHERE lower('comma separated values') LIKE 'value3'


text:
Q: Problems decoding XML in go I have a question regarding unmarshalling of XML in Go.
I have been trying to unmarshal this piece of XML
<?xml version="1.0" encoding="UTF-8"?>
<response>
        <folders>
                <folder id="78" name="Test 1" />
                <folder id="95" name="Test 2" />
                <folder id="96" name="Test 3" />
        </folders>
</response>

These are my structs
type XmlResponse struct {
    Folders     []Folder   `xml:"folders"`
}

type Folder struct {
    XMLName    xml.Name `xml:"folder"`
    Id   int    `xml:"id,attr"`
    Name string `xml:"name, attr"`
}

For some reason, Go won't unmarshal each folder into an array of folders, as defined in the struct. Instead i get the message
  "expected element type <folder> but have <folders>"

As you can see, i have added xml:"folders" to the list of folders, but it still won't recognize it correctly. I have tried to place the XMLName attributes in different places but i either end up with the above error, or just an empty XmlResponse struct. I have also tried to make a Folders struct containing an array of Folders, with the same result. Am i conceptually missing something regarding XML decoding? Are the names maybe a little too close to eachother?
I have made an example on Go playground that shows the issue: http://play.golang.org/p/XRCGVNzO_O
Thank you very much.

A: You need to change the xml:"folders" meta to xml:"folders>folder" to match the folder elements inside the folders element.
See this modified playground example.


text:
Q: Find out if query exceeds arbitrary limit using ROWNUM? I have a stored proc in Oracle, and we're limiting the number of records with ROWNUM based on a parameter. However, we also have a requirement to know whether the search result count exceeded the arbitrary limit (even though we're only passing data up to the limit; searches can return a lot of data, and if the limit is exceeded a user may want to refine their query.)
The limit's working well, but I'm attempting to pass an OUT value as a flag to signal when the maximum results were exceeded. My idea for this was to get the count of the inner table and compare it to the count of the outer select query (with ROWNUM) but I'm not sure how I can get that into a variable. Has anyone done this before? Is there any way that I can do this without selecting everything twice?
Thank you.
EDIT: For the moment, I am actually doing two identical selects - one for the count only, selected into my variable, and one for the actual records. I then pass back the comparison of the base result count to my max limit parameter. This means two selects, which isn't ideal. Still looking for an answer here.

A: You can add a column to the query:
select * from (
  select . . . , count(*) over () as numrows
  from . . .
  where . . .
) where rownum <= 1000;

And then report numrows as the size of the final result set.

A: You could use a nested subquery:
select id, case when max_count > 3 then 'Exceeded' else 'OK' end as flag
from (
 select id, rn, max(rn) over () as max_count
 from (
    select id, rownum as rn
    from t
  )
  where rownum <= 4
)
where rownum <= 3;

The inner level is your actual query (which you probably have filters and an order-by clause in really). The middle later restricts to your actual limit + 1, which still allows Oracle to optimise using a stop key, and uses an analytic count over that inner result set to see if you got a fourth record (without requiring a scan of all matching records). And the outer layer restricts to your original limit.
With a sample table with 10 rows, this gets:
        ID FLAG
---------- --------
         1 Exceeded
         2 Exceeded
         3 Exceeded

If the inner query had a filter that returned fewer rows, say:
select id, rownum as rn
from t
where id < 4

it would get:
        ID FLAG
---------- --------
         1 OK
         2 OK
         3 OK

Of course for this demo I haven't done any ordering so you would get indeterminate results. And from your description you would use your variable instead of 3, and (your variable + 1) instead of 4.

A: In my application I do a very simple approach. I do the normal SELECT and when the number of returned rows is equal to the limit then the client application shows LIMIT reached message, because is it very likely that my query would return more rows in case you would not limit the result.
Of course, when the number of rows is exactly the limit then this is a wrong indication. However, in my application the limit is set mainly for performance reasons by end-user, a typical limit is "1000 rows" or "10000 rows", for example.
In my case this solution is fully sufficient - and it is simple.
Update:
Are you aware of the row_limiting_clause? It was introduced in Oracle 12.1
For example this query
SELECT employee_id, last_name
  FROM employees
  ORDER BY employee_id
  OFFSET 5 ROWS FETCH NEXT 10 ROWS ONLY;

will return row 6 to row 16 of the entire result set. It may support you in finding a solution.
Another idea is this one:
SELECT employee_id, last_name
FROM employees
UNION ALL
SELECT NULL, NULL FROM dual
ORDER BY employee_id NULLS LAST

When you get the row where employee_id IS NULL then you know you reached the end of your result-set and no further records will arrive.

A: Select the whole thing, then select the count and the data, restricting the number of rows.
with
base as
(
    select c1, c2, c3
    from table
    where condition
)
select (select count(*) from base), c1, c2, c3
from base
where rownum < 100


text:
Q: Keep track of Thread in Executor Service First of: I'm not that familiar with Threading in general, though I know some of the basics (atleast, I think).
Now, after using the ExecutorService to create a FixedThreadPool, is it possible to keep track of a certain 'position' in this threadpool?
Example:
Create a new threadpool:
ExecutorService es = Executors.newFixedThreadPool(5);
Start some threads:
for (int i = 0; i < 10; i++) {
    es.execute(new Runnable()); //Implementation does not matter
}

Now, what will happen is that 5 threads will get executed, while the other 5 will be queued. Let's say the 3rd started thread is done, so the ExecutorService starts a task thread to top up the maximum of 5 threads again.
Is there a possible way of getting the new thread on that previously third position? Or in what order do threads get executed when the service has room for more threads.
I'd like to know this, because I want to implement some kind of 'thread table', in which you can see which Threads are running and which aren't (something similar to a task manager, but way less technical/advanced, just for a simple webcrawler).
Thanks in advance and please, don't blame me if this is a very 'noobish' or stupid question, as I have little experience with Threading and would just like to know whether this is possible.

A:
so the ExecutorService starts a new thread to top up the maximum of 5 threads again.

No, it keep the same 5 threads running until you shutdown the pool, even if those threads have nothing to do.

Is there a possible way of getting the new thread on that previously third position?

With a ThreadFactory you can create each thread as needed, e.g. to change the thread name, or make it a daemon.  As I mentioned there isn't one created, so you won't be told.

Or in what order do threads get executed when the service has room for more threads.

The pool creates 5 threads before you have any jobs, and they keep running.  There is no free slots as such.

I'd like to know this, because I want to implement some kind of 'thread table', in which you can see which Threads are running and which aren't (something similar to a task manager, but way less technical/advanced, just for a simple webcrawler).

I suggest using VisualVM.  It shows you all the thread which are running/blocking/waiting etc.  Giving your threads meaningful names is useful. ;)

[how to detect when it] "execute a new task".

You can sub-class the ThreadPoolExecutor.  It has two methods
 protected void beforeExecute(Thread t, Runnable r)

which will let you know when a thread is about to start a Runnable and
 protected void afterExecute(Runnable r, Throwable t)

which is called when a task has finished.


text:
Q: How to give type hint to a class that inherits from Generic class I have a Generic class in Python that is declared the following way:
class BaseClass(Generic[T]):
   def my_func(self):
      pass

There are 3 class that inherit from this Generic class:
class ClassA(BaseClass[Dog]):
   ...

class ClassB(BaseClass[Cat]):
   ...

class ClassC(BaseClass[Horse]):
   ...

Now I want to write a function with an argument that can be one of the 3 classes above.
I tried to write:
def my_func(my_arg: BaseClass):
   my_arg.my_func()

However, mypy throws the error:
 error: "BaseClass" not callable  [operator]

Do you have any idea what type hint to give to my_arg?

A: you can either use Union as mentioned in the answer above [answer 1], or (in case you have a lot of classes) create a new typeVar [answer 2] :
answer 1 :
from typing import Union

def my_func(my_arg: Union[ClassA, ClassB, ClassC]):
    ...

answer 2 :
from typing import Union, NewType

GenericType = NewType('GenericType', Union[ClassA, ClassB, ClassC])

def my_func(my_arg: GenericType):
    ...

A: from typing import Union

def my_func(my_arg: Union[ClassA, ClassB]):
    my_arg.my_func()


text:
Q: Integrals, intermediate value theorem question f∈c[a,b] (f is continuous in [a,b]), prove:
We tried to use the integral intermediate value theorem to try to prove it but we don't understand why the limit has to be the max and not any other value of f.
Thanks

A: Below follows an answer like the one here, but maybe with easier terminology. I will update if I find a simpler argument.
Let $M=\max_{x\in[a,b]}|f(x)|$ (which exist since $f$ is continuous and $[a,b]$ is compact).
To show $\leq$, note that, since $|f(x)|\leq M$ for all $x\in[a,b]$,
$$
\Bigl(\int_a^b |f(x)|^t\,dx\Bigr)^{1/t}\leq \Bigl(\int_a^b M^t\,dx\Bigr)^{1/t}=M(b-a)^{1/t}.
$$
In the limit $t\to+\infty$, we have $(b-a)^{1/t}\to 1$, and hence (one could do this more precise if needed)
$$
\lim_{t\to+\infty}\Bigl(\int_a^b |f(x)|^t\,dx\Bigr)^{1/t}\leq M=\max_{x\in[a,b]}|f(x)|.
$$
To show $\geq$, we let $0<\epsilon<M$ ($\epsilon$ arbitrary, but fixed below), and divide the interval into two disjoint parts,
$$
I_1=\{x\in[a,b]~:~|f(x)|\geq M-\epsilon\}
$$
and
$$
I_2=[a,b]\setminus I_1=\{x\in[a,b]~:~|f(x)|<M-\epsilon\}.
$$
Now, by throwing away the $I_2$ part, and using the fact that $|f(x)|\geq M-\epsilon$ when $x\in I_1$,
$$
\Bigl(\int_a^b |f(x)|^t\,dx\Bigr)^{1/t}
\geq \Bigl(\int_{x\in I_1}|f(x)|^t\,dx\Bigr)^{1/t}
\geq \Bigl(\int_{x\in I_1}(M-\epsilon)^t\,dx\Bigr)^{1/t}.
$$
The integrand in the right integral is constant, and thus can be calculated to be
$$
(M-\epsilon)\mu(I_1)^{1/t},
$$
where $\mu(I_1)$ denotes the measure (think: total length, in the case you are not familiar with measure theory) of $I_1$. Since $\mu(I_1)>0$, taking the limit as $t\to+\infty$,
$$
\lim_{t\to+\infty}\mu(I_1)^{1/t}=1,
$$
and hence
$$
\lim_{t\to+\infty}\Bigl(\int_a^b |f(x)|^t\,dx\Bigr)^{1/t}\geq M-\epsilon.
$$
The wanted inequality follows by letting $\epsilon\to0^+$.


text:
Q: Port 80 stopped responding using Ubuntu 18.04 on Compute Engine I am using Ubuntu 18.04 on GCP Compute Engine.
A simple go lang server listens to port 80 and responds to browser requests.
I was able to connect to the server on the Internet for a day.  I stopped the instance couple of times and started. Now port 80 doesn't respond any more and browser times out.
When I start the program, there are no errors reported and my println statement in server faithfully prints a message "listening to port 80".
How can I troubleshoot this problem? Is there a problem with port 80 on Ubuntu?
Also ssh stopped responding. I can only use the web console.
Any help will be appreciated.

A: Unless you assign your instance a static IP address, your instance has an ephemeral IP address. Stopping your instance releases an ephemeral address. When you start your instance again you are assigned a new address.
The solution is either to use the new IP address or to change the address to be static.

*

*Go to the Google Cloud Console -> Compute Engine.

*Make a note of the external IP address.

*Go to VPC Network -> External IP addresses.

*Locate the IP address assigned to your instance. Under the type column, click on
"Ephermal" and change to "Static".


text:
Q: How to change pythonpath to use Python 3.9 and venv I am trying to get to grips with Python on my Mac running OS X 10.15.7 Catalina.
My goal is to be able to run a program requiring Python 3.9 and associated libraries, in its own virtual environment, using venv.
My quest has led me over many rocky paths and blind alleys - including via Anaconda and Brew.
I am running zsh - specifically oh-my-zsh ys version. If that's important. Most online forums and tutorials assume bash. I would prefer to do all in zsh to avoid having to edit both zsh and bash profiles.
Current Shell Outputs
$ python -V
Python 2.7.16

$ which python
/usr/bin/python

$ python3 -V
Python 3.8.2

$ which python3.8
python3.8 not found

$ which python3.9
python3.9 not found

$ python3 -m -V
/Library/Developer/CommandLineTools/usr/bin/python3: No module named -V

Pausing there ..
Py 2.7 is the OS X system Python and I don't want to do anything with it.
It is odd that python3 -m returns a reference to the CLI tools. See below. The only location for py3.8 is in the CL tools.
What pythons do I have (output below is edited so as to show only main directories and Files)?
$ locate python
/Applications/LibreOffice.app/Contents/Frameworks/LibreOfficePython.framework/Versions/3.7/bin/python3
/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/bin/python3.8
/Library/Developer/CommandLineTools/SDKs/MacOSX10.15.sdk/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python
/Library/Developer/CommandLineTools/usr/bin/python3.8
/Library/Frameworks/Python.framework/Versions/3.9/bin/python3
/Library/Frameworks/Python.framework/Versions/3.9/bin/python3-config
/Library/Frameworks/Python.framework/Versions/3.9/bin/python3.9
/Library/Frameworks/Python.framework/Versions/3.9/bin/python3.9-config
/Library/Frameworks/Python.framework/Versions/3.9/share/man/man1/python3.1
/Library/Frameworks/Python.framework/Versions/3.9/share/man/man1/python3.9.1
/Library/Frameworks/SAVI.framework/Versions/A/Frameworks/Python.framework/Versions/3.6/lib/python3.6
/usr/bin/python
/usr/bin/python-config
/usr/bin/python2
/usr/bin/python2.7
/usr/bin/python2.7-config
/usr/bin/python3
/usr/bin/pythonw
/usr/bin/pythonw2.7
/usr/lib/libpython.dylib
/usr/lib/libpython2.7.dylib
/usr/lib/python2.7
/usr/local/bin/python3
/usr/local/bin/python3-config
/usr/local/bin/python3.9
/usr/local/bin/python3.9-config
/usr/share/file/magic/python
/usr/share/man/man1/python.1
/usr/share/man/man1/python2.7.1
/usr/share/man/man1/pythonw.1
/usr/share/man/man1/pythonw2.7.1
/usr/share/vim/vim81/autoload/python3complete.vim
/usr/share/vim/vim81/autoload/pythoncomplete.vim
/usr/share/vim/vim81/ftplugin/python.vim
/usr/share/vim/vim81/indent/python.vim
/usr/share/vim/vim81/syntax/python.vim
/usr/share/zsh/5.7.1/functions/_bpython
/usr/share/zsh/5.7.1/functions/_python
/usr/share/zsh/5.7.1/functions/_python_modules

WHAT ABOUT PIP?
$ pip3
WARNING: pip is being invoked by an old script wrapper. This will fail in a future version of pip.
Please see https://github.com/pypa/pip/issues/5599 for advice on fixing the underlying issue.
To avoid this problem you can invoke Python with '-m pip' instead of running pip directly.

$ pip3 install --upgrade pip
WARNING: pip is being invoked by an old script wrapper. This will fail in a future version of pip.
Please see https://github.com/pypa/pip/issues/5599 for advice on fixing the underlying issue.
To avoid this problem you can invoke Python with '-m pip' instead of running pip directly.
Defaulting to user installation because normal site-packages is not writeable
Requirement already satisfied: pip in ./Library/Python/3.8/lib/python/site-packages (20.3.3)

Note two points

*

*Although the wrapper warning comes up, PIP 20.3.3 is latest version which I have upgraded. Probably the reason for the warning is in the next lines, which suggest that PIP3 is being invoked from the CL Tools.

2; The 'normal site-packages is not writeable' error is supposed to be cured by specifying the Path. I have tried already to specify the correct path - see below - but this has not cured the problem and is another major reason for asking the question at the end of this post.
$ python -m pip
/System/Library/Frameworks/Python.framework/Versions/2.7/Resources/Python.app/Contents/MacOS/Python: No module named pip

$ python3 -m pip
Usage:
  /Library/Developer/CommandLineTools/usr/bin/python3 -m pip <command> [options]

$ which pip3
/usr/bin/pip3

$ locate pip3
/Applications/LibreOffice.app/Contents/Frameworks/LibreOfficePython.framework/Versions/3.7/bin/pip3
/Applications/LibreOffice.app/Contents/Frameworks/LibreOfficePython.framework/Versions/3.7/bin/pip3.7
/Library/Developer/CommandLineTools/usr/bin/pip3
/Library/Developer/CommandLineTools/usr/bin/pip3.8
/Library/Frameworks/Python.framework/Versions/3.9/bin/pip3
/Library/Frameworks/Python.framework/Versions/3.9/bin/pip3.9
/usr/bin/pip3
/usr/local/bin/pip3
/usr/local/bin/pip3.9

SYSTEM FILES
~/.zprofile contents - edited a few times to remove references to virfualenv and penv, both originally installed with brew and now removed. I have run brew uninstall and brew remove to try to clean everything up but may not have succeeded.
Start
# THIS FILE COMMENTED OUT RH 21DEC20
## Setting PATH for Python 3.9
## The original version is saved in .zprofile.pysave. **Note in this post only - cannot find this file**

PATH="/Library/Frameworks/Python.framework/Versions/3.9/bin:${PATH}"
export PATH  **Note in this post only - this does not seem to have worked - see above Python3 -V**

# export WORKON_HOME=~/.virtualenvs
# mkdir -p $WORKON_HOME
# . ~/.pyenv/versions/3.9.0/bin/virtualenvwrapper.sh
# eval "$(pyenv init -)"

# # AND THESE LINES ADDED FOLLOWING STACKOVERFLOW Q 33216679  **Note in this post only - commented out as shell threw errors .'cannot find virtualenvwrapper.sh**

# export WORKON_HOME=$HOME/.Envs
# # export VIRTUALENVWRAPPER_PYTHON=$/usr/bin/python3
# export VIRTUALENVWRAPPER_PYTHON=$/usr/local/bin/python3
#source $HOME/.local/bin/virtualenvwrapper.sh

END
Finally a word about Brew. Many tutorials advised the use of Brew to install Python, pyenv, and libraries etc. I did that and successfully created a test environment, but could not the utilise it. I have then removed as much as possible in order to get back to a 'clean' state to work with.
Current brew status is
$ brew doctor

Please note that these warnings are just used to help the Homebrew maintainers
with debugging if you file an issue. If everything you use Homebrew for is
working fine: please don't worry or file an issue; just ignore this. Thanks!

Warning: Unbrewed dylibs were found in /usr/local/lib.
If you didn't put them there on purpose they could cause problems when
building Homebrew formulae, and may need to be deleted.

Unexpected dylibs:
  /usr/local/lib/libdvdcss.2.dylib
  /usr/local/lib/libfuse.0.dylib
  /usr/local/lib/libulockmgr.0.dylib

Warning: Unbrewed header files were found in /usr/local/include.
If you didn't put them there on purpose they could cause problems when
building Homebrew formulae, and may need to be deleted.

Unexpected header files:
  /usr/local/include/ulockmgr.h

Warning: Unbrewed .la files were found in /usr/local/lib.
If you didn't put them there on purpose they could cause problems when
building Homebrew formulae, and may need to be deleted.

Unexpected .la files:
  /usr/local/lib/libulockmgr.la

Warning: Unbrewed static libraries were found in /usr/local/lib.
If you didn't put them there on purpose they could cause problems when
building Homebrew formulae, and may need to be deleted.

Unexpected static libraries:
  /usr/local/lib/libfuse.a
  /usr/local/lib/libulockmgr.a

SUMMARY
My first goal is to set Py3.9.x as default for new projects. I think also this would require/imply that pip and other commands run from v3.9 and not any other version or location. Must admit to being hazy about that.
Then I want to be able to create a virtual environment into which I can put the program I want to run and its associated libraries and packages. Doing this implies using terminal, but I need to know which directory I need to be in to run which commands.
At this point I have also been running into confusion with tutorials on how to create a virtual environment. From what I have read I think I should use venv over pyenv. What is not clear is whether I run the venv command (s) from root, or whether I have to create and cd to a different location, and if so what.
Any help in
1   Changing the default Python to 3.9
2   Creating a venv to use v3.9.
3   What commands to run where.
Will be greatly appreciated. Please keep it simple and don't assume any prior knowledge!

A: This is what I would do :
# For 1 Changing the default python to 3.9
cd /usr/local/bin
sudo ln -fs /Library/Frameworks/Python.framework/Versions/3.9/bin/python3.9 python3
sudo ln -fs python3 python

# And make sure /usr/local/bin is before (/usr/bin and /Library/Developer/CommandLineTools/usr/bin) in your $PATH

# For 2 Creating a venv to use v3.9
/usr/local/bin/python3.9 -m venv /tmp/python3.9-venv


text:
Q: Php select default dropdown based on dynamic dropdown Building an edit users form for my system and having a little trouble trying to figure out how to do a  selected="selected" for the value in the dropdown that goes with the users information in the database.
This is my code: http://pastebin.com/EVdUfTzN
The names of the offices are stored in one table called offices and the value of the office that the patient went to is stored in patients. Basically I want to select the information from both tables and add a selected option on it.
Here is picture of the offices table

Here is a picture of the patients table

Do you understand what i am trying to do? Maybe even simplify it so its one query with INNER JOIN

A: Try this (replace lines 25-29):
<?php
while ($dd_loc_row = mysql_fetch_array($dd_loc_result)) {
    echo "<option value=\"" . $dd_loc_row['office_id'] . "\"".($row['pat_loc'] == $dd_loc_row['office_id'] ? ' selected="selected"' : '').">" . $dd_loc_row["office_name"] . "</option>";
}
?>


text:
Q: How can we pass a CSV file using HTTP request methods from an angular application to a node application running on a server I have created a front-end application in angular, and using HTTP service methods to send request to a server (containing node.js code). At front-end, I have created a csv file which is saved in the same directory of the angular component. I want to send the file to the server (containing node.js code) using HTTP service methods. I have created following code:
Code of client side (front-end side), developed in angular.js:
uploadCSVFileOnServer(){
    let file = new File([""], "./abc.csv"));
    let formData = new FormData();
    formData.append("userForm", file);
    let userData = {
        firstName : "ABC",
        lastName : "DEF",
        userFormData: formData
    }

    this.http.post('url', userData)
    .subscribe(()=>{
        console.log("File uploaded successfully");
    })
}

Now http.post() methods send request to a method (getFile()) written in node.js running on a server. The node.js code (server side code) is as follows:
getFile(req, res){
    let file = req.body.userData.userFormData ;
    // PROBLEM: 'file' is an empty object here
}

My doubt is that, from client side I have sent a javascript object which also contains the FormData object (with key userFormData). But when I try to fetch the FormData object in getFile() method at server side , I get an empty object which is also not of type FormData.
What is the problem? Is FormData.append() not working at client side?

A: The FormData object is an exotic object that can not be POSTed as a property of a JavaScript object.
Instead append JSON data to the FormData object:
uploadCSVFileOnServer(){
    let file = new Blob([""], {type: "application/csv"});
    let formData = new FormData();
    formData.append("csvFile", file, "abc.csv");
    let userData = {
        firstName : "ABC",
        lastName : "DEF",
        //userFormData: formData
    }
    formData.append("userData", JSON.stringify(userData));

    this.http.post('url', formData)
    .subscribe(()=>{
        console.log("FormData uploaded successfully");
    })
}


text:
Q: Procreation with several genders Most mathematicians are aware that our species consists of two genders,
denoted for simplicity by the multisets $\lbrace X,X\rbrace$ and $\lbrace X,Y\rbrace$, with
offspring given by $\lbrace A,B\rbrace$ for $A\in\lbrace X,X\rbrace$
and $B\in \lbrace X,Y\rbrace$.
I am asking for the existence of combinatorial structures generalizing this construction.
More precisely, given a finite set $\mathcal C$ of $n$ distinct elements
($n=2$ and $\mathcal C=\lbrace X,Y\rbrace$ in the above example) and an integer $k$, we denote by $\mathcal M_k$ the set of all multisets containing exactly
$k$ not necessarily distinct elements of $\mathcal C$.
A gender partition of a subset $\mathcal S\subset \mathcal M_k$ is a partition of $\mathcal S$ into $k$ non-empty parts $\mathcal G_1,\dots,\mathcal G_k$ called genders such that the following two conditions hold:
(i) Given $(g_1,\dots,g_k)\in\mathcal G_1\times \dots
\times \mathcal G_k$, every element $(x_1,\dots,x_k)\in g_1\times \dots\times g_k$ gives rise to a multiset $\lbrace x_1,\dots,x_k\rbrace$ which is in $\mathcal S$.
(ii) Every multiset $g\in\mathcal S$ is of the form $\lbrace x_1,\dots,x_k\rbrace$
for $(x_1,\dots,x_k)\in g_1\times \dots\times g_k$ where $g_i\in
\mathcal G_i$ are suitable elements.
Examples with $\mathcal C=\lbrace X,Y\rbrace$ are:
(a) $\mathcal S= \lbrace X,X\rbrace\cup \lbrace X,Y\rbrace$ with $\mathcal G_i$
given by singletons.
(b) $\mathcal S= \lbrace \lbrace X,X\rbrace,\lbrace Y,Y\rbrace\rbrace
\cup \lbrace X,Y\rbrace$ with $\mathcal G_1=\lbrace \lbrace X,X\rbrace,\lbrace Y,Y\rbrace\rbrace$ and $\mathcal G_2$ consisting of $\lbrace X,Y\rbrace$.
(c) An example with $k=3$ (easily generalizable to arbitrary values of $k$)
is given by $\mathcal S=\lbrace \lbrace X,X,X\rbrace,\lbrace X,X,Y\rbrace,
\lbrace X,Y,Y\rbrace\rbrace$ with $\mathcal G_i$ given by singletons.
More examples of gender partitions $\mathcal S=\mathcal G_1\cup
\dots\cup \mathcal G_k$ are fairly easy to construct. (And there are fairly easy
notions for "products", "quotients", one can split an element of $\mathcal C$
into several new elements, etc.)
The following additional condition is more difficult to satisfy:
Call a gender partition $\mathcal S=\mathcal G_1\cup \dots\cup\mathcal G_k$
balanced if $\mathcal S$ admits a stationary probability measure
$\mu$ giving equal weight $\frac{1}{k}$ to all genders $\mathcal G_i$.
A probability measure $\mu$ on $\mathcal S$ is stationary if
the probabiliy $\mu(\lbrace x_i,\dots,x_k\rbrace)$ of every offspring
of $(g_1,\dots,g_k)$ (with respect to uniform choices for $x_i\in g_i$)
is proportional to $\prod_{i=1}^k\mu(g_i)$. (Stationary probability
measures exist always and are unique if $\mathcal S$ is
minimal in some sense.)
Example: The examples (a) and (b) above are balanced, (c) is not balanced.
Question: Produce other examples of balanced gender partitions.
Is there for example a balanced gender partition for $k=3$?
Remark: One can also consider probabilities on offsprings
which depend on the choice of $x_i\in g_i$. Example (c) is not balanced
even in this more general framework.
Variation: Instead of working with multisets, one can also work with
sequences of length $k$. An offspring of $k$ sequences
$g_1=(g_1(1),\dots,g_1(k)),\dots,g_k=(g_k(1),\dots,g_k(k))$ with
$g_i\in\mathcal G_i$ is then given by
$g_1(\sigma(1)),\dots,g_k(\sigma(k))$ where $\sigma$ is a (not necessarily arbitrary) permutation of
$\lbrace 1,\dots,k\rbrace$.

A: So, I hope I understand the definitions correctly.  Here's a way to construct an example with $k = 3$ genders (say A, B and C) using $n = 9$ sex chromosomes, which I will take to be the elements of $\mathbb{Z}/9\mathbb{Z}$: start with all 165 multisets of chromosomes unused.  Choose any unused multiset $\{x, y, z\}$, and add it, together with the multisets $\{x + 3, y + 3, z + 3\}$ and $\{x + 6, y + 6, z + 6\}$, to gender A, add the multisets $\{x + 1, y + 1, z + 1\}, \{x + 4, y + 4, z + 4\}, \{x + 7, y + 7, z + 7\}$ to gender B and add the multisets $\{x + 2, y + 2, z + 2\}, \{x + 5, y + 5, z + 5\}, \{x + 8, y + 8, z + 8\}$ to gender C.  Continue until every multiset of chromosomes is used up.  The resulting genders (each consisting of 55 multisets of chromosomes) are symmetric and so (if I'm not mistaken) are balanced.
It's easy to see how to construct a wide variety of similar gender partitions for given $k$ if we may choose $n$ appropriately.  These partitions have nice symmetry and use all possible multisets of chromosomes.  This says nothing at all about, say, constructing gender partitions for $n = 2$ (though I believe that I've confirmed by case analysis that there are no balanced gender partitions for $k = 3$ and $n = 2$).


text:
Q: Please explain (p ∧ q) --> r and what the correct method to work this out is I understand P ∧ Q, being that both must be equivalent, ie True & True, or False and False.
I understand P --> Q implies that if P is True we know what Q is and if Q is true then the result is True, if P is True and Q is False then the result is False, if P is False we do not know what Q is and assume it to be true.
So for (P ∧ Q) --> R, does this mean I do P && Q first and use those results as P as though I was doing P --> Q and R being Q.
I used a calculator online and it showed me this as the answer but I didn't understand it:
p   q   r   ((p ∧ q) → r)
--------------------------
F   F   F       T
F   F   T       T
F   T   F       T
F   T   T       T
T   F   F       T
T   F   T       T
T   T   F       F
T   T   T       T

So looking at the first row, p=F and q=F therefore p∧q is True?, r is False therefore the last column should be False no? Why is it True?
Or is the result true only when both are in fact True, not just equivalent?
F ∧ F = F?

A: Some overarching ideas:

*

*You could treat $P \land Q$ as a single statement.

*

*Thus for example you could look at $S \implies R$. Determine the truth value table for that.

*From there you can expand said table by looking at $S$'s truth values when $S$ is $P \land Q$.

*$P \land Q$ is only true if both $P,Q$ are.

*$X \implies Y$ does not require that $X,Y$ are both true, just that a false implication does not follow from truth.

*

*That is to say, truth implies truth. This, $X$ true and $Y$ true give $X \implies Y$ truth.

*$X$ false implies nothing about $Y$ necessarily, so $Y$ could be true or false. Implication is predicated on the precedent being true. Thus if $X$ is false, $X \implies Y$ is true outright.

*If $X$ is true and $Y$ is false, then obviously $X \implies Y$ is untrue.

Let $S$ represent the truth value for $P \land Q$ under this premise then. Then for the statement $S \implies R$ we get the usual truth table:
$$\begin{array}{cc|c}
S & R & S \implies R \\
\hline
T & T & T                           \\
T & F & F                           \\
F & T & T                           \\
F & F & T
\end{array}$$
What's the truth table for $S$, i.e. $P \land Q$?
$$\begin{array}{cc|c}
P & Q & P \land Q \\
\hline
T & T & T                           \\
T & F & F                           \\
F & T & F                           \\
F & F & F
\end{array}$$
Combining the two, then,
$$\begin{array}{cc|c|c|c}
P & Q & S = P \land Q & R & S = P \land Q \implies R \\
\hline
T & T & T & T & T \\
F & T & F & T & T \\
T & F & F & T & T \\
F & F & F & T & T \\
T & T & T & F & F \\
F & T & F & F & T \\
T & F & F & F & T \\
F & F & F & F & T
\end{array}$$

In summary:
Whenever the precedent $P \land Q$ is true but $R$ is false is the only case when the implication $P \land Q \implies R$ is false, because of how implication works from a logical perspective (it's reliant only on the truth of the precedent). In all other cases, we claim the implication to be true, since either the implication holds or the precedent is false and so has no bearing on the implication.
From there, we consider the circumstances under which the precedent $P \land Q$ is false or true, consider its effects on the implication, and make our truth table from there.

A: The only way to falsify $(p \land q) \to r$ is to make $p \land q$ true and $r$ false. So in the truth table there will be all true except when $p,q$ are true and $r$ false.

A: Maybe the problem comes from the fact you do not recognize the structure of the statement due to the fact that the antecedent is not an atomic formula.
Your main statement is a conditional.
The structure of a conditional is always  :
         ANTECEDENT  --> CONSEQUENT

The internal structure of the antecedent ( considered alone) or of the consequent ( considered alone) never affects the structure of the whole conditional, nor its truth-conditions.
The only requirement is that both " antecedent" and " consequent" be propositions, well formed formulas.
A proposition, a well formed formula, need not be an atomic sentence ( though it also can be an atomic one).
For example the whole biconditional formula : ( A <--> ( (B v ~ C) --> D )  )
can perfectly play the role of antecedent or of consequent in a conditional statement.
The method to determine the possible truth values of the whole conditional is always the same ( the only changes from one conditional to another will be the number of lines in your truth table, depending on the number of atomic sentences involved  in the antecedent and the consequent):
(1) compute the possible truth values of the whole antecedent ( however complex the formula  may be)
(2) compute the possible truth values of the consequent ( however complex...)
(3) compute the possible truth values of the whole conditional using the truth-table of the " if .. then " operator.


text:
Q: How can I bulk import into galleries? I have a large number of photo galleries in a database-driven site that I want to migrate into WordPress.  I can get the metadata and associations out of the database.
Is there a way to bulk import the photos into WordPress and generate photo galleries?

A: So I don't think it was an elegant solution, but this is what I did. I wrote a plugin that:

*

*Looped through the galleries in the old database

*Created a post for each gallery (I chose to use the envira gallery plugin) in the format used by a sample envira gallery post

*Looped through all the images in each old gallery and attached them to the new gallery post with appropriate metadata


text:
Q: How to get Bootstrap's affixed navlist style? I've been playing around with Bootstrap for sometime. While I've always been able to get everything working. I've been considering it for an upcoming project which requires an affixed side-nav exactly like the one present in the Twitter Bootstrap doc.
I've even tried to include these classes to my  element.

Any bootstrap mavens here who could help me figure out what I'd need to add to get these up and working. Also, I've been unable to get the chevrons to display exactly as done over there, my chevrons always get mashed up together with the text.

A: Have you remembered to turn it on in JS?
They use:
$('#navbar').affix()

, but you'll need to change the selector to whatever your need.
Ah, now you've rephrased what you want!
They have another class on that called .bs-docs-sidenav
.bs-docs-sidenav {
    width: 228px;
    margin: 30px 0 0;
    padding: 0;
    background-color: #fff;
    -webkit-border-radius: 6px;
    -moz-border-radius: 6px;
    border-radius: 6px;
    -webkit-box-shadow: 0 1px 4px rgba(0,0,0,.065);
    -moz-box-shadow: 0 1px 4px rgba(0,0,0,.065);
    box-shadow: 0 1px 4px rgba(0,0,0,.065);
}

They then add a class called active to the li, then specify the behaviour of that here:
.bs-docs-sidenav > .active > a {
    position: relative;
    z-index: 2;
    padding: 9px 15px;
    border: 0;
    text-shadow: 0 1px 0 rgba(0,0,0,.15);
    -webkit-box-shadow: inset 1px 0 0 rgba(0,0,0,.1), inset -1px 0 0 rgba(0,0,0,.1);
    -moz-box-shadow: inset 1px 0 0 rgba(0,0,0,.1), inset -1px 0 0 rgba(0,0,0,.1);
    box-shadow: inset 1px 0 0 rgba(0,0,0,.1), inset -1px 0 0 rgba(0,0,0,.1);
}

So in short, that isn't a built in function of bootstrap.

A: I had the same problem and could not get mine to work until found this include on the bootstrap documents page.
http://twitter.github.com/bootstrap/assets/js/application.js
!function ($) {

  $(function(){

    var $window = $(window)

    // Disable certain links in docs
    $('section [href^=#]').click(function (e) {
      e.preventDefault()
    })

    // side bar
    $('.bs-docs-sidenav').affix({
      offset: {
        top: function () { return $window.width() <= 980 ? 290 : 210 }
      , bottom: 270
      }
    })
  })
}(window.jQuery)

so adding the code abode while copying and pasting the bootstrap afix navigation should take care of the issue.

A: To get the same effect as the one on the github.io page you need the full css they added

include this in your template or html and follow the bootstrap side navigation format:

 Overview

 Transitions

          ....

      ....