text:
Q: Terminal.app On macOS Doesn't Preserve Preferences I used to work with mac os a while ago an now I am coming back. What I noticed is regular preferences update doesn't work for at least Terminal.app. This happens on any High Sierra.

*

*Start Terminal.app

*Go to your Preferences either through a menu or Cmd-,.

*Change something, e.g. use different profile as a default.

*Quit application

*Start Terminal.app again. Your preferences changes are reset.

What's going on ? Looks like a bug to me, perhaps I have missed something since Lion release.

A: It could be that your preferences are "stuck." Preferences in macOS has been broken for awhile now and can sometimes get into a state where the app can't read changes made, or changes never get applied.
Try deleting your ~/Library/Preferences/com.apple.Terminal.plist file along with any com.apple.Terminal.plist.lockfile and com.apple.Terminal.plist.<RANDOM> companion files you find. Restart your system and try it again.
Another way is to look at the ~/Library/Preferences/com.apple.Terminal.plist permissions. You may see something like this

Now if you run something like
sudo chown evgeniy.sharapov:staff ~/Library/Preferences/com.apple.Terminal.plist

And restart the Terminal.app, it seems to go back to normal and able to save changes in Preferences.


text:
Q: CXF (and interceptors) and 2.5 webapps I've a very basic question. When and How will CXF kick in if my webapp is 2.5 or higher. The weblogic 10.3 that I'm running picks up the WS annotation defined in my web-app.
Until now I had web-app version 2.3. When I upgraded it to 2.5 in webapp XML, I noticed my interceptors are not getting kicked in because now weblogic is able to handle the annotation and CXF is out of picture (based upon stacktrace analysis).
Is my observation correct, or am I totally wrong? I just changed from:
<DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>

to
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

A: You are right, changing Servlet version to 2.5 triggers autodiscovery of classes annotated with @WebService annotation.
To prevent this you have to tweak classloading policy. On Apache CXF site there is a good description: Apache CXF - WebLogic
According to this website you have two options:

*

*"Put the geronimo-ws-metadata_2.0_spec-1.1.1.jar in the $Weblogic_Home/jdk_../jre/lib/endorsed folder." - this will affect whole server and might break other web services running on WebLogic

*"Pack war in an ear, deploy the ear with weblogic-application.xml" - this way you change classloading policy for single EAR application, not for whole server.

I prefer to use solution based on weblogic-application.xml, as it is more portable.
However it didn't work for me immediately, I had to add additional library to EAR/WAR - geronimo-ws-metadata_2.0_spec-1.1.1.jar.
<dependency>
    <groupId>org.apache.geronimo.specs</groupId>
    <artifactId>geronimo-ws-metadata_2.0_spec</artifactId>
    <version>1.1.1</version>
</dependency>

If you don't have yet EAR archive you have to create one. Assuming you are using maven:
mvn archetype:generate -DarchetypeGroupId=org.codehaus.mojo.archetypes -DarchetypeArtifactId=ear-jee5

And add your WAR project to dependencies.

A: I didnt want to mess with WL as we have more than one app running on the WL.So the simple solution was to use the handlers. See here: handlers_introduction.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Bounding the power of a sum I know the bound
$|a+b|^q \leq 2^{q-1} (|a|^q + |b|^q)$
See here for a proof. I can use this to show the bound
$|a+b+c|^q \leq 2^{q-1}(|a|^q + 2^{q-1}(|b| + |c|))$
and since the order is arbitrary I can do
$|a+b+c|^q \leq 2^{q-1}(\min(|a|^q + 2^{q-1}(|b| + |c|), |b|^q + 2^{q-1}(|a| + |c|), |c|^q + 2^{q-1}(|a| + |b|)))$
But is this the sharpest bound?

A: Setting $(a, b, c) = (1, 1, 2)$ gives $$|a + b + c|^q = 4^q$$ and $$2^{q-1} (|c|^q + 2^{q-1} (|a| + |b|)) = 2^{q-1} (2^q + 2^q) = 4^q$$ (the alternative bounds from rearranging $a, b, c$ are all larger), so the bound you give is optimal.


text:
Q: jquery mobile: how to completely remove the pre-loader from jquery mobile? By changing the CSS for jquery mobile you can remove the pre-loader image on page reloads, but still a grey circle appears on page reloads.
What would be the way to remove the preload indication in jquery mobile all together?

A: The accepted answer was not working for me in jQuery Mobile 1.4.  I wanted to completely disable the Ajax loading so I have the
$.mobile.ajaxEnabled = false;

already running between the declaring of jQuery and jQuery Mobile files, but I was still seeing the grey circle.
I came up with this in my css file
.ui-loader {
  display:none !important;
}

and then the grey circle is gone.  But, a tester pointed out that I was still getting a javascript error on the page that it was failing to load ajax-loader.gif.  I searched around and found this in jquery.mobile-1.4.0.css
/* Loader */
.ui-icon-loading {
    background: url(images/ajax-loader.gif);
    background-size: 2.875em 2.875em;
}

So, I just also added this to my css file
.ui-icon-loading {
    background:none !important;
}

and now the javascript error is gone too.

A: The best way would be to disable it altogether.
Try using this on mobileinit event:
$.mobile.loadingMessage = false;

This should fully disable it:
$.mobile.hidePageLoadingMsg()

More about this (with some examples) can be found in jQuery mobile documentation here.

A: A bit late but maybe SO users could find this useful, I ran to this same problem and found that you can show | hide the loader using the $.mobile.loading() function so:
To show:
$.mobile.loading( 'show', {
    text: 'Verificando Datos',
    textVisible: true,
    theme: 'z',
    html: ""
});

To hide:
$.mobile.loading('hide');


text:
Q: What's the advantage or benefit of Slug field in Django? What's the benefit of the slug field? Does it make the url more searching engine friendly? If it does, how? Isn't a meaningful title of the page searching engine friendly enough?

A: The slug provides a human-friendly url fragment for the page. This is often useful when people are deciding whether or not to click a link. There's one in the url of this page, for example:
http://stackoverflow.com/questions/6192655/whats-the-advantage-or-benefit-of-slug-field-in-django
You can actually get to this question without the slug (in StackOverflow's system), but a slug is a more friendly and more semantic way to address the page. Search engines do place some weight on words that appear in the address of the page.
One downside of using only the slug to address a page is that if you change the content of the page and wish to change the title, you have to decide between changing the slug, or leaving it as is (and thus not reflecting the content of the page). StackOverflow's compromise of having the slug but not relying on it is  one solution.
Nothing in Django requires you to use slugs in your application, but it's a convenience that's present because many of us do.


text:
Q: How to force a full recompilation of all files for every make? I'm hoping to create a basic makefile template for small-scale C apps.  In this scenario, I'm less concerned with performance than clarity and want to recompile everything - All .h and .c files, and third-party .so files.
# Constants
#===============================================================================

# Specify the C complier
CC = gcc

# List the flags to pass to the compiler
#  -ggdb       Compile with debug information for gdb
#  -Wall       Give all diagnostic warnings
#  -O0         Do NOT optimize generated code
#  -m64        Generate code for a 64-bit environment
CFLAGS = -ggdb -Wall -O0 -m64

# Change the list of c source files into a list of object files by replacing
# the .c suffix with .o
OBJECTS := $(patsubst %.c,%.o,$(wildcard *.c))

# List libraries
# m    Math library
LIBRARIES = -lm

# Specify the build target
TARGET = heyyou

# Rules
#===============================================================================
# $@ = left side of the colon, the target
$(TARGET) : $(OBJECTS)
    @echo "Compiling $@..."
    $(CC) -o $(TARGET) $(OBJECTS) $(CFLAGS) $(LIBRARIES)

A: If you have made Makefile properly considering all the decencies, simply use
make clean

If you have made a proper Makefile, all dependencies will be handled automatically and for every change you make in your file system, you don't have to do "make clean" every time. A simple "make" would be enough.
If you have not handled all the dependencies in make, then you will notice that changes that make in your source code won't reflect in binaries.
So a simple work around this would be to add these lines in you Makefile
clean:
    rm *.so
    rm *.o

Now, for every compilation, do something like
make clean
make

Its not a proper way to handle Makefile but its a saviour in some frustrating situation.

A: You can add a clean function in your makefile,eg:
clean:
    rm -rf *.o $(PRG).elf *.eps *.png *.pdf *.bak
    rm -rf *.lst *.map

In your case you can add  also:
rm -rf $(OBJECTS)

Then you simply call make clean before call make

A: you can indicate -B option in your make command line.
make -B


text:
Q: How to configure postfix to receive mails and keep them in queue but not sending them out How to configure postfix to only receive mails and put them into local queue but not actually forwarding mails so they keep inside /var/spool/postfix

A: Try adding the following:
/etc/postfix/main.cf:
smtpd_recipient_restrictions =
...
check_recipient_access regexp:/etc/postfix/hold.regexp

/etc/postfix/hold.regexp:
/^/   HOLD

If you want to release all messages on hold, use postsuper:
postsuper -H ALL


text:
Q: GitHub: Forking a Branch Here's the situation:
I am contributing to this repo: https://github.com/HabitRPG/habitrpg
Here is my local repo: https://github.com/nafoster/habitrpg
I want to take the ja_trans branch from this person's repo: https://github.com/Fandekasp/habitrpg
and fork it into my own so later, I can pull request it into the original repo.
I'm still relatively new at GitHub/Git. How would I do this?

A: Fetch the branch you want.
git remote add fandekasp https://github.com/Fandekasp/habitrpg
git fetch fandekasp
git checkout ja_trans

Maybe commit some stuff, then push it to your own repo, assuming it's called origin:
git push origin ja_trans

Now set up a PR.

A: First of all, you need to set up fork syncing. There is some documentation here: https://help.github.com/articles/syncing-a-fork
You should keep your fork up to date when submitting pull requests, in order to make it easier to merge your changes.
After fetching from upstream, you should have all of the remote branches in your local repo. You can then create a new local branch from the remote branch:
# update upstream
$ git fetch upstream
# create local 'ja_trans' branch from upstream
$ git branch --no-track ja_trans upstream/ja_trans
# switch to 'ja_trans'
$ git checkout ja_trans
# push your 'ja_trans' branch to the fork
$ git push -u origin ja_trans

After you are happy with your changes you can push them to your fork and submit the pull request from there.
If you want to keep the branch up to date with the upstream branch, you can follow the instruction in the "syncing a fork" page. Just replace upstream/master with the branch from which you want to pull the changes ('ja_trans' in this example).


text:
Q: How to display more number of bits on the nrfcloud? I have set up an environment to upload data to the nrfcloud using nrfconnect and the nrf52 dk.I can only upload data upto ff and then it resets to zero .The value which i am uploading is an integer value, so i want to display numbers from 0 to atleast 32000 on the cloud.Here is an image of the cloud so far.I have used the code in this page to upload data using notification to the cloud.How must i increase the number of bits which is 00 to 0000 on the service where maximum value will be 65585.Do i have to do changes in the code?please help
here is the notification handler code.
  static void notification_timeout_handler(void * p_context)
  {
   UNUSED_PARAMETER(p_context);
   ret_code_t err_code;

  // Increment the value of m_custom_value before nortifing it.
  m_custom_value=pulses;
  ///where pulses is of type integer

  err_code = ble_cus_custom_value_update(&m_cus, m_custom_value);
  APP_ERROR_CHECK(err_code);
  }

and the ble_cus_custom_value_update() code is
     uint32_t ble_cus_custom_value_update(ble_cus_t * p_cus, uint8_t
           custom_value)

     {
      if (p_cus == NULL)
      {
       return NRF_ERROR_NULL;
      }

/* This code belongs in ble_cus_custom_value_update() in ble_cus.c*/
      uint32_t err_code = NRF_SUCCESS;
      ble_gatts_value_t gatts_value;

// Initialize value struct.
          memset(&gatts_value, 0, sizeof(gatts_value));
      gatts_value.len = sizeof(uint8_t);
      gatts_value.offset = 0;
      gatts_value.p_value = &custom_value;

      // Update database.
      err_code = sd_ble_gatts_value_set(p_cus->conn_handle,
      p_cus->custom_value_handles.value_handle,
       &gatts_value);
      if (err_code != NRF_SUCCESS)
      {
      return err_code;
      }
     /* This code belongs in ble_cus_custom_value_update() in ble_cus.c*/

     // Send value if connected and notifying.
         if ((p_cus->conn_handle != BLE_CONN_HANDLE_INVALID))
           {
           ble_gatts_hvx_params_t hvx_params;

         memset(&hvx_params, 0, sizeof(hvx_params));

         hvx_params.handle = p_cus->custom_value_handles.value_handle;
         hvx_params.type = BLE_GATT_HVX_NOTIFICATION;
         hvx_params.offset = gatts_value.offset;
         hvx_params.p_len = &gatts_value.len;
         hvx_params.p_data = gatts_value.p_value;

         err_code = sd_ble_gatts_hvx(p_cus->conn_handle, &hvx_params);
         }
         else
         {
         err_code = NRF_ERROR_INVALID_STATE;
         }

         return err_code;

         }

here is an image of what i could achieve


text:
Q: Assign php code to smarty template engine I make a new website for my company and i want to use smarty (v3.1.29) for it. Now the problem is that we store the code for all pages in our database (home, products, downloads, ...). Some pages contains PHP inline functions like:
<?php include("functions.php"); ?>

 Hello <?php echo printWorldInColor(); ?>

In my template (.tpl) file I have a div-section to load the content from our database:

      {$content}

So my code looks like this afterwards:

      <?php include("functions.php"); ?>

 Hello <?php echo printWorldInColor(); ?>

Is there a way that smarty processes the PHP-code before parsing it?
Hint: I dont want to edit my template file. I just want to parse the database content to my content-section of the website.

What i tried:

*

*saved database-content into a string and replaced PHP-tags with smarty-PHP-tags, then assign it to the template

*SmartyBC-Class

A: You can't do that in Smarty. Also running php code stored in the database sounds like a terrible idea. But if for some reason you have to go on with this nonsense (and considering that you can't use eval), you can try this:

