text:
Q: Find volume bounded by two cylinders using triple integration Given $x^2+y^2=2ay$ and $z^2=2ay$. I tried to use cylindrical  corordinated but unable to solve the integral

A: I will assume that $a>0$. Then $x^2+y^2=2ay\iff x^2+(y-a)^2=a^2$ and therefore $y\in[0,2a]$. In particular, $y\geqslant0$.
In cylindrical coordinates, you have $r^2=z^2=2ar\sin\theta$. Besides $\theta\in[0,\pi]$, since $y\geqslant0$. So, one needs to compute the triple integral$$\int_0^\pi\int_0^{2a\sin\theta}\int_{-\sqrt{2ar\sin\theta}}^{\sqrt{2ar\sin\theta}}r\,\mathrm dz\,\mathrm dr\,\mathrm d\theta.$$It turns out that\begin{align}\int_0^\pi\int_0^{2a\sin\theta}\int_{-\sqrt{2ar\sin\theta}}^{\sqrt{2ar\sin\theta}}r\,\mathrm dz\,\mathrm dr\,\mathrm d\theta&=\int_0^\pi\int_0^{2a\sin\theta}2\sqrt2r^{\frac32}\sqrt{a\sin\theta}\,\mathrm dr\,\mathrm d\theta\\&=\int_0^\pi\frac{32}5a^3\sin^3\theta\,\mathrm d\theta\\&=\frac{128}{15}a^3.\end{align}


text:
Q: How to find the wireless MAC address (aka BSSID) of any wireless access point I have aircrack-ng 1.2 beta 3 and I wanted to know how I can find the wireless MAC address (aka BSSID) of any wireless access point with aircrack-ng (or any other program).
I am currently running Ubuntu 14.10.

A: Use iw device scan to show all information about currently visible networks. The output has more than an entire screenful per network, so use grep to trim it down:
$ sudo iw wlan0 scan | egrep "^BSS|SSID:"
BSS 24:a4:3c:9e:d2:84(on wlan0) -- associated
    SSID: eduroam
BSS 24:a4:3c:ae:df:83(on wlan0)
    SSID: Example multi-AP network
BSS dc:9f:db:30:c1:7a(on wlan0)
    SSID: Example multi-AP network
BSS 00:19:3b:99:e2:80(on wlan0)
    SSID: TEO Wi-Fi

For some very old Wi-Fi card drivers, you'll need the iwlist device scan tool instead:
$ sudo iwlist wlan0 scan | egrep "Address:|ESSID:"
          Cell 01 - Address: 24:A4:3C:9E:D2:84
                    ESSID:"eduroam"
          Cell 02 - Address: 24:A4:3C:AE:DF:83
                    ESSID:"Example multi-AP network"
          Cell 03 - Address: DC:9F:DB:30:C1:7A
                    ESSID:"Example multi-AP network"
          Cell 04 - Address: 24:A4:3C:9E:D2:16
                    ESSID:"Example multi-AP network"

Aircrack also comes with the airodump-ng tool which repeatedly shows all networks it sees. (You need to enable monitor mode first, using airmon-ng.)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Django / DRF: annotate a model with extra (computed) information I'm adding a very simple roadmap voting feature to my website, where people can add feature requests, and people can then vote on each other's suggestions. The basics are pretty simple:
# models.py
class FeatureRequest(models.Model):
    title = models.CharField(max_length=50)
    description = models.TextField()
    author = models.ForeignKey(User, editable=False, on_delete=models.CASCADE)
    is_implemented = models.BooleanField(default=False, editable=False, db_index=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

class Vote(models.Model):
    feature = models.ForeignKey(FeatureRequest, editable=False, on_delete=models.CASCADE)
    user = models.ForeignKey(User, editable=False, on_delete=models.CASCADE)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        unique_together = ["feature", "user"]

#views.py
class RoadmapController(viewsets.ModelViewSet):
    permission_classes = (AuthorOrReadOnlyPermission,)
    serializer_class = FeatureRequestSerializer

    def get_queryset(self):
        return FeatureRequest.objects.filter(is_implemented=False)

    def perform_create(self, serializer):
        return serializer.save(author=self.request.user)

# serializers.py
class FeatureRequestSerializer(serializers.ModelSerializer):
    class Meta:
        model = FeatureRequest
        fields = "__all__"

There is also a separate view for actually creating and deleting votes, but that's not needed here for my question.
What I want is that the response of the feature request list includes the number of votes for each one, and a boolean if the logged-in user has voted for it:
[
  {
    "title": "This is a feature request",
    "description": "Foo bar",
    "author": 1,
    "number_of_votes": 1,
    "has_my_vote": true
  }
]

I already figured out that I can change my queryset to FeatureRequest.objects.filter(is_implemented=False).annotate(number_of_votes=Count("vote")), add number_of_votes = serializers.ReadOnlyField() to the serializer, and the number of votes is visible. Is that the best way? It adds a query for each feature request I would assume.
But most of all, I don't know how to add that "has_my_vote" boolean to the result (and how to keep that performant, of course).

A: After some trial and error, I came up with this:
    def get_queryset(self):
        return (
            FeatureRequest.objects.filter(is_implemented=False)
            .annotate(number_of_votes=Count("vote"))
            .annotate(has_my_vote=Exists(Vote.objects.filter(feature=OuterRef("pk"), user=self.request.user)))
        )

That works, and it only does one query instead of one plus one or two per feature request.


text:
Q: asymptotic curve, line of curvature and planar curve I met a problem to prove or disprove that:
a. If a curve is both an asymptotic curve and a line of curvature, then it must be planar.
b. If a curve is planar and an asymptotic curve, then it must be a line.
For a, I show that the derivative of the shape operator along the curve is 0 and concluding that it is true, although I am not fully convinced by my argument. However, for b, I am totally off.
This question is different from Geodesics and Curves on a Plane. The condition here is asymptotic, line of curvature and planar, but not geodesic. Please carefully reading the questions.


text:
Q: Powers of 2 above and below input I have the programming reading in middle just fine however using the pointer with below and above is not giving the correct value to be found using middle.
Why is below (most likely above as well) negative when running in the for loop?
Am I calling using pointers in the correct way?
/*
 *
 *Function pwrTwo has one parameter "middle" it reads the inout from the user
 *to find below and above
 *
 *the function is used to find the highest power of two below middle
 *and the lowest power of two above middle
 *
 *The function then returns the two values and they are printed in the
 * the main function displayed as below<middle<above
 *
 */

#include <stdio.h>

int pwrTwo(int m, int*above, int*below) {

  int i = 0;
  *above = 0;
  *below = 0;

  for (i = 2; *below < m; i += 1) {
    *below = pow(2, i);
    printf("%d,%d,%d\n", below, m, i); //my check to see if below middle and i are correct
  }

  for (i += 3; *above > m; i -= 1) {
    *above = pow(2, i);
    printf("%d,%d,%d\n", below, m, above); // checking again
  }

  return;
}

int main() {

  int middle = 1;
  int above = 0;
  int below = 0;

  while (middle > 0) {
    printf("Please input a value:");
    scanf("%d", &middle);
    pwrTwo(middle, &above, &below);
    printf("%d<%d<%d\n", below, middle, above);
  }
}

A: You need to include  to use pow function
Since you are getting the values in the parameters, your return type should be void,
and you dont need to use pointers in this case, you want just one value for below, and one for above, so you just use a int..but...
you can work with this:
void pwrTwo(int m, int*above,int*below){
double log2m = log2(m);
*below = pow(2,floor(log2m));
*above = pow(2,ceil(log2m));
}

A: You are using printf with an int* instead of in an int. I am surprised your compiler did not give you warnings, since my compiler gives me warnings about this.
When you print a pointer as an int, you will get a negative number if the sign bit happens to be set for the address it stores.
Try changing
printf("%d,%d,%d\n",below,m,i)

to
printf("%d,%d,%d\n",*below,m,i)

as well as changing printf("%d,%d,%d\n",below,m,above) to printf("%d,%d,%d\n",*below,m,*above).

A: #3 is the main issue.
1) Missing #include <math.h>
2) Mis-matched return.  Change from
int pwrTwo(int m, int*above, int*below) {
  ...
  return;
}

to
void pwrTwo(int m, int*above, int*below) {
  ...
  // return;
}

3) Wrong types in printf()
// printf("%d,%d,%d\n", below, m, i);
printf("%d,%d,%d\n", *below, m, i);
...
// printf("%d,%d,%d\n", below, m, above);
printf("%d,%d,%d\n", *below, m, *above);
...

4) Good idea to check return value from scanf()
// scanf("%d", &middle);
if (scanf("%d", &middle) != 1) Handle_Error();

5) Code may simplify.  Watch out for range errors.
// some_int = pow(2, i);
some_int = 1 << i;


