text:
Q: App force closes with java.lang.NoClassDefFoundError: android/os/AsyncTask We recently introduced OAuth login in our app. This means using a WebView to authenticate the user, and an AsyncTask to do necessary REST calls afterwards.
Unfortunately, after introducing this login method, we're getting reports of the app force closing. This seems to be related to other AsyncTasks  that are executed after the login, but the stack traces does unfortunately not tell us much:
java.lang.IllegalStateException: Could not execute method of the activity
at android.view.View$1.onClick(View.java:3100)
at android.view.View.performClick(View.java:3627)
at android.view.View$PerformClick.run(View.java:14329)
at android.os.Handler.handleCallback(Handler.java:605)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4511)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:980)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:747)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at android.view.View$1.onClick(View.java:3095)
... 11 more
Caused by: java.lang.NoClassDefFoundError: android/os/AsyncTask
at com.foo.bar.TransmissionActivity.transmit(TransmissionActivity.java:44)
... 14 more

We managed to fix the error above by using RoboAsyncTask (from RoboGuice), instead of AsyncTask from the Android SDK, but we have other activities that use WebViews. WebView apparently uses AsyncTask somewhere in its call stack, and errors similar the one shown above (Caused by: java.lang.NoClassDefFoundError: android/os/AsyncTask) have started to show in our error logs.
The error happens on different devices, and different Android versions, with no apparent pattern. We have tried to reproduce the error ourselves, without any luck.
Any ideas?

