text:
Q: What regex should be applied when selecting text between unknown XML tags but not the tags themselves? As the title suggests e.g.
<unknownTag>Select this only</unknownTag>
<anotherUnknownTag>Select this too</anotherUnknownTag>

To select:
- Select this only
- Select this too
A brief explanation on separate parts would be nice too if possible.

A: You can use this regex.
(?!<.+?>)([^<>]+?)(?=</.+?>)


text:
Q: compare datetime in postgresql For reseting password, I am checking if token is expires which is valid for an hour.
To achieve this, I save 'inOneHour' datetime in 'resetPasswordExpires' column (db) and compare with 'now' datetime on reset password request. But it fails.
moment.js
export const now = moment().format();
export const inOneHour = moment()
  .add(1, 'hours')
  .format();

postgresql
table.datetime('resetPasswordExpires', { useTz: false });

auth.js
exports.forgotPassword = (req, res) => {
const { username, email, inOneHour } = req.body;

  return knex('users')
    .where({ username, email })
    .first()
    .then(async user => {
        ...
        return knex('users')
          .where({ username })
          .first()
          .update({
            resetPasswordToken: token,
            resetPasswordExpires: inOneHour,
          })
          .then(() => {
            ...
    });
};

exports.resetPasswordWithToken = (req, res) => {
  const { newPassword, now } = req.body;
  const { token } = req.params;

  knex('users')
    .where({ resetPasswordToken: token })
    .andWhere('resetPasswordExpires', '>', now)
    .first()
    .then(user => {
      if (user) {
        const id = user.id;
        return setPassword(id, newPassword)
          .then(() =>
            knex('users')
              .where({
                id,
              })
              .first()
              .update({
                resetPasswordToken: null,
                resetPasswordExpires: null,
              }),
          )
          .then(() => res.status(200).json())
          .catch(err => res.status(409).json(err));
      }
      return res.status(409).json('Access token is invalid or has expired');
    })
    .catch(err => res.status(409).json(err));
};

when moment.format()
// passing datetime to update 'resetPasswordExpires' column
console.log(inOneHour) // 2019-07-19T01:19:16+09:00

// 'resetPasswordExpires' value after updated
console.log(resetPasswordExpires) // 2019-07-18T16:19:16.000Z

// passing datetime to compare
console.log(now) // 2019-07-19T00:20:02+09:00

when moment.format('MMMM DD YYYY, HH:mm:ss')
console.log(inOneHour) // July 19 2019, 01:16:17
console.log(resetPasswordExpires) // 2019-07-18T16:16:17.000Z
console.log(now) // July 19 2019, 00:17:38

Two different datetime formats are saved in the same format in database.
Even When I set the 'resetPasswordExpired' datetime type with Timezone and use moment.format(), It still doesn't work.
How can I work around this ?
when moment.format() && table.datetime('resetPasswordExpires');
console.log(inOneHour) // July 19 2019, 01:16:17
console.log(resetPasswordExpires) // 2019-07-18T16:16:17.000Z
console.log(now) // July 19 2019, 00:17:38

A: I reopen my laptop. somehow this code is working now ;;
But I realized that I don't actually need to save expired time of token in database since JWT token is already generated with expired time.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Ubuntu not seeing my main account? So this morning i fired up Ubuntu like i normally would and it asked me to setup an account like i just installed it.
I went ahead since there was no other way forward and obviously this was an entirely new account but all my apps where installed.
i logged out and tried to login with my old account but clicking 'Not Listed' at the login screen.
THIS WORKED! i can login to my old account this way and all is well.
Could one of you kind people help me to get back to normal.
My account isn't on the User section of settings and it don't show up on the login screen


text:
Q: How to convert (or transform) from one range to another? I have score ranges min score = 40 and max score = 60. I have same gpa ranges too 1.00 - 1.99.
Which formula I can use to calculate the gpa.  Like If I entered 45 then it should print 1.25.
Range of score and grade can be different.
P.S. I am a web developer, and I am a little poor in Math. I need to apply this formula in my coding.

A: Let the following denote:

*

*$S$: input score

*$S_{min}$: min score

*$S_{max}$: max score

*$G_{min}$: min gpa

*$G_{max}$: max gpa

*$G$: output gpa

Then your formula is:
$$G=\frac{(S-S_{min})\cdot(G_{max}-G_{min})}{S_{max}-S_{min}}+G_{min}$$

A: The general form of this question on how to map the interval $[a,b]$ onto the interval $[c,d]$ was answered in  Shift numbers into a different range (including a derivation) using the following expression
$$f(t) = c + \left(\frac{d-c}{b-a}\right)(t-a)$$
So to map the interval $[40,60]$ onto the interval $[1.0,2.0]$ use
\begin{align}
f(t) &= 1.0 + \left(\frac{2.0-1.0}{60-40}\right)(t-40) \\
     &= 1.0 + \left(\frac{t-40}{20}\right)
\end{align}
Using your example score of $45$
\begin{align}
f(45) &= 1.0 + \left(\frac{45-40}{20}\right) \\
      &= 1.25
\end{align}


text:
Q: OCaml -- return a list containing the tails of that list For [1;2;3;4;5], I want to return [[1;2;3;4;5];[2;3;4;5];[3;4;5;];[4;5];[5];[]]
I'm trying to use the List library but I'm unsure how to.  So far, I know I have to use List.tl to get the list without the first element
let rec tailsoflist (l : 'a list) : 'a list list =
  match l with
      [] -> [[]]
    | x::xs -> l::(tails xs)

I did this recursively but now I want to just use the list library without using recursion.
let tails (l : 'a list) : 'a list list

EDIT: Sorry guys, what I specified for the function to return is incorrect. Just updated it with the correct output.

A: As I said in the comment, these are not the tails of l but copies of the tails of l:
# let tails l = List.fold_right (fun e acc -> (e::(List.hd acc))::acc) l [[]] ;;
val tails : 'a list -> 'a list list = <fun>
# tails [1; 2; 3; 4] ;;- : int list list = [[1; 2; 3; 4]; [2; 3; 4]; [3; 4]; [4]; []]

A: There is no good way to write that function in terms of the built-in functions.
The answer you give in your question is fine but it would be more idiomatic to not annotate the types and use function:
let rec tails = function
  | [] -> [[]]
  | _::xs' as xs -> xs::tails xs'

Other languages, like F#, provide a List.unfold function that tails can be written in terms of.

A: Ah, the old trick to accumulate on the original list to cast tails as a catamorphism. This is done without explicit recursion using just functions on the List module:
let tails l = List.rev ( [] :: snd (List.fold_right
    (fun _ (t,ts) -> List.tl t, t::ts) l (l, [])) )

It produces the tails as you expect:
# tails [1;2;3;4;5];;
- : int list list = [[1; 2; 3; 4; 5]; [2; 3; 4; 5]; [3; 4; 5]; [4; 5]; [5]; []]

and the tails are the actual structural tails of the input list, so that List.tl l == List.hd (List.tl (tails l)).

A: "Without using recursion"... why ? Recursion is a useful tool, even outside the List library.
let rec suffixes = function
| [] -> [[]]
| hd::tl as suff -> suff :: suffixes tl

Your function (which doesn't compile because you use tails instead of tailsoflist) returns the list of suffixes of a list. Due to the list structure, it's easier to compute than the prefixes.
You can express the prefixes from the suffixes :
let prefixes li = List.map List.rev (suffixes (List.rev li));;

You could do a direct version using an accumulator:
let prefixes li =
  let rec pref acc = function
    | [] -> List.rev acc :: []
    | hd::tl -> List.rev acc :: pref (hd :: acc) tl
  in pref [] li

and express it using List.fold_left if you want to avoid recursion, but this is convoluted so you should prefer the direct version in my opinion:
let prefixes li =
  let acc, res =
    List.fold_left
      (fun (acc, res) e -> (e :: acc), (List.rev acc :: res))
      ([], []) li in
  List.rev acc :: res

Finally, it is possible to destroy your brain with a version using continuations, but I don't remember the exact code. Roughly, the continuation is equivalent to the "accumulator" of the direct version.


text:
Q: Having issues with XPutImage I have these function calls :
OSPImgBlit(&img->_obj, &win1->_obj, 0, 0, 0, 0, 640, 480);
OSPRun(&win1->_obj, OSPWND_SWAP);

for these implementations :
void OSPwnd_swap(OSPobj *obj, va_list arg) {
    OSPwindow *wnd = (OSPwindow *) obj;
    XdbeSwapInfo swpifo;

    swpifo.swap_window = wnd->_wnd;
    swpifo.swap_action = XdbeUndefined;

    // XdbeSwapBuffers returns true on success, we return 0 on success.
    if(XdbeSwapBuffers(wnd->_dpy->_dpy, &swpifo, 1)) {
        OSPrint(1, "OSPwnd_swap : Window %d swapped "
                    "on connection %d",
                    wnd->_wnd, XConnectionNumber(wnd->_dpy->_dpy));
/*      XFlush(wnd->_dpy->_dpy); */
    }
    else {
        OSPrint(1, "OSPwnd_swap : Unable to swap window %d "
                    "on connection %d",
                    wnd->_wnd, XConnectionNumber(wnd->_dpy->_dpy));
    }
}

void OSPImgBlit(OSPobj *orig, OSPobj *dest, int x_orig, int y_orig,
            int x_dest, int y_dest, unsigned int width, unsigned int height) {
    OSPimage *orig_as_image = (OSPimage *) orig;
    OSPwindow *orig_as_window = (OSPwindow *) orig;
    OSPimage *dest_as_image = (OSPimage *) dest;
    OSPwindow *dest_as_window = (OSPwindow *) dest;

    enum {
        image_to_image = 0,
        image_to_window = 1,
        window_to_image = 2,
        window_to_window = 3
    } mode = image_to_window;

    switch(mode) {
        case image_to_window:
            XPutImage(dest_as_window->_dpy->_dpy, dest_as_window->_bbf,
                        dest_as_window->_gc, orig_as_image->_img,
                        x_orig, y_orig, x_dest, y_dest, width, height);
        default:;
    }
}

The entire code is here : https://github.com/DJTECKING/OSPOOC.git
My application starts correctly but when I attempt to close the window I created, it happen one of these behavior randomly :
- segfault
- BadDrawable on X_PutImage
- nothing (not working close button on closing window)
- Correctly closed window and application
I guess something like I'm using a already closed window or freed image,
but in the entire code I don't understand how can this happen, any idea?
Also XPutImage only blits a square
while I was attempting to copy the whole window.
Yet another question that might be separated of this topic,
I continue to face ugly tearing effects, even with Xdouble buffer extension,
was not this extension supposed to avoid this?
I haven't 10 reputation so here is direct image link:
http://i.stack.imgur.com/AnlMo.png

A: Tearing effects might due to Xdbe mate implementation
No tearing effects under waylang on fedora22.
Segfault and BadDrawable is due to the event processing loop in OSPwnd:OSPDpyHdl.
It wasn't stopping till the event queue was empty, events on closing window arrived before other one like mouse pointer entering window.
Then OSPDpyHdl was deleting objects before using them to retrieve next events.
These events were also not treated corectly before returning from OSPDpyHdl.
Partial XPutImage was due to the fact that
user can't access data table of an image by the [x][y] order
since image is line contigous in memory.
So win->_data[y] accesses to each line and win->_data[y][x] each pixel.
The problem is that all image is sent 60 times per second encumbering the X connection and disabling server reactivity.


text:
Q: Custom Logging of IBM cloud functions We want to know how we can enable custom logging to IBM cloud functions, till now we used to see the logs in IBM Cloud Log Analysis Service which is enabled by default in IBM cloud and now its getting deprecated in mid July.
We want to add additional logging to IBM cloud functions, Please let us know how we can do this .

A: I would try adding an additional log appender to the standard logger for the log target that you want to use (logentries or splunk etc). Here's a link to the documentation that talks about tweaking the log settings: https://github.com/apache/openwhisk/blob/master/docs/logging.md
And this article does a good job describing how you can create a custom appender if your logging vendor provides one: https://www.baeldung.com/custom-logback-appender


text:
Q: Showing a function has one root in an interval Could anyone shine some light on this question please?
By considering $f'(x)$, show that $$f(x)=x^3 - 2$$ has exactly one root for $x$ greater than or equal to $0$.

A: Hint: $f'(x)=3x^2\ge 0$ for all $x$.
Note that the function is increasing and $f(0)<0$ and $f(2)>0$, what can you conclude using continuity of $f$?
Side-note the roots of the equation are $2^{1/3}\cdot \omega ^i$ where $i=0,1,2$ and $\omega$ is the cube root of unity. i.e. there is only one real root.

A: After differentiate, you have $f'> 0$ for $x>0$, so it's strictly increasing. Then by intermediate value theorem, there exists a root. By strictly increasing, the root is unique.

A: By intermediate value theorem, you can see that $f(0) < 0$ and $f(2)>0$, therefore $f$ has a root $x_0$ between 0 and 2. Now suppose there exists another $x_1 \geq 0$ such that $f(x_1) = f(x_0) = 0$ By Rolle's Theorem, that would mean there exists $x_0\leq x_2 \leq x_1$ such that $f'(x_2) = 0$.
Now $f'(x) = 3x^2$. Note that $f'(x) = 0 \iff x = 0$, but $0$ isn't found in the interval we're considering.
Therefore, there can't be two roots of this polynomial function greater or equal than 0.

A: Note that $f(0) < 0$. Take the derivative and note that it is positive on the entire interval.  Conclude that f must cross the axis only once.


text:
Q: Real integral using residue theorem - why doesn't this work? Consider the following definite real integral:
$$I = \int_{0}^\infty dx \frac{e^{-ix} - e^{ix}}{x}$$
Using the $\text{Si}(x)$ function, I can solve it easily,
$$I = -2i \int_{0}^\infty dx \frac{e^{-ix} - e^{ix}}{-2ix} = -2i \int_{0}^\infty dx \frac{\sin{x}}{x} = -2i \lim_{x \to \infty} \text{Si}(x) = -2i \left(\frac{\pi}{2}\right) = - i \pi,$$
simply because I happen to know that $\mathrm{Si}(x)$ asymptotically approaches $\pi/2$.
However, if I try to calculate it using the residue theorem, I get the wrong answer, off by a factor of $2$ and I'm not sure if I understand why. Here's the procedure:
$$I= \int_{0}^\infty dx \frac{e^{-ix}}{x} - \int_{0}^\infty dx \frac{ e^{ix}}{x} =  \color{red}{-\int_{-\infty}^0 dx \frac{e^{ix}}{x}} - \int_{0}^\infty dx \frac{ e^{ix}}{x}
 = -\int_{-\infty}^\infty dx \frac{e^{ix}}{x} $$
Then I define $$I_\epsilon := -\int_{-\infty}^\infty dx \frac{e^{ix}}{x-i\varepsilon}$$ for $\varepsilon > 0$ so that$$I=\lim_{\varepsilon \to 0^+} I_\varepsilon.$$
Then I complexify the integration variable and integrate over a D-shaped contour over the upper half of the complex plane. I choose that contour because
$$\lim_{x \to +i\infty} \frac{e^{ix}}{x-i\varepsilon} = 0$$ and it contains the simple pole at $x_0 = i \varepsilon$. Using the residue theorem with the contour enclosing $x_0$ $$I_\varepsilon = -2 \pi i \, \text{Res}_{x_0} \left( \frac{e^{ix}}{x-i\varepsilon}\right) = -2 \pi i \left( \frac{e^{ix}}{1} \right)\Bigg\rvert_{x=x_0=i\varepsilon}=-2 \pi i \, e^{-\varepsilon}.$$
Therefore,
$$I=\lim_{\varepsilon \to 0^+} \left( -2 \pi i \, e^{-\varepsilon} \right) = -2\pi i.$$
However, that is obviously wrong. Where exactly is the mistake?

A: You've replaced the converging integral $\int_0^\infty \frac{\mathrm{e}^{-\mathrm{i} x} - \mathrm{e}^{\mathrm{i} x}}{x} \,\mathrm{d}x$ with two divergent integrals, $\int_0^\infty \frac{\mathrm{e}^{-\mathrm{i} x}}{x} \,\mathrm{d}x$ and $\int_0^\infty \frac{\mathrm{e}^{\mathrm{i} x}}{x} \,\mathrm{d}x$.  (That something divergent has been introduced is evident in your need to sneak up on a singularity at $0$ that was not in the original integral.)
Also, notice that your D-shaped contour does not go around your freshly minted singularity at $x = 0$.  The singularity lands on your contour.  See the Sokhotski–Plemelj theorem to find that the multiplier for the residue of the pole is $\pm \pi \mathrm{i}$, not $\pm 2 \pi \mathrm{i}$.

A: You cannot shift the pole from the integration contour at will. Imagine that you shift it in the lower complex half-plane. Then instead of $-2\pi i$ you would obtain for the integral the value $0$!
The correct way to handle the pole is to take the half of its residue value, which is equivalent to bypassing the pole along a tiny semicircle around it (observe that the result does not depend on the choice between upper and lower semicircle).

A: There is a problem at the very first step. You cannot split the integral because both integrals are divergent.


text:
Q: Дебаг linux kernel Здравствуйте! Пытаюсь произвести дебаг ядра linux. Столкнулся с проблемами, на которые не получается найти ответ, поэтому прошу помощи у вас. Для начала как я все делаю:
На отлаживаемую машину, загружаю ядро с включенными флагами дебага
CONFIG_FRAME_POINTER=y

CONFIG_KGDB=y

CONFIG_KGDB_SERIAL_CONSOLE=y

CONFIG_KGDB_KDB=y

CONFIG_KDB_KEYBOARD=y

В файле загрузчика прописываю
kgdboc=ttymxc1,115200 kgdbwait

После чего при запуске ядра получаю
[    2.340109] KGDB: Registered I/O driver kgdboc
[    2.375570] KGDB: Waiting for connection from remote gdb...

Далее на другой машине запускаю
sudo gdb-multiarch vmlinux

и подключаюсь к отлаживаемой машине
(gdb) target remote /dev/ttyUSB0

подключение проходит успешно и gdb отвечает мне где мы находимся
Remote debugging using /dev/ttyUSB0
kgdb_cpu_enter (ks=0x0, regs=0x730, exception_state=-1050376452)
    at kernel/debug/debug_core.c:671
671     kgdb_info[cpu].enter_kgdb--;

Теперь к проблемам:
Куда бы я не ставил брекпоинты(я проходил step'ами и ставил брейкпоинт на функцию которую он точно проходит) он их игнорирует и после continue просто происходит загруза ядра. Собственно вопрос где я делаю ошибки, что я делаю не так.
Так же мне бы хотелось отладить модули которые загружены в ядро( я пытался ставить на их функции брейки, но ничего не происходит).
Иногда после continue gdb просто отваливается, а ядро просто продолжает загружаться.


text:
Q: How can i integrate Jenkins with Onedrive? I would like to integrate Jenkins with OneDrive to upload data's. I had a look at the Jenkins available plugins. But there is no OneDrive plugin to integrate. Is this possible to integrate? Any advice would be appreciated.

A: You will need to add code in some way, either bash / cmd / your-favorite-langauge and upload using the onedrive api
You should first attempt to do it locally, with a script or a few commands - later translate that into your Jenkins.
This is also best practice, you should stay away from Jenkins plugins since they are community driven. Unless the quality of life improvement is worth it.


text:
Q: Prove uniqueness of polar-coordinates $(R>0, \theta)$ up to angle $\theta+ 2 \pi$.
Prove uniqueness of polar-coordinates $(R>0, \theta)$ up to angle $\theta+ 2 \pi$.

Suppose we have $(x,y) \in \mathbb R^2$. Then we can transform this point to polar-cordinates $(R>0, \theta)$ where the polar-coordinates are stated to be unique up to $\theta+ 2 \pi$ .
How do I show that no other point $(a,b) \in \mathbb R^2$ different from $(x,y) \in \mathbb R^2$ doesn't have the same polar-coordinates ? I'm looking for an algebraic argument, not a "draw-and-see" argument.
I know I can prove uniquness of coordinate in $\mathbb R^n$ using linear algebra on the set $\{e_i\} $which form a basis.
More generally how are uniqueness of spherical coordinates proved ?

A: Uniquess of $R$ is easy, because $R=\sqrt{a^2+b^2}$. For the angle you have to do some trigonometric work (or quote that $e^{i\theta}=1$ iff $\theta$ is a multiple of $2\pi$)


text:
Q: How to traverse all components of a JPanel? I'm trying to traverse (loop through) a JPanel, with GridLayout(3,2). And for all components in it, if they are an instance of DescriptionPanel I want to call their getHours() method.
Question,
How do I best 'loop through' all components of a JPanel?
my own attempt, which keeps throwing an exception (see below)
double hoursWorked = 0;
JPanel panel = new JPanel(new GridLayout(3,2));
.
.
.
for( int i = 0; i < panel.getComponentCount(); i++ ) {
    if(panel.getComponent(i) instanceof DescriptionPanel) {  //DescriptionPanel extends JPanel
        DescriptionPanel dp = (DescriptionPanel) panel.getComponent(i);
        hoursWorked += dp.getHours();
    }
}

I have tried to switch panel.getComponentCount() to its actualt number (6 in this case). But it keeps throwing the same error message.
for( int i = 0; i < 6; i++ ) {
    if(panel.getComponent(i) instanceof DescriptionPanel) {
        DescriptionPanel dp = (DescriptionPanel) panel.getComponent(i);
        hoursWorked += dp.getHours();
    }
 }

Exception

Exception in thread "AWT-EventQueue-0"
  java.lang.ArrayIndexOutOfBoundsException: No such child: 2

A: The safest (and in my opinion more  elegant) option here, is to use getComponents() method of the panel and iterate through components. Then an instance check of the iterator will do the job.
JPanel panel = new JPanel();
for (Component c : panel.getComponents()) {
    if (c instanceof DescriptionPanel)
    {
        DescriptionPanel dp = (DescriptionPanel) c;
        int hours = dp.getHours();
        // Do something with hours
    }
}

A: Maybe I will post it as an answer for those who might be wondering why this can occur.
The layout of the components is modified in AWT thread which is probably updating something in the container, thus changing the component's count.
https://docs.oracle.com/javase/7/docs/api/java/awt/Container.html#getComponents()
The documentation states that you should synchronize the access to these methods using the Component.getTreeLock method.
Such as:
    JPanel panel = new JPanel();
synchronized(panel.getTreeLock()) {
for (Component c : panel.getComponents()) {
    if (c instanceof DescriptionPanel)
    {
        DescriptionPanel dp = (DescriptionPanel) c;
        int hours = dp.getHours();
        // Do something with hours
    }
}
}


text:
Q: bootstrap framework for SharePoint 2013 Is there any body who tried to use bootstrap framework for SharePoint 2013?
i want to use this framework for our company TeamSite branding but i got an error
"The user interface version can not be determined"


text:
Q: How to retrieve principal information from HttpSessionEvent in Spring Boot? I am using the javax.servlet.http.HttpSessionListener class to listen for session changes in my Spring Boot applciation
public interface HttpSessionListener extends EventListener {
    default void sessionCreated(HttpSessionEvent se) {
    }

    default void sessionDestroyed(HttpSessionEvent se) {
    }
}

The question is, how can I retrieve user information from HttpSessionEvent?
I want to delete all the files uploaded by the user after session destroy, that's why I need at least his ID

A: By default, Spring Security stores the SecurityContext in the session under the key defined by HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY. So, if the user is still logged in, you could do:
@Override
void sessionDestroyed(HttpSessionEvent se) {
    HttpSession session = se.getSession();
    SecurityContext context = (SecurityContext) session.getAttribute
        (HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY);
    Authentication authentication = context.getAuthentication();
    // drill down from here, but could be authentication.getName()
}

A: you can get session by the httpEvent object and from session you can get current user info
se.getSession()


text:
Q: Tangent ODE solutions for $x' = f(x/t)$ There is a continous $f(u)$ and $\varphi(t)=at$ which is a solution of $x' = f(\frac{x}{t})$. Prove that:

*

*if $f'(a) < 1$ then no other solution is tangent to $\varphi(t)$ at $(0,0)$

*if $f'(a) > 1$ then there exists infinitely many tangent solutions to $\varphi(t)$ at $(0,0)$
I am totally lost and appreciate any hints how can I tackle this.


text:
Q: Why my sticky bar doesn't totally work with safari and internet explorer?

/*sticky_navbar*/

window.onscroll = function() {myFunction()};

var navbar = document.getElementById("header");
var sticky = navbar.offsetTop;

function myFunction() {
  if (window.pageYOffset >= sticky) {
    navbar.classList.add("sticky")
  } else {
    navbar.classList.remove("sticky");
  }
}

$(document).ready(function(){// checks vertical position of scroll bar
var scrollY = $(this).scrollTop();
// when user refreshes psge
if (scrollY > 0) {
  // if it is anywhere but the top change opacity by adding class .isSticky
  $('#header').addClass('isSticky');
} else {
  $('#header').removeClass('isSticky');
}

$(window).on('scroll', function(){
  // while uesr scrolls check the scrollTop position
  var scrollY = $(this).scrollTop();
  if (scrollY > 0) {
   $('#header').addClass('isSticky');
  } else {
   $('#header').removeClass('isSticky');
  }
});
});
#header {
  display: flex;
  justify-content: flex-end;
  background: rgba(0, 1, 31, 1);
    -webkit-transition: background 0.5s ease-in-out;
  -moz-transition: background 0.5s ease-in-out;
  -ms-transition: background 0.5s ease-in-out;
  -o-transition: background 0.5s ease-in-out;
  transition: background 0.5s ease-in-out;
  z-index: 2;

  position: sticky;
  top: 0;
  left: 0;
  right: 0;
}

#header.isSticky {
  background: rgb(139, 139, 157, 0.9);
    -webkit-transition: background 0.5s ease-in-out;
  -moz-transition: background 0.5s ease-in-out;
  -ms-transition: background 0.5s ease-in-out;
  -o-transition: background 0.5s ease-in-out;
  transition: background 0.5s ease-in-out;
}

#Title {
  margin: 0 auto 0 0;
  height: 20px;
  margin-top: 13px;
  padding-left: 10px;
  border-bottom: 1px solid orange;
  padding-top: 1px;
  padding-bottom: 35px;
  flex: 1;
}

#navbar {
  display: flex;
  justify-content: flex-end;
  border-bottom: 5px solid orange;
  padding-bottom: 10px;
  padding-top: 15px;
}

IMG.background {
  display: block;
  margin-left: auto;
  margin-right: auto;
  z-index: 1;
  width: 60%;
}

#navbar a {
  display: block;
  color: #FFF;
  text-align: center;
  padding: 10px 16px;
  text-decoration: none;
  font-size: 17px;
}

#navbar a:hover {
  background-color: #ddd;
  color: black;
}

