text:
Q: How to perform a transitivity mocking of classes/objects in python unit testing I am new to unittesting in python and was trying to mock a object explained like below:
i have three scripts:

*

*test1.py (Class : test1)

*test2.py (Class : test2)

*test3.py (Class : test3)

test2.py is creating object of test3.py
test1.py is creating object of test2.py
I want to mock test3 inside test1, so that when it creates object of test2 it consider mocking object of test3.
test3.py:
class test3():

    def __init__(self):
        print("Created object os myclass")
        self.name = "rahul"

test2.py:
from test3 import test3

class test2():

    def __init__(self):
        self.sirName = "Rohilla"
        self.test3object = test3()

test1.py:
from unittest import mock
from test3 import test3
from test2 import test2

class test1():

    @mock.patch('test3.test3') # -> here i tried __name__+'.test3' but that didn't work
    def fun2(self, myclass):
        mockObject = mock.MagicMock()
        mockObject = {}
        myclass.return_value = mockObject
        test2Object = test2() # -> here test2Object doesn't have mockobject

main1 = test1()

main1.fun2()

My problem is test2Object doesn't contain mockedobject for test3. can someone suggest me any other way?


text:
Q: Search (still) doesn't work well with URLs This question, Search doesn't work well with URLs, is about searching for posts with links to http://www.joelonsoftware.com/items/2007/10/26.html, and includes that link as plain text in the question (which is then auto-linkified).
Thus, if we search for posts with that link here on Meta, that post should come up.
Actual results vary.

*

*naive - http://www.joelonsoftware.com/items/2007/10/26.html - 0 results

*quotes - "http://www.joelonsoftware.com/items/2007/10/26.html" - 1 result

*url search - url:http://www.joelonsoftware.com/items/2007/10/26.html - 0 results

*url w/quotes - url:"http://www.joelonsoftware.com/items/2007/10/26.html" - 2 results

*url no protocol - url:www.joelonsoftware.com/items/2007/10/26.html - 0 results

*url no protocol quoted - url:"www.joelonsoftware.com/items/2007/10/26.html" - 0 results

*url w/wildcard - url:*.joelonsoftware.com/items/2007/10/26.html - 0 results

*url w/wildcard quoted - url:"*.joelonsoftware.com/items/2007/10/26.html" - 3 results
(Some or all of these searches will presumably have their results changed once this post is indexed, but the results should be reproducible with any other link.)
This answer, which also includes that exact text as the title of a link (but not the link target), is never found with any of these searches.
The search FAQ entry doesn't have any tips about these differing behaviors, and the advanced search tips just offers the terse url:"*.example.com" with no further explanation of the ins and outs.
I'm sure that there's some rhyme or reason to explain all this, but either the url: search restriction needs to be documented a lot better or the behavior fixed to be more intuitive (or both!).
Google is useless in this instance because real results are overwhelmed by spurious results for question list pages (which is a separate problem).

A: Please retry the results, I've made some search tweaks that will help in many cases.  The changes are as follows:

*

*/ and \ are now allowed

*URL searches are auto-wildcarded front and back

The combination of these should mean URL searches are much more intuitive overall.  I'm on the fence of if a URL should be wildcarded if you included quotes already meaning an exact match in most other situations.  If that becomes an issue then I'll adjust the behavior to not wildcard that case.

redpajama_set_name: RedPajamaStackExchange


text:
Q: SearchRecentSuggestionsProvider DATABASE_MODE_2LINES configures Recent Suggestions to add a second line of text. Where does that text come from? From this developer guide,

The database mode must include DATABASE_MODE_QUERIES and can optionally include DATABASE_MODE_2LINES, which adds another column to the suggestions table that allows you to provide a second line of text with each suggestion.

From this reference doc,

public static final int DATABASE_MODE_2LINES
This mode bit configures the database to include a 2nd annotation line
  with each entry. optional

The question is that where does this annotation line/text come from?
From what I have read in the developer guide so far, we are not providing any annotation text with our search query which would go in the extra column added in the suggestions table, and later served in Recent Suggestion List as the second annotation line.

A: You provide it when you save a search query to your collection of recent queries by calling saveRecentQuery(searchQuery, annotationText) on an instance of RecentQuerySuggestions:
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    Intent intent  = getIntent();

    if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
        String query = intent.getStringExtra(SearchManager.QUERY);
        SearchRecentSuggestions suggestions = new SearchRecentSuggestions(this,
                MySuggestionProvider.AUTHORITY, MySuggestionProvider.MODE);
        suggestions.saveRecentQuery(query, null); // *** The second argument is that annotation text
    }
}

Reference
From the reference of saveRecentQuery:

public void saveRecentQuery (String queryString, String line2)
Add a query to the recent queries list. Returns immediately,
  performing the save in the background.
Parameters
queryString   The string as typed by the user. This string will be displayed as the suggestion, and if the user clicks on the suggestion,
  this string will be sent to your searchable activity (as a new search
  query).
line2 If you have configured your recent suggestions provider with DATABASE_MODE_2LINES, you can pass a second line of text here. It will
  be shown in a smaller font, below the primary suggestion. When typing,
  matches in either line of text will be displayed in the list. If you
  did not configure two-line mode, or if a given suggestion does not
  have any additional text to display, you can pass null here.


text:
Q: keybd_event в DirectInput Можно ли как то поместить команду нажатия кнопки (по типу keybd_event из WinAPI) в буфер DirectInput?
Есть приложение в Windows которое не обрабатывает события генерируемые keybd_event. Обработка идет через DirectInput. Как сгенерировать события клавиатуры и мышки для такого приложения.
В библиотеке DirectInput, как я понял, есть только обработка девайсов. Но нет команд для генерации событий. Возможно есть способ отправить событие которое перехватит DirectInput?


text:
Q: Exception defined in thrift I have a thrift file written by some one else, where there are some dataformat exceptions. I have java generated files by thrift compiler which I barely understood.I am trying to validate some date input and it should throw that exception when input is not valid. I am really not sure whether I can use that exception or not.

A: It depends on the Thrift IDL file from which the code was generated. If the IDL is not present, the Details can be obtained by having a look into the generated deserialization methods for each function call, typically they are named somthing like recv_Foo() and recv_Bar().
exception MyError
{
  1: i32  code
}

exception UglyError
{
  1: i64  what_a_mess
}

Service Sample
{
  i32 Foo() throws (1: MyError me)
  i32 Bar() throws  (1: MyError me, 2: UglyError ue)
}

Foo() can throw only MyError, while Bar() can throw both exceptions. If you throw an UglyError while processing a Foo() call, the Client will not see this error (but probably another exception).


text:
Q: facebook like chat application in ASP.net I want to build web based facebook like lightweight chat for my site.
Website build on ASP .net on SQL server 2005.
I am interesetd in XMPP commmunication, but not able to find open source XMPP server with supportedlibrary for C# so that I can create client for my site.
Have checked googling butno luck for C# library; all I could found is plugin and jar.
Is it possible to implement chat logic and XMPP server communication in different language, and accessing thisdata through iframe or by other means on my site.
Thanks,
Hitesh.

A: http://www.ag-software.de/agsxmpp-sdk/
That library seems to be pretty good.

A: There are many options to send a message since first human! But how about the intelligence on it, automated collaboration in object level or shared objects among the users etc. I suggest you to take a look for the samples in here and feel the difference.

A: What you'll want to do is follow jgauffin's suggestion, and use an XMPP library on the backend, and then typically you'd add in a comet server for integration with your web frontend (we've actually done exactly this @ Frozen Mountain, using WebSync).
If you're building a smaller site and/or don't need the "realtime" aspect, you could probably get away with polling as well, in which case you'd need to store the results from the XMPP library in your own system, and poll that (since XMPP is strictly event driven).


text:
Q: Read "public" file content in a Revel app I am currently writing a Go web app using Revel.
My app needs to read the content of an XML file which is stored on the server. At the moment, I store this file in the "public" folder where some other resources (css, js...) lie.
I am using ioutil.ReadFile to read the content of this file. While this is working when the server is run from the main app folder itself, I cannot figure how to access the file when the server is run from another location (say by running "revel run myapp" from $GOPATH).
Is there any way to deal with this situation in revel?
is there a generic way to know the path of the "public" folder?
Any hint would be appreciated.
Thanks! :)

A: The base path of the application is stored and accessible through revel.BasePath.
The "public" folder can thus be accessed through revel.BasePath + "/public/<...>".
This BasePath value is used, for example, in Static.Serve.


text:
Q: Controlling Single Masonry Item Position I'm using masonry layout in WordPress so my local site's masonry layout is put together with loops. I've created a fiddle to explain my question.
How do I control the positioning of one item within a masonry layout?
I want a div to always be at the top right of the masonry container (to the right of my top left corner stamp)
How do I override the positioning that masonry assigns its .box items?
#container { max-width:635px; width:100%; }
.corner-stamp { background:gray;  width: 90px; height: 90px; }

.box {
  width: 90px;
  height: 90px;
  margin: 5px;
  background: #6AD;
  float: left;
}

/* I want to freely position this item with css */
#biggerBlock{
  width: 395px;
  height: 200px;
  background: #6AD;
  left:25%; /* overidden by masonry */
}

.box.large {
  background: #084;
  z-index: 2;
}

UPDATE:
David Desandro answered the question on the official Masonry Git page. The new isotope v2 will have this feature with the ability to include 2 corner-stamps. Thanks for the downvote.

A: There is no cornerStampSelector property in pure masonry now. You can use stamp option:

Specifies which elements are stamped within the layout. These are
  special layout elements which will not be laid out by Masonry. Rather,
  Masonry will layout item elements below stamped elements.

$container.masonry({
    columnWidth: 100,
    animate: true,
    stamp: '#biggerBlock'
  });

And stamp method:

Stamp the elements in the layout. Masonry will lay out item elements
  around stamped elements.

$container.masonry('stamp',$('#biggerBlock'));


text:
Q: VPN : Cannot reach my own gateway using ipsec/strongswan I've followed this tutorial to setup my private VPN using StrongSwan and IPSec. It works very well.
But when I try to connect directly to my gateway/server (using SSH), the connection does not go trough the VPN.
If I look for the tables in my client, I see :
$ netstat -nr

Routing tables

Internet:
Destination        Gateway            Flags        Refs      Use   Netif Expire
default            link#19            UCS            85        0  ipsec0
default            172.21.15.254      UGScI          18        0     en0
8.8.8.8            link#19            UHWIi           7       33  ipsec0
10.10.10.1         10.10.10.1         UH              0        0  ipsec0
13.32.153.9        link#19            UHW3I           0        3  ipsec0     10
17.248.144.80      link#19            UHWIi           2       22  ipsec0
17.252.76.33       link#19            UHWIi           1       40  ipsec0
18.184.56.218      link#19            UHWIi           1        1  ipsec0
54.37.155.XX       172.21.15.254      UGHS          397      197     en0
...

The last line is added to my client when I connect to the VPN. 54.37.155.XX is the public address of my server. I don't understand what process add this line to my routing table.
If I remove the last line, it works well :
sudo route -n delete 54.37.155.XX 172.21.15.254

I suspect that a missing rule in /etc/ipsec.conf config file is adding this routing entry, but I cannot figure out which one :
config setup
    charondebug="ike 1, knl 1, cfg 0"
    uniqueids=no