*

*Read the php code from the database.

*Save to a temporal php file

*Turn on output buffering with ob_start()

*include the file you have created

*assign the output to a variable with ob_get_clean()

*assign the variable to the template

But if I was you, I would try to do the project in another way.


text:
Q: Output to a Picture Box Alternative For a project I'm working on, a stopwatch-like timer needs to be displayed to the form.  If I remember correctly in VB, text could be outputted to a picture box, but I can't find a way to do it in c#.  A label would work, if there is a way to prevent the resizing of the box. Thanks.

A: A Label would probably be the simplest option.  I'm not sure why you would need to prevent resizing of the picturebox (which is also simple to do).
If you are worried about your picturebox being resized and your Label no longer being centered, or being the wrong size, you can just put code in the resize event which dynamically updates the size and location of the Label and its font, based on the current size of the picturebox.
However, if you are determined to not use labels, you can always have your picturebox subscribe to the Paint event and then use e.Graphics to just draw your text whenever the picturebox is repainted.
private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
    using (Font myFont = new Font("Microsoft Sans Serif", 10))
    {
        e.Graphics.DrawString("This time is...Hammertime", myFont, Brushes.Black, new Point(0,0));
    }
}

However, you would also have to redraw this for every iteration of your timer.
Like I said, Label would be a better option than this. Calling e.Graphics wouldn't give you any real advantage over Label , but it would create more things for you to worry about.

A: Using a TextBox is probably the most appropriate thing for this; just set ReadOnly to true.


text:
Q: Why is a Manager().dict() only updated one level deep? I wanted to update a dict in a dict, the outside one being instantiated via multiprocessing.Manager():
import multiprocessing

def worker(key, container):
    # this one is not applied
    container['a'][key] = key
    # this one is
    container[key] = 3

if __name__ == "__main__":
    multiprocessing.freeze_support()

    c = multiprocessing.Manager().dict()
    c['a'] = {}

    p1 = multiprocessing.Process(target=worker, args=('x',c,))
    p2 = multiprocessing.Process(target=worker, args=('y',c,))

    p1.start()
    p2.start()
    p1.join()
    p2.join()
    print(c.copy())

The output of this code is
{'y': 3, 'a': {}, 'x': 3}

I expected to get
{'y': 3, 'a': {'x': 'x', 'y': 'y'}, 'x': 3}

The first level of the dict is addressable in worker, but operations on the nested dict are silently discarded. Why?
I initially thought that this my be due to the shallow copy, but the output is the same when using copy.deepcopy()

A: The Manager is implemented using a subprocess that keep a local version of your dict object and provide proxy functions that mimic the behavior of the object without Manager.
When you call container['a'], you use the proxy function that return a local copy of the value associated to the 'a' key. Thus if you modify this copy in one of your subprocess, the change is only local. If you want a global change, you can either:

*

*Modify the local copy and synchronize by using the proxy of set, ie container['a'] = new_dict as you proposed. The inconvenient is that it is not atomic and thus you have some concurrency issues as if p1 and p2 gets the dictionary, both get {}, and the update they submit will be {key: key} only, without taking into account the other update and only the second one will be registered in the end.

*A better way would be to use a nested Manager.dict:
import multiprocessing

def worker(key, container):
    container['a'][key] = key
    container[key] = 3

if __name__ == "__main__":
    multiprocessing.freeze_support()

    manager = multiprocessing.Manager()
    container = manager.dict()
    container['a'] = manager.dict()

    p1 = multiprocessing.Process(target=worker, args=('x', container))
    p2 = multiprocessing.Process(target=worker, args=('y', container))

    p1.start()
    p2.start()
    p1.join()
    p2.join()
    print(container.copy())
    print(container['a'].copy())

A: I think this is a bug.
I found an esoteric way to bypass the issue, I am not sure how robust it is. Any feedback is welcome.
import multiprocessing

def worker(key, container):
    add = {key: key}
    container['a'] = dict(container['a'], **add)
    container[key] = 3

if __name__ == "__main__":
    multiprocessing.freeze_support()

    c = multiprocessing.Manager().dict()
    c['a'] = {}

    p1 = multiprocessing.Process(target=worker, args=('x',c,))
    p2 = multiprocessing.Process(target=worker, args=('y',c,))

    p1.start()
    p2.start()
    p1.join()
    p2.join()
    print(c.copy())

This outputs
{'y': 3, 'a': {'y': 'y', 'x': 'x'}, 'x': 3}

A: You should pass the instance of the Manager to subprocesses, for example
import multiprocessing

def worker(key, container, manager):
    container[key] = manager.dict()  # create a dict using current manager
    container[key][1] = 3
    container[key][2] = manager.dict() # # create a dict using current manager
    container[key][2]['hh'] = 'test'

if __name__ == "__main__":
    with multiprocessing.Manager() as m:
        c = m.dict()
        c['a'] = 1
        p1 = multiprocessing.Process(target=worker, args=('x',c,m))
        p2 = multiprocessing.Process(target=worker, args=('y',c,m))

        p1.start()
        p2.start()
        p1.join()
        p2.join()
        print(c['a'])
        print(c['x'][1])
        print(c['x'][2]['hh'])
        print(c['y'][1])
        print(c['y'][2]['hh'])

The output is
> $ python3.7 ddd.py
1
3
test
3
test


text:
Q: PHP Using single Count++ on both loop/conditional & static content? Is it possible to use count++ and print it without conditionals or loop?
Normally I use it on conditionals/loop like example:
<?php $count = 1; { while( have_rows('test') ): the_row(); ?>
<a href="#div<?php echo $count;?>">Text <?php echo $count;?>
<?php $count++;?>
<?php endwhile; }?>

But I want it to use it in stuff like this:
<?php $count = 1; {?>
<a href="#div<?php echo $count;?>">Static Text <?php echo $count;?>
<a href="#div<?php echo $count;?>">Static Text <?php echo $count;?>
<?phpwhile( have_rows('test') ): the_row(); ?>
<a href="#div<?php echo $count;?>">Loop Text <?php echo $count;?>
<?php endwhile;?>
<?php $count++;?>
<?php}?>

How to make the counting work on both static & loop contents?


text:
Q: form_validation dynamically added form dropdown field codeigniter I have a form that dynamically adds dropdown fields depending on the number for results returned a db query that also populates the dropdown.
I need to validate if these dropdown fields. This is what I have at the moment
My view

