text:
Q: Ways of defining a recursive function that counts right-parentheses in a string I'm trying to find a more elegant way of defining a recursive function on $\{(,)\}$ that counts right-parentheses in a string.
Let $r$ be a function on $\{(,)\}$ defined recursively, such that:

*

*$r(\lambda) = 0$, and

*$r(sx) = r(s) + 1$, if x is symbol )

*$r(sx) = r(s)$, if x is symbol (

I have also found another way of saying the same thing:
Leg r be a function  $\{(,)\}$ defined recursively, such that:

*

*$r(\lambda) = 0$, $r\left(\mathbf(\right) = 0$, $r\left(\mathbf)\right) = 1$, and

*$r(sx) = r(s) + r(x)$, where x is a symbol

Is the last example correct? Is there anybody who can recommend a better way of defining this?

A: The two definitions are equivalent.  I agree with the commenter that the first form is more intuitive.
The only change I could suggest would be a typesetting/presentation change to the following:

Define $r(s)$ recursively by $r(\lambda) = 0$, and $$r(sx) =
\begin{cases}
r(s) +1 & \text{if } x=\mathbf{)}\\
r(s) & \text{otherwise}
\end{cases}$$
  (where $x$ is a character/symbol)

By using "otherwise" instead of "if $x=\mathbf($", it is abundantly clear that $\mathbf{)}$ is the only character we care about.  This also extends the definition to work for larger alphabets than $\{(, )\}$.


text:
Q: How to change Content Security Policy by meta tag? I build a MERN app in which I used Stripe for payments but when I upload it over heroku the following error comes:

I tried to set Content Security Policy meta tag in header of index.html as
  <meta http-equiv="Content-Security-Policy" content="default-src *; script-src *; img-src *; connect-src * ; style-src *; font-src * ">

Even then I got the same error while I set script-src to '*'.
I have also used helmet to set headers as:
app.use(
  helmet()
);

Please just some ways to remove this error.

A: You can't relax a CSP by adding another one, by adding another one the result can only become stricter. You need to identify where and how the preexisting CSP is set and modify it to allow whatever you need to run.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Deserializing a value with ktor than can be either a JsonPrimitive or a JsonArray I am using Ktor for deserialization in my project. I have a json-object that is containing a dynamic value-field, and I am not quite sure how to handle it. Here are some example of the values:
"value":["test","rest"]
------------------------
"value":"test"
------------------------
"value":true

Any suggestions on how I can best handle this?

A: You can represent it as a list of String values but in this case, there is no way to differentiate true and false values. If you need the result in only one place then you can inline the following code there.
val client = HttpClient(OkHttp) {
    install(ContentNegotiation) {
        json()
    }
}

val response = client.get("/")
val obj = response.body<JsonObject>()

val values: List<String> = when(val json = obj["value"]) {
    is JsonPrimitive -> {
        when {
            json.isString -> listOf(json.toString()) // JSON string is a list with a single value
            json.booleanOrNull != null -> emptyList() // JSON boolean is an empty list
            else -> error("Expected a string or boolean")
        }
    }

    is JsonArray -> json.map { el -> // JSON array is a list of strings
        if (el is JsonPrimitive && el.isString) {
            el.toString()
        } else {
            error("Expected an array of strings")
        }
    }

    else -> error("Expected an array or primitive value")
}

println(values)


text:
Q: How to use JavaScript to control the movement of a div Below is my code. There is a blue outlined ball with a white interior inside of a black rectangle css canvas. I'm looking to move this ball left, right, up and down using the arrow keys without being able to push the ball pass the boundaries of the black space. It works perfectly if you only tap the arrow key once in a consecutive direction but if you were to hold any of the arrow keys down it goes beyond the boundaries I have set in place to stop it from going past the black space. The function "topStop();" is one of 8 functions that I'm using to hinder the ball from exiting the black space but I'm kinda at a road block when it comes when someone holds the arrow keys down.

      <title>Animating Text</title>

topTracker

leftTracker

A: OK figured out a way to bypass the computers logic in regards to rerunning the code that forces it off the black space. the code is as follows (first i will post the modifications and then i will post entire code page)
***MODIFCATIONS***

if (topY < 1) {
topY = 0;
Y.style.top = topY;
};

if (topY > 500) {
topY = 500;
Y.style.top = topY;
};

if (leftX < 1) {
leftX = 0;
Y.style.leftX = leftX;
};

if (leftX > 920) {
leftX = 920;
Y.style.leftX = leftX;
};

***ENTIRE CODE***

<title>Portfolio</title>

topTracker

leftTracker


text:
Q: Unable to stop the timer created using AbstractAjaxTimerBehavior I am working on a single page wicket application. When ever user clicks on a Navigation Item a new Tab is opened. The requirement was to have two types of Panels one a normal one and another an Auto refresh panel.
I have a TabPanel class which extends from Panel which actually contains all the Tabs and methods to manage tabs like add, remove, set current.
Following is the customer timer that I have added to TabPanel.
private class AutoRefreshTimer extends AbstractAjaxTimerBehavior {
    public AutoRefreshTimer(Duration updateInterval) {
        super(updateInterval);
    }
    @Override
    protected void onTimer(AjaxRequestTarget target) {
        Tab currentTab = getCurrentTab();
        if(currentTab != null) {
            if(currentTab.getPanel() instanceof AutoRefreshPanel) {
                AutoRefreshPanel ajaxRefreshPanel = (AutoRefreshPanel) currentTab.getPanel();
                ajaxRefreshPanel.onRefresh(target);
            }
        }
    }
}

Following is the method to added the timer 'autoRefreshTimer' which is an instance variable in TabPanel class.
private void addNewAutoRefreshTimer(final Duration autoRefreshInterval) {
    autoRefreshTimer = new AutoRefreshTimer(autoRefreshInterval);
    add(autoRefreshTimer);
}

Following are the methods to control the timer:
public void startAutoRefreshTimer(final AjaxRequestTarget target, final Duration autoRefreshInterval) {
    if(!autoRefreshTimer.isStopped())
        addNewAutoRefreshTimer(autoRefreshInterval);
    autoRefreshTimer.restart(target);
}

public void stopAutoRefreshTimer(final AjaxRequestTarget target, final Duration autoRefreshInterval) {
    if(autoRefreshTimer.isStopped())
        addNewAutoRefreshTimer(autoRefreshInterval);
    autoRefreshTimer.stop(target);
}

public void toggleAutoRefreshTimer(final AjaxRequestTarget target){
    Tab currentTab = getCurrentTab();
    if(currentTab != null) {
        if(currentTab.getPanel() instanceof AutoRefreshPanel) {
            AutoRefreshPanel ajaxRefreshPanel = (AutoRefreshPanel)currentTab.getPanel();
            this.autoRefreshInterval = ajaxRefreshPanel.getAutoRefreshInterval();
            startAutoRefreshTimer(target, this.autoRefreshInterval);
            return;
        }
    }
    stopAutoRefreshTimer(target, this.autoRefreshInterval);
}

The timer starts and stops in my local server when ever the user switches between the tabs either opening a new, or switch to already opened, close current which selects the previous tab, or close another tab without switching from current.
But when I test the same in our staging server which is in a remote location, the timer fails in following scenario.
Following is the step which creates the issue in Remote:
1. Open two Normal tabs.
2. Open a tab containing AutoRefreshPanel.
3. Close 1st or 2nd normal tab by keeping the tab containing AutoRefreshPanel active/current. This expect the timer to be
fired/running.
4. Switch to the remaining Normal tab. This stops the timer in local server but not in Remote.

Apart from the above mentioned step in all other scenarios the timer starts and stops as expected in both local and remote.
// UPDATE: I found a fix for this issue. But not sure is it the best one. Following is the changes that I have made:
private class AutoRefreshTimer extends AbstractAjaxTimerBehavior {
    public AutoRefreshTimer(Duration updateInterval) {
        super(updateInterval);
    }
    @Override
    protected void onTimer(AjaxRequestTarget target) {
        Tab currentTab = getCurrentTab();
        if(currentTab != null) {
            if(currentTab.getPanel() instanceof AutoRefreshPanel) {
                AutoRefreshPanel ajaxRefreshPanel = (AutoRefreshPanel) currentTab.getPanel();
                ajaxRefreshPanel.onRefresh(target);
                return; // added return
            }
        }
        stop(target); // added a call to stop method.
    }
}

// Replaced startAutoRefreshTimer, stopAutoRefreshTimer and toggleAutoRefreshTimer with the following method:
public void manageAutoRefreshTimer(final AjaxRequestTarget target){
    Tab currentTab = getCurrentTab();
    if(currentTab != null) {
        if(currentTab.getPanel() instanceof AutoRefreshPanel) {
            AutoRefreshPanel ajaxRefreshPanel = (AutoRefreshPanel)currentTab.getPanel();
            this.autoRefreshInterval = ajaxRefreshPanel.getAutoRefreshInterval();
            if(!autoRefreshTimer.isStopped())
                addNewAutoRefreshTimer(autoRefreshInterval);
            autoRefreshTimer.restart(target);
        }
    }
}


text:
Q: Is it possible to execute REPAST model immediately from the IDE Is it possible to run my simulation directly without seeing the GUI? All I am interested in are console output data, so there is no need for me to interact with a GUI to play, pause or reset my simulation.

A: Yes, it is. The easiest way to do this is to run it as a batch model (even if you only run one run at a time).
If you're using the standard distribution with Eclipse and have created projects as described in the docs, you will have a Run configuration called Batch <your_model_name> model If you run this, you'll launch in batch mode - input parameters will be taken from a batch file you write as a one off job (or as often as you want to change parameters).
See this documentation for more information on how to set up and run batch models.


text:
Q: Applying a function to a custom type in F# On my journey to learning F#, I've run into a problem I cant solve. I have defined a custom type:
type BinTree =
  | Node of int * BinTree * BinTree
  | Empty

I have made a function which takes a tree, traverses it, and adds the elements it visits to a list, and returns it:
let rec inOrder tree =
 seq{
 match tree with
  | Node (data, left, right) ->
   yield! inOrder left
   yield  data;
   yield! inOrder right
  | Empty -> ()
 }
 |> Seq.to_list;

Now I want to create a function, similar to this, which takes a tree and a function, traverses it and applies a function to each node, then returns the tree:
mapInOrder : ('a -> 'b) -> 'a BinTree -> 'b BinTree

This seems easy, and it probably is! But I'm not sure how to return the tree. I've tried this:
let rec mapInOrder f tree =
 match tree with
 | Node(data, left, right) ->
  mapInOrder f left
  Node(f(data), left, right)
  mapInOrder f right
 | Empty -> ()

but this returns a unit. I havent worked with custom types before, so I'm probably missing something there!

A: Try this:
let rec mapInOrder f = function
  | Node(a,l,r) ->
      let newL = mapInOrder f l
      let b = f a
      let newR = mapInOrder f r
      Node(b,newL,newR)
  | Empty -> Empty

If the function is side-effect free, then traversal order is unimportant and you can instead write:
let rec map f = function
  | Node(a,l,r) -> Node(f a, map f l, map f r)
  | Empty -> Empty

A: A match is an expression. It returns the value of the matching case. That implies that all match cases must have the same type. The match expression itself then has that type.
In your first attempt, your Empty clause returned (), and thus had unit type--not the tree type you were looking for.
Since mapInOrder just returns the match result, it too took on unit return type.
The Node clause was fine because its return value is the result of calling mapInOrder, so it also took on unit type and the requirement that all match clauses have the same type was satisfied.
A key change in kvb's suggestion was making the Empty clause return a tree instead of unit. Once you do that, you get compiler errors and warnings pointing to the other problems.
You can often work through issues like this by explicitly coding the type you'd like, and then seeing where the compile errors and warnings show up.


text:
Q: What is wrong with my numeric_limits function C++ I have code like this:
// .h file
#include <iostream>
#include <limits>

class MyClass
{
public:
    myInput();
    int inputValue;
}

