text:
Q: split 64 bit loop to several 32 bit loops on integers Instead of using one 64bit long type variable as loop counter, i would rather have several 32bit loop counters. I need longer loops than 32bits can hold, and using 64bits it is slower in my case.
Any ideas how to achieve this, simple ?

A: If your desired loop count c can be divided into two factors that both fit in 32bit integers, then the following will loop m * n = c iterations using 32 bit counters. If c is a prime for example, this won't work.
uint32_t m, n; // initialize according to your needs
for(uint32_t i = 0; i < m; ++i) {
    for(uint32_t j = 0; j < n; ++j) {

    }
}

Here is a bit more elaborate solution that should work with any loop count. You don't need to factorize the number by hand either. Do note however, that if your loop count is not compile time constant, then any time gained by 32bit counters is surely lost to the 64bit division. If you don't trust that your compiler would substitute n and r with constant values, then do the calculation by hand.
const uint64_t c = 12000000000ull;
const uint32_t m = std::numeric_limits<uint32_t>::max();

const uint32_t n = c / m;
const uint32_t r = c % m;

for(std::uint32_t i = 0; i < n; ++i) {
    for(std::uint32_t j = 0; j < m; ++j) {
        do_stuff();
    }
}
for(std::uint32_t i = 0; i < r; ++i) {
    do_stuff();
}


text:
Q: Resolve Tenant Id in VirtualPathProvider MVC5 I am writing multitenant based application and I want to load custom view from storage base on url(tenant).
I type https://corporate.myapp.local/ in browser but in FileExistsmethod HttpContext.Current.Request.Url give me http://127.0.0.1/ it does not tell me which domain is this so i can get file base on domain and resolve tenantid
public class ViewPathProvider : VirtualPathProvider, ICustomVirtualPathProvider
    {
        VirtualPathProvider ICustomVirtualPathProvider.Instance => this;

        private readonly ILogger _logger;
        private readonly IThemeService _themeService;
        private readonly ISellutionSession _sellutionSession;

        public ViewPathProvider(ILogger logger, IThemeService themeService, ISellutionSession sellutionSession)
        {
            _logger = logger;
            _themeService = themeService;
            _sellutionSession = sellutionSession;
        }

        public override bool FileExists(string virtualPath)
        {

            _logger.Log($"CurrentCompanyId: {_sellutionSession.GetCurrentCompany(HttpContext.Current.Request.Url).CompanyId}");

            var isViewExist = Pages.IsExistByVirtualPath(virtualPath);
            return isViewExist || Previous.FileExists(virtualPath);
        }

A: You need to set up your Development environment to be able to accept sub domains,
This can be accomplished by editing the applicationHost.config file and the host file on the machine.
need to change how IIS Express runs your development environment.
In Visual Studio 2015, right-click on the solution file.
Select 'Open Folder in File Explorer'
Go to the containing folder and look for a .vs folder.
Inside, there will be a config folder containing an applicationhost.config file.
Open it in your favorite text editor (I use Notepad++)
Under the Configuration/system.applicationHost/Sites, you should see your site in bindings with a port and localhost.
<binding protocol="http" bindingInformation="*:38254:localhost" />

Duplicate this line and add your subdomain to this binding.
<binding protocol="http" bindingInformation="*:38254:m.localhost" />

Save this file and reload your project.
Host File
need to head to our Hosts file to modify that as well.
Go to C:\Windows\System32\Drivers\Etc in File Explorer.
Open the HOSTS file (it has no extension)
At the bottom of the hosts file, add the following two lines.
127.0.0.1    localhost
127.0.0.2    m.localhost

Save the file.
you need to give Visual Studio 2015 Administrative rights to use subdomains.
Now we can run our Visual Studio and see our subdomain actually run.st:3892
Here is a link to help you.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Speed up webcrawler I wrote this script, which works perfectly, except it is taking about 5 minutes (give a few) to run. What would be the best way to speed this up?
Kind regards, Rob
        System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
        sw.Start();
        int divnumber = 17476;
        HtmlAgilityPack.HtmlWeb web = new HtmlAgilityPack.HtmlWeb();
        while (divnumber < 18500)
        {
            string DivUrl = "https://www.hattrick.org/nl/World/Series/?LeagueLevelUnitID=" + divnumber;
            HtmlAgilityPack.HtmlDocument doc = web.Load(DivUrl);
            var ClassShy = doc.DocumentNode.SelectNodes("//a[@class='shy']");
            if (ClassShy != null)
            {
                ClassShy.ToList();
                int i = 0;
                foreach (var item in ClassShy)
                {
                    i++;
                }
                int divForList = divnumber - 17475;
                if (i > 4)
                {
                    Console.WriteLine("VI." + divForList + " - " + i);
                }
            }
            divnumber++;
        }
        sw.Stop();
        TimeSpan ts = sw.Elapsed;
        string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}:{3:00}", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10);
        Console.WriteLine("\nDone in " + elapsedTime);
        sw.Reset();


text:
Q: On histogram equalization So I'd like to do it without histeq, but my code seems to get out a rather peculiar, really whited out image, and doesn't seem all too much improved from the original picture. Is there a better way to apply the proper histogram?
Cumlative=zeros(256,1);
CumHisty=uint8(zeros(ROWS,COLS));
% First we need to find the probabilities and the frequencies

freq = zeros(256,1);
probab = zeros(256,1);

for i=1:ROWS
    for j=1:COLS
    value=I1(i,j);
    freq(value+1)=freq(value+1)+1;
    probab(value+1)=freq(value+1)/(ROWS*COLS);
    end
end

count=0;
cumprobab=zeros(256,1);
distrib=zeros(256,1);

for i=1:size(probab)
    count=count+freq(i);
    Cumlative(i)=count;
    cumprobab(i)=Cumlative(i)/(ROWS*COLS);
    distrib(i)=round(cumprobab(i)*(ROWS*COLS));
end

for i=1:ROWS
    for j=1:COLS
        CumHisty(i,j)=distrib(I1(i,j)+1);
    end

A: You probably want to do:
distrib(i) = round(cumprobab(i)*255);

EDIT:
Here is a version of your code without the redundant computations, and simplified looping:
freq = zeros(256,1);
for i = 1:numel(I1)
   index = I1(i) + 1;
   freq(index) = freq(index)+1;
end

count = 0;
distrib = zeros(256,1);
for i = 1:length(freq)
   count = count + freq(i);
   cumprobab = count/numel(I1);
   distrib(i) = round(cumprobab*255);
end

CumHisty = zeros(size(I1),'uint8');
for i = 1:numel(I1)
   CumHisty(i) = distrib(I1(i)+1);
end

I use linear indexing above, it's simpler (one loop instead of 2) and automatically helps you access the pixels in the same order that they are stored in. The way you looped (over rows in the outer loop, and columns in the inner loop) means that you are not accessing pixels in the optimal order, since arrays are stored column-wise (column-major order). Accessing data in the order in which it is stored in memory allows for an optimal cache usage (i.e. is faster).
The above can also be written as:
freq = histcounts(I1,0:256);
distrib = round(cumsum(freq)*(255/numel(I1)));
distrib = uint8(distrib);
CumHisty = distrib(I1+1);

This is faster than the loop code, but within the same order of magnitude. Recent versions of MATLAB are no longer terribly slow doing loops.
I clocked your code at 40 ms, with simplified loops at 19.5 ms, and without loops at 5.8 ms, using an image of size 1280x1024.


text:
Q: date format using CultureInfo wont work I am trying to change the default date format by the way below but the format wont change and there is no errors
I am excepting to get date in Arabic format. What I am getting now is the default system format date like this (12:00:00 03/01/2011) while I want to overwrite the system format date
Note: Working under oracle11g
TBNextDate.Text = Convert.ToDateTime(oraReder[4])
                         .ToString("hh:mm:ss dd/MM/yyyy", new CultureInfo("ar-AE"));

A: According to MSDN:

The provider parameter defines the pattern that corresponds to the standard format specifiers, as well as the symbols and names of date and time components.

When you specify a specific format like you do that does not include any name specifiers, the only thing the culture changes is the separator symbol (e.g. / or .)
If you want to use a date pattern specific to that culture, use a standard format string instead:
TBNextDate.Text = Convert.ToDateTime(oraReder[4]).ToString("d", new CultureInfo("ar-AE"));


text:
Q: Excel unresponsive when manipulating large amount of data from add-in I find that if I edit large amounts of data in an Excel sheet using an Excel add-in in the new, web-baed add-in model, the add-in becomes really unresponsive even though the getselectedata and setselecteddata are both async functions. Is this expected or are there ways to increase performance?

A: Rather than the getSelectedDataAsync (or set) functions that are available in all Office host applications, you could try to use the Excel specific (2016 only, unfortunately) APIs. These might be faster, especially when you use batching or syncing for the operations you perform on the document.
Please refer to the documentation of the 'ctx' APIs and the ctx.run() function specifically for batching. https://dev.office.com/docs/add-ins/excel/excel-add-ins-javascript-programming-overview?product=excel


text:
Q: How can I convert the output of `git diff --color-words` to HTML? For working with text that is prose, stored in plain text, I really like the output of git diff --color-words, but I don't like the way it is dependent on ANSI terminal escape sequences.  I'd like to get output that I can use to turn into HTML, some kind of user-friendly raw character display, or to generate statistics on the differences between the two files.
I prefer Perl (including CPAN), but would settle for pretty much anything.

A: This question asks about converting ANSI escape sequences into HTML color directives, and the accepted answer is a link to the Perl module HTML::FromANSI, in CPAN.


text:
Q: LiveCharts: How is the AxisCore internal properties accessible from WpfView Axis implementation? I'm looking through the code of the popular WPF graphing component LiveCharts, in an effort to port it to .NET 3.5. However, I'm not sure how this bit works:
LiveCharts.AxisCore.TopLimit is declared as an internal property. There are others too declared the same. Then, in LiveCharts.Wpf.Axis, a class variable  public AxisCore Model { get; set; } is declared, and these internal properties are referenced in various methods, for example in the method public void SetRange(double min, double max).
These are separate assemblies (as far as I can tell), with Core being a portable assembly targeted only at .NET Framework 4. and WpfView a vanilla class library. How can these internal properties be accessible without using the InternalsVisibleTo attribute?

A: The Core Project is using the InternalsVisibleTo Attribute in the file AssemblyInfo.cs:
[assembly:InternalsVisibleTo("LiveCharts.Uwp,PublicKey=002400000480000094000000060200000024000052534131000400000100010009132ae1a474e2ecf9903c1ef8945a2119aa0b9a3b4e40c43f6cb66233669e3007b4109d5c37957c2d0c5cfe7fce34366150210f83c618c18cdc8d7b763bff60419837a2185df1867c73f679e05f82b861e6ca764612eabc36d71858260b262bb9c3ad546c9692fe6379a520b6c5fc701e0ee6d071b52e9f20166fc0752ff894")]
[assembly:InternalsVisibleTo("LiveCharts.Wpf,PublicKey=002400000480000094000000060200000024000052534131000400000100010009132ae1a474e2ecf9903c1ef8945a2119aa0b9a3b4e40c43f6cb66233669e3007b4109d5c37957c2d0c5cfe7fce34366150210f83c618c18cdc8d7b763bff60419837a2185df1867c73f679e05f82b861e6ca764612eabc36d71858260b262bb9c3ad546c9692fe6379a520b6c5fc701e0ee6d071b52e9f20166fc0752ff894")]
[assembly:InternalsVisibleTo("LiveCharts.Geared,PublicKey=0024000004800000940000000602000000240000525341310004000001000100bd2e66fab8ce9a4900047ffda57d2f525cf6313dcc9d20994c5e6b3cd8fca906ba7ccd54bea5f7bd6cb503deb81d685259e355e3a9b5c21e5bc80091f08846246371b2a71ab306655651261e910adfa61be236b77d11df23a44d48f00a0e07c689f9a2daaff16d505a1c861d9854d92ed5a8a38fb28c1343fb691462873e71a1")]

