text:
Q: Effects while closing the Dialog box Am using Jquery Dialog box. In this I have Submit and Close buttons. I want to put UI effects like here for the Close button.
My Dialog box code is below,
$(document).ready(function() {
    $("#disableDivForm").dialog({
        autoOpen: true,
        position: 'center',
        height: 187,
        width: 472,
        modal: true,
        show: {
            effect: 'explode',
            duration: 400
        }
    });
    $('#body').show();
});

There is a Close button inside disableDivForm. Code is below,

    <input type="submit" id="cancelID" value="Close" onClick="return cancel()" class="but-bl2"/>

function cancel()
{
    document.disableForm.action=" - myAction goes here - ";
    document.disableForm.method="POST";
    document.disableForm.submit();
}

I tried below code for achieving effects.
$(document).ready(function(){
    $("#cancelID").click(function(){
       hide: {effect: 'explode', duration: 400}
    });
});

But, its not working. My Dialog box itself is not opening. No Java Script errors. I have placed code for .click function inside

A: check this fiddle out jsfiddle , might be what you want. you can add hide effect in during initializing of dialog box
  $("#disableDivForm").dialog({
    autoOpen: true,
    position: 'center',
    height: 187,
    width: 472,
    modal: true,
    show: {
        effect: 'explode',
        duration: 400
    },
    hide: {
        effect: 'explode',
        duration: 400
    }
});


text:
Q: Paint textures on object in Unity I am working on a game and I have made my own models in blender. I have made a ground plane in blender but I had some issues when trying to get the texture in to unity and since it is a simple texture I figured I could just paint it in unity. So basically what I want to do is paint on a grass texture on the model and then paint some paths using a sand soil texture. How do I do this?

A: I used InkPainter for a project, but it's create a texture in runTime and paint it with a brush texture passed in component with the color passed in component IDE too. It's very useful and had a way to save the texture in a bitmap file (or png or jpg), but when i install this in my project I've some problems like the component not painting some object that doesn't have the shader informed in the tool. I do a upgrade to work with default shader but I need to push it yet.
I found others tools but lots of then are payed.
blog of the creator of InkPainter

redpajama_set_name: RedPajamaStackExchange


text:
Q: Config WebRTC android for the lowest latency How to config WebRTC for the lowest latency for streaming live video only one side from Android phone camera to PC via WebRTC app on android to Firefox PC?
the quality maybe 15-24 fps and maybe 640 x 480?
My app need to live streaming video in android phone and transporting it as real time as possible to the PC to view in Firefox PC (using P2P protocol). That app looks like control some robot, play live streaming video game.
How do I do it for the best expected? Maybe it can do with 50 ms latency with 3G/4G network?
Thank you.

A:
Maybe it can do with 50 ms latency with 3G/4G network? Thank you.

Impossible.  You can't send a single packet with that little amount of latency over a mobile network, let alone capture video, encode video, mux video with audio, send it, receive it, buffer it, demux it, decode it, present it.  50ms latency per frame is not a whole lot higher than what you get with analog transmission!
You'll find that even many cameras on phones are going to have that much lag by the time the system gets the data to even work with it.
You realize it can take ~200ms for a human to even react to visual stimulus anyway?  My TV takes at least 150ms to display a frame from its lossless HDMI input.
Your project requirements are completely out of touch with reality.  You should also take time to gain an understanding of the tradeoffs that occur when you push digital video down into the extreme ends of low latency.  You're about to make some real sacrifices by going under 1s or 500ms or so.  Consider reading my post here:  https://stackoverflow.com/a/37475943/362536  Particularly the "why not [magic technology here]" section.


text:
Q: GEt data from array object Hi i'm new to PHP and have below problem. i have written below codes to add data in to the array, now i need to see the added data, please tell me how to do it.
class ShoppingCart
{
private $items = array();
private $n_items = 0;
function addItem( Item $item )
{
 $this->items[] = $item;
$this->n_items = $this->n_items + 1;
//print_r (array_values($this->items));
echo "item $this->items added sussesfully";
}
}

and
class Item {
protected $name;
protected $price;

public function __construct($name, $price) {
    $this->name = $name;
    $this->price = $price;
}

public function getName() {
    echo "item is $this->name";
    return $this->name;
}

public function getPrice() {
    return $this->price;
}

}

and
require_once('AddingMachine.php');
require_once('item.php');

//$arrayofnumbers = array(100,200);

$objectname = new ShoppingCart();
$objectname->addItem(new Item('My Super Cool Toy', 10.99));

Thanks

A: Since $items is a private property you will need to create a new method on the ShoppingCart class
public function getItems()
{
    return $this->items;
}

And then retrieve the $items array by calling the new method
$objectname = new ShoppingCart();
$items = $objectname->getItems();

var_dump($items);


text:
Q: Why does authorization fail when I commit to svn using VisualSVN? I have setup svnserve and for now now I am testing a repository with no credentials, so in svnserve.config I have
[general]
# anon-access = write
### auth-access = write

# use-sasl = false

And restarted the service
I have successfully got a working copy of a project on a seperate machine using VisualSVN and svn://server/repos however when I commit using VisualSVN I get authorization failed
Any ideas?

A: Uncomment the anon-access = write line; the default is read-only.


text:
Q: What are the best stats you can roll/reroll for each class? What are the best stats you can roll/re-roll for each class?  I know the basics, which stats are primary and secondary, but what's the whole picture?
Class       Primary  Secondary
Augurer     WIS      LCK
Barbarian   STR      CON
Bladesinger DEX      STR
Cleric      WIS      INT
Druid       WIS      CON
Fathomer    DEX      INT
Mage        INT      WIS
Nephandi    INT      DEX
Paladin     STR      WIS
Ranger      STR      WIS
Thief       DEX      CHA
Vampire     DEX      INT
Warrior     STR      DEX

A: Each new character's stats add to a total of 95 between the 9 statistics and range between 9-18 base.
The prevailing opinion is there are certain stats that every class will want to max out, namely strength, dexterity and luck.  Strength affects how much you can carry and dexterity affects things like quaffing potions.  Luck is vague but it's affects things like container scrapping versus breath attacks, saving throws in general, disarm, charm and many other things, according to the SMAUG 1.8 source code.
Here are some suggestions with the notation that stats are easy to get if you play devout and harder when you switch to evil.
Class       Suggestion based on mid range avatar gear
Augurer     16 str, 15 WIS, 16 dex, 16 LCK
Barbarian   18 STR, 18 dex, 16 CON
Bladesinger 18 STR, 18 DEX, 15 lck
Cleric      14 str, 14 WIS, 14 INT, 16 dex
Druid       14 str, 14 int, 18 WIS, 13 dex, 18 CON
Fathomer    16 str, 18 DEX, 16 INT
Mage        13 str, 17 INT, 17 WIS, 13 dex
Nephandi    14 str, 18 INT, 18 DEX
Paladin     18 STR, 16 WIS, 15 dex (can only be good aligned, lower strs are ok)
Ranger      18 STR, 15 dex, 16 WIS
Thief       18 str, 18 DEX, 15 lck
Vampire     18 str, 18 DEX, 16 INT (if neutral)
            16 str, 18 DEX, 18 INT (if evil)
Warrior     18 STR, 16 DEX, 15 con

This is based on some experience with rerolling and some assumptions.  It's hard to guess what's ideal in every situation in a game so open ended, someone may use a cleric in a very different way than I would and may need different gear to make a different build work.
Additionally I wouldn't want to hand roll any of these combinations, a script is highly advised.  Some of these combos are exceptionally hard for certain races.  In general a "hard" combination is something that when running 8 scripted characters all rerolling takes longer than 1-2 days to roll.


text:
Q: Profiling complex ant build scripts: How to find bottlenecks? My goal is to decrease the build times of our system. We are using Ant, and the build system built on top of it is quite complex.
To find bottlenecks, it would be great to display the elapsed times of the most expensive tasks. Do you know of a wrapper for Ant that is capable of doing that? Something like a profiler for Ant tasks.
For those, who a familiar with Grunt: I'm looking for a tool like time-grunt.

(At the moment, my strategy is to look at time-stamped console outputs to get an idea of the bottlenecks.)


text:
Q: search form not displaying correct result I am new to creating a search form, below is my code for the search form:

Search

 <form name="search" method="post" action="search_result2.php">
 Search for: <input type="text" name="find" /> in
 <Select NAME="field">
 <Option VALUE="testA">A</option>
 <Option VALUE="testB">B</option>
 <Option VALUE="testC">C</option>
 <Option VALUE="testD">D</option>
 </Select>
 <input type="hidden" name="searching" value="yes" />
 <input type="submit" name="search" value="Search" />
 </form>

UPDATED: search_result2.php:
<?php
 //This is only displayed if they have submitted the form
if (isset($_POST['searching']) && $_POST['searching'] == "yes")
{
echo "
Results

";
//If they did not enter a search term we give them an error
if (empty($_POST['find']))
{
echo "
You forgot to enter a search term";
exit;
}

 // Otherwise we connect to our Database
 mysql_connect("host", "username", "passw") or die(mysql_error());
 mysql_select_db("testdb") or die(mysql_error());

 // We preform a bit of filtering
 $find = strtoupper($_POST['find']);
 $find = strip_tags($_POST['find']);
 $find = trim ($_POST['find']);
 $field = trim ($_POST['field'])

 //Now we search for our search term, in the field the user specified
 $data = mysql_query("SELECT * FROM testtable WHERE upper($field) LIKE'%$find%'");

 //And we display the results
 while($result = mysql_fetch_array( $data ))
 {
 echo $result['testA'];
 echo " ";
 echo $result['testB'];
 echo "
";
 echo $result['testC'];
 echo "
";
 echo $result['testD'];
 echo "
";
 echo "
";
 }

 //This counts the number or results - and if there wasn't any it gives them a little message explaining that
 $anymatches=mysql_num_rows($data);
 if ($anymatches == 0)
 {
 echo "Sorry, but we can not find an entry to match your query

";
 }

 //And we remind them what they searched for
 echo "Searched For: " .$find;
 }
 ?>

==========================
now what is happening is whether I put in a search string or not it will display the following messages, which is exactly my code for the search result,
Results:

    "; //If they did not enter a search term we give them an error if ($find == "") { echo "

    You forgot to enter a search term";
    exit;
    } // Otherwise we connect to our Database
    mysql_connect("host", "username", "passw") or die(mysql_error());
    mysql_select_db("testdb") or die(mysql_error());
    // We preform a bit of filtering $find = strtoupper($find);
    $find = strip_tags($find);
    $find = trim ($find);
    //Now we search for our search term, in the field the user specified
    $data = mysql_query("SELECT * FROM testtable WHERE upper($field) LIKE'%$find%'");
    //And we display the results
    while($result = mysql_fetch_array( $data )) {
        echo $result['testA'];
        echo " ";
        echo $result['testB'];
        echo "    ";
        echo $result['testC'];
        echo "    ";
        echo $result['testD'];
        echo "    ";
        echo "  ";
    } //This counts the number or results - and if there wasn't any it gives them a little message explaining that $anymatches=mysql_num_rows($data); if ($anymatches == 0) { echo "Sorry, but we can not find an entry to match your query

    "; } //And we remind them what they searched for echo "Searched For: " .$find; } ?>

