text:
Q: save keras model with custom activation I want to save a Keras model with a custom activation function.  Saving just the weights is not an option since want to save the optimizer state.
If I use a built in activation function like relu, save works with no problem.  But if I use a custom activation function, I get an error; I assume this is because the activation function itself cannot be stored.   My custom activation function is:
def lrelu(x):
    return tf.maximum(x * 0.2, x)

If I use it with
keras.layers.Conv2D(filters, kernel_size, padding=padding, strides=strides, activation="lrelu")(x)

I get the error below.  Is there any work around?
Traceback (most recent call last):
  File "train_K.py", line 191, in <module>
    model.save(model_fn)
  File "C:\ProgramData\Anaconda3\envs\py352\lib\site-packages\keras\engine\topol
ogy.py", line 2576, in save
    save_model(self, filepath, overwrite, include_optimizer)
  File "C:\ProgramData\Anaconda3\envs\py352\lib\site-packages\keras\models.py",
line 111, in save_model
    'config': model.get_config()
  File "C:\ProgramData\Anaconda3\envs\py352\lib\site-packages\keras\engine\topol
ogy.py", line 2349, in get_config
    layer_config = layer.get_config()
  File "C:\ProgramData\Anaconda3\envs\py352\lib\site-packages\keras\layers\convo
lutional.py", line 466, in get_config
    config = super(Conv2D, self).get_config()
  File "C:\ProgramData\Anaconda3\envs\py352\lib\site-packages\keras\layers\convo
lutional.py", line 223, in get_config
    'activation': activations.serialize(self.activation),
  File "C:\ProgramData\Anaconda3\envs\py352\lib\site-packages\keras\activations.
py", line 92, in serialize
    return activation.__name__
AttributeError: 'Activation' object has no attribute '__name__'

A: I was  able to "solve" the problem by putting the custom activation function in the same file as the call to store the model.  So for example the following fails with the above error message:
# the file network_K.py has the definition of the function lrelu(x):
from network_K import *

model.save_weights("temp.h4")

But the following works fine:
# the file network_K.py has the definition of the function lrelu(x):
from network_K import *

def lrelu(x):
    return tf.maximum(x * 0.2, x)

get_custom_objects().update({'lrelu': Activation(lrelu)})

model.save_weights("temp.h4")

While I am considering this question answered (since I have a work around) I am still curious as to why including with import is not sufficient ....


text:
Q: Question about forms authentication in asp.net I need to secure the pages of an e-commerce website using forms authentication and there's a client requirement that in the login form there would be the "Remember Me" check box that when clicked will keep the user logged in for a month, else he'll have to login each time he visits the site. How can I do this with forms authentication?
Also I am confused about the parameter "createPersistentCookie" of the methods "RedirectFromLoginPage" or "SetAuthCookie", if set to true, it will create a persistent cookie. Persistent for how long?
Thanks

A: You specify the timeout of the cookie in the web.config:
<forms
   name="name"
   loginUrl="URL"
   defaultUrl="URL"
   protection="[All|None|Encryption|Validation]"
   timeout="[MM]"
   path="path"
   requireSSL="[true|false]"
   slidingExpiration="[true|false]">
   enableCrossAppRedirects="[true|false]"
   cookieless="[UseUri|UseCookies|AutoDetect|UseDeviceProfile]"
   domain="domain name"
   ticketCompatibilityMode="[Framework20|Framework40]">
   <credentials>...</credentials>
</forms>

http://msdn.microsoft.com/en-us/library/1d3t3c61.aspx
http://weblogs.asp.net/scottgu/archive/2005/11/08/430011.aspx
If you just want to set the cookie (Authenticate the user) and do your own redirect use the  SetAuthCookie with the "true" parameter.

A: Instead of relying on SetAuthCookie or RedirectFromLogin page you can create the FormsAuthenticationTicket and the cookie explicitly. Here you have control over the timeout of cookie as well as ticket.
FormsAuthenticationTicket Class
Also check this.

redpajama_set_name: RedPajamaStackExchange


text:
Q: mysql query syntax, get data from different tables I got this bookshop website, and I'm trying to generate some statistics about sales. I've got two tables; books and sales_item. They look like this:
books
id  title
1   Cats
2   Dogs
3   Frogs

and sales_item
book_id  qty
1        2
2        2
3        4
3        1
2        1
and so on for hundreds of rows

So what I'm after is a sql query and a html table that tells me that we've sold 2 Cats, 3 Dogs and 5 Frogs. I want to match id from one table with book_id from the other and then add all the qty for each title. I have a feeling that this involves sql JOIN but I'm still not very comfortable with the syntax. Any help would be much appreciated.

A: select b.id, b.title, sum(s.qty) as NumSold
from books b
left outer join sales_item s on b.id = s.book_id
group by b.id, b.title
order by b.title

SQL Fiddle Example

A: select sum(qty), title
from sales_item s
left join books b on s.book_id = b.id
group by s.book_id

SQL Fiddle example

A: You can do this:
$query = ("select sum(qty) as 'Quantity', title from books b left join sales_item s on b.id = s.bookid' group by book_id");

$result = mysql_query($query);

//and this would be the code to print the html table

echo "

Quantity
Pet

";

while($row = mysql_fetch_array($result))
  {
  echo "
";
  echo "" . $row['Quantity'] . "	";
  echo "" . $row['tittle'] . "	";
  echo "
";
  }
echo "
";

Got help from a w3school example.


text:
Q: How to repress scientific notation in factorplot y-axis Simple example below for this issue which I just can't solve.
N.B. Some other Seaborn plotting methods seems to have arguments to repress the exponential form but seemingly not factorplots. I tried some Matplotlib solutions including those suggested in this similar question but none work. Also this is not a dupe of this question. I use factorplots very frequently and ideally want to find a proper solution as opposed to a workaround.
data = {'reports': [4, 24, 31, 2, 3],'coverage': [35050800, 54899767, 57890789, 62890798, 70897871]}
df = pd.DataFrame(data)
df

Produces this dataframe:
    coverage    reports
0   35050800    4
1   54899767    24
2   57890789    31
3   62890798    2
4   70897871    3

And then this Seaborn code:
sns.factorplot(y="coverage", x="reports", kind='bar', data=df, label="Total")

Produces this plot:

Is there a way to get the y axis to display an appropriate numeric scale based on the coverage values?