// .cpp file
#include "MyClass.h"
void MyClass::myInput()
{
    std::cin >> inputValue;
    if (!std::cin)
    {
        //fix error
        std::cin.clear();
        std::cin.ignore(std::numeric_limits < std::streamsize >::max(), '\n');
    }
}

During compilation, the compiler is showing error:

Expected an identifier

In the line with
std::cin.ignore(std::numeric_limits < std::streamsize >::max(), '\n');

Moreover, the ::max() is underlined. I don't have an idea what is going on. Thanks for help!

A: Problem has solved. I'm using Visual Studio which have macro called max. So I added #undef max; at the begin of my file and everything is working. Thanks for help.


text:
Q: Vue Banner Better Warning Component is missing template or render function I want to create a simple Banner with vue-banner-better, I installed the module and configure scoped banner in a vue file. When i run it, i get the next warn and doesn't appear the desired banner. thanks in advance.
this is the warn:
    [Vue warn]: Component is missing template or render function.
  at <Banner autoplay="" indicator= {clickable: true, type: 'pill', showCounter: false}clickable: trueshowCounter: falsetype: "pill"[[Prototype]]: Objectconstructor: ƒ Object()hasOwnProperty: ƒ hasOwnProperty()isPrototypeOf: ƒ isPrototypeOf()propertyIsEnumerable: ƒ propertyIsEnumerable()toLocaleString: ƒ toLocaleString()toString: ƒ toString()valueOf: ƒ valueOf()__defineGetter__: ƒ __defineGetter__()__defineSetter__: ƒ __defineSetter__()__lookupGetter__: ƒ __lookupGetter__()__lookupSetter__: ƒ __lookupSetter__()__proto__: (...)get __proto__: ƒ __proto__()set __proto__: ƒ __proto__() show-navigation=""  ... >
  at <Hero>
  at <Home onVnodeUnmounted=fn<onVnodeUnmounted> ref=Ref< undefined > >
  at <RouterView>
  at <App>

This is my Hero.vue file:
    <template>

      <Banner
        autoplay
        :indicator="indicator"
        show-navigation
        disable-on-hover
        mode="loop"
      >
        <Slide>

        </Slide>
        <Slide>

        </Slide>
        <Slide>

        </Slide>
      </Banner>

</template>

My main.ts has commented the reference because I tested it but doesn't work too.
  import App from "./App.vue";
import { createApp } from "vue";
import { createRouter } from "./router";
import { createAuth0 } from "@auth0/auth0-vue";
import hljs from "vue3-highlightjs";
import "highlight.js/styles/github.css";
import { library } from "@fortawesome/fontawesome-svg-core";
import { faLink, faUser, faPowerOff } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/vue-fontawesome";
import { domain, clientId as client_id } from "../auth_config.json";
//import { Banner } from "vue-banner-better";

const app = createApp(App);

library.add(faLink, faUser, faPowerOff);

app
  //.use(Banner)
  .use(hljs)
  .use(createRouter(app))
  .use(
    createAuth0({
      domain,
      client_id,
      redirect_uri: window.location.origin,
    })
  )
  .component("font-awesome-icon", FontAwesomeIcon)
  .mount("#app");


text:
Q: Ajax POST from Shopify checkout page I have a checkout.liquid file in shopify were I'm trying to set the metadata to a customers profile.
This is the code I have in the checkout.liquid file:
var url = "/admin/customer/"+{{checkout.customer.id}}+"/metafields.json";
console.log("url:"+url);

$.ajax({
    type: "POST",
    url:url,
    namespace: 'QQQQQQQ',
    key: 'WWWWWWW',
    value: 'Test'
    success: function(msg){
        console.log( "Data Saved: " + msg );
    },
    error: function(XMLHttpRequest, textStatus, errorThrown) {
        console.log(errorThrown);
        console.log('error');
    }
});

I get this error in the console:
GET https://checkout.shopify.com/admin/auth/login 404 (Not Found)
I don't understad what's happening?
Do I not have permissions from the checkout.liquid page to access the API or is it something else?


text:
Q: Format Specific Cell in DataTable in R How can I format a specific cell with DT? In this example, how would I format every cell in the first column that is >0?
df = data.frame(
  V1 = c(5, -31, '-2'),
  V2 = c(-5, -7, '2'),
  V3 = c(4, -10, '22'))

DT = datatable(df) %>%
  formatStyle(...)

I thought something like backgroundColor = styleInterval(0, c('red', 'blue)) (in the formatStyle()) might work, but I have had no luck.

A: The below link for me is quite useful - has a variety of formatting permutations...
https://rstudio.github.io/DT/010-style.html
Specific to a column, which changes based on  > 0:
library(DT)

df = data.frame(
  V1 = c(5, -31, '-2'),
  V2 = c(-5, -7, '2'),
  V3 = c(4, -10, '22'))

DT = DT::datatable(df) %>%
     formatStyle('V1', backgroundColor = styleInterval(c(0),c('red','blue')))

Might have been the c() specifying the cuts as a vector...

Below is an example to format cells (but is a slight hack - not sure myself of another way)
  df = data.frame(
    V1 = c(5, -31, '-2'),
    V2 = c(-5, -7, '2'),
    V3 = c(4, -10, '22'))

Now create a column which has  your 'flag' value
  df$FLAG <- c(0,0.5,1)

Now create your choice of styles/colours and format the data frame (I then make the FLAG (4) column not visible so looks as if cells are formatted)
styles <- c("rgb(245,242,242)",
        "rgb(254, 204, 116)","rgb(255,83,83)")

datatable(df, caption = 'Test Format',
          options = list(dom='t',columnDefs =
                                  list(list(visible=FALSE,
                                                targets=4)))) %>%
          formatStyle("V1","FLAG",
                 backgroundColor = styleEqual(c(0,0.5,1),styles))

Note dom='t' just leaves out data table filtering and paging; And columnDefs is used to leave out the FLAG column


text:
Q: Order pagination result in Symfony 1 I have a question concerning pagination in Symfony 1. I have the code below which give me the paginated records of the Offer table. How could I change the order from asc to desc?
protected function getPager() {
    $pager = new sfDoctrinePager('Offer', 1000);
    $pager->setQuery($this->buildQuery());
    $pager->setPage($this->getPage());
    $pager->init();
    return $pager;
}

A: It's not the pager having to add the order but the query. So you can create a query manually (where you set also the ordering needed) and pass it to $pager->setQuery().

A: if i may add a solution.
use jQuery + datatables.net.  its neat and fast.  Message me for sample code.
ejaymejr@gmail.com
Preview of the Datatable i created.
https://imgur.com/a/a9w22


text:
Q: How to reset file icons associated with default program on El Capitan I've uninstalled my former default text editor which I used for many different file formats. Unfortunately the associated icons are not removed automatically. As a result, several file types still use the icon of the program, even though it's not on my machine anymore.
There a several similar questions around here and this one seemed to be most promising, but it doesn't work on El Capitan (version 10.11.5). Does anyone how I can achieve this on a current version of Mac OS X?
EDIT: After assigning a new default program (no matter if I do that via RCDefaultApp or Finder), the old icon remains. If, for instance, I choose Atom as the new default editor for XML files, the former editor icon (Emacs) is still there.

A: Run this command in Terminal: sudo rm -rf /Library/Caches/com.apple.iconservices.store
And G'bye atom icon.

A: Have you tried just setting a new default to one document, Get Info on one example, select a new app from the 'Open With' drop menu then hit the 'Change all' button below [hidden below drop menu in photo]

Alternatively, RCDefaultApp [freeware, old but still works well] can change many aspects of file association.


text:
Q: jquery modal dialog background does not extend beyond iframe I'm working on a web app that uses iframes. I wrote a modal dialog function using the jQuery library, which triggers a modal popup window inside the iframe.  Everything works except the dialog background, when the modal window is triggered, only covers the portion inside the iframe.
This is expected behavior and I thought the fix would be relatively easy with changing the z-index values, but I cannot escape the modal background outside the iframe. The code is pretty straightforward, I'll paste a bit here.
I should specify that our source tree only has access to the iframe, we inherit from parent elements/controls, but cannot access them, so I am limited to whatever the fix would be inside the iframe.
Any help or pointers would be appreciated.
<asp:Content ContentPlaceHolderID="CloudContent" runat="server">

Add Cloud-Based Application

</asp:Content>

A: After continued experimentation :-), a CSS change did the trick.  Changing the position to "fixed" from "absolute" resolved it.  A snippet of CSS below, and I hope this helps someone else.
#modalBackground {
    z-index:1000;
    position:fixed;
    width:100%;
    height:100%;
    top:0;
    left:0;
    background-color:#000;
    display:none;
}


text:
Q: Windows Workflow Foundation application (persistent) Server migration I'm doing a migration of a Windows Workflow Foundation application
From: Windows server 2008 R2 with IIS 7.0 Framework .Net 4.5 Windows Workflow Foundation 4.5
To: Windows 2012 server with IIS 8.0.9 Framework .Net 4.5 Windows Workflow Foundation 4.5
When I try to proceed with the execution of an instance of a running(migrated) process I got this error:

The execution of an InstancePersistenceCommand was interrupted because the instance key [GUID] was not associated to an Instance

The process instance's GUID of the error doesn't match with the one present in the database.
It seems like that the process instance's GUID is generated and not read from the database, but is generated with some data retrieved somewhere that changes with the new server.
Someone succeed on a migration of a Windows Workflow Foundation application with open instances of processes solving this problem?
thanks in advance,
Danny

A: Danny.
We did this migration (with two difference - not from IIS 7.0, but from IIS 7.5, and our hosting is AppFabric) and really we didn't found any problem in it at all(although there is no any blog entry on this topic, what disappointed me). We have many thousands of active instances.
So my recommendation:
1. Check if old server is shut down. If not, I recommend to do it.
2. Try to find instance with this ID in persistence database.
If you use AppFabric:
1. Open Dashboard, check for errors.
2. Try to find instance with this ID in persistence db using dashboard.
Good luck!


text:
Q: Compare two strings (similar to how GNU diff does) Is there any open source project or library, which has the ability to compare two strings in the way GNU diff does, but without launching an external process, and working with memory buffers instead of files?
That is, something looking like this hypothetical function:
comparison_result* diff(wchar_t *text1, wchar_t *text2);

I looked at GNU diffutils' source code, hoping it would be using such a function internally, but unfortunately, it is reading the files block by block, instead of reading them into a memory buffer and comparing that. The code itself is rather convoluted, and I'm not able to understand it very well, let alone rewrite it.
Is there such a function in an open-source project?

A: The source code for the diffutils programs / functions is indeed a bit difficult to adapt for this purpose given that it uses a number of partial buffering of the files during the comparison algorithm.
However, the functionality implemented by diff isn't really revolutionary or difficult to reproduce. And it has be reproduced in other libraries. For example, the google-diff-match-patch library from google-code, it's API is a bit crude, but it seems to do the job.
Another possibility is to write your data into in-memory FILE* buffers, and then use the diffutils functions, reading and writing to those in-memory buffers. You can create such buffers with fmemopen.

A: You can refer to libmba, whose diff source code is at http://www.ioplex.com/~miallen/libmba/dl/src/diff.c


text:
Q: My sticky/fixed-to-top navbar stops being sticky when in tablet/phone mode I've made a sticky/fixed-to-top navbar with Bootstrap. It's responsive so the nav options turn into a hamburger menu when the screen is below a set size. I've also added JavaScript from a tutorial so that it scrolls nicely.
It is working fine except in tablet/phone mode when the navbar stops being fixed to the top and becomes static instead. See here for the differences/what it should be like. I'm not sure what I've done wrong.
I've tried many versions/tutorials, sometimes I get it to be sticky in both situations but without the hamburger menu expanding etc. This is the best I've got it so far basically. Below is the HTML:

        <button type="button" id="nav-toggle" class="navbar-toggle" data-toggle="collapse" data-target="#main-nav">
        Toggle navigation

        </button>
        Company

Contact

About

Testimonials

and the javascript:


text:
Q: How to resize image before uploading it ? In my AIR app, the user can take a photo (from CameraRoll or CameraUI) and save it to a server.
Is there a way to automatically resize the image (800x600) in order to have a lighter file ?
Here's my code :
    var now:Date = new Date();
    var saveDirectory:String= "MyApp/PhotoUploads";
    var fileName:String = "MyPhoto" + now.fullYear + now.month + now.day + now.hours + now.minutes + now.seconds + ".jpg";
    var photoFile:File=File.documentsDirectory.resolvePath(saveDirectory+"/"+ fileName);

 function imageSelected( event:MediaEvent ):void{
    var mp:MediaPromise = event.data;

dataSource = mp.open();
 readMediaData();
}

function readMediaData():void{

    var imageBytes:ByteArray = new ByteArray();
     dataSource.readBytes( imageBytes );
    var stream:FileStream = new FileStream();
    stream.addEventListener( Event.CLOSE,photoFileSaved);
    stream.openAsync( photoFile,FileMode.WRITE);
    stream.writeBytes( imageBytes );
    stream.close();
    }

 function photoFileSaved(evt:Event):void{
     photoUpload();
 }

 function photoUpload():void{
     photoFile.upload( req );
     photoFile.addEventListener( ProgressEvent.PROGRESS, progress_func );
     photoFile.addEventListener( IOErrorEvent.IO_ERROR, ioErrorMedia );
     photoFile.addEventListener( Event.COMPLETE, complete_func );
 }

Apparently I can't do :
mp.width = 200;
mp.height= 200;

So how can I do that ?

A: var scale:Number = .6;

var m:Matrix = new Matrix();
m.scale (scale,scale);

var bmp:BitmapData = new BitmapData(sourceMc.width, sourceMc.height, false);
bmp.draw (sourceMc,m);


text:
Q: Question regarding account creation and sync on Android I've been reading the sample code from the dev docs on Android's site, specifically this:
http://developer.android.com/resources/samples/SampleSyncAdapter/src/com/example/android/samplesync/authenticator/AuthenticatorActivity.html
Which is the sole activity of the sample app. It refers to an intent in the onCreate method. I don't understand where this intent is coming from, or what it should contain if this is the only activity the app utilizes.
Log.i(TAG, "loading data from Intent");
        final Intent intent = getIntent();
        mUsername = intent.getStringExtra(PARAM_USERNAME);
        mAuthtokenType = intent.getStringExtra(PARAM_AUTHTOKEN_TYPE);
        mRequestNewAccount = mUsername == null;
        mConfirmCredentials = intent.getBooleanExtra(PARAM_CONFIRM_CREDENTIALS, false);

That's the block of code working with the intent. Why would you have an intent for the only activity in the app? Is this app called in an unusual way? The Manifest does not include an intent filter for the activity... I guess I'm just a bit lost on this whole thing! If someone could set me straight that'd be great, thanks.

A: *

*Why would you have an intent for the only activity in the app?
getIntent() gets you the intent that started this activity.

*Is this app called in an unusual way?
I guess this activity is called programmatically from another app or activity, since it has been passed some extra data: getStringExtra() is used to extract some data from the intent that started it. putExtra.. and getExtra.. is a way to pass data between activities when they are started.

A: In that specific example, the intent is sent from the addAccount method in Authenticator.java.  That method is called by the OS when you click the Add Account button in the Accounts & sync settings screen and choose your account type.


text:
Q: opencl debugger settings in vs 2010 I just want to ask a very simple question: where can I find the opencl debugger configuration dialog in visual studio 2010. There is no code builder tab in vs2010 as well as I could not find it under the tools tab. I just want to enable opencl debugger, play around work item values and debug my kernel code.
Any help would be appreciated?
p.s: everything has worked fine from installation to code building to application execution. Just want to know why the opencl sdk debugger plug-in does not appear anywhere in vs2010.
thanks,
Mork.

A: You can't use the Visual Studio debugger to debug OpenCL kernels.
Update: Per the informative comment from @Omair Khan, under certain conditions (source in file) you can debug CPU kernels in Visual Studio when using the Intel CPU driver. However, you cannot use the Visual Studio debugger for GPU kernels.


text:
Q: How do you stop a React application failing if a key doesn't exist in object or array? How can I check whether a key exists before iterating through an array with .map?
    import React from 'react';
    ReactDOM.render(

        myObj={
          "meat": {"main": ["Chicken", "Beef", "Lamb", "Pork"]}
        }

        const Dinner () =>{
        const course = 'main';
           return(
              <div>
                  //course might result in a lookup that doesn't exist
                  {myObj.meat[course].map((n) => n + '')}
              </div>
       );
    }
    export default Dinner;
    );

Because the key (course) is a variable, it could result in a lookup that doesn't exist e.g. myObj.meat['sillyKey'] and this is causing my application to fail. How do I stop the application failing in this case?
Many thanks,
Katie

A: You can implement a safeguard as follows:
{myObj.meat[course] && myObj.meat[course].map((n) => n + '')}


text:
Q: Table name show a syntax error in MySQL When I try to create a table with the following name in MySQL it show a syntax error but its not showing any problem if I use the phpmyadmin :
"attn-cse-a[3-1][mpms][10-8-2013]"
when I create a same type of table with a different name I am able to do it without any problems..
Any help would be greatly appreciated ..