A: Indeed use  <?phpinstead of <?
few other recommendations
if (isset($_POST['searching']) && $_POST['searching'] == "yes")
{
echo "
Results

";

//If they did not enter a search term we give them an error
if (empty($_POST['find']))
{
echo "
You forgot to enter a search term";
exit;
}

also suggest you strip tags on $field

A: don't use <? insted of use <?php short_open_tag can be disabled at server.


text:
Q: Playing a movie while it is still downloading I don't like downloading movies before playing them. I usually decide to play a movie and I want to see it immediately.
What is the best way to do it?
I need to do it on both Ubuntu and Windows 7. In windows one of the problem is that firefox stores partially downloaded file with to file with .part extension which is later renamed. This problem can be overcome by using Opera browser which stores partially downloaded file right way from the beginning and it doesn't rename it later.
Second problem is choosing right movie player program. I usually used KMplayer which asked me some question about when to make index and I had to click "Play now and build index later" button or something like that. And that worked perfectly and I could watch movie. This stopped working for me. I guess some update removed this feature. The movie stops playing when reaching the time to which it was downloaded when I had stared playing it. This way I am interupted several times during watching the movie which is still downloading although smart movie player could realize that during playing was another part of the video downloaded.
On the ubuntu machine I don't have any problems with file extension and I can double click file which is named with .part extension and any movie player I have knows that it is video. But the problem with the sensless interupting me during playing remains.
How do you do it?

A: In VLC, you can add the URL of the movie directly and VLC will take care of the downloading. This is really nice if you have an http link because you can seek through the file.

A: VLC is able to play even partially downloaded files - just open the .part file using VLC and possibly other players. Seeking might be problematic / not precise (mkv) or impossible (avi)

A: You can use wget command in ubuntu terminal. You can play video while downloading it.
https://www.computerhope.com/unix/wget.htm


text:
Q: Customising virtuemart cart I would like to customise the add to cart and actual checkout processes of the latest version virtuemart and Joomla 2.5.
The first thing i want to do is to change it so that when a product is added to the cart, instead of the JS popup box i want it to redirect straight the the first stage of the checkout.
Then i want to split the checkout into 4 pages starting with the user entering their details, then viewing the cart, payment and confirmation of the order.
I'm not expecting step by step instructions, just pointing the right direction.
Thanks.

A: You Can work like this,
First of all you need to redirect the add to cart  to another page.then go to admin configuration.
VM->configuration->checkout->Display modal popup upon 'Add to cart'  uncheck this.
then you will get first page (step of cart) ie, default_pricelist.php for VM2 and above.
Next step you can achieve with cart controller cart.php.
This step is involving selection of billing and shipping address you can find the files under view/users/ two functions in controller select BT and ST.
Also here you can define new steps by creating layout under cart view and use the cart controller.
The final step including the layout order_done.php
Best of luck.


text:
Q: JSP giving NullPointerException for request.getParameter() I'm new to jsp and am creating a webpage that has a form with a select box and a few other input boxes.
I'm populating these input boxes automatically with values from properties file:
NumConfig.properties
SELECT= , ,
ONE=1,I,FIRST
TWO=2,II,SECOND
THREE=3,III,THIRD

Here is my form:

  <form name="NumDetail" id="NumDetail" method="post">

          Select
            <select id="SelectText" name="SelectText" onchange="this.form.submit()">
              <option value="ONE">ONE</option>
              <option value="TWO">TWO</option>
              <option value="THREE">THREE</option>
            </select>

          Number
          Roman
          Position

            <input type="text" size=10 id="number">

            <input type="text" id="roman">

            <input type="text" id="position">

  </form>

And this is the JS code I'm using to load values from properties file:
< script type = "text/javascript" >
  <%
  ResourceBundle resource = ResourceBundle.getBundle("NumConfig");
String dbname;
if (request.getParameter("SelectText") == null)
  dbname = "SELECT";
dbname = request.getParameter("SelectText");
String[] num = resource.getString(dbname).split(","); %>
var number = "<%= num[0]%>";
var rom = "<%= num[1]%>";
var pos = "<%= num[2]%>";

document.getElementById("number").value = number;
document.getElementById("roman").value = rom;
document.getElementById("position").value = pos; < /script>

I can indirectly open this page by appending ?SelectText value in the URL.
But when opening this page directly I get NullPointerException at the line
String[] num = resource.getString(dbname).split(",");

Two Questions:

*

*How do I perform a null check or give the request parameter a default value so that page does not error out?

*Once I select a value from the dropdown and the form submits, the select box does not retain its value and goes back to the default. How to resolve this?

A: You just need an else statement
if (request.getParameter("SelectText") == null)
    dbname = "SELECT";
else
    dbname = request.getParameter("SelectText");

To make an option selected by default, you should try this selected="selected". Stock the value somewhere and change your selected option dynamically.
<option value="ONE" selected="selected">ONE</option>

A: Firstly my recommendation would be not to mix Java code within HTML code in a JSP page. Try using a Java Servlet to manage your request and respose so you don't end up having a messy code.
I'll answer your questions below:

*

*You are checking whether the parameter "SelectText" is null, and if that's the case then giving to 'dbname' a default value but the next instruction is replacing this given value with null.

The code should look like this:
String dbname = "SELECT";
String requestValue = request.getParameter("SelectText");

if (requestValue != null) {
    dbname = requestValue;
}

*Have you tried replacing your form request method with GET instead of POST?


text:
Q: Name of the optimization model based on variable type If the variable is binary 1,0  the model name is a binary integer optimization model
If the variable is any integer, the model name is integer optimization model
What if the variable is any integer that belongs to a set of values (ex, x belongs to {a1,a2,a3,a4,a5...an})?
What would be the name of this model?
Do you think "discrete optimizing model" is the correct name?
or is it still an integer optimization model (however, the integers are restricted to a set of given values)?

A: You could call it discrete optimization, as in the tag I just added to your question.  Such restrictions can be modeled with binary variables, as shown in https://or.stackexchange.com/questions/6545/how-to-linearize-membership-in-a-finite-set.


text:
Q: Looking for sequence of strings through multiple files in directory using R I am writing an R program that reads through CSV files in my directory, searches for strings of characters that I have stored in a vector called parentVector, and writes the corresponding row to an output CSV file called df.csv. This is what I have so far:
setwd("my_directory")

# variable for csv directory
csvFolder <- "csv_directory"

flist <- list.files(path = csvFolder)
masterCorpus <- data.frame()

# This vector gives you the full file list in your directory
allFilesInDirectory <- list.files(csvFolder, full=TRUE)

# This vector will read the data from allFilesInDirectory vector
allTheData <- lapply(allFilesInDirectory, read.csv, header=TRUE)

parentVector <- c("Mother","mother", "Father","father","Adult","adult","MOT","FAT")

How do I finish the component of this program to be able to read through each CSV file in my directory and searches for the strings contained in the parentVector?

A: This can be done very quickly using the stringr package
Once you have the csv read into a data frame, you can test whether a row contains any of the strings in the parentVector character vector by creating a regex for each of those elements separated by "|" the OR regex operator.  You can do this quickly with paste0, shown below.  Then use that as the regex you pass as the pattern argument to stringr's str_detect.  So if you have a csv read into a variable called df, it would look like:
library(stringr)
library(dplyr)

parent_vector_pattern <- paste0(parentVector, collapse="|")

filtered_df <- df %>%
    mutate(contains_pattern = str_detect(COLUMN_WITH_TEXT_NAME_HERE, parent_vector_pattern) %>%
    filter(contains_pattern)

Please note that the mutate, filter, and %>% are apart of the dplyr package.


text:
Q: Simulating event system using pandas I would like to simulate a system comprising:

*

*one emitter that produces n events randomly spaced within [0, 1000) ms

*one consumer that samples the event stream uniformly spaced at intervals of f ms

*one consumer that samples the event stream uniformly spaced at intervals of g ms

For example, with f sampling at 5ms and g sampling at 10ms, the sequence might look like:

*

*0ms: f samples, g samples

*5ms: f samples

*10ms: f samples, g samples

*12ms: event arrives

*13ms: event arrives

*15ms: f samples

*20ms: f samples, g samples

*25ms f samples

*27ms: event arrives

*30ms f samples, g samples

*35ms f samples

*37ms: event arrives
For each emission, the consumer which samples closest to (but after) the event time "wins". In the event of a tie the winner should be chosen randomly. For example f's sample at 15ms wins both the 12ms and the 13ms event.
I've attempted to implement this by merging the timelines onto one index:
import numpy as np
import pandas as pd

f = np.arange(0, 40, 5)
g = np.arange(0, 40, 10)
events = [12, 13, 27, 37]

df = pd.concat([pd.Series(f, f), pd.Series(g, g), pd.Series(events, events)], axis=1)

Which yields a DataFrame like this:
     f   g  events
0    0   0     NaN
5    5 NaN     NaN
10  10  10     NaN
12 NaN NaN      12
13 NaN NaN      13
15  15 NaN     NaN
20  20  20     NaN
25  25 NaN     NaN
27 NaN NaN      27
30  30  30     NaN
35  35 NaN     NaN
37 NaN NaN      37

I've been noodling around trying to find the winners with various operations against the following roll-up:
In [103]: pd.expanding_max(df)
     f   g  events
0    0   0     NaN
5    5   0     NaN
10  10  10     NaN
12  10  10      12
13  10  10      13
15  15  10      13
20  20  20      13
25  25  20      13
27  25  20      27
30  30  30      27
35  35  30      27
37  35  30      37

...but have been having a hard time finding a pandas-ish way to do it.
I feel pretty close with the following:
In [141]: x = pd.expanding_min(df.sort(ascending=False))
          gx = x.groupby('events')
          print gx.max()
events
12      15  20
13      15  20
27      30  30
37      35  30

Any ideas?

A: Use bfill to fill NaN's backward in "f" & "g" columns:
import numpy as np
import pandas as pd

f = np.arange(0, 40, 5)
g = np.arange(0, 40, 10)
events = [12, 13, 27, 37]

df = pd.concat([pd.Series(f, f), pd.Series(g, g), pd.Series(events, events)], axis=1)
df.columns = "f", "g", "event"
df[["f", "g"]] = df[["f", "g"]].bfill()
df2 = df.dropna()
print df2

here is the output:
     f   g  event
12  15  20     12
13  15  20     13
27  30  30     27

Then we can compare f & g:
print np.sign(df2.f - df2.g).replace({-1:"f", 1:"g", 0:"fg"})

the output is:
12     f
13     f
27    fg
dtype: object

This means the events at 12 & 13 is taken by "f", and event at 27 should be chosen randomly.


text:
Q: Limit number of foreign keys Let's take this example:
class Team (models.Model):
    name = models.CharField('Name', max_length=30)

class Round (models.Model):
    round_number = models.IntegerField('Round', editable=False) #Auto-incrementing per Team
    team = models.ForeignKey(Team)

There is a limit of 3 rounds. How can I raise an error inside the Admin and generally prevent a team from having more than 3 Rounds?

A: Normally you need to override the form:
class RoundAdminForm(forms.ModelForm):
    def clean_team(self):
        team = self.cleaned_data['team']
        if team.round_set.exclude(pk=self.instance.pk).count() == 3:
            raise ValidationError('Max three rounds allowed!')
        return team

class RoundAdmin(admin.ModelAdmin):
    form = RoundAdminForm

If Round is inline-edited in the change form page of Team, you could limit the max_num of RoundInline.

A: I liked the way using the validator:
def restrict_amount(value):
    if Round.objects.filter(team_id=value).count() >= 3:
        raise ValidationError('Team already has maximal amount of rounds (3)')

class Team (models.Model):
    name = models.CharField('Name', max_length=30)

class Round (models.Model):
    round_number = models.IntegerField('Round', editable=False) #Auto-incrementing per Team
    team = models.ForeignKey(Team, validators=(restrict_amount, ))

Using validator will make Django handle it properly, for example, display an error in the admin panel.

A: The best way to to do this is by overriding the save() method which will through an error if your conditions are not met. One limit this from front end and overriding save() method will be for back end validations only.


text:
Q: Check for Cookie, if it does not exist run script I'm struggling with the use of Cookies on a html page. I would like to have a script check to see if a user has a cookie, if not call this script to open a model window
<script type="text/javascript">
jQuery(document).ready(function() {
  jQuery("#myModal").reveal();
});
</script

The window contains "Yes" and "No" buttons, if you user selects "Yes" it will save a cookie so the modal doesn't open on future visits to that page, if the user selects "No" it will simply direct them to another page.

A: 1) Use the jQuery cookie library for ease of use. https://github.com/carhartl/jquery-cookie
2) Check if cookie exists and handle accordingly
if ($j.cookie("NameOfYourCookie") == null) {
//Do stuff if cookie doesn't exist like set a cookie with a value of 1
$j.cookie("NameOfYourCookie", 1, {expires: 10, path:'/'});
}