<?php

            if(!empty($result))
            {
                foreach($result as $row)
                {
                    echo "
";
                    echo "" . $row->project_no . "	";
                    echo "" . $row->sws_dwg_no . "	";
                    echo "" . $row->client_dwg_no . "	";
                    echo "" . $row->dwg_title . "	";
                    echo "" . $row->dwg_by . "	";
                    $rev = array('' => $row->dwg_rev);
                    $rev_change = array(
                        'A' => 'A',
                        'B' => 'B',
                        'C' => 'C',
                        'D' => 'D',
                        'E' => 'E'
                        );
                    $dropdown = array_merge($rev,$rev_change);

                    echo "" . form_dropdown('result['.$row->dwg_id.'][temp_dwg_rev]',$dropdown,'', 'id="theSelect' . $row->dwg_id .'"') . "	";
                    echo "" . date('Y/m/d', strtotime($row->dwg_date)) . "	";
                    echo "" . form_checkbox('result['.$row->dwg_id.'][temp_dwg_id]',$row->dwg_id,'', 'id="activate' . $row->dwg_id . '"') . "	";
                    echo "
";
?>

$row->dwg_id returns the table id of the results, i.e 1,2,3 or 4, to form the associative array.
My controller
public function issue()
{

    $this->form_validation->set_rules('result[][temp_dwg_rev]', 'Rev  ', 'required|callback_rev_change');
    $this->form_validation->set_rules('result[][temp_dwg_rev]', 'Rev  ', 'required|callback_rev_change');
    $this->form_validation->set_rules('result[][temp_dwg_rev]', 'Rev  ', 'required|callback_rev_change');
    $this->form_validation->set_rules('result[][temp_dwg_rev]', 'Rev  ', 'required|callback_rev_change');

    if($this->form_validation->run())
    {
      echo "All changed";
    }
    else echo validation_errors();
}

Currently only the first dropdown is validated and an error returned. I have tried adding the id number to the field name in the form validation rule and the same thing happens - only the first dropdown is validated.
I want it to work for all the dropdown fields in the form.

A: I solve the problem that I had. Thank you for your interest Saty
Here is what I did to solve the problem that I had. I used a foreach loop that takes the posted $row->dwg_id values to create the name of the form validation rule. The rule then matches the name of the input.
My controller
public function issue()
{
    $rows = array();
    $rows = $_POST['result'];
    $temp_array = array_column($rows, 'temp_dwg_id');
    foreach($temp_array as $key => $temp_dwg_id)
    {
        $this->form_validation->set_rules('result['.$temp_dwg_id.'][temp_dwg_rev]', 'Rev'.$temp_dwg_id , 'required');
    }

    if($this->form_validation->run())
    {
      //Do stuff.
    }
    else{
      //Do other stuff.
    }


text:
Q: Problema com Array vazio com mysql e nodejs Essa é a action que é ativada ao carregar a pagina: Nela eu recebo como resultado o seguinte array abaixo. Meu problema é, quando não tem nenhum registro o ARRAY retorna vazio, não consigo passar um parametro para o INPUT.
Ex.: input(value="#{data[0][0].alimentacao || 0}")
Se não encontrar o registro preenche com zero, porém antes disso já apresenta erro por não encontrar o parametro data[0][0].alimentacao e consequentemente não carrega a página.
No BD, já tentei setar os campos como default NULL e default 0 e mesmo assim não retorna os campos.
Se eu inserir dados manualmente, funciona perfeitamente.
 **[ [],** [{"nNomes":0,"salariosMembros":null}], [{"salarioTitular":null}] ]

getDespesa: function(req,res){
 var _id = req.params.id;

 db.query('SELECT * FROM despesas WHERE idCliente = ?;
           SELECT COUNT(nomeCompleto) as nNomes, SUM(ultimosalario) as salariosMembros FROM membros WHERE idCliente = ?;
           SELECT ultimoSalario as salarioTitular FROM cadastro WHERE idCliente = ?', [_id, _id, _id], function(err, result){
    if(err) throw err;

    var results = JSON.parse(JSON.stringify(result));
    console.log(results);

    var soma = (results[1][0].salariosMembros + results[2][0].salarioTitular) * 100;
    console.log(soma);

    var data1 = results[0][0];
    console.log(data1);

    res.render('titularDespesas', { id: _id, data: result });

    result = results;

    return result;
    });
},

Após pesquisar um pouco mais consegui chegar em um resultado:
Não sei se está da forma mais correta, sei que atendeu a meus propositos:
var data = {
  alimentacao : 0,
  agua : 0,
  luz : 0,
  iptu : 0,
  telefone : 0,
  mensalidadesEscolares : 0,
  transporte : 0,
  assistenciaMedica : 0,
  medicamentosContinuos : 0,
  totalDespesas : 0,
  rendaBruta : 0,
  rendaLiquida : 0,
  nMembros : 0,
  rendaPerCapita : 0
}

var valor;

if(**results[0]** == ''){
  valor = data;
}else{
  valor = results[0][0];
}

Vlw pessoal!

A: É responsabilidade do programador conferir se os dados que ele quer acessar existem. Usando if ou alguma outra estrutura para conferir isso.


text:
Q: What does $\int_0^\infty 1_{[X>t]}dt$ mean? X is a random variable What does $$\int_0^\infty 1_{[X>t]}dt$$ mean? X is a random variable. If X is a r.v., then so does $1_{[X>t]}$. Thus this is the integral of random variables on t. I think it may be defined in Stochastic Process or something, can anyone tell me its definition or give me a reference link? Thank you ahead.

A: This is the random variable $Y$ defined by the condition that, for every $\omega$ in $\Omega$,
$$
Y(\omega)=\int_0^\infty \mathbf 1_{[X(\omega)\gt t]}\,\mathrm dt.
$$
Exercise: Check that $Y=\max(X,0)$.


text:
Q: What does the "Balor" affix mean? When you get up to level 50+ or Hell mode (or both), you start seeing a lot of gear with the name "Balor" on it (like this).
What in the world does "Balor" mean in this context?  (Both lore-wise and gameplay-wise, if there's any gameplay effect).

A: "Balor" is just the name for a particular class of item, and doesn't provide any special benefits.  Each class of gear has its own adjective, and it's just there for flavor.
It's origins are likely from Dungeons and Dragons, where Balor is a type of demon:

In the original Dungeons & Dragons pamphlets, this breed of demon was known as "balrog", but the name was revised in subsequent supplements to simply "type VI demon" so as not to infringe on J. R. R. Tolkien's copyright.  In second edition AD&D, the name "type VI demon" was revised to "balor," taking the name of the greatest individual of their rank as the name for the entire breed. Also in second edition, balors now had vorpal swords.

So, you might think of these as "Demonic Gauntlets" or somesuch.
Balor is also a god from Celtic mythology, although the D&D Balor doesn't have much in the way of relation to this.

A: I believe that it is referring to the tier of the armor. Balor armor, for example, refers to a tier around the levels 53-54.


text:
Q: function with arrays with 2 dimensions in c++ I have a function to multiply arrays. The function is multiply:
void multiply(int array1[][], array2[][]);

But it doesn't work.
for example I have to arrays
int array1[4][10]
int array2[10][6]
multiply(arra1[4][10], array2[10][6])

But it doesn't works.
I need call de function with any size.
later I need to call the function with:
int array3[5][5]
int array4[5][5]
multiply(arra1[5][5], array2[5][5])

How do I get the arrays in the function?
multidimensional array must have bounds for all dimensions except the first
And i need variable rows and variabloe columns

A: You seem to use the multiply function like its definition would be like this: void multiply(int number1, int number2);
Perhaps you should post the whole definition of multiply function

A: C-style array is not really array but a set of hacks with pointer math. You can't return such array from a function at all, and passing in is really just passing a pointer under the hood.
As pointer works fine for simple arrays and with the same syntax we can forget that difference. In that case the array externt in the parameter is completely ignored.
With 2D array it will not work the same anymore, as for the pointer math to work you must pass a proper "slice".  So all but the first array extents are mandatory. You can leave the first empty or use with any number as before.
Certainly to make the function actually useful you must pass in the first extent too as a separate parameter unless the function can somehow figure it out from the data.
void multiply(const int in_array1[][10], const int in_array2[][10], int rows, int out_array[][10]);

could be a good function to multiply arrays with 10 columns and variable rows.
If you need all-variable, just pass in (int* arr, int rows, int cols) and calculate the cell position yourself.

A: Use std::vector to model arrays unless you have a specific reason for using an array.
Example:
vector< vector<int> > myArray1(3, vector<int>(2,0));
vector< vector<int> > myArray2(3, vector<int>(2,0));

// ...

vector< vector<int> > multiply(vector< vector<int> > &myArray1,
                               vector< vector<int> > &myArray2) {

    vector< vector<int> > result(myArray1.length(), myArray2[0].length());

    for(int i = 0; i < myArray1.length(); i++){
        for(int j = 0; j < myArray1[i].length(); j++){
            // ...
        }
    }

    return result;
}

A: You can accomplish this with a template definition for multiply().
template <unsigned L, unsigned M, unsigned N>
void multiply (int (&array1)[L][M], int (&array2)[M][N]) {
    //...
}

int main () {
    int array1[4][10];
    int array2[10][6];
    int array3[2][2];
    multiply(array1, array2);  // ok, inner dimensions match
    multiply(array1, array3);  // fail, inner dimensions don't match
}

The dimensions of the arrays will be determined by type deduction from the template function call.


text:
Q: IMAP on Mail.app, and Gmail questions I recently setup my gmail account with IMAP on my email account.
Unfortunately, I now have a stubborn white folder called [Gmail] that contains all of gmail's folders. I can't get rid of them, or hide them. When mail arrives, it also appears in Gmail's folders. Syncing is a little slow, so it can take a while for messages to be marked as read. Additionally, junk emails do not appear in the junk folder, they appear in the spam folder - which is all the way down my folder list, inside the white gmail folder ... so many more clicks to check that I'm not missing something.
Question One How can I tweak the display of gmail folders in mail.app?
Also, with a second (non-gmail) imap account that I have setup, when I send a message, it appears as unread. Is this due to the way my server (hMailServer) is setup, or just a quirk in mail.app?
Question Two How can I stop messages in my sent folders from showing up as unread? They're read, I just wrote them!

A: If you have Google Labs enabled, you can try out the advanced IMAP controls feature. Among other things, it allows you to define which labels/folders you want to sync.
This might help you with Question One.
Note also, that part of the reason that this is confusing is that Google designed Gmail from the ground up and it's built around labels -- each message can zero, one or many. IMAP is built on hierarchical folder -- each message is in one.
When Google added IMAP support to Gmail, they had to find a way to graft labels onto IMAP's folder protocol. This article in Gmail help has a nice table showing how IMAP actions map to actions you would perform in the Gmail web interface.

A: Read this..Patiently and you'll love it!
http://db.tidbits.com/article/10253

A: See some more details on Gmail settings at Greyed out emails in Mail.app. (Be sure to understand how the Gmail Trash works, and how to set up its SMTP server.)


text:
Q: flexbox nested: two vertical boxes in two vertical boxes with breakpoint I want 4 flex boxes in one row with the same height.
There is one breakpoint at which the 4 flex boxes should break in two lines with 2 flexboxes. The 2 Flexboxes in each line now should have the same height.
Here is the code:

.content {
  color: #fff;
  font-size: 20px;
  margin: 50px auto;
  max-width: 1045px;
  padding: 0;
  text-shadow: 1px 1px #000;
}
.content .fullContainer,
.content .halfContainer,
.content .quarterContainer,
.content .quarterSecondContainer {
  display: flex;
}
@media (max-width: 1075px) {
  .content .halfContainer,
  .content .quarterSecondContainer {
    display: block;
  }
}
.content .fullContainer .full {
  background-color: #ff0;
  color: #000;
  margin-bottom: 15px;
  width: 1045px;
}
@media (max-width: 1075px) {
  .content .fullContainer .full {
    width: 515px;
  }
}
.content .halfContainer .half {
  background-color: green;
  margin-bottom: 15px;
  width: 515px;
}
.content .halfContainer .half:first-child {
  margin-right: 15px;
}
@media (max-width: 1075px) {
  .content .halfContainer .half {
    display: block;
  }
  .content .halfContainer .half:first-child {
    margin-right: 0;
  }
}
.content .quarterContainer .quarter {
  background-color: pink;
  color: #fff;
  margin-bottom: 15px;
  margin-left: 15px;
  width: 250px;
}
.content .quarterContainer .first {
  margin-left: 0;
}
@media (max-width: 1075px) {
  .content .quarterContainer .firstInSecond {
    margin-left: 0;
  }
}

Full Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus

half Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus

half Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus musLorem ipsum dolor sit amet, consectetuer adipiscing
      elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus

quart

quart Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus

quart

quart

The pink one.


text:
Q: pam_unix(sudo:auth): auth could not identify password for [asteriskpbx] to install the asterisk program, I created a sudo user and added to  /etc/sudoers file like this:
asteriskpbx ALL=(ALL) NOPASSWD: ALL

but, when I try to start the service, I get the following report:
Jun 15 15:18:03 localhost.localdomain sudo[1023]: pam_unix(sudo:auth): conversation failed
Jun 15 15:18:03 localhost.localdomain sudo[1023]: pam_unix(sudo:auth): auth could not identify password for [asteriskpbx]

why can't it login? I have already added to the sudoers file to use no password.

A: What did you use to create the user?
My preliminary test shows that a simple
useradd <login>
visudo
# in visudo
<login> ALL=(ALL) NOPASSWD: ALL
# save and exit visudo

# as another user
$ sudo -u <login> hostname -f
$ sudo -u <login> -s

Should work without any further problems, what does the asterisk log tells you ?
Did you by any chance set a password on that new user ?
Remember <login> is a placeholder, please change it to what you feel needed, and I would recommend you to use useradd -r <login> as -r is system account.
What shell is your account using, the account that is not able to start up asterisk? Look in /etc/passwd
Do you use LDAP on your network and did you configure your machine to lookup using LDAP?


text:
Q: How to escape spaces while using command's output in command line I want to perform the following command in command line :
$ md5sum $(find . -type f)

But this would cause problems when it encounter files with spaces in filenames :
md5sum: Kaufmann: No such file or directory
md5sum: Mobile: No such file or directory
md5sum: 3D: No such file or directory
md5sum: Graphics: No such file or directory

A: Do this way instead:
find . -type f -exec md5sum {} \;

This way spaces in the matched filenames will be handled correctly.


text:
Q: How do I prevent PyCharm from creating a virtualenv every time I start a new project? I am a python hobbyist and installed pycharm to work on a number of projects. Every time I start a new project, pycharm community edition creates a new virtualenv without any packages. So for each small project, I have to install numpy, matplotlib, scikit etc again and again. This is irritating. How can this feature be disabled ?
I tried to search for this question but did not find it. Sorry if it is a duplicate.

A: You need to hit the little triangle next to "Project Interpreter" under the Location.  Then hit the radio button for existing interpreter.


text:
Q: How to set variable back to original in python loop I use python with selenium and pyautogui for image recognition. In this code I'm looping image searching, when the image is on screen it should type Hi and then wait 20 seconds and set the variable back to original value,then search for the image again. It works except it does not set the variable to original again and keeps writing Hi even the image is not on screen. Thanks for any help.
    for i in range(0,20000):
    time.sleep(2)
    global enjoy1
    enjoy1 = pyautogui.locateOnScreen('images/enjoy.png')
    enjoy1
    print(enjoy1)
    if enjoy1 == None:
        print("it is None")
    else:
        pyautogui.click(856, 816)
        pyautogui.typewrite('Hi')
        pyautogui.click(1184, 816)
        time.sleep(20)
        enjoy1 = None


text:
Q: listing a listview is taking too much time and memory in android i 3 classes, one which contains the list view and is the acitivity. second class is a adapter that i have built to populate the listview. third class which interacts with the database and gives info to the second class.
the functioning of all the three classes when i do the following:
listview.setAdapter(new CustomAdapter())
it is taking a whole of time because there are many records to display.
i want to use multithreading over here.
how do i go about it?
i know of AsyncTask. would it work if i kept the above mentioned statement in the doInBackground() method, but how will i know when the list is populated?
SOLUTION:
Got a solution. i am passing the progressdialog object from the mainactivity class into the custom adapter. over there in the getView method i am checking whether the int arg0 (the variable giving the position in the dataset) has reached the end. upon this i dismiss the progressdialog that i have passed.

A: You could also just show a certain amount of items, and add more items when the user scrolls to the bottom.
Here is a nice example on how to do this;
http://p-xr.com/android-tutorial-dynamicaly-load-more-items-to-the-listview-never-ending-list/

A: The AsyncaTask class contains methods like onProgressUpdate and publishProgress. So whenever you get some data you could call publishProgress to indicate that some data has been received.
Then in onProgressUpdate, you could show the data. Thus, the user does not have to see a Progress bar for too long and he can view the items as they appear.

A: The list control is smart enough to create only needed number of views which is equal to the max number of visible view + 2 extra. When you scroll down it reuses the views. I guess that the time consuming operation is in creating a single view. Are you loading something from remote address ?


text:
Q: How to Auto Trigger Button_Click event every 5 sec? I have one button name called Submit. I would like to trigger Auto Button_Click event for every 5sec.
E.g:
private void Button_Click(object sender, RoutedEventArgs e)
{
     MessageBox.Show("Welcome to WPF....");
}

Every 5sec I need to call this Button_Click event to show Message like "Welcome to Google...." automatically.
Please help me to solve.

A: In Wpf, you could use DispatcherTimer
public MainWindow()
{
    InitializeComponent();

     Loaded += MainWindow_Loaded;
}

private void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
    //Timer
    DispatcherTimer timer = new DispatcherTimer();
    timer.Tick += (s, ev) => btnClickMe.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
    timer.Interval = new TimeSpan(0, 5, 0);
    timer.Start();
}

A: create a timer to run every 5 seconds and send: Button_Click(null, null);
public static void Main()
{
    var timer = new Timer();
    timer.Elapsed+= OnTimedEvent;
    timer.Interval=5000;
    timer.Enabled=true;
    Console.ReadKey();
}

 private static void OnTimedEvent(object source, ElapsedEventArgs e)
 {
     Button_Click(null, null);
 }

A: It is as simple as this. Create a timer of 5 seconds duration and do this on the timer_tick event.
buttonName.RaiseEvent(new RoutedEventArgs(ButtonBase.ClickEvent));


text:
Q: Picturebox with Caption in VB.NET How can I have a picturebox (control) with a caption? I already can add Text over this picturebox, but I want it under the picturebox. But if the location of the text is beyond Picturebox's size, it won't be visible. It would be great if the text had a border & background color too.
Please help.
Here's the code:
Public Class neoPic
   Inherits PictureBox
   Protected Overrides Sub OnPaint(ByVal e As PaintEventArgs)
       MyBase.OnPaint(e)
       e.Graphics.DrawString("Caption ", New Font("Cambria", 10), Brushes.Black, New PointF(0, 60))
   End Sub
End Class

A: I ended up creating a UserControl. I put the working code here in case it saves another developer's time. I added a UserControl to my project (named PicTitled) and added a Picturebox (named PTPicturebox) and a Label (named PTLabel) stacked on each other.
Then I added Text & Image property for the PicTitled and an event handler for mouse click.
Public Class PicTitled
    Public Shadows Event MouseClick As MouseEventHandler

    Overrides Property Text As String
        Get
            Return PTLabel.Text
        End Get
        Set(ByVal Value As String)
            PTLabel.Text = Value
        End Set
    End Property

    Property Image As Image
        Get
            Return PTPicturebox.Image
        End Get
        Set(ByVal Value As Image)
            PTPicturebox.Image = Value
        End Set
    End Property

    Private Sub PicTitled_MouseClick(sender As Object, e As MouseEventArgs) Handles MyBase.MouseClick, PTPicturebox.MouseClick, PTLabel.MouseClick
        RaiseEvent MouseClick(Me, e)
    End Sub

End Class

And in the main form, I added a code like:
    Private Sub CreateObj()
        Dim pbPicture As New PicTitled
        pbPicture.Name = "Object"
        pbPicture.Location = New System.Drawing.Point(40, 40)
        pbPicture.Text = "Object"
        pbPicture.Image = My.Resources.IMG
        pbPicture.Size = New System.Drawing.Size(50, 50)
        AddHandler pbPicture.MouseClick, AddressOf PictureBox_MouseClick

        Panel1.Controls.Add(pbPicture)
    End Sub

    Private Sub PictureBox_MouseClick(sender As Object, e As MouseEventArgs)
        'Do stuff when mouse click happens...
    End Sub


text:
Q: SELECT INTO with more than one attribution This instruction works:
SELECT INTO unsolvedNodes array_agg(DISTINCT idDestination)
FROM road
WHERE idOrigin = ANY(solvedNodes)
AND NOT (idDestination = ANY(solvedNodes));

But I would like to use something this way:
SELECT INTO unsolvedNodes array_agg(DISTINCT idDestination), lengths array_agg(length)
FROM road
WHERE idOrigin = ANY(solvedNodes)
AND NOT (idDestination = ANY(solvedNodes));

How to use only one SELECT INTO instruction to set multiple variables?

A: In PL/pgSQL you can SELECT INTO as many variables at once as you like directly. You just had the syntax backwards:
SELECT INTO unsolvedNodes, lengths
       array_agg(DISTINCT idDestination), array_agg(length)
FROM   road
WHERE  idOrigin = ANY(solvedNodes)
AND    NOT (idDestination = ANY(solvedNodes));

You have the keyword INTO followed by a list of target variables, and you have a corresponding SELECT list. The target of the INTO clause can be (quoting the manual here):

...a record variable, a row variable, or a comma-separated list of
simple variables and record/row fields.

Also:

The INTO clause can appear almost anywhere in the SQL command.
Customarily it is written either just before or just after the list of
select_expressions in a SELECT command, or at the end of the command
for other command types. It is recommended that you follow this
convention in case the PL/pgSQL parser becomes stricter in future versions.

This is not to be confused with SELECT INTO in the SQL dialect of Postgres - which should not be used any more. It goes against standard SQL and will eventually be removed, most likely. The manual actively discourages its continued use:

It is best to use CREATE TABLE AS for this purpose in new code.

A: Yes,
SELECT name,family INTO cName, cFamily FROM "CommonUsersModel";

OR
SELECT INTO cName, cFamily name,family  FROM "CommonUsersModel"

A:     DO
  $$
  DECLARE var_one UUID;
    var_two UUID;
    var_three UUID;
    var_four UUID;
    var_five UUID;
 BEGIN
     Select INTO var_one,var_two,var_three,var_four,var_five
              h.foocol1,
              h.foocol2,
              h.foocol3,
              h.foocol4,
              h.foocol5
    from footable h
    where h.fooid = 2;

END;
$$;

This is how you can set multiple variables using SELECT INTO
Thanks !


text:
Q: How to convolve a 3 dimensional array (in this case a filter bank) with a 2 dimensional image (monochrome) in Python? I have a function definition that takes in an image that is monochromatic and 2 dimensional, and a filter bank that is a 3 dimensional array (48 2D filters). I need to convolve the two to find the feature vector at each pixel location. How do I do that?
I have tried scipy.ndimage.convolve() but get the error "filter weights array has incorrect shape."

A: To make things simple, simply loop over the temporal dimension of your filter bank, then apply convolution to the image and each filter within the filter bank.  After, stack the results into a 3D matrix.  This is actually what I would do for readability.
Suppose your image is stored in img and your filters are stored in filters.  img is of size M x N and your filters are of size R x C x D with D being the total number of filters you have.
As you've eluded to using scipy.ndimage.convolve, we can just use that.  However, it's possible to use cv2.filter2D too.  I'll show you how to use both.
Method #1 - Using scipy.ndimage.convolve
import scipy.ndimage
import numpy as np

outputs = []
D = filters.shape[2]
for i in range(D):
    filt = filters[...,i]
    out = scipy.ndimage.convolve(img, filt)
    outputs.append(out)

outputs = np.dstack(outputs)

The above is straight forward.  Create an empty list to store our convolution results, then extract the total number of filters we have.  After, we loop over each filter, convolve the image with said filter and append it to the list.  We then use numpy.dstack to stack all of the 2D responses together to a 3D matrix.
Method #2 - Using cv2.filter2D
import cv2
import numpy as np

outputs = []
D = filters.shape[2]
for i in range(D):
    filt = filters[...,i]
    filt = filt[::-1, ::-1]
    out = cv2.filter2D(img, -1, filt)
    outputs.append(out)

outputs = np.dstack(outputs)

This is exactly the same as Method #1 with the exception of calling cv2.filter2D instead.  Also take note that I had to rotate the kernel by 180 degrees as cv2.filter2D performs correlation and not convolution.  To perform convolution with cv2.filter2D, you need to rotate the kernel first prior to running the method.  Take note that the second parameter to cv2.filter2D is the output data type of the result.  We set this to -1 to say that it will be whatever the input data type is.

Note on indexing
If you want to avoid indexing into your filter bank all together and let the for loop do that for you, you can shift the channels around so that the number of filters is the first channel.  You can then construct the resulting 3D output matrix by list comprehension:
filters = filters.transpose((2, 0, 1))
outputs = np.dstack([scipy.ndimage.convolve(img, filt) for filt in filters])

A: You can make the monochrome image a 3D array by either padding zeros or replicating the image itself. The number of such paddings would depend on the depth of convolution kernel. For example, let d be the depth of the convolution kernel and I is your image, then
I_pad = np.empty((I.shape[0], I.shape[1], 0))

# Do this for copying the image across channels
I_pad = [np.concatenate((I_pad, I), axis=-1) for _ in range(d)]

# Do this for zero padding
I_pad = [np.concatenate((I_pad, np.zeros(size(I))), axis=-1) for _ in range(d)]

Then carry out the convolution. Hope it helps


text:
Q: Nativescript - publish to app store Incorrect Verification Code? I am trying to publish my app to appstore connect with the following command tns publish ios 'aaaaaa@bbb.ccc' 'dasdhasldasjdl' --bundle --env.* --appleApplicationSpecificPassword 'pdnlaksndi2dasd' and I get an sms with the code. Once I enter it in the console, i get the following:
    {
  "service_errors" : [ {
    "code" : "-21669",
    "title" : "Incorrect Verification Code",
    "message" : "Incorrect verification code.",
    "suppressDismissal" : false
  } ],
  "hasError" : true
}

What am I doing wrong?


text:
Q: SQL Server Clear transaction log I have a database that is in Full Recovery Mode that I restored from a backup file
Now I want to clear/truncate the transaction log file.
How I can do this.
Step 1 I tried to backup the transaction log using
BACKUP LOG [test] TO  DISK

but I get error:

BACKUP LOG cannot be performed because there is no current database backup.

So what I should do to clear the transition log if I want to keep the database in Full Recovery Mode

A: One solution is using shrink database files from database menus.
Another is using some scripting(change dbname to your database name):
ALTER DATABASE dbname
SET RECOVERY SIMPLE;
GO
-- Shrink the truncated log file to 1 MB.
DBCC SHRINKFILE (dbname_Log,10);
GO
-- Reset the database recovery model.
ALTER DATABASE dbname
SET RECOVERY FULL;
GO

A: This:

BACKUP LOG cannot be performed because there is no current database backup.

Means your database is in "pseudo-full" recovery, and until someone takes a full backup there's no way or need to take log backups, and the log will be still be truncated after each checkpoint, just like in the SIMPLE recovery model.


text:
Q: Access - Select Distinct based on Field Value My Code
I have an Access query:
SELECT DISTINCT [Request-Priority, ALL_Q].RequestID, "Awaiting Approval" AS RequestStatus
FROM [Request-Priority, ALL_Q] LEFT JOIN LIST_RequestBurndown_Q ON [Request-Priority, ALL_Q].RequestID = LIST_RequestBurndown_Q.RequestID
WHERE (((LIST_RequestBurndown_Q.MilestoneStatus)="Awaiting Approval") AND (([Request-Priority, ALL_Q].[Completed on]) Is Null))

UNION

SELECT DISTINCT [Request-Priority, ALL_Q].RequestID, "Blocked (see notes)" AS RequestStatus
FROM [Request-Priority, ALL_Q] LEFT JOIN LIST_RequestBurndown_Q ON [Request-Priority, ALL_Q].RequestID = LIST_RequestBurndown_Q.RequestID
WHERE (((LIST_RequestBurndown_Q.MilestoneStatus)="Blocked (see notes)") AND (([Request-Priority, ALL_Q].[Completed on]) Is Null))

UNION

SELECT DISTINCT [Request-Priority, ALL_Q].RequestID, "Completed - Awaiting Rollout" AS RequestStatus
FROM [Request-Priority, ALL_Q] LEFT JOIN LIST_RequestBurndown_Q ON [Request-Priority, ALL_Q].RequestID = LIST_RequestBurndown_Q.RequestID
WHERE (((LIST_RequestBurndown_Q.MilestoneStatus)="Completed") AND (([Request-Priority, ALL_Q].[Completed on]) Is Null));

The basic concept of the query... based on the status of individual milestones (LIST_RequestBurndown_Q.MilestoneStatus), determine an overall status of a RequestID ([Request-Priority, ALL_Q].RequestID).
My Issue
For some RequestID's, there will be milestones in more than one status. For example, I may get results like:
RequestID   RequestStatus
123         Awaiting Approval
243         Blocked
243         Awaiting Approval
243         Completed - Awaiting Rollout
542         Awaiting Approval

What I would like to do is "prioritize" which RequestStatus displays so there is only one record per RequestID.
I've been trying to think of how to do this using ORDER BY, WHERE, DISTINCT ON, or possibly even just creating a table of the possible status options with an associated priority and using MAX - but at this point I'm just overthinking this. Any help would be greatly appreciated!

A: Suggestion: a table to model the prioritization:
CREATE TABLE RequestStatusPrioritization
( RequestStatus VARCHAR(20) NOT NULL
     REFERENCES RequestStatuses ( RequestStatus ),
  RequestStatusRank INT NOT NULL );

...then join to this table and return the lowest (MIN) rank.


text:
Q: Shuffle vector in C++ I have a std::vector that I need to shuffle. It is only ~20 members in size. It also needs to produce a different shuffle every time the program is run.
Right now I am using random_shuffle, however, it gives the same result every time the program is run. I tried that srand(unsigned(time(NULL))); that was suggested in this thread, however, that didn't work on my platform.
If possible, I want to use only standard code.
Edit: Here is my implementation:
vector<Tile>gameTiles;
gameTiles.push_back(Tile(0,0));
gameTiles.push_back(Tile(0,1));
gameTiles.push_back(Tile(0,2));
gameTiles.push_back(Tile(0,3));
gameTiles.push_back(Tile(0,4));
//etc. ~20 member

random_shuffle(gameTiles.begin(), gameTiles.end());

A: If srand(unsigned(time(NULL))); doesn't help, then your implementation must not be using the standard rand() as its random number generator.  In that case, there is an alternative version of random_shuffle that takes a custom random number generator.  You could just pass a wrapper around rand(), like this:
int MyRand(int n)
{
    return std::rand() % n;
}

// ...
std::random_shuffle(bar.begin(), bar.end(), MyRand);
// ...

If you want something with a more uniform distribution, look into the C++11 <random> header.

A: Well the implementation you have give cannot work (you named a type foo and used the same literal as a variable). Anyways try something like this
// random generator function:
ptrdiff_t myrandom (ptrdiff_t i) { return rand()%i;}
// pointer object to it:
ptrdiff_t (*p_myrandom)(ptrdiff_t) = myrandom;

int main(void){
  srand(0)
  vector<Tile>gameTiles;
  gameTiles.push_back(Tile(0,0));
  gameTiles.push_back(Tile(0,1));
  gameTiles.push_back(Tile(0,2));
  gameTiles.push_back(Tile(0,3));
  gameTiles.push_back(Tile(0,4));
  random_shuffle(gameTiles.begin(), gameTiles.end(), p_myrandom);
}

It will ensure random_shuffle uses standard rand and that it is initialized properly. It should give different results unless you execute the application twice in the same second, that would lead to using the same seed for rand.
The code it right from here but there is anything to change, so i just used it.


text:
Q: Implementing unique connections for each goroutine using firebirdsql I'm intending to populate multiple firebird databases from multiple goroutines concurrently and in order to do that my worker function has a map (dbConnections) that holds the connections to databases (maps the name of the database to the connection):
func worker() {
    dbConnections := map[string]*sql.DB {}
    for dbName, dbFileName := range dbFiles {
        connection, err := sql.Open("firebirdsql", ("sysdba:master@localhost:3050/" + url.PathEscape(dbsPath + dbFileName)))
        err = connection.Ping()
        if err != nil {
            fmt.Println("Ping failed: ", err.Error()
            return
        } else {
            dbConnections[dbName] = connection
            fmt.Println(fmt.Sprintf("Connected to the: %v", dbName))
            defer dbConnections[dbName].Close()
        }
    }

    // using the connections to populate databases...
    // ...
}

The problem is that when I run worker function as just 1 goroutine, everything works just fine, but as soon as I increase the number of goroutines, it seems that dbConnections from other goroutines gets messed up and sql executions complain about insertion into non existing tables!
How can I create dbConnections in such a way that every goroutine, has its own unique version of it?
Edit:

*

*Go version: v1.14.2.windows-amd64

*firebirdsql version: v0.0.0 (f095ac7) (Published: May 5, 2020)

A: As many mentioned in the comment section, the problem was because of thread-safety
 in firebirdsql and especially when creating new tables. Defining a mutex and enclosing the sql execution method between mutex.Lock() and mutex.Unlock() (so that only one goroutine can create tables at any given time) solved the problem.


text:
Q: Is Intellij IDEA obsolete like Eclipse for Android development? Google officially announced that Eclipse should no longer be used for Android development and we should move to Android Studio.
Does the same apply to IntelliJ IDEA? I have multiple projects in Eclipse format which will not be ported to Gradle yet, so I am not sure if I can use IntelliJ IDEA for maintaining those project.
I was unable to find anything official about IntelliJ IDEA after Android Studio became stable so I suspected that nothing has changed with it (it's the only issue with ADT and support for ADT).
Note: I am using IntelliJ IDEA right now, as I have been using it for 3 years, and so far I have not faced any issues with it.

A: Android Studio is based on IntelliJ IDEA, so that won't happen until Android Studio is deprecated itself

A: I don't think you need to move your Android Projects from IntelliJ IDEA to Android Studio since they are both developped by JetBrains and Android Studio come from IntelliJ IDEA platform.
You can find more details on the IntelliJ IDEA and Android Studio FAQ.
Here's a quote from this FAQ :

If I'm already a user of IntelliJ IDEA, do I need to switch to Android Studio for Android development?
No. Android Studio is focused specifically on Android development and
  provides streamlined environment and project setup, but otherwise all
  of its features are available in IntelliJ IDEA.

A: Please read this faq. Short answer - yes, it's ok to use IntelliJ with Android plugin for development. Also have a look at Android page on Intellij site here.

Being the most intelligent IDE for Java IntelliJ IDEA provides
  out-of-the-box Android support that includes intelligent coding
  assistance, for professional development of Android applications.
  Android support is available in IntelliJ IDEA Ultimate and IntelliJ
  IDEA Community Edition.


text:
Q: perl regex for specific string I want to split a string into different columns. Each of the lines appears as the one below.
TR10052|c9_g13_i6_DESeqResultsBacterialen=248   gi|497816164|ref|WP_010130320.1|        97.56   82      2       0       1       246     9       90      7e-51     167

I can split by white space, tabs, and "|" but I'm having trouble splitting the rest of the first section "TR10052|c9_g13_i6_DESeqResultsBacterialen=248" by a specific match of characters. I want the first column to be the TR##### piece, the second column to be the c#_g#_i# piece and the third column to be the rest of it starting with "_DESeq..." etc.
while ( my $line = <RESULTS> ) {
    chomp $line;
    my @column       = split( /[\t|] /_DES.*/ /, $line );
    my $transcriptID = $column[0];
    my $isoform      = $column[1];
    my $deseq        = $column[2];
    }

A: Use a negative look ahead to split on underscores that are not followed by "letter digit".
Try splitting on this regex:
/\||\_(?![a-z]\d)|\s+/

See live regex demo matching the desired characters on which to split.

A: Two splits might make it easier for you:
my ($transcriptID, $rest) = split(/\|/, $line, 2);
my ($isoform, $deseq) = split (/_DESeq/, $rest, 2);
$deseq = "_DESeq$deseq";

Transforms:
"TR10052|c9_g13_i6_DESeqResultsBacterialen=248 gi|497816164|ref|WP_010130320.1| 97.56 82 2 0 1 246 9 90 7e-51 167"

Into:
"TR10052", "c9_g13_i6", "_DESeqResultsBacterialen=248 gi|497816164|ref|WP_010130320.1| 97.56 82 2 0 1 246 9 90 7e-51 167"

Is that what you're looking for?

A: It's easy to over-use split. In this case I think it's better to extract the fields you want by writing a custom regex pattern.
Like this
use strict;
use warnings;

while ( <DATA> ) {
  my ($transcript_id, $isoform, $deseq) = /^ ([^|]+) \| (c\d+_g\d+_i\d+) _ (\S+)/x;
  print $_, "\n" for $transcript_id, $isoform, $deseq;
}

__DATA__
TR10052|c9_g13_i6_DESeqResultsBacterialen=248   gi|497816164|ref|WP_010130320.1|        97.56   82      2       0       1       246     9       90      7e-51     167

output
TR10052
c9_g13_i6
DESeqResultsBacterialen=248


text:
Q: Passing request headers to all requests using cypress I want to intercept request headers for my application globally for all the requests and routes including html,js ,css
Tried below code but didn't work
tried cy.server
cy.route
code that i tried for intercepting.
'use strict'
describe(`TodoMVC using Cypress`, function () {
  it('passing request header', () => {

    cy.server({
      whitelist: (xhr) => {

        return xhr.method === 'GET' && /\.(jsx?|html|css)(\?.*)?$/.test(xhr.url)
      },
      onAnyRequest: (route,  proxy) => {
        proxy.xhr.setRequestHeader('Referer',  '***'),
        proxy.xhr.setRequestHeader('Authorization','***')

      }
    })

    var options = {
      url: 'http://localhost:8080',
      headers: {'Referer': '***','Authorization' :'**='}
    };
   cy.visit(options);
  })
})


text:
Q: Azure Monitor Workbooks - influence layouting of Graph visualization? I'm using the Graph visual in Azure Monitor Workbooks. The problem is that with every refresh the layout looks randomly differently.
Is there anyway to programmatically fix the layout (i.e. the positioning of the nodes)?
1)

*after only hitting refresh

A: Unfortunately, there's no way to guarantee it.  The portal's graph control is relatively limited in this regard.
One thing you can possibly do is to make sure that your query has a predictable order to the rows, so that the rows always are in the same order.  If the nodes are in the same order and edges are in the same order in the results, hypothetically it should lay out the same every time.


text:
Q: App.root must be an _instance_ of Widget. Invalid instance in App.root I'm not exactly new to python but wouldn't I know it well and fully, but I'm completely new to Kivy. It's just a small thing I'm doing just to start somewhere. I'm working in Visual Studio Code(VSC). Python version 3.10. The idea is: there are 5 buttons, each button has a name, when you click on a button, image(meme) should show up. Here is the full code, terminal, debugger and what is in command prompt:
code
code
Terminal
Terminal
Debugger
Debugger
Command Prompt
Command Prompt
Here is python itself and a folder "Projects"
C:\Users\Кирилл\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Python 3.10
enter image description here
Here is folder with virtual environment(App_EPQ) and a folder with code(App_code)
C:\Users\Кирилл\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Python 3.10\Projects
enter image description here
Thanks in advance
Tried to rewrite the code but that didn't work. Tried to find someone with a similar problem no luck there also. No idea what to do next and how to fix it so this is my last hope.

A: Your class has to inherit a layout as well as App:
    class HBoxLayoutExample(BoxLayout, App)

Another way to do it would be to create a class that builds the app and returns the layout:
    class HBoxLayoutExample(BoxLayout)
    **your code**

    class HBoxApp(App):
        def build(self):
            return HBoxLayoutExample
    if __name__ == '__main__':
        HBoxApp().run()

as shown here https://kivy.org/doc/stable/guide/lang.html#designing-with-the-kivy-language

A: Replace your line:
return layout, button

with:
return layout

That's all. build() method have to return one widget, which in your case is BoxLayout instance.


text:
Q: Given any 40 people, at least four of them were born in the same month of the year Given any 40 people, at least four of them were born in the same month of the year.
Why is this true?

A: Hint:  Suppose otherwise.  Then at most three people are born in each of the twelve months of the year.  What can you conclude?

A:
Given any $40$ people, at least four of them were born in the same month of the year.

The the phrase "at least four of them were born in the same month of the year" means just that there is some subset of four people out of the $40$
who share a common birth month. It does not mean that everyone belongs
to some clique of four people with the same birth month.
The usual proof of this uses a version of the so-called Pigeonhole Principle.
The idea is that if you have $n$ holes and can only put
$k$ pigeons in each hole, the total number of pigeons
you can put in the holes is $nk$.
We consider each month to be a "hole" and each person to be a "pigeon" in the "hole" named by the month they were born in.
The question is, is it possible to assemble a group of $40$ people without
ever putting a fourth person into any of the holes?
Of course it's easy to arrange it so that we do have four people who were born in the same month of the year, if we can pick whomever we want
to be in the group.
Just interview people until you find four with birthdays in January,
then add any other $36$ people.
But if you are trying not to have any subset of four people who have
the same birth month, then once you have three people born in any
particular month you cannot accept any more from that month.
Once you have three birthdays in March, for example, you cannot let in any more.
You can only take other months.
Once you have added the $36$th person to the group, one of the
following two things has happened:

*

*For each of the $12$ months, you have $3$ people born in that month;

*You already have at least four people born in the same month (for example, you might have $5$ July birthdays, or $4$ in September).

So when you add a $37$th person to the group, either you are in case 1, and no matter who you choose and what their birth month is, you already have three people born in that month and the new person makes four, or you
are in case 2 and already have four people born in the same month.
Some related groups sizes are:

*

*$4$ is the minimum number of people in your group in order for it to be possible to have at least four born in the same month.

*$36$ is the maximum number of people in your group if you do not have four people born in the same month. (There is no group of more than three born in the same month.)

*$37$ is the minimum number of people in your group in order for it to be necessary to have at least four born in the same month.

*$48$ is the maximum number of people in your group in order for it to be possible to have no group of more than four born in the same month.


text:
Q: What Is the most popular combination of technologies used to building Reactjs web apps I'm mid PHP/Laravel developer with some exp in jQuery and Vue.js
I want to start self-learning in reactive JS frameworks (for example ReactJS), because I see is the near future in web development.
I checked the [React + redux] is the most popular technology working on browser side, but what about back-end ?
Secured API to PHP/MySQL? or maybe run apps directly on NodeJS server ? if nodejs env. then where will be storing the data ? SQL? NoSQL?
Tell me please what back-end stack is the most popular? or what stack is the near future ?
What about PWA with ReactJS ?
Thank You!

A: In my experience node.js is more popular for startups and makes it easy to work with since its all javascript.
Java and C# tend to be popular in large enterprise companies
SQL systems, such as MYSQL and PSQL are by and far the most popular options for both small and large companies.
SQL systems such as, Oracle and Microsoft SQL server, are the most popular in extremely large companies.
MongoDB is the most popular NoSQL db but its not used as often in production.
PHP as a server side language is used in about 80% of websites, but that is mostly because of wordpress, I have personally never seen a React frontend being implemented with a PHP backend.
Django and flask are popular python server frameworks but I find them to be popular with AngularJS( the original angular not angular 2+) not React.
The most common stack Ive seen is React, Redux, Express, PSQL, AWS.
https://w3techs.com/technologies/overview/programming_language/all
https://db-engines.com/en/ranking

A: Hi with my previous experience
ReactJs + Redux + fire base
this is very good technical combination you can use
reactJs , redux , meterilaUI,Sementic UI,ant design for front end.
and fire base can easily connected with your application.
advantage of this architecture the app will real time data application , no end point integration , quickly development , easy to authenticate
sample project
ReactJs + Redux + REST + Spring-boot in this project back end service developed using java spring-boot and it possible for connect any relational data bases such as Oracle , MYSql, NoSql , even any kind of Data bases using Spting-Data-JPA or Hibernate , JPA.
But authentication and state management not much easy. need to implement JWT to any  state management method because REST is stateless.
advantage is good for micro services architecture , easy to build react app inside spring boot (packaging as .jar .war) and deployee j2EE server.
sample project
i have already developed project based on these 2 technologies stacks both are worked as my different requirements.


text:
Q: How get class name from 'this' reference in jquery I want to know how can I get the class name of an element from this reference.
I have following HTML element
<input type="checkbox" class="NotSelected @placeholderString" onchange="SaveCompairedOffers(this);">

jQuery code
function SaveCompairedOffers(obj) {
    //Hiding irrelevant code from here

    AddCompareOfferInCompareBox();
}

In the AddCompareOfferInCompareBox function I want to append class name of the object on compare-box class.
function AddCompareOfferInCompareBox()
{
    var innerHtml = "";
    $('.SelectedOffer').each(function ()
        //append class name of current passed object to this div
        innerHtml = innerHtml + '

';
    });
    $(".AddCompareOfferByMe").html(innerHtml);
}

How can I do this?

A: I would recommend you to use data-* prefixed attribute to store arbitrary data.
<input type="checkbox" class="NotSelected" data-str="@placeholderString" onchange="SaveCompairedOffers(this);">

This can be fetched using HTMLElement.dataset property

The HTMLElement.dataset property allows access, both in reading and writing mode, to all the custom data attributes (data-*) set on the element. It is a map of DOMString, one entry for each custom data attribute.

function SaveCompairedOffers(obj){
   var str =  obj.dataset.str;
   AddCompareOfferInCompareBox(str );
}

function AddCompareOfferInCompareBox(str)   {
    $('.SelectedOffer').each(function ()
        $('

', {
           "class" : "compare-box " + str
        }).appentTo(".AddCompareOfferByMe");
    });
}