A: Following line solved the issue for me (addition to Tony's answer)

sns.plt.ticklabel_format(style='plain', axis='y',useOffset=False)

A: It looks like the following line solves the issue:
plt.ticklabel_format(style='plain', axis='y')

Here is the documentation link.


text:
Q: Java Generic Types Mismatch Error I have a class with a constructor signature as follows:
public class MyClass <U>{
    public <T> MyClass(Set<T> data, Function<T,U> func)...
}

That's fine. But I want to overload the constructor, for the case that if you don't provide Function func, it will just use (item)->{return item;}. I've written another constructor that looks like this:
public <T> MyClass(Set<T> data){
    this(
      data,
      (item)->{return item;}
    );
}

This is causing a type mismatch error, because the function I'm providing as an argument to my constructor takes a value of type T, and returns that same value, which should be a U. I don't understand why the algebraic type system doesn't see that in this case U and T are the same and that's ok?

A: The system has to assume that T and U are two different types, since you gave them two different names. But you can just remove the additional generic type from your second ctor like that:
public class MyClass <U>{
    public <T> MyClass(Set<T> data, Function<T,U> func) {...}
    public MyClass(Set<U> data){
        this(
          data,
          (item)->{return item;}
        );
    }
}

A: Let's try to create an instance of your class using the second constructor :
Set<Integer> ints = new HashSet<>();
MyClass<String> myobj = new <Integer> MyClass (ints);

your first constructor would expect a Set<Integer> and a Function<Integer,String> parameters, but your second constructor would try to pass to it a Function<Integer,Integer>. That's the reason your code doesn't pass compilation.
When you define generic classes and methods, they must be valid for any combination of types that can substitute their type parameters.

A: Since you declared two distinct types T and U, compiler reasonably thinks they are different. If they are the same, do not declare T and use only U:
public MyClass(Set<U> data){
    this(
      data,
      (item)->{return item;}
    );
}


text:
Q: Multiple share button on one page or share website comments to facebook while adding I have a website where there is comments systems.  I want to add a comment to facebook while adding a comment to my website.
If it is not possible to add to Facebook while adding to my site is it possible to show share to facebook button with each comments so that clicking on it will share that comment on facebook. May be possible with fb.in?

A: Not 100% sure, but it sounds like you have your own comment system on your web site and that you'd like to auto-publish to FB the comment that someone makes on your own site.
You'd need to implement the Facebook SDK on your web site:

*

*Have your user authorize your site using 'FB.login' with 'publish_stream' permission (see docs).

*In your comment system code, after your user has entered in their comment, you can make a separate call to the Graph API to publish to the user's feed. For example, if using the Facebook Javascript SDK:

Following is the code:
var body = myJustEnteredComment;

FB.api('/me/feed', 'post', { message: body }, function(response)
{
    if (!response || response.error)
    {
        alert('Error!');
    }
});


text:
Q: Google maps API error handling I'm doing some test with the Google Maps Python API. The script is running fine, it loads GPS coordinates from a csv file and returns the address. It uses the googlemaps.reverse_geocode function.
However after a couple of "searches" I get an .....googlemaps.exceptions.TransportError: ('Connection aborted.....
It would be great if the script just continues when it receives an error.
I have no clue how to handle these error messages, the online documentation doesn't seem very clear about this.

A: One possibility is that you're using the free API which limits you to 10 requests per second, and you'r Python interpreter probably works a little bit faster, I would use a queue and a timer to fire up to 10 API requests per second. That would be the correct way to do the job if this is indeed the problem you're facing.
A straightforward solution to your problem would be using try and catch, so when the TransportError exception raises you'll know that you should time.sleep() for a while and retry the last API request before moving on to the next iteration.


text:
Q: Update main window DOM from other window in electron js Let's take a TODO app as example, there is a Main window - A, that will list all of the TODO items and a button 'Add Item'. So when click on the 'Add Item' , it will open up a second window - B, where there is a form for adding item. After the form is submitted, the newly added item will be append to the list in WIndow A.
So the problem here is, how can I update the Item list in WIndow A when when WIndow B form is submitted? I am using react js for the renderer. So, how can react component listen to the changes?

A: Ok, got the answer.
Turn out we can use webContents to send the message to the desired window. And that message can be listened in the window.
#main.js

mainWindow = new BrowserWindow({width: 800, height: 600});
mainWindow.webContents.send('addingitem','...blahblah balh ');

and in render
ipc.on("addingitem", (event, arg)=>{
     //doing the update DOM here.
}


text:
Q: Usar o "Array.prototype.filter" para listar o que faz e o que não faz parte da condição Existe alguma maneira de fazer um filter em um array e recuperar o que faz e o que não faz parte da condição?
Por exemplo o seguinte objeto:
{
  "data": [
    { "item": 1 },
    { "item": 2 },
    { "item": 3 },
    { "item": 4 },
    { "item": 5 },
    { "item": 6 }
  ]
}

Retornar um resultado do tipo:
{
  "conditionTrue": [
    { "item": 1 },
    { "item": 2 },
    { "item": 3 }
 ],
"conditionFalse": [
    { "item": 4 },
    { "item": 5 },
    { "item": 6 }
  ]
}

Filtrando da maneira a seguir consigo obter os elementos do caso verdadeiro e os do caso negativo:

a = {"data":[{"item":1},{"item":2},{"item":3},{"item":4},{"item":5},{"item":6}]};

a.data.filter(el => [1,2,3].includes(el.item));
// [{"item":1},{"item":2},{"item":3}]
a.data.filter(el => ![1,2,3].includes(el.item));
// [{"item":4},{"item":5},{"item":6}]

No entanto, queria fazer somente um filter para obter a condição caso seja verdadeira e caso seja negativa.
Tentei fazer algo como o mostrado a seguir, mas não funcionou.

a = {"data":[{"item":1},{"item":2},{"item":3},{"item":4},{"item":5},{"item":6}]};

a.data.filter(el => {
  return {
    conditionTrue: [1, 2, 3].includes(el.item),
    conditionFalse: ![1, 2, 3].includes(el.item)
  }
});

A: Não. O JavaScript não possui essa implementação nativamente, mas nada impede que você faça uma:

function filter(array, cb) {
  if (typeof cb !== 'function') {
    throw new TypeError('Invalid `cb` argument.');
  }

  const filteredValues = [];
  const removedValues = [];

  for (const [index, value] of array.entries()) {
    const test = !!cb(value, index, array);

    if (test) {
      filteredValues.push(value);
    } else {
      removedValues.push(value);
    }
  }

  return [filteredValues, removedValues];
}

// Irá remover os ímpares, mantendo somente os pares:
const [filteredValues, removedValues] = filter(
  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
  (el) => el % 2 === 0
);

console.log('Valores mantidos:', filteredValues);
console.log('Valores removidos:', removedValues);

Essa é somente uma das formas de se fazer isso. Use como ideia para criar algo melhor ainda. :)

A: Este exemplo não usa o filter(), usa o reduce():

let a = {
    "data":
        [
            { "item": 1 },
            { "item": 2 },
            { "item": 3 },
            { "item": 4 },
            { "item": 5 },
            { "item": 6 }
        ]
};

let sample = [1, 2, 3];

let result = a.data.reduce((acc, cur) => {
    let key = (sample.includes(cur.item)) ? 'conditionTrue' : 'conditionFalse';
    acc[key] = acc[key] || [];
    acc[key].push(cur);
    return acc;
}, {});

console.log(result);


text:
Q: Jquery, How to unselect all radio button in radio group Anyone know how to unselect all radio buttons in a radio group ?
HTML:

              How regulary do you employ people to help cultivate your land?

             <fieldset data-role="controlgroup" data-type="vertical" id="emptim">

              <input name="emptim" id="radio1" value="fromtimetotime" type="radio" openmrs-valuecoded="" />
               From time to time

              <input name="emptim" id="radio2" value="allthetime" type="radio" openmrs-valuecoded="" />
              All the time

              <input name="emptim" id="radio3" value="dontknow" type="radio" openmrs-valuecoded="" />
               Don't know
            </fieldset>

JQuery side:
$('input:radio[name=emptim]:checked').prop('checked', false); // doesn't work

I'm certainly missing something basic, but I can't figure out what is the problem.
First, I check Yes and then check a value of the second radio group :

Then, I check No to hide the second radio group:

Then, If I click on next, I get the value of what I've checked (but I checked no previously, so here I don't want an alert, I want the radioButton "From time to time" to be unchecked) :

Finally, if I come back, nothing happend :

A: This should do it. Notice the refresh option at the end to force the controlgroup to be updated.
An additional benefit of this method is that it targets a specific radio group by name, rather than all radio controls on a page.
$('input:radio[name=emptim]:checked').prop('checked', false).checkboxradio("refresh");

A: $('input:radio[name=indicatorType]').each(function () { $(this).prop('checked', false); });

Alternative solution for making 'unchecked' whole radio buttons of a radio group('indicatorType' for above code sample).

A: You can give them a classname and try:
$('.classname').prop('checked', false);

When you use an older version of jQuery than 1.6 it has to be:
 $('<selector>').attr('checked', false);

EDIT :
Call the method .checkboxradio("refresh"); has also worked for me.

A: I made a non-display radio button and called that via my PHP. You could use jquery to select the hidden button. I couldn't get the solutions here working, so I used some PHP, as I had to call the value from the DB. To help anyone, the solution I used is:
<input type="radio" id="test" value="" class = "timescale" name="timescale_radio_buttons" style="display: none" <?php $x = ((empty($gigObject->getTimescale())) || ($gigObject->getTimescale() == 'Blank')) ? 'checked="checked"' : ''; echo $x; ?>>

A: The prop doesnt works for me, bu this works perfectly :
('input:radio[name="RadioName"]').each(function () { $(this).attr('checked', false); });


text:
Q: How to prevent two NOW() columns updated at the same time when update a NOW() for one column I have  a table needs two different current times.
First, I have an insert procedure for insert actionnumber,  msgSentFrom_F_ID, msgSentTo_M_ID, and sentDate.
Second, an update procedure for updating respondDate.
my problem is, when I updated respondDate, the sentDate would be updated to the same time when I updated respondDate. Where did I do wrong?
(my purpose is i want the sentDate to be the current time when i insert, and another current time when i update respondDate.)

CREATE TABLE IF NOT EXISTS actions (
  actionnumber INT AUTO_INCREMENT PRIMARY KEY,
  msgSentFrom_F_ID INT,
  msgSentTo_M_ID INT,
  sentDate TIMESTAMP,
  respondDate TIMESTAMP NULL,
  FOREIGN KEY (msgSentFrom_F_ID)
    REFERENCES femaleUsers(femaleuserId)
  FOREIGN KEY (msgSentTo_M_ID)
    REFERENCES maleUsers(maleuserId)
);

DELIMITER //
create procedure (param_F_ID INT,param_M_ID INT,Sdate TIMESTAMP)
  BEGIN
  INSERT INTO actions (msgSentFrom_F_ID, msgSentTo_M_ID, sentDate)
    VALUES (param_F_ID,param_M_ID,Now());
  END; //
DELIMITER ;

CALL insert_actions ('5','5',NOW());

DELIMITER //
create procedure update_respondDate (param_ActionNum INT,
    param_respondDate TIMESTAMP)
  BEGIN
  UPDATE actions set respondDate = param_respondDate
  WHERE  actionnumber = param_ActionNum;
  END; //
DELIMITER ;

CALL update_respondDate('6',NOW());

A: It sounds like you have the system variable explicit_defaults_for_timestamp disabled. The documentation explains the result of this:

If the explicit_defaults_for_timestamp system variable is disabled, the first TIMESTAMP column has both DEFAULT CURRENT_TIMESTAMP and ON UPDATE CURRENT_TIMESTAMP if neither is specified explicitly. To suppress automatic properties for the first TIMESTAMP column, use one of these strategies:

*

*Enable the explicit_defaults_for_timestamp system variable. In this case, the DEFAULT CURRENT_TIMESTAMP and ON UPDATE CURRENT_TIMESTAMP clauses that specify automatic initialization and updating are available, but are not assigned to any TIMESTAMP column unless explicitly included in the column definition.

*Alternatively, if explicit_defaults_for_timestamp is disabled, do either of the following:

*

*Define the column with a DEFAULT clause that specifies a constant default value.

*Specify the NULL attribute. This also causes the column to permit NULL values, which means that you cannot assign the current timestamp by setting the column to NULL. Assigning NULL sets the column to NULL, not the current timestamp. To assign the current timestamp, set the column to CURRENT_TIMESTAMP or a synonym such as NOW().

Since sentDate is the first TIMESTAMP column in the table, it's automatically set to the current time whenever you make any change to the row.


text:
Q: Extract version number from file in shell script I'm trying to write a bash script that increments the version number which is given in
{major}.{minor}.{revision}

For example.
1.2.13

Is there a good way to easily extract those 3 numbers using something like sed or awk such that I could increment the {revision} number and output the full version number string.

A: Awk makes it quite simple:
echo "1.2.14" | awk -F \. {'print $1,$2, $3'} will print out 1 2 14.
flag  -F specifies separator.
If you wish to save one of the values:
firstVariable=$(echo "1.2.14" | awk -F \. {'print $1'})

A: $ v=1.2.13
$ echo "${v%.*}.$((${v##*.}+1))"
1.2.14

$ v=11.1.2.3.0
$ echo "${v%.*}.$((${v##*.}+1))"
11.1.2.3.1

Here is how it works:
The string is split in two parts.

*

*the first one contains everything but the last dot and next characters: ${v%.*}

*the second one contains everything but all characters up to the last dot: ${v##*.}
The first part is printed as is, followed by a plain dot and the last part incremented using shell arithmetic expansion: $((x+1))

A: I use the shell's own word splitting; something like
oIFS="$IFS"
IFS=.
set -- $version
IFS="$oIFS"

although you need to be careful with version numbers in general due to alphabetic or date suffixes and other annoyingly inconsistent bits.  After this, the positional parameters will be set to the components of $version:
$1 = 1
$2 = 2
$3 = 13

($IFS is a set of single characters, not a string, so this won't work with a multicharacter field separator, although you can use IFS=.- to split on either . or -.)

A: Pure Bash using an array:
version='1.2.33'
a=( ${version//./ } )                   # replace points, split into array
((a[2]++))                              # increment revision (or other part)
version="${a[0]}.${a[1]}.${a[2]}"       # compose new version

A: I prefer "cut" command for this kind of things
major=`echo $version | cut -d. -f1`
minor=`echo $version | cut -d. -f2`
revision=`echo $version | cut -d. -f3`
revision=`expr $revision + 1`

echo "$major.$minor.$revision"

I know this is not the shortest way, but for me it's simplest to understand and to read...

A: Inspired by the answer of jlliagre I made my own version which supports version numbers just having a major version given. jlliagre's version will make 1 -> 1.2 instead of 2.
This one is appropriate to both styles of version numbers:
function increment_version()
    local VERSION="$1"

    local INCREMENTED_VERSION=
    if [[ "$VERSION" =~ .*\..* ]]; then
        INCREMENTED_VERSION="${VERSION%.*}.$((${VERSION##*.}+1))"
    else
        INCREMENTED_VERSION="$((${VERSION##*.}+1))"
    fi

    echo "$INCREMENTED_VERSION"
}

This will produce the following outputs:
increment_version 1         -> 2
increment_version 1.2       -> 1.3
increment_version 1.2.9     -> 1.2.10
increment_version 1.2.9.101 -> 1.2.9.102

A: Yet another shell way (showing there's always more than one way to bugger around with this stuff...):
$ echo 1.2.3 | ( IFS=".$IFS" ; read a b c && echo $a.$b.$((c + 1)) )
1.2.4

So, we can do:
$ x=1.2.3
$ y=`echo $x | ( IFS=".$IFS" ; read a b c && echo $a.$b.$((c + 1)) )`
$ echo $y
1.2.4

A: Small variation on fgm's solution using the builtin read command to split the string into an array. Note that the scope of the IFS variable is limited to the read command (so no need to store & restore the current IFS  variable).
version='1.2.33'
IFS='.' read -r -a a <<<"$version"
((a[2]++))
printf '%s\n' "${a[@]}" | nl
version="${a[0]}.${a[1]}.${a[2]}"
echo "$version"

See: How do I split a string on a delimiter in Bash?

A: I'm surprised no one suggested grep yet.
Here's how to get the full version (not limited to the length of x.y.z...) from a file name:
filename="openshift-install-linux-4.12.0-ec.3.tar.gz"
find -name "$filename" | grep -Eo '([0-9]+)(\.?[0-9]+)*' | head -1
# 4.12.0


text:
Q: ng-view not loading site on Android Chrome App This question may have been asked before. But here goes:
My website is http://thecheeknee.com.
The site basic structure is as follows:
`index.html
js|-app.js
js|ctrls|pageLoad.js  -common controller for all pages
js|srvc|Datamap.js
templates/-about.html, etc`

The HTML basic view is as shown below:
<section ui-view></section>

The UI router angular code is as follows:
angular
.module('app',[
    'ui.router',
    'ngStorage'
    ])
.config(['$urlRouterProvider','$stateProvider',function($urlRouterProvider, $stateProvider){
    $urlRouterProvider.otherwise('/');
    $stateProvider
        .state('home',{
            url:'/',
            templateUrl:'templates/home.html',
    controller:'pageLoad'
        })

The controller is very basic.
angular
.module('app')
.controller('pageLoad',[ '$scope', 'Datamap', function($scope, Datamap){
    $scope.title = "thecheeknee";
    //$scope.$storage = $localStorage;
    //$scope.$storage.counter = $scope.$storage.counter+1 || 0;
    Datamap.getData().then(function(response){

  $scope.datamap = response.data;
});

The Data map service is as follows:
angular.module('app')
  .factory('Datamap', function($http) {
    //debugger;
    return{
      getData: function(){
        return $http.get('data/data.json',{ cache: true});
      }
    }
  });

The site works perfectly on the desktop across multiple browsers. But Chrome App on Android seems to load a blank page.
(I had designed the site to be responsive and had tested the UI thoroughly using Chrome's browser tool)
On observing, I noticed that the browser adds a #!/ and loads the view into the page. On the mobile browser however, it seems to be stopping at the site name itself (#!/ is not being added). So I assume the UI router is unable to load the route into the page.
I am relatively new to Angular, so is there anything minor I am missing out here?
Full source code at: https://github.com/thecheeknee/sitebase.git


text:
Q: WordPress: How to retrieve custom field data from the page? I'm trying to retrieve the value from a Custom field as below. It doesn't seem to get any value. Please point out the mistakes in it.
<?php
$gift_text_lines = get_sub_field( 'gift_text_lines' );
if ($gift_text_lines > 1) { ?>
    .fluentform .ff-el-image-holder {
        min-height: 264px;
        margin-bottom: 5px;
    }
<?php
}
?>

Custom fields are as seen in the image below.

A: You can try out :
$gift_text_lines = get_field( 'gift_text_lines' );

A: Can you try get_field if get_sub_field not work for you.
if(in_array('hide_footer_signup_for', get_sub_field('gift_text_lines')))
{
        echo 'some html';
}


text:
Q: In a field why does the multiplicative identity have an additive inverse, whereas the additive identity doesn't have a multiplicative inverse? Let $\langle K, +, * \rangle$ be our field. By definition, we know that every non-zero element, i.e every element except the additive identity, has an multiplicative inverse in the field, and we also do know that every element, including the multiplicative identity, has a additive inverse in the field.
However, giving the fact that additive and multiplicative operations are just binary operations, and they are just represented by different symbols, I would expect both addition and the multiplication to behave in the same way in the sense that if multiplicative identity has an additive inverse, so should the additive inverse to have a multiplicative inverse, i.e a symmetry between them.
So my question is exactly which property of those binary operations or the proper of the field is corresponds to this unsymmetrical behaviour ?

A: As I said in the comments, the symmetry is broken because of the distributivity, $a(b+c) = ab + ac$, which does not hold symmetrically (indeed $a+bc = (a+b)(a+c)$ is not true in general).
This identity, the group axioms for $+$ and the fact that $0\neq 1$ altogether imply that $0$ has no multiplicative inverse ($0a = (0+0)a = 0a + 0a$ and so $0a=0$, so unless $0=1$, $0$ has no inverse)
These axioms are there to generalize $\mathbb{Z},\mathbb{Q}$ (integral domains, or more generally rings with more than one element), and are therefore "natural", because in particular distributivity is essential in those structures.

A: It's because $$0r=(r-r)r=r^2-r^2=0,$$ so if $0r=1,$ we would have $0=1$, a contradiction.


text:
Q: SQL Server : Sum over a field changed after adding a LEFT JOIN I have a sample query like this:
;WITH view1 AS (
    SELECT 1 AS id, 1 AS pId, 'a' AS pName, 1 AS kind
    UNION ALL SELECT 2, 1, 'a', 2
    UNION ALL SELECT 3, 1, 'a', 1
    UNION ALL SELECT 4, 2, 'b', 2
    UNION ALL SELECT 5, 2, 'b', 2
    UNION ALL SELECT 6, 2, 'b', 1
), view2 AS (
    SELECT 1 AS id, 1 AS pId, 'a' AS pName, 5 AS price
    UNION ALL SELECT 3, 3, 'c', 3
    UNION ALL SELECT 6, 2, 'b', 3
)
SELECT
    ISNULL(v2.pId, v1.pId) AS pId,
    ISNULL(v2.pName, v1.pName) AS pName,
    SUM(CASE v1.kind WHEN 1 THEN 1 ELSE 0 END) AS countKind1,
    SUM(v2.price) AS sumPrice
FROM
    view1 v1
    LEFT OUTER JOIN
    view2 v2 ON v1.id = v2.id
GROUP BY
    ISNULL(v2.pId, v1.pId),
    ISNULL(v2.pName, v1.pName)

Its result is:
pId | pName | countKind1 | sumPrice
----+-------+------------+-----------
1   | a     | 1          | 5
2   | b     | 1          | 3
3   | c     | 1          | 3

But I wanted this result after adding ISNULLs and sumPrice:
pId | pName | countKind1 | sumPrice
----+-------+------------+-----------
1   | a     | 2          | 5
2   | b     | 1          | 3
3   | c     | 0          | 3

A: Your query looks a bit weird. I can create a few ways of getting desired result, but I'm not sure what's the meaning behind your data. In general, I'd always advice group your data as early as you can, so you probably could group view1 and then join by pId.
Here's the query which gives your results, though
;WITH view1 AS (
    SELECT 1 AS id, 1 AS pId, 'a' AS pName, 1 AS kind
    UNION ALL SELECT 2, 1, 'a', 2
    UNION ALL SELECT 3, 1, 'a', 1
    UNION ALL SELECT 4, 2, 'b', 2
    UNION ALL SELECT 5, 2, 'b', 2
    UNION ALL SELECT 6, 2, 'b', 1
), view2 AS (
    SELECT 1 AS id, 1 AS pId, 'a' AS pName, 5 AS price
    UNION ALL SELECT 3, 3, 'c', 3
    UNION ALL SELECT 6, 2, 'b', 3
), cte1 as (
SELECT
    ISNULL(v2.pId, v1.pId) AS pId,
    ISNULL(v2.pName, v1.pName) AS pName,
    SUM(v2.price) AS sumPrice
FROM
    view1 v1
    LEFT OUTER JOIN
    view2 v2 ON v1.id = v2.id
GROUP BY
    ISNULL(v2.pId, v1.pId),
    ISNULL(v2.pName, v1.pName)
), cte2 as (
    select pName, sum(case when kind = 1 then 1 else 0 end) as countKind1
    from view1
    group by pName
)
select
    c1.pId,
    c1.pName,
    isnull(c2.countKind1, 0) as countKind1,
    c1.sumPrice
from cte1 as c1
    left outer join cte2 as c2 on c2.pName = c1.pName

sql fiddle demo

A: As per @Roman's comment, you'll want to join on pID.
You'll also need to change the JOIN to a FULL OUTER join since view1 has no 'c's
Finally, SUM(Price) looks wrong - if this is price per 'each', you'll want to use a different aggregate, like Max:
;WITH view1 AS (
    SELECT 1 AS id, 1 AS pId, 'a' AS pName, 1 AS kind
    UNION ALL SELECT 2, 1, 'a', 2
    UNION ALL SELECT 3, 1, 'a', 1
    UNION ALL SELECT 4, 2, 'b', 2
    UNION ALL SELECT 5, 2, 'b', 2
    UNION ALL SELECT 6, 2, 'b', 1
), view2 AS (
    SELECT 1 AS id, 1 AS pId, 'a' AS pName, 5 AS price
    UNION ALL SELECT 3, 3, 'c', 3
    UNION ALL SELECT 6, 2, 'b', 3
)
SELECT
    ISNULL(v2.pId, v1.pId) AS pId,
    ISNULL(v2.pName, v1.pName) AS pName,
    SUM(CASE WHEN v1.kind = 1 THEN 1 ELSE 0 END) AS countKind1,
    MAX(v2.price) AS maxPrice
FROM
    view1 v1
    FULL OUTER JOIN
    view2 v2 ON v1.pid = v2.pid
GROUP BY
    ISNULL(v2.pId, v1.pId),
    ISNULL(v2.pName, v1.pName)

SqlFiddle here

A: I found a way for with using a inline select:
SELECT
    ISNULL(v2.pId, v1.pId) AS pId,
    ISNULL(v2.pName, v1.pName) AS pName,
    (SELECT COUNT(*) FROM view1 vi WHERE vi.kind = 1 AND vi.pId = ISNULL(v2.pId, v1.pId)) AS countKind1,
    SUM(v2.price) AS sumPrice
FROM
    view1 v1
    LEFT OUTER JOIN
    view2 v2 ON v1.id = v2.id
GROUP BY
    ISNULL(v2.pId, v1.pId),
    ISNULL(v2.pName, v1.pName)

And this one:
SELECT
    ISNULL(v2.pId, v1.pId) AS pId,
    ISNULL(v2.pName, v1.pName) AS pName,
    ISNULL(tc.Counts, 0) AS countKind1,
    SUM(v2.price) AS sumPrice
FROM
    view1 v1
    LEFT OUTER JOIN
    view2 v2 ON v1.id = v2.id
    LEFT OUTER JOIN
    (SELECT vi.pId, COUNT(*) Counts FROM view1 vi WHERE vi.kind = 1 GROUP BY vi.pId) AS tc ON tc.pId = ISNULL(v2.pId, v1.pId)
GROUP BY
    ISNULL(v2.pId, v1.pId),
    ISNULL(v2.pName, v1.pName),
    tc.Counts


text:
Q: Rudin: set of $n$ tuples are countable I am trying to work through Theorem 2.13 in Rudin, which states;

Let $A$ be a countable set, and let $B_n$ be the set of all $n$-tuples $(a_1, \ldots, a_n)$ where $a_k \in A$) ($k = 1, \ldots, n$), and the elements $a_1, \ldots, a_n$ need not be distinct. Then $B_n$ is countable.

Rudin proves it by induction on $n$. The base case is rather obvious since $B_1 = A$ and $A$ is countable by assumption. Supposing $B_{n-1}$ is countable, where
$$B_{n-1} := \{(a_1, \ldots, a_{n-1} \mid a_i \in A\},$$
we consider $B_n$, where
$$B_n := \{(a_1, \ldots, a_{n-1}, a_n) \mid a_i \in A\}.$$
This is where my confusion comes in, and it is mostly a notational issue. Rudin instead writes $B_n$ as the set of order pairs $(b,a)$ where $b \in B_{n-1}$ and $a \in A$. This is, in effect, an $(n-1)$-tuple within an $n$-tuple,i.e.,
$$((a_1, \ldots, a_{n-1}), a)$$
if in fact we were considering an element of $B_{n-1}$.
My question is: why can he call it $(b,a)$? Is this just an abuse of notation? The argument for why this establishes that $B_n$ is countable makes sense to me, and even if the solution is just that this is a reasonable way to list it, I would be fine with that. But the notion of calling this an ordered pair with element $b \in B_{n-1}$ is what is tripping me up.

A: Yes it is an abuse of notation. But this can be justified since there exists a bijection $((a_1,\cdots,a_{n-1}),a)\mapsto (a_1,\cdots,a_{n-1},a)$. This step is just omitted since it is too trivial.


text:
Q: Not receiving any sign up mail, when user registers... Both admin & user Not receiving any sign up mail, when user registers... Both admin & user .....
https://newsangels.com/manra?action=register
But user is registered, but no email sending...
However, If I try signup using the theme signup form which is at the top of site, it works then
I'm using following code as mu-plugin:
Is it causing the issue?
<?php
/*
Plugin Name: Functions
Description: Custom functions.php coding
Author: UsmanSwift
Version: 1.0

*/

#RankMaths#
add_filter( "rank_math/snippet/rich_snippet_article_entity", function( $entity ) {
    if ( in_category('News') ) {
    $entity['@type'] = 'NewsArticle';
}
 return $entity;
});

#Crunchify Remove Head Extra Codes

// *********** Crunchify Tips - Clean up WordPress Header START ******* //
function crunchify_remove_version() {
    return '';
}
add_filter('the_generator', 'crunchify_remove_version');

remove_action('wp_head', 'rest_output_link_wp_head', 10);
remove_action('wp_head', 'wp_oembed_add_discovery_links', 10);
remove_action('template_redirect', 'rest_output_link_header', 11, 0);

remove_action ('wp_head', 'rsd_link');
remove_action( 'wp_head', 'wlwmanifest_link');
remove_action( 'wp_head', 'wp_shortlink_wp_head');

function crunchify_cleanup_query_string( $src ){
    $parts = explode( '?', $src );
    return $parts[0];
}
add_filter( 'script_loader_src', 'crunchify_cleanup_query_string', 15, 1 );
// ******************** Clean up WordPress Header END ********************** //

#Crunchify Remove Comments and WP Bar

add_filter( 'pre_comment_content', 'esc_html' );  // remove html from comemnt

//add_filter('show_admin_bar', '__return_false'); // disable admin bar

//Author - Show Own Posts
function posts_for_current_author($query) {
    global $pagenow;

    if( 'edit.php' != $pagenow || !$query->is_admin )
        return $query;

    if( !current_user_can( 'edit_others_posts' ) ) {
        global $user_ID;
        $query->set('author', $user_ID );
    }
    return $query;
}
add_filter('pre_get_posts', 'posts_for_current_author');

//Author - Submit For Review
//function remove_author_publish_posts(){

    // $wp_roles is an instance of WP_Roles.
//    global $wp_roles;
 //   $wp_roles->remove_cap( 'author', 'publish_posts' );
//}

//add_action( 'init', 'remove_author_publish_posts' );

//Author - Prevent Own Posts Deletion
//function wpb_change_author_role(){
//    global $wp_roles;
//    $wp_roles->remove_cap( 'author', 'delete_posts' );
//    $wp_roles->remove_cap( 'author', 'delete_published_posts' );

//}
//add_action('init', 'wpb_change_author_role');

// Revert (Author - Prevent Own Posts Deletion)

//Remove Above Code and Add This

//function wpb_change_author_role(){
//    global $wp_roles;
//    $wp_roles->add_cap( 'author', 'delete_posts' );
//    $wp_roles->add_cap( 'author', 'delete_published_posts' );
//
//}
//add_action('init', 'wpb_change_author_role');

// Load Essential Fonts Awesome

add_filter( 'infophilic_fontawesome_essentials', 'infophilic_fontawesome_essentials' );
function infophilic_fontawesome_essentials()
{
   return true;
}

// Removing Emojis

//add_action( 'init', 'infophilic_disable_wp_emojicons' );
//function infophilic_disable_wp_emojicons()
//{
    // all actions related to emojis

//    remove_action( 'admin_print_styles', 'print_emoji_styles' );
//    remove_action( 'wp_head', 'print_emoji_detection_script', 7 );
//    remove_action( 'admin_print_scripts', 'print_emoji_detection_script' );
//    remove_action( 'wp_print_styles', 'print_emoji_styles' );
//    remove_filter( 'wp_mail', 'wp_staticize_emoji_for_email' );
//    remove_filter( 'the_content_feed', 'wp_staticize_emoji' );
//    remove_filter( 'comment_text_rss', 'wp_staticize_emoji' );
//}

// Remove Devicepx script

function jeherve_dequeue_devicepx() {
   wp_dequeue_script( 'devicepx' );
}
add_action( 'wp_enqueue_scripts', 'jeherve_dequeue_devicepx' );

// Remove WP embed script

function infophilic_stop_loading_wp_embed() {
   if (!is_admin()) {
      wp_deregister_script('wp-embed');
}
}
add_action('init', 'infophilic_stop_loading_wp_embed');

// Preload Newspaper fonts for responsive theme (main theme)

function dns_prefetch_responsive() {

    echo "<link href='https://newsangels.com/wp-content/themes/Newspaper/images/icons/newspaper.woff?19' rel='preload' as='font' type='font/woff' crossorigin>";
}
add_action( 'wp_head', 'dns_prefetch_responsive', 0 );

/**
 * Disable access to Media Images for Author
 */
function my_authored_content($query) {

//get current user info to see if they are allowed to access ANY posts and pages
$current_user = wp_get_current_user();
// set current user to $is_user
$is_user = $current_user->user_login;

//if is admin or 'is_user' does not equal #username
if (!current_user_can('manage_options')){
    //if in the admin panel
    if($query->is_admin) {

        global $user_ID;
        $query->set('author',  $user_ID);

    }
    return $query;
}
return $query;
}
add_filter('pre_get_posts', 'my_authored_content');

//Hide Menu Options in Admin Section
//add_action('admin_menu','wf_cli_remove_admin_menu');
//function wf_cli_remove_admin_menu()
//{
//    remove_menu_page('index.php');
//    remove_menu_page('separator1');
//    remove_menu_page('separator2');
//    remove_menu_page('edit-comments.php');
//    remove_menu_page('edit.php?post_type=tdb_templates');
//    remove_menu_page('tools.php');
//}

        add_action( 'admin_menu', 'wf_cli_remove_admin_menu' );
        function wf_cli_remove_admin_menu() {
            $wf_user    = wp_get_current_user();
            $wf_roles   = array( 'contributor', 'author' );
            if( array_intersect( $wf_roles, $wf_user->roles ) ) :
                remove_menu_page( 'index.php' );
                remove_menu_page( 'separator1' );
                remove_menu_page( 'separator2' );
                remove_menu_page( 'edit-comments.php' );
                remove_menu_page( 'edit.php?post_type=tdb_templates' );
                remove_menu_page( 'tools.php' );
            endif;
        }

/**
 * This function will connect wp_mail to your authenticated
 * SMTP server. Values are constants set in wp-config.php
 */
add_action( 'phpmailer_init', 'send_smtp_email' );
function send_smtp_email( $phpmailer ) {
    $phpmailer->isSMTP();
    $phpmailer->Host       = SMTP_HOST;
    $phpmailer->SMTPAuth   = SMTP_AUTH;
    $phpmailer->Port       = SMTP_PORT;
    $phpmailer->Username   = SMTP_USER;
    $phpmailer->Password   = SMTP_PASS;
    $phpmailer->SMTPSecure = SMTP_SECURE;
    $phpmailer->From       = SMTP_FROM;
    $phpmailer->FromName   = SMTP_NAME;
}

//Remove Comments from Admin bar
function my_admin_bar_render() {
    global $wp_admin_bar;
    $wp_admin_bar->remove_menu('comments');
}
add_action( 'wp_before_admin_bar_render', 'my_admin_bar_render' );

?>


text:
Q: spawning enemies in unity I want to spawn enemies from different and more than 50+ positions.
I tried this code for spawning like 15 positions but what can I do for like 100 posiitons? any shortway for it?
I tried to use s[randomIndex] but it doesnt defined so I got an error.
`
 switch (randomIndex)
            {
                case 0:
                    spawnedEnemy.transform.position = s0.position;
                    break;

                case 1: spawnedEnemy.transform.position = s1.position;
                    break;

                case 2:   spawnedEnemy.transform.position = s2.position;
                    break;

                case 3: spawnedEnemy.transform.position = s3.position;
                    break;

                case 4: spawnedEnemy.transform.position = s4.position;
                    break;

                case 5:
                    spawnedEnemy.transform.position = s5.position;
                    break;

                case 6:
                    spawnedEnemy.transform.position = s6.position;
                    break;

                case 7:
                    spawnedEnemy.transform.position = s7.position;
                    break;

                case 8:
                    spawnedEnemy.transform.position = s8.position;
                    break;

                case 9:
                    spawnedEnemy.transform.position = s9.position;
                    break;

                case 10:
                    spawnedEnemy.transform.position = s10.position;
                    break;

                case 11:
                    spawnedEnemy.transform.position = s11.position;
                    break;

                case 12:
                    spawnedEnemy.transform.position = s12.position;
                    break;

                case 13:
                    spawnedEnemy.transform.position = s13.position;
                    break;

                case 14:
                    spawnedEnemy.transform.position = s14.position;
                    break;

`

A: I think you may be approaching this in a non Unity-centric way.
Let's think about what you're trying to do. It seems like you need a bunch of spawn points, and randomly select one of them. Then spawn an enemy at that location.
I would create a very simple MonoBehaviour that we use as basically just a tag. It's an empty Monobehaviour script called SpawnPoint.
Now, let's create a spawn point by creating an empty game object in the scene, and adding our new script to it. Make this a prefab so you can reuse it.
Duplicate it 100 times, and move them around in your scene to the correct locations.
Now that you have your spawn points, we need to gather them in a list, and choose a random one. The following is pseudocode but should be enough to get you started:
public class RandomSpawner() : Monobehaviour {

    List<SpawnPoint> _spawnPoints;

    void Awake() {

       // Gathers all spawn points in your scene. There are more optimized ways to do this. but this is a good start.
       _spawnPoints = FindObjectsOfType<SpawnPoint>();
    }

    public void Spawn() {

        // generate some random index from your list

        SpawnPoint randomSpawnPoint = _spawnPoints[index];

        GameObject enemy = Instantiate(enemyPrefab);
        enemy.transform.position = randomSpawnPoint.transform.position;

    }

}

Hope that helps you get started.
In my experience, if you're using a switch statement and there are more than about 4 options, it usually means you need to think about the problem in a different way.


text:
Q: Is it possible to have Delphi auto-generate event-support code for an imported OLE/COM type library? I'm trying to generate _TLB import units for Outlook 2003, 2007 and 2010 (and also other OLE servers) analogous to the ones bundled with Delphi for Outlook 2000 and 2002. However, I couldn't get the type library importer to also generate the code for capturing events from the OLE servers that is found in the bundled units. The option to "Generate component wrappers" only creates wrappers for servers that are directly instantiatable but not for objects that are only returned via methods of other objects like TInspector, TExplorer, etc.
I could of course create the event handling code myself but that would be really tedious work.
Does anyone know if the importer contained with Delphi 2010 (tlibimp.exe) can be tweaked to generate that code? I really doubt that back in the day Borland created the existing Outlook2000.pas and OutlookXP.pas units manually...
Are there maybe any other tools around that can do this?

A: Good question! I never noticed that those components were not created (I only use Word_TLB). After playing a bit with tlibimp I found out that you need the -Yc+ flag. Probably all ignore flags are default on.
NB: this is on Delphi 7 with tlibimp.exe version 7.0.4.453


text:
Q: Removing a route Since I used scaffolding to create my Deposit model,
resources :deposits

generates a bunch of routes. i want to be able to delete some of those routes for particular models. For example I do not want a "deposts/23/edit" route. I know I can do a redirect in the controller or do a
match "deposits/:id/edit", :to => "deposit#new"

which just shows the new deposit page but does not change the url on the browser.
is there a way to completely remove a certain action through declaring something in the rails routes.rb file. so that particular actions are just not accessible.

A: resources :deposits, :only => { :create, :new }

A: I reccomend looking over the Ruby on Rails Guide for Routing it discuses important core concepts and presents you with some good information on how routes are wired the way they are.
If you still wish to remove the edit route you will find a useful part of the guide here the code you need is listed below:
resources :deposits, :except => :edit

A: resources :deposits, :except => :edit


text:
Q: Duo Security Auth Trying to auth to Duo Security admin API but stuck in their way of authenticating. Reference: https://duo.com/docs/adminapi#authentication
They have a function that says it would be used to construct the "Authorization" and "Date" headers. Does anyone know how to go about getting this started?
import base64, email, hmac, hashlib, urllib

def sign(method, host, path, params, skey, ikey):
    """
    Return HTTP Basic Authentication ("Authorization" and "Date") headers.
    method, host, path: strings from request
    params: dict of request parameters
    skey: secret key
    ikey: integration key
    """

    # create canonical string
    now = email.Utils.formatdate()
    canon = [now, method.upper(), host.lower(), path]
    args = []
    for key in sorted(params.keys()):
        val = params[key]
        if isinstance(val, unicode):
            val = val.encode("utf-8")
        args.append(
            '%s=%s' % (urllib.quote(key, '~'), urllib.quote(val, '~')))
    canon.append('&'.join(args))
    canon = '\n'.join(canon)

    # sign canonical string
    sig = hmac.new(skey, canon, hashlib.sha1)
    auth = '%s:%s' % (ikey, sig.hexdigest())

    # return headers
    return {'Date': now, 'Authorization': 'Basic %s' % base64.b64encode(auth)}


text:
Q: What are your thoughts on method scoped constants? For example:
public void doSomething() {

    final double MIN_INTEREST = 0.0;

    // ...
}

Personally, I would rather see these substitution constants declared statically at the class level.
I suppose I'm looking for an "industry viewpoint" on the matter.

A: I've used this method scoped constants myself but every so often a colleague will down mod it during code reviews. Again, these colleagues are not into reading/writing open source but they are used to enterprise software.
I tell them that it does NOT make sense to use a class level constant if it is used within a single method but I've found more than 1 colleague insisting that it be moved UP.
I usually comply since I'm not so rigid unless it affects readability and/or performance.

A: I would think that you should only put them at the class level if they are used by multiple methods.  If it is only used in that method then that looks fine to me.

A: Information hiding and modularity are key principles, and narrow scoping is better information hiding. If the constant is only needed by the method, the hiding is good. If and when the constant is useful elsewhere, bring it out to a broader scope, but only as broadly as needed.
You are probably concerned because this is a constant, and therefore, it may seem to belong to some global properties table. Maybe it does. Maybe it doesn't. Your concern is valid, but there is no one best place for all constants.

A: My starting position is that every variable or constant should be declared/initialized as close to its first use as possible/practical (i.e. don't break a logical block of code in half, just to declare a few lines closer), and scoped as tightly as possible. -- Unless you can give me a damn good reason why it should be different.
For example, a method scoped final won't be visible in the public API.  Sometimes this bit of information could be quite useful to the users of your class, and should be moved up.
In the example you gave in the question, I would say that MIN_INTEREST is probably one of those pieces of information that a user would like to get their hands on, and it should be scoped to the class, not the method.  (Although, there is no context to the example code, and my assumption could be completely wrong.)

A: Technically, there is no such thing as a "method scoped constant" in Java.  What you are referring to is simply a final local variable; it is created an destroyed with each method invocation.
http://www.java-tips.org/java-se-tips/java.lang/how-do-i-declare-a-constant-in-java.html

A: I have a different take on this: IMHO its better to place them at file/class scope especially if you are working in teams for this reason: say you start with a small piece of code...
public void doSomething() {

  final double MIN_INTEREST = 0.0;

  // ...
}

and other members of you team expand the class with whole bunch of methods and now the class is a wonderful 500 lines/50 methods giant class. Imagine the experience of an engineer who is trying to adding a new method with a constant, they will have to 1 scan the whole class looking for constants that match their need, 2 move the constant to class scope hoping that there are no conflicts with existing code and 3 also add their method.
If you instead add all constants at file/class scope to begin with, engineers have a 1 single place to look for existing constants and, 2 derive some constants from others where it makes sense. (for example if you have a constant for pi you may also want to define a new constant with a value of pi/2).

A: The reason why you can define a final variable at a class level or method (local) level it's because you can override the global static constant inside the (local) method.
Example:
public class Test {

    final double MIN_INTEREST = 0.0;

    /**
     * @param args
     */
    public static void main(String[] args) {

        Test test = new Test();

        test.doSomethingLocal();
        test.doSomethingGlobal();

    }

    public void doSomethingGlobal() {

        System.out.println("Global-> " + MIN_INTEREST);

    }

    public void doSomethingLocal() {

        final double MIN_INTEREST = 0.1;

        System.out.println("Local-> " + MIN_INTEREST);

    }
}

The output will be:
Local-> 0.1
Global-> 0.0

So your question doesn't make any sense.


text:
Q: Sandcastle how to include subtopics in TOC I'm just getting started with Sandcastle, trying to build a conceptual help file without any code component at all. I've got a basic framework working, but I'm having trouble figuring out how to get things into the Table of contents. As I understand it the TOC is based on the contents of the Content Layout.content file, but all I can add are FILES not links within a file.
Is there some syntax that will allow me to have a section within a file appear as a TOC entry? I'm working with some AML files provided by a client, and they include lots of tags that look like this:
<section address="_Toc190084020">

but the _Toc is apparently meaningless, because they don't appear anywhere.
cheers,
Marc

A: I asked this same question on the SHFB website (https://shfb.codeplex.com/discussions) and got an answer from Eric Woodruff, the maintainer of the project.
It turns out that the table of contents is based strictly on the files included in the project, so the only way to get more TOC entries is to break it into more files.


text:
Q: Django footer is in middle of page I'm doing a django project, but I'm just a beginner. I am making a web page, my page footer is in middle of page.
Here is my code snippet:
base.html
{% block content %}
{% endblock %}
...

home.html
{% extends "base.html" %}

{% block title %}home.html{% endblock %}

{% load staticfiles %}
{% block extrastyle %}{% static "css/home.css" %}{% endblock %}
{% block content %}
{% endblock content %}

and I run this page, enter image description here
i've tried
{% block footer %}

...

{% endblock %}

in base.html but is doesn't work. same...

A: Ideally, you would have your footer in a separate file, same for a header.
Example (header.html):

    BIM Data Manager

Then you would include this template in another template. Like so:
{% include "base/header.html" %}

base would be your Django app, and header the name of the template.
So put your footer in a separate file, and include it at the bottom of your desired template.


text:
Q: Change of variables for a trig integral Can I use change of variables to turn $\int_{3\pi/2}^{2\pi}\cos x\, dx$ into $\int_{0}^{\pi/2}\cos x\, dx$? Letting $x \mapsto x - 3\pi/2$ doesn't seem to work.

A: Try $u=2\pi-x$. The differential will change sign, but you'll also have to turn the integral upside down.

A: Simply you can't do any changes of variable to change the intervales, the primitive of $\cos x$ is $\sin x$ so why do you need this change of variable ! so
$$\int_{3\pi/2}^{2\pi}\cos x\, dx= [\sin x]_{3\pi/2}^{2\pi}=\sin 2\pi -\sin 3\pi/2 =0-(-1)=1$$


text:
Q: @Rest\Post 405- Method Not Allowed - FOSRestBundle I am trying to start my REST API with fosrestBUndle. I just run the GET with success. But I met with the POST display the error "405 Method not allowed" when I put this  command

wget -S  localhost/tutonew/web/app_dev.php/api/test/add

The action in the Controller:
/**
 * @Rest\View
 * @Rest\Post("/api/test/add")
 *
 */
public function postTestAction(Request $request) {
    $entity = new Test();
    $form = $this->createForm(new TestType(), $entity);
    $form->bind($request);

    if ($form->isValid()) {
        $em = $this->getDoctrine()->getManager();
        $em->persist($entity);
        $em->flush();

        return $this->redirectView(
                        $this->generateUrl(
                                'get_test', array('id' => $entity->getId())
                        ), Codes::HTTP_CREATED
        );
    }

    return array(
        'form' => $form,
    );
}

The Form that is called:
class TestType extends AbstractType {

public function buildForm(FormBuilderInterface $builder, array $options) {
    $builder
            ->add('field', 'text');
}

public function setDefaultOptions(OptionsResolverInterface $resolver) {
    $resolver->setDefaults(array(
        'data_class' => 'Minn\AdsAPIBundle\Entity\Test',
        'csrf_protection' => false
    ));
}

public function getName() {
    return 'test';
}

}
Thank you very much in advance.

A: You are using a GET method but in your controller you need a POST method.
Try this:
curl -i -H "Accept: application/json" -H "Content-type: application/json" -X POST -d '{"test":{"field":"xxx"}}' http://localhost/tutonew/web/app_dev.php/api/test/add


text:
Q: OpenLayers and WFS: Using a mapfile correctly with featureType and featureNS I went off the example at http://openlayers.org/dev/examples/wfs-reprojection.js and got that working just fine with the states vector layer showing up.
Now I'm trying to use my own mapfile (wfs_navdata_02.map) and do the same. Just one layer for now, cities_1x.
var wfs = new OpenLayers.Layer.Vector("My Layer", {
            strategies: [new OpenLayers.Strategy.Fixed()],
            protocol: new OpenLayers.Protocol.WFS({
                version: "1.1.0",
                srsName: "EPSG:4326",
                url:  "http://my_local_url/cgi-bin/mapserv.exe?map=/file_location/wfs_navdata_02.map",
                featureType: "cities_1x",
                featurePrefix: "",
                featureNS: "http://yourdomain/application/catalogLayer"
            }),
    });
    map.addLayer(wfs);

What do I put in for featureNS?
For the url, is referencing the mapfile like that ok?
I read one poster that said he needed to use featurePrefix but I don't think thats necessary here.
Also for featureType, is that the name of the LAYER or the wms_title within the layer?
I've successfully used WMS before but WFS is a bit more confusing. I am not having any errors in the javascript console via Chrome.
Snippet of mapfile can be seen here: http://codeshare.io/C1hki
Not sure if OUTPUTFORMAT is necessary.

A: This might help you move forward: by default, MapServer uses "ms:" as a prefix, and http://mapserver.gis.umn.edu/mapserver as a namespace:
featurePrefix: "ms",
featureNS: "http://mapserver.gis.umn.edu/mapserver"

OpenLayers might/did have some quirks when specifying both of these, so you might want to try setting only one of those at a time, c.f. http://lists.osgeo.org/pipermail/openlayers-users/2009-August/013320.html
You can also try with version: '1.0.0' as this will prevent lat/lon coordinate inversion. I also found a few issues with your mapfile:

*

*The mapfile should end with an END at the map level.

*The OUTPUTFORMAT is not mandatory.

*Make sure to use "init=epsg:4326" as your projection.

Using the NameSpace and prefix above and fixing the mapfile, I successfully got points in OpenLayers.


text:
Q: Problem with Jquery, setInterval inside a Facebook iframe I'm building a simple Facebook tab. I have two tabs that change every 3 seconds with with the help of setInterval and JQuery until the user interacts with them. Which them cancels the switching.
$(document).ready(function() {

    $('#item2').hide();
    $('li#tab1').addClass('selected');

    var timer = setInterval(function () {
        $('div.item').fadeToggle('fast')
        $('li.tab').toggleClass('selected') ;
    }, 3000);

    $(window).blur(function(){
        clearInterval(timer)
    })

    // setup. Set the first tab to selected
    $('li.tab').click(function(event) {
        clearInterval(timer);
        $('li.tab').toggleClass('selected')
        $('div.item').fadeToggle('fast')
    });

});

This works fine... mostly. The problem occurs when I lose focus on the page for a while ( 2-3 minutes ) and switch back, the tabs switch back and forth very fast for a while before returning to normal. I am able to fix this issue if NOT in an iframe with:
$(window).blur(function(){
    clearInterval(timer)
})

which just stops the switch altogether. But this does not work when the page is inside a iframe on Facebook. Can anyone suggest a solution?

A: Try using setTimeout instead of setInterval.
function doStuff(){
    //do some stuff
    setTimeout(doStuff, timeout);
}

setTimeout(doStuff, timeout);

This way, you only have one iteration going in the background, so it'll flash once immediately when the user switches back to the page (hopefully fast enough that he doesn't notice).


text:
Q: Why does Eclipse-CDT say self-assignment is an error? I was doing unit test in eclipse g++ using google test. I got an error when i tried to unit test the self assignment check in the class i designed.
as usual, the overload is pretty standard and looks like this:
CLASS operator=(const CLASS& rhs);

and when i tried to have this in the test:
CLASS A;
A = A;   //compile error here, saying self assignment to itself. have no clue why, though.

I wonder if there is a specific way for self assignment test. Thanks.
FYI, below is the snapshot of the error

A: A self assignment statement x = x; is not, of course, an error in C++
and you do not have any compiler error here.
If you run a build of your project and look at the output in the IDE Console
tab, rather than the Problems tab, you will see that the compiler does
not report such an error. Unless it does report some error, you project will build
successfully.
If you look at the self-assignment error reported under the Problems
tab you will see that its Type is Code Analysis Problem, not C/C++ Problem.
This means that the problem is reported by the Eclipse CDT Code Analyser
(Codan), not by the compiler.
Codan is reporting self-assignment as an error because self-assignment is
almost always a programming mistake. But in your case it is deliberate.
You have two choices:

*

*1). Ignore the Code Analysis error

*2). Change the Code Analysis settings of the project so that this error is
not reported.

To do 2):

*

*Navigate Properties -> C/C++ General -> Code Analysis

*Enable Use project settings

*Either:-

*

*Disable problem Assignment to itself, or

*Select Assignment to itself, then navigate Customize Selected... -> Preferences
and change the problem's severity from Error to Warning or Info.

*OK out of project Properties


text:
Q: Intent in action bar not working I have two activities with two layouts and a action bar.
The minimum API I am using is 14.
I go from one activity to another with no problem using intent, and I want to make a home button in the action bar to return to the activity that I choose.
I implemented a menu and called it from xml using the guides on the android developers site, but when I click on the button/menu from the action bar, it crashes with uncaught exception.
The main activity class:
         package com.example.quiz;

         import android.app.ActionBar;
         import android.app.Activity;
         import android.content.Intent;
         import android.os.Bundle;
         import android.view.Menu;
         import android.view.MenuInflater;
         import android.view.MenuItem;
         import android.view.View;
         import android.view.View.OnClickListener;
         import android.widget.Button;

         public class MainActivity extends Activity {

     Button new_b;
     ActionBar actionBar;

     @Override
     protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    ActionBar actionBar = getActionBar();
    actionBar.show();

         new_b=(Button)findViewById(R.id.new_button);

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

            Intent intent = new Intent(MainActivity.this,HomeActivity.class);
            startActivity(intent);
        };
          });

         }

     @Override
     public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu items for use in the action bar
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.activity_main_actions, menu);
        return super.onCreateOptionsMenu(menu);
     }

     @Override
     public boolean onOptionsItemSelected(MenuItem item) {
        // Handle presses on the action bar items
        switch (item.getItemId()) {
            case R.id.home_button:homeClick();
                return true;
            case R.id.info_button:homeClick();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
     }

     private void homeClick() {
        Intent intent_home = new Intent(this,HomeActivity.class);
        intent_home.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent_home);
     }
        }
       }

The home activity class:
         import android.app.ActionBar;
         import android.app.Activity;
         import android.content.Intent;
         import android.os.Bundle;
         import android.view.Menu;
         import android.view.MenuInflater;
         import android.view.MenuItem;

         public class HomeActivity extends Activity {

     ActionBar actionBar;

     @Override
     protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.home);
    ActionBar actionBar = getActionBar();
    actionBar.show();

     @Override
     public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu items for use in the action bar
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.activity_main_actions, menu);
        return super.onCreateOptionsMenu(menu);
     }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle presses on the action bar items
        switch (item.getItemId()) {
            case R.id.home_button:homeClick();
                return true;
            case R.id.info_button:homeClick();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }

     }

     private void homeClick() {
        Intent intent_home = new Intent(this,HomeActivity.class);
        intent_home.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent_home);
      }
         }
        }