#navbar a.active {
  background: rgba(217, 78, 68, 0.8);
  color: white;
}

.sticky {
  position: fixed;
  top: 0;
  width: 100%;
}

.sticky+.content {
  padding-top: 60px;

}

body {
  font-size: 28px;
  background-color: #00011f;
  margin-left: auto;
  margin-right: auto;
  margin-top: auto;
}

iframe{
  width: 100%;
}

h3{
  font-size: 28px
}

/*Contenu page d'accueil*/

#vignettes {
  padding: 16px;
  color: #000;
  background-color: #e8f1fa;
  height: auto;

}

#discovered{
  display: flex;
  justify-content: center;
  align-items: center;
  flex-wrap: wrap;

}

#research{
  display: flex;
  justify-content: center;
  align-items: center;
  flex-wrap: wrap;

}

#content{
  padding: 16px;
  color: #000;
  background-color: #e8f1fa;
  height: auto;

}

#file{
  margin : 5px;
}

img {vertical-align: middle;}

/* Slideshow container */

    .mySlides{
        display: flex;
        justify-content: center;

    }
    .mySlides > div {
        flex: 0 0 40%;
    }

.slideshow-container {
  max-width: 800px;
  position: relative;
  margin: auto;
  margin-top: 50px;

}

/* Caption text */
.text {
  color: #f2f2f2;
  font-size: 20px;
  padding: 8px 12px;
  box-sizing: border-box;

}

