text:
Q: Need assistance regarding showing download images as gallery In my app I am downloading images from url and saving into application documents directory. Now I want to show these downloaded images as image gallery. For image gallery I am using fGallery, I am able to configure it and successfully pushed it on navigation controller and fGallery view is also visible but its not showing my images, I provide fGalley with images array like this
Header File
@interface myController <FGalleryViewControllerDelegate>

@property (strong, nonatomic) FGalleryViewController *localGallery;
@property (strong, nonatomic) NSMutableArray *localImages;

Class File
    //These are delegate methods of FGalleryViewControllerDelegate
    - (NSString*)photoGallery:(FGalleryViewController*)gallery filePathForPhotoSize:(FGalleryPhotoSize)size atIndex:(NSUInteger)index
    {
        return [localImages objectAtIndex:index];
    }

    - (NSString*)photoGallery:(FGalleryViewController *)gallery urlForPhotoSize:(FGalleryPhotoSize)size atIndex:(NSUInteger)index
    {
        return [localImages objectAtIndex:index];
    }

    - (int)numberOfPhotosForPhotoGallery:(FGalleryViewController *)gallery
    {
        int num;

        num = [localImages count];

        return num;
    }

    - (FGalleryPhotoSourceType)photoGallery:(FGalleryViewController *)gallery sourceTypeForPhotoAtIndex:(NSUInteger)index
    {
         return FGalleryPhotoSourceTypeLocal;
    }
    //Delegate method ends here