Can I make it another way, or what can I do to make it work?
           04-20 19:31:57.610: I/Adreno200-EGL(5708): <qeglDrvAPI_eglInitialize:299>: EGL 1.4 QUALCOMM build:
           AU_LINUX_ANDROID_JB_REL_2.0.3.04.01.02.21.107_msm8625_JB_REL_2.0.3_CL3357771_release_AU (CL3357771)
           04-20 19:31:57.610: I/Adreno200-EGL(5708): Build Date: 02/25/13 Mon
           04-20 19:31:57.610: I/Adreno200-EGL(5708): Local Branch:
           04-20 19:31:57.610: I/Adreno200-EGL(5708): Remote Branch: quic/jb_rel_2.0.3
           04-20 19:31:57.610: I/Adreno200-EGL(5708): Local Patches: NONE
           04-20 19:31:57.610: I/Adreno200-EGL(5708): Reconstruct Branch AU_LINUX_ANDROID_JB_REL_2.0.3.04.01.02.21.107 +  NOTHING
           04-20 19:31:57.850: W/ResourceType(5708): getEntry failing because entryIndex 14 is beyond type entryCount 1
           04-20 19:31:57.850: W/ResourceType(5708): Failure getting entry for 0x7f0b000e (t=10 e=14) in package 0 (error -2147483647)
           04-20 19:32:09.390: E/dalvikvm(5708): GC_CONCURRENT freed 2965K, 22% free 12424K/15751K, paused 12ms+26ms, total 75ms
           04-20 19:32:10.600: W/dalvikvm(5708): threadid=1: thread exiting with uncaught exception (group=0x41d02438)