conn ikev2-vpn
    auto=add
    compress=no
    type=tunnel
    keyexchange=ikev2
    fragmentation=yes
    forceencaps=yes
    ike=aes256-sha1-modp1024,3des-sha1-modp1024!
    esp=aes256-sha1,3des-sha1!
    dpdaction=clear
    dpddelay=300s
    rekey=no
    left=%any
    leftid=@server_name_or_ip
    leftcert=/etc/ipsec.d/certs/vpn-server-cert.pem
    leftsendcert=always
    leftsubnet=0.0.0.0/0
    right=%any
    rightid=%any
    rightauth=eap-mschapv2
    rightdns=8.8.8.8,8.8.4.4
    rightsourceip=10.10.10.0/24
    rightsendcert=never
    eap_identity=%identity

Any idea ?

A: That's a known problem with macOS/iOS clients. The clients there install a direct route to the VPN server to prevent IKE traffic from getting tunneled via VPN. However, this means you can't access other services via the VPN server's public IP over the VPN either.
As a workaround, you could assign a virtual IP to the server from the subnet you used for virtual IPs assigned to clients. For instance, if you configure rightsourceip=10.10.10.2/24 then you can assign the reserved 10.10.10.1 to one of the server's interfaces and you should be able to access that IP from your VPN client.

A: As @ecdsa suggested, we need to change ipsec conf :
rightsourceip=10.10.10.2/24

Add those lines to /etc/network/interfaces.d/50-cloud-init.cfg :
iface ens3 inet static
    address 10.10.10.1/24

After, we can connect to the server trough vpn using 10.10.10.1 address


text:
Q: The signage of a displacement vector? Well, on my homework I had these two questions, but got a bit confused about what they are asking, and whether my answer is right or not.

*

*What is the sign of the displacement if you are moving away from the origin?

*What is the sign of the displacement if you are moving toward from the origin?

My thoughts are that for both questions the signage would be positive as the magnitude of the displacement will always be positive, since the lower limit (I think) is equal to 0.
Am I right, or is the signage differ for the displacement depending on if you move away/towards from the origin?

A: Displacement is the final position vector minus the initial position vector. In one dimension, the sign of the displacement indicates direction since we identify $e_1=1$ or $\hat{i}=1$. However, in two or more dimensions the sign is insufficient to give direction.
Let's consider one dimension. If you move left from the origin then the displacement is negative, whereas right motion starting from the origin gives positive displacement.


text:
Q: Expressions is showing id instead of value I've got the following code:
private EditText LeftBeam, BeamDistance, RightBeam;
private TextView Distance;
private float HeigtDifferenceBeams;
private float HeightLeftBeam, HeightRightBeam;

HeightLeftBeam = Float.parseFloat(LeftBeam.getText().toString());
HeightRightBeam = Float.parseFloat(RightBeam.getText().toString());

HeigtDifferenceBeams = Math.abs(HeightLeftBeam - HeightRightBeam);
DistanceBetweenBeams = Math.sqrt((Math.pow(HeigtDifferenceBeams, 2) + Math.pow(Float.parseFloat(BeamDistance.getText().toString()), 2)));

Distance.setText(String.format("%.2f",DistanceBetweenBeams));

When I run this on my device I get a FC. (07-08 20:22:43.399: ERROR/AndroidRuntime(25183): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.tricky_design.x/com.tricky_design.x.main}: java.lang.NullPointerException
When I run it in debug mode it get in the expression view "DistanceBetweenBeams"vis value (id=830126972712).
What is it that i'm doing wrong?
Already many thanks for your help.
Edit
I did instantiate the used editText and TextViews:
    LeftBeam = (EditText) findViewById (R.id.LeftBeam);
    LeftBeam.setOnLongClickListener(LongClickListener);
    LeftBeam.addTextChangedListener(TextChanged);

    RightBeam = (EditText) findViewById (R.id.RightBeam);
    RightBeam.setOnLongClickListener(LongClickListener);
    RightBeam.addTextChangedListener(TextChanged);

    Distance = (TextView) findViewById (R.id.DistanceTextView);

A: Your Distance TextView is not initialised, so it's null. That's the problem.
Distance needs to be made an object reference to a TextView in your layout, typically using findviewbyid().


text:
Q: Which GTK library emits these error messages? A snap CoqIDE installation on Debian 11.4 gives the following error messages:
Unable to init server: Could not connect: Connection refused
Fatal error: exception Gtk.Error("GtkMain.init: initialization failed\nml_gtk_init: initialization failed")

It has these dependencies, witnessed by the apt Debian package:
https://packages.debian.org/stable/coqide
dep: coq (= 8.12.0-3+b3)
    proof assistant for higher-order logic (toplevel and compiler)

dep: libc6 (>= 2.29) [not armel, mips64el, mipsel]
    GNU C könyvtár: megosztott könyvtárak
    also a virtual package provided by libc6-udeb

dep: libcairo2 (>= 1.12.0) [not armel, mips64el, mipsel]
    Cairo 2D vector graphics library

dep: libfontconfig1 (>= 2.12.6) [not armel, mips64el, mipsel]
    generic font configuration library - runtime

dep: libfreetype6 (>= 2.2.1) [not armel, mips64el, mipsel]
    FreeType 2 font engine, shared library files

dep: libgdk-pixbuf-2.0-0 (>= 2.22.0) [not armel, mips64el, mipsel]
    GDK Pixbuf library
or libgdk-pixbuf2.0-0 (>= 2.22.0)
    GDK Pixbuf library (transitional package)

dep: libglib2.0-0 (>= 2.35.9) [not armel, mips64el, mipsel]
    GLib library of C routines

dep: libgtk-3-0 (>= 3.1.4) [not armel, mips64el, mipsel]
    GTK graphical user interface library

dep: libgtksourceview-3.0-1 (>= 2.91.4) [not armel, mips64el, mipsel]
    shared libraries for the GTK+ syntax highlighting widget

dep: libpango-1.0-0 (>= 1.14.0) [not armel, mips64el, mipsel]
    Layout and rendering of internationalized text

If you are a developer using GTK, you might answer my question: which library emitted the two error messages?


text:
Q: How to output certain lines from a batch script result to a file I want to only output certain lines from a command result into another file.
This is my script
@echo off
del "C:\Users\admin\Desktop\script1results.txt"

cd C:\Users\ndujakov\DIG
for /f %%a in (C:\Users\admin\Desktop\script1inputs.txt) do (
dig %%a >> C:\Users\admin\Desktop\script1results.txt
)

Here are the results and what I want to specifically output
; <<>> DiG 9.10.6-P1 <<>> google.com
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 6710
;; flags: qr rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 1

;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 4096
;; QUESTION SECTION:
;google.com.            IN  A

;; ANSWER SECTION:
google.com.     248 IN  A   172.217.160.206    <---This one

;; Query time: 1 msec                          <---This one
;; SERVER: 10.231.0.106#53(10.231.0.106)
;; WHEN: Fri Feb 02 08:25:55 Pacific Standard Time 2018
;; MSG SIZE  rcvd: 55

A: You can get started with this batch file to filter your results :
@echo off
set "Inputfile=result.txt"
set "TmpFile=%Tmp%\%random%.txt"
set "OutPutFile=FilterResult.txt"
(FindStr /IR /C:"[0-9].[0-9].[0-9].[0-9]" /C:"msec" "%inputfile%")>"%TmpFile%"
(Findstr /IV "server" "%TmpFile%")>"%OutPutFile%"
Start "" "%OutPutFile%" & del "%TmpFile%"

Further Reading

*

*An A-Z Index of the Windows CMD command line - An excellent reference for all things Windows cmd line related.

*Findstr - Search for strings in files.


text:
Q: NoClassDefFoundError in GAE with Eclipse I'm trying to move an app running in Google app-engine from using the BlobstoreService Interface to the newer Cloud Storage without success.
To make things easier, I've started from scratch trying to run one of the Google provided examples (GitHub). I'm using Eclipse 4.6, Google Cloud SDK149.0.0 with the app-engine java version at 1.9.50. The code compiles flawlessly although does not work in the local environment (I expected that). However when deployed in GAE it fails at the runtime with a NoClassDefFoundError:

Uncaught exception from servlet
  java.lang.NoClassDefFoundError: com/google/api/services/storage/Storage$Builder
  at com.google.appengine.tools.cloudstorage.oauth.OauthRawGcsService.(OauthRawGcsService.java:175)
  at com.google.appengine.tools.cloudstorage.oauth.OauthRawGcsServiceFactory.createOauthRawGcsService(OauthRawGcsServiceFactory.java:41)
  at com.google.appengine.tools.cloudstorage.GcsServiceFactory.createRawGcsService(GcsServiceFactory.java:59)
  at com.google.appengine.tools.cloudstorage.GcsServiceFactory.createGcsService(GcsServiceFactory.java:44)
  at com.google.appengine.tools.cloudstorage.GcsServiceFactory.createGcsService(GcsServiceFactory.java:40)
  at com.clopez.storage.NewUpload.doPost(NewUpload.java:53)