// My method to show gallery with my images
-(void)ShowGallery
{
    localImages = [[NSMutableArray alloc]init];

     NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
NSString *dataPath = [documentsDir stringByAppendingPathComponent:chatWithUser;
NSString *msgsColumn;

    //database query to fetch all images name and then
    while([results next])
    {
        msgsColumn = [results stringForColumn:@"msgs"];
        if([[[msgsColumn componentsSeparatedByString:@"."]objectAtIndex:1]isEqualToString:@"jpg"])
        {
            [localImages addObject:[dataPath stringByAppendingPathComponent:msgsColumn]];
        }
    }

    [database close];

    localGallery = [[FGalleryViewController alloc]initWithPhotoSource:self];

    [self.navigationController pushViewController:localGallery animated:YES];
}

For images path i used stringByAppendingPathComponent but I also tried stringByAppendingString to guide that images resides in documents directory but nothing is working.
Please assist me to figure out what is going wrong.

A: I found the solution, and here it is
https://github.com/gdavis/FGallery-iPhone/issues/15


text:
Q: Gulpfile Javascript Concat Issue I am trying to get my gulp file working right and I am not sure whats wrong. Here is the file. https://gist.github.com/digilord/9265640 The section I am having issues with is the js:dev. When a coffeescript file is changed it drops the resulting js file into the app/js directory. The js:dev rule isn't picking up that change. Can anyone tell me what I am missing?

A: Immediate solution: gulp-watch needs the glob information to find new files. You can pass your glob to its glob option. Something like:
return gulp.src('app/js/*.coffee')
      .pipe(watch({glob: 'app/js/*.coffee'}))

Meanwhile if you were to use gulp.watch() it wouldn't pick up new files either but only because of a bug in its dependency, which a fix is coming soon for.
I have to also mention that your gulpfile is needlessly complex. Your coffee and js operations could be in the same stream instead of creating intermediate js files. I also don't really know why some of your streams are repeated twice. Stay dry:
var coffeeGlob = 'app/js/*.coffee';

gulp.task('js:dev', ['clean:dev'], function() {
    return gulp.src(coffeeGlob)
      .pipe(watch({glob: coffeeGlob}))
      .pipe(coffee({bare: true}).on('error', gutil.log))
      .pipe(concat('app.js'))
      .pipe(gulp.dest('build/js'))
      .pipe(reload());
});

As I mentioned on IRC the boilerplate you based it on might not be up to date with best practices, and I recommend basing on something newer like Yeoman's gulp generator's gulpfile.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is there a simpler way to read off *.jar or filesystem? I've developed a simple app using Sparkjava. I'm using Intellij, and when I run my tests, or run the app locally, all my resources are files.
However, when I deploy, the whole thing runs as a jar file. As such, I need a way to read my resources off the filesystem or the jar, depending on how the app is launched. The following code gets the job done, but it looks clumsy:
String startedOffFile = new java.io.File(Main.class.getProtectionDomain()
        .getCodeSource()
        .getLocation()
        .getPath())
        .getName();
InputStream inputStream;
if(startedOffFile.endsWith(".jar")) {
    ClassLoader cl = PropertiesParser.class.getClassLoader();
    inputStream = cl.getResourceAsStream("myapp.dev.properties");
} else {
    inputStream = new FileInputStream(filename);
}

Is there a cleaner/simpler way?

A: Have your main create this class to determine if your java executable has defined a config.location parameter or will look on the classpath.
eg. java -Dconfig.location=/here/myapp.dev.properties -jar youapp.jar
public class ApplicationProperties {
    public ApplicationProperties() throws IOException {
        final Properties properties = new Properties();

        String location = getProperty("config.location")
        if(location != null) {
            properties.load(new FileInputStream(getProperty("config.location", ENV_PROPERTIES_PATH)));
        } else {
            properties.load(Classname.class.getClassLoader().getResourceAsStream("myapp.dev.properties"));
        }
    }

    public Properties getProperties() {
        return properties;
    }
}

A: If you're using Maven with IntelliJ, just put the configuration properties file inside the src/main/resources directory in the module. If you're not using Maven then put the properties file in the root of your source tree (outside any package - like: src/myapp.dev.properties).
After packaging/exporting of the JAR the file will be accessible with new Object().getClass().getClassLoader().getResourceAsStream("myapp.dev.properties") (the new Object()... is used, because in some cases/platforms the static ClassLoader is not defined).
The same classpath is used by the IntelliJ/Eclipse environment, which means there is no need for a special case for loading the files.
If you need to differentiate between development and production properties. You can use Maven profiles for build time packaging or you can load the properties with a variable using the -D switch.


text:
Q: Validate before Stripe Checkout modal I have a simple form that has a select box to select the product, radio group to select the quantity and then a checkbox that if checked, shows a select box and an input field that becomes required if check box is selected.
<form action="stripeprocess.php">
<!-- fields and structure here, product, quantity, join mailing list checkbox and other mailing list questions that appear when checkbox is ticked -->
<script src="https://checkout.stripe.com/checkout.js"></script>
<button id="stripe-button" class="bin">Enter Pay Details with Stripe</button>
<script>
$('#stripe-button').click(function(){
  var token = function(res){
  var $id = $('<input type=hidden name=stripeToken />').val(res.id);
  var $email = $('<input type=hidden name=stripeEmail />').val(res.email);
  $('#order-form').append($id).append($email).submit();
};

StripeCheckout.open({
  key:          'hidden',
  name:         'hidden',
  image:        'logo.png',
  description:  'Complete your Order',
  panelLabel:   'Complete Order',
  billingAddress: true,
  zipCode:      true,
  token:            token
});

return false;
});
</script>
</form>

Everything works and order is processing, I just need to add validation. I know how to write the rules in jQuery validate, but I am not sure how to do that and implement it to run the validate and then the stripe checkout after success validate.
So in the simplest way of code, I would like to accomplish this:
if(submit button is pressed) {
  run jQuery validate on forms

  if(jQuery validate successful) {
     run stripe and launch modal
  }
}

Can someone assist me with this or point me in the right direction?
Thank you!

A:
I would like to accomplish this:

if (submit button is pressed) {
    // run jQuery validate on forms // part 1

    if(jQuery validate successful) {
        // run stripe and launch modal // part 2
    }
}

For "part 1", you are not supposed to have to worry about capturing the submit or click event.  The plugin will capture these automatically after it's properly initialized.
So for "part 1" simply initialize the jQuery Validate plugin within the DOM Ready event handler by attaching the .validate() method to the form element.
$(document).ready(function() {

    // initialize plugin
    $('form[action="stripeprocess.php"]').validate({
        rules: { ....

For "part 2", you can "do something" upon successful validation by putting it within the submitHandler function...
$(document).ready(function() {

    // initialize plugin
    $('form[action="stripeprocess.php"]').validate({
        rules: {
            ....
        },
        submitHandler: function (form) {
            // fires on valid form

            // run stripe and launch modal

            // form.submit();  // regular submit
        }
        ....

Although, if action="stripeprocess.php" represents launching Stripe, then you wouldn't need the submitHandler at all, since that's already the plugin's built-in functionality.


text:
Q: MVC3 - Firing unobtrusive JavaScript on JQuery UI Autcomplete Dropdown combox I'm using unobtrusive validation in an MVC3 app.  I've got a dropdown list with a [Required] validator on it.  This is my Model (simplified):
[Required(ErrorMessage = "Please select From Employee.")]
public string CurrentEmpId { get; set; }

public List<SelectListItem> CurrentEmp { get; set; }

And this is my View (simplified):
@Html.LabelFor(m => m.CurrentAdvisers)
@Html.DropDownListFor(m => m.CurrentEmpId, new SelectList(Model.CurrentEmp, "Value", "Text", Model.CurrentEmpId), "Please Select")
@Html.ValidationMessageFor(m => m.CurrentEmpId)

Now this is all working bo diddly until I make the dropdown list into a JQuery UI combox  jqueryui.com/demos/autocomplete/#combobox (see last argument).
@Html.DropDownListFor(m => m.CurrentEmpId, new SelectList(Model.CurrentEmp, "Value", "Text", Model.CurrentEmpId), "Please Select", new { @class = "selAutoComplete" })

The validation fires OK when I press a submit button and nothing has been selected.  There is one annoying thing that doesn't work though.  When an error is fired, if I then go and correct the error by selecting something in the dropdown and tab out the error doesn't disappear.  This did happen when it was a normal select box.
It's probably to do with the fact that the <select> is now hidden and replaced by an <input> by JQuery, but I can't figure out how to fire the correct js to remove the error message.
Any help will be gratefully received!
Thanks in advance

A: From your description, it seems that validation of the select control did not get triggered when you tabbed out of the jQ-UI combobox. One thing you could try is to force a blur or change event on the select control right after you tab away from the combobox, e.g.:
$('#CurrentEmpId').next('input').blur(function(e) {
    $('#CurrentEmpId').change();
    //$('#CurrentEmpId').blur();    // try this line if the above does not work
});

A: After some further research I've found the following solution works just fine:
How to use jQuery to remotely validate a field that depends on another field in the form?
$("select.selAutoComplete").change(function() {
    $(this).removeData("previousValue"); //clear cache when changing group
    $("form").data('validator').element('select.selAutoComplete');
});

@William Niu - I tried your solution and off the top of my head, I couldn't see why this didn't work.  Thanks for taking the time to answer though.
I hope this helps others.


text: Q: Run Apache2 as a different user with mod_event on Ubuntu 20.04 I have Ubuntu 20.04 having configured apache2 to serve website on HTTP/2 protocol. I use mpm-event as multi processing module. Can anybody please tell me how to run apache as different user based on websites hosted on the server. I cannot use mpm-itk because it is not compatible with HTTP/2 protocol. Thanks in advance for the guidance.


text:
Q: Submitting dynamic ajax field I have an an ajax drop down box that if selected adds another field to a form, this works but this new field doesn't get submitted with the form. Any suggestions?
findTest.php called via ajax
<?php
$work = ($_GET['work']);
if ($work == "Work1") {
    ?>

        New work1<input name="newWork1" size="20" type="text"/>

 <?
} elseif ($work == "Work2") {
    ?>

        New work<input name="newWork" size="20" type="text"/>

<?
} elseif ($work == "Work3") {
    ?>

        No work today

<?
}?>

Test.php
<?php
$page = '';
$answer = null; //clean start.
$Comments = $_POST['Comments'];
$new = $_POST['new'];

// Check if button name "Submit" is active, do this
if (isset($_POST['Submit'])) {
    ?>

Test message <?= $_POST['Comments'] ?>
        and <?= $_POST['new'] ?> or this should be
        work2 <?= $_POST['newWork'] ?>

<? } ?>

    <form name="meters" method="POST" action="test.php">

            Work Done:
            <select name="WorkDone" tabindex="14"
                        onchange="getWorkDone(this.value)">
                    <option value="Work1">Work1</option>
                    <option value="Work2">Work2</option>
                    <option value="Work3">Work3</option>
                    <option value="Other">Other</option>
                </select>

New Work<input name="newWork" size="20"
                                               type="text"/>

            Comments:
            <textarea name="Comments" tabindex="40" cols="40"
                          rows="4"><?= $_POST[Comments] ?></textarea>

            <input type="submit" name="Submit"
                                                  class="button" value="Submit">

</form>

UPDATE: new code.
findTest.php called via ajax
<?php
if (isset($_GET['work'])) {
$work= $_GET['work'];
if ($work == "Noworktoday") {
echo "
No work today
";
}  else {
echo "
New ".$work."
";
echo "<input name=\"new".$work."\" type=\"text\"";
echo " size=\"20\" value=\"new".$work."\" />";
echo "
";
}
}?>

And Test.php
<?php
$page = '';
$answer = null; //clean start.
if (isset($_POST['Comments'])) {
$Comments = $_POST['Comments']; } else {
$Comments = 'n/a'; }

if (isset($_POST['newWork1'])) {
$newWork = $_POST['newWork1']; } else {
$newWork = 'n/a'; }

if (isset($_POST['newWork1'])) {
$newWork = $_POST['newWork1']; } else {
$newWork = 'n/a'; }

if (isset($_POST['Submit'])) {
echo "message = ".$Comments."
";
echo "newWork1 = ".$newWork1."
";
echo "newWork2 = ".$newWork2."
";
echo "newOther = ".$newOther."
";
}
?>

<form name="meters" method="POST" action="test.php">

Work Done:
<select name="WorkDone" tabindex="14" onchange="getWorkDone(this.value)">
<option value="">Select</option>
<option value="Work1">Work1</option>
<option value="Work2">Work2</option>
<option value="Work3">Work3</option>
<option value="Other">Other</option>
</select>

New Work<input name="newWork" size="20" type="text" />

Comments:
<textarea name="Comments" tabindex="40" cols="40" rows="4" ><?=$_POST[Comments]?></textarea>

<input type="submit" name="Submit" class="button" value="Submit">

</form>

UPDATE edit double up and correct $newWork to $newWork1
<?php
$page = '';
$answer = null; //clean start.
if (isset($_POST['Comments'])) {
$Comments = $_POST['Comments']; } else {
$Comments = 'n/a'; }

if (isset($_POST['newWork1'])) {
$newWork1 = $_POST['newWork1']; } else {
$newWork1 = 'n/a'; }

if (isset($_POST['Submit'])) {
echo "message = ".$Comments."
";
echo "newWork1 = ".$newWork1."
";
echo "newWork2 = ".$newWork2."
";
echo "newOther = ".$newOther."
";}
?>

This now shows n/a but not the value of newWork1

A: You have very modified the original question, I can only respond to what was previously.

The important part is also findTest.php
from this script you replace your
document.getElementById('workdiv').innerHTML=req.responseText;

So how does findTest.php know about $_POST['newwork1']
New work1<input name="newWork1" ... value="<?=$_POST['newwork1']?>" />	..

This must come via a GET / POST, but in your GET there ist only
strURL="findTest.php?work="+workId;

Only 1 GET variable named  $_GET['work'].
and you use this variable (without test)
$work=$_GET['work'];

And then you mixed the request from $_GET to $_POST['newwork1']
so why not use your select value to get it all together.
Test.php
...
<select name="WorkDone" tabindex="14" onchange="getWorkDone(this.value)">
<option value="Work1">Work1</option>
<option value="Work2">Work2</option>
<option value="Noworktoday">No work today</option>
<option value="Other">Other</option>
</select>
...

findTest.php
if (isset($_GET['work'])) {
//for example : $work == "Work1"
$work=$_GET['work'];
if ($work=="Noworktoday") {
  echo "
No work today
";
}  else {
  echo "
New ".$work."
";
  echo "<input name=\"new".$work."\" type=\"text\"";
  echo " size=\"20\" value=\"new".$work."\" />";
  echo "
";
}

//
New Work1<input name="newWork1" type="text" size="20" value="newWork1" />

Update:
You can not see your values because you did'nt echo them
and you have to test all $_POST
$page = '';
$answer = null; //clean start.
if (isset($_POST['Comments'])) {
 $Comments = $_POST['Comments']; } else {
 $Comments = 'n/a';
}

if (isset($_POST['newWork1'])) {
 $newWork1 = $_POST['newWork1']; } else {
 $newWork1 = 'n/a';
}
....

and so on for all possible values

echo your variables
if (isset($_POST['Submit'])) {
    ?>

Test message = <? echo $Comments; ?>
        and = <? echo $newWork1; ?> or this should be
        work2 = <? echo $newWork; ?>

<? } ?>

Update:
I can not see the actual code, you need a if (isset ...  for all possible variables . In my example I have described only two possibilities. You need also e.g.
 if (isset($_POST['newWork2'])) { ...
 if (isset($_POST['newOther'])) { ...

and so on !! And make only asimple output.
if (isset($_POST['Submit'])) {
 echo "message = ".$Comments."
";
 echo "newWork1 = ".$newWork1."
";
 echo "newWork2 = ".$newWork2."
";
 echo "newOther = ".$newOther."
";
 }

and put it logical together
This is illogical Work2 assigned to newWork !!!


text:
Q: Pynput keyboard listener not working on Macbook air M2 I have recently purchased a Macbook air M2. One python code that I have been successfully been using on my older Macbook air, doesn't longer work for some reason.
I receive this error message when trying to run the code in Spyder 5.3.3 through Anaconda, despite adding accessibility to Anaconda via System preferences:

This process is not trusted! Input event monitoring will not be possible until it is added to accessibility clients.

When trying to run the code via terminal I receive the following error:

zsh: segmentation fault ...

OS: MacOS Ventura 13.0.1
There shouldn't be problems with the code, but it seems there is some problem adding the correct accessibility? Does pynput not work on the latest Macbooks or is there some other reason to it not working?
The code:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import pyperclip
import os
import os.path
from pynput.keyboard import Key, Listener
from striprtf import striprtf
import re

def replace_words(string, dictionary):
    # sort keys by length, in reverse order
    for item in sorted(dictionary.keys(), key = len, reverse = True):
        string = re.sub(item, dictionary[item], string)
    return string

SAVE_FILE = input("Name of clipboard file: ")

save_path = "/Users/username/Clipboard"
FileName = os.path.join(save_path, SAVE_FILE+".txt")
f= open(FileName, "w")

def on_release(key):

    print("f")
    if str(key) == "'c'":
        print('Copying the slected')
        text = pyperclip.paste()  # text will have the content of clipboard
        print(text)
        text = striprtf(text)
        text = text.replace('\n\n', '\n')
        print(text)
        f.write(text+"\n")

    print('{0} release'.format(
        key))
    if key == Key.esc:
        print("End")
        return False

# Collect events until released
with Listener(
        on_release=on_release) as listener:
    listener.join()

f.close()


text:
Q: PyCharm Vagrant Couldn't refresh skeletons for remote interpreter I configured remote Python interpreter 3 months ago with Vagrant, when I was using it, everything was fine, for the last two days I am receiving Couldn't refresh skeletons for remote interpreter  error very frequently, as on the video: http://take.ms/0Mr8b
I am not sure what might be error for this.
Environment:
Vagrant Ver.2.0.0
PyCharm 2017.3.3 (Professional Edition)
Build #PY-173.4301.16, built on January 11, 2018
Licensed to my name
Subscription is active until May 23, 2018
For educational use only.
JRE: 1.8.0_152-release-1024-b11 x86_64
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
Mac OS X 10.13.3

A: It is solved by cleaning .pycharm_helpers folder on remote interpreter.
rm -rf ~/.pycharm_helpers

A: It is solved by File-> Invalidate Caches & Restart in my case as suggested by youtrack forum

A: I needed to remove the Visible only for this project flag from the Deployment configuration that was attached to the remote interpreter. Then I invalidated the cache and restarted as suggested by the other answer.


text:
Q: "Beveled" Shapes in Quartz 2D I'm familiar with some of the basics of Quartz 2D drawing, like drawing basic shapes and gradients and so on, but I'm not sure how to draw a shape with a "beveled" look, like this:
beveled circle http://www.shaggyfrog.com/junk/beveled-circle.jpg
Essentially we've got a shine on one corner, and maybe some shading in the opposite corner. I think -- I didn't make this image, although I'd like to be able to approximate it.
Any ideas? This is on the iPhone, and I'd like to use built-in frameworks and avoid any external libraries if at all possible.

A: There are really only a few useful approaches you can take to this problem.

*

*Use your basic shape drawing techniques and combine them with a one or more gradient curves. (Implicit object construction) with curves/fills.

*Custom build a UIView and build the object up per-pixel in a drawRect.

*Pre-render your beveled/shadowed shapes and load them into an image and blit them into a UIImageView.


text:
Q: Link to a page and trigger toggle content on div Good morning,
Since last week I am struggling with what looks like a common issue (considering the number of topic I have read about this matter): how to link a toggled content from another page.
I have been able to progress into this topic.
I am still facing a problem though (as usual, a solution or an answer leads to another issue!):
The link from another page to the toggled content works BUT it opens all the div of the page.
The question is straight forward though: How can I toggle the content of a single div?
My code is as follow (it is an extract of the content of the page - I have more than 2 div with toggled content). And yes, I know it is pretty ugly, but I am trying to make my way in the HTML/CSS and whatever without much help.
Many thanks!

TITLE1

CONTENT1

TITLE2

CONTENT2

EDIT:
I guess the issue comes from:
if ( location.hash.length > 1 )
{
    Toggle( location.hash.substring(1) );
    Toggle2( location.hash.substring(1) );

}

If ( location.hash.length > 1 ), it opens both toggled content from the functions "Toggle" and "Toggle2". Is that correct?

A: What do you mean by "how to link a toggled content from another page"?
Given your code, it seems you want an external link to lead to your page and toggle a div, right?
If that's the case, then there are a few things to change. First of all, this...
Toggle( location.hash.substring(1) );

...will not work as you want it to work. Indeed, your function Toggle() takes no argument.
However, you could make a more "generalized" version of your function, which would take as an argument the ID of the div to toggle:
function Toggle(id) {
    var el = document.getElementById(id);
    if (el.style.display == "block") {
        el.style.display = "none";
    } else {
        el.style.display = "block";
    }
}

And at the end of the page...
if (location.hash.length > 1) {
    Toggle(location.hash.substring(1));
}

If your page is named, for instance, mypage.html, then a link to mypage.html#example-id would load your page and toggle the element of ID example-id.
One last thing; instead of applying display: none to every togglable div, create a class ToggleTarget and give it display: none. Then, give this class to every togglable element you have, while giving them a unique ID.
Working version

        <title>Test</title>

TITLE1

CONTENT1

TITLE2

CONTENT2


text:
Q: In creating a new column to a data frame using dplyr, R overwrites existing variable name I would like to add new columns to an existing data frame. The column names are generated in a FOR loop so that they are numerically sequential. Here is the code:
NewColumn <- paste("return_date", as.character(i), sep = "_")

When I display NewColumn, this is what I want:
[1] "return_date_2"

When I execute:
mutate(Cima, NewColumn = "01-01-01")

The name of the column is: NewColumn
I can rename it, but is there a way to avoid this step?
Why does R not recognize that NewColumn holds a string?

A: Do you have to use mutate in your code?
If not, replace mutate(Cima, NewColumn = "01-01-01") with Cima[NewColumn] <- "01-01-01"

A: Because mutate consider the left part of the equal sign to be already the column name. U can get over it with the code below:
library(dplyr)
library(rlang)

i <- 1
NewColumn <- paste("return_date", as.character(i), sep = "_")

> mutate(mtcars, !!NewColumn := 5)

    mpg cyl  disp  hp drat    wt  qsec vs am gear carb return_date_1
1  21.0   6 160.0 110 3.90 2.620 16.46  0  1    4    4             5
2  21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4             5
3  22.8   4 108.0  93 3.85 2.320 18.61  1  1    4    1             5
4  21.4   6 258.0 110 3.08 3.215 19.44  1  0    3    1             5
5  18.7   8 360.0 175 3.15 3.440 17.02  0  0    3    2             5
6  18.1   6 225.0 105 2.76 3.460 20.22  1  0    3    1             5
7  14.3   8 360.0 245 3.21 3.570 15.84  0  0    3    4             5
8  24.4   4 146.7  62 3.69 3.190 20.00  1  0    4    2             5
9  22.8   4 140.8  95 3.92 3.150 22.90  1  0    4    2             5
10 19.2   6 167.6 123 3.92 3.440 18.30  1  0    4    4             5
11 17.8   6 167.6 123 3.92 3.440 18.90  1  0    4    4             5
12 16.4   8 275.8 180 3.07 4.070 17.40  0  0    3    3             5
13 17.3   8 275.8 180 3.07 3.730 17.60  0  0    3    3             5
14 15.2   8 275.8 180 3.07 3.780 18.00  0  0    3    3             5
15 10.4   8 472.0 205 2.93 5.250 17.98  0  0    3    4             5
16 10.4   8 460.0 215 3.00 5.424 17.82  0  0    3    4             5
17 14.7   8 440.0 230 3.23 5.345 17.42  0  0    3    4             5
18 32.4   4  78.7  66 4.08 2.200 19.47  1  1    4    1             5
19 30.4   4  75.7  52 4.93 1.615 18.52  1  1    4    2             5
20 33.9   4  71.1  65 4.22 1.835 19.90  1  1    4    1             5
21 21.5   4 120.1  97 3.70 2.465 20.01  1  0    3    1             5
22 15.5   8 318.0 150 2.76 3.520 16.87  0  0    3    2             5
23 15.2   8 304.0 150 3.15 3.435 17.30  0  0    3    2             5
24 13.3   8 350.0 245 3.73 3.840 15.41  0  0    3    4             5
25 19.2   8 400.0 175 3.08 3.845 17.05  0  0    3    2             5
26 27.3   4  79.0  66 4.08 1.935 18.90  1  1    4    1             5
27 26.0   4 120.3  91 4.43 2.140 16.70  0  1    5    2             5
28 30.4   4  95.1 113 3.77 1.513 16.90  1  1    5    2             5
29 15.8   8 351.0 264 4.22 3.170 14.50  0  1    5    4             5
30 19.7   6 145.0 175 3.62 2.770 15.50  0  1    5    6             5
31 15.0   8 301.0 335 3.54 3.570 14.60  0  1    5    8             5
32 21.4   4 121.0 109 4.11 2.780 18.60  1  1    4    2             5

Take a look into this one to understand it better:
Use dynamic variable names in `dplyr`
You can also check advanced R from Hadley Wickham and take a look at the bang bang operator and see what it does.
https://adv-r.hadley.nz/


text:
Q: Graph with large minimum degree can be union of few complete (bipartite) graphs Problem:

Let $G$ be a bipartite graph with $n$ vertices on each side and
minimum degree $n-d$. Show that it can be written as the union of
$O(d\log n)$ complete bipartite graphs.

My approach with the probabilistic method: consider a random algorithm that generates a complete bipartite graph (whose edges are a subset of $E(G)$. If we can show that each edge shows up with probability at least $\frac 1d$, then say I use $\lceil 3d\log n \rceil$ cliques. For each edge $e$, let $1_e$ be the indicator variable that it is not in all of the $\lceil 3d\log n \rceil$ cliques. Let $X$ be the number of edges not in the union. Then
$$\mathbb{E}[X] = \sum_e \mathbb{E}[1_e] \le \sum_e (1-1/d)^{3d \log n} \le n^2 (1-1/d)^{3d \log n} = n^2 e^{-3\log n} = \frac 1n < 1$$
So it is possible that $X=0$ i.e. we are done.
I tried the following algorithm which satisfies each edge showing up with probability at least $d^{-2}$: take a random ordering of the vertices. Let $uv$ be an edge of the graph, $S_u=V\backslash (u\cup N(u)), S_v=V\backslash (v\cup N(v))$, and $I$ be the set of vertices that come before all other vertices that are NOT adjacent to it. Then the events that $u\in I, v\in I$ are independent, and each happen with probability at least $\frac 1d$.
This is unfortunately not strong enough. Can I have a hint? Thank you!


text:
Q: Should I use OAuth to have a SPA communicate with the back-end? I am building a SPA in VueJS. I want to create the back-end (API) in Laravel. I am unsure whether I should use OAuth2 for authenication.
All examples I have found that explain OAuth explain it using two services (Example: Login with Facebook on Spotify). But this isn't my use case.
My API and SPA VueJS app are basicly (part of) "the same application".
What from of authentication should I use?

A: Answer depends on your final requirement.
Use OAuth based authorization for back-end API if you have plans to expose the back-end API for other clients OR as a service
Use simple session based Authorization for back-end if your back-end will never get exposed for outside and tightly coupled with front-end (as you will never use external login options)

A: First of all, the fact that your SPA and API do belong to the same application is definitely no reason not to use OAuth2.
A good reason to use OAuth2, OIDC ... is the fact that many companies like Auth0, Okta and even Facebook and Google, offer you easy to use libraries to add authentication and authorization to your app so you don't have to worry about usernames, password yourself.
Laravel Passport seems to be a good starting point to integrate OAuth in your API (I, however, never used it myself).
oidc-client-js is a javascript library that I used extensively in SPA's written in pure javascript, React ...
These libraries point to another advantage of using OAuth2/OIDC: you can easily change your coding framework without impacting your auth integration.


text:
Q: How to pickle python object which has reference to cytpes library I am trying to pickle python function which uses ctypes object to call some function.
I have created a '.so' file with my sum function which I am trying to invoke in my python code
c code
#include <stdio.h>

int sum(int a, int b) {

    return a + b;

}

use in python code
from ctypes import cdll
libsum = cdll.LoadLibrary("libsum.so")

def cal_sum(param1, param2):
    return libsum.sum(param1, param2)

When I try to pickle the cal_sum function using
out = open("/tmp/abc", "wb")
cloudpickle.dump(cal_sum, out)
out.close()

I am getting below error
TypeError: can't pickle getset_descriptor objects.
Is there any way we can pickle such function


text:
Q: How to stop objects being lost between PagedList calls? Question Background:
I'm using PagedList MVC to provide paging for a large data set on my View.
The Issue:
I have a form on my View which passes an object populated with a users parameters on the form inputs to a method on the controller called Index, I also pass the page number the users wishes to navigate too. The first time the form is submitted to the controller method object is populated from the form as expected, when I click on page two I'm passing null properties to the object.
This makes sense as the users is not submitting a form anymore, but I have an issue now where I have lost the orginal filter parameters.
How can I store the original filtered parameters that popuate the model and send them each time a users changes page?
The Code:
The View with the form and Model:
            @using (Ajax.BeginForm("Index", "ShopComparator", new AjaxOptions { UpdateTargetId = "result", OnBegin = "LoadingSpinner", OnSuccess = "MessageSent", OnFailure = "FailedMail" }))
        {
            @Html.ValidationSummary(true)

                                @Html.TextBoxFor(m => m.SearchValues.searchTerm, new { @class = " form-control", placeHolder = "Item to search for", id = "name" })
                                @Html.ValidationMessageFor(model => model.SearchValues.searchTerm)

                                @Html.DropDownListFor(x => x.SearchValues.searchCatagory, new SelectList(Model.GetCatagories), "Select Product Catagory", new { @class = "form-control" })

                                @Html.DropDownListFor(x => x.SearchValues.countryCode, new SelectList(new List<string> {
                        "UK",
                        "US",
                        "FR",
                        "DE",
                   }), "Select Code", new { @class = "form-control" })

                                <input type="submit" class="btn btn-primary btn-block" value="Search Prices" />

        }

The Index Method on the HomePage Controller that is called by the above form along with the populated HomePageVM object passed from the form along with the page number. The HomepageVM model has null properties after subsequent page changes from page 1.
    public ActionResult Index(HomePageVM homePageSearch, int pageNo = 1)
    {
        RootObject response = _httpCaller.CallWebApiEndPoint(homePageSearch.SearchValues.searchTerm, homePageSearch.SearchValues.searchCatagory, homePageSearch.SearchValues.countryCode);

        List<ViewDisplayItem> viewModelResponseList = ConvertToViewModel(response);

        return View(viewModelResponseList.ToPagedList(pageNo, 3));
    }

Index View that displays the Items that will be Paged:
  @foreach (var item in @Model)
        {

@item.Title

@item.Price

See More

@item.Origin

        }

    @Html.PagedListPager(Model, page => Url.Action("Index", new { pageNo = page }), PagedListRenderOptions.OnlyShowFivePagesAtATime)

EDIT
I have taken Stephens comments onboard and now have a updated solution. This is nearly working put is giving a null HomePageVM object when passed back to the controller on the second page.
Code:
Updated HomePageVM model:
public class HomePageVM
{
    public List<string> GetCatagories { set; get; }

    public HomePageSearchVM SearchValues { set; get; }
}

public class HomePageSearchVM
{
    public string searchTerm { set; get; }
    public string searchCatagory { set; get; }
    public string countryCode { set; get; }
}

HomepageDisplayItems:
  public class HomepageDisplayItems
{
    public HomePageVM SearchProperties { set; get; }
    public PagedList<ViewDisplayItem> DisplayItems { set; get; }
}

Controller:
public ActionResult Index(HomePageVM homePageSearch, int pageNo = 1)
    {
        RootObject response = _httpCaller.CallWebApiEndPoint(homePageSearch.SearchValues.searchTerm, homePageSearch.SearchValues.searchCatagory, homePageSearch.SearchValues.countryCode);

        List<ViewDisplayItem> viewModelResponseList = ConvertToViewModel(response);

        var displayObj = new HomepageDisplayItems()
        {
            SearchProperties = homePageSearch,
            DisplayItems = new PagedList<ViewDisplayItem>(viewModelResponseList, pageNo, 12)
        };

        return View(displayObj);
    }

Index.cshtml:
NOTE: Setting homePageSearch to the model.SearchProperties object
@using PagedList.Mvc

@model ShopComparisonEngine.Models.HomepageDisplayItems

......

@Html.PagedListPager(Model.DisplayItems, page => Url.Action("Index", new { homePageSearch = Model.SearchProperties, pageNo = page }), PagedListRenderOptions.OnlyShowFivePagesAtATime)


text:
Q: calling user_save from within hook_init failing on Drupal6 I have a module that implements hook_init.
Within that I have a case where I try to call user_save like save
user_save ('');

I figure this should work since I am not setting a uid, so it should create a new one.  It also says that the $array should be allowed to be empty.
However, this always returns FALSE. ??
I have also tried setting these values in $array but this doesn't work either:
        $foo = array(
            'name' => 'the new user',
            'mail' => 'the new user mail',
            'pass' => user_password(),
            'status' => 1,
            );
        $new_user = user_save ('', $foo);

A: Look at the documentation:

Parameters
  $account The $user object for the user to modify or add. If $user->uid is omitted, a new user will be added.
  $array (optional) An array of fields and values to save. For example, array('name' => 'My name'); Setting a field to NULL deletes it from the data column.

So when you call user_save() the first parameter must be a user object. If that user object doesn't have a uid, or is a string like in your case, a new user will be created. Here the 2nd parameter is necessary. It's not required to use the function, but as it holds all the values you want to save, you wont get far trying to create a user with no data at all. What use is a user without password, username etc. So a minimum of data is required as well, so Drupal will know what to save.


text:
Q: Quartz Cron Job scheduling I want to schedule a Job in the Quartz Cron job format to run everyday at 4:30am. so i did   0 30 4 */1 * ?   . Will this work good.  How different is this expression when compared to  0 30 4 * * ?  . Plz tell me, if they are going to work the same or not !

A: Yes, they should work equally. */1 is cron idiom for "every 1 day", but that is already the default for cron expressions unless specified otherwise.


text:
Q: Laravel 5.4 Auth::User() with relationship not working I have Table Vendors (for test Auth relationship) and Table Vendor_users,
But i use  Auth::user() it not relationship

And This Database

In Vendor model
    protected $table = 'vendor_users';
 public function Vendor_test(){
        return $this->belongsTo(Vendor_test::class);
    }

And Vendor_test model
 protected $table = 'vendors';

public function Vendor(){
    return $this->hasMany(Vendor::class);
}

A: from chat and your current table structure, you should have relation like this
in Vendor Model
public function vendor_contact()
{
  return $this->belongsTo(Vendor_contact::class, 'vendor_contact_id');
}

in Vendor_contact Model
protected $primaryKey = 'vendContactId'; //check this

public function vendor()
{
  return $this->hasOne(Vendor::class, 'vendor_contact_id');
}

Now use lazy eager loading for loading vendor_contact relationship
Auth::user()->load('vendor_contact');
dd(Auth::user());

A: As per the discussion and the table structure you have,
Add the relation function in your model vendor_users.
protected $table = 'vendor_users';
public function vendor_contact()
{
   return $this->belongsTo(Vendor_contact::class, 'vendor_contact_id');
}

get the user with the vendor_contact and check
$user = Auth::user()->with('vendor_contact')->first(); //  As you asked with for auth
//OR
$user = Auth::user()->load('vendor_contact'); // From the rkj answer as I found this good.
// OR
$user = Vendor::find(1)->with('vendor_contact')->first();
dd($user);


text:
Q: How to activate spring's internal logging in a Spring application, which is not a Spring Boot application In the spring source code I see:
boolean debug = logger.isDebugEnabled();

What should I do to make debug true?
With Spring Boot, if I add the property logging.level.root=DEBUG, it works. But not in Spring.

A: Tested on springboot 2.1.9.RELEASE

*

*Set root log level directly in config file application.yml
logging:
  level:
    root: trace

*create file "logback.xml" under resources directory in maven project.

<?xml version="1.0" encoding="UTF-8"?>
<configuration debug="true" scan="false" scanPeriod="1 seconds">
    <appender name="stdout" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>%d [%thread] %-5level %logger{36} [%file : %line] - %msg%n</pattern>
        </encoder>
    </appender>
    <root level="trace">
        <appender-ref ref="stdout"/>
    </root>
</configuration>

debug="true" in config will output many useful debug log,such as
10:02:15,511 |-INFO in ch.qos.logback.classic.LoggerContext[default] - Found resource [logback.xml] at [file:/C:/Users/win/proj/my_web/manage/target/classes/logback.xml]
10:02:15,909 |-INFO in ch.qos.logback.classic.joran.action.RootLoggerAction - Setting level of ROOT logger to TRACE
10:02:15,909 |-INFO in ch.qos.logback.core.joran.action.AppenderRefAction - Attaching appender named [stdout] to Logger[ROOT]

if you see below output Propagating, it means you have config log level in somewhere, like logging.level.root=info in application.properties
10:02:17,026 |-INFO in ch.qos.logback.classic.jul.LevelChangePropagator@495b0487 - Propagating INFO level on Logger[ROOT] onto the JUL framework


text:
Q: java.util.zip.ZipException: duplicate entry: net/lingala/zip4j/core/HeaderReader.class При обновлении gradle-plugin появилась такая ошибка

Error:Execution failed for task
  ':app:transformClassesWithJarMergingForDebug'.
  com.android.build.api.transform.TransformException: java.util.zip.ZipException: duplicate entry:
  net/lingala/zip4j/core/HeaderReader.class

В версии gradle-plugin 1.3.1 всё нормально. Начиная с версии 1.5.0 уже не работает.
Я пробовал но не помогло:

*

*В терминале запускать "./gradlew clean"

*Invalidate cache and restart

*Clean and rebuild project

Файл build-gradle
    android {
    compileSdkVersion 23
    buildToolsVersion "23.0.3"

    defaultConfig {
        multiDexEnabled true
        applicationId "ru.statistic"
        minSdkVersion 15
        targetSdkVersion 23
        versionCode 1451145152
        versionName "1.1.1.1"
    }
    dexOptions {
        javaMaxHeapSize "4g"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}
dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])

    compile project(':MPChartLib')
    compile('de.psdev.licensesdialog:licensesdialog:1.6.0') {
        exclude module: 'support-v4'
    }

    compile 'com.android.support:multidex:1.0.1'
    compile 'com.android.support:appcompat-v7:23.4.0'
    compile 'com.android.support:cardview-v7:23.4.0'
    compile 'com.android.support:design:23.4.0'
    compile 'com.google.android.gms:play-services:9.4.0'
    compile 'com.github.andkulikov:transitions-everywhere:1.2.2'
    compile 'se.emilsjolander:stickylistheaders:2.5.2'
    compile 'com.afollestad.material-dialogs:core:0.9.0.0'
    compile 'com.pnikosis:materialish-progress:1.2'
    compile 'me.relex:circleindicator:1.1.3@aar'
    compile 'me.dm7.barcodescanner:zbar:1.9'
}

Библиотека zip4j_1.3.2.jar находится в папке libs. Даже если удалить его добавить в gradle

compile group: 'net.lingala.zip4j', name: 'zip4j', version: '1.3.2'

ничего не меняется.
Может кто-нибудь подсказать что делать?
Если запускать приложение в эмуляторе с андроидом 5.1, то ошибки почему то нет. А если с андроид 4.4 то уже ошибка.


text:
Q: DBA Setting in MySQL to avoid schema name as prefix for every table I have about 200 tables that are prefixed with the schema name- hram_whsql.   if i alter from MySQL workbench it still persists. If I create a table the new table has a prefix. I want to get rid of this prefix for all the tables.
Thanks!
Manish


text:
Q: How to keep scrollbar for div visible stop it hiding on Apple OS/iOS (Chrome/Safari)? I have a div with some inline content that is scrollable.
On Apple OS Yosemite (Chrome and Safari) and iOS iPad/iPhone (Chrome and Safari) this scroll thumb/bar is hidden (until you actually start scrolling the content then it appears).
On Windows Chrome/IE/FF this scroll thumb/bar is always visible.
How do I keep this scroll thumb/bar visible at all time on Apple OS/iOS for Safari and Chrome etc?

A: In both cases, browsers default to the OS's scroll views - on OS X, that means a scrollbar that disappears, on windows, it means the scroll thumb/bar is always hidden (ever wonder why all scrollable windows look pretty much the same on a given OS?). The only solution, is to NOT use the native scrollable area (overflow:hidden) and replace it with JavaScript (e.g. http://manos.malihu.gr/jquery-custom-content-scroller/) that re-implements it (but allows you to control the look of) the scrolling interface. Keep in mind that doing this presents it's own set of compatibility issues.
Honestly, the (arguably) best thing to do is just to present users with what they are familiar with - on OS X, that's a scrollbar that gets hidden and on Windows, it's an omnipresent scrollbar. Stick to the defaults and you'll never run into UX issues.

A: try this
::-webkit-scrollbar {
    display: none;
}

found here

A: ::-webkit-scrollbar {
    -webkit-appearance: none;
    width: 7px;
}
::-webkit-scrollbar-thumb {
    border-radius: 4px;
    background-color: rgba(0,0,0,.5);
    box-shadow: 0 0 1px rgba(255,255,255,.5);
}

from here


text:
Q: netsuite add back order quantity to invoice advanced pdf template I would like to add back order quantity to the invoice line items but the field doesn't appear in the template editor.  How can I add the field?

A: SuiteAnswers suggests that you use a custom field but I found that this did not return the value for the sales order - perhaps it returns the back order amount for an item, not a sales item.
I tried using the Chrome plugin NetSuite Field Explorer on the invoice form to see what field name NetSuite is using.  The sales order lines are kept in a separate lineItem field and that doesn't appear to be available in the template editor.  The NetSuite Field Explorer has a link which takes you to the record definition of the invoice record type.  On that page the back ordered field is listed as quantityremaining.  Plugging that into the template resulted in the display of the correct information, despite the template editor not recognizing the field (when it does, it displays the description otherwise, it just displays the freemarker markup):

${item.quantityremaining}


text:
Q: Is there a way I can count if the number of occurrences of semicolon in a string is more than two in C# I would like to do a check to count the number of times a ":" appears in a string. Already I have this code:
        if (string.IsNullOrWhiteSpace(entryTrimmed) ||
            isAvailable != null ||
            entryTrimmed.StartsWith("::") ||
            entryTrimmed.EndsWith("::")) ||
            entryTrimmed.
        {
            OK_Button.IsEnabled = false;
            return;
        }

Is there a simple way that I could also include where there are more than three ":"?

A: You can use count method
var colonCount = entryTrimmed.Count(e => e == ':')

A: Simple linq's count:
    if (string.IsNullOrWhiteSpace(entryTrimmed) ||
        isAvailable != null ||
        entryTrimmed.StartsWith("::") ||
        entryTrimmed.EndsWith("::")) ||
        entryTrimmed.Count(c => c == ':') > 3 // there are more than three ":"
    {
        OK_Button.IsEnabled = false;
        return;
    }

If you don't want to use linq, you can use Replace and Length:
    if (string.IsNullOrWhiteSpace(entryTrimmed) ||
        isAvailable != null ||
        entryTrimmed.StartsWith("::") ||
        entryTrimmed.EndsWith("::")) ||
        entryTrimmed.entryTrimmed.Length - entryTrimmed.Replace(":", "").Length > 3 // there are more than three ":"
    {
        OK_Button.IsEnabled = false;
        return;
    }


text:
Q: How to use GPS Service in android I'm working on Android project that related to GPS I still new to android so I don't know a lot about it.
My project is an app where it calculates the distance between user location and a specified other location so if the distance is less than (X) say 1KM the app will send a notification to the user.[[I know how to calculate the distance between two
locations]].
My problem is: how can I do this even if the user didn't open the app (I mean if there's anyway that I can make the app calculates the distance in the background while the app is closed).so I want the GPS feature works in the background.
Thanks in Advance.

A: You can use a service for background process.
For your question for getting location, you should try these links:
Best way to get user GPS location in background in Android
Get GPS location via a service in Android

A: My solution for this problem was simply :-
you can use Services for working in the background (when the Activity isn't showing)
check this : -Get GPS location via a service in Android
**if you want this service to run for ever, even if the app is closed/killed you can use broadcast receivers **

A: User services. They are simple to use and all you need.
Here is the documentation.
A service is another component of an android application (like activity). You need to define the service in manifest. After that you could start the device using startService (intent). If you need to take some info (communicate with one activity) you can use bindService instead of startService. (Also need to implement onBind).
Another solution is to sendData using a broadcast receiver. Or you can simple set a notification in service and use it.

A: To get the app to run in the background, you'll need to learn about a service.
Service is a service that causes applications to run in the background such as gps, notification and more ..
link:
https://developer.android.com/reference/android/app/Service.html


text:
Q: MatDialog Child Closes Parent MatDialog I have a dialog that is used as popup window form.  When user gets error the dialog pops up a smaller dialog with error message and OK button.
Clicking OK closes both matDialog windows.
How can I get it to just close its self and not its parent?
Parent =
<ng-template #dialogRef let-data>

Child =
this.dialog.open(ErrorDialogComponent, { data: message });

I have tried using different scopes, but OK seems to close all dialog windows.

A: You can close a dialog programmatically with:
constructor(private dialogRef: MatDialogRef<MyComponentToClose>){}

closeComponent(){
   this.dialogRef.close()
}

A: I had the same problem. This worked for me, though it's a slight workaround:
<button class="btn" mat-dialog-close="">Close</button>


text:
Q: How to prevent adding empty items to Room Database in Android I am working on a TodoList App and I set an Implementation to NOT allow users to add a Task if one or all of the required fields are empty. This Implementation was working perfectly before. However, when I recently encountered some bugs, it mysteriously stopped working. I've rechecked everything and even the commit when I made it work the first time and I didn't see any difference but it still isn't working. I humbly ask that you check to see if my implementation is right and suggest how to properly handle this feature. Here is my code...
First my Model
import androidx.room.Entity
import androidx.room.PrimaryKey
import java.util.*

/** Our Model class. This class will represent our database table **/

@Entity(tableName = "todo_table")
data class Todo(
    @PrimaryKey (autoGenerate = true) // here "Room" will autoGenerate the id for us instead of assigning a randomUUID value
    val id : Int = 0,
    var title : String = "",
    var date : Date = Date(),
    var time : Date = Date(),
    var todoCheckBox : Boolean = false
)

AddFragment
import android.graphics.Color
import android.os.Bundle
import android.text.SpannableString
import android.text.TextPaint
import android.text.TextUtils
import android.text.method.LinkMovementMethod
import android.text.style.ClickableSpan
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.fragment.findNavController
import com.bignerdranch.android.to_dolist.R
import com.bignerdranch.android.to_dolist.data.TodoViewModel
import com.bignerdranch.android.to_dolist.databinding.FragmentAddBinding
import com.bignerdranch.android.to_dolist.fragments.dialogs.DatePickerFragment
import com.bignerdranch.android.to_dolist.fragments.dialogs.TimePickerFragment
import com.bignerdranch.android.to_dolist.model.Todo
import java.text.SimpleDateFormat
import java.util.*

private const val DIALOG_DATE = "DialogDate"
private const val DIALOG_TIME = "DialogTime"
const val SIMPLE_DATE_FORMAT = "MMM, d yyyy"
const val SIMPLE_TIME_FORMAT = "H:mm"

private const val TAG = "AddFragment"

class AddFragment : Fragment() {

    private lateinit var todoViewModel : TodoViewModel
    private var _binding : FragmentAddBinding? = null
    private val binding get() = _binding!!
    private lateinit var todo : Todo

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        todo = Todo()
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentAddBinding.inflate(inflater, container, false)

        todoViewModel = ViewModelProvider(this)[TodoViewModel::class.java]

        remindersTextSpan()

        // will insert our database when clicked
        binding.abCheckYes.setOnClickListener {
            insertTodoInDatabase()
        }

        // showing our datePickerDialog
        binding.edDate.setOnClickListener {

            childFragmentManager.setFragmentResultListener("requestKey", viewLifecycleOwner)
{_, bundle ->
                val result = bundle.getSerializable("bundleKey") as Date
                // passing the result of the user selected date directly to the _Todo class instead
                todo.date = result
                // will ONLY update the date field when it is not empty so that we don't get a preloaded Date textView
                if(todo.date.toString().isNotEmpty()) {
                    updateDate()
                }
            }

            DatePickerFragment().show(this@AddFragment.childFragmentManager, DIALOG_DATE)
        }

        // showing our timePickerDialog
        binding.edTime.setOnClickListener {

            childFragmentManager.setFragmentResultListener("tRequestKey",
viewLifecycleOwner) {_, bundle ->
                val result = bundle.getSerializable("tBundleKey") as Date
                // passing the result of the user selected time directly to the _Todo class instead
                todo.time = result
                // will ONLY update the time field when it is not empty so that we don't get a preloaded Time textView
                if (todo.time.toString().isNotEmpty()) {
                    updateTime()
                }

            }
           TimePickerFragment().show(this@AddFragment.childFragmentManager, DIALOG_TIME)
        }
        return binding.root
    }

    // function to update Date
    private fun updateDate() {
        val dateLocales = SimpleDateFormat(SIMPLE_DATE_FORMAT, Locale.getDefault())
        binding.edDate.text = dateLocales.format(todo.date)

    }

    // function to update Time
    private fun updateTime() {
        val timeLocales = SimpleDateFormat(SIMPLE_TIME_FORMAT, Locale.getDefault())
        binding.edTime.text = timeLocales.format(todo.time)
    }

    // our reminders Text span
    private fun remindersTextSpan() {
        val spannableString = SpannableString("Set Reminders")

        val clickableSpan = object : ClickableSpan() {
            override fun onClick(widget: View) {
                Toast.makeText(context, "Set Reminders!", Toast.LENGTH_LONG).show()
            }

            override fun updateDrawState(ds: TextPaint) {
                super.updateDrawState(ds)

                ds.color = Color.BLUE
            }
        }
        spannableString.setSpan(clickableSpan, 0, 13,
SpannableString.SPAN_INCLUSIVE_EXCLUSIVE)

        binding.tvReminders.text = spannableString
        binding.tvReminders.movementMethod = LinkMovementMethod.getInstance()
    }

    // This function's job will be to insert Tasks in our database
    private fun insertTodoInDatabase() {
        val title = binding.edTaskTitle.text.toString()
        val date  = binding.edDate.text.toString()
        val time = binding.edTime.text.toString()

        if (inputCheck(title, date, time)) {
            val todo = Todo(0, title)
            todoViewModel.addTodo(todo)
            // This will make a toast saying Successfully added task if we add a task
            Toast.makeText(requireContext(), R.string.task_add_toast,
Toast.LENGTH_LONG).show()

            // FIXME: There is a bug here that allows the user to add Todos even when some OR all of the fields are empty.
            // FIXME: It has to do with updateTime and updateDate functions I think, so I will try to fix it but maybe not now.

            findNavController().navigate(R.id.action_addFragment_to_listFragment)
        } else {
            Toast.makeText(requireContext(), R.string.no_task_add_toast,
Toast.LENGTH_LONG).show()
        }
        Log.d(TAG, "Our todo widgets are $title $date and $time")
    }

    // This function will help us check if the texts are empty and then proceed to add them to the database
    // so that we do not add empty tasks to our database
    private fun inputCheck(title : String, date: String, time: String) : Boolean {

        // will return false if fields in TextUtils are empty and true if not
        return !(TextUtils.isEmpty(title) && TextUtils.isEmpty(date) && time.isEmpty())
    }

    override fun onDestroy() {
        super.onDestroy()
        _binding = null
    }
}

My DAO
 /**
  *  This will be our DAO file where we will be update, delete and add Todos to our
 database so it contains the methods used for accessing the database
  */

 @Dao
interface TodoDao {

    // onConflict will ignore any known conflicts, in this case will remove duplicate "Todos" with the same name
    @Insert(onConflict = OnConflictStrategy.IGNORE)
    suspend fun addTodo(todo: Todo)

    @Query("SELECT * FROM todo_table ORDER BY id ASC")
    fun readAllData() : LiveData<List<Todo>>

    @Query("DELETE FROM todo_table WHERE id IN (:idList)")
    suspend fun deleteSelectedTasks(idList : Long)

    @Query("DELETE FROM todo_table")
    suspend fun deleteAllTasks()
}

These are the emptyLists which weren't supposed be added even if one is missing which is the title in this case.

Then this my debugging test which proves that some or all the fields in any attempted Task is actually empty. The debug log messages that have spaces between "and" or only a date or a time proves that some or all the fields are empty but it still gets added. This was working perfectly before, I don't know why it stopped.

A: I think so... An error occurred in the inputCheck method.
Change the and operator to the or operator.
before
    // This function will help us check if the texts are empty and then proceed to add them to the database
    // so that we do not add empty tasks to our database
    private fun inputCheck(title : String, date: String, time: String) : Boolean {

        // will return false if fields in TextUtils are empty and true if not
        return !(TextUtils.isEmpty(title) && TextUtils.isEmpty(date) && time.isEmpty())
    }

after
    // This function will help us check if the texts are empty and then proceed to add them to the database
    // so that we do not add empty tasks to our database
    private fun inputCheck(title : String, date: String, time: String) : Boolean {

        // will return false if fields in TextUtils are empty and true if not
        return !(TextUtils.isEmpty(title) || TextUtils.isEmpty(date) || time.isEmpty())
    }

add comment.
'and' operator is all values must be true.
'is' operator is true even if only one value is true.
for example, field state. (title is empty, date is not empty, time is not empty.)
Before method step.

*

*!(TextUtils.isEmpty(title) && TextUtils.isEmpty(date) && time.isEmpty())

*!(true && false && false)

*!(false)

*true

After method step.

*

*!(TextUtils.isEmpty(title) || TextUtils.isEmpty(date) || time.isEmpty())

*!(true || false || false)

*!(true)

*false


text:
Q: Added GWT to web app. Other devs complain about compile time. What should I tell them? I recently added GWT to our project to implement an Ajax feature of our web app.  The other devs are complaining about the extra time GWT compile adds to the build and are asking why I didn't use JSON and jQuery instead.  What should I tell them?

A: Try to make the build smarter, if it isn't already: The GWT (client) part should only be re-compiled, when the client source changes. I assume, it's mostly you who changes that source, so the other developers won't experience the pain.
Caveat: This doesn't work of course, if your client source shares code with the existing project (I assume, it's a Java project on the server side?). But maybe you should avoid shared code in your case: Even though that's violating the DRY (Don't Repeat Yourself) principle, realize that you'd violate it anyway, if you didn't use GWT.
However, if you do reuse code from the server project, then you have a good argument, why you used GWT.

A: If developers have to compile the whole GWT stuff (all the permutations) in order to develop application it is real pain. Starting from GWT 2 you can configure the webapp project to be run in "development mode". It can be started directly from eclipse (Google plugin) thanks to built in jetty container. In such scenario only requested resources are compiled, and the process is incremental. I find this very convenient - GWT compilation overhead in our seam+richfaces+GWT application is very small during development cycle.
When it comes to application builds there are several options which can speed up GWT compilation. Here is checklist:

*

*disable soyc reports

*enable draftCompile flag which skips some optimization

*by adjusting localWorkers flag you can speed things a bit when building on multi-core CPU

*compile limited set of permutation: e.g. only for browsers used during development and only for one language

Release builds of the webapp should have draftCompile disabled though. Also all the laguage variants should be enabled. Maven profiles are very useful for parametrization of builds.

A: What was the reason you used GWT instead of JSON/jQuery?
I would ask the same question since for what you need, GWT may not be legitimately needed.

A: In my experience, I totally understand the complaints you are getting. GWT is a wonderful technology, and it has many benefits. It also has downsides and one of them is long compile time. The GWT compiler does lots of static code analysis and it's not something that has an order-of-magnitude solution.
As a developer, the most frustrating thing in the world is long development-deploy-test cycles. I know how your developers feel.
You need to make an architectural decision if the technological benefits of GWT are worth it. If they are, your developers will need to get used to the technology, and there are many solutions which can make the development much easier.

A: If there was a good reason for using GWT instead of pure javascript, you should tell them this reason (skills, debugging for a very hard to implement problem, you didn't want to deal with browser compatibility, etc). If there is no good reason, maybe they're right to be upset.
I use GWT myself and I know about this compile time :-)
If you used GWT for an easy-to-implement-in-javascript widget or something like that, maybe you should have consider using javascript instead.

A: What tool you're using to compile project?
Long time ago I've used ant and it was smart enough to find out that, when none of source files for GWT app (client code) has changed, the GWT compiler task was not called.
However, after that I've used maven and it was real pain, because it's plugin didn't recognize the code hasn't changed and GWT compilation was run all and over, no matter if it was needed or not.
I would recommend ant for GWT projects. Alternative would be rewriting the maven plugin or getting developers used to long compile time.


text:
Q: Create a 48 bit signed value from a byte array in Java I'm trying to extract 6 bytes from a byte array and convert them into a 48 bit signed integer value (I. E. a Java long). How can this be accomplished?
Edit:
For example, if a byte array has one of the following:
byte[] minInt48 = new byte[] { (byte)0x80, 0, 0, 0, 0, 0 };
byte[] maxInt48 = new byte[] { (byte)0x7F, (byte)0xFF, (byte)0xFF, (byte)0xFF, (byte)0xFF, (byte)0xFF };

How can I parse this into a Java primitive (i.e. Java long) such that the sign value is preserved?

A: First you need to understand sign extension.  You need to treat each byte as an unsigned value.
      long v = 0;
      byte q = -2; // unsigned value of 254
      v = v + q;
      System.out.println(v); // prints -2 which is not what you want.
      v = 0;
      v = v + (q & 0xFF); // mask off sign extension from q.
      System.out.println(v); // prints 254 which is correct.

This is one way of doing it.
     long val = 0;
     byte[] bytes = { -1, 12, 99, -121, -3, 123
     };
     for (int i = 0; i < bytes.length; i++) {
        // shift the val left by 8 bits first.
        // then add b.  You need to mask it with 0xFF to
        // eliminate sign extension to a long which will
        // result in an incorrect conversion.
        val = (val << 8) | ((i == 0 ? bytes[i]
              : bytes[i] & 0xFF));
     }
     System.out.println(val);


text:
Q: Prevent page from loading How can I prevent my PHP form from going to the next step if there are errors? So Basically I have my form named index.php and my PHP file named register.php which handles the form. How can I have register.php send errors to index.php and not go to register.php if there are errors? So basically I want to pass errors from register.php to index.php and if there are errors the user doesn't go to register.php. I hope this makes sense :)
register.php
<?php
include '/Users/idrisk/Colourity/s/db.php';

$name = mysqli_real_escape_string($con, $_POST['name']);
$username = mysqli_real_escape_string($con, $_POST['username']);
$email = mysqli_real_escape_string($con, $_POST['email']);
$pass1 = mysqli_real_escape_string($con, $_POST['pass1']);
$pass2 = mysqli_real_escape_string($con, $_POST['pass2']);

// Verification

if (empty($name) || empty($username) || empty($email) || empty($pass1) || empty($pass2))
    {
    echo "Complete all fields";

    // you can stop it here instead of putting the curly brace ALL the way at the bottom :)

    return;
    }

// Password match

if ($pass1 <> $pass2)
    {
    echo $passmatch = "Passwords don't match";
    }

// Email validation

if (!filter_var($email, FILTER_VALIDATE_EMAIL))
    {
    echo $emailvalid = "Enter a  valid email";
    }

// Password length

if (strlen($pass1) <= 6)
    {
    echo $passlength = "Password must be at least 6 characters long";
    }

// Password numbers

if (!preg_match("#[0-9]+#", $pass1))
    {
    echo $passnum = "Password must include at least one number!";
    }

// Password letters

if (!preg_match("#[a-zA-Z]+#", $pass1))
    {
    echo $passletter = "Password must include at least one letter!";
    }

?>

And my index.php
    <!DOCTYPE html>

<form method="post" action="register.php">
     Name: <input type="text" name="name" value="<?php if(!empty($_post['name'])){echo $name;}?>">

     Username: <input type="text" name="username" value="<?php if(!empty($_post['username'])){echo $username;}?>">

     Email: <input type="text" name="email" value="<?php if(!empty($_post['email'])){echo $email;}?>">

     Password: <input type="text" name="pass1" value="<?php if(!empty($_post['pass1'])){echo $pass1;}?>">

     Password, again: <input type="text" name="pass2" value="<?php if(!empty($_post['pass2'])){echo $pass2;}?>">

    <input type="submit" name="submit" value="submit">
</form>

So i want the errors from register.php to go to index.php And yes I know my code isn't secure. It's just being used as a demo on my computer only.

A: You are not actually posting to register.php but to the same page, index.php.
That seems the right thing to do because now you can use:
include 'register.php';

at the top of your script so that the variables are processed in the same page. Then - on a successful submission - you can redirect the visitor to another page where you display your success message.
And if the form contains errors, you can display them in / above / below the form itself.

A: there are 2 ways you can do it
1 - there is no need to send the info to another page, when you can handle it on the same page
<form method="POST" action="<?php echo $_SERVER["PHP_SELF"];>">

in this case you can use
if (condition here) {
// if true //
header('Location: register.php');
}
else {
echo "Error";
}

2 - you can set a temporary cookie on register.php too, if there are errors,
so on index.php you can have
like
if (error) {
setcookie("Error","Invalid Login",strtotime("+1 minute");
}

and on index.php
if (isset($_COOKIE["Error"]) {
echo "Invalid Login";
}

A: What you could do if this is just a demo, is to have everything all in one page.
Your index.php would contain a form that has an action="index.php"
<?php
include '/Users/idrisk/Colourity/s/db.php';

if(isset($_POST["submit"]) && !empty($_POST["submit"])) {

    $name = mysqli_real_escape_string($con, $_POST['name']);
    $username = mysqli_real_escape_string($con, $_POST['username']);
    $email = mysqli_real_escape_string($con, $_POST['email']);
    $pass1 = mysqli_real_escape_string($con, $_POST['pass1']);
    $pass2 = mysqli_real_escape_string($con, $_POST['pass2']);

    // Verification

    if (empty($name) || empty($username) || empty($email) || empty($pass1) || empty($pass2))
    {
        echo "Complete all fields";

        // you can stop it here instead of putting the curly brace ALL the way at the bottom :)

        return;
    }

    // Password match

    if ($pass1 <> $pass2)
    {
        echo $passmatch = "Passwords don't match";
    }

    // Email validation

    if (!filter_var($email, FILTER_VALIDATE_EMAIL))
    {
        echo $emailvalid = "Enter a  valid email";
    }

    // Password length

    if (strlen($pass1) <= 6)
    {
        echo $passlength = "Password must be at least 6 characters long";
    }

    // Password numbers

    if (!preg_match("#[0-9]+#", $pass1))
    {
        echo $passnum = "Password must include at least one number!";
    }

    // Password letters

    if (!preg_match("#[a-zA-Z]+#", $pass1))
    {
        echo $passletter = "Password must include at least one letter!";
    }

// check to see if all of the error variable are empty
if(empty($passmatch) && empty($emailvalid) && empty($passlength) && empty($passnum) && empty($passletter)) {
    // everything was empty so we have a good form
    // redirect to another page
    header('Location: example.com/');
}
}

?>

<!DOCTYPE html>

<form method="post" action="index.php">
     Name: <input type="text" name="name" value="<?php if(!empty($_post['name'])){echo $name;}?>">

     Username: <input type="text" name="username" value="<?php if(!empty($_post['username'])){echo $username;}?>">

     Email: <input type="text" name="email" value="<?php if(!empty($_post['email'])){echo $email;}?>">

     Password: <input type="text" name="pass1" value="<?php if(!empty($_post['pass1'])){echo $pass1;}?>">

     Password, again: <input type="text" name="pass2" value="<?php if(!empty($_post['pass2'])){echo $pass2;}?>">

    <input type="submit" name="submit" value="submit">
</form>

A: In index.php
Set action attribute value form to register.php.
Then at very top of register.php.
Check if empty field then redirect to index.php with header() function and exit;

Example code in register.php if found error.
header("Location: index.php");
exit;

A: hi try this code you need to use session or cookie.
register.php
<?php
session_start();

include '/Users/idrisk/Colourity/s/db.php';

$name = mysqli_real_escape_string($con, $_POST['name']);
$username = mysqli_real_escape_string($con, $_POST['username']);
$email = mysqli_real_escape_string($con, $_POST['email']);
$pass1 = mysqli_real_escape_string($con, $_POST['pass1']);
$pass2 = mysqli_real_escape_string($con, $_POST['pass2']);

$error = array();

// Verification

if (empty($name) || empty($username) || empty($email) || empty($pass1) || empty($pass2))
{
    $empty = "All Fields must be filled up!";
    array_push($error, $empty);
    $_SESSION['error'] = $error;
    header('Location: index.php');
}

// Password match

if ($pass1 <> $pass2)
{
    $passmatch = "Passwords don't match";
    array_push($error, $passmatch);
    $_SESSION['error'] = $error;
}

// Email validation

if (!filter_var($email, FILTER_VALIDATE_EMAIL))
{
    $emailvalid = "Enter a  valid email";
    array_push($error, $emailvalid);
    $_SESSION['error'] = $error;
}

// Password length

if (strlen($pass1) <= 6)
{
    $passlength = "Password must be at least 6 characters long";
    array_push($error, $passlength);
    $_SESSION['error'] = $error;
}

// Password numbers

if (!preg_match("#[0-9]+#", $pass1))
{
    $passnum = "Password must include at least one number!";
    array_push($error, $passnum);
    $_SESSION['error'] = $error;
}

// Password letters

if (!preg_match("#[a-zA-Z]+#", $pass1))
{
    $passletter = "Password must include at least one letter!";
    array_push($error, $passletter);
    $_SESSION['error'] = $error;
}

header('Location: index.php');

?>

index.php
<!DOCTYPE html>

<?php
session_start();
if(!empty($_SESSION["error"]))
{
    foreach($_SESSION["error"] as $error)
    {
        echo "
" . $error . "
";
    }
}
unset($_SESSION["error"]);
?>
<form method="post" action="register.php">
Name: <input type="text" name="name" value="<?php if(!empty($_post['name'])){echo $name;}?>">

Username: <input type="text" name="username" value="<?php if(!empty($_post['username'])){echo $username;}?>">

Email: <input type="text" name="email" value="<?php if(!empty($_post['email'])){echo $email;}?>">

Password: <input type="text" name="pass1" value="<?php if(!empty($_post['pass1'])){echo $pass1;}?>">

Password, again: <input type="text" name="pass2" value="<?php if(!empty($_post['pass2'])){echo $pass2;}?>">

<input type="submit" name="submit" value="submit">
</form>


text:
Q: Leverage Browser caching for static resources (only specific files) in asp.net Setting an expiry date or a maximum age for static resources programatically only for specific files (.css,.js,.png)
Any other way instead of altering web.config


text:
Q: I implemented card views in XML on Android Studios. How can I have this act as buttons? I'm new to Android and recently created a dashboard for my app. I followed a tutorial but it only covered the front end. I created a layout called content_main.xml with three Cardviews. Each of these Cardviews contains the code
android:clickable="true"

Beginning the back end of things, I created a java receiver class called DashboardActivity (as seen below). I want to make my Cardviews clickable so that when one is clicked, I am taken to another screen within my app. The other screens in my app I am trying to get to are fragments. Each of these screens has its own java class in my "Fragments" folder. One of them, of which I try calling on in the code that follows is called SettingsViewFragment().
So far, I have tried the following. It does nothing.
public class DashboardActivity  extends AppCompatActivity {

    CardView cd1, cd2, cd3;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.content_main);
        cd1 = (CardView) findViewById(R.id.dash_settings);
        cd2 = (CardView) findViewById(R.id.dash_profile);
        cd3 = (CardView) findViewById(R.id.dash_activity);

        cd1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Fragment fragment1 = new SettingsViewFragment();
            }

        });
    }
}

UPDATE: FULL CODE
public class DashboardActivity extends AppCompatActivity {

    CardView cd1, cd2, cd3;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.content_main);

        cd1 = findViewById(R.id.dash_settings);
        cd2 = findViewById(R.id.dash_profile);
        cd3 = findViewById(R.id.dash_activity);

        cd1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Log.i("Testing 123 123 123");
            }

        });

    }
}

And my XML: (it continues for 3 cards this way)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.example.newproject.DashboardActivity"
    tools:showIn="@layout/toolbar">

    <FrameLayout
        android:id="@+id/dashframe"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <LinearLayout
        android:clipToPadding="false"
        android:gravity="center"
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <android.support.v7.widget.CardView
            android:id="@+id/dash_settings"
            android:foreground="?android:attr/selectableItemBackground"
            android:clickable="true"
            android:focusable="true"
            android:layout_width="160dp"
            android:layout_height="190dp"
            android:layout_margin="10dp">
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical"
                android:gravity="center">
                <ImageView
                    android:layout_width="64dp"
                    android:layout_height="64dp"
                    android:background="@drawable/bg_circle1"
                    android:src="@drawable/ic_settingspicture"
                    android:padding="10dp"/>
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textStyle="bold"
                    android:layout_marginTop="10dp"
                    android:text="View your settings"/>
                <View
                    android:layout_width="match_parent"
                    android:layout_height="1dp"
                    android:background="@color/lightgray"
                    android:layout_margin="10dp"/>
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:gravity="center"
                    android:text="Follow along with guided tutorials"
                    android:padding="5dp"
                    android:textColor="@android:color/darker_gray"/>

            </LinearLayout>

A: Replace
Fragment fragment1 = new SettingsViewFragment();

With this
Fragment fragment1 = new SettingsViewFragment();
FragmentTransaction fragmentTransaction=getFragmentManager().beginTransaction();
                    fragmentTransaction.replace(R.id.Main_Layout,fragment1);
                    fragmentTransaction.addToBackStack(null);
                    fragmentTransaction.commit();

A: Change Fragment fragment1 = new SettingsViewFragment (); by Toast.makeText (mActivity, "onCLick", Toast.LENGTH_LONG) .show ();
//if show toast The problem is not the onClick, the problem is when loading the fragment

A: Fragments should be instantiated with the newInstance() static method.
cd1.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Fragment settingsFragment = SettingsFragment.newInstance();
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        fragmentTransaction.replace(R.id.contentView, settingsFragment);
        fragmentTransaction.commit();
    }

});