See https://github.com/beto-rodriguez/Live-Charts/blob/5709a2e415038d5e6ebb707f48b03927c50babec/Core/Properties/AssemblyInfo.cs#L33-L35


text:
Q: InvocationTargetException with JavaFx when using Labels (without fxml) I'm trying to create a small GUI using javafx. It works as long as I'm just setting up the scene, the stage, the title and a GridPane. As soon as I try to add labels or buttons it throws a (for me) incomprehensible Exception.
My IDE is intelliJ running on Ubuntu 18.04, I'm running Java openjdk 11.0.2. I tried different versions of javafx, but both (12.0.2 and 11.0.2) threw the same Exception under the same circumstances. I double checked the integration of the javafx library and "confirmed" this by getting another error massege ("java: package javafx.application does not exist", etc.) and by intelliJ going crazy in that case.
package sample;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;

public class Main extends Application {
    @Override
    public void start(Stage primaryStage){
        GridPane root = new GridPane();
        primaryStage.setTitle("Hello World");
        primaryStage.setScene(new Scene(root, 300, 275));

        //Label lbl = new Label("test");
        //GridPane.setConstraints(lbl, 0,0);
        //root.getChildren().addAll(lbl);

        primaryStage.show();
    }

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

The three lines that are commented out seem to be the root of all evil, as the code compiles and runs perfectly without them and chokes with them included.
With the evil lines inlcuded the following Exception is thrown:
Exception in Application start method
java.lang.reflect.InvocationTargetException
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:464)
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:363)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at java.base/sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:1051)
Caused by: java.lang.RuntimeException: Exception in Application start method
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:900)
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.lambda$launchApplication$2(LauncherImpl.java:195)
    at java.base/java.lang.Thread.run(Thread.java:834)
Caused by: java.lang.IllegalAccessError: superclass access check failed: class com.sun.javafx.scene.control.ControlHelper (in unnamed module @0x662766ad) cannot access class com.sun.javafx.scene.layout.RegionHelper (in module javafx.graphics) because module javafx.graphics does not export com.sun.javafx.scene.layout to unnamed module @0x662766ad
    at java.base/java.lang.ClassLoader.defineClass1(Native Method)
    at java.base/java.lang.ClassLoader.defineClass(ClassLoader.java:1016)
    at java.base/java.security.SecureClassLoader.defineClass(SecureClassLoader.java:174)
    at java.base/jdk.internal.loader.BuiltinClassLoader.defineClass(BuiltinClassLoader.java:802)
    at java.base/jdk.internal.loader.BuiltinClassLoader.findClassOnClassPathOrNull(BuiltinClassLoader.java:700)
    at java.base/jdk.internal.loader.BuiltinClassLoader.loadClassOrNull(BuiltinClassLoader.java:623)
    at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:581)
    at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
    at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
    at javafx.scene.control.Control.<clinit>(Control.java:86)
    at sample.Main.start(Main.java:16)
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$9(LauncherImpl.java:846)
    at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runAndWait$12(PlatformImpl.java:455)
    at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$10(PlatformImpl.java:428)
    at java.base/java.security.AccessController.doPrivileged(Native Method)
    at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$11(PlatformImpl.java:427)
    at javafx.graphics/com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:96)
    at javafx.graphics/com.sun.glass.ui.gtk.GtkApplication._runLoop(Native Method)
    at javafx.graphics/com.sun.glass.ui.gtk.GtkApplication.lambda$runLoop$11(GtkApplication.java:277)
    ... 1 more
Exception running application sample.Main

Process finished with exit code 1


text:
Q: How to open the built-in task manager when it's replaced by Process Explorer? I want to open the built-in task manager with Process Explorer's Replace Task Manager option checked. I've tried:

*

*Running taskmgr.exe from the run dialog. PE was opened instead.

*Creating a copy of taskmgr.exe in the same folder. Then run it. The built-in task manager was opened, but not working properly(its window was blank).

*Creating a symbolic link (using mklink) of taskmgr.exe in the same folder. Then run it. PE was opened instead.
Is there any other method I can try? Thanks.

A: There are two problems here:

*

*The way that Process Explorer takes over from Task Manager is by adding a registry value:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\taskmgr.exe\Debugger
This means whenever you start an executable named 'taskmgr.exe', start whatever is specified in this value instead. So moving task manager to a different directory does not work.

*

*Renaming taskmgr.exe to something else seems to break something
within Task Manager. That why you see an empty window. That's a
rather odd behavior, normally it is no problem to rename an
executable.
The renamed task manager behaves rather odd. Even if started from a medium integrity level, it automatically runs in high integrity level and it can not be killed even with local system privileges.
So for now, I don't see a way to have Process Explorer as default task manager and be able to run task manager at the same time.
The workaround is not too bad:
In Process Explorer, untick 'Options - Replace Task Manager', then run 'taskmgr.exe' and tick 'Options - Replace Task Manager' again.
Alternatively you can create a batch-file that removes that registry setting, starts task manager and puts the setting back in:
 reg.exe delete "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\taskmgr.exe" /v Debugger /f
 start taskmgr.exe
 reg.exe add "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\taskmgr.exe" /v Debugger /t REG_SZ /d "C:\PATHTO\PROCEXP.EXE" /f

The only problem with this batch is that you need to run it as an elevated administrator, so when creating a shortcut for it, specify to run it as an administrator. As a normal user you cannot change those registry settings.

A: RUnning Taskmanager from Run
Click the Start button then the All Programs folder. Under the Accessories folder click the Run command. You can also press they Windows Key + R on your keyboard or enable the Run command in your Start Menu. Finally, simply type "taskmgr" and hit Enter.
Running Taskmanager from shortcut
Or you may create a shortcut. Right-click on your desktop and choose New then click Shortcut. A new window will pop up. Browse to the same path as above, C:\Windows\System32. Scroll down until you see taskmgr.exe, highlight it, and then click OK. Click Next, type a name for your shortcut, and finally click Finish

A: Because it is impossible then we sway with the wind:
1.Open sysinternal version of taskmaneger ie. Processs Explorer.
2.Click the replacement: Options/Replace Task Manager
3.Open normal taskmanager by Winflag+R: C:\WINDOWS\System32\Taskmgr.exe
4.Do your thing
5.Reclick Options/Replace Task Manager


