text:
Q: JAVA URI Can't be null - assist with this function Hi wise sages of the StackOverflow universe. I was hoping you might be able to assist me with an issue I'm having.
The point of the code below is to show whether the symbol will solicit a valid response from the yahoo API.
The function GetSymbol takes a double and returns a string, in the case of GetSymbol(6149) the string returned is "IBM". (Just FYI, in the real thing, the
    symbol = GetSymbol(6149);
    //symbol = "IBM";           // This is to show that it works normally

Code is not really in the function, it is just there for my testing purposes. When the
symbol = "IBM"; is not // out, it works fine, but as such it does not. In the real code, the caller thread would look like if(test(GetSymbol(6149)) == 0). (0 means no error, 1 means error).
For some reason, even though the return value of GetSymbol(6149) is equivilent to "IBM", the URL yahootest accepts the latter but not the former. (using GetSymbol(6149) as an input for test() gives me URI cant be null as an exception. Can you think of any reason why?
And just in case you think it helps, I have listed the Get Symbol function below the test function. Its call is
    while(i <= Math.pow(26,4)){
    GetSymbol(i);
    i++;
    }

This is the test function
public int test(String symbol){

    int testnum = 0;
    symbol = GetSymbol(6149);
    //symbol = "IBM";           // This is to show that it works normally

    String url = "http://download.finance.yahoo.com/d/quotes.csv?s="
            + symbol + "&f=nsl1op&e=.csv";

        try{
        URL yahootest = new URL(url);
        URLConnection data = yahootest.openConnection();
        Scanner input = new Scanner(data.getInputStream());

    }catch(Exception e){
        System.out.println(e.getMessage());
        testnum++;
    }

    return testnum;
}

This is the GetSymbol function
 public  String GetSymbol(double i){

    double parts = Math.floor(i/26);
    double remainder = Math.floor(parts/26);
    double remainder2 = Math.floor(remainder/26);

    int a = 0;
    int b = 0;
    int c = 0;
    int d = 0;
    String e = "%5E";

    if(i <= 26){
        a = (int) (i + 64);
    }
    else if(i <= Math.pow(26,2)){
        a = (int) parts;
        b = (int) (i - (26*a));
        a = a + 64;
        b = b + 64;
        if(b == 64){b++;}
    }
    else if((i <= Math.pow(26,3))){
        a = (int) remainder;
        b = (int) (parts -(remainder*26));
        c = (int) (i - (parts*26));
        a = a + 64;
        b = b + 64;
        c = c + 64;
        if(b == 64){b++;}
        if(c == 64){c++;}
    }
    else if((i <= Math.pow(26,4))){
        a = (int) remainder2;
        b = (int) (remainder - (remainder2*26));
        c = (int) (parts - (remainder * 26));
        d = (int) (i - (parts*26));
        a = a + 64;
        b = b + 64;
        c = c + 64;
        d = d + 64;
        if(b == 64){b++;}
        if(c == 64){c++;}
        if(d == 64){d++;}
    }

    StringBuilder stringBuilder = new StringBuilder();
    stringBuilder.append(String.valueOf((char) a));
    stringBuilder.append(String.valueOf((char) b));
    stringBuilder.append(String.valueOf((char) c));
    stringBuilder.append(String.valueOf((char) d));
    String string = stringBuilder.toString();

    symbol = string;
     return symbol;
 }

This is the entire stack trace
java.lang.IllegalArgumentException: URI can't be null.
at sun.net.spi.DefaultProxySelector.select(DefaultProxySelector.java:147)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect0(HttpURLConnection.java:1097)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:997)
at sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:931)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1511)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1439)
at Stocks.Begin.test(BasicApp.java:185)
at Stocks.Begin.<init>(BasicApp.java:42)
at Stocks.BasicApp.main(BasicApp.java:21)

A: If I had to take a guess, it's something to do with the fact that you append 4 characters together to create your URL when using GetSymbol, yet IBM is only three characters. Most likely when using GetSymbol instead of just "IBM", there is a hidden symbol, something like "IBM\0". From what I can tell, what you need to do is modify your GetSymbol function as such:
StringBuilder stringBuilder = new StringBuilder();
if(a > 0) stringBuilder.append(String.valueOf((char) a));
if(b > 0) stringBuilder.append(String.valueOf((char) b));
if(c > 0) stringBuilder.append(String.valueOf((char) c));
if(d > 0) stringBuilder.append(String.valueOf((char) d));

String string = stringBuilder.toString();

What this does is it ensures that each characters is not your default 0 that you set earlier (int a = 0; ...) before it puts it on the string, because sites don't like it when you say "example.com/test\0", they'd prefer "example.com/test". Not sure if I made this completely clear so just tell me if you have any questions. Simply put, you were checking how many characters you needed and setting a,b,c, and d likewise but then you proceeded to append all 4 no matter how long you knew it was


text:
Q: Is it possible to have line number for erlang source code? The emacs is used and erlang code is for print.
Because the author modifying the source code in git, sourcetree shows me line number. If the line number is printed, it is much better to quickly find it by line number. But how to configure it?