In the SettingsFragment
 public static SettingsFragment newInstance() {
            return new SettingsFragment();
 }

XML for content_main
LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical">

    <android.support.v7.widget.CardView
        android:id="@+id/dash_settings"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"

        ...

     </android.support.v7.widget.CardView>

        <android.support.v7.widget.CardView
        android:id="@+id/dash_profile"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"

        ...

        </android.support.v7.widget.CardView>

      <android.support.v7.widget.CardView
        android:id="@+id/dash_activity"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"

        ...

        </android.support.v7.widget.CardView>

    <FrameLayout
        android:id="@+id/contentView"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
    </FrameLayout>

</LinearLayout>

This will transact the fragment into the FrameLayout that is positioned below the CardViews. Now this is probably not ideal, you would most likely want to launch a new activity that will host the fragment but this should work. Unless this is already in some Activity that hosts the fragment. But the key code is in the onClick.


text:
Q: Passing functions between REACT components I am building a REACT app which will show some recommendations for various restaurants.
The main component has two handlers called
1. handleLiked
handleLiked = () => {
    console.log("in like");
}

*handleDisliked

handleDisliked = () => {
        console.log("in like");
    }

I pass the state and these two handlers from MainComponent.js to Listings.js
<Listings listings={this.state.listings} city={this.state.selectedCity} likedCounter={this.handleLiked} dislikedCounter={this.handleDisliked}/>

