text:
Q: Google Script Only Reads Frst Few Lines I want the monitorEmails function to find new messages in the Inbox. For whatever reason, GS does not read past the first two lines of code, I know this because the Log only shows the first
Logger.log(..)

statement has been verified.  GS only logs the first few lines and doesn't give any feedback beyond the first statement.
How can I get GS to show the Logger.log(..) statements?
Here's code:
    //set a time-driven trigger to run this function on the desired frequency
function monitorEmails() {
  var thread = GmailApp.getInboxThreads(0,1)[0]; // get first thread in inbox
  // log the number of messages in the thread
  var firstThread = GmailApp.getInboxThreads(0,1)[0];
  var numMsgs = firstThread.getMessageCount();  // # of messages in a given thread
  Logger.log(firstThread.getMessageCount());
  var messages = firstThread.getMessages();
  if (firstThread.isUnread()=='true'){  // check if thread is Read
    //Logger.log(firstThread.isUnread()=='true');
    for (var i = 0; i < messages.length; i++) {  //Go through each message within a   Thread
      // Logger.log(messages[i].getSubject());
      if (messages[i].isUnread()){   // if the message is unread
        Logger.log(messages[i].isUnread());
        var unreadBody = messages[i].getBody();  // Body contents variable that contains the body
        Logger.log(messages[i].getBody());
        var unreadFrom = messages[i].getFrom();  // Email Sender contents variable
        //Logger.log(messages[i].getFrom());
        messages[i].markRead();  // Mark message as read
        //Logger.log(messages[i].markRead());
        var fullLot = "Full";  // look for "Full" in text message.
        //Logger.log(unreadBody.search(fullLot) =='true');
        if(unreadBody.search(fullLot) == 'true' && getEmail()==AdminTest()){
          // if the sender has the proper admin email / phone #, then call function sendEmails
          sendEmails();
        }
      }
    }
  }
}

Thanks for your help!

