Configuring ASP.NET MVC2 on Apache 2.2 using mod_aspdotnet

Question: Trying to get an Microsoft MVC2 website to run on Apache 2.2 web server (running on Windows) that utilizes the mod_aspdotnet module. Have several ASP.NET Virtual Hosts running, trying to add another. MVC2 has NO default page (like the first version of MVC had e.g default.aspx). I have tried various changes to the config: commented out 'DirectoryIndex', changed it to '/'. Set 'ASPNET' to 'Virtual', will not load first page, always get: '403 Forbidden, You don't have permission to access / on this server.'
Below is from my http.conf:
LoadModule aspdotnet_module "modules/mod_aspdotnet.so"
AddHandler asp.net asax ascx ashx asmx aspx axd config cs csproj licx rem resources resx soap vb vbproj vsdisco webinfo

<IfModule aspdotnet_module>

 # Mount the ASP.NET /asp application
 #AspNetMount /MyWebSiteName "D:/ApacheNET/MyWebSiteName.com"
 Alias /MyWebSiteName" D:/ApacheNET/MyWebSiteName.com"

 <VirtualHost *:80>
 DocumentRoot "D:/ApacheNET/MyWebSiteName.com"
 ServerName www.MyWebSiteName.com
 ServerAlias MyWebSiteName.com
 AspNetMount / "D:/ApacheNET/MyWebSiteName.com"

# Other directives here
  <Directory "D:/ApacheNET/MyWebSiteName.com">
    Options FollowSymlinks ExecCGI
    AspNet All
   #AspNet Virtual Files Directory
    Order allow,deny
    Allow from all
    DirectoryIndex default.aspx index.aspx index.html
   #default the index page to .htm and .aspx
  </Directory>
 </VirtualHost>

 # For all virtual ASP.NET webs, we need the aspnet_client files
 # to serve the client-side helper scripts.
 AliasMatch /aspnet_client/system_web/(\d+)_(\d+)_(\d+)_(\d+)/(.*) "C:/Windows /Microsoft.NET/Framework/v$1.$2.$3/ASP.NETClientFiles/$4"

 <Directory "C:/Windows/Microsoft.NET/Framework/v*/ASP.NETClientFiles">
   Options FollowSymlinks
   Order allow,deny
   Allow from all
 </Directory>

</IfModule>

Has anyone successfully run Microsofts MVC2 (or the first version of MVC) on Apache with the mod_aspdotnet module? Thanks !
Comment: What do you mean? If you have a Windows license, you're fully entitled to run IIS... there's no additional license needed.
Comment: I'm really curious here: if you're on Windows and if you want to run ASP.NET... why Apache instead of IIS?!?
Comment: Because IIS requires licenses, Apache is free.
Comment: XP Home does not come with IIS, Professional on up has it. Many business sites run ASP.NET applications on Apache (usually on Linux) to save costs.
Comment: Agreed. But I really don't see the point in doing that on a **Windows server**...
Comment: I second Massimo. When your application grows you anyway need to move it away from Windows XP Home as it is not a server OS. And with any Microsoft server OS you get IIS for free.
Comment: Could a reason for doing this be to, instead of having to install your shipped web based product into an existing iis installation, actually ship your product with a preconfigured web server? (Something we'r considering because of alot of hassle with supporting different IIS versions)
Answer: Enabling MVC apps on mod_aspdotnet is much easier than that. If you simply add
SetHandler asp.net

to your directory section in order to force all requests through the module. It behaves just like a wildcard mapping in IIS. Since this will process all requests, you'll want to make an exclusion for non-.Net content by adding a location section like this:
<Location ~ "^/MyWebSiteName/Content/.*"> SetHandler none </Location>

Where your Content directory contains all of your image files, css, etc. Alternatively you could write the rule to match a list of file extensions, but I find this easier. The added benefit to this is that you don't have to recode your apps.
One other issue that you may encounter is with MVC2 you may not have a default.aspx placehoder to handle your root requests. To deal with use mod_rewrite and added:
  RewriteEngine On
  RewriteBase /MyWebSiteName/
  RewriteRule ^$ Home [R=301]

to my directory configuration which forces redirects the / request to the Home controller.
Comment: Where were you 3 weeks ago when I needed you !  :-)

Switched over to your idea, removed the .mvc extensions.
Put SetHandler and RewriteEngine lines inside of . Put

 SetHandler None

inside of  Also, changed to 'RewriteBase /'
Removed 'mvc' from 'AddHandler' line, removed 'DirectoryIndex' line.

My way was causing asp.net to load the Script and Content files. Had to change/correct 'letter case' in all my paths, asp.net was not case sensitive like Apache is.