A: You can use this code as an example:
MainActivity.java
package com.example.quiz;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.MenuItem;

public class MainActivity extends Activity {

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

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

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch(item.getItemId()) {
            case R.id.go_home:
                Intent intentHome = new Intent(this, HomeActivity.class);
                startActivity(intentHome);
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

}

/res/menu/activity_main_actions.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android" >

    <item
        android:id="@+id/go_home"
        android:showAsAction="ifRoom"
        android:title="@string/go_home" />

</menu>

A: It turned out that I was trying to format my strings with html code.
Example:
I was using:
    <string name="title"> <b>App title</b> </string>

When I was supposed to use:
    <string name="title"> App title <string>


text:
Q: Advapi32.lib missing from Visual Studio 2013 Community Edition My code compiles and links just fine on PC #1 using VS 2013 Pro.  It fails linking on PC #2 using VS 2013 Community Edition.  The failure is three unresolved externals from Advapi32.lib -- CryptAcquireContextW, CryptReleaseContext, and CryptGenRandom.
This leads to several key questions:

*

*Why doesn't VS 2013 warn you when it can't find a library that's on the linker input line?

*Why is Advapi32.lib unavailable in the Community Edition?

*What can one do to fix this problem?

Thanks.


text:
Q: Chat with express.io I have two files, one named index.js and the other index.html.
When I press the send button the message doesn't appear
The code of the file index.js is the following:
    app = require('express.io') ();
    app.http().io();