A: You've got a problem in comparisons like this:
if (firstThread.isUnread()=='true'){  // check if thread is Read

You are comparing a Boolean to a String. Both true and false are keywords, so they should not be enclosed in quotes:
if (firstThread.isUnread() == true){  // check if thread is Read

In a couple of places, you're performing a comparison, then logging the result of the comparison inside the if block - it's more useful to log that before the comparison.
I think you'd help yourself out by making your logs more meaningful, with some context information - the modified script shows examples of this.
Logs
[13-07-02 09:40:53:583 EDT] numMsgs=1
[13-07-02 09:40:53:583 EDT] Subject=YOU could be our Player of the Week!
[13-07-02 09:40:53:658 EDT] firstThread.isUnread()==true
[13-07-02 09:40:53:658 EDT] messages[0].subject=YOU could be our Player of the Week!
[13-07-02 09:40:53:658 EDT] messages[0].isUnread=true
...

Modified script
function monitorEmails() {
  var thread = GmailApp.getInboxThreads(0,1)[0]; // get first thread in inbox
  // log the number of messages in the thread
  var firstThread = GmailApp.getInboxThreads(0,1)[0];
  var numMsgs = firstThread.getMessageCount();  // # of messages in a given thread
  Logger.log("numMsgs="+numMsgs);
  Logger.log("Subject="+firstThread.getFirstMessageSubject());
  var messages = firstThread.getMessages();
  Logger.log("firstThread.isUnread()=="+firstThread.isUnread());
  if (firstThread.isUnread()== true ){  // check if thread is Read
    for (var i = 0; i < messages.length; i++) {  //Go through each message within a   Thread
      Logger.log("messages["+i+"].subject="+messages[i].getSubject());
      Logger.log("messages["+i+"].isUnread="+messages[i].isUnread());
      if (messages[i].isUnread()){   // if the message is unread
        var unreadBody = messages[i].getBody();  // Body contents variable that contains the body
        Logger.log("messages["+i+"].body="+unreadBody);
        var unreadFrom = messages[i].getFrom();  // Email Sender contents variable
        Logger.log("messages["+i+"].from="+messages[i].getFrom());
        messages[i].markRead();  // Mark message as read
        Logger.log("messages["+i+"].isUnread="+messages[i].isUnread());
        var fullLot = "Full";  // look for "Full" in text message.
        var searchResult = unreadBody.search(fullLot);
        Logger.log("messages["+i+"].searchResult="+searchResult);
        if(searchResult == true && getEmail()==AdminTest()){
          // if the sender has the proper admin email / phone #, then call function sendEmails
          sendEmails();
        }
      }
    }
  }
}


text:
Q: deepstream is it possible to publish from my server, without opening a client connection in a browser I am somewhat confused in deepstream, is it possible to communicate to a client from my server? For example, is there any way to do something like this on a server? I am currently opening a client connection in browser that publishes to other clients. I would rather have the code below in my server.
var client = deepstream('localhost:6020').login()
var record = client.record.getRecord('new-record')

#Publish a message to all listeners of 'listen-channel' from my server?
record.set('listen-channel', 'message');

and then have clients listen:
record.subscribe('listen-channel', function(value) {
        console.log(value);

A: Sure, just run it from a node process. Deepstream "clients" can be backend and frontend processes alike, permissioning is used to distuinguish between who can do what.

redpajama_set_name: RedPajamaStackExchange


text:
Q: how to setup node with docker-compose i'm learning docker and nodejs, and i want to start a project with both of those tools.
What i'm trying to achieve is installing the node dependencies in the build phase of docker, and then copy the node_modules folder to my host machine via docker-compose volumes.
This is my Dockerfile:
FROM node:latest

COPY . /myproject/back/

WORKDIR /myproject/back/

RUN npm install --save-dev nodemon
RUN npm install --save \
  express \
  multer

CMD npm run dev

And this is my docker-compose.yml:
version: "3.3"

services:

  back:
    build: ./back
    expose:
      - 3000
    ports:
      - "3000:3000"
    volumes:
      - ./back:/myproject/back

And when i run docker-compose build it builds correctly, but when i run docker-compose up i get this error:
back_1  | > back@1.0.0 dev
back_1  | > nodemon main.js
back_1  |
back_1  | sh: 1: nodemon: not found
back_1  | npm ERR! code 127

What am i missing? Is this the recommended approach?

A: Nodemon should be used ideally only on your development environment. You can configure your dockercontainer to restart if an error occurs, discarding the need of Nodemon inside the container.
Now if you really want to have Nodemon running you node app inside docker, then you need to first install Nodemon globally:
Replace this RUN npm install --save-dev nodemon with this RUN npm install -g nodemon, this will make the command nodemon available in your container.


text:
Q: using clmm with random factor. Output? I have a data set of trees from different populations (Pop_ID) that I scored based on leaf senescence (Score) at different moments in time (Date).
I want to use a mixed models for ordinal data with Gen_ID (genotype) as a random factor. I use the ordinal package.
fit=clmm(Score~Date*Pop_ID+ (1|Gen_ID), data=subset)

Here is what my data looks like:

ID2 Gen_ID  Pop_Id    Country    Score Datum Date
1   2  FR213    FR2    France         2 23okt      1
2   4  PO148    PO2    Poland         3 23okt      1
3   5  FR218    FR6    France         2 23okt      1
4   6   NE91    NE4 The Netherlands   2 23okt      1
5   8   FR21    FR1    France         2 23okt      1
6   9    D68    DU2    Germany        2 23okt      1

I don't understand the different options that clmm uses such as link or treshold.
I am also unsure how to read the output. I would like to do an anova but I get the following error:

Error in (function (object, ...)  :    anova is not implemented for a
  single "clm" object

Anova(fit) also gives me an error:

Error in vcov.clm(object, method = "Cholesky") : Cannot compute vcov:
  Hessian is not positive definite

I would like to use a lsmeans but I am not sure how to
lsmeans(fit,~Datum2,mode="linear.predictor")

But this gives me the following error

Error in vcov.clm(object, method = "Cholesky") : Cannot compute vcov:
  Hessian is not positive definite

How can I solve this?
When would you use Hess=T in your model?
I would appreciate the help. Thank you!


text:
Q: Jquery extension BeautyTips doesn't work with dynamic ajaxPath option I'm using the BeautyTips jQuery extension, but I'm not having any luck passing dynamic URLs as the ajaxPath.  In the documentation, they suggest:
$('#example18').bt({
  ajaxPath: ["$(this).attr('href')", 'div#content']
});

I have
$( '.username' ).bt({
    ajaxPath: ["$(this).attr('title')"]
});

However, when I hover over the username element, instead of bringing up the URL stored in the title attribute within the Beautytip, it attempts to send the whole browser to another page (or refresh; it's hard to tell because the browser address doesn't change, but the page goes blank, and a View Source shows an entirely different page.)
I have verified that the title in the element in question is correct and is being addressed correctly.  If I statically pass the path, it works, but I'd rather not write a new version of this function for every item on the page that needs a Beautytip.
Is there a syntax issue here?  Any help would be much appreciated.
My HTML is like:
Username

A: Okay, I had to dig through the extension, but I figured this one out.
The plugin author (for reasons I did not spend the time to decipher) kills the "title" attribute of the element that BeautyTips operates on and moves its value to an attribute called "bt-xtitle" instead.  I guess this is why his sample used the "href" attribute instead of the title attribute, and it was my dumb luck to attempt this maneuver on the wrong attribute.
Anyway, this works:
$( '.username' ).bt({
    ajaxPath: ["$(this).attr('bt-xtitle')"]
});


text:
Q: Why does using "and" between two lists give me the second list (as opposed to an error)? I encountered a bug in some code. The (incorrect) line was similar to:
[x for x in range(3, 6) and range(0, 10)]
print x

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

(the correct way of writing this statement is not part of the question)
Wondering what someList and someOtherList does, I experimented. It seems to only ever set the result to the last parameter passed:
x = range(0,3)   # [0, 1, 2]
y = range(3, 10) # [3, 4, 5, 6, 7, 8, 9]
z = range(4, 8)  # [4, 5, 6, 7]

print x and y       # [3, 4, 5, 6, 7, 8, 9]
print y and x       # [0, 1, 2]
print z and y and x # [0, 1, 2]

I would assume that this is an unintentional consequence of being able to write something that is useful, but I'm not really seeing how the semantics of the "and" operator are being applied here.
From experience, python won't apply operators to things that don't support those operators (i.e. it spits out a TypeError), so I'd expect an error for and-ing something that should never be and-ed. The fact I don't get an error is telling me that I'm missing... something.
What am I missing? Why is list and list an allowed operation? And is there anything "useful" that can be done with this behaviour?

A: The and operator checks the truthiness of the first operand. If the truthiness is False, then the first argument is returned, otherwise the second.
So if both range(..)s contain elements, the last operand is returned. So your expression:
[x for x in range(3, 6) and range(0, 10)]

is equivalent to:
[x for x in range(0, 10)]

You can however use an if to filter:
[x for x in range(3, 6) if x in range(0, 10)]
In python-2.7 range(..) however constructs a list, making it not terribly efficient. Since we know that x is an int, we can do the bounds check like:
[x for x in range(3, 6) if 0 <= x < 10]
Of course in this case the check is useless since every element in range(3,6) is in the range of range(0,10).


text:
Q: HTML Audio accessibility with Input Range Minimal problem example: https://codepen.io/sidouglas/pen/LYPZaOG
When input range is focused, with either Chrome Vox or Mac's Voice over — every value of valuetext is read out continuously.
<input
 ...
  v-bind:aria-valuemax="valueMax"
  v-bind:aria-valuenow="valueNow"
  v-bind:aria-valuetext="currentTime + ' of ' + totalDuration"
  ...
/>

Contrast this to the very accessible https://plyr.io/#audio component - When focused it continues to update its aria values, yet only announce to the screen reader twice.
Does anyone know how plyr does it?

new Vue({
  el: '#range',
  data: {
    valueMax:100,
    duration:100,
    current:0,
    totalDuration:'1:40'
  },
  computed:{
    currentTime: function() {
      return this.convertTime(this.current);
    },
     valueNow() {
      return Math.round(this.current);
    },
  },
  methods: {
    convertTime(time) {
      const minutes = Math.floor(time / 60);
      const seconds = time - (minutes * 60);
      return `${minutes}:${seconds.toFixed(0).toString().padStart(2, '0')}`;
    },
  },
  mounted: function(){
   var self = this;
   setInterval(function(){
     self.current = Number(self.current) + 1;
     if(self.current >= self.valueMax){
        self.current = 0;
     }
    },2000);
  },
});
.audio-file-player__slider-range{
  border:1px solid red;
  width:100%;
}

.audio-file-player__slider-range:focus {
  box-shadow: 0 0 10px blue;
}

  <input
         aria-label="Seek"
         aria-valuemin="0"
         autocomplete="off"
         class="audio-file-player__slider-range u-color-gray-111111 u-width-100"
         min="0"
         role="slider"
         step="1"
         type="range"
         v-bind:aria-valuemax="valueMax"
         v-bind:aria-valuenow="valueNow"
         v-bind:aria-valuetext="currentTime + ' of ' + totalDuration"
         v-bind:max="duration"
         v-model="current"
         />

current: {{ current }}

aria-valuenow: {{ valueNow }}

aria-valuetext: {{ currentTime + ' of ' + totalDuration }}

A: For anyone who comes across this the easy solution is to override the value using aria-valuetext.
When the item is playing I would set the aria-valuetext to 'current: currentTime, remaining: remainingTime' when it first receives focus.
Then do not update the time while the item is playing (leave the aria-valuetext alone).
Then when play is paused / stopped change the aria-valuetext again to reflect the current time.
Finally I would update the current time on a throttle of say 200ms for when someone is seeking using the arrow keys.
You can decide whether to do this while playing or only when not playing as I am not sure which is the best solution in terms of information vs interruption.
I would lean towards not updating while playing as a user could always tab to the current time if you made that focusable.
By doing this you can ensure that it does not interfere with playing music or announce 200 different times.
plyr.io theory - it repeated for me too at first, then I changed my settings on announce speed. I believe the reason some people do and some people don't get announcements is the speed at which they update the current time (looks like 3-4 times a second) and I think that repeats so quickly that the Screen Reader decides not to confuse the user with it. Only a theory but my best guess as they aren't doing anything clever I can see.

A: Turn your song path into a computed property then get its currentTime. Like below:
<template>

Audio Player Test

    <audio
      ref="myMusic"
      src="https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3"
      @timeupdate="onTimeUpdateListener"
    ></audio>
    {{currentTime}}
    <button @click="play">Play</button>
    <button @click="pause">Pause</button>

</template>

data() {
    return {
      songCurrent: 0,
      currentTime: "00:00" // The initial current time
    };
},
computed: {
    song() {
      return this.$refs.myMusic;
    }
}
methods: {
    play() {
      this.song.play();
    },
    pause() {
      this.song.pause();
    },
    onTimeUpdateListener: function() {
      // Update current time
      this.currentTime = this.$refs.myMusic.currentTime;
    }
  }


text:
Q: multi-label classification error based on tf.slim When build tfrecord, I have encoded the labels as N-hot encoding.
Then I comment the following code:
labels = slim.one_hot_encoding(
labels, dataset.num_classes - FLAGS.labels_offset)

But it crash when train:
Traceback (most recent call last):
  File "../train_image_classifier_multilabel.py", line 620, in <module>
    tf.app.run()
  File "/root/anaconda3/lib/python3.6/site-packages/tensorflow/python/platform/app.py", line 126, in run
    _sys.exit(main(argv))
  File "../train_image_classifier_multilabel.py", line 519, in main
    clones = model_deploy.create_clones(deploy_config, clone_fn, [batch_queue])
  File "/root/Projects/scene-tf/slim/deployment/model_deploy.py", line 193, in create_clones
    outputs = model_fn(*args, **kwargs)
  File "../train_image_classifier_multilabel.py", line 513, in clone_fn
    label_smoothing=FLAGS.label_smoothing, weights=1.0)
  File "/root/anaconda3/lib/python3.6/site-packages/tensorflow/python/ops/losses/losses_impl.py", line 676, in sigmoid_cross_entropy
    logits.get_shape().assert_is_compatible_with(multi_class_labels.get_shape())
  File "/root/anaconda3/lib/python3.6/site-packages/tensorflow/python/framework/tensor_shape.py", line 764, in assert_is_compatible_with
    raise ValueError("Shapes %s and %s are incompatible" % (self, other))
ValueError: Shapes (32, 63) and (32,) are incompatible

The sigmoid_cross_entropy encounters problem:
tf.losses.sigmoid_cross_entropy(
logits=logits, multi_class_labels=labels,
label_smoothing=FLAGS.label_smoothing, weights=1.0)

Obviously, the shape of logits is   (32, 63)  and labels is  (32,) .
It seems that the comment of one_hot_encoding is wrong.
But I don't know how to fix it.


text:
Q: Fprintf functions in c programs that arent redirected with stdout I've created a C program in Unix where fprintf is declared like this:
       #Include<stdio.h>
        ...
       fprintf(stdout,"Example\n");

The problem is when I try to redirect stdout to another file like this:
      $./ExampleProgram > file.txt

The expected result is to have is Example inside the file, but instead the output is like this one (I type on command promt lines 00 and 02 below):
     00. BASH4.1$./ExampleProgram > file.txt
     01. Example
     02. BASH4.1$cat file.txt
     03. BASH4.1$

If I redirect the stderr the output is like this one:
     00.BASH4.1$./ExampleProgram &> file.txt
     01.BASH4.1$ cat file.txt
     02.BASH4.1$

There's no output at all
Any idea why this is happening?
EDIT: The problem may be the Buffer of the fprintf but I've tried to fix it using fflush(stdout) but it doesn't work
EDIT2: Added more details.

A: I have just tested the example you've listed above. It worked just fine.
Here's the code for the example test c-file:

#include <stdio.h>

int main()
{
   fprintf(stdout,"Example\n");
   return 0;

}

compile with : gcc example.c -o example
I used bash environment to compile and run.
Maybe you forgot to include stdio.h ?


text:
Q: Generate C# delegate method stub in VS 2010? There are a similar question Generate a C# delegate method stub and a feature request at microsoft.com Generate method stub should support non-existent method names passed as delegates referenced in its author's blog (No "Add Method Stub" When Passing or Assigning Delegates).  In the question they said the feature was going to be available in VS 2010, and the feature request is marked as fixed.  However, I don't get any hints for creating delegate handlers in my code (using VS 2010).  How is this and what am I doing wrong?  Here is an example code:
class BaseEditor { }

delegate void ObjectEditorCreatedDelegate( BaseEditor editor );

class ArrayPropertyEditor
{
    public ObjectEditorCreatedDelegate OnObjectEditorCreated;
}

class SomeUserCode
{
    public void someMethod()
    {
        ArrayPropertyEditor ape = new ArrayPropertyEditor();
        ape.OnObjectEditorCreated = new ObjectEditorCreatedDelegate( OnEditorCreated );
        // -------------------------------------------------------------------------^
    }

    private void OnEditorCreated( BaseEditor editor ) { }
}

When the cursor is at the pointed place (after OnEditorCreated usage) and OnEditorCreated is not yet created, VS 2010 suggests "generate property stub" and "generate field stub".  How do I generate a method?


text:
Q: "Telephone" is a required value in customer edit form I have overrided customer edit form. But while saving record I'm getting error message

"Telephone" is a required value.

I don't want telephone field. So in my form telephone field is not there but still error is coming.

A: There is a Magento2 feature that is by default telephone field is required.
    There is a lot of discussion on below topic:
https://github.com/magento/magento2/issues/1691
There is also a suggestion on this topic that we can make it optional by running SQL script
update eav_attribute set is_required=0 where attribute_code='telephone';

Read full topic and then run the query.
Note: Take a backup of DB before making any change.
After run query check eav_attribute table and make sure attribute column value changed to is_required to 0.
Run reindex command for attributes only
php bin/magento indexer:reindex catalog_product_attribute

and delete all cache and static files, compile and regenerate code by below command
php bin/magento setup:di:compile
php bin/magento setup:static-content:deploy

Hope this will help you.

A: You can remove telephone field from using following changes.

*

*Using sql query update eav_attribute set is_required=0 where attribute_code='telephone';

*Modified
Magento\Sales\Model\Order\Address\Validator::validateForCustomer()

*Modified Magento\Customer\Model\ResourceModel
\AddressRepository::_validate()

*Modified Magento\Customer\Model\Address\AbstractAddress::validate()

A: I followed the steps in the answer by akgola, except instead of following the step:
php bin/magento indexer:reindex catalog_product_attribute

I instead ran
php bin/magento indexer:reindex customer_grid

and this worked for me. It is a customer and not product attribute being updated, so that is probably why that answer isn't working for others?


text:
Q: PHP upload error - Invalid argument supplied for foreach() I have an error with my photo upload form.
I have two fields, one for multiple photos and one for an archive.
<input type="file" name="file[]" multiple="multiple" class="custom-file-input" id="file_upload_gallery" accept="image/*"/>

<input type="file" name="file" class="custom-file-input" id="file_upload" accept="application/zip, application/rar" /> <span class="custom-file-control">

And my PHP script, that throws an error - Invalid argument supplied for foreach()
<?php
    if (!is_dir($_SERVER['DOCUMENT_ROOT']. '/user_uploads/' . $_POST['user_name'] . '/')){
        mkdir($_SERVER['DOCUMENT_ROOT']. '/user_uploads/' . $_POST['user_name'] . '/');
        foreach($_FILES['file']['name'] as $key=>$filename) {
            print_r($_FILES);
            if(move_uploaded_file($_FILES['file']['tmp_name'][$key], $_SERVER['DOCUMENT_ROOT']. '/user_uploads/' . $_POST['user_name'] . '/' . $filename)) {
                $uploaded[] = $filename;
            }
        }
        echo json_encode($uploaded);
    } else {
        foreach($_FILES['file']['name'] as $key=>$filename) {
            print_r($_FILES);
            if(move_uploaded_file($_FILES['file']['tmp_name'][$key], $_SERVER['DOCUMENT_ROOT']. '/user_uploads/' . $_POST['user_name'] . '/' . $filename)) {
                $uploaded[] = $filename;
            }
        }
        echo json_encode($uploaded);
    }
?>

Where's a problem? Please help!
Thank you!

A: May be problem in the name you use same name file for the two input.
and also for this
foreach($_FILES['file[]']['name'] as $key=>$filename) {

you need to write
foreach($_FILES['file']['name'] as $key=>$filename) { // Omit the [] from file


text:
Q: calculating uniformity for a 64 by 64 image I am fairly new to python and to programming in genral. I've been trying to calculate uniformity for an image using python and its libraries. The image is in a 64 by 64 matrix padded with zeros, because detector size is smaller than the "image". Before calculating, I have to smooth the image using weighted kernel: ([[1,2,1], [2,4,2], [1,2,1]]).
But before smoothing I have to set the values of border pixels accordingly:

*

*Any pixels at the edge of useful field of view (ufov) containing containing less than 75% of mean value in central field of view (75% of ufov), shall be set to zero.

*Pixels which have at least one of their four directly abbuted neighbors containing zero, shall be set to zero.

*The weighting factor for a pixel outside the analysed area in 9 point filter, shall be zero.
I've used ma.masked_equal to exclude the padded area. But I am having troubles to apply above conditions. Not to mention applying them only to the edge of the useful field of view.
As English is not my first language, I hope I've explained understandably. Otherwise I aplogize.
import numpy as np
import numpy.ma as ma
import scipy
from scipy import ndimage

#ufov = useful field of view - non-zero elements
#cfov = central field of view - in this example 50% of ufov

img = ([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 2, 0, 2, 0, 0, 1, 0, 8, 0, 7, 0, 0, 0],
        [0, 0, 0, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 0, 0, 0],
        [0, 0, 0, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 1, 0, 0],
        [0, 0, 0, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 0, 0, 0],
        [0, 0, 0, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 0, 0, 0],
        [0, 0, 0, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 0, 0, 0],
        [0, 0, 6, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 0, 0, 0],
        [0, 0, 6, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 0, 0, 0],
        [0, 0, 0, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 0, 0, 0],
        [0, 0, 0, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 0, 0, 0],
        [0, 0, 0, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0, 0, 4, 1, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]])

img = ma.masked_equal(img, 0) #mask zeros

axis_0 = ma.notmasked_edges(img,0) #start/end masked pixel value along axis=0
axis_1 = ma.notmasked_edges(img,1) #start/end masked pixel value along axis=1

xstart = min(axis_1[0][1]) #start along x axis -rows (last masked pixel)
xend = max(axis_1[1][1]) #end along x axis -rows (last masked pixel)

ystart = min(axis_0[0][0]) #start along y axis -columns (last masked pixel)
yend = max(axis_0[1][0]) #end along y axis -columns (last masked pixel)

ufov = img[ystart:yend+1, xstart:xend+1] #ufov sliced along the masked array edge

#cfov is 50% of ufov(sliced from ufov)

cfovystart = int((ufov.shape[0] - ufov.shape[0] * 0.5)/2)
cfovyend = int(ufov.shape[0] - cfovystart)
cfovxstart = int((ufov.shape[1] - ufov.shape[1] * 0.5)/2)
cfovxend = int(ufov.shape[1] - cfovxstart)

cfov = ufov[cfovystart:cfovyend, cfovxstart:cfovxend]

#1. condition - applied over the whole ufov (want edges)
#pixels containing less than 75% of cfov mean value are replace with 0
mean = int(cfov.mean()*0.75)

ufov[ufov < mean]=0

#2. condition
#pixels which have at least one of their four directly abbuted neighbors containing zero
#shall be set to zero ???

#3.condition
#the weighting factor for a pixel outside the analysed are in 9 point filter
#shall be zero ???

#smoothing befor calculating (but not including the 3.condition
weights = np.array([[1,2,1],
                   [2,4,2],
                   [1,2,1]])

kernel = weights*1/16

img_smth = ndimage.convolve(ufov, kernel, mode="constant", cval=0)

#then calculate the uniformity of ufov - useful field of view as follows

#max_pix = int(ufov.max())
#min_pix = int(ufov.min())

#unif_ufov = (max_pix-min_pix) / (max_pix+min_pix) * 100


text:
Q: How to position a border at the top? It should be simple, but I don't know how. What I want is that the .current class adds a border to the current list item within the navigation menu.
I've done this already (see example: http://codepen.io/anon/pen/jARqOr)
But I would like to have the border aligned to the top of the header, like in this imag (the red border):

What should I do to get this result?
Looking forward to your response.
Thanks.

A: I'm not sure if this is the best solution, but this worked:
ul li a.current {
  padding-top: 50px;
  margin-top: -55px;
}

Setting margin-top to -55px (the negative value of the header's padding) takes it to the top, and then adding a padding-top of 50px (55px - 5px for the border) brings the text down to be even with the other anchor elements.
One issue with this solution is that all the space above the .current anchor is part of the clickable area.

A: I haven't seen your comment
black is Photoshop
anyways this code just use CSS.
see output you want just using CSS
-- CSS --
  ul li a.current {
             border-top: 4px solid #000;
            /*box-shadow:  0px -5px 0px black;*/
             padding :0px 5px 5px 5px;
             color: red!important;
   }

   ul li a.current span {
            padding:5px 0px ;
            border-top: 2px solid red;
            /*box-shadow: 0px -2px 0px red;*/

   }

--- same size double border then
use this CSS instead
 ul li a.current {
      box-shadow:  0px -5px 0px black,  /* add as many as you want */
      inset  0px 2px 0px red;
      padding:5px;
      color: red!important;
    }

A: You could try something like this:
ul .current a {
    padding-top: 42px;
    background: linear-gradient(to bottom,  #005f37 0%,#005f37 100%);
    background-size: 100% 7px;
    background-repeat: no-repeat;
    color: #006038;
}

It works for me


text:
Q: Metaphors about death What are some sayings or metaphors that would interact well with a massacre or calamity?
for example "The crows feasted for days"

A: Individual death:

*

*Met his Maker.

*Bought the farm.

*Kicked the bucket.

*Bought the big one.

*Is pushing up daisies.

*Went on to his reward.

*Shuffled off this mortal coil.
Huge number of deaths:

*

*genocide

*massacre

*carnage

*extinction

*bloodbath

*internecine

*life is cheap

*Armageddon

*depopulated

*mass carnage

*angel of death (biblical reference - see Passover)

*rained death (attack from the sky)

*scorched earth (destruction of property as well as killing of people)

*reign of terror (ongoing government-sanctioned killing)

*dropping like flies

*not a man left standing

*plague, epidemic, scourge (death by disease)

*smell of death in the air

*not a soul left to tell the tale

*ground littered with corpses

*corpses rotting in the streets

A: You might have better luck if you start with some of the specifics details.
If there was a lot of blood for example you could go with:
The "x" ran red with blood.
*substitute x with your choice of rivers, streets, halls etc.
The wet smell of iron hung in the air.
Or if there were fires burning, then the black ash could darken the sky.
Or if there were survivors then the moans of their suffering could fill the location.
Or you could just Lovecraft it and say it was incomprehensible in some respect. That works well if it's some inconceivably graphic scene.


text:
Q: Modify Address Magento 2.1.3 Magento is confusing. I want to modify how the address in the front end displays but I can't locate where it should be modified.
In the checkout page,the address fill out form shows in this order:

*

*Street Address

*Municipality

*Prefecture

*Zip Code

*Country

But I want it in japan address format:

*

*Country

*Zip Code

*Prefecture

*Municipality

*Street Address

Do you have any tips on how to find the page easily?

A: Generally the address formats are contained in app/code/core/Mage/Customer/config.xml look for some markup like this:
<default>
  <customer>
    <address_formats>
     <text><![CDATA[{{depend prefix}}{{var prefix}} {{/depend}}{{var firstname}} {{depend middlename}}{{var middlename}} {{/depend}}{{var lastname}}{{depend suffix}} {{var suffix}}{{/depend}}
{{depend company}}{{var company}}{{/depend}}
{{if street1}}{{var street1}}
{{/if}}
{{depend street2}}{{var street2}}{{/depend}}
{{depend street3}}{{var street3}}{{/depend}}
{{depend street4}}{{var street4}}{{/depend}}
{{if city}}{{var city}},  {{/if}}{{if region}}{{var region}}, {{/if}}{{if postcode}}{{var postcode}}{{/if}}
{{var country}}
T: {{var telephone}}
{{depend fax}}F: {{var fax}}{{/depend}}}]]></text>
    </address_templates>
  </customer>
</default>

or you can try this one also -
Go to:
`STORES->Configuration->Customer->Customer Configuration -> Address Templates`.

There you find the same code as in the XML file.


text:
Q: Java - Implementing sorting algorithms the 'right' way I'm currently playing with implementing various sorting algorithms in Java, mostly for fun, but I'm struggling with how to do it 'right'. That is, I want the user to be able to call the sorting algorithm of choice on anything that is comparable - ints, longs, Strings, booleans (actually, are these comparable in Java?), their own classes; whatever. The question is how to do this.
I was thinking of using a class to represent the sorting algorithm, and therefore store the things to be sorted inside using a generic list or whatever (List<E>). This would also allow me to use multiple constructors and thus allow the user to pass in the data in various forms - Lists, Arrays, whatever. Is this the correct way to do it? My current problem is that I don't wish for the user to have to create a class when they want to sort something, I'd rather it was able to be called much like System.out.println or the like.
// Example:

int[] myInts = {5,4,3,2,1};

// This is what I do *not* want.
InsertionSort mySort = new InsertionSort();
int[] sortedInts = mySort.sort(myInts);

// This is more like what I want.
int[] sortedInts = Sorting.insertionSort(myInts);

I apologise with what may seem like a basic question, but I am just learning my way with programming languages. Which is a bit ridicolous for a 2nd year Computing student working at a software company for his summer job, but you'd be surprised at how little programming knowledge is required for most of my work... it's usually more design knowledge.
EDIT:
For clarity, my three main question are:

*

*Is it better to have the user create a class to do the sorting, or to have a static method in a class the user imports?

*Is it possible to deal with both primitive data types and generic objects easily? Since I want to be able to handle any generic object that implements comparable (or likewise), this then causes problems with primitives (as they don't implement anything ;) ).

*What is the best way to handle generic input - what should I check for before I try to sort them (implementing Comparable, for example)?

A: You could take as example the way Collections provides the binarySearch operation ... And indeed, the
int[] sortedInts = Sorting.insertionSort(myInts);

is more java-way, even if I would personnally prefer
public class Sorting {
     public static <DataType extends Comparable> Iterable<DataType> insertionSort(Iterable<DataType> data);
}

*

*<DataType> ensure output data is of the same type than input

*Iterable<DataType> data input data is an iterable, to ensure maximum compatibility. Obviously, using a List would be by far simple, as it allows internal item reordering. Howeve"r, using an iterable ensure the implementor of this method will have to re-create the list in order to modify it, guaranteeing that the input list is left unchanged, and that the output list is another one.

Since I just saw you edit your question, let me reply to it point by point (and consider chosing an answer after that, as it is easier to add new questions than to edit existing ones endlessly - unless you make your question a community wiki, like I do of this reply)

Is it better to have the user create a class to do the sorting, or to have a static method in a class the user imports?

To my mind, using a static method in this case is preferable, as you here have to manipulate objects you didn't create, in a quite "basic" fashion.

Is it possible to deal with both primitive data types and generic objects easily? Since I want to be able to handle any generic object that implements Comparable (or likewise), this then causes problems with primitives (as they don't implement anything ;) ).

Have you heard about autoboxing ? It's a feature of Java 5 which makes primary types "equivalents" of objects. That's to say int are automatically converted into Integer, which, as you know, implement Comparable.

What is the best way to handle generic input - what should I check for before I try to sort them (implementing Comparable, for example)?

Notice that, due to my method declaration (the ), checking that input data implements Comparable is not done by you, but by the Jav compiler, allowing your IDE to show you mistakes.

A: I think you answered your own question? If you want to expose a static method instead of making the user create and object and call an instance method, then just do that. Sorting.insertionSort() looks fine to me.
Internally that can dispatch to whatever you like. Inside, if you want to implement this with classes and polymorphism and whatnot, go ahead. It does seem like a bit overkill though. I am not sure inheritance and polymorphism help a lot here.

A: The normal way of implementing a sorting algorithm would be to implement a static method, e.g. take a look at the source code for Arrays.sort(). You can overload this method with diferent implementations for different parameter types (e.g. objects that implement comparable vs. provide your own comparator vs. primitive arrays etc.)
Here's one I wrote earlier:
public static <T> void swap(T[] a, int x, int y) {
    T t=a[x];
    a[x]=a[y];
    a[y]=t;
}

public static <T extends Comparable<? super T>> void mergeInOrder(T[] src, T[] dst, int p1, int p2, int p3, int p4) {
    if (src[p2].compareTo(src[p3])<=0) return; // already sorted!

    // cut away ends
    while (src[p1].compareTo(src[p3])<=0) p1++;
    while (src[p2].compareTo(src[p4])<=0) p4--;

    int i1=p1;
    int i3=p3;
    int di=p1;
    while(di<p4) {
        if (src[i1].compareTo(src[i3])<=0) {
            dst[di++]=src[i1++];
        } else {
            dst[di++]=src[i3++];
            if (i3>p4) {
                System.arraycopy(src,i1,dst,di,p2-i1+1);
                break;
            }
        }
    }

    System.arraycopy(dst, p1, src, p1, (p4-p1)+1);
}

public static <T extends Comparable<? super T>> void mergeSort(T[] src, T[] dst, int start, int end) {
    if (start+1>=end) {
        if (start>=end) return;
        if (src[start].compareTo(src[end])>0) {
            swap(src,start,end);
        }
        return;
    }

    int middle=(start+end)/2;
    mergeSort(src,dst,start, middle);
    mergeSort(src,dst,middle+1, end);
    mergeInOrder(src,dst,start,middle,middle+1,end);
}

private static ThreadLocal<Comparable<?>[]> mergeSortTemp=new ThreadLocal<Comparable<?>[]>();

@SuppressWarnings("unchecked")
public static <T extends Comparable<? super T>> void mergeSort(T[] src) {
    int length=src.length;
    Comparable<?>[] temp=mergeSortTemp.get();
    if ((temp==null)||(temp.length<length)) {
        temp=new Comparable[length*3/2];
        mergeSortTemp.set(temp);
    }
    mergeSort(src,(T[])temp,0,length-1);
}

However, I can think of two good reasons to implement a sorting algorithm as a class where you generate your own instance:

*

*It lets you polymorphically pass around instances of sorting algorithms - this could be useful if e.g. you were creating a collection of sorting algorithms and wanted to run lots of benchmarks on them for example.

*You can have private state in the sorter instance - this is useful for some sorting algorithms, e.g. having some pre-allocated arrays for temporary storage, and it makes sense to put it in a class instance if you want to be able to simultaneously use different sort instances from multiple threads - a static method implementation would need some form of synchronisation (e.g. see the use of the ThreadLocal in the code above).

A: I'm not sure if this is what you are struggling with ... but it is next to impossible to implement an algorithm that works both for reference types and (real) primitive types.  The reason is the Java type system does not have a notional universal type that has the primitive types and Object as subtypes.
The normal workaround for this is to wrap the primitive types using their corresponding wrapper classes; e.g. Integer for int, Boolean for bool and so on.  This allows you to implement (for example) a sorting algorithms that for for any Collection<T> or any <T>[].
This approach has performance / memory usage issues when applied to large arrays of (say) integers.  Either you wear the performance hit, or you implement the algorithm and its supporting classes separately for each primitive type.
(I said next to impossible, because it is possible to abstract the comparison of a pair of array elements and swapping of a pair of array elements in a way that doesn't expose the actual element type in the interface; e.g.
public interface ArraySortAdapter {
  public abstract int compareElements(Object array, int pos1, int pos2);
  public abstract void swapElements(Object array, int pos1, int pos2);
}

and provide different implementations for different array types; e.g.
public class IntArraySortAdapter implements ArraySortAdapter {
  public int compareElements(Object array, int pos1, int pos2) {
      int[] intArray = (int[]) array;
      if (intArray[pos1] < intArray[pos2]) {
          return -1;
      } else if (intArray[pos1] > intArray[pos2]) {
          return +1;
      } else {
          return 0;
      }
  }

  ...
}

However, this is cumbersome and inefficient, to say the least ...)


text:
Q: Push notification with non-public image Is there a way of adding a non-public image, i.e. one at a URL that requires authentication, to a push notification? From what I've read you can only supply an image URL in the notification payload, and that URL is fetched by the OS (Android/iOS), not the associated app.
If it isn't possible, does anyone know of a best practice workaround? A time-limited URL was one thing that sprung to mind.
Using FCM.
I'm not the developer on this issue btw (or a mobile dev in any sense), just asking as an interested party.

A: Apologies, I read it as you are using firebase storage, if you are:
In firebase storage, you can see to the right of a selected image, under the preview, a drop down called 'file location' here you can see storage location and an access token. If you click the access token it will copy a link with the access token.
This should be sufficient for the task


text:
Q: Set cookies in Android WebView I know there are a number of questions related to this topic but none of them has worked for me.
I have a String that contains some cookies in the form key=value; key=value; ....
My app:
public class MainActivity extends AppCompatActivity {

    private WebView webView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        webView = new WebView(this);
        setContentView(webView);

        configWebView();
        loadCookies();
   }

    @SuppressLint("SetJavaScriptEnabled")
    void configWebView() {
        webView.getSettings().setJavaScriptEnabled(true);
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
                 Map<String, String> requestHeaders = request.getRequestHeaders();
                 return super.shouldInterceptRequest(view, request);
            }
        });
    }

    void loadCookies() {
        // Do things
        loadPage(cookies);
    }

    void loadPage(String cookies) {
        CookieManager cookieManager = CookieManager.getInstance();

        for (String cookie : cookies.split(";")) {
            cookieManager.setCookie(DOMAIN, cookie.trim());
        }
        cookieManager.flush();

        webView.loadPage(URL);
    }
}

I don't see the result I'm expecting and if I inspect the content of requestHeaders, I see there are no Cookies passed to the server.
What am I missing?


text:
Q: calculate object size in a image I have a camera with 73º diagonal field of view and a 1/4' sensor capable of doing 1280*720
I have a fixed distance from certain object and I want to measure it on the photos taken by the camera...
I thought about trying to get the amount of centimeters by pixel giving a certain distance and the field of view angle... I don't know if this is the right way to do it....
Can someone point me to the right way and / or explain how to accomplish...
thanks a lot

A: Ok I think I have it figured out for you -
Tan 45 = 1
// this is important

sqareroot(1280squared + 720squared) = 1468.6
// this is the diagonal measured in pixels widths

73/2 = 36.5
// this is half the diagonal view angle.

1468.6/2 = 734.3

Tan 36.5 = 0.73996

734.3 / 0.73996 = 992.3509
// this is the amount of pixels you would need
// to see 45 degrees from the center of the frame.

So to measure your object you would need to do -
((pixelDimensionOfObject / 2) / 992.3509) * distance from object = size of object.

Be aware though, that I think in order for this to be correct the object you a photographing and measuring must be in the center of the frame. Otherwise I think it becomes a lot more complicated.

A: i think this can work the other way around where we want to know the distance of the object and we know the object's real size


text:
Q: How to delete DOM element and related array index at same time? Edit: Never mind...I give up...I'm done with studying web dev...
I have an array (myLibrary) of "book" objects that are pushed into said array when a user submits input from a form.
let myLibrary = [];

function Book(title, author, pages, read) {
  this.title = title;
  this.author = author;
  this.pages = pages;
  this.read = read;
}

function addToLibrary() {
  let Newbook = new Book(
    titleInput.value,
    authorInput.value,
    pagesInput.value,
    readInput.checked
  );

  myLibrary.push(Newbook);
}

Upon submitting, a card is also generated on the DOM displaying the information from the form. I also add a delete button on each dynamically generated card. I am able to delete the card itself using an event listener (in bold), but I am unable to also delete the related object in the array.
function renderBookCard() {
  const newCard = document.createElement("div");
  const removeBook = document.createElement("img");
  const bookTitleDiv = document.createElement("div");
  const titleLabel = document.createElement("p");
  const dynamicTitle = document.createElement("p");
  const authorDiv = document.createElement("div");
  const authorLabel = document.createElement("p");
  const dynamicAuthor = document.createElement("p");
  const pagesDiv = document.createElement("div");
  const pagesLabel = document.createElement("p");
  const dynamicPages = document.createElement("p");
  const readDiv = document.createElement("div");
  const dynamicRead = document.createElement("p");
  //
  MainBookContainer.appendChild(newCard);
  newCard.appendChild(removeBook);
  removeBook.classList.add("trash");
  removeBook.setAttribute(
    "src",
    "./Images/delete_FILL0_wght400_GRAD0_opsz48.svg"
  );
  newCard.classList.add("book-card-container");
  newCard.appendChild(bookTitleDiv);
  bookTitleDiv.classList.add("book-title");
  newCard.appendChild(titleLabel);
  titleLabel.textContent = `Title:`;
  newCard.appendChild(dynamicTitle);
  newCard.appendChild(authorDiv);
  authorDiv.classList.add("book-author");
  newCard.appendChild(authorLabel);
  authorLabel.textContent = `Author:`;
  newCard.appendChild(dynamicAuthor);
  newCard.appendChild(pagesDiv);
  pagesDiv.classList.add("book-pages");
  newCard.appendChild(pagesLabel);
  pagesLabel.textContent = `Pages:`;
  newCard.appendChild(dynamicPages);
  newCard.appendChild(readDiv);
  readDiv.classList.add("book-read");
  newCard.appendChild(dynamicRead);

  //
  let i;
  for (i = 0; i < myLibrary.length; i++) {
    dynamicTitle.textContent = myLibrary[i].title;
    dynamicAuthor.textContent = myLibrary[i].author;
    dynamicPages.textContent = myLibrary[i].pages;
    if (!readInput.checked) {
      dynamicRead.textContent = "Unread";
    } else {
      dynamicRead.textContent = "Read";
    }
  }

  //

  **newCard.addEventListener("click", function (e) {
    if (e.target.classList.contains("trash")) {
      newCard.remove();
      myLibrary.splice([i], 1);**

    }
  });
}

How am I able to delete the card and the related object in the array? I hope I was able to ask in a clear way. If not I apologize.

A: Here is my example. I think it might help you.
*If you have many elements to append to your HTML feel free to use insertAdjacentHTML or other methods, this will help you easily to organize your code.
*In my case, I use the filter method to update my list.

let bookList = [];

const addBook = document.querySelector("#add_book");
const bookWrap = document.querySelector("#book_wrap");

addBook.addEventListener("click", () => {
  const bookName = document.querySelector("#book_name");
  const bookAuthor = document.querySelector("#book_author");

  bookList.push({
    book_name: bookName.value,
    book_author: bookAuthor.value
  })

  const bookTemplate = `

${bookName.value}

${bookAuthor.value}

        <button id="trash_${bookName.value}">Trash</button>

`;

  bookWrap.insertAdjacentHTML("beforeend", bookTemplate);
  // console.log(bookList)

  document.querySelector(`#trash_${bookName.value}`)
    .addEventListener("click", (e) => {
      e.target.closest(".book").remove();
      bookList = [...bookList.filter(item => item.book_name !== e.target.id.split("_")[1])]

      // console.log(bookList)
    })

  bookName.value = null;
  bookAuthor.value = null;
})
.book-wrap {
  min-width: 250px;
  min-height: 200px;
  border-radius: 10px;
  border: 1px solid black;
  margin: 20px 0;
  padding: 20px;
}

.book {
  display: flex;
  justify-content: space-between;
  width: 200px;
  gap: 40px;
  margin-bottom: 20px;
}

h2,
p{
  margin: 0;
}

p {
  color: #999;
}

    Book name:

    <input id="book_name" type="text" />

    Author name:

    <input id="book_author" type="text" />

    <button id="add_book">Add Book</button>

Hope this might help you.
Enjoy the journey into Web dev.


text:
Q: MKPinAnnotationView red pin is replaced with image I have replaced the MKPinAnnotationView red pin  with an image in
-(MKAnnotationView *)mapView:(MKMapView *)mV viewForAnnotation:(id <MKAnnotation>)annotation
{
MKAnnotationView *annotationView=[mapView dequeueReusableAnnotationViewWithIdentifier:parkingAnnotationIdentifier];
//If one isn't available, create a new one
if(!annotationView){
annotationView=[[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:parkingAnnotationIdentifier];
//Here's where the magic happens
annotationView.image=[UIImage imageNamed:@"dot.png"];
}
return annotationView;
}

Now i have a detail disclosure when I click on any button it will go to the detailed page of that annotation.
Up to here its fine. Now the problem is that when I come back to the map view again from the detail page the default red pin appears instead of dot.png because when a view is loaded for the first time -(MKAnnotationView *)mapView:(MKMapView *)mV viewForAnnotation:(id <MKAnnotation>)annotation
 this method is called but when we come back from the detail page view will appear is not getting called. How to resolve this issue?
if ([list_array count]>0) {
        location1.latitude = [[[list_array objectAtIndex:0]valueForKey:@"latitude"]floatValue];
        location1.longitude = [[[list_array objectAtIndex:0]valueForKey:@"longitude"]floatValue];
        region.center = location1;

        if ([[list_array objectAtIndex:0]valueForKey:@"company_id"]) {
            for (int i=0; i<[list_array count]; i++)
            {
                CLLocationCoordinate2D location1;
                location1.latitude = [[[list_array objectAtIndex:i]valueForKey:@"latitude"]floatValue];
                location1.longitude = [[[list_array objectAtIndex:i]valueForKey:@"longitude"]floatValue];
                region.span = span;

                BasicMapAnnotation *addAnnotation1 = [[BasicMapAnnotation alloc] initWithLatitude:location1.latitude andLongitude:location1.longitude] ;
                addAnnotation1.tag = i;
                [mapView addAnnotation:addAnnotation1];
            }
        }
    }

    [mapView setRegion:region animated:TRUE];
    [mapView regionThatFits:region];
    //[self.view addSubview:self.mapView];

A: just add the whole pins or setRegion in viewWillAppear: or viewDidAppear: method
here viewForAnnotation is called again when we addAnnotation in MKMapView so just call it or also refresh it with setRegion method of MKMapView.
Or just remove these whole pins and add again in viewDidAppear: like bellow....
-(void)viewDidAppear:(BOOL)animated
{
    NSArray *existingpoints = mapView.annotations;
    if ([existingpoints count] > 0)
        [mapView removeAnnotations:existingpoints];

    if ([[list_array objectAtIndex:0]valueForKey:@"company_id"]) {
   for (int i=0; i<[list_array count]; i++)
   {
    CLLocationCoordinate2D location1;
    location1.latitude = [[[list_array objectAtIndex:i]valueForKey:@"latitude"]floatValue];
    location1.longitude = [[[list_array objectAtIndex:i]valueForKey:@"longitude"]floatValue];
    region.span = span;

    BasicMapAnnotation *addAnnotation1 = [[BasicMapAnnotation alloc] initWithLatitude:location1.latitude andLongitude:location1.longitude] ;
    addAnnotation1.tag = i;
    [mapView addAnnotation:addAnnotation1];
    }
}
   [mapView setRegion:region animated:TRUE];
   [mapView regionThatFits:region];
}

i hope this helpful to you...


text:
Q: Does MongoDB fit here? Modelling event registration with arbitrary extra data I'm writing a basic event registration web application and I'm wondering whether MongoDB would be a good choice for the datastore and if so, how to model my domain. The app will be very small, so performance and scalability is not a concern, however when I started to think out the model in RDBMS third-normal terms it sounded quite complicated for what it is and from the bits and pieces I'm picking up about Mongo, sounded like a typical use-case. Is it?
The Application
The app allows creation of events, and for attendees to sign up to those events, giving their name, date of birth, etc. Easy, two tables with n:n join. The tricky part is that the organisers wish to be able to ask attendees of certain events for information particular to that event, for example on one event there might be a question about their accomodation preference. I narrowed it down to two types of question: those that require to select from certain options (will be an HTML select list) and questions which allow free-text answers. By the way it's a Rails app in case that matters.
Traditional RDBMS
In an RDBMS I would need perhaps a table for Constrained Question (where answers are from a list), a table for Answer Options, a table for Free Text Question and Free Text Answers; and to appropriately link this all up to the event and the atendee via a Signup. If you think about it the links between the tables are rather complicated!
Mongo
Would this be simpler to model in Mongo? I thought that perhaps besides the Attendee and Event collections, there could be a Question collection which has its allowed answers embedded, if there are no answers then it's free text. A Signup collection that relates an Attendee to an Event and references the id of the relevant Question, and embeds the text of the answer? If the text of an answer option ever changes it might get complicated... but I guess that's the tradeoff of Mongo.
Is this a good use case for Mongo on should I stick with Postgres? Can you suggest a (or improve my) schema?

A: Mongodb is a awesome tool for this job. You can pretty much utilize the  embedded collection here to maximize the performance.
Your current schema is perfectly fine. By tweaking this a little bit with embedded collections , it will be a blast.
For instance, instead of keeping the Question collection seperately, you can have this inside Attendee. This will let you store all relevant info about the attendee in single place.
- Attendee
     - Info
     - Event_id
     - Questions {
           -Question id
           - Answers [ {
                 - answer id 1
                 - or answer text
             },{
                 - answer id 2
                 - or answer text
             }],
     }

Also you can cache the frequently used data about the attendees inside the Event collection.
This will be immensely useful for quickly displaying home page data.
For example, you may need to display the users who are attending the event and their count in the event home page. To do that you need to first query the event and query the Attendees.
But i suggest you to do store the attendee_id/name inside the Event as an array, which looks
  Event :
        - Info
        - attendees {
             attendee_id : 'xx'
             name : 'Fletch'
          }

So you can populate the event home page with a single db call to Event collection. Because you can get a minimum info to be displayed about the user and total user count for an event will be retrieved here itself. You can query the attendee when you need to display more info about the user like his question/answers.
Hope this helps


text:
Q: Titanium Orientation Change fired for landscape whenever im leaning iPad towards myself My function to get the orientation
function getOrientation(o) {
     switch (o) {
        case Titanium.UI.PORTRAIT: return 'portrait';
        case Titanium.UI.UPSIDE_PORTRAIT: return 'portrait';
        case Titanium.UI.LANDSCAPE_LEFT: return 'landscape';
        case Titanium.UI.LANDSCAPE_RIGHT: return 'landscape';
    }}}

Even listener triggered on orientationchange. This should only trigger an alert box when rotating from portrait to landscape and vise versa.
Ti.Gesture.addEventListener('orientationchange', function(e) {
     var orientation = getOrientation(e.orientation);

     if(orientation == 'portrait'){
         alert('portrait');
     }else if(orientation == 'landscape'){
         alert('landscape');
     }else{
         //do nothing
     }}

Why would I receive an alert for "landscape" whenever I am already in landscape view, and I tilt the top of my iPad towards me? It seems like that would be the 'face down' gesture. With the code above, I would expect to receive no alert. Any help would be greatly appreciated.

A: Even I've come across this while coding according to orientation.. I guess this happens since eventlistener listens to every single acceleration change in orientation while we use iPad.


text:
Q: TinyMCE javascript errors i Have downloaded TinyMCE and running examples. When i run any example and click on html button of TinyMCE GUI i am getting js errors

Permission denied for <file://> to get property Window.tinymce from <file://>.

  and

this.params is undefined

Check these errors in Firefox while opening firebug.

A: Browsers can be overly strict when loading files directly from the file system.  Try putting the examples on a web server and you'll probably find they work correctly.
Regards,
Adrian Sutton
http://tinymce.ephox.com


text:
Q: How is the `cov.unscaled` for `lm` calculated in R I just want to know how the the cov.unscaled calculated in R.
for example, if I fit a model:
fit <- lm(y~x)
summary(fit)$cov.unscaled

This should give me the answer, but how is it calculated?

A: Its the coefficients which aren't scaled by the variance
From the documentation:

cov.unscaled:  a p x p matrix of (unscaled) covariances of the coef[j],j=1, … p


text:
Q: How to add QPixmap for Display and Control button in PyQT4 I just started pyqt4.
My UI has two tabs Face and Human.
When I press Face tab or Human tab, I should see Display area displaying images from webcam at left side and Control group box at right side (includes push buttons, radio buttons etc).
I don't know how to make the whole UI, but prepare individual parts.
My existing code is as follow.
How should I continue?
import sys
import cv2
from PyQt4.QtCore import *
from PyQt4.QtGui import *

class Thread(QThread):
    changePixmap = pyqtSignal(QImage)

    def run(self):
        cap = cv2.VideoCapture(0)
        while True:
            ret, frame = cap.read()
            if ret:
                rgbImage = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
                convertToQtFormat = QImage(rgbImage.data, rgbImage.shape[1], rgbImage.shape[0], QImage.Format_RGB888)
                p = convertToQtFormat.scaled(640, 480, Qt.KeepAspectRatio)
                self.changePixmap.emit(p)

class Display(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    @pyqtSlot(QImage)
    def setImage(self, image):
        self.label.setPixmap(   .fromImage(image))

    def initUI(self):
        self.setWindowTitle(self.title)
        # create a label
        self.label = QLabel(self)
        self.label.move(280, 120)
        self.label.resize(640, 480)
        th = Thread(self)
        th.changePixmap.connect(self.setImage)
        th.start()

class Human(QWidget):
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)
        self.setLayout(QGridLayout())

        #Add display

        #Add control components
        layout = QVBoxLayout()
        self.b1 = QPushButton("Button1")
        self.b1.setCheckable(True)
        self.b1.toggle()
        self.b1.clicked.connect(lambda:self.whichbtn(self.b1))
        self.b1.clicked.connect(self.btnstate)
        layout.addWidget(self.b1)

    def btnstate(self):
      if self.b1.isChecked():
         print "button pressed"
      else:
         print "button released"

    def whichbtn(self,b):
      print "clicked button is "+b.text()

class Face(QWidget):
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)
        self.setLayout(QGridLayout())

        #Add display

        #Add control components
        layout = QVBoxLayout()
        self.b1 = QPushButton("Button1")
        self.b1.setCheckable(True)
        self.b1.toggle()
        self.b1.clicked.connect(lambda:self.whichbtn(self.b1))
        self.b1.clicked.connect(self.btnstate)
        layout.addWidget(self.b1)
    def btnstate(self):
      if self.b1.isChecked():
         print "button pressed"
      else:
         print "button released"

    def whichbtn(self,b):
      print "clicked button is "+b.text()

class Page1(QTabWidget):
    def __init__(self, parent=None):
        super(Page1, self).__init__(parent)
        self.face = Face()
        self.human = Human()
        self.addTab(self.face, "Face")
        self.addTab(self.human, "Human")

class MainWindow(QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.setGeometry(200, 200, 800, 600)
        self.startPage1()

    def startPage1(self):
        x = Page1(self)
        self.setWindowTitle("Face & Human")
        self.setCentralWidget(x)
        self.show()

def main():
    app = QApplication(sys.argv)
    main = MainWindow()
    main.show()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

UI I like to see is as follow.


text:
Q: Adding a new row in a UITableView HI Everyone,
It is my first post here and this is my problem:
I am trying to get some data from a REST API call and show then in a UITableView.
This s what I am doing:
in the viewDidLoad: 1) here I initialize my array of things to show in the Table (that is empty at the beginning) 2) the table is loaded (with 0 rows) and 3) then the HTTP async call is issued.
Done this I do my stuff with the HTTP Response and when ready I call the reloadData on my table. Here the strange happens.
numberOfRowsInSelection returns me the correct number of rows
but
tableView:cellForRowAtIndexPath:indexPath for the indexPath.row always returns me zero!
so no new row is added to the table.
  - (void)doJSONRequest{
    responseData = [[NSMutableData data] retain];

    NSString *addr = [[NSString alloc] initWithFormat:@"http://localhost:8080/blabla/v1/items?count=10"];
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:addr]];

    [[NSURLConnection alloc] initWithRequest:request delegate:self];
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    [addr release];
}