Listings.js is a functional component and I receive props.
if I console.log(props)
I can see the handlers.
From Listings.js I run a loop on the records in the state and pass the data to a child component called Listing.js. I have a for loop which generates the following call to the child component called Listing.
            return <Listing
            key={listing.key}
            listingTitle={listing.listingTitle}
            listingCity={listing.listingCity}
            listingBodyText={listing.listingBodyText}
            listingLikes={listing.likes}
            listingDislikes={listing.dislikes}
            listingLikesHandler={listing.likedCounter}
            listingDislikesHandler={listing.dislikedCounter}
            />

When I receive props in Listing.js, I can see all the properties such as city, bodytext etc. but the handlers become undefined. Can you please help me understand how to pass these to the Listing component in my example.


text:
Q: Forgot password emails not sending in Django I am trying to implement password reset functionality.
My urls contains:
url(r'^password_reset/$','django.contrib.auth.views.password_reset', {'template_name': 'resetpassword.html', 'post_reset_redirect' : '/password_reset/mailed/'},
name="password_reset"),

url(r'^password_reset/mailed/$',
'django.contrib.auth.views.password_reset_done',{'template_name': 'resetpassword_mailed.html'}),

url(r'^password_reset/(?P<uidb36>[0-9A-Za-z]{1,13})-(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$',
'django.contrib.auth.views.password_reset_confirm',
{'post_reset_redirect' : '/password_reset/complete/'}),