My code (in fact Google's own code) fails at:
GcsService gcsService = GcsServiceFactory.createGcsService(RetryParams.getDefaultInstance());

As I've read in several other Stackoverflow posts, this is usually due to jars not present in my WEB-INF/lib directory so I've included there appengine-api-1.0-sdk-1.9.50.jar, appengine-gcs-client-0.6, com.google.guava_20.0.0, joda-time-2.9.9 and all the jars in the latest Google Java Client API. My WEB-INF directory once deployed is like:
Stackoverflow doesn't allow me to show pictures here, so here's the link
However this keeps failing and I'm astonished. I do not know how to move ahead.

A: I'm not using Maven so I need to manually include all the needed jars into WEB-INF/lib. Even if I copied all the libraries in the google-api-services-storage-v1-rev104-java-1.22.0.zip package I forgot to include the main one (not under the libs directory in that package). In short dropping google-api-services-storage-v1-rev104-1.22.0.jar into the WEB-INF/lib directory in Eclipse did the job. Thanks a lot.


text:
Q: Custom Arbitrary Mask or Keystroke format Adobe Acrobat I am trying to create a field in Acrobat that follows the formatting of 999-9999-9999[a-zA-Z]{0,1}.  So that the user doesn't have to type to dashes and the last character can be any alpha character but not required.
Examples of accepted:
123-4567-8912,
123-4567-8912h,
123-4567-8912H
Having a difficult time with Arbitrary Mask as I don't think there is an optional selection and I am unfamiliar with the Keystroke/Format under Custom.  Would love some direction or help.


text:
Q: Calling Powershell script from ASP.NET (C#), but not wait for results I have a powershell script that I want to call from a web page.  I have the c# code in and it works, but the script is ultimately doing some sql tasks that aren't speedy in return.  It doesn't have any results that I want to display to the web page, so I can't seem to get the web page to fire the script and then move on.  It keeps stating "waiting for server..." in the bottom of my browser even though there isn't anything to return.  Eventually the page times out.
I've tried to use the InvokeAsync() option, but it's still giving me the same results.  Would using Process.Start() have any better luck in calling a Powershell script and then moving on?
Thanks,
Greg
Runspace runspace = RunspaceFactory.CreateRunspace();
runspace.Open();
string cmdArg = scriptfile + " " + TextBox4.Text + " " + RadioButtonList1.SelectedValue;
//Collection<PSObject> psresults;
using (Pipeline pipeline = runspace.CreatePipeline())
{
    pipeline.Commands.AddScript(cmdArg);
    //psresults = pipeline.Invoke();
    pipeline.InvokeAsync(); // InvokeAsync calls it as a background process so it won't make the web page timeout.
}

runspace.Close();

A: You're using the Runspace pipeline asynchronously, but you opened your Runspace synchronously
Try to use :
runspace.OpenAsync();

Hope that helped :)

A: You should not be putting the runspace in a using clause - it will try to dispose it immediately after the invokeasync call, and block. You should instead be disposing the runspace in a callback.


text:
Q: Android Studio java autocomplete doesn't work after a while and Android Studio project doesn't recognize some classes The java icon does not appear in the square in the picture and the autocomplete does not work. As an example from the screenshot, the LiquidPager color is green and turns white when this problem occurs.
This problem arose after updating android studio to version 4.1.1. Then I installed the old version again but the problem did not fix.
I did delete .idea all .iml files inside the project then invalidate & restart build project again. But no luck, no matter what I did it doesn't get resolved. I have an old backup of this project and not a recent one, so I want to get this fixed . No problem with XML autocomplete.
problem screenshoot


text: Q: selenium webdriver is not recognizing web elements I am working with selenium webdriver and testNG. It seems selenium webdriver is not recognizing elements. what can be the reason for it. I have tried to recognize elements by xpath/css/id/link nothing is working. I am not able able to understand what is happening exactly. Can somebody please guide. I am also using the implicit wait command.


text:
Q: Images uploaded into ActionText text area not linking correctly to S3 I am using ActionText with image upload using the image_processing gem.  However, when uploading images they do not go to S3 which is set in Active Storage.
All other image uploads work fine and go into my S3 buckets as expected.  It is just images uploaded into the ActionText editor that does not use the S3 URL.  They do go into the correct buckets, however.  It is just the URL that I can't change or get access to in the blob element.
I assume there is a setting in an initializer or config that I have not been able to find but I can't find it through the documentation or google.
The URL the blob is currently using is the rail/active_storage/ storage URL and I need it to use the S3 URL I have set in the active_storage.yml file.

A: Turns out I could edit the URL in the _blob.html.erb file.  First I had to check if I was in Production or not.  Once I verify that I was able to construct the URL to grab from S3 using the blob.key.
  <% if blob.representable? %>
    <% if Rails.env == 'production' %>
      <img class: "post-actiontext-image" src="https://<%= ENV['S3_BUCKET'] %>.s3-<%= ENV['AWS_REGION'] %>.amazonaws.com/<%= blob.key %>" />
    <% else %>
      <%= image_tag blob.representation(resize_to_limit: local_assigns[:in_gallery] ? [ 800, 600 ] : [ 1024, 768 ]), class: "post-actiontext-image" %>
    <% end %>
  <% end %>


text:
Q: kafka stream api not generating messages into new topic I am running Pipe.java as given in the stream api example here https://kafka.apache.org/20/documentation/streams/tutorial . I am doing exactly as given in the link. Kafka broker is also running on localhost and port 9092.
I have created topics streams-plaintext-input and streams-pipe-output. While I send some messages into topic streams-plaintext-input using kafka-console-producer.sh utility, I do not see any messages coming into topic streams-pipe-output.
Can someone tell me what wrong I am doing?
package myapps;

import java.util.Properties;
import java.util.concurrent.CountDownLatch;

import org.apache.kafka.common.serialization.Serdes;
import org.apache.kafka.streams.KafkaStreams;
import org.apache.kafka.streams.StreamsBuilder;
import org.apache.kafka.streams.StreamsConfig;
import org.apache.kafka.streams.Topology;
import org.apache.kafka.streams.kstream.KStream;

public class MyPipe {

    public static void main(String[] args) {
        Properties props = new Properties();
        props.put(StreamsConfig.APPLICATION_ID_CONFIG, "mystreams-pipe");
        props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
        props.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG, Serdes.String().getClass());
        props.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, Serdes.String().getClass());
        final StreamsBuilder builder = new StreamsBuilder();
        builder.stream("streams-plaintext-input").to("streams-pipe-output");
        final Topology topology = builder.build();
        System.out.println(topology.describe());
        final KafkaStreams streams = new KafkaStreams(topology, props);
        final CountDownLatch latch = new CountDownLatch(1);

        // attach shutdown handler to catch control-c
        Runtime.getRuntime().addShutdownHook(new Thread("streams-shutdown-hook") {
            @Override
            public void run() {
                streams.close();
                System.out.println("closing");
                latch.countDown();
            }
        });

        try {
            System.out.println("starting stream application.");
            streams.start();

            System.out.println("started");
            latch.await();
        } catch (Throwable e) {
            e.printStackTrace();
            System.exit(1);
        }

        System.out.println("exiting");
        System.exit(0);
    }

}


text:
Q: When should I use AutoSeededRandomPool (and not NonblockingRng)? I found Crypto++ provides several random generators: AutoSeededRandomPool, AutoSeededX917RNG and so on. I know some details about these generators and the usage of them, I just wondered when I need them?
AutoSeededRandomPool and AutoSeededX917RNG default base on NonblockingRng, and NonblockingRng base on /dev/urandom, the /dev/urandom base on /dev/random and ChaCha.
I googled and found many articles said that /dev/urandom is secure enough and suit for all(almost?) scenarios, so why use DES/AES to encrypt the data read from /dev/urandom and much slower than use '/dev/urandom' directly?
When should I use AutoSeededRandomPool or AutoSeededX917RNG?

A:
When should I use AutoSeededRandomPool or AutoSeededX917RNG?

You should use AutoSeededRandomPool. It uses a PGP-style generator based on AES to extract entropy from the OS pool. It also mixes time with the seed to help harden against VM rollback attacks.
You should also create one AutoSeededRandomPool per thread. If you use a single generator for all threads then you need to supply the locks.
AutoSeededX917RNG is from a time when NIST approved an AES-based ANSI X9.31 generator for use in FIPS 140 validated cryptography. The X9.17 and X9.31 generators are also used in some other standards, like Automotive and Financial.
NIST deprecated the AutoSeededX917RNG generator in 2014 or so in favor of deterministic bit generators specified in SP800-90.
You can use AutoSeededX917RNG if you like. But unless you have requirements to do so then you should just use AutoSeededRandomPool.


text:
Q: Upload only one file per each directory using blueimp file upload I have encountered one boring problem  when working with blueimp file upload. The problem is:
I have carousel in my web site. Each Image has its own Title, Description and other details stored in database. But I have not stored the image's url in database table. The images are stored in a seperate directory as :
carousels <root dir>
   |
   +---- {carousel_id} <dir>
   |   |___ image 1 <image file 1>
   |
   +---- {carousel_id} <dir>
       |___ image 1 < image file 1>
       |___ image 2 <image file 2> # Which I do not want

I want only one file (image for now) per each directory.
What I am doing now is , First I fetch all the carousels from the database table and find out the related image using the carousel_id (which is auto-increment primary key in database table). But if there are multiple files in some directory (say in dir "1") I am currently selecting one image file randomly. And what I know is each carousel can have only one image.
In very short:
How can I delete other files from the directory when I upload a single file to the same directory successfully using blueimp jquery file-upload.
I am using PHP in server side.
Please Help me.
Thankyou.


text:
Q: React: Function in Parent Component not receiving data from Child Component I'm working on a project using React where I need to update the state of the Parent Component with the Child Component's input.  I did console.log() my way through each function in the chain and found that the fetchText() function in my parent component didn't receive the text
Here's what my parent component looks like
class AppComponent extends React.Component{
  constructor(props){
    super(props);
    this.state = { markdownText: `` };

    this.fetchText = this.fetchText.bind(this);
  }

  fetchText(text){
    this.setState({ markdownText: text });
    console.log(text);
  }

  render(){
    return(

Markdown Viewer

        <MarkDownComponent userInput={this.fetchText} />
        <PreviewComponent />

    );
  }
}

My Child Component looks like this
class MarkDownComponent extends React.Component{
  constructor(props){
    super(props);
    this.state = { text: ``};

    this.getInput = this.getInput.bind(this);
    this.sendInput = this.sendInput.bind(this);
  }

  getInput(event){
    this.setState({ text: event.target.value });
    this.sendInput();
  }

  sendInput(){
    this.props.userInput = this.state.text;
    //console.log(this.props.userInput);
  }

  render(){
    return(

        <textarea id="editor" rows="16" onChange={this.getInput}></textarea>

    );
  }
}

When console.log()ing this.props.userInput in the Child Component I get the value back as I type.  So that indicates the value is making it to the property, but why isn't it updating in the parent component?

A: The issue is you are assigning state value to a function which is not correct.
this.props.userInput = this.state.text; // this is incorrect

//Right one

class MarkDownComponent extends React.Component{
  constructor(props){
    super(props);
    this.state = { text: ``};

    this.getInput = this.getInput.bind(this);
    this.sendInput = this.sendInput.bind(this);
  }

  getInput(event){
    this.setState({ text: event.target.value });
    this.sendInput();
  }

  sendInput(){
    this.props.userInput(this.state.text);
    //console.log(this.props.userInput);
  }

  render(){
    return(

        <textarea id="editor" rows="16" onChange={this.getInput}></textarea>

    );
  }
}

You can directly call this.props.userInput function in getInput function:
class MarkDownComponent extends React.Component{
      constructor(props){
        super(props);
        this.state = { text: ``};

        this.getInput = this.getInput.bind(this);
      }

      getInput(event){
        this.props.userInput(event.target.value);
      }

      render(){
        return(

            <textarea id="editor" rows="16" onChange={this.getInput}></textarea>

        );
      }
    }

ES6 way:
class MarkDownComponent extends React.Component{
      constructor(props){
        super(props);
        this.state = { text: ``};
      }

      getInput = (event) => {
        this.props.userInput(this.state.text);
      }

      render(){
        return(

            <textarea id="editor" rows="16" onChange={this.getInput}></textarea>

        );
      }
    }

A: Few things to note here:
you cannot change the value of props, it is passed to the component through it parent
this.props.userInput = this.state.text;
this won't work.
So, to make fetchData of parent get the text from textarea you should do like this
<textarea id="editor" rows="16" onChange={this.props.userInput}></textarea>
and in parent component :
fetchText(event){
    console.log(event.target.value)
    this.setState({ markdownText: event.target.value });
}

you don't require functions like getInput and sendInput to send data to the parent component.

A: As told in the comments, there is no need to assign a state to your function. Also, if your desire is to change the text with a Child and nothing more you don't need a state in your Child. Don't use state if it is not necessary.

class AppComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = { markdownText: "" };

    this.fetchText = this.fetchText.bind(this);
  }

  fetchText(e) {
    this.setState({ markdownText: e.target.value});
  }

  render() {
    return (

Markdown Viewer

        Value is now: {this.state.markdownText}
        <MarkDownComponent userInput={this.fetchText} />

    );
  }
}

const MarkDownComponent = ( props ) => {
  return (

      <textarea id="editor" rows="16" onChange={props.userInput}></textarea>

  )
}

ReactDOM.render(<AppComponent />, document.getElementById("root"));


text:
Q: Flask, managing DB connections(without ORM) I'm newbie in Flask and web programming on the whole, so I'm trying to understand the principles of contexts and db operations of the framework.
Now I want to make out how to manage DB connections without Sql-Alchemy and other ORMs, just with plain sql.
So the simple example with sqlite3 db.
The structure of my test project:
.
├── application
│   ├── __init__.py
│   ├── routes.py
│   └── templates
│       ├── base.html
│       ├── index.html
├── config.py
├── requirements.txt
├── run.py
└── test.db

init.py
from flask import Flask,g
from config import Config
import sqlite3

app = Flask(__name__)
app.config.from_object(Config)

def get_db():
    db = getattr(g, '_database', None)
    if db is None:
        db = g._database = sqlite3.connect('test.db')
    return db

@app.teardown_appcontext
def close_connection(exception):
    db = getattr(g, '_database', None)
    if db is not None:
        db.close()