text:
Q: Argument of \pgfmath@dimen@@ has an extra } Using TikZ and pgf versions v3.1.9a (3.1.9a), I tried to compile the following code
\documentclass[tikz,border=5]{standalone}
\usetikzlibrary{trees,mindmap}
\tikzset{grow cyclic list/.code={%
  \def\tikzgrowthpositions{{#1}}%
  \foreach \n [count=\i,remember=\i]in {#1}{}%
  \let\tikzgrowthpositionscount=\i%
  \tikzset{growth function=\tikzgrowcycliclist}}}
\def\tikzgrowcycliclist{%
  \pgftransformshift{%
    \pgfpointpolar{\tikzgrowthpositions[mod(\the\tikznumberofcurrentchild-1,\tikzgrowthpositionscount)]}%
      {\the\tikzleveldistance}}}
\begin{document}
\begin{tikzpicture}[small mindmap, concept color=blue!20,
  every child node/.style={concept}]
\node [concept] (languages)
  {O} [grow cyclic list={90,0,-45,210}]
    child { node {A} }
    child { node {B} }
    child { node {C}
      [clockwise from=0, sibling angle=45]
      child { node {C1} }
      child { node {C1} }
      child { node {C1} }
    }
    child { node {D} };
\end{tikzpicture}
\end{document}

which is a part of the Mark Wibrow's answer here. But it throws the following error:

Argument of \pgfmath@dimen@@ has an extra }. ^^Ichild { node {D} };

Does anybody know how to resolve it?

A: The problem is that the old answer exploited a misfeature of \foreach that has been since fixed.
What happened was that the "count" that was "remembered" was still available at the end of \foreach, but this is wrong: you'd clobber the meaning of \i in your case. And if you had an accented "î" in some node…
There's a much easier way to count elements of a list:
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{trees,mindmap}

\ExplSyntaxOn
\cs_set_eq:NN \clistcount \clist_count:n
\ExplSyntaxOff

\tikzset{
  grow cyclic list/.code={%
    \def\tikzgrowthpositions{{#1}}%
%    \foreach \n [count=\i,remember=\i]in {#1}{\global\let\tikzgrowthpositionscount=\i}%
    \edef\tikzgrowthpositionscount{\clistcount{#1}}%
    \tikzset{growth function=\tikzgrowcycliclist}
  }
}

\def\tikzgrowcycliclist{%
  \pgftransformshift{%
    \pgfpointpolar{%
      \tikzgrowthpositions[mod(\the\tikznumberofcurrentchild-1,\tikzgrowthpositionscount)]%
    }%
    {\the\tikzleveldistance}
  }%
}

\begin{document}

\begin{tikzpicture}[
  small mindmap,
  concept color=blue!20,
  every child node/.style={concept}
]
\node [concept] (languages)
  {O} [grow cyclic list={90,0,-45,210}]
    child { node {A} }
    child { node {B} }
    child { node {C}
      [clockwise from=0, sibling angle=45]
      child { node {C1} }
      child { node {C1} }
      child { node {C1} }
    }
    child { node {D} };
\end{tikzpicture}

\end{document}

I left commented the alternative \foreach method, but my suggestion is much more efficient.
For a "pure TikZ" solution
\tikzset{
  grow cyclic list/.code={%
    \def\tikzgrowthpositions{{#1}}%
    \pgfmathsetmacro\tikzgrowthpositionscount{dim({#1})}%
    \tikzset{growth function=\tikzgrowcycliclist}
  }
}

A: I would think that \tikzgrowthpositionscount needs to be set inside the \foreach loop and it should be made global to be accessible outside the loop. The remember option only stores the last item value, but it does not make the variable accessible outside the for loop (might have been changed at some point in time).
\documentclass[tikz,border=5]{standalone}
\usetikzlibrary{trees,mindmap,calc}
\tikzset{grow cyclic list/.code={%
  \def\tikzgrowthpositions{{#1}}%
  \foreach \n [count=\i]in {#1}{%
    \global\let\tikzgrowthpositionscount=\i%
  }%
  \tikzset{growth function=\tikzgrowcycliclist}}}
\def\tikzgrowcycliclist{%
  \pgftransformshift{%
    \pgfpointpolar{\tikzgrowthpositions[mod(\the\tikznumberofcurrentchild-1,\tikzgrowthpositionscount)]}%
      {\the\tikzleveldistance}}}
\begin{document}
\begin{tikzpicture}[small mindmap, concept color=blue!20,
  every child node/.style={concept}]
\node [concept] (languages)
  {O} [grow cyclic list={90,0,-45,210}]
    child { node {A} }
    child { node {B} }
    child { node {C}
      [clockwise from=0, sibling angle=45]
      child { node {C1} }
      child { node {C1} }
      child { node {C1} }
    }
    child { node {D} };
\end{tikzpicture}
\end{document}


text:
Q: Как в Django добавить CKEditor в форму на странице? Всем привет.
В интернете решения не нашел.
В админке CKEditor работает:

Но в форме его нет:

models.py

class Post(models.Model):
    post_title = models.CharField(max_length=250, verbose_name='Заголовок')
    post_content = RichTextField(max_length=450000, verbose_name='Содержание', default='test')

forms.py

class PostForm(forms.ModelForm):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['cat'].empty_label = 'категория не выбрана'

    captcha = CaptchaField()

    class Meta:
        model = Post
        fields = ['post_title', 'post_content']

    def clean_post_title(self):
        post_title = self.cleaned_data['post_title']
        if len(post_title) >= 250:
            raise ValidationError('Длина превышает 250 символов')

        return post_title

views.py

class FormAdd(View):

    def get(self, request):
        form = PostForm
        return render(request, 'sitelogic/addpost.html', context={'form': form})

        def post(self, request):
        request_keep = PostForm(request.POST, request.FILES)
        if request_keep.is_valid():
            request_keep.save()
            return redirect('home_page')
        return render(request, 'sitelogic/addpost.html', context={'form': request_keep})

addpost.html

    <form action="{% url 'add_post' %}" method="post" enctype="multipart/form-data">
        {% csrf_token %}
        {{ form.as_p }}
        <button type="submit">добавить</button>
    </form>

P.S: Ссылка на CKEditor https://django-ckeditor.readthedocs.io/en/latest/

A: В ModelForm:
post_content = forms.CharField(widget=CKEditorWidget())

В templates:
<form>
    {{ myform.media }}
    {{ myform.as_p }}
    <input type="submit"/>
</form>


text:
Q: Workflow failed to get user profile for user when using SharePoint Designer- Just some particular users When running send email activity in SharePoint Designer 2010 - Data Source: User Profiles, I see that some users get "Workflow failed to get user profile for user" while others are just fine.
I also noticed when i click on their names on a list e.g the name column some users get to the
_layouts/userdisp.aspx?ID=3 page

and some to the mySite
/my/Person.aspx?accountname=Domain\username

The user that i get the error with gets to see only the _layouts/userdisp.aspx?ID=SomeID page
Is this an issue with the Activity or SharePoint
thanks in advance.

A: Few months back I too faced same kind of issues, where the newly added users in the Active Directory were not getting the notification emails. It was because the users in the active directory should be added in the Site Collection also, so that the workflow can fetch the email ID of the users and send mail. To bring in all the users from Active Directory to your web application, you have to configure the User Profile Synchronization in the Central Administrator.
Please configure the below in the sharepoint server,
1.Configure User profile Synchronization.

REF:
  http://technet.microsoft.com/en-us/library/ee721049(v=office.14).aspx

1.1 Once after configuring, you need to set up a Timer Job which keeps the SharePoint 2010 Server in sync with the Active Directory, Schedule User profile Synchronization.

REF:
  http://technet.microsoft.com/en-us/library/ee890103(v=office.14).aspx

Once after the above configuration, we can also create a Windows task Scheduler to run the Synchronization code in a daily basis (same like #2), to do that please follow the below link.

REF :
  http://gallery.technet.microsoft.com/office/Sync-user-information-in-d1b9aed5


text:
Q: how to Run an external vbs file for particular excel file I have written a vbs code as
Sub rectangle()
    With ActiveSheet.Shapes.AddShape(msoShapeRectangle, 10, 10, 200, 100).TextFrame
        .Characters.Text = "This is a rectangle"
        .HorizontalAlignment = xlHAlignCenter
        .VerticalAlignment = xlVAlignCenter
        ChDir "D:"
        ActiveWorkbook.SaveAs Filename:="D:\Book.xls", _
        FileFormat:=xlOpenXMLWorkbookMacroEnabled, CreateBackup:=False
        ActiveWorkbook.Save
    End With
    ActiveWorkbook.Save
    Range("F5").Select
End Sub

but am getting error as
script: D:\test.vbs
Line: 10
Char: 36
Error: Expected statement
Code: 800A0400
Source: Microsoft VBscript Compilation error

I have pasted the excel file and vb file in D drive. can anyone correct me ?

A: This is how I would do in a .vbs file.
Const xlHAlignCenter = -4108
Const xlVAlignCenter = -4108
Const xlOpenXMLWorkbookMacroEnabled = 52
Const msoShapeRectangle = 1

Dim oXLApp, oXLWB, oXLWs

Set oXLApp = CreateObject("Excel.Application")

'<~~ I am adding a new workbook for demonstration purpose.
'<~~ You can open one if you want
Set oXLWB = oXLApp.Workbooks.Add
Set oXLWs = oXLWB.Sheets("Sheet1")

oXLApp.Visible = True

With oXLWs
    With .Shapes.AddShape(msoShapeRectangle, 10, 10, 200, 100).TextFrame

        .Characters.Text = "This is a rectangle"
        .HorizontalAlignment = xlHAlignCenter
        .VerticalAlignment = xlVAlignCenter

    End With
End With

oXLWB.SaveAs "D:\Book.xls", xlOpenXMLWorkbookMacroEnabled, , , , False


text:
Q: Struggling with VLOOKUP, INDEX and MATCH in Excel I have a small spreadsheet that is intended to display current freight costs per shipping merchant, by shipping port and by office location.
I also have a smaller summary table that displays per shipping port, the cheapest rate, the merchant offering it, and the location to which it applies.
The main table is administered by our end-users, but the smaller table should update itself based on the end-user's inputs.

The values in the red box are how it should look. I have managed to display the lowest rate in its row by using AGGREGATE.
But I cannot work out how to insert the corresponding depot and merchant into the summary in the same way.
I've tried various combinations of INDEX, MATCH, VLOOKUP and HLOOKUP without success - it usually ends up with a circular reference somewhere.
L

A: Perhaps you could try using functions like INDEX() instead of using volatile functions.
A friendly suggestion

OFFSET() is a flexible function and it can point to a
different-sized range that is calculated on-the-fly. It is a
volatile function. If you go to a completely unrelated cell and enter a number, all of the OFFSET() functions will calculate—even if
that cell has nothing to do with.
It has been found, Excel is very careful to spend time calculating
the cells that needs to be calculated. But once you use the
OFFSET(), all of the OFFSET() cells, plus everything downline from
the OFFSET(), starts calculating after every change in the
worksheet.
Why it matters ? INDEX() is not volatile. You enjoy all of the
flexible goodness of OFFSET() without the time-sucking recalculations over and over.

Here is shown below, what you can try:

Getting the MIN values.
• Formula used in cell AB7
=AGGREGATE(15,6,(Q7:Z7)/ISNUMBER(Q7:Z7),1)

Note: I have used 15 which refers to SMALL instead of 5 with an ISNUMBER() Function which ignores all the text values as well as #N/A() as well. Thus, giving the Minimum values of each office location.

Getting the Merchant Name,
• Formula used in cell AC7
=INDEX(Q7:Z7,,MATCH(AB7,Q7:Z7,0)+1)

Note: The MATCH() returns the relative position of the MIN value column wise, and to get the Merchant we are simply adding 1 to it, and wrapping the whole within INDEX().

Getting the Depot Name
• Formula used in cell AD7
=INDEX($Q$5:$Z$5,,MATCH(AB7,Q7:Z7,0))

Note: Same as above the MATCH() returns the min value position, and then we are wrapping it within INDEX() to get DEPOT for the respective MIN
values.
Also, here for the Depot cells I have not used Merge & Center instead have used the Alignment as Center Across Selection, that way it much easier to use a formula and not resorting to complicated ones. Avoid using Merge & Center .

Note: All the above formulas used, you need to fill down, and it has been assumed you may not have duplicate Min values. If you get duplicate values for Rates then the formulas for Merchant & Depot will change.

A: You can use INDEX/MATCH wrapped with OFFSET to help you achieve this. This is assuming that merchants are never numeric.
Cell M3 (min) formula:
=MIN(B3:J3)

Cell N3 (merchant) formula, which locates the min(rate) in that row and returns the value 1 column to the right of it:
=OFFSET(INDEX(B3:K3,MATCH(MIN(B3:K3),B3:K3,0)),,1)

Cell O3 (depot) formula, which locates the min(rate) in that row and returns the first row in that column. Or more precisely, x-nbr of rows above it.
=OFFSET(INDEX(B3:K3,MATCH(MIN(B3:K3),B3:K3,0)),-ROW(A2),)


text:
Q: How do I capture screenshots of browser using JavaScript? I don't want to take a capture of the site ,I need to take a picture of the full screen like this:
exemple

A: To do what you want, we can take advantage of the WebRTC features and APIs that modern browsers supports. It allow devloppers to get user media (webcam) without using flash that is no more supported, and to share user's screen. It's the later that we want to use.
Requirements
The given solution will work on browsers that supports WebRTC (newest Chrome, Firefox, Edge and Opera will work for sure).
As for any WebRTC feature, you MUST work on an HTTPS page. Even for local development. Without https, the features will be disabled and your browser will prompt an error in the console. For security sakes, using it into Iframes can be tricky. For instance, a code snippet on stackoverflow will not work because of same origin policy.
Obviously, the user must explicitly give it's permission and will have to choose the screen that he wants to share and even if he wants to share only a window, a browser tab (inner document only) or the full screen. You can't overcome that decision, it only belong to the user.
For more infos, see this Screen Capture API documentation on MDN
A working demo
So, since we can get the real-time user's screen as a stream, the idea is to attach this stream to a video, and then capture a video frame into a canvas. From a canva, you can get all the data you need. Send it to a server, create a Blob and allow your user to download it or whatever.

<html lang="en">
    <body>
        <video id="video" style="display:none;" autoplay></video>
        <canvas id="screenshot" width="600px" height="400px"></canvas>
        <button id="capture">Take screenshot</button>

        <script>
            const videoElem = document.getElementById("video");
            const canvas = document.getElementById("screenshot");
            const context = canvas.getContext('2d');

            //We don't want the audio, and we want to see the user's cursor
            const displayMediaOptions = {
                video: {
                    cursor: "always"
                },
                audio: false
            };

            async function takeScreenshot() {
                try {
                    //There, we get a full screen capture in real time using the WebRTC API.
                    //And we set the video source with the stream in srcObject.
                    videoElem.srcObject = await navigator.mediaDevices.getDisplayMedia(
                        displayMediaOptions
                    );

                } catch(err) {
                    console.error("Error: " + err, err);
                }
            }

            //We want to take our screenshot when our stream is ready
            videoElem.addEventListener('playing', () => {

                //If we are too fast, we will get the browser-prompted window
                //in the screenshot, so we add a little delay.
                setTimeout(() => {
                    context.drawImage(videoElem, 0, 0, canvas.width, canvas.height);
                    //We got our screenshot, we can stop to capture the user's screen
                    let tracks = videoElem.srcObject.getTracks();

                    tracks.forEach(track => track.stop());
                    videoElem.srcObject = null;
                    video.pause();
                }, 500);
            });

            document.getElementById('capture').addEventListener('click', takeScreenshot);
        </script>
    </body>
</html>

It's the simplest way to do it. It's not perfect and there is room for improvment, but you should get the idea.

A: This is out of scope of the browser, it's only possible for it to capture within the browser boundaries only. This is safety measurements by design. You might however be able to find an extension that does that for you.


text:
Q: Angular : Fetch value of textbox onclick of button I want to print the value of textbox when i click of button. But it throws nullpointerexception. I also need to keep some value in the textbox i dont understand why?. Whatever i type in textbox and when i click on buttom i need to print the value of textbox What is the issue?
Below is my code:
ts file
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-mypage',
  templateUrl: './mypage.component.html',
  styleUrls: ['./mypage.component.scss']
})
export class mypageComponent implements OnInit {

  constructor(private router: Router) {

  }

  ngOnInit() {
  }

  myFunc() {

      var num1 = ((document.getElementById("exchageRateDate") as HTMLInputElement).value);
      console.log(num1);
  }

}

HTML File

Welcome.

Place - <input type="text" value="Sydney" ng-model="placeId" />
<button (click)="myFunc(placeId)" formtarget="_blank">Test</button>

Error:
ERROR TypeError: Cannot read property 'value' of null

A: You need to set id of input tag remove ng-model because it's a angularjs(1.x.x) not angular(2/4/5/6/7/8)
In html

Welcome.

 Place - <input id="exchageRateDate" type="text" value="Sydney"  />
 <button (click)="myFunc()" formtarget="_blank">Test</button>

In typescript:
myFunc() {
    var num1 = ((document.getElementById("exchageRateDate") as HTMLInputElement).value);
    console.log(num1);
}

Here is working example: Get value of input tag using HTMLInputElement

A: Seems like you forgot to add id in input field
<input id="exchageRateDate" type="text" value="Sydney" ng-model="placeId" />

Edit: Angular way to do it
As you are using Angular so I will suggest you a better way to do this using NgModel
Try this

Welcome.

Place - <input type="text" value="Sydney" [(ngModel)]="placeId" />
<button (click)="myFunc(placeId)" formtarget="_blank">Test</button>

In component:
myFunc(num1) {
  console.log(num1);//here you will get input value through ng-model
}

A: <input type="text" class="textbox" id="Summary" name="Summary"placeholder="Summary" value="{{Item.summary}}">
(document.getElementById("Summary") as HTMLInputElement).value;


text:
Q: PHP: Count amount of times specific value shows in RSS feed I am working with the Met Office RSS feed:
$metourl = "http://www.metoffice.gov.uk/public/data/PWSCache/WarningsRSS/Region/UK";
$metoxml = simplexml_load_file($metourl);
$count = $metoxml->channel->item;

I can easily establish if there are any "weather warnings" (in this case):
if($count && $count->count() >= 1){

What I want to do, if possible, is to count how many times 'YELLOW', or 'RED' warnings occur under
$metoxml->channel->item->warningLevel

so I can then echo that?
E.g. "There are x yellow and x red warnings.".
Thank you!

A: You can use the xpath method:
$metourl = "http://www.metoffice.gov.uk/public/data/PWSCache/WarningsRSS/Region/UK";
$metoxml = simplexml_load_file($metourl);
$metoxml->registerXpathNamespace('metadata',
  'http://metoffice.gov.uk/nswws/module/metadata/1.0');
$wl = $metoxml->xpath('//channel/item/metadata:warningLevel');

$counters = [ 'YELLOW' => 0, 'RED' => 0 ];

foreach ($wl as $e) {
  $str = trim((string)$e);
  if ($str === 'YELLOW')
    $counters['YELLOW']++;
  elseif ($str === 'RED')
    $counters['RED']++;
}

printf('There are %d yellow and %d red warnings.',
  $counters['YELLOW'], $counters['RED']);

Sample Output
There are 14 yellow and 0 red warnings.


text:
Q: Rails 3.2 has_one with conditions always places foreign_key into where clause I have a has_one relationship setup with conditions => proc {["test_column = 10"]} and it always puts primary_key = 1 in with the conditional statement giving me incorrect results. How can I create a has_one relationship with a custom set of conditions that will not have the current models key in it?
has_many testers,
  :class_name => "testers",
  :conditions => proc {["test_column = 10"]}

I am using Rails 3.2.12

A: If you want to put the condition in the the has_one association, please find the below code.
has_one tester, :conditions => "testers.test_column = 10"

You can refer to
http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html


text:
Q: The "RazorGenerate" task was not found. Trying to run a Blazor project in a Rider IDE and always get this error. What's wrong? I'm trying to run a Blazor Solution in my Rider IDE.
I'm currently using the SDK 3.0.100-preview3-010431 at the time of writing this and I'm also hyper new to razor pages.
After the projects are loaded, the [MySilyProject].Client solution issues a warning:
Project '[MySilyProject].Client' load finished with warnings: The "RazorGenerate" task was not found. Check the following: 1.) The name of the task in the project file is the same as the name of the task class. 2.) The task class is "public" and implements the Microsoft.Build.Framework.ITask interface. 3.) The task is correctly declared with  in the project file, or in the *.tasks files located in the "C:\Program Files\dotnet\sdk\3.0.100-preview3-010431" directory. at (93:5)
I cannot proceed because of this and Blazor pages aren't compiled or executed.
This is the reason for the build failure:
  Microsoft.NET.Sdk.Razor.Component.targets(93, 5): [MSB4036] The "RazorGenerate" task was not found. Check the following: 1.) The name of the task in the project file is the same as the name of the task class. 2.) The task class is "public" and implements the Microsoft.Build.Framework.ITask interface. 3.) The task is correctly declared with  in the project file, or in the *.tasks files located in the "C:\Program Files\dotnet\sdk\3.0.100-preview3-010431" directory.
I downloaded .vsix file from the VS Marketplace (https://marketplace.visualstudio.com/items?itemName=DavidEbbo.RazorGenerator), but the file doesn't recognize the jetbrains IDE.
In the IDE, I tried running the file haphazardly from my IDE, but nothing happened. Tbh, I don't know if I went through this route appropriately
Also went through NuGet: tried Microsoft.AspNet.Razor(3.2.7) and RazorGenerator.Mvc(2.4.9). Warning still persists, and the pages aren't executed
What did I do wrong? Please help?

A: Check that you have matching version for MVC and for Blazor files. Make sure that you do not include Microsoft.AspNetCore.Razor.Design package.


text:
Q: Eclipse Does Not Download All Plugins From A p2 Repository I have been given an RCP application to build in eclipse. I was also provided with a list of p2 repository locations (on Nexus repo manager). When I try to build a target platform (or install the repos as new software in Eclipse) I notice that the Eclipse does not fetch all the plugins in a p2 repo.
I can visit the p2 repo site. I can see the repo structure with the content.xml/jar and artifacts.xml/jar, with plugins and features folders
The structure of the repo:

There are a lot of plugins in the plugins folder but when this site is installed as a new software in Eclipse (or added to a target platform) there are just a few of them downloaded.
I can find the reference to missing plugins in the artifact.xml and content.xml (and I cannot see any difference between those that have been fetched)
What could be wrong?


text:
Q: How to set Empty View for FragmentActivity? I want to set an empty view / show a text in the middle of the ViewPager when there are no screens on a FragmentActivity. I could use getCount() with the mPagerAdapter and add a fragment with a layout with the empty string but it seems like an overkill.
I'd like to know if there is a better option. I think setEmptyView() is made for this cases but I haven't been able to implement it. I just want to show a string with a hint of how to add screens to the ViewPager for my users.
How can it be done?
This is what I'm doing now:
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mPager = (ViewPager) findViewById(R.id.pager);
    mPagerAdapter = new PagerAdapter(getSupportFragmentManager());
    //...
    if(mPagerAdapter.getCount() == 0)
    {
        setContentView(R.layout.fragment_screen_empty);
    }

A: My current implementation:
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mPager = (ViewPager) findViewById(R.id.pager);
    mPagerAdapter = new PagerAdapter(getSupportFragmentManager());
    //...
    if(mPagerAdapter.getCount() == 0)
    {
        setContentView(R.layout.fragment_screen_empty);
    }


text:
Q: Not able to Format USB from all possibilities

I have a Sandisk Pendrive of 16GB. Unfortunately, I filled the pen drive full except for 0.98 GB free space. Now when I am trying to use that USB drive in my PC, it is just loading and then I get an error saying something like "USB not recognized".
I also used the command format F: to format the USB drive.
I even tried to uninstall the drive from devmgmt.msc and also drivers got updated. I am still facing the issue.
I also tried disk part. When I search for disks using list disk it takes a long time and giving error as virtual disk service error.

A: The delay when you do a list disk in diskpart is very telling. It indicates that Windows has problems trying to talk to the controller chip inside the stick.
Conclusion: That USB stick is broken. Throw it away.

A: You can try Transcend's RecoveRx software available on official transcend website. I think it will definitely work.


text:
Q: Hadoop program compile without hadoop install How can I compile an hadoop example program(ex. word count) without hadoop install?
I am planning to run my program on Amazon EMR, so I don't need to run my program on my local machine.

A: You need to add the hadoop and map reduce client jar to your class path.
For example, these two should get the wordcount example to compile

hadoop-common-2.2.0.jar
hadoop-mapreduce-client-core-2.2.0.jar

hadoop-common has the org.apache.hadoop.io package you'll need for your XxxWritable, Text classes and such. hadoop-mapreduce-client-core has the org.apache.hadoop.mapreduce you'll need for your map reduce program (Mapper, Reducer) and some basic classes for your job. I've never used Amazon EMR so I don't know how it works, and don't know if you need other jars packaged or not (or if you need an specific version). But these will get a simple map reduce program to compile.
If you're using maven, you can get these dependencies
<dependency>
    <groupId>org.apache.hadoop</groupId>
    <artifactId>hadoop-common</artifactId>
    <version>2.2.0</version>
</dependency>
<dependency>
    <groupId>org.apache.hadoop</groupId>
    <artifactId>hadoop-mapreduce-client-core</artifactId>
    <version>2.2.0</version>
</dependency>


text:
Q: jQuery validate non english letters
I need a custom validation method for jquery.validate plugin, which allows me to type only letter and special characters like üõöä.
Right now I have a custom method, which allows me to  type only letters without special characters.
jQuery.validator.addMethod("letters", function(value, element)
{
    return this.optional(element) || /^[a-z ]+$/i.test(value);
}, "Please enter a letters only.");

A: In order to test for BOTH english AND non-english letters you can use this regex:
([^\x00-\x7F]|[a-zA-Z])

It will test for letters that are NOT in the range of a-zA-Z or letters in that range.
This is the within the jQuery validator:
jQuery.validator.addMethod("letters", function(value, element)
{
    return this.optional(element) || /^([^\x00-\x7F]|[a-zA-Z])+$/i.test(value);
}, "Please enter a letters only.");

Another option - if you want to use a specific set of chars to allowed:
jQuery.validator.addMethod("letters", function(value, element)
{
    return this.optional(element) || /^([a-zA-ZÆÐƎƏƐƔIJŊŒẞÞǷȜæðǝəɛɣijŋœĸſßþƿȝĄƁÇĐƊĘĦĮƘŁØƠŞȘŢȚŦŲƯY̨Ƴąɓçđɗęħįƙłøơşșţțŧųưy̨ƴÁÀÂÄǍĂĀÃÅǺĄÆǼǢƁĆĊĈČÇĎḌĐƊÐÉÈĖÊËĚĔĒĘẸƎƏƐĠĜǦĞĢƔáàâäǎăāãåǻąæǽǣɓćċĉčçďḍđɗðéèėêëěĕēęẹǝəɛġĝǧğģɣĤḤĦIÍÌİÎÏǏĬĪĨĮỊIJĴĶƘĹĻŁĽĿNŃN̈ŇÑŅŊÓÒÔÖǑŎŌÕŐỌØǾƠŒĥḥħıíìiîïǐĭīĩįịijĵķƙĸĺļłľŀ'nńn̈ňñņŋóòôöǒŏōõőọøǿơœŔŘŖŚŜŠŞȘṢẞŤŢṬŦÞÚÙÛÜǓŬŪŨŰŮŲỤƯẂẀŴẄǷÝỲŶŸȲỸƳŹŻŽẒŕřŗſśŝšşșṣßťţṭŧþúùûüǔŭūũűůųụưẃẁŵẅƿýỳŷÿȳỹƴźżžẓ])+$/i.test(value);
}, "Please enter a letters only.");


text:
Q: Difference Integration results from mathematica.
N[Integrate[.]] gives me a quite large number while NItegrate[.] gives me a small one. According to plot of integrand, it seems the numerical integration is more reasonable. However, can anyone explain what's the problem here? Thanks!

A: I think that you could ask the question at https://mathematica.stackexchange.com/.
This seems to be related to accuracy issues since the explicit formula in terms of $x$ is correct but for $x=100$, the result is
$$-\frac{18004190799729005916153364606626760}{9009}+$$ $$99920027994400699944002799920001
   \log \left(\frac{101}{99}\right)$$ which does not look simple (on my side, I gave up).
Computing each piece separately to $50$ significant decimals, I effectively obtained $0.0059908$.
Edit
In fact, problems happen even for quite small values of $x$. We even can get negative values for the integral. For example, using $x=11$, the result is given as $\color{red}{-1.00000}$ while it corresponds to
$$42998169600000000 \log \left(\frac{6}{5}\right)-\frac{32102724739022409728}{4095}$$ Doing the same as above, this is $0.0544852$ which is exactly the value obtained using numerical integration.

A: I second Claude Leibovici's answer by providing the following computation using Mathematica 11

As you see, specifying the tolerance does give a correct numerical result. So it seems that there is an issue with N[] function without second argument.


text:
Q: can we override start field with custom fields in event object can we put custom date field & custom picklist field with no's in it. IN start(SartDateTime) field in event object with trigger code. plz can any one provide me with a sample code please
when event is created for opportunity, date field and picklist field should override the star feild and populate the custom fields values.

A: Step 1: Create a VF page like : New_event_Override:
<apex:page standardController="event" action="{!urlredirect}" extensions="event_override">
</apex:page>

controller:
public with sharing class event_override {
public date custom_date;
public string custom_picklistval;
    public event_override(ApexPages.StandardController controller) {
    custom_date = date.newInstance(2012, 11, 30);
    custom_picklistval = '07:00 AM';
    }
    public pagereference urlredirect(){
    Pagereference page = new pagereference('/00U/e');
    page.getparameters().put('StartDateTime',string.valueof(custom_date.format()));
    page.getparameters().put('StartDateTime_time',custom_picklistval);
    page.setredirect(true);
    return page;
    }
}

NOTE : The way I get the 'StartDateTime' and 'StartDateTime_time' is by going to the input field next to the start right clicking on the field and inspecting element in chrome ( this gives the Id of the field , which we can override)


text:
Q: How to convert a single Image to MP4 Video? How to convert a single image to mp4 video.
For example, I need to play the same image for 20 seconds (duration will be dynamic)
I know it's possible with ffmpeg. I searched in google & SO but unfortunately, I am not able to find the correct tutorial.
I just want a correct direction.
Any comment or suggestion is welcome.

A: Basic syntax is
ffmpeg -loop 1 -i image -pix_fmt yuv420p -t 20 out.mp4

The -t option sets the time, in seconds.

A: You can always use any video edit like windows movie maker.
Just add the photo to a project change the duration to 20 seconds and export
And then you have a 20 second video file of one image


text:
Q: Using GTK+ in Visual C++ I want to use GTK for user interface for C++ project.
I do not know how to set development environment for it.
I downloaded  all-in-one  bundle of gtk from http://www.gtk.org/download-windows.html
How to use it with visual c++ 2008 ?

A: I have gotten the Hello World Tutorial explained here: http://developer.gnome.org/gtk-tutorial/stable/c39.html#SEC-HELLOWORLD to work with Visual C++ 10 in Windows 7 32-bit.
Here are the steps I went through (assuming you installed GTK+ to C:\GTK+):
Go to Properties/Configuration Properties/Debugging and add this to the Environment
PATH=%PATH%;C:\GTK+\bin

Go to Properties/Configuration Properties/C/C++/General and add to Additional Include Directories(I'm sure there's a better way to do this but it works):
C:\GTK+\include\gtk-2.0;C:\GTK+\include\glib-2.0;C:\GTK+\lib\glib-2.0\include;C:\GTK+\include\cairo;C:\GTK+\include\pango-1.0;C:\GTK+\include\gtk-2.0\gdk;C:\GTK+\lib\gtk-2.0\include;C:\GTK+\include\gdk-pixbuf-2.0;C:\GTK+\include\atk-1.0

Properties/Configuration Properties/Linker/General and add to Additional Library Dependencies:
C:\GTK+\lib

Finally Properties/Configuration Properties/Linker/Input:
gtk-win32-2.0.lib;gdk-win32-2.0.lib;atk-1.0.lib;gdk_pixbuf-2.0.lib;pangowin32-1.0.lib;pangocairo-1.0.lib;pango-1.0.lib;cairo.lib;gthread-2.0.lib;gobject-2.0.lib;gmodule-2.0.lib;glib-2.0.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)

This worked for the Hello World tutorial, but I have a feeling if you use more commands, there may be some libs/headers I left out. This should provide a good foundation though for anyone programming with GTK+ in Visual C++

A: For any kind of library, first you need to make sure you have the available lib files and associated headers. After you have those, you simply modify your projects properties under the C++ > General > Additional Include directories, to contain the path to the headers, and under the Linker > General > Additional Library Dependencies, to contain the path to your lib files. Then under Linker > Input > Additional Dependencies, you add the file name (not the full path) of the .lib files you need.

A: There are some old instructions here and here. You will probably have to adjust them for your needs.
GTK also has some email lists you could join to discuss this. The best lists for this particular question are gtk-app-devel-list@gnome.org or gtk-list@gnome.org.
There's also an irc channel, #gtk+ on irc.gnome.org. My experience there is you get either quick answers or no answers at all.
If you can, you might try switching from Visual C++ to mingw, which is a Unix/Linux like build system for Windows. Very few GTK developers use it on Windows, and almost all of those people use mingw.

A: I was going to post it as comment to @Anthony's answer but it gave me "too many characters" and as answer I can use formatting and make it more readable.
I followed Anthony's explanation and it worked fine. I've compiled only the hello world although. I'm on Windows 8 64-bit machine but my VS target x86 so I downloaded the gtk+ 32-bit.
If you're using Visual Studio 13 and GTK+ 3.6.4, assuming you installed GTK on C:\gtk directory, here's the Properties/C/C++/General/Additional Include Directories:

C:\gtk\include\gtk-3.0;C:\gtk\include\glib-2.0;C:\gtk\include\cairo;C:\gtk\include\pango-1.0;C:\gtk\include\gtk-3.0\gdk;C:\gtk\include\gdk-pixbuf-2.0;C:\gtk\include\atk-1.0;C:\gtk\lib\glib-2.0\include

And Properties/Linker/Input:

gtk-win32-3.0.lib;gdk-win32-3.0.lib;atk-1.0.lib;gdk_pixbuf-2.0.lib;pangowin32-1.0.lib;pangocairo-1.0.lib;pango-1.0.lib;cairo.lib;gthread-2.0.lib;gobject-2.0.lib;gmodule-2.0.lib;glib-2.0.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)

A: Most include paths are:
C:\gtk\include

Initially I missed out this
C:\gtk\lib\glib-2.0\include

Having added this I am able to get it running.
Windows 10 X64, GTK-3.0 X64 Windows bundle, Visual Studio 2017, Visual C++ in C mode (.c files).

A: For Windows:
Install gtk using vcpkg dependency manager (https://vcpkg.io/en/index.html); after installing vcpkg run the command
.\vcpkg install gtk

or
.\vcpkg install gtk:x64-windows

or
.\vcpkg install gtk:x86-windows


text:
Q: Asp.net webforms with Entity Framework 6 Update page I'm working with asp.net webforms and I'm a beginner with Entity Framework. I need to know how to make an update page and send data from page to a method (binding) without having to bind field by field and save changes.
Suppose I have this class :
public class Fiche
{
    [Key]
    public int Id { get; set; }
    public string mrmme  { get; set; }
    public string nometprenom { get; set; }
    public string adresse { get; set; }
    public string ville { get; set; }
    public string cp { get; set; }
    public string tele { get; set; }
    public string portable { get; set; }
    public string datenaissance { get; set; }
    public string email { get; set; }
    public string situation { get; set; }
    public string profession { get; set; }

    #region // Santé & Prévoyance
    public string typesp { get; set; }
    public string nombresassures { get; set; }
    public string regime { get; set; }
    public string nbrenfants { get; set; }
    public string mutuelleactuelle { get; set; }
    public string tarifcontrat { get; set; }
    public string niveaugaranties { get; set; }
    public string mutuelle { get; set; }
    #endregion

    public string Createdbynom {
        get {
            return Data.Db.Users.Find(Createdby).nom;
        }
    }

    public string Affectedtonom
    {
        get
        {
            return Data.Db.Users.Find(Affectedto).nom;
        }
    }

    public ICollection<Contrat> Contrats { get; set; }
    public ICollection<Commentaire> Commentaires { get; set; }

    public string Createdby { get; set; }
    [ForeignKey("Createdby")]
    public ApplicationUser createuser { get; set; }

    public string Affectedto { get; set; }

    [ForeignKey("Affectedto")]
    public ApplicationUser affetcteduser { get; set; }
}

I have lot of fields if I want to create a form to update this model. I need to create textbox for every field and when I click "submit" button, I need to get every value from every textbox and bind to model and call SaveChnages?
Is this the only way in webforms to update data a database?
Is there any way to binding data from my form to my update method?


text:
Q: In cryptography, why do we reduce elliptic curves over finite fields? What's wrong with real numbers? Is the continuous logarithm problem "easy" to solve for elliptic curves?
Here's what I believe: elliptic curves over the real numbers have infinitely many points, many of them can't be represented by a computer (either because of floating point precision, or because of memory limitations). The discrete logarithm problem is not harder than the continuous one.
Is it right?

A: In cryptography, numbers are not used as a measurement of a quantity; its simply a tag (a primary key in a data base). So two numbers close to each other means nothing about the objects for which they are tags. That is in internet banking instead of paying from the account of a person with a specific credit card number N, if we pay from a nearby number $N+k$ with $k\ll N$, it is no use. And as you suggested representing a real number in a computer will introduce round-off errors and depositing money into an account whose number agrees with my account number with $99.99\%$ accuracy does not make me $99.99\%$ happy.

A:
Is the continuous logarithm problem "easy" to solve for elliptic curves?

The answer to that appears to be, we don't know. I don't know of any results that say it is easy or hard.

What's wrong with real numbers?

You mention one problem, representation on a computer with finite memory. This will result in rounding error, which is unsuitable for cryptography.
Another issue is speed. Working in the reals on a computer is much slower than working in a finite field. Finite field arithmetic on a computer is very fast.
Another thing to consider.
Let's say instead of working in $E(\mathbb{R})$ we work in $E(\mathbb{Q})$. This should be faster and not have rounding error. However, analyzability suffers in this case. When working over a finite field, we can say things about the order of the resulting group, the order of elements, etc. This all helps in analyzing the cryptosystem because we need all (or most) instances of a problem to be hard to solve, not just some. Analyzability is critical in cryptography these days.


text:
Q: Sizing button on ionic 2 with col A very simple problem,
I want all my button to take 90 % of the width of my columns in ionic 2, and not be dependent of the text inside
.button-pink {
    color: #F63566;
    background-color: white;
    text-transform: uppercase;
    font-size: 75%;
    border: 2px solid #F63566;
    padding: 6% 23%;
    margin: auto;
    white-space: nowrap;
    text-align: center;
    font-family: "SanFranciscoText-Regular";
    font-weight: bold;
    letter-spacing: 0.3em;
}

here is my button css, i can't manage to make them fit the width of the column, and not be dependent of the text (if i change the text inside my button, the size is changing, and i don't want that)
Thank you in advance and good day to everyone !

A: You need to set the width of the button in your CSS.
.button-pink {
  width: 90%;
}


text:
Q: Auto-incrementing numbers I am having trouble with auto incrementing numbers in my googlesheet.  Here is what I'm trying to do.
I created a googlesheet for issue tracking.  The columns are Issue Status, Group, Issue Number, Priority, etc....  Issue Status is a drop down list with values OPEN and CLOSED.  When I select OPEN from the drop-down list I want the ISSUE NUMBER to automatically display in the Issue Number column for that row.
For Example.....
I have an empty issue log. I report the first issue by selecting OPEN in the ISSUE STATUS column.  The number 1 should automatically populate in the Issue Number column for the first issue.
I report the 2nd issue by selecting OPEN on the next row.  The number 2 should automatically populate in the Issue Number column for the second issue.
I report the 3rd issue by selecting OPEN on the next row.  The number 3 should automatically populate in the Issue Number column for the second issue.
Currently I am manually entering the number.  I want it to automatically populate when selecting OPEN from the list.
Auto Increment Issue Number
The line of code that I'm trying to use for this does not work as I want it to.  In my case statement for OPEN, I added the following line
SpreadsheetApp.getActiveSheet().getRange('C5').setValue(SpreadsheetApp.getActiveSheet().getRange('C5').getValue() + 1);
Here's my code:

    function onEdit(event)
{
  var ColA = 1;   // Column Number of "A"
  var ColN = 14;  // Column Number of "N"
  var ColO = 15;  // Column Number of "O"
  var ColP = 16;  // Column Number of "P"
  var changedRange = event.source.getActiveRange();
  if (changedRange.getColumn() == ColA && changedRange.getSheet().getSheetName() == "Issues")
   {
    // An edit has occurred in Column A
    var state = changedRange.getValue();
    var user = Session.getActiveUser().getEmail().substring(0, 2).toUpperCase();
    var DateOpened = event.source.getActiveSheet().getRange(changedRange.getRow(),ColA+9);
    var DateClosed = event.source.getActiveSheet().getRange(changedRange.getRow(),ColA+10);
    var Iteration1 = event.source.getActiveSheet().getRange(changedRange.getRow(),ColA+13);
    var Iteration2 = event.source.getActiveSheet().getRange(changedRange.getRow(),ColA+14);
    var Iteration3 = event.source.getActiveSheet().getRange(changedRange.getRow(),ColA+15);
    var d = new Date();
    var timestamp = user + "_" + d.dateNow() + "_" + d.timeNow() + "\n";
    // Determine the state of Col A
    switch (state)
    {
      case "OPEN":
        SpreadsheetApp.getActiveSheet().getRange('C5').setValue(SpreadsheetApp.getActiveSheet().getRange('C5').getValue() + 1);
        // Write timestamp in Date Opened column
        DateOpened.setValue(timestamp);
        Iteration1.setValue("NOT EXECUTED");
        Iteration2.setValue("NOT EXECUTED");
        Iteration3.setValue("NOT EXECUTED");
        break;
      case "CLOSED":
        // Write timestamp in Date Closed column
        DateClosed.setValue(timestamp);
        break

    }
  }

Any suggestions?

A: You could use PropertiesService in order to store and keep track of the issue number. You would have to:

*

*Retrieve the corresponding script property at the beginning of your code (and set the property to 0 if no issue was created before, with getProperty(key) and setProperty(key, value).

*Get the cell to edit (edited row, column C).

*Increment the script property by 1 and write it to the cell retrieved in last step.

It could be something along the following lines (I deleted the parts that are not directly related to this issue). Please check inline comments for more details:
function onEdit(event){
  // Retrieve previously stored script properties.
  // If not property called 'numIssues' exist, set it to 0:
  var scriptProperties = PropertiesService.getScriptProperties();
  scriptProperties.getProperties();
  if(!scriptProperties.getProperty("numIssues")) scriptProperties.setProperty("numIssues", 0);
  // Get event data:
  var ColA = 1;   // Column Number of "A"
  var ColC = 3;   // Column Number of "C"
  var firstIssueRow = 5; // Row at which issues start (please change if necessary)
  var changedRange = event.source.getActiveRange();
  var changedRow = changedRange.getRow();
  var sheet = changedRange.getSheet();
  // Check that edited column, row and sheet are correct:
  if (changedRange.getColumn() == ColA && sheet.getSheetName() == "Issues" && changedRow >= firstIssueRow) {
    var state = changedRange.getValue();
    switch (state) {
      case "OPEN":
        var colCRange = sheet.getRange(changedRow, ColC); // Get range to edit
        if (colCRange.getValue() === "") { // Check that cell is empty (otherwise do nothing)
          scriptProperties.setProperty("numIssues", Number(scriptProperties.getProperty("numIssues")) + 1); // Increment 1 to property 'numIssues'
          sheet.getRange(changedRow, ColC).setValue(scriptProperties.getProperty("numIssues")); // Write new property value to cell
        }
        // Write timestamp in Date Opened column
        break;
      case "CLOSED":
        // Write timestamp in Date Closed column
        break
    }
  }
}

Reference:

*

*PropertiesService


text:
Q: Laravel update upload using AJAX This is the code for editing uploaded image and title, I don't know how to pass the id to the controller:
Here form
<form role="form" name="campaignForm" id="campaignForm" action="" method="POST"  enctype="multipart/form-data">
 <input type="hidden" class="form-control" name="id" id="id">
<input type="text" class="form-control" name="title_edit" id="title_edit" autofocus>

 <input type="file" name="image" id="image" autocomplete="off" placeholder="" class="form-control">

 <button type="button" id="btn-edit" class="btn btn-success add" data-dismiss="modal">Add</button>
</form>

Ajax
   $("#btn-edit").click(function (e) {
       $.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
    }
});

    e.preventDefault();

   var form = document.forms.namedItem("campaignForm");
var formData = new FormData(form);

$.ajax({
    'id': $("#id").val(),
    type: 'POST',
    url: 'update-advertisement/',
    contentType: false,
    data: formData,
    processData: false,

    success: function (data) {
 }

route
   Route::post('update-advertisement',['as'=>'update-advertisement','uses'=>'AdverController@updatebanner']);

Controller
     I dont know if this is correct because the id maybe is not sending correctly
     public function updatebanner(Request $request,$id)
   {
   $post = Advertisement::findOrFail($id);
    if ($request->hasFile('image')) { $imagename = time().'.'.$request->file('image')->getClientOriginalExtension();
     $path =$request->file('image')->storeAs('/images', $imagename);
  $post->adver_title=$request->sendthis_title;
  $post->adver_photo=$imagename;
  $post->save();
  return response()->json($post);
   } }

A: In order for the "update" feature to work, you would do very similar things to what you've already done for the "Add" functionality.
1) Make sure you have a route defined for an /update route.  Can you post your routes file above so we can take a look at it?
2) Make sure your route is calling the right controller and the right method inside that controller.
3) Make sure the controller mentioned in step 2 has that method defined.
4) Make an Ajax call with the right data to the new /update route you've defined in step 1.
5) Make sure that the Ajax call in step 4) gets triggered when the user clicks an "update" button or some other action indicating they want to update the original Advertisement.
If you post more of your code, I can give you more specific directions.


text:
Q: React: Is it safe to return false from shouldComponentUpdate? I have create a React component that renders it's children into grid markup. Since the component is stateless and the grid markup will never change, is it ok to return false from shouldComponentUpdate?
My only concern that I of course don't want to prevent the children from re-rendering but only the grid component.

A: Stop renders at the source using shouldComponentUpdate
Take a look at this nested Component structure:

By default, if an Update is triggered in A, then all the other children will also go through their updates. This can easily cause a performance issue, because now we have many Components going through each step of the process.+
By adding logic checks in shouldComponentUpdate() at A we can prevent all its children from re-rendering. This can improve overall performance significantly. But keep in mind, if you prevent A from passing props down to the children you may prevent required renders from occurring.
So, Answering your question, if you prevent element A from re-render it will cause a cascade effect and will affect your grid component.


text:
Q: how to pass Model with Url.Action? I want to return a partial view in Jquery Dailog and wanted to pass the viewmodel object to particular controller action, how to do that?
View
@Html.DropDownListFor(model => model.SelectedCountry, new SelectList(Model.CountryList, "CountryCode", "CountryName"), "---SELECT COUNTRY---",
                                    new { @class = "chosen", @onchange = "this.form.action='/Home/Index'; this.form.submit(); " })
<input type="button" id="button1" value="Push"/>

Js


text:
Q: How small can the largest of $N$ probabilities be? Suppose you have $N$ events which are mutually exclusive and whose probabilities add up to one, and suppose that event $1$ has probability $p$ and events $2$ through $N$ have probabilities less than $p$.  Then my question is, how small can $p$ be?
Clearly $p > \frac{1}{N}$, but are there any other constraints?

A: You are correct that we must have $p(E_1)>1/N$, because $p(E_i)<p$ for $i>1$ and so $1=\sum p(E_i)<Np$.
It is easy to see that we can get $p$ arbitrarily close to $1/N$. For example, we could take $p(E_i)=p-i\epsilon$, which gives $p=1/N+\frac{(N-1)\epsilon}{2}$ (which is arbitrarily close to $1/N$ for $\epsilon$ sufficiently small.
Although there are no other conditions on $p$ in the general case, it will obviously have to be bigger than $1/N$ if the values $p(E_i)$ (for $i>1$) are not close to $p$. To take an extreme example, if we took them all to be 0, then we would have to have $p=1$. If we took just one of them to be 0, then we would effectively have the same problem with $N-1$ instead of $N$, so we would need $p>1/(N-1)$.


text:
Q: Can the two "high" input to a digital logic gate have different voltage values? Suppose there is a logic gate and it has two inputs.I want both the inputs to be "high" i.e logic 1, can i have two different voltage values at these two inputs? e.g 3v on one and 4v on another?

A: Read the datasheet.
There will be a spec for the minimum input voltage so that the signal is guaranteed to be interpreted as a logic high.  As long as the two inputs meet this criterion, and don't violate any other spec, the logic gate will see both its inputs as high.  There is generally no requirement that the two signals be within some voltage of each other, only that each be a valid logic high voltage.
Yes, this really is as simple as it sounds.


text:
Q: I want to show/hide content with tabs AND change fullscreen background at the same time. Is this even possible? I'm working with a client who wants a site with a full-screen background that changes when a show/hide tab is clicked.
I consider myself pretty good at adapting jquery, but i'm stumped.  I don't really have any code to show, but if anyone can at least point me in the right direction I can probably figure it out.
thanks in advance.

A: Try this: http://jsfiddle.net/HzWRT/


text:
Q: Mysql result to set session variable I want to use the result of a mysql query to set a session variable however at present I am struggling to make it set.
My code I have is:
<?php

ob_start("ob_gzhandler");

?>
<?php
// Include required MySQL configuration file and functions
require_once('config.inc.php');
require_once('functions.inc.php');

// Start session
session_start();

// Check if user is already logged in
if ($_SESSION['logged_in'] == true) {
          // If user is already logged in, redirect to main page
          redirect('../index.php');
} else {
          // Make sure that user submitted a username/password and username only consists of alphanumeric chars
          if ( (!isset($_POST['username'])) || (!isset($_POST['password'])) OR
               (!ctype_alnum($_POST['username'])) ) {
                        redirect('../login.php');
          }

          // Connect to database
          $mysqli = @new mysqli(DB_HOSTNAME, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
// Check connection
          if (mysqli_connect_errno()) {
                        printf("Unable to connect to database: %s", mysqli_connect_error());
                        exit();
          }

          // Escape any unsafe characters before querying database
          $username = $mysqli->real_escape_string($_POST['username']);
          $password = $mysqli->real_escape_string($_POST['password']);

          // Construct SQL statement for query & execute
          $sql              = "SELECT * FROM users WHERE username = '" . $username . "' AND password = '" . md5($password) . "'";
          $result = $mysqli->query($sql);

// If one row is returned, username and password are valid
          if (is_object($result) && $result->num_rows == 1) {
                        // Set session variable for login status to true

                        $_SESSION['auth_lvl'] = $Auth_lvl;
                        $_SESSION['logged_in'] = true;

                        redirect('../index.php');
          } else {
                        // If number of rows returned is not one, redirect back to login screen
                        redirect('../login.php');
          }
}
?>

I am then testing the session variables with:
<?php
session_start();
echo "Login Status is:".$_SESSION['logged_in'];
echo "<br/>";
echo "Auth status is level:".$_SESSION['auth_lvl'];
?>

On my testing page the session logged in works fine displaying the correct information however the auth lvl variable displays nothing.
I can only assume that I am not calling the information correctly that I am setting the variable with in the first place.
Any help would be appreciated.
Alan.
Something I have notice and I have been trying the suggestions is that if I set a definative rather than trying to retreive a value from the database that value will return on my test page. i.e.
$_SESSION['auth_lvl'] = 'test';

This tells me it is the way in which I am pulling the data from the database and trying to set it as $_SESSION['auth_lvl'] that is causing the problem.

A: Found the problem.
the code read:
$result = $mysqli->query($sql);

// If one row is returned, username and password are valid
if (is_object($result) && $result->num_rows == 1) {

// ADD THIS SET OF LINES
$data = mysql_fetch_assoc( $result );

// Replace auth_lvl with the name of your database column name
$Auth_lvl = $data['Auth_lvl'];

// Set session variable for login status to true
$_SESSION['auth_lvl'] = $Auth_lvl;
$_SESSION['logged_in'] = true;

Because I had used mysqli on this code I had not notice that on the //ADD THIS SET OF LINES piece of code that an 'i' was missing. When I changed the code to:
$data = mysqli_fetch_assoc( $result );

Everything fired into life.
Thanks for your help guys.

A: I can't see anywhere that you have assigned $Auth_lvl with a value, so when you do:
$_SESSION['auth_lvl'] = $Auth_lvl;

It's presumably getting assigned null.

A: I'm not seeing where you are setting $Auth_lvl.  After you check for the results being there, and rows, you're going straight to setting a session variable against an empty variable.
      if (is_object($result) && $result->num_rows == 1) {
                    // ADD THIS SET OF LINES
                    $data = mysql_fetch_assoc( $result );

                    // Replace auth_lvl with the name of your database column name
                    $Auth_lvl = $data['auth_lvl']'

                    // Set session variable for login status to true

                    $_SESSION['auth_lvl'] = $Auth_lvl;
                    $_SESSION['logged_in'] = true;

                    redirect('../index.php');

Then with your logged_in session variable, you're setting it as a boolean, true, and then trying to echo it out as normal text.
if ( $_SESSION['logged_in'] ) { echo "Login status is: True"; }

I hope that helps.
-Dan


text:
Q: OData getting zero values in .net application I am developing a .net application using OData. When I call OData service from my application, I am getting zero values, but when I check same odata service in Browser, I am not getting zero values.  Please refer following screen shots.
.net application output

Browser output

Code
        Uri serviceUri = new Uri(@"http:/service_url/sales_and_delivery.xsodata");

        SalesData.sales_and_delivery dataContext = new SalesData.sales_and_delivery(serviceUri);

        var query = (from d in dataContext.SalesOrderandDelivery
                     select d).ToList();
        foreach (var item in query)
        {
               ///
        }

What could be the possible reason?
Thanks

A: In my previous project, there is strange behavior while adding web service using Add Service Reference.
My Childs object doesn't load.
I then try to change the method to the predecessor method using Add Web Reference and child object loaded.
You could try to use Add Web Reference. Here is how to add web reference in the newer visual studio:
https://forums.asp.net/post/5660283.aspx
Also, make sure you map data type between web service and C# object correctly Edm.Decimal >> Decimal.


text:
Q: Getting row data from Datatables I have a web2py app that uses Datatables extensively, but in fairly simple forms. One of the views uses server-side processing to populate a table, and I need to get data from the row when a user clicks on a row of the table. I've used example code from the Datatables site, but can't get it to work.
Here is the Datatables intialization (datatables 1.10):
<script type="text/javascript" charset="utf-8">
var oTable;
$(document).ready(function() {
    oTable = $('#parts-list').dataTable({
        searching: true,
        displayLength: 10,
        lengthChange: false,
        paging: true,
        processing: true,
        serverSide: true,
        ajax: '/init_ss/default/get_data_server_side',
        "language" : {
            zeroRecords: "The search turned up no part"},
        "columnDefs": [
          {
            "data": null,
            "targets": [ 6 ],
            "defaultContent" : "Click on row to add to request for information</a>"
          }
        ]
    });
});
</script>

This works as expected: the table gets constructed properly, with the last column's content being the words "Click on row to add to request for information."
To process a click on a row in the table with an id of "parts-list," I have this code:
<script>
$(document).ready(function() {
var table = $('#parts-list').DataTable();

$('#parts-list tbody').on( 'click', 'tr', function () {
    console.log( table.row( this ).data() );
        alert("retrieved data from selected row");
} );
</script>

This is straight from the Datatables website, in the API reference for row(), data(). For me, it doesn't work - I can't see that the function to retrieve the row data ever gets called when I click in any row of the table.


text:
Q: Generating SQL Schema from XML We are using an Oracle 11 database and a java development environment (using Eclipse) and would like to migrate several xml schemas to SQL schemas.
Have looked ax xsd but really need something that we can run from ant/
Eclipse without SQL Server installed.
Regards,
Andy

A: What is the XML schema definition? Is it proprietary or open? An XSLT transform can be easily scripted to do the conversion.

A: Another option would be to use JAXB to generate Java objects, and use Hibernate to create a schema based on the class hierarchy.
That being said, it depends on what you are trying to do, and I think such solutions are probably going to be brittle and hard to maintain.


text:
Q: How can I utilise reactive values without passing them to an output? Let's say I have some Shiny/R functionality which generates Javascript on-the-fly, and this JS produces new UI elements which in turn produce reactive values i.e a quantity which can be incremented or decremented.
I am having trouble passing back the values to use on the server side. Consider this minimal example:
library(shiny)
library(htmltools)

# Define UI for application that draws a histogram
ui <- fluidPage(

    # Application title
    titlePanel("Test"),

    # Sidebar with a slider input for number of bins
    sidebarLayout(
        sidebarPanel(

        ),

        # Show a plot of the generated distribution
        mainPanel(
          shiny::tags$script(htmltools::HTML('
          $(document).on("shiny:connected", function() {
            quantity = 1;
            console.log(quantity);
            Shiny.setInputValue("hi", quantity);
          });'))
       ,
        )
        )

)

# Define server logic required to draw a histogram
server <- function(input, output) {

  sayHi <- reactive({ input$hi })

  getHi <- renderText({ sayHi() })

  print(getHi) # prints function
  print(getHi()) # error

}

# Run the application
shinyApp(ui = ui, server = server)

I don't want to pass the quantity value straight to an output i.e output$id. Instead, I want to use it in an R function. But I can't "get" to that value. getHi returns the function and getHi() produces, "Operation not allowed without an active reactive context." - but I thought the reactive context was setup by renderText. How can I pass updating values to e.g an R function, without passing them straight to an output?


text:
Q: How can auto generate war file for java maven project in GitLab? How can auto generate war file for java maven project in GitLab, once the developer commit the code in gitlab repository automatic generate war ?

A: Add a custom hook to your GitLab repo

Hooks can be placed in hooks/<hook_name>.d (global) or custom_hooks/<hook_name>.d (per project) directories supporting chained execution of the hooks.

In your case: <project>.git/custom_hooks/<hook_name> on the server side: that hook can, when receiving new commits, build the war.


text:
Q: Make Custom Camera look full screen android What I have
I a have a Custom Camera that uses only rear camera hardware no selfies :)
My problem
My Camera is not full screen & image looks little zoomed .Camera takes only 80% of the screen
What I tried
I googled and came across many codes that give surety of full screen camera, but non works in my case
My code
camera_activity.xml
<FrameLayout
        android:id="@+id/camera_preview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true" />

CameraActivity.java
private CameraPreview mPreview;
private FrameLayout cameraPreview;

cameraPreview = (FrameLayout) findViewById(R.id.camera_preview);
ViewGroup.LayoutParams layoutParams=new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
mPreview.setLayoutParams(layoutParams);
cameraPreview.addView(mPreview);

CameraPreview.java
public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback {
    private static final String TAG = "CameraPreview";
    private final List<Camera.Size> mSupportedPreviewSizes;
    private SurfaceHolder mHolder;
    private Camera mCamera;
    private Camera.Size mPreviewSize;

    public CameraPreview(Context context, Camera camera) {
        super(context);
        mCamera = camera;

        mCamera.setDisplayOrientation(90);
        // supported preview sizes
        mSupportedPreviewSizes = mCamera.getParameters().getSupportedPreviewSizes();
        for (Camera.Size str : mSupportedPreviewSizes)
            Log.e(TAG, str.width + "/" + str.height);
        mHolder = getHolder();
        mHolder.addCallback(this);
        // deprecated fragment_setting, but required on Android versions prior to 3.0
        mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
    }

    public void surfaceCreated(SurfaceHolder holder) {
        try {
            // create the surface and start camera preview
            if (mCamera == null) {
                //mCamera.setDisplayOrientation(270);

                Camera.Parameters param = mCamera.getParameters();
                param.setPreviewSize(mPreviewSize.width, mPreviewSize.height);
                mCamera.setParameters(param);
                mCamera.setPreviewDisplay(holder);
                mCamera.startPreview();
            }
        } catch (IOException e) {
            Log.d(VIEW_LOG_TAG, "Error fragment_setting camera preview: " + e.getMessage());
        }
    }

    public void refreshCamera(Camera camera) {
        if (mHolder.getSurface() == null) {
            // preview surface does not exist
            return;
        }
        // stop preview before making changes
        try {
            mCamera.stopPreview();
        } catch (Exception e) {
            // ignore: tried to stop a non-existent preview
        }
        // set preview size and make any resize, rotate or
        // reformatting changes here
        // start preview with new fragment_setting
        setCamera(camera);
        try {
            /*mCamera.setPreviewDisplay(mHolder);
            mCamera.startPreview();*/
            Camera.Parameters parameters = mCamera.getParameters();
            parameters.setPreviewSize(mPreviewSize.width, mPreviewSize.height);
            mCamera.setParameters(parameters);
            mCamera.setDisplayOrientation(90);
            mCamera.setPreviewDisplay(mHolder);
            mCamera.startPreview();

        } catch (Exception e) {
            Log.d(VIEW_LOG_TAG, "Error starting camera preview: " + e.getMessage());
        }
    }

    public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
        refreshCamera(mCamera);
    }

    public void setCamera(Camera camera) {
        //method to set a camera instance
        mCamera = camera;
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        // TODO Auto-generated method stub
        // mCamera.release();

    }

    private Camera.Size getOptimalPreviewSize(List<Camera.Size> sizes, int w, int h) {
        final double ASPECT_TOLERANCE = 0.1;
        double targetRatio = (double) h / w;

        if (sizes == null)
            return null;

        Camera.Size optimalSize = null;
        double minDiff = Double.MAX_VALUE;

        int targetHeight = h;

        for (Camera.Size size : sizes) {
            double ratio = (double) size.height / size.width;
            if (Math.abs(ratio - targetRatio) > ASPECT_TOLERANCE)
                continue;

            if (Math.abs(size.height - targetHeight) < minDiff) {
                optimalSize = size;
                minDiff = Math.abs(size.height - targetHeight);
            }
        }

        if (optimalSize == null) {
            minDiff = Double.MAX_VALUE;
            for (Camera.Size size : sizes) {
                if (Math.abs(size.height - targetHeight) < minDiff) {
                    optimalSize = size;
                    minDiff = Math.abs(size.height - targetHeight);
                }
            }
        }

        return optimalSize;
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        final int width = resolveSize(getSuggestedMinimumWidth(), widthMeasureSpec);
        final int height = resolveSize(getSuggestedMinimumHeight(), heightMeasureSpec);

        if (mSupportedPreviewSizes != null) {
            mPreviewSize = getOptimalPreviewSize(mSupportedPreviewSizes, width, height);
        }

        float ratio;
        if (mPreviewSize.height >= mPreviewSize.width)
            ratio = (float) mPreviewSize.height / (float) mPreviewSize.width;
        else
            ratio = (float) mPreviewSize.width / (float) mPreviewSize.height;

        // One of these methods should be used, second method squishes preview slightly
        setMeasuredDimension(width, (int) (width * ratio));
//        setMeasuredDimension((int) (width * ratio), height);
    }

    private Camera.Size getBestPreviewSize(int width, int height, Camera.Parameters parameters) {
        Camera.Size result = null;

        for (Camera.Size size : parameters.getSupportedPreviewSizes()) {
            if (size.width <= width && size.height <= height) {
                if (result == null) {
                    result = size;
                } else {
                    int resultArea = result.width * result.height;
                    int newArea = size.width * size.height;

                    if (newArea > resultArea) {
                        result = size;
                    }
                }
            }
        }
        return (result);
    }
}

A: Add getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); in onCreate()-CameraActivity.java
public class CameraActivity extends Activity {
    private static final String TAG = "Camera Activity";
    private CameraPreview mPreview;
    private FrameLayout cameraPreview;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.camera);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
        try {
            cameraPreview = (FrameLayout) findViewById(R.id.camera_preview);
            ViewGroup.LayoutParams layoutParams=new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
            mPreview.setLayoutParams(layoutParams);
            cameraPreview.addView(mPreview);
        } catch (Exception e) {
            Log.e(TAG, e.getMessage());
        }
    }


text:
Q: Create Update function to take data from unique assignment sheet and populate results to each student Purpose: Track Manitoba Education Outcomes for a Grade/Subject
Each student has a sheet which is named their full name; each assignment  has a sheet with filtered outcomes and populated with students.
Outcomes (116 for English broken down into 5 categories GOC1..GOC5 Teacher's filter for the outcomes they are tracking for a particular assignment.
Need to get and paste (values only) into each student's individual sheet a) Title of assignment (C1) to StudentName!B4 (4 should be lastRow) b) Student name (D7) entire array (D7:AI7) - array? c) Outcome averages from individual assignment are located in (d2:d6) {Entire outcomes (d2:ai6)} to StudentName!C4:G4 (4 should be lastRow)
Then go back to the assignment and do it again for the next student.
I have attempted map(), copyValuesTo(), setValues(). Pastes 1 value across the 5 GOCs. Struggling to get the student's name (sheet name for each student) to go into getSheetByName(). Also created arrays of data, named ranges for each d2:d6 which clears itself then creates new named ranges for new assignment.  I was thinking this would help as those ranges never change but the assignment does.
//Purpose: Track Manitoba Education Outcomes for a Grade/Subject
//Each student has a sheet which is named their full name; each assignment  has a sheet with filtered outcomes and populated with students
//Outcomes (116 for English broken down into 5 categories GOC1..GOC5 Teacher's filter for the outcomes they are tracking for a particular assignment
//Need to get and paste (values only) into each student's individual sheet a) Title of assignment (C1) to StudentName!B4 (4 should be lastRow) b) Student name (D7) entire array (D7:AI7) - array? c) Outcome averages from individual assignment are located in (d2:d6) {Entire outcomes (d2:ai6)} to StudentName!C4:G4 (4 should be lastRow)
//Then go back to the assignment and do it again for the next student.
//I have attempted map, copyvaluesto, setvalues. Pastes 1 value across the 5 GOCs
//Struggling to get the student's name (sheet name for each student) to go into getSheetByName
//Also created arrays of data, named ranges for each d2:d6 which clears itself then creates new named ranges for new assignment.  I was thinking this would help as those ranges never change but the assignment does.
function goArrayAssignment() {
  //trying to take val from assign. and put into 1 student, then for loop
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var source = ss.getActiveSheet();
  var destination = ss.getSheetByName("StudentName").getRange("C4:G4"); //need lastrow?

  var dArray = source.getRange("d2:d6").getValues().flat().toString(); //   [3.0, , 3.0, , ] //use for loop?
  Logger.log(dArray);
  destination.setValue(dArray[0][0]); //outputs data but always 1st pos. of array
}

//Did I macro From Spelling unit assignment to Jeff Hiebert
function updateInfoMacro() {   //Macro of what I want to do.  Need to var assignName, studentName(Row7 of assignment)
  var spreadsheet = SpreadsheetApp.getActive();
  spreadsheet.getCurrentCell().offset(-5, -2).activate();
  spreadsheet.setActiveSheet(spreadsheet.getSheetByName('Jeff Hiebert'), true);
  spreadsheet.getCurrentCell().offset(0, 1).activate();
  spreadsheet.getRange('\'Spelling Test - Unit 23\'!D2').copyTo(spreadsheet.getActiveRange(), SpreadsheetApp.CopyPasteType.PASTE_VALUES, false);
  spreadsheet.getCurrentCell().offset(0, 1).activate();
  spreadsheet.setActiveSheet(spreadsheet.getSheetByName('Spelling Test - Unit 23'), true);
  spreadsheet.getCurrentCell().offset(1, 0).activate();
  spreadsheet.setActiveSheet(spreadsheet.getSheetByName('Jeff Hiebert'), true);
  spreadsheet.getRange('\'Spelling Test - Unit 23\'!D3').copyTo(spreadsheet.getActiveRange(), SpreadsheetApp.CopyPasteType.PASTE_VALUES, false);
  spreadsheet.getCurrentCell().offset(0, 1).activate();
  spreadsheet.setActiveSheet(spreadsheet.getSheetByName('Spelling Test - Unit 23'), true);
  spreadsheet.getCurrentCell().offset(1, 0).activate();
  spreadsheet.setActiveSheet(spreadsheet.getSheetByName('Jeff Hiebert'), true);


text:
Q: Creating a connection with Microsoft's JDBC driver is 3 times faster than with jTDS I googled a lot but I can't figure out the reason of this strange behaviour. I'm using microsoft sql server 2012 with windows authentication. I'm connecting like that:
try {
  Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
  conn = DriverManager.getConnection("jdbc:sqlserver://MY-PC:1433;databaseName=database;integratedSecurity=true");
} catch (Exception e) {
  System.out.println("failed" + e.getMessage());
  e.printStackTrace();
}

This connection is aproximately 3 times faster than when I use jtds driver (and also add .jar to project library and so on) net.sourceforge.jtds.jdbc.Driver and appropriate connection string (jdbc:jtds:sqlserver://MY-PC:1433/database;instance=SQLEXPRESS).
Does anybody know why? I read that jtds driver is much faster than sqldbc drivers, but I don't know what I'm doing wrong.
Thank you

A: jTDS driver has a lot of improvements related to the way queries work after the connection is made. Their benchmark does not mention the initial connection speed: http://jtds.sourceforge.net/benchTest.html. They only measure operations that are executed after connection is already active.
I suspect that connection initialization code is slower than for other drivers. That's why it is worth keeping a connection pool of precreated connections to get maximum performance. In fact it's true about any driver.


text:
Q: send mail to gmail inbox instead of spam by using php in smtp connection I used the php mailing function to send mail.but my mails send to spam folder. I want to send my mail to inbox.How can I send mail to gmail inbox instead of spam by using php in smtp connection.

A: So, you want us to tell you how to spam a mailbox with the Google genius detecting it's spam. Not happening.
However, if you are serious... Email applications look for spam if it looks like spam. Be sure to sent the proper settings in the email and don't look like a spammer with stuff like 'here is some text. Wait click this link'
AKA php has no power to override email filters.


text:
Q: Is this how to "Implement IDisposable correctly"? I ran Code Analysis on one of my projects, and it gave me two finger wags, namely:
CA1063 Implement IDisposable correctly Provide an overridable implementation of Dispose(bool) on 'UserStore' or mark the type as sealed. A call to Dispose(false) should only clean up native resources. A call to Dispose(true) should clean up both managed and native resources.
...on this line of  code:
public class UserStore : IUserStore<User>, IUserPasswordStore<User>,  IUserClaimStore<User>

...and this:
CA1063 Implement IDisposable correctly Modify 'UserStore.Dispose()' so that it calls Dispose(true), then calls GC.SuppressFinalize on the current object instance ('this' or 'Me' in Visual Basic), and then returns.
...on my empty Dispose:
public void Dispose()
{
    //
}

Can I assassinate two avians with one petrified dirtclod by doing this:
public override void Dispose()
{
    Dispose(true);
    GC.SuppressFinalize(this);
}

? Is that what it's suggesting?
UPDATE
To answer my question (sort of), apparently not - I figured I'd just add the code and see if the Code Analysis would then feed back the yearned-for "'NRBQ.API.UserStore.Dispose()': no suitable method found to override"


text:
Q: how to set which binary file to execute in linux I have 2 binaries named 'jupyter-notebook' in my machine:
$ which jupyter-notebook

I get result:
jupyter-notebook is /usr/local/bin/jupyter-notebook
jupyter-notebook is /anaconda3/bin/jupyter-notebook

Seems when I type$ jupyter-notebook it will automatically run the first one. How do I configure it to run the second one?

A: You can use alias for that. Run the following command in your shell.

alias jupyter-notebook="/anaconda3/bin/jupyter-notebook"

If you want it to be permanent then put it in your shell rc file.


text:
Q: Hide a div container based on timestamp I would like to display an alert banner (div) on a page for 30 minutes after a piece of content was created. After 30 minutes, the banner should not display anymore. This is to let a user know that a video takes time to transcode, so may be unavailable until then.
The idea:
var timeStamp = format_date(var node.created, 'custom', 'M j, Y g:i A');
var currentTime = new Date();

if {
    currenTime < timeStamp + (30_minutes) = document.getElementById(alert_banner).style.display = 'block';
}
else {
    currentTime > timeStamp + (30_minutes) = document.getElementById(alert_banner).style.display = 'none';
}

A: You can try it
var time = 1000 * 60 * 30 //milisecond * second * minute
setTimeout(function(){
    // Your function here e.i
    document.getElementById(alert_banner).style.display = 'none';
}, time)

A: As the headlikearock mentioned, the timing intervals are probably your best bet:
setInterval(function(){document.getElementById(alert_banner).style.display = 'none';},1800000);

Place that in your on load JS code, and it should fire off the inline defined JS function 30 seconds after that statement is run.
Here is an example with a disappearing div after 5 seconds.

A: You can use the setTimeout method (http://www.w3schools.com/js/js_timing.asp) to hide the div after 30 minutes.


text:
Q: What is the file path I need to use to view my html pages in my java project on netbeans? I am using NetBeans IDE 8.2.  I have a java web project, lets call it ProjectName.  My project folder looks like this:
>ProjectName
  >build
  >dist
  >nbproject
  >src
  >web
    >index.html
    >foo.html
    >bar.html
  >build.xml

Right now, if I run my project, a browser will open and display index.html.  The URL reads "localhost:54782/ProjectName".
But I cannot view foo.html or bar.html.  I have tried "localhost:54782/ProjectName/foo", and "localhost:54782/ProjectName/web/foo", and many other variations of this pattern.  Please help me and tell me what I need to do to view my foo.html and bar.html.

A: You indicate that you tried localhost:54782/ProjectName/foo. Did you try it with the extension .html? if you did try it with localhost:54782/ProjectName/foo.html. It works by without the extension for index.html because there is a mapping defined in the web.xml file in the  tag.


text:
Q: Javascript form validation(oninput) I have two tables and functions. Function validation() validates username character length and checks if the name already exists in an array.
Function myFunction() works with oninput and outputs the text I enter in the username textfield. I would want to change that in the way it would display form validation/the mistakes I'm making while entering text if you get what I mean.
The only problem I have is that "x" . How can I use "if" and "for" validation as an variable so the output will be the mistake.
I hope you understand the concept.

        Username:<input type="text" id="myInput" oninput="myFunction()">

<form onsubmit="return validacija()">

                Uporabniško ime:
                <input type="text" id="upor_ime" name="upor_ime">

</form>

A: <Form> Tag & input Event

HTMLFormControlsCollection

*

*Wrap a <form> tag around all relevant form controls

*Reference the <form> tag using the Document.forms property.

*Collect all of the <form> tag's form controls using HTMLFormElement.elements property.

Reference: JavaScript and Forms Tutorial

Form & Form Control Events
Besides the common events like click, <form> tags and form controls have some exclusive events as well:
<form>

*

*submit

*reset
<input>, <textarea>

*

*change (including <select>)

*

*Trigger: User must enter data into or change value of the form control, then click anywhere except the form control itself.

*input

*

*Trigger: User enters data into the form control.

Event Handling
Onevent Handlers

*

*Try to avoid using the onevent attribute handler:
<form id='xForm' onsubmit="return validate()">

*Although it's not recommended, an onevent property handler is a better alternative:
document.forms.xForm.onsubmit = validate;

I personally prefer using the previously mentioned event handler because of it's terse syntax.

*The recommended way of event handling is to use event listeners:
document.forms.xForm.addEventListener('submit', validate);

Avoid alert()
alert() sux, use console.log()

Demo

var xF = document.forms.xForm;
var fields = xF.elements;
var xI = fields.xInput;
var xM = fields.xMessage;

xF.oninput = validate;

function validate(e) {
  var names = ["tilen", "marko", "teja", "tisa", "rok", "luka", "mojca"];
  for (let i = 0; i < names.length; i++) {
    if (names[i] === xI.value.toLowerCase()) {
      return log(xI.value + " že obstaja.");
    }
  }
  if (xI.value.length > 20 || xI.value.length < 3) {
    return log("uporabniško ime mora biti vsaj 3 in ne sme biti daljše od 20 znakov.");
  } else {
    return log('');
  }
}

function log(msg) {
  var color = msg === '' ? 'black' : 'red';
  Array.from(fields).forEach(function(fc) {
    fc.style.color = color;
  });
  xM.value = msg.charAt(0).toUpperCase() + msg.slice(1).toLowerCase();
  return false;
}
html,
body {
  font: 400 14px/1.5 Consolas;
}

th {
  text-align: left;
  vertical-align: top;
  width: 150px;
}

input,
output {
  font: inherit;
  display: inline-block;
  width: 96%;
}

#xInput {
  transform: translateY(-3px);
  padding: 0 3px;
}
<form id='xForm' width='100%'>

      Uporabniško Ime:
      <input id="xInput" type="text" autocomplete="off">

      Obvestilo O Napaki:
      <output id="xMessage"></output>

</form>


text:
Q: VueJs + Firebase - how to read simple data I know this is very simple question, but I can't find out a simple answer anywhere.
I start messing around with Firebase, and I want to just get all information of user then paste it where I need in my app.
For example, I have Database, inside I have "Users" - then keys (like -KjVkK3QCAXxMCfdyROe) and then all the info (name, age, job...).
What I come out until now is:
let app = Firebase.initializeApp(config)
let db = app.database()
let usersRef = db.ref('Users')

Then in my vue app component -
firebase: {
  users: usersRef.child('-KjVxBYyKv3_PFLavId3')
},

Now I want to know how to get the name, age, job values? I tried this.users.name - but it is undefined.
I looked and found that code, but it too long and not efficient:
this.users.on("value", function(snapshot) {
  var username = snapshot.val().name;
});

Please give hand and help me understand how can I get to the object and get the info simple like regular object. How can I turn Firebase Reference into simple Object?

A: Sanity check first:  the firebase{} construct isn't automatically part of vuejs. Do you have vuefire installed?
Vuefire supports two different ways of passing data to components:
let app = Firebase.initializeApp(config)
let db = app.database()

Vue.component('myComponent', {
  firebase: function() {return {
    foo: db.ref('path/to/foo')
  }},
  mounted: function() {return {
    this.$bindAsArray('bar',db.ref('path/to/bar')); // or use $bindAsObject depending on the type of data you're loading
  }}
}

That's all that's necessary; you can now use this.foo and this.bar in component code, or {{foo}} and {{bar}} in the component template, to access the firebase data from those paths.
You don't need to do this sort of thing in your components:
this.users.on("value", function(snapshot) {
  var username = snapshot.val().name;
});

because vuefire takes care of those bindings for you.
Once you have hold of a firebase reference, you can optionally pass it to child components as a regular prop and the binding will continue to work in the child component. So for example if that parent component's template contained <child-component :foo="foo" :bar="bar"></child-component> then the child would read the data like so:
Vue.component('childComponent', {
  props: ['foo','bar'],
  // ...
}

Passing database references around as component props is optional, but in many circumstances can be simpler than having each child component request its own data reference from Firebase. (There's not much difference in terms of performance; Firebase apparently handles its own cacheing internally for duplicate requests from different components.)
TL;DR
Looking at the screenshot you posted in comments: if that's what you're getting in this.users, it looks like your data binding is working, but may be pointing to the wrong path in your database, or your database structure may not be what you expect: you've got an array of three objects instead of a single user object.

A: Its better you start using vuex as your state management.
Since fetching data from firebase is asynchronous you must do the fetching process in the vuex action.
In vuex actions you can commit mutations, these are synchronous changes
So for your usage the vuex store would be:
import Vue from 'vue'
import Vuex from 'vuex'
import * as firebase from 'firebase'

Vue.use(Vuex);

export const store = new Vuex.Store({
    state:{
        user:{
            userName:'',
            orherData: null,
            someOtherData: null
        }
    },
    getters:{
        //getters return the state and can be used in your components to get the current value of the state,

        getUserInfo: (state) => {
            return state.user;
        }
    },
    mutations:{
        //mutation gets state as the 1st parameter and the paylozd you passed in the action you commited thiz mutation as 2nd parameter

        addUserInfo:(state, userInfo) => {

            //here you can change or mutate the values present in the state , in your case user.

            state.user.userName = userInfo.name;

        }
    },
    actions:{
        fetchUserData:({commit}) => {
            const ref = firebase.database().ref('Users');
            ref.child('-KjVxBYyKv3_PFLavId3').on('value', (snap) => {
                //you commit the  mutation passing the snapshot value you recieved from firebase as payload to the mutation
                commit('addUserInfo', snap.val());
            });
        }
    }

});

The advantage of a centalized state is that using vuex is that now you can acess your user info in any  component by using getters as follows:
computed:{
    userInfo: this.$store.getters.getUserInfo;
}

The computed property userInfo can be used in the html of you component