else {
//They have a cookie so do something
alert ('You have a cookie with name NameOfYourCookie');
}

* EDIT *
Thought I might edit my answer to be more appropriate to your question.
        <button class="yes">YES</button>
        <button class="no">No</button>

     var $j = jQuery.noConflict();

$j(document).ready(function(){
//Show modal on page load
$j("#myModal").show();

$j('.yes').click(function(){
        $j("#myModal").hide();
        $j.cookie("YesButtonCookie", 1, {expires: 10, path:'/'});
        alert ('You have clicked yes, a cookie has been dropped');

  });

        if ($j.cookie("YesButtonCookie") == 1){
            // Don't show the div
            $j("#myModal").hide();
            alert ('Cookie found, you cant see myModal');
        }

        if ($j.cookie("YesButtonCookie") == null){
                    // Cookie Not Found
                    alert ('Cookie Not found, you can see myModal');
                    $j("#myModal").show();
        }

    $j('.clearcookie').click(function(){
        $j.cookie("YesButtonCookie", null);
        alert('Cookie Cleared');
    });

});

JSFIDDLE TO TEST


text:
Q: OnMouseOver doesn't work in Safari http://localboyoutfitters.com
Works fine in Chrome/Firefox/IE but only the third hover image works in Safari.
Here is my code for one of the images.. (my tab button is broke so sorry for bad formatting)
(i have a bracket on the a href below but bc of my keyboard limitations I had to take it away)

This is placed in a Wordpress widget area.
If anyone has any solutions it would be greatly appreciated!

A: Better would be to use mouseenter and mouseleave:

A: You can do that easily in Jquery, some javascript codes wont work with other browsers you can check jquery,you have to create a function. You have to add this code:


text:
Q: Subscribe to facebook page feed real time updates I'm writing a facebook app in Scala and Play!. I want real time updates for user feed and feed of pages this user administers, so I subscribed to those. This is what comes back from GET /{my_app_id}/subscriptions:
{
  "data": [
  {
    "object": "user",
    "callback_url": "***",
    "fields": [
      "feed"
    ],
    "active": true
  },
  {
    "object": "page",
    "callback_url": "***",
    "fields": [
      "feed"
    ],
    "active": true
  }
  ]
}

My server receives updates about the feed of the user that uses my app (including when he posts on his page's wall as himself), but no updates about posts made by the page he administers. The application is granted read_stream, user_status and manage_pages permissions. The question is can I get page feed updates without having the user add my app as a tab to his page? My app is not meant to be used as a tab app.
Short survey to show I actually did my homework:
here the support engineer says it is possible, although it is unclear how to "use a Page Access Token tied to the both the Page and app when creating the subscription".
On the other hand, here CBroe says one has to add app as a tab. Here Caroline suggests to create a tab and delete it immediately, which looks ugly. I tried to add my app as a tab without prompting the user, like this, with the Graph API Explorer and got "Application does not have permission for this action".

A: The truth lies in the middle: one has to make a POST to https://graph.facebook.com/pageId/tabs?app_id=appId&access_token=page_access_token to get real time updates for the page, but this does not seem to add an app as a tab, the app just shows up among added apps in page settings. I did the POST through Graph API explorer to debug my update processing code, and the updates get to the server OK.


text:
Q: Using Inner Actions in Enterprise Architect V11 I am new here and would be grateful If anybody helps me. recently I have been working on state machine diagrams and UML language in general. I have been using Enterprise Architect (EA) V11 for drawing some state machine diagrams like drawing states, triggers, guards and events. It is known that there are two types of triggers 1. transition triggers that cause a transition from a state to another 2. inner triggers that doesn't cause a transition. EA supports only three types of inner triggers ( Entry, Exit, Do ) because of this I can't put in my own inner triggers as an example if enter button is pressed turn on a device. Another thing that I can't write commands that are going to be executed inside the state.
So I have two questions 1. How to name my own inner triggers? 2. how to write commands inside a state?
Any help please...

A: I have found the solution. To create an inner trigger for a state, a self transition will do the trick. Create a transition connector issuing from and terminating in the state element and then modify its properties to be of kind internal. Then commands can be added by editing the Effect textbox.


text:
Q: Replacing one line of code due to php 7 with a (shell) script So with PHP 7.0 came some issues. Most notably w3 totalcaching is now causing an error that is spamming my httpd error logs.
Tue May 17 04:11:50.865647 2016] [proxy_fcgi:error] [pid 2554:tid 139695893694208] [client 195.154.181.168:59106] AH01071: Got error 'PHP message: PHP Warning:  Parameter 1 to W3_Plugin_TotalCache::ob_callback() expected to be a reference, value given in /home/x/domains/x/public_html/wp-includes/functions.php on line 3464\n', referer: http://www.googlebot.com/bot.html

The fix is rather easy https://github.com/gadelkareem/wp-w3-total-cache/commit/e71030e89f4cd666742ae2ec39451782beb42f3a, but I have to do this for about 12 sites. And possibly again when the plugin is updated.
The file is always here (* is variable user and domain related folder):
/home/*/domains/*/public_html/wp-content/plugins/w3-total-cache/lib/W3/Plugin/TotalCache.php

Is there a way I can safely script this?

A: On github, user pratham2003 has the same problem as you and propose the following sed command to apply the patch:
sed -i.bak 's/function ob_callback(&/function ob_callback(/g' /path/to/public_html/wp-content/plugins/w3-total-cache/lib/W3/Plugin/TotalCache.php

The -i.bak option can be skip to prevent a backup file from being created.
You can then apply the patch locally and write a script that update the file on each of your servers or ssh on each server and apply the sed command on each server.
You can also maintain a forked plugin and install from this plugin.
But the best will be that the upstream maintainer do himself the modification.