/* Number text (1/3 etc) */
.numbertext {
  color: #f2f2f2;
  font-size: 12px;
  padding: 8px 12px;

}

/* The dots/bullets/indicators */
.dot {
  height: 5px;
  width: 5px;
  margin: 0 2px;
  background-color: #bbb;
  border-radius: 50%;
  display: inline-block;
  transition: background-color 0.6s ease;
}

.active {
  background-color: #717171;
}

/* Fading animation */
.fade {
  -webkit-animation-name: fade;
  -webkit-animation-duration: 1.5s;
  animation-name: fade;
  animation-duration: 1.5s;
}
html>

 <link rel="stylesheet" href="CSS/style2.css" />
 <link rel="stylesheet" href="CSS/navbar.css" />
 <link rel="shortcut icon" href="IMAGES/PNG/favicon.png" />

        <meta charset="utf-8" />
        <title>CORAMP</title>
        <meta name="viewport" content="width=device-width, initial-scale=1">

 ACCUEIL

 L'ELECTROPHOTONIQUE

 CONTACT

« Visualisation en 3D d'un pont photonique obtenu entre un système biologique et un principe actif »

« Visualisation d'un stress hydrique sous l'effet d'un set de très basse fréquence »

« Ponts photoniques obtenus à partir de deux composites dentaires de composition différente »

I can't find why my sticky bar doesn't fade and doesn't change color when I scroll on my page.
I try to understand with the chrome console but my knowledge with JS is really poor... I tried to use and transform a tutorial from here : "https://www.w3schools.com/howto/howto_js_navbar_sticky.asp" .
On safari the navbar is jumping and doesn't fade with scroll and with IE I think it's doesn't fade too (I don't remember I can't test it on my mac)
You can see the website on this link : http://www.coramp.eu
On the simulator you can see a top-margin but I don't have it on any browser and I don't want it. I'm looking to stick the navbar on the top of the window
Can I get help please ? :'(

A: Sticky is not supported on all IE versions, see: https://caniuse.com/#search=sticky

On safari the navbar is jumping and doesn't fade

Not fading on Safari because you are using RGBA as you specified the opacity as 0.9, but you put RGB. So instead rgb(139, 139, 157, 0.9), it should be rgba(139, 139, 157, 0.9);, so:
#header.isSticky {
  background: rgba(139, 139, 157, 0.9);
    ...
}

The jumping is because when your header became sticky, it behaves like position fixed, and all the content below is "jumping" to that position because it became available. A workaround would be add a padding to your .slideshow-container and then position it behind the header applying a negative margin.
.slideshow-container {
    ...
    padding-top: 120px; /* 50px plus header height */
    margin-top: -70px; /* header height */
}

Does it make sense for you?


text:
Q: Dynamically added fields not working with calendar field I am trying to attach a calendar field to a dynamically added html code.
Initially, the code shows 3 input fields (as shown in the "p_scents" div).
When the "Add Another Employer" is clicked, it should generate another 3 inputs( as the ones above).
It is working fine for me to generate the first 2 fields (without the calendar field), but when I add the calendar field, it is not working.

Add Another Employer

    Employer Name<input class="dynamic" type="text" name="employern" id="employern" />
    Job Title<input class="dynamic" type="text" name="jtitle" id="jtitle" />
    Start Date
<input type="text" name="startd" class="textfield" />

Remove
').appendTo(scntDiv);
            i++;
            return false;}
        else{
            alert('Maximum Reached!');
        }
    });

    $('#remScnt').live('click', function() {
            if( i > 2 ) {
                    $(this).parents('p').remove();
                    i--;
            }
            return false;
    });
});
</script>

A: Sorry, but there is lot of stuff wrong/not good in your code. I'm trying to give some suggestions how to improve this, but first, what's wrong:

*

*IDs have to be unique. In your code, you give multiple elements the same ID. Especially the remove link will not work.

*Strings cannot span multiple lines in JavaScript.

*Don't add such a bunch of HTML as string. You have a quotation error in this string.

*Don't add


text:
Q: File I/O functionality is normally available in the 'Microsoft.VisualBasic' namespace, but the targeted platform does not support it I would like to open my .txt file, but i get this error
Error   1   'Open' is not declared. File I/O functionality is normally available in the 'Microsoft.VisualBasic' namespace, but the targeted platform does not support it.
I'm using vb2010 and I think the code is wrong cuz it's for vb6. How to change it to work in vb2010?
Private Sub zapisz_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles zapisz.Click
    Open "C:\Plik.txt" For Append As #1 'zapis
    print #1, "a" & a.Text
    Print #1, "b" & b.Text
    Print #1, "c" & c.Text
    Print #1, "d" & d.Text
Close #1
End Sub

Private Sub wczytaj_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles wczytaj.Click
    Dim strText As String, strIndex As String
Open "C:\Plik.txt" For Input As #1
    Do Until EOF(1)
        Input #1, strText
        strIndex = Left(strText, 1)
        strText = Right(strText, Len(strText) - 1)
        Select Case strIndex
            Case "a" : a = strText
            Case "b" : b = strText
            Case "c" : c = strText
            Case "d" : d = strText
        End Select
    Loop
Close #1
End Sub

A: The tools in the .NET framework make this sort of thing much cleaner and intuitive than the old VB6 file access statements:
Private Sub zapisz_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles zapisz.Click
    Using writer As New StreamWriter("C:\Plik.txt", True)
        writer.WriteLine("a" & a.Text)
        writer.WriteLine("b" & b.Text)
        writer.WriteLine("c" & c.Text)
        writer.WriteLine("d" & d.Text)
    End Using
End Sub

Private Sub wczytaj_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles wczytaj.Click
    For Each line As String In File.ReadAllLines("C:\Plik.txt")
        Dim index As String = line.Substring(0, 1)
        Dim text As String = line.Substring(1)
        Select Case index
            Case "a"
                a = text
            Case "b"
                b = text
            Case "c"
                c = text
            Case "d"
                d = text
        End Select
    Next
End Sub


text:
Q: detail in proof of the mean value theorem for integrals I am trying to prove the following result

If $f$ is a continuous function on a closed interval $[a,b]$, then
there exists a $c \in (a,b)$ such that,
$$f(c)=\frac{1}{b-a}\int_a^bf(x)\;\mathrm{d}x$$

I have worked out the following proof
Because $f$ is continuous on the interval, it reaches a minimum $m$, and a maximum $M$ so that we have
$$\begin{aligned} m&\leq f(x)\leq M \\ m(b-a)\leq  & \int_a^bf(x)\;\mathrm{d}x\leq M(b-a) \\  m\leq &\frac{1}{b-a}\int_a^bf(x)\;\mathrm{d}x\leq M\end{aligned}$$
and the IVT guarantees the exxistence of $c$ as above.
How do I prove that $c \neq a\ \& \ c\neq b$?
Thanks for the help !

A: If $f$ is constant, there is nothing to do.
Otherwise, let $M=\max f$ and $m=\min f$ on $[a,b]$ with $m\neq M.$ Then, $m\le \frac{\int_a^bf(t)dt}{b-a}\le M$ so the Intermediate Value Theorem gives us a $c\in [a,b]$ such that $f(c)=\frac{\int_a^bf(t)dt}{b-a}.$
If $c\in (a,b),$ we are done.
If $c=a$ then $f(a)=\frac{\int_a^bf(t)dt}{b-a}.$ If $f(a)=m,$ then $\int_a^b(f(t)-m)dt=0$ and since $f-m\ge 0$ on $[a,b]$ and continuous there, $f-m=0$ and $f$ is constant. Similarly, if $f(a)=M$ we get $f=M$.
So there are $a<x_0\neq x_1<b$ such that $f(x_0)=m$ and $f(x_1)=M.$ Without loss of generality, $x_0<x_1.$
Then, $m<f(a)<M$ so appying the IVT again, we get a $x_0\le d\le x_1$ such that $f(d)=f(a)$ and the result follows.
An almost identical argument shows that the result also holds if $c=b.$