url(r'^password_reset/complete/$',
'django.contrib.auth.views.password_reset_complete',{'template_name': 'resetpassword_complete.html'}),

and settings.py:
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.mail.ru'
EMAIL_HOST_USER = 'noreply@mysite.com'
DEFAULT_FROM_EMAIL = 'noreply@mysite.com'
EMAIL_HOST_PASSWORD = 'password'
EMAIL_PORT = 587
EMAIL_USE_TLS = True

URL routing works just fine, however email are not being sent.
If I try to use Django shell and test sending:
email = EmailMessage('Subject', 'Body', to=['test@email.com'])
email.send()

And it works just fine as well.
How could I fix this? I don't get any error messages and don't know how could I debug this.
UPD
I have found out that in django/contrib/auth/views.py: password_reset method I always go to
else:
    post_reset_redirect = resolve_url(post_reset_redirect)

part and never to actually sending email. How's that?
if post_reset_redirect is None:
    post_reset_redirect = reverse('password_reset_done')
else:
    post_reset_redirect = resolve_url(post_reset_redirect)
if request.method == "POST":
    form = password_reset_form(request.POST)
    if form.is_valid():
        print 'reset form valid'
        opts = {
            'use_https': request.is_secure(),
            'token_generator': token_generator,
            'from_email': from_email,
            'email_template_name': email_template_name,
            'subject_template_name': subject_template_name,
            'request': request,
            'html_email_template_name': html_email_template_name,
        }
        if is_admin_site:
            opts = dict(opts, domain_override=request.get_host())
        form.save(**opts)
        return HttpResponseRedirect(post_reset_redirect)