from application import routes

routes.py
# -*- coding: utf-8 -*-
from flask import render_template,redirect
from application import app, get_db
# import sqlite3

@app.route('/')
def index():
    cur = get_db().cursor()
    cur.execute('select*from users')
    select=cur.fetchall()
    return render_template('index.html',title='DBSelectTest', posts=select)

I've copied "get_db" and "close_connection" functions from the official site of Flask framework, but I'm not clearly understand how it works and what will be the difference if I use just simple code for "def get_db" without "g" like this:
con = sqlite3.connect("catalog.db")
cur = con.cursor()

And obviously close connections after query is done like this:
cur.close()
con.close()

I'm just trying to catch how the application and the request contexts work in that case with using g.
The main problem that I don't understand what is a "request" in that case.
My wrong understanding of this case:
So in init.py we create "global variable" g which  is in application context and should be accessible for each tread in request context.
In routes.py we get query from client with root route("/") so in that moment request context is created and after that application context as well.
So as I understand "get_db" is accessible from our request context and we're able to connect to the db and use that g value in all functions inside the current tread? What about "close_connection"? Because of decorator "teardown_appcontext" the connections have to been closed after app context is failed or ended? Will it work in my code?
So, could anyone provide a correct case of using plain sql with separate connection function?

A: Flask application and request contexts behave like global variables for the purposes of your code, but are in fact proxies that will contain different values every time your application receives a new web request. The request context contains data specific to that particular web request such as form data, remote ip address, http headers, etc.
Every time a web request is received, new application and request contexts are created before your view function is called and these are then destroyed after a response has been returned and the processing of the web request has been completed. The g proxy is stored with the application context and it's used to store variables with a lifetime of that particular web request. This is used to pass information between functions called by flask as a result of events and signals.
In your code you use a decorator to register the function close_connection with the teardown_appcontext event, thus guaranteeing it is called after completion of handling of every web request. There are many other events that can be hooked to execute before or after your view function to provide pre- and post-processing of the request or response. The g proxy is merely used to store your database connection, which was created in your view function, and makes it available to the close_connection function where it is guaranteed to be closed. This prevents the database connection being left open if an error occurs in your application code.
The pattern, as shown below, is used to accomplish exactly the same thing as would be achieved by using a context manager (or try, except, finally block) to close the database connection within your function. This pattern is commonly used with an ORM to hide the underlying management of the database connection and reduce boilerplate code. The following code should produce the same effect without the use of events or the g proxy.
# -*- coding: utf-8 -*-
from flask import render_template, redirect
from application import app
from contextlib import closing
import sqlite3

def get_db():
    return sqlite3.connect('test.db')

@app.route('/')
def index():
    with closing(get_db()) as conn:
        cur = conn.cursor()
        cur.execute('select * from users')
        select = cur.fetchall()
    return render_template('index.html', title='DBSelectTest', posts=select)


text:
Q: Find all primes $p,q$ such that $p^3+p=q^7+q$ The following has been unanswered in art of problem solving and other forums for months.
Find all primes $p,q$ such that
$p^3+p=q^7+q$
One solution is $(5,2)$ and it has been computer checked that there is no other solution till $10^7$.
I am really curious to see a complete solution.

A: Assume we have another solution, so that $q\ge 3$. We know that $p(p^2+1)=q(q^2+1)(q^4-q^2+1)$. We also have  $p>q^2+1$. In fact, otherwise
$p\le q^2+1$ and then
$$
q^7+q=p^3+p\le (q^2+1)^3+q^2+1=q^6+3q^4+4q^2+2,
$$
and so $q^7< q^6+3q^4+4q^2+2< 2q^6$, which is impossible if $q\ge 3$.
Since we also have $p>q$, it follows that $p|(q^4-q^2+1)$ and so there exist a natural number $k$ such that
$pk=q^4-q^2+1$. But then
$$
p(p^2+1)=q(q^2+1)pk,
$$
and so $p^2+1=q(q^2+1)k$. This implies
$$
p^2k^2+k^2=q(q^2+1)k^3.
$$
Since $p^2k^2=(q^4-q^2+1)^2$, we arrive finally at
$$
(q^4-q^2+1)^2+k^2=q(q^2+1)k^3,
$$
which we rewrite as
$$
(q^3+q)(q^5-3q^3+6q)-8q^2+1+k^2=(q^3+q)k^3.
$$
So we obtain
$$
(1)\quad\qquad\qquad\qquad\qquad\qquad\qquad (q^3+q)(k^3-q^5+3q^3-6q)=k^2+1-8q^2.
$$
It follows that $k^2+1\equiv 0 \mod q$.
Let $y\in\{0,1,\dots, q-1\}$ be such that $k\equiv y\mod q$.
If $y< \sqrt{q-1}$ or $q-y<\sqrt{q-1}$, then $0\le y^2<q-1$ or $q(2y-q)\le y^2<q(2y-q)+q-1$, so in particular it is impossible that $k^2\equiv y^2\equiv -1\mod q$.
Now, since $k^3\equiv -k\equiv -y\mod q$, for any $N\in\Bbb{N}$ we have $|k^3+qN|\ge \sqrt{q-1}$.
So, from (1), we deduce that
$$
|1+k^2-8q^2|=(q^3+q)|k^3+q(3q^2-q^4-6)|\ge (q^3+q)\sqrt{q-1}.
$$
By hand one verifies that $q=3$, $q=5$ and $q=7$ are not solutions, so we can assume $q>8$, hence $q^3> 8q^2$ and so necessarily $k^2+1>8q^2$ and then
$|1+k^2-8q^2|=k^2+1-8q^2<k^2$.
So we arrive at
$$
k^2>q^3\sqrt{q-1}.
$$
But then $k^{12}>q^{18}(q-1)^3$ and so
$$
(p^2+1)^{12}=k^{12}q^{12}(q^2+1)^{12}>q^{18}(q-1)^3q^{12}(q^2+1)^{12}>q^{54}(q-1)^3.
$$
On the other hand $p>10$ implies $2p^8>(p^2+1)^4$, and so
$$
(p^2+1)^{12}=(p^2+1)^{8}(p^2+1)^{4}<2(p^2+1)^{8}p^8=2(p^3+p)^8=2(q^7+q)^8.
$$
Putting the inequalities together, we obtain finally
$$
2(q^7+q)^8>q^{54}(q-1)^3,\quad\quad\quad\quad\quad\quad\quad(*)
$$
which is impossible, since the left hand side is of order 56 and the right hand side has order 57.
$\textbf{Detailed proof that (*) is impossible:}$
Since $q>10$, we have that $q-1>\frac{9}{10}q$ and since $\left(\frac{9}{10}\right)^3>\frac 12$, we obtain $(q-1)^3>\frac{q^3}{2}$. Hence (*) implies
$$
4(q^6+1)^8>q^{49},\quad\quad\quad\quad\quad\quad\quad(**)
$$
On the other hand, for any $\alpha>10^6$ we have $2\alpha^8>(\alpha+1)^8$,
for example, using that $(1+\frac{1}{\alpha})^8<(1+10^{-6})^8<2$.
In particular, for $\alpha=q^6>10^6$, we have $2(q^6)^8>(q^6+1)^8$, and so from (**) we obtain
$$
8q^{48}=4(2(q^6)^8)>4(q^6+1)^8>q^{49},
$$
which is impossible, since $q>8$.
${\textbf{Note:}}$
The proof uses crucially that $p$ is prime when deducing that $p$ divides $q^4−q^2+1$. However, the condition that $q$ is prime is not needed.


text:
Q: Display row where string column starts with specific letter I researched how to solve my problem, but the compiler I'm using keeps throwing an invalid identifier error. Let me explain.
I have a table with the columns and data types matching respectively
Id | City | State
------------------------
NUMBER | VARCHAR2(21) | VARCHAR(2)

I want to grab all non-duplicate cities which names start with the letter "a". I have tried the below query
SELECT DISTINCT CITY
FROM STATION
WHERE CITY LIKE "A%";

I have also tried
SELECT CITY
FROM STATION
WHERE CITY LIKE "A%"
ORDER BY CITY;

But I keep receiving
ORA-00904: "A%": invalid identifier

I have looked up questions with a similar problem, and the answer seems to integrate the "LIKE" condition. I have done that, but alas, an error. This seems like it should be an easy problem to solve. Any ideas?

A: Use single quotes! Double quotes are meant for identifiers only (such as column names, table names, and so on), hence the error you are getting.
On the other hand, single quotes stand for literal strings, which is what you mean here:
SELECT DISTINCT CITY
FROM STATION
WHERE CITY LIKE 'A%';

In that regard, Oracle strictly follows the ANSI SQL specification. There are other databases that allow double quotes for strings, and use other characters to quote identifiers (MySQL for example)... but I personally find that it makes things more confusing that they would need to.


text:
Q: Google Authenticaion via Scrapy I was curious to know if google authetication could be achieved via scrapy. I tried with the following code snippet to achieve so.
My code:
import scrapy
from scrapy.http import FormRequest, Request
import  logging
import json

class LoginSpider(scrapy.Spider):
    name = 'hello'
    start_urls = ['https://accounts.google.com']
    handle_httpstatus_list = [404, 405]
    def parse(self, response):
        print('inside parse')
        print(response.url)
        return [FormRequest.from_response(response,
                    formdata={'Email': 'abc@gmail.com'},
                    callback=self.log_password)]

    def log_password(self, response):
        print('inside log_password')
        print(response.url)
        return [FormRequest.from_response(response,
                    formdata={'Passwd': 'password'},
                    callback=self.after_login)]

    def after_login(self, response):
        print('inside after_login')
        print(response.url)
        if "authentication failed" in response.body:
            self.log("Login failed", level=logging.ERROR)
            return
        # We've successfully authenticated, let's have some fun!
        else:
            print("Login Successful!!")

if __name__ == '__main__':
    process = CrawlerProcess({
        'USER_AGENT': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36',
        'DOWNLOAD_DELAY': 0.2,
        'HANDLE_HTTPSTATUS_ALL': True
    })

    process.crawl(LoginSpider)
    process.start()

But I'm getting following output when I run the script.
Output
2018-08-15 10:38:05 [scrapy.utils.log] INFO: Scrapy 1.5.1 started (bot: scrapybot)

