text:
Q: javascript code highlight with new lines and indentation I'm writing a little single page app (using knockout.js :-)) whereby i have a series of examples of javascript code. this code is wrapped in a function and i call toString on the function to show the source code in the browser.
on the whole everything works great! but because of the nature of the examples (as learning exercises), they contain some code which might normally be considered redundant. for example, this code is an example which demonstrates false-y values in javascript:
var example = function() {
    if("" || 0 || null || undefined || NaN) {
     console.log("i'll never be logged");
    }
    else {
     console.log("i'll always be logged");
    }
};

in firefox, if i call example.toString() the string returned does not contain 0, null or "" - so my example isn't accurately portrayed! in IE however, the aforementioned values are contained in the result of the toString() call, but the string is just a single line - no indentation or anything!
So what i was wondering is
1. more likely solution: anybody knows a
    JS-implemented code highlighter that will handle the
    formatting/indentation for me, if given a long, single-line string
    of javascript code. Or a highlighter that allows simple extensibility to deliver this kind of feature

*

*less likely solution: if anybody knows a way to get accurate results in FF, or properly

any help will be much appreciated, it's really frustrating not getting the results i want to make the app perfect :)
EDIT: seems i was being dense, IE does format correctly, it's just with the basic examples i was working with when building the app i declared the functions as a single line, so the formatting was carried over exactly! So for once in the history of the web, IE does exactly what you expect with no issues :) Would be nice if someone could offer a reason for firefox dropping certain parts of the code from the string representation

A: Firstly, script engines are allowed to optimise code. If the compiler sees branches that will never execute, it may trim them.
Secondly, Function.prototype.toString is implementation dependent:
ECMA–262 15.3.4.2 Function.prototype.toString ( )

An implementation-dependent representation of the function is
  returned. This representation has the syntax of a FunctionDeclaration.
  Note in particular that the use and placement of white space, line
  terminators, and semicolons within the representation String is
  implementation-dependent.

If you want the script content to be reasonably formatted, get a reference to the script element and use its textContent or innerText (whichever is supported).
But if you want properly formatted code, search for "javascript pretty print" or do it yourself in the HTML.


text:
Q: Radio button doesn't set as checked I making some test - http://magora-systems-test.esy.es/ , and one of the task make Radio Buttons stilization by JavaScript(jQuery). I remaking construktion again and again but always one problem: JS successfully set input radio button attribute as checked="checked" by clicking the stylized clone , but it doesn't set as chosen indeed, and required attribute talkink the same. I doen't understand WHY?
HTML:
<fieldset class="userAge">

            Возраст:

            <input type="radio" name="userAge" id="seventeen" title="Выберите если вы младше 17" required>
            17 и младше
            <input type="radio" name="userAge" id="eighteen" title="Выберите если вы старше 18" required>
            18 и старше

</fieldset>

JS:
;(function($) {
    // Расширяем набор элементов jQuery новым плагином.
    $.fn.sexyElement = function() {

        // Запуск для всех инициализаций на странице.
        $(this).each(function() {
            var element = $(this);

            // RADIO
            else if (element.is(':radio')) {

                // Для всех существующих радио кнопок.
                element.each(function() {

                        // Создание и обработка радио кнопок.
                        var createRadio = function(){
                            var sexyRadio = '
\

\

\

';
                            element.before(sexyRadio);
                        }

                        // Запуск функции.
                        createRadio();
                });

                // Определяем основные элементы.
                var commonParent = element.parents().eq(0),
                    buttons = commonParent.find(':radio');

                // Обработка щелчка мыши.
                $('.radio').click(function() {
                    $(this).addClass('checked').siblings().removeClass('checked');
                    buttons.attr('checked', false);
                    $(this).next(':radio').attr('checked', true);
                    buttons.change();
                });
            }
            // END RADIO

            // В противном случае.
            else {
                alert('Пожайлуста убедитесь, что выбранный вами элемент является select или radio');
                return false;
            }
        });
    }
})(jQuery);

Launch plugin:
$(document).ready(function() {
    $(':radio').sexyElement();
});

PS: Sorry some titles on Russian language. And label JS code do not written yet.

A: I do not really know why but this bug was SOLVED by puting input radio button to his label.
Before:
<fieldset class="userAge">

            Возраст:

            <input type="radio" name="userAge" id="seventeen" title="Выберите если вы младше 17" required>
            17 и младше
            <input type="radio" name="userAge" id="eighteen" title="Выберите если вы старше 18" required>
            18 и старше

</fieldset>

After:
<fieldset class="userAge">

        Возраст:

            <input type="radio" name="userAge" id="seventeen" title="Выберите если вы младше 17" required>
            17 и младше

            <input type="radio" name="userAge" id="eighteen" title="Выберите если вы старше 18" required>
            18 и старше

</fieldset>

Anyway any ideas why?

redpajama_set_name: RedPajamaStackExchange


text:
Q: ActiveRecord - how to do includes after the query was executed? In a scenario with 1->N->N assocations. For example: Post->Comments->Votes (votes will be list of names of people who voted on the comment). To display a page the query with includes might look like:
@post = Post.where(:id => 100).includes({:comments => :votes}).first

I am starting to add caching support. Which means if the comments partial is already cached I will not need to run include the comments/votes all the time. So I wonder if there is a way to make the code appear like:
# controller
@post = Post.find(100)

# view
<% cache('comments', @post.last_comment_time do %>
    <% @post.includes({:comments => :votes}).comments.each do |comment| # ???? %>
<% end %>

Running the "post-query" includes, will "fill in" the associations. So @post.comments will be populated and each comment will include all the votes. Is there a way to achieve this?
P.S. I am aware the view is not the best place to run the query, this is just an example.

A: in latest releases of rails, all the finder-methods return a proxy object, that will only trigger a database-call once you send it some iterator-method like all or first in your case. this is why you can chain all the calls like Post.where.order.sort.bla.
it's not possible though to load the post model and use an includes call later. includes works by using a join call on the relations that get loaded with the model instance, so that you have just one database-call instead of one for each relation.
executing active_record code in your view is also a bad practice. the data-retrieval is the responsibility of the controller, not the view.

A: This is a fairly old question but this can be done now like this
# controller
@post = Post.find(100)

# view
<% cache('comments', @post.last_comment_time do %>
    <% ActiveRecord::Associations::Preloader.new.preload @post, comments: :votes # this will trigger one query %>
    <% @post.comments.each do |comment| # this will not trigger any additional queries %>
<% end %>

Not the cleanest way but it does the job


text:
Q: Prove that the sequence has a limit I got a problem in my homework I'm having troubles to solve.
Let ${a_n}$ be a sequence such that for every n $\in \mathbb N$
$|a_2 − a_1|+|a_3 − a_2|+...+|a_n− a_{n-1}| < c$
$c\in \mathbb R$

*

*prove that ${a_n}$ has a limit.

I took ${b_n}$ to be $|a_2 − a_1|+|a_3 − a_2|+...+|a_n− a_{n-1}|$
$0\le{b_n}\lt c$ and ${b_ {n-1}- b_n}\ge 0$, therefore monotone and bounded and therefore is a cauchy sequence.
So for every $\epsilon \gt 0$ and $P \in \mathbb N$  ,there is such $N \in \mathbb N$ that for every $n>N$,
$|{b_{n+p}- b_n}|< \epsilon$
But I'm stuck at this stage.
I would appreciate if anyone could help me. Thanks in advance.

A: Since $\sum_{n=1}^N|a_n-a_{n-1}|<c$ for all $N\in \Bbb N$ by hypothesis, the series is convergent if we take the limit as $N\to\infty$. In particular, for any $\varepsilon>0$, we can take $J$ large enough so that $\sum_{n=J}^\infty|a_n-a_{n-1}|<\varepsilon$. Thus, for any $j,k>J$, we have
$$
|a_j-a_k|\leq|a_{j+1}-a_j|+\cdots+|a_k-a_{k-1}|\leq\sum_{n=J}^\infty |a_n-a_{n-1}|<\varepsilon.
$$
Hence, the sequence $\{a_n\}_{n=1}^\infty$ is a Cauchy sequence and is therefore convergent.

A: Rephrasing:
$ S_n := \sum_{k=2}^{n} |a_k-a_{k-1}|;$
$S_n$ bounded above, increasing, hence convergent.
$\rightarrow:$
$S_n$ is a Cauchy sequence:
For $\epsilon \gt 0$ there is a $n_0$ such that for $m\ge n \gt  n_0:$
$|S_m-S_{n-1}| \lt \epsilon$, i. e.
$\sum_{k=n}^{m} |a_k -a_{k-1}| \lt \epsilon$.
We have:
$ |a_{m} - a_{n-1}| =$
$ |a_{m} - a_{m-1} + a_{m-1} -a_{m-2} +a_{m-2} $
$....+a_n -a_{n-1}| \le $
$|a_{m} -a_{m-1}| +...|a_{n} - a_{n-1}| =$
$|S_m-S_{n-1}|  \lt \epsilon.$
Hence $a_n$ is Cauchy , hence convergent.


text:
Q: What better way to write a HashMap inserting? Here i have simple class Doctor
public class Doctor {
    private int id;
    private String surname;
    private String name;
    private String speciality;

    //constructor
    //getters
    //setters

Here is a list of doctors
List<Doctor> doctorList = new ArrayList<>();
        doctorList.add(new Doctor(1, "Smith", "John", "laryngologist"));
        doctorList.add(new Doctor(2, "Duncan", "Sylvester", "dentist "));
        doctorList.add(new Doctor(3, "Reid", "Otis", "dentist "));
        doctorList.add(new Doctor(4, "Jenkins", "Ford", "oculist "));

Map<String, Integer> specializationAmountOfDoctors = new HashMap<>(); // key: specialization , value: amount of doctors

I want to count which specialization is the most using HashMap.
How can I write better way this code ? :
(Maybe using Stream ?)
for (Doctor d : doctorList) {
            if(!specializationAmountOfDoctors.containsKey(d.getSpeciality())){
                specializationAmountOfDoctors.put(d.getSpeciality(), 1);
            } else {
                int tmp = specializationAmountOfDoctors.get(d.getSpeciality());
                specializationAmountOfDoctors.put(d.getSpeciality(), tmp+1);
            }
        }

To get Max from Map i have using Stream :
Map.Entry<String, Integer> specializationMax = specializationAmountOfDoctors.entrySet().stream().max(Comparator.comparingInt(Map.Entry::getValue)).get();
Thanks

A: Typically, I would utilise an enumeration to represent the possible values of speciality:-
public enum Speciality {
    LARYNGOLOGIST, DENTIST, OCULIST
}

You can use the Streams API to perform a count of the number of objects that match a certain criteria:-
final Speciality expected = Speciality.DENTIST;
final long count = doctorList.stream()
                       .filter(d -> d.getSpeciality().equals(expected)).count();

Following the approach you have made above, you could populate the map like so:-
final Map<Speciality, Long> specialityMap = new HashMap<>();
Arrays.stream(Speciality.values()).forEach(s -> {
    final long count = doctorList.stream()
                           .filter(d -> d.getSpeciality().equals(expected)).count();
    specialityMap.put(s, count);
});

But a better approach would be to use the Collectors.groupingBy functionality:-
final Map<String, List<Doctor>> grouped = doctorList.stream()
     .collect(Collectors.groupingBy(Doctor::getSpeciality));

Though this returns a slightly different output to what you were expecting so you will need to handle that accordingly. @Eritrean came up with a great suggestion to use a second Collector like so:-
Map<String, Long> grouped = doctorList.stream()
        .collect(Collectors.groupingBy(Doctor::getSpeciality, Collectors.counting()));

Finally, you can find the maximum value in a similar manner to how you have described above. But please do take care to handle the event that two (or more) specialities have the same count.

A: Yes, it may be better to collect into a map using Collectors.groupingBy and Collectors.counting:
Map.Entry<String, Long> specializationMax = doctorList
    .stream()
    .collect(Collectors.groupingBy(
        Doctor::getSpeciality, Collectors.counting()
    ))
    .entrySet()
    .stream()
    .max(Comparator.comparingLong(Map.Entry::getValue))
    .get();

Or Collectors::collectingAndThen may be used with Collectors.toMap and a finisher function to convert the map into max entry:
Map.Entry<String, Integer> specializationMax = doctorList
    .stream()
    .collect(Collectors.collectingAndThen(
        Collectors.toMap(Doctor::getSpeciality, x -> 1, Integer::sum),
        (map) -> map.entrySet()
            .stream()
            .max(Comparator.comparingInt(Map.Entry::getValue))
            .get()
    )
);


text:
Q: Express using acuityscheduling API I have tried a bunch of things with no success. Hope you guys can spare some knowledge.
I am using acuityscheduling's API to retreive appointments. their documentation says to do something like this:
on my express server:
  // https://acuityscheduling.com/api/v1/appointments?email=
  console.log(req.params);
  let email = req.params.email
  let apt;
  // res.send("appointments IS WORKING!!!")
  apt = acuity.request('/appointments?email='+email, function (err, res, appointments) {
    if (err) return console.error(err);
    apt = appointments;
    console.log(appointments)
  });
  console.log(apt);
  res.send(apt);
})

when i do a request using insomnia:
http://localhost:3000/appointments/email@gmail.com
  "uri": {
    "protocol": "https:",
    "slashes": true,
    "auth": null,
    "host": "acuityscheduling.com",
    "port": 443,
    "hostname": "acuityscheduling.com",
    "hash": null,
    "search": "?email=email@gmail.com",
    "query": "email=email@gmail.com",
    "pathname": "/api/v1/appointments",
    "path": "/api/v1/appointments?email=lornebatman@gmail.com",
    "href": "https://acuityscheduling.com/api/v1/appointments?email=lornebatman@gmail.com"
  },
  "method": "GET",
  "headers": {
    "User-Agent": "AcuityScheduling-js/0.1.9",
    "host": "acuityscheduling.com",
    "authorization": "Basic MTQ1OTg2ODM6ZDdlZTA0YjljMjNjNTMwZTVmOGEzNzYzZmNkZDdmZWQ=",
    "accept": "application/json"
  }
}