    app.get('/', function(req, res){
    res.sendfile('index.html');
 });

app.io.on('connection', function(socket){
socket.on('chat message',function(msg) {
 app.io.emit('chat message' ,msg)
 });
console.log('a user connected');
socket.on('disconnect', function(){
console.log('user disconnected');
});
});

app.listen(3000);

The code of the file index.html is the following:
<!doctype html>

<title>Example of chat</title>

 <form action="">
   <input id="m" autocomplete="off" /><button>Send</button>

 </form>

A: write this instead
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);

server.listen(3000);

app.get('/', function (req, res) {
  res.sendfile('index.html');
});

io.on('connection', function (socket) {
  socket.on('chat message', function (data) {
    socket.broadcast.emit('chat message',data);
  });
});


text:
Q: Animation in Live Wallpaper Android? I am fairly new developer and trying to make a live wallpaper app. Among many animations, my first target is to show a rotating Bitmap which is actually a Black Hole.
    public class Painting extends Thread {

    /** Reference to the View and the context */
    private SurfaceHolder surfaceHolder;
    private Context context;

    /** State */
    private boolean wait;
    private boolean run;

    /** Dimensions */
    private int width;
    private int height;

    /** Time tracking */
    private long previousTime;

    boolean first = true;

    Bitmap hole;

    int degree;
    public Painting(Context con , SurfaceHolder surf)
    {
            context = con;
            surfaceHolder = surf;
            this.wait = true;
            Log.i("Live Test","UnInitialized");
            Drawable d = (con.getResources().getDrawable(R.drawable.vlack));
            hole = ((BitmapDrawable)d).getBitmap();
            hole.prepareToDraw();
            if(hole != null)
            Log.i("Live Test","Initialized");
            run = true;wait = false;
            degree = 0;

    }

    @Override
    public void run()
    {
            while (run) {
                    this.run = true;
                    Canvas c = null;

                    Log.i("Live Test","Draw Color");
                    while (run) {
                            try {
                                    c = this.surfaceHolder.lockCanvas();
                                    synchronized (this.surfaceHolder) {
                                            doDraw(c);
                                    }
                            } finally {
                                    if (c != null) {
                                            this.surfaceHolder.unlockCanvasAndPost(c);
                                            Log.i("Live Test","Unlocked And Posted");
                                    }
                            }
                            // pause if no need to animate
                            synchronized (this) {
                                    if (wait) {
                                            try {
                                                    wait();
                                            } catch (Exception e) {
                                                    Log.i("Live Test","Error wait");
                                            }
                                    }
                            }
                    }
            }

    }

    public void setSurfaceSize(int width, int height) {
            this.width = width;
            this.height = height;
            synchronized(this) {
                    this.notify();
            }
    }

     /**
 * Pauses the livewallpaper animation
 */
public void pausePainting() {
    this.wait = true;
    synchronized(this) {
        this.notify();
    }
}

/**
 * Resume the livewallpaper animation
 */
public void resumePainting() {
    this.wait = false;
    synchronized(this) {
        this.notify();
    }
}

/**
 * Stop the livewallpaper animation
 */
public void stopPainting() {
    this.run = false;
    synchronized(this) {
        this.notify();
    }
}

    private void doDraw(Canvas canvas) {
            if(first)
            {
                    canvas.save();
                    canvas.drawColor(0x60444444);
                    canvas.drawBitmap(hole, 80,80,null);
                    canvas.restore();
                    first = false;
            }
            else
            {
            long currentTime = System.currentTimeMillis();
            long elapsed = currentTime - previousTime;
            if (elapsed > 20) {

            canvas.save();
            degree+= 5;
            if(degree>359)degree = degree -358;
            canvas.rotate((float) degree);
            canvas.restore();
            Log.i("Live Test","rotated");
            }
            previousTime = currentTime;
    }
  }
}