A: Assume $w<z, w,z\in [a,b]$ with $f(w) = m, f(z) = M$
If $m=M \implies f$ is a constant function then all $c\in(a,b)$ works.
Suppose $m<M$
We have that for $c\in [w,z]$, $f(c) = \frac{1}{b-a}\int_{a}^{b}f(x)dx$
Suppose $c = a$, then $a = w$, because $a\leq w \leq c \leq  z \leq b$
Then $f(a) = m$ is the  minimum of the function
$f(z) =M>m \implies$ there exist some $\delta >0$ such that $f(x)>m+\epsilon$ for some $\epsilon>0$ for all $x\in (z-\delta,z]$
Thus we have that $\begin{aligned}\int_{a}^{b}f(x)dx & = \underbrace{\int_{a}^{z-\delta}f(x)dx}_{\geq f(a)\cdot(z-\delta -a)} +\underbrace{\int_{z-\delta}^{z}f(x)dx}_{\geq (f(a) + \epsilon)\cdot\delta>f(a)\cdot \delta}+\underbrace{\int_{z}^{b}f(x)dx}_{\geq f(a)\cdot(b-z)}>f(a)\cdot(b-a)\\  &\underbrace{\frac{1}{b-a}\int_{a}^{b}f(x)dx}_{f(c)} > f(a)\end{aligned}$
that is a contradiction. Then $c \neq a$
I hope it help you,
I think the other cases will be analogous
(for example, apply this reasoning to $-f$)

A: Here is another approach. Assume that $$f(x) > K=\frac{1}{b-a}\int_a^b f(x) \, dx$$ for all $x\in(a, b) $. This means that $g(x) =f(x) - K>0$ for all $x\in(a, b) $. Hence $$\int_{a} ^{b} g(x) \, dx>0$$ ie $$\int_{a} ^ {b} f(x) \, dx>K(b-a) $$ which is absurd.
Similarly one can show that $f(x) <K$ for all $x\in(a, b) $ can't hold. Thus by intermediate value theorem we must have $f(c) =K$ for some $c\in(a, b) $.

A: Sometimes a figure is worth 1000 words:

What is the area in blue?
$$\int\limits_a^b f(x)\ dx$$
What is the area in orange?
$$f(c) \cdot (b-a)$$
QED.


text:
Q: float vs. inline-block changes margin and parent height So I have been trying to wrap my mind around this and cant figure it out why.
Note: Margin and padding is 0.
The 1st example is

I have two images - One is float, the other is inline-block.
The height of the div is shown by the gray color.
float: left;

display: inline-block;

The 2nd example is

Again, left and inline-block do different things
float: left;

display: inline-block;

Bottom Line
Any suggestions beside the question is welcome.
I don't know why margin / padding is changing and why div size matters by float and display. Thanks

A: There are 2 problems here.
1) Like someone mentioned in the comments, inline block takes space into account, meaning on the parent div you should have:
font-size:0;

2) Floating takes the element out of the document flow, meaning the parent will expand only past the last non floated child element. To fix this you should put a clearfix class in your css and add it to the parent of the floated element(s).
.clearfix::after{
   content:'';
   display:block;
   clear:both;
}

So once you've done this your first example should look like this:

Now the gray box should expand past the purple box;
As a matter of consistency i don't think you should mix inline-block with floating. One, it won't work on the same element and 2, they are designed for different things.


text:
Q: In Heinlein's Future History, When Does the Soviet Union Fall? In The Man Who Sold the Moon, Harriman attracts support from an anti-communist by suggesting that the SU may "paint" a hammer-and-sickle across the face of the Moon, if America doesn't get there first. So clearly it still exists in 1978. But I don't recall hearing of it later than that, not even in "The Green Hills of Earth".
Is there any mention anywhere of what happened to it, and when/how it eventually fell, as I presume it does?


text:
Q: Entity framework and storing japanese text Is it possible to store english and japanese in the same field? The field is of type NVARCHAR(1024). The only thing that i see are question marks.
I added another field to the table and set it's collation to japanese. That seems to work. But i don't want 2 columns, i want just 1.
Everywhere i read that NVARCHAR can hold unicode without changing the default collation, is that true and if so how do i tell EF it's english or japanese?

A: you can check the encryption of the string that you would like to save in DB by the entity-framework and then decide where you will save it!
To handle this issue, I suggest you use Encoding.GetEncoding Method (String) to make it.
Here is a function for you and you may test it and let me know if it works.
public static bool IsUnicode(string input)
{
    foreach (char chr in input)
    {
        string str = chr.ToString();
        Encoding code = Encoding.GetEncoding("GB18030");
        if (code.GetByteCount(str) == 2)
        {
            return false;
        }
    }
    return true;
}
And here is my test result:

string zh = "微软";
string en = "Microsoft";
bool Izh = IsUnicode(zh);   //return false
bool Ien = IsUnicode(en);   //return true

To the parameter in the method, you could visit the MSDN at http://msdn.microsoft.com/zh-cn/library/aa332097(VS.71).aspx to get the right string.
Best Regards,
Nader SGHIR


text:
Q: SQL query with multiple criteria and sub selects I am fairly new to using joins and selecting from multiple tables. I have successfully figured out how to get data from 2 tables based on a number of conditions. Now my issue is that I need to return a count only if another condition is also met. The idea is like this:
I have a query that returns the number of items in a specific status at a specific time. My query for this is:
SELECT count(*),
       e.campus_id,
       e.course_id
FROM statuses_history AS sh,
     enrolments AS e
WHERE sh.date_added > '2015-08-01 00:00:00'
  AND sh.date_added < '2015-08-20 23:59:59'
  AND sh.status_id = 57
  AND sh.item_id = e.enrolment_id
  AND (e.course_id = 2
       OR e.course_id =7
       OR e.course_id = 8
       OR e.course_id = 9)
GROUP BY e.campus_id,
         e.course_id;

Now I have to check that it has been in a different status, lets say sh.status_id = 50 before it was in 57. It also does not have to fall within the data range specified. So I basically need to change my query in some way to also select if it's ever been in status_id 50 and then only return the result if both the statuses are found. sh.status_id =57 will be bound by the dates specified.
Thanks in advance for the help.

A: You can adjust the subselect as needed, but this will return a row if another value is found in the database.
I don't like subselects, but this should work.  I have not tested the syntax.
select count(*), e.campus_id, e.course_id
FROM statuses_history as sh, enrolments as e
WHERE sh.date_added > '2015-08-01 00:00:00'
      AND sh.date_added < '2015-08-20 23:59:59'
      AND sh.status_id = 57
      AND sh.item_id = e.enrolment_id
      AND (e.course_id = 2 OR e.course_id =7
          OR e.course_id = 8 OR e.course_id = 9)
      AND EXISTS (select sh2.status_id from statuses_history as sh2
                 WHERE NOT sh2.status_id = 57
                   AND sh2.item_id = e.enrolment_id)
GROUP BY e.campus_id, e.course_id;

A: I assume that the primary key is item_id?
You just have to join the same tables by the primary key and the status_id = 50.
For this case I will use INNER JOIN (my preference) but you can use FROM/WHERE CLAUSE.
select count(*), e.campus_id, e.course_id
FROM statuses_history as sh, enrolments as e

INNER JOIN statuses_history AS oldSh ON oldSh.item_id = sh.item_id AND oldSh.status_id = 50

WHERE sh.date_added > '2015-08-01 00:00:00' AND sh.date_added < '2015-08-20 23:59:59' AND sh.status_id = 57 and sh.item_id = e.enrolment_id AND (e.course_id = 2 OR e.course_id =7 OR e.course_id = 8 OR e.course_id = 9)
GROUP BY e.campus_id, e.course_id;

But if you prefer WHERE, you can do the following:
select count(*), e.campus_id, e.course_id
FROM statuses_history as sh, enrolments as e, statuses_history AS oldSh ON
WHERE oldSh.item_id = sh.item_id AND oldSh.status_id = 50 AND
sh.date_added > '2015-08-01 00:00:00' AND sh.date_added < '2015-08-20 23:59:59' AND sh.status_id = 57 and sh.item_id = e.enrolment_id AND (e.course_id = 2 OR e.course_id =7 OR e.course_id = 8 OR e.course_id = 9)
GROUP BY e.campus_id, e.course_id;

A: Add a left join and use a case statement to do your count.
LEFT JOIN statuses_history sh2 ON sh2.item_id = e.enrollment_id AND sh2.status_id = 50

You'll need to use a different format for your inner joins in order to do the left join.  Here's the new query:
select count(sh.status_id), e.campus_id, e.course_id  , SUM(CASE WHEN sh2.status_id IS NOT NULL THEN 1 ELSE 0 END) as cnt
FROM statuses_history sh
INNER JOIN enrolments e ON sh.item_id = e.enrolment_id
LEFT JOIN statuses_history sh2 ON sh2.item_id = e.enrollment_id AND sh2.status_id = 50
WHERE sh.date_added > '2015-08-01 00:00:00' AND sh.date_added < '2015-08-20 23:59:59' AND sh.status_id = 57 AND (e.course_id = 2 OR e.course_id =7 OR e.course_id = 8 OR e.course_id = 9)
GROUP BY e.campus_id, e.course_id;


text:
Q: How to display both points and edges in MeshLab? I'm new to MeshLab, but can anyone tell me how to display BOTH points AND edges? Now, I can only choose either one, not both. I'm using a .ply file to load the mesh. Thanks in advance!

A: Show edges using the usual toolbar button and then activate the Show Vertex Dots decoration (in the menu Render->Show Vertex Dots).
Optionally, activate the layer side dialog and in its lower part you will see the options for this decoration where you can change the dot size.


text:
Q: Neo4j data export from Windows to Linux machines I have embedded Neo4j, modelled the data in Windows machine. My production database server is on centos. So, I need to move the data(Folder X)  from windows machine to CentOS.
The problem that I am facing:  Even if on the linux machine, I pointed the data base (by changing the server configuration location) to the data folder X, Neo4j doesn't recognize that data.
Is it because the format of files  data created for Neo4j is different from that in Linux .
Please help.


text:
Q: Workflow for App Engine I'm about to start an App Engine project for the first time.  Most likely with Python.  I was wondering if anybody could give me a leg up by detailing their workflow when developing for it.  What tools do you use to go from start to deployed?  Did you do any app engine specific configurations to those tools?

A: How big of an application are you planning? Using the python runtime, it's pretty easy to get even a medium-to-large sized app developed with nothing more than a text editor (I use TextMate or vi).
Python is an incredibly terse language (or can be), and you can have multiple related handlers in one file, so you don't need anything to handle more than a dozen files across a bunch of directories, like you might with Java for example.
To test your app locally you just need dev_appserver.py and to upload your app you just need appcfg.py.  Easy peasy.
Even if you're planning on writing a huge complex app, I would just start small with a simple text editor and find more robust tools when you find that you need them (and know specifically what you need from them).


text:
Q: How to draw text on image and show it in a grid? I am using SqaureImageView class as:
    public class SqaureImageView extends AppCompatImageView {

    int widthMeasureSpec;
    int heightMeasureSpec;

    public SqaureImageView(Context context) {
        super(context);
    }

    public SqaureImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public SqaureImageView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, widthMeasureSpec);
        this.widthMeasureSpec=widthMeasureSpec;
        this.heightMeasureSpec=heightMeasureSpec;
    }

    public int getWidthMeasureSpec(){
        return widthMeasureSpec;
    }

    public int getHeightMeasureSpec(){
        return heightMeasureSpec;
    }
}

I am using this SquareImageView in an arrayAdapter like so:
public class GridPostAdapter extends ArrayAdapter<String> {

    private Context mContext;
    private LayoutInflater mInflater;
    private int layoutResource;
    private String mAppend;
    private ArrayList<String> imgColor;
    private ArrayList<String> imgCaption;

    public GridPostAdapter(Context context, int layoutResource, String append, ArrayList<String> imgColor, ArrayList<String> imgCaption) {
        super(context, layoutResource, imgColor);
        mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        mContext = context;
        this.layoutResource = layoutResource;
        mAppend = append;
        this.imgColor = imgColor;
        this.imgCaption = imgCaption;

    }