However if you still want to use class name, then Element.className property can be used.

className gets and sets the value of the class attribute of the specified element.

usage
function SaveCompairedOffers(obj){
   var str =  obj.className;
}

A: The simplest way to this is vanilla javascript. In your function, where you want to reference this, add the following code to assign your classes to a variable:
var classes = this.className

If you want to get an array of all classes, you can achieve this by using the split() function, like the following:
var classes = this.className.split(' ')

A: To answer the actual question, how to get the css class assigned to an object from a jQuery reference to it, try this:
var elementClass = ($(myselector).prop('className');


text:
Q: Symfony : should logic about formatting a parameter be in repository or controller? What is the best practice according the Symfony way ?
Option 1 :
class MyController extends Controller
{
    public function myAction(...)
    {
        // ..
        $example = $this->getDoctrine()->getRepository('AppBundle:Contract')->getContracts(array(
            'company_id'                => $company->getId(),
            'contract_month_date_start'  => date('Y-m-d', strtotime('first day of this month', $contractDate->getTimestamp())),
            'contract_month_date_end'    => date('Y-m-d', strtotime('last day of this month', $contractDate->getTimestamp())),
        ));
        // ..
    }
}

class ExampleRepository extends EntityRepository
{
    public function getContracts($options)
    {

        //..

        $qb->select('contract')
            ->from('AppBundle:Contract', 'contract')
            ->where('contract.companyId = :company_id')
            ->andWhere('contract.startDate < :contract_month_date_end')
            ->andWhere('contract.endDate < :contract_month_date_end')
            ->setParameter('company_id', $options['company_id'])
            ->setParameter('contract_month_date_start', $options['contract_month_date_start'])
            ->setParameter('contract_month_date_end', $options['contract_month_date_end']);

        //..
    }
}

Option 2 :
class MyController extends Controller
{
    public function myAction(...)
    {
        // ..
        $example = $this->getDoctrine()->getRepository('AppBundle:Contract')->getContracts(array(
            'company'      => $company,
            'contractDate' => $contractDate
        ));
        // ..
    }
}

class ExampleRepository extends EntityRepository
{
    public function getContracts($options)
    {

        //..

        $company_id                = $options['company']->getId();
        $contract_month_date_start = date('Y-m-d', strtotime('first day of this month', $options['contractDate']));
        $contract_month_date_end   = date('Y-m-d', strtotime('last day of this month', $options['contractDate']));

        $qb->select('contract')
            ->from('AppBundle:Contract', 'contract')
            ->where('contract.companyId = :company_id')
            ->andWhere('contract.startDate < :contract_month_date_end')
            ->andWhere('contract.endDate < :contract_month_date_end')
            ->setParameter('company_id', $company_id)
            ->setParameter('contract_month_date_start', $contract_month_date_start)
            ->setParameter('contract_month_date_end', $contract_month_date_end);

        //..
    }
}

I feel like the second one is better (less duplicate code between the differents controllers using the repository). But I also feel like it gives too much responsibility to the Repository.

A: Symfony best practices  are not clear regarding your task, but IMHO the following statement could be mapped to your second option

Overall, this means you should aggressively decouple your business logic from the framework while, at the same time, aggressively coupling your controllers and routing to the framework in order to get the most out of it.

As you have already stated, the second option keeps the controllers thinner and moves the logic to the repository level, which is in terms of a Symfony way a totally valid approach.
This best practice statement adds some additional support for option 2

In Symfony applications, business logic is all the custom code you write for your app that's not specific to the framework (e.g. routing and controllers). Domain classes, Doctrine entities and regular PHP classes that are used as services are good examples of business logic.

If you need this formatting at different places around your application another approach could be to create a service class which you can inject into the Repositories where you need it.

A:
TL;DR: in your example, your formatting logic should ideally be
  handled in an intermediate layer.

Here are a few improvements:
First, do not get the repository from your controller. Instead, declare it as a service (for example, in your app/config/services.yml).
Also, you could abstract the access to your data (= your repository) using a new layer. The communication would be done like this:
Controller <=> Business layer <=> Data access.

*

*Controller: responsible for calling the correct methods of the business layer and handling responses (rendering HTML, returning JSON, etc.).

*Business layer: responsible for the logic of your app.

*Data access: responsible for querying your DB (for example) and getting the data without including any business logic. Can only be accessed by the business layer.

Using such an architecture will help you having a more scalable application without taking too long to implement it.
In your code, it would look like the following:
Your controller, responsible for "routing" the user's request to the correct service
class MyController extends Controller
{
    public function myAction()
    {
        // Accessing the contract manager, previously declared as a service in services.yml
        $contractManager = $this->get('manager.contract');
        $contracts = $contractManager->getMonthlyContracts($company);
    }
}

Your business layer, responsible for executing the logic:
// This class must be declared as a service in services.yml
class ContractManager {
    private $contractRepository;

    public function __construct(ContractRepository $contractRepository)
    {
        $this->contractRepository = $contractRepository;
    }

    public function getMonthlyContracts(Company $company)
    {
        // The business layer is responsible for the logic of fetching the data. Therefore, its methods are business-related (here "find the monthly contracts for company X", which is very specific).
        // It is its role to set the start and end dates, not the controller's
        $contracts = $this->contractRepository->findByCompany(
            $company,
            new \DateTime('first day of this month'),
            new \DateTime('last day of this month')
        );

        // Do some logic with the contracts if required...

        return $contracts;
    }
}

Your repository, responsible for accessing the data:
class ContractRepository extends EntityRepository
{
    // The repository handles basic access to data without any logic, hence the generic "findByCompany" method name
    public function findByCompany(Company $company, \DateTime $from, \DateTime $to)
    {
        $qb->select('contract')
            ->from('AppBundle:Contract', 'contract')
            ->where('contract.company = :company')
            ->andWhere('contract.startDate > :from')
            ->andWhere('contract.endDate < :to')
            ->setParameter('company', $company)
            ->setParameter('from', $from)
            ->setParameter('to', $to);

        //...
    }
}

Please have a look at the Symfony doc about how to declare a repository as a service in your services.yml.

A: I prefer to do this kind of job in the presentation layer, if you are using TWIG you should take a look at the date format filter or if it is an api you can work to the presentation layer with JMS serialization as example.
In this manner the business logic don't change and is not affected about change of the presentation logic
My two cents.


text:
Q: Multi-threading with WPF ui I'm not sure if this is possible, but I couldn't find anything when I searched about it.
I have a visual schedule made in WPF that loads and displays appointments. The problem is that it takes a while to load all the visuals and the program becomes unresponsive during that time.
Is it possible to load the appointment visuals and modify the schedule grid in a separate thread while leaving the main thread open for other things? Or possibly keep the schedule grid permanently in a second STA thread so it can do its own thing without interfering with the window?
edit:
Currently what I have:
    private static void FillWeek()
    {
        BindingOperations.EnableCollectionSynchronization(ObservableAppointments, _lockobject);
        for (int i = 1; i < 6; i++)
        {
            FillDay(Date.GetFirstDayOfWeek().AddDays(i).Date);
        }
    }
    private static ObservableCollection<AppointmentUIElement> ObservableAppointments = new ObservableCollection<AppointmentUIElement>();
    private static object _lockobject = new object();
    public static async Task FillDay(DateTime date)
    {
        ClearDay(date);
        Appointment[] Appointments;
        var date2 = date.AddDays(1);
        using (var db = new DataBaseEntities())
        {
            Appointments = (from Appointment a in db.GetDailyAppointments(2, date.Date) select a).ToArray();
        }
        await Task.Run(()=>
        {
            foreach (Appointment a in Appointments)
            {
                var b = new AppointmentUIElement(a, Grid);
                ObservableAppointments.Add(b);
            }
        });
    }
    private static void ObservableAppointments_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
    {
        if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Add)
        {
            var a = e.NewItems[0] as AppointmentUIElement;
            a.Display();
        }
    }
    private static void ClearDay(DateTime date)
    {
        var Queue = new Queue<AppointmentUIElement>(Grid.Children.OfType<AppointmentUIElement>().Where(a => a.Appointment.Start.DayOfWeek == date.DayOfWeek));
        while (Queue.Count > 0)
        {
            var x = Queue.Dequeue();
            Grid.Children.Remove(x);
            ObservableAppointments.Remove(x);
        }
        var Queue2 = new Queue<GridCell>(Grid.Children.OfType<GridCell>().Where(g => g.Date.Date == date));
        while (Queue2.Count > 0)
        {
            Queue2.Dequeue().AppointmentUIElements.RemoveAll(a => true);
        }
    }