So I am trying to rotate the bitmap and show it again so it looks like its sucking stars and all.
Also I have removed Basic onPause onResume Functions so that you guys can understand the code easily. I know there is something basic I am missing, but What?

A: Hmmm.  It would take more time than I have right now to puzzle this out, but I do have one suggestion: code your wallpaper using a simpler approach.  Scrap the thread and do something more along the lines of the Cube example, that is to say make a runnable which schedules calls to itself using postDelayed.  Hope this helps.  George.


text:
Q: Why is mongoose removing part of my query I have the following query which works in the mongoDB CLI:
db.organisations.updateOne({ _id: ObjectId("5f687da23a4dc9071baefd6d")}, {$pull: {courseIds:
ObjectId("5f687b863a4dc9071baefd6c"), "groups.$[].courseIds":
ObjectId("5f687b863a4dc9071baefd6c") }})

And the following query which is what I believe to be the mongoose equivalent:
await Organisation.updateOne({_id: "5f687da23a4dc9071baefd6d"},
{$pull: {courseIds: "5f687b863a4dc9071baefd6c", "groups.$[].courseIds":
"5f687b863a4dc9071baefd6c"}})

Using mongoose debugging I can see that the following query which mongoose translates to is removing the entire second half of my pull operation for all documents in the array. Why is this?
organisations.updateOne({ _id: ObjectId("5f687da23a4dc9071baefd6d") }, { '$pull': {
courseIds: ObjectId("5f687b863a4dc9071baefd6c") } }, {})