text:
Q: JSON or XML either way I need to format a JS array from a URL I'm using the JQuery Autocomplete plugin and I need some help formatting data available to me. I have a url that can output data in XML or JSON:
JSON example:
[{"location":{"address":"Dortha Pike","city":"Emmerichburgh","created_at":"2011-05-19T00:03:20Z","id":3,"name":"Caroline Fahey DDS","state":"Illinois","updated_at":"2011-05-19T00:03:20Z","zip":"80822-2018"}}

XML example:
<locations type="array">
<location>
<address>Dortha Pike</address>
<city>Emmerichburgh</city>
<created-at type="datetime">2011-05-19T00:03:20Z</created-at>
<id type="integer">3</id>
<name>Caroline Fahey DDS</name>
<state>Illinois</state>
<updated-at type="datetime">2011-05-19T00:03:20Z</updated-at>
<zip>80822-2018</zip>
</location>

The function below accepts data in a JS array. My problem is I need to take either of the above data and format it like you see var data is below:
$(document).ready(function(){
    var data = "Core Selectors Attributes Traversing Manipulation CSS Events Effects Ajax Utilities".split(" ");
$("#example").autocomplete(data);
  });

A: If your using the autocomplete I think your using, the string seperated by spaces is only one format... you can use JSON as long as you have particular names for the variables.
$item =  $item . "{ \"id\": \"$id\", \"label\": \"$name\"},";

So in your case you have to pick a field, like name, and parse all the names into a string like:
   [
    {
        "id": 1,
        "label": "Caroline Fahey DDS"
    },
    {
        "id": "2",
        "label": "Another Name"
    }
   ]

Can certainly help you with that, just check that string works first as it might be a different plugin.
EDIT: Provided example
the php/ajax response
<?php
$q = getGET("term");
if($q != "")
{
  $q = fquery_sanitize($q);
  $sql = "select ManufacturerID, ManufacturerName from sds_manufacturer ".
         " where ManufacturerName LIKE '%$q%' ".
         " order by ManufacturerName";
  $result = fquery_db($sql);
  $item= "";
  while($row=mysql_fetch_assoc($result))
  {
    $id = $row["ManufacturerID"];
    $name = $row["ManufacturerName"];
    $item =  $item . "{ \"id\": \"$id\", \"label\": \"$name\"},";
  }
  echo "[";
  echo trim($item, ",");
  echo "]";
}

?>

The autocomplete
$('.manufacturer-form .name').autocomplete({
          source: "/portal/inc/prod_manage/man-list-json.php",
            minLength: 3,
            select: function( event, ui ) {
                     manufacturer_select(ui.item.id);
          }


text:
Q: Quicksand jumping in transition when filtering a portfolio I updated my site to wordpress 3.8 and along with that came a weird jump when filtering the portfolio. inspecting this with chrome, it is very hard to see what exactly is going on. margins, padding, etc. are not being changed nor are elements being inserted. Other than this the effect/transition functions fine, and display correctly before and after the transition.
you can visit the page here to see the effect.FYI I already took a look at this link and this isn't the issue.
Thank you in advance.
EDIT:
This only seems to be happening in Chrome

A: just add overflow:hidden to li


text:
Q: Jmeter freezes with a CPU of 100% I have been working on some test cases using jmeter.  For the past month its been working fine but now when I run a test (even old previously used one's which worked).   The GUI freezes and the CPU is 100%.  I have not changed anything different so I am really stumped as to what has happened.  I suspect a log file or temp file is full but I do not know of any?  Can someone help

A: Don't use GUI for running load tests. JMeter GUI is designed for tests development and debugging only. Run your test in command-line non-GUI mode like
jmeter -n -t /path/to/testplan.jmx -l /path/to/results.jtl

Once test run is complete you can launch JMeter GUI and open results.jtl with the listener of your choice.
Other things to consider:

*

*use latest versions of JMeter, Java and JMeter Plugins

*increase Java Heap space allocated to JMeter. Default is 512MB which is not enough for running an immense load test

*disable all the listeners during test run

*use pre/post processors and assertions only where required

See 9 Easy Solutions for a JMeter Load Test "Out of Memory" Failure for detailed information on above and few more JMeter tips and tweaks.


text:
Q: Strange css priority behavior for font-family in Chrome I need to customize styles for my menu. In IE, it works fine, but in Chrome, I find I cannot modify the font-family for links in the menu. For text in span or div, it's OK. I use simple selector to make my rule prior to default rule. But the development tool shows like this:

You can see that my rule doesn't override the default rule. I tried to add important, development tool shows OK as below, but the font doesn't change at all:

The only thing I tried to make my rule work is to delete the original CSS rule ".tundra .dijitMenuItem" in "Menu.css". But it is the default rule given by framework, I don't want to modify it.
The element in dom is shown below:

How can this happen, and how to make my rule work?
Updated: I tried many ways to test the behaviors. Seems like if only I put my rule to .dijitMenuItem or it's children, it can override the default. Otherwise, no matter how specific my selector is, it won't be applied. I made a simple example like below: the complete example is on JsFiddle:
.theme .sub-container
{
  font-family: Arial;
}

body.theme div.container
{
    font-family: sans-serif; //this doesn't work
}

.theme .sub-container2
{
    font-family: sans-serif;
}
body.theme div.sub-container2
{
    font-family: Arial; //this works
}

Can anyone explain this? Does font-family's inherit and overridden are different with other CSS properties?

A: try to Set the font family in your anchor tag. i think it should be work.


text:
Q: Accessing json object in vb.net after converting from XML I convert XML to JSON like so:
Dim doc As XmlDocument
doc.LoadXml(arg_strXml)
Dim jsonObject As String = JsonConvert.SerializeXmlNode(doc)

Now I would like to be able to go into jsonObject to get values, like so
Dim mode As String = jsobObject.mode

Or more advanced example
Dim usersFirstName As String = jsonObject.people[1].firstname

Do I need to create a class which represents the XML structure or can I do it another way, even if I lose the intellisense, like so
Dim mode As String = jsonObject["mode"]

A: Seems like you first conversion was unnecessary,
you can access all values you need from xml with LINQ to XML and feature of vb.net XML Literals
Dim xmlString as String = "
<someobject>
    <property1>Value 1</property1>
    <property2>1001</property2>
</someobject>"

Dim xmlObject As XElement = XElement.Parse(xmlString)
Dim value1 As String = xmlObject.<property1>.First().Value
Dim value2 As String = xmlObject.<property2>.First().Value


text:
Q: ExactTarget - How to obtain all tracking data for a list of subscribers... I'm attempting to get all the subscribers and subscriber tracking data for a given account using the SOAP service.

*

*iterating over the stacks to find the correct stack with the username/pw.

*method: fetch the subscribers object.

*pass the subscriber keys into method: ABC and object: XYZ
Can you help me define ABC and XYZ?

A: So, to answer your question, I've attached a sample SOAP envelope for subscribers, clicks, and opens.
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
   <soapenv:Header>
      <fueloauth xmlns="http://exacttarget.com">hxvn5eq6wgetnffjmn9g4upg</fueloauth>
   </soapenv:Header>
   <soapenv:Body>
  <RetrieveRequestMsg xmlns="http://exacttarget.com/wsdl/partnerAPI">
     <RetrieveRequest>
          <!-- Retrieving Subscribers after Create Date -->

        <ObjectType>Subscriber</ObjectType>
        <Properties>ID</Properties>
        <Properties>CreatedDate</Properties>
        <Properties>Client.ID</Properties>
        <Properties>EmailAddress</Properties>
        <Properties>SubscriberKey</Properties>
        <Properties>Status</Properties>
        <Properties>UnsubscribedDate</Properties>
        <Properties>EmailTypePreference</Properties>
        <Properties>SubscriberKey</Properties>

     </RetrieveRequest>
  </RetrieveRequestMsg>

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
   <soapenv:Header>
      <fueloauth xmlns="http://exacttarget.com">hs828jcnjkwq2bhkve3j4va3</fueloauth>
   </soapenv:Header>
   <soapenv:Body>
  <RetrieveRequestMsg xmlns="http://exacttarget.com/wsdl/partnerAPI">
         <RetrieveRequest>
        <Properties>BatchID</Properties>
        <Properties>CreatedDate</Properties>
        <Properties>EventDate</Properties>
        <Properties>EventType</Properties>
        <Properties>ID</Properties>
        <Properties>ModifiedDate</Properties>
        <Properties>SendID</Properties>
        <Properties>SubscriberKey</Properties>
        <Properties>TriggeredSendDefinitionObjectID</Properties>
        <Properties>URL</Properties>
        <ObjectType>ClickEvent</ObjectType>
     </RetrieveRequest>
  </RetrieveRequestMsg>

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
   <soapenv:Header>
      <fueloauth xmlns="http://exacttarget.com">ktq8ttvmkedw4pvm93s8v3vg</fueloauth>
   </soapenv:Header>
   <soapenv:Body>
      <RetrieveRequestMsg xmlns="http://exacttarget.com/wsdl/partnerAPI">
     <RetrieveRequest>
        <ObjectType>OpenEvent</ObjectType>

        <Properties>BatchID</Properties>
        <Properties>CreatedDate</Properties>
        <Properties>EventDate</Properties>
        <Properties>EventType</Properties>
        <Properties>ModifiedDate</Properties>
        <Properties>PartnerKey</Properties>
      <Properties>SendID</Properties>
        <Properties>SubscriberKey</Properties>
        <Properties>TriggeredSendDefinitionObjectID</Properties>
     </RetrieveRequest>
  </RetrieveRequestMsg>


text:
Q: Node JS logout function shows error: `onWebTokenError: jwt malformed` File:
routes > auth.js
var express = require('express');
var authController = require('../controllers/auth');

var router = express.Router();

//Registration POST
router.post('/register', authController.register);

//Login POST
router.post('/login', authController.login);

//Logout
router.get('/logout', authController.logout);

module.exports = router;

File
routes > pages.js
var express = require('express');
var authController = require = require('../controllers/auth');

var router = express.Router();

//Home page
router.get('/', authController.isLoggedIn, function(req,res){
  res.render('index', {
    user: req.user
  });
});

//Register Form
router.get('/register', function(req,res){
  res.render('register');
});

//Login form
router.get('/login', function(req,res){
  res.render('login');
});

router.get('/profile', authController.isLoggedIn, function(req, res){

  if(req.user) {
      res.render('profile', {
        user: req.user
      });
  }

  else {
    res.redirect('/login');
  }

});

module.exports = router;

File
controllers > auth.js
var mysql = require('mysql');
var jwt = require('jsonwebtoken');
var bcrypt = require('bcryptjs');
var { promisify } = require('util');

//database connection
var db = mysql.createConnection({
  host: process.env.DATABASE_HOST,
  user: process.env.DATABASE_USER,
  password: process.env.DATABASE_PASSWORD,
  database: process.env.DATABASE
});

exports.login = async function(req, res) {
  try {
    var {email, password} = req.body;

    if(!email || !password) {
      return res.status(400).render('login', {
        message: 'Please provide an email and password'
      });
    }

    db.query('select * from users where email = ?', [email], async function(error, results){
      console.log(results)

      if(!results.length || !(await bcrypt.compare(password, results[0].password))){
        res.status(401).render('login', {
          message: 'The email or password is incorrect'
        });
      }
      else{
        var id = results[0].id;
        var token = jwt.sign({ id }, process.env.JWT_SECRECT, {
          expiresIn: process.env.JWT_EXPIRES_IN
        });

        console.log("The token is: " + token);

        var cookieOptions = {
          expires: new Date(
            Date.now() + process.env.JWT_COOKIE_EXPIRES * 24 * 60 * 60 * 1000
          ),
          httpOnly: true
        }

        res.cookie('jwt', token, cookieOptions);
        res.status(200).redirect("/");
      }
    });

  } catch (e) {
    console.log(e);
  }
}

exports.register = function(req, res) {
  console.log(req.body);

  //Taking values from HTML Register page
  var {name, email, password, passwordConfirm} = req.body;

  db.query("select email from users where email = ?", [email], async function(error, results) {
    if(error) {
      console.log(error);
    }

    if(results.length > 0){
      return res.render('register', {
        message: 'That email is already taken'
      })
    } else if(password !== passwordConfirm) {
      return res.render('register', {
        message: 'Password do not match'
      })
    }

    let hashedPassword = await bcrypt.hash(password, 8);
    console.log(hashedPassword);

    db.query('insert into users set ?', {email: email, name: name, password: hashedPassword}, function(error, result){
      if(error) {
        console.log(error);
      }
      else{
        console.log(results);
        return res.render('register', {
          message: 'User registered'
        });
      }
    })

  });

}

exports.isLoggedIn = async function(req, res, next){
  console.log(req.cookies);
  if(req.cookies.jwt) {
    try {
      var decoded = await promisify(jwt.verify)(req.cookies.jwt, process.env.JWT_SECRECT);

      console.log(decoded);

      //Check if the user still exists
      db.query('Select * from users where id = ?', [decoded.id], function(error, result) {

        if(!result) {
          return next();
        }

        req.user = result[0];
        return next();

      } );
    }

    catch (e) {
      console.log(e);
    }
  }

  else{
      next();
  }
}

exports.logout = async function(req, res) {
  res.cookie('jwt', 'logout', {
    expires: new Date(Date.now() + 5 * 1000),
    httpOnly: true
  });

  res.status(200).redirect('/');
}

File
.env
DATABASE = TEST
DATABASE_HOST = someserver
DATABASE_USER = username
DATABASE_PASSWORD = password
JWT_SECRECT = mysupersecretpassword
JWT_EXPIRES_IN = 90d
JWT_COOKIE_EXPIRES = 90

Issue:
Everything works fine expect the logout in controllers > auth.js.
What the logout should do - it should overwrite the cookie to expiry in 5 seconds and redirect me to homepage.
What the logout currently does is shows me this error:
onWebTokenError: jwt malformed
    at module.exports (C:\Users\LV98\Desktop\Coding\Node JS\Login System\node_modules\jsonwebtoken\verify.js:63:17)
    at internal/util.js:297:30
    at new Promise (<anonymous>)
    at internal/util.js:296:12
    at exports.isLoggedIn (C:\Users\LV98\Desktop\Coding\Node JS\Login System\controllers\auth.js:111:48)
    at Layer.handle [as handle_request] (C:\Users\LV98\Desktop\Coding\Node JS\Login System\node_modules\express\lib\router\layer.js:95:5)
    at next (C:\Users\LV98\Desktop\Coding\Node JS\Login System\node_modules\express\lib\router\route.js:137:13)
    at Route.dispatch (C:\Users\LV98\Desktop\Coding\Node JS\Login System\node_modules\express\lib\router\route.js:112:3)
    at Layer.handle [as handle_request] (C:\Users\LV98\Desktop\Coding\Node JS\Login System\node_modules\express\lib\router\layer.js:95:5)
    at C:\Users\LV98\Desktop\Coding\Node JS\Login System\node_modules\express\lib\router\index.js:281:22

I am following a tutorial on SkillShare - I am on my final part and ran into this error and not sure how to solve it.
Question
What is the error? How can I fix it?
And also, how can I understand from the error output what that error means?

A: When user go to /logout, you set the jwt value to "logout", not deleting it.
exports.logout = async function(req, res) {
  res.cookie('jwt', 'logout', {
    expires: new Date(Date.now() + 5 * 1000),
    httpOnly: true
  });

  res.status(200).redirect('/');
}

thus whenever user access a route with isLoggedIn middleware, your express app will still detects the user as logged in
exports.isLoggedIn = async function(req, res, next){
  console.log(req.cookies);
  if(req.cookies.jwt) { // this still returns true, because you set the jwt cookies to "logout"
     // ...
  }

Instead of setting the jwt value to logout, delete it like this:
res.clearCookie('jwt');

so your logout controller will look like this:
exports.logout = async function(req, res) {
  res.clearCookie('jwt');
  res.status(200).redirect('/');
}


text:
Q: Writing a JavaScript program to calculate a leap year I am writing a JavaScript program that takes in a date typed by the user and determines what day of the week the given date falls on. I am able to get the program to take in the date. I have used debug statements to print the values of the day, the month, the year, and the century to make sure the program is getting the values correctly, which they are so far.
I also have a debug variable called totalNumDays which stores the number of days for each month since that value differs. (January has 31 days, April has 30 days, February has either 28 or 29 days). The problem I am having is getting the number to be correct for the month February.
What I did was create an array of all the months with 31 days:
//1 = January, 3 = March, 5 = May,..., etc.
var monthNumsWith31 = [1, 3, 5, 7, 8, 10, 12];

Then later on I use a for loop to iterate through to determine the number of days. I tried a couple different things here. The one I thought made the most sense was:
for(var i = 0; i < monthNumsWith31.length; i++)
{
   if(month == monthNumsWith31[i])
   {
      totalNumDays = 31;
   }
   else
   {
      if(month == 2 && isLeapYear() == true)
      {
         totalNumDays = 29;
      }
      else if(month == 2 && isLeapYear() == false)
      {
         totalNumDays = 28;
      }
      else
      {
         totalNumDays = 30;
      }
   }

I tried a whole bunch of different things and can't seem to get it to store the correct number of days for February. I even tried creating a second array of monthNumsWith30 and use two different for loops to iterate through both of those and set the appropriate number of days for months with 30 and 31 days. I think the problem might be in my isLeapYear() function. Here is the code for isLeapYear(). Note that year is global so the function does have access to it.
function isLeapYear() {
    if(year % 4 == 0)
    {
       if(year % 100 == 0)
       {
          if(year % 400 == 0)
          {
             return true;
          }
          else
          {
             return false;
          }
       }
       else
       {
          return true;
       }
    }
    else
    {
       return false;
    }
}

I tried to follow the formula for determining whether a year is a leap year or not. The formula can be seem here: https://gyazo.com/9e4b7fb92014d1e27315807c188fd5e0
Does anyone know why my function is not doing what it is supposed to be doing? Thanks.
UPDATE
I got it working correctly now for figuring the correct number of days for each month. I am having another issue however.
To find out which day of the week a given date occurs on, I am using Zeller's Congruence. The particular formula I am using is ((26M - 2) / 10 + D + Y + Y/4 + C/4 + 5C) MOD 7 where M, D, Y are exactly what they seem and C is the century (first two digits of the year). There is a part of the algorithm that states
IF Month < 3 THEN
   Year = Year - 1
   Month = Month + 10
ELSE
   Month = Month - 2
END IF

I got all that working seemingly correctly. I put in many debug statements to make sure it gets the correct values which it is, but for some reason the computer is evaluating the expression incorrectly.
This algorithm will give a number between 0 and 6. 0 being Sunday, 1 being Monday, etc. For example, taken the date 2/15/16. This date occurred on a Monday. Monday, February 15, 2016.
In my program I have the following code
var weekdayIndex = (Math.floor((26 * monthVal) - 2 / 10) + dayVal +
    yearVal + Math.floor(yearVal / 4) + Math.floor(centuryVal / 4) +
    (5 * centuryVal)) % 7;

When this expression runs, it should equal 1, but for some reason it equals 0. I did the math by hand and evaluated each individual expression over and over again and kept getting 1. Doing this by hand I got the numbers to be (31 + 15 + 15 + 3 + 5 + 20) % 7. When I put this expression into the computer directly (without all the variable names and Math.floor expressions, just numbers) it correctly gets the value. I don't know why it is incorrect when I use the variable names and expressions rather. Any ideas?

A: Your function is ok, except for a simple thing: you are missing the year parameter!
function isLeapYear(year) {
  return year % 4 == 0 &&
    (year % 100 !== 0 || year % 400 === 0);
}

But, with your extended syntax is ok too:
function isLeapYear(year) {
    if(year % 4 == 0)
    {
       if(year % 100 == 0)
       {
          if(year % 400 == 0)
          {
             return true;
          }
          else
          {
             return false;
          }
       }
       else
       {
          return true;
       }
    }
    else
    {
       return false;
    }
}

isLeapYear(1900) yields false, as expected, 2000 true, 1996 true, 1997 false.
Seems legit to me.

A: I think that your logic is rather suspect.  I use the following function to determine whether a given year is a leap year:
CsiLgrDate.leap_year = function (year)
{ return ((year % 4 === 0 && year % 100 !== 0) || year % 400 === 0); };

A: Your function is correct, the error is because javascript Array for month's is zero-indexed.
Change this line:
var monthNumsWith31 = [1, 3, 5, 7, 8, 10, 12];

To this:
var monthNumsWith31 = [0, 2, 4, 6, 7, 9, 11];

And subtract one from all your month references (february is Array index 1)

You can test it by typing (new Date()).getMonth() on the console: you will see that march == 2.
Hope it helps.

A: Here give this a shot. I assume you're just starting. We can avoid a lot of the nested if statements. Also, you'll want to start to get into the habit of using triple equals (===) as it does type checking and won't do weird things with "truthy" values.
First thing, looking at your isLeapYear function. When you do a check for an if statement and use the equal operator to compare them, it's going to return a true or false, so if we aren't doing weird things were we expect true to be false (though there are easy ways to do that too) we can actually just return the expression to get true or false, instead of needing to return true or false if your expression is true or false.
It also might be worth wild to pass in the year as an argument instead of getting it from the parent's scope. But in this case it doesn't actually matter, I'm sure.
The && will check if a statement is true, then it will execute the next expression. And you can chain it if you are expecting everything to be true, because if one thing is false, then everything is false. So no need to write nested if statements.
function checkLeapYear(yearToCheck) {
    return yearToCheck%4 === 0 && yearToCheck%100 === 0 && yearToCheck%400 === 0;
}

So looping through an array is kind of expensive. You might learn that if you start to loop through arrays within arrays. But luckily we don't even need that for this example.
This is a switch statement. It's very handy if you have values you need to equal the same thing. But you might hear from a lot of people the way I wrote mine is wrong and that you should never let a case fall through. I disagree with those people, because I think this is a great example of when you'd want to do just that.
This switch will take a variable, the month in this case. Compare it with the value in the cases, then execute the code for the case. It will fall through into the next case without a break; Because we want 1, 3, 5, 7, 8, 10, 12 to all make totalNumDays = 31 we set that for the lowest case and have the rest fall into.
But when if month equals 2, we want it totalNumDays to be 29 on leap years or 28 otherwise. Ternary Operator It basically works like a shorthand if statement. You give it an expression, in this case the checkLeapYear function, then a ? to start the ternary operator. Then the value for when it's true, this case we want it to equal 29. Then for false values use : then put want you want the false value to be, in this case 28.
In the switch statement, default just means do this if there are no matches. Which is making totalNumDays equal 30. Which this could be a bit dangerous as if we make month equal to 13 or 'A' it will still make totalNumDays equal 30. But preparing for every possibility isn't something I'm too concerned around right now.
switch(month) {
  case 1:
  case 3:
  case 5:
  case 7:
  case 8:
  case 10:
  case 12:
    totalNumDays = 31;
    break;
  case 2:
    totalNumDays = checkLeapYear(year) ? 29 : 28;
    break;
  default:
    totalNumDays = 30;
    break;
}

Anyway, I hope that helps and wasn't too much to take in. As for why your code isn't working. I think it might be because your loop starts on month 0. Which is going to be a 30 day month.

A: The code actually works if the year parameter is used in the isLeapYear call and in the function declaration.
Here is the code exactly as posted (well, I added a missing closing } that I assume was a posting omission):

// Set some test values
var monthNumsWith31 = [1, 3, 5, 7, 8, 10, 12];
var month = 2;
var year = 2000

for(var i = 0; i < monthNumsWith31.length; i++)
{
   if(month == monthNumsWith31[i])
   {
      totalNumDays = 31;
   }
   else
   {
      if(month == 2 && isLeapYear(year) == true)
      {
         totalNumDays = 29;
      }
      else if(month == 2 && isLeapYear(year) == false)
      {
         totalNumDays = 28;
      }
      else
      {
         totalNumDays = 30;
      }
   }
}

function isLeapYear(year) {
    if(year % 4 == 0)
    {
       if(year % 100 == 0)
       {
          if(year % 400 == 0)
          {
             return true;
          }
          else
          {
             return false;
          }
       }
       else
       {
          return true;
       }
    }
    else
    {
       return false;
    }
}

document.write(totalNumDays);

A: https://codepen.io/pen?template=QWmqeqj
Steps:
1). If the year is evenly divisible by 100, then If the year is evenly divisible by 400.
*The year is a leap year.*

2). If the year is not evenly divisible by 100, then If the year is evenly divisible by 4.
*The year is a leap year.*

3). If the year is not evenly divisible by 100 and year is not evenly divisible by 400 or year is not evenly divisible by 4.
*The year is not a leap year.*


text:
Q: Prove that $n \in \mathbb{Z}^\star \Leftrightarrow n \mid 1$ and $n-1 \mid 1$ or $n+1 \mid 1$, and $(x-1)/(t-1) \equiv n \pmod {t-1}$ I want to prove the following lemma:

Let $F[t,t^{-1}]$ be the ring of the polynomials in $t$ and
  $t^{-1}$ with coefficients in the field $F$ and assume that the characteristic of $F$ is zero.
Then for any $n$ in $F[t, t^{-1}]$, $n$ is a nonzero integer
  if and only if

*

*$n$ divides $1$

*either $n-1$ divides $1$ or $n+1$
  divides $1$, and

*there is a power $x$ of $t$, so that $\dfrac{x-1}{t-1}
 \equiv n \pmod {t-1}$.

Could you give me some hints how we could show that?
$$$$
EDIT:
I thought that we could use the following, but I am not sure:
an integer is nonnegative iff it is the sum of four integer squares and $x$ is nonzero iff there is a nonnegative integer $y$ so that $x=y+1$ or $x=−y−1$.
Does this help?

A: I had wanted to give some hints and then put the solution into the "hidden" mode.  However, the command >! didn't seem to be working with my text (this might have something to do with LaTeX commands), so I will just put my solution then.  I would greatly appreciate if anybody can suggest a way to hide my text below.
First, suppose $n\in\mathbb{Z}\setminus\{0\}$.  Clearly, $n\mid 1$, and either $n+1\mid 1$ or $n-1\mid 1$.  Furthermore, if $n>0$, then $$\frac{t^n-1}{t-1}=\sum_{j=0}^{n-1}\,t^j=n+(t-1)\left(\sum_{j=0}^{n-1}\,\frac{t^j-1}{t-1}\right)=n+(t-1)\left(\sum_{j=1}^{n-1}\,\sum_{k=0}^j\,t^k\right)\equiv n\pmod{t-1}\,.$$
If $n<0$, then
$$\frac{t^n-1}{t-1}=-t^{n}\left(\frac{t^{-n}-1}{t-1}\right)\equiv -t^n(-n)\equiv nt^n\equiv n\pmod{t-1}\,.$$
Now assume that $f(t)\in F\left[t,t^{-1}\right]$ is such that
(a) $f(t)\mid 1$,
(b) $f(t)+1\mid 1$ or $f(t)-1\mid 1$, and
(c) there exists $n\in\mathbb{Z}$ such that $\frac{t^n-1}{t-1}\equiv f(t)\pmod{t-1}$.
We shall prove that $f(t)=n \neq 0$.  Condition (c) implies that $f(t)-n$ is divisible by $t-1$.  Hence, $$f(t)=n+(t-1)\,g(t)$$ for some $g(t)\in F\left[t,t^{-1}\right]$.  Since $f(t)\mid 1$, $f(t)$ is a unit in $F\left[t,t^{-1}\right]$, whence $f(t)=at^k$ for some $a\in F\setminus\{0\}$ and $k\in\mathbb{Z}$.  If $f(t)\pm 1 \mid 1$, then $f(t)\pm 1$ is also a unit.  That is, $at^k\pm 1$ is of the form $bt^l$, where $b\in F\setminus\{0\}$ and $l\in\mathbb{Z}$.  If $k\neq 0$, we note that $at^k\pm1$ has a nonzero root in the algebraic closure of $F$, but $bt^l$ does not.  Therefore, $k=0$.  Hence, $f(t)=a$ is a nonzero, constant polynomial.  Now, from $f(t)=n+(t-1)\,g(t)$, we have $0\neq a=f(1)=n$.  Ergo, $f(t)=n \neq 0$ as desired.


text:
Q: Unable to get profile variable using ssh Unable to retrieve the profile variable using ssh.
server2 ==> user apptst ==> bash profile has $APPHOME variable.
Was trying to retrieve the value from server1 using ssh but failed.
Used options below
server1> ssh apptst@server2 'echo $APPHOME'

server1> ssh apptst@server2 echo '$APPHOME'

server1> ssh apptst@server2 echo "$APPHOME"

server1> ssh apptst@server2 "echo $APPHOME"

when tried
server1> ssh apptst@server2 ls -ld $APPHOME

it works fine.
Any suggestions what is missing and how can I get the variable from server2?

A: This command should work:
 server1> ssh apptst@server2 'bash -l -c "echo \$APPHOME"'

*

*you need ' quotes to pass that complete command to ssh as one argument; this also prevents the shell on server1 to expand $APPHOME itself

*bash -l starts a login shell, which reads in the profiles files, where $APPHOME gets defined (as @chepner pointed out in his answer, this is not default when invoked by sshd)

*-c executes the next argument, again with quotes that the complete echo command gets executed.

*escaping \$ is necessary, because otherwise the parent (non-login) shell which sshd invokes (and which inherits the environment diretly from init (*)) does expand $APPHOME. But this is too early as $APPHOME only gets defined for login shells (via ~/.profile). [added this point after comment from OP]

(*) correct me, if I'm wrong here.

A: The problem is that when you specify an exact command to run via ssh, the remote sshd does not start a login shell to execute it, but a regular non-interactive shell. In that case, .bash_profile is not executed, and so APPHOME is not defined.
And while typing this, mph has posted the correct solution to force a login shell that processes .bash_profile.


text:
Q: protobuf-net: Backward compability when type has changed? is there a way to provide backward compability when a member type has changed? For example, class Person consists in version 1 of one integer, but in version 2 of a string. I know that this is breaking the contract, but the example is an issue that isn't seldom in the real life software development.
Thanks in advance.
// Version 1
[ProtoContract]
class Person
{
    [ProtoMember(1)]
    public int ID { get; set; }
}

// Version 2
[ProtoContract]
class Person
{
    [ProtoMember(1)]
    public string ID { get; set; }
}

A: A shim property is probably your best bet:
// Version 2
[ProtoContract]
class Person
{
    [ProtoMember(1)]
    private int? ID_v1 {
        get { return null; } // means it won't be serialized
        set { if(value != null) ID = value.ToString(); }
    }

    [ProtoMember(2)]
    public string ID { get; set; }
}


text:
Q: What is the difference between words and symbols in Qsys, how to know which one to use? Qsys offers options to select address unit or address type. All I know is that my custom components shall write 32 or 64 bit data to a specific address and it is not byte addressable.
How do I decide which address type to use? This question comes up in Qsys custom component generation and also when instantiating an Avalon-MM BFM.
So my questions are:

*

*What is the motivation behind have "Address units", I am confused how to decide which one to use?

*Regardless of whether I select "WORDS" or "SYMBOLS", there is always a box saying "Bits per symbol" in the GUI. Why is this so?

*When instantiating an Avalon-MM BFM there are options for Symbol width and Number of symbols. How do I know what to select?
Selecting over the other seems to have a big impact on the address span. But not clear how.

A: A symbol is the smallest unit of addressable memory. You need to be able to specify how many bits are in your symbol, but it is usually 8.
If the number of bits per symbol differs between master and slave, logic is required to convert the slave to match the master. For example how could a slave with a 9-bit symbol be accessed by a master with an 8-bit symbol.
I've previously built very simple Qsys blocks that do nothing but pass through signals to trick Qsys into allowing dissimilar modules to connect. But this requires knowing the side effects and making sure they are what you intend.
A word is the size of your memory bus. Frequently the memory bus is larger than a symbol. For example, take:

*

*Symbol Size: 8-bit

*Word Size: 32-bit

This would be so for a typical 32-bit processor. You have 8 bits per symbol, and 4 symbols per word. Essentially number of bits per symbol sets your primary data size, and number of symbols selects your data bus width.
Then say you have the following symbol addresses:

*

*0x0000

*0x0020

*0x0024

These correspond to word addresses of:

*

*0x0000

*0x0008

*0x0009

If you are using word addressing, you would typically have an additional byte enable signal which is used to address one or more symbols in a word as the smallest unit you could otherwise access is a whole word.
Word addressing means that if you had an address width on your slave of 1-bit, then you can address two words, which in the example above is 8 bytes worth. You can use the byte enable to address individual bytes. Of course there is no requirement to support byte enables in which case each access is implied to be an entire word.
Symbol addressing would mean you would need a 3-bit address to access each symbol individually. You would have no byte enable signal as the address alone is enough.
Which you use depends on how you designed your logic. Typically word addressing is most useful. Otherwise you can only access a single byte at a time on your wider data bus which reduces the point of having said wide bus. Word addressing allows you to access the slave at its full width.
Address span is usually shown in Qsys in units of symbols regardless of whether you are using word addressing or symbol addressing. Basically the maximum span of your interface is:

*

*(symbols per word) × 2(address width)


text:
Q: Calculating the voltage drop in a split-phase system We are working with an electrician to install permanent wiring to a large trailer unit - it will be a 120/240 V split-phase system (the trailer itself uses a NEMA 14-50 dryer plug) delivering 50 amps at a distance of 300 ft.
I (think I) understand that this wiring set up effectively gives us three circuits - two 120 V/50 A circuits and a single 240 V/50 A circuit.
What I am struggling to understand is how I determine the proper wiring size for the system, given the parameters of the circuit and our voltage drop needs ( <3% ). Following Ohm's Law, I have been using the formula to calculate the expected voltage drop for particular wire gauges (4 AWG or 1 AWG):
Vd = 2 * L * R * A
Where:
Vd: voltage drop
L: one way distance (in thousands of ft)
R: resistance of wire (in Ohms per 1000 ft)
A: load current (in amperes)
Ex. 1 1 AWG wire, 300ft, 50A
Resistance of 1 AWG wire / 1000ft = .124 Ohms
Vd = 2 * 50 * (.3) * (.124)
Vd = 3.72 V
Ex. 2 4 AWG wire, 300ft, 50A
Resistance of 4 AWG wire / 1000 ft = .249 Ohms
Vd = 2 * 50 * (.3) * (.249)
Vd = 7.47 V
Based on this information, my numbers suggest that we would need to use 1 AWG wire, but the electrician has said that 4 AWG is more than sufficient. I have complete confidence in this electrician, so I am sure there is something that I am missing. How does the presence of the split-phase 240 V system affect voltage drop considerations (if at all?).
Any comments or help is greatly appreciated!

A: The 50A breaker pair feeding the NEMA 14-50 plug limits the current on any phase to ... 50A, period, no matter how you load your phases. The breakers are linked, so if you have a single-phase fault on L1, it will trip itself and L2.
Your electrician will use that breaker panel limit not only to calculate the IR drop, but also the allowable cable temperature rise given the ambient temperature, conduit type, wire material and insulation type, as these all affect the 'ampacity' of the wire.
As for the voltage drop, the NEC specifies a maximum drop of 5%, not 3%. See https://www.mikeholt.com/technnical-voltage-drop-calculations-part-one.php
At 300ft and 50A, #4 ga. copper will be less than that, about 3.5%. So, plenty.
Your electrician knows what they're doing.
BONUS: An IR drop calc, with a wire resistance chart: https://www.calculator.net/voltage-drop-calculator.html
tl; dr:

*

*resistance of #4 ga. is 0.2485 ohm/1000ft

*One-way IR drop for 300' at 50A = 50 * 300/1000 = 3.73V

*Two-way IR drop is 7.46V, or 3.1%


text:
Q: Problem unit testing a delete method with mock service worker (MSW), node and React I have MSW setup with React and Typescript, the code works in the browser, ie, it deletes the employee, but not in the test, the other tests are working fine. I'm stumped, there's probably something daft that I'm doing, any help would be greatly appreciated
github repo https://github.com/cherry15/cc2022react
handlers.ts

  rest.delete(`${url}/:employeeId`, (req, res, ctx) => {
    const { employeeId } = req.params
    if (employeeId) {
      const employeeIndex = EmployeesData.findIndex(
        (employee) => employee.id === employeeId.toString()
      )
      if (employeeIndex !== -1) {
        EmployeesData.splice(employeeIndex, 1)
        return res(ctx.status(200))
      } else {
        return res(ctx.status(404))
      }
    }
    return res(ctx.status(400))
  }),

employees.test.tsx

describe('Delete employee', () => {
  test('clicking on the OK button deletes the employee', async () => {
    renderWithProviders(<EmployeeList />)
    await screen.findByRole('heading', { name: /ada lovelace/i })
    await screen.findAllByRole('button', { name: 'Delete employee' })

    fireEvent.click(screen.getAllByRole('button', { name: 'Delete employee' })[0])
    fireEvent.click(await screen.findByText('OK'))
    expect(screen.getByText(/ada lovelace/i)).not.toBeInTheDocument()
  })
})

A: This isn't exactly a MSW or RTK Query issue. Being that you're performing async operations, you need to await the disappearance of the target element.
test("clicking on the OK button deletes the employee", async () => {
renderWithProviders(<EmployeeList />);

// Wait for ada lovelace to show up to the party!
await screen.findByRole("heading", { name: /ada lovelace/i });
await screen.findAllByRole("button", { name: "Delete employee" });

fireEvent.click(
  screen.getAllByRole("button", { name: "Delete employee" })[0]
);
fireEvent.click(await screen.findByText("OK"));

// Let's wait to make sure she's gone!
await waitForElementToBeRemoved(() =>
  screen.queryByRole("heading", { name: /ada lovelace/i })
);
});


text:
Q: How to access TextMate grammar parsing results from Language Server? I have a VS Code extension with syntax highlighting support – I described language grammar via .tmLanguage.json file. Now I want to improve this extension with DocumentSymbolProvider – and it appears that now I need to implement all the grammar parsing, including tokenization, from scratch. Is there any option to access grammar parsing results via VS Code API?

A: Found https://github.com/microsoft/vscode-textmate, that is the tool that VS Code uses internally


text:
Q: Efficiently printing the intersection and union of huge different lists of strings I have three lists of differents sentences :
the first has (6228 elements), the second  (30177) elements and the last (1059).
The string in each list correspond to sentences betwen 3 to more than 150 characters. Those sentences were extracted and seperated in different list in order to write them in different .tsv files. So Now I want to search in them to find the common sentences to the three lists and also the intersection between them.
I would like to print the intersection of the three lists  with and without doublon (because somme elt in list_1  can be present in list_2 or list_3.
I want also to print the intersection between each list with the other one  :
for example  intersection of  element in list 1  and 2 but not in list 3 ;  element in list 2 & 3  but not in list 1;  and element in list 3 & 1 but not in list  2 ;
I come up with this algorythm  but is there any better way to get what I want  ?
I ask because soince I amdealing with long string(sentences)  I am afraid sometimes the looping in the list is not really efficient and do not brought me accurate result. Since my files are huges. I give you this small sample
    l_1 = ['je mange du pain', 'tu es laid', 'je suis beau', 'vive la vie', 'vive l\'horizon']
    l_2 =  ['je mange du pain', 'vive l\'horizon', 'L\'esprit des eaux est vaincu', 'Satan tu es vaincu', 'Jésus est puissant et t\'a vaincu', 'Satan tu n\'es rien' , 'tu ne peux pas m\'intimider', 'Je suis couverte par le Sang de Jésus']
    l_3 = ['je mange du pain', 'vive l\'horizon', 'L\'esprit des eaux est vaincu', 'Je suis couverte par le Sang de Jésus', 'vive la vie']

    sentences_1 = []    # intersection
    sentences_2_1 = []   # intersection between two list without checking if the elt is present the last list
    sentences_2_2 = []
    sentences_2_3 = []

    sentences_2_1_0 = []  intersection between two list with checking if the elt is present the last list
    sentences_2_2_0 = []
    sentences_2_3_0 = []
    sentences_3 = []      # Union of the three list (can contains sentences which are present more than once)

    #  One case
    for elt in l_2:
      if elt in l_1 and elt in l_3 :
        if elt not in sentences_1:
          sentences_1.append(elt)

    print('Phrases communes aux trois conditions :', len(sentences_1))

    # Second case
    for elt in l_1:
      if elt in l_2:
        if elt not in sentences_2_1_0:
          sentences_2_1_0.append(elt)

    print('Phrases communes aux sets 1 & 2 :', len(sentences_2_1_0))

    for elt in l_1:
      if elt in l_2 and elt not in l_3:
        if elt not in sentences_2_1:
          sentences_2_1.append(elt)

    print('Phrases communes aux sets 1 & 2 mais pas 3:', len(sentences_2_1))

    # Second case
    for elt in l_2:
      if elt in l_3:
        if elt not in sentences_2_2_0:
          sentences_2_2_0.append(elt)

    print('Phrases communes aux sets 2 & 3 :', len(sentences_2_2_0))

    for elt in l_2:
      if elt in l_3 and elt not in l_1 :
        if elt not in sentences_2_2:
            sentences_2_2.append(elt)

    print('Phrases communes aux sets 2 & 3 mais pas 1:', len(sentences_2_2))

    # Second case
    for elt in l_3:
      if elt in l_1 :
        if elt not in sentences_2_3_0:
          sentences_2_3_0.append(elt)

    print('Phrases communes aux sets 3 & 1 :', len(sentences_2_3_0))

    for elt in l_1:
      if elt in l_3 and elt not in l_2 :
          if elt not in sentences_2_3:
            sentences_2_3.append(elt)

    print('Phrases communes aux sets 3 & 1 mais pas 2:', len(sentences_2_3))

    # third case
    for elt in l_1:
      sentences_3.append(elt)

    for elt in l_2:
      sentences_3.append(elt)

    for elt in l_3:
      sentences_3.append(elt)
      #any(x, y, z) not in sentences_3:

    print('Union des trois sets:', len(sentences_3))

    sentences_3_filtered = sorted(list(set(sentences_3)))  # Print the union of the three list without doublon, we keep each sentences just once deleting doublons or triple

    print( "sans doublon :", len(sentences_3_filtered))

A: Even a list of 30177 items (each a 150 character string) isn't very big.
You can just use sets directly, and do whatever intersection logic you'd like:
a = set([<items>...])
b = set([<items>...])
c = set([<items>...])

and then, e.g.:
a_and_b = a & b
a_and_c_but_not_b = a & c - b  # order of operations wouldn't matter anyway

should all be very fast.
If you have a truly large number of truly very large lists, sorting them first externally and then doing merge operations can provide some benefits.

A: There are 2 ways to do this: First either use a set or map. set would be wiser choice as it will save you space. Secondly if data you are processing is too big than you might want to consider the parallel procession by dividing it int equal parts.


text:
Q: How to control [Android] permissions with Phonegap? Sorry for the length of this. Please read on.
How can I configure phonegap's project files so that either phonegap platform add or phonegap build generate APK (or intermediate files that are used to generate APK) without any permissions, while not touching any of the /platform/android/ files manually?
Below describes what I tried.
I'm using the latest Phonegap and I'm trying to use CLI (so, not Adobe's build service). I went through everything that I could find online (documentation, forums, here) trying to find at least some hints on how to control the build process, preferably via config (specifically for Android), so that files in /platforms/android/ (e.g. AndroidManifest.xml) get assembled the way that I want.
For example, even with all plugins removed (phonegap plugin remove [plugin name] + manually removed <plugin element from /config.xml, resulting in nothing but an empty json object in /plugins/fetch.json), I can't get AndroidManifest.xml to get created without these 3:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>

I'd really not like to get into the discussion of why I'm trying to remove all permissions without manually changing /platform/android/AndroidManifest.xml. I previously used Visual Studio Cordova project template, and I was able to make this work (it's got a different file merge/replacement system, equivalent of which I'm trying to discover on Phonegap side). Both Phonegap and Cordova documentation in general are very selfish/basic, IMO (but, that's another topic).
Of course, I've been removing/re-adding android-platform via phonegap platform remove/add android + phonegap build android each time after config change attempts (which I tried within /config.xml; I also tried to find a spot in the folder tree to place AndroidManifest.xml that would replace the one in /platform/android), but nothing worked. I've been verifying success/failure of my mission via aapt d permissions "platforms\android\build\outputs\apk\android-debug.apk", and by manually checking generated /platforms/android/AndroidManifest.xml, and - no kidding - by release-bulding + signing + uploading to my Google account for their report of my APK (by that was before I discovered aapt.exe).
If anyone can share some links, samples, book titles, or similar - I'd be grateful.
Thank you.

A: Add:
xmlns:android="http://schemas.android.com/apk/res/android"

to widget declaration in config.xml.
Then add the following:
<platform name="android">
    <config-file target="AndroidManifest.xml" parent="/manifest">
        <uses-permission android:name="android.permission.RECORD_AUDIO" />
    </config-file>
</platform>

Hope it helps!


text:
Q: unresolved refrence: @MusicService I have used this class inside my service class, to help me access the service from my activity. My service class name is MusicService.
class MusicBinder: Binder(){
      fun getService():MusicService{
          return this@MusicService
      }
}

But i get this error:
unresolved reference: @MusicService

I tried 'inner' keyword for MusicBinder class but it didn't work.
I would appreciate if you helped me with this.
Update:
here is a part of my activity that i use to access service.
private val serviceConnection = object : ServiceConnection {
        override fun onServiceDisconnected(p0: ComponentName?) {
        }
        override fun onServiceConnected(p0: ComponentName?, p1: IBinder?) {1
            musicService = p1.getService()
        }
    }

A: Proper Android Service binding implementation in Kotlin:
class MusicService : Service() {

    private val musicBinder = MusicBinder()

    inner class MusicBinder: Binder() {
        fun getService() : MusicService {
            return this@MusicService
        }
    }

    override fun onBind(intent: Intent): IBinder {
        return musicBinder
    }
}

and in your Activity:
private var isBinded = false
private var musicService: MusicService? = null
private val musicServiceConnection = object: ServiceConnection {
    override fun onServiceDisconnected(name: ComponentName?) {
        musicService = null
    }

    override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
        musicService = (service as MusicService.MusicBinder).getService()
    }
}

fun bindService() {
    if (bindService(Intent(this, MusicService::class.java), musicServiceConnection, Context.BIND_AUTO_CREATE)) {
        isBinded = true
    } else {
        // log error here
    }
}

fun unbindService() {
    if (isBinded) {
        unbindService(musicServiceConnection)
        isBinded = false
    }
}

override fun onDestroy() {
    unbindService()
    super.onDestroy()
}

More info can be found here: https://developer.android.com/reference/android/app/Service.html or in Service class JavaDoc.


text:
Q: Bootstrap 3 broken row on mobile only I am having a problem with bootstrap 3 and some thumbnails where although I'm using the same code and the image sizes are exactly the same the last image row is broken on mobile when in vertical only
Here is the code:

styling

colour

extensions

hair enhancements

smoothing treatment

hair up

meet the team

price list

A: This is happening because some of the text below the thumbnails is wrapping, and as a result the thumbnail heights are different. One way to fix this problem is to clear the columns float on mobile with CSS like this..
@media (max-width: 768px) {
    .row > .col-xs-6:nth-child(2n+1) {
        clear: left;
    }
}

Demo 1: http://codeply.com/go/Bgt8JFkPht
Another option (simpler), is to use CSS text-overflow ellipsis on the text DIV's since it's these DIVs that are causing the height to be different on each thumbnail. When the thumbnail heights are the same, the row wrapping is not an issue..
Demo 2: http://codeply.com/go/5uOP4bM5pk

A: Check your text-margin class, when adding a margin or padding to some items in Bootstrap, you change the width of your columns.


text:
Q: CircularProgressIndicator does not stop It is probably a basic question, but I did not found an answer.
I execute CircularProgressIndicator() and the screen shows the circle but the circle is stopped?
In my case, it continues... endless...
Why? Do I need to make a call in order to stop it?
below the sample code:
import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:web_scraper/web_scraper.dart';
import 'dart:io';

void main() => runApp(MyApp());

/// This Widget is the main application widget.
class MyApp extends StatelessWidget {
  static const String _title = 'Flutter Code Sample';

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: _title,
      home: MyStatefulWidget(),
    );
  }
}

class MyStatefulWidget extends StatefulWidget {
  MyStatefulWidget({Key key}) : super(key: key);

  @override
  _MyStatefulWidgetState createState() => _MyStatefulWidgetState();
}

class _MyStatefulWidgetState extends State<MyStatefulWidget> {
  int _count = 0;
  bool ShowCircle = true;

  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Sample Code'),
      ),
      body: Center(
      child : Column(
      children: <Widget>[
        //sleep(const Duration(seconds:2)),
        Text("Sample",style:TextStyle(fontSize: 21)),
      ]

      )),
      backgroundColor: Colors.blueGrey.shade200,
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          ShowCircle = !ShowCircle;
          if (ShowCircle)
          CircularProgressIndicator(value:0.0);
          else
            CircularProgressIndicator(value:1.0);
        },
        tooltip: 'Increment Counter',
        child: const Icon(Icons.add),
      ),
    );
  }
}