    private static class ViewHolder {
        SqaureImageView image;
        ProgressBar mProgressBar;
    }

    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {

        /*
        Viewholder build pattern (Similar to recyclerview)
         */
        final ViewHolder holder;
        if (convertView == null) {
            convertView = mInflater.inflate(layoutResource, parent, false);
            holder = new ViewHolder();
            holder.mProgressBar = (ProgressBar) convertView.findViewById(R.id.gridImageProgressbar);
            holder.image = (SqaureImageView) convertView.findViewById(R.id.gridImageView);
            holder.image.setBackgroundColor(Integer.parseInt(imgColor.get(position)));

            Bitmap bm = BitmapFactory.decodeResource(getContext().getResources(), R.drawable.ic_blank);
            Bitmap newImage = bm.copy(Bitmap.Config.ARGB_8888, true);

            Canvas  c = new Canvas(newImage);
            c.drawBitmap(newImage, 0, 0, null);

            Paint paint = new Paint();
            paint.setColor(Integer.parseInt(String.valueOf(R.color.black)));
            paint.setStyle(Paint.Style.FILL);
            paint.setTextSize(20);

            c.drawText(imgCaption.get(position), 0, 5, paint);

            holder.image.setImageBitmap(newImage);

            convertView.setTag(holder);

        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        ImageLoader imageLoader = ImageLoader.getInstance();

        //https://firebasestorage.googleapis.com/v0/b/projectx-971e6.appspot.com/o/photos%2Fusers%2F8QemZCZPRabTR88Vkpv1yDXHLEn1%2Fphoto1?alt=media&token=124af00f-c02b-4785-a6d5-ecb042dd18d2
        imageLoader.displayImage("", holder.image, new ImageLoadingListener() {
            @Override
            public void onLoadingStarted(String imageUri, View view) {
                if(holder.mProgressBar != null){
                    holder.mProgressBar.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
                if(holder.mProgressBar != null){
                    holder.mProgressBar.setVisibility(View.GONE);
                }
            }

            @Override
            public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
                if(holder.mProgressBar != null){
                    holder.mProgressBar.setVisibility(View.GONE);
                }
            }

            @Override
            public void onLoadingCancelled(String imageUri, View view) {
                if(holder.mProgressBar != null){
                    holder.mProgressBar.setVisibility(View.GONE);
                }
            }
        });

        return convertView;
    }
}

I have a UniversalImageLoader class in place for loading the images:
public class UniversalImageLoader {

    private static final int defaultImage = R.drawable.ic_android;
    private static final int defaultImageBlank = R.drawable.ic_blank;

    private Context mContext;

    public UniversalImageLoader(Context context) {
        mContext = context;
    }

    public ImageLoaderConfiguration getConfig(){
        DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
                .showImageOnLoading(defaultImage)
                .showImageForEmptyUri(defaultImageBlank)
                .showImageOnFail(defaultImage)
                .considerExifParams(true)
                .cacheOnDisk(true).cacheInMemory(true)
                .cacheOnDisk(true).resetViewBeforeLoading(true)
                .imageScaleType(ImageScaleType.EXACTLY)
                .displayer(new FadeInBitmapDisplayer(300)).build();

        ImageLoaderConfiguration configuration = new ImageLoaderConfiguration.Builder(mContext)
                .defaultDisplayImageOptions(defaultOptions)
                .memoryCache(new WeakMemoryCache())
                .diskCacheSize(100 * 1024 * 1024).build();

        return configuration;
    }

    /**
     * this method can be sued to set images that are static. It can't be used if the images
     * are being changed in the Fragment/Activity - OR if they are being set in a list or
     * a grid
     * @param imgURL
     * @param image
     * @param mProgressBar
     * @param append
     */
    public static void setImage(String imgURL, ImageView image, final ProgressBar mProgressBar, String append){

        ImageLoader imageLoader = ImageLoader.getInstance();
        imageLoader.displayImage(append + imgURL, image, new ImageLoadingListener() {
            @Override
            public void onLoadingStarted(String imageUri, View view) {
                if(mProgressBar != null){
                    mProgressBar.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
                if(mProgressBar != null){
                    mProgressBar.setVisibility(View.GONE);
                }
            }

            @Override
            public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
                if(mProgressBar != null){
                    mProgressBar.setVisibility(View.GONE);
                }
            }

            @Override
            public void onLoadingCancelled(String imageUri, View view) {
                if(mProgressBar != null){
                    mProgressBar.setVisibility(View.GONE);
                }
            }
        });
    }

I want to draw text on each image and show it in a gridview. Using this I can only see coloured images and without the text being drawn on them. I am new to android and I am unsure how to use bitmap and canvas to draw the text on the images. Please have a look at my code and point out the modifications/improvements.

A: I have used one function which converts my image + text in a bitmap. Then I am able to display that bitmap image easily in grid view.
Here is my output with gridview.

//create bitmap from view and returns it
public static Bitmap getBitmapFromView(View view) {
    //Define a bitmap with the same size as the view
    Bitmap returnedBitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888);
    //Bind a canvas to it
    Canvas canvas = new Canvas(returnedBitmap);
    //Get the view's background
    Drawable bgDrawable = view.getBackground();
    if (bgDrawable != null) {
        //has background drawable, then draw it on the canvas
        bgDrawable.draw(canvas);
    } else {
        //does not have background drawable, then draw white background on the canvas
        canvas.drawColor(Color.WHITE);
    }
    // draw the view on the canvas
    view.draw(canvas);
    //return the bitmap
    return returnedBitmap;
}

Here view is my RelativeLayout which contains image-view and edit-text. Hope I have understood your question well and you got hint from this.


text:
Q: Gallery square miniature with title I finally give up my previous idea... I tried with table but seems to be hard too. I have another idea:
A squared div containing:

*

*the text at the bottom (no percentage) certainly with: position:absolute;bottom:0;

*the miniature img-responsive at the top of caption vertically/horizontally centered (maybe display:table-cell; can help)

I often see solutions with a predefining widht (e.g 30% or so) but I want this to adapt to any width (because they will be different depending of the screen size)
|-------------------|  |-------------------|
|                   |  |         I         |
|                   |  |         M         |
|p  i  c  t  u  r  e|  |         A         |
|                   |  |         G         |
|                   |  |         E         |
|title (caption)    |  |title (caption)    |
|-------------------|  |-------------------|

PREVIOUSLY
It's been 3 hours that I'm trying to get what I want, but impossible (checked stackoverflow, bootstrap options, jsfiddle, w3schools and others...)
My problem look somehow simple:
The goal is to get a formatted gallery.
I explain my self:
Each "thumbnail" (bootstrap's one) need to be square and contain:

*

*the thumbnail (max 70% of height, 100% width, vertically and horizontally centered) and need to be fill width or height

*the Title under (30% left, vertically and horizontally centered)

As an image is better than long text I created a Paint
Example
I represented 3 column, but the idea is to get as much as i need in a row
I tried to:

*

*Use a table

*Modify This (because the title isn't vertically-centered in the 30%

*A hack to center but it doesn't work when height is not a px value (can't post more than 2 links)

*and a various other

As a note, I would like to use CSS only, and get Bootstrap on my website.
I hope you understand my problem, and will help me to solve this.
Using the comment below, my code now looks:

Title

This works nicely, but vertical image aren't resized correctly. Please give me a hack to allow this (add max-height:100%; doesn't work"

A: Finally I got my answer, maybe not optimal but this works:

.image{
    position:relative;
    overflow:hidden;
    padding-bottom:80%;
 height:100%;
    margin:0px;
}
.outer img{
 margin:auto;
}

.outer {
 width:100%;
 height:100%;
    position:absolute;
 display:flex;
}
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

Title

Title

I hope this will help :)


text:
Q: In Rust, how to use variable in format! macro? I have a very simple program:
fn main() {
    let y = format!("{:0>3}", 11);
    println!("{}", y);
}

The output is the string 011. The problem is that the width specifier 3 in {:0>3} is coming from a variable like this:
fn main() {
    let x = 3usize;
    let y = format!("{:0>3}", 11);
    println!("{}", y);
}

How can I use variable x to replace 3 in {:0>3}?

A: fn main() {
    let x = 3;
    let y = format!("{:0>width$}", 11, width=x);
    println!("{}", y);
}

As it may be hard to remember the whole formatting syntax, it's a good idea to get used to find the reference.


text:
Q: xpath get by div id not working my script dont get any results(blank page) and i dont understand why
I've used this script on other websites and work
$url = 'http://ip-score.com/checkip/207.224.78.193';
libxml_use_internal_errors(true);
$html = file_get_contents($url);
$dom = new DOMDocument();
$dom->loadHTML($html);
$xpath = new DOMXPath($dom);

$my_xpath_query = "//div[@id='MaxMind']";
$result_rows = $xpath->query($my_xpath_query);

foreach ($result_rows as $result_object){
echo $result_object->childNodes->item(0)->nodeValue;
}

i've aspect to get this results:
207.224.78.193  United States
State: Minnesota
City: Minneapolis
ZIP: 55407
Hostname: 207-224-78-193.mpls.qwest.net, Whois
Organization: CenturyLink, History
ISP: CenturyLink
Mail Server: N\A
IP range: 207.224.71.0 - 207.224.97.191
Current region time: Thu 12th Mar 2015 - 02:52:15 GMT: -05:00
Region timezone: America/Chicago

i want to get all info from url(state,city,zip...) but i can not get it one by one so i decise to get all then split it into var

A: Your xpath expression is currently looking for that div as the root element of the document. You probably want to use //div[@id='MaxMind'] to search the document entirely, or just use $dom->getElementById("MaxMind") as xpath isn't really needed for this query.
Also worth noting: the first child of that element is just a text node full of white space. To dump out everything in the div replace
echo $result_object->childNodes->item(0)->nodeValue;

with
echo $result_object->nodeValue;

Though if you want to get at that stuff in a more reasonable manner, instead of just one blob of text, an xpath expression like //div[@id='MaxMind']/p will give you each "line" within.


text:
Q: ros tuetlebot3 launh file bug
I am using ubuntu version 20.0.4
I have followed all the turtlebot simulation instruction here but don't what is the issue I also check my bashrc file all the path are correct. Can anyone help me
Update by bashrc file
Run the turtlebot launch file

A: You're running 20.04, which means your ROS version will be Noetic. However the tutorial you're referencing is written for Kinetic; which means you're installing a package for the wrong version.
You can either repeat the install instructions with: git clone -b noetic-devel https://github.com/ROBOTIS-GIT/turtlebot3_simulations.git. Or cd into the cloned package and checkout the right branch via: git checkout noetic-devel.
Note that you'll most likely need to clean your workspace as it will not have built right.


text:
Q: How to access the element of a list/vector that passed by reference in C++ The problem is passing lists/vectors  by reference
   int main(){
        list<int> arr;
        //Adding few ints here to arr
        func1(&arr);
        return 0;
    }

    void func1(list<int> * arr){
     // How Can I print the values here ?

     //I tried all the below , but it is erroring out.
     cout<<arr[0]; // error
     cout<<*arr[0];// error
     cout<<(*arr)[0];//error

     //How do I modify the value at the index 0 ?

     func2(arr);// Since it is already a pointer, I am passing just the address
     }