A: Use back quotes to wrap tablename:
create table `attn-cse-a[3-1][mpms][10-8-2013]` (...

A: You may use illegal characters by escaping them with backticks, but I won't recommend it, since it will only bring you trouble for the rest of the project's lifetime.


text:
Q: Git GUI tool to show incoming changes for conflicted files When I delete a file, which was modified on another branch; then I merge that branch, I end up with a conflict saying CONFLICT (modify/delete): ..file.. deleted in HEAD and modified in ..other-branch..
In this case - but only in this case - TortoiseGit shows this window:

The Show changes button shows the incoming changes of the conflicted file - aka the changes it had on the other branch.
This is a very useful feature.
It would be great to have this feature for all kind of conflicts.
There are 46 GIT GUI client tools listed here:
https://git-scm.com/downloads/guis
From them, I use every day: TortoiseGit, SourceTree, Fork. And of course the GIT CLI.
How to get the incoming changes of a conflicted file in these clients, or in any other GIT client available?
I'm also open for a CLI alias if no GUI client can do this.
[Edit] Example use case
For example I move a code block from file1 to file2.
On the other branch, that code block was modified in file1.
file1.js
...

function myFunction() {
    ...
}

I move this code blokk into file2.js, thus I delete it from file1.js.
On the other branch, myFunction gets modified like this:
file1.js
...
const aVariableWhichWontConflict = calcIt(...)

function myFunction() {
    ...
    useIt(aVariableWhichWontConflict)
    ...
}

I only will get merge conflict within myFunction, the line const aVariableWhichWontConflict = calcIt(...) will be merged into file1 without conflict.
I will have to detect this change and move it into file2 as well.
The example above is simple and easy, but in real life these could be much more complicated.
To be able to see the incoming changes of file1 in one diff would help a lot with these kind of merges.


text:
Q: How to return a shuffled list considering mutually exclusive items? Say I have a list of options and I want to pick a certain number randomly.
In my case, say the options are in a list ['a', 'b', 'c', 'd', 'e'] and I want my script to return 3 elements.
However, there is also the case of two options that cannot appear at the same time. That is, if option 'a' is picked randomly, then option 'b' cannot be picked. And the same applies the other way round.
So valid outputs are: ['a', 'c', 'd'] or ['c', 'd', 'b'], while things like ['a', 'b', 'c'] would not because they contain both 'a' and 'b'.
To fulfil these requirements, I am fetching 3 options plus another one to compensate a possible discard. Then, I keep a set() with the mutually exclusive condition and keep removing from it and check if both elements have been picked or not:
import random

mutually_exclusive = set({'a', 'b'})
options = ['a', 'b', 'c', 'd', 'e']
num_options_to_return = 3

shuffled_options = random.sample(options, num_options_to_return + 1)

elements_returned = 0
for item in shuffled_options:
    if elements_returned >= num_options_to_return:
        break

    if item in mutually_exclusive:
        mutually_exclusive.remove(item)
        if not mutually_exclusive:
            # if both elements have appeared, then the set is empty so we cannot return the current value
            continue

    print(item)
    elements_returned += 1

However, I may be overcoding and Python may have better ways to handle these requirements. Going through random's documentation I couldn't find ways to do this out of the box. Is there a better solution than my current one?

A: One way to do this is use itertools.combinations to create all of the possible results, filter out the invalid ones and make a random.choice from that:
>>> from itertools import combinations
>>> from random import choice
>>> def is_valid(t):
...     return 'a' not in t or 'b' not in t
...
>>> choice([
...     t
...     for t in combinations('abcde', 3)
...     if is_valid(t)
... ])
...
('c', 'd', 'e')

A: Maybe a bit naive, but you could generate samples until your condition is met:
import random

options = ['a', 'b', 'c', 'd', 'e']
num_options_to_return = 3
mutually_exclusive = set({'a', 'b'})

while True:
    shuffled_options = random.sample(options, num_options_to_return)
    if all (item not in mutually_exclusive for item in shuffled_options):
        break

print(shuffled_options)

A: I would implement it with sets:
import random

mutually_exclusive = {'a', 'b'}
options = ['a', 'b', 'c', 'd', 'e']
num_options_to_return = 3

while True:
    s = random.sample(options, num_options_to_return)
    print('Sample is', s)
    if not mutually_exclusive.issubset(s):
        break
    print('Discard!')

print('Final sample:', s)

Prints (for example):
Sample is ['a', 'b', 'd']
Discard!
Sample is ['b', 'a', 'd']
Discard!
Sample is ['e', 'a', 'c']
Final sample: ['e', 'a', 'c']

A: You can restructure your options.
import random

options = [('a', 'b'), 'c', 'd', 'e']
n_options = 3

selected_option = random.sample(options, n_options)

result = [item if not isinstance(item, tuple) else random.choice(item)
          for item in selected_option]

print(result)

A: I created the below function and I think it's worth sharing it too ;-)
def random_picker(options, n, mutually_exclusives=None):
    if mutually_exclusives is None:
        return random.sample(options, n)
    elif any(len(pair) != 2 for pair in mutually_exclusives):
        raise ValueError('Lenght of pairs of mutually_exclusives iterable, must be 2')

    res = []
    while len(res) < n:
        item_index = random.randint(0, len(options) - 1)
        item = options[item_index]
        if any(item == exc and pair[-(i - 1)] in res for pair in mutually_exclusives
               for i, exc in enumerate(pair)):
            continue
        res.append(options.pop(item_index))
    return res

Where:

*

*options is the list of available options to pick from.

*n is the number of items you want to be picked from options

*mutually_exclusives is an iterable containing tuples pairs of mutually exclusive items

You can use it as follows:
>>> random_picker(['a', 'b', 'c', 'd', 'e'], 3)
['c', 'e', 'a']
>>> random_picker(['a', 'b', 'c', 'd', 'e'], 3, [('a', 'b')])
['d', 'b', 'e']
>>> random_picker(['a', 'b', 'c', 'd', 'e'], 3, [('a', 'b'), ('a', 'c')])
['e', 'd', 'a']

A: import random

l = [['a','b'], ['c'], ['d'], ['e']]
x = [random.choice(i) for i in random.sample(l,3)]

here l is a two-dimensional list, where the fist level reflects an and relation and the second level an or relation.


text:
Q: How to access a java.util.prefs.Preferences object defined in another class I am seeking to understand how to access a java.util.prefs.Preferences object that is defined in a different class. Or, for that matter, what are the best practices for using Preferences?
I currently have the preferences saved from a Settings dialog, like so:
public class Settings extends JDialog {
    // [...]
    private final Preferences prefs = Preferences.userRoot().node(this.getClass().getName());
    // [...]
}

This works great for setting the various preferences, reverting to defaults, etc. However, once those preferences are saved, I'll need to access them from another class, specifically, my main dialog. However, once the Settings dialog has been disposed of, there seems to be no way to access its prefs. And I cannot use this.getClass().getName() if I make prefs static.
I cannot seem to find any information on how to do this properly and need guidance. What do I need to do? I wouldn't mind putting prefs into its own class, but I will still run into the static problem and referencing it from another class.

A: A Preferences object is obtained via a lookup. It doesn't matter where you are in the code, if you use the same lookup key, you get the same Preferences object. The API provides different lookup methods. You just have to select one and be consistent. In my code I use [static] method userNodeForPackage. The method accepts a single parameter which is a Class object. As long as I call method userNodeForPackage and pass the same Class object, I will get the same Preferences object.
One way (but not the only way) to obtain a Class object is via [static] method forName in class java.lang.Class. However, the way you obtain the Class object is irrelevant, just as long as you obtain the correct Class object.
Perhaps this article will be helpful:
The Preferences API


text:
Q: Loading font from node_modules in Nextjs I'm installing a npm package that uses fonts like:
var _font = _interopRequireDefault(require("../../style/fonts/font123.eot"));

When i start my nextjs project, it returns me this error:
Error before webpack loader
To fix this issue, I placed a webpack loader on next.config.js:
config.module.rules.push({
  test: /\.(woff|woff2|ttf|eot|svg)$/,
  loader: 'file-loader',
  options: {
    name: 'fonts/[name].[ext]'
  }
});

But it fails to parse every font, not only .eot files.
error after adding webpack loader
I already tried many webpack loaders and nothing seems to work

A: I've experienced the same problem, resolved it with this config.
module.exports = {
  webpack(config, options) {
    config.module.rules.push({
      test: /\.(woff|woff2|ttf|eot|svg)$/,
      loader: "file-loader",
      options: {
        esModule: false,
        name: "[name].[ext]",
        outputPath: "static/media/fonts/",
        publicPath: "../assets/fonts/",
      },
    });

    return config;
  },
};

Here is an article that can help you more.


text:
Q: Possible to build a shared library with static link used library? I can build a executable with gcc with static link:

gcc -static xxx.c -o xxx

So I can run xxx without any external dependent library.
But what if I want to build shared library without externel dependent library? which I mean I want
the shared library statically linked its externel reference in.

A: There's some neat hackery you can do with Rpath so that a ELF executable or .so will look for its dependent .so files first in the same directory as itself:

*

*make a short script echo-rpath consisting of
echo '-Wl,--rpath=$ORIGIN'

*add that to your build command line as gcc -o file -lwhatever `echo-rpath ` objects
(The echo mechanism prevents Make or the shell from eating the $ sign and ensures it gets passed into ld.)

A: This will work:
# Generate position independent code (PIC)
gcc -fPIC -c -o xxx.o xxx.c

# Build a shared object and link with static libraries
ld -shared -static -o xxx.so xxx.o

# Same thing but with static libc
ld -shared -static -o xxx.so xxx.o -lc

A clarification: the -static flag, if given to gcc, is passed on to the linker (ld) and tells it to work with the static version (.a) of a library (specified with the -l flag), rather than the dynamic version (.so).
Another thing: On my system (Debian) the last example gives a libc.a ... recompile with -fPIC error. Pretty sure that means that the libc.a I have on my system wasn't compiled with -fPIC. An apt-cache search libc pic did give some results however.
See also: Program Library HOWTO, SO: combining .so libs, ld(1), gcc(1)

A: If you have any plans on portability for your shared library, use libtool(1). It will handle most of the details of compiler flags for you and will make your life infinitely easier. If you don't use libtool, but later decide you want to port your program to OS X or Windows, you're going to end up reinventing it anyway.


text:
Q: Firebase | Export collection data in CSV format using firebase console I have query regarding the data export from Firebase Console. Can we export collection data in CSV format using Firebase console?
Any help would be appreciated

A: You can export to JSON, then write your own code to convert that into whatever other format you want.  You can't export directly to any other format.


text:
Q: how to pop show exact right click event location i have following code but my Pop does not show exact location of my right click how do this please help. how to pop show on my right click exact location

  function openPopup() {
             //document.getElementById('test').style.display = 'block';
             $('#test').fadeIn(1000);
         }

         function closePopup() {
             //document.getElementById('test').style.display = 'none';
             $('#test').fadeOut(500);
         }
 google.maps.event.addListener(_map, "rightclick", function (event) {
                 openPopup();
             });

      .popup {
    position:fixed;
    top:0px;
    left:0px;
 bottom:0px;

    padding:10px;
    background-color:rgb(240,240,240);
    border:2px solid grey;
    z-index:100000000000000000;
}

.cancel {
    display:relative;
    cursor:pointer;
    margin:0;
    float:right;
    height:10px;
    width:14px;
    padding:0 0 5px 0;

    z-index:100000000000000000;
}

.cancel:hover {
    background:rgb(255,50,50);
}

    This is a test message

A: You don't need to create a new pop up box for that, you can do this with google's google.maps.InfoWindow class
Use this
var map;
var markers   =   [];
var latalng   =   {lat:26.912082488274702, lng:75.81622123718262}
var infowindow;
function initMap() {
    map = new google.maps.Map(document.getElementById('map'), {
      center: latalng,
      zoom: 17
    });

   //infoWindow Object
   infowindow = new google.maps.InfoWindow();

  //add event to right click
  map.addListener('rightclick', function(event) {
    //Set content to show on popup
      infowindow.setContent("Your Messaage To show");

    //get the position form google.maps.MouseEvent class passed in event objevc
      var latLang = { lat: event.latLng.lat(),lng:event.latLng.lng()};

    //set the position of popup(infowindow)
      infowindow.setPosition(latLang);

    //open infowindow
     infowindow.open(map, this);
});

}


text:
Q: Converting true/false to 0/1 boolean in a mixed dataframe I have a dataframe with mixed data types. I want to create a function that goes through all the columns and converts any columns containing True/False to int32 type 0/1.  I tried a lambda function below, where d is my dataframe:
f = lambda x: 1 if x==True else 0
d.applymap(f)

This doesn't work, it converts all my non boolean columns to 0/1 as well. Is there a good way to go through the dataframe and leave everything everything untouched except the boolean columns and convert them to 0's and 1's? Any help is appreciated!

A: Let's modify your lambda to use an isinstance check:
df.applymap(lambda x: int(x) if isinstance(x, bool) else x)

Only values of type bool will be converted to int, everything else remains the same.

As a better solution, if the column types are scalar (and not "mixed" as I originally assumed given your question), you can instead use
u = df.select_dtypes(bool)
df[u.columns] = u.astype(int)

A: You can select the columns using loc and change data type.
df = pd.DataFrame({'col1':np.random.randn(2), 'col2':[True, False], 'col3':[False, True]})

df.loc[:, df.dtypes == bool] = df.astype(int)

    col1      col2  col3
0   0.999358    1   0
1   0.795179    0   1

A: If you have a dataframe df, try:
df_1=df.applymap(lambda x: int(x) if type(x)==bool else x)


text:
Q: Android: Out of memory error when loading text files. How to get available memory before loading files I want to load a text file in a wordprocessing apps. But I get out of memory error when files are of too big. I finalized  that I can load upto 1 MB files. But sometimes I get out of memory even for 1MB files.  But I have to say before loading whether I can load files  or not.
I tried for solution of finding maximum possible available memory, apart from freeMemory(),
that is freememory + (maxmemory - totalmemory)  which will give the total possible available memory for the  application. (Say it will be around 18MB to 20 MB). But I get outofMemory error after completely utilizing the heap. say for example(24 MB).

*

*My question is really that (18MB to 20 mb) of "maximum possible available memory" is utilized for allocation when loading 1MB file.

*How much of memory should be available to load 1MB file.

*How can I roughly compute it.

*Is there any way out of PSS, Privatedirty. I couldn't understand much about PSS. But I couldn't get much info regarding of summing up in article "How to discover memory usage of my application in Android"
Thanks

A: Remember, the way you store the files in variables matters quite a lot. Using char array manually is one of the most memory-efficient ways, but you still need to account for every character taking 16 bits, or 2 bytes. So, if you have text file using some 8-bit encoding and you load it into char array, it takes twice as much space.


text:
Q: If $q^k n^2$ is an odd perfect number with Euler prime $q$, which of the following relationships between $q^2$ and $n$ hold? (Preamble #1:  In what follows, we take $\sigma=\sigma_{1}$ to be the sum of the divisors, and denote the abundancy index of $x \in \mathbb{N}$ as $I(x)=\sigma(x)/x$.)
(Preamble #2:  My sincerest apologies for the somewhat very long post -- I just had to put in all the details into one place for ease of quick reference later.)
PROBLEM

If $q^k n^2$ is an odd perfect number with Euler prime $q$, which of the following relationships between $q^2$ and $n$ hold?

(A) $$q^2 < \sigma(q^2) < n < \sigma(n)$$
(B) $$q^2 < n < \sigma(q^2) < \sigma(n)$$
(C) $$n < \sigma(n) < q^2 < \sigma(q^2)$$
(D) $$n < q^2 < \sigma(n) < \sigma(q^2)$$

PRELIMINARIES
(0) Of course, first of all, note that $q^2 \neq n$ since $\gcd(q,n)=1$.
(1) Note that
$$\frac{q^2}{n}+\frac{n}{q^2} < \frac{\sigma(q^2)}{n}+\frac{\sigma(n)}{q^2} < 2\cdot\bigg(\frac{q^2}{n}+\frac{n}{q^2}\bigg).$$
Consequently, we know that
$$\frac{q^2}{n}+\frac{n}{q^2} \text{ is bounded from above } \iff \frac{\sigma(q^2)}{n}+\frac{\sigma(n)}{q^2} \text{ is bounded from above.}$$
In general, since the function $f(z) := z + (1/z)$ is not bounded from above, this means that we do not expect
$$\frac{\sigma(q^2)}{n}+\frac{\sigma(n)}{q^2}$$
to be bounded from above.
(2) $n < q^2 \implies k = 1$ [Dris, 2012]
(3) $$1 < I(q^2) \leq \frac{q^2 + q + 1}{q^2} = 1+\frac{1}{q}+\bigg(\frac{1}{q}\bigg)^2 \leq 1+\frac{1}{5}+\bigg(\frac{1}{5}\bigg)^2 = \frac{25+5+1}{5} = \frac{31}{25}$$
since $q$ being the Euler prime implies that $q$ is prime with $q \equiv 1 \pmod 4$, therefore $q \geq 5$.
Now, $1 < I(n) < 2$ since $n > 1$ is deficient, $n$ being a proper factor of the (odd) perfect number $q^k n^2$.
Consequently,
$$1 < I({q^2}n) = I(q^2)I(n) = \frac{\sigma(q^2)}{n}\cdot\frac{\sigma(n)}{q^2} < 2\cdot\frac{31}{25} = \frac{62}{25}.$$
(4) It follows from (1) and (3) that the following hold:
(a) $\sigma(n) \neq \sigma(q^2)$
Proof:  Assume that $\sigma(n) = \sigma(q^2)$.  Then we have (by (3))
$$I(q^2) = \frac{\sigma(q^2)}{q^2} = \frac{\sigma(n)}{q^2} < \frac{31}{25}$$
and
$$I(n) = \frac{\sigma(n)}{n} = \frac{\sigma(q^2)}{n} < 2.$$
It follows that
$$\frac{\sigma(q^2)}{n}+\frac{\sigma(n)}{q^2} < 2+\frac{31}{25}=\frac{81}{25}.$$
This implies that
$$\frac{\sigma(q^2)}{n}+\frac{\sigma(n)}{q^2}$$
is bounded from above, contradicting (1).
(b) $\sigma(q^2) \neq n$.
Suppose to the contrary that $\sigma(q^2)=n$.  Then we have (from (3))
$$1\cdot\frac{\sigma(n)}{q^2} = \frac{\sigma(q^2)}{n}\cdot\frac{\sigma(n)}{q^2} < \frac{62}{25}.$$
It follows that
$$\frac{\sigma(q^2)}{n}+\frac{\sigma(n)}{q^2}=1+\frac{\sigma(n)}{q^2}<1+\frac{62}{25}=\frac{87}{25}.$$
This implies that
$$\frac{\sigma(q^2)}{n}+\frac{\sigma(n)}{q^2}$$
is bounded from above, contradicting (1).
The proof for the following is similar to that of (b):
(c) $\sigma(n) \neq q^2$
MAIN RESULTS
The proofs of the succeeding three lemmas are trivial.
Lemma 1.  The inequality
$$I(q^2) + I(n) < \frac{\sigma(q^2)}{n}+\frac{\sigma(n)}{q^2}$$
is true if and only if the biconditional
$$q^2 < n \iff \sigma(q^2) < \sigma(n)$$
is true.
Lemma 2.  The inequality
$$\frac{\sigma(q^2)}{n}+\frac{\sigma(n)}{q^2} < I(q^2) + I(n)$$
is true if and only if the biconditional
$$q^2 < n \iff \sigma(n) < \sigma(q^2)$$
is true.
Lemma 3.  The equation
$$I(q^2) + I(n) = \frac{\sigma(q^2)}{n}+\frac{\sigma(n)}{q^2}$$
is true if and only if either $q^2 = n$ or $\sigma(q^2)=\sigma(n)$ hold.
We now prove our first main result:
Theorem 1. If $q^k n^2$ is an odd perfect number, then the inequality
$$I(q^2) + I(n) < \frac{\sigma(q^2)}{n}+\frac{\sigma(n)}{q^2}$$
holds.
Proof:  Suppose to the contrary that
$$\frac{\sigma(q^2)}{n}+\frac{\sigma(n)}{q^2} \leq I(q^2)+I(n).$$
Since $I(q^2) \leq 31/25$ and $I(n) < 2$, this implies that
$$\frac{\sigma(q^2)}{n}+\frac{\sigma(n)}{q^2} < 2 + \frac{31}{25} = \frac{81}{25}$$
so that
$$\frac{\sigma(q^2)}{n}+\frac{\sigma(n)}{q^2}$$
is bounded from above, contradicting (1).
By using Lemma 1, we are able to obtain the following Corollary to Theorem 1.
Corollary 2.  If $q^k n^2$ is an odd perfect number, then the biconditionals
$$q^2 < n \iff \sigma(q^2) < \sigma(n) \iff \frac{\sigma(q^2)}{n} < \frac{\sigma(n)}{q^2}$$
hold.
Proof: Trivial.

Note that Corollary 2 proves that the list of inequalities given in the Problem Statement exhausts all possible cases.

We now claim that:
Theorem 3.  If $q^k n^2$ is an odd perfect number, then $q^2 < \sigma(n)$ and $n < \sigma(q^2)$ cannot be both true.
Proof:
Suppose that both
$$1 < \frac{\sigma(q^2)}{n}$$
and
$$1 < \frac{\sigma(n)}{q^2}$$
hold.
Then it follows that both
$$\frac{\sigma(n)}{q^2} < \frac{\sigma(q^2)}{n}\cdot\frac{\sigma(n)}{q^2} = I({q^2}n) < \frac{62}{25}$$
and
$$\frac{\sigma(q^2)}{n} < \frac{\sigma(q^2)}{n}\cdot\frac{\sigma(n)}{q^2} = I({q^2}n) < \frac{62}{25}$$
hold.
This means that
$$\frac{\sigma(q^2)}{n}+\frac{\sigma(n)}{q^2} < 2\cdot\frac{62}{25} = \frac{124}{25}$$
which implies that
$$\frac{\sigma(q^2)}{n}+\frac{\sigma(n)}{q^2}$$
is bounded from above, contradicting (1).

Note that Theorem 3 immediately rules out Case (B) and Case (D) above.

INQUIRIES
We are left to consider the following two (2) remaining cases:

(A) $$q^2 < \sigma(q^2) < n < \sigma(n)$$
(C) $$n < \sigma(n) < q^2 < \sigma(q^2)$$

Question #1 By this answer, we know (?) that the implication $n < q^{k+1} \implies k \neq 1$ is true if and only if $q^2 < n$.  Can this result be improved?
Question #2 Following this answer, it is conjectured that $k \neq 1$.  This would follow if we could rule out $q = q^k < \sigma(q) = \sigma(q^k) < n < \sigma(n)$.  (That is, if we could prove that $\sigma(q^k) < n$ is false.)  To what extent can a proof along this thread of thought be pursued, given Brown's arguments for a partial proof of $q^k < n$ in A Partial Proof of a Conjecture of Dris and the considerations in this MSE post?

A: This post (and other related posts) seem to prove the following assertion:
CONJECTURE  If there is an odd perfect number, then there are infinitely many of them.
Proof:  Suppose that there are only a finite number of odd perfect numbers.
This means that there exists an effectively computable constant $\mathcal{C}$ such that
$$q^k n^2 < \mathcal{C}.$$
Since $q^k < n^2$ [Dris, 2012], then it follows that
$$q^{2k} < {q^k}{n^2} < \mathcal{C}.$$
This implies that
$$q^2 \leq q^{2k} < \mathcal{C},$$
so that
$$q < \mathcal{C}^{1/2}$$
which means that the Euler prime is bounded from above.
Note that we also have
$$n^2 < {q^k}{n^2} < \mathcal{C}$$
so that $n < \mathcal{C}^{1/2}$, that is to say, the square root of the non-Euler part (which is $n$) is bounded from above.
Going back to the considerations in this post, we either have $q^2 < n$ or $n < q^2$.  (In both cases, note that we have $q < n$ by [Brown, 2016], [Starni, 2017], and [Dris, 2017].)
In the first case, we have
$$q^2 < n < \mathcal{C}^{1/2}$$
so that
$$\frac{q^2}{n}+\frac{n}{q^2} < 1 + \frac{\mathcal{C}^{1/2}}{25}.$$
This contradicts (1) in the question.
In the second case, we have
$$q < n < q^2$$
so that $n > {10}^{500}$, and
$$\frac{q^2}{n}+\frac{n}{q^2} < 1 + \frac{\mathcal{C}}{{10}^{500}}.$$
Again, this contradicts (1) in the question, and the CONJECTURE in this answer is proved.


text:
Q: Go to LVM with an already non-LVM disk, how to? I plan to use LVM. My Ubuntu is currently non-LVM based.
I wonder if I can do that without resintalling or
if I can:

*

*resize current partition (call it part Old)

*create new partition (call it part LVM)

*clone part OLD files to part LVM files

*delete part old

And finally have the same Ubuntu LVM-based.
Is this naive vision possible ?
If not, which is the normal way ?
Thanks.

A: Yes, you can. You can even put your swap space and /boot files on the LVM so you will have two logical volumes: one for the swap space and the other for /.


text:
Q: How to remove query string from a url? I have the following URL:
https://stackoverflow.com/questions/7990301?aaa=aaa
https://stackoverflow.com/questions/7990300?fr=aladdin
https://stackoverflow.com/questions/22375#6
https://stackoverflow.com/questions/22375?
https://stackoverflow.com/questions/22375#3_1

I need URLs for example:
https://stackoverflow.com/questions/7990301
https://stackoverflow.com/questions/7990300
https://stackoverflow.com/questions/22375
https://stackoverflow.com/questions/22375
https://stackoverflow.com/questions/22375

My attempt:
url='https://stackoverflow.com/questions/7990301?aaa=aaa'
if '?' in url:
    url=url.split('?')[0]
if '#' in url:
    url = url.split('#')[0]

I think this is a stupid way

A: You can split on something that doesn't exist in the string, you'll just get a list of one element, so depending on your goal, you could do something like this to simplify your existing code:
url = url.split('?')[0].split('#')[0]

Not saying this is the best way (furl is a great solution), but it is a way.

A: In your example you're also removing the fragment (the thing after a #), not just the query.
You can remove both by using urllib.parse.urlsplit, then calling ._replace on the namedtuple it returns and converting back to a string URL with urllib.parse.unsplit:
from urllib.parse import urlsplit, urlunsplit

def remove_query_params_and_fragment(url):
    return urlunsplit(urlsplit(url)._replace(query="", fragment=""))

Output:
>>> remove_query_params_and_fragment("https://stackoverflow.com/questions/7990301?aaa=aaa")
'https://stackoverflow.com/questions/7990301'
>>> remove_query_params_and_fragment("https://stackoverflow.com/questions/7990300?fr=aladdin")
'https://stackoverflow.com/questions/7990300'
>>> remove_query_params_and_fragment("https://stackoverflow.com/questions/22375#6")
'https://stackoverflow.com/questions/22375'
>>> remove_query_params_and_fragment("https://stackoverflow.com/questions/22375?")
'https://stackoverflow.com/questions/22375'
>>> remove_query_params_and_fragment("https://stackoverflow.com/questions/22375#3_1")
'https://stackoverflow.com/questions/22375'

A: You could try
urls = ["https://stackoverflow.com/questions/7990301?aaa=aaa",
"https://stackoverflow.com/questions/7990300?fr=aladdin",
"https://stackoverflow.com/questions/22375#6",
"https://stackoverflow.com/questions/22375"?,
"https://stackoverflow.com/questions/22375#3_1"]

urls_without_query = [url.split('?')[0] for url in urls]

for example, "https://stackoverflow.com/questions/7990301?aaa=aaa".split() returns a list that looks like ["https://stackoverflow.com/questions/7990301", "aaa=aaa"], and if that string is url, url.split('?')[0] would give you "https://stackoverflow.com/questions/7990301".
Edit: I didn't think about # arguments. The other answers might help you more :)

A: The very helpful library furl makes it trivial to remove both query and fragment parts:
>>> furl.furl("https://hi.com/?abc=def#ghi").remove(args=True, fragment=True).url
https://hi.com/

A: You can use w3lib
from w3lib import url as w3_url
url_without_query = w3_url.url_query_cleaner(url)

A: Here is an answer using standard libraries, and which parses the URL properly:
from urllib.parse import urlparse

url = 'http://www.example.com/this/category?one=two'
parsed = urlparse(url)
print("".join([parsed.scheme,"://",parsed.netloc,parsed.path]))

expected output:
http://www.example.com/this/category
Note: this also strips params and the fragment, but is easy to modify to include those if you want.


text:
Q: regression - is there any linear unbiased estimator of E(y|x) with a lower variance than the OLS solution? In linear regression, Gauss-Markov theorem states that the $\hat{\beta}$ (estimator of $\beta$) by OLS has the minimum variance than other linear unbiased estimators.
So I was wondering that if it can also applied for the estimator of E(y|x)?
In other words, does $\hat{y}$ = $X\hat{\beta}$ have the minimum variance among any other linear unbiased estimator of E(y|x)?
And how to proof this?
Any suggestion is grateful.
Thanks!

A: If $E[Y|X=x]$ is linear,   i.e., for example $\beta_0 + \beta_1x$, then $\hat{\beta}_0 + \hat{\beta}_1x$ the it is still unbiased and have minimal variance (as the best linear predictor). However, if $E[Y|X=x] = g(\beta; x)$ is nonlinear, then $g(\hat{\beta}; x)$ is simply biased by the Jensen inequality, thus clearly is not a minimal variance unbiased estimator.


text:
Q: Как убрать ошибку: error: Entities and Pojos must have a usable public constructor Как решить ошибку:
error: Entities and Pojos must have a usable public constructor. You can have an empty constructor or a constructor whose parameters match the fields (by name and type).
Tried the following constructors but they failed to match:
Category(int,java.lang.String,java.lang.String,java.lang.String,java.lang.String,int,boolean,boolean,int) -> [param:n2 -> matched field:unmatched, param:string2 -> matched field:unmatched, param:string3 -> matched field:unmatched, param:string4 -> matched field:unmatched, param:string5 -> matched field:unmatched, param:n3 -> matched field:unmatched, param:bl -> matched field:unmatched, param:bl2 -> matched field:unmatched, param:n4 -> matched field:unmatched]

Пробовал искать в интернете, но там дают советы для Kotlin.
Вот код:
@Entity
public class Category implements Comparable<Category>, MenuPosition {
  @ColumnInfo(name="has_products")
  private boolean hasProducts;
  @ColumnInfo(name="has_subgroups")
  private boolean hasSubgroups;
  @PrimaryKey
  private int id;
  private String image;
  @ColumnInfo(name="image_checksum")
  private String imageChecksum;
  @ColumnInfo(name="image_thumb")
  private String imageThumb;
  @ColumnInfo(name="parent_id")
  private int parentId;
  private int position;
  private String title;

public Category(int n2, String string2, String string3, String string4, String string5, int n3, boolean bl, boolean bl2, int n4) {
    this.id = n2;
    this.image = string2;
    this.imageThumb = string3;
    this.imageChecksum = string4;
    this.title = string5;
    this.position = n3;
    this.hasSubgroups = bl;
    this.hasProducts = bl2;
    this.parentId = n4;
}

@Override
public int compareTo(@NonNull Category category) {
    return Integer.compare(this.position, category.position);
}

@Override
public String getIcon() {
    return this.imageThumb;
}

@Override
public int getId() {
    return this.id;
}

public String getImage() {
    return this.image;
}

public String getImageChecksum() {
    return this.imageChecksum;
}

public String getImageThumb() {
    return this.imageThumb;
}

@Override
public String getImageUrl() {
    return this.image;
}

@Override
public String getMenuTitle() {
    return this.title;
}

public int getParentId() {
    return this.parentId;
}

public int getPosition() {
    return this.position;
}

public String getTitle() {
    return this.title;
}

public boolean isHasProducts() {
    return this.hasProducts;
}

public boolean isHasSubgroups() {
    return this.hasSubgroups;
}

@Override
public boolean isProduct() {
    return false;
}

public void setParentId(int n2) {
    this.parentId = n2;
}

}


text:
Q: AgGrid 26 ServerSide DataSource does not stop loading rows Version: AgGrid 26.0.1
Problem: AgGrid does not display loaded rows, keeps firing requests to the backend with the same startRow (endRow argument changes to the last row number after first request is fired and remains the same afterwards), always shows the loading indicator.
My AgGrid options:
      <AgGridReact
        debug
        modules={AllModules}
        defaultColDef={defaultColDef}
        frameworkComponents={{ [CellRenderer.Action]: ActionCellRenderer, [CellRenderer.Button]: ButtonCellRenderer }}
        context={context}
        rowData={rows}
        rowModelType={onRowsFetch ? 'serverSide' : 'clientSide'}
        serverSideStoreType={ServerSideStoreType.Partial}
        serverSideDatasource={{ getRows }}
        rowBuffer={0}
        cacheBlockSize={50}
        maxBlocksInCache={shouldHideRow ? undefined : 100}
        blockLoadDebounceMillis={1000}
        maxConcurrentDatasourceRequests={1}
        infiniteInitialRowCount={1}
        suppressContextMenu
        colResizeDefault="shift"
        columnDefs={columnDefs}
        columnTypes={columnTypes.reduce((ac, a) => ({ ...ac, [a]: {} }), {})}
        onGridReady={onGridReady}
        onModelUpdated={resizeColumns}
        onGridSizeChanged={onGridSizeChanged}
        onFilterChanged={handleFilterChange}
        onSortChanged={handleSortChange}
        onToolPanelVisibleChanged={resizeColumns}
        rowSelection="multiple"
        suppressRowClickSelection
        suppressMovableColumns
        suppressColumnMoveAnimation
        suppressMenuHide
        sideBar={disableSideBar ? false : sideBarDef}
        alwaysShowVerticalScroll={!disableVerticalScroll}
        scrollbarWidth={disableVerticalScroll ? 0 : undefined}
      />

onGridReady:
  function onGridReady({ api, columnApi }: GridReadyEvent) {
    gridApi.current = api;
    gridColumnApi.current = columnApi;
    api.sizeColumnsToFit();
    api.setFilterModel({});
  }

My serverSideDatasource config (getRows):
  async function getRows({ request, successCallback, failCallback }: IServerSideGetRowsParams) {
    if (!onRowsFetch) {
      return;
    }

    try {
      const lastPageLoadedBefore = request.endRow >= lastRow.current && lastRow.current !== 0;
      const result = await onRowsFetch({
        startRow: request.startRow,
        endRow: lastPageLoadedBefore ? lastRow.current : request.endRow,
        sort: parseSortModel(request.sortModel),
        filter: parseFilterModel(request.filterModel),
      });
      lastRow.current = result.data.lastRow ?? 0;
      successCallback(result.data.content, request.endRow);
    } catch (error) {
      failCallback();
      throw error;
    }
  }

Everything worked fine with AgGrid v24. The only thing that has been changed since the version update was that I've added serverSideStoreType={ServerSideStoreType.Partial} to the grid options.
I have tried changing successCallback lastRow parameter to -1, 0, 1 and undefined but the requests keep firing no matter what. What am I missing?


text:
Q: swift append to file if exists or create file otherwise I want to write a String to a file. If the file doesn't exist it should be created.
If it does, the String should be appended.
I tried:
    let data = text.data(using: String.Encoding.utf8)
    let filemgr = FileManager.default
    let path = filemgr.urls(for: FileManager.SearchPathDirectory.documentDirectory, in: FileManager.SearchPathDomainMask.userDomainMask).last?.appendingPathComponent("out.txt")
    if !filemgr.fileExists(atPath: (path?.absoluteString)!) {
        filemgr.createFile(atPath: (path?.absoluteString)!, contents: data, attributes: nil)
    } else {
        var file = FileHandle(forReadingAtPath: (path?.absoluteString)!)
        let databuffer = String(describing: file?.readDataToEndOfFile())
        file = FileHandle(forWritingAtPath: (path?.absoluteString)!)
        if file != nil {

            file?.seek(toFileOffset: 10)
            file?.write(data!)
            file?.closeFile()
        }
    }

so far the file doesn't even seem to get created, since it jumps to the createFile every time. what am I doing wrong?

A: Use (path?.path)! instead of (path?.absoluteString)!.


text:
Q: WebDriver: Select a value from the drop down by using Javascript executor Application that I am working on has drop downs implemented using AngularJS. The values load on the click of the drop down field and when user selects the element, the value is stored in the drop down field.
What I have tried to make it work?

*

*Wait for the object to be visible/clickable before clicking on the value to be selected

*Move to the element before clicking on it (using action class)

*Get the list of the elements, iterate and select the value

I am able to currently make this work in Firefox and Chrome using the following code. This works fine when I am running the test scripts sequentailly but fails to work when I run tests in parallel..
    WebDriver driver = getDriver();
    JavascriptExecutor executor = (JavascriptExecutor) driver;
    executor.executeScript("arguments[0].click();", element);

Is there a better solution to do this??
I am not good at java scripts, but I believe this is the js that is called when user selects the value. Is there a way to find out what is the return value this function is expecting so that  we can return the value directly to the browser using JavaScriptExecutor..
Any direction on this will be greatly appreciated.. I have been stuck in this for quite few days now.. Thank you...!
return function(i, o, a, s, l) {
                    var u = a.groupBy,
                        c = a.groupFilter;
                    if (s.parseRepeatAttr(a.repeat, u, c), s.disableChoiceExpression = a.uiDisableChoice, s.onHighlightCallback = a.onHighlight, u) {
                        var d = o.querySelectorAll(".ui-select-choices-group");
                        if (1 !== d.length) throw n("rows", "Expected 1 .ui-select-choices-group but got '{0}'.", d.length);
                        d.attr("ng-repeat", t.getGroupNgRepeatExpression())
                    }
                    var f = o.querySelectorAll(".ui-select-choices-row");
                    if (1 !== f.length) throw n("rows", "Expected 1 .ui-select-choices-row but got '{0}'.", f.length);
                    f.attr("ng-repeat", t.getNgRepeatExpression(s.parserResult.itemName, "$select.items", s.parserResult.trackByExp, u)).attr("ng-if", "$select.open").attr("ng-mouseenter", "$select.setActiveItem(" + s.parserResult.itemName + ")").attr("ng-click", "$select.select(" + s.parserResult.itemName + ",false,$event)");
                    var p = o.querySelectorAll(".ui-select-choices-row-inner");
                    if (1 !== p.length) throw n("rows", "Expected 1 .ui-select-choices-row-inner but got '{0}'.", p.length);
                    p.attr("uis-transclude-append", ""), r(o, l)(i), i.$watch("$select.search", function(e) {
                        e && !s.open && s.multiple && s.activate(!1, !0), s.activeIndex = s.tagging.isActivated ? -1 : 0, s.refresh(a.refresh)
                    }), a.$observe("refreshDelay", function() {
                        var t = i.$eval(a.refreshDelay);
                        s.refreshDelay = void 0 !== t ? t : e.refreshDelay
                    })
                }

Below is the html of the drop down. DIV is loaded only when user clicks on the drop down arrow. I want to select 'Value1' or 'Value2' in this.
    <div class="ui-select-container ui-select-bootstrap dropdown ui-select-container ui-select-bootstrap dropdown ng-pristine ng-touched error open" ng-class="{open: $select.open}" gw-field-empty="" style="position: absolute; left: 502px; top: 1467px; width: 228.75px;" ng-change="loanBoarding.vm.loanReceipt.isOverFlow = false;loanBoarding.validateContact()" ng-disabled="shouldDisable([loanBoarding.parent.loan.isApplicationEditable && perms.editLoanBoarding && (!loanBoarding.parent.loan.currentApplicationDisposition ? true : perms.updLoan1stDisp), loanBoarding.parent.loan.isApplicationEditable && !loanBoarding.parent.loan.isLoanInUWPhase]) || (loanBoarding.isLocationDisabled || (!!loanBoarding.parent.loan.commitmentNumber && !perms.editLocationType))" ng-model="loanBoarding.vm.loanPath.locationType" name="locationType">

<input class="form-control ui-select-search ng-pristine ng-untouched ng-valid" type="text" ng-show="$select.searchEnabled && $select.open" ng-model="$select.search" placeholder="" aria-activedescendant="ui-select-choices-row-11-0" aria-owns="ui-select-choices-11" aria-label="Select box" aria-expanded="true" tabindex="-1" autocomplete="off" style=""/>

 0" role="listbox" repeat="d.value as d in loanBoarding.locationTypes | filter: { text: $select.search }" style="opacity: 1;">

 0"/>

Value2

Value3

<ui-select-single/>
<input id="focusser-11" class="ui-select-focusser ui-select-offscreen ng-scope" type="text" role="button" aria-haspopup="true" aria-label="Select box focus" ng-disabled="$select.disabled" tabindex="1" disabled=""/>


text:
Q: Displaying fields dependent on SQL values in Rails Views was wondering if anyone can help me.
I'm just starting ou so this may seem a bit mundane to some people. I
have a view which I need to display certain fields if a particular
value is selected in the database.
The example is similar to a blog post where you may or may not want to
show a source link. So in the backend there is a tick box which is
attached to a sql boolean value then if that is ticked you can also
put the link in for the source location.
On the front end however if the boolean is set to false  I don't want
to display the data in that field. What's the best way of going about
this?

A: You can use conditionals in erb views.
For example:
<% if @v == 4 %>

v is equal 4.

<% else %>

v isn't equal 4.

<% end %>


text:
Q: getting data from excel sheet put them as dropdowns in shiny app I have made an shiny app where I am giving a fileInput where user can input an excel sheet like this: 'enter image description here'. I have designed an app which looks like this: 'enter image description here'. My code is this:
library(shiny)
library(readxl)
library(tidyverse)

ui <- fluidPage(
  fileInput("config","Load Configuration File",accept =c('.xls',',xlsx')),
  actionButton("show_fields","Show Fields"),
  actionButton("estimate","Estimate"),
  uiOutput("ui"),
  textOutput("prod")

)
server <- function(input,output) {

  x <- reactive({read_excel(input$config$datapath)})
  conf <- reactive({x() %>% column_to_rownames(., var = "Rows")})
  design <- eventReactive(input$show_fields, {
    fluidPage(
      numericInput("size","Size",value = 0),
      lapply(1:nrow(conf()),function(i) {
        selectInput(row.names(conf())[i],label = row.names(conf())[i],choices = colnames(conf()))
      })
    )
  })
  output$ui <- renderUI({design()})

  mul <- eventReactive(input$estimate, {
    sapply(1:nrow(conf()), function(j) {
      conf()[row.names(conf())[j],eval(parse(text = paste0("input$",row.names(conf())[j],sep = "")))]
    })
  })

  output$prod <- renderText({paste("Product is: ",prod(mul(),na.rm = TRUE)*input$size)})

}

shinyApp(ui=ui,server = server)

when loading the xls sheet, 'Show Fields' button will show all the Rows as Drop-downs with columns as choices. So at last whatever I choose upon clicking 'Estimate' button Product will be shown of all corresponding values from excel sheet and the inputed size.
So now what I want:
1: All the boxes (numericInput & selectInputs) shall come in two or three columns. The page shall look filled.
2: The actual excel sheet I do have is not exactly I have shown above. It is actually like one you can see in the following image: 'enter image description here'.
Here A-E,U-Z,K-O are drop-downs choices, for corresponding rows(like A-Z for Ram, Shyam etc. , U-Z for Predeep, Sudeep and K-O for Aneeta). I want each such dropdowns and whatever user selects I need to provide the product of all corresponding values from excel sheet along with given Size.
I am trying this out for many days now, and now I am frustated. Somebody please do it.


text:
Q: Radio button always select the first one regardless which one is selected I don't know why, whenever any of these radio button is clicked, it always select the first one. The radio buttons are auto-generated by the values from the database. How can I fix this?
The Blaze template:

   {{#each OnlyUsersSchool}}

        <input type="radio" id="schoolsstudent" name="schoolsstudent" value="{{_id}}">{{addschoolname}}, {{trimString geocomplete 0 40}}

   {{/each}}

The helper function:
OnlyUsersSchool: function () {
        var subValues = Meteor.subscribe('allUserSchools');
        if (Meteor.userId() && subValues.ready()) {
            if (Meteor.user().emails[0].verified) {
                return SchoolDb.find({userId: Meteor.userId()}).fetch().reverse();
            } else {
                Bert.alert('Please verify your account to proceed', 'success', 'growl-top-right');
            }
        }
    }

A: Sorry, It was a mistake on my part. I ought to change id to be unique. So finally. This is what worked.

   {{#each OnlyUsersSchool}}

         <input type="radio" id="{{_id}}" name="schoolsstudent" value="{{_id}}">
         {{addschoolname}}, {{trimString geocomplete 0 45}}

    {{/each}}


text:
Q: VB.net Recognize strings under 'a*' I am trying to Write a program to recognize strings under 'a*'
PROGRAM LOGIC: By using transition diagram i want to verify input of the state.
 If the state recognize  the given pattern rule. Then print string is accepted under a*      Else print string not accepted.
this is what i have tried
      Dim regex As Regex = New Regex("\ba*\b")
      Dim match As Match = regex1.Match(txt_input.Text)
 If match.Success Then
        lbl_output.Text = txt_input.Text & " is accepted under rule 'a*'"
 Else
            lbl_output.Text = txt_input.Text & " is not recognized"
        End If

the problem is when i enter string like saa is will accept it. it allows any character to come before the character a.
i want it to accept only when the string contains the character a. for example a,aaa,aaa,

A: Why not try the following regex:
^a+$

Code:
Dim regex As Regex = New Regex("^a+$")
Dim match As Match = regex.Match("aaaa")
If match.Success Then
    Console.WriteLine("match")
Else
    Console.WriteLine("no match")
End If

Demo here:
Rextester

A: Try below
Dim regex As Regex = New Regex("\ba\S*\b")


text:
Q: New Tensorflow 2.4 GPU issues Question
Tensorflow 2.4.1 doesn't recognize my GPU, even though I followed the official instructions from Tensorflow as well as the ones from NVIDIA for CUDA and NVIDIA for cuDNN to install it in my computer. I also installed it in conda (which I'm not sure if it is needed?).
When I try the official way to check if TF is using GPUs, I get 0:
import tensorflow as tf
print("Num GPUs Available: ", len(tf.config.list_physical_devices('GPU')))

Num GPUs Available: 0

Specifications
Hardware:
My NVIDIA fulfills the requirements specified by Tensorflow.
Software
I installed CUDA (with CUPTI) and cuDNN as mentioned above, so I got:

*

*ubuntu 20.04 LTS

*NVIDIA driver = 460.39

*CUDA (+CUPTI) = 11.2

*cuDNN = 8.1.1
In a conda environment I have:

*

*python = 3.8

*tensorflow = 2.4.1 (which I understand is the new way of having the GPU support)

and I installed extra the cudatoolkit==11.0 and cudnn==8.0 for conda as mentioned here.
Procedure followed:
It did not work when I didn't have the conda extra packages, and it still doesn't work even though I installed those extra packages.

A: After quite a bit of extensive research, it finally works on my computer: the latest versions of the components (i.e. CUDA 11.2, cuDNN 8.1.0) are not tested and not ensure a working result in TF 2.4.1. Therefore, this is my final configuration:

*

*nvidia-drivers-460.39 have CUDA 11.2 drivers. However, you can still install CUDA 11.0 runtime and get it from the official NVIDIA archive for CUDA. Following the installing instructions is still mandatory (i.e. adding the path variables and so on).

*cuDNN library needs to be on the version 8.0.4. You can get it also from the official NVIDIA archive for cuDNN
After installing both components on these specific versions, I successfully get:
import tensorflow as tf
print("Num GPUs Available: ", len(tf.config.list_physical_devices('GPU')))

Num GPUs Available: 1

with a few debut messages indicating that the GPU libraries were correctly imported.
EDIT:
By the way! For the folks out there who use Pycharm, either you include the environment variables also in PyCharm, or make them system-wide. Otherwise you won't still get your TF to get the GPUs.


text:
Q: How to debug python script started with python27.dll from gVim? I am using gVim on windows 7.
I am trying to investigate why rope (as part of python-mode plugin) shows me a lot of errors when I trying to use auto complete feature.
Opening [C:windowssystem32] project ...
Error detected while processing function RopeCodeAssistInsertMode..RopeCodeAssist:
line    1:
  File "<string>", line 1, in <module>
And so on...

gVim uses python27.dll for evaluating python code.
Are there ways for debugging gVim plugins?
Can I to attach to gVim for debug python code, evaluated from gVim?


text:
Q: How can I check if IP is a Tor exit node? I have someone attacking my site and it would seem some of the IPs are Tor exit nodes.
Is there somewhere I can input an IP and definitively see if it's registered as a Tor exit node?

A: The Tor Project has a tool to do this at:
https://exonerator.torproject.org/
For automated lookups, they also provide a DNSBL-based lookup; information on that is available at:
https://www.torproject.org/projects/tordnsel.html.en

A: I actually implemented the solution @duskwuff suggested.
Check it out at - https://github.com/assafmo/IsTorExit
CLI:
npm install -g istorexit
istorexit [ip...]

NodeJs:
const IsTorExit = require("istorexit");
IsTorExit("104.200.20.46").then(console.log); // true
IsTorExit("1.1.1.1").then(console.log); // false

A: https://www.ipqualityscore.com/tor-ip-address-check/lookup
On this link you can check if IP is an tor exit node.

A: Here's a perl solution based on https://github.com/assafmo/IsTorExit
my @ips = ('1.1.1.1','1.2.1.1','1.3.1.1','1.4.1.1','1.5.1.1','104.200.20.46');
foreach (@ips)
{
    print("IP: $_\n");

    # Build the command by reversing the IP address (ie. 1.5.1.1 to 1.1.5.1)
    # Checking 1.5.1.1 via 1.1.5.1.dnsel.torproject.org
    # (https://2019.www.torproject.org/projects/tordnsel.html.en - How can I query the public TorDNSEL service?)
    # Lookup from a linux system using dig (+short to have a light answer)
    my $cmd = "dig +short ".join(".", reverse split(/\./, $_)).".dnsel.torproject.org";
    my $res = `$cmd`;
    $res =~ s/^\s^|\s+$//g;
    print(" Command: [$cmd] ; Result: [$res]\n");

    # A records inside net 127/8, except 127.0.0.1, are reserved for future use
    # and should be interpreted by clients as indicating an exit node
    # (https://2019.www.torproject.org/projects/tordnsel.html.en - What do the received answers mean?)
    my $is_tor = 0;
    $is_tor = 1 if ($res =~ /^127\.0\.0\./ && $res ne "127.0.0.1");
    print(" Is Tor? [$is_tor]\n");
}

A: Download the list of all exit node IPs from https://check.torproject.org/torbulkexitlist and check whether the IP is in the list.
Alternatively, you can do a DNS query to check a single IP address. Make a DNS A query to [reverse ip address].dnsel.torproject.org. If it returns 127.0.0.2, then the IP is a Tor exit IP address. For example, to check the 12.34.56.78 address, you can run this console command:
nslookup 78.56.34.12.dnsel.torproject.org

If it returns Address: 127.0.0.2, then it's a Tor IP.


text:
Q: Connect to Azure Data Lake Gen 2 from local Spark job I'm trying to connect from a local Spark job to my ADLS Gen 2 data lake to read some Databricks delta tables, which I've previously stored through a Databricks Notebook, but I'm getting a very weird exception, which I can't sort out:
Exception in thread "main" java.io.IOException: There is no primary group for UGI <xxx> (auth:SIMPLE)
    at org.apache.hadoop.security.UserGroupInformation.getPrimaryGroupName(UserGroupInformation.java:1455)
    at org.apache.hadoop.fs.azurebfs.AzureBlobFileSystemStore.<init>(AzureBlobFileSystemStore.java:136)
    at org.apache.hadoop.fs.azurebfs.AzureBlobFileSystem.initialize(AzureBlobFileSystem.java:108)
    at org.apache.hadoop.fs.FileSystem.createFileSystem(FileSystem.java:3303)
    at org.apache.hadoop.fs.FileSystem.access$200(FileSystem.java:124)
    at org.apache.hadoop.fs.FileSystem$Cache.getInternal(FileSystem.java:3352)
    at org.apache.hadoop.fs.FileSystem$Cache.get(FileSystem.java:3320)
    at org.apache.hadoop.fs.FileSystem.get(FileSystem.java:479)
    at org.apache.hadoop.fs.Path.getFileSystem(Path.java:361)
    at org.apache.spark.sql.delta.DeltaTableUtils$.findDeltaTableRoot(DeltaTable.scala:94)

Searching around, I've not found many hints on this. One, which I tried was to pass the config "spark.hadoop.hive.server2.enable.doAs", "false", but it didn't help out.
I'm using io.delta 0.3.0, Spark 2.4.2_2.12 and azure-hadoop 3.2.0.
I can connect to my Gen 2 account without issues through an Azure Databricks Cluster/ Notebook.
I'm using code like the folling:
 try(final SparkSession spark = SparkSession.builder().appName("DeltaLake").master("local[*]").getOrCreate()) {
            //spark.conf().set("spark.hadoop.hive.server2.enable.doAs", "false");
            spark.conf().set("fs.azure.account.key.stratify.dfs.core.windows.net", "my gen 2 key");
            spark.read().format("delta").load("abfss://myfs@myaccount.dfs.core.windows.net/Test");
}

A: ADLS Gen2 requires Hadoop 3.2, Spark 3.0.0, and Delta Lake 0.7.0. The requirements are documented in https://docs.delta.io/latest/delta-storage.html#azure-data-lake-storage-gen2
ADLS Gen2 Hadoop connector is only available in Hadoop 3.2.0, and Spark 3.0.0 is the first Spark version that supports Hadoop 3.2.
Databricks Runtime 6.x and older versions runs Hadoop 2.7 and Spark 2.4 but ADLS Gen2 Hadoop connector is backported to this old Hadoop version internally. That's why Delta Lake can work in Databricks without upgrading to Spark 3.0.0.


text:
Q: ol.inherits in OpenLayers 6 I'm testing OpenLayers 6 beta.
ol.inherits looks missing in OpenLayers 6.
ol.inherits(ol.source.NowMap, ol.source.OSM);

This causes error
Uncaught TypeError: ol.inherits is not a function

What should I use instead?

A: It's mentioned in the update notes https://github.com/openlayers/openlayers/blob/master/changelog/upgrade-notes.md
A simple fix which the ol-ext library uses is to replace it with the something based on the old function
var ol_ext_inherits = function(child,parent) {
  child.prototype = Object.create(parent.prototype);
  child.prototype.constructor = child;
};

or see the OL6 examples for a method which will need some recoding
https://openlayers.org/en/master/examples/custom-controls.html
https://openlayers.org/en/master/examples/custom-interactions.html

A: Just a notice, as I do not have the reputation points requred for a proper comment. The suggested solutions is actually more in line with recomendations than the code given in the actual OpenLayers examples that are linked. Namely, the __proto__ method is deprecated and the proper method for inheritance is by using Object.create(). Link.
Cheers,
Miha


text:
Q: java.sql.SQLException: Access denied for user 'guacamole'@'172.17.0.4' in Guacamole Docker I am new to guacamole as well as docker. I am using mysql for the authentication.
The commands that i am trying are mentioned below
docker run --name some-guacd -d guacamole/guacd
docker run --name some-mysql -e MYSQL_ROOT_PASSWORD=root -d mysql:latest
docker run --name some-guacamole --link some-guacd:guacd --link some-mysql:mysql -e MYSQL_DATABASE=guacamole -e MYSQL_USER=guacamole -e MYSQL_PASSWORD=some_password -e MYSQL_ROOT_PASSWORD=root -v /local/path:/etc/guacamole -e GUACAMOLE_HOME=/etc/guacamole -d -p 8080:8080 guacamole/guacamole

but I am getting below provided exception.
Fri Mar 22 07:59:36 UTC 2019 WARN: Establishing SSL connection without
server's identity verification is not recommended. According to MySQL
5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established
by default if explicit option isn't set. For compliance with existing
applications not using SSL the verifyServerCertificate property is set to
'false'. You need either to explicitly disable SSL by setting useSSL=false,
or set useSSL=true and provide truststore for server certificate
verification.
Fri Mar 22 07:59:36 UTC 2019 WARN: Establishing SSL connection without
server's identity verification is not recommended. According to MySQL
5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established
by default if explicit option isn't set. For compliance with existing
applications not using SSL the verifyServerCertificate property is set to
'false'. You need either to explicitly disable SSL by setting useSSL=false,
or set useSSL=true and provide truststore for server certificate
verification.
07:59:36.126 [http-nio-8080-exec-7] ERROR o.a.g.rest.RESTExceptionMapper -
Unexpected internal error:
### Error querying database.  Cause: java.sql.SQLException: Access denied
for user 'guacamole'@'172.17.0.4' (using password: YES)
### The error may exist in
org/apache/guacamole/auth/jdbc/user/UserMapper.xml
### The error may involve
org.apache.guacamole.auth.jdbc.user.UserMapper.selectOne
### The error occurred while executing a query
### Cause: java.sql.SQLException: Access denied for user
'guacamole'@'172.17.0.4' (using password: YES)

And my guacamole.properties
guacd-hostname:localhost
guacd-port:4822
lib-directory:/var/lib/guacamole/classpath

#basic-user-mapping:/etc/guacamole/user-mapping.xml
#auth-provider:
net.sourceforge.guacamole.net.basic.BasicFileAuthenticationProvide
auth-
provider:net.sourceforge.guacamole.net.auth.mysql
.MySQLAuthenticationProvider
mysql-hostname:127.0.0.1
mysql-port:3306
mysql-database:guacamole
mysql-username:guacamole
mysql-password:some_password

I am not sure where am I doing wrong ?

A: Guacamole does not have a MYSQL_ROOT_PASSWORD environment variable like the MySQL container does. Instead, you specify a username and password to connect with. The simplest way to get the containers working with each other would be as follows:
docker run --name some-guacd -d guacamole/guacd
docker run --name some-mysql -e MYSQL_ROOT_PASSWORD=root -e MYSQL_DATABASE=guacamole -d mysql:latest
docker run --name some-guacamole --link some-guacd:guacd --link some-mysql:mysql -e MYSQL_DATABASE=guacamole -e MYSQL_USER=root -e MYSQL_PASSWORD=root -v /local/path:/etc/guacamole -e GUACAMOLE_HOME=/etc/guacamole -d -p 8080:8080 guacamole/guacamole

I removed the MYSQL_ROOT_PASSWORD variable and updated the other environment variables to reflect your MySQL config. I also updated the MySQL container environment variables to create the database you want the Guacamole data to go in.
One important thing to note: It is not secure to run Guacamole with the root MySQL user. I would recommend creating a new database user for Guacamole to run as and giving it proper permissions to the database.


text:
Q: Prob. 15, Sec. 1.3, in Herstein's TOPICS IN ALGEBRA 2nd ed: If $(m, n)=1$, then, given $a$ and $b$, there is an $x$ such that Here is Prob. 15, Sec. 3, in the book Topics in Algebra by I.N. Herstein, 2nd edition:

If $(m, n) = 1$, given $a$ and $b$, prove that there exists an $x$ such that $x \equiv a \mod m$ and $x \equiv b \mod n$.

[ Here $(m, n)$ denotes the Greatest Common Divisor (GCD) of the positive integers $m$ and $n$. ]
My Attempt:

We note that there is an integer $x$ such that $x \equiv a \mod m$ and $x \equiv b \mod n$ if and only if we have $m | (x-a)$ and $n | (x-b)$, which is the case if and only if there are integers $p$ and $q$ such that $x-a = mp$ and $x-b =nq$, and hence
  $$ a + mp = b +nq, $$
  which holds if and only if
  $$ mp - nq = b-a. \tag{1}$$
Now as $(m, n) = 1$, so by Lemma 1.3.1 in Herstein there exist integers $r$ and $s$ such that
  $$ mr + ns = 1, $$
  and hence
  $$ mr(b-a) + ns(b-a) = b-a. \tag{2} $$
Comparing (1) and (2) above, we find that if we put
  $$ x \colon= a + mr(b-a) = b - ns(b-a), $$
  then our desired conditions hold.

Is this proof correct? If so, is it rigorous enough for Herstein? If not, then where are the issues?


text:
Q: Sprite Kit: How to make a node "jump" and also move it left or right, dependant on node position and length of touch? This is my first post so go easy haha.
I'm new to 'iOS' 'coding', 'Xcode' and 'spritekit'. I'm looking to make an image node "jump" a distance on the positive y-axis if I touch anywhere on the screen, although if I touch somewhere to the left or right if the image and hold for a certain time, it moves in the respective left or right direction, a distance respective to the length of the touch.
Not sure if that's very clear, but any help would be appreciated! Thanks!

A: You could move a node like this
In touchesEnded: or touchesBegan: method:
{
node.position.y += 50;
}

In order for sprite to move somewhere you could also use actions, there is a family of actions like moveTo action.
I would suggest picking upa tutorial or a book about sprite kit. Good site with free tutorials is raywenderlich.com

A: Please Try this code :
a sprite move : left/right according to your touch direction anywhere on screen
  // CGPoint initialPos; // in .h file

  -(void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
  {
     UITouch *touch = [touches anyObject];
     CGPoint touchPt = [touch locationInView:touch.view];
     initialPos = [[CCDirector sharedDirector] convertToGL:touchPt];
  }
  -(void) ccTouchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
  {
     UITouch *myTouch=[touches anyObject];
     CGPoint currentPos=[myTouch locationInView:[myTouch view]];
     currentPos=[[CCDirector sharedDirector] convertToGL:currentPos];

     float diffX = currentPos.x - initialPos.x;
     float diffY = currentPos.y - initialPos.y;

     CGPoint velocity = ccp(diffX, diffY);
     initialPos = currentPos;
     [Sprite setPosition:ccpAdd([SmileBall position], velocity)];
  }

  - (void) ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
  {
     UITouch *myTouch=[touches anyObject];
     CGPoint currentPos=[myTouch locationInView:[myTouch view]];
     currentPos=[[CCDirector sharedDirector] convertToGL:currentPos];
     float diffX = currentPos.x - initialPos.x;
     float diffY = currentPos.y - initialPos.y;
     CGPoint velocity = ccp(diffX, diffY);
     initialPos = currentPos;
     [Sprite setPosition:ccpAdd([SmileBall position], velocity)];
  }

a sprite jump up: according to your touch on screen
  -(void) ccTouchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
  {
     CCSprite *RunningChar;
     RunningChar=(CCSprite *)[self getChildByTag:10];
     UITouch *touch = [touches anyObject];
     CGPoint touchPt = [touch locationInView:touch.view];
     touchPt = [[CCDirector sharedDirector] convertToGL:touchPt];

     float radian = ccpToAngle(ccpSub(touchPt, prevPoint));
     float degrees = CC_RADIANS_TO_DEGREES(radian);

     if (degrees >= 22.5 && degrees <= 112.5) // for upward direction :). otherwise you can write only code without ant condition
     {
         CCJumpTo *jump=[CCJumpTo actionWithDuration:0.7 position:CGPointMake(RunningChar.position.x, 87) height:110 jumps:1];
         [RunningChar runAction:seq];
     }
     else
     {

     }
  }

Try this :)


text:
Q: How to cryptographically verify the authenticity and integrity of Mozilla releases (Firefox, Thunderbird, etc) For a given software release published by Mozilla, how can I cryptographically verify the authenticity and integrity of the file that I downloaded before I execute it to install that program?
Today I wanted to download firefox and thunderbird for Windows, but the download page said nothing about how to verify the release after download.

*

*https://www.mozilla.org/en-US/firefox/all/#product-desktop-release
I expected to see a message telling me the fingerprint of their release signing key, a link to further documentation, and links to [a] a manifest file (eg SHA256SUMS) and [b] a detached signature of that manifest file (eg SHA256SUMS.asc, SHA256SUMS.sig, SHA256SUMS.gpg, etc)
How can I preform this verification with mozilla products, such as firefox and thunderbird?

A: Windows releases are signed using Authenticode, so the signature is embedded into the executable and the OS automatically verifies it upon launch against a Microsoft-maintained list of X.509 certificate authorities. The individual files extracted into 'C:\Program Files' are likewise Authenticode-signed when possible.
You can view the signature details in the file's "Properties" window, or using sigcheck (from Sysinternals), or using Get-AuthenticodeSignature (PowerShell cmdlet), or using signtool verify (part of Windows developer kit), or using osslsigncode verify (available in many Linux distributions).
Linux releases (source and pre-compiled) are signed using PGP, with a detached signature being available at the same URL + .asc suffix. They're at
https://ftp.mozilla.org/pub/firefox/releases/:

*

*https://ftp.mozilla.org/pub/firefox/releases/83.0/linux-x86_64/en-US/firefox-83.0.tar.bz2

*https://ftp.mozilla.org/pub/firefox/releases/83.0/linux-x86_64/en-US/firefox-83.0.tar.bz2.asc
(Mozilla's "Downloading the source code" article points to https://archive.mozilla.org, but that is basically the same server with the same contents.)
Of course, for PGP to be useful at all, you need to find some other way to verify the signing key instead of just grabbing it from the same directory. It seems Mozilla publishes their release keys on their blog.
As long as you're dealing with single files, a separate "SUMS" manifest is basically redundant – it only adds several extra steps for verification while doing nothing for the actual security. You get exactly the same value from verifying a signature made directly against the file that you wanted to verify.
Nevertheless, the Mozilla FTP server does include SHA256SUMS manifests containing every file belonging to the release (including Windows and macOS), together with a PGP signature.

*

*https://ftp.mozilla.org/pub/firefox/releases/83.0/SHA256SUMS

*https://ftp.mozilla.org/pub/firefox/releases/83.0/SHA256SUMS.asc