- (void)doJSONRequestWithURL:(NSString *)url{
    responseData = [[NSMutableData data] retain];

    NSString *addr = [[NSString alloc] initWithFormat:url];
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:addr]];

    [[NSURLConnection alloc] initWithRequest:request delegate:self];
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    [addr release];
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    //NSLog(@"[%@] connection:didReceiveResponse %@",[self class], response);
    [responseData setLength:0];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    //NSLog(@"[%@] connection:didReceiveData %@",[self class], data);
    [responseData appendData:data];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    NSLog(@"[%@]",[NSString stringWithFormat:@"Connection failed: %@", [error description]]);
    UIAlertView *alert = [[UIAlertView alloc] init];
    [alert setTitle:@"NETWORK ERROR!"];
    [alert setMessage:@"App will close"];
    [alert setDelegate:self];
    [alert addButtonWithTitle:@"Close"];
    [alert show];
    [alert release];
    [alert show];
    [alert release];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    //NSLog(@"[%@] connectionDidFinishLoading %@",[self class], connection);
    [connection release];
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;

    NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
    [responseData release];

    NSDictionary *res = [NSDictionary dictionaryWithDictionary:[responseString JSONValue]];

    NSDictionary *tmp = [res valueForKey:@"reviews"];
    tmp = [tmp valueForKey:@"reviews"];
    NSEnumerator *e = [tmp objectEnumerator];
    NSDictionary *tmp_review;

    int i=0;
    while (tmp_review = [e nextObject]) {
        //NSLog(@"tmp_review %@", tmp_review);
        //NSLog(@"count %d", i++);

            MyObject r = [... doing my staff...]
        [reviews addObject: r];
        [r release];
    };
    [reviewListTableView reloadData];
    [responseString release];

}