     void func2(list<int> *arr){

     //How do I print and modify the values here ? I believe it should be the same as above but
     // just in case.
     }

Is the vectors any different from the lists ? Thanks in advance.
Any links where these things are explained elaborately will be of great help. Thanks again.

A: You aren't passing the list by reference, but by a pointer. In "C talk" the two are equal, but since there is a reference type in C++, the distinction is clear.
To pass by reference, use & instead of * - and access "normally", i.e.
void func(list<int>& a) {
    std::cout << a.size() << "\n";
}

To pass by pointer, you need to derefer the pointer with an asterisk (and do take note of operator presedence), i.e.
void func(list<int>* arr) {
    std::cout << (*a).size() << "\n"; // preferably a->size();
}

There is no operator[] in std::list.

A:    //note the return type also!
   void func1(list<int> * arr)
   {
    for (list<int>::iterator i= arr->begin() ; i!= arr->end(); i++ )
    {
          //treat 'i' as if it's pointer to int - the type of elements of the list!
          cout<< *i << endl;
    }
   }

In your example, return type of func1() is not specified. So I specified it. You may change from void to some other type. Also don't forget to specify return type for func2() and main() too.

If you want to use subscript operator [], then you've to use std::vector<int>, as list<> doesn't overload operator[].  In that case, you can write :
for(std::vector<int>::size_type i = 0 ; i < arr->size() ; i++ )
{
    cout << (*arr)[i] << endl;
}

I'm still assuming arr is pointer to vector<int>.
Maybe, you would like to modify your code a little bit, like this:
   void func1(vector<int> & arr) // <-- note this change!
   {
         for(std::vector<int>::size_type i = 0 ; i < arr.size() ; i++ )
         {
                cout << arr[i] << endl;
         }
   }


text:
Q: MongoDB throws "Error: Connection was destroyed by application" during insert I check if a specific key value pair exists and insert if they don't exist. For some strange reason MongoDB throws an error during insert. Any help would much appreciated.
Update #2: Added entire function.
{
    var connectURL  = "mongodb://something";
    var mycollection= "something2";
    var db;
    var col;

    async.series([
      // Connect to DB
      function(callback) {
              MongoClient.connect(connectURL,function(error, db2) {
                      if (error) {console.log("db connect error" + error);callback(error,"db connect error"); return;}
                      db = db2;
                      callback(null,"connect success");
              });
      },
      function(callback) {
              col = db.collection(mycollection);
          callback(null,"collection success");
      },
      function(callback) {
              //console.log ("insert begin ...");
              var i = 1;
              async.whilst(
                function() { return i <= count },
                function(callback) {
                    var mydocument = rows.shift();
                    col.findOne({ "sha" : mydocument.sha}, function(err, doc) {
                      console.log ("checked ....",  mydocument.sha);
                      if(doc != null) {
                        console.log ("Exist :" + mydocument.sha);
                      } else {
                        console.log ("Inserting : " + mydocument.sha);
                        col.insert(mydocument,function(error,result) {
                         if (error) {
                         console.log("insert error:" + error);
                         callback(error);
                         return;
                         }
                         i++;
                        console.log ("inserted ...");
                       }); //end insert
                    } //end else
             i++;
             });//end findOne
            callback(null);
        },
                function(error) {
                  callback(error,"insert sucess")
                }
              ); //end async.whilst
      },
      function (callback){
              //console.log ("###########close db");
              db.close();
              console.log("## end insert: "+ moment().format());
              callback(null,"connection closed");
      }
     ], function(error, results) {
                    if (error) { console.log("error"); }
                            //console.log(results);
            });
}

Output
checked .... 078d40cc537de96310e945a50a60b0084e21d2e1
Inserting : 078d40cc537de96310e945a50a60b0084e21d2e1
insert error:Error: Connection was destroyed by application

TypeError: Cannot read property 'sha' of undefined

A: Denote cb1 as the callback of col.findOne, and cb2 as the callback of col.insert.
cb1 returns once it issues col.insert without waiting cb2 to finish. Since cb1 also increment i and your testing function provided to async.whilst would then evaluate to be false, which cause the async.whilst thought it has finished all iterations.
So async.series moves on to the next task, which then issues db.close. Therefore the database connection may be closed before the remaining insertion commands are finished.
By the way, it seems your code snippet would jam the database by repeatedly issue col.findOne. Your i increases in either cb1 or cb2, but the async.whilst may repeatedly do the testing and execution many many times before each time i can be incremented. Perhaps you could use setTimeout(callback,...) instead of calling the callback immediately.


text:
Q: AppleScript to read and save website content (API) I have an AppleScript to read URLs line by line and open them in Safari. This one:
set thePath to (path to desktop as Unicode text) & "sites.txt"
set theFile to (open for access file thePath)
set theContent to (read theFile)
close access theFile

set theURLs to every paragraph of theContent

tell application "Safari"
    repeat with theURL in theURLs
        make new document
        set URL of front document to theURL
        delay 1
        repeat until ((do JavaScript "document.readyState" in front document) is "complete")
            delay 30
        end repeat
        close front document
    end repeat
end tell

In this example I work with these URLs - they are really similar to my use case, which I can't share.
http://www.omdbapi.com/?t=True%20Grit&y=1969
http://www.omdbapi.com/?t=Avatar&y=2009
This AppleScript works fine for me, but I can't write the content back to txt-file on my desktop, request by request.
Can anybody help?

A: Try:
set thePath to (path to desktop as text) & "sites.txt"
set outPath to quoted form of (POSIX path of (path to desktop as text) & "sites content.txt")

set theUrls to every paragraph of (read file thePath)

set myContent to {}
repeat with aURL in theUrls
    set end of myContent to aURL & return
    set pageContent to do shell script "curl " & aURL
    set end of myContent to pageContent & return & return
end repeat

do shell script "echo " & quoted form of (myContent as text) & " >> " & outPath


text:
Q: Laravel export excel from array return empty file I want to download excel file from array with Laravel
Library:
use Maatwebsite\Excel\Facades\Excel;

This is my code:
$ex = [
    ['one', 'name'],
    ['two', 'family']
];

return Excel::download(new TestExport([$ex]), 'test.xlsx');

My class:
class TestExport
{
    protected $arrays;

    public function __construct(array $arrays)
    {
        $this->arrays = $arrays;
    }

    public function array(): array
    {
        return $this->arrays;
    }
}

But this code download empty xlsx file

A: I found answer:
class TestExport implements FromCollection, WithHeadings
{
    protected $data;

    /**
     * Write code on Method
     *
     * @return response()
     */
    public function __construct($data)
    {
        $this->data = $data;
    }

    /**
     * Write code on Method
     *
     * @return response()
     */
    public function collection()
    {
        return collect($this->data);
    }