AppointmentUIElement is derived from Border

A: Yes
Now the challenge of all this is that visual elements and bound ObservableCollections can only be modified by the UI thread without some additional work. Bound properties that are not collections do not require this.
So lets say you have the "appointment visuals" from the UI bound to an ObservableCollection that has you appointment data in it. What you can do is make your 'search appointments' function async and register your collection for thread synchronization as below. I'm leaving out anything related to INotifyPropertyChange for brevity.
  public ObservableCollection<Appointments> Appointments = new ObservableCollection<Appointments>();
  private static object _lockobject = new object();
  public async Task Load()
  {
        await Task.Run(() => { /*load stuff into the Appointments collection here */ });
        ///possibly more code to execute after the task is complete.
  }

  //in constructor or similar, this is REQUIRED because the collection is bound and must be synchronized for mulththreading operations
  BindingOperations.EnableCollectionSynchronization(YourCollection, _lockobject);

There is also a much nastier and not recommended way of modifying UI thread created visual elements.
 this.Dispatcher.Invoke(() => {/* do stuff with ui elements or bound things*/});

The gist of what happens is that you call load from the UI thread and when it hits the 'await task.run' it will work the contents of the task in a seperate thread while allowing the UI thread to continue responding to the user. Once the task completes it will then under the hood return to the ui thread to execute whatever else was under it in the load method.
If you forget the EnableCollectionSynchronization part then any attempts to add or remove items inside the task.run will throw an error complainging that you cannot change the contents of a collection in a different thread then the same one it was created with (almost same error as trying to modify a ui element directly).
Comment reply -> the problem with what your doing is here
  AppointmentUIElement(a,Grid)