A: You can use line number mode, but you can even use goto-line to jump to a line number directly:
`M-g M-g'
`M-g g'
     Read a number N and move point to the beginning of line number N
     (`goto-line').  Line 1 is the beginning of the buffer.  If point
     is on or just after a number in the buffer, that is the default
     for N.  Just type <RET> in the minibuffer to use it.

A: If you'd like to have visual line numbers (like in Eclipse for instance) you can have a look at linum-mode (it's part of Emacs since version 23). To enable linum globally just add this line to your .emacs (or equivalent):
(global-linum-mode +1)

A: You can use a2ps to create the printout.  It accepts the options -C (put line number on every fifth line) and --line-number=NUM (put line number on every NUMth line).  For example:
a2ps -o foo.ps -C foo.erl

A: You can use highlight.
It supports both line numbering and Erlang syntax highlighting.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Line bundles over $\Bbb P^1_k$ I am trying to understand the line bundle $O(1)$ over $\Bbb P^1_k$ and why

$$ O(1)^{\otimes n} = O(n)$$ from Vakil's notes, p398, line 6.

His explanation is rather long, so I took a screen shot.

I don't understand Vakil's explanation of why we have the equality because of the transition functions.

A: The whole point here is that if we take two invertible sheaves $\scr L$ and $\scr M$ on $X$ and an open cover $\{U_i\}$ of $X$ such that $\mathscr L$ and $\scr M$ are both trivializable, so that $\scr L$ and $\scr M$ are given by transition functions (satisfying the cocyle conditions) over the intersections, say by $f_{ij}\in\mathscr O_X(U_{ij})^\times$ and $g_{ij}\in\mathscr O_X(U_{ij})^\times$ respectively (I am writing $U_{ij}:=U_i\cap U_j$), then $\mathscr L\otimes\scr M$ is also trivializable on the cover $\{U_i\}$ and the associated transition functions for the tensor product on this cover are exactly given by $f_{ij}g_{ij}$ over $U_{ij}$.
How to see this? Well let's recall quickly where the "transition functions" are coming from; for each $i$ we have isomorphisms $\varphi_i:\mathscr L|_{U_i}\to\mathscr O_X|_{U_i}$, and then over $U_{ij}$ we have an isomorphism
$$\mathscr O_X|_{U_{ij}}\overset{\varphi_i^{-1}|_{U_{ij}}}\longrightarrow\mathscr L|_{U_{ij}}\overset{\varphi_j|_{U_{ij}}}\longrightarrow\mathscr O_X|_{U_{ij}}$$
but any such isomorphism is determined by a global section of $\mathscr O_X|_{U_{ij}}$, given by the image of $1\in\mathscr O_{X}(U_{ij})$ under the map on sections of $U_{ij}$, and this is exactly the element $f_{ij}$ we are calling the transition function (sorry for the drawn out details if this is all obvious to you); similarly we have $g_{ij}$ coming from $\psi_j\circ\psi_i^{-1}$ (actually the restrictions to $U_{ij}$ as we wrote more carefully above), where $\psi_i:\mathscr M|_{U_i}\to\mathscr O_X|_{U_i}$ are some local trivializations for $\mathscr M$.
Now notice we have a sequence of isomorphisms
$$(\mathscr L\otimes\mathscr M)|_{U_i}\longrightarrow\mathscr L|_{U_i}\otimes\mathscr M|_{U_i}\overset{\varphi_i\otimes\psi_i}\longrightarrow\mathscr O_X|_{U_i}\otimes\mathscr O_X|_{U_i}\longrightarrow\mathscr O_X|_{U_i}$$
(the composition of which we will call $\rho_i$) where the last map is just multiplication, and this gives us explicit trivializations of $\mathscr L\otimes\mathscr M$ on the cover $\{U_i\}$. Now that we know more precisely what the transitions exactly are from our discussion above, let's compute them with respect to our chosen trivializations $\rho_i$; the map $\rho_j\circ\rho_i^{-1}$ on sections over $U_{ij}$ is explicitly the composition
$$\mathscr O_X(U_{ij})\to\mathscr O_X(U_{ij})\otimes\mathscr O_X(U_{ij})\overset{\varphi_i^{-1}\otimes\psi_i^{-1}}\longrightarrow\mathscr L(U_{ij})\otimes\mathscr M(U_{ij})\overset{\varphi_j\otimes\psi_j}\longrightarrow\mathscr O_X(U_{ij})\otimes\mathscr O_X(U_{ij})\to\mathscr O_X(U_{ij})$$
and then if we chase down where $1\in\mathscr O_X(U_{ij})$ goes under this map we find
$$1\mapsto 1\otimes 1\mapsto \varphi_i^{-1}(1)\otimes\psi_i^{-1}(1)\mapsto(\varphi_j\circ\varphi_i^{-1})(1)\otimes(\psi_j\circ\psi_i^{-1})(1)=f_{ij}\otimes g_{ij}\mapsto f_{ij}g_{ij}$$
proving $f_{ij}g_{ij}$ indeed are the transition functions of the tensor product over this cover.
Hope this helps; when I was learning this stuff I was furious there were tons of details like this nobody was being precise about, so I tried to be as explicit as I could.


text:
Q: Angular i18n == multiple copies of the same app? I'm new to the i18n in Angular. (And I'm using Angular 5.1.0.)
I decided to use the built-in i18n (and not ngx-translate or other), because I think that will be more supported in the future.
I started to read the official documentation and other articles, but there is one thing I don't get:
Let's say that I have to use 3 different languages, then... I have to build my application 3 times? So basically that means, that I have 3 copies of the same application, and switching between languages is actually loading the other copy of the app?
I know, that I can't change language in runtime, but having multiple copies of the same app doesn't feel right. I hope I'm wrong. Or is there any other solution to this?


text:
Q: Resuming activity from where it left if user killed the app manually I am working on one application in which i move from Activity A(Main Activity) to Activity B to  Activity C.
All of this is working fine but the problem occurs when user killed the app by removing it from Task tray.
To understand my problem say user moved from A to B and then C but before finishing the task in activity C user killed the app.
so when user again opens the app by pressing App icon i want to start the last activity C where user was when he killed the app instead of android default behavior of starting(Main Activity A) a fresh instance of app again.
What i have tried:
1) I tried using "onSaveInstanceState" and "onRestoreInstanceState", but i think they are used when orientation is changed or we go back by pressing back button.
2) I tried to save everything in "onPause" as onpause calls 99.99% times when activity destroyed and by using static flags i opens the last activity and it worked for me but i want some good example or technique to this work.
so can anyone help me on achieving the same..??
I request fellow members to provide code examples.
thanks in advance.

A: Store the state in every Activity's @onPause().
So in every Activity you want:
@Override
protected void onPause() {
    super.onPause();

    SharedPreferences prefs = getSharedPreferences("RESTART", MODE_PRIVATE);
    Editor editor = prefs.edit();
    editor.putString("last_left", getClass().getName());
    editor.commit();
}

And a Shell Activity which will be a Launcher, Main Activity:
public class Shell extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Class<?> classActivity;

        try {
            SharedPreferences prefs = getSharedPreferences("RESTART", MODE_PRIVATE);
            classActivity = Class.forName(prefs.getString("last_left", getClass.getName()));
        }
        catch(ClassNotFoundException ex) {
            classActivity = your_Activity1.class;
        }

        startActivity(new Intent(this, classActivity));
    }
}

[Source Modified]

A: you can use SharedPreferences to store last user state.@onPause activity
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME,  MODE_PRIVATE).edit();
editor.putString("state", "A/B/C");
editor.commit();

OnResume Activity
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
String stateApp = prefs.getString("state", null);

if (stateApp != null) {
   switc(stateApp){
      case 'A':
        // Go TO A activity
        break;

      case 'B':
        // Go TO B activity
        break;
      default:
       // Go TO C activity
        break;

   }
}

A: The Intent that was used to launch the activity is saved by the system when the process is about to be killed.Once the user returns into the app which has been killed, then the app is restored and the same Intent (Activity A in your case) is fired to launch the activity including all the extras that it might have.
Go for SharedPrefrences:https://developer.android.com/reference/android/content/SharedPreferences.html
refer the official documentation.

A: Try to use sharedPreferences concept, save the activity name in sharedPreferences while the opening of that activity, then check the sharedPreferences value while reopening the application. I think you got it!
sample tutorial link:
https://developer.android.com/training/basics/data-storage/shared-preferences.html


text:
Q: How to do a index/match conditional formatting on a cell that contains structured table references I am trying to get the cell to be colored red using conditional formatting when the matched text is "Monthly Regular"
The sample code is below:
=IF(index(Salary[Type],match($A2,Salary[Person],0))="Monthly Regular",TRUE,FALSE)

The error i'm getting is:

A: To use a structured table reference in a conditional formatting formula, use the INDIRECT function. So your conditional formatting formula becomes:
=INDEX(INDIRECT("Salary[Type]"),MATCH($A2,INDIRECT("Salary[Person]"),0))="Monthly Regular"

Note also that you don't need the IF... TRUE,FALSE function.


text:
Q: Dark L in unstressed syllables I was wondering. I was reading in one forum about the dark L someone said about how you can also have a dark L in an unstressed syllable so a word like only (ˈoʊnli)  will actually have dark L.
Can someone enlighten me a little.bit.more about this please?
However, a word like maleficent wouldn't have a Dark L, it'll have a Light L, since the Letter L  Is the stressed in the word.
I need a little help about unstressed L's being a Dark L.

A: To start with, I would say not to worry about this too much, as I think it would be hard to perceive the difference in this position. For me, "dark l" (i.e. /l/ with a back articulation, phonetically transcribed as [ɫ]) is most noticeable in its effect on the pronunciation of a preceding vowel, so when I try to pronounce the /l/ in a word like "only" as dark vs. light, I can't hear much difference.
It seems somewhat plausible to me that /l/ in a word like "only" might be dark, although it certainly is light in many accents. If you're getting into the phonetic details, you might want to know that according to the phonetician Jack Windsor Lewis, "only" is often pronounced without any [l] sound at all (see my answer to the question Is it common to pronounce 'only' as 'own-knee'?).
Different accents are known to follow different rules for the distribution of light and dark /l/. As Janus Bahs Jacquet said, there are supposed to be accents that take one of the two extreme options of "all /l/s are light" or "all /l/s are dark". And there are a number of different types of in-between rules:

*

*For "RP" English, the rule is typically described as using light /l/ before a vowel (or before /j/), and dark /l/ elsewhere. Word boundaries are supposed to be irrelevant, so we would hear light /l/ in a context like "full of sand".

*For "SBE" (which is supposed to be a modern British accent, unlike "RP") the rule may be somewhat different. One exception to the "preceding a vowel" rule that I've seen given is syllabic l: according to this web page, that would be dark in "SBE" even when a vowel follows.

*Bermúdez-Otero (2013) cites Sproat and Fujimura (1993) as describing a different rule for the distribution of dark /l/ in a certain accent of American English. In this accent, word-final /l/ is always dark, regardless of whether a vowel or a consonant follows, but word-internal /l/ is light when a vowel follows. The examples given to illustrate this are "Beelik" (light l) vs. "Beel equates" (dark l).

*There are accents of American English and of British English that show l-darkening in more contexts (yellow and village are the examples given). Bermúdez-Otero analyzes these accents as having a "foot-based" rule, like the rule for t-flapping. For this rule, stress is relevant: /l/ cannot be dark at the start of a stressed syllable, but it can be dark at the start of an unstressed syllable (assuming that we syllabify words like "holy" as "ho.ly").
I didn't see a detailed analysis of how this rule was supposed to apply. For t-flapping, Bermúdez-Otero says there are actually two rules involved: at the word level, /t/ in non-foot-initial position is supposed to be lenited, and then at the phrase level, lenited /t/ is supposed to be flapped when it is followed by a vowel and preceded by /r/ or a vowel. This allows us to explain why we don't see flapped /t/ in words like "guilty". If a similar two-part process is supposed to account for l-darkening, then we would only expect to see "dark" l when the preceding sound is a vowel or /r/. But it seems plausible to me that some accents might have a simple rule of darkening non-foot-initial /l/ regardless of the identity of the preceding sound.

My accent has what Bermúdez-Otero would call a "foot-based" type rule, and I use dark /l/ in angrily and daily. Based on the pronunciation of the vowel, I believe that I use light l in lowly, slowly and grayly, and sometimes in gaily, presumably because the morpheme boundary is more salient than the one in daily. I always use dark l in "-Vly" words when there is no morpheme boundary before the /l/, e.g. holy, mealy, steely, wooly.
I use dark l in words like wholly, totally, finally.
I think that I use light l in words like invisibly, unbearably.
I think that I use light l in only, although as mentioned in the first two paragraphs, it doesn't seem very noticeable.

A: I don't think the "l" in "only" would be dark, because the change to dark "l" depends on the syllable position of "l"; "l" is dark in the offset of a syllable, by which I mean the part of the syllable after the vowel. "Only" is divided into two syllables "on-ly", and "l" is at the beginning of the second syllable, even though the vowel of the second syllable is not stressed, so the "l" is probably not dark.
By the same reasoning, the "l" of your other example, "curly", should also not be dark, but this is less clear than the first example, because the syllable division could be "curl-y", in which case the "l" is at the end of a syllable and should be dark. In my own speech, the syllable division is "cur-ly", and the "l" is not dark, just as for your first example, but this might not be true for other people. There are two complicating factors here that might give a different result:
(1) If you take away the last vowel in the first example, you are left with "onl", which is not a possible word of English. But in the second example, you are left with "curl", which is a word, and in fact is the word from which "curly" is derived. Since syllable boundaries sometimes tend to follow the divisions between meaningful parts of words, this might cause the syllable division "curl-y".
(2) Sometimes a single consonant in English between a stressed vowel and an unstressed vowel is shifted into the preceding syllable with the stressed vowel. Since "ur" is a single stressed vowel (even though it's spelled with two letters), and "-y" is an unstressed vowel, the "l" might shift into the first syllable for this reason. That should make the "l" dark. (But that doesn't happen in my own pronunciation.)


text:
Q: Convergence of an infinite series containing the sine function Does the following infinite series converge?
$\displaystyle \sum _{k=1}^{\infty } \frac{\sin (k)}{\sqrt[3]{k^2+1}}$
In case it converges, does it have a closed-form value or solution? Or just a numerical solution?

A: Dirichlet's test can be used to show the convergence of
$$\sum_{n=1}^\infty\sin(n)a_n$$
for any monotone $(a_n)_{n=1}^\infty$ that tends to $0$.
It is doubtful that this has a closed form, though numerical approximation can be managed. For example, this program gives the approximation:
$$0.8529108\approx\sum_{n=1}^\infty\frac{\sin(n)}{\sqrt[3]{n^2+1}}$$
and this program gives:
$$0.852910820165\approx\sum_{n=1}^\infty\frac{\sin(n)}{\sqrt[3]{n^2+1}}$$

A: As Yanko commented
$$\sum _{k=1}^{\infty } \frac{\sin (k)}{\sqrt[3]{k^2+1}} <\sum _{k=1}^{\infty } \frac{\sin (k)}{\sqrt[3]{k^2}}= \frac{1}{2} i
   \left(\text{Li}_{\frac{2}{3}}\left(e^{-i}\right)-\text{Li}_{\frac{2}{3}}\left(e^
   i\right)\right)\approx 1.06095$$


text:
Q: Using cur_column() with mutate(across(all_of())) - Recursive Error My goal is to take a subset of columns (COL_NAMES) within a dataframe (LR_DATA) and apply a function (FUNCTION). The dataframe (LR_DATA) is mostly nested vectors except for one identifying column (var1). However, I cannot seem to correctly pass the override inputs which are nested under the current column name with the additional suffix "_OVERRIDE".
TRENDED_LR_DATA <- LR_DATA %>% mutate(across(all_of(COL_NAMES), ~list(FUNCTION(var1, unlist(var2), unlist(.x), unlist(!!sym(paste0(cur_column(), "_OVERRIDE")))))))

Specifically I get the error:

If I replace cur_column() with a hardcoded string the code works (though obviously not as intended since it would be referencing the same override column for each specified column in COL_NAMES. Any tips this group has would be greatly appreciated - I'm relatively new to R so please bear with me ^_^.
EDIT: Below is code to reproduce the error in full. Sorry for not including this on the original question submission.
library(dplyr)

LR_DATA <- data.frame(STATE = c(1,2,3),
                      YEAR = c(2000,2001,2002),
                      DEVT_A = c(2,4,6),
                      DEVT_B = c(3,6,9),
                      DEVT_C = c(4,8,12))

LOSS_COLS <- c("DEVT_A", "DEVT_B", "DEVT_C")

DATA_OVERRIDE <- data.frame(STATE = c(1,2,3),
                            DEVT_A_OVERRIDE = c(NaN,1,1),
                            DEVT_B_OVERRIDE = c(1,1,1),
                            DEVT_C_OVERRIDE = c(1.5,1.5,1.5))

LR_DATA <- LR_DATA %>% left_join(DATA_OVERRIDE, by = 'STATE')

TRENDED_LR_DATA <- LR_DATA %>% summarise(across(everything(), list), .groups = "keep") %>%
  mutate(across(all_of(LOSS_COLS), ~list(TREND_LOSS(unlist(.x), unlist(YEAR), unlist( !!sym(paste0(cur_column(), "_OVERRIDE"))) ))))

TREND_LOSS <-

  function(LOSSES,
           YEARS,
           OVERRIDES) {

  x <- YEARS
  y = log(LOSSES)
  xy = x * y
  x_sq = x * x
  sum_x <- sum(x)
  sum_y <- sum(y)
  sum_xy <- sum(xy)
  sum_x_sq <- sum(x_sq)
  n <- length(YEARS)
  Slope <- (n*sum_xy - sum_x*sum_y) / (n*sum_x_sq - sum_x*sum_x)

  OVERRIDES[is.na(OVERRIDES)] <- Slope
  TRENDED_LOSSES <- LOSSES*exp(OVERRIDES)
  return(TRENDED_LOSSES)

  }

}


text:
Q: In Sharepoint 2010 is it possible to click a list item and have that bring up a form again to edit this item? I have a pretty typical Sharepoint List that looks like below:

Is there way I can set this view up so that I can click somewhere on one of the records (i.e. Jonathan Morgan) and this will pull up a form with all the existing information already entered in but where I can edit all of the information in this row?
Thanks!

A: One of the available columns that you can add to the view is titled "Edit", and it usually works best to place this column first in the view. It will display as a small icon that, when clicked, will bring up the edit form for the record.

A: You have three options to open up an edit form from the list.

*

*Edit

*Title

Edit opens the edit from, while title opens the view form, from which you can navigate to edit from also. You can enable these columns by modifying the view.

Other way is to create a calculated column and adding a link to the form if you know the URL like:
=" "&[%field_name%]&""

A: If you want to be able to click anywhere then you'll have to create some custom javascript on your list view page that will add an "onclick" event handler to every "tr" that will open the edit page for that item. It would work but then you end up with duplicate onclick events if the row has any links in it.


text:
Q: Is it possible to use synchronous process in functions? i=0;
If rising_edge (clk) then
y(i)<=x(i) ;
i=:i+1;
end if;

Is a block like above, possible in a function block? If it is not, is there any function-like sub-program style to achieve this?
Or is there any synthetizable 'for loop' usage instead of 'if statement'?

A: You can use procedures:
  procedure SetBits(signal clk : in std_logic; signal y : out std_logic_vector(7 downto 0)) is
  begin
    for i in 7 downto 0 loop
      wait until (rising_edge(clk));
      y(i) <= '1';
    end loop;
  end procedure;

and then something like this
  sequential : process
  begin
    SetBits;
    wait;
  end process sequential;

A: No, you can't have a clocked process inside a function. You can use a loop, though:
if rising_edge(clk) then
  for i in 0 to x'length - 1 loop
    y(i) <= x(i); -- or whatever operation
  end loop;
end if;

You can wrap the for-loop portion only in a function if you really want:
function f(x : std_logic_vector) return std_logic_vector is
  variable result : std_logic_vector(x'range);
begin
  for i in x'range loop
    result(i) := x(i); -- or whatever operation
  end loop;
  return result;
end function f;

if rising_edge(clk) then
  y <= f(x);
end if;

I'm assuming you want to do more than just assign bits, of course, or else you wouldn't need a loop or function at all.


text:
Q: FlinkKafkaConsumer082 auto.offset.reset setting doesn't work? I have a Flink streaming program which read data from a topic of Kafka. In the program, auto.offset.reset is set to "smallest". When test in IDE/Intellij-IDEA, the program could always read data from the beginning of the topic. Then I set up a flink/kafka cluster and produced some data into kafka topic. The first time I run the streaming job, it could read data from the beginning of the topic. But after that I stopped the streaming job and run it again, it will not read data from the beginning of the topic. How could I make the program always read data from the beginning of the topic?
    Properties properties = new Properties();
    properties.put("bootstrap.servers", kafkaServers);
    properties.put("zookeeper.connect", zkConStr);
    properties.put("group.id", group);
    properties.put("topic", topics);
    properties.put("auto.offset.reset", offset);

    DataStream<String> stream = env
            .addSource(new FlinkKafkaConsumer082<String>(topics, new SimpleStringSchema(), properties));

A: If you want to read always from the beginning you need to disable checkpointing in your stream context.
Also disable it on the level of consumer properties:
enable.auto.commit=false or auto.commit.enable=false (depends on kafka version)
Another way:
you can keep ckeckpointing for failover but generate new group.id when you need to read from the beginning(just clean up sometimes zookeeper)


text:
Q: Facing a lot of issues after upgrading to 18.04.2 I recently updated my system to 18.04.2 the kernel version is 4.18.0-15-generic and I'm following following issues:

*

*After the boot starts up the lockscreen is never loading and i see a splash/flashing screen continously.

*When i lock my laptop and when i want to sign in back the same splash/flashing screen is seen again i need to force shutdown my laptop and start again.

Is this a bug?


text:
Q: TF - ValueError: The two structures don't have the same number of elements I am trying to run the code for a research paper Learned Optimizers that Scale and Generalize
When I run the metarun.py file (which is the main file), I get the following error:
Traceback (most recent call last):
File "metarun.py", line 394, in
tf.app.run()
File "/home/rvl224/anaconda3/lib/python3.5/site-packages/tensorflow/python/platform/app.py", line 48, in run
_sys.exit(main(_sys.argv[:1] + flags_passthrough))
File "metarun.py", line 388, in main
callbacks=[])
File "/home/rvl224/models/research/metaopt.py", line 184, in train_optimizer
train_output = opt.train(problem, dataset)
File "/home/rvl224/models/research/learned_optimizer/optimizer/trainable_optimizer.py", line 347, in train
swap_memory=True, shape_invariants=invariants)
File "/home/rvl224/anaconda3/lib/python3.5/site-packages/tensorflow/python/ops/control_flow_ops.py", line 2816, in while_loop
result = loop_context.BuildLoop(cond, body, loop_vars, shape_invariants)
File "/home/rvl224/anaconda3/lib/python3.5/site-packages/tensorflow/python/ops/control_flow_ops.py", line 2640, in BuildLoop
pred, body, original_loop_vars, loop_vars, shape_invariants)
File "/home/rvl224/anaconda3/lib/python3.5/site-packages/tensorflow/python/ops/control_flow_ops.py", line 2597, in _BuildLoop
nest.assert_same_structure(list(packed_vars_for_body), list(body_result))
File "/home/rvl224/anaconda3/lib/python3.5/site-packages/tensorflow/python/util/nest.py", line 222, in assert_same_structure
% (len_nest1, nest1, len_nest2, nest2))
ValueError: The two structures don't have the same number of elements.

First structure (120 elements):
[<tf.Tensor 'while/Identity:0' shape=() dtype=int32>, <tf.Tensor 'while/Identity_1:0' shape=() dtype=float32>, [<tf.Tensor 'while/Identity_2:0' shape=(11, 1) dtype=float32>, <tf.Tensor 'while/Identity_3:0' shape=(3, 1) dtype=float32>, <tf.Tensor 'while/Identity_4:0' shape=(9, 1) dtype=float32>, <tf.Tensor 'while/Identity_5:0' shape=(7, 1) dtype=float32>, <tf.Tensor 'while/Identity_6:0' shape=(5, 1) dtype=float32>, <tf.Tensor 'while/Identity_7:0' shape=(13, 1) dtype=float32>, <tf.Tensor 'while/Identity_8:0' shape=(12, 1) dtype=float32>], [<tf.Tensor 'while/Identity_9:0' shape=(11, 1) dtype=float32>, <tf.Tensor 'while/Identity_10:0' shape=(3, 1) dtype=float32>, <tf.Tensor 'while/Identity_11:0' shape=(9, 1) dtype=float32>, <tf.Tensor 'while/Identity_12:0' shape=(7, 1) dtype=float32>, <tf.Tensor 'while/Identity_13:0' shape=(5, 1) dtype=float32>, <tf.Tensor 'while/Identity_14:0' shape=(13, 1) dtype=float32>, <tf.Tensor 'while/Identity_15:0' shape=(12, 1) dtype=float32>], [[<tf.Tensor 'while/Identity_16:0' shape=(11, 1) dtype=float32>, <tf.Tensor 'while/Identity_17:0' shape=(11, 1) dtype=float32>, <tf.Tensor 'while/Identity_18:0' shape=(11, 1) dtype=float32>, <tf.Tensor 'while/Identity_19:0' shape=(11, 1) dtype=float32>, <tf.Tensor 'while/Identity_20:0' shape=(11, 1) dtype=float32>, <tf.Tensor 'while/Identity_21:0' shape=(1, 20) dtype=float32>, <tf.Tensor 'while/Identity_22:0' shape=(11, 1) dtype=float32>, <tf.Tensor 'while/Identity_23:0' shape=(11, 1) dtype=float32>, <tf.Tensor 'while/Identity_24:0' shape=(11, 1) dtype=float32>, <tf.Tensor 'while/Identity_25:0' shape=(11, 1) dtype=float32>, <tf.Tensor 'while/Identity_26:0' shape=(11, 1) dtype=float32>, <tf.Tensor 'while/Identity_27:0' shape=(11, 10) dtype=float32>, <tf.Tensor 'while/Identity_28:0' shape=(11, 1) dtype=float32>, <tf.Tensor 'while/Identity_29:0' shape=(11, 1) dtype=float32>], [<tf.Tensor 'while/Identity_30:0' shape=(3, 1) dtype=float32>, <tf.Tensor 'while/Identity_31:0' shape=(3, 1) dtype=float32>, <tf.Tensor 'while/Identity_32:0' shape=(3, 1) dtype=float32>, <tf.Tensor 'while/Identity_33:0' shape=(3, 1) dtype=float32>, <tf.Tensor 'while/Identity_34:0' shape=(3, 1) dtype=float32>, <tf.Tensor 'while/Identity_35:0' shape=(1, 20) dtype=float32>, <tf.Tensor 'while/Identity_36:0' shape=(3, 1) dtype=float32>, <tf.Tensor 'while/Identity_37:0' shape=(3, 1) dtype=float32>, <tf.Tensor 'while/Identity_38:0' shape=(3, 1) dtype=float32>, <tf.Tensor 'while/Identity_39:0' shape=(3, 1) dtype=float32>, <tf.Tensor 'while/Identity_40:0' shape=(3, 1) dtype=float32>, <tf.Tensor 'while/Identity_41:0' shape=(3, 10) dtype=float32>, <tf.Tensor 'while/Identity_42:0' shape=(3, 1) dtype=float32>, <tf.Tensor 'while/Identity_43:0' shape=(3, 1) dtype=float32>], [<tf.Tensor 'while/Identity_44:0' shape=(9, 1) dtype=float32>, <tf.Tensor 'while/Identity_45:0' shape=(9, 1) dtype=float32>, <tf.Tensor 'while/Identity_46:0' shape=(9, 1) dtype=float32>, <tf.Tensor 'while/Identity_47:0' shape=(9, 1) dtype=float32>, <tf.Tensor 'while/Identity_48:0' shape=(9, 1) dtype=float32>, <tf.Tensor 'while/Identity_49:0' shape=(1, 20) dtype=float32>, <tf.Tensor 'while/Identity_50:0' shape=(9, 1) dtype=float32>, <tf.Tensor 'while/Identity_51:0' shape=(9, 1) dtype=float32>, <tf.Tensor 'while/Identity_52:0' shape=(9, 1) dtype=float32>, <tf.Tensor 'while/Identity_53:0' shape=(9, 1) dtype=float32>, <tf.Tensor 'while/Identity_54:0' shape=(9, 1) dtype=float32>, <tf.Tensor 'while/Identity_55:0' shape=(9, 10) dtype=float32>, <tf.Tensor 'while/Identity_56:0' shape=(9, 1) dtype=float32>, <tf.Tensor 'while/Identity_57:0' shape=(9, 1) dtype=float32>], [<tf.Tensor 'while/Identity_58:0' shape=(7, 1) dtype=float32>, <tf.Tensor 'while/Identity_59:0' shape=(7, 1) dtype=float32>, <tf.Tensor 'while/Identity_60:0' shape=(7, 1) dtype=float32>, <tf.Tensor 'while/Identity_61:0' shape=(7, 1) dtype=float32>, <tf.Tensor 'while/Identity_62:0' shape=(7, 1) dtype=float32>, <tf.Tensor 'while/Identity_63:0' shape=(1, 20) dtype=float32>, <tf.Tensor 'while/Identity_64:0' shape=(7, 1) dtype=float32>, <tf.Tensor 'while/Identity_65:0' shape=(7, 1) dtype=float32>, <tf.Tensor 'while/Identity_66:0' shape=(7, 1) dtype=float32>, <tf.Tensor 'while/Identity_67:0' shape=(7, 1) dtype=float32>, <tf.Tensor 'while/Identity_68:0' shape=(7, 1) dtype=float32>, <tf.Tensor 'while/Identity_69:0' shape=(7, 10) dtype=float32>, <tf.Tensor 'while/Identity_70:0' shape=(7, 1) dtype=float32>, <tf.Tensor 'while/Identity_71:0' shape=(7, 1) dtype=float32>], [<tf.Tensor 'while/Identity_72:0' shape=(5, 1) dtype=float32>, <tf.Tensor 'while/Identity_73:0' shape=(5, 1) dtype=float32>, <tf.Tensor 'while/Identity_74:0' shape=(5, 1) dtype=float32>, <tf.Tensor 'while/Identity_75:0' shape=(5, 1) dtype=float32>, <tf.Tensor 'while/Identity_76:0' shape=(5, 1) dtype=float32>, <tf.Tensor 'while/Identity_77:0' shape=(1, 20) dtype=float32>, <tf.Tensor 'while/Identity_78:0' shape=(5, 1) dtype=float32>, <tf.Tensor 'while/Identity_79:0' shape=(5, 1) dtype=float32>, <tf.Tensor 'while/Identity_80:0' shape=(5, 1) dtype=float32>, <tf.Tensor 'while/Identity_81:0' shape=(5, 1) dtype=float32>, <tf.Tensor 'while/Identity_82:0' shape=(5, 1) dtype=float32>, <tf.Tensor 'while/Identity_83:0' shape=(5, 10) dtype=float32>, <tf.Tensor 'while/Identity_84:0' shape=(5, 1) dtype=float32>, <tf.Tensor 'while/Identity_85:0' shape=(5, 1) dtype=float32>], [<tf.Tensor 'while/Identity_86:0' shape=(13, 1) dtype=float32>, <tf.Tensor 'while/Identity_87:0' shape=(13, 1) dtype=float32>, <tf.Tensor 'while/Identity_88:0' shape=(13, 1) dtype=float32>, <tf.Tensor 'while/Identity_89:0' shape=(13, 1) dtype=float32>, <tf.Tensor 'while/Identity_90:0' shape=(13, 1) dtype=float32>, <tf.Tensor 'while/Identity_91:0' shape=(1, 20) dtype=float32>, <tf.Tensor 'while/Identity_92:0' shape=(13, 1) dtype=float32>, <tf.Tensor 'while/Identity_93:0' shape=(13, 1) dtype=float32>, <tf.Tensor 'while/Identity_94:0' shape=(13, 1) dtype=float32>, <tf.Tensor 'while/Identity_95:0' shape=(13, 1) dtype=float32>, <tf.Tensor 'while/Identity_96:0' shape=(13, 1) dtype=float32>, <tf.Tensor 'while/Identity_97:0' shape=(13, 10) dtype=float32>, <tf.Tensor 'while/Identity_98:0' shape=(13, 1) dtype=float32>, <tf.Tensor 'while/Identity_99:0' shape=(13, 1) dtype=float32>], [<tf.Tensor 'while/Identity_100:0' shape=(12, 1) dtype=float32>, <tf.Tensor 'while/Identity_101:0' shape=(12, 1) dtype=float32>, <tf.Tensor 'while/Identity_102:0' shape=(12, 1) dtype=float32>, <tf.Tensor 'while/Identity_103:0' shape=(12, 1) dtype=float32>, <tf.Tensor 'while/Identity_104:0' shape=(12, 1) dtype=float32>, <tf.Tensor 'while/Identity_105:0' shape=(1, 20) dtype=float32>, <tf.Tensor 'while/Identity_106:0' shape=(12, 1) dtype=float32>, <tf.Tensor 'while/Identity_107:0' shape=(12, 1) dtype=float32>, <tf.Tensor 'while/Identity_108:0' shape=(12, 1) dtype=float32>, <tf.Tensor 'while/Identity_109:0' shape=(12, 1) dtype=float32>, <tf.Tensor 'while/Identity_110:0' shape=(12, 1) dtype=float32>, <tf.Tensor 'while/Identity_111:0' shape=(12, 10) dtype=float32>, <tf.Tensor 'while/Identity_112:0' shape=(12, 1) dtype=float32>, <tf.Tensor 'while/Identity_113:0' shape=(12, 1) dtype=float32>]], [<tf.Tensor 'while/Identity_114:0' shape=(1, 20) dtype=float32>], <tf.Tensor 'while/Identity_115:0' shape=(?,) dtype=float32>, <tf.Tensor 'while/Identity_116:0' shape=() dtype=float32>, <tf.Tensor 'while/Identity_117:0' shape= dtype=float32>, <tf.Tensor 'while/Identity_118:0' shape= dtype=int32>, <tf.Tensor 'while/Identity_119:0' shape= dtype=int32>]

Second structure (23 elements):
[<tf.Tensor 'while/add_21:0' shape=() dtype=int32>, <tf.Tensor 'while/Add:0' shape=() dtype=float32>, [<tf.Tensor 'while/LOL/PerTensor/sub_15:0' shape=(11, 1) dtype=float32>, <tf.Tensor 'while/LOL/PerTensor_1/sub_15:0' shape=(3, 1) dtype=float32>, <tf.Tensor 'while/LOL/PerTensor_2/sub_15:0' shape=(9, 1) dtype=float32>, <tf.Tensor 'while/LOL/PerTensor_3/sub_15:0' shape=(7, 1) dtype=float32>, <tf.Tensor 'while/LOL/PerTensor_4/sub_15:0' shape=(5, 1) dtype=float32>, <tf.Tensor 'while/LOL/PerTensor_5/sub_15:0' shape=(13, 1) dtype=float32>, <tf.Tensor 'while/LOL/PerTensor_6/sub_15:0' shape=(12, 1) dtype=float32>], [<tf.Tensor 'while/LOL/PerTensor/sub_15:0' shape=(11, 1) dtype=float32>, <tf.Tensor 'while/LOL/PerTensor_1/sub_15:0' shape=(3, 1) dtype=float32>, <tf.Tensor 'while/LOL/PerTensor_2/sub_15:0' shape=(9, 1) dtype=float32>, <tf.Tensor 'while/LOL/PerTensor_3/sub_15:0' shape=(7, 1) dtype=float32>, <tf.Tensor 'while/LOL/PerTensor_4/sub_15:0' shape=(5, 1) dtype=float32>, <tf.Tensor 'while/LOL/PerTensor_5/sub_15:0' shape=(13, 1) dtype=float32>, <tf.Tensor 'while/LOL/PerTensor_6/sub_15:0' shape=(12, 1) dtype=float32>], <map object at 0x7f0a9b8f4be0>, [<tf.Tensor 'while/LOL/Layer2_RNN/BiasGRUCell/add:0' shape=(1, 20) dtype=float32>], <tf.Tensor 'while/concat:0' shape=(?,) dtype=float32>, <tf.Tensor 'while/Identity_116:0' shape=() dtype=float32>, <tf.Tensor 'while/Identity_117:0' shape= dtype=float32>, <tf.Tensor 'while/Identity_118:0' shape= dtype=int32>, <tf.Tensor 'while/Identity_119:0' shape= dtype=int32>]

I tried following the solution as suggested here, but I am not able to figure as to where to make changes in the code. It would be a big help if anyone can guide a way!
Thanks in Advance :)

A: I too faced a similar error once.
The reason for this error might be because this code is Python 3.x incompatible and works only for Python 2.7.x version. Please check once and let me know!


text:
Q: Javascript Bug in stackoverflow title for new question? I'm using:
Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.6; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7
When I click the title element for adding a new question the text What's your programming question? Be specific, doesn't disappear until I click on another element on the page and then back to that element again.
This just started happening in the last day or two.

A: Confirmed (inconsistently): the text does not go away when the text field is clicked in (build version 6176) -- Firefox 3.5.7, Mac OSX 10.6.2. This is not always reproducible; it occurs about 75% of the time at the https://stackoverflow.com/questions/ask page.

A: This is by design -- the help text disappears when you begin typing.
The title field had to be handled a bit differently because it typically has focus when the page loads.
I think this might actually be a behavior we want to extend to the tags field, since the help text disappearing on focus is not exactly helpful when you, y'know, need help entering text on that field.. the one you just tabbed into.


text:
Q: Could not find my Intuit QBMS merchant account number I am new to QBMS my problem is that when I try to login to quickbooks merchant service (test environment) it redirect me to:  [https://merchantcenter.intuit.com/msc/portal/addAcct] but when I click to I need a confirmation code it's asking for me to submit the merchant account number . But I am not able to find my merchant account number even though I have followed all the steps described here [https://merchantcenter.intuit.com/wapweblet/ims-mp-help/en/qbms/svc_mp_find_account_number.html] . I try to resolve it for the last 2 days but I could not.

A: That is QBMS production and not a test environment. Try going through the steps here - https://developer.intuit.com/docs/030_qbms/0030_get_set_up - for testing.


text:
Q: past tense + potential (could + [verb]) I am trying to edit the Statement of Purpose for graduate school of a friend who is a non-native English speaker. I saw the sentence:

As a result, I could be admitted to [a certain undergraduate school], and I chose to go there.

The intent of the sentence was to say he studied a lot in high school, and was able to get into a certain undergraduate school.
As we all know, could + [verb] can either be past tense

When I was a boy, I could eat a lot of food

or a hypothetical

I could get into my dream school if I ace the GRE

But for some reason, with his sentence I only interpret it as a hypothetical. As a native speaker, I have the strong urge to correct the sentence to

As a result, I was able to be admitted to [a certain undergraduate school], and I chose to go there.

Does anyone have an explanation why, or a different interpretation of the original sentence?

A: This is one of the common errors made by learners. Perhaps, we already have a similar old question on our site, but because I can't remember one, I decide to post this answer.
You're right that was able to is more appropriate than could in the sentence. (I may go with managed to or perhaps simply write was admitted to ...) This grammar point in Practical English Usage by Michael Swan can explain this perfectly:

122 can and could (2): ability
5 past: could is not always possible
We use could for 'general ability' - for example to say that somebody could do something at any time, whenever he/she wanted.
    When I was younger, I could run 10km in under 40 minutes.
We do not normally use could to say that somebody did something on one occasion. Instead, we use other expressions.
    I managed to run 10km yesterday in under an hour. (NOT I could run 10km yesterday ...)
    How many eggs were you able to get? (NOT ... could you get?)
    [...]
However, we use couldn't to say that something did not happen on one occasion.
    I managed to find the street, but I couldn't find her house.

A: I find these questions to be particularly easy to answer by finding a counterexample - think of the construction in a different context, and see if that construction makes sense.
So, let's try this in the context of...leg surgery!

In 1985, the doctors operated on my foot. As a result, I could walk again, and I chose to become a runner.

Success! This construction seems to work just fine in a different context as the past tense.
Now as to why you seemed to only read it as a hypothetical, I can't say for sure. I can guess however! Looking at the sentence:

As a result, I could be admitted to [a certain undergraduate school], and I chose to go there.

The thing that clarifies that this is in the past tense is the past tense use of "choose" at the end in, "I chose to go there." Maybe because the sentence is long-ish and busy before that point, you just weren't noticing the past tense use very clearly? Maybe you've heard "could be admitted" used as a hypothetical many more times than as past tense (which is likely to be the case) so your mind automatically thinks of it as a hypothetical? Maybe it's another reason. I really don't know.
Either way, both sentences are correct. Both require context, and both mean the same thing.
EDIT:
After thinking about it, I did find one difference between the two. I think your edited version makes a little bit more sense logically.

As a result, I was able to be admitted to [a certain undergraduate school], and I chose to go there.

In this case, you use "I was able to be admitted" - this implies that your friend not only could be admitted, but also that he WAS admitted, which makes more sense when you follow up with "I chose to go there."
"I could be admitted" doesn't have the implication that "I was able to be" carries with it, so the logical jump is bigger between "I could be admitted" and "I chose to go there."
However, I'll maintain that they are both correct, and this distinction is very nit-picky. In practice, both mean the same thing.


text:
Q: Doctrine and quoting reserved word of MySql I have in my Symfony 4.3 project entity named Group and table group in MySql database. Group is a reserved word. I have 3 entities : User, Group, UserGroup. They have relations:  User ->OneToMany-> UserGroup   and Group -> OneToMany -> UserGroup ( UserGroup has additional attributes, so I can't use ManyToMany relation). When I try to get group names for user with id=1:
$entityManager = $this->getDoctrine()->getManager();
   $user = $entityManager->getRepository(User::class)
        ->find($id);
   $groups = $user->getUserGroups();

   foreach ($groups as $group) {
        $group_name = $group->getGroupId()->getName();
        echo $group_name, '<br>';
    }

I get error message :
You have an error: An exception occurred while executing 'SELECT t0.id AS id_1, t0.name AS name_2 FROM group t0 WHERE t0.id = ?' with params [1]: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'group t0 WHERE t0.id = 1' at line 1 with code: 0
There is a recipe in documentation (http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/basic-mapping.html#quoting-reserved-words) how to enable quoting of reserved words:
<?php
use Doctrine\ORM\Mapping\AnsiQuoteStrategy;

$configuration->setQuoteStrategy(new AnsiQuoteStrategy());

I don't understand where I have to use this code - in EntityManager, in Controller? And how I can get $configuration?

A: I think the better solution is to use ticks in the definition of your entity as mentioned in Doctrine Documentation.
<?php

namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity(repositoryClass="App\Repository\GroupRepository")
 * @ORM\Table(name="`group`")
 */
class Group
{
    // ...
}

Note, that this approach will work only if you are using the default quote strategy. So, delete quote_strategy parameter or set it as doctrine.orm.quote_strategy.default.
# config/packages/doctrine.yml

doctrine:
    # ...
    orm:
        quote_strategy: doctrine.orm.quote_strategy.default


text:
Q: Динамическая загрузка текстур в OpenGL Всем доброго времени суток. Появилась такая проблема:
Нужно динамически менять текстуру для примитива. Т.е. предварительно есть 4-5 текстур. Нужно во время работы программы изменять текстуры у примитива.
Все найденные мною мануалы показывают применение текстур на примере VAO, где текстура лежит в массиве с координатами/цветами и прочим. Но в таком случае смещение задаётся сразу и статически.
Подскажите пожалуйста, какая из идей может быть верной?
1) Прописать в массив сразу все координаты всех текстур. Т.е. помимо 9-ти координат примитива (пока пробую на обычном треугольнике) будут ещё 6 * 4 координат для текстур. И затем, в процессе работы программы, передавать в некую функцию аргумент, который будет значить текущее смещение для текущей текстуры.
2) С помощью uniform загружать не только текстуру, но и координаты текстуры в фрагментный шейдер. Тут встаёт вопрос, как это сделать? Это было бы значительно проще, по-моему. Но фрагментый шейдер описывает отдельные фрагменты, и координаты текстуры загружаются в формате vec2. Я понимаю, что в таком случае я не смогу загрузить сразу вес массив из 6-ти координат, и надо передавать каждые 2 координаты отдельно. Пробовал так:
        GLuint texLoc = glGetUniformLocation(ourShader.Program, "tex");
        GLuint texCoord = glGetUniformLocation(ourShader.Program, "texcoord");
        for (int j = 0; j < 3; j++)
        {
            glUniform2f(texCoord, vectorOfPrimitives[i].texcoord[j][0], vectorOfPrimitives[i].texcoord[j][1]);
        }
        glUniform1i(texLoc, texture);

И шейдер:
#version 330 core
in vec2 TexCoord;

out vec4 color;

uniform vec4 ourColor;
uniform vec2 texcoord;

uniform sampler2D ourTexture;

void main(){
    color = texture(ourTexture, TexCoord) * ourColor;
}

Это неправильно, но как ещё можно загрузить данные для каждой координаты в шейдер? И возможно ли это?

A: Вторая идея неверна в корне, так как не получится «оторвать» текстурные координаты от вершины, поместить их во внешний буфер, а в вершине оставить индекс. Корень проблемы — в усреднении значения вершинных атрибутов при растеризации точки внутри треугольника. Соответственно, дискретные повершинные индексы будет «размазаны» и тем самым искажёны.
Первая идея в чистом виде тоже неприемлема, так как ведёт к значительному увеличению размера массива вершинных атрибутов. Это плохо тем, что при нехватке в видеопамяти даже одного байта весь этот большой массив будет постоянно вытесняться в основное ОЗУ и возвращаться обратно, что сильно ударит по производительности.
Однако эту идею можно улучшить выносом координат в отдельные VBO, чтобы координаты для каждой из текстур лежали в отдельном буфере. Это работает, потому что функция glVertexAttribPointer(), задающая источник данных для указанного атрибута, копирует идентификатор текущего VBO в свои внутренние параметры. Как результат, мы можем привязать glBindVertexArray()-ом какой-то VBO, разметить в нём атрибуты, затем привязать другой VBO и разметить в нём ещё какие-то атрибуты (при этом шейдер продолжит помнить о первом буфере и о том, что и как из него можно вытащить).
Тогда процесс визуализации может выглядеть в коде следующим образом.
Пусть у нас имеются идентификаторы всех вершинных атрибутов, которые были либо явно заданы при компиляции посредством glBindAttribLocation(), либо получены после компиляции силами glGetAttribLocation().

*

*Если мы переключали шейдер вызовом glUseProgram(), и при этом у нас нет VAO, который бы хранил в себе всё состояние.

*

*Проходим по всем атрибутам и активируем их с помощью glEnableVertexAttribArray().

*Привязываем первый, «основной» буфер вызовом glBindVertexArray().

*Последовательно вызываем glVertexAttribIPointer(), указывая этим размещение всех атрибутов (кроме текстурных координат) в буфере.

*Привязываем другой буфер, с координатами, соответствующими нужной нам текстуре.
Чтобы упростить себе жизнь, можно хранить std::map, ключами которого являются пары «текстура – mesh», а полезной нагрузкой — идентификатор VBO-буфера.

*Вызываем glVertexAttribIPointer() для атрибута текстурных координат.

*Если же у нас есть VAO — активируем его и, ...

*

*если он подготовлен, производим шаги 1.4 и 1.5;

*если он только что создан, производим все действия в шаге 1.

*Визуализируем mesh с помощью glDrawElements(). И да, текстура к этому моменту уже должна быть активирована.


text:
Q: Maximum number of $m\times n$ rectangles that fit in a $k \times k$ square I'm sure this has been asked before but I have searched for ages and can't quite find what I'm looking for. Here's the problem:

Essentially what is the maximum possible number of rectangles of a given size $(m \times n)$ that will fit without overlapping in a given sized square ($k \times k$).

How can you tackle it?

A: In general, this kind of packing problem is very difficult.  Of course there is an obvious upper bound
of $\lfloor k^2/(mn) \rfloor$ from consideration of areas, and a lower bound of $\lfloor k/m \rfloor \lfloor k/n \rfloor$.
There can be a lot of room between these.
See e.g. Recursive partitioning approach
for the Manufacturer's Pallet Loading Problem.


text:
Q: Why by refreshing page localhost on browser bundle_client is stuck on pending status? I made super simple ssr app on node + react. By refreshing page on localhost on browser (Chrome or Safari, no matter) bundle_client.js is stuck on pending status.
GIT:
https://github.com/antonkalik/ssr-app-chrome-issue
When I changed in src/server/index.js this:
  res.status(200).send(`<!doctype html>${markup}`);
  res.end();

to this:
  res.status(200).end(`<!doctype html>${markup}`);

pending disappears.
What's wrong with that? Where I messed up?
As you can see in package.json I using react 17 and webpack 5. I want to keep it up to date.
PROJECT STRUCTURE:

Screens from browsers

A: You don't have to call res.end() if you call res.send(). res.send() calls res.end() for you.
https://github.com/expressjs/express/blob/4.17.1/lib/response.js#L221


text:
Q: Generating signed APK outputs no file When generating a signed APK, no file is being output. There are no errors in the gradle build log as is attached below, so I don't know where to start with this problem.
Here's a video showing the phenomenon: https://www.youtube.com/watch?v=AuZvSRXe-b0
And here is the gradle console log:
   Executing tasks: [:app:assembleRelease]

    Parallel execution with configuration on demand is an incubating feature.
    Incremental java compilation is an incubating feature.
    :app:preBuild UP-TO-DATE
    :app:preReleaseBuild UP-TO-DATE
    :app:checkReleaseManifest
    :app:preDebugBuild UP-TO-DATE
    :app:prepareCnPedantSweetalertLibrary13Library UP-TO-DATE
    :app:prepareComAndroidSupportAnimatedVectorDrawable2340Library UP-TO-DATE
    :app:prepareComAndroidSupportAppcompatV72340Library UP-TO-DATE
    :app:prepareComAndroidSupportCardviewV72340Library UP-TO-DATE
    :app:prepareComAndroidSupportDesign2340Library UP-TO-DATE
    :app:preDebugAndroidTestBuild UP-TO-DATE
    :app:prepareComAndroidSupportMultidex101Library UP-TO-DATE
    :app:prepareComAndroidSupportRecyclerviewV72340Library UP-TO-DATE
    :app:prepareComAndroidSupportSupportV132340Library UP-TO-DATE
    :app:prepareComAndroidSupportSupportV42340Library UP-TO-DATE
    :app:prepareComAndroidSupportSupportVectorDrawable2340Library UP-TO-DATE
    :app:prepareComGithubChyrtaAndroidOnboarder06Library UP-TO-DATE
    :app:prepareComGoogleAndroidGmsPlayServicesAds900Library UP-TO-DATE
    :app:prepareComGoogleAndroidGmsPlayServicesAdsLite900Library UP-TO-DATE
    :app:prepareComGoogleAndroidGmsPlayServicesAnalytics900Library UP-TO-DATE
    :app:prepareComGoogleAndroidGmsPlayServicesAnalyticsImpl900Library UP-TO-DATE
    :app:prepareComGoogleAndroidGmsPlayServicesBase900Library UP-TO-DATE
    :app:prepareComGoogleAndroidGmsPlayServicesBasement900Library UP-TO-DATE
    :app:prepareComGoogleAndroidGmsPlayServicesGcm900Library UP-TO-DATE
    :app:prepareComGoogleAndroidGmsPlayServicesIid900Library UP-TO-DATE
    :app:prepareComGoogleAndroidGmsPlayServicesLocation900Library UP-TO-DATE
    :app:prepareComGoogleAndroidGmsPlayServicesMaps900Library UP-TO-DATE
    :app:prepareComGoogleAndroidGmsPlayServicesTasks900Library UP-TO-DATE
    :app:prepareComGoogleFirebaseFirebaseAds900Library UP-TO-DATE
    :app:prepareComGoogleFirebaseFirebaseAnalytics900Library UP-TO-DATE
    :app:prepareComGoogleFirebaseFirebaseAnalyticsImpl900Library UP-TO-DATE
    :app:prepareComGoogleFirebaseFirebaseCommon900Library UP-TO-DATE
    :app:prepareComGoogleFirebaseFirebaseCore900Library UP-TO-DATE
    :app:prepareComGoogleFirebaseFirebaseIid900Library UP-TO-DATE
    :app:prepareComKarumiDexter222Library UP-TO-DATE
    :app:prepareComMikepenzAboutlibraries566Library UP-TO-DATE
    :app:prepareComMikepenzFastadapter151Library UP-TO-DATE
    :app:prepareComMikepenzFontawesomeTypeface4501Library UP-TO-DATE
    :app:prepareComMikepenzGoogleMaterialTypeface2101OriginalLibrary UP-TO-DATE
    :app:prepareComMikepenzIconicsCore2511Library UP-TO-DATE
    :app:prepareComMikepenzMaterialdrawer464Library UP-TO-DATE
    :app:prepareComMikepenzMaterialize051Library UP-TO-DATE
    :app:prepareComOgaclejapanSmarttablayoutLibrary160Library UP-TO-DATE
    :app:prepareComOgaclejapanSmarttablayoutUtilsV4160Library UP-TO-DATE
    :app:prepareComPnikosisMaterialishProgress10Library UP-TO-DATE
    :app:prepareComWdullaerMaterialdatetimepicker230Library UP-TO-DATE
    :app:prepareIoGithubYavskiFabSpeedDial104Library UP-TO-DATE
    :app:prepareNetDanlewAndroidJoda292Library UP-TO-DATE
    :app:prepareReleaseDependencies
    :app:compileReleaseAidl UP-TO-DATE
    :app:compileReleaseRenderscript UP-TO-DATE
    :app:generateReleaseBuildConfig UP-TO-DATE
    :app:mergeReleaseShaders UP-TO-DATE
    :app:compileReleaseShaders UP-TO-DATE
    :app:generateReleaseAssets UP-TO-DATE
    :app:mergeReleaseAssets UP-TO-DATE
    :app:generateReleaseResValues UP-TO-DATE
    :app:generateReleaseResources UP-TO-DATE
    :app:mergeReleaseResources UP-TO-DATE
    :app:processReleaseManifest UP-TO-DATE
    :app:processReleaseResources UP-TO-DATE
    :app:generateReleaseSources UP-TO-DATE
    :app:incrementalReleaseJavaCompilationSafeguard UP-TO-DATE
    :app:compileReleaseJavaWithJavac UP-TO-DATE
    :app:compileReleaseNdk UP-TO-DATE
    :app:compileReleaseSources UP-TO-DATE
    :app:lintVitalRelease
    :app:prePackageMarkerForRelease
    :app:processReleaseJavaRes UP-TO-DATE
    :app:transformResourcesWithMergeJavaResForRelease UP-TO-DATE
    :app:transformClassesAndResourcesWithProguardForRelease UP-TO-DATE
    :app:collectReleaseMultiDexComponents UP-TO-DATE
    :app:transformClassesWithMultidexlistForRelease UP-TO-DATE
    :app:transformClassesWithDexForRelease UP-TO-DATE
    :app:mergeReleaseJniLibFolders UP-TO-DATE
    :app:transformNative_libsWithMergeJniLibsForRelease UP-TO-DATE
    :app:validateExternalOverrideSigning
    :app:packageRelease UP-TO-DATE
    :app:assembleRelease

    BUILD SUCCESSFUL

    Total time: 3.483 secs

A: I use gradle scripts to assemble release apk to target path.
Here is the code:
android {
   applicationVariants.all{ variant->
      variant.outputs.each { output->
        if(variant.buildType.name.equals('release')){
            output.outputFile = new File('/Users/yourname/Desktop/', 'myapk.apk')
        }
    }
   }
}

A: Try restarting and invalidating cache:

As mentioned in this answer:

A: So it turns out that Android Studio 2.2 Preview 1 sometimes likes to output the file in the wrong directory. The files were being put in AndroidStudioProjects/AppName/app/build/outputs/apk, instead of the chosen directory in the popup dialog when trying to generate an APK.

A: me too,just change your gradle 2.2.0-alpha1 to gradle 1.5.0 or other,can generate signed apk normally.


text:
Q: How to get the netmask of a device in bash using `ip`? I'm writing a bash function which adds ip routes such as the following:
ip route add table 128 to 192.168.1.0/24 dev eno1

To get the current netmask, I can do ip -f inet -o addr show dev eno1 which will give me a value such as 192.168.1.123/24, but this is not accepted by ip. The unmasked bits need to be zero, e.g. 192.168.1.0/24.
How do I most easily change the unmasked bits of the netmask to zero in bash?

A: As mentioned in the comments ipcalc or sipcalc will both do it for you.
e.g.
$ ipcalc 192.168.0.1/24
Address:   192.168.0.1          11000000.10101000.00000000. 00000001
Netmask:   255.255.255.0 = 24   11111111.11111111.11111111. 00000000
Wildcard:  0.0.0.255            00000000.00000000.00000000. 11111111
=>
Network:   192.168.0.0/24       11000000.10101000.00000000. 00000000
HostMin:   192.168.0.1          11000000.10101000.00000000. 00000001
HostMax:   192.168.0.254        11000000.10101000.00000000. 11111110
Broadcast: 192.168.0.255        11000000.10101000.00000000. 11111111
Hosts/Net: 254                   Class C, Private Internet

or
$ sipcalc 192.168.0.1/24
-[ipv4 : 192.168.0.1/24] - 0

[CIDR]
Host address        - 192.168.0.1
Host address (decimal)  - 3232235521
Host address (hex)  - C0A80001
Network address     - 192.168.0.0
Network mask        - 255.255.255.0
Network mask (bits) - 24
Network mask (hex)  - FFFFFF00
Broadcast address   - 192.168.0.255
Cisco wildcard      - 0.0.0.255
Addresses in network    - 256
Network range       - 192.168.0.0 - 192.168.0.255
Usable range        - 192.168.0.1 - 192.168.0.254


text:
Q: Silverlight and .NET RIA Services - Managing Users I am building a Silverlight 3 application that uses .NET RIA Services. This application is hosted in an ASP.NET application that uses the default aspnet_Membership tables. My Silverlight application requires users to login. If they are a member of a certain role, I want to allow them to manage the application's users.
Currently, I can authenticate a user and see what roles they belong to. However, I cannot figure out how to do other tasks handled by the ASP.NET MembershipProvider. Things like creating users, resetting their password, etc.
How do I do these types of things through a Silverlight application that uses .NET RIA Services?
Thank you!

A: Correct me if I am wrong, but as I checked MembershipProvider, there are already methods for Creating Users, Resetting Password, Changing Passwords or Deleting Users
Or probably you wanted to ask something else or probably the question is incomplete?


text:
Q: images overlapping with masonry on rails i am trying to use masonry for a gallery on rails. right now this is my html:

<%= image_tag"https://36.media.tumblr.com/tumblr_m9aqegpJ4j1rzugjbo1_r1_500.png" %>

<%= image_tag "http://41.media.tumblr.com/tumblr_m5wb2lom6X1rz6b7fo1_500.jpg" %>

<%= image_tag "https://41.media.tumblr.com/tumblr_m9as7bOSXt1rzugjbo1_500.png" %>

<%= image_tag "http://36.media.tumblr.com/886f9d69a50a45330bd5c6c958eeed72/tumblr_ngnn3tUjJs1tpjk9no1_400.png"%>

<%= image_tag "https://s-media-cache-ak0.pinimg.com/736x/fc/f7/f4/fcf7f4416b58634117766e5e705d1ef6.jpg" %>

<%= image_tag "http://fanaru.com/spongebob-squarepants/image/8392-spongebob-squarepants-tea-at-the-treedome-episode-screencap-1x3.jpg" %>

<%= image_tag "http://www.barnorama.com/wp-content/images/2013/01/Times-Spongebob-Made-Absolutely/01-Times-Spongebob-Made-Absolutely.jpg" %>

this is my css in my home.scss file:
.grid-item {
width: 120px;
}

this is my javascript file:
 $(document).ready(function(){
  var $grid = $('#grid').masonry({
  itemSelector: '.grid-item',
  columnWidth: 200
});

  $grid.imagesLoaded().progress(function() {
  $grid.masonry('layout');
});

});

right now my images are overlapping. how do i get them to not overlap?

A: That's because masonry does the magic by setting the position of each image by their sizes. But before images are loaded, it doesn't know what the sizes are so it just use the img tag's size.
You need to use the imagesLoaded function, and call masonry in the callback, which will tell masonry to calculate the position after images are loaded.
In your case, try this
$(document).ready(function(){
  var $gridItem = $('.grid-item');
  $gridItem.hide(); // this will hide the images until they are loaded
  var $grid = $('#grid').imageLoaded(function() {
    $gridItem.fadeIn();  // you don't need this if you didn't hide them in the first place.
    $grid.masonry({
      ... // your properties here
    });
  });


text:
Q: Permissions for using gwmi win32_ntlogevent instead of get-eventog? The problem I have: get-eventlog works (I tested by doing "run as" on the PoSH ISE).  Get-WMIObject win32_ntlogevent does not. It's a perm issue of some sort.  Help please.
Background:
I've built a script that uses gwmi win32_ntlogevent to pull event logs.  (I chose it because it was an order of magnitude faster than either get-winevent or get-eventlog, even with filters).
However, I cannot reach some other servers in my environment.  So I had the Servers group add a credential to connect under, that has some sort of Log Reader right.  (not sure what they added)
Get-Eventlog:
$server = "myserver"
get-eventlog -ComputerName $server -logname "application"

(above returns results)
Get-WMIObject win32_ntlogevent does not. Neither with
Get-WmiObject win32_ntlogevent -ComputerName $server

or
$time = [System.Management.ManagementDateTimeConverter]::ToDmtfDateTime('2015/05/01 5:00:00am')
$EventQuery = @"
    select
      Logfile, RecordNumber, Timegenerated, TimeWritten, EventCode, EventType, Type, Category, CategoryString, SourceName, InsertionStrings, ComputerName, User, Message
    from Win32_NTlogEvent
    where timewritten >='$time'
    and LogFile = 'system'
"@ #this line must be un-recessed

gwmi -computername $server -Query $EventQuery

Instead, I get:
gwmi : Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))
At line:10 char:1
+ gwmi -computername "myserver" -Query $EventQuery
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Get-WmiObject], UnauthorizedAccessException
    + FullyQualifiedErrorId : System.UnauthorizedAccessException,Microsoft.PowerShell.Commands.GetWmiObjectCommand

Thanks!


text:
Q: Lucky Draw Concept : SQL Query to get random option based on percentage of appearance I am developing a Lucky draw concept as following
There will be multiple options at database we have to get the random options according to percentage of appearance
Database table is as following
option_id |   option_name |  option_type | option_in_day(%) |  option_status
----------------------------------------------------------------------
1             $2 Off         2             100                 1
2             $3 Off         2             95                  1
3             $4 Off         2             95                  1
4             $5 Off         2             90                  1
5             $8 Off         2             90                  1
6             $60 Cashback   2             10                  1
7             $100 Cashback  2             5                   1
8             Umbrela        2             50                  1
9             Iphone         2             2                   1
10            International
              Tour           2             1                   1
11            Fidget
              Spinner        2             70                  1
12            Free
              membership     2             30                  1
13            Samsung S8     2             10                  1
14            $20 Off        2             60                  1
15            Travel Card    2             50                  1
16            Soft Toys      2             70                  1

Now from this table I want to get random 8 option according to percentage.
Less percentage option chance to retrieve in result will be less.
I have tried with random function in sql but can't reach the requirement.

A: This is how you should be able to do it:
set @percentage = 100 * rand();
select *
from table_name
order by table_name.percentage >= @percentage, rand()
limit 0, 8;

This query stores a random percentage into a variable. Then, we order the query by two criterias. The first criteria is that the percentage of the table is higher or equal to the percentage randomized. This makes sure that if there are elements both above and below the randomized percentage, then the elements above will be preferred. Elements having similar result in the first ordering criteria will be randomly ordered.


text:
Q: Deserialization Json file with objectMapper in Java REST app Hi Everyone, I hava a Json file like this:
 {
   "Events":[{
     "sport_event_id": "sr:sport_event:27636100",
     "start_date": "2021-06-22T18:00:00+00:00",
     "sport_name": "Soccer",
     "competition_name": "UEFA Champions League",
     "competition_id": "sr:competition:7",
     "season_name": "UEFA Champions League 21/22",
     "competitors": [
       {
         "id": "sr:competitor:37863",
         "name": "SS Folgore Falciano Calcio",
         "country": "San Marino",
         "country_code": "SMR",
         "abbreviation": "FFC",
         "qualifier": "home",
         "gender": "male"
       },
       {
         "id": "sr:competitor:277829",
         "name": "FC Prishtina",
         "country": "Kosovo",
         "country_code": "KOS",
         "abbreviation": "PRI",
         "qualifier": "away",
         "gender": "male"
       }
     ],
     "venue": {
       "id": "sr:venue:8329",
       "name": "Elbasan Arena",
       "capacity": 12500,
       "city_name": "Elbasan",
       "country_name": "Albania",
       "map_coordinates": "41.115875,20.091992",
       "country_code": "ALB"
     },
     "probability_home_team_winner": 2.5,
     "probability_draw": 88.1,
     "probability_away_team_winner": 9.4
   }
   ]
 }

I would like to read the json from the file and display the contents.
For Json deserialization, I created appropriate Entity,Repo and Service classes for:
Competitor, Venue, Events
Venue Class:
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
        "id",
        "name",
        "capacity",
        "city_name",
        "country_name",
        "map_coordinates",
        "country_code"
})
@Entity
public class Venue implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @JsonIgnore
    private Long venueId;
    @JsonProperty("id")
    private String id;
    @JsonProperty("name")
    private String name;
    @JsonProperty("capacity")
    private int capacity;
    @JsonProperty("city_name")
    private String cityName;
    @JsonProperty("country_name")
    private String countryName;
    @JsonProperty("map_coordinates")
    private String mapCoordinates;
    @JsonProperty("country_code")
    private String countryCode;

    public Venue() {
    }

    public Venue(Long venueId, String id, String name, int capacity, String cityName, String countryName,
                 String mapCoordinates, String countryCode) {
        this.venueId = venueId;
        this.id=id;
        this.name = name;
        this.capacity = capacity;
        this.cityName = cityName;
        this.countryName = countryName;
        this.mapCoordinates = mapCoordinates;
        this.countryCode = countryCode;
    }

    public Long getVenueId() {
        return venueId;
    }

    public void setVenueId(Long venueId) {
        this.venueId = venueId;
    }

    @JsonProperty("id")
    public String getId() {
        return id;
    }

    @JsonProperty("id")
    public void setId(String id) {
        this.id = id;
    }

    @JsonProperty("name")
    public String getName() {
        return name;
    }

    @JsonProperty("name")
    public void setName(String name) {
        this.name = name;
    }

    @JsonProperty("capacity")
    public Integer getCapacity() {
        return capacity;
    }

    @JsonProperty("capacity")
    public void setCapacity(Integer capacity) {
        this.capacity = capacity;
    }

    @JsonProperty("city_name")
    public String getCityName() {
        return cityName;
    }

    @JsonProperty("city_name")
    public void setCityName(String cityName) {
        this.cityName = cityName;
    }

    @JsonProperty("country_name")
    public String getCountryName() {
        return countryName;
    }

    @JsonProperty("country_name")
    public void setCountryName(String countryName) {
        this.countryName = countryName;
    }

    @JsonProperty("map_coordinates")
    public String getMapCoordinates() {
        return mapCoordinates;
    }

    @JsonProperty("map_coordinates")
    public void setMapCoordinates(String mapCoordinates) {
        this.mapCoordinates = mapCoordinates;
    }

    @JsonProperty("country_code")
    public String getCountryCode() {
        return countryCode;
    }

    @JsonProperty("country_code")
    public void setCountryCode(String countryCode) {
        this.countryCode = countryCode;
    }
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Venue venue = (Venue) o;
        return capacity == venue.capacity && Objects.equals(venueId, venue.venueId) && Objects.equals(id, venue.id) && Objects.equals(name, venue.name) && Objects.equals(cityName, venue.cityName) && Objects.equals(countryName, venue.countryName) && Objects.equals(mapCoordinates, venue.mapCoordinates) && Objects.equals(countryCode, venue.countryCode);
    }

    @Override
    public int hashCode() {
        return Objects.hash(venueId, id, name, capacity, cityName, countryName, mapCoordinates, countryCode);
    }

    @Override
    public String toString() {
        return "Venue{" +
                "venueId=" + venueId +
                ", id='" + id + '\'' +
                ", name='" + name + '\'' +
                ", capacity=" + capacity +
                ", cityName='" + cityName + '\'' +
                ", countryName='" + countryName + '\'' +
                ", mapCoordinates='" + mapCoordinates + '\'' +
                ", countryCode='" + countryCode + '\'' +
                '}';
    }
}

**Competitor Class:
**
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
        "id",
        "name",
        "country",
        "country_code",
        "abbreviation",
        "qualifier",
        "gender"
})
@Entity
public class Competitor implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @JsonIgnore
    private Long competitorId;
    @JsonProperty("id")
    private String id;
    @JsonProperty("name")
    private String name;
    @JsonProperty("country")
    private String country;
    @JsonProperty("country_code")
    private String countryCode;
    @JsonProperty("abbreviation")
    private String abbreviation;
    @JsonProperty("qualifier")
    private String qualifier;
    @JsonProperty("gender")
    private String gender;
    public Competitor() {
    }

    public Competitor(Long competitorId, String id, String name, String country, String countryCode, String abbreviation,
                      String qualifier, String gender) {
        this.competitorId = competitorId;
        this.id=id;
        this.name = name;
        this.country = country;
        this.countryCode = countryCode;
        this.abbreviation = abbreviation;
        this.qualifier = qualifier;
        this.gender = gender;
    }

    public Long getCompetitorId() {
        return competitorId;
    }

    public void setCompetitorId(Long id) {
        this.competitorId = id;
    }
    @JsonProperty("id")
    public String getId() {
        return id;
    }
    @JsonProperty("id")
    public void setId(String id) {
        this.id = id;
    }
    @JsonProperty("name")
    public String getName() {
        return name;
    }
    @JsonProperty("name")
    public void setName(String name) {
        this.name = name;
    }
    @JsonProperty("country")
    public String getCountry() {
        return country;
    }
    @JsonProperty("country")
    public void setCountry(String country) {
        this.country = country;
    }
    @JsonProperty("country_code")
    public String getCountryCode() {
        return countryCode;
    }
    @JsonProperty("country_code")
    public void setCountryCode(String countryCode) {
        this.countryCode = countryCode;
    }
    @JsonProperty("abbreviation")
    public String getAbbreviation() {
        return abbreviation;
    }
    @JsonProperty("abbreviation")
    public void setAbbreviation(String abbreviation) {
        this.abbreviation = abbreviation;
    }
    @JsonProperty("qualifier")
    public String getQualifier() {
        return qualifier;
    }
    @JsonProperty("qualifier")
    public void setQualifier(String qualifier) {
        this.qualifier = qualifier;
    }
    @JsonProperty("gender")
    public String getGender() {
        return gender;
    }
    @JsonProperty("gender")
    public void setGender(String gender) {
        this.gender = gender;
    }
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Competitor that = (Competitor) o;
        return Objects.equals(competitorId, that.competitorId) && Objects.equals(id, that.id) && Objects.equals(name, that.name) && Objects.equals(country, that.country) && Objects.equals(countryCode, that.countryCode) && Objects.equals(abbreviation, that.abbreviation) && Objects.equals(qualifier, that.qualifier) && Objects.equals(gender, that.gender);
    }

    @Override
    public int hashCode() {
        return Objects.hash(competitorId, id, name, country, countryCode, abbreviation, qualifier, gender);
    }

    @Override
    public String toString() {
        return "Competitor{" +
                "competitorId=" + competitorId +
                ", id='" + id + '\'' +
                ", name='" + name + '\'' +
                ", country='" + country + '\'' +
                ", countryCode='" + countryCode + '\'' +
                ", abbreviation='" + abbreviation + '\'' +
                ", qualifier='" + qualifier + '\'' +
                ", gender='" + gender + '\'' +
                '}';
    }
}

Events Class:
@Entity
@JsonPropertyOrder({
        "sport_event_id",
        "start_date",
        "sport_name",
        "competition_name",
        "competition_id",
        "season_name",
        "competitors",
        "venue",
        "probability_home_team_winner",
        "probability_draw",
        "probability_away_team_winner"
})
public class Events implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @JsonIgnore
    private Long eventsId;
    @JsonProperty("sport_event_id")
    private String sportEventId;
    @JsonProperty("start_date")
    private ZonedDateTime startDate;
    @JsonProperty("sport_name")
    private String sportName;
    @JsonProperty("competition_name")
    private String competitionName;
    @JsonProperty("competition_id")
    private String competitionId;
    @JsonProperty("season_name")
    private String seasonName;
    @OneToMany
    @JsonProperty("competitors")
    private List<Competitor> competitors;
    @ManyToOne
    @JoinColumn
    @JsonProperty("venue")
    private Venue venue;
    @JsonProperty("probability_home_team_winner")
    private double probabilityHomeTeamWinner;
    @JsonProperty("probability_draw")
    private double probabilityDraw;
    @JsonProperty("probability_away_team_winner")
    private double probabilityAwayTeamWinner;
    public Events() {
    }

    public Events(Long eventsId, String sportEventId, ZonedDateTime startDate, String sportName, String competitionName, String competitionId, String seasonName,
                  List<Competitor> competitors, Venue venue, double probabilityHomeTeamWinner, double probabilityDraw, double probabilityAwayTeamWinner) {
        this.sportEventId = sportEventId;
        this.startDate = startDate;
        this.sportName = sportName;
        this.competitionName = competitionName;
        this.competitionId = competitionId;
        this.seasonName = seasonName;
        this.competitors = competitors;
        this.venue = venue;
        this.probabilityHomeTeamWinner = probabilityHomeTeamWinner;
        this.probabilityDraw = probabilityDraw;
        this.probabilityAwayTeamWinner = probabilityAwayTeamWinner;
    }

    public Long getEventsId() {
        return eventsId;
    }

    public void setEventsId(Long eventsId) {
        this.eventsId = eventsId;
    }
    @JsonProperty("sport_event_id")
    public String getSportEventId() {
        return sportEventId;
    }
    @JsonProperty("sport_event_id")
    public void setSportEventId(String sportEventId) {
        this.sportEventId = sportEventId;
    }
    @JsonProperty("start_date")
    public ZonedDateTime getStartDate() {
        return startDate;
    }
    @JsonProperty("start_date")
    public void setStartDate(ZonedDateTime startDate) {
        this.startDate = startDate;
    }
    @JsonProperty("sport_name")
    public String getSportName() {
        return sportName;
    }
    @JsonProperty("sport_name")
    public void setSportName(String sportName) {
        this.sportName = sportName;
    }
    @JsonProperty("competition_name")
    public String getCompetitionName() {
        return competitionName;
    }
    @JsonProperty("competition_name")
    public void setCompetitionName(String competitionName) {
        this.competitionName = competitionName;
    }
    @JsonProperty("competition_id")
    public String getCompetitionId() {
        return competitionId;
    }
    @JsonProperty("competition_id")
    public void setCompetitionId(String competitionId) {
        this.competitionId = competitionId;
    }
    @JsonProperty("season_name")
    public String getSeasonName() {
        return seasonName;
    }
    @JsonProperty("season_name")
    public void setSeasonName(String seasonName) {
        this.seasonName = seasonName;
    }
    @JsonProperty("competitors")
    public List<Competitor> getCompetitors() {return competitors; }

    @JsonProperty("competitors")
    public void setCompetitors(List<Competitor> competitors) {
    this.competitors = competitors;
}
    @JsonProperty("venue")
    public Venue getVenue() {
        return venue;
    }
    @JsonProperty("venue")
    public void setVenue(Venue venue) {
        this.venue = venue;
    }
    @JsonProperty("probability_home_team_winner")
    public double getProbabilityHomeTeamWinner() {
        return probabilityHomeTeamWinner;
    }
    @JsonProperty("probability_home_team_winner")
    public void setProbabilityHomeTeamWinner(double probabilityHomeTeamWinner) {
        this.probabilityHomeTeamWinner = probabilityHomeTeamWinner;
    }
    @JsonProperty("probability_draw")
    public double getProbabilityDraw() {
        return probabilityDraw;
    }
    @JsonProperty("probability_draw")
    public void setProbabilityDraw(double probabilityDraw) {
        this.probabilityDraw = probabilityDraw;
    }
    @JsonProperty("probability_away_team_winner")
    public double getProbabilityAwayTeamWinner() {
        return probabilityAwayTeamWinner;
    }
    @JsonProperty("probability_away_team_winner")
    public void setProbabilityAwayTeamWinner(double probabilityAwayTeamWinner) {
        this.probabilityAwayTeamWinner = probabilityAwayTeamWinner;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Events events = (Events) o;
        return Double.compare(events.probabilityHomeTeamWinner, probabilityHomeTeamWinner) == 0 && Double.compare(events.probabilityDraw, probabilityDraw) == 0 && Double.compare(events.probabilityAwayTeamWinner, probabilityAwayTeamWinner) == 0 && Objects.equals(eventsId, events.eventsId) && Objects.equals(sportEventId, events.sportEventId) && Objects.equals(startDate, events.startDate) && Objects.equals(sportName, events.sportName) && Objects.equals(competitionName, events.competitionName) && Objects.equals(competitionId, events.competitionId) && Objects.equals(seasonName, events.seasonName) && Objects.equals(competitors, events.competitors) && Objects.equals(venue, events.venue);
    }

    @Override
    public int hashCode() {
        return Objects.hash(eventsId, sportEventId, startDate, sportName, competitionName, competitionId, seasonName, competitors, venue, probabilityHomeTeamWinner, probabilityDraw, probabilityAwayTeamWinner);
    }

    @Override
    public String toString() {
        return "Events{" +
                "eventsId=" + eventsId +
                ", sportEventId='" + sportEventId + '\'' +
                ", startDate=" + startDate +
                ", sportName='" + sportName + '\'' +
                ", competitionName='" + competitionName + '\'' +
                ", competitionId='" + competitionId + '\'' +
                ", seasonName='" + seasonName + '\'' +
                //", competitors=" + competitors +
                ", venue=" + venue +
                ", probabilityHomeTeamWinner=" + probabilityHomeTeamWinner +
                ", probabilityDraw=" + probabilityDraw +
                ", probabilityAwayTeamWinner=" + probabilityAwayTeamWinner +
                '}';
    }
}

In EventsController, I implemented the getItemFromJSon() method which is supposed to return the contents of a Json.
EventsController Class:
@RestController
public class EventsController {
    private final ObjectMapper objectMapper;
    private final EventsServiceImpl eventsServiceImpl;

    public EventsController(EventsServiceImpl eventsServiceImpl, ObjectMapper objectMapper) {
        this.eventsServiceImpl = eventsServiceImpl;
        this.objectMapper= objectMapper;
    }
    @GetMapping("/json/events")
    public Events getItemFromJson() throws IOException {
     /*   InputStream inputStream = new FileInputStream(new File("src/main/resources/BE_data.json"));
        TypeReference<Events> typeReference = new TypeReference<Events>(){};
        return  objectMapper.readValue(inputStream,typeReference);
      */

        return objectMapper.readValue(new File("src/main/resources/BE_data.json"), Events.class);
    }
}

After running the program and calling endpoint, I get a response in the form of :
{
    "sport_event_id": null,
    "start_date": null,
    "sport_name": null,
    "competition_name": null,
    "competition_id": null,
    "season_name": null,
    "competitors": null,
    "venue": null,
    "probability_home_team_winner": 0.0,
    "probability_draw": 0.0,
    "probability_away_team_winner": 0.0
}

What did I do wrong in my code?
For Json deserialisation I used objectMapper.

A: Please try these POJO classes. I have used this online tool to autogenerate the POJO Objects
public class Competitor{
    public String id;
    public String name;
    public String country;
    public String country_code;
    public String abbreviation;
    public String qualifier;
    public String gender;
}

public class Event{
    public String sport_event_id;
    public Date start_date;
    public String sport_name;
    public String competition_name;
    public String competition_id;
    public String season_name;
    public ArrayList<Competitor> competitors;
    public Venue venue;
    public double probability_home_team_winner;
    public double probability_draw;
    public double probability_away_team_winner;
}

public class Root{
    @JsonProperty("Events")
    public ArrayList<Event> events;
}

public class Venue{
    public String id;
    public String name;
    public int capacity;
    public String city_name;
    public String country_name;
    public String map_coordinates;
    public String country_code;
}

Then deserialize it like this
return objectMapper.readValue(new File("src/main/resources/BE_data.json"), Root.class);


text:
Q: About with(any(Class.class))) with JMock With JMock:
context.checking(new Expectations() {{
    // Other oneOf() will() statements ...

    oneOf(shopAccount).enter(100, with(any(String.class)));
    will(returnValue(true));

   // Other oneOf() will() statements ...
}});

The following exception will be raised during execution:

java.lang.IllegalArgumentException: not all parameters were given explicit matchers: either all parameters must be specified by matchers or all must be specified by values, you cannot mix matchers and values.

Why i cannot do this way? using with(any(Klass.class)) ?

A: if you use a with clause for any parameter, you must use them for all the parameters, try

oneOf(shopAccount).enter(with(equalTo(100)), with(any(String.class)));


text: Q: Oscar Django many categories slow down the site I've created a site ( Clothing Shop )  which has 426 categories . The site is really slow due to having many categories . ( Even when creating a child category it is saved in Category at the database as seen from shell (oscar category creation)) . I've tried many methods to optimize the queries that are made when a page is loading but still too slow . I've followed the django doc for optimized categories (https://docs.djangoproject.com/en/4.0/topics/db/optimization/) . I've also tried to cache some queries . Moreover the fact that I think the slowness comes from categories is because I've seen that the category queries take the most time through django toolbar .Any help would be great ! . ( Also sorry if my question is not well written I am kinda new around here )


text:
Q: About the proof of 1-8 Theorem in "Calculus on Manifolds" by Michael Spivak I am reading "Calculus on Manifolds" by Michael Spivak.
I think we need to modify the proof of 1-8 Theorem.
Spivak wrote "Since $f$ is continuous at $a$, we can ensure that $f(x) \in B$, provided we choose $x$ in some sufficiently small rectangle $C$ containing $a$".
I think we need to modify as follows:
"Since $f$ is continuous at $a$, we can ensure that $f(x) \in B$, provided we choose $x$ in the intersection of $A$ and some sufficiently small rectangle $C$ containing $a$"
Am I right or not?

A: You are right.
In my opinion Spivak is a bit sloppy. He starts at a very elementary level, defines everything ab ovo, but since he does so, he should be more precise. Let me explain what I mean.
On p. 1 he introduces the (Euclidean) norm $\lvert x\rvert$ on $\mathbb R^n$. In exercise 1-5 he introduces the (Euclidean) distance between $x$ and $y$ as the quantity $\lvert x - y \rvert$. This is a metric, but he doesn't mention it.
Open rectangles and open sets $U \subset \mathbb R^n$ are introduced on p. 5, but Spivak does not mention the essential fact that $U$ is open if and only if for each $x \in U$ there exists an $\epsilon > 0$ such that for all $y$ satisfying  $\lvert x - y \rvert < \epsilon$ one has $y \in U$. The proof is of course easy. Note that the part after "only if" is the standard definition of an open set.
On p. 11 Spivak defines the limit of a function $f : A \to \mathbb R^m$ at $x \in A$ via the Euclidean distance. This leads to the definition of continuity at $a$. In the proof of Theorem 1-8 he tacitly invokes  two facts which he doesn't prove:

*

*There exists $\epsilon > 0$ such that for all $z$ satisfying  $\lvert f(a) - z \rvert < \epsilon$ one has $z \in B$. See the above remark concerning the concept of "open set".

*By continuity there exists $\delta > 0$ such that for all $y \in A$ such that $\lvert a - x \rvert < \delta$ one has $\lvert f(a) - f(x) \rvert < \epsilon$. Now he says that $f(x) \in B$ provided we choose $x$ in some sufficiently small (of course open) rectangle $C $ containing $a$. This means that $x \in A \cap C$ implies $\lvert a - x \rvert < \delta$. His claim is true, but I think that again there is a gap.
The main shortcoming is that Spivak does not sufficiently precisely address the topology of $\mathbb R^n$. What he should have done is to prove (or at least to mention in an exercise) that

*

*If $x \in \mathbb R^n$ and $\epsilon > 0$, then there exists an open rectangle $R$ containing $x$ such that $y \in R$ implies $\lvert x - y \rvert < \epsilon$.

*If $x$ is contained in an open rectangle $R$, then there exists $\epsilon > 0$ such that $\lvert x - y \rvert < \epsilon$ implies $y \in R$.
Anyway, I do not see any reason why Spivak decided to work with open rectangles instead of open balls. An approach based on open balls would be more transparent.


text:
Q: NameError: name 'image' is not defined I am getting the error in the post title when I attempt to run a pretrained MobileNet classification. The image I am using to run the script is located in my 'MobileNet-inference-images/American_Cam.jpg directory.
Any help or advice would be appreciated.
Here is my script, my environment, the error traceback, and what have investigated so far.
import numpy as np
import keras
from keras import backend as K
from keras.layers.core import Dense
from keras.optimizers import Adam
from keras.metrics import categorical_crossentropy
from keras.preprocessing.image import ImageDataGenerator
from keras.models import Model
from keras.applications import imagenet_utils
from sklearn.metrics import confusion_matrix
import itertools
import matplotlib.pyplot as plt
%matplotlib inline

mobile =keras.applications.mobilenet.MobileNet()

def prepare_image(file):
    img_path = 'MobileNet-inference-images/'
    img = image.load_img(img_path + file, target_size=(224, 224))
    img_array = image.img_to_array(img)
    img_array_expanded_dims = np.expand_dims(img_array, axis=0)
    return
    keras.applications.mobilenet.preprocess_imput(img_array_expanded_dims)

preprocessed_image = prepare_image('MobileNet-inference-images/American_Cam.jpg')
predictions = mobile.predict(preprocessed_image)
results = imagenet_utils.decode_predictions(predictions)
results

I am running python 3.6.1 in an Anaconda "custom" environment (64 bit) in a Juypter notebook.
The traceback is
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-40-90b9684f2691> in <module>()
----> 1 preprocessed_image = prepare_image('MobileNet-inference-images/American_Cam.jpg')
      2 predictions = mobile.predict(preprocessed_image)
      3 results = imagenet_utils.decode_predictions(predictions)
      4 results

<ipython-input-32-c204346d1e63> in prepare_image(file)
      1 def prepare_image(file):
      2     img_path = 'MobileNet-inference-images/'
----> 3     img = image.load_img(img_path + file, target_size=(224, 224))
      4     img_array = image.img_to_array(img)
      5     img_array_expanded_dims = np.expand_dims(img_array, axis=0)

NameError: name 'image' is not defined

I have seen an error of the same name here, but that appears to be a separate issue(as I am enclosing my image path). Other posts have suggested an issue with PIL. But if I test is PIL is operating with a simple script(such as below), I don't get a PIL error.
from PIL import Image
im = Image.open('MobileNet-inference-images/American_Cam.jpg')
im.show()

A: from image you import only ImageDataGenerator but you also need other attributes,
better change it
from keras.preprocessing.image import ImageDataGenerator

to
from keras.preprocessing import image
# and use
# image.ImageDataGenerator()
# image.load_img()


text:
Q: How to parallel process a large file without load all in memory I have a large json line file (each line is a json object). I would like to read each line and process each line in parallel.
Here is what I got:
import gzip
import multiprocessing as mp
import pandas as pd
from json import loads

def process_file(file_line):
    json_line = loads(file_line)
    data = json_line.get('data', None)
    if data:
        df = pd.DataFrame(data)
        return df.groupby(['style']).score.describe()
    return pd.DataFrame()

pool = mp.Pool(8)
jobs = []
with gzip.open('2018.jl.gz') as f:
    for line in f:
        jobs.append(pool.apply_async(process_file,(f)))

for job in jobs:
    job.get()

pool.close()

However, the processing takes longer than reading the file and it end up with appending too many jobs and causing memory issues.
Is there a way I could parallel this? How could I coded it the way that each thread will grab a line and process the line and when it finish, it will grab a new line, and the loop would pause if all threads are busy?


text:
Q: quiero que me indique el promedio y me diga que el promedio fue menor o mayor que el anterior mes delimiter //

CREATE PROCEDURE sp_promdio_venta(IN _fecha1 date, IN _fecha2 date )
BEGIN
    DECLARE LOCAL int;

DECLARE promedio int;

SET
LOCAL = promedio;

SET
promedio =(
SELECT
    avg(Valor_Venta)
FROM
    ventas
WHERE
    FechaYHora BETWEEN _fecha1 AND _fecha2);

SELECT
    Valor_Venta,
    FechaYHora,
    promedio
FROM
    ventas
WHERE
    FechaYHora BETWEEN _fecha1 AND _fecha2
HAVING
    Valor_Venta >= ANY (
    SELECT
        promedio
    FROM
        ventas
    WHERE
        FechaYHora BETWEEN _fecha1 AND _fecha2 );

IF promedio < LOCAL THEN
SELECT
    Valor_Venta,
    FechaYHora,
    'El promedio fue menor' AS promdedio
FROM
    ventas
WHERE
    FechaYHora BETWEEN _fecha1 AND _fecha2;
ELSE
SELECT
    Valor_Venta,
    FechaYHora,
    'El promedio fue mayor' AS promdedio
FROM
    ventas
WHERE
    FechaYHora BETWEEN _fecha1 AND _fecha2;
END IF;
END //

A: Si lo que quieres es comparar el promedio del último mes con el anterior, prueba así:
SELECT IF(
    (
      SELECT AVG(Valor_Venta) FROM ventas
        WHERE FechaYHora BETWEEN NOW()-INTERVAL 1 MONTH AND NOW()
    )>(
      SELECT AVG(Valor_Venta) FROM ventas
        WHERE FechaYHora BETWEEN NOW()-INTERVAL 2 MONTH AND NOW()-INTERVAL 1 MONTH
    ),'El promedio fue mayor','El promedio fue menor'
  );

Y evitarás el procedimiento almacenado. Estoy suponiendo que tu tabla es:
CREATE TABLE ventas(
  FechaYHora datetime,
  Valor_Venta float
  );

Déjame cualquier duda en los comentarios.


text:
Q: How to implement dynamic roles and rights in Express Js? I need to implement an authentication system where a super admin can create multiple different roles with different rights for users. That is, not a system with a set number of roles, but have the option to create as many roles with different combination of rights as the superadmin wants, and then assign them to new users. Also with the option of editing these roles, deleting them etc. I'm fairly new at Node Js. Is this something hard to implement? Are there any articles/videos I can read/watch, to start understanding the process? Where do I start? I'd really appreciate any help. Thank you in advance!

A: You're thinking about Role-Based Access Control (RBAC). I have actually implemented this in Node.js before, feel free to checkout how I implemented it here: https://github.com/JLCarveth/nodeblog.
It's relatively simple. You need a table for tracking roles. Each role has 0 or more permissions. These permissions can be comma-separated strings, or IDs referencing a permissions table. Each user is then assigned a role.
Each route is protected with a middleware that specifies the needed permissions. If a user accesses this route, check that they have the necessary permissions and continue, reject if not.