    /**
     * Write code on Method
     *
     * @return response()
     */
    public function headings() :array
    {
        return [
            'ID',
            'Name',
            'Email',
        ];
    }
}

Source: https://www.itsolutionstuff.com/post/laravel-create-csv-file-from-custom-array-using-maatwebsiteexample.html

A: I appreciate your research to find the answer yourself. Agreeing with your own answer, I also want to emphasize that the Excel library that you are using, accepts Laravel collection, not an array. So, you need to convert your array to a collection using the 'collect' helper function as bellow:
$myCollection = collect($this->ar);

Then export it using Excel facade:
return Excel::download(new TestExport($myCollection), 'test.xlsx');


text:
Q: Composition operators on fractional-order (periodic) Sobolev spaces (The question was originally posted on MSE.)
Preliminaries: We know that the fractional-order Sobolev spaces $\mathrm{H}^s(\mathbb{R})$ and $\mathrm{H}^s(\mathbb{T})$ are closed under multiplication provided $s > 1/2$. This is proved for example in the following questions on MSE using the Fourier convolution theorems:

*

*Sobolev space is an algebra

*For which $s \in \mathbb{R}$, is $H^s(\mathbb{T})$ a Banach algebra?
Thus we infer that $u^p \in \mathrm{H}^s(\mathbb{R})$ for all $p \in \mathbb{Z}_+$ whenever $u \in \mathrm{H}^s(\mathbb{R})$. Likewise for $\mathrm{H}^s(\mathbb{T})$.
Question: Is there a simple argument to conclude that $u^p \in \mathrm{H}^s(\mathbb{R})$ (and $\mathrm{H}^s(\mathbb{T})$) for all interpolating values $p \in [1, \infty)$, too?
More generally, from a MathOverflow question it is stated that the composition $f \circ u \in \mathrm{H}^s(\mathbb{R})$ for all real-valued $u \in \mathrm{H}^s(\mathbb{R})$ provided $f \in \mathrm{C}^{\lfloor s + 2 \rfloor}(\mathbb{R})$ with $f(0) = 0$. I would like to see references to this result or an outline of a proof.
Revised question: As pointed out by Joonas Ilmavirta below, I had made an elementary mistake concerning the expression $u^p$ for $p \in (1, \infty) \setminus \mathbb{Z}_+$, which should have been $|u|^p$ instead. Then I ask:

For which $p \in (1, \infty) \setminus \mathbb{Z}_+$ and $s > \frac{1}{2}$ is $|u|^p$ or $u|u|^{p - 1}$ in $\mathrm{H}^s(\mathbb{T})$ whenever $u \in \mathrm{H}^s(\mathbb{T})$?
(Similarly for $\mathrm{H}^s(\mathbb{R})$, but the periodic case is most important.)

Note: $|\cdot|^p$ and $\cdot |\cdot|^{p-1} \in \mathrm{C}^{\lfloor p \rfloor}$ for $p > 1$.

A: Let $\frac12<s<1$, let $u\in H^s(\mathbb R)$, then also $u\in C_0$, and let $f$ be Lipschitz on $[-||u||_\infty \ ,+||u||_\infty]$ with $|f(x)-f(y)|\leq M|x-y|$. Then $$\int\int \frac{|f(u(t))-f(u(t'))|^2}{|t-t'|^{1+2s}}dt\ dt'\leq M^2\int\int\frac{|u(t)-u(t')|^2}{|t-t'|^{1+2s}}$$With $f(0)=0$ you also have $|f(u)|\leq M|u|$ so that $f(u)\in L^2$.
More generally, for $s=m+\sigma$ with $m$ (an integer) $\geq1$ and $0<\sigma<1$, use the equivalent definitions of $H^s$ as $\{u\in H^m: D^mu\in H^\sigma\}$ and of $H^\sigma$ as $\{v\in L^2: \int\int\frac{|v(t)-v(t')|^2}{|t-t'|^{1+2\sigma}}<\infty\}$, together with a development of $D^m (f(u))$. ($f\in W^{m+1,\infty}_{loc}$ with $f(0)=0$ is enough in this case).

A: Hint at a partial answer to the revised question, extended to $p\in (0,\infty)$: for $\frac12<s<1$,  $p\geq 1$ is necessary and sufficient.
The "if" part is straightforward using the double integral definition of $H^s$. The "only if" part will better be dealt with using Fourier series  $i\ \sum \pm|n|^{-\alpha} e^{int}$ ($\pm :=$ sign of $n$) or $\sum |n|^{-\alpha} (e^{int}-1)$ that vanish at $0$ with a singularity.


text:
Q: Java disable other vue when my variable is equals to a specific number I have a variable with 4 values possibles : 1,2,3 and 4
I woudlike to do a function to disable my view in javafx.
example 1 : my variable equals 1 so disable 2,3 and 4
example 2 : if my variable equals 3 so siable 1,2 and 4
Java :
int valueType = 3;

if (valueType==1 || valueType==2 || valueType ==4)anchorpaneView.getChildren().get(i).setVisible(false);

Is it possible to have a generic function to do this ?


text:
Q: Having trouble with my C++ program. Involes resizing an integer array dynamically Here is what I have so far: http://cpp.sh/54vn3
#include <iostream>
#include <string>
#include <cmath>
#include <iomanip>
#include <cstdlib>
using namespace std;

int *reSIZE(int *&original, int &SIZE, const int &maxSIZE); //function prototype resize
void sortFUNC(int *&original, int &SIZE, const int &maxSIZE); //function prototype sortFUNC

int main()
{
    int SIZE = 4; //size of current array
    int maxSIZE = 10; //size of final array
    int *original = new int[SIZE] {5, 7, 3, 1}; //old(current) array

    cout << "Elements in array: "; //test output
    reSIZE(original, SIZE, maxSIZE); //call function resize
    cout << endl << endl; //blank line
    cout << "Elements in array in increasing order: "; //test output
    sortFUNC(original, SIZE, maxSIZE); //call function sortFUNC
    cout << endl << endl;
    return 0;
}

int *reSIZE(int *&original, int &SIZE, const int &maxSIZE)//function definition
{
    int *temporiginal = new int[SIZE + 3]; //(final)new array

    for (int i = 0; i < SIZE; i++) //copy old array to new array
    {
        temporiginal[i] = original[i];
        cout << original[i] << setw(3);
    }

    delete[] original; //delete old array
    original = temporiginal; //point old array to new array
    return temporiginal;
}

void sortFUNC(int *&original, int &SIZE, const int &maxSIZE)
{
    for (int i = 0; i < SIZE; i++)
    {
        int smallest = original[i];
        int smallestINDEX = i;

        for (int m = i; m < SIZE; m++)
        {
            if (original[m] < smallest)
            {
                smallest = original[m];
                smallestINDEX = m;
            }
        }

        swap(original[i], original[smallestINDEX]);
    }

    int *temporiginal = new int[SIZE + 3];

    for (int i = 0; i < SIZE; i++)
    {
        temporiginal[i] = original[i];
        cout << original[i] << setw(3);
    }

    delete[] original;
    original = temporiginal;
}

I want to add a few elements at the end of the array in main, but when I do, the program crashes when I run it. The resize function that I created is supposed to expand the function in main to hold 10 elements. The one in main originally holds 4. The new array is supposed to change that to 10. How do I add three more integers to the array in main without it crashing? Is my resize function wrong? Or is it a problem in my main? The program that is shown right now works as is. But when I add another integer in the array in main, it crashes. Like, if I add a 2 after the 1.
Thanks.
Edit: I was able to add elements at the end of the array in main by adding them in the resize function.
cpp.sh/35mww
Like mentioned earlier, maxSIZE isn't being used. There are more useless stuff as well. I have to clean this up, but I figured out what I was trying to figure out. I don't know how to use structures yet. I know that there are a lot of different ways to write a program. I'm just a beginner.
Thanks, everyone.

A: You need to modify the value of size everytime you call the function rezise other wise even if u call the function resize 3 times u always will have SIZE+3 on your array size.After call resize try
original[4] = 0;
original[5] = 0;
original[6] = 0;

and after that try to do this.
   original[7] = 0;

you should be able to see your mistake


text:
Q: indexOf in google script I'm trying to use findIndex() on a object in google script but it does not work. Here is a exemple:
function myFunction() {
var searchingJohn = "John";
var DATA = {namesList: []};
 DATA.namesList.push({name: "John", otherDataForThisName: []});
 var result = DATA.namesList.findIndex(function (element)
       {return element.name == this;}, searchingJohn);
 return result;
}

this work well in a javascript consol but google script return me a "TypeError: Fonction findIndex not found in object....."

A: You can't.
You are trying to use findIndex() on a object, but findIndex() is for arrays.
From the MDN documentation on findIndex():

The findIndex() method returns the index of the first element in the array that satisfies the provided testing function. Otherwise -1 is returned.

The reason is that objects don't hold key-value pairs in any particular order. For example,
{key1:value1, key2:value2}

and
{key2:value2, key1:value1}

are exactly the same object. So there is no index to be found.

A: This is the example of using findIndex() function for searching string in object in google script. Example:
function myFunction() {
  var DATA = {namesList: []};
  DATA.namesList.push({name: "John", otherDataForThisName: []});
  DATA.namesList.push({name: "Mark", otherDataForThisName: []});
  DATA.namesList.push({name: "Twin", otherDataForThisName: []});
  const searching = "Mark";

  var result = DATA.namesList.findIndex(function (element){
     return element.name.toLowerCase() == searching.toLowerCase();
  });
  return result;
}

findIndex() function is also use for 2 dimensional array.

A: var ss = SpreadsheetApp.getActiveSpreadsheet();
var cellRange = ss.getRange("B5:Q10").getValues();
var someString = "John";

if (cellRange == "John")
{
    //Do this code.
}

This is the only way I can think to pull out the information you're trying to get. IndexOf(); pulls from an index ergo if "John" was in an array it would look like this ["J", "o", "h", "n"] which is why it can't be found that way.
The code above will find it in a range of cells and you can do the whole sheet but the more "Empty" you add to it the slower it will run. Another nested if loop could clean that up for you if you need a massive sheet checked.

A: I have the same issue with many basic javascript functionalities working with gscript, I added the polyfill at the top of my script and it worked with many functionalities.
Paste this code on the top of your script, it will support indexOf.
// This version tries to optimize by only checking for "in" when looking for undefined and
// skipping the definitely fruitless NaN search. Other parts are merely cosmetic conciseness.
// Whether it is actually faster remains to be seen.
if (!Array.prototype.indexOf)
  Array.prototype.indexOf = (function(Object, max, min) {
    "use strict"
    return function indexOf(member, fromIndex) {
      if (this === null || this === undefined)
        throw TypeError("Array.prototype.indexOf called on null or undefined")

      var that = Object(this), Len = that.length >>> 0, i = min(fromIndex | 0, Len)
      if (i < 0) i = max(0, Len + i)
      else if (i >= Len) return -1

      if (member === void 0) {        // undefined
        for (; i !== Len; ++i) if (that[i] === void 0 && i in that) return i
      } else if (member !== member) { // NaN
        return -1 // Since NaN !== NaN, it will never be found. Fast-path it.
      } else                          // all else
        for (; i !== Len; ++i) if (that[i] === member) return i

      return -1 // if the value was not found, then return -1
    }
  })(Object, Math.max, Math.min)

reference https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf#Polyfill


text:
Q: Let $s(t)$ denote the position of a particle at time $t$, and let $v$ and $a$ be the velocity and acceleration $$10+3^t-3t^2 , s(0)=-8 , s(2)=-7$$
Find the function describing the position of the particle
I tried:
$$10+3t-3t^2
=10t+(3/2)t^2-(t^3)
=5t^2+(1/2)t^2-(1/4)t^4$$
I got $c_2=8$
and then $c_1=-11$
and I put $5t^2+(1/2)t^3-(1/4)t^4-11t+8$
but it was incorrect

A: I assume you mean $a(t)=10+3t-3t^2$
Then $$v(t)=10t+\frac{3t^2}{2} - t^3 +c_1$$
$$s(t)=5t^2+\frac{t^3}2 -\frac{t^4}4+c_1 t +c_2$$
By substituting t=0, $c_2=-8$
$s(2)=20+4-4+2c_1-8=-7$
$c_2=\frac{-19}2$


text:
Q: Getting 401 error on using TFS VSTS Rest APIs from the TFS Extension We are migrating from TFS 2015 to TFS 2017. We have developed an extension for TFS 2017 on premises, which calls VSTS Rest APIs to fetch workitems from the TFS Server. The Web API calls were working fine in TFS 2015, but gives 401 Unauthorized error in TFS 2017. Even, I am getting the same error while I try to use TFS_Wit_WebApi.getClient().getWorkItem() method.
I am using below code with authorization token to consume the service.

VSS.getAppToken().then(function(token){
 authHeader = VSS_Auth_Service.authTokenManager.getAuthorizationHeader(token);
 getData(authHeader);
});

function getData(authHeader)
{
 var projectName = 'My Project';
 var webContext = VSS.getWebContext();
 var collectionUrl =  webContext.host.uri + webContext.project.name +
     "_apis/wit/wiql?api-version=1.0";

 var d = { "query": "Select [System.Id] from WorkItems Where [System.WorkItemType] = 'Requirement' and [System.TeamProject] = '" + projectName + "' and [State] <> 'Closed' and [State] <> 'Proposed'" };

      $.ajax({
           type: 'POST',
           url : collectionUrl,
           contentType: 'application/json',
          data: JSON.stringify(d),
  headers: {
   "Authorization":  authHeader
   },
              success: function (data) {
    for (i = 0; i < data.workItems.length; i++) {
                        $.ajax({
                             type: 'GET',
                              url: data.workItems[i].url,
                 contentType: 'application/json',
    headers: {
      "Authorization":  authHeader
    },
                           success: function (data) {
item = data.id + "-" + data.fields["System.Title"];
                             },
                                    error: function (msg, url, line) {
                                        alert(msg);
                                    }

                                });
                            }
                            ;
    }, // Success Function
    error: function (msg, url, line) {
                            alert("Msg:"+ msg);

                        }

                    });
  }

A: Try to use VSS.getAccessToken() method instead.


text:
Q: java jdbc check if value exists before inserting into table I'm working on a Java project and I've hit a wall regarding inserting values into my table. I wanted to have a check before inserting into this table to see if there were any duplicates.
I've tried an executeUpdate with a resultset for executequery afterwards, but I'm getting "java.sql.SQLException: Can not issue data manipulation statements with executeQuery()."
Here is the code I'm working with, thank you in advanced!
    public void registernow(ActionEvent actionEvent) throws IOException, SQLException {
    ConnectionClass registerClass = new ConnectionClass();
    Connection register = registerClass.getConnection();

    try {
        Statement registerStatement = register.createStatement();
        String sql = "INSERT INTO userAuth (username, password) VALUES ('" + txt_username.getText() + "' , '" + txt_password.getText() + "')";
        registerStatement.executeUpdate(sql);

        ResultSet resultSet = registerStatement.executeQuery(sql);

        if (resultSet.next()) {
            FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("register.fxml"));
            Parent fxmlregister = (Parent) fxmlLoader.load();
            Stage stage = new Stage();
            stage.setTitle("COMP228 Project Registration Complete!");
            stage.setScene(new Scene(fxmlregister));
            stage.show();
        } else {
            FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("registerfailed.fxml"));
            Parent fxmlregisterfailed = (Parent) fxmlLoader.load();
            Stage stage = new Stage();
            stage.setTitle("COMP228 Project Registration Failed!");
            stage.setScene(new Scene(fxmlregisterfailed));
            stage.show();
        }

A: As the error and @JBNizet already told you, you are trying to execute the same update statement but with the ExecuteQuery.
So you are trying to execute an update statement with a executeQuery, you should try your second command with a query
sql = "SELECT COUNT(1) FROM yourTable WHERE yourCondition = true";
ResultSet resultSet = registerStatement.executeQuery(sql);

And you sould really take notes of the comment of @JBNizet, is bad to concat strings to create queries.

A: The Answer by rekiem87 is correct, as are the two comments on the Question.
UPSERT
Besides those points, if you wish to update an existing record  or otherwise insert a new one, that behavior is commonly known as an UPSERT (meaning, UPdate or else inSERT) or a "merge".
As I recall, such a feature is not defined in the SQL standard. But many databases have implemented one.
For example, in Postgres, use INSERT ON CONFLICT. See this first look,  this tutorial, this posting, feature description for Postgres 9.5, and this presentation on YouTube.
INSERT INTO user_ ( username_ , password_ )
VALUES ( 'Alice' , 'pw123' )
ON CONFLICT ( username_ )
DO UPDATE SET ( password_ ) = ( 'pw123' )
;

Note that at least in the Postgres implementation, you can choose to do nothing if a row already exists.
INSERT INTO user_ ( username_ , password_ )
VALUES ( 'Alice' , 'pw123' )
ON CONFLICT ( username_ )
DO NOTHING
;

Of course I am ignoring the entire topic of properly storing passwords for users. I am sure this example in the Question is quite contrived and that you would never just write passwords.


text:
Q: How to find total salary of all departments SELECT D_ID, SUM(SALARY)
FROM EMPLOYEE
GROUP BY D_ID.

I want to get total salary of all departments with this query.

A: If department wise sum then your query is proper.
SELECT D_ID, SUM(SALARY)
FROM EMPLOYEE
GROUP BY D_ID

If you want the total sum then can do a sum of salary.
SELECT SUM(SALARY)
FROM EMPLOYEE

If you want to display both a single query then use:
SELECT D_ID,
       SUM(SALARY) OVER (PARTITION BY D_ID) AS [Dept Salary],
       SUM(SALARY) OVER () AS [Total Salary]
FROM EMPLOYEE

A: Ideal query should be as below:
SELECT D.D_ID, SUM(E.SALARY)
FROM DEPARTMENT D
LEFT JOIN EMPLOYEE E ON D.D_ID=E.D_ID
GROUP BY D.D_ID
UNION
SELECT 0 D_ID, SUM(SALARY) SALARY
FROM EMPLOYEE

A: From OP's comments, I think he is asking for this.
mysql> select * from xyz;
+------+------------+---------------+--------+------------+
| roll | name       | location      | salary | department |
+------+------------+---------------+--------+------------+
|    1 | Pranav     | Parasi        | 25000  | A          |
|    2 | Pragya     | Chitwan       | 20000  | A          |
|    3 | Prabhuddha | New Playmouth | 28000  | B          |
|    4 | Smriti     | Kathmandu     | 35000  | B          |
|    5 | Shruti     | Butwal        | 40000  | A          |
+------+------------+---------------+--------+------------+
5 rows in set (0.00 sec)

mysql> select department, sum(salary) from xyz group by department;
+------------+-------------+
| department | sum(salary) |
+------------+-------------+
| A          |       85000 |
| B          |       63000 |
+------------+-------------+
2 rows in set (0.01 sec)

By doing this, we can show the department in one column and the department's salary in another column.


text:
Q: How to upload image to PHP server in Nativescript? I'm trying so long time and there are no effect.
I have a app in Nativescript and server PHP.
I'm trying that
function sendImages(fileUri) {
var request = {
    url: "http://path/to/my/server",
    method: "POST",
    headers: {
        "Content-Type": "application/x-www-form-urlencoded",
        "ENCTYPE":"multipart/form-data",
        "Content-Disposition": "form-data",
        "File-Name": fileUri,
    },
    description: "{uploading:"+fileUri+"}"
};
var task = session.uploadFile(fileUri, request);
return task;
}

or
function sendImages(fileUri){
    var locationRequest = 'http://path/to/my/server';
    var request = new XMLHttpRequest();
    var fs = require("file-system");
    var path = fs.path.normalize(fileUri);
    var file = fs.File.fromPath(path);
    file.readText().then(function(content){
        request.open("POST",locationRequest,true);
        request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

        request.onload = function(data){
            console.log('success');
        };
        request.onerror = function(data){
            console.log(this.responseText);
            console.log(data);
        };

        request.send('fileUri='+content);
    }, function(error){
        alert('error: '+error);
    });
}

and I have somewhere about result in $_POST and $_REQUEST array:
array(11) {
 ["яШяб"]=>
  string(0) ""
  ["'()*456789:CDEFGHIJSTUVWXYZcdefghijstuvwxyzѓ"…†‡€‰Љ'""•–—™љўЈ¤Ґ¦§Ё©ЄІіґµ¶·ё№єВГДЕЖЗИЙКТУФХЦЧШЩЪбвгдежзийкстуфхцчшщъяД"]=>
  string(0) ""
  ["'()*56789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz'ѓ"…†‡€‰Љ'""•–—™љўЈ¤Ґ¦§Ё©ЄІіґµ¶·ё№єВГДЕЖЗИЙКТУФХЦЧШЩЪвгдежзийктуфхцчшщъяЪ"]=>
  string(0) ""
  ["бПyUљVчЎI4е~ьЦґ№\Zoд
_лЫЏя"]=>
  string(0) ""
  ["гJMКK^јїv*Ri?›hўЉgдБEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEP_J~О±‡‡х
GсgгЭпЩtЖ·ыMѕущдаџ6y8*¤rq'OjтЩПАцџю8x{ВЊBKiпјЛЁЫЈЕґ®§ШЄшЧµБDю)ji«iџt«¦ЉНmыRHО¬Y–$oe_2КzЁВwШэsГЬ›'Бd8о,О(*ф°Ь°§MЫ–udЧД›ХGљ-¦¤њdЭ›ЌџAuыFюВЮи~шom}gk\iю…•±юЬЕYыуО}jн‡Ѓbя"]=>
  string(169) "hеHкҐгЦ®йж8zр®ЙРtТ'ЉkHоУKH№sҐї ±їсЇаПЉѕшЪ_ш—lЁWН±ѕ‰HЋкH3Рс'ЅЏЁБ;їІOВk?‹я lґmfЬK¦iс5юЈt'4 ,gЩќђэТХпЯµН–•с‹цOУ>0ЫЪЄ\ЩЕi9("нЋXіиФџъж ђя 'iЕl|Mв№9lmU}ҐдЭъ…э)"
  ["Ъ;kр6CCЕ,і'|Ш,Z§€''m{7Н/fщµj\–WЧ–IJн6ПЫЧгЦЁъпь(П   ЯµЅ•¤(ъСЃ¶™¤a№`8юR¤Ћ"°оЧМµШ~Р7—_ь]-щ>`свьЗ8U™ХGэтqфв¬Џ€с77ЗgsЏћ*Wцu'J__Fе(Е$Ы¶ЬОЦNR"vВѕ'эѓѕ:jѕсдхЛч"HЦK'І-nЂ$mфWБR?јTъззЪи~НymсkГ3йьОћ І0Њхo"]=>
  string(317) "p)џ5ГщЦ/‡sЄ–ыф¤¤µjйomydЇwM®§{ыk|(ІшaсћkФE§k°эєЮ4X¤,DЁ=б» p;WђЧХ?рSЎай'Џ0ќAIцgя щZ"v>ПЕьв6>ќтЕК3·ч§N3"щКMьфР(ўЉgжЎEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEP¤юИ:х—‡?i/ЯЯИ9.¤¶З<РЙгОЈс®лю
'б
KLші§шИДЖПTТ–$—°–"
  ["`ЛнтІДъWПцЧwЭЪLСЛ‡ЋDl2°9Ды'б‡Ж/"_µзГTшUс‰ ѓ]UPСЙ_‰§•AqlЗшъе"]=>
  string(346) "ИБ^Ёэ‡ГмГ.ОxgБшЪсўс5(NzAUЌЇJъsЁЕGOжJтqЊѕ3§G"H°Г;і ЄЈ$"Р_Jш—ю   µвшх7я ";в6ќ5™l§ц"2G"ЏC°0cпЗРWgр§цFш]ы:°ш©сѓЖЦ··y[Йp' [W!ЂbLІqтфзўдEР°ЮсЗЧy1Р…<[s*"Ь#Э№ЩKљЦWIЁфжqWiЯ¬ЗВїШ6ЧАъбЯKa§ЩyDя ЛЗ'ИїЂI?*сџШKв§Ѓю:Е¤кs€нµыF°Зf,#х,»»Х/ЪГцЋЏ,ЉЛAY!рю"МєzH0ЧxiШvИ (<Ѓћ"'^QУ[L—тґrFБ'С€*AИ Ћ†"ґ0гЋ/АSг<|ЌуQЛЎF•)6Ъ©м[•Э№]›|®ПЮK™4Ґeнї·oВќCБ_"
  ["сЕµ«fx€    Ј•WеK…P%B}Nып>†јBѕ»ш9ыIь,эЎ|я"]=>
  string(0) ""
  ["WAШy'†хЪґ"¶Њъ$аXшЃЉџp"ЈUVjUh9Ж5)T•Ь›SiZRMьZ¶щ9ЎЄщ'ЅЏц!шSЁ|@шСiвimЏцg‡o_f_БgЙ@Ѕјnъ!ц®лБїрMЅyп'_€"¶RГЈВТ;Ћа<ЃB}v·Тєя"]=>
  string(0) ""
  ["ќЅе¬љM$"sЏ–БA|kвЏЊЮУо'x~ЗЛ©Иќо?ѓон^
Sj:ЌюЇЁП«j—rOss3Kq<–'Ш'МOrI"]=>
  string(0) ""
  ["Ў¦•'щqn_в<NkV<®¬®—h¤ЈЯVўў›конЁQEПњ
(ўЂ
(ўЂ
(ўЂ
(ўЂ
(ўЂ
(ўЂ
(ўЂ
(ўЂ
(ўЂ
(ўЂ
(ўЂ
(ўЂ
(ўЂ
(ўЂ
(ўЂ
(ўЂ
(ўЂ
(ўЂ
(ўЂ
(ўЂ
(ўЂ
(ўЂ
(ўЂ
(ўЂ
(ўЂ
(ўЂ
(ўЂ
(ўЂ
(ўЂ
(ўЂ
(ўЂ
(ўЂ
(ўЂ
_д}(ўЂ:#г§ЖЅПы?GшЇЇБ"]=>
  string(0) ""
}

if I change the "Content-Type" value to "application/octet-stream" or "multipart/form-data" or another, I have empty $_POST, $_GET, $_FILES and $_REQUESTarrays on my server.
All the same, how I can to upload images on my server PHP?

A: I resolved the upload converting the image to base64, like string. You have to take care in the replace chars for encoding, but it works.


text:
Q: How do I protect my backend from receiving requests that do not come from the frontend? I'm using Strapi API for my CMS/backend which has a path localhost:1337/products.
I have a Vue frontend that makes a graphql POST to the backend whenever the user accesses localhost:3000/products and uses the information to render the products page and, if the user is logged in, the prices of said products.
In order for this method to work I must grant access to the /products path to the user, which means they can also directly access localhost:1337/products.
How do I restrict access to the backend while still allowing the frontend to make requests to it?
This is how my frontend looks:
<template>

        <router-link :to="{ name: 'product-id', params: { id: product.id }}" tag="a">

{{ product.name }}

        </router-link>

{{ product.price.toFixed(2) }}

           Sign in to see price!

</template>

A: I assume users do not actually access localhost:3000 from their browser but use the IP address or hostname of your server. If so, then either:

*

*Configure the CMS to accept only connections from within the server. Often a service accepts connections on all network interfaces (all IP addresses) by default but you can normally configure it to listen only on the localhost interface (IP address 127.0.0.1).

*Configure the firewall on the server to only allow access on port 3000.

A: You really can't. Any API calls your client makes to your backend can be made by any computer on the Internet if they have the endpoint, credentials, etc.. Backends are agnostic to the source making the call. Even though the backend can determine the origin of the call, any hacker can still fake it to look like your own client app.


text:
Q: Meteor download binaries from server? Using Meteor and Iron Router, is there a Meteor module that makes it easy to serve up binary files for download on the local filesystem, outside of the Meteor app container?
So if the Meteor app is in /home/meteor/app is it possible to provide download links to /data/files within Meteor?
I'm guessing the answer is No since it appears Meteor isolates itself within its container, but figured I'd ask.
I don't want to put the files in Meteor's /public because they need to be in a network folder, outside of the Meteor app itself.

A: It doesn't directly answer the question, but I did it like this.  There might be a better iron router way.
WebApp.connectHandlers.use('/filename.txt', function(req, res, next) {
  //the filename in the url and the filename on disk don't have to be
  //the same but I made them the same here

  var fs = Npm.require('fs');

  var data = fs.readFileSync("/path/to/filename.txt");

  //if it's in the project's private directory,
  //or if you are working in a package and you added filename.txt with addAssets
  //you can probably just use
  //var data = Assets.getBinary("filename.txt");

  res.write(data);
  res.end();

});


text:
Q: Map whole list in Scala I want to be able to do smth like this
List(1, 2, 3).someFunc?(list => List(list, list)) // List(List(1,2,3), List(1,2,3))

The general idea is I want smth like map, but acting not on the elements of the list, but on the whole list itself. Alternative is to write smth like this:
val list = List(1, 2, 3)
val res = List(list, list)

But I'd like some function that could be used in chains. Is there a function like this?
EDIT:
Ideally I'd like to chain map over elements and this "kind of map" for the whole list interchangably, e.g.
 List(1, 2, 3).map(_ + 1).someFunc?(list => List(list, list))

A: You can easily define your own operator:
implicit class RichList[T](l: List[T]){
  def applyFun[U](f: List[T] => U): U = f(l)
}

You can even add some restriction on the output type of the function that can be applied, eg if you want to make sure that the output is still a list (just replace U with List[U] as the output of f and the output of applyFun[U]).

A: I think an option suits your needs well:
Option(List(1, 2, 3)).map(lst => List(lst, lst))

You may also want to consider streams:
Stream.continually(List(1, 2, 3)).take(2).toList

You can then map over this list of lists however you want.

A: I think you can use a pattern matching here:
List(1, 2, 3) match { case x => List(x, x) }
// res25: List[List[Int]] = List(List(1, 2, 3), List(1, 2, 3))


text:
Q: how to call angularjs function which is appended in div $scope.showtbleoption =  function(id)
{
    console.log(id);
    $("#showoption").empty();
    $("#showoption").append('<button class="btn btn-info" ng-click="editrc(id)">');
};

how to call editrc() function in angularjs controller ?

A: Appending raw DOM with jQuery would make angular directive compile. You have to use $compile service, by which you will be $compile that DOM first & then inject that DOM in DOM tree. $compile is API function(returns function) which ask for DOM, then you can again call that function by passing $scope to evaluate against particular context. $compile API method will take care of compiling all directives on DOM & update bindings.
In below case id value wouldn't be available inside $scope directly, you could either store it in a scope variable or pass it by string concatenation.
var compiledDom=$compile('<button class="btn btn-info" ng-click="editrc('+id+')">')($scope);
$("#showoption").append(compiledDom);

A: Instead of appending using jQuery, use $compile service to bind it to dom. Like this:
$scope.domEle = $compile('<button class="btn btn-info" ng-click="editrc(id)">')

and in HTML call like this:
{{ domeEle }}

And in controller define editrc function like this:
$scope.editrc = function(val){

}

A: You can use the ng-bind-html directive to bind the html's to the template dynamically . You will however have to compile the html using $compile by doing $compile(<html>) . Any expressions mentioned in the compiled html could call the definitions you provide in the controller .