BR
Asi

A: As the official documentation says, the CircularProgressIndicator have two behavior :

*

*Determinate. Determinate progress indicators have a specific value at each point in time, and the value should increase monotonically from 0.0 to 1.0, at which time the indicator is complete. To create a determinate progress indicator, use a non-null value between 0.0 and 1.0.

*Indeterminate. Indeterminate progress indicators do not have a specific value at each point in time and instead indicate that progress is being made without indicating how much progress remains. To create an indeterminate progress indicator, use a null value.

https://api.flutter.dev/flutter/material/CircularProgressIndicator-class.html
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
  bool _showCircle = true;

  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Sample Code'),
      ),
      body: Center(
        child: Column(
          children: <Widget>[
            Text("Indeterminate", style: TextStyle(fontSize: 21)),
            _showCircle ? CircularProgressIndicator() : CircularProgressIndicator(value: 0.0),
            Text("Determinate", style: TextStyle(fontSize: 21)),
            _showCircle ? CircularProgressIndicator(value: 0.7) : CircularProgressIndicator(value: 0.0),
          ],
        ),
      ),
      backgroundColor: Colors.blueGrey.shade200,
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          setState(() {
            _showCircle = !_showCircle;
          });
        },
        tooltip: 'Increment Counter',
        child: const Icon(Icons.add),
      ),
    );
  }
}