text:
Q: Showing a compact metric space has a countable dense subset I know that this is separable, but that has not been covered by the text at this point. I believe my proof (below) to be correct, but not very rigorous. Assuming that it actually is correct, could someone please help me make it more formal? (If it's not correct, please help with the proof). Thanks.
Proof: Let $X$ be a compact metric space. Let $B_n = \{B(x,\frac1{n}) : x\in X\}$. be the collection of open balls centered at $x$. Let $\{x\}^{(n)}$ be the set of centers for some particular $n$. Then by compactness of $X$, there are also a finite number of centers for a particular $n$ (corresponding to each open ball).
[This is where I have trouble properly saying what's on my mind:]
Consider $B(x,r_0)$, where $r_0 = \frac{1}{n_0}$. When we decrease the magnitude of $r_0$ to $r_1$, we must still be able to cover $X$. Meaning some open ball(s) must be "formed" where $B(x,r_0)$ was once "covering". So by adding open balls, we also add to our collection of centers. This means at $B(x,r_0)$, there was originally a point $y \in B(x,r_0)$ s.t. $B(y,r') \subset B(x,r_0)$ for some $r'$. That is, $B(x,r_0)$ contained another point of $X$. Thus, by definition, $X$ contains a countable dense subset.

A: I think that you can pretty much ignore where exactly are the new balls that replaced the old balls. There is no harm in adding in redundant ball center as long as it is still finite, so you can keep the centre of the big ball and the centre of the small ball.
So I think the 2nd part can be fixed simply by this:
For each $n$ there is a finite set of centre $C_{n}\subset \{x\}^{(n)}$ such that all ball of radius $\frac{1}{n}$ around these centre cover $X$ completely.
Simply produce the set $Z=\bigcup\limits_{i=1}^{\infty} C_{i}$ which is countable.
Given any point $x\in X$, and any $\epsilon>0$ then the ball $B_{\epsilon}(x)$ must intersect $Z$. Why? Because remember that there exist a $C_{n}\subset Z$ where $\frac{1}{n}<\epsilon$ that means that there is a collection of ball radius $\frac{1}{n}$ with centre $C_{n}$ that cover $X$ completely, that means $x$ is not more than $\frac{1}{n}<\epsilon$ from at least 1 point in $C_{n}\subset Z$. Since this apply to all $\epsilon>0$ then $x$ is in the closure of $Z$.

A: First a notational observation: the notation $\{x\}^{(n)}$ is truly horrible. It looks as if you're performing some operation on the singleton set $\{x\}$ whose sole element is $x$.
Your basic idea is just fine, but you're making it too complicated; that's part of why you're having trouble expressing it clearly. As others have suggested, you don't need to try to relate the centres of one 'level' to those of any other 'level'. Here's a relatively efficient version of the idea:

For each $n\in\Bbb Z^+$ let $$\mathscr{U}_n=\left\{B\left(x,\frac1n\right):x\in X\right\}\;;$$ $\mathscr{U}_n$ is an open cover of the compact space $X$, so there is a finite $F_n\subseteq X$ such that $$\left\{B\left(x,\frac1n\right):x\in F_n\right\}$$ covers $X$. Let $D=\bigcup_{n\in\Bbb Z^+}F_n$; $D$ is a countable union of finite sets, so $D$ is countable. To see that $D$ is dense in $X$ let $y\in X$ and $\epsilon>0$ be arbitrary. There is an $n\in\Bbb Z^+$ such that $\frac1n\le\epsilon$, and there is then an $x\in F_n$ such that $y\in B\left(x,\frac1n\right)$. But then $d(x,y)<\frac1n\le\epsilon$, so $y\in D\cap B(x,\epsilon)$, and $D$ is indeed dense in $X$. $\dashv$

You might like to note, by the way, that we could have got the same result had each of the sets $F_n$ been countable: we did not actually need them to be finite. Thus, the same argument shows that every Lindelöf metric space is separable. And this actually is a stronger result, since $\Bbb R$ with its usual metric is Lindelöf but not compact.

A: Let $\epsilon > 0$. Then, since the space is compact, there are $x_0, x_1, \cdots x_n$ so that that
$$X = \bigcup_{k=0}^n B_\epsilon(x_k).$$
Such a set is called an $\epsilon$-net of $X$.
For each positive integer $p$, choose a (finite) $1/p$-net $N_p$ of $X$.  Then $\bigcup_p N_p$ is a countable union of finite sets, so it is countable.  It  is also easy to argue it is dense in $X$.


text:
Q: Can I user AdSence Code in User Control in ASP.NET? I think it is not the feasible way out here to ask. But, Can I use AdSense code in UserControl in ASP.NET?
If I use it in User Control, does the Same ad will be displayed at all the places where the User Control is used?
PS: This Question will be deleted up on suggestion, if it is not useful for future viewers of SO.

A:
does the Same ad will be displayed at all the places where the User Control is used?

No, Ad will be different according to page...as User control renders along with page where its used..so when your page 'll render. Your user control will render also..and new request for Adsense code will go to google to display a different ad.


text:
Q: Let S = {${a_1, a_2, a_3, ... a_n}$} be a finite nonempty set of real numbers a. prove bounded b. show lub and glb are elements of S Question:
Let S = {${a_1, a_2, a_3, ... a_n}$} be a finite nonempty set of real numbers.
(a) show that S is bounded
(b) Show that lub S and glb S are elements of S

for (a) I see an attempt to answer it was made here: Prove that a finite non empty set of real numbers in bounded .
But the logic is escaping me. Why is M necessarily larger than $a_i$ in the posted example?
(b) I don't know where to begin for this one... I know that if S is bounded then there must be a lub and glb. But why would they necessarily be elements of S? I didn't think a lub or glb had to be an element in a set? Am I misunderstanding?

A: Let $$M=max \{|a_1|,|a_2|,...,|a_n|\}$$
We have $$-M\le a_i\le M, i =1,2,...,n$$
That is $S$ is bounded.
The minimum element of $S$ is a lower bound of $S$ and it is the greatest lower bound because if $x$ is greater than the minimum then $x$ is not a lower bound due to the fact that an element of the set namely the minimum is less than that.
Similar argument works for the maximum being the least upper bound.

A: For part (a), note that for each $i$, $a_i\leq|a_i|$. Also, adding more positive numbers to $|a_i|$ simply makes the number greater. So we get that for each $i$, $a_i\leq|a_i|\leq|a_1|+\cdots+|a_i|+\cdots+|a_n|$. Hence, the set is bounded.
For part (b), note that if a set contains its maximum, then the least upper bound of that set is its maximum. To prove this, let $S$ be a set bounded above that contains its maximum. Then we know it has a supremum $\sup S$, which satisfies the properties that $\sup S$ is an upper bound for $S$, and that any upper bound of $S$ is greater than or equal to $\sup S$. Now note that the maximum of the set $S$ is an upper bound for $S$, since any element of $S$ is less than or equal to the maximum of the set $S$. What can you conclude?


text:
Q: c# сделать функцию параметром функции Есть множество функций типа flipImageV. До и после кода в этих функциях должны быть одинаковые строки кода. Что бы в каждой функции типа flipImageV их не писать, хочу сделать одну, куда буду передавать нужную функцию на выполнение...
Вот универсальная функция, куда передаю выбранную функцию типа flipImageV:
protected void editImage(delegate func) {
        currentImage.ImageUrl = @"..\images\img0.jpg";
        func();
        photo.Save(@"~\" + imagePath);
    }

Функция типа flipImageV:
protected void flipImageV(object sender, EventArgs e) {
        photo.FlipVertical();
    }

Использование того шаблона:
editImage(flipImageV);

или
protected void flipImageV(object sender, EventArgs e) {
        editImage(photo.FlipVertical());
    }

Что должно быть вместо delegate func? Как это лучше сделать?

A: Используйте просто Action:
protected void editImage(Action func) {
    currentImage.ImageUrl = @"..\images\img0.jpg";
    func();
    photo.Save(@"~\" + imagePath);
}

Вызывать как-то так:
editImage(() => photo.FlipVertical());

Если вам нужно непременно передавать внутрь функцию наподобие flipImageV, которая получает два игнорируемых аргумента, можно так:
editImage(() => flipImageV(null, EventArgs.Empty));


text:
Q: Coloring $5 \times5$ transparent chessboard in space.
We have $5 \times 5$ chessboard floating in space , so rotation and reflection are allowed. We want to color it using $m$ distinct colors such that when we color a square , the both sides of that square will be colored , so the both faces of chess board will be coloring while we are coloring one face. (You may think that this chessboard is transparent ) How many nonequivalent coloring are there ?

My work:

*

*$\psi(\pi_0^*)=m^{25}$ , the identity permutation.

*$\psi(\pi_1^*)=m^{7}$ , $90$ degree rotation.

*$\psi(\pi_2^*)=m^{13}$ , $180$ degree rotation.

*$\psi(\pi_3^*)=m^{7}$ , $270$ degree rotation.

*$\psi(r_1^*)=m^{15}$ , horizontal reflection.

*$\psi(r_2^*)=m^{15}$ , vertical reflection.

*$\psi(r_3^*)=m^{15}$ , diagonal reflection (positive slope diagonal).

*$\psi(r_4^*)=m^{15}$ , diagonal reflection (negative slope diagonal).
$$\frac{1}{4}(m^{25}+2m^7 +m^{13} +4m^{15})$$
Is my solution correct ?
EDITED ANSWER: $$\frac{1}{8}(m^{25}+2m^7 +m^{13} +4m^{15})$$

A: You are very close. Remember, there are $8$ possible transformations, so you need $\frac18$ in front, not $\frac14$. (As a quick check, what should the answer be if there is only a single color available, i.e. $m = 1$?)
Apart from that, I agree with all your calculations, and also with your decision to go with Burnside's lemma.


text:
Q: Develop e commerce web site in nopCommerce in mvc4 i want to develop e commerce websites and i want to use technology is MVC4. some one suggest me about nopCommerce please guide me about this framework is it good for e commerce websites or any other framework you suggest. if this is good framework then please also guide me how to customize it any good video tutorial or ebook which you suggest. thank you

A: nopCommerce is the popular open-source eCommerce solution. It provides fully customizable, stable & highly usable shopping cart. And it is totally free.
You can also download it's source code from here.
You can see the demo from here.
There is an ebook available for beginners here.
Lots of video tutorials are available on the internet, just google it. And almost all major web hosting providers also supports it.
Finally conclusion: It is good & perhaps the best free eCommerce solution available in the market. Go for it.


text:
Q: Error in executing jquery function I am executing following code but i am getting error: "Objected Expected"
I checked the code but didnt find any problem.
<!DOCTYPE html>

            Click me
            hello

            mid

                    hi

A: Your id should be
Click me

There was a # in your id.
** EDIT **
Your other problem is that you can't load a page on another domain into your site. You'll have to use an iframe for that.

A: Try removing the hash sign from the id of clickme
Click me


text:
Q: Has this spider been seen before? In season 2 episode 2 of The Mandalorian, a vicious, spider-like species plays heavily into the story.

I instantly recognized them as very similar in appearance to the krykn found on Atollon in the animated show Rebels.

Are these creatures the same or related in any way?

A: This is a new species
Lucasfilm's Creative Art Manager, Phil Szostak, has confirmed via Twitter that while both  creatures are inspired by the same Ralph McQuarrie art depicting a giant spider on Degobah, they are a completely different species.


text:
Q: Error allocating Mem BAR for PCI Device 0X/00/0 I am getting the following error when I boot my Dell Precision 390.  Everything appears to be working fine, but I would like to understand what  the error means and how to fix it.  I believe it started happening when I plugged in my second video card, but that card is working great.
Error allocating Mem BAR for PCI device 04/00/0
Error allocating Mem BAR for PCI device 05/00/0
Error allocating Mem BAR for PCI device 05/02/0
Error allocating Mem BAR for PCI device 05/05/0
Error allocating Mem BAR for PCI device 05/04/0
Error allocating Mem BAR for PCI device 05/04/0
Error allocating Mem BAR for PCI device 05/05/0

A: For PCI and PCIe devices, a BAR is a Base Address Register that is used by the BIOS or OS to tell the device what physical addresses to map its memory resources into. Most PCI devices in your system requests a certain amount of memory space, and the BIOS tries to fit them all below 4 GB in order to ensure compatibility with 32-bit operating systems. It sounds like your computer has 4 GB of RAM and that both video cards contain large amounts of RAM.
In those error messages, the location of the device is specified as bus/device/function. I have access to a Dell Precision 390 and it appears that all of the onboard devices on that system are on PCI bus number 0, so your errors probably refer to a device that you have plugged into a PCI or PCIe slot. Each PCIe slot gets its own bus number, so bus number 5 might actually correspond to a multi-function PCIe device such as a sound card or video capture card.
You should be able to track down which devices are 4/0/0, 5/2/0, 5/4/0, and 5/5/0 once the OS is loaded, if the BIOS doesn't print this information before booting. (Note that this assumes that the OS doesn't reassign the PCI bus numbers on boot, which would destroy the evidence; if that happens, the OS may be patching up the mess that the BIOS left.)
If you use Windows, you can find the PCI bus/device/function numbers of a device by right clicking on it in Device Manager, selecting Properties..., and looking at Location: on the General tab. (On Vista and Windows 7, this same information also shows up when you select the Details tab and choose Location information from the Property listbox.)
If you use Linux, you can find the PCI bus/device/function numbers using the lspci command.

A: The documentation lists that code: Error allocating Mem BAR for PCI Device

The system encountered a problem while trying to configure an expansion card or integrated on-board devices.
If the device number points to an expansion card, the card can be removed. See "Troubleshooting Expansion Cards" in "Troubleshooting Your System."
If the device number points to a an on-board device, disable the device. See "Using the System Setup Program" in your User's Guide for details.

A: Have you tried clearing the NVRAM with the modem card out of the system?
If that doesn't do the trick then pull all of the PCI expansion cards out of the system to see if it will boot normally.  You may have to clear the NVRAM again.
I assume you are using this method to clear the NVRAM....
Reboot system and enter the BIOS Setup by pressing F2.
Turn on Caps Lock, Scroll Lock and  Num Lock.
Press ALT+ E then ALT+ F (should hear beep) then ALT+ B


text:
Q: Multiple objects with the same key error Hi I'm getting following error while updating the record

An object with the same key already exists in the ObjectStateManager.
  The ObjectStateManager cannot track multiple objects with the same
  key.

Here's my Edit (Post) Action.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit([Bind(Include = "Id,Name,Type,Weightage,Description,ParentId")] HiringFactor hiringfactor)
    {
        if (ModelState.IsValid)
        {
            var childCount = 0;
            var indent = "";
            var parentId = hiringfactor.ParentId;

            HiringFactor parentFactor = db.HiringFactors.Find(parentId);
            if (parentFactor != null)
            {
                childCount = parentFactor.ChildHiringFactors.Count;
                indent = parentFactor.Indent + "." + (childCount + 1);
            }
            else
            {
                var parentCount = db.HiringFactors.Count(hf => (hf.ParentId == null || hf.ParentId == 0));
                indent = (parentCount + 1).ToString();
            }
            hiringfactor.Indent = indent;

            db.Entry(hiringfactor).State = EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        ViewBag.ParentFactors = new SelectList(db.HiringFactors, "Id", "IndentName", hiringfactor.ParentId);
        return View(hiringfactor);
    }

Is it becaus of I'm dealing with objects of Same Type within DB Context?

A: The problem seems originated from EntityState.Modified before SaveChanges method, assuming hiringfactor is new entity as modification target:
db.Entry(hiringfactor).State = EntityState.Modified;

By convention, you can't re-attach a model once the entity has been loaded by the same key value. Try using this code right before SaveChanges:
db.Entry(parentFactor).CurrentValues.SetValues(hiringfactor);

Another way to set modified entity is using AsNoTracking when doing Find method like this:
HiringFactor parentFactor = db.HiringFactors.AsNoTracking().Find(parentId);

Similar issues:
An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key
An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key


text:
Q: PHP str_replace exceptions I have some customer data that i convert from CSV to json using a php script.
once converted the data is all jumbled together, like this:
[{"Customer Number":"12345","Customer Name":"customer 1","Address Code":"PRIMARY","Salesperson ID":"aa","Ship to Address 1":"12345","Ship to Address 2":"123, fake street","Ship to Address 3":"","Ship to City":"Toronto","Ship to Province":"ONTARIO","Ship to Postal Code":"A1A 1A1","Country Code":"CA","Ship to Country":"CANADA","Ship to Contact Person":"John Doe","Ship to Phone":"416-555-5555","Ship to Fax":"416-555-5552","Shipping Method":"OUR TRUCK","Bill to Address 1":"12345","Bill to Address 2":"123, fake street","Bill to Address 3":"","Bill to City":"Toronto","Bill to Province":"ONTARIO","Bill to Postal Code":"A1A 1A1","Bill to Phone":"416-555-5555","Tax Schedule ID":"HST ON/S","Location Code":"TOR","Payment Terms ID":"30 DAYS PD CHEQUE","Credit Limit Amount":"2,000.00","Comment1":"30D PDC /10/11-NSF=WR BK ACCT","Comment2":"","Hold":"1","Price List":"EASTGEN"}]
.
I then use some str_replace to organize the output and make the it look nice. here's what i have:
$newArray = str_replace(":",": ",json_encode($newArray));
$newArray = str_replace("[","[\n",$newArray);
$newArray = str_replace("{","{\n",$newArray);
$newArray = str_replace(",",",\n",$newArray);
$newArray = str_replace("},","\n},",$newArray);
$newArray = nl2br($newArray);
.
the problem i'm having is that the output appears like this:
[
{
"Customer Number": "12345",
"Customer Name": "customer 1",
"Address Code": "PRIMARY",
"Salesperson ID": "aa",
"Ship to Address 1": "12345",
"Ship to Address 2": "123,
fake street",
"Ship to Address 3": "",
"Ship to City": "Toronto",
"Ship to Province": "ONTARIO",
"Ship to Postal Code": "A1A 1A1",
"Country Code": "CA",
"Ship to Country": "CANADA",
"Ship to Contact Person": "John Doe",
"Ship to Phone": "416-555-5555",
"Ship to Fax": "416-555-5552",
"Shipping Method": "OUR TRUCK",
"Bill to Address 1": "12345",
"Bill to Address 2": "123,
fake street",
"Bill to Address 3": "",
"Bill to City": "Toronto",
"Bill to Province": "ONTARIO",
"Bill to Postal Code": "A1A 1A1",
"Bill to Phone": "416-555-5555",
"Tax Schedule ID": "HST ON/S",
"Location Code": "TOR",
"Payment Terms ID": "30 DAYS PD CHEQUE",
"Credit Limit Amount": "2,
000.00",
"Comment1": "30D PDC /10/11-NSF=WR BK ACCT",
"Comment2": "",
"Hold": "1",
"Price List": "EASTGEN"}]
Please notice Ship to Address 2 , Bill to Address 2 , and Credit Limit Amount. because of my str_replace it added a line break there. the problem is that the app i use that reads the json needs it on the same line to register properly. is there a way that i can replace the comma's with a line break UNLESS they are part of an address or another variable?

A: Why are you modifying a JSON-encoded string? If you're just trying to make it look "pretty", then you should use json_encode($str, JSON_PRETTY_PRINT) - don't do any other modifications to the string.


text:
Q: better word for "feed him" What would be a good substitute word for the term "feed him"? Suppose you have a new employee in your office who happens to be from your own village (or the place you grew up in). Your another colleague, who is also from the same place, wants to give this new guy a treat. So, I was asking my colleague, "Why do you want to feed him?". But I don't feel good about this. It should be, "why do you want to take him out for a lunch?" or something like that. What should be a good sentence for this kind of conversation.

A: "Feed him" is a phrase you might use for animals, small children, and unwanted guests, so you are right to want something more polite.  Some better options:

Where should we take him to eat?
Where can we all go to lunch?
What kind of food do you think he likes?
Where do you think he'd like to go to eat?
Do you think he'd like [X] food?

As well as others.  Please take note that something like:

What kind of food do you think he eats?

is also not at all polite.

A: You have different alternatives as follows, depending on the context:

Why do you want to take him out to lunch/dinner?
Why do you want to take him out for a meal?
Why do you want to give him lunch/dinner/a meal?


text:
Q: Missing entry point in my C#/C++ interoperability I work on my program, which I need for my bachelor work(C#/C++ interoperability) and I have problem with missing entry point in my code... I try create simply number generator, which will be genarated number in C++ class calling from C# ... At first I don't know how I pass a class, but then I found way how to do it on this page... Please help me fix it...
I added my code:
[C++]
#include <iostream>
#include <cstdlib>
#include <time.h>

using namespace std;

__declspec(dllexport) class Generator
    {
private:
    int zaciatok;
    int koniec;
    int pocetprvkov;
    int *pole;
public:
      Generator(){}

      void Vytvor (int zaciatok, int koniec, int pocetprvkov)
    {
         srand((unsigned)time(0));
         pole= new int [pocetprvkov];
    }

       void Napln()
    {
        for(int a=0; a<pocetprvkov; a++)
          {
              pole[a] = rand() % (koniec - zaciatok +1) + zaciatok;
         }
    }
       void Vypis()
    {
        for(int a=0; a<pocetprvkov; a++)
        cout << pole[a] << endl;
    }

      ~Generator()
       {
           delete[] pole;
           pole= 0;
       }

    };

extern "C"
{
 __declspec(dllexport) Generator* Vytvor_Triedu() { return new Generator(); }
 __declspec(dllexport) void Vytvor(Generator* prva) {prva->Vytvor(5,25,4); }
 __declspec(dllexport) void Napln(Generator* prva) {prva->Napln(); }
 __declspec(dllexport) void Vypis(Generator* prva) {prva->Vypis(); }
 __declspec(dllexport) void Vymaz(Generator* prva) { delete prva; }
}

[C#]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.InteropServices;

namespace GeneratorCsharp
{
    class Program
    {
        [DllImport("DllTriedaGenerator.dll", CallingConvention = CallingConvention.Cdecl)]
        public static extern IntPtr Vytvor_Triedu();

        [DllImport("DllTriedaGenerator.dll", CallingConvention = CallingConvention.Cdecl)]
        public static extern void Vytvor(IntPtr value);

        [DllImport("DllTriedaGenerator.dll", CallingConvention = CallingConvention.Cdecl)]
        public static extern void Napln(IntPtr value);

        [DllImport("DllTriedaGenerator.dll", CallingConvention = CallingConvention.Cdecl)]
        public static extern void Vypis(IntPtr value);

        [DllImport("DllTriedaGenerator.dll", CallingConvention = CallingConvention.Cdecl)]
        public static extern void Vymaz(IntPtr value);

        static void Main(string[] args)
        {
            IntPtr trieda = Vytvor_Triedu();
            Vytvor(trieda);
            Napln(trieda);
            Vypis(trieda);
            Vymaz(trieda);

        }
    };
}

Thanks a lot!

A: Well, you should use dumpbin, find the mangled name of your function then add EntryPoint="yourMangledName" in your DllImport attribute.


text:
Q: TFS - API page not found I am trying to acces some source files. I need to get a list of the files to acces. I would like to use the CodeSearch function of the TFS Rest API. All I get is a page not found error.
I have searched all over the internet for TFS 2017 API documentation, but I always end up here, I can not find any TFS 2017 - specific documentation.
I think its similar problem to what this question was about.
I am successfully retrieving the source code by sending a GET request on to
.eu/Development/_apis/tfvc/items?path=%24%2FProjectName%2FFileName%2FMain%2SubFolder%2FGetRandomArticle.cs
but when I try to send a POST request on to
.eu/Development/_apis/search/codesearchresults?api-version=4.1-preview.1
I get a 401 "Page not found."
This is thetest request body:
{
     "searchText": "IEnumerable",
     "$skip": 0,
     "$top": 1,
}

A: According to the official docs, the version 4.1-preview1 of the REST API is not present in TFS 2017. Thus, the behavior you're observing might be because the incorrect version of the API is used. Try switching to 3.0 and try again.
If you follow this link, you'll find out how to explore the pre-4.1 REST API.


text:
Q: DGrid Selection/selectionMode Not Working in AccordionContainer I am using a custom dgrid w/Selection, DijitRegistry and Pagination that I add to a ContainerPane in an AccordionContainer (dojo 1.9), code below. Data populates properly, and I have set the idProperty of the store I use to a unique identifier (numerical id's). However, I cannot select a row in my grid; it seems the entire grid area beneath the headers gets selected. Any suggestions?
Code:
    registry.byId("calAccordion").addChild(new dijit.layout.ContentPane({
        id: "allCalPane",
        title: "All Calendars"
    }), "first");
    var CustomGrid = declare([Grid, Selection, DijitRegistry, Pagination]);
    var grid = new CustomGrid({
        store: calStore,
        id: "allCalGrid",
        columns: {
            last: "Last Name",
            first: "First Name"
        },
        selectionMode: "single"
    });
    registry.byId("allCalPane").addChild(grid);
    grid.on("dgrid-select", function(event) {
        console.log(event.rows[0].data);
    });
    registry.byId("calAccordion").selectChild(registry.byId("allCalPane"), false);

A: Could you break it out into a simple but complete runnable example for me to test on my system? I'm currently putting a dgrid into a SplitContainer without issue, so I'm up to speed on what you are trying to do.


text:
Q: Beamer xelatex images not show % Created 2019-11-13 Wed 10:48
% Intended LaTeX compiler: xelatex
\documentclass[presentation]{beamer}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{graphicx}
\usepackage{grffile}
\usepackage{longtable}
\usepackage{wrapfig}
\usepackage{rotating}
\usepackage[normalem]{ulem}
\usepackage{amsmath}
\usepackage{textcomp}
\usepackage{amssymb}
\usepackage{capt-of}
\usepackage{hyperref}
\usepackage{xeCJK}
\setCJKmainfont{Source Han Serif CN}
\setCJKsansfont{Source Han Serif CN}
\setCJKmonofont{Cascadia Code}
\usetheme{Boadilla}
\date{2019-11-12}
\title{ImageTest}
\author{Jilen} % BAD ORDER XXX
\hypersetup{
 pdfauthor={Jilen Jilen},
 pdftitle={ImageTest},
 pdfkeywords={},
 pdfsubject={},
 pdfcreator={Emacs 27.0.50 (Org mode 9.2.6)},
 pdflang={English}}
\begin{document}

\maketitle

\begin{frame}[label={sec:org407d30b}]{Beamer image test}
\begin{center}
\includegraphics[width=.9\linewidth]{foo.png}
\end{center}
\end{frame}
\end{document}

This beamer presentation is exported by org-mode.
But the image is not show.
I tried both png/jpeg/bmp, no lucky.
Log related to image
File: """foo".png Graphic file (type bmp)
<"""foo".png>
 [2

]

Version: This is XeTeX, Version 3.14159265-2.6-0.999991 (TeX Live 2019/Arch Linux) (preloaded format=xelatex)

A: It seems there is something wrong with the grffile package [1]. Org-mode inserts it by default. Apparently it is fixed in the new release of the package (which only loads graphicx) but I also haven't received the update containing it.  I opted for removing grffile from org-latex-default-packages-alist.
[1] https://github.com/ho-tex/grffile/issues/7


text:
Q: How to do a simple GraphQL query in a native Ruby script I'm trying to figure out how to do a simple GraphQL query without using gems. The following cURL commands works
curl -X POST "https://gql.example.com/graphql/public" \
  -H "Authorization: Bearer <ACCESS_TOKEN>" \
  -H "Content-Type: application/json" \
  -d '{ "query": "query { user { id defaultEmail } }", "variables": {} }'

and the corresponding javascript code is
fetch('https://gql.example.com/graphql/public', {
  method: 'POST',
  headers: {
    'Authorization': 'Bearer <ACCESS_TOKEN>',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    query: 'query { user { id defaultEmail } }',
    variables: {}
  })
})
.then(r => r.json())
.then(data => console.log(data));

Is it possible to do this easily in Ruby without using the graphql gem? I only need to do simple queries like the examples above so I'm hoping it's easy to do them in a single Ruby script.

A: You can use Ruby core lib Net/HTTP and build your requests like so:
require 'net/http'
uri = URI('https://gql.example.com/graphql/public')
params = {'query': 'query { user { id defaultEmail } }', 'variables': {} }
headers = {
    "Authorization'=>'Bearer #{ENV['MY_ACCESS_TOKEN']}",
    'Content-Type' =>'application/json',
    'Accept'=>'application/json'
}

https = Net::HTTPS.new(uri.host, uri.port)
response = https.post(uri.path, params.to_json, headers)

See this answer as well


text:
Q: What IDE to use? I come from Linux and Windows programming is fairly new to me. On linux, I used to use vim and the command line and everything worked fine, even for large projects. However, on windows, the command line seems a lot more cumbersome and I hear that lots of devs use IDEs. The question is, what do I use (C++ here)? What does everyone usually use? VC++? I've read about Eclipse, how is the C++ support for it? I have used Netbeans for Java and I absolutely love it, is the C++ support upto par? Also, Netbeans seems to need make for windows, which is a pain to set up, is there a good alternative?

A: I don't think you can get an objective answer to a question as general as this.  Different people have different experiences with different IDEs, and opinions are subjective.
My best advice is to be lazy.  If the tools you are used to using do a good (or even half good) job, then don't change.  The real point of an IDE is to get the job done effectively.  Spending lots of time evaluating, setting up, going through the learning curves, switching back and forth doesn't get the job done.

A: If you are moving to doing development for windows, VC++ is a very good IDE, and arguably the best for pure windows development, I perfer eclipse though, mainly so that I have a single IDE that I use no matter what platform I'm on (Windows, Linux, and Mac).
The C++ support is execlent with the latest eclipse and CDT (C/C++ Development Tools) versions so that shouldn't be much of a problem.
I never have been that happy using Netbeans, but that is personal taste I think.

A: I generally use Eclipse for Java and love it, have had no problems.  The intellisense is great and the automatic formatting works perfectly.
Currently I am using Visual Studio for C# and C++ but it leaves much to be desired in terms of performance, so I too am looking for a new solution there.

A: I thought Netbeans used Ant for build scripts, but I could be wrong. It's been a long time.
I use Visual Studio and find it's a fairly nice IDE with decent command line for build scripts, etc.

A: You might want to take a look at CodeBlocks.  It is the IDE I used for C++ to make the transition.  Worked well for me.

A: It depends. :-)
Are you moving to Windows "permanently", or just creating a new port? You can continue to use your old tools, if you work on several platforms.
Otherwise, VC++ is the native compiler for Windows. Obviously the one Microsoft uses for compiling Windows itself. The source code debugger is very well integrated with the rest of the IDE, and supports downloading debug info for the system binaries as well. Can be very useful.

A: For Java irrespective of the OS you are using, I highly recommend IDEA IntelliJ. There is also an open source "Community Edition" now which is quite cool.

A: i think if you used to use vim and command line in linux u'll find anything in Windows OS is so simple comparing with vim and command line so i thinkmit's so easy for u to convert to any IDE in Windows but i think it's better to use the native IDE for C++ by Microsoft itself not to use any other IDE from any another company because as i think the biggest advantage in Microsoft is its Support for its products and u can find easily tutorials and documentation easily


text:
Q: Using JRebel for non webapp projects I have a non-web app maven project which relies on Kafka which is my message queue. now in order to do computation on incoming messages I need to run 4 JAR files concurrently. How can I use JRebel in this case so I can change my code and I don't have to recompile those JAR files every time and run it again?
Any help would be appreciated.

A: Easiest is to setup JRebel using an IDE. JRebel has plugins for IntelliJ, Netbeans and Eclipse all of which can also set up IDE run configurations automatically.
However, it's also possible to prepare your jar-s with JRebel maven plugin.
If you want to run your JAR-files from command-line then IDE plugins contain instructions in JRebel settings > Startup > Run using CLI > Standalone application. Alternatively, you can find more general CLI instructions here.


text:
Q: What is the difference between a real vs. a linear factor within the realm of complex numbers? When you factorise something like 243z^5 + 32 = 0, how would you determine the real factors after finding the roots of the equation? What makes it a real factor?

A: Real factor of a function of order $n$ means $a_0+a_1x+a_2x^2+\cdots+a_rx^r$ where $a_i$s  are real and $1\le r<n$
We have
$(3z)^5-(-2)^5=0$
Now $x^5-1=(x-1)(x^4+x^3+x^2+x+1)$
What if $x-1=0$
Else use Quadratic substitution question: applying substitution $p=x+\frac1x$ to $2x^4+x^3-6x^2+x+2=0$


text:
Q: Quotient of Jacobson ring is Jacobson as in Eisenbud I wanted to prove the following:

Let $R$ be a Jacobson ring, $\mathfrak{p}<R$ a (prime) ideal. Then $R/\mathfrak{p}$ is Jacobson.

The statement has been taken from Eisenbud's Commutative Algebra with a View Towards Algebraic Geometry, p. 132 in the proof of lemma 4.20.
I want to prove it with what I have available there, hence:

A ring $R$ is Jacobson if $$\mathfrak{p}=\bigcap_{\substack{\mathfrak{m}\in\max(R)\\ \mathfrak{p}\subseteq\mathfrak{m}}}\mathfrak{m}\quad\forall \mathfrak{p}\in \operatorname{prime}(R)$$ where $\max(R)$ is the collection of maximal ideals and $\operatorname{prime}(R)$ is the collection of prime ideals in $R$.

We have to show that $\mathfrak{q}\in\operatorname{prime}(R/\mathfrak{p})$ implies $\mathfrak{q}=\bigcap_{\mathfrak{m}\in\max(R/\mathfrak{p}), \mathfrak{q}\subseteq \mathfrak{m}}\mathfrak{m}$. Let $\mathfrak{r}:=\bigcap_{\mathfrak{m}\in\max(R),\pi^{-1}(\mathfrak{q})\subseteq\mathfrak{m}}\pi(\mathfrak{m})$. In what follows I denote by $\pi:R\to R/\mathfrak{p}$ the canonical projection. I used the following claim:

Let $R$ be a ring, $\mathfrak{p}<R$ an ideal (not necessarily prime), $\mathfrak{m}$ a maximal ideal containing $\mathfrak{p}$, then $\pi(\mathfrak{m})$ is a maximal ideal and $\pi$ yields a bijection between maximal ideals containing $\mathfrak{p}$ in $R$ and ideals in $R/\mathfrak{p}$.

$$\begin{align*}\pi^{-1}(\mathfrak{r})=&\bigcap_{\substack{\mathfrak{m}\in\max(R)\\\pi^{-1}(\mathfrak{q})\subseteq\mathfrak{m}}}\pi^{-1}(\pi(\mathfrak{m}))\\ =&\bigcap_{\substack{\mathfrak{m}\in\max(R)\\\pi^{-1}(\mathfrak{q})\subseteq\mathfrak{m}}}\mathfrak{m}\qquad\text{(as of the 1-1 correspondence)}\\
=&\pi^{-1}(\mathfrak{q})\qquad\text{(as $\pi^{-1}(\mathfrak{q})< R$ is prime and $R$ is Jacobson)}\end{align*}$$
Because $\pi(\mathfrak{m})$ is an ideal for every $\mathfrak{m}\in\max(R)$ such that $\mathfrak{p}\subseteq\mathfrak{m}$ by the 1-1 correspondence, so is $\mathfrak{r}$ and as of the 1-1 correspondence between maximal ideals containing $\mathfrak{q}$ and maximal ideals containing $\pi^{-1}(\mathfrak{q})$, $\mathfrak{r}=\bigcap_{\mathfrak{m}\in\max(R/\mathfrak{p}),\mathfrak{q}\subseteq\mathfrak{m}}\mathfrak{m}$.
Thus the 1-1 correspondence implies $\mathfrak{r}=\mathfrak{q}$.
Question: does this make sense? Is this correct reasoning? Thank you!

A: What you have written doesn't quite make sense (though these may just be typos): if $\mathfrak{r}:=\bigcap_{\mathfrak{m}\in\max(R),\pi^{-1}(\mathfrak{q})\subseteq\mathfrak{m}}\mathfrak{m}$, then
$\pi^{-1}(\mathfrak{r})$ is not $\bigcap_{\substack{\mathfrak{m}\in\max(R)\\\pi^{-1}(\mathfrak{q})\subseteq\mathfrak{m}}}\pi^{-1}(\pi(\mathfrak{m}))$. Also, note that for any maximal ideal $\mathfrak{m}$ of $R$, $\pi^{-1}(\pi(\mathfrak{m})) = \mathfrak{m}$ always holds. As an alternative way to view the Jacobson condition, consider the following:
$\DeclareMathOperator{nil}{nil}
\DeclareMathOperator{rad}{rad}$
Proposition: Let $\nil(R)$ be the nilradical of $R$ (i.e. intersection of all primes), $\rad(R)$ the Jacobson radical of $R$ (i.e. intersection of all maximal ideals). The following are equivalent:
i) $R$ is Jacobson
ii) $\nil(R/I) = \rad(R/I)$ for every ideal $I$
iii) $\nil(R/p) = \rad(R/p)$ for every prime $p$
The implications (i) $\implies$ (ii) and (iii) $\implies$ (i) follow immediately from the correspondence of primes and maximal ideals in the quotient (try proving this carefully!). Once this characterization is shown though, the property of being Jacobson is seen to pass to any quotient, since any quotient of $R/p$ is still a quotient of $R$.

A: there is some nice reference on this topic you may want to have a look:
https://en.wikibooks.org/wiki/Commutative_Algebra/Jacobson_rings_and_Jacobson_spaces
For a solution in the "self-contained" way as you want:
Let $p$ be a prime in $R/I$, and it can be pulled back to the unique prime $P$ in $R$. Denote $\pi$ the canonical projection from $R$ to $R/I$. We also assume that
\begin{equation}
P = \cap M_{\alpha} \text{ ,where $M_{\alpha}$ is maximal.}
\end{equation}
Then we have the following:
\begin{equation}
p=\pi(\pi^{-1}(p))
=\pi(P)=\pi(\cap M_{\alpha})=\cap \pi (M_{\alpha})
\end{equation}
It's worth noticing that the last equality doesn't hold in general.
In this case, the nontrivial direction holds since
\begin{equation}
\forall y \in\pi(\cap M_{\alpha}),\forall \alpha, (y+ I)\subset M_{\alpha}+I
\end{equation}
This leads to $y=x_{\alpha}+i_{\alpha}$ ,where $x_{\alpha} \in M_{\alpha}$ and $i_{\alpha} \in I$
So $ \forall \alpha , y\in M_{\alpha} $


text:
Q: Where is the messaging menu in 12.10? All of a sudden, after the volume slider disappeared, now the messaging menu has disappeared too!
after the last update, now the messaging menu does not show anything written!
here is a screenshot-

its all that can be seen! now how do i get it back?


text:
Q: Exception while loading data from Mysql in spark i am getting the below exception while running spark code to fetch the data from MYsql. can soneone please help.
code is below
    private static final String MYSQL_CONNECTION_URL = "jdbc:mysql://localhost:3306/company";
    private static final String MYSQL_USERNAME = "test";
    private static final String MYSQL_PWD = "test123";

    private static final SparkSession sparkSession =
            SparkSession.builder().master("local[*]").appName("Spark2JdbcDs")
                       .config("spark.sql.warehouse.dir", "file:///tmp/tmp_warehouse")
                       .getOrCreate();

    public static void main(String[] args) {
        //JDBC connection properties
        final Properties connectionProperties = new Properties();
        connectionProperties.put("user", MYSQL_USERNAME);
        connectionProperties.put("password", MYSQL_PWD);

        Dataset<Row> jdbcDF = sparkSession.sql("SELECT * FROM emp");

        List<Row> employeeFullNameRows = jdbcDF.collectAsList();

        for (Row employeeFullNameRow : employeeFullNameRows) {
            LOGGER.info(employeeFullNameRow);
        }

16/09/23 13:17:55 INFO internal.SharedState: Warehouse path is 'file:///tmp/tmp_warehouse'.
16/09/23 13:17:55 INFO execution.SparkSqlParser: Parsing command: SELECT * FROM emp
Exception in thread "main" java.lang.UnsupportedOperationException: Not implemented by the DistributedFileSystem FileSystem implementation
    at org.apache.hadoop.fs.FileSystem.getScheme(FileSystem.java:217)
    at org.apache.hadoop.fs.FileSystem.loadFileSystems(FileSystem.java:2624)
    at org.apache.hadoop.fs.FileSystem.loadFileSystems(FileSystem.java:2624)
    at org.apache.hadoop.fs.FileSystem.getFileSystemClass(FileSystem.java:2634)
    at org.apache.hadoop.fs.FileSystem.createFileSystem(FileSystem.java:2651)
    at org.apache.hadoop.fs.FileSystem.access$200(FileSystem.java:92)
    at org.apache.hadoop.fs.FileSystem$Cache.getInternal(FileSystem.java:2687)
    at org.apache.hadoop.fs.FileSystem$Cache.get(FileSystem.java:2669)
    at org.apache.hadoop.fs.FileSystem.get(FileSystem.java:371)
    at org.apache.hadoop.fs.Path.getFileSystem(Path.java:295)
    at org.apache.spark.sql.catalyst.catalog.SessionCatalog.makeQualifiedPath(SessionCatalog.scala:115)
    at org.apache.spark.sql.catalyst.catalog.SessionCatalog.createDatabase(SessionCatalog.scala:145)
    at org.apache.spark.sql.catalyst.catalog.SessionCatalog.(SessionCatalog.scala:89)
    at org.apache.spark.sql.internal.SessionState.catalog$lzycompute(SessionState.scala:95)
    at org.apache.spark.sql.internal.SessionState.catalog(SessionState.scala:95)
    at org.apache.spark.sql.internal.SessionState$$anon$1.(SessionState.scala:112)
    at org.apache.spark.sql.internal.SessionState.analyzer$lzycompute(SessionState.scala:112)
    at org.apache.spark.sql.internal.SessionState.analyzer(SessionState.scala:111)
    at org.apache.spark.sql.execution.QueryExecution.assertAnalyzed(QueryExecution.scala:49)
    at org.apache.spark.sql.Dataset$.ofRows(Dataset.scala:64)
    at org.apache.spark.sql.SparkSession.baseRelationToDataFrame(SparkSession.scala:382)
    at org.apache.spark.sql.DataFrameReader.jdbc(DataFrameReader.scala:238)
    at org.apache.spark.sql.DataFrameReader.jdbc(DataFrameReader.scala:194)
    at sparksql.sparksql1.main(sparksql1.java:40)
below is pom file
    <!-- Hadoop Mapreduce Client Core -->
    <dependency>
        <groupId>org.apache.hadoop</groupId>
        <artifactId>hadoop-mapreduce-client-core</artifactId>
        <version>2.7.1</version>
    </dependency>

    <dependency>
        <groupId>org.apache.hadoop</groupId>
        <artifactId>hadoop-common</artifactId>
        <version>2.7.1</version>
    </dependency>

    <!-- Hadoop Core -->
    <dependency>
        <groupId>org.apache.hadoop</groupId>
        <artifactId>hadoop-core</artifactId>
        <version>1.2.1</version>
    </dependency>

    <!-- Spark  -->
    <dependency>
        <groupId>org.apache.spark</groupId>
        <artifactId>spark-core_2.10</artifactId>
        <version>2.0.0</version>
    </dependency>

    <!-- Spark SQL  -->
    <dependency>
        <groupId>org.apache.spark</groupId>
        <artifactId>spark-sql_2.10</artifactId>
        <version>2.0.0</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.20</version>
    </dependency>

A: You have added both hadoop-core and hadoop-common in pom.xml.
Remove hadoop core and try it


text:
Q: Unsure on how to show the featured page as my homepage I am creating a Ghost Theme and I want to have my index.hbs show the featured post as the page. I have tried a range of things but nothing seems to work:
index.hbs
{{!< default}}
{{!-- The tag above means: insert everything in this file
into the {body} of the default.hbs template --}}

{{!-- The main content area --}}
<main>
{{#foreach posts}}
  {{#has featured="true"}}
      {{post}}
  {{/has}}
{{/foreach}}
</main>

A: I think the best way to achieve having a featured post as the main page would be to use Dynamic Routing and route / to the post or page with featured flag. Alternatively, you could fetch and display the featured post using the {{get}} query described here.


text:
Q: implementacion de una vista en SQL en base a una consulta Tengo un error que no sé cómo solucionar.
Quiero implementar una vista, erp.v_imp_pend sobre la consulta que muestro a continuación:
código de la CONSULTA:
SELECT c.co_code, c.co_name, p.cust_no, p.cust_name, i.iva_amount, i.tot_amount
FROM (erp.tb_invoice AS i JOIN erp.tb_company AS c ON c.co_code = i.co_code)
JOIN erp.tb_customer AS p ON c.co_code = i.co_code
WHERE i.payed = 'N'
ORDER BY c.co_name, c.co_code DESC;

En esta consulta lo que quiero hacer es proporcionar una lista de facturas pendientes por cobrar.
Muestro el código de la VISTA que he planteado:
CREATE OR REPLACE VIEW erp.v_imp_pendiente AS
SELECT *
FROM (erp.tb_invoice AS i JOIN erp.tb_company AS c ON c.co_code = i.co_code)
JOIN erp.tb_customer AS p ON c.co_code = i.co_code
WHERE i.payed = 'N'
ORDER BY c.co_name, c.co_code DESC
WITH CHECK OPTION;

El error mostrado es el siguiente:
ERROR:  WITH CHECK OPTION sólo puede usarse en vistas automáticamente actualizables
HINT:  Las vistas que no extraen desde una única tabla o vista no son automáticamente actualizables.

Las tablas a emplear son las que muestro:

tb_invoice
tb_company
tb_customer

Code – foreign key company
Code – primary key
Cust_no

Invoice_id – primary key
Name
cust_name

Invoice_no
Address
cust_cif

Cust_no - foreign key customer
City
Last_updated_by

Site_id- foreign key site
Country
Last_update_date

Payednet_amount
Last_updated_by

Iva_amount
Last_update_date

Tot_amount

Last_updated_by

Last_update_date

No soy capaz de entender qué está fallando. Solo puedo emplear una tabla para hacer la vista actualizable? (pregunta en base al HINT)
Gracias por la aclaración.

A: tl;dr: Quítale el WITH CHECK OPTION. Te dio pereza crear la vista sin eso y probar. Si lo pruebas en tu vista que tiene un JOIN, no te va a dejar hacer insert ni update porque esa es la configuración de la BD para esas vistas que usan JOIN. NO USES WITH CHECK OPTION y ya.
Versión larga:
El primer camino siempre debe ser leer ese log y leer la documentación oficial.
De acuerdo a la documentación, es claro el conjunto de condiciones para una vista actualizable:
The view must have exactly one entry in its FROM list, which must be a table or another updatable view.

The view definition must not contain WITH, DISTINCT, GROUP BY, HAVING, LIMIT, or OFFSET clauses at the top level.

The view definition must not contain set operations (UNION, INTERSECT or EXCEPT) at the top level.

The view's select list must not contain any aggregates, window functions or set-returning functions.

Que en español de la calle se traduce más o menos como:
La vista debe tener exactamente UNA entrada en su cláusula FROM, que debe ser una tabla u otra vista actualizable.

La definición de la vista no debe contener cláusulas WITH, DISTINCT, GROUP BY, HAVING, LIMIT u OFFSET en el nivel principal de la consulta (no incluye subconsultas, mejor dicho).

La definición de la vista no debe contener operaciones de conjunto (UNION, INTERSECT o EXCEPT) en el nivel principal.

La lista de campos en el SELECT no debe contener agregados, _window functions_ o funciones-que-retornen-conjuntos.

No cumples la primera condición.
Por qué quieres usar WITH CHECK OPTION en este escenario? Efectivamente, esta condición de la vista evita que los usuarios inserten o modifiquen datos directamente en la vista que no puedan verse en ella. Si tienes más de una tabla generando la vista, el motor no es capaz de validar este comportamiento porque ese JOIN no es una vista actualizable.
Edito: para tu segunda pregunta, hay que seguir leyendo la misma documentación oficial. Piensa que son tus colegas tratando de hacer lo mismo que tú, avisándote de los peligros en el camino ;)
Si revisas en la sección de Vistas actualizables, dice

A more complex view that does not satisfy all these conditions is read-only by default: the system will not allow an insert, update, or delete on the view

Que, de nuevo, en español de la calle en Colombia, es más o menos

Una vista más compleja que no cumpla con las condiciones es de sólo-lectura por defecto: el sistema (o sea, PostgreSQL) no va a permitir inserciones, actualizaciones o borrados en la vista.

Así pues, por qué no comienzas por probar creando la vista común y corriente e intentando luego tú mismo un insert para ver qué pasa? (Debería salir un error o si no, ¡encontraste un bug!)


text:
Q: How to add a LinearLayout after another LinearLayout? I created this layout:
<!-- create_structure.xml -->
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/ly_create_structure"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
</LinearLayout>

and this other
<!-- add_level_in_structure.xml -->
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/ly_level"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/txt_num"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="1#"
        android:layout_weight="1"/>

    <EditText
        android:id="@+id/edit_sb"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:inputType="number"
        android:layout_weight="3">
        <requestFocus />
    </EditText>

    <ImageButton
        android:id="@+id/add_level"
        android:scaleType="fitXY"
        android:layout_width="48dip"
        android:layout_height="48dip"
        android:cropToPadding="false"
        android:paddingLeft="10dp"
        android:src="@drawable/ic_menu_add" />
 </LinearLayout>

I wanto to add programmatically the LinearLayout.ly_level in LinearLayout.ly_create_structure after the click "Add level" in alertDialog (each level in LinearLayout.ly_level has a link to show an alertDialog).
The code is:
public class CreateStructureActivity extends Activity {

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.create_structure);

        addLevel();
    }

    private void addLevel() {
        LinearLayout mainActivityLayout = (LinearLayout)findViewById(R.id.ly_create_structure);
        LayoutInflater li = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        LinearLayout ly = (LinearLayout) li.inflate(R.create_structure, null);

        ImageButton ib = (ImageButton) ly.findViewById(R.id.add_level);

        ib.setOnClickListener( new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDialog();

            }
        });

        mainActivityLayout.addView(ly);
    }

    private void showDialog() {
        final CharSequence[] items = {"Add Level", "Delete"};
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Actions");

        builder.setItems(items, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int item) {

                switch(item){
                    case 0:
                        addLivello();
                    break;

                    case 1:
                        delete();
                    break;
             }
                }
            });

        AlertDialog alert = builder.create();
        alert.show();
    }
}