but the output on my console returns the right data that I need.
Why would this be happening?
What am I missing to be able to retrieve the data from my frontend?
Thank you so much.

A: Ended up changing things a bit and this worked.
  // https://acuityscheduling.com/api/v1/appointments?email=
  console.log(req.params);
  let email = req.params.email
  let apt;
  // res.send("appointments IS WORKING!!!")
  apt = acuity.request('/appointments?email='+email, function (err, response, appointments) {
    if (err) return console.error(err);
    apt = appointments;
    console.log(appointments)
    res.send(appointments);
  });
  console.log(apt);
  // res.send(apt);
})


text:
Q: indexOf returns -1 searchInCollection I'm so very sorry if this has been asked before. I'm new to this. Im ready for downvotes, just please help :/
My Code:
public void searchInCollection() {
        query = "ASD123";
        int indexOfQuery = carData.indexOf(query);
        System.out.println(indexOfQuery);
        carData.forEach(System.out::println);
    }

Output is:
run:
-1
Bil: Ford ASD123
Årsmodell: 1900
Ägare: Asd Asd
Mätarställning: 1937
Inlämnad: Thu Jan 02
Beräknad tid att laga: 10 arbetsdagar
Beräknad kostnad för lagning: 6613 kronor
Bil: Volvo QWE123
Årsmodell: 1950
Ägare: David Ahlstrlm
Mätarställning: 26839
Inlämnad: Thu Jan 02
Beräknad tid att laga: 13 arbetsdagar
Beräknad kostnad för lagning: 10435 kronor
Bil: Motorolo ZXC123
Årsmodell: 2000
Ägare: Zxc Zxc
Mätarställning: 37706
Inlämnad: Thu Jan 02
Beräknad tid att laga: 19 arbetsdagar
Beräknad kostnad för lagning: 9931 kronor
BUILD STOPPED (total time: 8 seconds)

As you can see the list is there with the data and the searchquery should return line 1. But it doesn't.  I'm losing my mind here...
To clarify: I want to search for the element (string) "ASD123" in the list and find the indexposition.

A: If carData was a string, then you would get the index. However, it is a list of string, so when you say carData.indexOf("ASD123"), you are searching for a string in the list which equates to ASD123 exactly, not a string in the list which contains the search string.
One way to get the index could be to iterate over the list and then do indexOf on each item in the list:
int index = 0;
boolean resultFound = false;
for (String car : carData) {
    if (car.indexOf(query) != -1) {
        resultFound = true;
        break;
    }
    index++;
}
if (resultFound) {
    ...
}

You need the resultFound flag because you want to make sure you didn't loop over the whole list without finding a match.

A: since carData is list of string , then the method indexOf will return the index if the full string match not part of it.
I suggest you define your own find method
private int findFirstContain(String str , List<String> list){
    for(int i=0;i<str.length;i++){
        if(list.get(i).contains(str)) return i;
    }
    return -1
}

and then use it in searchInCollection method
public void searchInCollection() {
        query = "ASD123";
        int indexOfQuery = findFirstContain(query , carData);
        System.out.println(indexOfQuery);
        carData.forEach(System.out::println);
    }

A: indexOf will not find the query you give because your first element is Bil: Ford ASD123 and not ASD123. They should be an exact match. You can try to loop through the list and see if any String element in it contains 'ASD123' in it
int index = 0;
    for(String str: carData) {
        if(str.contains(query)) { break; }
           index++;
}

A: Your list doesn't contains an item that is equals to your String "ASD123"
the first Item in your List is "Bil: Ford ASD123", and "Bil: Ford ASD123".equals("ASD123") returns false
indexOf methode is comparing using equals methode
 /**
   * Returns the lowest index at which element appears in this List, or
   * -1 if it does not appear.
   *
   * @param e the element whose inclusion in the List is being tested
   * @return the index where e was found
   */
   public int indexOf(Object e)
   {
     for (int i = 0; i < size; i++)
       if (equals(e, data[i]))
         return i;
     return -1;
 }

Source code


text:
Q: 2FA with Ubuntu 18.04 I'm using 2FA on Ubuntu 18.04.4 LTS with Google Authenticator. I added auth required pam_google_authenticator.so nullok to /etc/pam.d/common-session and correctly set up Google Authenticator.
The 2FA works great when getting back to a session after sleep mode. However when I shut my computer down and boot again, the 2FA doesn't prompt and I'm only asked to enter my master password. Do you have any idea why?

A: Problem was related to the encryption of home directory. As stated in Google Authenticator libpam

If your system encrypts home directories until after your users
  entered their password, you either have to re-arrange the entries in
  the PAM configuration file to decrypt the home directory prior to
  asking for the OTP code, or you have to store the secret file in a
  non-standard location

. If you're the only user of your laptop, below are the steps to follow to boot Ubuntu 18.04 with 2FA:

*

*create an unencrypted directory, let's call it ga:

sudo mkdir -m 700 /home/ga
sudo chown yourname:yourgroup /home/ga

*

*when you run and configure Google Authenticator (i.e., command google-authenticator in a terminal), it creates a configuration file at the root directory. Copy this file to your unencrypted directory:

sudo cp ~/.google_authenticator /home/ga/.

*

*finally add this line at the end of the file /etc/pam.d/gdm-password:

auth required pam_google_authenticator.so secret=/home/ga/.google_authenticator

Boot your computer and you should be good to go.
Sources
https://github.com/google/google-authenticator-libpam#encrypted-home-directories
Google Authenticator for Desktop (lightdm or gdm plugin)
https://wiki.archlinux.org/index.php/Google_Authenticator#Desktop_logins
Possible to Create Unencrypted Folder Outside Ecryptfs Home?


text:
Q: Monoid how to use mempty I have following datatype, that is implemented in Monoid typeclass:
data Optinal a =
    Nada
  | Only a
  deriving (Eq, Show)

instance Monoid a => Monoid (Optinal a) where
  mempty = Nada
  mappend Nada (Only a) = Only a
  mappend (Only a) Nada = Only a
  mappend Nada Nada = Nada
  mappend (Only a) (Only b) = Only (mappend a b)

My question is, how to use mempty function?

A: The mempty in a Monoid defines the "unit" element. One particular scenario in which it might be used is if we had a function that aggregates over a list of Monoids:
aggregate :: (Monoid a) => [a] -> a
aggregate [] = mempty
aggregate (x:xs) = x `mappend` aggregate xs

Remember that Monoids are an abstraction over common forms of computation. When you write general functions for Monoids, that's where mempty may show up.


text:
Q: L4978 voltage regulator feedback resistor values I am trying to use a L4978 to create a 6 V regulator. I, however, am unable to find how they calculate the resistor divider in Figure 4 to get a given output voltage. Does anyone know how they are calculating this?

A: The chip will be happy when the feedback voltage on pin 8 is 3.3 V. So for a 3.3 V output set the upper resistor, R3, to zero. Any other voltage can be obtained by simple voltage divider using R3 and R4.
The sample circuit uses a constant 4.7k for R4 and at 3.3 V there will be 0.7 mA flowing through it. For 6 V you will want the output 2.7 V higher than 3.3 V and since we know the current we can calculate R3.
R4's value will be mid-range. Too low and it will waste current. Too high and it may be loaded by pin 8 or susceptible to noise.

We can work out the formula. The relationship between \$ V_F \$, the feedback voltage on pin 8, and \$ V_O \$, the output voltage is given by
$$ \frac {V_F}{V_O} = \frac {R4}{R3+R4} $$
Rearranging we get
$$ V_O R4 = V_F(R3+R4) $$
$$ (V_O - V_F) R4 = V_F R3 $$
$$ R3 = \frac {(V_O - V_F) R4}{V_F} $$
Sample test for 12 V out:
$$ R3 = \frac {(12 - 3.3) 4k7}{3.3} = \frac {40k9}{3.3} = 12k4 $$
The datasheet recommends the nearest E12 value of 12 kΩ so our maths looks right.
We could work out the error with this rounding from
$$ V_O = \frac {R3 + R4}{R4}V_F = \frac {12k + 4k7}{4k7} 3.3 = 11.7 \, \mathrm V$$
You can keep on going with this by examining the conditions with max and min combinations of resistor tolerance and \$ V_F \$ for the chip but most of us would be happy enough with 11.7 V.


