text:
Q: Edited form not getting saved in django I've fixed almost everything, the form opens and I can make the edits but as soon as I make the edits and click on save, this shows up:

I don't understand what's wrong. I did the same thing for my edit profile page and it worked perfectly there so I don't understand why it's not working here.
views.py:
class EditComplaint(UserPassesTestMixin, UpdateView):
   model = Complaint
   fields = ('reportnumber', 'eventdate', 'event_type', 'device_problem', 'manufacturer',
  'product_code', 'brand_name', 'exemption', 'patient_problem', 'event_text', 'document')
   template_name = 'newcomplaint.html'
   def form_valid(self, request):
       complaint = request.user.complaint
       form = ComplaintForm(instance=complaint)
       if request.method == 'POST':
          form = ComplaintForm(request.POST, request.FILES, instance=complaint)
          if form.is_valid():
             form.save()
       context = {'form': form}
       return render(request, 'newcomplaint.html', context)

   def test_func(self):
       complain = self.get_object()

       if self.request.user == complain.user:
           return True
       raise Http404(_('This complain does not exist'))

urls.py:
path('Complaint/<int:pk>/edit/', accounts.views.EditComplaint.as_view(),
name='Complaint')

What seems to be wrong? I think I need to change something in my views because everything else seems to work well so I'm not including anything else. But i don't understand what needs to be changed
forms.py:
class DateInput(forms.DateInput):
input_type = 'date'