2018-08-15 10:38:05 [scrapy.utils.log] INFO: Versions: lxml 4.2.3.0, libxml2 2.9.8, cssselect 1.0.3, parsel 1.5.0, w3lib 1.19.0, Twisted 18.7.0, Python 3.6.4 (default, Mar 22 2018, 14:05:57) - [GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.42.1)], pyOpenSSL 18.0.0 (OpenSSL 1.1.0h  27 Mar 2018), cryptography 2.3, Platform Darwin-15.6.0-x86_64-i386-64bit 2018-08-15 10:38:05 [scrapy.crawler] INFO: Overridden settings: {'DOWNLOAD_DELAY': 0.2, 'USER_AGENT': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36'} 2018-08-15 10:38:05 [scrapy.middleware] INFO: Enabled extensions: ['scrapy.extensions.corestats.CoreStats',  'scrapy.extensions.telnet.TelnetConsole',  'scrapy.extensions.memusage.MemoryUsage',  'scrapy.extensions.logstats.LogStats']

2018-08-15 10:38:05 [scrapy.middleware] INFO: Enabled downloader middlewares: ['scrapy.downloadermiddlewares.httpauth.HttpAuthMiddleware',  'scrapy.downloadermiddlewares.downloadtimeout.DownloadTimeoutMiddleware', 'scrapy.downloadermiddlewares.defaultheaders.DefaultHeadersMiddleware', 'scrapy.downloadermiddlewares.useragent.UserAgentMiddleware',  'scrapy.downloadermiddlewares.retry.RetryMiddleware',  'scrapy.downloadermiddlewares.redirect.MetaRefreshMiddleware',  'scrapy.downloadermiddlewares.httpcompression.HttpCompressionMiddleware', 'scrapy.downloadermiddlewares.redirect.RedirectMiddleware',  'scrapy.downloadermiddlewares.cookies.CookiesMiddleware',  'scrapy.downloadermiddlewares.httpproxy.HttpProxyMiddleware',  'scrapy.downloadermiddlewares.stats.DownloaderStats']

2018-08-15 10:38:05 [scrapy.middleware] INFO: Enabled spider middlewares: ['scrapy.spidermiddlewares.httperror.HttpErrorMiddleware',  'scrapy.spidermiddlewares.offsite.OffsiteMiddleware',  'scrapy.spidermiddlewares.referer.RefererMiddleware',  'scrapy.spidermiddlewares.urllength.UrlLengthMiddleware',  'scrapy.spidermiddlewares.depth.DepthMiddleware']

2018-08-15 10:38:05 [scrapy.middleware] INFO: Enabled item pipelines: []

2018-08-15 10:38:05 [scrapy.core.engine] INFO: Spider opened 2018-08-15 10:38:05 [scrapy.extensions.logstats] INFO: Crawled 0 pages (at 0 pages/min), scraped 0 items (at 0 items/min)

2018-08-15 10:38:05 [scrapy.extensions.telnet] DEBUG: Telnet console listening on 127.0.0.1:6023

2018-08-15 10:38:06 [scrapy.downloadermiddlewares.redirect] DEBUG: Redirecting (302) to <GET https://accounts.google.com/ManageAccount> from <GET https://accounts.google.com>

2018-08-15 10:38:07 [scrapy.downloadermiddlewares.redirect] DEBUG: Redirecting (302) to <GET https://accounts.google.com/ServiceLogin?passive=1209600&continue=https%3A%2F%2Faccounts.google.com%2FManageAccount&followup=https%3A%2F%2Faccounts.google.com%2FManageAccount> from <GET https://accounts.google.com/ManageAccount>

2018-08-15 10:38:09 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://accounts.google.com/ServiceLogin?passive=1209600&continue=https%3A%2F%2Faccounts.google.com%2FManageAccount&followup=https%3A%2F%2Faccounts.google.com%2FManageAccount> (referer: None)

**inside parse**

https://accounts.google.com/ServiceLogin?passive=1209600&continue=https%3A%2F%2Faccounts.google.com%2FManageAccount&followup=https%3A%2F%2Faccounts.google.com%2FManageAccount

2018-08-15 10:38:09 [scrapy.core.engine] DEBUG: Crawled (405) <POST https://accounts.google.com/> (referer: https://accounts.google.com/ServiceLogin?passive=1209600&continue=https%3A%2F%2Faccounts.google.com%2FManageAccount&followup=https%3A%2F%2Faccounts.google.com%2FManageAccount)

**inside log_password**
https://accounts.google.com/

2018-08-15 10:38:10 [scrapy.core.scraper] ERROR: Spider error processing <POST https://accounts.google.com/> (referer: https://accounts.google.com/ServiceLogin?passive=1209600&continue=https%3A%2F%2Faccounts.google.com%2FManageAccount&followup=https%3A%2F%2Faccounts.google.com%2FManageAccount)

    Traceback (most recent call last):   File "/Users/PathakUmesh/.local/share/virtualenvs/python3env-piKhfpsf/lib/python3.6/site-packages/twisted/internet/defer.py", line 654, in _runCallbacks
        current.result = callback(current.result, *args, **kw)   File "google_login.py", line 79, in log_password
        callback=self.after_login)]   File "/Users/PathakUmesh/.local/share/virtualenvs/python3env-piKhfpsf/lib/python3.6/site-packages/scrapy/http/request/form.py", line 48, in from_response
        form = _get_form(response, formname, formid, formnumber, formxpath)   File "/Users/PathakUmesh/.local/share/virtualenvs/python3env-piKhfpsf/lib/python3.6/site-packages/scrapy/http/request/form.py", line 77, in _get_form
        raise ValueError("No <form> element found in %s" % response) ValueError: No <form> element found in <405 https://accounts.google.com/>

2018-08-15 10:38:10 [scrapy.core.engine] INFO: Closing spider (finished)
2018-08-15 10:38:10 [scrapy.statscollectors] INFO: Dumping Scrapy stats: {'downloader/request_bytes': 1810,  'downloader/request_count': 4,  'downloader/request_method_count/GET': 3,  'downloader/request_method_count/POST': 1,  'downloader/response_bytes': 357598,  'downloader/response_count': 4,  'downloader/response_status_count/200': 1,  'downloader/response_status_count/302': 2,  'downloader/response_status_count/405': 1,  'finish_reason': 'finished',  'finish_time': datetime.datetime(2018, 8, 15, 4, 53, 10, 164911),  'log_count/DEBUG': 5,  'log_count/ERROR': 1,  'log_count/INFO': 7,  'memusage/max': 41132032,  'memusage/startup': 41132032,  'request_depth_max': 1,  'response_received_count': 2,  'scheduler/dequeued': 4,  'scheduler/dequeued/memory': 4,  'scheduler/enqueued': 4,  'scheduler/enqueued/memory': 4,  'spider_exceptions/ValueError': 1,  'start_time': datetime.datetime(2018, 8, 15, 4, 53, 5, 463699)}

2018-08-15 10:38:10 [scrapy.core.engine] INFO: Spider closed (finished)

Any help would be appreciated

A: Error 405 means that URL doesn't accept the HTTP method, in your case POST generated at parse.
Google default login page is much more complex than simple POST form heavily using JS and Ajax under the hood. To login using Scrapy you have use https://accounts.google.com/ServiceLogin?nojavascript=1 as start URL instead.


text:
Q: Implement with QML or C++? I've just started learning Qt recently, finding QML quite interesting for implementing UI component. Before the project really kick off, I've got some questions:

*

*For a fresh start project, should I just use QML? Does QML be designed for replacing QWidget?)

*If I go with QML, is there anything else must be implemented with C++? Or better implemented with C++ for better performance? (I know some customized UI components can be integrated through plugin) What's the relationship between QML and C++ widget?

*As for performance or rendering issue, does QML better than native C++ widget?

A: When you start a question with 'Should I use', it is quite a good hint that SO might not be the right place to ask it. Even more when there are only answers, which start with 'It depends on...'.
QML is not designed to replace QWidget. It is a different technique. Which one to use, depends on your requirements.
Whether or not you must implement additional stuff in C++ depends on your project. Some things are easier in C++, others in QML. And some stuff is not possible in QML at all.
There is no relationship between QML and C++ widgets.
And the performance of QML is in most cases more than sufficient. In almost every case QML is used to create user interfaces. I doubt that there are many cases where clicking a button or opening a dropbox folder is performance critical.