text:
Q: Lua program not working I decided to try and recreate a sorting algorithm in Lua just for fun. It works for some values, but in larger values that have repeating numbers, it doesn't work properly. I was wondering why this is happening.
Here's the code (I added comments to make it easier to see):
numbers = "9876554321" -- Number to sort, I will refer to this as the "string to sort"
length = tonumber(string.len(numbers)) -- The length of the string to sort
changes = 1 -- The next few lines are just variables
totalchanges = 0
iterations = 0
newNumbers = numbers
print("")
while changes ~= 0 do -- This repeats until the number of changes equals zero
  iterations = iterations + 1 -- This variable doesn't do anything for the code, it's only used at the end
  changes = 0
  print(newNumbers)
  x = 1 -- More variables
  y = 0
  z = 0
  w = false
  while x < length do -- While the x variable is less than the length of the string to sort, repeat this code
    y = tonumber(string.sub(newNumbers, x, x)) -- The 'x'th place in the string
    z = tonumber(string.sub(newNumbers, x + 1, x + 1)) -- The 'x + 1'th place in the string
    w = y > z -- If the 'x'th place is larger than the 'x + 1'th place, this value is set to true
    print(y) -- Print statements
    print(z)
    print(w)
    if w == true then -- Checks if y > z is true
      newNumbers = string.gsub(newNumbers, tostring(z), tostring(y), 1)  -- The next two lines swap around the numbers if y > z
      newNumbers = string.gsub(newNumbers, tostring(y), tostring(z), 1)
      changes = changes + 1 -- Increases the number of changes
    end
    print("")
    x = x + 1 -- Increases the x value, this lets the code know where to check in the string
  end
  totalchanges = totalchanges + changes -- This variable is like the iterations variable, it's only used for the last print statements
end
print("") -- These last print statements are just showing information about the sort
print("Sorting complete!")
print("Original string: " .. tostring(numbers))
print("Sorted string: " .. tostring(newNumbers))
print("Total changes made: " .. tostring(totalchanges))
print("Total iterations used: " .. tostring(iterations))

Does anyone know what the problem is?

A: newNumbers = string.gsub(newNumbers, tostring(z), tostring(y), 1)
newNumbers = string.gsub(newNumbers, tostring(y), tostring(z), 1)

These two lines are just wrong on so many levels.
Let's start with only one of them: Assuming z == 5, and in your example code there's 2 5s, every 5 in the sequence would get turned into y, not only the one you are trying to swap.
Next is the even more obvious problem that you first turn all zs into ys, and then all ys into zs. The problem here is that you also turn into zs the ys that you just turned into ys, so basically
aaaayzaa -> aaaayyaa -> aaaazzaa

and not
aaaayzaa -> aaaazyaa

Even if that wasn't the case though, don't use strings for that kind of stuff. Strings in Lua are a bit different1 than usual. You'd be much better off turning the string into a sequence, doing stuff with it, and finally concatenating it back into a string.
Also keep in mind that you can directly compare two characters, and Lua will compare them lexicographically, so no need to tostring() everything. "2" < "9" works just as 2 < 9 would.

1 Lua Performance Tips by Roberto Ierusalimschy, page 22 "About Strings"


text:
Q: Module not found: Can't resolve '@material/core/Grid' I cloned a repository that uses MUI and the following components are already imported when I cloned (they work)
import Card from '@mui/material/Card'
import CardActions from '@mui/material/CardActions'
import CardContent from '@mui/material/CardContent'
import CardMedia from '@mui/material/CardMedia'
import Typography from '@mui/material/Typography'

then I tried to import Grid from '@material/core/Grid' but got the error Module not found: Can't resolve '@material/core/Grid' even though I ran the following commands both in the repository folder as well as "/Downloads":
npm install @material-ui/core
npm install
npm install @material-ui/core/Grid

I can provide more info if needed

A: You see how all the working components are @mui/material/SOMETHING?
Also see the documentation for Grid.
It's import Grid from '@mui/material/Grid'; not from '@material/core/Grid'.


text:
Q: Minimization problem in Sobolev spaces This is a homework problem and I don't know how to solve it:
Consider the following minimization problem on the real-valued sobolev space $H^{1,2}(\Omega)$ with dimension $n=1$ and $\Omega=(0,1)$:
$$F(u) = \int_0^1 \left(u^2+ \text{min}\left\{(u'-1)^2, (u'+1)^2\right\}\right) \ \mathrm{d}x \ \to\ \min$$
($u'$ denotes the derivative of $u$).
a) How to prove, that $F\colon H^{1,2}(\Omega) \to \mathbb R$ is continuous?
b) How to prove, that $\displaystyle\inf_{u\in H^{1,2}(\Omega)} F(u) = 0$, but there is no $u \in H^{1,2}(\Omega)$ with $F(u)=0$ ?
I think, $F$ is not linear mapping (because of quadratic terms in the integral). So it is maybe not the right way to show that the operator norm is bounded. Do I have to prove the continuity of $F$ by the definition (with $\varepsilon$ and $\delta$) or is there another possibility? And I don't know how to determine the infimum.