With this code I can to add a LinearLayout as the last, but I want to add it after the LinearLayout that contains the button clicked to show an AlertDialog. Could you help me to implement this?
UPDATE 1:
I can't understand how to get the index. I trying in this way:
private void addLevel() {
        LinearLayout mainActivityLayout = (LinearLayout)findViewById(R.id.ly_create_structure);
        LayoutInflater li = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        LinearLayout ly = (LinearLayout) li.inflate(R.create_structure, null);

        ImageButton ib = (ImageButton) ly.findViewById(R.id.add_level);

       /**
         * New code to get index
         */
        ViewGroup vg = (ViewGroup) ib.getParent();
        int index = mainActivityLayout.indexOfChild(vg);

        ib.setOnClickListener( new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDialog();

            }
        });

        mainActivityLayout.addView(ly, index);
    }

UPDATE 2:
I solved the problem. I moving the code below in showDialog()
ViewGroup vg = (ViewGroup) ib.getParent();
int index = mainActivityLayout.indexOfChild(vg);

A: You can use method at Dev Android
which takes index of view in parameter as well.
private void addLevel(int index) {
        LinearLayout mainActivityLayout = (LinearLayout)findViewById(R.id.ly_create_structure);
        LayoutInflater li = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        LinearLayout ly = (LinearLayout) li.inflate(R.create_structure, null);

        ImageButton ib = (ImageButton) ly.findViewById(R.id.add_level);

        ib.setOnClickListener( new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDialog();

            }
        });

        mainActivityLayout.addView(ly, index);
    }