What you really should be doing here is putting the Grid into a custom control that has a bound item template defined that binds to items from the ObservableAppointments which should actually be the appointment data, not UI elements. All of this should be happening through ViewModels on context. The way your doing it will ONLY work if there is just a single thread managing EVERYTHING, as soon as another thread gets involved it will all fall apart on you.

A:
Is it possible to load the appointment visuals and modify the schedule grid in a separate thread while leaving the main thread open for other things? Or possibly keep the schedule grid permanently in a second STA thread so it can do its own thing without interfering with the window?

You could load and display the schedule grid in a separate window that runs on a dedicated dispatcher thread. Please refer to this blog post for an example of how to launch a WPF window in a separate thread.
Keep in mind that an element created on the new thread won't be able to interact with an element created on the main thread though. So you can't simply load the schedule on another thread and then bring it back to the main thread. A visual element can only be accessed from the thread on which it was originally created on.


text:
Q: Why am I getting an unexpected token error in jQuery 1.4.4.min file? Why am I getting this error:
Uncaught SyntaxError: Unexpected token <
c.b.extend.globalEval                          jquery-1.4.4.min.js:32
c.extend.httpData                              jquery-1.4.4.min.js:144
c.extend.ajax.L.w.onreadystatechange           jquery-1.4.4.min.js:140