A: Some hints, since it's a homework problem I won't give the full solution.
For the first question, since for all $a,b\in\mathbb R, 2\min (a,b)=a+b-|a-b|$, we have
\begin{align*}
F(u)&=\int_{[0,1]}\left(u^2+\frac 12((u'+1)+(u'-1)^2-|(u'-1)^2-(u'+1)^2|)\right)dx\\\
&=\int_{[0,1]}\left(u^2+\frac 12(2u'^2+2-4|u'|)\right)dx\\\
&=\int_{[0,1]}u^2dx+\int_{[0,1]}u'^2dx -2\int_{[0,1]}|u'|dx+1.
\end{align*}
Since in any Banach space $x\mapsto \lVert x\rVert$, and $F(u)=\lVert u\rVert_{H^{1,2}(\Omega)}^2-2\int_{[0,1]}|u'|dx$, you only have to show that $L(u):=\int_{[0,1]}|u'|dx$ is continuous from $H^{1,2}$ to $\mathbb R$. But $L$ is linear and Cauchy-Schwarz inequality gives you the result.
For the second question, if $F(u)=0$ for a $u$ then $u=0$, but we can't have $\min ((u'-1)^2,(u'+1)^2)=0$ since $u'=0$. To show that the infimum is indeed $0$, fix $n\geq 1$. We cut $(0,1)$ into $2n$ of length $\frac 1{2n}$, and use a piece wise affine function with $u_n\left(\frac{2k}{2n}\right)=0$ and $u_n\left(\frac{2k}{2n}\right)=\frac 1n$.
Check that this function is indeed in $H^{1,2}$ and compute $F(u_n)$.

A: This problem reminds me the classical Bolza example (named after Oskar Bolza) in the CoV, because $\inf F =0$ can be proved using sawtooth functions.
Obviously $F[u]\geq 0$, thus $\inf F \geq 0$. Now, take:
$$\phi (x):=\begin{cases} 1 -|x-1| &\text{, if } |x-1|\leq 1 \\ 0 &\text{, otherwise}\end{cases}$$
and, for $N\in \mathbb{N}$, define $u_N:[0,1]\to \mathbb{R}$ via:
$$u_N(x):= \frac{1}{2N}\ \sum_{n=0}^{N-1}\phi (2Nx-2n)\; ;$$
then $u_N$ is a nonnegative continuous function mapping $[0,1]$ onto $[0,1/(2N)]$ which is a.e. differentiable and, in particular:
$$u_N^\prime (x)=\pm 1\quad \text{for a.e. } x\in [0,1]\; ;$$
hence:
$$\min \Big\{(u_N^\prime (x)-1)^2,(u_N^\prime (x)+1)^2\Big\} =0 \quad \text{for a.e. } x\in [0,1]$$
and therefore:
$$F[u_N]=\int_0^1 u^2 +\int_0^1\min \Big\{(u_N^\prime (x)-1)^2,(u_N^\prime (x)+1)^2\Big\} \leq \frac{1}{4N^2}\; .$$
The latter inequality yields $\inf F =0$.
For the continuity, you can argue as follows.
You notice that using the reverse triangular inequality and other elementary tricks you get:
$$\begin{split} |F[u]-F[v]| &\leq \Big| \lVert u\rVert_2^2 -\lVert v\rVert_2^2\Big|\\
&\phantom{\leq} + \left| \int_0^1 \bigg( \min \Big\{ |u^\prime -1|,|u^\prime +1|\Big\}\bigg)^2 -\int_0^1\bigg( \min \Big\{ |v^\prime -1|,|v^\prime +1|\Big\}\bigg)^2\right|\\
&= (\lVert u\rVert_2+\lVert v\rVert_2)\ \Big| \lVert u\rVert_2 -\lVert v\rVert_2 \Big|\\
&\phantom{\leq} +\left| \left\lVert \min \Big\{ |u^\prime -1|,|u^\prime +1|\Big\}\right\rVert_2^2 -\left\lVert \min \Big\{ |v^\prime -1|,|v^\prime +1|\Big\} \right\rVert_2^2\right|\\
&\leq (\lVert u\rVert_2+\lVert v\rVert_2)\ \Big| \lVert u\rVert_2 -\lVert v\rVert_2 \Big|\\
&\phantom{\leq} +\left( \left\lVert \min \Big\{ |u^\prime -1|,|u^\prime +1|\Big\}\right\rVert_2 +\left\lVert \min \Big\{ |v^\prime -1|,|v^\prime +1|\Big\}\right\rVert_2 \right)\times \\
&\phantom{\leq +}\times \left| \left\lVert \min \Big\{ |u^\prime -1|,|u^\prime +1|\Big\}\right\rVert_2 -\left\lVert \min \Big\{ |v^\prime -1|,|v^\prime +1|\Big\}\right\rVert_2  \right|\\
&\leq (\lVert u\rVert_2+\lVert v\rVert_2)\ \lVert u-v\rVert_2\\
&\phantom{\leq} +\left( \left\lVert \min \Big\{ |u^\prime -1|,|u^\prime +1|\Big\}\right\rVert_2 +\left\lVert \min \Big\{ |v^\prime -1|,|v^\prime +1|\Big\}\right\rVert_2 \right)\times \\
&\phantom{\leq +} \times \left\lVert \min \Big\{ |u^\prime -1|,|u^\prime +1|\Big\} -\min \Big\{ |v^\prime -1|,|v^\prime +1|\Big\}\right\rVert_2\end{split}$$
for each $u,v\in W^{1,2}(0,1)$.
Now, it is easy to prove that function:
$$\mathbb{R}\ni s\mapsto \min \Big\{ |s-1|,|s+1| \Big\} \in \mathbb{R}$$
is Lipschitz with constant $L=1$ (draw a picture), hence:
$$\tag{1} \begin{split}
|F[u]-F[v]| &\leq (\lVert u\rVert_2+\lVert v\rVert_2)\ \lVert u-v\rVert_2\\
&\phantom{\leq} +\left( \left\lVert \min \Big\{ |u^\prime -1|,|u^\prime +1|\Big\}\right\rVert_2 +\left\lVert \min \Big\{ |v^\prime -1|,|v^\prime +1|\Big\}\right\rVert_2 \right)\ \lVert u^\prime -v^\prime\rVert_2 \; .
\end{split}$$
Finally, if you fix $v$ and let $u\stackrel{W^{1,2}}{\longrightarrow} v$ in (1) you obtain $|F[u]-F[v]|\to 0$ as you wanted.


text:
Q: Php productcode Entered Probelm if i enter the correct product code relavent  details should show.if i remove the productcode details should remove. i attached the screenshot image below.
if i remove the productcode still details should shown. what i tried so far i attached below.

    function getProductcode() {
        $("#barcode").empty();
        $("#barcode").keyup(function(e) {
            var q = $("#barcode").val();
            $.ajax({
                type: "POST",
                url: "get_product.php",
                dataType: "JSON",
                data: { barcode: $("#barcode").val() },
                success: function(data) {
                    if (data != null) {

                        is_product = true;
                        $("#pname").val(data[0].p_name);
                        $("#pro_price").val(data[0].retail_price);
                        $("#qty").focus();
                        $('#barcode').parent('div').removeClass('has-error');
                        $('#price').html('');
                    }

                    else
                    {

                        $('#barcode').parent('div').addClass('has-error');
                        is_product = false;
                        $("#pname").val('');
                        $("#pro_price").val('');

                        $('#qty').val('1');
                    }

        });
}

html

                    <input type="text" tabindex="2" class="form-control" placeholder="barcode" id="barcode" name="barcode"  required>

                 <input  type="text" class="form-control" placeholder="barcode" id="pname" name="pname" disabled>

                <input type="text" class="form-control pro_price" id="pro_price" name="pro_price"
                       placeholder="price" disabled>

                <input type="number" class="form-control pro_price" id="qty" name="qty"
                       placeholder="qty" min="1" value="1"  required>

                <input type="text" class="form-control" placeholder="total_cost" id="total_cost" name="total_cost" disabled>


text:
Q: adb.exe start server failed-run manually if neccessary When I started running my app in Android, I got a message saying that "adb.exe start server failed-run manually if neccessary".

I tried many commands shown on Stack Overflow in the command prompt, but the problem is not rectified. This is the error I get,

I even reinstalled Android Studio, but in vain. And my adb.exe is not found in the Task Manager.
How can I solve this problem?

A: first close android studio then press alt + ctrl + delete  to open task manager then search for adb.exe, click that then press end task. this is the solution that i got from googling,but it didn't work for me.
Then i tried this one, search for java in task manager. end task java(services) also. then open android studio.it will work

A: If you are using a genymotion emulator to run the app then to solve this problem first run android studio and then start genymotion.

A: You can see all the status using cmd. Most of the time adb's home directory ais also available in own PC home director. Such as

C:\User\USER_NAME

What you have to do is first check the availability of adb. Just type and enter
adb service OR adb in your cmd
Then you can see adb version, where it's installed and global option and much more info. If those info doesn't appear you should install Android Studio correctly.
Then you can kill the adb server and start the adb serveer
1.to kill--->> adb kill-server
2.to start-->> adb start-server
All done

A: just need to exit Android Studio and once again run it as administrator :D

A: I haven't seen any solution as mine but I think this is similar to the answer above. As for me, this will happen then my Android Studio won't show any devices, at all. I have "search everything" software on my PC and that when I try to search adb.exe I see a lot of app crash folders. It adds a new one everytime I try to run my android program.
So I go to task manager and found multiple adb runs (as much as how many times I tried to run my program). I closed each and every one of them. Then, I will try to run my program again and adb will run and show my devices.
Runs everytime. No restart, reinstall, run, or re-download needed.


text:
Q: How to count each video unique views Application is written in Zend Framework 1.12.
My videos are available under url:
test.com/videos/video/id/1
test.com/videos/video/id/2
test.com/videos/video/id/3
...

where the number is a unique parameter generated from MySQL DB.
I would like to count views of each video (unique).
My video action in VideosController looks like:
public function videoAction() {
     $video_id = $this->_getParam('id', 0);
     $hits = new Application_Model_DbTable_Hits();
     $hit = $hits->fetchRow($hits->select()->where('belongs_to_video = ?', $video_id));

     if (!isset($_SESSION['views']) || !($_SESSION['views'] == $video_id){
         $_SESSION['views'] = $video_id;
         $newViews = $hit->count + 1;
         $data = array('count' => $newViews, );
         $hits->update($data);
     }

}

It works, however, not in a right way. After visiting particular video views rise (after refreshing the site not), after going to another one views also rise (after refreshing the site not), but after coming back to the first one they rise again (they should not).
Any help appreciated.

A: Sessions aren't a good solution for this. I'd recommend that you log IP address and create blocking cookies to avoid recording duplicate views.
IP Address Logging: This is a good method to avoid logging multiple views. All you need is to put a record in the database as soon as the viewer finishes watching the video (or whatever you count as watched) and the next time, check if the record exists in y our database.
Blocking Cookies: You can also put blocking cookies in your viewers' browsers. This is fairly effective to avoid recording multiple views. You need to send a cookie when a viewer watches the video and check if the cookie exists in the second attempt.
In my opinion, IP Address Logging is enough for this. If your website includes a membership system, you can then simply implement IP Address Logging (but instead of IP addresses, you log user_ids there).


text:
Q: no other flower in the park vs no other flowers in the park (a) No other flower in the park is as expensive as orchids.
(b) No other flowers in the park are as expensive as orchids .
Which one is correct ?

A: There's a connection between flower in the first clause and orchid in the second clause. As such, the numbers must match. Valid sentences are therefore

No other flower in the park is as expensive as an orchid.
No other flowers in the park are as expensive as orchids.

Your sentence a is not appropriate because flower is singular and orchids is plural.

A:
(a) No other flower in the park is as expensive as orchids.
(b) No other flowers in the park are as expensive as orchids .

The word other in your example suggests orchids are also found in the park, but American and British speakers of English tend not to find orchids in our parks. So let's change the sentence:

No other tree on the street is as foul-smelling as the ginkgo.
No other trees on the street are as foul-smelling as the ginkgo.

The singular is certainly correct, and the plural is marginally correct. You'll hear both forms in conversation, especially in contexts where the noun refers to something which lacks personality and individuality  (trees, flowers, cars, etc). However, the plural is less likely when the noun refers to a something that does not typically exist as an undifferentiated multitude but as something or someone possessing unique characteristics:

No other president was as popular as President X.
No other presidents were as popular as President X.  less
  likely/marginal
No other striker has scored as many goals in a single season.
No other strikers have scored as many goals in a single season. less
  likely/marginal


text:
Q: OPNsense move interface to other hardware port I have an OPNsense with interfaces directy configured to the hardware ports. The corresponding switch port is also an access port.
We plan to change the switch port to a trunk port to transport multiple VLANs via this port. Is there a way to move the already configured OPNsense interface (IPs, rules, etc.) to the new corresponding vlan port?

A: I have figured it out.

*

*Add the VLAN interface to the hardware port via "Other Types"

*Change the FW interface assignment to the VLAN interface at "Assignments"

*Reboot to flush and recreate the state table

*In case of a cluster, start with the passive host and do a CARP Switch Over.


text:
Q: TypeError: movies is undefined using React Hooks I am importing data from an API into an array using React hooks and I am getting the error TypeError: movies is undefined.
Here is my full code:
import React, { useEffect , useState } from 'react';
import axios from './axios';
import "./Row.css";

function Row({ title, fetchUrl, isLargeRow = false}) {
    const [movies, setMovies] = useState([]);
    const base_url = "https://image.tmdb.org/t/p/original/";

    useEffect(() => {
        async function fetchData(){
            const request = await axios.get(fetchUrl);
            setMovies(request.data.results);
            return request;
        }

        fetchData();
    }, [fetchUrl]);

    console.log(movies);

    return (

{title}

        {movies.map(movie => (

        ))}

    );
}

export default Row;

When I do console.log(movies); , I seem to get a few empty arrays before it shows some arrays with data. I wonder if the error is because there are no values in the first few arrays.
Image showing arrays in the console
The error itself

A: Updated Answer: You are trying to read from movies array when there is not any element in the movies. You might wanna conditionally render the component so it renders after you set the movies.
 {movies && movies.map(movie => (

    ))}

something likes this.


text:
Q: How to set shell upper tabs to take full width shell xamarin I just have a question is there any way to distribute tab evenly throughout the length in xamarin? Now these are against each other and I would like to distribute them all over the page. I tried to follow different solutions already on stack overflow like this one, but I can't use that. How to set shell upper tabs to take full width. Now I was wondering if there is an easier solution to achieve this today?

<?xml version="1.0" encoding="UTF-8"?>
<Shell xmlns="http://xamarin.com/schemas/2014/forms"
       xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
       xmlns:local="clr-namespace:Eindproject.Views"
       Title="Eindproject"
       x:Class="Eindproject.AppShell">

    <!--
        The overall app visual hierarchy is defined here, along with navigation.

        https://docs.microsoft.com/xamarin/xamarin-forms/app-fundamentals/shell/
    -->

    <Shell.Resources>
        <ResourceDictionary>
            <Style x:Key="BaseStyle" TargetType="Element">
                <Setter Property="Shell.BackgroundColor" Value="{StaticResource Primary}" />
                <Setter Property="Shell.ForegroundColor" Value="White" />
                <Setter Property="Shell.TitleColor" Value="White" />
                <Setter Property="Shell.DisabledColor" Value="#B4FFFFFF" />
                <Setter Property="Shell.UnselectedColor" Value="#95FFFFFF" />
                <Setter Property="Shell.TabBarBackgroundColor" Value="{StaticResource Primary}" />
                <Setter Property="Shell.TabBarForegroundColor" Value="White"/>
                <Setter Property="Shell.TabBarUnselectedColor" Value="#95FFFFFF"/>
                <Setter Property="Shell.TabBarTitleColor" Value="White"/>
            </Style>
            <Style TargetType="TabBar" BasedOn="{StaticResource BaseStyle}" />
            <Style TargetType="FlyoutItem" BasedOn="{StaticResource BaseStyle}" />

            <!--
            Default Styles for all Flyout Items
            https://docs.microsoft.com/xamarin/xamarin-forms/app-fundamentals/shell/flyout#flyoutitem-and-menuitem-style-classes
            -->
            <Style Class="FlyoutItemLabelStyle" TargetType="Label">
                <Setter Property="TextColor" Value="White"></Setter>
            </Style>
            <Style Class="FlyoutItemLayoutStyle" TargetType="Layout" ApplyToDerivedTypes="True">
                <Setter Property="VisualStateManager.VisualStateGroups">
                    <VisualStateGroupList>
                        <VisualStateGroup x:Name="CommonStates">
                            <VisualState x:Name="Normal">
                                <VisualState.Setters>
                                    <Setter Property="BackgroundColor" Value="{x:OnPlatform UWP=Transparent, iOS=White}" />
                                    <Setter TargetName="FlyoutItemLabel" Property="Label.TextColor" Value="{StaticResource Primary}" />
                                </VisualState.Setters>
                            </VisualState>
                            <VisualState x:Name="Selected">
                                <VisualState.Setters>
                                    <Setter Property="BackgroundColor" Value="{StaticResource Primary}" />
                                </VisualState.Setters>
                            </VisualState>
                        </VisualStateGroup>
                    </VisualStateGroupList>
                </Setter>
            </Style>
            <!--
            Custom Style you can apply to any Flyout Item
            -->
            <Style Class="MenuItemLayoutStyle" TargetType="Layout" ApplyToDerivedTypes="True">
                <Setter Property="VisualStateManager.VisualStateGroups">
                    <VisualStateGroupList>
                        <VisualStateGroup x:Name="CommonStates">
                            <VisualState x:Name="Normal">
                                <VisualState.Setters>
                                    <Setter TargetName="FlyoutItemLabel" Property="Label.TextColor" Value="{StaticResource Primary}" />
                                </VisualState.Setters>
                            </VisualState>
                        </VisualStateGroup>
                    </VisualStateGroupList>
                </Setter>
            </Style>
        </ResourceDictionary>
    </Shell.Resources>

    <Shell.FlyoutHeaderTemplate>
        <DataTemplate>
            <Grid BackgroundColor="Black"
                  HeightRequest="100">
                <Image Aspect="AspectFill"
                       Source="https://idsb.tmgrup.com.tr/ly/uploads/images/2022/07/12/217928.jpg"
                       Opacity="0.6" />
                <Label Text="HOTA"
                       TextColor="White"
                       FontAttributes="Bold"
                       HorizontalTextAlignment="Center"
                       VerticalTextAlignment="Center" />
            </Grid>
        </DataTemplate>
    </Shell.FlyoutHeaderTemplate>

    <!--
        When the Flyout is visible this defines the content to display in the flyout.
        FlyoutDisplayOptions="AsMultipleItems" will create a separate flyout item for each child element
        https://docs.microsoft.com/dotnet/api/xamarin.forms.shellgroupitem.flyoutdisplayoptions?view=xamarin-forms
    -->

    <FlyoutItem Title="Home" Icon="outline_home_black_24dp.png">
        <ShellContent Route="Home" ContentTemplate="{DataTemplate local:Home}" />
    </FlyoutItem>

    <FlyoutItem Title="Logs" Icon="outline_local_airport_black_24dp.png">
        <ShellContent Route="Logs" ContentTemplate="{DataTemplate local:Logs}" />
    </FlyoutItem>

    <FlyoutItem Title="Weather" Icon="outline_light_mode_black_24dp.png">
        <ShellContent Route="Weather" ContentTemplate="{DataTemplate local:Weather}" />
    </FlyoutItem>

    <FlyoutItem Title="Stations" Icon="outline_my_location_black_24dp.png">
        <ShellContent Route="Stations" ContentTemplate="{DataTemplate local:Stations}" />
    </FlyoutItem>

    <FlyoutItem Route="animals" Title="Test">
        <Tab Title="test" Route="test">
            <ShellContent Route="Taf" Title="Taf" ContentTemplate="{DataTemplate local:Weather}" />
            <ShellContent Route="Metar" Title="Metar" ContentTemplate="{DataTemplate local:Metar}" />
        </Tab>
    </FlyoutItem>

    <!--
        TabBar lets you define content that won't show up in a flyout menu. When this content is active
        the flyout menu won't be available. This is useful for creating areas of the application where
        you don't want users to be able to navigate away from. If you would like to navigate to this
        content you can do so by calling
        await Shell.Current.GoToAsync("//LoginPage");
    -->

    <!-- Optional Templates
    // These may be provided inline as below or as separate classes.

    // This header appears at the top of the Flyout.
    // https://docs.microsoft.com/xamarin/xamarin-forms/app-fundamentals/shell/flyout#flyout-header
    <Shell.FlyoutHeaderTemplate>
        <DataTemplate>
            <Grid>ContentHere</Grid>
        </DataTemplate>
    </Shell.FlyoutHeaderTemplate>

    // ItemTemplate is for ShellItems as displayed in a Flyout
    // https://docs.microsoft.com/xamarin/xamarin-forms/app-fundamentals/shell/flyout#define-flyoutitem-appearance
    <Shell.ItemTemplate>
        <DataTemplate>
            <ContentView>
                Bindable Properties: Title, Icon
            </ContentView>
        </DataTemplate>
    </Shell.ItemTemplate>

    // MenuItemTemplate is for MenuItems as displayed in a Flyout
    // https://docs.microsoft.com/xamarin/xamarin-forms/app-fundamentals/shell/flyout#define-menuitem-appearance
    <Shell.MenuItemTemplate>
        <DataTemplate>
            <ContentView>
                Bindable Properties: Text, Icon
            </ContentView>
        </DataTemplate>
    </Shell.MenuItemTemplate>

    -->

</Shell>

A: You can achieve that with the following Shell custom renderer.
Create a class named MyShellRenderer that is a subclass of the ShellRenderer class under the Android project:
[assembly: ExportRenderer(typeof(App1_xamarin_forms.AppShell),typeof(App1_xamarin_forms.Droid.MyShellRenderer))]
namespace App1_xamarin_forms.Droid
{
    public class MyShellRenderer : ShellRenderer
    {
        public MyShellRenderer(Context context) : base(context)
        {
        }

       protected override IShellTabLayoutAppearanceTracker CreateTabLayoutAppearanceTracker(ShellSection shellSection)
        {
            return new MyTabLayoutAppearanceTracker(this);
        }
    }
}

And then create MyTabLayoutAppearanceTracker class which derives from the ShellTabLayoutAppearanceTracker class under the Android project:
namespace App1_xamarin_forms.Droid
{
    public class MyTabLayoutAppearanceTracker : ShellTabLayoutAppearanceTracker
    {
        public MyTabLayoutAppearanceTracker(IShellContext shellContext) : base(shellContext)
        {
        }

       public override void SetAppearance(TabLayout tabLayout, ShellAppearance appearance)
        {
            base.SetAppearance(tabLayout, appearance);
            var displayWidth = (int)Xamarin.Essentials.DeviceDisplay.MainDisplayInfo.Width;
            for (int i = 0; i < tabLayout.TabCount; i++)
            {
                TabLayout.Tab tab = tabLayout.GetTabAt(i);
                if (tab.CustomView==null)
                {
                    TextView textview = new TextView(Android.App.Application.Context)
                    {
                        Text = tabLayout.GetTabAt(i).Text,
                        TextSize = 20,
                        Typeface = Typeface.DefaultBold,
                        Gravity = GravityFlags.Center
                    };
                    textview.SetWidth(displayWidth/2);
                    tab.SetCustomView(textview);
                }
            }
        }
   }
}


text:
Q: How to mount two seperate applications inside one Vue project? I am creating a frontend and a backend application inside one Vue 3 project. Everything works fine except that app.js is throwing following error, depending on which component is visited in the browser.
I you visit the app.vue:
[Vue warn]: Failed to mount app: mount target selector "#cms" returned null.

and if you visit the cms.vue:
[Vue warn]: Failed to mount app: mount target selector "#app" returned null.

The mounting file app.js looks like this:
require('./bootstrap');

import {createApp} from 'vue';
import app from "../vue/app";
import cms from "../vue/cms";
import router from "./router";

createApp(app)
    .use(router)
    .mount("#app");

createApp(cms)
    .use(router)
    .mount("#cms");

Is there any way I can prevent the browser warning?

A: You could query the document for those elements, and only mount the ones that exist:
const appEl = document.querySelector('#app');
if (appEl) {
  createApp(app).use(router).mount(appEl);
}

const cmsEl = document.querySelector('#cms');
if (cmsEl) {
  createApp(cms).use(router).mount(cmsEl);
}


text:
Q: C# Networking - Send struct buffer with StructLayout pack 1 I have a server client program which is written by myself. I am using socket with TCP protocol. I am trying to send a buffer from the client to the server. That buffer is struct which I convert it to byte array send it and on the server I convert it back to struct from byte array:
    public static byte[] StructToByteArray(loginStruct obj)
    {
        int len = Marshal.SizeOf(typeof(loginStruct));
        byte[] arr = new byte[len];

        IntPtr ptr = Marshal.AllocHGlobal(len);
        Marshal.StructureToPtr(obj, ptr, true);
        Marshal.Copy(ptr, arr, 0, len);

        Marshal.FreeHGlobal(ptr);
        return arr;

    }
    public static void ByteArrayToStruct(byte[] buffer, ref loginStruct obj)
    {
        int len = Marshal.SizeOf(typeof(loginStruct));

        IntPtr i = Marshal.AllocHGlobal(len);
        Marshal.Copy(buffer, 0, i, len);
        obj = (loginStruct)Marshal.PtrToStructure(i, obj.GetType());

        Marshal.FreeHGlobal(i);
    }

My struct:
[StructLayout(LayoutKind.Sequential, Pack = 1)]
struct loginStruct
{
    public string userName;
    public string password;

    public loginStruct(string userName, string password)
    {
        this.userName = userName;
        this.password = password;
    }
}

I got a runtime error on the line:
obj = (loginStruct)Marshal.PtrToStructure(i, obj.GetType());

The error is:

Attempted to read or write protected memory. This is often an indication that other memory is corrupt.

On the server in the function ByteArrayToStruct len is equals to the buffer size which is 16.

A: If you are trying to send char * buffers of a fixed size, then the default marshaling for strings is probably not going to work for you. You should tag your strings with the MarshalAs attribute and specify the actual buffer size, so that .NET knows how much memory to allocate and copy in the unmanaged version of your structure. It would look something like this:
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
struct loginStruct
{
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst=8)]
    public string userName;
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst=8)]
    public string password;

    public loginStruct(string userName, string password)
    {
        this.userName = userName;
        this.password = password;
    }
}

For more information on how strings are marshaled across the managed/unmanaged boundary, see: Default Marshaling for Strings, especially the Strings Used In Structures section.
Incidentally, I don't think you need to specify Pack since your arrays are 8 bytes each, so there's no room for padding. You need to be very sure that you need to override the packing on a structure, especially if your code needs to work on both 32- and 64-bit systems. If the C definition doesn't include a #pragma pack or similar, you probably shouldn't either.


text:
Q: Set Directory listing as variable in batch file dir /B /A-D /S | find /c /v "~~~" I am trying to write a bat file that counts all files in a directory and subdirectoires and sets a variable based on the output. Something like this:
set /a FILECOUNT=dir c:\Dir1 /B /A-D /S | find /c /v "~~~"
echo %FILECOUNT%

The output of the dir is only a number, I can't figure out how to get that number into my variable.

A: for /f %%a in ('dir c:\Dir1 /B /A-D /S | find /c /v "~~~"') do set FileCount=%%a


text:
Q: Why does my database crash when I leave the page? Whenever I navigate to a particular page and then leave it some tables are deleted.  The only thing that differs between this page and the rest is that this page uses a different DbContext.  The tables deleted are also part of a different DbContext which is not used on the page visited.  This has really got me, any suggestions?
The controller that crashes the page is.
public class GenerationController : Controller
{
    private GenerationDbContext GenerationDb = new GenerationDbContext();
    private string generatedDir = "~/App_Data/Generated";

    //
    // GET: /Generation/

    public ViewResult Index()
    {
        var viewModel = new GenerationIndexViewModel
        {
            Generations = GenerationDb.Generations
                .OrderByDescending(g => g.GeneratedOn)
                .ToList()
        };

        return View(viewModel);
    }

    protected override void Dispose(bool disposing)
    {
        GenerationDb.Dispose();
        base.Dispose(disposing);
    }
}

UPDATE:  I just realized I have another page that accesses both DbContexts.  For some reason, I can navigate to this page and then leave without deleting tables.  It is just this one page that deletes all the tables for the other context.
UPDATE:  When I change the Index action to.
public ActionResult Index()
{
    return Content("Hello.");
}

I can navigate between the page and all the other pages fine.  No errors about tables being deleted.  Ergo, I'm positive it has to do something with the model or database context.  Which are so.
public class Generation
{
    public int Id { get; set; }

    [Required]
    public DateTime GeneratedOn { get; set; }

    [Required, StringLength(4000)]
    public string Name { get; set; }
}

public class GenerationDbContext : DbContext
{
    public DbSet<Generation> Generations { get; set; }
}

UPDATE:  Using the Database Explorer provided with VWD, there is the Generations table when I navigate to the page.  And when I navigate to another page that use a different database context, the Generations table is still the only table.  Argh!

A: Sounds like you have Code First; the first time each dbcontext runs, it checks the database it is configured to connect to. If the schema is not what it expects to find, it flattens the database and recreates tables based on the model classes used by that context.
There are numerous paths to solve this. The easiest are to combine your contexts, or direct each one to its own separate database.


text:
Q: How to design a Terraform resource with multiple sensitive attributes Context: I'm developing a new resource for my TF Provider.
This foo resource has a name and associated config: a list of key value pairs (both sensitive and non-sensitive).
There're 3 options I've identified:
resource "foo" "option1" {
  name = "option1"
  config = {
    "name"            = "option1"
    "errors.length"   = 3
    "tasks.type"      = "FOO"
  }
  config_sensitive = {
    "jira.key"         = "..."
    "credentials.json" = "..."
  }
}

resource "foo" "option2" {
  name = "option2"
  config = {
    "name"            = "option1"
    "errors.length"   = 3
    "tasks.type"      = "FOO"
    "jira.key"         = "..."
    "credentials.json" = "..."
  }
}

resource "foo" "option3" {
  name = "option3"
  config = file("config.json")
}

The advantage of option #3 is it looks very readable but requires a user to store an extra json file (with secrets) in the same folder (I'm not sure how acceptable that setup is). Option #2 looks tempting but foo should accept updates and if we mark the whole block as sensitive (since it may contain secret key-value pairs), the update functionality will suffer (user won't see the expected change). So Option #1 is the winner in my eyes since it's the most explicit one and allows us to distinguish between sensitive and non-sensitive attributes (while allowing updates for non-sensitive ones). Reading from file the whole config is probably not ideal since it doesn't really allow an engineer to see how the config looks like without opening another file.
There's also this weird duplicated name attribute but let's ignore it for now.
What configuration is the most acceptable and used by other TF Providers?

A: Option #3 should be struck immediately for three reasons:

*

*You cannot realiably use the sensitive flag in the schema struct like you can with 1 and 2.

*It requires a JSON format value which is cumbersome to work with unless you are forced into it (e.g. security policies).

*Someone could inline the JSON and not store it in a file, which would completely workaround your attempt to obscure the secrets.

Options 1 and 2 are honestly no different from a secrets management perspective. You could apply the sensitive flag to either in the nested schema struct on a per-attribute basis, and use e.g. Vault to pass in values on a KV basis for either.
I would opt for 1 over 2 simply because it appears to me from your question that the arguments and values in the two blocks have no relationship with each other. Therefore, it makes more sense to organize your schema into two separate blocks for code cleanliness purposes.
I will also mention that if it is possible to refactor the credentials.json into your provider, and leverage the JIRA provider for the jira.key, then that would be best practices by both code architecture and security. It is also how the major providers handle this situation.

A: Terraform providers should handle the credential/auth implementation and the resource handles the resource configuration.
e.g.
resource "jira_issue" "some_story" {
  title  = "My story"
  type   = "story"
  labels = ["someexampleonstackoverflow","jakewashere"]
}

Notice there's no config that doesn't relate to the thing I'm creating inside the Terraform resource.
It's very acceptable to have some documented convention in your provider that reads credentials from somewhere, whether that's an OS variable, file on disk etc.
For example: The Google Cloud provider, will read an environment variable if it's populated, if not it'll attempt to read either a configuration file that sits inside a hidden directory within $HOME or attempts to read a localhost http metadata server for the credentials.


text:
Q: confusion past tense and present tense, if I say

*

*I told you to wait until he came back.

*I told you to wait until he comes back.

which one is correct? if both sounds nothing wrong to you, what's the  difference?

A: There are two issues here, one is past tense vs. present tense and the other is back-shifting reported speech.

I told you, "Wait until he comes back."

If I change this to reported speech, I can backshift the verb tense within the quote to be in the past tense:

I told you to wait until he came back.

Without any context, we can't know the relative time frame of all these events. Has he come back yet or not?

I told you to wait until he came back.

(Reported speech of something I told you in the past, but it's unclear whether he has come back yet or not)

I told you to wait until he comes back.

(Reported speech of something I told you in the past, and he hasn't yet come back)
You can use either, because the person you're talking to knows the context -- when they were told, whether "he" has come back, etc.


text:
Q: Android getting Error while show ProgressDialog I have an Activity where I want to show a ProgressDialog. I override onCreateDialog in my Activity. Everytime the dialog returns in onCreateDialog I get an force-close, saying:
07-13 13:10:11.449: ERROR/AndroidRuntime(8720): android.util.AndroidRuntimeException:     requestFeature() must be called before adding content
07-13 13:10:11.449: ERROR/AndroidRuntime(8720):     at com.android.internal.policy.impl.PhoneWindow.requestFeature(PhoneWindow.java:181)
07-13 13:10:11.449: ERROR/AndroidRuntime(8720):     at com.android.internal.app.AlertController.installContent(AlertController.java:199)
07-13 13:10:11.449: ERROR/AndroidRuntime(8720):     at android.app.AlertDialog.onCreate(AlertDialog.java:251)
07-13 13:10:11.449: ERROR/AndroidRuntime(8720):     at android.app.ProgressDialog.onCreate(ProgressDialog.java:176)
07-13 13:10:11.449: ERROR/AndroidRuntime(8720):     at android.app.Dialog.dispatchOnCreate(Dialog.java:307)
07-13 13:10:11.449: ERROR/AndroidRuntime(8720):     at android.app.Activity.createDialog(Activity.java:886)
07-13 13:10:11.449: ERROR/AndroidRuntime(8720):     at android.app.Activity.showDialog(Activity.java:2557)
07-13 13:10:11.449: ERROR/AndroidRuntime(8720):     at     android.app.Activity.showDialog(Activity.java:2524)

the onCreateDialog(int id) looks like this:
    protected Dialog onCreateDialog(int id){
    switch (id) {
    case DOWNLOAD_DIALOG:
        ProgressDialog dialog = new ProgressDialog(ListMapActivity.this);
        dialog.setTitle(getResources().getString(R.string.dialog_download_title));
        dialog.setCancelable(true);
        dialog.setOnCancelListener(new OnCancelListener() {

            @Override
            public void onCancel(DialogInterface dialog) {
                if ((mTask.getStatus().equals(AsyncTask.Status.RUNNING)
                    || mTask.getStatus().equals(AsyncTask.Status.PENDING))
                    && !mTask.isCancelled()){
                    mTask.cancel(true);
                }
                Toast.makeText(getApplicationContext(), R.string.dialog_download_cancel, Toast.LENGTH_LONG).show();
            }
        });
        TextView tw = new TextView(ListMapActivity.this);
        dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        LayoutParams params = new ViewGroup.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
        tw.setLayoutParams(params);
        tw.setText(getResources().getString(R.string.dialog_download_text));
        dialog.setContentView(tw);

        return dialog;

    default:
        return null;
    }
}

Note: I tried ProgressDialog.Show(context, title, message) to execute directly instead of showDialog(), with this result:
07-13 13:03:42.910: ERROR/AndroidRuntime(8444): android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application
07-13 13:03:42.910: ERROR/AndroidRuntime(8444):     at android.view.ViewRoot.setView(ViewRoot.java:531)
07-13 13:03:42.910: ERROR/AndroidRuntime(8444):     at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:177)
07-13 13:03:42.910: ERROR/AndroidRuntime(8444):     at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)
07-13 13:03:42.910: ERROR/AndroidRuntime(8444):     at android.app.Dialog.show(Dialog.java:241)
07-13 13:03:42.910: ERROR/AndroidRuntime(8444):     at android.app.ProgressDialog.show(ProgressDialog.java:107)
07-13 13:03:42.910: ERROR/AndroidRuntime(8444):     at android.app.ProgressDialog.show(ProgressDialog.java:90)
07-13 13:03:42.910: ERROR/AndroidRuntime(8444):     at android.app.ProgressDialog.show(ProgressDialog.java:85)

I assume I forget something to initialize. I don't even know where this requestFeature() is been called. Any Idea is welcome
UPDATE:
I played around a little bit and found out, that everything works again, if I delete these lines:
        LayoutParams params = new ViewGroup.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
        tw.setLayoutParams(params);
        tw.setText(getResources().getString(R.string.dialog_download_text));
        dialog.setContentView(tw);

So I'm lost on how to set the Content of this View. It doesn't help, when I create the Main-design in onCreate of my Activity as a member and put this into ProgressDialog. I simply don't get the problem. What is wrong putting a TextView on-the-fly to put it as Content from my Dialog?

A: simply try this.
ProgressDialog dialog = ProgressDialog.show(yourActivity.this, "",
                        "Loading. Please wait...", true);

Thanks.

A: This error message requestFeature() must be called before adding content means that you are invoking a method on the dialog, that you aren't allowed to invoke after you had added content.
I would move these lines:
dialog.setCancelable(true);
dialog.setTitle(getResources().getString(R.string.dialog_download_title));

So that they are before this line:
dialog.setContentView(tw);

setTitle is your most likely candidate for the error.


text:
Q: android group notification show last notification instead of first one I am trying to implement group notification like whatsapp. But issue here is first 6 notification are visible to user. How can i display the last 6 notification instead of first one.
PFB demo code for same:
import android.app.Notification;
import android.app.NotificationManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;

import static android.R.attr.value;

@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
public class MainActivity extends AppCompatActivity {
    Notification.InboxStyle inboxStyle = new Notification.InboxStyle();
    private final int NOTIFICATION_ID = 237;
    private static int NOTIFICATION_ID1 = 237;

    final static String GROUP_KEY_EMAILS = "group_key_emails";

    static int i=0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        send(++i+"");
        send(++i+"");
        send(++i+"");
        send(++i+"");
        send(++i+"");
        send(++i+"");
        send(++i+"");
        send(++i+"");
        send(++i+"");
        send(++i+"");
        send(++i+"");
        send(++i+"");
        send(++i+"");
        send(++i+"");
        send(++i+"");
        send(++i+"");
        send(++i+"");
        send(++i+"");
        send(++i+"");
        send(++i+"");
        send(++i+"");
        send(++i+"");
        send(++i+"");
        send(++i+"");
        send(++i+"");
        send(++i+"");
        send(++i+"");
        send(++i+"");
        send(++i+"");
        send(++i+"");
        send(++i+"");
        send(++i+"");
        send(++i+"");
        send(++i+"");
        send(++i+"");
        send(++i+"");
        send(++i+"");
        send(++i+"");
        send(++i+"");
        send(++i+"");
        send(++i+"");
        send(++i+"");

    }

    public void send(String message)
    {
        NotificationManager nManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        Notification.Builder builder = new Notification.Builder(this);
        builder.setContentTitle(message+"Lanes");
        builder.setContentText(message+"Notification from Lanes"+value);
        builder.setSmallIcon(R.mipmap.ic_launcher);
        builder.setAutoCancel(true);
        inboxStyle.setBigContentTitle(message+"Enter Content Text");
        inboxStyle.addLine(message+"hi events "+value);
        builder.setStyle(inboxStyle);
        nManager.notify("App Name",NOTIFICATION_ID ,builder.build());

    }

}