A: I had a chance to put this question to a few Qt experts at the World Summit today and the general take was that because QML component rendering can be done through hardware acceleration that it is preferred for apps requiring high performance graphics, eg automotive dashboards. OTOH widgets seem to be used for desktop applications. Another consideration is that while widgets can be styled using Qss (Qt's version of Css), QML components cannot.
In QML based applications computationally intensive functions are generally written in C++.
HTH,
Eric G


text:
Q: Seeding a uniformly generated number from (0,1)? I am using numpy random generator to generate a number from (0,1) with
np.random.uniform(0,1)

I can't find a way to seed a number and still keep it uniformly and randomly chosen from 0 to 1.
I am also desperately new at coding.

A: I personally would recommend creating a new numpy.random.RandomState object rather than using np.random.seed. For example:
import numpy as np

rs = np.random.RandomState(0)
x = rs.randn(10)

will give an equivalent result to:
np.random.seed(0)
x = np.random.randn(10)

However the first method is much more explicit and makes it easier to keep track of the RNG state, for example in cases where you need multiple random number generators with different internal states.

A: If you want to set the seed for the generator use numpy.random.seed.


text:
Q: How can I target a EF6 migration to only execute on SQL Server? I would like to ensure specific features are turned on in SQL Server. I am currently using EF6 Migrations to generate my change scripts. I am using my migrations against both SQL Server 2012 and SQL Server CE 4 (for basic unit testing of my mapping). The specific feature I want to enable is not supported by SQL Server CE.
How can I create a migration that only applies to SQL Server?
Here is the migration in question:
public partial class EnableSnapshotIsolation : DbMigration
{
    public override void Up()
    {

        Sql(@"  ALTER DATABASE CURRENT
                SET READ_COMMITTED_SNAPSHOT ON", true);

        Sql(@"  ALTER DATABASE CURRENT
                SET ALLOW_SNAPSHOT_ISOLATION ON", true);
    }

    public override void Down()
    {
        Sql(@"  ALTER DATABASE CURRENT
                SET READ_COMMITTED_SNAPSHOT OFF", true);

        Sql(@"  ALTER DATABASE CURRENT
                SET ALLOW_SNAPSHOT_ISOLATION OFF", true);
    }
}

Note: that we do manual deployments of change scripts. A person opens a SSMS window and executes the script. I provide a change script using the update-database -script command as part of my build packaging process. So EF is NOT creating the database.

A: After poking around quite a bit, I found that there is no way in the migration its self to suppress a migration based on database type. But, you can implement your own migrator for a specific provider.
My solution involves updating my configuration class like so.
public class Configuration : DbMigrationsConfiguration<ApplicationDbContext>
{
    public Configuration()
    {
        AutomaticMigrationsEnabled = false;
        MigrationsDirectory = "Data\\Migrations";
        SetSqlGenerator("System.Data.SqlClient", new SqlMigrator());
    }

    private class SqlMigrator : SqlServerMigrationSqlGenerator
    {
        public override IEnumerable<MigrationStatement> Generate(
            IEnumerable<MigrationOperation> migrationOperations, string providerManifestToken)
        {
            var statements = new List<MigrationStatement>
            {
                new MigrationStatement
                {
                    Sql = "ALTER DATABASE CURRENT SET READ_COMMITTED_SNAPSHOT ON",
                    SuppressTransaction = true
                },
                new MigrationStatement
                {
                    Sql = "ALTER DATABASE CURRENT SET ALLOW_SNAPSHOT_ISOLATION ON",
                    SuppressTransaction = true
                }
            };
            statements.AddRange(base.Generate(migrationOperations, providerManifestToken));
            return statements;
        }
    }
}

Note: This of course will fail on Sql Server versions prior to 2012, so make your script as beefy as it needs to be to set these flags. This works for my specific case.


text:
Q: Add 'Gregwar's Image class' to Laravel I want add this class to laravel - https://github.com/Gregwar/Image
There is 'Using with composer' - I added this line to composer.json
"gregwar/image": "dev-master"

I was run:
php artisan optimize
composer dump-autoload

But if i want use this class - have this error:
Class 'Image' not found

class is installed (by composer) in root: vendor/gregwar/...

A: As the readme says, you have to "require" it using its namespace:
use Gregwar\Image\Image;

So your code should look like:
<?php

use Gregwar\Image\Image;

echo Image::open('test.png')
    ->sepia()
    ->jpeg();


text:
Q: Page not found 404 when accessing custom module in system configuration When i try to access my system > configuration > i got an error saying page not found 404
here's my code:
config.xml :
<?xml version="1.0"?>
<config>
    <modules>
        <Lime_Sellercenter>
            <version>0.0.0.4</version>
        </Lime_Sellercenter>
    </modules>
    <admin>
        <routers>
            <lime_sellercenter>
                <use>admin</use>
                <args>
                    <module>Lime_Sellercenter</module>
                    <frontName>lime_sellercenter</frontName>
                </args>
            </lime_sellercenter>
            <adminhtml>
                <args>
                    <modules>
                        <Lime_Sellercenter before="Mage_Adminhtml">Lime_Sellercenter_Adminhtml</Lime_Sellercenter>
                    </modules>
                </args>
            </adminhtml>
        </routers>
    </admin>
    <global>
        <models>
            <lime_sellercenter>
                <class>Lime_Sellercenter_Model</class>
                <resourceModel>lime_sellercenter_resource</resourceModel>
            </lime_sellercenter>
            <lime_sellercenter_resource>
                <class>Lime_Sellercenter_Model_Resource</class>
                <entities>
                   <listing>

lime_sellercenter_listing

                    </listing>
                    <listingattributes>

lime_sellercenter_listing_attributes

                    </listingattributes>
                    <listing_store>

lime_sellercenter_listing_store

                    </listing_store>
                    <listing_product>

lime_sellercenter_listing_product

                    </listing_product>
                    <lazadacategories>

lime_sellercenter_lazadacategories

                    </lazadacategories>
                    <ordersyncqueue>

lime_sellercenter_ordersyncqueue

                    </ordersyncqueue>
                    <ordererrorlog>

lime_sellercenter_ordererrorlog

                    </ordererrorlog>
                </entities>
            </lime_sellercenter_resource>
        </models>
        <blocks>
            <lime_sellercenter>
                <class>Lime_Sellercenter_Block</class>
            </lime_sellercenter>
        </blocks>
        <helpers>
            <lime_sellercenter>
                <class>Lime_Sellercenter_Helper</class>
            </lime_sellercenter>
        </helpers>
        <resources>
            <lime_sellercenter_setup>
                <setup>
                    <module>Lime_Sellercenter</module>
                    <class>Lime_Sellercenter_Model_Resource_Setup</class>
                </setup>
            </lime_sellercenter_setup>
        </resources>
        <events>
            <sales_order_save_commit_after>
                <observers>
                    <lime_sellercenter>
                        <class>lime_sellercenter/observer</class>
                        <method>orderCancel</method>
                    </lime_sellercenter>
                </observers>
            </sales_order_save_commit_after>
            <catalog_product_save_commit_after>
                <observers>
                    <lime_sellercenter>
                        <class>lime_sellercenter/observer</class>
                        <method>afterProductSave</method>
                    </lime_sellercenter>
                </observers>
            </catalog_product_save_commit_after>
            <adminhtml_widget_container_html_before>
                <observers>
                    <lime_sellercenter>
                        <class>lime_sellercenter/observer</class>
                        <method>syncOrderButton</method>
                    </lime_sellercenter>
                </observers>
            </adminhtml_widget_container_html_before>
            <sales_order_shipment_save_after>
                <observers>
                    <lime_sellercenter>
                        <class>lime_sellercenter/observer</class>
                        <method>afterShipmentSave</method>
                    </lime_sellercenter>
                </observers>
            </sales_order_shipment_save_after>
        </events>
        <fieldsets>
            <sales_convert_quote>
                <sellercenter_vendor><to_order>*</to_order></sellercenter_vendor>
                <vendor_order_id><to_order>*</to_order></vendor_order_id>
            </sales_convert_quote>
        </fieldsets>
    </global>
    <crontab>
        <jobs>
            <lime_sellercenter_sync_order_queue>
                <schedule>
                    <cron_expr>*/5 * * * *</cron_expr>
                </schedule>
                <run>
                    <model>lime_sellercenter/observer::processQueue</model>
                </run>
            </lime_sellercenter_sync_order_queue>
            <lime_sellercenter_autosync_order_process>
                <schedule><cron_expr>0 * * * * *</cron_expr></schedule>
                <run><model>lime_sellercenter/observer::autoDownload</model></run>
            </lime_sellercenter_autosync_order_process>
        </jobs>
    </crontab>
    <adminhtml>
        <layout>
            <updates>
                <lime_sellercenter>
                    <file>lime_sellercenter.xml</file>
                </lime_sellercenter>
            </updates>
        </layout>
        <acl>
            <resources>
                <admin>
                    <children>
                        <system>
                            <children>
                                <config>
                                    <children>
                                        <lime_sellercenter>
                                            <title>Sellercenter Settings</title>
                                        </lime_sellercenter>
                                    </children>
                                </config>
                            </children>
                        </system>
                    </children>
                </admin>
            </resources>
        </acl>
        <events>
          <core_block_abstract_prepare_layout_after>
              <observers>
                  <lime_sellercenter_listing_product>
                      <type>singleton</type>
                      <class>lime_sellercenter/adminhtml_observer</class>
                      <method>addProductListingBlock</method>
                  </lime_sellercenter_listing_product>
              </observers>
          </core_block_abstract_prepare_layout_after>
          <catalog_product_save_after>
              <observers>
                  <lime_sellercenter_listing_product>
                      <type>singleton</type>
                      <class>lime_sellercenter/adminhtml_observer</class>
                      <method>saveProductListingData</method>
                  </lime_sellercenter_listing_product>
              </observers>
          </catalog_product_save_after>
      </events>
      <global_search>
          <listing>
              <class>lime_sellercenter/adminhtml_search_listing</class>
              <acl>lime_sellercenter</acl>
          </listing>
      </global_search>
    </adminhtml>
</config>

adminhtml.xml :
<?xml version="1.0"?>
<config>
    <acl>
        <resources>
            <admin>
                <children>
                    <system>
                        <children>
                            <config>
                                <children>
                                    <lime_sellercenter translate="title" module="lime_sellercenter">
                                        <title>Sellercenter</title>
                                    </lime_sellercenter>
                                </children>
                            </config>
                        </children>
                    </system>
                    <lime_sellercenter translate="title" module="lime_sellercenter">
                        <title>Sell on Lazada</title>
                        <children>
                            <listing translate="title" module="lime_sellercenter">
                                <title>Listing</title>
                                <sort_order>0</sort_order>
                            </listing>
                        </children>
                    </lime_sellercenter>
                </children>
            </admin>
        </resources>
    </acl>
    <menu>
        <lime_sellercenter translate="title" module="lime_sellercenter">
            <title>Sell on Lazada</title>
            <sort_order>35</sort_order>
            <children>
                <listings translate="title" module="lime_sellercenter">
                    <title>Listings</title>
                    <action>adminhtml/sellercenter_listing</action>
                    <sort_order>1</sort_order>
                </listings>
            </children>
        </lime_sellercenter>
    </menu>
</config>

system.xml:
<?xml version="1.0"?>
<config>
    <tabs>
        <lime translate="label">
            LIME
            <sort_order>500</sort_order>
        </lime>
    </tabs>

    <sections>
        <lime_sellercenter translate="label" module="lime_sellercenter">
            Seller Center Integration
            <tab>lime</tab>
            <frontend_type>text</frontend_type>
            <sort_order>100</sort_order>
            <show_in_default>1</show_in_default>
            <show_in_website>1</show_in_website>
            <show_in_store>1</show_in_store>
            <groups>
                <lazada translate="label">
                    Lazada Settings
                    <frontend_type>text</frontend_type>
                    <sort_order>10</sort_order>
                    <show_in_default>1</show_in_default>
                    <show_in_website>1</show_in_website>
                    <show_in_store>1</show_in_store>
                    <fields>
                        <status translate="label">
                            Enabled:
                            <frontend_type>select</frontend_type>
                            <sort_order>0</sort_order>
                            <show_in_default>1</show_in_default>
                            <show_in_website>1</show_in_website>
                            <show_in_store>1</show_in_store>
                            <source_model>adminhtml/system_config_source_yesno</source_model>
                        </status>
                        <service_url translate="label">
                            API URL:
                            <frontend_type>text</frontend_type>
                            <sort_order>10</sort_order>
                            <show_in_default>1</show_in_default>
                            <show_in_website>1</show_in_website>
                            <show_in_store>1</show_in_store>
                            <depends>
                                <status>1</status>
                            </depends>
                        </service_url>
                        <api_user translate="label">
                            API User ID:
                            <frontend_type>text</frontend_type>
                            <sort_order>20</sort_order>
                            <show_in_default>1</show_in_default>
                            <show_in_website>1</show_in_website>
                            <show_in_store>1</show_in_store>
                            <depends>
                                <status>1</status>
                            </depends>
                        </api_user>
                        <api_key translate="label">
                            API Key:
                            <frontend_type>password</frontend_type>
                            <sort_order>30</sort_order>
                            <show_in_default>1</show_in_default>
                            <show_in_website>1</show_in_website>
                            <show_in_store>1</show_in_store>
                            <depends>
                                <status>1</status>
                            </depends>
                        </api_key>
                        <debugmode translate="label">
                            Debug Mode:
                            <frontend_type>select</frontend_type>
                            <sort_order>2</sort_order>
                            <show_in_default>1</show_in_default>
                            <show_in_website>1</show_in_website>
                            <show_in_store>1</show_in_store>
                            <source_model>adminhtml/system_config_source_yesno</source_model>
                        </debugmode>
                        <sync_orders_from translate="label">
                            Sync Orders After:
                            <frontend_type>text</frontend_type>
                            <frontend_model>lime_sellercenter/adminhtml_system_config_date</frontend_model>
                            <sort_order>40</sort_order>
                            <show_in_default>1</show_in_default>
                            <show_in_website>1</show_in_website>
                            <show_in_store>1</show_in_store>
                            <depends>
                                <status>1</status>
                            </depends>
                            <comment>Leave field empty to disable order syncing.</comment>
                        </sync_orders_from>
                        <auto_download_time translate="label">
                            Auto Sync Order At:
                            <frontend_type>text</frontend_type>
                            <sort_order>70</sort_order>
                            <show_in_default>1</show_in_default>
                            <show_in_website>1</show_in_website>
                            <show_in_store>1</show_in_store>
                            <depends>
                                <status>1</status>
                            </depends>
                            <comment>Enter 0 - 23. Separated by comma (eg. 1,6,13,23)</comment>
                        </auto_download_time>
                    </fields>
                </lazada>
            </groups>
        </lime_sellercenter>
    </sections>
</config>

A: Most likely it's cache playing the role. Just Log Out and Log In again. See this why you need to do this.
Also, consider adding ACL role, if you haven't already added.
Learn how to add ACL here.


text:
Q: Accessing global variables in parallel process using parallel.js in node.js I'm trying to access data from the main thread using paralleljs. This is my code:
var Parallel = require('paralleljs');
var b = 2
var p = new Parallel(3, {
    env: {
        b: b,
    }
});
p.spawn(function(){
    console.log(global.env.b);
}).then(function(){
});

Apparently global.env is undefined.


text:
Q: JSDOM - ECONNREFUSED 127.0.0.1:80 when running test in Azure DevOps When the job is running on Azure DevOps yarn test:unit the following error happens multiple times. This does not prevent tests to pass. The project runs vue and jest for testing. When runs locally, no errors occur.
jest.config.js
const Vue = require('vue');
const Vuetify = require('vuetify');

Vue.use(Vuetify);

module.exports = {
  preset: '@vue/cli-plugin-unit-jest/presets/typescript-and-babel',
  collectCoverage: false,
  collectCoverageFrom: [
    'src/**/*.{js,vue}',
    '!src/registerServiceWorker.js',
    '!src/helpers.js',
    '!src/constants/**',
    '!src/mixins/**',
    '!src/plugins/**',
    '!src/router/**',
    '!src/test/**',
    '!src/main.js', // No need to cover bootstrap file
  ],
  transform: {
    'vee-validate/dist/rules': 'babel-jest',
  },
  transformIgnorePatterns: [
    '<roodDir>/node_modules/(?!vee-validate/dist/rules)',
  ],

  testEnvironmentOptions: {
    // Allow test environment to fire onload event
    // See https://github.com/jsdom/jsdom/issues/1816#issuecomment-355188615
    resources: 'usable',
  },
};

axios.js
let baseURL = '';
switch (process.env.NODE_ENV) {
  case 'development': {
    baseURL = 'https://localhost:44359/api/v1';
    break;
  }
  case 'production': {
    baseURL = 'webapi/api/v1';
    break;
  }
  case 'docker': {
    const port = process.env.VUE_APP_WebAPI_PORT;
    const path = process.env.VUE_APP_WebAPI_Path;
    const version = process.env.VUE_APP_WebAPI_Version;
    const url = new URL(window.location.origin);
    url.port = port;
    baseURL = `${url.origin.toString()}/${path}/${version}`;
    break;
  }
  default: baseURL = 'webapi/api/v1';
}

/* eslint-disable import/prefer-default-export */
export const http = axios.create({
  baseURL,
  withCredentials: true,
  headers: {
    Accept: 'application/json',
    'Content-Type': 'application/json',
  },
  paramsSerializer: (params) => {
    Object.keys(params).forEach((key) => {
      if (_isArray(params[key]) && !params[key].length) {
        delete params[key];
      }
    });
    return qs.stringify(params, { arrayFormat: 'repeat' });
  },
});

Error

Error: Error: connect ECONNREFUSED 127.0.0.1:80
at Object.dispatchError (/home/vsts/work/1/s/node_modules/jsdom/lib/jsdom/living/xhr-utils.js:54:19)
at Request. (/home/vsts/work/1/s/node_modules/jsdom/lib/jsdom/living/xmlhttprequest.js:675:20)
at Request.emit (events.js:327:22)
at Request.onRequestError (/home/vsts/work/1/s/node_modules/request/request.js:877:8)
at ClientRequest.emit (events.js:315:20)
at Socket.socketErrorListener (_http_client.js:426:9)
at Socket.emit (events.js:315:20)
at emitErrorNT (internal/streams/destroy.js:92:8)
at emitErrorAndCloseNT (internal/streams/destroy.js:60:3)
at processTicksAndRejections (internal/process/task_queues.js:84:21) undefined
console.error node_modules/jsdom/lib/jsdom/virtual-console.js:29

Any help would be welcome

A: This error could be due to i18n usage. I have noticed that when I have the same problem and debug it, it gets this error because it cannot access localization files. You can use the moduleNameMapper setting as a solution.
https://jestjs.io/docs/en/configuration#modulenamemapper-objectstring-string--arraystring


text:
Q: Number of matrices over finite fields $\mathbb{F}_q$ with some minors to be $0$ is (or is not?) polynomial in $q$? It's well-known that
$$\# \operatorname{GL}_2(\mathbb{F}_q)=(q^2-1)(q^2-q)$$
is a ($\mathbb{Z}$-coefficient) polynomial of $q$. As a corollary,
$$\#\left\{ A \in M_{2\times 2}(\mathbb{F}_q)\, \middle|\,\det A =0 \right\}=q^4-(q^2-1)(q^2-q)$$
is a polynomial of $q$.
In general, fix $n \in \mathbb{N}_{>0}$, $\Lambda$ denotes for the subset of
$$X:=\left\{ (k,I,J)\, \middle|\, \begin{aligned}
   &I:1 \leqslant i_1 < \cdots <i_k \leqslant m\\
   &J:1 \leqslant j_1 < \cdots <j_k \leqslant m
   \end{aligned}  \right\},$$
$A_{I,J}$ denote for the corresponding minor, is
$$\#\left\{ A \in M_{n\times n}(\mathbb{F}_q)\, \middle|\,A_{I,J} =0, \;\forall\, (k,I,J) \in \Lambda  \right\}$$
always a polynomial of $q$?
A possible nontrivial case to work with:
$$\#\left\{ A \in M_{3\times 3}(\mathbb{F}_q)\, \middle|\,\begin{vmatrix} a_{11} & a_{12}  \\ a_{21} & a_{22}  \end{vmatrix} =\begin{vmatrix} a_{22} & a_{23} \\ a_{32} & a_{33}  \end{vmatrix} =\begin{vmatrix} a_{11} & a_{12} & a_{13} \\ a_{21} & a_{22} & a_{23} \\a_{31} & a_{32} & a_{33}  \end{vmatrix}=0 \right\}.$$
When the answer is true, maybe the proof can be generalized to show that
$$\#\left\{ A \in M_{n\times n}(\mathbb{F}_q)\, \middle|\,\begin{aligned}
   &A_{I_1,J_1} =0, \;\forall\, (k,I_1,J_1) \in \Lambda_1\\
   &A_{I_2,J_2} =1, \;\forall\, (k,I_2,J_2) \in \Lambda_2\\
    &A_{I_3,J_3} \neq 0, \;\forall\, (k,I_3,J_3) \in \Lambda_3
   \end{aligned}  \right\} \qquad (\ast)$$
is a polynomial of $q$, where $\Lambda_1, \Lambda_2,\Lambda_3$ are disjoint subsets of $X$. When the answer is false, the counterexample should be not too complicated. Anyhow, this can be viewed as a purely combinational problem.
Related question: Number of $3\times 3$ anticommuting matrices over finite fields $\mathbb{F}_p$ is (or is not?) polynomial in $p$?
Edit: at least for the generalization $(\ast)$, there is a counterexample. The number
\begin{equation}
\begin{aligned}
&\#\left\{ \begin{pmatrix} a & 0 & 0 \\ 0 & b & 0 \\ 0 & 0 & c  \end{pmatrix} \in M_{3\times 3}(\mathbb{F}_q)\, \middle|\,\begin{vmatrix} a & 0 \\ 0 & b  \end{vmatrix} =\begin{vmatrix} b & 0 \\ 0 & c  \end{vmatrix} =\begin{vmatrix} a & 0 \\ 0 & c  \end{vmatrix}=1 \right\}\\
=\;& \#\left\{ a \in \mathbb{F}_q^{\times}\, \middle|\,a^2=1 \right\}
\end{aligned}
\end{equation}
is not a polynomial of $q$.


text:
Q: DNN - make new pages viewable to All Users by default I have a DNN 7 site. For new pages that are created in the portals, we want "All Users" to be checked under View Page by default.
How do we do this? I think I've found the right template file:
/Portals/_default/Templates/Default.page.template
But I can't find any documentation about the tags therein.
It does have:
          <inheritviewpermissions>true</inheritviewpermissions>

But where are the view permissions inherited from?  And how to override them?
Again, we want it so that new pages are viewable to all users by default; no need to go change anything after new page creation. (Yeah, I know, but that's the requirement.)


text:
Q: How to change radio button behavior? I have this form:
<%= form_for(@submitted_quiz) do |f| %>
<%= f.hidden_field :quiz_id, :value => @quiz.id %>
<%= f.hidden_field :name, :value => @quiz.name %>

<%= @quiz.questions.each do |question| %>

<%= f.label question.content %>

<%= question.answers.each do |answer| %>
<%= f.label answer.content %>

<%= f.fields_for (:submitted_answers) do |ff| %>

<%= ff.radio_button :content, value: answer.content %>

<% end #fields_for (:submitted_answers) do %>
<% end #answer.each do  %>
<% end #questions.each do %>

<%= f.submit %>
<% end #form_for  %>

But I'm able to check all the radio buttons off, instead of just one radio button per question set (each question has 4 answers and I want to check off only one out of the 5 answers). I know why this is happening, since each submitted_answers is unique and I'm constructing a standalone radio button for each of them, but I don't know how to actually fix this. Any ideas?

A: I solved it by putting the  question.answers.each loop into the fields_for. I have a sort-of-maybe idea of how this works but I'm still not 100% sure why this solved it.
<%= f.fields_for (:submitted_answers) do |ff| %>

<%= question.answers.each do |answer| %>
<%= ff.label :content, answer.content %>
<%= ff.radio_button :content, answer.content %>

<% end #answer.each do %>
<% end #fields_for (:submitted_answers) do %>


text:
Q: How to convert bson.Binary to []byte in Go I'm writing a small application that receives message in BSON format from network(its not MongoDB) and have to save fields in files on local machine. I'm using gopkg.in/mgo.v2/bson for message unmarshaling and it works fine.
Almost everything works except one. There "userdefined" binary field in message and I have to save it to separate file. I tried to use:
var pwr = msg["pwr"].([]byte)

but got an "error panic: interface conversion: interface is bson.Binary, not []uint8".
Can some one point me an example how to convert bson.Binary to []byte, so I can save it to file.

A: This does what you want:
pwr := bson.Binary(msg["pwr"].(bson.Binary)).Data

But assumes msg["pwr"] can't be anything other than a bson.Binary... if that's not an invariant you should do the type assertion first (handle the possible type mismatch case when it happens) and then cast to get the Data field.


text:
Q: Transition for transform scale on html is only animating when mouse is moving This is my simple code, which I want it to scale my whole document (html) with a delay of 1s (with javascript) and it should animate slowly the scale of the whole website.
In this fiddle, it is not really working at all - but on my file it actually animates it, but only when the user moves the mouse constantly.
html {
height: 100%;
width:100%;
transition: transform 15s linear;
transform: scale(0.6)

setTimeout(function(){
  document.querySelector("html").style.transform = "scale(0.7)";
},1000)
html {
  height: 100%;
  width:100%;
  transition: transform 15s linear;
  transform: scale(0.6);  background:url("https://www.toptal.com/designers/subtlepatterns/patterns/moroccan-flower-dark.png");
 }

A: I could not make it work with your code so I modified it like this:

And it seems to work as expected for me, whether I move the mouse or not. The issue is that the background on html or body tag will fill the full size of the screen even if zooming in and out or resizing.
EDIT:
If you want the background to fit the full window while the content is growing: I just added a div in your body to see easier what is happening. Is this what you want to have?

setTimeout(function(){
  document.querySelector("html").style.transform = "scale(0.8)";
},1000)
html {
  height: 100%;
  width:100%;
  transition: transform 15s linear;
  transform: scale(0.6);
  background:url("https://www.toptal.com/designers/subtlepatterns/patterns/moroccan-flower-dark.png");
}

body{
  height: 100%;
  width:100%;
}

div{
  height: 100%;
  width:100%;
  background-color: #000;
}


text:
Q: Covariance of two truncated random variables Assume that $X=(X_1,X_2)^T$ is a random vector that is multivariate normal with mean vector $\mu$ and variance-covariance matrix $\Sigma$. I.e. we have $$ X \sim N_2(\mu, \Sigma).$$
I am interested in the truncated version of this normal distribution and assume that $X_1$ and $X_2$ are smaller than some threshold $c$. Hence I am searching for $X^*=(X_1^*,X_2^*)^T$ that is jointly trucnated normal
$$ X^*~\sim TN_2(\mu, \Sigma,c)$$
While there are formulas for the expectation and the variance of the univariate truncated normal I do not know how to compute the covariance of $X_1^*$ and $X_2^*$: $\operatorname{Cov}(X_1^*,X_2^*)= \operatorname{Cov}(X_1,X_2\mid X_1<c,X_2<c)$.


text:
Q: How to fix the text cursor position in an html textarea with unicode-bidi: plaintext with a RTL language? We've been using textareas with the css setting unicode-bidi: plaintext this handled mixing left to right and right to left languages beautifully until about 2 months ago with the new release of chrome.  The text positioning still works properly, but from chrome 86 and on (I think - I don't remember which version broke this) the cursor started jumping to the beginning of the line after a space with RTL languages. Take a look the recording here...

https://i.stack.imgur.com/YursB.gif
In chromium edge the cursor positioning still works, but not everyone wants to use edge.
Anyone know how to fix the cursor jump after a space for RTL languages?


text:
Q: Toast The method makeText(context, charSequance, int) in the type Toast is not applicable for the argument (multiFunction,String, int) I'm new to android development, I have created a new class called multiFunction and created two functions for Toast but I'm getting an error says: The method makeText(context, charSequance, int) in the type Toast is not applicable for the argument (multiFunction,String, int)
package com.s.smart;

import android.content.Context;
import android.widget.Toast;

public class multiFunction {
//function to generate toast message

public void longMessage(String yourMessage){
    Toast.makeText(multiFunction.this,yourMessage, Toast.LENGTH_LONG).show();

}
public void shortMessage(String yourMessage){
    Toast.makeText(multiFunction.this,yourMessage, Toast.LENGTH_SHORT).show();

}
}

A: I found the issue....
package com.s.smart;

import android.content.Context;
import android.widget.Toast;

public class multiFunction {
    private Context context;
    public multiFunction(Context context){
        this.context = context;
    }
//function to generate toast message

    public void longMessage(String yourMessage){
        Toast.makeText(this.context,yourMessage, Toast.LENGTH_LONG).show();
    }
    public void shortMessage(String yourMessage){
        Toast.makeText(this.context,yourMessage, Toast.LENGTH_SHORT).show();

    }
}


text:
Q: Creating my first JDBC Realm(Glassfish V3) I want to create a JDBC Realm for my web app. Since my users are very different from each other i need to have just one table, with the usernames and passwords for the realm, i decided to create a new table in my database called ROLE(oneToOne relationship with the other users table).
This is how my users domain model looks like:

I am following this tutorial http://blog.gamatam.com/2009/11/jdbc-realm-setup-with-glassfish-v3.html but i am stuck, i dont know how to continue.
I will post the configuration i made at the glassfish server and also my file sun.resources.xml so you can correct me if i am making any mistake:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE resources PUBLIC "-//Sun Microsystems, Inc.//DTD Application Server 9.0  Resource Definitions //EN" "http://www.sun.com/software/appserver/dtds/sun-resources_1_3.dtd">
 <resources>
 <jdbc-resource enabled="true" jndi-name="jdbc/myDatasource" object-type="user" pool- name="Derby_grupovina_grupovinauserPool"/>
 <jdbc-connection-pool allow-non-component-callers="false" associate-with-thread="false" connection-creation-retry-attempts="0" connection-creation-retry-interval-in-seconds="10" connection-leak-reclaim="false" connection-leak-timeout-in-seconds="0" connection-validation-method="auto-commit" datasource-classname="org.apache.derby.jdbc.ClientDataSource" fail-all-connections="false" idle-timeout-in-seconds="300" is-connection-validation-required="false" is-isolation-level-guaranteed="true" lazy-connection-association="false" lazy-connection-enlistment="false" match-connections="false" max-connection-usage-count="0" max-pool-size="32" max-wait-time-in-millis="60000" name="Derby_grupovina_grupovinauserPool" non-transactional-connections="false" pool-resize-quantity="2" res-type="javax.sql.DataSource" statement-timeout-in-seconds="-1" steady-pool-size="8" validate-atmost-once-period-in-seconds="0" wrap-jdbc-objects="false">
<property name="serverName" value="localhost"/>
    <property name="PortNumber" value="1527"/>
    <property name="DatabaseName" value="grupovina"/>
    <property name="User" value="grupovinauser"/>
    <property name="Password" value="grupovina"/>
    <property name="URL" value="jdbc:derby://localhost:1527/grupovina;create=true"/>
    <property name="driverClass" value="org.apache.derby.jdbc.ClientDriver"/>
   </jdbc-connection-pool>
  </resources>

In the above comfiguration i have a few doubts, I dont really understand what should i ad at Group table and Group name Column.
The tutorial im following says that i should add security roles at the file sun-web.xml, and i wanted to do it but i dont know what to put in the configuratio. This is just what i added to that file but i think it is not correct. Where in that file should i add the role mapping and how should i configure it?
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE sun-web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Application Server 9.0 Servlet 2.5//EN" "http://www.sun.com/software/appserver/dtds/sun-web-app_2_5-0.dtd">
<sun-web-app error-url="">
<context-root>/GroupBuySystem</context-root>
<class-loader delegate="true"/>
<jsp-config>
<property name="keepgenerated" value="true">
  <description>Keep a copy of the generated servlet class java code.</description>
</property>
</jsp-config>
<security-role-mapping>
<role-name> </role-name>
<group-name> </group-name>
</security-role-mapping>
</sun-web-app>

The guy of the tutorial said he had not need for a web.xml, but i do need that file. What  should i add my web.xml?
This is my first jdbc realm, i am very confused :)

A: I assume (from your previous question) that you don't have a group table. In fact you don't necessarily need one. JDBCRealm works with only a user table containing a group column as well.
In your Glassfish admin console change the following:
Group Table: Role
Group Name Column: userType
Since you used different typings (letter cases) for the word "role", make sure that the configuration values for your realm are exactly the same as in the table.


text: Q: Bind combobox in DataGrid template using DataTable Can you tell me how to bind combo-box in WPF Datagrid Column and bind it using database. I have search so many artistic or blog here but could get proper help for it. So please guide me how to achieve that.


text:
Q: JavaScript - Change string to number but keep decimals I am having difficulties with a small math calculation.
I have a string from a form field which I need to convert to a number so I can multiply two fields together (it's a cost and qty field that then sets my total cost line).
The issue I am having is sometimes the number is a solid number (100, 150, 3), sometimes it has commas and sometimes it has decimals.
I have a .replace to replace all the commas with nothing to assist with this issue and it works well.
It works great when I parseInt(var_name) except it strips off my decimal points. I don't want rounding since it's actually part of a purchasing script.
How would I change my two string fields to a numeric field?
var num1 = '100.00';
var num2 = '200,000.51';
alert(num1 X num2); // 20,000,051.00


text:
Q: String data doesn't return when I do that with a name containing _ in front of name enter image description here
Plz let me know.. why it doesn't work here??
there says it is undefinied name.

A: Define the function witin the StoryBrain class and call the function using StoryBrain().getStory()

A: Firts, you define variable in a class, so you can't use it variable directly, you need an instance of class to call it variable.
Second, in dart _ mean private.


text:
Q: somewhere between sub-gaussian and central limit theorem (problem statement revamped.)
Definition:
A random variable $X$ is a sub-gaussian if $$\Pr(|X|>t) \leq \exp(-t^2/k^2) \quad \text{for all $t\geq 0$ and for some constant $k$.}$$

I want to compute trace of a matrix by Monte Carlo simulation. For example, in lattice Quantum Chromodynamics, we need to compute the trace of a function of a large matrix, trace($f(\mathbf{A}')$) where explicit computation of $f(\mathbf{A}')$ is impractical but computing $\mathbf{x}f(\mathbf{A}')\mathbf{x}^T$ is feasible. For simplicity, let's say the quadratic form is $\mathbf{x}\mathbf{A}\mathbf{x}^T$.

One standard approach is Monte Carlo simulation where the trace is estimated by $X=\frac{1}{M}\sum_{i=1}^M\mathbf{x}_i\mathbf{A}\mathbf{x}_i^T$ where each entry in $\mathbf{x}_i$ is sampled from $N(0,1)$ independently. I know that $X$ is sharply concentrated around $E(X) = tr(\mathbf{A})$, and $X$ is sub-gaussian, to be precise.
One standard way to show that a random variable is sharply concentrated around the mean is $(\epsilon,\delta)$-approximation of tail bound.
$$\Pr(|X - E(x)|>\epsilon)<\delta$$
which can be easily computed from the definition of sub-gaussian in my problem. And this tells us how many samples $M$ are required to guarantees $(\epsilon,\delta)$-approximation.
Meanwhile, the Central Limit Theorem tells us that $\sqrt{M}(X- E(x))$ converges in distribution to $N(0, \sigma^2)$, which is sharply concentrated around the shifted mean 0.
 Even though it requires $M\to\infty$, it tells us the exact probability distribution of $X$. Maybe it's not a correct interpretation, but it seems to me that these two are the exact opposite of the spectrum.

*

*Sub-gaussian: a finite number of samples, but $(\epsilon,\delta)$-approximation

*CLT : number of samples $\to\infty$, but exact probability distribution.

Let's say I have two matrices $\mathbf{A}$ and $\mathbf{B}$ which differ at only one entry. I ran Monte Carlo simulation to obtain the value $X=\frac{1}{M}\sum_{i=1}^M \mathbf{x}_i\mathbf{A}\mathbf{x}_i^T$ and $Y=\frac{1}{M}\sum_{i=1}^M \mathbf{y}_i\mathbf{B}\mathbf{y}_i^T$ where each entry in $\mathbf{x}_i$ and $\mathbf{y}$ is independently sampled from $N(0,1)$.

Question: Is there anyway to point-wise compare the probability distribution functions of $\mathbf{X}$ and $\mathbf{Y}$ to show that
$$\exp(-\alpha)f_Y(t) \leq f_X(t) \leq \exp(\alpha)f_Y(t)$$
with probability at least $1 − \beta$ over $t$ drawn from the range of $X$ or $Y$?
This kind of inequality may seem odd, but it's used in some recent papers. For example, let's say $X$ is sampled from a Laplace distribution with density function
$$h(x)=\frac{1}{2b}\exp(-|x|/b)$$ and compare it to Y which is sampled from a shifted Laplace distribution with density function
$$h(x+\delta)=\frac{1}{2b}\exp(-|x+\delta|/b).$$
Then the ratio $h(x)/h(x+\delta)\leq \exp(|\delta|/b)$ where I can show that $$h(x) \leq \exp(|\delta|/b)h(x)$$
for the entire domain of $X$.
In case that the random variable is sampled from a standard Gaussian with density function $$g(x)=\frac{1}{\sqrt{2\pi}}\exp(-\frac{x^2}{2}),$$ the picture is slightly nuanced: we can show that $g(x)/g(x+\delta)$ is bounded in the region of $|x|\leq \xi$ where $\xi$ depends on $\delta$. This results in $(\alpha,\beta)$ approximation.
This inequality may look too strong, but it's based on the intuition that

*

*sub-gaussian random variables must be sharply concentrated around the mean, and

*subgaussian ranodm variable is a generalization of Gaussian random variable.

Is there any way to do that, or is my conjectured inequality too strong?


text:
Q: proving point wise convergence but no uniform convergence on f Let f$_n$: E → $R$ be continuous functions for 1 ≤ n ≤ N. Let a$_k$$^n$ be N convergent sequences of numbers and assume $\lim_{k \to inf}$ a$_k$$^n$  = a$_n$. Let f = $\sum_{n=1}^N$a$_n$f$_n$.
I am looking at $\sum_{n=1}^N$ a$_k$$^n$f$_n$. I am pretty sure that it converges pointwise to f but I don't think it converges uniformly to f. However, I am having trouble proving the point wise convergence to f and cannot think of a good counterexample for the uniform convergence to f. Any help would be great!