This error doesn't point me to a place in my JS that is triggering this issue. Just the jQuery min file.
How do I debug this and fix it ?
Edit1: Here are some screenshots of my call stack around this error. Still not sure though, which file has the syntax error that is being called by jQuery.

Edit 2:
Here are some of my AJAX calls:
$('form#project-ajax-form').submit(function(){
    if(compv.steps.selectedClient.id != null){
    $('input#project_client_id').val(compv.steps.selectedClient.id);
        console.debug("Project Client Value: " + $('input#project_client_id').val());
        return true;
    }
    console.debug("Project Client Value not found");
    compv.tools.clientError();
    return false;
});
$('#project-ajax-form')
        .bind("ajax:success", function(evt, data, status, xhr){
        compv.updateStepView('project', xhr);
});

$('#client-ajax-form')
    .bind("ajax:success", function(evt, data, status, xhr){
    console.log("Calling Step View");
    compv.updateStepView('client', xhr);
});

$('form#stage-ajax-form').submit(function(){
if(compv.steps.selectedProject.id != null){
$('input#stage_project_id').val(compv.steps.selectedProject.id);
    console.debug("Stage Project Value: " + $('input#stage_project_id').val());
    return true;
}
console.debug("Stage Project Value not found");
compv.tools.clientError();
return false;
});
$('#stage-ajax-form')
    .bind("ajax:success", function(evt, data, status, xhr){
    compv.updateStepView('stage', xhr);
});