A: Use a string array to store new notification messages.
Each time a new notification is generated,cancel the notification and
add messages to the notification builder from the end of the list.
I tried this and it worked !
private final int NOTIFICATION_ID = 237;
ArrayList<String> notificationText = new ArrayList<>();
Notification.InboxStyle inboxStyle ;

static int i=0;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    send(++i+"");
    send(++i+"");
    send(++i+"");
    send(++i+"");
    send(++i+"");
    send(++i+"");
    send(++i+"");
    send(++i+"");
    send(++i+"");
    send(++i+"");
    send(++i+"");
    send(++i+"");
    send(++i+"");
    send(++i+"");
    send(++i+"");
    send(++i+"");
    send(++i+"");
    send(++i+"");
    send(++i+"");
    send(++i+"");
    send(++i+"");
    send(++i+"");
    send(++i+"");
    send(++i+"");
    send(++i+"");
    send(++i+"");
    send(++i+"");
    send(++i+"");
    send(++i+"");
    send(++i+"");
    send(++i+"");
    send(++i+"");
    send(++i+"");
    send(++i+"");
    send(++i+"");
    send(++i+"");
    send(++i+"");
    send(++i+"");
    send(++i+"");
    send(++i+"");
    send(++i+"");
    send(++i+"");

}

public void send(String message)
{
    notificationText.add(message);
    NotificationManager nManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    nManager.cancelAll();

    Notification.Builder builder = new Notification.Builder(this);
    inboxStyle = new Notification.InboxStyle();
    builder.setContentTitle(message+"Lanes");
    builder.setContentText(message+"Notification from Lanes"+value);
    builder.setSmallIcon(R.mipmap.ic_launcher);
    builder.setAutoCancel(true);
    inboxStyle.setBigContentTitle(message+"Enter Content Text");
    for(int i=notificationText.size()-1;i>=0;i--){
        inboxStyle.addLine(notificationText.get(i)+"hi events "+value);
    }
    builder.setStyle(inboxStyle);
    nManager.notify("App Name",NOTIFICATION_ID ,builder.build());

}