A: It turns out I have the big stupid. My mongoose schemas were incorrect.


text:
Q: Assign mutiple ranges (non consecutive) to a single Constants (apps script) I have this (below) as part of my apps script and I am wondering if there is a way to simplify this:
const fieldRange = ["C9","C10","C11","C12","C15","C16","C17","C18","C19","C20","C21","C22","C23","C24","C25","C26","C27","C28","C29","C30","C33","C34","C35","C36","C37","C38","C41","C42","C45","C46","C47","C48","C49","C50"]
maybe something like ['(C9:C12)','(C15:C30)', etc.

A: In your situation, how about the following sample script?
Sample script:

// This value is from your question.
const fieldRange = ["C9", "C10", "C11", "C12", "C15", "C16", "C17", "C18", "C19", "C20", "C21", "C22", "C23", "C24", "C25", "C26", "C27", "C28", "C29", "C30", "C33", "C34", "C35", "C36", "C37", "C38", "C41", "C42", "C45", "C46", "C47", "C48", "C49", "C50"];

// Ref: https://tanaikech.github.io/2021/10/08/compiling-continuous-numbers-using-google-apps-script/
const compilingNumbers = (ar) => {
  const { values } = [...new Set(ar.sort((a, b) => a - b))].reduce((o, e, i, a) => {
    if (o.temp.length == 0 || (o.temp.length > 0 && e == o.temp[o.temp.length - 1] + 1)) {
      o.temp.push(e);
    } else {
      if (o.temp.length > 0) {
        o.values.push({ start: o.temp[0], end: o.temp[o.temp.length - 1] });
      }
      o.temp = [e];
    }
    if (i == a.length - 1) {
      o.values.push(o.temp.length > 1 ? { start: o.temp[0], end: o.temp[o.temp.length - 1] } : { start: e, end: e });
    }
    return o;
  }, { temp: [], values: [] });
  return values;
};

const r1 = fieldRange.reduce((o, e) => {
  const k = e.replace(/[0-9]+/, "");
  const v = Number(e.toUpperCase().replace(/[A-Z]+/, ""));
  o[k] = o[k] ? [...o[k], v] : [v];
  return o;
}, {});
const res = Object.entries(r1).flatMap(([k, v]) => compilingNumbers(v).map(({ start, end }) => `${k}${start}:${k}${end}`));
console.log(res); // ["C9:C12","C15:C30","C33:C38","C41:C42","C45:C50"]

*

*When this script is run, ["C9:C12","C15:C30","C33:C38","C41:C42","C45:C50"] is obtained.

*If you want to retrieve the value like maybe something like ['(C9:C12)','(C15:C30)', etc., please modify ${k}${start}:${k}${end} to (${k}${start}:${k}${end}).
Note:

*

*From your showing sample value, this script supposes that all values in your expected array including A1Notation are only one cell. Please be careful about this.

References:

*

*reduce()

*map()


text:
Q: JQuery UI icon-only buttons that POST I have some icon-only action buttons on my application. The buttons are plain old anchor tags styled using JQuery UI, for example:
Up

$('.move-up-button-icon-only').button({
  text: false,
  icons: {
    primary: "ui-icon-arrowthick-1-n"
  }
});

Some of the buttons have a side-effect, so I want to POST to the href.
I know I can use a standard <input type="submit"/> button, but then I cannot use the icon-only button, as JQuery UI cannot put an icon on a normal submit button. I'd really like to keep the visual consistency with my other buttons, so is there any way to change the method of an anchor link from GET to POST?
(It is OK if this does a GET request for browsers that don't support, say, Javascript. I will have a confirmation page in that case, and a regular form to POST.)

A: This seems to work, but it really feels like a dirty hack to me. Is this OK, or is there a better way?
$('.move-up-button-icon-only').click(function () {
  if ($.browser.msie) {
    var form = document.createElement("form")
    $(form).attr('method', 'post').attr('action', $(this).attr('href'));
    document.body.appendChild(form);
    form.submit();
    document.body.removeChild(form);
  } else {
    $('<form/>').attr('method', 'post')
                .attr('action', $(this)
                .attr('href')).submit();
  }
});

Note that you have to add the form to the DOM in IE, other browsers just work.

A: Use a <button /> instead, no jQuery required for styling (though you might use it to attach button behaviors), and icon-only works fine:
<button class="my-button" />

...
.my-button {
    background:url('ui-icon-arrowthick-1-n.png') no-repeat left top;
    height:16px;  /* or whatever */
    width:16px;
}

Semantically, if you're creating a button with no form, use the tools that you have at your availability - <button /> should be what you want.
Docs here.
Cheers


text:
Q: Porque o isset não funciona bem com $_POST? Preciso que o título da página varie de acordo com o form, para isso eu usei o código dentro do <head>:
<?php
    $titulo = isset($_POST['titulo']) ? $_POST['titulo'] : 'Sem titulo';
?>
<title><?php echo $titulo." - Minimalist";?></title>

Ele funciona bem caso eu adicione o título no form, mas não retorna o 'Sem título', quando o mesmo for vazio. Isso funcionava perfeitamente com o $_GET. Por acaso, ao usar o $_POST, ele retorna uma string vazia?

A: O isset verifica se uma variável foi definida/inicializada, não é verificado se possuí um valor.
O isset sempre vai retornar true para $_POST porque ele vai estar sempre definido, porém pode estar vazio, que é provavelmente a origem do teu problema.
Veja a documentação do $_POST:

Esta é uma superglobal, ou global automática, variável. Isto
  simplesmente significa que ela está disponível em todos escopos pelo
  script.

Para verificar se a variável está vazia, use o empty:
$titulo = empty($_POST['titulo']) ? 'Sem titulo' : $_POST['titulo'];

Semelhante ao isset, o empty também verifica se a variável foi inicializada, porém não emite um aviso. O que é considerado vazio pelo empty:

*

*""  (uma string vazia)

*0   (0 como um inteiro)

*0.0 (0 como um ponto flutuante)

*"0" (0 como uma string)

*NULL

*FALSE

*array() (um array vazio)

*$var;   (uma variável declarada, mas sem valor)

Segundo a documentação, o empty é essencialmente equivalente a !isset($var) || $var == false.

Uma outra alternativa é usar o isset e uma condição para verificar se variável não está vazia:
$titulo = isset($_POST['titulo']) && $_POST['titulo'] !== '' ?
                                     $_POST['titulo'] : 'Sem titulo';

Veja também:

*

*Tabela de comparações de tipos do PHP

*Diferença entre null, empty, 0 e false


text:
Q: How to calculate multiple user input values with fixed price? Background info:
I'm currently working on a calculator and need to calculate current income based on amount of buildings the user has purchased
Example:
User inputs he has 3 houses and 4 mansions.
Each house gives $500 income and each mansion gives $1,000 income.
The submit button would return the user has $5,500 income

I've tried:
$a=$_GET['house'];
$b=$_GET['houseprice'];
echo "Sum : ",$a+'975';

A: Try this :
$a= floatval($_GET['house']); // 1000.00
$b= floatval($_GET['houseprice']); // 1000.00
echo "Sum : ".  $a + 975; // 1975.00

A: Roughly you can just get all the inputs and do the math:
$houses = $request->input('houses');
$housePricing = 500;
//$housePricing = $request->input('house_pricing');

$mansions = $request->input('mansions');
$mansionPricing = 1000;
//$mansionPricing = $request->input('mansion_pricing');

$total = ($houses * $housePricing) + ($mansions * $mansionPricing);


text:
Q: How to move back from Preferences subscreen to main screen in PreferenceFragmentCompat? I am trying to implement a Settings screen using PreferenceFragmentCompat. My preference xml has a preference subscreen like this:
preferences.xml

    <CheckBoxPreference
        android:defaultValue="false"
        android:key="@string/pref_sound_key"
        android:summary="@string/pref_sound_summary"
        android:title="@string/pref_sound_title" />

    <PreferenceScreen android:title="Inner Screen">
        <CheckBoxPreference
            android:defaultValue="true"
            android:key="@string/key_1"
            android:title="@string/title_1" />

        <CheckBoxPreference
            android:defaultValue="true"
            android:key="@string/key_1"
            android:title="@string/title_1" />

        <CheckBoxPreference
            android:defaultValue="true"
            android:key="@string/key_2"
            android:title="@string/title_2" />

        <CheckBoxPreference
            android:defaultValue="true"
            android:key="@string/key_3"
            android:title="@string/title_3" />
    </PreferenceScreen>

</PreferenceScreen>

Preference Main Screen
Now, in the app, the subscreen does not open until I implement PreferenceFragmentCompat.OnPreferenceStartScreenCallback interface in parent activity, as specified in PreferenceFragmentCompat doc.
MainActivity.java
public boolean onPreferenceStartScreen(PreferenceFragmentCompat preferenceFragmentCompat,
 PreferenceScreen preferenceScreen) {
    preferenceFragmentCompat.setPreferenceScreen(preferenceScreen);
    return true;
}

Here's where the problem arises. On implementing the interface, the subscreen opens, but then there is no way I can find to move back to first screen.
Preference Subscreen
Pressing back key closes the app.
Is there any way I can put a back arrow on app bar so that pressing it will bring the main screen back?

A: I have added a complete working example with screenshots and code snippets here in this post, I hope this will be helpful to someone.
It covers following scenarios:-- 1) A main setting screen with two checkboxes and a subscreen title. 2) On click of subscreen title, the new preference subscreen opens. 3) On back pressed, the control goes to main Settings screen. So the back press is handled properly.
The MainActivity looks like this(overridden onPreferenceStartScreen method handles the opening of new subscreen in a new window):--
  public class MainActivity extends AppCompatActivity implements PreferenceFragmentCompat.OnPreferenceStartScreenCallback {

    private static final String TAG = MainActivity.class.getName();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        FragmentManager fragmentManager = getSupportFragmentManager();
        Fragment fragment = null;
        if (savedInstanceState == null) {
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            fragment = new AdvancedSettingsFragment().newInstance("Advanced Setting");
            fragmentTransaction.add(R.id.fragment_container, fragment);
            fragmentTransaction.commit();
        }
    }

    @Override
        public boolean onPreferenceStartScreen(PreferenceFragmentCompat preferenceFragmentCompat,
                                           PreferenceScreen preferenceScreen) {
        Log.d(TAG, "callback called to attach the preference sub screen");
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        AdvancedSettingsSubScreenFragment fragment = AdvancedSettingsSubScreenFragment.newInstance("Advanced Settings Subscreen");
        Bundle args = new Bundle();
        //Defining the sub screen as new root for the  subscreen
        args.putString(PreferenceFragmentCompat.ARG_PREFERENCE_ROOT, preferenceScreen.getKey());
        fragment.setArguments(args);
        ft.replace(R.id.fragment_container, fragment, preferenceScreen.getKey());
        ft.addToBackStack(null);
        ft.commit();
        return true;
    }