- (void)viewDidLoad {
//- (void)initUI {

    //review is the array where I put my data
    //it is empty at the beginning
    reviews = [[NSMutableArray alloc] initWithObjects:nil];
    [super viewDidLoad];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [reviews count]
}

A: Sounds like you may not have properly implemented numberOfSectionsInTableView:. You should log indexPath.section in tableView:cellForRowAtIndexPath:indexPath to see what section value you are passing. You will have multiple indexPath.row values of zero because there is a zero row for each section.

A: add new object in the array and [mytableview reloadData];

A: Implement following data source return number of section to be present in the table view.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView;

In tableView:cellForRowAtIndexPath:indexPath check section number and do your operation.
Note: If you don't need sections you can remove it.


text:
Q: SiteMinder web agent freeze with apached 2.4 (32bit) on Windows 2012 64 I am using Apached with Siteminder for single-sign on authentication. My config is as follow:
64 bit Windows 2012 (64) R1.
Apached 2.4, (32 bits) (We tried the 64 bits but it does not work with the siteminder agent, dll problem). It was downloaded from apache lounge
The problem i am facing today is that every hour the webagent freeze, and the authentication does not work until i restart apache.
Apache is used as a reverse proxy for Tomcat. The tomcat service runs well, no problem. But then i have to restart my apache all the time to keep the service on tomcat running properly.
My question is:

*

*has anyone ever experience a similar issue, where the SiteMinder web-agent somewhat freeze every now and then stopping the authentication service ? If yes, what did you do to solve it ?

*Is there a way to integrate SiteMinder to Tomcat directly? Is it recommended ? What can be the consequence of it ? Does the integration works with Tomcat 8 ?

*Is there any known issue between Siteminder and Windows 2012 ?
Best,
M


text:
Q: 1080p LCD not entirely filled up I have recently build a new machine with XFX ATi Radeon 5830 for GPU. I have an Asus LCD VH236H monitor which supports 1080p resolution yet when I have it set to the recommended 1080p resolution the screen is not entirely filled up. There is ~1cm (on top and bottom) and ~1.5cm (on right and left side) black frame. I would like to use the LCD's actual size to the fullest but I cannot do it when I use HDMI, unless there is something I am missing. Should I use DVI instead? Any help will be really appreciated. Thanks

A: While connected via HDMI and running at your intended resolution, go into the Catalyst Control Center and find Scaling Options under Digital Flat Panel. Move the slider to the right.
If that options screen isn't there, the black borders probably aren't coming from the ATI driver. Instead, try different options in your monitor's on-screen menu.

A: Go into the CCC and ensure that overscan is set to none. HDMI outputs typically contain overscan to account for old (say rear projection) screens, while DVI does not.
Also see Kill overscan for ATI drivers?.
I can't seem to find this option on fglrx with a DVI connector though.