text:
Q: Class with a db query, extending, functions and views. Am I doing it right way? I have just a little progress in practicing. Most of my code works but I am not sure if I do things the right way?
Please, can you tell me if I do mistakes and correct me.
First, I create autoload functions:
function autoload_models($model) {
    if (file_exists(MODELS_PATH . $model . '.php')) {
        require_once MODELS_PATH . $model . '.php';
        return true;
    } else {
        return false;
    }
}

spl_autoload_register('autoload_models');

function autoload_controllers($controller) {
    if (file_exists(CONTROLLERS_PATH . $controller . '.php')) {
        require_once CONTROLLERS_PATH . $controller . '.php';
        return true;
    } else {
        return false;
    }
}

spl_autoload_register('autoload_controllers');

I have a class like this:
class Category {

    public $db;
    public $rows;
    public $id;

    public function build_category() {

        global $db;
        global $rows;

        $db = new Database();
        $db->query("SELECT * from categories");
        $rows = $db->resultset();
    }

    public function category_items() {

        global $db;
        global $rows;
        global $id;

        $db = new Database();
        $db->query("SELECT * from posts WHERE category_id = '$id'");
        $rows = $db->resultset();
    }

}

I extend with another class (still have some issues here. Nothing prints):
class Category_Items extends Category {