A: If the user has no password (e.g. created with create_user()), the password reset won't send anything!  Make sure you create a password as well via:
password = User.objects.make_random_password()
Then, you also need to set the password and save, for example
user.set_password(password)
user.save()

A: Could be a trivial question but the user you are using to test has a valid email set? If it's empty will not send the email neither raise an exception.
Check the send method source code.
Other way to see if the email is being generated is use the console backend:
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'

and look at the console because the email should appears there.
Thanks


text:
Q: Map control -- popup is shown behind pin in UWP i created a sample UWP application with a map and bind ItemsSource to locations. When i click any location i need to show a TextBlock with clicked pin info, but the TextBlock is going behind the pins.
Can someone please look into this and let me know what i am doing wrong here please.
sample project can be downloaded from https://1drv.ms/u/s!AiRUJ-H3vDEwgYgbI3nhZ-lvU8EZKg?e=6qPu4C and screen shot is attached for reference.

A:
popup is shown behind pin in UWP

I'm afraid you can't  set the custom xaml  elements on top of map, because currently, it does not provide such zindex poperty. So for this scenario, we suggest place the TextBlock  in the MapItemsControl's DataTemplate, and give it left top value that to make sure the pin element will not covered.
<map:MapControl
    x:Name="myMap"
    HorizontalAlignment="Stretch"
    VerticalAlignment="Stretch">
    <map:MapItemsControl ItemsSource="{x:Bind ViewModel.Things}">
        <map:MapItemsControl.ItemTemplate>
            <DataTemplate>
                <Grid>
                    <Canvas map:MapControl.Location="{Binding Location}">
                        <Path
                            Margin="0"
                            Data="M14-32h-28v27h8l6 5 6-5h8z"
                            Fill="HotPink"
                            IsHitTestVisible="True"
                            Stroke="Black"
                            StrokeThickness="2">
                            <interactivity:Interaction.Behaviors>
                                <core:EventTriggerBehavior EventName="Tapped">
                                    <core:InvokeCommandAction Command="{Binding SelectMeCommand, Mode=OneWay}" />
                                </core:EventTriggerBehavior>
                            </interactivity:Interaction.Behaviors>
                        </Path>
                        <Grid
                            Canvas.Left="16"
                            Canvas.Top="-40"
                            Width="300"
                            Height="30"
                            Background="Blue"
                            Canvas.ZIndex="0"
                            Visibility="{Binding Avaiable}">
                            <TextBlock Text="{Binding Name, Mode=OneWay}" />
                        </Grid>
                    </Canvas>
                </Grid>
            </DataTemplate>
        </map:MapItemsControl.ItemTemplate>
    </map:MapItemsControl>
    <map:MapElementsLayer />