A: Have you tried DVI?  If DVI resolves the problem (which it probably will), then use it instead.  I've found that HDMI doesn't always work as expected.

A: Possibly you may need to open your monitors settings, although with new monitors it might be different. Just press the button on the monitor, and usually you can stretch it to fill the empty space.


text:
Q: How to cast T[] to IEnumerable at runtime I have a Generic Function that needs to interpret a dynamic variable at runtime:
U[] HandleDynamic<U>(dynamic value)
    if (value is IEnumerable enumerable)
    {
        // get all typeof(T) for each implemented IEnumerable<T>
        Type[] types = enumerable
                        .GetType()
                        .GetInterfaces() // all implemented interfaces
                        .Where(x => x.IsGenericType && (x.GetGenericTypeDefinition() == typeof(IEnumerable<>))) // all IEnumerable<> interfaces
                        .Select(x => x.GetGenericArguments().First()) //  gets first of all generic arguments in each IEnumerable<> since IEnumerable<> only has one generic Type Argument
                        .ToArray();
        // get all constructors that accept a type in types
        foreach (Type type in types)
        {
            ConstructorInfo? ctor = typeof(U)
                            .GetConstructor(
                                BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance,
                                new Type[]
                                {
                                    type        // the first Generic type Argument of IEnumerable<> (-> T)
                                });

            if (ctor is not null)
            {
                return value.Select(new Func<dynamic, U>(o => (U)ctor.Invoke(new object[] { o }))).ToArray(); // Syntax Error here
            }
        }
    }
    throw new InvalidCastException();
}

If I have a custom class like so:
internal class LongProxy
{
    long _value;
    public LongProxy(long value)
    {
        _value = value;
    }
}

When I then call my code like so:
dynamic[] myDynamicArray = new long[10];
LongProxy[] myProxyArray = HandleDynamic<LongProxy>(myDynamicArray);

I get the Syntax error System.Array does not contain a definition for 'Select' at return ... in HandleDynamic. That kind of makes sense since value is still a dynamic{long[]}. How would I convert the array into an IEnumerable? I could use reflection (again), but I was hoping that something similar to (IEnumerable<dynamic>)value works as a cast. The correct cast would be IEnumerable<type>, but that doesn't work since type is a variable, not a Type.


text:
Q: Circles within ellipses What is the largest circle centered at $(x_0, y_0)$ that is totally enveloped by an ellipse with a major axis $A$ and minor axis $B$? In this problem, assume a constraint s.t. the major axis is in the $x$ direction. Alternate cases of the problem would be solved by a rotation of the major axis to the $x$ axis as a first step. Additionally, assume $(x_0, y_0)$ is within the ellipse. The ellipse is centered at $(0,0)$.
I think that the closed form solution is not guaranteed if neither $x_0$ nor $y_0$ are zero. I know a closed form solution can be found if either $x_0$ or $y_0$ is equal to zero.
Thank you for your time

A: Assuming the ellipse center is at $(0,0)$, here are some steps that can be followed to come up with the solution:

*

*Find the line normal to the ellipse passing through a generic point on the ellipse $(x_1, y_1)$.

The ellipse is $\frac{x^2}{A^2} + \frac{y^2}{B^2}=1$ (I). Taking derivatives: $\frac{2x}{A^2} + \frac{2 y y'}{B^2} = 0 \Rightarrow y'= - \frac{B^2 x}{A^2 y}$, which is the slope of the tangent line. The normal line is perpendicular to the tangent line, so its slope is $m_n=\frac{A^2 y}{B^2x}$. The normal line passing through $(x_1, y_1)$ is then: $y-y_1 = \frac{A^2 y_1}{B^2x_1} (x-x_1)$

*Impose that the normal line goes through the given point $(x_0, y_0)$ and that the point $(x_1, y_1)$ satisfies the equation of the ellipse. That is two equations and two unknowns; get $(x_1, y_1)$ as a function of $(x_0, y_0)$. In general, there will be two solutions.

The point $(x_0, y_0)$ should satisfy  $y-y_1 = \frac{A^2 y_1}{B^2x_1} (x-x_1)$, then:  $y_0-y_1 = \frac{A^2 y_1}{B^2x_1} (x_0-x_1)$ (II)
Solving the system of equations (I), (II) yields at most two solutions for $(x_1,y_1)$, say $(x_{11},y_{11})$ and $(x_{12},y_{12})$.

*The radius of the desired circle is the smallest of the distances between $(x_0, y_0)$ and, respectively, $(x_{11},y_{11})$ and $(x_{12},y_{12})$ (call it $d$).

$d=\min_{i \in\{1,2\}} \sqrt{(x_{1i}-x_0)^2 + (y_{1i}-y_0)^2} $, then the equation of the desired circumference (around the desired circle) is $(x-x_0)^2 + (y-y_0)^2 = d^2$.


text:
Q: Why I can't find g++ in my dictionary when I was trying to install "iRF" package in R? I was trying to install "iRF" in R.
Here is the error:
/bin/sh: /usr/local/bin/g++: No such file or directory
make: *** [ExportedFunctionsRIT.o] Error 127
ERROR: compilation failed for package 'iRF'
* removing '/Library/Frameworks/R.framework/Versions/4.2-arm64/Resources/library/iRF'

And when I turned into the terminal to see my g++ and gcc, I found them in a different path:
Apple clang version 14.0.0 (clang-1400.0.29.102)
Target: arm64-apple-darwin21.6.0
Thread model: posix
InstalledDir: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin

I never faced this before. I was trying to install gfortran and this error came when I installed xcode and gcc again. I'd appreciate it if someone could help me fix this. By the way, if you know how to install gfortran to deal with the compline error in installing packages form gihub, that would be nice.
Thanks!


text:
Q: Convert Flash art to OpenGL-ready vector format? Say I have some 2D artwork in Flash CS4 format .FLAs, and I'd like to put it into an iPhone game that uses OpenGL ES, keeping it in vector format. An OpenGL-ready format could just be a list of vertex positions and colors for a triangle strip.
Is there a converter available that can do that easily?

A: You could port gameswf to iPhone, it supports most SWF tags, it loads and renders in OpenGL. It's coded in C++ so it's easy to embed it into your iPhone application. Be warned that's it's usable but it has its limits.

A: Claus Wahlers's project looks pretty cool, check out: https://github.com/claus/as3swf/wiki/shape-export-to-objective-c

A: I would recommend converting the swfs to .svg format, Either in Illustrator, or with this online tool. I actually used a small java console app to automate this part for what I had to do recently, it worked pretty well.
Once that's done, you can use Qt to do the rendering bit for you as commented on here.

A: You could use smokescreen to convert the flash to html5, and then use the stock HTML viewer found In interface builder. Just my 2 cents.


text:
Q: Get different sets of numbers with repetition I have a list of numbers:
lst = [1, 2, 3, 1,4]

def permutation(lst):
    # If lst is empty then there are no permutations
    if len(lst) == 0:
        return []

    # If there is only one element in lst then, only
    # one permuatation is possible
    if len(lst) == 1:
        return [lst]

        # Find the permutations for lst if there are
    # more than 1 characters

    l = []  # empty list that will store current permutation

    # Iterate the input(lst) and calculate the permutation
    for i in range(len(lst)):
        m = lst[i]

        # Extract lst[i] or m from the list.  remLst is
        # remaining list
        remLst = lst[:i] + lst[i + 1:]

        # Generating all permutations where m is first
        # element
        for p in permutation(remLst):
            l.append([m] + p)
    return l

if __name__ == "__main__":
    lst = [1, 2, 3, 1,4]
    v_out = permutation(lst)
    print(v_out)

I am only getting permutations of 4 length, I want permutatins of all lengths, and only distinct permutations. But within each permutation, repetition is allowed.

A: This should work...  Using the permutations function from itertools and making a set out of everything to prevent duplicates from being added to the overall result
In [20]: from itertools import permutations

In [21]: a = [1, 1, 2, 3]

In [22]: all_results = set()

In [23]: for i in range(1, len(a)):
    ...:     all_results.update(set(permutations(a, i)))
    ...:

In [24]: all_results
Out[24]:
{(1,),
 (1, 1),
 (1, 1, 2),
 (1, 1, 3),
 (1, 2),
 (1, 2, 1),
 (1, 2, 3),
 (1, 3),
 (1, 3, 1),
 (1, 3, 2),
 (2,),
 (2, 1),
 (2, 1, 1),
 (2, 1, 3),
 (2, 3),
 (2, 3, 1),
 (3,),
 (3, 1),
 (3, 1, 1),
 (3, 1, 2),
 (3, 2),
 (3, 2, 1)}

In [25]:


text:
Q: syntax error, unexpected ':' in site layout section of railstutorial.org I'm following a RoR tutorial and I'm following directions exactly (or so I think).
This is my app/views/static_pages/home.html.erb file:
<% provide(:title, 'Home') %>

Sample App

  This is the home page for the
  Ruby on Rails Tutorial
  sample application.

<%= link_to "Sign up now!", '#', class: "signup_button round" %>

When I run it in the local host, though, I get the error:

sample_app/app/views/static_pages/home.html.erb:9: syntax error, unexpected ':'
  ...to "Sign up now!", '#', class: "signup_button round" );@outp...

I don't understand what I have to change and why. Any help?

A: Ruby 1.9 allows
{foo: "bar"}

As an alternative to
{:foo => "bar"}

It looks you're running ruby 1.8 locally, hence the error. I'd recommend upgrading to ruby 1.9. Ruby 1.8 is on its way out.

A: think i found it.
if you are running newer version of rails
it should be called
<%= link_to "Sign up now!", '#', :class => "signup_button round" %>

instead of what you have there


text:
Q: Allow only my domain to serve images from my server I know there are answered questions closely related to this one, but even after thorough research I have not found a solution that is applicable to my problem.
The problem is as follows: I have a file system that allows my users to upload a profile picture, and in the future an entire private gallery. I want to be able to, from one of my own pages, be able to fetch those profile pictures, say in the chatbox by simply adding . At the same time I want to prevent people from entering http://example.org/usercontent/[FOLDERID]/profilepicture.png in their URL bar and just view the picure directly, because these pictures are supposed to only be visible to logged on users.
Is this possible? I have tried things like
    <IfModule mod_rewrite.c>
     RewriteEngine on
     RewriteCond %{HTTP_REFERER} !^$
     RewriteCond %{HTTP_REFERER} !^http://(www\.)?example\.org/.*$ [NC]
     RewriteRule .(gif|jpg|png|jpeg)$ [R,NC,L]
     </ifModule>

in my .htaccess file, but this results in all my images being blocked, even when I try , which should just display the image, given that the image tag is written on one of my own pages.

A:
I want to prevent people from entering http://example.org/usercontent/[FOLDERID]/profilepicture.png in their URL bar and just view the picure directly, because these pictures are supposed to only be visible to logged on users

You'll have to write a script that checks the user is logged in and returns the image file if so, eg using readfile() and suitable type and cache headers, or possibly mod_sendfile.
Referrer checking is neither secure nor reliable; it is not a workable authentication mechanism.


text:
Q: Janko Group and subgroups. I want to work with the Janko simple group $J_2$ using the computer, and if it is possible, the Janko simple group $J_4$ too. In specific, I want to take certain subgroups of it and compute their lattice subgroup. Other question is if exists accesible bibliography about those groups to read about its subgroups and others characteristics of them.
I was working in GAP, but it doesn't support the $J_2$ group, because after certain point using the commands, it breaks and doesn't do correctly the commands based on it. I'm trying to use Magma, but it doesn't have a command to obtain the subgroups of a certain group, only conjugation classes, and brings me different solutions against the (mathematically proved) solutions that GAP gives. Any help will be really appreciated.