    public $db;
    public $rows;
    public $id;

    public function display_category_items() {

        // Call the parent class function
        parent::category_items();

        global $rows;
        global $id;

        // Check if the page parameter is integer
        if (ctype_digit($_GET['id'])) {
            $id = $_GET['id'];
        } else {
            print "Illegal category page parameter";
        }

        foreach ($rows as $row) {

            print "test";
            print $row['post_title']; // This does not work yet. Nothing prints
        }
    }

}

Class for building a menu with categories (Everything works here):
class Categories_Menu extends Category {

    public $db;
    public $rows;

    public function build_category_menu() {

        parent::build_category();

        global $rows;

        foreach ($rows as $row) {

            require VIEWS_PATH . 'categories/categories_menu.php';
        }
    }

}

And finally instances:
$category_menu = new Categories_Menu();
$category_menu->build_category_menu();

$category_items = new Category_Items();
$category_items->display_category_items();

Thank you for your time and help!

A: Where do the global variables come from?
Anyway, you should get rid of them.
I guess your rows var does not get changed, after any interaction. Using globals also will not be relevant in extending classes.
Your public properties and globals mentioned, does no interact each other. Thus, the object members seems to be totally useless.
What I would suggest in simple schems would be
class Model {

    protected $_db;

    public function __construct(Database $db) {
        $this->_db = $db;
    }
}

class Category extends Model {

    public $_rows;
    public $_id;

    public function build_category() {
        $this->_db->query("SELECT * from categories");
        $this->_rows = $this->_db->resultset();
    }

    public function category_items() {
        $this->_db->query("SELECT * from posts WHERE category_id = '{$this->_id}'");
        $this->_rows = $this->_db->resultset(); // here you will overwrite $_rows ?
    }

class Categories_Menu extends Category {

    public $_rows;

    public function build_category_menu() {
        $this->build_category();
        foreach ($this->_rows as $row) {
            require VIEWS_PATH . 'categories/categories_menu.php';
        }
    }
}

class Category_Items extends Category {

    public $_rows;
    public $_id;