ViewModel
public class MainViewModel : BaseViewModel
{
    public MainViewModel()
    {
        Things = new ObservableCollection<Thing>
        {

            new Thing("Place One", 17.4947934, 78.3996441, SelectMe),
            new Thing("Place Two", 17.3616, 78.4747, SelectMe),
            new Thing("Place Three", 17.4375, 78.4482, SelectMe),
            new Thing("Place Four", 17.3930, 78.4730, SelectMe)
        };
    }

    public ObservableCollection<Thing> Things { get; }

    private Thing _selectedThing;

    public Thing SelectedThing { get => _selectedThing; private set => SetProperty(ref _selectedThing, value); }
    private Thing previousThing;
    private void SelectMe(Thing thing)
    {
        if (previousThing != null)
        {
            previousThing.Avaiable = false;
        }

        if (thing != null)
        {
            thing.Avaiable = true;
            previousThing = thing;
        }
    }
}

public class Thing : BaseViewModel
{
    public Thing(string name, double latitude, double longitude, Action<Thing> selector)
    {
        Name = name;
        Location = new Geopoint(new BasicGeoposition { Latitude = latitude, Longitude = longitude });
        SelectMeCommand = new RelayCommand(() => selector(this));
    }

    public string Name { get; set; }
    public Geopoint Location { get; set; }
    public ICommand SelectMeCommand { get; }
    private bool _avaiable;
    public bool Avaiable
    {
        get => _avaiable;

        set => SetProperty(ref _avaiable, value);

    }
}