A: You can wrap the circular progress indicator in a Visibility widget:
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
  bool _showCircle = true;

  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Sample Code'),
      ),
      body: Center(
        child: Visibility(
          visible: _showCircle,
          child: CircularProgressIndicator(),
        ),
      ),
      backgroundColor: Colors.blueGrey.shade200,
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          setState(() {
            _showCircle = !_showCircle;
          });
        },
        tooltip: 'Show/Hide Circular Progress Indicator',
        child: const Icon(Icons.add),
      ),
    );
  }
}

In this example, pressing the button will toggle the visibility of the circular progress indicator on/off.


text:
Q: Can async await increase total time to execute a function My question relates to the overall time it takes to execute an async function compared to synchronous function.
My understanding is as follows:
-Async function gets called
-Code executes until the awaited code is reached
-Whilst awaited code is executed (eg db read), the executing thread is freed up to do another task
-Once awaited code is complete, a thread is assigned to complete this call
Assuming what I say is correct, is it the case that on a busy server the async call could and often would be slower than the synchronous call?
My reasoning is as follows:

*

*There is an overhead to async (keeping track of everything)

*As the async code has to wait for a thread to execute the remaining code, it has to wait for a thread to become available - so if all the threads are busy it would have to wait for one?
If this is true, then I assume this also means that if there was an awaited method that did not do any I/O, it would still release the executing thread and wait for the next one to become available to complete the task?
UPDATE:
I know await/async does not make response times faster, but instead allows the server to be more efficient.
The main point I am trying to clarify is whether a request could take longer to complete due to the fact that there are no threads available when the async task has completed eg if the db call has completed, does it ever have to wait more time for a thread to become available? I know there are many dimensions to await and many more points to consider, but I am just trying to understand this one point in isolation.
UPDATE 2:
Assume I have a well designed async system, but I have one method that I need to be as fast and lean as possible - I do not ant anything to ever get in the way of the execution time for this one call. Surely in this situation, if I make this method async and free up the thread, the call could potentially have to wait for a thread to finish its execution if it is async, whereas if it is sync the thread will always be there waiting - at the expense of the performance of the rest of the application?