A: It might be an issue with the build setup. (Build order of src/gen has been known to cause some issues, the libs folder for the compat library being called lib has caused some issues for me on new sdk versions).
To see if it is create a new project (in eclipse, since that's 100% android official). Add a webview and an asynctask and then do a diff on the project with your project. Ignoring src/gen/res. Hopefully you'll find that the src/gen are built in the wrong order or something like that.
~ Anders


text:
Q: dual boot, dual drive Macbook pro unibody mid 2012 I have recently bought a new SSD for my macbook pro, and plans to put my old HDD in a caddy and place it on the optical drive slot.
In my old HDD is ParrotOS and some important files. I plan to install Catalina on the SSD
I tried installing linux and MacOS in the same drive in the past, but Failed miserably. This way, it will be at different drives, and different file formats, so it wont interfere with each other. I have slow internet and cant afford to download large files regularly.
What are the available resources to download to have smoother Boot Switching between the two OS?

A: Macs have a builtin Startup Manager that can be accessed by holding down the option key at startup. This will detect an installation of macOS on either drive and will permit you to select to boot. You can test to see if your existing ParrotOS installation is compatible with the Startup Manager by booting to the Startup Manager. If compatible, then the ParrotOS will appear as a selection. Usually, the label will be EFI Boot.
If the builtin Startup Manager will not detect the ParrotOS installation, then you can try installing the rEFInd Boot Manager. This boot manager can usually detect any linux installation.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to give infinite width to a div? Suppose there are two divs, A & B.
Div B has been given a width of 900px;
Screen resolution is 500px;
this would cause a horizontal scroll.
the problem is when I scroll to right, I see that DivA is not REALLY 100%.
Is there any ways I can make DivA always fill remaining space ?
see the image,

adding the following image for the purpose of explaining the problem :

A: Hi now give to your body min-width:900px;
as like this
body{
min-width:900px;  // total width of your wraper as like wraper width
}

A: i think you missing float: left of DivA
.DivA{
float: left
width: 100%
}

A: If you use the CSS3 -webkit-box-flex property it will help.
But the problem is, it wont work on all the browsers.

A: Couldn't you just use width:100% for DivA It will fill the blank space. Moreover, add float:left; position:relative for both divs.

A: The problem is: the div container is not expanding over the window width... the divA has autowidth, so it will expand to the container width, the grid div has a min-width greater than the window width (i think... can't see it in the code)
My answer is:
Html:

Child Expand Test

<form action="#">

</form>

CSS:
    form {
        /* just to show the form doesn't expand, if you need expand it /
        / move the answer line to this class */
        background-color: silver;
        padding-top: 1em;
        padding-bottom: 1em;
    }
.divContainer {
    display: inline-block; /* this is the answer line, to expand over the window width */
}

.divA { /* this div will expand over the window width */
    background-color: red;
}

.divGrid {
    background-color: blue;
     min-width: 1500px; /* This is the reason why its needed, yo expand one child width over the size of the window */
}

Here is a fiddle: http://jsfiddle.net/bjb7drdm/


text:
Q: Is there a way to use .innerHTML multiple times? I would like to write two variable values into a div container (with id myDiv) using innerHTML. My Div container is only showing the second value.
<button type="button" onclick="myFunction()">Click me</button>
<input type="text" id="First" name="firstname">
<input type="text" id="Last" name="lastname">

A: First you need to use correct ids everywhere. Second you can just add x+y in one assignment only like this:
<button type="button" onclick="myFunction()">Click me</button>
<input type="text" id="First" name="firstname">
<input type="text" id="Last" name="lastname">

or you can use += for if you want to keep appending to previously assigned value.
document.getElementById("myDiv").innerHTML = x;
document.getElementById("myDiv").innerHTML += y;


text:
Q: If $f$ is convex, is $\sup_x f(x,y)$ convex? Suppose that $f(x,y)$ convex. Let $g(y) = \sup_x f(x,y)$. Then is $g$ convex?
I can't find a counter example but I know that this holds true if we substitute $\inf$ for $\sup$, so I feel that it should not hold true.

A: Let $f:D\subset \mathbb{R}^{2}\rightarrow \mathbb{R}$ be convex on $D$ and assume there exists $c=c(y)\in \mathbb{R}$
$$f(x,y)\leq c(y)$$ for a fixed  all $(x,y)\in D$.
Now fix $(x,b)\in D\cap \big\{(x,y)\in D: y=b\big\},\;$ $\lambda \in [0,1].\;$ Since $f$ is convex on $D$ then
$$ f( (1-\lambda) (x,y)+\lambda (x,b)) \leq
 (1-\lambda) f(x,y)+\lambda f(x,b)) $$
Simply take the supremum over $x$ to get
$$ g( (1-\lambda) (y)+\lambda g(b)) \leq
 (1-\lambda) g(y)+\lambda g(b) $$
for every $y\in \mathbb{R}$ such that $(x,y)\in D$. Since the line $y=b$ was chosen arbitrarily, then $g$ is convex.


text:
Q: Struggling to open PDF file in IE Im struggling to open a pdf file in Internet explorer
Console shows up a warning
"HTML1527: DOCTYPE expected. The shortest valid doctype is "<!DOCTYPE html>"."

Markup rendered
<head></head>
<body topmargin="0" leftmargin="0" scroll="no">
    <embed width="100%" height="100%" src="websitename/file.pdf" type="application/pdf" fullscreen="yes">
</body>

I've also tried disabling "Display PDF in browser" option from Adobe Reader Preferences, still no luck.

A: To allow Internet Explorer to open PDF directly, ensure Acrobat Viewer add-on is enabled.
Reference: http://answers.microsoft.com/en-us/ie/forum/ie9-windows_7/how-to-force-internet-explorer-9-to-open-pdf-in/76e03210-d03a-4c13-bcd9-ac899c3a0ae1?msgId=e7c98b6a-de1b-4873-9210-4ba0a0c574ae

A: You should see if other web-based PDFs open correctly in your browser. Assuming they do this will confirm a problem in the way the content is being sent from the server.
You can detect exactly what the problem is using a tool like IEWatch to see the headers and data. I would suspect that the content-disposition is incorrect.
There are common causes of this type of issue detailed here:
http://www.websupergoo.com/support.htm?nav=6.16
I work on the ABCpdf .NET software component hence the link above. It's just what I know. :-)

A: I recently had this error in a similar context and it was caused by my server using SSL, and the pdf source server not, causing a type of mixed-content problem with IE.
I used a proxy page to pull the pdf via https and that worked. Only remaining issue is the PDF file name got lost to adobe reader, so when the user goes to save, it prompts them for 'proxy.pdf'


text:
Q: Disable JTable rowsorter for HeaderView I am having 2 JTables, one for displaying the rows and one for displaying the data:

Problem: When the data table are sorted, also the rows are sorted:

Is it possible to make the "RowHeaderView" table to not get sorted like the data table?
public class SimpleJTableHeader extends JFrame {

    public JTable table;

    public SimpleJTableHeader() {

        // CREATE A JTABLE
        Object rowData[][] = { { "a" }, { "b" }, { "c" }, { "d" } };
        Object columnNames[] = { "1" };
        table = new JTable(rowData, columnNames);
        table.setRowHeight(20);
        table.setAutoCreateRowSorter(true);

        JScrollPane scrollPane = new JScrollPane(table);

        // ADD ROW NUMBERS TO THE TABLE
        scrollPane.setRowHeaderView(getHeaderTable());

        // SHOW TABLE
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(scrollPane, BorderLayout.CENTER);
        frame.setSize(300, 150);
        frame.setVisible(true);
    }

    public JTable getHeaderTable() {
        final AbstractTableModel model = new AbstractTableModel() {

            private static final long serialVersionUID = 1L;

            @Override
            public int getColumnCount() {
                return 1;
            }

            @Override
            public Object getValueAt(int row, int column) {
                return table.convertRowIndexToModel(row);
            }

            @Override
            public int getRowCount() {
                return table.getRowCount();
            }
        };
        JTable headerTable = new JTable(model);
        headerTable.setPreferredScrollableViewportSize(new Dimension(40, 0));
        headerTable.setRowHeight(20);
        return headerTable;
    }

    public static void main(String args[]) {
        new SimpleJTableHeader();
    }
}

A: Thanks to mKorbel the new correct getHeaderTable method:
public JTable getHeaderTable() {
    DefaultTableModel model = new DefaultTableModel() {

        private static final long serialVersionUID = 1L;

        @Override
        public int getColumnCount() {
            return 1;
        }

        @Override
        public boolean isCellEditable(int row, int col) {
            return false;
        }

        @Override
        public int getRowCount() {
            return table.getRowCount();
        }

        @Override
        public Class<?> getColumnClass(int colNum) {
            switch (colNum) {
            case 0:
                return String.class;
            default:
                return super.getColumnClass(colNum);
            }
        }
    };

    JTable headerTable = new JTable(model);
    for (int i = 0; i < table.getRowCount(); i++) {
        headerTable.setValueAt((i + 1), i, 0);
    }
    headerTable.setPreferredScrollableViewportSize(new Dimension(40, 0));
    headerTable.setRowHeight(20);
    return headerTable;
}


text:
Q: How to pass options to MiniMagick while using Carrierwave's process? I have an uploader like this:
class PhotoUploader < CarrierWave::Uploader::Base
  include CarrierWave::MiniMagick

  storage :file

  version :titers_112x108 do
    process resize_to_fill: [112, 108, 'North']
  end
end

The problem is that I want to pass a quality parameter while resizing an image, so that my PNG image won't loose any quality in the process.
This option is available for ImageMagick's mogrify which is used in MiniMagick under the hood and suggested to use by Carrierwave as a separate process.
Looking into the code of CarrierWave::MiniMagick.resize_to_fill we can see that we can pass options as the last argument to the method, so I tried doing this:
process resize_to_fill: [112, 108, 'North', { quality: '0' }]

but it fails with
ArgumentError: unknown keyword: quality
  from .../gems/carrierwave-1.3.1/lib/carrierwave/processing/mini_magick.rb:191:in `resize_to_fill'

I'm using Carrierwave version 1.x.


text:
Q: mapping a single column in a table to two different columns in two different tables i have two tables
Brand and Store
A brand can be sold in multiple stores
and a store can sell multiple brands.
I have a bridge table brand_store.
There is a parent store table called StoreGroup.
This storegroup will contain all stores that belongs to a parent.
For eg: All stores of KFC will be mapped to a single parent in the store_group table.
Now I have to create a User table where a user can play multiple roles.
if the user is an admin then he has to be tied to the storegrp
if the user is a storeowner then he has to be tied to a particular store.
The merchant table looks like"
Merchant

id

login_email_id
login_password
store_or_store_group_id
role_id
....
Scenario:
Each KFC head can appoint an admin, a storemanager etc.
In the merchant table, if the role id   is admin then it should be tied to KFC head in store_group table, but if the role id is store manager then it should be tied to a particular store of KFC in store table.
how do i handle this scenario. is this the right way of doing ?

A: If you are using InnoDB, and you want MySQL to enforce foreign key constraints, you'd need to create two separate columns in merchant table, rather than the single column.
 , store_id       int  comment 'fk ref Store'
 , storegroup_id  int  comment 'fk ref StoreGroup'

 , CONSTRAINT FK_merchant_store FOREIGN KEY (store_id) REFERENCES Store(id)
 , CONSTRAINT FK_merchant_storegroup FOREIGN KEY (storegroup_id) REFERENCES StoreGroup(id)

There's no declarative constraint to prevent both columns from being populated, of you want the database to enforce that, you'd need to create a BEFORE INSERT and BEFORE UPDATE trigger.
If you go with the single combined column, then you won't be able to define a foreign key constraint. You'll also need a way to determine whether the value stored in that column is a reference to the Store table or the StoreGroup table (or, is that the purpose of the role_id column?)

A: I think you're close. Your Store table can have foreign key "store_group_id" instead.
And you just have the store id in your merchant table. Now you will be able to fetch the store_group_id based on the role_id (if he is 'admin' you can join the store table with merchant table to fetch the store_group_id). I hope this helps

A: I think, you should create different tables to bind merchants to different models. 'Merchant' is the common information about an user. And there are some (now only two) different roles. These roles define different behaviour. If now all differences in database lie in diverse bindings, then, later on, roles may acquire other different attributes. So, in my opinion there must be something like this:
Merchant table:
  id, login_email_id, login_password, role_id

AdminMerchant table:
  merchant_id - FK to merchant table, Unique
  store_group_id - FK to Store group table

ManagerMerchant table:
  merchant_id - FK to merchant table, Unique
  store_id - FK to store table


text:
Q: For what sort of workload can a Core i7-920 be faster than a i7-860? Core i7-860 has a slightly higher clock speed (2.8 vs 2.66 GHz)
Core i7-920 has QPI and tri-channel DDR3 (vs DMI and dual-channel)

A: AnandTech have a good comparison of the performance of these CPUs. The performance is very similar, but overall the i7 860 is faster. The i7 860 is a newer CPU, but there are some benefits for opting for a Bloomfield CPU (such as the i7 920):

1) High-end multi-GPU performance (or other uses of high bandwidth PCIe)
  2) Stock Voltage Overclocking
  3) Future support for 6-core Gulftown CPUs

As you point the i7 860 lacks the QPI, and so memory-intensive applications should tend to be faster on the i7 920:

There are definitely cases where Bloomfield's memory controller is a boon, the Core i7 860 is able to approach but not outperform the i7 920.

Edit: Using virtual machines and (extreme) gaming are the only things I can think of that the 920 would be better at, but decent benchmarks are needed to confirm this hunch (also the hard drive may end up being the bottleneck for VMs). This site has an excellent dissection of the pros and cons, and comes to more or less the same conclusion. And this post reinforces that the 920 has greater PCI-e potential than the 860 - which may be important if you plan to opt for dual graphics cards for gaming/graphics performance:

*

*P55 motherboards are less expensive than X58 motherboards.

*P55 motherboards have no PCI-e slots free to use with raid controllers or other cards.

*Overclock capabilities at stock voltages is very limited with the i7-860.

*Support for QPI has been abolished with the i7-860.

*P55 [860] is limited to 16 PCI-e lanes, X58 [920] has 36 lanes.

*X58 is fully compatible with the new hex-core Gulftown, P55 is not.

*P55 is limited to 4 memory slots, X58 has 6 memory slots.

A: The 920 will be faster when your problem is memory bound and not compute bound.  So most things with large working datasets will be faster with it.

A: The main advantage of the 920 is it's memory controller. This gives you a higher memory bandwidth and a higher max memory. Having enough memory for your application can be vastly faster than grinding swap.
I have also seen reports that while Intel say the max memory on the 9xx series is 24GB, unofficially it can drive 8GB dimms for a total of 48GB while the 8xx series cannot drive 8GB dimms. If that is true then it increases the difference in max memory from 1.5x to 3x.


text:
Q: Is there a way to batch resample and mosaic/merge many large raster files at once? I have over 400 large raster DEM files at 1 m resolution that I need to resample to 10 m resolution and merge/mosaic them all into one file. I am wondering if there is a way to do this all in one step or as few steps as possible. I assume it would be faster to resample first, then mosaic.
The reason I need to resample is because the other data I am working with is 10 m resolution. I have looked into the problem online, but have not found anything helpful yet.
Does anyone know any tools that can to do this? And which program can do it best? I have ArcGIS and QGIS but may be able to get access to other programs if needed.


text:
Q: Spring Boot 2 static resources subfolder I'm working with Spring Boot 2.1.2, trying to get webservices and MVC working. Right now I have a directory structure like this:

Whenever I try to access localhost:8080/findme.css it resolves, but when I go to localhost:8080/css/main.css I get a 404.
I have tried messing around with WebMvcConfigurer's addResourceHandlers method, but haven't had any luck. I've tried more combination's than whats pictured, but none seem to work.

How do I get resources in subfolders to be served?
Just to add some more possibly relevant information, I'm running Intellij IDEA Ultimate 2018.3.  I'm starting the server by debugging the main function pictured here (at the root my my project). I'm also using gradle, not maven.

Edit:
So it seems Intellij has something to do with it. If I run bootJar and run the resulting .jar in project/build/libs it starts up and I can access localhost:8080/css/main.css. I'm not sure why it won't work with Intellij's run configuration so far.


text:
Q: Passing parameter externally to a TestNG class My @DataProvider looks up some restful url as below.
@DataProvider(name = "dbconfig")
    public Object[][] provideDbConfig() {
        Map map = SwaggerUtility.getSwaggerData("http://petstore.swagger.io/v2/swagger.json");
I ideally want a way to pass the url externally to the TestNG run or class.
Is there a way to do that?
Ideally the tests would be integrated with some CI tool which needs to pass the parameter down to the TestNG job.
I do not see a way to pass parameters directly to a TestNG class.
Please let me know if there is a way around

A: You can pass it as an argument as a system level property - read it in your beforeclass method using System.getProperty("nameOfProp") and set a variable as you need for your class.


text:
Q: you can see SQL connection string username and password in compiled DLL when you store connection string in app.config I have a .net class library that compiles to dll. in this project I have dataset. under my project - settings.settings I keep my connection string. it is SQL authentication.

Then when I did a search using wingrep for username and password, low and behold, I can see it clearly in clear text in the DLL.

is there a way to have the dll not easily readable using notepad?
is having connection string under settings.settings not the best idea?
please advise?
thank you
not sure if this will serve my purpose?
http://www.developer.com/net/vb/article.php/10926_3500906_2/Encrypt-Connection-Strings-in-VS-2005-config-Files.htm I'll test and update tomorrow.

A: How are you deploying this app?
If it's a web app, then anyone who can own your system to the level of opening the DLL in a text editor can probably get into the database already and it won't matter what you do with the connection string.
If it's a desktop app, then the suggestion to use Windows authentication is probably the best. If that's not an option, then just make sure each user has their own username/password and store it securely outside the DLL.

A: I found this that I think that will serve my goal. indeed it is for winforms and my application is a DLL. but it should be similar enough that it will work
How to securely store a connection string in a WinForms application?


text:
Q: How can I keep SQL Server 2012 Management Studio connected to the DB for longer periods of time? Got a question on SQL Server 2012 Management Studio.
Is there a way to set up/customize the Management Studio so that if I don't use it for 30 minutes (approximately) it won't boot me out of the application and make me sign in all over again?
I don't want to keep it on forever, but an extra 30 minutes/1 hour would be nice. Not sure if that's possible.

A: You can use sp_who or sp_who2 to see what your SPID is while connected. If your management studio is connected you will show up as a user in the list. If something is killing your connection it is either your client configuration at connection time (connection timeout) or something configured to kill connections at the server (Group Policy on the network). By default your connection just goes into "Sleeping" status if no client connection timeout is issued at the time of connection. Connections don't typically get killed because it affects caching session for that spid to just drop it.


text:
Q: Are these the isolated singularities? Find the isolated singularities of the function $$f(z)=\frac{e^z-1}{z^4(z^2+4\pi^2)}$$
$$$$
I have done the following :
We set the denominator equal to zero : $$z^4(z^2+4\pi^2)=0 \Rightarrow z=0 \text{ or } z^2+4\pi^2=0 \Rightarrow z=\pm 2\pi i$$ These are the isolated singularities, right?


text:
Q: Resolving Circular References (C#) I'm having a couple of problems with circular reference/dependency that I've been sitting on all day. Something must be wrong with my thought process, I just don't get it.
Here are my projects:

Flip.Main     (ASP.NET MVC)
Flip.Domain   (C# DLL)
Flip.Services (C# DLL)
Flip.Utility  (C# DLL)

Current References/Dependencies:

Flip.Main ->     Flip.Domain, Flip.Services, Flip.Utility
Flip.Services -> Flip.Domain, Flip.Utility
Flip.Domain ->   Flip.Utility

I wanted to structure my project in a way that my services project has all services, my domain project the model, repository and 'fluent' extensions to query the model, and the main and utility project are pretty much self explanatory.
Problems encountered:
1) I have an EmailService in my Flip.Services project, which needs to send out localized emails. All localization is done in Flip.Main's App_GlobalResources. No idea how to get the strongly typed emails and other localized resources now to my service layer as Flip.Main already depends on the service layer and therefore I can have it depend back to the Main project.
2) I have business classes, e.g. CustomerSearchFilter which represents a strongly typed search query. I want those business classes outside of the Flip.Domain project because they are not part of the domain model. However, in my CustomerSearchFilter class I have domain class instances (e.g. CustomerGroup) so it needs to know about domain classes. At the same time my Fluent interface in my Flip.Domain project needs to know what CustomerSearchFilter is so I can apply it to my IQueryable interface. Circular reference again.
3) I have a custom [AuthorizeSessionState] attribute which I use to decorate specific controller actions in my ASP.NET MVC Flip.Main project. This is an ActionFilterAttribute which needs to instantiate my SessionService who resides in my Flip.Services project. I can't put this into my Utility class though (because Flip.Services already references Flip.Utility). I don't think they should be in Flip.Main either - do I have to make another project for this!?
(20 more)
I feel like I'm making a mistake somewhere down the line, especially when I read that others usually don't encounter circular reference problems. Help?

A: Use interfaces for all non-trivial classes. Place interfaces in a different assembly from implementation.

A: The question comes down to what you separate by namespace and what you separate by DLL.  If you have a good reason to keep EVERYTHING modular, you have to work really hard.  But if each of these dlls only have a class or two in them, perhaps you could merge them together?

A: Take a few minutes and sort out the procedures ... create an identifier for each project (FM, FS, FD, FU). List each publicly accessible procedure on a page and then add an identifier for a project, if that project uses the procedure ...
Then you can see which procedure needs to be in (or accessible to) which project.
Hope that helps!

A: *

*You can put your localized email strings in Flip.Services. The downside is that you have two places to maintain localized resources. You can also have a separate dll for all your resources to minimize the place to edit resources.

*You have to move the fluent interface to an other dll or make CustomerSearchFilter part of the domain.

*You will need to add more projects or rearrange your structure and use namespaces to create the separation.

A: It sounds like your building on concrete implementations instead of interfaces/contracts. As Ima suggests define interfaces that describe what a certain class should be able to do. Use this interface when you declare properties, parameters and the like. Keep the interfaces separate from the implementaion and both the implementation and the projects that uses the interface can reference the interface project.
You then get the nice option of using dependency injection making your code easier to test as an a side

A: In the "tiers" of a domain, repositories and services live at the same logical level, above the domain in an infrastructure role. I would suggest moving your repository implementations (queries, etc.) outside of the domain itself. That solves #2 at least.


text:
Q: Docker charm on juju Ubuntu 18.04
Why I get this error, how can I fix it?
Could not add requested charm. Server responded with: cannot retrieve charm "cs:trusty/docker-8": cannot get archive: Get https://api.jujucharms.com/charmstore/v5/trusty/docker-8/archive: x509: certificate signed by unknown authority

A: I found the solution:
All my servers are behind proxy, And I needed to add all Proxy related certificate to that specific node which I ma trying to deploy charm, using this command:
Obtain the certificate(s) in Base64 encoded X.509 format.

    1. Copy them to /usr/local/share/ca-certificates

    2. If the extension is not .crt rename the files.

    3. sudo update-ca-certificates


text:
Q: Estimates with $L^n$ norm this is my question:
Show that $\epsilon ||f||_{L^n(\Omega')}\leq \epsilon^{\frac{x}{n}}$, where $x$ is a positive number, using these two facts:

*

*$\int_{\Omega}|f|^x\leq C $

*$|f|\le\dfrac{C}{\epsilon}$  in  $\Omega'$
with $\Omega'$ subset of $\Omega$.
I think that the trick is something like Holder inequality, but i can't state something useful.


text:
Q: Adding post limit on certain page using PHP I am currently using the following code in a new page template from Wordpress to add specific category posts to the home page:
<?php global $post; // required
$args = array('category' => 3); // include category 3
$custom_posts = get_posts($args);
foreach($custom_posts as $post) : setup_postdata($post);

// put here what you want to appear for each post like:
//the title:

the_title('
', '
');

// an excerpt:
the_excerpt();

//and so on...

endforeach;
?>

All work fine however I need to limit the amount of posts showing, they already appear on the main news page, I just need to show the latest 2 or 3 on home page.

A: <?php global $post; // required
$args = array('category' => 3, 'numberposts' => 5); // include category 3 and limit to 5 posts
$custom_posts = get_posts($args);
foreach($custom_posts as $post) : setup_postdata($post);

// put here what you want to appear for each post like:
//the title:

the_title('
', '
');

// an excerpt:
the_excerpt();

//and so on...

endforeach;
?>


text:
Q: Python Unit Testing a loop function This is a followup question from 1
I need to test the function with two given cases in a loop. However, based on the printed results, it seems like only the first iteration is checked? Is this related to runner.run(unittest.makeSuite(MyTestCase))?
import unittest
from StringIO import StringIO
import rice_output

class MyTestCase(unittest.TestCase):
    def setUp(self):
        #####Pre-defined inputs########
        self.dsed_in=[1,2]
        self.a_in=[2,3]
        self.pb_in=[3,4]

        #####Pre-defined outputs########
        self.msed_out=[6,24]

        #####TestCase run variables########
        self.tot_iter=len(self.a_in)

def testMsed(self):
    for i in range(self.tot_iter):
        print i
        fun = rice_output.msed(self.dsed_in[i],self.a_in[i],self.pb_in[i])
        value = self.msed_out[i]
        testFailureMessage = "Test of function name: %s iteration: %i expected: %i != calculated: %i" % ("msed",i,value,fun)
        return self.assertEqual(round(fun,3),round(self.msed_out[i],3),testFailureMessage)

from pprint import pprint
stream = StringIO()
runner = unittest.TextTestRunner(stream=stream)
result = runner.run(unittest.makeSuite(MyTestCase))
print 'Tests run ', result.testsRun
print 'Errors ', result.errors

Here is he output:
0
Tests run  1
Errors  []
[]
Test output
testMsed (__main__.MyTestCase) ... ok

----------------------------------------------------------------------
Ran 1 test in 0.000s

OK

Any suggestions? Thanks!

A: Remove the return statement
def testMsed(self):
  for i in range(self.tot_iter):
    print i
    fun = rice_output.msed(self.dsed_in[i],self.a_in[i],self.pb_in[i])
    value = self.msed_out[i]
    testFailureMessage = "Test of function name: %s iteration: %i expected: %i != calculated: %i" % ("msed",i,value,fun)
    self.assertEqual(round(fun,3),round(self.msed_out[i],3),testFailureMessage)


text:
Q: Construction in Euclidean Geometry I came across the following problem in my Euclidean Geometry text:
Construct a triangle given the ratio of an altitude to the base, the vertical angle (the angle opposite the base), and a median to a lateral side.
I started with the given vertical angle at a point B and tried to first construct a similar triangle to the sought for one, by choosing an arbitrary ratio m:n for base and altitude. I also choose B as the center of similitude. However I can't seem to figure out how to incorporate the median. Any help would be appreciated!


text:
Q: Leanest way to prevent scripted abuse of a web app? I am running flask/memcached and am looking for a lean/efficient method to prevent automated scripts from slamming me with requests and/or submitting new posts too quickly.
I had the thought of including a 'last_action' time in the session cookie and checking against it each request but no matter what time I set, the script could be set up to delay that long.
I also thought to grab the IP and if too many requests from it are made in x amount of time, deny anymore for so long, but this would require something like redis to run efficiently, which I'd like to avoid having to pay for.
I prefer a cookie-based solution unless something like redis can prove it's worth.
What are the 'industry standards' for dealing with these kinds of situations? What methods come with the least amount of cost/performance trade-offs?

A: There is no way to achieve this with cookies, since a malicious script can just silently drop your cookie. Since you have to support the case where a user first visits (meaning without any cookies set), there is no way to distinguish between a genuine new user and a malicious script by only considering state stored on the client.
You will need to keep track of your users on the server-side to achieve your goals. This can be as simple as an IP-based filter that prevents fast posting by the same IP.

A: You should sit down and decide what exactly your "core" problems in the scenario of your app are, and who your likely users will be.  That will help you guide the right solution.
In my experience, there are a lot of different problems and solutions in this subject - and none are a "one size fits all"

*

*If you have a problem with Anonymous users , you can try to migrate as much of the functionality behind an 'account wall' as possible.

*If you can't use an account wall, then you'll be better off with some IP
based tracking, along with some other headers/javascript stuff.  Going by IP alone can be a disaster because of corporate proxies , home routers, etc.  You'll run the risk of too many false positives.  If you add in browser info, unsavory users can still fake it - but you'll penalize fewer real users.

*You might want an account wall to only serve as a way to enforce a cookie , or it might plug into the idea of having a site identity where experience earns privilege

*You might want an account that can map to another trusted site's account.  For example, I generally trust a 3rd party account binding against Facebook - who are pretty decent at dealing with fake accounts.  I don't trust a 3rd party account binding against Twitter - which is largely spam.

*You might only require site "registration" to need solving a captcha , or something else mildly inconvenient to weed out most unsavory visits. If the reward for bad behavior is high enough though, you won't solve anything.

I could talk about this all day.  From my perspective, you have to solve the business logic and ux concepts first - and then a tech solution is much easier.

A: An extremely simple method that I have used before is to have an additional input in the registration form that is hidden using CSS (i.e. has display:none). Most form bots will fill this field in whereas humans will not (because it is not visible). In your server-side code you can then just reject any POST with the input populated.


text:
Q: Downloading a file from S3 into a Zapier Task I would like to download a file from S3 in Zapier and use it (as file exists but not shown) in the rest of a Zap.  Strangely the S3 integration doesnt offer this (although you can do this in Box, Drive etc).
I guess we will need to use Code by Zapier and I have this basic JS - but I think I need to specify region and not sure how to link the output into Zap?
var AWS = require('aws-sdk');
AWS.config.update(
  {
    accessKeyId: ".. your key ..",
    secretAccessKey: ".. your secret key ..",
  }
);
var s3 = new AWS.S3();
s3.getObject(
  { Bucket: "my-bucket", Key: "my-picture.jpg" },
  function (error, data) {
    if (error != null) {
      alert("Failed to retrieve an object: " + error);
    } else {
      alert("Loaded " + data.ContentLength + " bytes");
      // do something with data.Body
    }
  }
);
output = need to put my file here!!

I'd appreciate any pointers - I am surprised this has not been asked before - I hope it doesnt mean that I have missed something very obvious!

A: Here is example to get json document from s3
var AWS = require('aws-sdk');
const s3 = new AWS.S3({
  accessKeyId: ".. your key ..",
  secretAccessKey: ".. your secret key ..",
  region: "region",
});
var s3params = {
  Bucket: "bucket",
  Key: "key",
};
s3.getObject(s3params, function (err, data) {
  if (err) {
    console.error(err.message);
  } else {
    let jsonString = data.Body.toString();
    let result = JSON.parse(jsonString);
    return result;
  }
});


text:
Q: asp loop hangs web site while running I have a loop on page to update an access database that takes 15-20 seconds to complete. I only run it once a month at most but I noticed that every time I run it the web site (IIS 6) simply stops serving pages.
After the loop ends, pages begin opening again.
Here's my code:
For each Email in Emails
    if Trim(Email) <> "" then
        ' execute the update
        Set MM_editCmd = Server.CreateObject("ADODB.Command")
        MM_editCmd.ActiveConnection = MM_Customers_STRING
        MM_editCmd.CommandText = "UPDATE Customers SET MailingListUpdates=False WHERE Email='" & Trim(Email) & "'"
        MM_editCmd.Execute
        MM_editCmd.ActiveConnection.Close
        Response.Write "Email address " & Email & " successfully removed from the mailing list.
"
    end if
Next

Is there anything I can do to avoid this?
Emails on the last update was around 700 records.

A: You are probably using up all the available connections in the connection pool. Try this instead:
Set MM_editCmd = Server.CreateObject("ADODB.Command")
MM_editCmd.ActiveConnection = MM_Customers_STRING
For each Email in Emails
    if Trim(Email) <> "" then
        ' execute the update
        MM_editCmd.CommandText = "UPDATE Customers SET MailingListUpdates=False WHERE Email='" & Trim(Email) & "'"
        MM_editCmd.Execute
        Response.Write "Email address " & Email & " successfully removed from the mailing list.
"
    end if
Next
MM_editCmd.ActiveConnection.Close

Also as a more long term thing try upgrading to SQL Server Express

A: MM_ the bane ASP programming.  Create the command object and opening and closing a connection on every iteration can't be good for performance.  Concatenating the string to create a new command string each time isn't good for security either.
Try this:-
Dim con : Set con = Server.CreateObject("ADODB.Connection")
Dim cmd : Set cmd = Server.CreateObject("ADODB.Command")
con.Open MM_Customers_STRING
Set cmd.ActiveConnection = con
cmd.CommandType = 1 // adCmdText (note SO not good at detecting VB comment)
cmd.CommandText = "UPDATE Customers SET MailingListUpdates=False WHERE Email=?"
Dim param : Set param = cmd.CreateParameter("email", 200, 1, 50) // adVarChar, adParamInput, size: 50
cmd.Parameters.Append param
Dim Email
For Each Email in Emails
    Email = Trim(Email)
    If Email <> "" Then
        param.value = Email
        cmd.Execute
    End If
Next
con.Close

An index on the Email field would be nice.

A: I suggest to take a creation/deletion of Command and setup out of the loop and use bind variables (via Parameters collection).

A: What is the source for the "Emails" collection?  If it is from your database, you'd get much better performance by leaving it there and joining against it rather than retrieving and iterating programmatically.  An additional improvement would be to only perform the update if it is necessary - i.e., the MailingListUpdates attribute is not already false.


text:
Q: PhoneGap open file in native app. Build via build.phonegap.com At first:
YES, there are many solutions in StackOverflow, but non of them works in my case.

*

*I got application built in SmartGWT.mobile

*I attached config files and all needed files to this build to prepare it for PhoneGap

*Application is build via build.phonegap.com site.

*It works perfectly fine on Android 4.1.1

I want to:

*

*Download file to local filesystem it is an PDF file - It is working fine using:
var fileTransfer = new FileTransfer();
fileTransfer.download(.....

*Open PDF in native app (for eg. Adobe Reader) whichever is installed on android for PDFs - it is not working:
I tried:
(1)
cordova.exec("ChildBrowserCommand.showWebPage", encodeURI(theFile.toURL()) );

(2)
window.plugins.childBrowser.showWebPage(encodeURI(theFile.toURL()));

(3)
window.open(encodeURI(theFile.toURL()), '_blank', 'location=yes');

(4)
even HTML5 plugin for open PDFs by firefox
All variations with "file://" without with "./" at front and so on.
childBrowser shows only white screen, each time adds "http://" at front, window.open - the same.
I finally found something interesting like WebIntent, so i did:
    window.plugins.webintent.startActivity({
          action: window.plugins.webintent.ACTION_VIEW,
          type: "application/pdf",
          url: encodeURI(theFile.toURL().substring(7))},
          function() {},
          function() {alert('Failed to open URL via Android Intent')}
    );

but its not working due to fact that phonegap-build not attaching class file and It can not find WebIntent Class
I declare this plugin using in config.xml:
    <gap:plugin name="com.borismus.webintent.WebIntent" />

Do you know why it is not working, or what I'm doing worng ?
Maybe you know other way to open file just like that in native app, it suppose to be simple
I just want my app to download and show (in native app) the PDF for user.

A: don's FileOpener version have worked on my app cordova 3.0
phonegap local plugin add https://github.com/don/FileOpener

all the xmls, plugin, etc are then added automatically.
added fileopener.js on index.html
and then
window.plugins.fileOpener.open( path );

A: $("#page").on('pageshow', function(event, ui) {
 if(event.handled !== true)
    {
    window.requestFileSystem  = window.requestFileSystem || window.webkitRequestFileSystem;
    window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail);
    event.handled = true;
    }
  return false;
});

function fail() {
    console.log("failed to get filesystem");
}

function gotFS(fileSystem) {
   console.log("got filesystem");

   // save the file system for later access
   console.log(fileSystem.root.fullPath);
   window.rootFS = fileSystem.root;
    downloadImage(url, fileName);
}

function downloadImage(url, fileName){
   var ft = new FileTransfer();
   ft.download(
    url,
    window.rootFS.fullPath + "/" + fileName,
    function(entry) {
        console.log("download complete: " + entry.fullPath);
    },
    function(error) {
            console.log("download error" + error.code);
    }
 );
}


text:
Q: How do I override the base price against Custom option Pricing? Hi this was a question from magento forum on their site.. However I am looking for the same thing for a while, could any answer this ?
*I need the exact area in which Magento adds Base price and Custom option price *

I have been looking across these forums so many apologies if this is a
  duplicate, but I am having a lot of trouble with the custom option
  pricing on front-end not being absolute, but adding itself onto the
  base price of the product.
I have been looking at a few modules, which I am happy to purchase, if
  easy to implement, but there are quite a few that are going around.
Attached are some images if anyone has a solution.
The base price on the product (is a product with many different custom
  options, could be size options also) is £7.32, which is fine as the
  page states 'From £7.32'
However, there are a few options selectable, which rather than show
  (+) and ultimately add to the base price, should show the actual price
  and not onto of the base price.
So Rhynogrip 70 x 198 price is actually £48.96, however when selected
  it adds this to the £7.32, rather than replace it. The attached all
  show this.
If anyone could help that would be great!
Thanks in advance.

A: I recommend you set the price of Rhinogrip 70x198 to 48.96 - 7.32 because that is what MAgento expects.


text:
Q: QProcess gpg2 error in windows I need to encrypt some text with gpg using Qt. QCA is no choice.
My function is working in Linux but in Windows I get exitCode 2.
Executing the gpg2.exe with the same arguments on the commandline is working like expected.
QString PGPProcess::encrypt(QString toAddress, QString message)
{

    this->start(QStringList() << "--trust-model always" << "-a" << "-e" << "-r " + toAddress);
    this->waitForStarted(PROCESS_WAIT);
    this->write(message.toUtf8());
    this->waitForBytesWritten(PROCESS_WAIT);
    this->closeWriteChannel();
    this->waitForFinished(PROCESS_WAIT);

    if(this->exitCode()) {
        qDebug() << this->exitCode();
        return message;
    } else {
        return this->readAllStandardOutput();
    }

}

I think it hast to do with closeWriteChannel(). Commandline has to send CRTL-D (Linux) that gpg is encrypting the written text.
In Windows CTRL-D does not do anything, there I have to press CTRL-C.
But calling terminate() on the QProcess does not work too.

A: Ok simply changing the arguments QStringList to the following does the trick ...
this->start(QStringList() << "--trust-model" << "always" << "-a" << "-e" << "-r" << toAddress);


text:
Q: How to rbind two matrix with different number of columns? How to rbind two matrix with different row numbers
I have two matrix with different number of row, when I tried to combine them, there is error report:
A <- matrix (1:4, 2)
B <- matrix (6:11, 2)
rbind(A,B)

"Error in rbind(A, B):
  number of columns of matrices must match (see arg 2)"

I want
       [,1] [,2] [,3]
 [1,]    1    3
 [2,]    2    4
 [1,]    6    8   10
 [2,]    7    9   11

A: We can  convert to data.frame and use bind_rows.  If the column names are not matching, it will fill NA by default
library(dplyr)
out <- bind_rows(as.data.frame(A),  as.data.frame(B))
as.matrix(out)

A: We can use plyr package:
plyr::rbind.fill.matrix(A, B)

 #>      1 2  3
 #> [1,] 1 3 NA
 #> [2,] 2 4 NA
 #> [3,] 6 8 10
 #> [4,] 7 9 11


text:
Q: Firebase console reads cost Does using the firebase console and clicking on different collection/documents count against my read operations quota?
I have about 2 real users and about 13 fake ones and my usage is showing 1100 reads so far today. There are only about 30 documents in the entire database!

A: Any document read from the server is going to be billed.  It doesn't matter where the read came from.  The console should be included in that.


text:
Q: How to Extract the Word Following a Symbol? I have a string that could have any sentence in it but somewhere in that string will be the @ symbol, followed by an attached word, sort of like @username you see on some sites.
so maybe the string is "hey how are you" or it's "@john hey how are you".
IF there's an "@" in the string i want to pull what comes immediately after it into its own new string.
in this instance how can i pull "john" into a different string so i could theoretically notify this person of his new message? i'm trying to play with string.contains or .replace but i'm pretty new and having a hard time.
this btw is in c# asp.net

A: You can use the Substring and IndexOf methods together to achieve this.
I hope this helps.
Thanks,
Damian

A: Here's how you do it without regex:
string s = "hi there @john how are you";

string getTag(string s)
{
    int atSign = s.IndexOf("@");

    if (atSign == -1) return "";

    // start at @, stop at sentence or phrase end
    // I'm assuming this is English, of course
    // so we leave in ' and -
    int wordEnd = s.IndexOfAny(" .,;:!?", atSign);

    if (wordEnd > -1)
        return s.Substring(atSign, wordEnd - atSign);
    else
        return s.Substring(atSign);

}

A: You should really learn regular expressions. This will work for you:
using System.Text.RegularExpressions;

var res = Regex.Match("hey @john how are you", @"@(\S+)");

if (res.Success)
{
    //john
    var name = res.Groups[1].Value;
}

Finds the first occurrence. If you want to find all you can use Regex.Matches. \S means anything else than a whitespace. This means it also make hey @john, how are you => john, and @john123 => john123 which may be wrong. Maybe [a-zA-Z] or similar would suit you better (depends on which characters the usernames is made of).  If you would give more examples, I could tune it :)
I can recommend this page:
http://www.regular-expressions.info/
and this tool where you can test your statements:
http://regexlib.com/RESilverlight.aspx

A: The best way to solve this is using Regular Expressions.  You can find a great resource here.
Using RegEx, you can search for the pattern you are after.  I always have to refer to some documentation to write one...
Here is a pattern to start with - "@(\w+)" - the @ will get matched, and then the parentheses will indicate that you want what comes after.  The "\w" means you want only word characters to match (a-z or A-Z), and the "+" indicates that there should be one or more word characters in a row.

A: RegularExpressions. Dont know C#, but the RegEx  would be
/(@[\w]+) / - Everything in the parans is captured in a special variable, or attached to RegEx object.

A: You can try Regex...
I think will be something like this
string userName = Regex.Match(yourString, "@(.+)\\s").Groups[1].Value;

A: Use this:
var r = new Regex(@"@\w+");
foreach (Match m in r.Matches(stringToSearch))
    DoSomething(m.Value);

DoSomething(string foundName) is a function that handles name (found after @).
This will find all @names in stringToSearch


text:
Q: How to handle bad strings as pseudo booleans in Kotlin? Let's say I'm using gson to serialize and deserialize json to and from a Kotlin data class. One of the values is a string set as "yes" or "no" and the other is a string set as "on" or "off". Yes, this is terrible terrible practice, but let's presume it can't be changed.
Whats the best way to handle this in Kotlin?
APIdata.json
{
   "value" : "On",
   "anotherValue" : "Yes"
}

APIdata.kt
data class APIdata (val value : String, val anotherValue: String)

I want to be able to treat them both as Booleans for the purposes of getting and setting.

A: You can use a mapping function and a corresponding constructor, also you can define get methods:
data class APIdata(val value: String, val anotherValue: String) {
    fun mapToBoolean(string: String) =
        when (string.toLowerCase()) {
            "yes" -> true
            "on"  -> true
            else  -> false
        }

    constructor(value: Boolean, anotherValue: Boolean) :
        this(if (value) "on" else "off", if (anotherValue) "yes" else "no")

    fun getValue(): Boolean {
        return mapToBoolean(value)
    }

    fun getAnotherValue(): Boolean {
        return mapToBoolean(anotherValue)
    }
}

In this case using a data class can be misleading, because the Kotlin compiler generates hashCode and equals assuming valueand anotherValue are String rather than Boolean. It is better design to implement them yourself like this:
class APIdata( val value: String, private val anotherValue: String) {
    fun mapToBoolean(string: String) =
        when (string.toLowerCase()) {
            "yes" -> true
            "on"  -> true
            else  -> false
        }

    constructor(value: Boolean, anotherValue: Boolean) :
        this(if (value) "on" else "off", if (anotherValue) "yes" else "no")

    fun getValue(): Boolean {
        return mapToBoolean(value)
    }

    fun getAnotherValue(): Boolean {
        return mapToBoolean(anotherValue)
    }

    override fun equals(other: Any?): Boolean {
        if (this === other) return true
        if (javaClass != other?.javaClass) return false

        other as APIdata

        if (getValue() != other.getValue()) return false
        if (getAnotherValue() != other.getAnotherValue()) return false

        return true
    }

    override fun hashCode(): Int {
        var result = getValue().hashCode()
        result = 31 * result + getAnotherValue().hashCode()
        return result
    }
}

A: You need to use a TypeAdapter.
class ApiDataTypeAdapter: TypeAdapter<APIData>() {

  override fun read(`in`: JsonReader) {
    var valOne = false
    var valTwo = false

    `in`.beginObject()
    while (`in`.hasNext()) {
        when(`in`.nextName()) {
          "val" -> valOne = `in`.nextString() == "On"
          "anotherVal" -> valTwo = `in`.nextString() == "Yes"
    }
    `in`.endObject()

    return APIData(valOne, valTwo)
  }

  override fun write(out: JsonWriter, apiData: APIData)
  {
    out.beginObject()
    out.name("val").value(if (apiData.`val`) "On" else "Off")
    out.name("anotherVal").value(if (apiData.anotherVal) "Yes" else "No")
    out.endObject()
  }
}

And then register it for your APIData class:
val builder = GsonBuilder()
builder.registerTypeAdapter(APIData::class.java, ApiDataTypeAdapter().nullSafe())
val gson = builder.create()


text:
Q: is differ between distributive lattice vs semi-lattice on Turing Degrees We know a Posed Closed under suprema but not necessarily under infima is an upper semi-lattice.
We now r.e set forms a distributive lattice.
But my question is why following statement is hold? I think the Turing degree is distributive lattice. I not need a formal proof, just some hint is enough.

Turing Degrees $(D, \leq)$ under the partial order induced by Turing
  Reducibility $\leq_T$ form only upper semi-lattice.

A: This is a standard fact given as Corollary 4.4 on page 100 of Soare's book: there exists a pair of degrees with no greatest lower bound. All the details are provided there.


text:
Q: Project Naming Convention I am in a debate about what a best practice would be for naming projects within a .sln on our team. We are working in Visual Studio and debating about what the project naming and placement of classes should be. Here are the two arguments:

*

*There should be a "Common" project which will contain two folders: "Contracts" and "Model". Within "Contracts" folder will be the interfaces and of course within "Model" folder will be the data model. The advantage to this is that there will only be one .dll published which will have both the model and contracts within it.

*There should be a "Model" project and a "Contracts" project. "Model" project should contain the data model and the "Contracts" project will contain the interfaces. The advantage here is in the naming, you know what will be in each .dll.

So simplified the question really is, is it better to have two separate projects or one project for the interfaces and model?

A: I'd separate them into separate projects. Your solution will likely include more DLLs, and you'll want to be able to access the interfaces from any of them. If you dump them into the same DLL with your Models, you run a higher risk of a circular dependency down the road.

A: It depends, I would keep projects on RE USABILITY basis. Means each project specific to content oriented.
Also note even after keeping separate you can merge them in single dll. So you objective of naming will also be achieved.


text:
Q: What is StubRoutines::jbyte_disjoint_arraycopy I'm measuring some single-threaded method invocation (written in Scala) and wanted to analyze the benchmark. Here is how it looks like (implementation details omitted)
@State(Scope.Benchmark)
class TheBenchmarks {

    var data: Array[Byte] = _
    @Param(Array("1024", "2048", "4096", "8192"))
    var chunkSize: Int = _

    @Setup
    def setup(): Unit = {
        data = //get the data
    }

    @Benchmark
    @OutputTimeUnit(TimeUnit.MICROSECONDS)
    @BenchmarkMode(Array(Mode.AverageTime))
    def takeFirstAvroRecord(bh: Blackhole): Unit = {
      val fr = //do computation with data and chunk size
      bh.consume(fr)
    }

}

Okay, I got some result and wanted to understand it, but the output of the  -prof perfasm is a bit unclear to me. First of all:
....[Hottest Regions]...............................................................................
 44.20%   40.50%        runtime stub  StubRoutines::jbyte_disjoint_arraycopy (205 bytes)
  6.78%    1.62%         C2, level 4  cats.data.IndexedStateT$$Lambda$21::apply, version 1242 (967 bytes)
  4.39%    0.79%         C2, level 4  my.pack.age.Mclass::cut0, version 1323 (299 bytes)

and
....[Hottest Methods (after inlining)]..............................................................
 44.20%   40.50%        runtime stub  StubRoutines::jbyte_disjoint_arraycopy
  8.40%    3.93%         C2, level 4  cats.data.IndexedStateT$$Lambda$21::apply, version 1242
  5.76%    2.67%         C2, level 4  my.pack.age.Mclass::cut0, version 1323

I found some about jbyte_disjoint_arraycopy. It is declared as follows here as follows.
StubRoutines::_jbyte_disjoint_arraycopy  = generate_disjoint_byte_copy(false, &entry,
                                                                           "jbyte_disjoint_arraycopy");

Judging by the source of the generate_disjoint_byte_copy method it looks like an assembly code generation thing... I could guess that it is some intrinsic array copy for x86...
Question: Can you please give some explanation about the StubRoutines and what may cause it to be the hottest region?

A: You guessed right. <type>_disjoint_arraycopy stubs are functions generated in run time specifically for speeding up System.arraycopy calls.
When JVM starts, it produces optimized machine code for certain routines using currently available CPU features. E.g. if CPU supports AVX2, generated arraycopy stubs will make use of AVX2 instructions.
System.arraycopy is HotSpot intrinsic method. When compiled by C2, an invocation of System.arraycopy performs neccessary checks and then calls one of the generated arraycopy stub routines.
If StubRoutines::jbyte_disjoint_arraycopy is the hottest region, it basically means that your benchmark spends most of the time inside System.arraycopy dealing with byte[] arrays. You may try async-profiler to see where this arraycopy is called from.


text:
Q: Request counter for individual all the web service api I have created web services for my project, using rest and some of using only servlet.
I want to create request counter for individual all the web service api to analyse individual request ratio per hour,per day and many more.
I don't want to put counter for every api. Can I achieve it by using Servlet Listner or Servlet Filter? yes then how??? Small demo would be great if possible.
Note : I know that I can analyse most of the details from access log.

A: Simplest solution would be to create and register a Filter.
In the web.xml you can use wildcards (*) to map it to any urls or just the urls of the Servlets you want to count, so one Filter could do the counting for all your Servlets including the custom ones you create or any shipped Servlets that come from 3rd party libraries (because they are also created and mapped in your web.xml to the URL patterns of your choice).
In Filters you can also provide additional filters whether you want to count a call based in the url, parameters etc.
Serving all requests that match the URL patterns of any registered Filters starts and ends in the code of the Filters, so in a Filter you also have the possibility to do the counting before or after serving the requests. You also have the possibility to count based on the response status code etc.
So in a Filter you can do an advanced counting like counting all requests, their average execution time, error rate, average received and sent bytes etc. also broken down to Servlets.


text:
Q: Starting sound on button click in audio tag in React doesn't functioning I have main component App, a drum with 9 buttons with letters, on mouse click on each button must be started different sound file.
With onClick event and function soundDetectionHandler I am detecting which letter was pressed. When detected, I am setting the state  in currentKey variable to that letter/object with keyCode, keyTrigger, id, url. In child component Keypress for each letter I have
div in which is embedded audio tag, with no showed own controls. In it there is a button which is onClick calling a audioActivationHandler function in main component, which should start playing of sound file(url) based on detection of class name of audio tag.
document.getElementsByClassName("player").play();
Unfortunately it's not working on mouse click, can somebody check, and if this is not the best solution, has anybody to suggest a better solution.
Here it is the main component:
import React, { Component } from 'react';
import './App.css';
import Keypress from '.././components/Keypress/Keypress';

class App extends Component {
    constructor(props) {
        super(props)
        this.state = {
            currentKey: [],
                bankTwo : [{
                keyCode: 81,
                keyTrigger: 'Q',
                id: 'Chord-1',
                url: 'https://s3.amazonaws.com/freecodecamp/drums/Chord_1.mp3'
            }, {
                keyCode: 87,
                keyTrigger: 'W',
                id: 'Chord-2',
                url: 'https://s3.amazonaws.com/freecodecamp/drums/Chord_2.mp3'
            }, {
                keyCode: 69,
                keyTrigger: 'E',
                id: 'Chord-3',
                url: 'https://s3.amazonaws.com/freecodecamp/drums/Chord_3.mp3'
            }, {
                keyCode: 65,
                keyTrigger: 'A',
                id: 'Shaker',
                url: 'https://s3.amazonaws.com/freecodecamp/drums/Give_us_a_light.mp3'
            }, {
                keyCode: 83,
                keyTrigger: 'S',
                id: 'Open-HH',
                url: 'https://s3.amazonaws.com/freecodecamp/drums/Dry_Ohh.mp3'
            }, {
                keyCode: 68,
                keyTrigger: 'D',
                id: 'Closed-HH',
                url: 'https://s3.amazonaws.com/freecodecamp/drums/Bld_H1.mp3'
            }, {
                keyCode: 90,
                keyTrigger: 'Z',
                id: 'Punchy-Kick',
                url: 'https://s3.amazonaws.com/freecodecamp/drums/punchy_kick_1.mp3'
            }, {
                keyCode: 88,
                keyTrigger: 'X',
                id: 'Side-Stick',
                url: 'https://s3.amazonaws.com/freecodecamp/drums/side_stick_1.mp3'
            }, {
                keyCode: 67,
                keyTrigger: 'C',
                id: 'Snare',
                url: 'https://s3.amazonaws.com/freecodecamp/drums/Brk_Snr.mp3'
            }],
            isChecked: false
        }
    }

    soundDetectionHandler = (event) => {
        let currentKey = this.state.bankTwo.filter((el, key) => {
            return el.id === event.target.id
        })

        this.setState ({
            currentKey: currentKey
        })
    }

    audioActivationHandler = () => {
        document.getElementsByClassName("player").play();

    }

    checkBoxHandler = () => {
        this.setState({
            isChecked: !this.state.isChecked
        })
    }

    render () {
        const drum = this.state.bankTwo.map((keypress, key) => {
            return <Keypress
                key={keypress.keyCode}
                keypress={keypress}
                soundDetection={this.soundDetectionHandler}
                activated={this.audioActivationHandler}
            />
            }
        )
        return (

                                {drum}

                                    <input type="checkbox"
                                        onChange={this.toggleChange}
                                    />

        )
    }
}
export default App;

Here it is a child stateless component Keypress:
import React from 'react';

const keypress = (props) => {
    return (

        {props.keypress.keyTrigger}
            <audio className="player" src={props.keypress.url}>
                <button onClick={props.activated}>Play</button>
            </audio>

    );
}
export default keypress;

A: This is what you're after. I refactored your code quite a bit.
Making this work in react think was a bit mind-bending I must confess.
There are a few comments. Hope this helps :)
app.css:
.player {
  width:100px;
  height: 100px;
  border: 1px solid black;
  color: black;
  display: flex;
  align-items: center;
  justify-content:center;
  cursor: pointer;
  box-sizing: border-box;
}

player.js:
import React from 'react'
import './app.css'

export default class Player extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      active: false,
    }
    this.audio = React.createRef()
  }
  playAudio = () => {
    this.audio.current.play()
  }
  toggleActiveState = () => {
    this.setState({
      active: !this.state.active,
    })
  }
  render() {
    return (

        <audio
          ref={this.audio}
          src={this.props.url}
          onEnded={this.toggleActiveState}
        />
        {this.props.keyTrigger}

    )
  }
}

index.js:
import React from 'react'
import Player from './player'

const page = {
  width: '100vw',
  height: '100vh',
  display: 'flex',
  alignItems: 'center',
  justifyContent: 'center',
}
const keyboard = {
  width: '300px',
  height: '300px',
  display: 'flex',
  flexWrap: 'wrap',
  alignItems: 'center',
  justifyContent: 'center',
  border: '1px solid black',
}

export default class App extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      currentKey: [],
      bankTwo: [
        {
          keyCode: 81,
          keyTrigger: 'Q',
          id: 'Chord-1',
          url: 'https://s3.amazonaws.com/freecodecamp/drums/Chord_1.mp3',
        },
        {
          keyCode: 87,
          keyTrigger: 'W',
          id: 'Chord-2',
          url: 'https://s3.amazonaws.com/freecodecamp/drums/Chord_2.mp3',
        },
        {
          keyCode: 69,
          keyTrigger: 'E',
          id: 'Chord-3',
          url: 'https://s3.amazonaws.com/freecodecamp/drums/Chord_3.mp3',
        },
        {
          keyCode: 65,
          keyTrigger: 'A',
          id: 'Shaker',
          url:
            'https://s3.amazonaws.com/freecodecamp/drums/Give_us_a_light.mp3',
        },
        {
          keyCode: 83,
          keyTrigger: 'S',
          id: 'Open-HH',
          url: 'https://s3.amazonaws.com/freecodecamp/drums/Dry_Ohh.mp3',
        },
        {
          keyCode: 68,
          keyTrigger: 'D',
          id: 'Closed-HH',
          url: 'https://s3.amazonaws.com/freecodecamp/drums/Bld_H1.mp3',
        },
        {
          keyCode: 90,
          keyTrigger: 'Z',
          id: 'Punchy-Kick',
          url: 'https://s3.amazonaws.com/freecodecamp/drums/punchy_kick_1.mp3',
        },
        {
          keyCode: 88,
          keyTrigger: 'X',
          id: 'Side-Stick',
          url: 'https://s3.amazonaws.com/freecodecamp/drums/side_stick_1.mp3',
        },
        {
          keyCode: 67,
          keyTrigger: 'C',
          id: 'Snare',
          url: 'https://s3.amazonaws.com/freecodecamp/drums/Brk_Snr.mp3',
        },
      ],
      isChecked: false,
      bgColor: 'white',
    }
    this.handleKeyPress = this.handleKeyPress.bind(this)

    this.Q = React.createRef()
    this.W = React.createRef()
    this.E = React.createRef()
    this.A = React.createRef()
    this.D = React.createRef()
    this.S = React.createRef()
    this.Z = React.createRef()
    this.X = React.createRef()
    this.C = React.createRef()
  }

  componentDidMount() {
    document.addEventListener('keydown', this.handleKeyPress)
  }

  componentWillUnmount() {
    document.removeEventListener('keydown', this.handleKeyPress)
  }

  playAudioOnClick = e => {
    e.target.children[0].play()
    this[e.target.id].current.toggleActiveState()

  }

  handleKeyPress = e => {
    if (this.state.isChecked) {
      // in any case uppercase
      let which = e.key.toUpperCase()

      // check if the pressed key is defined as a keyTrigger in the state else do nothing
      if (
        this.state.bankTwo.some(key => {
          return key.keyTrigger === which
        })
      ) {
        // trigger functions in child
        this[which].current.playAudio()
        this[which].current.toggleActiveState()
      }
    }
  }
  handleCheck = () => {
    this.setState({
      isChecked: !this.state.isChecked,
    })
  }

  render() {
    const drum = this.state.bankTwo.map(player => {
      return (
        <Player
          id={player.keyTrigger}
          ref={this[player.keyTrigger]}
          key={player.keyCode}
          keyTrigger={player.keyTrigger}
          url={player.url}
          clicked={this.playAudioOnClick}
        />
      )
    })

    return (

        {drum}

          play with keyboard
          <input type="checkbox" onChange={this.handleCheck} />

    )
  }
}

It works generally but playing too fast will leave some fields highlighted even if not active. I would love to see a better solution. For a real instrument though I would suggest using the Web Audio API.


text:
Q: Why Enums doesn't return real numbers? Enums are something I really love to implement in my code, but I want to know why Enums are limited to byte, sbyte, short, ushort, int, uint, long, or ulong as return type.
Lets say we have a scenario, where we need to get a discount according to the discount type,
public enum DiscountType : float
{
    Student = 10.5,
    SeniorCitizen = 15.5,
    BeautifulWomen = 25.5,
    SmartGuy = 25.5
}

I know there are several ways to implement this requirement (example using Structs). But I'll be really interested to do with Enums, is it Possible ? If not Why Enums are Restricted ?


text:
Q: boost units parsing string stream The boost units library provides useful compile time "units of measure" type checking. It also provides stream io operations to serialize units. However, I am struggling with the string parsing bit.
For example, the following lines:
boost::units::quantity<boost::units::si::force> f(2.0 * boost::units::si::newton);
std::cout << "Force = " << f << std::endl;

produce the output:
Force = 2.0 N

Can someone point me to an example that parses these standard serialization back to boost units?
// f.parse_string("2.0 N");  or using stream operators??

Thanks!

A: It's not directly supported by the library.
There's an example that could give some inspiration: http://www.boost.org/doc/libs/1_56_0/doc/html/boost_units/Examples.html#boost_units.Examples.RuntimeUnits

This example shows how to implement an interface that allow different
  units at runtime while still maintaining type safety for internal
  calculations.
namespace {

using namespace boost::units;
using imperial::foot_base_unit;

std::map<std::string, quantity<si::length> > known_units;

}

quantity<si::length> calculate(const quantity<si::length>& t)
{
    return(boost::units::hypot(t, 2.0 * si::meters));
}

int main()
{
    known_units["meter"] = 1.0 * si::meters;
    known_units["centimeter"] = .01 * si::meters;
    known_units["foot"] =
        conversion_factor(foot_base_unit::unit_type(), si::meter) * si::meter;

    std::string output_type("meter");
    std::string input;

    while((std::cout << "> ") && (std::cin >> input))
    {
        if(!input.empty() && input[0] == '#')
        {
            std::getline(std::cin, input);
        }
        else if(input == "exit")
        {
            break;
        }
        else if(input == "help")
        {
            std::cout << "type \"exit\" to exit\n"
                "type \"return 'unit'\" to set the return units\n"
                "type \"'number' 'unit'\" to do a simple calculation"
                << std::endl;
        }
        else if(input == "return")
        {
            if(std::cin >> input)
            {
                if(known_units.find(input) != known_units.end())
                {
                    output_type = input;
                    std::cout << "Done." << std::endl;
                }
                else
                {
                    std::cout << "Unknown unit \"" << input << "\""
                         << std::endl;
                }
            }
            else
            {
                break;
            }
        }
        else
        {
            try
            {
                double value = boost::lexical_cast<double>(input);

                if(std::cin >> input)
                {
                    if(known_units.find(input) != known_units.end())
                    {
                        std::cout << static_cast<double>(
                            calculate(value * known_units[input]) /
                            known_units[output_type])
                            << ' ' << output_type << std::endl;
                    }
                    else
                    {
                        std::cout << "Unknown unit \"" << input << "\""
                            << std::endl;
                    }
                }
                else
                {
                    break;
                }
            }
            catch(...)
            {
                std::cout << "Input error" << std::endl;
            }
        }
    }
}


text:
Q: Modify Sign Up Path Devise I want to redirect a user to a specific page based on where they sign up within my application. For example, if you sign up from /users/sign_up you'll be directed to the homepage, but if you sign up from a sign up form from /users/1 then I want to redirect you back to that user's profile after you sign up. Is this possible with Devise?

A: Try to do as bellow :
class ApplicationController < ActionController::Base
  before_filter :remember_my_last_path

  def after_sign_up_path_for resource
    if cookies[:last_path].blank?
      super
    else
      cookies[:last_path]
    end
  end

  private
  def remember_my_last_path
    cookies[:last_path] = request.fullpath
  end

end

In this way you set hash value last_path to your cookies and call this in every controller. When you click on register, you call devise method after_sign_up method which you overrided,  and then you send user to specific path or to default path .
Hope this will help you  .


text:
Q: SmartGit - Select all files across multiple commits I'm looking for a way in SmartGit to select all files across multiple commits. In essence, I need a list of every file that has changed between commit A and commit C, including the files from commit B. I was also looking for a way to copy the relative file path of every changed file, but the file view only allows the option to select the relative file path when only a single file is selected. As soon as I select more than one file, my ability to copy their file paths disappears.
Any ideas? Thanks!

A: Select the commits A and C in log window. In the Files list you can see all files. Then press Ctrl-C.


text:
Q: Reading integers from a file and store it in a 2D vector I've a problem in reading from a file and saving back in a 2D vector. This is the function that write on the file:
void create_input (int num_frames, int height, int width)
{
    ofstream GridFlow;

    GridFlow.open ("GridDB");

    for (int i = 0; i < num_frames; i++)
    {
        for (int j = 0; j < height; j++)
        {
            for (int k = 0; k < width; k++)
            {
                GridFlow << setw(5);
                GridFlow << rand() % 256 << endl;
            }
        }
    }

    GridFlow.close();
}

That simply writes a random number for each line (height * width * num_frames) number of times. Like this:
    3
   74
  160
   78
   15
   30
  127
   64
  178
   15
  107

What I want to do is to read back from the file and save different chunks of the file (width * height) in different frames. I've tried to do this but the program blocks without any error:
vector<Frame> movie;
movie.resize(num_frames);

for (int i = 0; i < num_frames; i++)
{
    Frame frame;

    int offset = i*width*height*6;

    vector<vector<int>>tmp_grid(height, vector<int>(width, 0));

    ifstream GridFlow;
    GridFlow.open ("GridDB");
    GridFlow.seekg(offset, GridFlow.beg);

    for (int h = 0; h < height; h++)
    {
        for (int g = 0; g < width; g++)
        {
            int value;

            GridFlow >> value;

            tmp_grid[h][g] = value;
        }
    }

    frame.grid = tmp_grid;
    movie[i] = frame;
}

I've used an offset that each time is multiplied by 6 (number of bytes * line) to start reading, the structure Frame is only a 2D vector to store the values. I've to do this with the offset because the next step will be doing this multi threading, each thread knowing the number of the frame should compute the right offset to start reading and storing.

A: Suppose the file is like this:
1, 2, 3, 4, 5,
6, 7, 8, 9, 10,
11, 12, 13, 14, 15,

Here's one approach on how you could read the file into a vector and output it to another file:
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include <sstream>

int main()
{
    using vvint = std::vector<std::vector<int>>;
    std::ifstream file{ "file.txt" };
    vvint vec;

    std::string line;
    while (std::getline(file, line)) {
        std::stringstream ss(line);
        std::string str_num;
        std::vector<int> temp;
        while (std::getline(ss, str_num, ',')) {
            temp.emplace_back(std::stoi(str_num));
        }
            vec.emplace_back(temp);
    }

    std::ofstream out_file{ "output.txt" };
    for (const auto& i : vec) {
        for (const auto& j : i) {
            out_file << j << ", ";
        }
        out_file << '\n';
    }
}


text:
Q: The maximum number of some elements in the finite field. Consider the finite field $\mathbb{F}_{p^q}$ for some $p$ and $q$ where $p$ is a prime number. Suppose that $r$ in $\mathbb{F}_{p^q}$ has multiplicative order $n$. Consider the set ${\bf L}=\{0,1,r,r^2,\cdots ,r^{n-1}\}$.
Let the elements of ${\bf R}=\{a_1,a_2,,\cdots ,a_t\}$ in $\mathbb{F}_{p^q}$ for some $t$, satisfy the following condition:

For any $1\leq i,j\leq t$, $i \neq j$, we have $a_i\, a_j^{-1}$ is not an element of the set $\bf L$ and also $a_i's\not \in {\bf L}$.

Example: Suppose that  $\mathbb{F}_{2^4}$ is constructed from the primitive polynomial ${\bf f}=x^4+x+1$ over $\mathbb{F}_{2}$. Let $\alpha$ be a root of  $\bf f$. It is easy to check that $\alpha^5$ has multiplicative order $3$. Now consider the set ${\bf L}=\{0,1,{\alpha}^{5},{\alpha}^{10}\}$. Suppose that we want get four elements $a_i$ with $1\leq i \leq 4$ such that for any $1\leq i,j\leq 4$ we get $a_i\, a_j^{-1}$ is not an element of the set $\{0,1,{\alpha}^{5},{\alpha}^{10}\}$. By search we get:
${\bf R}=\{{\alpha}^{11},{\alpha}^{4},{\alpha}^{7},{\alpha}^{8}\}$. It can be verified that the elements of $\bf R$ satisfy the mentioned condition.
My Question: What is the maximum value for $t$ when $p$,$q$ and $r$ are fixed?
Thanks for any suggestion.

A: The keys to this question are the observations that

*

*$L^*=\{1,r,r^2,\ldots,r^{n-1}\}$ is a subgroup of the multiplicative group $\Bbb{F}_{p^q}^*$, and

*the condition $a_ia_j^{-1}\notin L^*$ is equivalent to the condition
$$a_i\notin a_jL^*.$$ By elementary group theory $a_i\notin a_j L^*$ is equivalent to $a_iL^*\neq a_j L^*$. In other words, you want the elements $a_i,i=1,2,\ldots,t$, to come from distinct cosets of $L^*$.

The other condition $a_i\notin L$ rules out the coset $L^*=1\cdot L^*$, but doesn't affect anything else. Including $0$ into $L$ doesn't affect anything either because the presence of multiplicative inverses in the condition already excluded $0$ as an element of $\mathbf{R}$.
Anyway, the number of cosets of $L^*$ is
$$
N=\frac{|\Bbb{F}_{p^q}^*|}{|L^*|}=\frac{p^q-1}n.
$$

The conditions are met if and only if $\mathbf{R}$ only contains a single element from each coset of $L^*$ in $\Bbb{F}_{p^q}^*$ other than $L^*$ itself. The maximum cardinality of $\mathbf{R}$ is thus
  $$t=N-1=\frac{p^q-1-n}n.$$

It is also easy to describe explicit sets $\mathbf{R}$ of $N-1$ elements. If $g$ is any generator of the multiplicative group $\Bbb{F}_{p^q}^*$, IOW, a primitive element, then we can use
$$
\mathbf{R}=\{g,g^2,g^3,g^4,\ldots,g^{N-1}\}.
$$
Here $g^N$ is the lowest power of $g$ contained in the subgroup $L^*$.
More generally,
we can use
$$
\mathbf{R}=\{g^s\mid s\in S\},
$$
where $S$ consists representatives of cosets of the subgroup $H=N\Bbb{Z}_{p^q-1}$ in
$\Bbb{Z}_{p^q-1}$ other than $H$ itself. In the OP's case $p^q-1=15$, $g=\alpha$, $N=5$. The set of exponents
$$S=\{4,7,8,11\}$$
works because none of them is divisible by five, and they fall into distinct residue classes modulo five.


text:
Q: Debezium with GCP Cloudsql postgresql Google finally added the support for Cloudsql postgresql logical replication/decoding support.
What I am trying to do is to use Debezium to capture the changes on the database tables, and then publish the changes in json to Gcp pubsub.
I am using Debezium server with Gcp Pubsub Sink just to verify the connection is working, but keep getting following error message org.postgresql.util.PSQLException: ERROR: could not access file "decoderbufs": No such file or directory
So seems like it defaults the plugin to decoderbufs, however I did set the database.source.plugin.name in the environment variable. According to this doc https://hub.docker.com/r/debezium/server, I am using DATABASE_SOURCE_PLUGIN_NAME. Here is the snippet of my k8s manifest
      serviceAccountName: cloudsql-client
      containers:
      - name: debezium-standalone-server-dv
        image: debezium/server:1.6
        env:
          - name: DEBEZIUM_SOURCE_CONNECTOR_CLASS
            value: io.debezium.connector.postgresql.PostgresConnector
          - name: DEBEZIUM_SOURCE_DATABASE_HOSTNAME
            value: localhost
          - name: DEBEZIUM_SOURCE_DATABASE_PORT
            value: "5432"
          - name: DEBEZIUM_SOURCE_DATABASE_USER
            value: cdc
          - name: DEBEZIUM_SOURCE_DATABASE_PASSWORD
            value: cdc
          - name: DEBEZIUM_SOURCE_DATABASE_DBNAME
            value: postgres
          - name: DEBEZIUM_SINK_TYPE
            value: pubsub
          - name: DEBEZIUM_SINK_PUBSUB_PROJECT_ID
            value: myproject
          - name: DEBEZIUM_SOURCE_OFFSET_STORAGE_FILE_FILENAME
            value: data/offsets.dat
          - name: DEBEZIUM_SOURCE_OFFSET_FLUSH_INTERVAL_MS
            value: "0"
          - name: DEBEZIUM_SOURCE_DATABASE_SERVER_NAME
            value: CDC_POC
          - name: DATABASE_SOURCE_PLUGIN_NAME
            value: wal2json

From Cloudsql, i have already turn on the logical decoding and add the REPLICATION attribute to the user, and i am able to "manually" create it by running SELECT * FROM pg_create_logical_replication_slot('test_slot', 'wal2json'); I can also see the changes by querying the replication slot SELECT * FROM pg_logical_slot_get_changes('test_slot', NULL, NULL);
so what am i missing here?

A: I am guessing it is a typo on the docker configuration documentation.
After i changed the configuration from DATABASE_SOURCE_PLUGIN_NAME to DEBEZIUM_SOURCE_PLUGIN_NAME it chooses the plugin correctly


text:
Q: SQL Unique rows Data before Output

New to SQL. In the data, I need an SQL query that will return rows in a way that if Init is not null, then return the max of Att Date by month, otherwise it should just return the date. So, the output for the above example needs to be as below.
Output

A: use group by
select ID, FORMAT(AsgnDate, 'dd/MM/yyyy', 'en-us') AsgnDate
,FORMAT(AttDate, 'dd/MM/yyyy', 'en-us') AttDate ,
case when max(INIT) is null then '' else max(INIT) end as INIT from t
group by ID, AsgnDate,AttDate

http://www.sqlfiddle.com/#!18/6a1f8/9
ID  AsgnDate    AttDate INIT
1   01/05/2018  22/05/2018  ABC
1   01/05/2018  28/06/2018
1   01/05/2018  10/07/2018
2   01/05/2018  09/05/2018  DEF
2   01/05/2018  25/07/2018


text:
Q: Custom GIF through UIImageView on Xcode not appearing? I am a beginning programmer trying to create a custom GIF using the UIImageView on iOS's Xcode. I have the code below, but it is not displaying at all. I feel like the solution is very simple and right in front of me but I've been hitting my head all day trying to figure out what's wrong with no success. I am doing almost all of this game in sprite kit and am doing this in the MyScene class (not the view controller).
    UIImageView *testGIF= [[UIImageView alloc] initWithFrame:CGRectMake(self.size.width/2,self.size.height/4,100,100)];
    NSMutableArray *GIFImageArray = [@[] mutableCopy];
    NSString *GIFImageNames[15];
    for (int i = 1; i <=15; i++) {
        UIImage *GIFImage = [UIImage imageNamed:[NSString stringWithFormat:@"DragAndMatch-%i.png", i]];
        GIFImageNames[i-1]=[NSString stringWithFormat:@"DragAndMatch-%i.png", i];
        [GIFImageArray addObject:GIFImage];
    }

    testGIF.animationImages = GIFImageArray;
    testGIF.animationRepeatCount = 1;
    testGIF.animationDuration = 5;

    [self.view addSubview: testGIF];
    [testGIF startAnimating];

A: One thing may cause the loading issue, your line below:
UIImage *GIFImage = [UIImage imageNamed:[NSString stringWithFormat:@"DragAndMatch-%i.png", i]];

I believe it should be
[NSString stringWithFormat:@"DragAndMatch-%d.png", i]];

In the stringWithFormat The %d is for converting Signed 32-bit integer such as the i variable. Try it and see. More information are available here about string formatting specifiers:
https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/Strings/Articles/formatSpecifiers.html#//apple_ref/doc/uid/TP40004265-SW1
Hope this helps!

A: I think the answer is hidden in your question - you mentioned "am doing this in the MyScene class (not the view controller)." what do you think is in self.view then? if self.view is not the view of the controller, then its not going to show.
Add the testGIF to your VC's self.view and you should be good to go


text:
Q: Spring data Redis HGETALL operation I am using Redis as data store for my spring web application and using Spring Data-Redis as my client to interact with Redis.
I am using HashMap to store one my objects having multiple fields. I am able to put all the fields into Redis at once using DefaultRedisMap.putAll() method, but I am not able to get the whole object at once instead using BoundHashOperations to get each field using get() method.
I am wondering is there any way I can do that just like HGETALL operation supported in Redis?

A: DefaultRedisMap.entrySet() or BoundHashOperations.entries() should give you all the keys and values at once.

A: you can use HashOps::entries() to get all the entries (key and value) at once.


text:
Q: Remote Desktop client for Windows XP Home
Possible Duplicates:
How to connect to XP Home PC from XP Pro using Remote Desktop
Windows XP Remote Desktop program

Hi,
I'm looking for a remote desktop client that works in windows xp home edition the same way Windows remote desktop does. this is, without the need to install anything on the server.
is there any tool that does that?
thanks

A: Windows XP Home doesn't contain the server feature natively. A client is available:
From http://www.microsoft.com/windowsxp/downloads/tools/rdclientdl.mspx:

The Remote Desktop Connection software
  is pre-installed with Windows XP. To
  run it, click Start, click All
  Programs, click Accessories, click
  Communications, and then click Remote
  Desktop Connection. This software
  package can also be found on the
  Windows XP Professional and Windows XP
  Home Edition product CDs and can be
  installed on any supported Windows
  platform. To install from the CD,
  insert the disc into the target
  machine's CD-ROM drive, select Perform
  Additional Tasks, and then click
  Install Remote Desktop Connection.

If you're looking for a replacement that requires no additional installation on the server side, I'm not sure any exists. I do know of Teamviewer. It has a portable version that requires no installation and runs from a single .exe file.


text:
Q: Понимание массивов классового типа
Обьесните, пожалуйста, для чего нужна 16-ая строка...Ведь если уже был инициализирован массив с его тремя элементами, почему нужно делать это снова?...

A: Потому что, когда ты делаешь так
Mix4[] m4a = new Mix4[3]

ты создаешь только массив своих объектов. Если посмотреть, что лежит в этом массиве, то ты увидишь, что там лежат 3 объекта, которые ссылаются на null.
Для того, чтобы заполнить массив, как раз и вызывается 16 строчка из твоего кода.
12 строка инициализирует массив, 16 строка инициализирует элементы массива.

A: Согласно Java-спецификации:
... Каждый элемент массива инициализируется стандартным значением (§15.9, §15.10):

Для всех ссылочных типов (§4.3) стандартным значением является null.

Таким образом в первой строке выделяется память под массив из 3 элементов, каждый из которых имеет значение null.
P.S.: судя по вашему коду, вы выделяете память под 3 элемента, но в цикле переменная x изменяется от 0 до 3 включительно, т.е. инициализируете 4 элемента. Должно появляться исключение ArrayIndexOutOfBoundsException.


text:
Q: LINQ seems to ignore part of Where clause (probably due to ICollection issue) during Mapping let me use this sample data to make my problem clearer:
public class Booking

public override int Id { get; set; }
public int? AddressId { get; set; }
public virtual Address Adress { get; set; }
public DateTime? Date { get; set; }
public decimal? Hours { get; set; }

public class Address

public override int Id { get; set; }
public ICollection<Booking> Bookings{ get; set; }

Having these two entities when trying to do the following in Linq while mapping Booking to a ListItemDto:
Mapper.CreateMap<Booking, MyListItemDto>()
    .ForMember(t  => t.HoursSum,
              map => map.MapFrom(e => e.Address.Bookings
                          .Where(b => b.Datum.Value == e.Datum.Value)
                          .Sum(b => b.Hours))

weirdly, the result is the Sum of all Hours of the Bookings of this Address(for every row).
 Meaning that the date clause seems to be completely ignored.
My brain can't get what the problem is but I'm guessing it has to do with the fact that I'm going from Booking -> Address-> Bookings and then comparing the values.
But database wise it's normal since each Booking has a unique AddressId but each Address can be related with many Bookings AND more than one Booking can exist in a given date.
I hope my problem is clear and that I'm providing enough information. If anyone needs something more, feel free to tell me.

A: Just to answer my question since I found a solution to the problem:
The cause is that the expression is interpreted wrongly. Specifically the
.Where(b => b.Datum.Value == e.Datum.Value)

part is getting mixed up and in the query that is generated both b. and e. are considered to be the same Booking.
The solution is to actually do it like this:
map => map.MapFrom(e => e.Address.Bookings
                      .Select(b => new {b.Datum, b.Hours})
                      .Where(b => b.Datum.Value == e.Datum.Value)
                      .Sum(b => b.Hours))

That (for whatever reason, it doesn't look nice I know) solves the problem and the expression is translated to a correct query.
I'm assuming it's some sort of a bug with the version of Automapper we are using (3.3)
Cheers!


text:
Q: MySQL - PhpMyadmin - Create Multiple Tables I can´t understand why this query is not working to create this table structure in PHPMyAdmin.
I always receive this error message:

1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use
near 'MAX),
      FOREIGN KEY (form_id) REFERENCES form (Id) )' at line 4

CREATE TABLE form(
    Id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    Title VARCHAR(500),
    Is_Active BIT,
    Is_Trash BIT,
    Date_Created DATETIME
);
CREATE TABLE form_data(
    Id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    form_id INT,
    formdata VARCHAR(MAX),
    FOREIGN KEY (form_id) REFERENCES form (Id)
);

A: varchar(max) is MS SQL Server's syntax.  MySQL doesn't have an equivalent, so you'll just have to use a very long size. Additionally, once you'll solve this problem, you'll encounter a problem where form_data.form_id is not of the the same type as form.id (one is unsigned and the other isn't), so it cannot reference it. In short:
CREATE TABLE form_data(
    Id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    form_id INT UNSIGNED, -- Second issue
    formdata VARCHAR(4000), -- First issue
    FOREIGN KEY (form_id) REFERENCES form (Id)
);

A: There are 2 problems in table form_data:

*

*type of form_id, it should be INT UNSIGNED to match type of Id type of table form

*Using formdata VARCHAR(MAX), you should change MAX to real integer, 255 for example

Try this code:
CREATE TABLE form(
    Id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    Title VARCHAR(500),
    Is_Active BIT,
    Is_Trash BIT,
    Date_Created DATETIME
);
CREATE TABLE form_data(
    Id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    form_id INT UNSIGNED,
    formdata VARCHAR(255),
    FOREIGN KEY (form_id) REFERENCES form (Id)
);

A: Your error come from :
formdata VARCHAR(MAX),

Change MAX to a value.


text:
Q: Update file configuration but preserve previous value via Ansible Is possible to update file configuration via lineinfile or different module but preserve previous value?
For example:
SOME_ARGS=" -AA:1AA -BB:2BB -CC:3CC"

Add at the end of the line or begining -DD:4DD so result will be:
SOME_ARGS=" -AA:1AA -BB:2BB -CC:3CC -DD:4DD"

or
SOME_ARGS="-DD:4DD -AA:1AA -BB:2BB -CC:3CC"

This won't work as it will replace text with line value:
- lineinfile:
    path: "/some/file.txt"
    regexp: "^SOME_ARGS=.*-DD:4DD"
    line: "-DD:4DD"
    insertafter: "^SOME_ARGS=\""
    state: present

Thank you for any help!

A: It's something difficult with Ansible, I recommend you that these value changes were stored on a VCS, after that you can go back to any previous value.
Using lineinfile, a simple solution can be to apply the module twice, one pass to comment previous value, putting a # at the start for example, and the second one that will insert a new line after this commented one with the new value.
Take care that you regexp need to take care of other file values, this module in Ansible is a bit dificult to get working correctly with some configuration files.


text:
Q: Switching independent experiments: Does $I_A(X_1,\dots,X_n,Y_{n+1},Y_{n+2},\dots)$ converge almost surely? Suppose there is a sequence of independent random variables $X=(X_1,X_2,\dots)$ with $X_i$ taking values in some arbitrary measure space $E_i$. Now there is a second sequence $Y=(Y_1,Y_2,\dots)$ independent of $X$ with the same distribution. Let $A\subseteq E_1\times E_2\times\cdots$ be any event. For $n\geq 1$ define
$$I^A_n:=I((X_1,X_2,\dots,X_n,Y_{n+1},Y_{n+2},\dots)\in A):=\begin{cases}0~,~\text{if}~(X_1,\dots,X_n,Y_{n+1},Y_{n+2},\dots)\notin A\\
1~,~\text{if}~(X_1,\dots,X_n,Y_{n+1},Y_{n+2},\dots)\in A,\end{cases}$$
so $I^A_n$ is an indicator.
Now set
$$I^A:=I((X_1,X_2,X_3,\dots)\in A):=\begin{cases}0~,~\text{if}~(X_1,X_2,X_3,\dots)\notin A\\
1~,~\text{if}~(X_1,X_2,X_3,\dots)\in A\end{cases}.$$
For example consider the infinitely repeated toss of a fair coin. Imagine two people are tossing a coin independently with results $X_1,X_2,\dots$ and $Y_1,Y_2,\dots$. Here the event $A$ would be a Borel set of $\{0,1\}^{\mathbb{N}}$. For example $A=\{\text{Heads in the 27.th toss}\}.$ For each $n$ I built a new sequence of coin tosses: The first $n$ tosses come from $X$, the other infinitely many tosses come from $Y$. So the sequence of tosses is $(X_1,\dots,X_n,Y_{n+1},Y_{n+2},\dots)$. For the example $A=\{\text{Heads in the 27.th toss}\}$ you have $I^A_n=I(Y_{27}=1)$ for $n< 27$ and $I^A_n=I(X_{27}=1)=I^A$ for all $n>27$. Now in the general setting:
$$\text{Is it true that $I^A_n$ converges almost surely towords $I^A$ as $n\rightarrow\infty$?}$$
Since the RVs are $\{0,1\}$-valued convergence means that the RVs stay finally constant.
I failed to prove this and I also failed to find a counterexample. I know the following:

*

*$I^A_n$ and $I^A$ have the same distribution for all $n$.

*The set $\mathcal{D}:=\{\text{Events $A$ for which above statement is true}\}$ is closed under finite unions, intersections, taking complements and contains all cylindric events.

*For every event $A$ the convergence $I^A_n\rightarrow I^A$ holds in $L^1$, so there is a deterministic subsequence $1\leq n_1<n_2<\dots$ depending on $A$ for which $I^A_{n_k}\rightarrow I^A$ hold almost surely as $k\rightarrow\infty$.

*The event $\{I^A_n~\text{converges as $n\rightarrow\infty$}\}$ is contained in $\sigma(X)$ a.s.

*The statement is true for any event $A$ with $P(X\in A)\in\{0,1\}$ so in particular for every terminal event, because of Kolmogorov-$0$-$1$-law.

*Borel-Cantelli can't be used in general to prove almost sure convergence. There are examples where $\sum_{n\geq 1}P(|I^A-I^A_n|=1)=\infty$, but $I^A_n\rightarrow I^A$ almost surely holds anyway.
I failed to prove that $\mathcal{D}$ contains every event, so I tried to construct a counterexample: $E_i=\{0,1\}$ for every $i$ and $X$ is a sequence of independent fair coin tosses. By letting $U(x_1,x_2,\dots):=\sum_{i\geq 1}x_i/2^i$ and $C\subset[0,1]$ be a fat cantor set, i thought that $A:=\{(x_1,x_2,\dots):U(x_1,x_2,\dots)\in C\}$ gives a counterexample, but i failed to show that as well. See: https://mathoverflow.net/questions/242919/speed-of-convergence-in-lebesgues-density-theorem/242990#242990
there $2\cdot a_n(C)=P(|I^A-I^A_n|=1)$. The counterexample given there is not a counterexample for this question.
Do you know how to prove or how to give a counterexample?