Works like a charm now, thank you, you BigWetDog!
Answer: A Answer
I am running XP Home with Apache 2.2.10 with NOSSL and MS SQL 2008 Express (Advanced). If you want to know how to get ASP.NET to run on Apache do this first.  What I discovered about MVC on web servers was from (http://www.asp.net/learn/mvc/tutorial-08-cs.aspx). (I am a new user and cannot submit with more that one hyperlink, go figure) I choose the .mvc extension option. Below is my configuration:
LoadModule aspdotnet_module "modules/mod_aspdotnet.so"
AddHandler asp.net mvc asax ascx ashx asmx aspx axd config cs csproj licx rem resources resx soap vb vbproj vsdisco webinfo
<IfModule aspdotnet_module>
 Alias /MyWebSite"D:/ApacheNET/MyWebSite.com"

<VirtualHost *:80>
 DocumentRoot "D:/ApacheNET/MyWebSite.com"
 ServerName www.MyWebSite.com
 ServerAlias MyWebSite.com
 AspNetMount / "D:/ApacheNET/MyWebSite.com"

# Other directives here
  <Directory "D:/ApacheNET/MyWebSite.com">
    Options FollowSymlinks ExecCGI
    #AspNet Files Directories Virtual
    AspNet All
    Order allow,deny
    Allow from all
    DirectoryIndex index.html
    #default the index page to .htm and .aspx
  </Directory>
</VirtualHost>

Added mvc to AddHandler above.
I changed the Default route in global.aspx:
routes.MapRoute(
                "HomeIndex",
                "default.mvc",
                new { controller = "Home", action = "Index" }
                );

routes.MapRoute(
                "Default",
                "{controller}.mvc/{action}/{id}",
                new { action = "Index", id = "" }
                );

Then I made a index.html file that re-directed the incoming root visitor to default.mvc. That's about it.


Finding the number of integers $(x_1,...,x_k)$ such that $1\leq x_1<x_2<\cdots<x_k\leq n$

Question: I got this problem:

Find the number of vectors in the set $S=\{(x_1,...,x_k)\in \Bbb{Z}^k| 1\leq x_i \leq n \land x_1<x_2<...<x_k\}$ where $1\leq k,n\in\Bbb{Z}$.
Answer: If $k>n$ it is clear that there are no elements in $S$. Assume therefore that $k\le n$. Now the numbers $(x_1,...,x_k)$ are just a subset of $(1,2,...,n)$, and the condition $x_1<x_2<...<x_k$ ensures that we don't need to worry about ordering. The number of elements in $S$ is then the number of ways of selecting $k$ objects from a collection of $n$ objects, which is simply $n\choose k$.
Comment: Thanks for the sentence "the condition $x_1<x_2<...<x_k$ ensures that we don't need to worry about ordering". Now I got it.
Comment: "We don't need to worry about ordering" - Does it mean that after we select $k$ numbers from $n$, there is only one way to put them in the desired order?


Java/Android - Plus minus button on a calculator

Question: This is not a duplicate. Unlike other StackOverflow questions, I don't want to display the result of the expression and then add a minus or plus sign. I want to turn the entire expression into negative or positive when pressed.
For example:
-(5*8+7/7)

or when +/- pressed again:
5*8+7/7

Here is what I have so far:
negative = !negative;

if (negative == true)
{
    expression = "-(" + expression + ")";
}
else
{
    expression = "+(" + expression + ")";
}

While this does work fine in terms of calculation, I am finding trouble figuring out how to create an intelligent way such that +( and -( do not keep getting appended to the expression.
Comment: Check if the first symbol is a `+` or `-` and then append?
Comment: The +( ... ) part is wrong in any case. It doesn't do anything (it should be a minus also in this case).
Answer: Keep the positive/negative state in a boolean and add the -(...) part when rendering. Otherwise you can match the beginning and and to match -( resp. ) and simply remove it. However, that will miss the simple case of -5. To cover all corners you will write quite some code. I would keep it as a separate state if possible.
Edit: Just want to add that the "proper" solution would be to parse the string and build a tree representing the expression (an AST) and detect if the outermost operator is a unary minus and simply remove it (or add it if it is not there), then check if the next operator are the parentheses and remove them (if you didn't just add the minus), and finally regenerate the string. But all this require quite some more work.
Answer: I think you can use two textfield include the expression, like [textfield A][expression][textfield B], and textfield A and textfield B can not be input from user, just only change when user press negative/positive button.
View will like:
-(  5*8+7/7  )

or

  5*8+7/7
Think this can help you.


How to pass in parameters for in clause that is in a stored procedure?

Question: How would I take this query that is in my stored procedure and pass in the correct parameters?
select * from Inventory
where category in (@categories) and qty > @qty and condition in (@conditions)

I seen that I should do something like this
CREATE PROCEDURE [dbo].[usp_DoSomethingWithTableTypedParameter]
(
    @categories categories READONLY
    @Qty int,
    @conditions
)

But how does the ADO.NET side look like? If I were to pass in for categories  'Tools', 'Hardware' and for conditions 'New', 'Used'.
How would I do this?
Comment: Thanks @DaleK , that's really useful :)
Comment: And don't use [addwithvalue](http://www.dbdelta.com/addwithvalue-is-evil/)
Comment: Do you have documentation for this, @DaleK ? Everything I've ever seen specifically on Table Value Parameters, including the the [documention](https://learn.microsoft.com/en-us/dotnet/framework/data/adonet/sql/table-valued-parameters#passing), uses `AddWithValue`.
Comment: Also, pretty sure that last link if a good duplicate candidate for this question. :)
Comment: yes qty would be a single value coming in and the rest of the conditions are in clauses. In my real query I probably will have a couple single value parameters coming in at the same time.
Answer: To add 3 further parameters to your SP, @Qty, @Category & @Condition you just duplicate the steps you've already taken.

Create any additional User Defined Table Types

Both @Category and @Condition need a UDT, @Qty doesn't as it is a native type.
Some people will prefer having a separate UDT each for @Category and @Condition, personally given they both take the same datatype I create a single general purpose utility UDT e.g.
CREATE TYPE [dbo].[udt_ShortString] AS TABLE
(
    [Value] [varchar](128) NULL
)

Modify the SP e.g.

CREATE PROCEDURE [dbo].[usp_DoSomethingWithTableTypedParameter]
(
    @UserIdList udt_UserId READONLY
    , @CategoryList udt_ShortString READONLY
    , @ConditionList udt_ShortString READONLY
    , @Qty int
)
AS

Add the values to your command object, where you load the new datatables exactly the same as you are already loading your existing userId table e.g.

cmd.Parameters.Add(new SqlParameter("@UserIdList", System.Data.SqlDbType.Structured) { TypeName = "udt_UserId", Value = userIdList });
cmd.Parameters.Add(new SqlParameter("@CategoryList", System.Data.SqlDbType.Structured) { TypeName = "udt_ShortString", Value = categoryList });
cmd.Parameters.Add(new SqlParameter("@ConditionList", System.Data.SqlDbType.Structured) { TypeName = "udt_ShortString", Value = conditionList });
cmd.Parameters.Add(new SqlParameter("@Qty", SqlDbType.Int) { Value = qty });

Note: For clarity I have hardcoded the parameter names and type names in - you are of course free to pass them as variabled as you were doing.
Comment: So, I will have to duplicate all the data for each "row" (maybe roleId, was a bad example as each user could have a different role). If I say had something like CreatedDate what I wanted to do a between range or if I had another "in" clause how would it be added to the row?
Comment: Ok, let me come up with an example.
Comment: ok, so I am not creating a separate Table scrip in the database? Also how and what am I populating in the data table?
Comment: I mean do I need to make something like? CREATE TYPE [dbo].[udt_UserId] AS TABLE
Comment: so would I make 3 parameters one for qty, one for category, one for condition?
Comment: Ah then I misunderstood what you were asking, all values in the where condition are coming in from the C# code.
Comment: Yes, it is starting to make more sense, I basically have to create a UDT for each parameter. That was what was tripping me up. As I thought I would have to make all the parameters. To be clear you are not using Datatables and dataRows correct? This was something else I thought you had to do as well.
Comment: You have to create a UDT for each distinct parameter type - I have a handful of common data combinations which I use.
Comment: Yes it still needs a datatable per UDT parameter, exactly as you are already loading the values into your userID parameter in C#. So you need 3 datatables now.
Comment: Ok, when I make the datatable what do I put for the data column?  I am not sure what it is being used for since you are using SqlParamater (I think maybe data column has a bigger use if you use AddWithValue)
Comment: Also is there a downside to use varchar(Max) otherwise I going to have to make a few of these just for different type sizes.
Comment: @chobo2 Your original datatable used `dt.Columns.Add("UserId", typeof(int));` for an int, so for a string you would use `dt.Columns.Add("UserId", typeof(string));` (There are .net/sql datatype conversions which you can google). There is no downside to using `varchar(max)` as you say its more versitle.
Comment: well what does the "column name" from the data table get used for if we are passing in a parameter?
Comment: @chobo2 At this point you're asking why does the sun shine :) the answer is Microsoft designed it that way. Under the hood the .NET framework has to convert the datatable you provide into an SQL data structure. I don't know how the internals work. I just know how you make use of it. Name the columns in your datatable the same as in your UDT and match the datatypes and it will work :)
Comment: I believe so - thats what works anyway. Its entirely possible it ignores the column name and just works on position - but I always name them consistently.


Approximation of Dirac measure by absolutely continuous measures (w.r.t. Lebesgue measure)

Question: Let $\mathcal{P}$ be the set of probability measures on the Borel $\sigma$ Algebra on the unit circle $S^1$.
Let $a\in S^1$ and $\delta_a$ the Diracmeasure in $a$.
I want to find a sequence $(\mu_n)_{n\in\mathbb{N}}\subset\mathcal{P}$ with $\mu_n\ll\lambda$ for all $n$, such that
$\mu_n\rightarrow\delta_a$, in the sense that $$\int_{S^1}fd\mu_n\rightarrow\int_{S^1}fd\delta_a$$ for every continuous $f$.
My thoughts so far: Since $\int_{S^1}fd\delta_a= f(a)$, I want to find a sequence of functions $(g_n)_{n\in\mathbb{N}}$, such that
$$\int_{S^1}fg_nd\lambda\rightarrow f(a)$$ for every continuous $f$.
Then I can define $\mu_n$ as $$\mu_n(E)=\int_E g_nd\lambda,$$ which satisfies $\mu_n\ll\lambda$ and
$$\int_{S^1}fd\mu_n=\int_{S^1}fg_nd\lambda\rightarrow f(a)=\int_{S^1}fd\delta_a.$$
I just have trouble finding such a sequence $(g_n)$. I would appreciate any help on that. Or maybe my approach isn't even the right way to go about this problem? Thanks in advance!
Answer: Let $a \in S^1$ be arbitrary point, and let $\delta_a$ be a probability measure on $(S^1,\mathcal B(S^1))$ (dirac measure).
You want to find sequence $(\mu_n)$ of probability measures on $(S^1,\mathcal B(S^1))$ that are absolutelly continuous (w.r.t Leb measure on $S^1$) and converge weakly (by probabilistic definition) to $\delta_a$ measure (because every continuous function on $S^1$ is bounded, by compactness). In other words, you want to find sequence $(X_n)$ of random variables, such that $\mu_n$ is distribution of $X_n$ and $X_n \Rightarrow X$ in distribution, where $X \sim \delta_a$.
We'll use two facts:

If $Y,Z$ are independent and $Y$ is absolutelly continuous w.r.t Leb measure, then $Y+Z$ is absolutelly continuous.

If $Y_n \to Y$ almost surely, then $Y_n \Rightarrow Y$ in distribution.

Let $Z$ be Uniformly distributed on $S^1$ and independent of $X \sim \delta_a$. Take $X_n = X + \frac{1}{n}Z$. Then by fact (1), we know that $X_n$ is absolutelly continuous. Moreover, since $||X_n - X|| = \frac{1}{n}||Z|| = \frac{1}{n} \to 0$, then $X_n \to X$ almost surely, so by fact (2), $X_n \to X$ in distribution. Hence $\mu_n \sim X + \frac{1}{n}Z$ is such a sequence of probability measures that are absolutelly continuous w.r.t Leb measure, that converges in the weak sense to $\delta_a$.
In other words, $\mu_n = \delta_a * \nu_n$, where $\nu_n$ is a distribution of $\frac{1}{n}Z$ which can be viewed as uniform distribution on $S^1(0,\frac{1}{n}) := \{ x \in \mathbb R^2 : ||x|| = \frac{1}{n} \}$


Concat RTL string with LTR string in javascript

Question: I'm facing trouble in concatenating Arabic string with English string but their order is being messed!
I tried + operator and str1.concat(..) but nothing works for me.
var a = 'english'
var b = 'أ.ب-000082-13'
var c = '000004-ر خ-2014.xml'

//var myCoolString =a + '\\' + b + '\\' + c;

var myCoolString =a.concat("\\",b,"\\",c)

document.getElementsByTagName('output')[0].innerHTML = myCoolString;

The result was like this: english\أ.ب-000082-13\000004-ر خ-2014.xml
Comment: May be helpful: http://stackoverflow.com/questions/6177294/string-concatenation-containing-arabic-and-western-characters .. however, are your numbers written LTR? you may find you have the direction changing within each string too
Answer: The characters your are looking for are \u202A, \u202B and \u202C
function wrap_dir(dir, str) {
    if (dir === 'rtl') return '\u202B' + str + '\u202C';
    return '\u202A' + str + '\u202C';
}

wrap_dir('ltr', a) + wrap_dir('ltr', '\\') + wrap_dir('rtl', b) + wrap_dir('ltr', '\\') + wrap_dir('ltr', c);
// "english\أ.ب-000082-13\000004-ر خ-2014.xml"

Not sure why c wanted to be LTR, maybe because it ends .xml?
Comment: Thanks Paul! I know this is an old thread and this answer works great but something I encountered that I would like to share with everyone. If anyone is planning to use the wrapped text in the browser URL make sure you escape the characters added in this function so it appears correctly. Thank you


Binding a state to another div after altered (VueJS)

Question: I'm using a slider from UIKit, which has no documentation on how to use their events. The slider's data is fed by an API with Vuex. I am using a v-for to iterate through the data and show that many slides. I also have another section in the site that needs to be updated depending on the slide with class="uk-active" (generated by UIKit). I bound an ID to the slides to make them unique. What am looking to do here is:

If slide has class uk-active, save its ID on a variable.
Once I have the ID captured according to the uk-active class, show the piece of state value called "number" that corresponds to that ID

template excerpt:

POD number here

  ... the data that gets looped ...

I tried to fetch the ID by className in the mounted lifecycle hook, but the classList was not recognized. The class changes on-off according to the slider changing, so perhaps its effect is in a different lifecycle. Either way, I couldn't figure it out.
I'm ok with a Vue solutions using directives or a Javascript solution as well.
JSFiddle
Comment: If I understand the problem correctly, your fiddle seems to already be doing what you're seeking (i.e., displaying `pods.number` corresponding to the active slider item). What am I missing?
Comment: @tony19 it does it within the v-for because the data is within scope. I need to access the populate the pods.number where it says "number here" which is outside of the v-for loop
Answer: Use Vue's string interpolation and event handling instead of DOM manipulation.
The UIKit slider's beforeitemshow event has an event-detail that indicates the item about to be shown, which also includes the item's index in the list. You could attach a beforeitemshow-handler to the uk-slider (1) that uses the item index to look up the corresponding ID in allPods (2).
To have the ID shown in the header div, add a data property to be interpolated in the template (3), initialize it in the mounted hook (4) (or in a watcher on allPods), and set that property when the item ID is determined in the event handler previously mentioned (5).

POD {{currentPodId}}

...

new Vue({
  el: '#app',
  data: {
    currentPodId: '', /* (3b) */
    allPods: [{ id: 'pod1' }, /* ... */]
  },
  mounted() {
    this.currentPodId = this.allPods[0].id /* (4) */
  },
  methods: {
    onItemShown(e) { /* (1b) */
      const shownItem = e.detail[0]
      this.currentPodId /* (5) */ = this.allPods[shownItem.index].id /* (2) */
    },
  }

updated jsfiddle
Comment: Thank you so much for this. Works exactly as I envisioned it. And I can see the logic in how you did it. Which will help me on other stuff I got going on. I do have a TypeError tho, but as long as it works, I'm not too worried.
`Error in mounted hook: "TypeError: Cannot read property 'id' of undefined"`
Comment: That likely means `allPods` is not yet populated by your Vuex store. In that case, use a watcher instead, so that the setting is not dependent on lifecycle hooks.


TouchableWithoutFeedback breaks ScrollView. How to fix without putting view inside ScrollView?

Question: I'm trying to get a TouchableWithoutFeedback wrapped ScrollView work.
In the real problem I'm unable to access the ScrollView.
Here's a working Expo Snack for easy testing.
And here's the code.
import * as React from 'react';
import {
  Text,
  View,
  StyleSheet,
  ScrollView,
  FlatList,
  TouchableWithoutFeedback,
} from 'react-native';
import Constants from 'expo-constants';
import LongText from './components/LongText';

export default class App extends React.Component {
  render() {
    return (
      <View style={{ flex: 1, paddingTop: Constants.statusBarHeight }}>
        {/* https://stackoverflow.com/a/46606223/25197
            BROKE on iOS
        */}
        <TouchableWithoutFeedback onPress={() => console.log('Pressed 2')}>
          <View style={[styles.container, { borderColor: 'red' }]}>
            <Text style={styles.label}>
              {'2) Touchable > View > View > ScrollView\n'}
              {' - iOS:          BROKE\n - Android: WORKING\n'}
            </Text>

            <View
              style={{ flex: 1 }}
              onStartShouldSetResponder={() => true}
              // onStartShouldSetResponderCapture={() => true}
              onResponderGrant={() => console.log('Granted View 2')}>
              <ScrollView
                style={{ flex: 1 }}
                keyboardShouldPersistTaps={true}
                onResponderGrant={() => console.log('Granted ScrollView 2')}>
                <LongText />
              </ScrollView>
            </View>
          </View>
        </TouchableWithoutFeedback>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    borderWidth: 5,
    flex: 1,
    justifyContent: 'center',
    backgroundColor: '#ecf0f1',
    padding: 8,
  },

  label: { fontWeight: 'bold' },
});

The ScrollView works as expected on Android.
How can I get it working on iOS?
In the real problem I'm unable to access the ScrollView.
Answer: Snack working link https://firstname.lastname@example.com/touchable-wrapped-scrollview
You should change this code
 <View
              style={{ flex: 1 }}
              onStartShouldSetResponder={() => true}
              // onStartShouldSetResponderCapture={() => true}
              onResponderGrant={() => console.log('Granted View 2')}>
              <ScrollView

Add onStartShouldSetResponder={() => true} to View instead of Scrollview
<ScrollView
                style={{ flex: 1 }}>
                <View  onStartShouldSetResponder={() => true}><LongText /></View>
              </ScrollView>

App Preview
Comment: Thanks for the response!
I **bolded** part of the question that makes the issue a little more difficult (It's also in the title). Thanks again for the response.


How to get high frame rate while using putpixel() in C?

Question: I was working with a code to print pixels.
// C code

#include <graphics.h>
#include <conio.h>

int main()
{
    int gd = DETECT, gm;

     initgraph(&gd, &gm, "C:\\TC\\BGI");

     for (int i = 0; i < 100; i++)
     {
         for(j = 0; j < 200; j++)
         {
             putpixel(i, j, GREEN);
         }
     }

     getch();
     closegraph();
     return 0;
}

Is there any way of achieving faster response from C compiler while using putpixel() in this code? The speed with which console gets colored with the execution of putpixel() is pretty slow, so I was wondering if there was any other library which I could use to speed up the printing pixel process on the screen using C on a windows system or a Linux one?
Comment: Welcome to Stack Overflow.  Question should not be requests for a library or software, as they can lead to spam and many opinion-based answers.
Comment: see [Graphics in C/C++](http://stackoverflow.com/a/21699076/2521214) as you are using BGI I cant help (did not use it for 2 decades) if you gonna use something more recent like GDI then simply create bitmap get the pointer to its lines and use them as any Array in C/C++. when done rendering copy the bitmap at once to visible area (like window,...) this is also called back buffering. But you are probably still using MS DOS environment so may be direct memory access + VESA will be better option if your OS does not limit your access to it
Comment: `putpixel()` is not a standard C function; you need perhaps to be clear about the toolchain and library you are using.  Are you using the genuine BGI library in a 16 bit Borland compiler (seems unlikely) or are you in fact using the WinBGIm Win32 emulation?  Either way it will be relatively slow, WinBGIm is no more that a BGI API wrapper to Win32 GDI under the hood.
Comment: Hi Clifford, I am using winBGIm Win32 one, not the genuine library.
Comment: Hi Spektre, Thank you. I"ll check that. What about this direct memory access + VESA, could you please give me an example or any link?
Answer: I'm afraid the answer is almost always going to be "don't use putpixel()".
The problem is that it requires a lot of work to achieve so little (a one-pixel change!) and you have to do it tens of thousands of times before you've done anything useful.
In an ideal world you might hope for it all to be inlined and optimised down to what you really need, but if putpixel() handles many different screen formats (and from what I remember of BGI, it does) then that would require highly improbable degrees of inlining and loop unswitching.
What you want to do is to find a more high-level operation, like putimage(), or in your simple example bar(), which can achieve more with a single function call.
You probably want to move to something more performance-oriented like SDL, but you'll still have the same fundamental problem if you try to use a function call for every single pixel.
Answer: putpixel() is pretty slow, no matter which framework or library you use. Try to create a bitmap and calculate the memory address of each pixel yourself.
Cross-platform frameworks that allow you to do such a thing are SDL and Allegro.
See also:

http://lazyfoo.net/SDL_tutorials/
Comment: Thanks Aaron. I don't have much experience in this field. Any example or link which should I refer while working on SDL? Another thing, without incorporating any cross platform framework, is there any way out for calculating memory address and printing a pixel?
Comment: Tutorials for SDL: http://lazyfoo.net/SDL_tutorials/ Direct access to memory is always hardware specific. There is no generic, cross-platform way to do that. But the main problem is to set up the graphics environment. That's thousands of lines of code - platform specific and on Linux, it depends on the distribution and the installed drivers and frameworks.
Comment: I suggest that you download the source for SDL and have a look to see how much effort it would be to "simply" create a graphics context to render into.


Incoherent post hoc pairwise Tukey test using beta binomial distribution and betareg()

Question: I am fitting a beta binomial regression to my data, which is proportion data (lifetime reproductive success ratio) ranging [0,1]. I transformed the 0s and 1s following Smithson and Verkuilen 2006 (y.(N-1)+0,5)/N) to fit the beta regression, as I have quite some zero and they are important datapoints which can not be discarded (See response variable (RAT) distribution after transformation and dotplot of datapoints across treatments below)

I fitted the model below:
mod1 <- betareg(RAT ~ treatment*exposure, data = lrs2)
hist(lrs2$RAT, breaks=20)
summary(mod1)
Anova(mod1, type=3)
par(mfrow=c(2,2))
plot(mod1)
AIC(mod1)
BIC(mod1)

And here is what came out of it:
> mod1 <- betareg(RAT ~ treatment*exposure, data = lrs2)
> hist(lrs2$RAT, breaks=20)
> summary(mod1)

Call:
betareg(formula = RAT ~ treatment * exposure, data = lrs2)

Standardized weighted residuals 2:
    Min      1Q  Median      3Q     Max
-5.8206 -0.3005  0.2031  0.6408  6.3900

Coefficients (mean model with logit link):
                       Estimate Std. Error z value Pr(>|z|)
(Intercept)             -0.8153     0.1228  -6.642  3.1e-11 ***
treatmentpc             -0.3720     0.1774  -2.097  0.03602 *
exposure1d               0.4516     0.1773   2.546  0.01088 *
exposure3d               0.4482     0.1711   2.619  0.00881 **
exposure7d               0.1035     0.1753   0.591  0.55481
treatmentpc:exposure1d   0.4941     0.2489   1.986  0.04707 *
treatmentpc:exposure3d   0.4812     0.2435   1.977  0.04809 *
treatmentpc:exposure7d   0.8268     0.2483   3.330  0.00087 ***

Phi coefficients (precision model with identity link):
      Estimate Std. Error z value Pr(>|z|)
(phi)   4.2043     0.2667   15.77   <2e-16 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Type of estimator: ML (maximum likelihood)
Log-likelihood: 97.24 on 9 Df
Pseudo R-squared: 0.08414
Number of iterations: 32 (BFGS) + 2 (Fisher scoring)
> Anova(mod1, type=3)
Analysis of Deviance Table (Type III tests)

Response: RAT
                   Df   Chisq Pr(>Chisq)
(Intercept)         1 44.1108  3.103e-11 ***
treatment           1  4.3964    0.03602 *
exposure            3 10.7253    0.01331 *
treatment:exposure  3 11.2268    0.01056 *
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
> par(mfrow=c(2,2))
> plot(mod1)
> AIC(mod1)
[1] -176.4816
> BIC(mod1)
[1] -140.1622

What I am most interested about is whether effect of treatment (pc/npc) is consistant or not across exposure times (1d, 3d, 7d, 14d).
Anova says it is quite so, with P=0.01, and this fits what the means + SE in red on the dotplot say, however when I run post hoc pairwise Tukey comparison, I get model estimates (obtained extracting LS.EM.MEANS of my betareg model) that really do not match what can be observed on the dotplot:
> lsmod1 <- lsmeans(mod1,
+                     pairwise ~ treatment*exposure,
+                     adjust="tukey")
>
> lsmod1
$lsmeans
 treatment exposure lsmean     SE  df asymp.LCL asymp.UCL
 npc       14d       0.307 0.0261 Inf     0.256     0.358
 pc        14d       0.234 0.0233 Inf     0.188     0.279
 npc       1d        0.410 0.0311 Inf     0.349     0.471
 pc        1d        0.440 0.0291 Inf     0.383     0.497
 npc       3d        0.409 0.0290 Inf     0.352     0.466
 pc        3d        0.436 0.0285 Inf     0.380     0.492
 npc       7d        0.329 0.0279 Inf     0.275     0.384
 pc        7d        0.436 0.0293 Inf     0.379     0.494

Confidence level used: 0.95

$contrasts
 contrast          estimate     SE  df z.ratio p.value
 npc,14d - pc,14d  0.073023 0.0347 Inf  2.104  0.4123
 npc,1d - pc,1d   -0.029837 0.0426 Inf -0.701  0.9970
 npc,3d - pc,3d   -0.026634 0.0406 Inf -0.656  0.9980
 npc,7d - pc,7d   -0.106898 0.0404 Inf -2.645  0.1399

P value adjustment: tukey method for comparing a family of 8 estimates

> x =emmeans(mod1, spec='treatment','exposure')
> summary(x)
exposure = 14d:
 treatment emmean     SE  df asymp.LCL asymp.UCL
 npc        0.307 0.0261 Inf     0.256     0.358
 pc         0.234 0.0233 Inf     0.188     0.279

exposure = 1d:
 treatment emmean     SE  df asymp.LCL asymp.UCL
 npc        0.410 0.0311 Inf     0.349     0.471
 pc         0.440 0.0291 Inf     0.383     0.497

exposure = 3d:
 treatment emmean     SE  df asymp.LCL asymp.UCL
 npc        0.409 0.0290 Inf     0.352     0.466
 pc         0.436 0.0285 Inf     0.380     0.492

exposure = 7d:
 treatment emmean     SE  df asymp.LCL asymp.UCL
 npc        0.329 0.0279 Inf     0.275     0.384
 pc         0.436 0.0293 Inf     0.379     0.494

Confidence level used: 0.95
> contrast(x, method='pairwise')
exposure = 14d:
 contrast estimate     SE  df z.ratio p.value
 npc - pc   0.0730 0.0347 Inf  2.104  0.0354

exposure = 1d:
 contrast estimate     SE  df z.ratio p.value
 npc - pc  -0.0298 0.0426 Inf -0.701  0.4832

exposure = 3d:
 contrast estimate     SE  df z.ratio p.value
 npc - pc  -0.0266 0.0406 Inf -0.656  0.5120

exposure = 7d:
 contrast estimate     SE  df z.ratio p.value
 npc - pc  -0.1069 0.0404 Inf -2.645  0.0082

If any within-exposure pairwise comparison were to be significant, I would expect it to be within 1d and within 14d, but here LS/EM means are telling me otherwise (and I clearly don't trust what they are telling me, it's nonsense)... Does it mean my beta regression is not ideal? Here comes the R plots of the betareg.

Thanks a lot for any help/suggestion/correction you could provide.
Quentin
EDIT:
RAW MEANS

MODEL ESTIMATES
Comment: I seem to recall that `car::Anova` isn't reliable with `betareg`.
Answer: Note that in both sets of comparisons, the estimates and standard errors for the comparisons within the same exposure match up. It is only the $P$ values that differ. The reason is that the $P$ values in the first set are adjusted for multiplicity, and the $P$ values in the second set are not.
The first set of EMM comparisons consists of ${8\choose2}=28$ pairwise comparisons, of which only 4 are shown in the posting. The Tukey correction adjusts the $P$ values for simultaneously testing these 28 comparisons, making them considerably higher than the unadjusted $P$ values.
In the second set of comparisons, we treat the means as 4 families of 2 comparisons, and hence no multiplicity adjustment. The $P$ values shown are thus the unadjusted $P$ values, which are those you would have obtained in the first set if you had specified adjust = "none".
I wonder if you noticed that the plot has the exposures in numerical order: 1d, 3d, 7d, 14d -- whereas the factor levels are alphabetized by default: 14d, 1d, 3d, 7d -- is that's the source of the confusion?
It's hard to see the intervals in the plot, and I wonder how they were computed. If computed using some other method than beta regression, then that implies a different model, so comparing those intervals with the intervals obtained using beta regression is like comparing apples and oranges. Remember, in this kind of data, not all observations have the same variance; those near .5 are more variable than those approaching 0 or 1.
Anyway, I disagree about these results being "nonsense."
Comment: Thank you for your answer and clarifying why P values are different. I am not sure which makes more sense in my case though; I would say without multicomparison adjustment as other comparisons are irrelevant to the ecological hypothesis I am interested in, right? The plot gives the factors in a different order because I re-ordered them, for the reader's convenience. The means and SE on the dotplot were calculated manually, and added the the dotlot afterwards. Shouldn't the model give me estimates that are somehow ressembling what the raw data says, if the model is a good fit?
Comment: I think the 4 focused comparisons are the way to go. The estimates DO resemble your manual calculations, don't they? But they won't be the same. I think for reporting purposes you should draw the dotplots and superpose the EMMs and their SEs.
Comment: I edited my original post and added the plots of raw means +-SE and model estimates +- SE. I am not sure how defendable the post hoc tests on model estimates will be, in regard to what the raw means +- SE show, it's a clearly different story. I am not even sure what conclusion to draw anymore.
Comment: These do look more different than one might expect. In the new plots, I think you mean to label the last group "14d", not "15d". Do you agree that the biggest discrepancies are associated with the situations having the most zero and 1 observations? That's the pattern I think I see. You say you transformed those 0s and 1s? In which computations? I'm thinking you probably should not transform any of the data you use in `betareg`. If you send me the data (maintainer e-mail for emmeans package), I promise not to distribute it to anyone, but could use it to check what emmeans is doing.
Comment: Try this: Set `grid = expand.grid(treatment = factor("npc","pc"), exposure = factor(c("14d","1d","3d","7d")))`. Then do `predict(mod1, newdata = grid, type = "response")` -- and I am pretty sure you will get exactly the estimates that `emmeans` shows. So if there is a problem, it is in the model, not in `emmeans`.
Comment: I used Smithson & Verkuilen (2006) to transform the data: y'= =(y*(N-1)+0,5)/N. I can not use betareg, or any other beta regression without transformation of the 0s and 1s, otherwise they get discarded by the model that only runs on the (0;1) interval. I agree with you on the fact that if anything is wrong, it must be with the model, which is maybe not the best fit for my data.. I tried the commands you just sent but R only gave me NAs.. Thanks for offering looking into it, I will get back to you if I am sure the model runs well, if need be to check what emmeans are doing
Comment: OK on the transformatikon. Make sure you use that for *all* the data, not just the 0s and 1s. On the `predict` thing, I can't imagine what went wrong. But try the same thing but define `grid <- emmeans(mod1,~treatment*exposure)@grid`; then `predict(mod1, new=grid, type = "response")`. `grid` just contains the 8 combinations of the two factors. There is no need for me to see the data as that's not where the problem is; but it is a saturated model for the fixed effects, so it ought to be better than just computing the means because it takes the beta structure into account.
Comment: ... However, since these are proportions, did you try just a generalized linear model? Something like `mod <- glm(RAT ~ treatment*exposure, weights=N, data=lrs2, family=binomial)` -- but `RAT` should be the actual ratios including 0s and 1s. That is, what's the reason for using beta regression rather than an ordinary GLM?
Comment: Thank you for the predict command; it seems to be working well now and provide the same estimates as emmeans.  I am using a beta binomial as I read it was a distribution well suited to fix overdispersion problems.  I first used `mod1 <- glm(cbind(WT,SPA)~exposure*treatment,family= "binomial", data=lrs2)`, as WT/SPA is actually the ratio I have calculated. The summary function gives me `Residual deviance: 19780  on 410  degrees of freedom`, that is why I switched to beta binomial models.


Least norm in convex set in Banach space

Question: The following statement is true for Hilbert spaces $H$:

Every closed convex set ${\cal C} \subset H$ has a unique element $x$ such that for any $y \in C$, we have $|x| \leq |y|$.

Is this statement still true for Banach spaces? If not, what is a counterexample?
Comment: $\mathcal C$ better be nonempty.
Answer: This is a bit too long for a comment. The question was answered by Jonas and Giuseppe. Let me add that a result sometimes called the Day-James theorem characterizes the spaces for which the statement in your question is true:

For a normed space $X$ the following are equivalent:

$X$ is strictly convex and reflexive (in particular $X$ is complete).
Every non-empty closed convex set in $X$ has a unique point of minimal norm.

See the discussion after the proof of Corollary 5.1.19 on page 436 of Megginson's book An introduction to Banach space theory.
The space in Giuseppe's answer is not strictly convex and the ones in Jonas's answer are neither strictly convex nor reflexive.
The question Distance minimizers in $L^1$ and $L^{\infty}$ could also be of interest to you.
Answer: Exercises 4 and 5 of Chapter 5 of Rudin's Real and complex analysis state:

4 Let $C$ be the space of all continuous function on $[0,1]$, with the supremum norm.  Let $M$ consist of all $f\in C$ for which $$\int_0^{1/2}f(t)\,dt-\int_{1/2}^1f(t)\,dt=1.$$  Prove that $M$ is a closed convex subset of $C$ which contains no element of minimal norm.
5 Let $M$ be the set of all $f\in L^1([0,1])$, relative to Lebesgue measure, such that $$\int_0^1f(t)\,dt=1.$$  Show that $M$ is a closed convex subset of $L^1([0,1])$ which contains infinitely many elements of minimal norm. (Compare this and Exercise 4 with Theorem 4.10.)

You can guess what Theorem 4.10 is.
Answer: The answer is no, in general. For a simple example consider the plane $\mathbb{R}^2$ equipped with the norm
$$\lVert (x, y)\rVert_{\infty}=\max(\lvert x\rvert, \lvert y\rvert).$$
Then consider the vertical segment $\{(x, y)\ :\ x=1,\ y\in[-1, 1]\}$.


gcloud auth activate-service-account needs access to .ssh folder?

Question: I run gcloud auth activate-service-account --key-file=pathtokey
then I run:
gcloud compute scp sdfsdfsdfsdf.txt myinst:/tmp --zone us-east1-b

And I get this error:
WARNING: The PuTTY PPK SSH key file for gcloud does not exist.
WARNING: The public SSH key file for gcloud does not exist.
WARNING: The private SSH key file for gcloud does not exist.
WARNING: You do not have an SSH key for gcloud.
WARNING: SSH keygen will be executed to generate a key.
open C:\Windows\system32\config\systemprofile\.ssh\google_compute_engine: The system cannot find the path specified.

i don't understand, why it need access to .ssh I just gave it the path to the key
Answer: There's a difference between the service account key and the SSH key used for an instance.
The service account key lets you access GCP. You need it to set up an SSH key.
The SSH key lets you log into a particular instance. You can only set one up if you have GCP access (for instance, via a service account key). But the SSH program works via SSH keys, so you'll need one set up.
You can change the location where the SSH key is written using the --ssh-key-file flag. See the documentation for gcloud compute ssh for more information.


Pegar ultimo valor de tabela do banco e mostrar no JTextField

Question: Tenho um programa aqui na fábrica que, a cada 1 minuto, um equipamento ligado a um supervisório lança um valor direto em uma tabela no banco de dados (SQL Server).
Gostaria de saber como faço para pegar sempre o último valor e mostrar em um JTextField, e a cada minuto ele tentar fazer essa consulta.
No caso, esse código me atende perfeitamente, mas a minha dúvida agora como faço para pegar o último valor do banco de dados que no caso seria (SQL Server).
    int delay = 5000;   // delay de 5 seg.
    int interval = 5000;  // intervalo de 1 seg.
    Timer timer = new Timer();

    timer.scheduleAtFixedRate(new TimerTask() {
        public void run() {
          jTextField6.setText("1");
        }
    }, delay, interval);
}

Comment: Sim, é possivel. O que você já fez?
Comment: @Articuno, Até o momento fiz apenas a alteração desses valores, para que a pessoa possa setar os valores de um equipamento de dentro do escritorio, mas para que isso fique leal, eu precisava trazer esse valor real pq o equipamento mesmo setando, ele nunca chega na temperatura ideal, pois ele sempre tem a variação.
Comment: No caso de java-swing, existe a classe [`swing.Timer`](https://docs.oracle.com/javase/9/docs/api/javax/swing/Timer.html) que provavelmente será a que você precisará usar. [**Neste link**](https://docs.oracle.com/javase/tutorial/uiswing/misc/timer.html) ensina como ela funciona e como usar, se você apresentar algo que já fez no formato de um **[mcve]**, posso demonstrar seu uso na prática.
Comment: No momento não tenho muito que te apresentar, é mais uma duvida e de que maneira posso começar.
Comment: Pois é, o problema é que a duvida se torna ampla da forma como está a pergunta, pois além dessa maneira que expliquei, existem inumeras outras que não cabe explicar todas aqui. Se você apresentar algo para exemplificar o que pretente em um **[mcve]**, fica mais facil sugerir algo mais especifico.
Comment: Blz, vou ver oq da pra fazer com o Timer, e caso tenha duvida recorro a vocês.
Comment: Não é essa a classe timer que você deveria usar. É a que deixei o link, pois se trata de interface gráfica.
Comment: Mas nesse caso se eu colocar uma tarefa para ele ir no banco e buscar a ultima informação daria certo também, não? ou poderia dar problemas futuros?
Answer: Se for utilizar a classe java.util.Timer, certifique-se de que o componente seja atualizado dentro da EDT, pois essa Thread é que deve ser a única responsável por gerenciar componentes da API swing:
int delay = 5000;   // delay de 5 seg.
int interval = 5000;  // intervalo de 1 seg.
Timer timer = new Timer();

timer.scheduleAtFixedRate(new TimerTask() {
    public void run() {
      SwingUtilities.InvokeLater(()-> jTextField6.setText("1"));
    }
}, delay, interval);

Lembrando que o tempo seja 1 minuto, o intervalo precisa ser 60*1000 pois o argumento que o método scheduleFixedRate() espera tanto o delay (atraso pra primeira execução) quanto o interval(tempo entre as repetições) em milissegundos.
Quanto a busca na tabela, pelo que entendi você quer buscar o último resultado inserido na tabela, provavelmente precisará adaptar a query abaixo dentro do TimerTask, retornando o campo somente da última linha da tabela:
SELECT TOP 1 * FROM <tabela> ORDER BY <campo a ser ordenado> DESC

Comment: Estou tentando mostrar m um optionpane, mas não está funcionando. da uma olhadinha ai q vou postar la em cima
Comment: @Lucas16 sem um [mcve] este é o maximo que posso ajudar, pois não tem como eu simular algo que não foi apresentado. a resposta mesmo foi feita baseada no que supostamente eu entendi do problema. E a edição inseriu uma duvida completamente diferente da original por isso, reverti a pergunta.
Comment: Entendi. Fico grato, deu certo em questão do tempo, mas meu problema agora está na hora de buscar as informações, mas vc já me ajudou muito. obrigado.


What is the most likely meaning of a confidence interval?

Question: I'm using a service (Optimizely, as it happens), which show a confidence interval but doesn't explain what it is.
I'm assuming it is a Binomial Confidence Interval, but I have no idea what the % certainty of the range is, or the detailed meaning. Searching the Internet doesn't help - there is nobody with a clear explanation of what the default for this kind of thing is.
For example, for 97 success out of 939 trials, Optimizely says "10.33% (±1.95)".
What does that ±1.95 likely mean, exactly?
And yes, I've already complained to them that they should document it. But clearly, there is some default that statisticians habitually use. What is it?
Comment: Talking about this a bit more in the office here at ScraperWiki, it seems in some disciplines there is a different assumption. e.g. Physics uses 1 sigma (68%) only quite often. Would love good in answer to this in an answer too!
Answer: Exactly? You want an exact answer to a statistical question? And you're willing to pay a service to provide it? Did you formerly work for AIG?
Seriously, we will need to guess here. My guess is that you are being offered an estimate of the 95% confidence interval using a Normal approximation around the point estimate of the binomial proportion for your data. My guess is informed by the fact that I have an open R console session:
<code>> binom.test(97, 939,  10.33/100)

    Exact binomial test

data:  97 and 939
number of successes = 97, number of trials = 939, p-value = 1
alternative hypothesis: true probability of success is not equal to 0.1033
95 percent confidence interval:
 0.08457063 0.12456106
sample estimates:
probability of success
             0.1033014

> abs(0.08457063 - 0.12456106)
[1] 0.03999043
> abs(0.08457063 - 0.12456106)/2
[1] 0.01999522
</code>
There's an "exact" answer, but exact has a different meaning than the word you are probably asking. Furthermore, you will notice that one half the span of the 95% CI 1.99995%  is not the same as your Optimizely answer of 1.95%. The exact CI's are not symmetric when the binomial proportion is far away for 0.5.
Answer: Following DWin's answer, I used R to find some more binomial confidence intervals:
<code>> library(binom)
> binom.confint(97, 939)
          method  x   n      mean      lower     upper
1  agresti-coull 97 939 0.1033014 0.08535696 0.1244784
2     asymptotic 97 939 0.1033014 0.08383472 0.1227681
3          bayes 97 939 0.1037234 0.08452740 0.1233938
4        cloglog 97 939 0.1033014 0.08487358 0.1237776
5          exact 97 939 0.1033014 0.08457063 0.1245611
6          logit 97 939 0.1033014 0.08539352 0.1244537
7         probit 97 939 0.1033014 0.08514200 0.1241205
8        profile 97 939 0.1033014 0.08492041 0.1238435
9            lrt 97 939 0.1033014 0.08491887 0.1238435
10     prop.test 97 939 0.1033014 0.08493732 0.1249860
11        wilson 97 939 0.1033014 0.08542358 0.1244118
</code>
"10.33% (±1.95)" looks like the asymptotic 95% confidence interval.
Comment: Thanks for this, shows that for my purposes the calculation method doesn't matter much!
Answer: The Optimizely documentation says:

What these numbers mean is that at the time the experiment was running, if you were to take a bunch of random samples, 95% of the time, the conversion rate would fall in the range listed. For example, if the conversion rate is 6.0% and the confidence interval is 0.11%, then 95% of the tests will have a conversion rate between 5.89% and 6.11%.

More generally, Wikipedia suggests this is common practice:

In applied practice, confidence intervals are typically stated at the 95% confidence level. However, when presented graphically, confidence intervals can be shown at several confidence levels, for example 50%, 95% and 99%.

And discussion with friends suggests it's field specific.


How do I list all names of the same group type?

Question: For a Group type (Birds), I tried to create a View in Drupal 9 to list all groups of that type, but I end up getting a group title entry for every node, for example this list.

Birds groups

Hawks
Hawks
Hawks
Jays
Jays

I want it to be a group oriented list, and not group member oriented.

Birds groups

Hawks
Jays

I'm only a view (an unformatted list) with group relationships. Groups aren't tied to users in any way.
What I tried to do is editing a view that shows nodes and change it to show groups by playing around with relationships from the Advanced settings section.
Answer: If your goal is to show groups, create a view that displays them.
Create a new view from /admin/structure/views/add - in View settings, Show Group of type Birds.


How to use the -C option correctly in Make

Question: I need to compile this program in my archlinux install.
When I do, as instructed in that thread:
make -j4 -C /lib/modules/$(uname -r)/build M=$(pwd) modules

I get the following error:
 make -j4 -C /lib/modules/$(uname -r)/build M=$(pwd) modules
scripts/Makefile.build:41: /home/jenia/Documents/kernel-modules/camera/Makefile: No such file or directory
make[1]: *** No rule to make target '/home/jenia/Documents/kernel-modules/camera/Makefile'.  Stop.
make: *** [Makefile:2021: /home/jenia/Documents/kernel-modules/camera] Error 2

The makefile is indeed not located in /home/jenia/Documents/kernel-modules/camera/Makefile but rather in:
ls -l /lib/modules/$(uname -r)/build/Makefile
-rw-r--r-- 1 root root 71855 Mar  3 10:58 /lib/modules/6.2.2-arch1-1/build/Makefile

How do I correctly point make to lib/modules/$(uname -r)/build/Makefile? Notice that I'm using the -C flag already but to no avail.
Comment: make -f ?
Comment: This isn't so much about `make` in general as it is about the Linux kernel build system (which relies on `make`).
Answer: Semi-informed speculation.
You have:
make -j4 -C /lib/modules/$(uname -r)/build M=$(pwd) modules

The M=$(pwd) records the directory you are running the build from, and is probably used in the makefile to identify where the included makefile (some subset of kernel-modules/camera/Makefile) should be found.  But you don't have that in your /home/jenia/Documents directory.
Without having tested it in the slightest, I think your problem is that your current directory needs to be closer to where the software is located.  I'm not sure exactly which directory, but /lib/modules might be a reasonable guess (therefore, it is probably wrong).
But the key point is:

Make sure you launch the build from the correct/expected directory.

Your use of -C is fine; the problem is the M=$(pwd) part.
Note that the file /lib/modules/6.2.2-arch1-1/build/Makefile is probably not the one that the scripts/Makefile.build is looking for; that should be in a sub-directory camera somewhere.

In support of my theory about 'start from correct directory', I note that comment #19 in the linked article says:

First, enable source code repositories, then fetch the source code with the following in terminal
apt-get source linux-modules-extra-$(uname -r)

Then navigate to the /drivers/media/usb/uvc directory and rename the uvcdriver.c to uvcdriver.old, choose open directory in terminal then
wget https://raw.githubusercontent.com/Giuliano69/uvc_driver-for-Quanta-HD-User-Facing-0x0408-0x4035-/main/uvc_driver.c

make -j4 -C /lib/modules/$(uname -r)/build M=$(pwd) modules
sudo cp uvcvideo.ko /lib/modules/$(uname -r)/kernel/drivers/media/usb/uvc/

Then see if it works

This suggests you should launch your build from the /drivers/media/usb/uvc directory.
Comment: `makefile` is not the correct file name.
Answer:
How do I correctly point make to lib/modules/$(uname -r)/build/Makefile?

In light of the make command you are executing, the error messages you report indicate that you already have directed make to that makefile.  The main error is coming from a sub-make, so the top-level makefile must have been found.

When I do, as instructed in that thread:
make -j4 -C /lib/modules/$(uname -r)/build M=$(pwd) modules

I get the following error:
 make -j4 -C /lib/modules/$(uname -r)/build M=$(pwd) modules
scripts/Makefile.build:41: /home/jenia/Documents/kernel-modules/camera/Makefile: No such file or directory
make[1]: *** No rule to make target '/home/jenia/Documents/kernel-modules/camera/Makefile'.  Stop.
make: *** [Makefile:2021: /home/jenia/Documents/kernel-modules/camera] Error 2

That error seems to indicate that although you are executing a command that you drew from the referenced thread, you have not fully followed the instructions there:

First, enable source code repositories, then fetch the source code with the following in terminal
apt-get source linux-modules-extra-$(uname -r)

Then navigate to the /drivers/media/usb/uvc directory and rename the uvcdriver.c to uvcdriver.old, choose open directory in terminal then
wget https://raw.githubusercontent.com/Giuliano69/uvc_driver-for-Quanta-HD-User-Facing-0x0408-0x4035-/main/uvc_driver.c

make -j4 -C /lib/modules/$(uname -r)/build M=$(pwd) modules

sudo cp uvcvideo.ko /lib/modules/$(uname -r)/kernel/drivers/media/usb/uvc/

(Emphasis and some formatting added.)
It's not clear exactly which instructions you have followed and which not, but certainly you are running the make command from a different directory than /drivers/media/usb/uvc.  Likely you have performed the wget command in whatever directory you are running the build from as well, instead of from the one specified in the instructions.  I can't tell whether you have run the apt-get command or not.
There may be other ways to do it, but you cannot expect it to work to pick and choose only some of a particular set of instructions.


A selection of objects (with replacement) using combination formula

Question:
Consider an example where a pack contains 4 blue, 2 red, and 3 black pens. If a pen is drawn at random from the pack, replaced, and the process repeated 2 more times, what is the probability of drawing 2 blue pens and 1 black pen?

Now I am aware that a every single draw is an independent event and so we can use the multiplication rule of probability.
$$\text{Pr(drawing a blue pen)} = \frac{4}{9}$$
$$\text{Pr(drawing a black pen)} = \frac{3}{9}$$
$$\text{Pr(drawing a blue pen on first draw AND drawing a blue pen on the second draw AND drawing a black pen on the third draw)} = \frac{4}{9}\cdot\frac{4}{9}\cdot\frac{3}{9}$$
2 blue pens and 1 black pen can be arranged in $\frac{3!}{2!}$ ways so the total probability is $3\cdot\frac{4}{9}\cdot\frac{4}{9}\cdot\frac{3}{9}$.
My question is whether this can be done using just the combination formula?
I learned that you can select $r$ objects out of $n$ with replacement using $${n+r-1 \choose r}.$$
So we can select 2 blue balls out of 4 in ${4+2-1 \choose 2}$ ways and 1 black ball out of 3 using ${3 \choose 1}$ ways. We can choose 3 balls out of a total of 9 (with replacement) in ${9+3-1 \choose 3}$ ways.
According to me the probability using the combination formula should be
$$\frac {{5 \choose 2}{3 \choose 1}}{11 \choose 3}.$$ But this is not the same as what I got using the multiplication rule.
I would be really thankful if someone could guide me where I went wrong.
Answer: The issue is that you wrongfully assume that each of the $\binom{11}{3}$ combinations are equally likely.
Getting the combination of $\text{black}_1,\text{black}_1, \text{black}_1$ has a probability of occurring with $\frac{1}{9^3}$ but getting the combination of, say, $\text{black}_1, \text{black}_1, \text{blue}_1$ is not the same, but rather $\frac{3}{9^3}$.
This same mistake of thinking each outcome is equally likely can also be wrongly applied to say that the probability of flipping one head and one tails in two coin flips is $\frac13$. Someone might say "well there are three ways to choose an outcome on two coin flips without order mattering: $HH, HT, TT$. Therefore the probability of one head and one tails is $1/3$"
Perhaps it is easier to see why that method will not work in this more trivial example
Comment: I kind of get your point but at the same time... not really (I don't mean that as an offence; I'm just dumb as a brick). I don't seem to grasp your point about the combinations not being equally likely. Can your elaborate or link me to some kind of website that talks in depth the importance of each of combination have the same likelihood of occurence? I just know one thing about probability: $\text{Pr(event) = number of times the event occured/total number of elements in the sample space}$.
Comment: Let's say you buy one Powerball ticket and one mega million ticket. Now we only have four outcomes here: either they are both losers, the Powerball is a winner, the mega million is a winner, or both are winners. Now we all know the lottery is known for having excessively slim chances of winning. But if we only look at the different outcomes and divide the number of outcomes that are favorable (i.e. winning) by the total number of outcomes, we get that the probability of winning in at least one lottery is $.75$ which is abaurd
Comment: In other words, the combinations with repitition formula is used to find the proportion of outcomes that have two blue pens and one black pen rather than the probability
Comment: You mean the very last formula I wrote in my original post?
Comment: @VineetKumarVerma that "one thing you know about probability" is only true if the outcomes that you are counting in the sample space are equally likely, otherwise it's not true. In virtually all commonly encountered probability models, stars-and-bars outcomes (as in your second formula) are not equally likely.
Answer: If we write the generating function that depicts the drawing, we get :
$$  \left( \frac 4 9 b + \frac 3 9 k + \frac 2 9 r \right)^3 $$
The coefficient of $b^2k$ is then
$${3 \choose 2,1,0} \cdot \frac 4 9  \cdot \frac 4 9  \cdot \frac 3 9 $$
We do need the multinomial coefficient and the specific probabilities.


Showing that a $T_{1\frac{2}{3}}$-space is a $T_{1\frac{1}{3}}$-space

Question: Here's part two (sort of) to this question.
I am trying to show that every $T_{1\frac{2}{3}}$-space is a $T_{1\frac{1}{3}}$-space, where a space is $T_{1\frac{2}{3}}$ if each compact set is closed, and a space is $T_{1\frac{1}{3}}$ if each sequence has at most one limit.
Unfortunately, after playing around with various properties of compact spaces, closed spaces, the definition of a convergent sequence, etc., I've really gotten nowhere.
Can someone give me a hint as to how to go about this?  Thanks.
Answer: HINT: Suppose that $\langle x_n:n\in\Bbb N\rangle$ converges to $p$ and to $q$, and consider the compact set $K=\{p\}\cup\{x_n:n\in\Bbb N\}$; if $q\ne p$, is $K$ closed?
Comment: I definitely understand the idea, but why is $K$ compact?
Comment: @Alex: Let $\mathscr{U}$ be an open cover of $K$. There must be some $U_0\in\mathscr{U}$ such that $p\in U_0$. And then there is some $m\in\Bbb N$ such that $x_n\in U_0$ for all $n\ge m$, so ... ?
Comment: So there are only finitely many $x_n$ not in $U_0$, and since every finite set is compact, then so is $K$. (I try to tag you and it disappears when I post the comment.)
Comment: @Alex: You've got it. (Comments on an answer automatically ping the author of the answer; that's why you can't add the ping tag.)
Comment: Good.  And I wasn't aware of that, thanks.
Comment: @Alex: You're welcome.


Como alterar a versão do aplicativo em tempo de execução no C#

Question: Preciso alterar a versão do aplicativo de 18.104.22.168 para 188.8.131.52 em tempo de execução, como posso fazer já que a propriedade ProductVersion é apenas get;
Comment: Acredito não ser possível. Pode explicar o por que quer mudar a versão em `runtime`?
Comment: Como você já disse, não tem como alterá-la em tempo de execução: `public static string ProductVersion { get; }`.
Comment: Não pode ser { get; set; } ?
Answer: Acredito que em tempo de execução não seja a maneira ideal para isso.
O modo ideal para se atualizar esse id de versão, seria durante seu processo de Integração Continua, por exemplo, eu utilizo o VSTS (Visual Studio Team Services) para meu cenário de DevOps, e realizo justamente a alteração que você está necessitando.
Durante meu processo de build automatizada, eu executo um script powershell (ou mesmo uma task do vsts) que acessa o arquivo assemblyinfo.cs (no caso do c# claro), e atualiza esse ID de versão, de acordo com o ID da build, para que caso necessário eu consiga rastrear que a versão 220.127.116.1193 foi gerado pela build com mesmo ID.


How to prevent the pppd to remove the default route?

Question: We use multiple providers, one of them to create connection uses pppoe through pppd daemon on ubuntu 14.04.
Early without multiple providers pppd manages default route by itself (creating it when connection is established and remove it when pppoe is down). But now I banned it with following options in peers/rt
nodefaultroute
noreplacedefaultroute

Because I need more complex ip rules for the running scheme with multiple providers.
I researched pppd scripts ip-up, ip-down, ip-up.d, ip-down.d but does not found removing default route.
So I assumed that it does it in their code.
I can add post-down directive in the provider configuration /etc/network/interfaces file as is:
ip route add default dev ppp60 table default

As a trick.
I planned to manage default route in separate init script.
Is there are a workaround for prevent pppd to manage (remove) a default route ?
UPDATE1:
I want to forbid pppd to remove default route default dev ppp60 scope link, when connections is reinitiating or go down.
I use interfaces(pppd is managed by ifup and ifdown commands) and standart debian/ubuntu network subsystem configuration tools, as is:
auto rt
iface rt inet ppp
provider rt
pre-up /sbin/ifconfig ethtop up
post-up until ip a | grep -q ppp60; do sleep 1 > /dev/null; done
post-up ip route add default via "$( ip -4 a show dev "ppp60" |   grep -E '\<peer\>' | sed -r 's/.*peer ([^ /]*).*/\1/' )" table isc-rt
post-up ip rule add pref 30001 fwmark "0x$( gethostip -x "$(ip -4 a show dev "ppp60" | grep -E '\<inet\>' | sed -r 's/.*inet ([^ /]*).*/\1/')" )" lookup isc-rt
post-up ip rule add pref 30002 from "$( ip -4 a show dev "ppp60" | grep -E '\<inet\>' | sed -r 's/.*inet ([^ /]*).*/\1/' )" lookup isc-rt
post-up ip rule add pref 30003 to "$( ip -4 a show dev "ppp60" | grep -E '\<peer\>' | sed -r 's/.*peer ([^ ]*).*/\1/'  )" lookup isc-rt
post-up /etc/init.d/fw restart
post-down ip route flush table isc-rt
post-down ip rule del pref 30001
post-down ip rule del pref 30002
post-down ip rule del pref 30003
post-down /etc/init.d/fw restart

That's my main routes:
root@gate:/etc/ppp# ip route list
default dev ppp60  scope link
10.0.3.0/24 dev lxcbr0  proto kernel  scope link  src 10.0.3.1
10.8.0.0/24 via 192.168.128.13 dev br-eth0
83.Y.Y.196 dev ppp60  proto kernel  scope link  src 93.Y.Y.67
95.X.X.0/24 dev ethmiddle  proto kernel  scope link  src 95.X.X.40
192.168.128.0/24 dev br-eth0  proto kernel  scope link  src 192.168.128.1

Also I have tables for each provider with it's default gateway
That's my pppd options:
root@gate:/etc/ppp# awk '!/^ *#/ && NF' /etc/ppp/options
asyncmap 0
noauth
crtscts
lock
hide-password
modem
lcp-echo-interval 30
lcp-echo-failure 4
noipx

That's my current provider peer config:
user "gsdf6sg84"
noipdefault
defaultroute
unit 60
hide-password
lcp-echo-interval 20
lcp-echo-failure 3
noauth
persist
mtu 1492
maxfail 0
plugin rp-pppoe.so ethtop
debug

Comment: Could you please edit the question and make clear what are you trying to achieve and what happens? `ip route list` output wouldn't also hurt. Is *pppd* run by root, from startup script, or by unprivileged user? What's in */etc/ppp/options*?
Comment: As noted in the answer it is a kernel which removes the route when the device goes down. You can have a look at `pppd` `demand` option as it should create/keep networking devices even without establishing a link and check if it can be of any help in your case.
Answer: The kernel (not pppd) automatically removes all related routes when corresponding interfaces are being removed.


What external events trigger TCustomForm.RecreateWnd?

Question: A particular VCL application is crashing, rarely, and apparently spontaneously, and I strongly suspect it is because the main form's window handle is being recreated in response to some external trigger from the operating system.
I do know for certain that if the main form's window handle were to change then trouble would certainly follow (because background threads post messages to this handle).
But I would like to know how to reproduce this bug before I set about making code changes intended to fix it, if only so I can confirm that this is a plausible cause of the crashes, that the symptoms match those reported, and that the code changes do indeed fix it. (Also if there is no way the OS can trigger a call to TCustomForm.RecreateWnd I need to find some other explanation for the crashes. Yes, I could post CM_RECREATEWND to the main form but that just begs the question.)
(I am aware that the correct way to post messages from background threads to the VCL thread is to create a hidden message window purely for this purpose using AllocateHWnd - that is my proposed fix.)
I have seen a similar error with a descendent of TCustomListView where RecreateWnd was being triggered by changing the desktop style from Windows XP to Windows Classic. But I haven't been able yet to find such a method to trigger RecreateWnd on a TCustomForm. (I've spent a considerable amount of time reading through the VCL code and I must be missing something.)
Summary:
Under what stimuli from the operating system does the VCL end up calling RecreateWnd on a TCustomForm? (I'm especially interested in Windows 7 if that makes a difference.)
If there is such a stimulus from the OS, I can prove whether it causes the observed symptoms. If there definitively isn't then I can prove window recreation isn't the cause.
Comment: Override CreateWindowHandle and make a log, and for app startup and exit. Then you don't have to guess if the window is recreated. This is assuming it's the main form, need to adjust otherwise.
Comment: Do you have any evidence that window recreation is the problem? You've got a madexcept log or similar I presume?
Comment: I can't back it up, but I've seen the window handle change every time another VCL style is applied.
Comment: Have a look at the source code for the vcl. That's where I would start
Comment: @DavidHeffernan I've already spent the entire morning reading the VCL source and either I'm missing something, or the OS doesn't trigger RecreateWnd on forms. I was hoping someone might just know the answer.
Comment: @GünthertheBeautiful `TStyleManager.SetStyle` sends `CM_CUSTOMSTYLECHANGED` to each form, which the triggers `CM_RECREATEWND`, but this doesn't seem to occur in response to an OS event. (At least changing the Windows 7 theme doesn't trigger it.) I presume it happens when you apply a different skin programatically.
Comment: @DavidHeffernan Only indirect evidence I'm afraid. There are a number of different symptoms but the most common ones are the GUI 'spontaneously' stops receiving updates (from the worker threads) - so no MadExcept log for that, and a crash involving TCustomListView that appears somewhat like the one I mentioned in the question. I've never seen the problem first hand though.
Comment: You aren't going to be able to be 100% sure that you've found the specific recreation trigger anyway. You may as well just get your app to recreate the window in response to some external trigger. And then see if you get behaviour consistent with what your clients report. You need to fix the bug no matter what though. I'd probably just fix it.
Comment: @DavidHeffernan I think I'll do that. But I'm assuming that any external trigger that causes RecreateWnd will have the same effect. So I don't care whether I find the specific trigger, but I do very much care whether there is (a non-artificial) one. **If there isn't**, then I might have fixed a bug but won't have fixed the problem the users are reporting :-(
Comment: Why would your app **crash** even if `RecreateWnd` was triggered if all you do is post messages from a worker threads?
Comment: @kobik One possible reason is that component properties that aren't published don't automatically get preserved across RecreateWnd. So for instance a reference could become invalid. I think I've got more than one different fault, and I want to find out if RecreateWnd could be a common trigger. Knowing this will let me either reproduce the faults at will or rule this out as a possible cause. When you can't reproduce the problem, debugging is HARD.
Comment: See [How do I make form or windowed control RecreateWnd-aware properly?](http://stackoverflow.com/q/21011780/576719).
Answer: Windows will destroy your form if it is owned or parented to another window that is being destroyed.
That will cause your form's handle to be destroyed.
But since your form is still around, Delphi will re-create the handle the next time.
Comment: Good point. This mechanism wouldn't be explicit as such in the VCL source. What if the owner form was the Delphi application object? I'm guessing that *doesn't* get destroyed and recreated during the normal lifetime of the process.
Comment: @IanGoldby That is true. Windows never (is unable) to call `RecreateWnd`. That method is called internally when the window handle needs to be recreated. The VCL source code is littered with the situations when a form's handle will need to be re-created (e.g. you change the `FormStyle`, `BorderStyle`, `BiDiMode`, `BorderIcons`, `Position`. But in all these cases, it is the VCL itself doing it.
Comment: The crucial point is that it is the VCL doing it *in response to something in the developer's application code* rather than in response to something that happens externally (such as the user changing the desktop style).
Comment: Things like docking/undocking, re-parenting, window style changes, VCL style changes, etc will all trigger window re-creations. Also, any external destruction of a window will reset the owning control's `Handle` to 0 and destroy all child windows, resetting child control `Handle`s to 0 as well.


How to add alt and title attributes field for user picture?

Question: In my Drupal project I have user picture enabled to all users, I want to add alt field and title field for Drupal user picture feature, so I can add my custom text instead of "user's picture" text.
I also want to utilize both fields in views as well.
Thanks,
Answer: You would need to override this function in your template.php file and override the alt tag.
Another option would be to uncheck "Enable user pictures" in account settings and add your own custom imagefield.  Then you should be able to enable alt and title fields in the field settings.  You can also use this field in views.
Comment: Thanks for your answer, I can't add additional field to user profile/account at the moment. I want to add alt and title to user picture itself.
Comment: Updated my answer.
Comment: Cool, but `template_preprocess_user_picture` will solve part of my issue (this option is useful for user profile page and views with default image-style). So I used views with different image style (custom style) `template_preprocess_user_picture` will no longer be useful. Any other ideas?! thanks
Comment: @Aboodred1 Fields are the built-in way to do this, unfortunately if you can't use them you'll have to code something custom
Answer: My solution to my own question is as follow:
I've created a custom module to change user picture alt and title for the uploaded image
first overrides this function if you need to change "user's picture" in user profile page. (thanks to @jsheffers for pointing this out)
function MODULE_NAME_preprocess_user_picture(&$variables) {

  $variables['user_picture'] = '';
  if (variable_get('user_pictures', 0)) {
    $account = $variables['account'];
    if (!empty($account->picture)) {
      if (is_numeric($account->picture)) {
        $account->picture = file_load($account->picture);
      }
      if (!empty($account->picture->uri)) {
        $filepath = $account->picture->uri;
      }
    }
    elseif (variable_get('user_picture_default', '')) {
      $filepath = variable_get('user_picture_default', '');
    }
    if (isset($filepath)) {
      $alt = t('YOUR CUSTOM ALT TEXT');
      $title = t('YOUR CUSTOM TITLE TEXT');

      if (module_exists('image') && file_valid_uri($filepath) && $style = variable_get('user_picture_style', '')) {
        $variables['user_picture'] = theme('image_style', array('style_name' => $style, 'path' => $filepath, 'alt' => $alt, 'title' => $title));
      }
      else {
        $variables['user_picture'] = theme('image', array('path' => $filepath, 'alt' => $alt, 'title' => $title));
      }
      if (!empty($account->uid) && user_access('access user profiles')) {
        $attributes = array(
          'attributes' => array('title' => t('View user profile.')),
          'html' => TRUE,
        );
        $variables['user_picture'] = l($variables['user_picture'], "user/$account->uid", $attributes);
      }
    }
  }
}

To make it work with views you need to create a new views handler field and extend this handler class
class views_MODULE_NAME_handler_field_user_picture extends views_handler_field_user_picture {

  function render($values) {
    if ($this->options['image_style'] && module_exists('image')) {
      // @todo: Switch to always using theme('user_picture') when it starts
      // supporting image styles. See http://drupal.org/node/1021564
      if ($picture_fid = $this->get_value($values)) {
        $picture = file_load($picture_fid);
        $picture_filepath = $picture->uri;
      }
      else {
        $picture_filepath = variable_get('user_picture_default', '');
      }
      if (file_valid_uri($picture_filepath)) {
        $alt = t('YOUR CUSTOM ALT TEXT');
        $title = t('YOUR CUSTOM TITLE TEXT');
        $output = theme('image_style', array('style_name' => $this->options['image_style'], 'path' => $picture_filepath, 'alt' => $alt, 'title' => $title));
        if ($this->options['link_photo_to_profile'] && user_access('access user profiles')) {
          $uid = $this->get_value($values, 'uid');
          $output = l($output, "user/$uid", array('html' => TRUE));
        }
      }
      else {
        $output = '';
      }
    }
    else {
      // Fake an account object.
      $account = new stdClass();
      if ($this->options['link_photo_to_profile']) {
        // Prevent template_preprocess_user_picture from adding a link
        // by not setting the uid.
        $account->uid = $this->get_value($values, 'uid');
      }
      $account->name = $this->get_value($values, 'name');
      $account->mail = $this->get_value($values, 'mail');
      $account->picture = $this->get_value($values);
      $output = theme('user_picture', array('account' => $account));
    }

    return $output;
  }
}

Make sure to call the new handler instead of the original handler by overriding this function
function MODULE_NAME_views_data_alter(&$data) {
  foreach ($data as $table => $config) {
    foreach ($config as $item => $item_config) {
      if (isset($item_config['field']['handler']) && $item_config['field']['handler'] == 'views_handler_field_user_picture') {
        $data[$table][$item]['field']['handler'] = 'views_MODULE_NAME_handler_field_user_picture';
      }
    }
  }

  return $data;
}

Comment: could it be possible to make only views override alt text overriding views_MODULE_NAME_handler_field_user_picture but without overriding MODULE_NAME_preprocess_user_picture.
This is to disallow user to have their own alt text but override alt text in views with replacement token for ex. when hovered text will be like " author of  total articles  "


Better Performance by putting image dimensions

Question: YSlow advises that all images should have dimension attributes even if they are presented at 1:1 scale, so that the browser knows the dimensions before the images are loaded, to start rendering the page faster.
I have a view of 20 taxonomy titles and their image fields. How I can make Drupal put their dimensions attributes on each image html tag?
I have drupal 7.
Comment: Which version of drupal are you referring to? Tag it.
Comment: The problem is that these images are most likely generated through image styles, which means that they might not even exist in the target size yet and it is configurable in the UI. And when you start to add code to detect the image size, you would probably very quickly spend more time doing that than you would gain in the browser by adding that information. That is just a guess, though :)
Comment: i found that google mod_pagespeed module for apache can do that. but it's a pity to add an extra compontent to the system just for that. and what about the people that don't use apache anyway
Answer: This is a known issue in Drupal 7. A conscious choice, as it were, from the issue Remove unnecessary I/O from theme_image().
There is a patch to fix this here: Images are not printed with height and width.


Manipulations with convergence a.e.

Question: Let functions $f_n$ be measurable, $n \in N$, $f_n\rightarrow f$ almost everywhere. Prove that $\operatorname{arctg}f_n \rightarrow \operatorname{arctg}f$ almost everywhere.
Honestly speaking, we have had so many theorems on different types of convergence and relationships between them that I find it very hard to mix them in order to solve problems.
First of all, we are given that the measure of the set of points for which $f_n$ does not converge to $f$ is zero.
How should I think about the problem next? How do we show that $arctg$ preserves convergence?
I have my lecture notes, but when it comes to practice I often feel helpless and do not know how to approach the problem. Probably, you could recommend some good problem book with solved examples.
Thank you
Comment: use the continuity of $arctg$, namely fix a point $x$ where $f_n(x) \to f(x)$ and prove that $arctg f_n(x) \to arctg f(x)$ for that $x$ using the continuity of $arctg$ at the point $f(x)$.
Answer: Suppose that $g : E \subset \mathbb{R}^l \to \mathbb{R}$ is continuous, and let $(f_n)_n :\mathbb{R}^k \to E$ converge almost everywhere to some function $f : \mathbb{R}^k \to E$. Now, by continuity, if $x \in \mathbb{R}^k$ is such that $f_n(x) \to f(x)$, then $gf_n(x) \to gf(x)$. By the contrapositive, then, if $gf_n(x) \not \to gf(x)$ we have that $f_n(x) \not \to f(x)$. That is,
$$
\{x : gf_n(x) \to gf(x)\}^c \subset \{x : f_n(x) \to f(x)\}^c
$$
and so
$$
\mu(\{x : gf_n(x) \to gf(x)\}^c) \leq \mu(\{x : f_n(x) \to f(x)\}^c) = 0.
$$
Hence $gf_n \to gf$ a.e.

Manipulations with convergence a.e.


how to set picture as background image inside an url with inline css in react js

Question: i have started just  learning react js and i'm making a carousel where i want to set the picture as a bgImg putting it inside url() in a div but picturing is not getting render but when i'm puting the same in  tag it is coming
import { Banners } from '../Assignment/carasoul_data'

<div className="carousel-area" style={{backgroundImage : `url(${Banners[0]})`}}>

//picture not getting render
some have suggested to use required but that also didn't worked for me
<div className="carousel-area" style={{backgroundImage: `url(${require(Banners[0])})`}} >

i have tried this too
"url(" + Banners[0]+ ")"

My images list which i want to render
import banner1 from'../Assignment/carasoul/Web assignment.jpeg'
import banner2 from'../Assignment/carasoul/Web assignment2.jpeg'
import banner3 from'../Assignment/carasoul/Web Banner3.jpeg'
import banner4 from'../Assignment/carasoul/Web Banner4.jpeg'

export const Banners =[banner1,banner2,banner3,banner4]

Answer: It is not a react error just you have to add min-height & width to your carousel css Whenever you provide empty div you have to give specific height & width therefore the image is not visible
you can try below sandbox for help
https://codesandbox.io/s/zen-kare-h6l648
Comment: thank you so much for your response.. but i have also given height and width in the css file its just coming a blank area...and after playing arround i got to know that it is not showing .jpeg it's working fine when i use .png and in the other side .jpeg is working fine with  could you please guide me what to to do
Comment: you can see my sandbox i have added jpg files only
Comment: yeahhh i'm sharing you my sendbox link please help me with my thing..i'll be greatful.     https://codesandbox.io/s/empty-bush-e87ez1


trying to record on a blank cassette via aux, but external mic is also recording

Question: I'm trying to record on my Panasonic RQ-345 (Portable cassette player/ recorder) using an auxiliary cord connected to my phone, I can hear the audio im trying to record, but I can hear the outside audio as well over it so im guessing the external mic is also recording along with the aux, how can I make this stop?? Ive looked everywhere on google for answers but I cant find anything on this
Comment: I'm voting to close this question because it is not about music practise or performance & would require detailed knowledge of the operational foibles of a 40-year-old dictation recorder.
Answer: I looked at the service manual and the aux connector is an output not an input. I don't think there's any way (without modifying the circuitry) to record a line in signal; you can only record from the microphone.


Binary Classification problem for imbalanced dataset

Question: I am new to machine learning and need help. I have a dataset with two classes(0,1) where is 0 is Profitable and 1 is Unprofitable. Ratio of 0:1 in train set is 150/52
Taking positive as "1"(Unprofitable) and negative as 0(Profitable),False Negative cost is 4900 and False Positive cost is 4000.
Objective is to maximize f(profit) = 4000*(No of True Negative-No of False Positive)-(4900*No of False Negative) such that is atleast > 1775$(base profit without any model)
With EDA I figured Years At employer, Debt/Income Ratio and Age to be most important predictors.
With XGBoost having scale_pos_weight =3 I get excellent results on training set but fails badly (overfits) on test set.
No matter how much I try I am not able to improve Profits for test set beyond 1375\$ (as mentioned above needs to be at least > 1775$)
Even rpart with loss function does not help much... Can anyone please provide any input?
However If I take an alternative approach (i.e take only observations with Years at employer <20) and then apply glm or rpart results are really great on both train and test set, but is this approach even right ? (I did this because EDA shows that all unprofitable customers were with "years at employer <20",in train set)
Comment: Maybe dups:  https://stats.stackexchange.com/questions/6067/does-an-unbalanced-sample-matter-when-doing-logistic-regression, https://stats.stackexchange.com/questions/283170/when-is-unbalanced-data-really-a-problem-in-machine-learning, https://stats.stackexchange.com/questions/235808/binary-classification-with-strongly-unbalanced-classes, https://stats.stackexchange.com/questions/247871/what-is-the-root-cause-of-the-class-imbalance-problem,  https://stats.stackexchange.com/questions/312780/why-is-accuracy-not-the-best-measure-for-assessing-classification-models
Comment: Could you provide some data?
Answer: Sometimes the base profit without any model is truly the best one can do. Compare How to know that your machine learning problem is hopeless?, and tangentially related Is it unusual for the MEAN to outperform ARIMA?
If your alternative approach works in production, then it works. There is little "right" or "wrong" here. Do you automatically classify everyone with <20 years tenure as "unprofitable"? Note that "all unprofitable customers had <20 years tenure" is not the same as "everyone with <20 years tenure is unprofitable"!
My answer to "Classification probability threshold" may be helpful.
Comment: Thanks for your input . No I do not automatically classify everyone with <20 years as Unprofitable. I just took subset where Year of exp was less than 20 and then build the model, to predict profitable/Unprofitable


Rsyslog segregate logs for wildcard files

Question: I have a central server to log my different application logs, i forward the logs using rsyslog's(8.36) wildcard(<code>/var/log/sample/*.log</code>), i'd like to segregate the logs on my central server based upon the filename being monitored, how do i go about it?
Forwarder:
<code>`input(type="imfile" File="/var/log/sample/*.log"
Tag="sample-req_params.log"
StateFile="/var/spool/rsyslog/app-req_params"
Severity="error"
Facility="local7")
*.* @@X.XX.X.XXX:514`
</code>
Receiver:
<code>`$template MYFILENAME,"/var/log/sample/%programname%.log"
if $programname contains 'sample' then ?MYFILENAME`
</code>
Answer: Sorry for this not being the greatest answer, but I hope I can push you into the right direction. The default templates do not transmit the file name. On the original system, however, it is available as imfile metadata. You need to define a template on the client side that contains that metadata and the use it on the server side to extract the file name.


What is three-point backward difference?

Question: I fully understand two-point, forward/backward/central difference. I know them mathematically and graphically but I'm not quite sure what the three-point backward difference is. I know that we get the derivative using the previous two points but I don't really get the concept of it. Can someone explain it preferably with the aid of diagram or a graph please?
Comment: The finite differences can be obtained from polynomial interpolation.
Comment: @SeanRoberson Can you kindly elaborate please?
Answer: As mentioned in the comments, one way to derive the 3-point backwards finite difference would be to perform polynomial interpolation. However, I'll derive the 3-point backwards difference using Taylor series.
Let $h>0$ denote our working spatial increment. For a smooth function $f(x)$, Taylor's theorem gives
$$f(x-h) = f(x) - f'(x)h + f''(x)\frac{h^2}{2} + \mathcal{O}(h^3),$$
$$f(x-2h) = f(x) - 2f'(x)h + 2f''(x)h^2+ \mathcal{O}(h^3).$$
Therefore,
$$f(x-h) - \frac{1}{4}f(x-2h)= \frac{3}{4}f(x) - \frac{1}{2}f'(x)h + \mathcal{O}(h^3).$$
Solving for the derivative $f'(x)$ then gives
$$f'(x) = \frac{\frac{3}{2}f(x) - 2f(x-h)+\frac{1}{2}f(x-2h)}{h} + \mathcal{O}(h^2).$$
This is the second order accurate three point backward finite difference approximation to the derivative. There are also other first order discretizations as well.
Comment: Thank you for giving me the derivation but in fact I know how to derive it too. I just don't understand the concept of it.
Comment: Oh. Well why do you find it confusing compared to the 2 point differences?
Comment: It may sound silly but I don't know why we're subtracting f(x-h) from f(x-2h). What would it give us?
Comment: Couldn't you ponder the same thing about the forward or backward Euler method? One way to think about it is, for a three point stencil, we are fitting the function to a quadratic polynomial, taking that polynomial's derivative, and using it as our approximation of the original function's derivative.
Comment: Ah I see! Thank you sir!
Answer: You want the first-order derivative approximated to second error order. We already know that the central difference quotient is second order. To apply this here we need to move the center backwards. Use Taylor for that, $f'(t)=f'(t-h)+hf''(t-h)+O(h^2)$. Now insert the difference quotients centered at $t-h$,
$$
f'(t)=\frac{f(t)-f(t-2h)}{2h}+\frac{f(t)-2f(t-h)+f(t-2h)}{h}+O(h^2)
$$


"Windows cannot find the Microsoft Software License Terms" when installing Windows Server 2016 in a VM

Question: I downloaded Windows Server 2016 iso from the link. The iso file size is 4.95 GB.
While installing Windows Server 2016 in VMware Workstation 2012, I see following error message.
Windows cannot find the Microsoft Software License Terms. Make sure the installation sources are valid and restart the installation.
Please let me know, how to fix it.
Regards
InTech
Comment: Do what it said.
Answer: I had the same issue installing Server 2016 on VMware player 2012. I was using the easy install and no matter how much ram or cores it still gave the error. The solution was to choose "I will install the operating system later." Then just manually set it all up from there without easy install and it works fine.
Comment: This is essentially the same solution OP linked in a comment on another answer: https://serverfault.com/questions/832411/windows-cannot-find-the-microsoft-software-license-terms-when-installing-windo#comment1065203_832457 In this case, it is the correct answer.
Comment: Ah. I had chosen the wrong option so I just exited Setup and when the VM rebooted it suddenly started working.
Comment: 2021, using VMware Workstation 16 Player and still having this issue. This was still the solution.
Answer: That happens frequently with Server 2012 R2 and higher if the VM has a very low amount of RAM or has dynamic RAM.
Give the VM at least 2 GB (better 4 GB) of RAM for the OS installation and it should work. You can change the RAM back to what it was after the installation finished.
Comment: I fixed it by going through http://www.top-password.com/blog/vmware-fix-windows-cannot-find-the-microsoft-software-license-terms/
Comment: @EinfoMail Could you please write down your solution and accept it as an answer?
Comment: I did same i.e. 4GB RAM, total processor cores: 4. and 80 GB disk size. However, I see same error message.
Comment: Did you give the VM a **fixed** amount of RAM? It won't work reliably with dynamic RAM or ballooning or whatever it's called in VMware.
Answer: I used the following workaround successfully:
Install Windows Server 2016 in an Oracle VirtualBox VM, but make sure you set the disk format to VMware compatible.
Shut down the vm and stop VirtualBox.
Then create an empty virtual machine in your VMware environment, but replace the disk with vmdk file created in VirtualBox.
After that you will get a running instance in VMware. VirtualBox can then be uninstalled, if you wish.
Answer: It could be that you have selected Dynamic Memory but forgot to change the default value from 512 MB to at least 1024 MB.
So, changing the Minimum RAM to 1024 MB will enable the license terms option.


Meu personagem segue o mouse, mas fica girando de ponta cabeça

Question: Meu personagem se movimenta ('voa') seguindo o mouse, mas ele fica a todo momento virando para os lados ou de ponta-cabeça. Alguém sabe como resolver isso? (para ele permanecer em pé, como é a sprite)?
Quando troco o Set angle toward por Set position (imagem abaixo), o Player para de girar de ponta cabeça, mas aí ele fica se movimentando (seguindo o mouse) muito rápido, ignorando a Behavior de bullet (que está no speed 40).
As Behaviors que o Player tem são: BoundToLayout + Bullet + Solid.
Faz dois dias que tento resolver isso, então agradeço muito se alguém puder me ajudar.
Comment: Olá. Se você fornecer um link com um [Exemplo Mínimo Completo](http://pt.stackoverflow.com/help/mcve), facilitaria muitíssimo que alguém conseguisse te ajudar. Caso contrário, as pessoas precisarão ficar adivinhando o possível problema do seu jogo.
Answer: Como o personagem tem o behavior Bullet ativado, acredito que uma solução possível seja utilizar o método Set angle of motion (desse behavior), ao invés do Set angle toward do personagem.
O parâmetro informado na chamada do método é o ângulo entre o objeto e o cursor do mouse:
angle(Self.X, Self.Y, Mouse.X,Mouse.Y)

Na ação do personagem, fica da seguinte forma:

Para que não haja rotação do objeto durante o movimento, a propriedade Set angle do behavior Bullet deve ter o valor No:

Com essas alterações, o resultado fica assim:
Comment: Olá, @Gomiero. Obrigado pela ajuda! Era exatamente o que eu precisava.
Valeu! :)
Comment: @AilsonBezerra marque a resposta como aceita então para dar como encerrado essa pergunta.


Adding the is_front variable to a Paragraphs template

Question: Is the is_front variable not available in a Paragraphs template override?
I'm trying to do the following:

          {% if is_front and content.field_section_title %}

{{ content.field_section_title }}

          {% elseif content.field_section_title %}

{{ content.field_section_title }}

          {% endif %}

          {{ content.field_text }}

          {{ content.field_section_image }}

However, when I set a node that uses this paragraph type as the homepage, it doesn't take the is_front condition and just uses the h4 tag instead of the h2 which is what I would like for it to do.
Is there a way for my paragraphs templates to use the is_front condition? Or is there a different way to go about this?
Answer: You should be able to add this with a preprocess function in mytheme.theme of your theme.
/**
 * Implements hook_preprocess_paragraph().
 * @param $variables
 */
function mytheme_preprocess_paragraph(&$variables) {
  $variables['is_front'] = Drupal::service('path.matcher')->isFrontPage();

  // Ensure the cache varies correctly.
  // Drupal 8.2.x or lower
  $variables['#cache']['contexts'][] = 'url.path';

  // Ensure the cache varies correctly.
  // Drupal 8.3.x+
  $variables['#cache']['contexts'][] = 'url.path.is_front';
}

This should add is_front as a variable to any paragraph twig template. Clear cache after adding this code.
Per 4k4's comment, if this is Drupal 8.3 you will also need to add a cache context.
Comment: You also need a cache context `url.path`. In Drupal 8.3 there will be a new one for this: `url.path.is_front` - https://www.drupal.org/node/2830442
Comment: Excellent. This did the trick. Thanks again Kevin.
Comment: @Kevin, I've seen the edited answer about Drupal 8.3, you need the cache context for all D8 versions. Prior to 8.3 you don't have the front page specific one, so you can only use `'url.path'`.
Comment: Okay, I updated my answer.
Comment: Great, that's a very nice answer!
Comment: I've added the updated code to my site and it crashes it. I get the following message: Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException: You have requested a non-existent service "cache_context.url.path.is_front". Did you mean one of these: "cache_context.url.path", "cache_context.url.path.parent"? in Drupal\Component\DependencyInjection\Container->get() (line 157 of /var/www/html/core/lib/Drupal/Component/DependencyInjection/Container.php).
Comment: That would only be if you are running Drupal 8.3.x , use the other if you are on 8.2 or lower.


check box with date module

Question: I need a solution for reservation, for example i have a swimming pool and i want to Reserve it, the visitor will choose the time he want, let me say i will select the start and end date (the reservation time) mmmm in our example from 8 am to 9am, what i need to display the available reservation time like this:

And the visitor can select one hour or more to reserve the swimming pool.
Is there a module can do this?and if not is there a reservation module can do what i nees by another way? thanks
Answer: As far as i know, there  is no module which will display exact User Interface as check-boxes that will integrate with date module.
What i would like to suggest is to create time field to display from and to time of timing slots using date module.
If you need exact User interface what you are asking then follow below steps.

Add checkboxes field with different timings.
Then create date from and to time fields.
Hide date from and to fields using css.
On click of check-boxes update the hidden date from & to fields using jquery or javascript, so that you can use Date module features.
Comment: i need to to display the available time dynamically because i have a lot of places to reserve.thanks for your suggestion my friend :D
Comment: In that case you can use form alter technique to alter the form and add checkboxes based on the available timings.... http://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_form_alter/7

check box with date module