$.ajaxSetup({
  beforeSend: function(xhr) {
    xhr.setRequestHeader("Accept", "text/javascript");
  }
});

$('.ajax-form')
.bind("ajax:success", function(evt, data, status, xhr){
  var $form = $(this);
    console.log("Form Success: %s", $(this).attr('id'));

  // Reset fields and any validation errors, so form can be used again, but leave hidden_field values intact.
  $form.find('textarea,input[type="text"],input[type="file"]').val("");
  $form.find('div.validation-error').empty();
})
.bind("ajax:failure", function(evt, xhr, status, error){
  var $form = $(this),
      errors,
      errorText;
    console.log("Form Failure: %s", $(this).attr('id'));

  try {
    // Populate errorText with the comment errors
    errors = $.parseJSON(xhr.responseText);
  } catch(err) {
    // If the responseText is not valid JSON (like if a 500 exception was thrown), populate errors with a generic error message.
    console.error("Server Error for Form: %s", $(this).attr('id'));
    errors = {"Server Error": "Please reload the page and try again"};
  }

  // Build an unordered list from the list of errors
  errorText = "There were errors: \n
";

  for ( error in errors ) {
    errorText += "
" + error + ': ' + errors[error] + "
 ";
  }

  errorText += "
";

  // Insert error list into form
  var errorDiv = $form.find("div.validation-error");
  errorDiv.html(errorText);
  errorDiv.show(300);
});

A: The callstack indicates that jQuery is calling eval from the response to an AJAX request.
You're calling getScript for a Javascript file with a syntax error.

To answer your stated question, you can debug this by switching to the debug version of jQuery (not .min) and using a debugger, such as Firebug or Chrome's Developer Tools.

A: This was answered in another question: Uncaught SyntaxError: Unexpected Token - jQuery - Help!


text:
Q: Paypal shipping calculator not overideing I am trying to get Paypal's shipping rate system working i have it set up like so:

*

*All State
0.01 - 5 = $5
5.01 - 10 = $10
10.01 - 15 = $15
15.01 - 20 = $20

and then when I go and place a test order it goes with the default i sent at the start of the trans of $50 shipping. It also looks like its trying to call for the call back and in the sand box it does ask for the call back but does not take it. Item weigh is 8.
Here is a copy of the call to paypal to start the trans:
{
    "amt": "339.99",
    "itemAmt": "289.99",
    "maxAmt": "339.99",
    "l_name0": "2.0T TSI TFSI Oil Cooler Kit - Stainless Steel",
    "L_NUMBER0": "226106227",
    "L_ITEMWEIGHTVALUE0": "8",
    "l_amt0": "289.99",
    "l_qty0": "1",
    "callback": "https://www.bahnbrenner.com/media/php/userman/paypal-callback.php?reason=callback",
    "callbackTimeout": "6",
    "l_shippingOptionIsDefault0": "true",
    "l_shippingOptionName0": "Shipping",
    "l_shippingOptionLabel0": "Ground",
    "l_shippingOptionAmount0": "50.00",
    "shippingAmt": "50.00",
    "RETURNURL": "https://www.bahnbrenner.com/media/php/paypal.php?reason=return",
    "CANCELURL": "https://www.bahnbrenner.com/media/php/cart.php?reason=cancel"
}

Is there an option I am missing that tells paypal to deal with the shipping?
What am I missing if i set just the shipping price and nothing else for the shipping it sets it and never resets it once in paypal.
Thank you very much for the help.

A: Please follow below steps to update one configuration in your PayPal account.

*

*Login merchant PayPal account at www.paypal.com

*Open https://www.paypal.com/cgi-bin/customerprofileweb?cmd=_profile-shipping page directly, then click edit button.

*Enable " Allow transaction-based shipping settings to override profile settings (Optional)."

*Click "Save Changes" button.


text:
Q: Do not apply requestFocus on EditText that is inside CarouselView I have a EditText in the RecyclerView item that, once the item is selected, I want to display the keyboard and Focus on the EditText, but I do not do anything.
I use the CarouselView library, which is the same as the RecyclerView.
In Activity:
listStudent.setOnItemSelectedListener(new CarouselView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(CarouselView carouselView, int position, int adapterPosition, RecyclerView.Adapter adapter) {

                try {
                      View view = listStudent.getLayoutManager().findViewByPosition(listStudent.getCurrentAdapterPosition());
                      final EditText ed = ButterKnife.findById(view, R.id.edScore);
                      ed.requestFocus();

                      ed.post(new Runnable() {
                           @Override
                           public void run() {
                              InputMethodManager imm = (InputMethodManager)
                              AppController.Context.getSystemService(Context.INPUT_METHOD_SERVICE);
                              imm.showSoftInput(ed, InputMethodManager.SHOW_IMPLICIT);
                      }});

                 } catch (Exception ex) {}
            }

            @Override
            public void onItemDeselected(CarouselView carouselView, int position, int adapterPosition, RecyclerView.Adapter adapter) {

            }
     });

In XML Item Child
<EditText
            android:id="@+id/edScore"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:background="@xml/layout_border_color_primary"
            android:digits="0123456789."
            android:focusable="true"
            android:focusableInTouchMode="true"
            android:gravity="center"
            android:lines="1"
            android:maxLength="5"
            />

A: just add inside your try block
ed.setFocusableInTouchMode(true);


text:
Q: Can node.js replace my javascript timer? I posted here a short while ago today. I had asked whether I could compile JavaScript using jscript.net.
I was told (quite rightly) that jscript.net was old technology and not unsupported) and that I should look at new technology like node.js.
I have taken a look at node.js.  I understand it is a standalone web server that can sit side-by-side with IIS.
I have developed an asp.net application.  It uses a lot of jquery/JavaScript with ajax calls from the client.
I am using a JavaScript timer that calls a url to my generic handler (asmx)to return a image in bytes.
I wanted to see if I could compile JavaScript using jscript.net (hence the original question) which would:
Hide my url address call and perhaps improve performance of my JavaScript.
I have looked at sample code for node.js but could not find anything that would 'replace' my javascript timer.
I admit my javascript/client skills are not that great.
But firstly, is this possible to do with node.js?
I am ready to learn...

A:
I have taken a look at node.js. I understand it is a standalone web server that can sit side-by-side with IIS.

Node.js is a platform on which you can execute JavaScript (generally on a server). You could certainly use it side-by-side with IIS.

Hide my url address call and perhaps improve performance of my JavaScript.

You can never hide your request details, there are many many ways to view request details. I would suggest changing your approach if you are security conscious.

I have looked at sample code for node.js but could not find anything that would 'replace' my javascript timer.

As the Javascript timer is executed client side, you could not use node.js to replace it. You could use node.js to process the timed request that the client sends, like you would do with your .NET handler.


text:
Q: Create a event (like on tap) for a Custom widget I am creating my custom widget in which I am using RaisedButton
I want to export onTap event from RaisedButton to parent widget. How can I do that?

A: Create a custom widget:
class MyCustomWidget extends StatelessWidget {
  final String text;
  final VoidCallback? onTap;

  const MyCustomWidget(this.text, {
    Key? key,
    this.onTap,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return ElevatedButton(
      onPressed: onTap,
      child: Text(text),
    );
  }
}

Usage:
MyCustomWidget(
  'My button',
  onTap: () {},
)