and finally the in subscreen fragment setPreferencesFromResource(R.xml.preferences, rootKey); handles the attachment of subscreen to the rootkey.
public class AdvancedSettingsSubScreenFragment extends PreferenceFragmentCompat {
    private static final String TAG = AdvancedSettingsSubScreenFragment.class.getName();
    public static final String PAGE_ID = "page_id";

    public static AdvancedSettingsSubScreenFragment newInstance(String pageId) {
        AdvancedSettingsSubScreenFragment f = new AdvancedSettingsSubScreenFragment();
        Bundle args = new Bundle();
        args.putString(PAGE_ID, pageId);
        f.setArguments(args);
        return (f);
    }

    @Override
    public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
        // rootKey is the name of preference sub screen key name , here--customPrefKey
        setPreferencesFromResource(R.xml.preferences, rootKey);
        Log.d(TAG, "onCreatePreferences of the sub screen " + rootKey);
    }
}

A: By using setPreferenceScreen you are setting the root preference screen to the sub preference screen which is preventing you from having a hierarchy of preference screens to navigate back through.
I suggest that you treat each PreferenceScreen as a Fragment and add a new Fragment when you navigate into a sub screen.
@Override
public boolean onPreferenceStartScreen(PreferenceFragmentCompat preferenceFragmentCompat,
                                       PreferenceScreen preferenceScreen) {
    FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
    MyPreferenceFragment fragment = new MyPreferenceFragment();
    Bundle args = new Bundle();
    args.putString(PreferenceFragmentCompat.ARG_PREFERENCE_ROOT, preferenceScreen.getKey());
    fragment.setArguments(args);
    ft.add(R.id.fragment_container, fragment, preferenceScreen.getKey());
    ft.addToBackStack(preferenceScreen.getKey());
    ft.commit();
    return true;
}

MyPreferenceFragment
public class MyPreferenceFragment extends AppPreferenceFragment {

   public static final String FRAGMENT_TAG = "my_preference_fragment";

   public MyPreferenceFragment() {
   }

   @Override
   public void onCreatePreferences(Bundle bundle, String rootKey) {
       setPreferencesFromResource(R.xml.preferences, rootKey);
   }
}

AppPreferenceFragment
public abstract class AppPreferenceFragment extends PreferenceFragmentCompat {

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    // Set the default white background in the view so as to avoid transparency
      view.setBackgroundColor(
              ContextCompat.getColor(getContext(), R.color.background_material_light));

  }
}

That way when you press the back button each Fragment will be popped from the stack.
For more information see this GitHub project


text:
Q: Retrieving data from hasMany Relationship I want to show data from 'personas' (parent table) that has at least one 'residente' (child table), its a one to many relationship,  and i want to show data of that residente too.
I was trying to do it using the has() method like the laravel documentation says:
https://laravel.com/docs/9.x/eloquent-relationships#querying-relationship-existence
but it does not work.
Models looks like this
//in the Persona class

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

//in the Residente class

public function persona()
  {
    return $this->belongsTo(Persona::class);
  }

//in the PersonasController

public function index()
    {
        $personas = Persona::has('residentes')->get();

        dd($personas);

    }

the Result
enter image description here
//it doesn't get the data from "residentes"

A: Try :
 public function index()
{
    $personas = Persona::with('residentes')->get();
    dd($personas);

}

If you want to search using some keys inside the residentes relationship you can use whereHas
Persona::with('residentes')
       ->whereHas('residentes',function($residente){
           return $residente->where('column_name',$value);
         })->get();

Also try to mention the local_key and the foreign_key in the relationship itself reference : https://laravel.com/docs/9.x/eloquent-relationships
return $this->hasMany(Comment::class, 'foreign_key', 'local_key');

A: Please try the following in the place of key give actual field names.
//in the Persona class

public function residentes()
{
   return $this->hasMany(Residente::class, 'foreign_key', 'local_key');
}

//in the Residente class

public function persona()
{
    return $this->belongsTo(Persona::class,'foreign_key', 'owner_key');
}

//in the PersonasController

public function index()
{
    $personas = Persona::with('residentes')->get();
    foreach($personas as $person){
       echo "<pre>";
       print_r($person->residentes()->get()->toArray());
     }
}


text:
Q: File no found following use of Name function I am trying to do is rename a file. Here is my code. It comes back with "File not found". The directory is correct. I have double and tripled checked. The error message persists. Here is the code. What am I doing wrong?
Sub RenamePictureFileName()

    Dim sPath As String
    Dim oldPrato As String, newPrato As String
    Dim oldName As String, newName As String

    oldPrato = "Migas de Couve.jpeg"
    newPrato = "Mais migas de couve.jpeg"

   sPath = "/Users/victorgameiro/Dropbox/AT Macela/Excel Databases/" & _
        "FICHAS TÉCNICAS/Fotos/Fotos FT/"

    oldName = sPath & oldPrato
    newName = sPath & newPrato
    Debug.Print oldName
    Debug.Print newName
    Name oldName As newName

End Sub

A: Try adding the drive letter like this:
sPath = "C:/Users/victorgameiro/Dropbox/AT Macela/Excel Databases/" & _
        "FICHAS TÉCNICAS/Fotos/Fotos FT/"
If it isn't C: replace the letter to the drive the file is.
—-
Please mark the answer if this helped you.

A: I apologize for not mentioning that I am indeed working with Excel for Mac which means that the path indicated is the proper way to identify the path. There is no C:\ drive on a Mac. The path indicated in my code works fine in other uses. Given that the problem persists, is it then possible that the code does not work on the Mac version of excel?
Thank you all for your help.

A: The Mac system does not use letters as drives. If I do add the letter for the drive it comes back with "cannot find drive". I suspect that this function is just another of the functions that does not work on the Mac version of Excel. I have to find a way around it until such time as MS decides to fix this problem.  In the mean time I'll test the code on a PC to see if my code works.
I appreciate the help.


text:
Q: Schema markup for logo [application/ld+json] I have implemented for a website the "Schema Logo" according to schema.org.
While testing it both from Goolge Search Console and the google data testing tool (https://search.google.com/test/rich-results?hl=it) the element contains no errors or warning but both tools call it "Element without name".
This is correct or we can define a name for the "snippet" ? I have search google without success.
<script type="application/ld+json">
{
    "@context": "https://schema.org",
    "@type": "Organization",
    "url": "<?php echo $this->serverurl(); ?>",
    "logo": "<?php echo $this->serverurl(); ?>/img/logo-microdata.png"
}

A: According to the Google Documentation it doesn't look like there's a way to provide a name for the logo snippet.
It will still work correctly, it just shows as Unnamed Item in Google Search Console.


text:
Q: MongoError: PlanExecutor error during aggregation I have tree records in mongodb but there could be many more, I'm getting shops by an ID coming from frontend
I need to get 20 records and group them by itemId and colorId, and get counts for every shop. the count of shops can be 1,2,3,....10etc..
this is output I need:
+--------+----------+-------+-------+-------+
| itemId | colorId  | shop1 | shop2 | shop3 |
+========+==========+=======+=======+=======+
| 1      | colorId1 | 5     | 0     | 3     |
+--------+----------+-------+-------+-------+
| 2      | colorId2 | 3     | 0     | 0     |
+--------+----------+-------+-------+-------+
| 3      | colorId2 | 0     | 3     | 0     |
+--------+----------+-------+-------+-------+
| 2      | colorId1 | 0     | 5     | 0     |
+--------+----------+-------+-------+-------+
| 3      | colorId1 | 0     | 0     | 5     |
+--------+----------+-------+-------+-------+

here is my data and query - here shopId is string and it's work good.
but when I use this query on my local mashine, I'm getting this error:
MongoError: PlanExecutor error during aggregation :: caused by :: $arrayToObject requires an object with keys 'k' and 'v', where the value of 'k' must be of type string. Found type: objectId
but when I change shopId to the ObjectId I'm getting error.
ObjectId versoin

A: Per your request in the comments (if I got it right):
    db.collection.aggregate([
  {
    "$match": {}// <-- Highly recommend you to use match due to the complexity of this query
  },
  {
    $group: {
      _id: 0,
      data: {
        $push: {
          shopId: "$shopId",
          shopItems: "$shopItems"
        }
      },
      shopIds: {
        "$push": {
          shopId: "$shopId",
          "count": 0
        }
      }
    }
  },
  {
    $unwind: "$data"
  },
  {
    $unwind: "$data.shopItems"
  },
  {
    $group: {
      _id: {
        itemId: "$data.shopItems.itemId",
        colorId: "$data.shopItems.colorId"
      },
      data: {
        $push: {
          shopId: "$data.shopId",
          count: "$data.shopItems.itemCount"
        }
      },
      existing: {
        $push: {
          shopId: "$data.shopId",
          "count": 0
        }
      },
      shopIds: {
        $first: "$shopIds"
      }
    }
  },
  {
    "$addFields": {
      "missing": {
        "$setDifference": [
          "$shopIds",
          "$existing"
        ]
      }
    }
  },
  {
    $project: {
      data: {
        $concatArrays: [
          "$data",
          "$missing"
        ]
      }
    }
  },
  {
    $unwind: "$data"
  },
  {
    $sort: {
      "data.shopId": 1
    }
  },
  {
    $group: {
      _id: "$_id",
      counts: { // here you can change this key
        $push: "$data"
      },
      totalCount: {
        $sum: "$data.count" // if you want it
      }
    }
  }
])

After the first $match, we $group in order to get all shopIds in each document.
Next we $unwind and $group by the group you wanted: by colorId and itemId. Then we are adding all the shops with count 0 and removing the ones that do have actual count. Last three steps are just for sorting, summing and formating.
You can play with it here.


text:
Q: Laravel config:clear Caused Crash After running php artisan config:clear my site is now stuck on a "This page isn't working example.com is currently unable to handle this request. HTTP ERROR 500".
I have tried restarting apache, power cycling the server, and looking in error logs.
I don't know what to do!

A: I had faced the similar issue in past don't know what caused it but as of now you can delete the config.php from /vendor it won't break your code.
And your code will be start working..