text:
Q: How to make Visual Studio go into the #define during debugging? When i am debugging my code in visual studio and it goes to a #define like this :
#define DEC_CONSTRUCTOR(a,b) line 1 \
        line 2 \
        line 3

and code is
DEC_CONSTRUCTOR ( arg1, arg2 ) {     < - LINE X
... some things ...                  < - LINE Y

};

When i debug point reaches LINE X even for one step ahead it goes to LINE Y.
It would be great if i could make it go through line 1, 2 and 3 in anyway like doing something [ like some option ] and then recompiling.
Thanks in advance.

A: Unfortunately this is not possible. #define macros are handled by the preprocessor, so the compiler cannot generate debug info for it.


text:
Q: Creating an orthogonal basis given the polynomials $x^0,x^1,x^2$ Here is the question from my worksheet:

Consider the space of continuous functions on the interval $[-1,1]: $$\mathcal C^0([-1,1])$ The inner product on this space is defined as follows:
$$\langle f,g\rangle=\int_{-1}^{1} f(x)g(x)dx$$
Given the polynomials $p_0(x)=1, p_1(x)=x, p_2(x)=x^2$, use the Gram-Schmidt process find to the polynomals $P_0,P_1,P_2$ such that
$\langle P_i,P_j\rangle=0$ for $i \not=j$ and $P_i(1)=1$ for $i=0,1,2$. (You just have to find an orthogonal (not orthonormal) basis).

Here is what I have got so far:
$P_0=p_0=1$
$P_1=p_1(x)-\frac{\langle p_1(x),P_1\rangle}{\langle P_0,P_0\rangle}P_0=x-(\int_{-1}^1\tau d \tau)(\frac{1}{2})=x-0=x$
$P_2=p_2(x)-\frac{\langle p_2(x),P_0\rangle}{\langle P_0,P_0\rangle}P_0-\frac{\langle p_2(x),P_1\rangle}{\langle P_1,P_1\rangle}P_1=x^2-(\int_{-1}^1 \tau^2 d\tau) \frac{1}{2}-(\int_{-1}^1 \tau^3 d\tau )\frac{P_1}{\langle P_1,P_1\rangle}=x^2-\frac{1}{3}$
$$\boxed{P_0=1, P_1=x, P_2=x^2-\frac{1}{3}}$$
Now I can check the first property: $\langle P_i,P_j\rangle=0$ for $i\not=j$
$\langle P_0,P_1\rangle=\int_{-1}^1x dx=\frac{(1)^2}{2}-\frac{(-1)^2}{2}=0$
$\langle P_0,P_2\rangle=\int_{-1}^1 (x^2-\frac{1}{3})dx=(\frac{x^3}{3}-\frac{1}{3}x)_{x=-1}^{x=1}=(\frac{1}{3}-\frac{1}{3})-(-\frac{1}{3}--\frac{1}{3})=0$
$\langle P_1,P_2\rangle=\int_{-1}^1 (x^3)dx=(\frac{x^4}{4})_{x=-1}^{x=1}=\frac{1}{4}-\frac{1}{4}=0$
However the property $P_i(1)=1$ is not satisfied for every $i$ since:
$P_2(1)=\frac{2}{3}$
Is this a mistake in the question or am I doing something wrong here?

A: It is clearly mentioned that $P_i$'s need not have norm $1$. Multiply the polynomials you have found by constants $c_0,c_1,c_2$ so that the new polynomials have the value $1$ when $x=1$. The new ones are still orthogonal.


text:
Q: Como trazer informação de arquivos em uma pasta Olá
Tenho que fazer uma análise qualitativa de imagens que estão no meu site, tenho todos os arquivos em uma pasta e preciso trazer duas informações para o Excel:
Nome do arquivo e suas dimensões.

A: As duas dimensões vêm juntas (provavelmente há uma propriedade que as traga separadas), mas testei aqui com uma imagem .jpg e consegui. É necessário fazer referência à biblioteca Microsoft Shell Controls and Automations.
Function PegarDimensoes() as String

Dim sh As New Shell32.Shell
Dim arq As Shell32.FolderItem
Dim CaminhoPasta As String
Dim NomeArquivo As String

CaminhoPasta = "C:\Users\usuarioTal\Desktop\"
NomeArquivo = "gatos_sorriso.jpg"

Set arq = sh.Namespace(CaminhoPasta).Items.Item(NomeArquivo)
PegarDimensoes = arq.ExtendedProperty("dimensions")

End Sub