A:

*

*There is an overhead to async (keeping track of everything)

Correct. However, the speed gained from asynchronous tasks tends to far outweigh the overhead cost, so it's negligible. Unless you start spamming many tasks with tiny execution bodies, at which point the overhead (per task) will start to become a noticeable factor.

The main point I am trying to clarify is whether a request could take longer to complete due to the fact that there are no threads available when the async task has completed eg if the db call has completed, does it ever have to wait more time for a thread to become available?

Pedantically, that is correct. Your "first" operation that was put aside because it was waiting for a task to complete will not be able to butt in line at the exact time where its task is complete.
The operation will have to rejoin the queue, but does get priority over operations that have not been started yet. This is very analogous to e.g. how a post office works:

*

*You queue

*You get to the front desk, the postal worker gives you a form to fill in (and thus awaits you filling in that form)

*You step aside and fill in the form while the postal worker can help others instead of idling while she waits for you.

*When you are done with your task, you do not push the customer currently being helped aside... (this is what you seem to want: getting the immediate attention of a thread and not waiting for finish what it's currently doing).

*...but you will be allowed to jump the queue in front of people who have not yet spoken to the postal worker.

Note: At least that is how my culture (Western Europe) deals with this. Your mileage may vary.
So, yes, your assumption is in fact correct; but I do want to stress that the time difference here is astronomically negligible compared to the gains from working asynchronously.
If you want to squeeze a particular operation for the absolutely fastest performance, you would have to give it its own thread and not let it partake in the "async pooling" schedule. But I highly suggest against that as the benefit from doing so will be exceedingly marginal and will in no way outweigh the complexity of developing it.
Secondly, consider that in a "well designed async system" (as per your question), tasks will be split up into the smallest reasonable operations, and thus the execution of a single task (excluding any wait times inbetween) will not be significant. In practice, you will not notice having to wait for a thread to become available - unles you are massively oversaturating your server's workload and really pushing the limits - at which points you've got other bigger fish to fry.

Assume I have a well designed async system, but I have one method that I need to be as fast and lean as possible - I do not ant anything to ever get in the way of the execution time for this one call. Surely in this situation, if I make this method async and free up the thread, the call could potentially have to wait for a thread to finish its execution if it is async, whereas if it is sync the thread will always be there waiting - at the expense of the performance of the rest of the application?

I don't understand your reasoning here.
If you assume that "the thread is waiting for me" in the synchronous example, that means that this thread is available and currently not busy. But for your asynchronous example, you assume that all thread are busy and none are available.
These are completely different situations. If all threads are saturated in an asynchronous application, then all threads (be it one or more) in a synchronous application would also be busy.
The intent of async is quite the opposite. If a thread is currently busy but idling, in a synchronous application, you will be forced to wait and you cannot use the thread. In an asynchronous application, however, the waiting thread will be able to start handling your request as it's currently idling because it's waiting for another task that is not yet completed.

A: async-await is more about responsiveness that performance.
In a client UI, the UI is (usually) managed in a single thread (the UI thread). If you block that thread, the UI is blocked. async-await provides a mechanism to start a task outside of the UI thread and resume execution on the UI thread when that task is complete. That task can either be IO or CPU intensive. The main goal is to get out of the UI thread.
In a server (ASP.NET) the thread pool is limited so, releasing threads when doing IO makes the application able to handle more requests. On the other hand, using tasks for CPU intensive work will just trade one thread pool thread for another twice.
All this is extra work which, obviously, uses more resources (CPU cycles and memory). It's all about responsiveness, not performance.


text:
Q: How to close iframe from within an iframe cross origin I have created a page which will be used by the endusers through iframe.
Inside the page which i have created there are two buttons Submit and Decline. On click of the decline button i want to close the iframe. I have tried couple of methods but getting permission denied error due to cross origin as my webpage will be on the another server and the enduser who is going to consume my page through iframe will be on different server.
Methods which I tried is
Using ContentWindow,
window.parent
and also tried to get current page parent url and redirect at the same page
window.top.href = window.top

A: Here's a CSS solution using an overlay (<nab>) z-indexed over the , a button in the overlay (), and a [hidden] checkbox associated with the  (<input id='dismiss'>). Once the  is clicked by user, the <input id='dismiss'> gets :checked which causes the
 containing the  to disappear.

html,
body {
  overflow: hidden;
}

:checked+section {
  width: 0vw;
  height: 0vh;
  left: -999vw;
}

section {
  position: relative;
  width: 100vw;
  height: 100vh;
  overflow: hidden;
}

nav {
  position: absolute;
  top: 0;
  bottom: 0;
  right: 0;
  left: 0;
  z-index: 1;
  width: 100%;
  height: 100%;
  overflow: hidden;
}

label {
  display: block;
  width: 7ch;
  height: 2ch;
  position: absolute;
  top: calc(50% - 2.5ch);
  bottom: 0;
  right: 0;
  left: 50%;
  z-index: 12;
  border: 2.5px outset grey;
  border-radius: 6px;
  font: 2.5ch/1 "Segoe UI";
  text-align: center;
  background: #fff;
  cursor: pointer;
}

iframe {
  display: block;
  position: absolute;
  top: 0;
  bottom: 0;
  right: 0;
  left: 0;
  z-index: 0;
  width: 100%;
  height: 100%;
  overflow: hidden;
}
<!doctype html>

  <meta charset='utf-8'>

  <input id='dismiss' type='checkbox' hidden>

      Dismiss