class ComplaintForm(ModelForm):
   class Meta:
       model = Complaint
       fields = '__all__'
       widgets = {
           'reportnumber': forms.TextInput(attrs={'placeholder': 'Report
            number'}),
           'event_type': forms.TextInput(attrs={'placeholder': 'Event
            type'}),
           'eventdate': DateInput(),
           'device_problem': forms.TextInput(attrs={'placeholder':
           'Device Problem'}),
           'event_text': forms.Textarea(attrs={'style': 'height:
            130px;width:760px'}),
            'manufacturer': forms.TextInput(attrs={'placeholder': 'Enter
            Manufacturer Name'}),
           'product_code': forms.TextInput(attrs={'placeholder': 'Enter
            Product Code'}),
           'brand_name': forms.TextInput(attrs={'placeholder': 'Enter
            Brand Name'}),
           'exemption': forms.TextInput(attrs={'placeholder': 'Enter
            Exemption'}),
           'patient_problem': forms.TextInput(attrs={'placeholder':
           'Enter Patient Problem'}),
       }

   def clean(self):
       cleaned_data = super(ComplaintForm, self).clean()
       reportnumber = cleaned_data.get('reportnumber')
       event_text = cleaned_data.get('event_text')
       if not reportnumber and not event_text:
           raise forms.ValidationError('You have to write something!')
       return cleaned_data

models.py:
class Complaint(models.Model):
   user = models.ForeignKey(User, on_delete= models.CASCADE, null =
   True, blank=True)
   id = models.AutoField(blank=False, primary_key=True)
   reportnumber = models.CharField(max_length=500 ,null = True, blank=
   False)
   eventdate = models.DateField(null=True, blank=False)
   event_type = models.CharField(max_length=300, null=True, blank=True)
   device_problem = models.CharField(max_length=300, null=True,
   blank=True)
   manufacturer = models.CharField(max_length=300, null=True,
   blank=True)
   product_code = models.CharField(max_length=300, null=True,
   blank=True)
   brand_name = models.CharField(max_length = 300, null=True,
   blank=True)
   exemption = models.CharField(max_length=300, null=True, blank=True)
   patient_problem = models.CharField(max_length=500, null=True,
   blank=True)
   event_text = models.TextField(null=True, blank= True)
   document = models.FileField(upload_to='static/documents', blank=True,
   null=True)

   def __str__(self):
       return self.reportnumber

A: form_valid has as second parameter the form that has been validated, not the request. You can access the request with self.request.
But you do not need to handle this yourself: the UpdateView logic has already logic in place to create and validate a POST request. It will run form_valid only if the form is valid, and by default save the form and redirect to the success url:
from django.contrib.auth.mixins import LoginRequiredMixin

class EditComplaint(LoginRequiredMixin, UpdateView):
    model = Complaint
    form_class = ComplaintForm
    success_url = 'url-to-redirect-to'

    def get_queryset(self, *args, **kwargs):
        return super().get_queryset(*args, **kwargs).filter(
            user=self.request.user
        )

I did the same thing for my edit profile page and it worked perfectly.

Class-based views normally implement most of the codeflow, so it is usually only a matter of specifying some items like the form_class, success_url, etc. Usually, if you need to write large blocks of logic it means you implement the logic that is already there in place, or the view is complicated and thus should be implemented by a function-based view, or another class-based view.
When the success url depends on the object, you can override get_success_url:
from django.contrib.auth.mixins import LoginRequiredMixin
from django.urls import reverse

class EditComplaint(LoginRequiredMixin, UpdateView):
    model = Complaint
    form_class = ComplaintForm

    def get_queryset(self, *args, **kwargs):
        return super().get_queryset(*args, **kwargs).filter(
            user=self.request.user
        )

    def get_success_url(self):
        return reverse('Complaint', kwargs={'pk': self.object.pk})
You can automatically set the user by omitting the user field in the form, and set the user with:
from django.contrib.auth.mixins import LoginRequiredMixin
from django.urls import reverse

class EditComplaint(LoginRequiredMixin, UpdateView):
    model = Complaint
    form_class = ComplaintForm

    def get_queryset(self, *args, **kwargs):
        return super().get_queryset(*args, **kwargs).filter(
            user=self.request.user
        )

    def get_success_url(self):
        return reverse('Complaint', kwargs={'pk': self.object.pk})

    def form_valid(self, form):
        form.instance.user = self.request.user
        return super().form_valid(form)

Note: You can limit views to a class-based view to authenticated users with the
LoginRequiredMixin mixin [Django-doc].


text:
Q: Why do we use grand canonical ensemble for BEC description? The system we consider has constant $N$, $V$ and $T$ (the number of particles, volume and temperature) This is just the thermodynamic variables for the canonical ensemble, why we use fugacity $z$ or chemical potential $\mu$ there?

A: If you choose to set $N$, $V$ and $T$, then you are choosing the Canonical Ensemble, so $N$ is fixed. In this approach, the chemical potential $\mu$ is just a parameter that you've to determine by imposing that the total number of particles is $N$.
Viceversa, if you choose the grandcanonical ensemble, you fix $\mu$ and so the number of particles $N$, fluctuates around an average value $\langle N \rangle$. I hope that I've well understood your problem and answered properly.

A: In the thermodynamic limit fluctuations in particle number should tend to $0$ and so we should get the same result whether we use the cannonical or grand canonical ensamble. If we are ultimately interested in a system with a fixed particle number, we can, if we so choose, set up the problem in the grand cannonical ensamble and then invert the equation for $\langle N \rangle$ to find what chemical potential will give us the desired mean particle number.
For systems of identical quantum particles we generally choose to use the grand cannonical ensamble because it turns out to be dramatically simpler. In such systems it is convenient to use an occupation number representation for states, rather than listing the state of each individual particle, since it can then be assumed that an appropriate (anti-)symmeturization procedure has been applied and not have to think about it. In the cannonical ensamble, however, we now encounter a problem; since the total number of particles is fixed the occupaion numbers of differnet states are not independant, but must satisfy a constraint. This leads to a rather convoluted combinatorics problem to list the set of allowed ocupation numers.
In the grand cannonical ensamble we do not encounter this problem, since all values of $N$ are allowed. We simply consider all possible sets of occupation numbers, but since states with very large or very small particle number are exponentially weighted against, they do not contirbute. In effect we allow the statistics of the problem to "automatically" find the states with the correct particle number for us.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Screen resolution settings menu disappeared For some reason, I cannot edit screen resolution from the system settings menu. I have to do it with xrandr from the terminal, which is inconvenient for an eternally casual Linux user such as myself. Does anybody have an idea of what might be going wrong here? I tried doing sudo dpkg-reconfigure xserver-xorg like this extremely old Linux forum post suggests, but predictably it didn't work.
I am running Kubuntu 18.04
edit: Here is the output of xrandr (my screen's resolution is 1920x1080 for the record):
Screen 0: minimum 8 x 8, current 1920 x 1080, maximum 16384 x 16384
DVI-I-0 disconnected primary (normal left inverted right x axis y axis)
DVI-I-1 disconnected (normal left inverted right x axis y axis)
DVI-I-2 connected 1920x1080+0+0 (normal left inverted right x axis y axis) 477mm x 268mm
   1920x1080     60.00*+
   1280x1024     75.02    60.02
   1152x864      75.00
   1024x768      75.03    60.00
   800x600       75.00    60.32
   640x480       75.00    59.94
HDMI-0 disconnected (normal left inverted right x axis y axis)
DVI-I-3 disconnected (normal left inverted right x axis y axis)


text:
Q: Where should I place "only" in this sentence? I have three sentences that I am still not clear about. Are they correct or okay to use?

*

*Only will be send BILL and other documents after 100% payment has been completed.

*BILL and other documents will be send after 100% payment has been completed.

*Only BILL and other documents will be send after 100% payment has been completed.

Which one is okay to go for? Please help.
Thank you.

A: None of the above. the correct answer is:

The bill and other documents will be sent only after 100% payment has been completed.

Alternatively:

Only after 100% payment has been completed will the bill and other documents be sent.

3 might be correct in a different context - one that requires other documents e.g.:

The receipt will be sent immediately. Only (the) bill and other documents will be sent (send) after 100% payment has been completed.


text:
Q: Using SpriteKit crashes Xcode 8, is there a way to resolve? Whenever I try and add any SpriteKit elements to my project, Xcode crashes. The files are created but not added to the project and if adding them manually, it still crashes when trying to open them. After some searching it looks as though previous versions have suffered with the same issue. I had the same issue with 8 beta 6 too.
Is there anything I can do to help with the issue? I can't find anything on the most up to date version so I'm guessing it's either something I'm doing or a problem with my setup.

A: I've the same issue when I try to maintain 2 Xcode versions in the same system, it is possible but you should install them into separate directories, for example Xcode_731 and Xcode_8 (my actual version is 8A218a GM, I haven't any crash).
This should be unuseful without crashes, but try also to free some memory (quit also simulator app after your crash), in your terminal:
sudo purge


text:
Q: Proper Case with extra rules in Excel I have used vba for Proper Case in Excel but I need to add an exception rule for it to save much manual editing. I need the first letter after "-" to also be Capitalized, example is:
"michael-jordan" becomes "Michael-jordan" now when I run my script.
I need "michael-jordan" to become "Michael-Jordan".
Here is my code:
I also have an exception for "von", "af" and "de" in my code.
Sub ProperCase()

Dim rng As Range

'Use special cells so as not to overwrite formula.
For Each rng In Selection.SpecialCells(xlCellTypeConstants, xlTextValues).Cells
    Select Case rng.Value
        Case "von", "af", "de"
            rng.Value = StrConv(rng.Value, vbLowerCase)
        Case Else
            'StrConv is the VBA version of Proper.
            rng.Value = StrConv(rng.Value, vbProperCase)
    End Select
Next rng

End Sub

A: Here is a copy of my answer from this Post. It should work nicely for you.
I used Rules for Capitalization in Titles of Articles as a reference to create a capitalization exceptions list.
Function TitleCase uses WorksheetFunction.ProperCase to preproccess the text.  For this reason, I put in an exception for contractions because WorksheetFunction.ProperCase improperly capitalizes them.
The first word in each sentence and the first word after a double quotation mark will remain capitalized. Punctuation marks are also handled properly.
Function TitleCase(text As String) As String
    Dim doc
    Dim sentence, word, w
    Dim i As Long, j As Integer
    Dim arrLowerCaseWords

    arrLowerCaseWords = Array("a", "an", "and", "as", "at", "but", "by", "for", "in", "of", "on", "or", "the", "to", "up", "nor", "it", "am", "is")

    text = WorksheetFunction.Proper(text)

    Set doc = CreateObject("Word.Document")
    doc.Range.text = text

    For Each sentence In doc.Sentences
        For i = 2 To sentence.Words.Count
            If sentence.Words.Item(i - 1) <> """" Then
                Set w = sentence.Words.Item(i)
                For Each word In arrLowerCaseWords
                    If LCase(Trim(w)) = word Then
                        w.text = LCase(w.text)
                    End If

                    j = InStr(w.text, "'")

                    If j Then w.text = Left(w.text, j) & LCase(Right(w.text, Len(w.text) - j))

                Next
            End If
        Next
    Next

    TitleCase = doc.Range.text

    doc.Close False
    Set doc = Nothing
End Function

A: Instead of
rng.Value = StrConv(rng.Value, vbProperCase)

use
rng.Value = WorksheetFunction.Proper(rng.Value)

Though this does not consider cases like don't doesn't as mentioned by Thomas Inzina.

A: Here is a little VBA Function using Split wich should do the desired work:
Function properCase(str As String) As String

Dim splitStr() As String

splitStr = Split(str, "-")

Dim i As Integer

For i = LBound(splitStr) To UBound(splitStr) Step 1

    splitStr(i) = UCase(Left(splitStr(i), 1)) & Right(splitStr(i), Len(splitStr(i)) - 1)
Next i

properCase = Join(splitStr, "-")
End Function

A: Is there any reason to do this in VBA when it's easily done on the worksheet?
=PROPER("michael-jordan")

returns Michael-Jordan as required


text:
Q: Using Thread in a window 8 application Is there a way to use the Thread class inside a No-Longer-Named-Metro application?
I'm trying to write a timer class with a "TimeLeft" property and can't understand how to accomplish this using Tasks.

A: I would suggest using the DispatcherTimer class to accomplish doing timer.
var timer = new DispatcherTimer();
timer.Interval = TimeSpan.FromSeconds(1);
timer.Tick += OnTimerTick;

...
private void OnTimerTick(object sender, object e)
{
    // do somthing
}


text:
Q: UIImageView uses a lot of memory I'm creating some kind of image gallery. User can swipe between photo's. (Its just the concept, i know there are good library's out there that can handle this, but it's just to explain the concept).
I'm loading in 3 UIImageView, and i'm constantly reusing them. (Lazy loading). Problem is, when i change the image dynamiccaly from one imageview, and keep changing it, the memory is filling up. It's like it does not releases previous attached images. I'm using an array of UIImages that I already downloaded from some kind of web service.
As i load my view, i'm allocing and init my UIImageView,  then I add it to the view.
UIImageView* _imgView;
NSArray* _imgArray;

So this array contains UIImage
-(void)changeImageIndex: (int) i
{
   _imgView.image = [_imgArray objectAtIndex:i];
}

if i keep changing the imageindex, memory just gets filled up and filled up.. :s.
My project is ARC enabled.
Somebody has a clue how to solve it?
The image is added (actually changed) by this method:
-(void)setCurrentMovie:(GFilm*)film
{

    _currentMovie = nil;
    _currentMovie = film;
    _posterView.image = nil;
    [_youtubeView loadHTMLString:@"" baseURL:nil];
    [_youtubeView stopLoading];
    [_youtubeView setDelegate:nil];

    [[NSURLCache sharedURLCache] removeAllCachedResponses];
    [_scrollView setContentOffset:CGPointMake(0, 0) animated:NO];

    CGFloat leftHeight = 0.f;

    _leftView.frame = CGRectMake(10, 10, 110, 205);
    leftHeight += _leftView.frame.size.height;
    _posterView.frame = CGRectMake(0, 0, _leftView.frame.size.width, _leftView.frame.size.height - 40);

    GImage* img = (GImage*)[_currentMovie.imageList objectAtIndex:0];
    //_posterView.image = img.localImage;
    //@autoreleasepool {

    _posterView.image = [UIImage imageWithData:UIImagePNGRepresentation(img.localImage)];

    _btnVertoningen.frame = CGRectMake(0, _posterView.frame.origin.y + _posterView.frame.size.height + 5, _leftView.frame.size.width, 35);

    _posterView.userInteractionEnabled = YES;
    UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(posterClick)];
    singleTap.numberOfTapsRequired = 1;
    [_posterView addGestureRecognizer:singleTap];
    [_leftView addSubview:_posterView];

    CGFloat rightHeight = 0.f;
    _rightView.frame = CGRectMake(_leftView.frame.origin.x + _leftView.frame.size.width + 5, _leftView.frame.origin.y, self.view.frame.size.width - (_leftView.frame.size.width + _leftView.frame.origin.x) - 15, 1);

    _lblRegie.frame = CGRectMake(0, rightHeight, 48, 16);

    NSMutableString* text = [[NSMutableString alloc]init];
    NSArray*  arr = _currentMovie.directorList;

    etc.....
}

A: Probably your app have memory leak. Try use imageWithContentsOfFile instead of imageNamed:
_imgView.image =  [UIImage imageWithContentsOfFile:imagePath];

Another possibility to have memory leaks with ARC is using a separate thread without an autorelease pool set up. Check this link:
https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmAutoreleasePools.html:


text:
Q: How to handle error in parser javacc in attachment, my parser generated with javacc in eclipse. I don't know as to handle errors of sintax in my parser.
how I can to do? what ways there are?
I prefer if you can posting your code that show it.
Thank you very much in advanced.
    /**
 * JavaCC template file created by SF JavaCC plugin 1.5.17+ wizard for JavaCC 1.5.0+
 */
options
{
  JDK_VERSION = "1.5";
  IGNORE_CASE = true;
  LOOKAHEAD = 2;
  static = true;
}

PARSER_BEGIN(MyParser)
import java.io.* ;

public class MyParser
{
  public static void main(String args []) throws ParseException
  {
    Token t;
        MyParserTokenManager tm;
        int numToken = 0;

        if (args.length<1) {
            System.out.println("Sorgente non specificato");
            System.exit(1);
        }

        try {
            java.io.InputStream infile;
            infile = new java.io.FileInputStream(args[0]);
            tm = new MyParserTokenManager(new SimpleCharStream(infile));
        }
        catch (java.io.FileNotFoundException e) {
            System.out.println("File "+args[0]+" non trovato");
            return;
        } // catch

        t = tm.getNextToken();
        numToken++;
        while(t.kind != MyParserConstants.EOF){
            t = tm.getNextToken();
            System.out.printf("%s\t %s\n",tokenImage[t.kind],t.image);
            numToken++;
        }// while
  }

  static void error_skipto(int kind) {
  ParseException e = generateParseException();  // generate the exception object.
  System.out.println(e.toString());  // print the error message
  Token t;
  do {
    t = getNextToken();
  } while (t.kind != kind);
}
}

PARSER_END(MyParser)

void Stm() :
{}
{
  try {
    (
      SE()
    |
      MENTRE()
    |
      DO()
    |
      PER()
    |
      condizione()
    |
      espressione()
    |
      expres()
    )
  }catch (ParseException e) {
    error_skipto(PV);
  }
}

SKIP :
{
  " "
| "\r"
| "\t"
| "\n"
}

TOKEN : /* OPERATORS */
{
    <PIU: "+">
|   <MENO: "-">
|   <PER: "*">
|   <DIV: "/">
}

TOKEN :
{
    <PAR_SIN: "(">
|   <PAR_DES: ")">
|   <QUAD_SIN: "[">
|   <QUAD_DES: "]">
|   <UGUALE: "==">
|   <VIRGOLA: ",">
|   <ASS: "=">
|   <NEG: "?=">
|   <PV: ";">
|   <FOR: "da">
|   <TO: "a">
|   <IF: "se">
|   <ELSE: "altrimenti">
|   <END_IF: "fine">
|   <WHILE: "mentre">
|   <DO: "esegui">
|   <COST_INT: (["0"-"9"])+>
|   <ID: ["a"-"z","A"-"Z"]>

}

void SE() :
{}
{
  (<IF> <QUAD_SIN> condizione() <QUAD_DES> <PAR_SIN> espressione() <PV> <PAR_DES> <END_IF>)
|  (<IF> <QUAD_SIN> condizione() <QUAD_DES> <PAR_SIN> espressione() <PV> <PAR_DES> <ELSE> <PAR_SIN>
    espressione() <PV> <PAR_DES> <END_IF>)
}

void MENTRE() :
{}
{
  <WHILE> <QUAD_SIN> condizione() <QUAD_DES> <PAR_SIN> espressione() <PV> <PAR_DES>
}

void DO() :
{}
{
  <DO> <PAR_SIN> espressione() <PV> <PAR_DES> <WHILE> <QUAD_SIN> condizione() <QUAD_DES> <PV>
}

void PER() :
{}
{
  <FOR> (<ID>)+ <ASS> <COST_INT> <TO> (<COST_INT>)+ <PAR_SIN> espressione() <PV> <PAR_DES>
}

void condizione():
{ }
{
  (<ID>)+ (<NEG> | <UGUALE>) ((<ID>)+ | (<COST_INT>)+)
}

void espressione ():
{}
{
  (<ID>)+ <ASS> ((<ID>)+ | (<COST_INT>)+ | expres() )
}

void expres() :
{}
{
  ((<ID>)+ <PIU> ((<ID>)+ | (<COST_INT>)+))
| ((<ID>)+ <MENO> ((<ID>)+ | (<COST_INT>)+))
| ((<ID>)+ <PER> ((<ID>)+ | (<COST_INT>)+))
| ((<ID>)+ <DIV> ((<ID>)+ | (<COST_INT>)+))

}


text:
Q: JS: Regex in replace i need this in php to javascript.
echo preg_replace('/(\S)+\?/', '', 'http://example.com/?test=1');

THX
BTW: I tried
alert('http://example.com/?test=1'.replace('/(\S)+\?/g', ''));

but no happens.

A: Remove quotes from your RegExp:
alert('http://example.com/?test=1'.replace(/(\S)+\?/g, ''));

If you have quotes there, then it's trying to replace the string '/(\S)+\?/g' with '', and therefore not doing regular expression replace.

A: You need to create a regular expression object:
alert('http://example.com/?test=1'.replace(/(\S)+\?/g, ''));


text:
Q: How easily will uniqid() with more entropy create a duplicate? This might be an off topic question but i hope someone can answer this question.
Per how many nanoseconds, mili seconds or seconds does uniqid() with more entropy run the risk of creating a duplicate?
With reference to link below, uniqid will collide if two id are created in one milisecond. What about with more entropy?
(My goal is to use a small indexable alphanumeric string as document id at creation that can be created fast with minimum processor power without db interference.)
Answers here dont seem to provide any exact number:
How unique is uniqid?

A: From the source code, more_entropy adds nine random decimal digits, so you can expect a collision after 37,000 or so calls. (For how a billion turned into 37,000, see the birthday attack.) That of course ignores the fact that these digits are not actually random but generated by an LCG, and the same LCG is probably used in other places in the code, so the actual chance of collision is probably higher (by how much exactly, I have no idea).
Also worth noting that uniqid does not actually guarantee microsecond resolution as some PHP implementations (Windows, specifically) don't have access to a microsecond-precision clock.
In short, if you need a unique ID for anything security-sensitive, or collisions are costly, avoid uniqid. Otherwise, using it with more_entropy is probably fine (although the common pattern is to use uniqid(mt_rand(), true) to add even more extra entropy).


text:
Q: How to get php string values already set into an array I get some values from laravel query builder. I would like to get and set these values into somewhere of my code. So i get undefined index exception message with the following codes :
laravel query :
$generatedRowValue = DB::table('myTableName')
                         ->where('id', '=', 'someValue')
                         ->where('anyOtherValue', '=', 'anotherValue')
                         ->get();

I want to reach the values set in $generatedRowValue variable.
P.S. : Yeah i can get the values from the query, checked it out with var_dump(); dd(); etc. and i know my values are not undefined.
I'm new on this platform so i don't know how to reach these values.
Any help would be appreciated.
---UPDATE---

This is a simple HTML file which includes php partially.
<?php
   $html = new simple_html_dom();
   $html->load('<input type="text" value="'.$generatedRowValue['thevalueName'].'">')
?>

So i need $generatedRowValue['thevalueName'] 's value.

A: get() returns an array of objects. I think you want to use first() instead since you only expect one result.
$generatedRowValue = DB::table('myTableName')
                     ->where('id', '=', 'someValue')
                     ->where('anyOtherValue', '=', 'anotherValue')
                     ->first();

By the way, you can also use the object syntax in your view (if you want)
$generatedRowValue->thevalueName


text:
Q: Link only available for my own app I upload some data to my server with my application. I send the data to a PHP file on the server and this PHP write the data in my database. This works fine.
But currently I have the link to this PHP unsave in my Android code.
Is there a possibility to save this link or make my PHP only for my app available?

A: Try to send some secret key as GET parameter to your PHP script.
You can set it on your app and then check it in your PHP script.
Something like this:
script.php?key=893284932890482304

And in your PHP script:
if ($_GET['key'] = '893284932890482304')
{
   // do the rest
}

Another option is to set "User-Agent" in your app and then check this information in your PHP script. To be honest, I have no idea how to set "User-Agent" in Android app or iPhone app or whatever you have there, but there is probably some way to do so.

A: A static key could work but if the key is compromised by an app owner sniffing their own network traffic this protection will quickly break. A cryptographic system should be used instead, for example simple hashing of a secret salt with the time and date.
Both the client and the server should take the date and time to the minute in the same string format, concatenate it with a secret salt, and hash that. As long as the times are in synchrony, it should be fine.
You can also use a challenge-response system. The first request gets a challenge value, and all future requests include hash($challenge.$secretkey) which the server verifies.
More complex but worthwhile is OAuth.


text:
Q: How to pass list of images as MLMultiArray in coreML Swift? I have a image classification model, whose input is:
MultiArray (Float32 1 × 224 × 224 × 3)

and output:
MultiArray (Float32)

And I am not able to figure out how to pass the input in the prediction function.
I have a list of images, which i got through this code

let fileList = FileManager.default.enumerator(at: url, includingPropertiesForKeys: keys)
let ar = try? MLMultiArray(shape: [1, 224, 224, 3], dataType: MLMultiArrayDataType.float32)
let model = try Classification(configuration: MLModelConfiguration())
for case let file as URL in fileList {
    guard url.startAccessingSecurityScopedResource() else {
        continue
    }
    let image = UIImage(contentsOfFile: file.path)!

    // ar?[i] = getArrayOfBytesFromImage(imageData: image.jpegData(compressionQuality: 1)! as NSData)
    url.stopAccessingSecurityScopedResource()
}

How can I pass list of images into MLMultiArray?


text:
Q: State not updating as a plain value, but updates as a function I just get this situation, I'm using react-use useKey hook and got a pretty weird behavior
The usage example of this hook is that:
import {useKey} from 'react-use';

const Demo = () => {
  const [count, set] = useState(0);
  const increment = () => set(count => ++count);
  useKey('ArrowUp', increment);

  return (

      Press arrow up: {count}

  );
};

As we can see it uses a function on the state update method set, but I found that too much and tried to made a simple change:
import {useKey} from 'react-use';

const Demo = () => {
  const [count, set] = useState(0);
  const increment = () => set(count + 1);
  useKey('ArrowUp', increment);

  return (

      Press arrow up: {count}

  );
};

The only change I've made was replacing that count => ++count with count + 1, but for some reason my change does not work, it acts like the new value of the state don't update on the increment function, but it does on the component.
Like, if I console.log on the component body it shows me 0 at first and then 1 after press arrow up, but if I press arrow up again the state does not update and if I try to log count inside the increment function it stills show 0.
Does anyone know why this is happening?

A: on react when your state depends on old state value you must update it like this :
const increment = () => set(oldcount=>oldcount+ 1);

check The React documentation for more info


text:
Q: Understanding, countable or not? Read the sentence below-

"Christine Sterling's determination to repackage her Olvera Street concept into something Chinese has been matched by her total lack of understanding of our culture, history, and taste."

I wonder if the word 'understanding' here is countable or uncountable
Sorry, if you find this question easy, stupid or useless, I'm a beginner.

A: This question is not useless.  It is not stupid.  It is certainly not easy.
American English is my native and only language.  Even so, I find that I'm not completely sure whether this specific instance of "understanding" is countable.  I suspect that it is not, but I can't quite prove that it isn't.
On one level, we're talking about one understanding of Chinese sensibility, in contrast to other, better understandings of it.  I have an understanding.  You have an understanding.  Christine has an understanding that is (or so we can easily assume) worse than both of ours.  That's three understandings that I can easily count.
On another level, we're not talking directly about an understanding.  We're talking about a lack.  I can assume that her lack is more severe than my lack.  I can further assume that my lack is still quite significant.  I have no doubt at all that these are two countable lacks.  The grammar of the sentence supports this notion -- she has a lack, one lack that is all her own.
If the sentence read "her total lack of an understanding", then I'd be certain that it was countable.  If it read "her total lack of any understanding", then I'd be certain it was not.
I think that this is the uncountable sense.  I think that "a total lack of understanding" is closer to "a lack of any understanding" than it is to "a lack of an understanding".
I suspect that we both need to wait for a better answer.

Edit:
On second thought, I have to assume that this use is uncountable.  The countable use would have to include something that implies counting, such as the indefinite article.  The counting of "lack" can be implied by the genitive pronoun "her".  The counting of this "understanding" isn't implied by anything, and that implies that there is nothing to count.
If this is the countable sense, then we should be able to make a plural form make sense.  For instance, "Our understandings are different" seems to be a sensible use of the countable sense.  However, if I talk about how both you and I lack understanding, "We both have a lack of understandings" doesn't seem as sensible.  It does seem sensible to say "We both have a lack of understanding."  In this context, the uncountable sense makes more sense.

A: Abstract nouns are generally uncountable but then it is not a rule of thumb. Depending upon the context, they can be used as countable.
EnglishPractice website quotes -

The uncountable form is used with a 'general' meaning whereas the countable form has a 'particular' meaning.

Cambridge Dictionary supports that.
In your case, it seems uncountable. But then, understanding can be used as a countable noun.
Have a nice time!

COCA gives 2 result of the phrase lack of an understanding over 430 results of lack of understanding

A: "Understanding" is not countable. You wouldn't say something like "five understandings".
You might be confused because people talk about partial understanding, or understanding something better. But understanding is continuous. You can have more or less, but you can't have two or three. Continuous things are not (directly) countable.


text:
Q: When can cohomology be calculated on the coarse moduli space? Suppose $\cal{X}$ is a DM-stack, and X its coarse moduli space. Let F be a sheaf on $\cal{X}$, and $\pi : \mathcal{X} \to X$ the projection. In all examples I have seen, it has been true that
$H^i(\mathcal{X},F) = H^i(X,\pi_\ast F)$.
Is there a simple example where this fails? Are there easy conditions where this is true?

A: (This mostly just adds some references to Tyler's answer)
$\newcommand{\X}{\mathcal X}$
As Tyler said, if $F$ is a quasi-coherent $\cal O$-module, you get the Grothendieck spectral sequence
$$H^p(X,R^q\pi_*(F))\Rightarrow H^{p+q}(\X,F)$$
so it suffices to impose the condition that $R^q\pi_*=0$ for $q>0$ (i.e. that $\pi_*$ is exact). This is exactly the condition that $\X$ is tame. See Abramovich-Olsson-Vistoli's Tame stacks in positive characteristic. In particular, DM stacks in characteristic 0 are always tame.†
Note that it didn't matter that $\pi$ was a coarse space map. We just needed that $\pi_*$ is exact (that "$\pi$ is cohomologically affine"). In particular, the isomorphism holds when $F$ is quasi-coherent and $\pi:\mathcal X\to X$ is a good moduli space.
† This is asserted in the first paragraph of the paper, but I don't see how to prove it. Perhaps somebody could clarify in a comment.

A: Let k be a field and your DM-smack be [Spec(k)//G] for a trivial action of a group G.  A sheaf on this stack is roughly a sheaf with a group action, and cohomology is group cohomology.  If you consider a sheaf where multiplication by |G| is invertible, then group cohomology vanishes in high degrees, but otherwise there is a lot of information not coming from the cohomology of Spec(k).
EDIT: Under amenable circumstances when the left adjoint $\pi^\*$ is exact, you can get a sufficient condition for your isomorphism to hold. (I'm not sure what kind of topology you want to work with, or whether you're working with simply sheaves of abelian groups or sheaves of $\mathcal{O}$-modules or quasicoherent modules or...) In this case, $\pi\_\*$ preserves injectives and so there's a Grothendieck spectral sequence
$$
H^p(X, {\mathbb R}^q \pi\_* F) \Rightarrow H^{p+q}(\mathcal{X},F)
$$
and so a sufficient condition is for the higher direct image functors $\mathbb{R}^q \pi\_* F$ to vanish for q > 0.  These are the sheaves associated to the presheaves $U \mapsto H^q(\pi^{-1} U, F)$, and often their stalks are related to the cohomology of the fibers of $\pi$ - which are, in this case of a DM-stack, pretty much the group cohomology of the stabilizers.


text:
Q: i can't delete component in CRUD app on button click trying to delete component on button click
i have added unique id to component but i cant access it
this is my main parent component, and i am trying to delete the Person Component on click of remove button
class MyFriends extends Component{

  state = {
    persons: [],
  }

   async componentDidMount( ){
     let response = await axios(`https://randomuser.me/api/?results=1`)
     this.setState(prevState => ({
       persons: [...prevState.persons, ...response.data.results]
     }))
  }

   update = async () => {
    const response = await axios(`https://randomuser.me/api/?results=1`)

    this.setState(prevState => ({
      persons: [...prevState.persons, ...response.data.results]
    }))

  }

  handleDelete = (e) => {
    const test = this.state.persons.splice(-1)
    let oare = this.state.persons.filter( i => i !== test)
    this.setState({
      persons: oare
    })
  }

  updatePerson = (state, first, last, age, email, numar, pic, nat) => {
    const persoana_noua = {
      name: {first: first, last: last},
      dob: {age:age},
      email: email,
      login: {sha1: numar},
      picture: {large:pic},
      nat: nat,
    }

    const proba = this.state.persons
    this.setState(prevState => ({
      persons: [ ...prevState.persons, persoana_noua]
    }))

  }

  remove = (e) => {
    e.persist();
    e.target.value = 1
    // this.setState(prevState => ({
    //   persons: [...this.state.persons.filter(i => i.target.id.value !== test)]
    // }))

     console.log(e.target.id.value)
  }

  render(){

    const test = this.state.persons.map( i =>
      <Person  data={this.state} remove={this.remove} test={this.just_testing} consoleLog={this.updatePerson} key={i.login.sha1} id={Math.random()} first_name={i.name.first} last_name={i.name.last} nat={i.nat}
      picture={i.picture.large} email={i.email} age={i.dob.age}
      />
    )
    return(

      {test}
      <button style={{fontSize: '2em', border: '1px solid green'}} onClick={this.update}>add new friend</button>
      <button style={{fontSize: '2em', border: '1px solid green'}} onClick={this.handleDelete}>delete
      last added friend
      </button>
      <button onClick={this.handleChange}>test</button>

    )
  }

}

export default MyFriends;

and this is my child component which i am trying to delete, it has a unique id and Key , but i cant access it , to use filter in state

class Person extends Component {
    state={
      modifica : false,
    }

    handleToggle = (e) => {
      this.setState({
        modifica : !this.state.modifica
      })

    }
    handleSubmit = (e) => {

      const first_name  = document.querySelector('.first_name input').value;
      const last_name = document.querySelector('.last_name input').value;
      const age = document.querySelector('.age input').value;
      const email = document.querySelector('.email input').value;
      const numar = Math.random();
      const pic = this.props.picture;
      const nat = this.props.nat;
      e.preventDefault();
      this.props.consoleLog(this.props.data, first_name, last_name, age, email, numar, pic, nat);
      const form = document.querySelector('form')

      this.setState(prevState => ({
        modifica: false,
        persons: [this.props.data]
      }))
      //this.props.test()
    }

    render(props){

      if(this.state.modifica){
        let individ = {}
       individ =

          <form  name= 'person' onSubmit={this.handleSubmit}>

First Name: <input  name = 'person' type='text'/>

Last Name: <input type='text' />

Age: <input type='number' />

            <img className='flag' src={`https://www.countryflags.io/${this.props.nat}/flat/64.png`}/>

email:<input type='text' />

            <button >Save</button>

          </form>

        return individ
      }else{
      const individ =

First Name: {this.props.first_name}

Last Name: {this.props.last_name}

 Age : {this.props.age}

            <img className='flag' src={`https://www.countryflags.io/${this.props.nat}/flat/64.png`}/>

email: {this.props.email}

            <button onClick={this.handleToggle}>edit</button>
            <button  onClick={this.props.remove}>remove</button>

          return individ
        }
    }
  }
export default Person;

A: Okay so I checked out the code you have and the mistake is a little subtle, but the core of it is that e.target refers to the element that fired the event not the parent component.
If you modify your remove() method in the MyFriends component you can see the error:
remove = e => {
    e.persist();
    e.target.value = 1;
    // this.setState(prevState => ({
    //   persons: [...this.state.persons.filter(i => i.target.id.value !== test)]
    // }))

    console.log(e);
    console.log(e.target);
    console.log(e.target.id.value);
  };

the console logs I see when I do this are:
Class {dispatchConfig: Object, _targetInst: FiberNode, nativeEvent: MouseEvent, type: "click", target: HTMLButtonElement…}

<button value="1">remove</button>

undefined

So clearly e.target is referring to the button that was pressed to trigger the event.
To perform your intended action you need to find a way to pass the id of the Person into the this.props.remove method instead of just passing the event.
A good way would be using the this.props.id field to gain access to this data.

A: You cannot use e.target.value here are you are not using any form element in delete. Accesses the item to be removed by an id (person id) or using array index.
Something like this should work for you.
Pass the array index to remove method.
remove = (index) => {
  let newPersonList = this.state.persons.splice(index, 1); // the item from array

    this.setState({ persons: newPersonList });
  }

And modify remove props of Person like this
const test = this.state.persons.map( (i, index) =>
      <Person  data={this.state} remove={()=>this.remove(index)} test={this.just_testing} consoleLog={this.updatePerson} key={i.login.sha1} id={Math.random()} first_name={i.name.first} last_name={i.name.last} nat={i.nat}
      picture={i.picture.large} email={i.email} age={i.dob.age}
      />
    )

A: with help from kiranvj i found the solution ( thx again kiranvj ) , so first we need to select the correct Component of which the pressed "remove" button belongs to, then apply filter method and compare all existing Components to the selected one , which will return an array with out the particular Component on which we pressed the "remove" button , and apply the array returned to the setState. Here is the code :
  remove = (index) => {
  let newPersonList = this.state.persons.splice(index, 1); // the item from array
  const proba = this.state.persons.filter(i => i !== newPersonList)
  this.setState({
    persons: proba
  })
  }

i am still struggling to understand how to correctly select elements in events in react.js so if you guys have any material i can read or watch to better understand the concept please link


text:
Q: Google Map in Window Store App in C# Is it possible to use google map API in windows metro style app using C# and XAML ?

A: It's very possible. Use JSON or REST Services entailed in the Google MAP API. With those you can do just about any platform. Please state what you've tried, and be more specific in the future.


text:
Q: Console Pasting Newlines Pycharm In pycharm version 2017.2.3, when you copy from console and paste in console, it generates a new line. How to disable that?

A: Inspired from answers here:
1.Settings
2) Keymap
3) Search in keymap: "Copy as Plain Text"
4) Right click and add keyboard shortcut
5) Fill in with Ctrl+C
6) Answer: "remove" if prompted on already mapped key


text:
Q: Extracting multiple values from a hash in ruby, modifying the original hash and returning the extracted values I have a YAML file which I am using to seed some Ruby on Rails models. I load this using YAML.load(filename). Some of the keys need some post processing before creating the RoR models, for example, files need to be opened from filenames.
I want to extract two values from the hash into variables, leaving the hash without these values present.
What is the most idiomatic way of doing this in Ruby?
Edit:
I have tried doing:
value1 = hash.delete(:key1)
value2 = hash.delete(:key2)

which gives me value1 and value2 fine but leaves hash unchanged.

A: How about to use an enumerator and extract each value from hash, retaining the hash in it's original entity.
hash = { :key1 => value1, :key2 => value2 }

# Iterates over values
hash.each_value {|val| print val}

or another alternative:
print hash.shift[1] while not hash.empty?

Normally the delete method delete the specified key from hash and returns the deleted value.
hash.delete (:key1) # => returns the deleted value. Now the hash should contain {:key2=>value2}

A: The hash generated by YAML.load uses string keys rather than symbol keys. I was trying to delete using symbol keys so nothing was being deleted.


text:
Q: ASP.NET MVC 5 Model Navigation Properties Error So I have two models that I am trying to get working,
public class Contract
{
   [Key]
   public int Id { get; set; }
   public string AwardId { get; set; }

   [ForeignKey("Id")]
   public virtual ICollection<ContractHistory> contractHistory { get; set; }
}

And
public class ContractHistory
{
   [Key]
   public int Id { get; set; }
   public string AwardId { get; set; }

   [ForeignKey("Id")]
   public virtual Contract contract { get; set; }
}

There are many ContractHistory related to one Contract.
I keep getting a run-time InvalidCastException with that setup but when I remove the navigation property within the ContractHistory, and modify the Contract navigation property to:
public virtual ContractHistory contractHistory { get; set; }

It performs the join correctly without any errors.
I only have a year of experience working with .NET and at a lose as to what the issue could be. Ideally, I would like to navigate from Contract to a list of ContractHistory and from ContractHistory to one Contract. Worst case would be for me to create independent data repository methods to explicitly pull in these records but would prefer to figure out the solution to this problem for future reference.
Any advice or follow up questions are welcomed and thanks in advance!

A: As far as I see you want to implement one-to-many relationship, if so you have to remove the foreginkey attribute from the contract history collection in the contract class, and add contractId property as foreignkey in the contract history class as below:
public class Contract {
[Key]
public int Id { get; set; }
public string AwardId { get; set; }

public virtual ICollection<ContractHistory> contractHistory { get; set; }
}

public class ContractHistory {
[Key]
public int Id { get; set; }
public string AwardId { get; set; }

public int ContractId { get; set;}

[ForeignKey("ContractId")]
public virtual Contract contract { get; set; }
}

A: Your ContractHistory class does not have a foreign key property.
Furthermore, you don't need to have the ForeignKeyAttribute overtop of public virtual ICollection<ContractHistory> contractHistory { get; set; } because you should be referencing the foreign key in the ContractHistory class.
The ForeignKeyAttribute constructor takes a string as a parameter.
Per MSDN

Parameters
name
Type: System.String
If you add the ForeigKey attribute to a foreign key property, you should specify the name of the associated navigation property. If you add the ForeigKey attribute to a navigation property, you should specify the name of the associated foreign key(s). If a navigation property has multiple foreign keys, use comma to separate the list of foreign key names.

So in your case:
[ForeignKey("Id")]
public virtual Contract contract { get; set; }

You are placing the ForeignKeyAttribute on the navigation property, contract.  So essentially your class will search for a property called Id and identify that as the foreign key.  But in your class, Id has the Key attribute which means you are declaring that as your primary key.
So in order to resolve this, you need to add another property to your ContractHistory class that will be the foreign key.  And then change the string in your ForeignKeyAttribute to the name of that property.
Example:
public class ContractHistory
{
    [Key]
    public int Id { get; set; }
    public string AwardId { get; set; }
    public int contractID {get;set;}

    [ForeignKey("contractID")]
    public virtual Contract contract { get; set; }
}

Hope this helps!


text:
Q: Why are daylighting fibre optics so much more inefficient than other fibre optic cables? Comparing Optical Fiber Light Tubes losses and regular Fiber Optic Losses, there seems to be a large disparity.
The light tubes reach 100m, whereas the regular ones go for kilometers.
I've tried to look into it via the wikipedia sources, but all I can guess is that having multiple daylight wavelengths interfere?
What physical property causes this loss in the light tube version vs the non-light tube version?

A: Promoted from a comment:

Long haul fiber optics use a very narrow range of wavelengths selected for being centered on the minimum loss window of highly-pure silica around 1.5 microns. The desire to stretch across oceans with minimal repeaters drove a very large research effort. Bringing some light a 100 meters or so has no such hard engineering requirements and is driven by cost not performance.


text:
Q: Continuous monotone maps and pre-image of connected sets. Given a continuous monotone function $f: \mathbb{R}^n \rightarrow \mathbb{R}^n$, is it true that for any connected subset $C\in \mathbb{R}^n$, $f^{-1}(C)$ must also be connected?
The definition of monotonicity that I am using is the following:
If $f: \mathbb{R}^n \rightarrow \mathbb{R}^n$ is monotone, then for all $p, q\in \mathbb{R}^n$, $(p - q) \cdot (f(p) - f(q)) \geq 0$, where $\cdot$ is the inner product of vectors.

A: Here is a counterexample.
Let $f:\mathbb R ^2\to \mathbb R ^2$ be defined as follows.
(1) I am first going to homoemorphically deform the domain, and then define the mapping. First, think of the domain as the strip $\mathbb R \times (0,1)$. Now bend the ends at $\pm$ infty around so that you form something homeomorphic to an open annulus minus a radial line segment.

(2) Put this in the $x$-$y$-plane in $\mathbb R ^3$ (i.e.,  the plane $z=0$). Deform it into part of a spiral by pulling the top part to height $z=1$. So now the closure has two "radial" segments, one above the other.
(3) Add a vertical copy of $[0,1)\times (0,1)$ between the two "radial" segments, so that $\{0\}\times (0,1)$ coincides with the radial segment in the $z=1$ plane.

The resulting set is still homeomorphic to $\mathbb R ^2$.  Now let $f$ be its projection onto the plane $z=0$ (so $f$ maps $\mathbb R ^2\to \mathbb R ^2$). You can check that the preimage of a point in the $z=0$ plane is either empty, a single point, or a segment like $[0,1)$. Thus $f$ is monotone.
Note that the image of $f$ is the entire open annulus.  Let $C$ be an arc inside this annulus that cuts across the initial radial segment.

Then $C$ is connected but $f^{-1}[C]$ is not.


text:
Q: Key functionality is disappearing I have literally no clue what is happening or why.
My computer is relatively new (a couple of months old). I'm running Ubuntu 20.04. I keep the computer in pretty good shape (don't do anything crazy with it, don't eat over it, if it leaves the house it's in a bag, etc.) Recently, and for no good reason, the super key (the Windows key) just stopped functioning. Thinking it was a hardware issue, I opened the console and ran showkey, which showed that when I pressed the key, the console logged keycode 240 press and keycode 240 release. So it's not a hardware issue--the key still works. But the bindings aren't working, and when I press it on its own--which should display all open windows--nothing happens.
What happened here and why? How do I fix this?

A: I've discovered that there is a second "mode" for the super key, which is reached by the Fn-SuperKey combination. When Fn-SuperKey is pressed, the super key will "flash" each time it is pressed, instead of maintaining a sustained input. Pressing Fn-SuperKey again will release that "mode" and return functionality to normal.
I'll continue doing some research as to exactly what this functionality is and why it is exists, but that is what is happening and why.


text:
Q: BGL Interior properties for implicit graph I'm trying to use the A* search from Boost BGL on an implicit graph. I have implemented my own graph type which models the concept of Graph and IncidenceGraph. According to the documentation of A*, I should be using the astar_search_no_init function with implicit graphs.
Just to get the whole thing working, I have tried to implement dummy versions of all of the needed concepts. This includes the graph, the visitor, the heuristic and the vertex type. My main function looks like this
int main()
{
   graph g;
   // The vertex type is a simple wrapper for int.
   vertex start(1);
   vertex goal(10);

   boost::astar_search_no_init(g, start, heuristic(),
        boost::visitor(visitor(goal)));
}

Without specifying any of the named parameters, the implementation should be using some default values. Apparently these default values require some support from my graph. The graph looks like this:
struct graph
{
   typedef void adjacency_iterator;
   typedef void in_edge_iterator;
   typedef void vertex_iterator;
   typedef void edge_iterator;
   typedef void vertices_size_type;

   typedef void edge_iterator;
   typedef void edges_size_type;

   typedef vertex vertex_descriptor;
   typedef double edge_descriptor;
   typedef boost::directed_tag directed_category;
   typedef boost::disallow_parallel_edge_tag edge_parallel_category;
   typedef boost::incidence_graph_tag traversal_category;

   typedef std::vector<double>::iterator out_edge_iterator;
   typedef int degree_size_type;
};

When compiling, the first and the most interesting error is this:
error C2039: 'edge_property_type' : is not a member of 'graph'
From what I understand, I need to add properties for my graph. I believe these properties should be interior properties. My question is: how do I add interior properties for my own implicit graph type?


text:
Q: How to get a mask from every country This is my map image
imgPro = Uncompress[FromCharacterCode[
   Flatten[ImageData[Import["http://i.stack.imgur.com/Zoj4F.png"],"Byte"]]]]

I want to get a mask from every country.But note the color is not very pure in my imgPro,which is a difficult points in this question.
Colorize[IntegerPart[
  ArrayComponents[Map[Total] /@ ImageData[imgPro]]]]

Note the part pointed by red arrow,which mean the color is slight different with the ambient color.This is a method by DominantColors.
Flatten[Image /@ Values[ComponentMeasurements[#, "Mask"]] & /@
  Rest[DominantColors[imgPro, Automatic, "CoverageImage",
    MinColorDistance -> .1]]]

But I'm not very content with it,because I think it will fail to implement it when there are two adjacent country with similar color in the map image.Is there better method can do this?


text:
Q: Middleware not workign as expected in Laravel 5.2 I have made middleware that checks if class exists as per url segment and conducts appropriate tasks.However before the middleware is triggered laravel catches the exception and throws error:
    ReflectionException in Route.php line 280:
Class App\Http\Controllers\cms\modules\asdfasdfsadf\asdfasdfsadfController does not exist

if I die and dump any thing on checkClass middleware the value is dump only when the class exists.
My route where middleware is applied is:
Route::group(['prefix' => PREFIX,'middleware'=>array('auth','role','checkClass')], function () {
    Route::group(['namespace' => 'cms' . '\\modules\\' . Request::segment(2) ], function () {

        Route::get('{module}/pages/{page}', Request::segment(4) . 'Controller@index');

        Route::get('{module}', Request::segment(2) . 'Controller@index');

        Route::get('{module}/{page}', Request::segment(2) . 'Controller@' . Request::segment(3));

        Route::post('{module}/{page}', Request::segment(2) . 'Controller@' . Request::segment(3));

        Route::get('{module}/{page}/{id}', Request::segment(2) . 'Controller@' . Request::segment(3));

        Route::get('{module}/pages/{page}/{id}', Request::segment(4) . 'Controller@' . Request::segment(5));

        Route::post('{module}/pages/{page}/{id}', Request::segment(4) . 'Controller@' . Request::segment(5));

        Route::get('{module}/pages/{page}/{abc}/{id}', Request::segment(4) . 'Controller@' . Request::segment(5));

        Route::post('{module}/pages/{page}/{abc}/{id}', Request::segment(4) . 'Controller@' . Request::segment(5));
    });
});

Here we can see that I have dynamically created routes as per URL segment.Here is my checkClass middleware:
    <?php

namespace App\Http\Middleware;

use Closure;
use Request;
use Illuminate\Contracts\Auth\Guard;

class CheckClass
{
    /**
     * The Guard implementation.
     *
     * @var Guard
     */
    protected $auth;

    /**
     * Create a new filter instance.
     *
     * @param  Guard  $auth
     * @return void
     */
    public function __construct(Guard $auth)
    {
        $this->auth = $auth;
    }

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {

        if (!class_exists('App\\Http\\Controllers\\cms\\modules\\'.Request::segment(2).'\\'.Request::segment(2).'Controller')) {

                return view("errors.404");

        } else {
            return $next($request);
        }

        return $next($request);
    }
}

Shouldn't middleware fire before laravel searches controller class as per route ?

A: The middleware are fired after Laravel finds the route since it needs to find out which middleware to use (since a route can be nested in multiple groups and such).
This error however should result in a 404 by default. Maybe check youre exception handler to make sure it does (and check with app.debug set to false because it then displays exceptions like this instead of just showing a 404.


text:
Q: List index out of range for Python I have a question regarding the following exercise:
def addstock():
        time = datetime.now().strftime("%B %d, %Y")
        hour = datetime.now().strftime("%I:%M%p")
        query = 'SELECT TotalStock FROM Stocks WHERE name = ? ORDER BY MovementID DESC LIMIT 1'
        parameters = (name.get(),)
        lastrecord = run_query(query, parameters)
        print(float(lastrecord.fetchall()[0][0]))
        print(float(quantity.get()))
        totalstock = (float(lastrecord.fetchall()[0][0])) + (float(quantity.get()))
        query = 'SELECT precio FROM product WHERE name = ?'
        precio = run_query(query, parameters)
        pricequant = precio.fetchall()[0]
        pricequantity = pricequant * quantities
        query = 'SELECT precio FROM product WHERE name = ?'
        parameters = (name.get(),)
        precio = run_query(query, parameters)
        priceforall = pricequant * totalstock

In this function, I print lastrecord.fetchall()[0][0] and quantity.get to make sure they are float. So the program prints in that case: 5.0 for lastrecord.fetchall and quantity.get
Up to now, no problem, but when I try to us them up, it gives me an error of List Index Out Of Range, so program do not find the value of lastrecord.fetchall()[0][0] which 2 lines before I was able to print successfully. Can someone explain why?

A: According to documentation:

The method fetches all (or all remaining) rows of a query result set and returns a list of tuples. If no more rows are available, it returns an empty list.

When you first time used lastrecord.fetchall()[0][0] all the records of lastrecord curser are fetched, so on the second call on totalstock = (float(lastrecord.fetchall()[0][0])) + (float(quantity.get())) there is no more rows left for the curser. If you want to reuse the fetched data, store it, then use it anytime you want, like this:
all_records = lastrecord.fetchall()
// ...
print(float(all_records[0][0]))
// ...
totalstock = (float(all_records[0][0])) + (float(quantity.get()))


text:
Q: Cardview inside tab fragment I'm working on material design navigation drawer with sliding tabs and I have implemented the same.
Now I want to add cardview with recycler view inside one of the tab fragment but don't know how to do it.
Please can someone help me with this?
Here's my Tab fragment code:-
    public class TabFragment extends Fragment {

    public static TabLayout tabLayout;
    public static ViewPager viewPager;
    public static int int_items = 2 ;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        /**
         *Inflate tab_layout_tens and setup Views.
         */
        View x =  inflater.inflate(R.layout.tab_layout_tens,null);
        tabLayout = (TabLayout) x.findViewById(R.id.tabs);
        viewPager = (ViewPager) x.findViewById(R.id.viewpager);

        /**
         *Set an Apater for the View Pager
         */
        viewPager.setAdapter(new MyAdapter(getChildFragmentManager()));

        /**
         * Now , this is a workaround ,
         * The setupWithViewPager dose't works without the runnable .
         * Maybe a Support Library Bug .
         */

        tabLayout.post(new Runnable() {
            @Override
            public void run() {
                tabLayout.setupWithViewPager(viewPager);
            }
        });

        return x;

    }

    class MyAdapter extends FragmentPagerAdapter{

        public MyAdapter(FragmentManager fm) {
            super(fm);
        }

        /**
         * Return fragment with respect to Position .
         */

        @Override
        public Fragment getItem(int position)
        {
            switch (position){
                case 0 : return new CurrentFragment();
                case 1 : return new FavouriteFragment();

            }
            return null;
        }

        @Override
        public int getCount() {

            return int_items;

        }

        /**
         * This method returns the title of the tab according to the position.
         */

        @Override
        public CharSequence getPageTitle(int position) {

            switch (position){
                case 0 :
                    return "Current";
                case 1 :
                    return "Favourite";

            }
            return null;
        }
    }
}

And this is my fragment class in which I have added recycler view but it is giving NULL Point exception while setting the adapter.
 public class FavouriteFragment extends Fragment {
    private List<Person> persons;
    private RecyclerView rv;

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

    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.favourite_layout,container,false);

        RecyclerView rv = (RecyclerView)rootView.findViewById(R.id.rv);
        final LinearLayoutManager llm = new LinearLayoutManager(getActivity());
        rv.setLayoutManager(llm);

        initializeData();
        initializeAdapter();
        return rootView;
    }
    private void initializeData(){
        persons = new ArrayList<>();
        persons.add(new Person("XYZ", "jhxdjksd", R.drawable.profilepic));
        persons.add(new Person("ABC", "bsxhbs", R.drawable.profilepic));
        persons.add(new Person("PQR", "bsahxb", R.drawable.profilepic));
    }

    private void initializeAdapter(){
        RVAdapter adapter = new RVAdapter(persons);
        rv.setAdapter(adapter);
    }
}

MainActivity
    public class Tens extends AppCompatActivity {

    DrawerLayout mDrawerLayout;
    NavigationView mNavigationView;
    FragmentManager mFragmentManager;
    FragmentTransaction mFragmentTransaction;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tens);

        /**
         *Setup the DrawerLayout and NavigationView
         */

        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
        mNavigationView = (NavigationView) findViewById(R.id.shitstuff) ;

        /**
         * Lets inflate the very first fragment
         * Here , we are inflating the TabFragmentTens as the first Fragment
         */

        mFragmentManager = getSupportFragmentManager();
        mFragmentTransaction = mFragmentManager.beginTransaction();
        mFragmentTransaction.replace(R.id.containerView,new TabFragmentTens()).commit();
        /**
         * Setup click events on the Navigation View Items.
         */

        mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(MenuItem menuItem) {

                Fragment fragment = null;

                Class fragmentClass = null;
                switch(menuItem.getItemId()) {
                    case R.id.nav_item_tracker:
                        Intent intent = new Intent(
                        Tens.this, Tracker.class);
                startActivity(intent);
                        break;
                    case R.id.nav_item_clinic:
                        fragmentClass = ClinicFragment.class;
                        break;
                    case R.id.nav_item_about:
                        Intent intent0 = new Intent(
                                Tens.this, AboutFragment.class);
                        startActivity(intent0);
                        break;
                    case R.id.nav_item_settings:
                        Intent intent1 = new Intent(
                                Tens.this, SettingsFragment.class);
                        startActivity(intent1);
                        break;

                    case R.id.nav_item_logout:
                        Intent intent2 = new Intent(
                                Tens.this, MainActivity.class);
                        startActivity(intent2);

                        break;
                }

                try {
                    fragment = (Fragment) fragmentClass.newInstance();
                } catch (Exception e) {
                    e.printStackTrace();
                }

                FragmentTransaction xfragmentTransaction = mFragmentManager.beginTransaction();
                    xfragmentTransaction.replace(R.id.containerView, new TabFragmentTens()).commit();

                mDrawerLayout.closeDrawers();

                return false;
            }

        });

        android.support.v7.widget.Toolbar toolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.toolbar);
        ActionBarDrawerToggle mDrawerToggle = new ActionBarDrawerToggle(this,mDrawerLayout, toolbar,R.string.app_name,
                R.string.app_name);

        mDrawerLayout.setDrawerListener(mDrawerToggle);

        mDrawerToggle.syncState();

    }
}

Here's my recyclerview class:-
 public class RVAdapter extends RecyclerView.Adapter<RVAdapter.PersonViewHolder> {

    public static class PersonViewHolder extends RecyclerView.ViewHolder {

        CardView cv;
        TextView personName;
        TextView personAge;
        ImageView personPhoto;

        PersonViewHolder(View itemView) {
            super(itemView);
            cv = (CardView)itemView.findViewById(R.id.cv);
            personName = (TextView)itemView.findViewById(R.id.person_name);
            personAge = (TextView)itemView.findViewById(R.id.person_age);
            personPhoto = (ImageView)itemView.findViewById(R.id.person_photo);
        }
    }

    List<Person> persons;

    RVAdapter(List<Person> persons){
        this.persons = persons;
    }

    @Override
    public void onAttachedToRecyclerView(RecyclerView recyclerView) {
        super.onAttachedToRecyclerView(recyclerView);
    }

    @Override
    public PersonViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
        View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.card_view_tens_fvrt, viewGroup, false);
        PersonViewHolder pvh = new PersonViewHolder(v);
        return pvh;
    }

    @Override
    public void onBindViewHolder(PersonViewHolder personViewHolder, int i) {
        personViewHolder.personName.setText(persons.get(i).name);
        personViewHolder.personAge.setText(persons.get(i).age);
        personViewHolder.personPhoto.setImageResource(persons.get(i).photoId);
    }

    @Override
    public int getItemCount() {
        return persons.size();
    }

I want to add cardview with recycler view inside Favourite fragment. I know how to implement cardview but unable to implement it inside fragments.

A: first Make Changes in your mainactivity .
here i added a navigation drawer and tablayout in mainactivity.
public class HomeActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

        TabLayout tabLayout1 = (TabLayout) findViewById(R.id.tab_layout1);
        tabLayout1.addTab(tabLayout1.newTab().setIcon(R.drawable.tab_ic_home));
        tabLayout1.addTab(tabLayout1.newTab().setIcon(R.drawable.tab_ic_map));
        tabLayout1.addTab(tabLayout1.newTab().setIcon(R.drawable.tab_ic_login));

        tabLayout1.setTabGravity(TabLayout.GRAVITY_FILL);

        final ViewPager viewPager1 = (ViewPager) findViewById(R.id.pager1);
        final PagerAdapter1 adapter = new PagerAdapter1
                (getSupportFragmentManager(), tabLayout1.getTabCount());
        viewPager1.setAdapter(adapter);
        viewPager1.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout1));
        tabLayout1.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                viewPager1.setCurrentItem(tab.getPosition());
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.home, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        // Handle navigation view item clicks here.
        int id = item.getItemId();
        RelativeLayout mainLayout=(RelativeLayout)findViewById(R.id.main_layout);

           if (id == R.id.nav_project) {
            ProjectFragment fragment = new ProjectFragment();
            fragmentTransaction.replace(R.id.mainlayout, fragment);
            fragmentTransaction.addToBackStack(null).commit();
            }
        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }
}

Then create a pager adapter.
here u can add fragments for your tabs..
i named it as PagerAdapter1.java.
  import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;

public class PagerAdapter1 extends FragmentStatePagerAdapter {
    int mNumOfTabs;

    public PagerAdapter1(FragmentManager fm, int NumOfTabs) {
        super(fm);
        this.mNumOfTabs = NumOfTabs;
    }

    @Override
    public Fragment getItem(int position) {

        switch (position) {
            case 0:
                HomeTabFragment1 tab1 = new HomeTabFragment1();
                return tab1;
            case 1:
                HomeTabFragment2 tab2 = new HomeTabFragment2();
                return tab2;
            case 2:
                HomeTabFragment3 tab3 = new HomeTabFragment3();
                return tab3;
            default:
                return null;
        }
    }

    @Override
    public int getCount() {
        return mNumOfTabs;
    }
}

i just wanted a Recycler view in first tab. So i added code for recyclerview in HomeTabFragment1.java.
public class HomeTabFragment1 extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v=inflater.inflate(R.layout.home_tab_fragment_1, container, false);
        RecyclerView rv = (RecyclerView)v.findViewById(R.id.home_recyclerview);
        setupRecyclerView(rv);
        return v;

I hope the rest you can do..

A: Looks like the field "rv" is never initialized in the FavouriteFragment class, you did initialize the local variable "rv" in method onCreateView.
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.favourite_layout,container,false);

    RecyclerView rv = (RecyclerView)rootView.findViewById(R.id.rv);
    final LinearLayoutManager llm = new LinearLayoutManager(getActivity());
    rv.setLayoutManager(llm);

    initializeData();
    initializeAdapter();
    return rootView;
}


text:
Q: generate stored procedure from SQL server to Hibernate POJOs classes in IntelIJ I'm looking for the method to generate stored procedures in sql to  Hibernate POJOs classes in IntelIJ, such as
@NamedStoredProcedureQuery(name = "addEmployee",
                                procedureName = "postEmployeeElement",
                                resultClasses = Employee.class,
                                parameters = {
                                        @StoredProcedureParameter( name = "employeeID", type = Integer.class, mode = ParameterMode.IN ),
                                        @StoredProcedureParameter(name = "firstName", type = String.class, mode = ParameterMode.IN ),
                                        @StoredProcedureParameter(name = "lastName", type = String.class, mode = ParameterMode.IN ),
                                        @StoredProcedureParameter( name = "address",type = String.class,mode = ParameterMode.IN )}
    )

I'm really need, but i can't search any way to resolve.

A: You can use IDE scripting capabilities to generate POJO classes from database objects. See example scripts and video. Some more information in related blog post. E.g. when you select a procedure in Database tool window then in SELECTION object you should have the Iterable<com.intellij.database.model.DasRoutine>. The API for the objects you can see in openapi.jar in <IDE_HOME>\lib directory.


text:
Q: comprimir zip con java he generado mi codigo mi codigo para crear un zip apartir de una variable que tiene el contenido a comprimir en este caso son pdf , el problema es que se realiza la descarga del zip pero este viene con pdf de dañado y con 0 de tamaño.
les comparto parte de mi codigo donde hace la compresion.
tengo un ouputstream que es ahi donde se guardan los pdfs que necesito comprimir y es el que paso al metodo zip para realizar la compresion.
public void generarPDF(Long idEnvio ) {
        try {
            String nombre = "envio-taller" + idEnvio + ".pdf";
            List<ByteArrayOutputStream> outputStreams =
            this.enviosLocalesServicio.crearReportes(idEnvio);

            zip(outputStreams);

        } catch (Exception e) {
            log.error(e);
        }
    }

private byte[] zip(List<ByteArrayOutputStream> outputStreams ) throws
        ServletException, IOException  {
        ByteArrayOutputStream zip = new ByteArrayOutputStream();
        ZipOutputStream zout = null;
        FacesContext facesContext = FacesContext.getCurrentInstance();
        HttpServletResponse response = (HttpServletResponse)
        facesContext.getExternalContext().getResponse();
        try {
            int zipNombre = 0;
            zout = new  ZipOutputStream(zip);
            for (ByteArrayOutputStream doc : outputStreams) {
                zipNombre ++ ;
                ZipEntry ze = new ZipEntry(zipNombre + ".pdf");
                zout.putNextEntry(ze);
                zout.write(doc.toByteArray());
                zout.closeEntry();
            }
        } catch (IOException e) {
            log.info(e.getMessage());
            // TODO Auto-generated catch block
            e.printStackTrace();
        }catch (Exception e) {
            log.info(e.getMessage());
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        finally {
            if (zout != null) {
                ServletOutputStream resp = response.getOutputStream() ;
//              response.reset();
                response.setContentType("application/zip");
                response.setHeader("Content-disposition", "attachment; filename=documen.ZIP" );

                resp.write(zip.toByteArray());
                resp.close();
                facesContext.responseComplete();
                zout.close();
            }
        }
        return zip.toByteArray();
    }

A: esto es parte del codigo
public List<ByteArrayOutputStream> crearReportes(Long idEnvio) throws OutletExcepcion {
        List<ByteArrayOutputStream> pdfs = null;
        try {
            EnvioLocalDTO envioDatos = this.obtenerEnvio(idEnvio);
            if (envioDatos!= null) {
                pdfs = new ArrayList<ByteArrayOutputStream>();
                ByteArrayOutputStream pdf=null;
                Empresa empresa = empresaServicio.obtenerEmpresa(1);
                opcionesBucket bucket = opcionesBucket.configuracion_app;
                String url = storageServicio.consultaporNombre(bucket, null, empresa.getImagen3());

                Map<Integer, List<EnvioLocalDetDTO>> detallesTaller = envioDatos.getDetallesTaller();
                for (Map.Entry<Integer, List<EnvioLocalDetDTO>> entry : detallesTaller.entrySet()) {
                    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
                    Map<String, Object> datos = new HashMap<String, Object>();
                    datos.put("fecha", sdf.format(envioDatos.getFecha()));
                    datos.put("chofer", envioDatos.getNombreChofer());
                    datos.put("folio", envioDatos.getIdEnvio());
                    datos.put("idRuta", envioDatos.getIdRuta());
                    datos.put("nombreRuta", envioDatos.getNombreRuta());
                    datos.put("nombreTaller", envioDatos.getActuales().get(0).getNombreTaller());
                    datos.put("nombreMarca", envioDatos.getActuales().get(0).getNombreMarca());
                    datos.put("nombreTipo", envioDatos.getActuales().get(0).getNombreTipo());
                    datos.put("modelo", envioDatos.getActuales().get(0).getModelo());

                    JRBeanCollectionDataSource dataSource = new JRBeanCollectionDataSource(entry.getValue());
                    pdf = UtileriaPdf.crearReporte(Constantes.PLANTILLAPDF_INVENTARIO_TALLER, datos, dataSource, empresa, url);
                    pdfs.add(pdf);
                }
            } else throw new


text:
Q: MongoDB - can read cause write locks? I have a MongoDB database with ~100GB data size. I ran a test with 300 threads and a total 10,000 'read' queries. I notice on the MMS lock% it is showing 0.6 ~ 1% of write lock. My question is, the queries are purely 'read', why is it showing write lock?

A: First off, to correct the comment: the profiler does not write to the local database, it writes to whatever database you are profiling in the system.profile collection.  So if you were reading from database foo and had profiling turned on, the collection would be foo.system.profile.  You could turn on profiling for the local database, and hence have the profiler write there of course, but it is not a default of any kind.
Then, if you have the profiler enabled, regardless of where it writes too, all writes require a write lock whether they are to the system.profile collection or anywhere else. Just because it is getting input internally does not exclude the system.profile collection from following the same rules as any other collection on a database.
If you turn the profiler off I would expect the lock to disappear.  There may still be the occasional blip in the global lock percentage in the stats but that is essentially just background noise.


text:
Q: jq --arg variable used in quoted string within select() I want to select() an object based on a string containing a jq variable ($ARCH) using -arg jq argument. Here's the use-case while looking for "/bin/linux/$ARCH/kubeadm" from Google...
# You may need to install `xml2json` IE
# sudo gem install --no-rdoc --no-ri xml2json and run the script I wrote to do the xml2json:

#!/usr/bin/ruby
# Written by Jim Conner
require 'xml2json'

xml = ARGV[0]

begin
  if xml == '-'
    xdata = ARGF.read.chomp
    puts XML2JSON.parse(xdata)
  else
    puts XML2JSON.parse(File.read(file2parse).chomp)
  end
rescue => e
  $stderr.puts 'Unable to comply: %s' % [e.message]
end

Then run the following:
curl -sSL https://storage.googleapis.com/kubernetes-release/ > /var/tmp/k8s.xml | \
xml2json - | \
jq --arg ARCH amd64 '[.ListBucketResult.Contents[] | select(.Key | contains("/bin/linux/$arch/kubeadm"))]'

...which returns an empty set because jq doesn't transliterate inside quotes. I know I can get around this by using multiple select/contains() but I'd prefer not to if possible.
jq simply may not do it, but if someone knows a way to do it, I'd much appreciate it.

A: jq does support string interpolation, and in your case the string would be:
"/bin/linux/\($ARCH)/kubeadm"

Notice that this is not a JSON string: the occurrence of "\(" signals that the string is subject to interpolation.  Very nifty.
(Alternatively, you could of course use string concatenation:
"/bin/linux/" + $ARCH + "/kubeadm")
Btw, you might wish to avoid contains here.  Its semantics is (are?) quite complex and perhaps counter-intuitive.  Consider using startswith, index, or (for regex matches) test.


text:
Q: Gnuplot polar plot with top theta clockwise keeps the inner radial grid origin at 0 angle I have a simple time/value dataset like this:
1   20
2   21
# ...
15  36

Where the first column is a time value, and other columns store some measurements. I wanted to plot these values in a "clock plot", that is a polar plot (or a radar chart) where angles correspond to time instants, and the radius keeps the value of the measurement.
Since I would like to reproduce a clock, I want my first measurement to start in a vertical position, and I can do set theta top clockwise. Having 15 seconds in my dataset, I can split the 360 degrees in angles of 24 degrees (one for each second) set grid polar 24.
However, the grid values start from the 0 degree angle (and not, as expected, from the top angle of 90 degrees). This bothers me because my measurements have an offset with respect to the grid. (Check the picture attached).
How can I solve this problem? Can I rotate the grid to start counting at 90 degrees? Thank you a lot in advance.

A: As a workaround you could draw your grid lines manually. Not very nice but you visually get the desired result.
Code:
### polar grids aligned to north
reset session
set size square
set angle degrees

set polar
set theta clockwise top
unset border
set border polar
unset xtics
unset ytics
set ttics 24 format ""
set rtics 10
set grid rtics
unset key

set rrange[0:40]

# manually draw grid lines
do for [i=0:360:24] {
    set arrow i+1 from 0,0 to polar i,40 lw 0.5 dt 3 lc rgb "black" nohead
}

set samples 16
plot t/9 w lp pt 7 lc rgb "red"
### end of code

Result:


text:
Q: Exponentially Distributed Random Variable? Suppose that the time (in hours) required to repair a machine is an exponentially distributed random variable with parameter $\lambda = 0.2$. What is:
(a) the probability that a repair time exceeds 10 hours?
(b) the conditional probability that a repair takes at least 7 hours, given that it takes more than 6 hours?
I was able to answer part (a). The survival function of the exponential distribution is $e^{-\lambda t}$ so I plugged in for $\lambda = 0.2$ and $t = 10$ to calculate the probability that repair time is greater than $2$. I got $e^{-0.2\times 10} = .13533$ which is correct.
For part (b), I know I have to use the standard rules of conditional probability:
$$
P(X > 7 | X > 6) = \frac{P(X > 7 \cap X > 6)}{P(X > 6)}
$$
but for some reason my answer is incorrect.
Am I doing this incorrectly?

A: My guess is you have a cancellation error -- your approach seems correct.
The exponential random variable has the "memoryless property":  given that we have seen no event up to time $t$, the conditional distribution of the remaining time until the event is the same as it originally was.
As you noted, if $X$ is the time until the first event, and we have times $t$ and $t + s$ (with $s \geq 0$), we have
\begin{equation*}\begin{split} P(X > t + s | X > t) &= \frac{P(X > t + s)}{P(X > t)} \\ &= \frac{e^{-\lambda(t + s)}}{e^{-\lambda t}} \\ &= e^{-\lambda s} \\ &= P(X > s). \end{split}\end{equation*}


text:
Q: MySQL database row COUNT optimization I have a MySQL (5.6.26) database with large ammount of data and I have problem with COUNT select on table join.
This query takes about 23 seconds to execute:
SELECT COUNT(0) FROM user
LEFT JOIN blog_user ON blog_user.id_user = user.id
WHERE email IS NOT NULL
AND blog_user.id_blog = 1

Table user is MyISAM and contains user data like id, email, name, etc...
CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(50) DEFAULT NULL,
  `email` varchar(100) DEFAULT '',
  `hash` varchar(100) DEFAULT NULL,
  `last_login` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
  `created` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
  PRIMARY KEY (`id`),
  UNIQUE KEY `id` (`id`) USING BTREE,
  UNIQUE KEY `email` (`email`) USING BTREE,
  UNIQUE KEY `hash` (`hash`) USING BTREE,
  FULLTEXT KEY `email_full_text` (`email`)
) ENGINE=MyISAM AUTO_INCREMENT=5728203 DEFAULT CHARSET=utf8

Table blog_user is InnoDB and contains only id, id_user and id_blog (user can have access to more than one blog). id is PRIMARY KEY and there are indexes on id_blog, id_user and id_blog-id_user.
CREATE TABLE `blog_user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `id_blog` int(11) NOT NULL DEFAULT '0',
  `id_user` int(11) NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`),
  UNIQUE KEY `id_blog_user` (`id_blog`,`id_user`) USING BTREE,
  KEY `id_user` (`id_user`) USING BTREE,
  KEY `id_blog` (`id_blog`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=5250695 DEFAULT CHARSET=utf8

I deleted all other tables and there is no other connection to MySQL server (testing environment).
What I've found so far:

*

*When I delete some columns from user table, duration of query is shorter (like 2 seconds per deleted column)

*When I delete all columns from user table (except id and email), duration of query is 0.6 seconds.

*When I change blog_user table also to MyISAM, duration of query is 46 seconds.

*When I change user table to InnoDB, duration of query is 0.1 seconds.

The question is why is MyISAM so slow executing the command?

A: First, some comments on your query (after fixing it up a bit):
SELECT COUNT(*)
FROM user u LEFT JOIN
     blog_user bu
     ON bu.id_user = u.id
WHERE u.email IS NOT NULL AND bu.id_blog = 1;

Table aliases help make it easier to both write and to read a query.  More importantly, You have a LEFT JOIN but your WHERE clause is turning it into an INNER JOIN.  So, write it that way:
SELECT COUNT(*)
FROM user u INNER JOIN
     blog_user bu
    ON bu.id_user = u.id
WHERE u.email IS NOT NULL AND bu.id_blog = 1;

The difference is important because it affects choices that the optimizer can make.
Next, indexes will help this query.  I am guessing that blog_user(id_blog, id_user) and user(id, email) are the best indexes.
The reason why the number of columns affects your original query is because it is doing a lot of I/O.  The fewer columns then the fewer pages needed to store the records -- and the faster the query runs.  Proper indexes should work better and more consistently.

A: To answer the real question (why is myisam slower than InnoDB), I can't give an authoritative answer.
But it is certainly related to one of the more important differences between the two storage engines : InnoDB does support foreign keys, and myisam doesn't. Foreign keys are important for joining tables.
I don't know if defining a foreign key constraint will improve speed further, but for sure, it will guarantee data consistency.
Another note : you observe that the time decreases as you delete columns. This indicates that the query requires a full table scan. This can be avoided by creating an index on the email column. user.id and blog.id_user hopefully already have an index, if they don't, this is an error. Columns that participate in a foreign key, explicit or not, always must have an index.

A: This is a long time after the event to be much use to the OP and all the foregoing suggestions for speeding up the query are entirely appropriate but I wonder why no one has remarked on the output of EXPLAIN. Specifically, why the index on email was chosen and how that relates to the definition for the email column in the user table.
The optimizer has selected an index on email column, presumably because it's included in the where clause. key_len for this index is comparatively long and it's a reasonably large table given the auto_increment value so the memory requirements for this index would be considerably greater than if it had chosen the id column (4 bytes against 303 bytes). The email column is NULLABLE but has a default of the empty string so, unless the application explicitly sets a NULL, you are not going to find any NULLs in this column anyway. Neither will you find more than one record with the default given the UNIQUE constraint. The column DEFAULT and UNIQUE constraint appear to be completely at odds with each other.
Given the above, and the fact we only want the count in the query, I'd then wonder if the email part of the where clause serves any purpose other than slowing the query down as each value is compared to NULL. Without it the optimizer would probably pick the primary key and do a much better job. Better yet would be a query which ignored the user table entirely and took the count based on the covering index on blog_user that Gordon Linoff highlighted.
There's another indexing issues here worth mentioning:
On the user table
 UNIQUE KEY `id` (`id`) USING BTREE,

is redundant since id is the PRIMARY KEY and therefore UNIQUE by definition.

A: To answer your last question,
The question is why is MyISAM so slow executing the command?
MyISAM is dependent on the speed of your hard drive,
INNODB once the data is read is at speed of RAM.  1st time query is run could be loading data, second and later will avoid hard drive until aged out of RAM.


text:
Q: Create Table - Time Statement I am having trouble trying to create a table using MS Access.
I know for sure my problem lies in the "datetime" field but I can not figure what I am missing or doing wrong.
When I click "run" I get the

"Syntax Error in Field Definition"

Create Table Appointments
(DocID             char(4)             not null       primary key,
 PatID             char(8)             not null,
 Day               varchar(8)          not null,
 Time              datetime            not null,
 Procedure         varchar(50)         null);

A: Time and procedure are reserved words, and therefore should be escaped:
Create Table Appointments
(DocID             char(4)             not null       primary key,
 PatID             char(8)             not null,
 [Day]             varchar(8)          not null,
 [Time]            datetime            not null,
 [Procedure]       varchar(50)         null);

Or better yet, find names that aren't reserved words:
Create Table Appointments
(DocID             char(4)             not null       primary key,
 PatID             char(8)             not null,
 AppointmentDay    varchar(8)          not null,
 AppointmentTime   datetime            not null,
 MedicalProcedure  varchar(50)         null);

A: Here Procedure and Time are reserved words and so need to be escaped using [] like below. See Documentation for more information
Create Table Appointments
(DocID             char(4)             not null       primary key,
 PatID             char(8)             not null,
 [Day]               varchar(8)          not null,
 [Time]              datetime            not null,
 [Procedure]         varchar(50)         null);

A: As Time & Procedure are reserved keyword, so wrap Time & Procedure column in brackets [] or choose alternate names, if possible. See List of Keyword
[Time] and [Procedure]


text:
Q: How to start powershell process with impersonate ImpersonationLevel? I have to set RPC_C_IMP_LEVEL_IMPERSONATE to powershell process. Do you have any idea how i can achieve this ?
I've only found this info. It's about Changing the Default Impersonation Levels Using C++ via CoInitializeSecurity. But unfortunately I can't use it for powershell. It's required having a main function.
/// <summary>
/// The main entry point for the application.
/// Do not set STAThread since CoInitializeSecurity is called
/// with to high security automatically (and it can only be called once).
/// </summary>
//[STAThread]
static void Main()
{
    // Set threading apartment
    System.Threading.Thread.CurrentThread.ApartmentState = ApartmentState.STA;
    CoInitializeSecurity( IntPtr.Zero, -1, IntPtr.Zero,
        IntPtr.Zero,RpcAuthnLevel.None ,
        RpcImpLevel.Impersonate,IntPtr.Zero, EoAuthnCap.None, IntPtr.Zero );

    Application.MainForm = new MainForm();
    System.Windows.Forms.Application.Run(Application.MainForm);
}

I have a client(powershell) and service. I can't call service because it gives me following error:
Either a required impersonation level was not provided, or the provided impersonation level is invalid.

And I found in *.log that current impersonation level is Identification.


text:
Q: parallelization with n_jobs in scikit-learn pairwise_distances Thanks to Philip Cloud's great answer to a previous question, I went and dug into the source code for pairwise_distances in scikit.
The relevant part is:
def pairwise_distances(X, Y=None, metric="euclidean", n_jobs=1, **kwds):
    if metric == "precomputed":
        return X
    elif metric in PAIRWISE_DISTANCE_FUNCTIONS:
        func = PAIRWISE_DISTANCE_FUNCTIONS[metric]
        if n_jobs == 1:
            return func(X, Y, **kwds)
        else:
            return _parallel_pairwise(X, Y, func, n_jobs, **kwds)
    elif callable(metric):
        # Check matrices first (this is usually done by the metric).
        X, Y = check_pairwise_arrays(X, Y)
        n_x, n_y = X.shape[0], Y.shape[0]
        # Calculate distance for each element in X and Y.
        # FIXME: can use n_jobs here too
        D = np.zeros((n_x, n_y), dtype='float')
        for i in range(n_x):
            start = 0
            if X is Y:
                start = i
            for j in range(start, n_y):
                # distance assumed to be symmetric.
                D[i][j] = metric(X[i], Y[j], **kwds)
                if X is Y:
                    D[j][i] = D[i][j]
        return D

Is it correct to understand from this that if I were to calculate a pairwise distance matrix like:
matrix = pairwise_distances(foo, metric=lambda u,v: haversine(u,v), n_jobs= -1)
where haversine(u,v) is a function that calculates the Haversine distance between two points and this function is not in PAIRWISE_DISTANCE_FUNCTIONS, that calculation would not be parallelized even though n_jobs= -1?
I realize that the #FIXME comment seems to imply this, but I want to make sure I'm not crazy, as it seems a little odd that there would be no informative alert thrown stating that the computation would not actually be parallelized when you pass n_jobs= -1 with a callable function that is not in PAIRWISE_DISTANCE_FUNCTIONS.

A: Confirmed. Passing a callable as the metric along with n_jobs= -1 will not result in parallelization if the callable is not in PAIRWISE_DISTANCE_FUNCTIONS.


text:
Q: IO completion ports for concurrent database access I have a .NET WCF service that will need to handle multiple client requests at once.
The service makes database calls (both read and write) for each client request.
Could IO completion ports be useful for the database access portions of this code to improve concurrent performance? How would they be used in such a situation?

A: ADO.NET 2.0 supports async command execution which internally use IO completion ports. (BeginXXX & EndXXX methods)
Check out http://msdn.microsoft.com/en-us/library/ms379553(VS.80).aspx

A: That depends on how you are doing the database reads and writes. If you're using some sort of direct socket or file input/output calls then you can increase the number of calls you can service concurrently. However, the time to actually do database reads/writes is dependent on the server.
But it is very likely that you're accessing the database through ODBC/OLEDB/ADO/ADO.NET, in which case those libraries do not use IO completion ports. And you can't make them use IO completion ports.
IO completion ports are used to prevent your thread from blocking when it is waiting for IO to complete. Think of it like asynchronous reads/writes.