    public function display_category_items() {

        if (ctype_digit($_GET['id'])) { // just intval it, or use is_int?
            $this->_id = $_GET['id'];
        } else {
            print "Illegal category page parameter";
        }

        // You assign value to $_id, then call the function that requires it

        $this->category_items();

        foreach ($this->_rows as $row) {

            print "test";
            print $row['post_title'];
        }
    }
}


text:
Q: AngularJS Redirect Page is there a way to use base_url() in angularJS?
here's my code:
it worked fine. but I'm just curious if there's a way for me to use base_url like in the comment of the code, than typing the whole fixed url.
$scope.login = function(){
    console.log($scope.users);
    var inputs = 'myData=' + JSON.stringify($scope.users);
    $http({
        method:'POST',
        url:'lib/login_c.php',
        data: inputs,
        headers:{'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8'}
    }).success(function(res){
        console.log(res);
        if(res == 1){
             $window.location.href = "http://localhost/angularjs/index.php";
             //$windows.location.href=baseurl() + '/index.php';
        }else{
            $scope.message = true;
        }
    });
};

A: You can just use a / to use root url. And in your case you want to href to the index page just do like this:
$window.location.href = "index.php"

You may also find this helpful:
"./index.php" //dot is for root


text:
Q: What does "look what the wind blew in" mean? From the movie Masterminds (2016)
In the beggining the main character is saying about the story of his life.

In 1997, I was a quiet middle-aged man knocking on 40. But then, then
  the wind blew in Miss Kelly Campbell.

Searching the Internet I learned that "look what the wind blew in" probably has the same meaning as "look what the cat dragged in" which a one says when someone that is disliked shows up. But in the movie the main character's saying the phrase about "the wind" blandly, like he actually was glad that Miss Kelly Campbell showed up in his life.
My question is - does the phtase mean only something or someone unpleasant or it has more neutral nature, like "But then she showed up"

A: This phrase means something happened unexpectedly. There is no implication of unpleasantness.


text:
Q: Prisma How to automatically update "updatedAt" field of parent element when a child element is created or updated? Let's say I have this schema:
model User {
   id String @id @default(cuid())
   name String
   email String
   profile Profile?
   createdAt DateTime @default(now())
   updatedAt DateTime @updatedAt
}

model Profile {
   id Int @id @default(autoicrement())
   bio String?
   avatar String?
   user User @relation(fields: [userId], references: [id], onDelete: Cascade)
   userId String @unique
}

Now what I want to archive is, if a user's profile is updated, for example, a bio field is updated, I want the updatedAt field on User model to automatically reflect that and get updated too to the current timestamp.
Any guide, hint or suggestion will be much appreciated!!

A: The easiest way would be to make some wrapper function I think, for example:
const updateUserProfile = (id, data) => {
  return prisma.profile.update({
    where: {
      id
    },
    data: {
      ...data,
      user: {
        update: {
          updatedAt: new Date()
        }
      }
    }
  })
}


text:
Q: Поиск подстроки и скобочных групп Я пытаюсь найти целую строку и все скобочные группы. Я хочу сделать это в строке:

contract var str = "contract CryptoGO is StandardToken, Babaika, Pisos, Banana { string public name; uint8 public decimals; string public symbol; string public version = 'H1.0'; uint256 public unitsOneEthCanBuy; uint256 public totalEthInWei; address public fundsWallet; function CryptoGOToken() { balances[msg.sender] = 1000000000000000000000000000; totalSupply = 1000000000000000000000000000; name = \"CryptoGO\"; decimals = 18; symbol = \"CGO\"; unitsOneEthCanBuy = 10000; fundsWallet = msg.sender; } function() payable{ totalEthInWei = totalEthInWei + msg.value; uint256 amount = msg.value * unitsOneEthCanBuy; if (balances[fundsWallet] < amount) { return; } balances[fundsWallet] = balances[fundsWallet] - amount; balances[msg.sender] = balances[msg.sender] + amount; Transfer(fundsWallet, msg.sender, amount); fundsWallet.transfer(msg.value); } function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); if(!_spender.call(bytes4(bytes32(sha3(\"receiveApproval(address,uint256,address,bytes)\"))), msg.sender, _value, this, _extraData)) { throw; } return true; }}";

Пример моего кода:

var str = "contract CryptoGO is StandardToken, Babaika, Pisos, Banana {   string public name;    uint8 public decimals;    string public symbol;    string public version = 'H1.0';    uint256 public unitsOneEthCanBuy;    uint256 public totalEthInWei;    address public fundsWallet;    function CryptoGOToken() {        balances[msg.sender] = 1000000000000000000000000000;        totalSupply = 1000000000000000000000000000;       name = \"CryptoGO\";        decimals = 18;        symbol = \"CGO\";        unitsOneEthCanBuy = 10000;        fundsWallet = msg.sender;    }    function() payable{        totalEthInWei = totalEthInWei + msg.value;        uint256 amount = msg.value * unitsOneEthCanBuy;        if (balances[fundsWallet] < amount) {            return;        }        balances[fundsWallet] = balances[fundsWallet] - amount;        balances[msg.sender] = balances[msg.sender] + amount;        Transfer(fundsWallet, msg.sender, amount);        fundsWallet.transfer(msg.value);   }    function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) {        allowed[msg.sender][_spender] = _value;        Approval(msg.sender, _spender, _value);        if(!_spender.call(bytes4(bytes32(sha3(\"receiveApproval(address,uint256,address,bytes)\"))), msg.sender, _value, this, _extraData)) { throw; }        return true;    }}";
            var re = /[^(//)]?\s?contract\s+([a-zA-Z0-9_\-]+)\s*is?\s+([a-zA-Z0-9_\-]+)\s*[, {]/ig;
            var res
            while ((res = re.exec(str)) != null) {
                   console.log(res);
            }

Сейчас я имею вывод:
[
  "contract CryptoGO is StandardToken,",
  "CryptoGO",
  "StandardToken"
]

А хочу получить следующий вывод:
[contract CryptoGO is StandardToken, Babaika, Banana {,
CryptoGO,
StandardToken,
Babaika,
Banana]

Как правильно переписать регулярное выражение, чтобы оно давало ожидаемый вывод?


text:
Q: Database Server Can't Find 300GB I have a Windows Server 2008 R2 running Microsoft SQL Server 2008 R2.  I have some how lost 300 GB of disk space, and I can't seem to find it anywhere.  The Hard Drive is 500GB and I can only account for 200GB.  I have "Show Hidden Files" on and "Hide Protected Files" off.  I have check the details for every folder top level folder, and I still can only find 200 GB of a 500 GB Hard Disk.  The disk is almost full and this doesn't make any sense.  Any one have any ideas of where I might be able to find this lost space?  On a weekly basis I delete old back ups of the databases.  Maybe that might have something to do with it?

A: Use Windirstat.  It'll give you a graphical view of your disk space usage, as well as sort your folders by space used.  A lot easier than trying to hunt through Windows Explorer for what's chewing up your disk space.

A: If one doesn't fix it, try the next:

*

*Run chkdsk against the disk.

*Run vssadmin list shadows to see if there are any volume snapshots.

*Run a program that can list directory sizes, such as Winstatdir listed by HopelessN00b.


text:
Q: How can I keep SSH sessions alive when the IP changes when switching between Wi-Fi and Ethernet? In Mac OS X Yosemite, I want to be able to create a virtual interface with a Static IP that's tied to both my Ethernet and Wi-Fi interfaces, so that when I undock my laptop, I don't lose my SSH connections.
The simple answer of just working off of Wi-Fi isn't acceptable as the network hits congestion or signal constraints and I get awful lag or drop connections sitting at my desk. Bridging the adapters using Mac OS X's built in option creates a network loop that I don't seem to be able to avoid—even using spanning tree—unless I've over looked something.
Any suggestions?
**Edit
Screen is not a good solution. I already use it on the server side when I'm connected because of this issue. I don't want to lose my ssh connection at all when I switch interfaces, meaning, I don't want to have to reconnect and reauth every time I switch from ethernet to wifi. I usually have upwards of 10 ssh sessions going, and it's a lot to reconnect them all

A: You can use the screen utility to do keep the session running even after you detach and then you can re-attach to the session. It's available for Mac OS X, I believe.
More information can be found at howtogeek and rackaid tutorials.

Edit:
Since screen is not what the OP is looking for, Mobile Shell (mosh) would fit the use case perfectly. (This is also mentioned by @lnrdo in another answer on this thread).
Here is Keith Winstein, author of mosh, introducing it in this video.
Although, sometime back, I had difficulties installing mosh on the ssh server when I didn't have sudo access. I don't know if things have changed since then.

A: I've not tried it - indeed I don't own a Mac, but I've bumped into this type of problem before over a WAN, and the solution could work for you - Set up a VPN between your Mac and your server - in this way the VPN can reconnect and give you the same VPN address - provided you manage to route your SSH session through the VPN tunnel, the keep-alives built in to SSH will allow the session to work regardless of whether you are using WIFI or LAN or switching between the 2.
Another possibility - and again, no mac, so I'm theorising - would be to provide the same IP address (statically) configured for your LAN IP and WIFI address, and then use some kind of profile switching to ensure that WIFI is turned off whenever you are docked - if thats possible on a MAC.   Depending on the complexity of the switching network you have this might or might not upset your switching equipment.

A: You need something as mosh. It requires both server and client side components, but it works for mobile (roaming) devices.
Screen and tmux may help you continue your work after reconnecting, but mosh keeps you connected/reconnecting. In my experience it also is helpful wen your router has a dynamic IP address.

A: You can modify some parameters on your sshd.conf file. In particular ClientAliveInterval, which could be set to 60 or 120 and TCPKeepAlive(yes or no).


text:
Q: Proving that $(-\infty,0]\subseteq \sigma(\Delta)$ Consider $w,g\in L^2(\mathbb{R}^n)$ such that $\lambda w-\Delta w=g$.  Show that for all $\lambda>0, \lambda\in \rho(\Delta)$.  That is, $\sigma(\Delta)=(-\infty,0]$.  Where $\sigma(\Delta)$ is the spectrum of $\Delta$.
In my answer, I have used Fourier transform by as in the following:
$\hat{\lambda w}-\hat{\Delta w}=\hat{g}$ which led me to $\hat{w}=\hat{g}/(\lambda+\left|\xi\right|^2)$.  Thus for $g \in L^2$, $(\lambda I - \Delta)^{-1} g = \left((\lambda +|\xi|^2)^{-1} \hat{g}\right)^\vee$
I followed the solution on this link:
[What is spectrum for Laplacian in $\mathbb{R}^n$?
From which I was able to prove that $\sigma(\Delta)\subseteq(-\infty,0]$.
However, I have found it hard to elementarily show that $(-\infty,0]\subseteq \sigma(\Delta)$, in order to establish the equality.    Even the proof on the link is complicated.

A: The resolvent of $\Delta$ is $(\Delta-\lambda I)^{-1}$, which is defined at least for $\lambda\notin\mathbb{R}$, and can be found with the Fourier transform to be
$$
             (\Delta-\lambda I)^{-1}f = \frac{1}{(2\pi)^{n/2}}\int\frac{1}{-|\xi|^2-\lambda}\hat{f}(\xi)d\xi,\;\;\; \lambda\in\mathbb{C}\setminus\mathbb{R}.
$$
From this you can also see that resolvent set includes $\mathbb{C}\setminus(-\infty,0]$. So $\sigma(\Delta)\subseteq(-\infty,0]$.
To show that $(-\infty,0]\subseteq\sigma(\Delta)$, let $r > 0$. For any $0 < \epsilon < r$, let $f_{r,\epsilon}$ be defined so that
$$
       \hat{f_{r,\epsilon}}(\xi) = \chi_{[r-\epsilon,r+\epsilon]}(|\xi|).
$$
Then $\|f_{r,\epsilon}\|=\|\hat{f_{r,\epsilon}}\|=\|\chi_{[r-\epsilon,r+\epsilon]}\|$, and
$$
          \|(\Delta+rI)f_{r,\epsilon}\|=\|(|\xi|-r)\chi_{[r-\epsilon,r+\epsilon]}(|\xi|)\| \le \epsilon\|\chi_{[r-\epsilon,r+\epsilon]}\|=\epsilon\|f_{r,\epsilon}\|.
$$
So $(\Delta +rI)$ cannot have a bounded inverse for any $r > 0$. So $(-\infty,0]=\sigma(\Delta)$.


text:
Q: how to get generated primary key after persisting record in Camel I am trying to get the primary key which is autogenerated after inserting data into the database using Camel. I saw, there was a JIRA issue(https://issues.apache.org/jira/browse/CAMEL-7313) and it was resolved.
                     from("file:data/source?noop=true")
                        .to("validator:books.xsd")
                        .split()
                        .tokenizeXML("book")
                        .unmarshal(jaxb)
                        .to("jpa:com.labs.Book")
                        .process(new Processor() {
                            public void process(Exchange exchange)
                                    throws Exception {
                                //here i want to get that primary key
                            }
                        });

Can someone point me to an example for this ....

A: Yeah after some googling and suggestions from the experts above. I got the answer for my question
from("file:data/source?noop=true")
                        .to("validator:books.xsd")
                        .split()
                        .tokenizeXML("book")
                        .unmarshal(jaxb)
                        .to("jpa:com.labs.Book")
                        .process(new Processor() {
                            public void process(Exchange exchange)
                                    throws Exception {
                                //here it is
                                int Id = exchange.getIn().getBody(Book.class).getId();
                            }
                    });

Thank you everyone.

A: The primary key gets set on the entity class, so check that class. You need to configure your JPA entity with the JPA annotations, where you define which field is the primary key.
Just search the web or this site for jpa primary key


text: Q: Left-to-right segue in swift I'm trying to create a left to right segue using the standard animation method, kinda like this one. When I animate only the destination view controller from the right to the center of the screen, it works fine. However, if I add in simultaneously the source view controller's animation (from the center of the screen to the left), the animation gets bugged and displays a black screen for the rest of the specified duration. Is there any other way in which I can achieve a left-to-right segue, or could you guys please help me understand what I'm doing wrong?


text:
Q: Python parse from log file I have a big log file with huge volume. How do i take only the json string, just the json string only when there is an error in the next line but after '_____GP D_____' in the previous line?
2017-04-22T11:27:11+06:00 smth.com pgp: [16136]: INFO:modules.gp.helpers.parameter_getter:_____GP D_____
2017-04-22T11:27:11+06:00 smth.com pgp: [16136]: {'D': 't12', 'telephone': None, 'from_time': '2016-04-22 11:30', 'C': 'C12', 'to_time': '2016-04-22 11:40', 'email': None}
2017-04-22T11:27:11+06:00 smth.com pgp: [16136]: INFO:tornado.access:200 POST /gp/C (192.168.1.240) 15.77ms

2017-04-22T11:28:19+06:00 smth.com pgp: [16136]: INFO:modules.security.authentication:LOADING USER...
2017-04-22T11:28:19+06:00 smth.com pgp: [16136]: INFO:modules.gp.helpers.parameter_getter:_____GP D_____
2017-04-22T11:28:19+06:00 smth.com pgp: [16136]: {'D': 'testim12', 'telephone': None, 'from_time': '2017-04-20 17:30', 'C': 'CnGP13', 'to_time': '2017-04-22 21:40', 'email': None}
2017-04-22T11:28:19+06:00 smth.com pgp: [16136]: ERROR:modules.common.actionexception:ActionError: [{'from': 'time is already passed'}]
2017-04-22T11:28:19+06:00 smth.com pgp: [16136]: Traceback (most recent call last):
2017-04-22T11:28:19+06:00 smth.com pgp: [16136]:   File "/app/src/modules/base/actions/base_action.py", line 96, in do_action
2017-04-22T11:28:19+06:00 smth.com pgp: [16136]:     self._produce_response()
2017-04-22T11:28:19+06:00 smth.com pgp: [16136]: modules.common.actionexception.ActionValidationErr: []

for example from this log file i want
'{'D': 'testim12', 'telephone': None, 'from_time': '2017-04-20 17:30', 'C': 'CnGP13', 'to_time': '2017-04-22 21:40', 'email': None}'.
Only when i have an exception, ' ERROR:modules.common.actionexception:ActionError:' in the next line? how do i do it?

A: You could use this, where the JSON string is in capture group 1
(?m)^.*?_____GP[ ]D_____.*\r?\n\s*^[^{\r\n]+(.+)\r?\n\s*^.*?ERROR:.*
https://regex101.com/r/UQ8gni/2
Explained
 (?m)                          # Modifiers: multi-line
 ^ .*? _____GP [ ] D_____ .*   # Line that starts error block
 \r? \n \s*                    # Required newline
 ^ [^{\r\n]+                   # Up to start of Json string
 ( .+ )                        # (1), Json string
 \r? \n \s*                    # Required newline
 ^ .*? ERROR: .*               # Line that ends error block

A: That's the same problem as the one you had yesterday, just with an additional check before selecting the line - for example checking if the next line contains ]: ERROR: string:
found_line = None  # store for our matched line
with open("input.log", "r") as f:  # open your log file
    for line in f:  # read it line by line
        if line.rstrip()[-14:] == "_____GP D_____":  # if a line ends with our string...
            found_line = next(f).rstrip()  # grab the next line as our potential candidate
            if next(f).find("]: ERROR:") != -1:  # if the next line contains an error marker
                break  # match found, break out as we don't need to search any more...
            else:  # the next line wasn't an error...
                found_line = None  # ... reset the potential result and continue searching

However, since your found_line would actually contain the whole line (including the timestamp), you need to first strip that out, and that all depends on how your logger is set. A reasonable way, based on your data is to skip the first 39 characters (<date-time> smth.com pgp:) and pick up everything after the next colon, assuming that the number in the following brackets can change (if not - you can just strip out the first n characters and be done with it):
if found_line:
    found_line = found_line[found_line.find(":", 39) + 1:].strip()

Beware, tho, that the 'error' check might fail if some of the logged data contains that exact pattern - if you want to hone in on it you can try using the similar technique that we use to lift the JSON out of the log line and check if it begins with ERROR:.
You should also try doing things on your own instead of blindly copying code from SO - you won't learn much this way.

A: Using a generator function:
def getjson (f):
    for line in filter(lambda x: '_GP D_' in x, f):
        line1 = next(f)
        line2 = next(f).split(' ', 4)
        if line2[4].startswith('ERROR'):
            yield line1.rstrip().split(' ', 4)[4]

with open('input.log', 'r') as f:
    for json in getjson(f):
        print(json)

One of the interest of the generator is that it will catch an eventual stopIteration exception caused by next() (for example when there are less than 2 lines after the line with _G PD_.) and stop.
Note that this approach assumes that _G PD_ lines are separated by at least two lines.


text:
Q: How can I know in the linux terminal how many physical disks a server has installed? i need get how many physical disks have my server.
I tried fdisk -l but I do not get the full features of the disk

A: df -h command will list the disks mounted, their mount point, size, used and available space.