A: In Magma
> S := [ s`subgroup : s in Subgroups(G) ];
> SS:= &cat[[s^t : t in Transversal(G,Normaliser(G,s))] : s in S];
> #SS;
1104344

gives a list of all 1104344 subgroups of $J_2$. I am sure you can do it in a similar way in GAP by starting with $\mathtt{ConjugacyClassesSubgroups}(G)$.
I fin it unlikely that you will succeed in computing a list of all subgroups of $J_4$.

A: In GAP (at least in principle -- my laptop did not have enough memory to store all of J2):
g:=SimpleGroup("J2");
u:=ConjugacyClassesSubgroups(g);;
v:=Concatenation(List(u,Elements));;

You will get repeatedly (after exceeding 2GB, 4GB, etc of memory) a warning from GAP "Error, reached the pre-set memory limit". This is a safety feature to stop a computing task potentially bringing the whole computer to its knees. Simply enter
return;

to continue the calculation.


text:
Q: Loading a Tcl package written in C (DLL) from .NET assembly I'm writing in C# and want to use tcl.
After searching I found Tcl/Csharp project which does the job, however is missing a package that allows it to work with the registry. I have the package in a form of dll file but I"m unable to load it.
class Program
{
    static void Main(string[] args)
    {
        Interp interp = new Interp();

        interp.eval("puts hello world");     // Works
        interp.eval("load tclreg12.dll");    // Throws TclException Invalid command name "load"
        interp.eval("package req registry"); // Throws TclException "cant find package registry"

        TclObject result = interp.getResult();
        Console.WriteLine(result);

        interp.dispose();
    }
}

How can I use this package?

A: As M.Babcock correctly pointed out, that Tcl/Csharp package you're using is just an attempt to implement a Tcl interpreter on top of the .NET stack, but the load command is highly special as it (in the "real" Tcl) is intended to load Tcl packages written in C, and such packages are supposed to use the C API exposed by the Tcl runtime itself.  This C API is quite comprehensive and, naturally, making a pure .NET code properly emulate all that C API stuff would be a huge undertaking, if at all possible.
Since Windows registry manipulations are trivially done in .NET, I suppose you have a large legacy program written in Tcl at hand, which you need to call from your .NET program (as you probably estimated that porting that program would be more hassle than making it run as is).  If this is true, I would have taken one of these routes:

*

*Turn your program into a starpack and bundle the resulting executable file along with your "host" program, then just execute it as a separate program.  (That file would be single and have no special dependencies.)

*Write a special wrapper assembly which would use P/Invoke to load the real Tcl runtime (Tcl's shell, tclshXY.exe is just a thin program, and the real thing is tclXY.dll plus a set of library files, and this is the DLL you're supposed to load).  Then your code could pass the Tcl runtime a script (in the form of the string) which would load and execute the actual Tcl program you need to run.


text:
Q: MySQL: UPDATE ... ON DUPLICATE KEY "ANOTHER UPDATE"? I've stumbled on a problem which is supposedly should have a valid solution in a single MySQL query, yet I can't figure it out (I'm far from an expert in MySQL, alas).
The table has the following columns: A, B, C. (A, B) is a primary key (INTs). C - is a string. The table is populated with records.
Under some conditions I need to update a value x in column A to new value y. If some records do already have y in A (can be many at once, for records with different values in B), "duplicate key(s)" condition occurs. In such case, I need to concatenate values in C from old records and corresponding pending updates, for every specific b.
Example:

|  A  |  B  |   C
|  1  |  2  |  ABC
|  1  |  4  |  DEF
|  2  |  2  |  GHI
|  2  |  4  |  JKL
|  2  |  5  |  MNO

After update in A as 2 -> 1, I need to get:

|  A  |  B  |   C
|  1  |  2  |  ABCGHI
|  1  |  4  |  DEFJKL
|  1  |  5  |  MNO

There is a well-known INSERT ... ON DUPLICATE KEY UPDATE statement. But how to handle gracefully the same problem on updates? I'm not sure if and how REPLACE statement or REPLACE function can be used for the task.
Thanks in advance.

A: I think, whatever happens, you will need two statements:
ALTER TABLE myTable ADD UNIQUE INDEX (A, B);

INSERT INTO myTable (A, B, C)
  SELECT 1, B, C
  FROM   myTable t
  WHERE  A = 2
ON DUPLICATE KEY UPDATE
  C = CONCAT(myTable.C, VALUES(C))
;

DELETE FROM myTable WHERE A = 2;

See it on sqlfiddle.
If there is a risk of concurrency issues, you will obviously need to perform these within a transaction to preserve atomicity.


text:
Q: Query by date with column that is a datetime How can I query for all records of a certain date if the column is a datetime?
This doesn't work. Is there a preferred way to do this in sequelize?
startDate and endDate are datetime's
Thing.findAll({
  where: {
    startDate = {
      [Op.gte]: '02-20-2020'
    },
    endDate = {
      [Op.lte]: '02-20-2020'
    },
  }
});

A: Split them and create a javascript Date object before using that straight in the query parameters.
const [month, day, year] = '02-20-2020'.split('-')
const date = new Date(year, month, day)

Thing.findAll({
  where: {
    startDate = {
      [Op.gte]: date
    }
  }
});

See Several ways to create a Date object


text:
Q: WCF RESTful service working on HTTP but not HTTPS (Fiddler help) Now HTTPS works but HTTP does not I've been looking around for a fix for this for some time now. I have been adding, which seems enlessly, to my web.config file all suggestions I've seen in order to fix this not working over SSL and working over basic http.
This is my current web.config:
<?xml version="1.0"?>
<configuration>
  <appSettings/>
  <system.web>
    <compilation debug="true" targetFramework="4.0"/>
    <httpRuntime/>
    <pages controlRenderingCompatibilityVersion="3.5" clientIDMode="AutoID"/>
  </system.web>
  <system.serviceModel>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="false" multipleSiteBindingsEnabled="true"/>
    <bindings>
      <customBinding>
        <binding name="basicConfig">
          <binaryMessageEncoding/>
          <httpTransport transferMode="Streamed" maxReceivedMessageSize="67108864" />
        </binding>
      </customBinding>
      <webHttpBinding>
        <binding name="Binding" crossDomainScriptAccessEnabled="true">
          <security mode="Transport">
            <transport clientCredentialType="None"/>
          </security>
        </binding>
        <binding name="httpbind" crossDomainScriptAccessEnabled="true"/>
      </webHttpBinding>
    </bindings>
    <client/>
    <services>
        <service name="Wcf.App.Service1" behaviorConfiguration="ServiceBehaviour">
          <endpoint address="customBinding" binding="customBinding" bindingConfiguration="basicConfig" contract="Wcf.App.IService1"/>
          <endpoint address="" binding="webHttpBinding" behaviorConfiguration="REST" contract="Wcf.App.IService1"/>
        </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="ServiceBehaviour">
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="true"/>
        </behavior>
        <behavior name="REST">
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="true" />
        </behavior>
      </serviceBehaviors>
      <endpointBehaviors>
        <behavior name="REST">
          <webHttp helpEnabled="true" defaultOutgoingResponseFormat="Json"/>
        </behavior>
      </endpointBehaviors>
    </behaviors>
  </system.serviceModel>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
    <!--
        To browse web app root directory during debugging, set the value below to true.
        Set to false before deployment to avoid disclosing web app folder information.
      -->
    <directoryBrowse enabled="true"/>
  </system.webServer>
</configuration>

Most wsources say to do either 1 or the other (sometimes both) of the below:
 <security mode="Transport">
      <transport clientCredentialType="None"/>
 </security>

and/or
 <serviceBehaviors>
    <behavior name="ServiceBehaviour">
      <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
      <serviceDebug includeExceptionDetailInFaults="true"/>
    </behavior>
    <behavior name="REST">
      <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
      <serviceDebug includeExceptionDetailInFaults="true" />
    </behavior>
  </serviceBehaviors>

Which I currently have both in my web.config file.
As stated above, it works just fine when using HTTP:

But when using HTTPS:

I've also made sure that the IIS 8 that I am using to host the WCF RESTful web service was configured correctly. Again, I searched a lot and made sure that whatever was suggested I did. I currently have a legit PositiveSSL certificate from Comodo.

So any help with this issue to get resolved would be great!
UPDATE FIDDLE
#   Result  Protocol    Host            URL                                 Body    Caching Content-Type                Process    Comments    Custom
1   200     HTTP        Tunnel to       s--------a.info:443                 0                                           chrome:1796
2   404     HTTPS       s--------a.info /Service1.svc/GetData/5556932587    3,353   private text/html; charset=utf-8    chrome:1796

And this is what it looks like in fiddler for HTTP:
#   Result  Protocol    Host            URL                                 Body    Caching Content-Type                Process    Comments    Custom
1   200     HTTP        s--------a.info /Service1.svc/GetData/5556932587    620     application/json; charset=utf-8     chrome:1796

However, just going to Service1.svc in HTTPS loads up just fine:
#   Result  Protocol    Host            URL             Body        Caching Content-Type        Process     Comments    Custom
1   200     HTTPS       s--------a.info /Service1.svc   2,939       text/html; charset=UTF-8    chrome:1796

Update again
Well it looks like I finally got the web.config file correct to enable the SSL version to work but now that breaks the original HTTP.....
<?xml version="1.0"?>
<configuration>
  <appSettings/>
  <system.web>
    <compilation debug="true" targetFramework="4.0"/>
    <httpRuntime/>
    <pages controlRenderingCompatibilityVersion="3.5" clientIDMode="AutoID"/>
  </system.web>
  <system.serviceModel>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="false" multipleSiteBindingsEnabled="true"/>
    <bindings>
      <customBinding>
        <binding name="basicConfig">
          <binaryMessageEncoding/>
          <httpTransport transferMode="Streamed" maxReceivedMessageSize="67108864" />
        </binding>
      </customBinding>
      <webHttpBinding>
        <binding name="basicConfig">
          <security mode="None">
            <transport clientCredentialType="Basic"/>
          </security>
        </binding>
        <binding>
          <security mode="Transport">
            <transport clientCredentialType="None"/>
          </security>
        </binding>
      </webHttpBinding>
    </bindings>
    <client/>
    <services>
        <service name="Wcf.App.Service1" behaviorConfiguration="ServiceBehaviour">
          <endpoint address="customBinding" binding="customBinding" bindingConfiguration="basicConfig" contract="Wcf.App.IService1"/>
          <endpoint address="" binding="webHttpBinding" behaviorConfiguration="REST" contract="Wcf.App.IService1"/>
        </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="ServiceBehaviour">
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="true"/>
        </behavior>
        <behavior name="REST">
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="true" />
        </behavior>
      </serviceBehaviors>
      <endpointBehaviors>
        <behavior name="ServiceBehaviour">
          <webHttp helpEnabled="true" defaultOutgoingResponseFormat="Json"/>
        </behavior>
        <behavior name="REST">
          <webHttp helpEnabled="true" defaultOutgoingResponseFormat="Json"/>
        </behavior>
      </endpointBehaviors>
    </behaviors>
  </system.serviceModel>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
    <!--
        To browse web app root directory during debugging, set the value below to true.
        Set to false before deployment to avoid disclosing web app folder information.
      -->
    <directoryBrowse enabled="true"/>
  </system.webServer>
</configuration>

Anyone have suggestions on how to make both work at the same time?


text:
Q: Data outside of Request is Undefined Section that is invoking the code.
** index.js **
var express = require('express');
var request = require('request');
var cheerio = require('cheerio');
var RagialJS     = express();

RagialJS.get('/scrape', function(req, res){

  console.log(getItemJSON("Minor Brisket", "Renewal"));

}) // End RagialJS.get

I expect this to print out a JSON object but returns undefined.
** getItemJSON() **
// Returns buy, sell, and metrics of item as a JSON
function getItemJSON(itemName, server) {
  var url = getItemURL(itemName, server);
  request(url, function(error, response, html) {
    if(!error && response.statusCode == 200) {
        var $ = cheerio.load(html);

        // Logic that parses and puts data in JSON here...

        // console.log(json); works here
        return json;
        } else {
          console.log(error);
        }
  }); // End request
// console.log(json); DOESN'T works here
}

The problem here is that if I console.log(json); before the request ends then it works fine but if I do it outside of the request (or another function) then it returns undefined. (Same problem for getItemURL())
Is there a way to resolve this problem? Or am I overlooking some fundamental idea about requests for data?
Full Source Code if interested
Any help or comments are appreciated.

A: the main problem is that you are doing async calls and expecting to get the results in a sincronous way.
The request function second parameter is a callback that is called when the request gets a response.
So the problem is:
request(url, function(error, response, html) {
    console.log('A');
}) // End Request
console.log('B');

You are expecting that the console output is:
A
B

but the output is:
B
A

That's because the function is asyncronous and it will be called when the request gets a response, and the code continues executing while the request is waiting for that response.
*I have downloaded your code and changed few things to test it, tell me if you want me to send it to you.


text:
Q: iOS Push Notification open different app Can IOS push notifications open another app via its URL scheme (ie. SOMEAPP://someUrlScheme)?
I've looked through the documentation but haven't seen any mention of this.

A: Directly from the notification bar I think it is not possible, but you can handle notification received event show a popup and launch another app on click event of that popup