A: Good,
First of all, you will get the view object and then create linearlayout object as you are make in the our current code and add viewObject.addView("linearlayout object");. I think, this is help full to you..


text:
Q: APK Can't Install on Any Mobile enter image description hereI developped an Android Mobile Application, and extract APK fro Android studio but when I send APK to other Mobiles ,, a Message display message say cannot install this APK ..Could anyenter image description hereone help me where is the Problem and how to solve it ?

A: You don't give any detail information. So I guess...

*

*minSDK - 24 / real device - 21 -> You can not install.
you should check your minSDK from your build.gradle.

*appropriate building : menu -> Build -> Build APK.
then you can find your APK from "YourProject\app\build\outputs"

A: Try to install you APK on the same device that you can already run your app from android studio, if there'll be an error then generate your apk correctly, or if there'll be no errors then it should be from device version, change you minSDK version from gradle
try to change minSdkVersion 15

A: Usually this occurs when there is an unchecked runtime error in the code or if the compile version is different from the Mobile.
Also you should check your AndroidManifest to see if here maybe a services used in the code that are not requisitioned in the manifest file


text:
Q: How do I terminate an asynchronous starmap multiprocessing pool in python once any process has encountered an error I'm using the starmap_async function from Python's multiprocessing library. However, I noticed that if my code encounters an error in one of the processes, the exception is not thrown until all processes have finished. Here's the relevant code:
from multiprocessing import Pool, cpu_count
import datetime
import itertools
import time

       with Pool(max(cpu_count()//2, 1)) as p:
            #p = Pool()
            df_iter = df_options.iterrows()
            ir = itertools.repeat
            results = p.starmap_async(_run,zip(df_iter,ir(fixed_options),ir(outputs_grab)), chunksize=1)
            p.close() #no more jobs to submit

            #Printing progress

            n_remaining = results._number_left + 1
            while (not results.ready()):
                time.sleep(1)
                #Check for errors here ... How ????
                #Then what? call terminate()?????
                if verbose:
                   if results._number_left < n_remaining:
                      now = datetime.datetime.now()
                      n_remaining = results._number_left
                      print('%d/%d  %s' % (n_remaining,n_rows,str(now)[11:]))

            print('joining')
            p.join()

            all_results = results.get()

        df = pd.DataFrame(all_results)

Currently if I raise an error in the spawned processes it appears that other processes not only finish running, but start new tasks despite there being an error from one of the calls.
Some searching is leading me to believe that this may not be possible. One person seemed to suggest I might need to use concurrent.futures instead, although it is unclear how to map my example to that example, especially with keeping the real time feedback as processes finish.
discussion of concurrent.futures: https://stackoverflow.com/a/47108581/764365

A: tldr; Use imap_unordered to have the smallest latency to the main process knowing about a child throwing an exception as it allows you to process results in the main process as soon as they come in via the results Queue. You can then use a wrapper function to build your own "star" version of the function if you desire. As a point of code design, most Pool methods tend to re-raise exceptions from the child whereas concurrent.futures tends to set an attribute of the return value to indicate the exception that was raised.
from random import random
from functools import partial
from multiprocessing import Pool
from time import sleep

def foo(a, b):
    sleep(random()) #introduce some processing delay to simulate work
    if random() > .95:
        raise Exception("randomly rasied an exception")
    else:
        return f"{a}\t{b}"

def star_helper(func, args):
    return func(*args)

if __name__ == "__main__":
    n = 20
    print("chance of early termination:", (1-.95**n)*100, "%")
    with Pool() as p:
        try:
            for result in p.imap_unordered(partial(star_helper, foo), zip(range(n), range(n))):
                print(result)
        except:
            p.terminate()
            print("terminated")
    print("done") # `with Pool()` joins the child processes to prove they quit early


text:
Q: IVR-style dialog system / workflow / menu I need to build a dialog system similar to IVR used in call centers. My system is not phone-based, but the dialog is similar. Something like
System: "Main menu: Enter [1] for menu1, [2] for menu2"
User: [1]
System: "menu1: enter [1] for apples, [2] for oranges, [3] for main menu"
User: [7]
System: "What??"
System: "menu1: enter [1] for apples, [2] for oranges, [3] for main menu"
User: [2]
    ... and so on

I want to have a nice declarative description of all the possible options and a nice way to run through that tree, guided by user input.
Already considered: ANTLR-generated lexer/parser (seems to be an overkill), SCXML-based state machine (seems like only transitions can be declared, the rest needs to be coded)

A: I've never seen SCXML before, but after a short glimpse on the project pages and the examples, it looks to me like it has everything you need. Your IVR can be modeled as a state diagram. Entering a state either presents the next choices or starts an activity (while presenting the next menu level is an activity too).
It might be tricky to implement a 'wrong user input' state (or SCXML already has a solution for this common task).
You could invent a small DSL to simplify editing this statemachine. Documents written in this DSL would be translated to SCXML files that would drive the IVR system.
(thanks for the SCXML pointer!)


text:
Q: mod_rewrite debugging shows unexpected REWRITE_COND order of events I noticed something unexpected when debugging rewrite rules: it seems that the order of events is that Apache processes a rule, and then retroactively applies the preceding conditions to it. Is this as-designed, or am I misinterpreting something?
Here's a simple example of a rewrite rule in my .htaccess file. It doesn't really do anything useful -- it's just an example.
    RewriteEngine on
    Options FollowSymLinks
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . / [L]

And here is the resulting trace (heavily redacted for readability)
[...redacted...] init rewrite engine with requested uri /test.html
[...redacted...] pass through /test.html
[...redacted...] [perdir /var/www/html/] strip per-dir prefix: /var/www/html/test.html -> test.html
[...redacted...] [perdir /var/www/html/] applying pattern '.' to uri 'test.html'
[...redacted...] [perdir /var/www/html/] RewriteCond: input='/var/www/html/test.html' pattern='!-f' => not-matched
[...redacted...] [perdir /var/www/html/] pass through /var/www/html/test.html

Notice that "RewriteCond" gets applied after the pattern gets applied. The ultimate result is a pass-through, which is correct (since the file does, in fact exist), so it doesn't really matter. I couldn't find anything about this in the documentation.

A:
it seems that the order of events is that Apache processes a rule, and then retroactively applies the preceding conditions to it. Is this as-designed, or am I misinterpreting something?

Yes, that is how it works.
The RewriteRule has to match first. Only if that is the case, the RewriteCond-itions are evaluated. If these then match, the rewrite is performed.
This is not so clearly mentioned on the manual page that describes the syntax for RewriteCond and -Rule; https://httpd.apache.org/docs/2.4/mod/mod_rewrite.html#rewritecond just says,

The following rule is then only used if both the current state of the URI matches its pattern, and if these conditions are met.

Now you could imply the processing order from this maybe (if you read it in "logical" order, left to right), but it is not very explicit.
But https://httpd.apache.org/docs/2.4/rewrite/intro.html#regex says,

Regex Back-Reference Availability
One important thing here has to be remembered: Whenever you use parentheses in Pattern or in one of the CondPattern, back-references are internally created which can be used with the strings $N and %N (see below). These are available for creating the Substitution parameter of a RewriteRule or the TestString parameter of a RewriteCond.
Captures in the RewriteRule patterns are (counterintuitively) available to all preceding RewriteCond directives, because the RewriteRule expression is evaluated before the individual conditions.

(Highlight at the end by me.)
So in that place you find this behavior explicitly mentioned.


text:
Q: Python dict.setdefault uses more memory? I was writing some Python code that involved something like this
values = {}
for element in iterable:
    values.setdefault(element.name, []).append(element)

Because I could have sorted the input previously, I also implemented it like this
values = {}

cur_name = None
cur_list = None

for element in iterable:
    if element.name != cur_name:
        values[cur_name] = cur_list
        cur_name = element.name
        cur_list = []
    cur_list.append(element)
if cur_list:
    values[cur_name] = cur_list
del values[None]

Here the input is already sorted by element.name.
The second approach was much faster than the first approach, and it also used less memory.
What's the reason for this?
Or have I made some sort of mistake in the second approach?

A: Your original code every time round the loop will create a list that mostly then just gets thrown away. It also makes multiple dictionary lookups (looking up the method setdefault is a dictionary lookup and then the method itself does a dictionary lookup to see whether the object was set and if it isn't does another to store the value). .name and .append() are also dictionary lookups but they are still present in the revised code.
for element in iterable:
    values.setdefault(element.name, []).append(element)

The revised code only looks up the dictionary when the name changes, so it it removes two dictionary lookups and a method call from every loop. That's why it's faster.
As for the memory use, when the list grows it may sometimes have to copy the data but can avoid that if the memory block can just be expanded. My guess would be that creating all of those unused temporary lists may be fragmenting the memory more and forcing more copies. In other words Python isn't actually using more memory, but it may have more allocated but unused memory.
When you feel a need for setdefault consider using collections.defaultdict instead. That avoids creating the list except when it's needed:
from collections import defaultdict
values = defaultdict(list)
for element in iterable:
    values[element.name].append(element)

That will probably still be slower than your second code because it doesn't take advantage of your knowledge that names are all grouped, but for the general case it is better than setdefault.
Another way would be to use itertools.groupby. Something like this:
from itertools import groupby
from operator import attrgetter
values = { name: list(elements) for name,elements in
    groupby(elements, attrgetter('name')) }

That takes advantage of the ordering and simplifies everything down to a single dictionary comprehension.

A: I can think of a couple of reasons why the second approach is faster.
values.setdefault(element.name, []).append(element)

Here you're creating an empty list for each element, even if you're never going to use it. You're also calling the setdefault method for every element, and that amounts to one hash table lookup and a possible hash table write, plus the cost of calling the method itself, which is not insignificant in python. Finally, as the others have pointed out after I posted this answer, you're looking up the setdefault attribute once for each element, even though it always references the same method.
In the second example you avoid all of these inefficiencies. You're only creating as many lists as you need, and you do it all without calling any method but the required list.append, interspersed with a smattering of dictionary assignments. You're also in effect replacing the hash table lookup with a simple comparison (element.name != cur_name), and that's another improvement.
I expect you also get cache benefits, since you're not jumping all over the place when adding items to lists (which would cause lots of cache misses), but work on one list at a time. This way, the relevant memory is probably in a cache layer very near the CPU so that the process is faster. This effect should not be underestimated -- getting data from RAM is two orders of magnitude (or ~100 times) slower than reading it from L1 cache (source).
Of course the sorting adds a little time, but python has one of the best and most optimized sorting algorithms in the world, all coded in C, so it doesn't outweigh the benefits listed above.
I don't know why the second solution is more memory efficient though. As Jiri points out it might be the unneccessary lists, but my understanding is that these should have been collected immediately by the garbage collector, so it should only increase the memory usage by a tiny amount -- the size of a single empty list. Maybe it's because the garbage collector is lazier than I thought.

A: Your first version has two inefficient parts:

*

*calling and dereferencing values.setdefault in a loop. You can assing values_setdefault = values.setdefault before the loop and it can speed things up a bit.

*as other answer suggested, creating new empty list for every element in your list is very slow and memory inefficient. I do not know how to avoid it and using setdefault at once.


text:
Q: Error initializing complex filters. No such filter: '' in ffmpeg I installed ffpmeg through terminal with the following command:
sudo apt-get install -y mjpegtools
I ran into an error after trying to run the following command:
ffmpeg -y -i 1676476701.mp3  -filter_complex ";[0:a]asetpts=PTS-STARTPTS,afade=t=out:st=63:d=5[afadedMusic];[segmentsAudio][afadedMusic]amix,asplit=2[mergedAudio][mpgAudio];, format=yuv420p,split=2[video][mpgVideo]" -map [video] -threads 16 -map "[mergedAudio]" -t 68 test.mp4 -map [mpgVideo] -threads 16 -map [mpgAudio] -target ntsc-dvd -aspect 16:9 -t 68 /home/artyst/projects/video-api/efs/assets/20230221212507_6353_6383_final_0_4X5fB1ejS2/deliverables/converted/video.mpg;
I get an error as:
[AVFilterGraph @ 0x5620b8bf8680] No such filter: ''
Error initializing complex filters.
Invalid argument

My ffmpeg version is 4.4.2-0
I am a new beginner with ffpmeg and i only need it to have a project running for work. I am not able to figure out what filter is causing this.


text:
Q: How to get from an R data.table to a list of matrices I have the following data.table:

How can I transform it into a list of matrices, where for each MV value, I have 3 matrices (consumption, dailySd and isAbsentBool) containing the elements of each time period (there are 178 periods in total):

A: use lapply
lapply(as.list(unique(DF$mv)), function(x){return(as.matrix(DF[(mv==x), list(consumption, dailySd, period)]))})

first argument of lapply is unique list of mv values, second argument is a function that filters data.table, keeps relevant columns and convert it to matrix. lapply automatically loops over the list and returns list

A: Another way of writing this using data.table::split:
lapply(
    split(DT, by="mv", keep.by=FALSE),
    function(DT) DT[, as.matrix(.SD),
        .SDcols=c("consumption", "dailySd", "isAbsentBool")]
)

data:
library(data.table)
DT <- data.table(consumption=c(10,10,50,70),
    dailySd=c(1,2,3,4),
    isAbsentBool=c(0,0,0,0),
    mv=c("A.V1", "A.V1", "A.v2", "A.V3"),
    period=c(1,2,3,4))


text:
Q: How can I create a sparse matrix as a list of lists? (C++) The question is: Is it possible to create a sparse matrix using the following sparse list implementation? In special, using a class template with a class template (SparseList*>)?
I've created a class template named SparseList where I can add elements in whatever index I want.
I'd like to use it to create a SparseMatrix class template. So I tried the following...
//SparseMatrix.h

template <typename T>
class SparseMatrix {
    public:
        SparseMatrix();

    private:
        SparseList<SparseList<T>*> *matrix;
};

template <typename T>
SparseMatrix<T>::SparseMatrix() {
    matrix = new SparseList<SparseList<T>*>();
}

But when I try to instantiate it on main...
int main() {
    SparseMatrix<int> *matrix;
    matrix = new SparseMatrix<int>(); //without this line it compiled normally.

    return 0;
}

I got the following error...
In file included from src/main.cpp:
SparseMatrix.h:   instantiated from 'SparseMatrix<T>::SparseMatrix() [with T = int]'
main.cpp:   instantiated from here
SparseList.h: error: template argument required for 'struct SparseMatrix'

I'm using NetBeansIDE 6.9.1 with MinGW.
EDIT:
//SparseList.h
template <typename T>
class SparseList {

    template <typename U>
    friend std::ostream & operator<<(std::ostream &output, const SparseList<U> &list);

public:
    SparseList();
    virtual ~SparseList();

    void insert(T &entry, int index);
    T & get(int i);
    int length();

private:
    struct ListNode {
        int index;
        T *entry;
        ListNode *next;
    };

    ListNode *head; //pointer to the first entry in the sparse list.
    int size; //# of entries.
};

I already tested inserts and gets, constructors and destructors, everything in the SparseList. Working fine... =)

A: Why all the pointers?
This should do the job as your data storage inside your class:
std::map<std::pair<I, I>, T>

Where I is your index type (e.g. int) and T is your number type (e.g. double).
Or you could just use compressed_matrix from boost::ublas.


text:
Q: Visual Studio C# String to double without parse My teacher expects me to my project without "functions like ToString". I don't want to chance it and use parse, so is there a way to send a string to double? I am making a calculator.
    private void btnln_Click(object sender, EventArgs e)
    {
        if (Store.Length > 0) //Check if store is longer than 0
        {
            double x = double.Parse(Store); //Put store into a double
            Store = ""; //Clear store
            Store += Math.Log(x); //Natural logarithm
            lblNumbers.Text = Store; //Update numbers label
        }
    }

So I would like the line
double x = double.Prase(Store);
to be replaced


text:
Q: JQuery image swap inside a div I'm trying to achieve something similar to this.
The image will be coming from a feed url,  I'm unsure of how to prevent each of them opening up in a new window, here is what I have so far:
Javascript:
jquery/1.3.2/jquery.min.js

HTML

     1 Day
     5 Days
     1 Month

Please help!
Thanks!

A: Try adding a line to your JavaScript to test and see if it will add the paragraph tag. If it does, you may instead have a problem with the the urls for your images instead of with the code here.
jQuery(function($){
    $('#more-views a').click(function(){
        $('#main-image p').fadeOut('slow').delay(2000).remove();
//-------v add this line for testing
        $('#main-image').append('
' + $(this).attr('href') + '
);

        $('#main-image').append('');
        $('#main-image p').fadeIn('slow');
        return false;
    });
});

==Less Old==
Ok, I think I understand your problem now.  Instead of having your  tags have a href attribute, use a data attribute instead.
So your anchor tag should look like this:
image1

And then you will need to replace two of your JavaScript lines:
$('#main-image').append('<img src="' + $(this).attr('href') + '" alt="" style="display:none;" />');

Becomes:
$('#default-market-chart').append('');

And, you will have to replace all instances of #main-image in your JavaScript with #default-market-chart, since you don't seem to have an element with and id of main-image
==Old==
Try replacing the < and > with < and >, so that your web page will treat the string you are giving it as an HTML tag, and not just a string.


text:
Q: Can not access the javax.servlet.error.* for error code 500 in JSF 2.2 with PrimeFaces 5.1 I am working on JSF 2.2 with PrimeFaces 5.1, in my application for exception handling I have configured error code 500 in web.xml like below
<error-page>
    <error-code>500</error-code>
    <location>/500.xhtml</location>
</error-page>

and in 500.xhtml I am trying to access error code like below
<h:outputText  value="#{requestScope['javax.servlet.error.status_code']}"></h:outputText>

at the time of testing I found that, I was redirected to a url like below
https://localhost:8443/appname/500.xhtml
which is wrong it should like https://localhost:8443/appname/configerd_path
and here I found that in requestScope I don't have javax.servlet.error.*
so I cannot display error code, error message and so on ...
I would like to ask here that, what is the best practice to handle this kind of error in JSF 2.2 and how can I access error code and error message ?

A: As I am using primefaces and it's provides a built-in exception handler to take care of exceptions in ajax and non-ajax request easily.
with the following EL, I am able to catch exception at my 500.xhtml page.
<h:outputText value="#{pfExceptionHandler.exception}" ></h:outputText>
<h:outputText value="#{pfExceptionHandler.type}"></h:outputText>
<h:outputText value="#{pfExceptionHandler.message}" ></h:outputText>

I hope it helps others :-)


text:
Q: Creating new aggregated R dataframes with a function in lapply I want to create new aggregated dataframes from existing ones that are collected in a list. Ideally they would appear as their own dataframes indicated by a prefix. This is where I've got:
dfList <- list(A = data.frame(y = sample(1:100), x = c("grp1","grp2")),
               B = data.frame(y = sample(1:100), x = c("grp1","grp2")))

agrFun <- function(df){
    prefix <- deparse(substitute(df))
    assign(paste0(prefix,"_AGR"),
           aggregate(y ~ x, data = df, sum))
}

lapply(seq_along(dfList), function(x) agrFun(dfList[[x]]))

Aggregation happens as intended but I'm not sure what I need to do otherwise in order to create dataframes A_AGR and B_AGR.
EDIT:
A bit of clarification. I want to have the aggregated dataframes appear in the environment.
So instead of this

ls()
  [1] "agrFun" "dfList"

my goal is to have

ls()
  [1] "A_AGR" "B_AGR" "agrFun" "dfList"

EDIT2:
Or more ideal would be to have dfList include dataframes A, A_AGR, B and B_AGR after the process.
EDIT3:
And I also want to preserve the names of the dataframes.

A: Your way to do seems extremely complicated. You can create the wanted named data.frames in a list with this one liner:
setNames(lapply(dfList, function(u) aggregate(y~x, u, sum)), paste0(names(dfList),"_AGR"))

#$A_AGR
#     x    y
#1 grp1 2340
#2 grp2 2710

#$B_AGR
#     x    y
#1 grp1 2573
#2 grp2 2477

With your function agrFun:
lst = setNames(lapply(dfList, function(x) agrFun(x)), paste0(names(dfList),"_AGR"))

If you want to append the two lists:
dfList = append(lst, dfList)