text:
Q: Moving messages in DLQ if message processing Fails I have a standalone program to send message in IBM MQ. I am able to put message in Queue successfully.
JmsFactoryFactory ff = JmsFactoryFactory.getInstance(WMQConstants.WMQ_PROVIDER);
JmsConnectionFactory cf = ff.createConnectionFactory();

// Set the properties
cf.setStringProperty(WMQConstants.WMQ_HOST_NAME, HOST);
cf.setIntProperty(WMQConstants.WMQ_PORT, PORT);
cf.setStringProperty(WMQConstants.WMQ_CHANNEL, CHANNEL);
cf.setIntProperty(WMQConstants.WMQ_CONNECTION_MODE, WMQConstants.WMQ_CM_CLIENT);
cf.setStringProperty(WMQConstants.WMQ_QUEUE_MANAGER, QMGR);
cf.setStringProperty(WMQConstants.WMQ_APPLICATIONNAME, "JmsPutGet (JMS)");
cf.setBooleanProperty(WMQConstants.USER_AUTHENTICATION_MQCSP, true);
cf.setStringProperty(WMQConstants.USERID, APP_USER);
cf.setStringProperty(WMQConstants.PASSWORD, APP_PASSWORD);

// Create JMS objects
context = cf.createContext();
destination = context.createQueue("queue:///" + QUEUE_NAME);

long uniqueNumber = System.currentTimeMillis() % 1000;
TextMessage message = context.createTextMessage("Your lucky number today is " + uniqueNumber);

producer = context.createProducer();
producer.send(destination, message);

I have the following MDB deployed in JBoss and i reads the message from the Queue. I am explicitly throwing throw new RuntimeException("-----------1111111111--------------"); so that message processing fails, and the message is moved to DLQ (dead letter queue). In my case exception happens and the message is getting re-delivered multiple times, and calling onMessage of EJB again and again.
@MessageDriven(activationConfig = {
@ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue"),
@ActivationConfigProperty(propertyName = "useJNDI", propertyValue = "false"),
@ActivationConfigProperty(propertyName = "hostName", propertyValue = "${websphere.hostName}"),
@ActivationConfigProperty(propertyName = "username", propertyValue = "${websphere.username}"),
@ActivationConfigProperty(propertyName = "password", propertyValue = "${websphere.password}"),
@ActivationConfigProperty(propertyName = "port", propertyValue = "${websphere.port}"),
@ActivationConfigProperty(propertyName = "channel", propertyValue = "${websphere.channel}"),
@ActivationConfigProperty(propertyName = "queueManager", propertyValue = "${websphere.queueManager}"),
@ActivationConfigProperty(propertyName = "destination", propertyValue = "${websphere.queueName}"),
@ActivationConfigProperty(propertyName = "transportType", propertyValue = "CLIENT"),
@ActivationConfigProperty(propertyName = "acknowledgeMode", propertyValue = "Auto-acknowledge") })
@ResourceAdapter(value = "wmq.jmsra.rar")
@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)

public class TestMDB implements MessageListener {

@Override
public void onMessage(Message message) {

if (message instanceof TextMessage) {
    try {
        String mqmsg = ((TextMessage) message).getText();
        System.out.println("MSG RECEIVED: " + mqmsg);
        if (uploadFile(mqmsg)) {
            System.out.println("MSG WRITE TO FILE ");
        }

        message.setJMSExpiration(1000);

        throw new RuntimeException("-----------1111111111--------------");

    } catch (JMSException e) {
        throw new IllegalArgumentException(e);
    }
}
}
}

I tried to find a way by setting re-try count, but failing to do so.
What I am trying to achieve is that is it possible to set a parameter so that after lets say 2 tries, it is moved to DLQ ?
I have been able to achieve this result for JBoss in built queue, but don't know how and where to set parameter for IBM MQ.
I am making use of following link to run my IBM MQ as docker image: https://developer.ibm.com/tutorials/mq-connect-app-queue-manager-containers/
I have tried the following by not able to make it work:
https://www.ibm.com/support/knowledgecenter/SSFKSJ_7.5.0/com.ibm.mq.dev.doc/q031670_.htm
https://www.ibm.com/support/pages/how-specify-expiration-mq-message-and-when-expired-messages-are-removed-queue
https://www.ibm.com/support/knowledgecenter/en/SSWMAJ_2.0.0/com.ibm.ism.doc/Developing/devjms_poisonmessages.html
More details of my sender program is here: https://developer.ibm.com/series/badge-ibm-mq-developer-essentials/


text:
Q: Android - AJAX request doesn't work when APK is signed I am using eclipse to build my phonegap application and I have configured all the setting by referring Google and you tube. When I build my application in eclipse, by default its generate the apk in bin/res folder. For testing purpose, I have install that apk on my devices and its working well!! Even its working fine in eclipse emulator.
But when I generate the Keystore and sign the apk then the ajax request is not working properly. It executed the error as (jqXHR.status === 0). I can't figure out what is going wrong??

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can zip4j be used to extract Tar files? In an application we use the zip4j library to decompress zip files.
File toBeExtractedFile = new File("valid/path/to/File");
ZipFile zipFile = new ZipFile(toBeExtractedFile);
zipFile.setFileNameCharset(StandardCharsets.UTF_8.name);
zipFile.extractAll("valid/path")

With .zip files this code works perfectly fine. But when done with a .tar file, this wil throw a new ZipException("zip headers not found. probably not a zip file");
Can the zip4j library extract TAR files when given additional info or parameters or do i have to resort to using something else like a TarArchiveInputstream?

A: No, ZIP and TAR are two different archive formats. You can use Apache Commons Compress which supports TAR format.


text:
Q: Remove Duplicates from a list of namedtuples I often gets confused with list and tuples due to my Javascript background, so please excuse me.
I have a list of namedtuples something like this:
[AdminInfo(username='abc', is_admin=False), AdminInfo(username='cde', is_admin=False), AdminInfo(username='efg', is_admin=False), AdminInfo(username='hij', is_admin=True), AdminInfo(username='jkl', is_admin=False), AdminInfo(username='abc', is_admin=False), AdminInfo(username='xyz', is_admin=False)]

I am trying to remove the duplicates from here. For simple list, I can do
a = list(set(<var>))

But in this case, it seems we can't convert to set. If I try, it fails with error:
TypeError: unhashable type: 'AdminInfo'

Can anyone please help me removing duplicates from above list.

A: Extract the names from each class an check if a list of the checked already contains it.
class AdminInfo:
    name = None

    def is_admin(self):
        return self.val_is_admin

    def __init__(self, username='Undefined', is_admin=False):
        self.val_is_admin = is_admin
        self.name = username

ai_list = [AdminInfo(username='abc', is_admin=False), AdminInfo(username='cde', is_admin=False),
           AdminInfo(username='efg', is_admin=False), AdminInfo(username='hij', is_admin=True),
           AdminInfo(username='jkl', is_admin=False), AdminInfo(username='abc', is_admin=False),
           AdminInfo(username='xyz', is_admin=False)]

if __name__ == '__main__':
    names = []
    n_list = []
    for i in ai_list:
        if i.name not in names:
            names.append(i.name)
            n_list.append(i)
    print(names)

A: Here the snippet you need:
import numpy
class AdminInfo:
    def __init__(self, **kwargs):
        [setattr(self, key, kwargs[key]) for key in kwargs]

def remove_duplicated(l):
    numpy.array(l)[numpy.unique(numpy.array([user.username for user in l]), return_index=True)[1]].tolist()

if __name__ == '__main__':
    start_list = [
        AdminInfo(username='abc', is_admin=False),
        AdminInfo(username='cde', is_admin=False),
        AdminInfo(username='efg', is_admin=False),
        AdminInfo(username='hij', is_admin=True),
        AdminInfo(username='jkl', is_admin=False),
        AdminInfo(username='abc', is_admin=False),
        AdminInfo(username='xyz', is_admin=False)
    ]
    final_list = remove_duplicated(start_list)

    assert len(start_list) == len(final_list) + 1
    assert [user.username for user in start_list].count("abc") == 2
    assert [user.username for user in final_list].count("abc") == 1

Using numpy arrays, this solution is much more adapted for large amont of datas.

A: I think you're confused because you want a list of unique AdminInfo objects, based on the value of the username property. In your code, you have created a list of eight unique AdminInfo objects, two of which share the same name.
This code should give you what I think you're looking for. It will return a list of the last instance of each AdminInfo object with a given username. It exploits the fact that if you add a duplicate key to a dictionary, the new value will overwrite the old value.
ai_list = [AdminInfo(username='abc', is_admin=False), AdminInfo(username='cde', is_admin=False), AdminInfo(username='efg', is_admin=False), AdminInfo(username='hij', is_admin=True), AdminInfo(username='jkl', is_admin=False), AdminInfo(username='abc', is_admin=False), AdminInfo(username='xyz', is_admin=False)]
ai_dict = dict((item.name, item) for item in ai_list)
ai_list = list(ai_dict.values())


text:
Q: Why is first two elements inside flexbox acting different to others with same css The first two elements inside my flexbox container containing my posts from wordpress float around 10px higher than the rest. They all have the same css. I'm using PHP to get the posts from wordpress. Its only on the top row that it does this. As you can see from the photo the same template and post format is used lower on the page and it does not have this issue. Please help.
I have already tried commenting parts of the code like the read more button or the icons to see if maybe margins or padding inside the post container is doing it but its not. I've tried setting a height on the flexbox container to 930px the exact height to stop it floating - that hasnt worked. This is after setting no margins on the posts but that still hasn't worked - they were previously 5px.
This is the html template for each post inside the post loop that has the standard post format. Each post: standard and image follow the css with the 'standard' in the class names and the quote and video post format follow the classes with 'quote' in them.
 <article id="grid-post-<?php the_ID(); ?> " <?php post_class(); ?>>

<?php the_title(); ?>

<?php the_time('d/m/y'); ?>

    <a href="<?php the_permalink(); ?>" class="btn"><button><?php _e('Read More');?></button>

HERE IS THE POST FORMAT TEMPLATE FOR THE VIDEO AND QUOTE POSTS:
 <article id="grid-post-<?php the_ID(); ?> " <?php post_class(); ?>>

<?php the_title(); ?>

<?php the_time('d/m/y'); ?>

    <a href="<?php the_permalink(); ?>" class="btn"><button><?php _e('Read More');?></button>

HERE IS INDEX PAGE

<?php

if(have_posts() ):

   echo '
';

  while( have_posts() ): the_post();
     get_template_part('template-parts/gridcontent', get_post_format()
);

  endwhile;

  echo '
';

endif;

?>

HERE IS THE CSS:
 .grid-whole-container{
     display: inline;
     flex-wrap: wrap;
     flex-direction: row;
     width: 100%;

      }

 .grid-standard-post-container {
   width: 32%;
   flex: 100%;
   height: 300px;
   -webkit-box-shadow: 10px 10px 19px -5px rgba(0,0,0,0.75);
   -moz-box-shadow: 10px 10px 19px -5px rgba(0,0,0,0.75);
   box-shadow: 10px 10px 19px -5px rgba(0,0,0,0.75);
   float: left;

 }

 .grid-standard-post-container:hover {

 }

 .grid-standard-title-container {
   width: 80%;
   margin-left: auto;
   margin-right: auto;

 }

 .grid-standard-title {
   font-family: coolvetica;
   text-transform: uppercase;
   color: white;
   text-align: center;
   letter-spacing: 3px;
   text-shadow: 2.5px 3px black;
   font-size: 27px;
   position: relative;
   top: 80px;

 }

 .grid-standard-date-container {
   width: 30%;
   margin-left: auto;
   margin-right: auto;

 }

 .grid-standard-date {
   letter-spacing: 6px;
   color: black;
   font-family: coolvetica;
   font-size: 13px;
   text-align: center;
   position: relative;
   top: 60px;
 }

 .grid-button button {
   width: 50%;
   margin-left: 25%;
   margin-right: 25%;
   position: relative;
   top: 90px;
   background: transparent;
     background-repeat:no-repeat;
     border: none;
     cursor:pointer;
     overflow: hidden;
     outline:none;
   font-family: coolvetica;
   text-transform: uppercase;
   color: white;
   letter-spacing: 7px;

 }

 .grid-load-more {
   margin-top: 100px;
 }

 /* INDEX GRID LAYOUT - QUOTE                  ========================================================================     ============================= */

 .grid-quote-post-container {
   width: 32%;
   flex: 100%;
   height: 300px;
   -webkit-box-shadow: 10px 10px 19px -5px rgba(0,0,0,0.75);
   -moz-box-shadow: 10px 10px 19px -5px rgba(0,0,0,0.75);
   box-shadow: 10px 10px 19px -5px rgba(0,0,0,0.75);
   float: left;
   background-color: #aecfd7;
 }

 .grid-quote-icon-container {
   color: white;
   font-size: 60px;
   text-align: center;
   width: 30%;
   margin-left: auto;
   margin-right: auto;
   margin-top: 30px;
  margin-bottom: -70px;
 }

Expected that these divs would all act the same as they all have the same css but top row floats up. Please help.
This is what it looks like.The first two should not float up like that


text:
Q: What is the importance of higher generations of particles in cosmology? Although there are 6 types of quarks and 3 leptons according to the standard model, most of them are unstable and rapidly decay to the lighter, first generation analogues. Only the up and down quarks and the electron make up a substantial fraction of the universe.
If those heavier analogues did not exist, would the universe be much different from how it is right now? Would it affect, for instance, the life cycle of stars or the abundance of elements in the universe? What is the importance of higher generations of particles in cosmology?

A: From [1]: "Nature is very good at blowing up stars. We [theoretical physicists] are not." That's a reference to the fact that we still don't completely understand why core-collapse supernovae explode. We do know that most ($\sim$ 99%) of the radiated energy from a core-collapse supernova is in the form of neutrinos [2], and we do know that this includes significant contributions from all flavors (generations) of neutrinos [2][3]. The core-collapse environment is so extreme that neutrino-neutrino interactions are significant [4]. According to [5], the core-collapse environment is the only known environment in which significant neutrino-neutrino interactions can be observed.
Altogether, this raises the possibility that neutrinos — and the fact they come in multiple flavors — might have a significant influence on core-collapse supernova explosions. So this might provide an interesting answer to your question, insofar as the existence and features of core-collapse supernovae are important for cosmology. The Standard Model of particle physics is not mathematically consistent unless each generation is complete — which means that if multiple generations of neutrinos exist, then multiple generations of the other leptons and quarks are also required.$^\dagger$
As far as I know, the the relevance of multiple neutrino flavors to the supernova explosion mechanism is still an open question. One recent study [6] says this about the role of multiple neutrino generations:

Neutrino oscillations [which require multiple flavors] do impact the dynamics of the simulations [of core-collapse supernovae], but do not cause the explosion to occur.

Further research may tell us how significant (or not) this "impact" really is.

Footnote:
$^\dagger$ The details of the connection between generations and neutrino flavors might turn out to be more subtle, because neutrinos are massless in the original (renormalizable) Standard Model. Explaining the observed neutrino masses requires something beyond that original model, which could conceivably change the simple "one neutrino flavor per generation" picture. This, like the details of how core-collapse supernova work, is still an active area of research.

References:
[1] Slide 22 in "The Neutrino Mechanism of Core-Collapse Supernovae" (https://www.astro.princeton.edu/~burrows/classes/541/NeutrinoMechv2.pdf)
[2] Page 127 in "Introduction to neutrino physics" (https://cds.cern.ch/record/677618/files/p115.pdf)
[3] Page 5 in "Supernova Signatures of Neutrino Mass Ordering" (https://dukespace.lib.duke.edu/dspace/bitstream/handle/10161/15940/sn_mo.pdf)
[4] Page 7 in "Supernova Neutrinos: Theory" (https://arxiv.org/abs/1604.07332)
[5] First page in "Theory and Phenomenology of Supernova Neutrinos" (https://aip.scitation.org/doi/pdf/10.1063/1.4915560)
[6] Last slide in "The Effects of Neutrino Oscillations on Core-Collapse Supernova Explosions" (https://indico.ectstar.eu/event/47/contributions/979/attachments/705/926/SNCrossroads_Stapleford.pdf), dated 2019


text:
Q: Mysterious side-effect of calling printf or not in C before calling an asm function? This program has to calculate pi with accuracy provided by the user.
The calculate_pi () function is written in NASM.
Can someone explain to me why if this line is commented:
//printf("accuracy: %.15f\n", precision);       //<- This line

The program does not work correctly. Send strange numbers to the calcuta_pi() function?   If this line is commented, a very small value is sent to the function and the program runs infinitely.
But if it is not a commented program works correctly.
#include <stdio.h>
#include <math.h>

extern double calculate_pi(double precision); /* external function declaration */

double calculate_pi(double precision);   /* function prototype */

int main()
{
double precision = 1;

printf("A program that calculates pi, with accuracy provided by the user\n");
printf("Give me accuracy\n");

while(1)
{
    if (scanf("%lf", &precision) != 1)
    {
        printf("reading error\n");

        fseek(stdin,0,SEEK_END);

        continue;
    }
    if(precision<0)
        precision = fabs(precision);

    //printf("accuracy: %.15f\n", precision);       //<- This line
    printf("pi: %.15f\n", calculate_pi(precision));
}

return 0;
}

This is my assembly code:
;   arctg(1)=a
;   tg(arctg(1))=tg(a)
;   atan(x) = x - x^3/3 + x^5/5 - x^7/7 + x^9/9..
;   PI/4 = atan(1) = 1 - 1/3 + 1/5 - 1/7 + 1/9...
;   PI = (4/1) - (4/3) + (4/5) - (4/7) + (4/9) - (4/11) + (4/13) - (4/15) ...

section .text use32

global  _calculate_pi

_calculate_pi:

%idefine    a   [ebp+12]

;ramka stosu
push    ebp
mov ebp, esp

;ustawianie zmiennych
fld qword [const_wynik]
fstp qword [wynik]

fld qword [const_licznik]
fstp qword [licznik]

fld qword [const_mianownik]
fstp qword [mianownik]

.loop:
finit ; inicjalizacja stosu FPU

fld qword [licznik]         ;licznik na stos
fld qword [mianownik]       ;mianownik na stos
fdiv                        ;wynik dzielenia st1/st0
fadd qword [wynik]          ;st0 = wynik dzielenia + [wynik]

fstp qword [wynik]          ;wywalamy z st0 do [wynik]

                            ;zmieniamy mianownik + 2
fld qword [mianownik]       ;mianownik na stos
fadd qword [zwiekszmian]    ;st0 = mianownik + 2
fstp qword [mianownik]          ;wywalamy z st0 do [mianownik]

                            ;zmieniamy licznik *(-1)
fld qword [licznik]         ;licznik na stos
fchs                        ;st0 = -st0 = -licznik
fstp qword [licznik]        ;wywalamy z st0 do [licznik]

                        ;sprawdzanie dokladnosci
fld qword[wynik]        ;wynik na stos
fldpi                   ;pi na stos
fsub                    ;st0 = wynik-pi = st1 - st0
fabs                    ;st0 = |wynik-pi|

fld qword a             ;st0 = zadana dokladnosc

                            ;(Unordered Compare ST(0) to ST(i) and set CPU flags and Pop ST(0))
                            ;Przyrostek p oznacza obniżenie stosu rejestrów koprocesora, przyrostek i oznacza zapisywanie wyników bezpośrednio do flag procesora a nie flag koprocesora
fucomip st0, st1            ;porownanie z dokladnoscia  if(zadana dokladnosc > uzyskana)

jb    .loop   ;only the C0 bit (CF flag) would be set if no error

fld qword [wynik]

        ;zwraca to co w st0
leave   ; LEAVE = mov esp, ebp / pop ebp
ret

section .data:

wynik       dq 4.0
licznik     dq -4.0
mianownik   dq 3.0
zwiekszmian dq 2.0

const_wynik     dq 4.0
const_licznik   dq -4.0
const_mianownik dq 3.0

Sample output:

I'm using:

*

*NASM version 2.11.06 compiled on Oct 20 2014

*gcc (MinGW.org GCC-6.3.0-1) 6.3.0

Compilation and assembler commands:
nasm -o pi.o -f coff pi.asm
gcc pi.o pi_interface.c -o projekt.exe -Wall -Wextra

A: I think you're accessing the function arg incorrectly, offset by 4 bytes.  When you make a stack frame, the first arg is at [ebp+8], but you're loading from [ebp+12].  (This applies to all calling conventions that pass args on the stack.  I think 32-bit mingw does that for double by default.)
This means the double value you're using as precision has its high 4 bytes from whatever the caller happened to leave on the stack above the 8-byte arg slot.   This explains why changes in the caller affect the behaviour of your function, and why you can get an infinite loop: if the bytes you load happen to represent a very small double, your loop never exits.
The low 4 bytes (32 least-significant bits of the mantissa) come from the top 4 bytes of what the caller passed.
You would have easily found this with a debugger by looking at registers and noticing the value you load wasn't the value the caller passed.  Also, @Ped7g's suggestion to just try returning precision in a trivial asm function would have found the problem, too.


text:
Q: Storing access token object in rails 4 Hi all currently I am facing an issue while storing object of OAuth::AccessToken. First let me describe the situation.
I am working on rails 4 application and I am consuming / using API of another site say example.com, which uses 3-legged oauth authorization (same as twitter). To achieve this functionality I have used this link and implemented the same.
Now I am able to open communication channel between the example.com and my application also able use their API's.
Here is my sample implementation
Create consumer
consumer = OAuth::Consumer.new API_KEY,
                               API_SECRET,
                               {
                                 site: SITE_URL,
                                 header: { ACCEPT_HEADERS },
                                 http_method: :get,
                                 request_token_url: request_token_uri,
                                 access_token_url: access_token_uri,
                                 authorize_url: authorizerequest_token_uri
                               }

Fetching request token
request_token = consumer.get_request_token({}, CALLBACK_URL)

Goto to the authorize url and get the access token verifier'
request_token.authorize_url
verifier = gets.chomp

Fetch access tokene
access_token = request_token.get_access_token(oauth_verifier: verifier)

Now I am using this access_token (Object of OAuth::AccessToken) throughout the application. (For making get, post API calls). As I have to use in the application I have stored this object into the session.
session[:access_token] = access_token

But sometimes I am getting the cookie overflow error. So I have a following queries.

*

*What is the good way to store this object? (other than DB).

*Should I have to implement middleware?

*Or is there any other way to achieve same type of functionality.

A: I got the same type of problem. I have stored access token in database, (I am using mysql database). For this, I have used Marshal class of ruby.
From the doc

The marshaling library converts collections of Ruby objects into a
  byte stream, allowing them to be stored outside the currently active
  script. This data may subsequently be read and the original objects
  reconstituted.

Here is my sample code for storing the access token
access_token = request_token.get_access_token(oauth_verifier: verifier)
encrypt_access_token = Marshal.dump(access_token)
AccessTokenUser.create(user_id: 1, access_token: encrypt_access_token)

Retrieve stored acceess_token
decrypt_access_token = Marshal.load(access_token)

Then you can use this decrypted access token for making API call.

A: You can try a different session storage mechanism, for example memcached or redis (on the server). This may allow for a larger session. However, this is just "implementing a different type of database".
If you were brave or foolish, you could also try compressing the data or storing it directly in an encrypted cookie, or splitting into multiple chunks and storing in separate cookies, but all these are hacks and the best answer is to implement a db backend or upgrade your session storage. :)


text:
Q: wordpress advanced custom fields google map api key
I have a problem with loading google map with the Advanced Custom Field plugin. I make everything like in the instruction on the plugin page here https://www.advancedcustomfields.com/resources/google-map.
I add google-map field in ACF, but on the page where it should be it appears for a second, and then disappears with the     inscription "Oops! Something went wrong. This page didn't load Google Maps correctly. See the JavaScript console for technical details." (see the screenshot). Console says that I need to set the Google API key. I guess I also need to modify some strings in .js file from the ACF instruction, but I don't know which ones. May be someone could help.
Thank you in advance.
screenshot

A: ACF updated the Google Map documentation
You first have to get a Maps API key and make sure you activate the following APIs :

*

*Maps JavaScript API

*Geocoding API

*Places API

Then register the API key in your functions.php
If using ACF free
function my_acf_google_map_api( $api ){
    $api['key'] = 'xxx';
    return $api;
}
add_filter('acf/fields/google_map/api', 'my_acf_google_map_api');

If using ACF pro
function my_acf_init() {
    acf_update_setting('google_api_key', 'xxx');
}

add_action('acf/init', 'my_acf_init');

In my case I had to delete & recreate the field so that it saves correctly.

A: A solution could be editing the functions.php in your template
//TODO: fix api key for advanced custom field
add_action('acf/fields/google_map/api', function($api){
$api['key'] = '<YOUR_API_KEY>';
return $api;
});

or you can check my article for a complete solution

A: add this line in your script..replace with your key..
<script src="javascripts/jquery.js"></script>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=YOUR-API-KEY"></script>
<script type="text/javascript" src="javascripts/jquery.googlemap.js"></script>

A: I have found a couple of different solutions for this issue, but before starting to explain what to do let me remember to you to get a google maps api key.
I followed these instructions because I'm using Listify theme, but I'm pretty sure they can help you regardless the theme you have.
Here my solutions:
frontend
Somewhere (I guess in your functions.php or in your-awesome-widget.php) you should have a line like these
wp_enqueue_script( 'googlemaps_api' );
or
wp_enqueue_script( 'googlemaps' );
the solution I've found is add the key in the script registration before enqueuing it, in this way
wp_register_script('googlemaps', 'http://maps.googleapis.com/maps/api/js?key='.$YOUR_API_KEY, false, '3');

wp_enqueue_script('googlemaps');

Backend
This one is quick and totally dirty because I've read that ACF support is already working on the official solution, so, for me, is not a problem if it will be erased by a plugin update.
Open those two files:

*

*advanced-custom-fields/js/input.min.js

*advanced-custom-fields/js/input.js (in theory if you are using the .min version this one is useless)
This piece of code is repeated twice in each file:
google.load('maps', '3', { other_params: $.param(self.api), callback: function(){ ...
change those two occurencies adding the key as querystring, in this way
other_params: $.param(i.api) + 'key=YOUR_API_KEY', callback ...
Et voilá! It should work.
The official page about the topic is here
I hope to have been helpful!

A: With the current version (4.4) of ACF, you can find functions.php in the template you are using and add this to the end of the code:
function my_acf_google_map_api( $api ){
    $api['key'] = 'YOUR_API_KEY';
    return $api;
}
add_filter('acf/fields/google_map/api', 'my_acf_google_map_api');

Change 'YOUR_API_KEY' to your API KEY generated from Google.


text:
Q: Array of reference (or pointer) to labels in c# Say I have a form with a long bunch of temperature readouts, so in the designer:
this.lblTemperatureDevice01 = new System.Windows.Forms.Label();
this.lblTemperatureDevice02 = new System.Windows.Forms.Label();
this.lblTemperatureDevice03 = new System.Windows.Forms.Label();
// ...
this.lblTemperatureDevice50 = new System.Windows.Forms.Label();

In the main form code, how do I add the labels to an array so that I can update the labels using a loop in a timer event eg:
private void tmrUpdateLabels_Tick(object sender, EventArgs e)
{
    // Disable timer
    tmrUpdateLabels.Enabled = false;
    if (m_bExiting)
        return;

    // Update temperatures (if device has returned a reading)
    for (int device = 0; device < MAX_DEVICES; device++)
    {
        if (m_aHasNewReading[device])
        {
            m_aHasNewReading[device] = false;
            labels[device].Text = m_aTemperature[device].ToString();
        }
    }

    // Restart timer
    tmrUpdateLabels.Enabled = true;
}

How do I create the labels[MAX_DEVICES] array? Must I use:
private Label[] labels = new Label[MAX_DEVICES];

or is there a way to get a reference (or pointer) to the existing label(s) without creating new labels? Coming from a C++ background where I might have simply stored the address of each label in an array.

A: you can take all labels from Controls collection of the form
private Label[] labels;
.ctor
{
    InitializeComponent();
    labels = this.Controls.OfType<Label>()
            .Where(lbl => lbl.Name.StartsWith("lblTemperatureDevice"))
            .OrderBy(lbl => int.Parse(lbl.Name.Replace("lblTemperatureDevice","")))
            .ToArray();
}

A: Create just two of these labels with the designer.
See what the designer produced.
Create a loop which creates an array of labels in your program, just after InitializeComponents();
Throw all the code from the desgner (for these labels) away.


text:
Q: Laravel Passing Data From One View to Another View I am thinking of making a landing page from the home page, which will direct the guest to the register page. I thought of making two forms for sending data and two submit buttons in them, let's say reader and writer and according to the button they use to go to the register form page, I want to pass the profession string from the button in the landing page and then, place it into the register form in /auth/register.
    {!! Form::open(array('url' => '/auth/register', 'profession' => 'writer')) !!}

    {!! Form::submit('Writer', array('class' => 'btn btn-warning')) !!}

    {!! Form::close() !!}

    {!! Form::open(array('url' => '/auth/register', 'profession' => 'reader')) !!}

    {!! Form::submit('Reader', array('class' => 'btn btn-default')) !!}

    {!! Form::close() !!}

It is not directing me to the page app.com/auth/register. But it works when I directly type the link.
What I thought was using $profession in /auth/register/ and access the value and use it as a hidden field in the registeration form.
(using laravel 5.1)

Edit:
In view source:
    <form method="POST" action="http://app.com/auth/register" accept-charset="UTF-8" profession="writer"><input name="_token" type="hidden" value="dZXQsNI1BGQ39JjDLFUEkSQzL5bTNwe8o3rpiSQL">

    <input class="btn btn-warning" type="submit" value="Writer">

    </form>

    <form method="POST" action="http://app.com/auth/register" accept-charset="UTF-8" profession="reader"><input name="_token" type="hidden" value="dZXQsNI1BGQ39JjDLFUEkSQzL5bTNwe8o3rpiSQL">

    <input class="btn btn-default" type="submit" value="Reader">

    </form>

Edit 2:
    {!! Form::open(array('url' => '/auth/register', 'profession' => 'writer')) !!}

    {!! link_to('/auth/register', 'Writer', array('class' => 'btn btn-default')) !!}

    {!! Form::close() !!}

I tried this instead. At least, now it is directing the page but I still can't access the data value of profession

Edit 3:
Routes:
Route::get('auth/register', 'Auth\AuthController@getRegister');
Route::post('auth/register', 'Auth\AuthController@postRegister');

Route::get('/', function()
{
    return view('pages.home');
});

and https://app.com/auth/register is working.

A: Here's a step by step walkthrough on how to implement it. I tested it. So it works. This is for 'writer', but you could replicate it as you had originally planned for other professions.
I assume you've registered the Laravel Collective package since you're using the curly braces and exclamation points.
Step 1:
In your landing page view, where you have the writer button, add a hidden field with the string 'writer'. Like this:
{!! Form::open(['route' => ['writer_path']]) !!}
{!! Form::hidden('profession', 'writer') !!}
{!! Form::submit('Writer', array('class' => 'btn btn-warning')) !!}
{!! Form::close() !!}

Not that in the open field we are using a named route ('writer_path').
Step 2:
Register a route and a controller on your routes.php file, like this:
Route::post('auth/register', [
'as' => 'writer_path',
'uses' => 'SampleController@displayForm'
]);

Step 3:
In your sample controller, you define the displayForm method.
Within that method you first obtain the value you passed from the landing page view.
If you don't know how to create a controler, you can do
php artisan make:controller SampleController

from the command line
Because the value arrives as an array, you have to obtain the string 'writer' from the array and then pass it to the new view (the view with the registration form for the writer).
<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Input;

class SampleController extends Controller
{
/**
 * Display a listing of the resource.
 *
 * @return Response
 */
public function displayForm()
{
    $input = Input::get();
    $profession = $input['profession'];
    return view('writerregistration', ['profession' => $profession]);
}

}

Last Step:
In the new view which you will create as writerregistration.blade.php, you will display the form with the field you just passed ('profession') which contains the string 'writer'. Like this:
{!! Form::open() !!}

{!! Form::label('username', 'Username:') !!}
{!! Form::text('username', null, ['class' => 'form-control']) !!}

{!! Form::label('profession', 'Profession:') !!}
{!! Form::text('profession', $profession, ['class' => 'form-control']) !!}

{!! Form::label('email', 'Email:') !!}
{!! Form::text('email', null, ['class' => 'form-control']) !!}

{!! Form::label('passowrd', 'Password:') !!}
{!! Form::password('password', ['class' => 'form-control']) !!}

{!! Form::label('password_confirmation', 'Password Confirmation:') !!}
{!! Form::password('password_confirmation', ['class' => 'form-control']) !!}

{!! Form::submit('Sign Up', ['class' => 'btn btn-primary']) !!}

{!! Form::close() !!}

Presto, you've populated the field in the registration form for the writer with the info on the hidden field that belonged to the writer button in the landing page.


text:
Q: ActionView::Template::Error (no implicit conversion of Fixnum into String on heroku I am working on ROR app with Mongodb.App is working fine on localhost, but when i deploy it in heroku i am getting error. One of my view file command is this:
@h=Portfolio.last.folders
<%= @h%>

The Portfolio is a collection with field folders as array. Mongodb on production contain this.
Even i try do same in heroku rails console I got the same error which is :
TypeError: no implicit conversion of Fixnum into String
from /app/vendor/bundle/ruby/2.0.0/gems/moped-1.4.3/lib/moped/protocol/commands/authenticate.rb:35:in `+'
from /app/vendor/bundle/ruby/2.0.0/gems/moped-1.4.3/lib/moped/protocol/commands/authenticate.rb:35:in `digest'
from /app/vendor/bundle/ruby/2.0.0/gems/moped-1.4.3/lib/moped/protocol/commands/authenticate.rb:47:in `build_auth_command'
from /app/vendor/bundle/ruby/2.0.0/gems/moped-1.4.3/lib/moped/protocol/commands/authenticate.rb:25:in `initialize'
from /app/vendor/bundle/ruby/2.0.0/gems/moped-1.4.3/lib/moped/node.rb:488:in `new'
from /app/vendor/bundle/ruby/2.0.0/gems/moped-1.4.3/lib/moped/node.rb:488:in `login'
from /app/vendor/bundle/ruby/2.0.0/gems/moped-1.4.3/lib/moped/node.rb:48:in `block in apply_auth'
from /app/vendor/bundle/ruby/2.0.0/gems/moped-1.4.3/lib/moped/node.rb:47:in `each'
from /app/vendor/bundle/ruby/2.0.0/gems/moped-1.4.3/lib/moped/node.rb:47:in `apply_auth'
from /app/vendor/bundle/ruby/2.0.0/gems/moped-1.4.3/lib/moped/cluster.rb:250:in `with_secondary'
from /app/vendor/bundle/ruby/2.0.0/gems/moped-1.4.3/lib/moped/session/context.rb:104:in `with_node'
from /app/vendor/bundle/ruby/2.0.0/gems/moped-1.4.3/lib/moped/session/context.rb:43:in `query'
from /app/vendor/bundle/ruby/2.0.0/gems/moped-1.4.3/lib/moped/query.rb:115:in `first'
from /app/vendor/bundle/ruby/2.0.0/gems/mongoid-3.0.15/lib/mongoid/contextual/mongo.rb:233:in `last'
from /app/vendor/bundle/ruby/2.0.0/gems/mongoid-3.0.15/lib/mongoid/contextual.rb:18:in `last'
from /app/vendor/bundle/ruby/2.0.0/gems/mongoid-3.0.15/lib/mongoid/finders.rb:129:in `last'
from (irb):2
from /app/vendor/bundle/ruby/2.0.0/gems/railties-3.2.12/lib/rails/commands/console.rb:47:in `start'
from /app/vendor/bundle/ruby/2.0.0/gems/railties-3.2.12/lib/rails/commands/console.rb:8:in `start'
from /app/vendor/bundle/ruby/2.0.0/gems/railties-3.2.12/lib/rails/commands.rb:41:in `<top (required)>'
from script/rails:6:in `require'

In development machine I can do this in console. Any guesses why this error on heroku.


text:
Q: no intellisense for objects I have just installed Visual Studio Code IDE version 1.2.1 on a Linux Mint 17.3 OS.
I have a slim application in PHP and wanted to see if the IDE will show the various properties and methods under the slim object. Not happy this was not the case, no intellisense for the slim object. Below is the code snippet:
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;
use \Algos\App\classes\PDO_connection;

//slim framework initialization
$app = new \Slim\App;

$container = $app-> //expected list of properties and methods here

Is there any work around for this?

A: came across crane extension for VS Code


text:
Q: Can panning/zooming be disabled in an android MapView while allowing users to click on an ItemizedOverlay? Is there a way of disabling panning/zooming and keeping map overlays clickable?
I am specifically thinking about an ItemizedOverlay that I want to be tappable while denying users from moving around the map's viewport (It's for a game).
I've seen the same question answered but the answer sadly doesn't allow for overlay items to be clicked.
Thanks alot,
best regards,
Alex

A: I know this question is a little old but I had the same problem and found a workaround, it's not a graceful solution but appears to work.
First you have to create your own map subclass overriding the onTouchEvent handler
public class NonPannableMapView extends MapView {

    public NonPannableMapView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public NonPannableMapView(Context context, AttributeSet attrs){
        super(context, attrs);
    }

    public NonPannableMapView(Context context, String apiKey) {
         super(context, apiKey);
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
          //Handle a move so there is no panning or zoom
          if(ev.getAction() == MotionEvent.ACTION_MOVE)
              return true;
      return super.onTouchEvent(ev);
    }
}

Then it's just a case of changing the MapView reference in your layout to NonPannableMapView.

A: Try this:
mapView.setBuiltInZoomControls(false);

Hope that works! Have fun!


text:
Q: Unity 3D rendering issues on iPad Mini So, my team and I are experiencing an interesting issue. We're developing an app for the iPad mini. When I build the app for an iPad 4 or 2, it looks like this:

This is the way it's supposed to look. However, when my client receives the build on testflight on his iPad mini 4 (or even when he builds it himself from xCode), he sees the pictures below, and the app is extremely laggy and broken. The AR Camera we're using (Vuforia is in the project, but these issues persist even when all AR stuff is disabled) won't work. It looks like it could be some kind of rendering problem, but why it would happen on his iPad, and not any of mine, completely mystifies me. Can anyone explain this?
The specs for my friend's iPad are as such (he lives thousands of miles away, and there's no chance I can inspect the iPad personally).


text:
Q: Read Excel data .csv file sequentially in Jmeter I have a scenario to use data from each row for validation using a HTTP Request. have tried with the CSV config but it reads the first row only for the iteration.
I have a single iteration and all my samplers are in a single thread group. The data from csv file is retrieved sequentially only when i give the iterations to a value say 3 (each iteration each row is taken)
How to achieve on reading the csv file rows sequentially for single iteration ,where the thread group contains many HTTP request and i need the value from each row for each requests.
Kindly suggest me a solution

A: As per CSV Data Set Config documentation:

By default, the file is only opened once, and each thread will use a different line from the file. However the order in which lines are passed to threads depends on the order in which they execute, which may vary between iterations. Lines are read at the start of each test iteration. The file name and mode are resolved in the first iteration.

So implementing your scenario using CSV Data Set Config doesn't seem to be possible, I would recommend considering using JMeter functions instead such as:

*

*__StringFromFile()

*__CSVRead()
These functions read next line from the file each time they're called so you can use them instead of CSV Data Set config in each of the HTTP Request samplers. Check out Apache JMeter Functions - An Introduction to get familiarized with JMeter Functions concept.


text:
Q: two types of directory separators in joomla while debugging in JPath::find, my $path variable attain a value which is a mixture of directory separators. Half are back slashes and half are forward slashes. why is this so??
C:\Users\arslan\Desktop\xampp-win32-1.8.1-VC9\xampp\htdocs\COM/components/com_hello/views/pendingHello/tmpl

A: Windows uses back slashes \ and linux/mac (all unix based) use forward slashes / for the directory separator normally. Within PHP, either one actually works, as well as a mix like you see.
There is a constant in PHP called DIRECTORY_SEPARATOR which has the correct slash for your OS. However, when creating a path this isn't typically necessary, because Windows will still process what you have correctly.
So, the short answer is that / is used within the component which works fine no matter where Joomla is installed; however the first part of the path is system generated and Windows will always generate the path with \.
You can see a bit more on this here: http://alanhogan.com/tips/php/directory-separator-not-necessary


text:
Q: Can I move Geany's Sidebar to the Right Side? This isn't really that important, but is there a way to change the Geany IDE's sidebar to the right side instead of the left?
http://www.geany.org/

A: The answer is yes, but it depends on which version of Geany you are using.
Check out this mailing list entry and read through the discussion.
The change was committed in October 2009. Which according to the homepage means it is in version "Geany 0.18.1".
You can get this version from here.
I personally am using 0.18, released in August 2009, so have not tested this works.
EDIT: Following the comment, I have checked the source and can confirm the code does not appear to be there to alow this functionality.
The answer therefore is you should be able to, but you cannot.
I asked on #geany on freenode.net about this missing functionality, but have not had a reply yet.
You may get a result if you report this as a bug.


text:
Q: How to input a string with unknown size I'm a bit confused about strings in C. I understand that declaring buffer size is important since otherwise, it can cause buffer overflow. But I need to know how do I take a string input that I don't know the size of. For instance, if I wanted  to take a line of text from the user as input and I had no way of knowing how long their text would be, how do I do it?
I've tried dynamically allocating memory as the user gives an input. Here's the code-
#include<stdio.h>
#include<stdlib.h>

int main()
{
    char *str, ch;
    int size = 10, len = 0;
    str = realloc(NULL, sizeof(char)*size);
    if (!str)return str;
    while (EOF != scanf_s("%c", &ch) && ch != '\n')
    {
        str[len++] = ch;
        if (len == size)
        {
            str = realloc(str, sizeof(char)*(size += 10));
            if (!str)return str;
        }
    }
    str[len] = '\0';
    printf("%s\n", str);
    free(str);
}

The problem is, when I compile it using VS-2017, I get these errors-

source.c(10): warning C4473: 'scanf_s' : not enough arguments passed
  for format string
source.c(10): note: placeholders and their parameters expect 2
  variadic arguments, but 1 were provided
source.c(10): note: the missing variadic argument 2 is required by
  format string '%c'
source.c(10): note: this argument is used as a buffer size

I think that dynamically allocating memory as I go on(like in the above code) should work, but I'm probably doing something wrong. Is there a way to make this work?
EDIT: Word.

A: *

*You should use getchar not scanf_s

*You should use int ch; not char ch; for EOF
The following code could work:
#include<stdio.h>
#include<stdlib.h>

int main() {
    char *str = NULL;
    int ch;
    size_t size = 0, len = 0;

    while ((ch=getchar()) != EOF && ch != '\n') {
        if (len + 1 >= size)
        {
            size = size * 2 + 1;
            str = realloc(str, sizeof(char)*size);
        }
        str[len++] = ch;
    }
    if (str != NULL) {
        str[len] = '\0';
        printf("%s\n", str);
        free(str);
    }

    return 0;
}

A: *

*scanf_s requires a buffer size as argument, and you don't want that

*Generally scanf will read from stdin once the \n is fed anyways.

*Using getchar here is a better approach

Here is a version using getchar:
#include <stdio.h>
#include <stdlib.h>

int     main()
{
  char  *str = NULL;
  int   ch;
  int   capacity = 10, size = 0;

  str = realloc(str, sizeof(*str) * (capacity + 1));
  if (!str) return 1;
  while ((ch = getchar()) != EOF && ch != '\n')
    {
      if (size == capacity)
      {
        capacity += 10;
        str = realloc(str, sizeof(*str) * (capacity + 1));
        if (!str) return 1;
      }
      str[size] = (char)ch;
      size++;
    }
  str[size] = '\0';
  printf("%s\n", str);
  free(str);
  return 0;
}

A: scanf_s requires an additional "buffer-size" parameter for each formatted input place holder. That's what your compiler complains. So when using scanf_s, you'd have to write scanf_s("%c", &ch, 1). But you could simply use scanf as well, as you can guarantee that your buffer ch is large enough to take on a character value in any case. So scanf("%c",&ch) will work securely as well.
Note further that scanf (and scanf_s) return the number of values correctly read in; A return value of 0 would be possible as well, also indicating that nothing was read in.
So I'd test it as ...
while (scanf("%c", &ch)==1 && ch != '\n')

A: Your code is almost fine.
Two things should be changed:

*

*don't use scanf but use getc

*ch should be int, otherwise the comparision with EOF will cause trouble.

*Nitpicking detail: main should return 0 in case of success and a value different from 0 in case of failure.

#include <stdio.h>
#include <stdlib.h>

int main()
{
  char *str;
  int ch;
  int size = 10, len = 0;

  str = realloc(NULL, sizeof(char)*size);
  if (str == NULL)
    return 1;

  while ( (ch = getc(stdin)) && ch != EOF && ch != '\n')
  {
    str[len++] = (char)ch;

    if (len == size)
    {
      str = realloc(str, sizeof(char)*(size += 10));

      if (str == NULL)
        return 1;
    }
  }

  str[len] = '\0';
  printf("%s\n", str);
  free(str);
}

A:
The problem is, when I compile it using VS-2017, I get these errors-
source.c(10): warning C4473: 'scanf_s' : not enough arguments passed for format string

source.c(10): note: placeholders and their parameters expect 2 variadic arguments, but 1 were provided

source.c(10): note: the missing variadic argument 2 is required by format string '%c'

source.c(10): note: this argument is used as a buffer size

The warning and notes are quite explicit, aren't they?
Looking up the related documentation reveals under the "Remarks" section:

Unlike scanf and wscanf, scanf_s and wscanf_s require the buffer size to be specified for all input parameters of type c, C, s, S, or string control sets that are enclosed in []. The buffer size in characters is passed as an additional parameter immediately following the pointer to the buffer or variable.

So you want to change
  while (EOF != scanf_s("%c", &ch) && ch != '\n')

to look at least like this:
  while (EOF != scanf_s("%c", &ch, sizeof ch) && ch != '\n')

even better would be to provide complete error checking like this:
  {
    int result;
    while (1 == (result = scanf_s("%c", &ch, sizeof ch))
           && ch != '\n')
    {
      ...
    }

    if (EOF == result && ferror(stdin)) /* As scanf'ing uses stdin,
                                           test its error status. */
    {
      fprintf(stderr, "scanf_s() failed.\n")
    }
  }


text:
Q: Comparison between residual intersection in Fulton's intersection theory and Aluffi's result on Milnor class $\textbf{Question}$ I deduced that $m(A \cup B, V) = 0 $ for nonsingular variety $V$ and nonsingular hyper surfaces $A$ and $B$ whose intersection is also nonsingular. But I do not think it is true compared to Aluffi's result. Can you help me to know which step is wrong?

*

*$m(A \cup B, V)$ is a Milnor class of $A \cup B \subset V$ which will be defined later.

p.161, Fulton, Intersection theory :
$\textbf{Proposition 9.2}$ Let $D \subset W \subset V$ be closed embeddings of schemes, with $V$ a k-dimensional variety, and $D$ is a Cartier divisor on V. Let $R$ be a residual scheme to $D$ in $W$. Then for all $m$,
$$ s(W, V)_m = s(D, V)_m + \sum_{j = 0}^{k-m} {k-m \choose j} (-D)^j \cdot s(R, V)_{m+j} $$
in $A_m(W)$.
My quesetion is here :
Let $V$ be a nonsingular projective variety.
Let $A$ and $B$ be two nonsingular hypersurfaces of $V$ and $D$ be the intersection of $A$ and $B$ which is also nonsingular. Let $\eta : \tilde{V} \to V$ be the blow up of $V$ along $D$ and denote $\tilde{D}$ by the inverse image of $D$ under $\eta$. Let $\tilde{A}$ and $\tilde{B}$ be strict transforms of $A$ and $B$ under $\eta$. Note that $\tilde{A}$ and $\tilde{B}$ does not intersect by the exercise 7.12 of Hartshorne ChapterII.
If the residual schemes to $\tilde{D}$ in $\eta^{-1}(A), \eta^{-1}(B)$ and $\eta^{-1}(A \cup B)$ are $\tilde{A}, \tilde{B}$ and $ \tilde{A} \sqcup \tilde{B} $, respectively, then we can apply $\textbf{Proposition 9.2}$ as follows :
$$ s(\eta^{-1}(A \cup B), \tilde{V}) = s(\tilde{D}, \tilde{V}) + \sum_{m \geq 0 } \sum_{j = 0}^{k-m} {k-m \choose j} (- \tilde{D}^j) \cdot s(\tilde{A} \sqcup \tilde{B}, \tilde{V})_{m+j}  $$
$$ s(\eta^{-1}(A), \tilde{V}) = s(\tilde{D}, \tilde{V}) + \sum_{m \geq 0 } \sum_{j = 0}^{k-m} {k-m \choose j} (- \tilde{D}^j) \cdot s(\tilde{A}, \tilde{V})_{m+j}  $$
$$ s(\eta^{-1}( B), \tilde{V}) = s(\tilde{D}, \tilde{V}) + \sum_{m \geq 0 } \sum_{j = 0}^{k-m} {k-m \choose j} (- \tilde{D}^j) \cdot s(\tilde{B}, \tilde{V})_{m+j}  $$
Since $s(\tilde{A} \sqcup \tilde{B}, \tilde{V})_l = s(\tilde{A}, \tilde{V})_l + s(\tilde{B}, \tilde{V})_l$ for all $l$, we have following :
$$ s(\eta^{-1}(A \cup B), \tilde{V}) + s(\tilde{D}, \tilde{V}) = s(\eta^{-1}(A), \tilde{V}) + s(\eta^{-1}(B), \tilde{V}) \cdots (*) $$
By taking $\eta_*$ we obtain
$$ s(A \cup B, V) + s(D , V) = s(A, V) + s(B, V) \cdots (**)$$ since $\tilde{D} = \eta^{-1}(D)$ and by $\textbf{Proposition 4.2, Fulton}$.
However this contradicts to Aluffi's result : ($\textbf{Aluffi 2003}$)
Let $X$ be a subvariety of nonsingular variety $M$. Chern-Fulton class $c_F(X)$ is defined by $c(T_M) \cap s(X, M)$. Since total Segre class for closed embedding $X \subset M$ does not satisfy the inclusion-exclusion principle for singular varieties, instead, Aluffi defined another class $s^{\circ}(X, M)$ given by $c_{SM}(X) = c(T_M) \cap s^{\circ}(X, M)$ where $c_{SM}(X)$ is the Chern-Schwartz-MacPherson class which satisfies the inclusion-exclusion principle for every algebraic varieties. Since $c_{SM}(X) = c_F(X)$ when $X$ is a nonsingular subvariety, $s^{\circ}(X, M) = s(X, M)$ in this case.
Aluffi defined the difference $s^{\circ}(X, M) - s(X, M)$ by $m(X, M)$ which is called by Milnor class. Especially, $m(X, M) = 0$ when $X$ is nonsingular. If $X$ is a hypersurface of $M$ and $Y$ is a singular scheme of $X$, we have following formular by Aluffi :
$$ m(X, M) = c(\mathcal{O}(X))^{-1} \cap (s(Y, M)\breve{} \otimes_M \mathcal{O}(X)) $$
The dual and tensor product notation are defined in $\textbf{Aluffi(1999)}$, section 1.4.
In my case, since $V, A, B$ and $D$ are nonsingular, $s^{\circ}(T, V) = s(T, V)$ where $T$ is one of $A, B$ and $D$. Thus $s(A \cup B, V) = s^{\circ}(A, V) + s^{\circ}(B, V) - s^{\circ}(D, V) = s^{\circ}( A \cup B, V)$.
Then $m(A \cup B, V) = 0$. However I do not think that $c(\mathcal{O}(A \cup B))^{-1} \cap (s(D, V)\breve{} \otimes_V \mathcal{O}(A \cup B))$ is zero for general hypersurfaces $A$ and $B$ such that whose intersection is also nonsingular.
........Which step is wrong.....


text:
Q: Insert a note in a Google Sheet with google-sheets-api I'm looking at the following documentation for Google Sheets and I'm wondering how do I add/update a cell with a Note attached to it.
https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/update
PUT https://sheets.googleapis.com/v4/spreadsheets/{spreadsheetId}/values/{range}

I can't seem to find a sample request body of what it looks like to add a note. I've tried to send a PUT request but of course it returned a 400.
{
  "values": [
    [
      {
        "note": "sample note"
      }
    ]
  ]
}

This returns the following error:
{
  "error": {
    "code": 400,
    "message": "Invalid values[17][0]: struct_value {\n  fields {\n    key: \"note\"\n    value {\n      string_value: \"sample note\"\n    }\n  }\n}\n",
    "status": "INVALID_ARGUMENT"
  }
}


text:
Q: Struts 2, type conversion of Dates in a List, non-default format I have an action, that action has List of Dates property. The request parameters will come in "yyyy.MM.dd" format.
In have "-coversion.properties" file (I don't want to use global type converter for this purpose).
I am not using annotations.
If it was just a single Date, not a collection, property-specific conversion would be easy. Is it possible to do apply a property-specific type conversion to the elements of a List?

A: I wrote a sample code which works fine. It's structure is as above.

At first I wrote a converter in /util/MyDateConverter.java as below:
package util;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

import com.opensymphony.xwork2.conversion.TypeConversionException;

import ognl.DefaultTypeConverter;

public class MyDateConverter extends DefaultTypeConverter {
@Override
public Object convertValue(Map context, Object object, Class type) {
    if (type == Date.class) {
        String datePattern = "yyyy.MM.dd";
        DateFormat format = new SimpleDateFormat(datePattern);
        format.setLenient(false);
        try {
            String[] dateString = (String[]) object;
            return format.parse(dateString[0]);
        } catch (Exception e) {
            throw new TypeConversionException("Given Date is Invalid");
        }
    }
    return null;
}
}

Then, to use struts2 collection conversion support, I wrote /util/MyDate.java as below:
package util;
import java.io.Serializable;
import java.util.Date;

public class MyDate implements Serializable {

    public MyDate(int myId, Date value) {
        super();
        this.myId = myId;
        this.value = value;
    }

    int myId;
    Date value;

    public Date getValue() {
        return value;
    }

    public void setValue(Date value) {
        this.value = value;
    }

    public int getMyId() {
        return myId;
    }

    public void setMyId(int myId) {
        this.myId = myId;
    }

    @Override
    public String toString() {
        return value.toString();
    }
}

Then I told struts2 how to support collection by writing /action/Action1-conversion.properties as below:
KeyProperty_dates=myId
Element_dates=util.MyDate
CreateIfNull_dates=true

Then told him how to convert MyDate.value by writing /util/MyDate-conversion.properties as below:
value=util.MyDateConverter

Then I prepared /index.jsp as below:
<%@ taglib uri="/struts-tags" prefix="s"%>

<s:form>
    <s:date name="dates(1).value" format="yyyy.MM.dd" id="dateSD1" />
    <s:textfield name="dates(1).value" value="%{dateSD1}" label="New Date 1" />

    <s:date name="dates(2).value" format="yyyy.MM.dd" id="dateSD2" />
    <s:textfield name="dates(2).value" value="%{dateSD2}" label="New Date 2"/>

    <s:submit value="Update" />
    <pre>
    Current Date 1: <s:date name="dates(1).value" />
    Current Date 2: <s:date name="dates(2).value" />
    </pre>
</s:form>

and /action/Action1.java as below:
package action;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import util.MyDate;

import com.opensymphony.xwork2.ActionSupport;

public class Action1 extends ActionSupport {

    public Action1() {
        super();
        dates.add(new MyDate(1, new Date()));
        dates.add(new MyDate(2, new Date()));
    }

    public String execute() {
        return SUCCESS;
    }

    List<MyDate> dates = new ArrayList<MyDate>();

    public void setDates(List<MyDate> dates) {
        this.dates = dates;
    }

    public List<MyDate> getDates() {
        return dates;
    }
}

After running application, the Update button works well as expected which shows that conversions have been working well.
I hope this sample code can help you.
Reference: Apache Struts2 Type Conversion


text:
Q: Get the width of a TreeViewColumn that would like to be if it were autosized Is there a way to get the width, in pixels, that a gtk.TreeViewColumn would want to be if the sizing mode was set as gtk.TREE_VIEW_COLUMN_AUTOSIZE, even if it's currently gtk.TREE_VIEW_COLUMN_FIXED?

A: I think gtk.TreeViewColumn.cell_get_size() will do the job.
Sample code:
def show_size(treeview):
    col = treeview.get_column(0)
    cell = col.get_cell_renderers()[0]
    size = col.cell_get_position(cell)
    print 'current size: position=%s, width=%s' % size
    size = col.cell_get_size()
    print 'autosize: %s, x=%s, y=%s, w=%s, h=%s' % size


text:
Q: What Open Source Libraries are available (and compile) on PIC Micro devices? I do some hobby work with PIC Microcontrollers and I really enjoy using them because they are cheap and perfect for the applications that I use them for. However, it has become increasingly apparent that I do not know what open source libraries will actually compile for the PIC Micro devices.
Obviously there are the whole set of example code that Microchip themselves release; though that is not quite Open Source.
And there are example projects around the web that may have reusable code but what I am talking about is large projects, like maybe mp3 encoders/decoders written in C that will work with a PIC Micro C compiler.
I am looking for suggested projects that will work. Does anybody know any open source C (or otherwise) projects that will compile on PIC Micro devices?

A: I use the open source Small Device C Compiler (sdcc) for my PIC stuff.  It also supports a variety of microcontrollers.  A lot easier for a hobbyist to stomach than most of the other (expensive) options.
I do my PIC stuff under Ubuntu linux.  There are a number of cool tools available (such as piklab, gpsim, etc.) as well as linux drivers for the Microchip programmers.  I had to create a custom programmer profile in piklab, as my particular programmer is newer than those piklab supports.
You can find routines here and there for doing particular operations, such as addressing an LCD display, but I am not aware of any libraries where these sorts of things have been consolidated.
I imagine that something as complex as an MP3 player would be hard to fit into most PICs due to the limited RAM, if not impossible.  Of course someone may prove me wrong on this...


text:
Q: How does SE's single signon work? Basically I just want to know how does StackExchange's single signon system work?
In the SE network you need to login only once in one of the websites to be automatically logged in to the other sites upon visiting.
How should I implement such a feature in my own network of sites?
I assume it uses the cookie which resides on the user's browser and then authenticates it with the originating site. If it is legit then it logs the user in automatically.

A: You have to implement SAML or oauth2 to allow sso on your network.
In case of SAML your child websites will be service providers or resource servers.
While you need to setup and identity provider.
The sequence of events will be like this.
1. User hits a url of songs website, this site is resource server and does not handle authentication.
2.To authenticate resource server will construct a SAML authrequest and redirects to identity provider after signing it.
Idp verifies the signature after receiving authrequest.
3. User will be presented with a login form, user has to end login credentials.
4. After user authentication idp will generate a SAMl token and redirect back to resource server.
5. Resource server will extract identity information from SAML token, resource server will login the user with session or cookie.
Depends upon which technology you are working in i have implemented it in php using simplesamlphp.


text:
Q: Right exact sequence and exact functors I'm wondering if we have a left exact sequence $ 0 \rightarrow E \rightarrow F \rightarrow G$ of objects, and an exact functor  T from some abelian category $A$ to $Com(A)$.
Can we have something similar to a long exact sequence of homology or cohomology?
I'm especially interested in the case that $T(F)$ and $T(G)$ are exact complexes.
Thank you!

A:
Theorem: If

*

*$0 \to A \to B \to C \to D \to 0$ is an exact sequence of complexes,

*$B$ is an exact complex, and

*$C$ is an exact complex,

  then $H_n(A) \cong H_{n+2}(D)$.

I like to approach problems by looking at the corresponding bicomplex. You can usually learn a lot from the two spectral sequences for computing its total homology.
In the spectral sequence where you take horizontal homology first, the $E^1$ page looks like
$$ \begin{matrix}
\vdots & \vdots & \vdots & \vdots
\\ 0 & 0 & 0 & 0
\\ 0 & 0 & 0 & 0
\\ \vdots & \vdots & \vdots & \vdots
\end{matrix} $$
because every row is exact. Thus, the total homology is zero.
In the spectral sequence where you take vertical homology first, the $E^1$ page looks like
$$ \begin{matrix}
\vdots & \vdots & \vdots & \vdots
\\ H_3(A) & 0 & 0 & H_3(D)
\\ H_2(A) & 0 & 0 & H_2(D)
\\ H_1(A) & 0 & 0 & H_1(D)
\\ H_0(A) & 0 & 0 & H_0(D)
\\ \vdots & \vdots & \vdots & \vdots
\end{matrix} $$
Since the total homology is zero, the groups in the above diagram have to eventually be eliminated as you step through the spectral sequence. There is only one possibility for there to be differentials — in the $E^3$ page, where the differentials go 3 steps right and 2 steps up.
Since the homology has to be zero, the differentials have to be isomorphisms.

I posted the above since the proof technique is powerful enough that one should learn it! However, there is a more elementary method available: you can split the exact sequence into two short exact sequences
$$ 0 \to A \to B \to E \to 0 \qquad 0 \to E \to C \to D \to 0 $$
and the long exact sequence in homology shows
$$ H_n(A) \cong H_{n+1}(E) \cong H_{n+2}(D) $$


text:
Q: When should I use $ref versus the object id in Open API I'm working on a schema in OpenAPI with Swagger, and I'm not sure if I'm misusing the $ref element. I have a User model and a Project model, similar to something like
User:
      type: object
      properties:
        id:
          type: string
          format: uuid
        name:
          type: string
        ...
Project:
      type: object
      properties:
        id:
          type: string
        user_id:
          $ref: "#/components/schemas/User"
        ...

I don't see much in the Open API Spec documentation as to what the $ref element is specifically, but in the JSON Schema documentation—of which Open API extends the $ref element—I've found the following description of the item:

The easiest way to describe $ref is that it gets logically replaced with the thing that it points to.

In the case above, I just want to refer to the user who posted a project. It seems unnecessary to essentially include all of the information about the User in the Project model if that is what it's doing. Would it be better practice to just have a string element of the uuid of the user_id? Or is it correct as is? Is it more common to name the field user rather than user_id if that is the case?
Edit:
I realize the heart of what was bothering me is if there were to be recursive references. If a User has an array of $ref to Projects, but also a Project has an array of $ref to Users, the replacement (if that's what it's doing) would infinitely embed each model in the other. I assume this wouldn't happen in practice, assuming that a $ref is just a pointer to the Model?

A: In your example it might make sense to extract the userId definition into its own schema (assuming it is the userId only that appears, not an entire User object), then it is clearer what's going on:
components:
  schemas:
    User:
      type: object
      properties:
        id:
          $ref: '#/components/schemas/userId'
        name:
          type: string
        ...
    Project:
      type: object
      properties:
        id:
          type: string
        user_id:
          $ref: "#/components/schemas/userId"
        ...
    userId:
      type: string
      format: uuid

But there is nothing stopping you creating a direct $ref to #/components/schemas/User/properties/id instead, as long as what is pointed to is a valid OpenAPI schemaObject.
Circular references are allowed by the JSON Reference and OpenAPI specifications, so your analogy of a pointer is a sound one.


text:
Q: How to add a border to a surface? This is my code
I'm trying to add a border to a surface, i've tried many variations what am i doing wrong?
This is just a red bar, I want any kind of border on it, but this proves to be difficult, what's going on?
var surface = new Surface({
    size: [window.innerWidth/2, 10],
    border: [10],
    properties: {
        background: 'red',
        border:10,
        borderColor:'blue'}

});

var sizeModifier = new Modifier({
    size: [window.innerWidth, window.innerHeight]
});

var alignModifier = new Modifier({
    align: [0.5, 0.5],
    origin:[0.5, 0.5]
});

mainContext.add(sizeModifier).add(alignModifier).add(surface);

A: It seems that your surface has a too small height to draw a 10px border. You should also add a line style to the border e.g. solid. You could try the following to see a border:
var surface = new Surface({
    content: '
Famous in JSFiddle
',
    size: [window.innerWidth / 2, 100],
    border: [10],
    properties: {
        background: 'red',
        border: '10px solid',
        borderColor: 'blue'
    }
});

Famous.loaded(function () {
    var Engine = Famous.Core.Engine;
    var Modifier = Famous.Core.Modifier;
    var RenderNode = Famous.Core.RenderNode;
    var Surface = Famous.Core.Surface;
    var Transform = Famous.Core.Transform;

    var mainContext = Engine.createContext();

    var surface = new Surface({
        content: '
Famous in JSFiddle
',
        size: [window.innerWidth / 2, 100],
        border: [10],
        properties: {
            background: 'red',
            border: '10px solid',
            borderColor: 'blue'
        }
    });

    var sizeModifier = new Modifier({
        size: [window.innerWidth, window.innerHeight]
    });

    var alignModifier = new Modifier({
        align: [0.5, 0.5],
        origin: [0.5, 0.5]
    });

    mainContext.add(sizeModifier).add(alignModifier).add(surface);

    /*
    var surface = new Surface({
        content: '
Famous in JSFiddle
'
    });

    var modifier = new Modifier({
        transform: Transform.translate(50, 50)
    });
    */

    //var node = new RenderNode(modifier);
    //node.add(surface);

    var appContext = mainContext; //Engine.createContext();
    //appContext.add(node);

    Engine.pipe(Application);
});

<link href="https://rawgit.com/jperl/famous-compiled/e9c12b1fa657820d3f9bad093ea72e8ee2dfec46/dist/lib/famous/core/famous.css" rel="stylesheet"/>


text:
Q: Trace of product of three Pauli matrices Consider the four $2\times 2$ matrices $\{\sigma_\mu\}$, with $\mu = 0,1,2,3$, which are defined as follows
$$
\sigma_0 =\left( \begin{array}{cc} 1 & 0 \\ 0 & 1 \end{array}\right)
$$
$$
\sigma_1 =\left( \begin{array}{cc} 0 & 1 \\ 1 & 0 \end{array}\right)
$$
$$
\sigma_2 =\left( \begin{array}{cc} 0 & -i \\ i & 0 \end{array}\right)
$$
$$
\sigma_3 =\left( \begin{array}{cc} 1 & 0 \\ 0 & -1 \end{array}\right)
$$
i.e. the identity matrix and the three Pauli matrices. For the trace of the product of any two matrices $\sigma_\mu$ one has the identity $\text{tr}(\sigma_\mu \sigma_\nu)= 2 \delta_{\mu \nu}$. I was wondering if a similar identity can be derived for the product of three sigma matrices,
$$
\text{tr}(\sigma_\mu \sigma_\nu \sigma_\lambda)= \;?
$$

A: You can check that $\sigma_1\sigma_2\sigma_3 = i I$ so $\mathrm{tr}(\sigma_1\sigma_2\sigma_3) = 2i$. By cyclic invariance of the trace, we also have
$$\mathrm{tr}(\sigma_1\sigma_2\sigma_3)  = \mathrm{tr}(\sigma_2\sigma_3\sigma_1) = \mathrm{tr}(\sigma_3\sigma_1\sigma_2) = 2i$$
Since $\sigma_r \sigma_s = - \sigma_s \sigma_r$ for distinct $r,s \in \{1,2,3\}$, we also get
$$\mathrm{tr}(\sigma_2\sigma_1\sigma_3)  = \mathrm{tr}(\sigma_3\sigma_2\sigma_1) = \mathrm{tr}(\sigma_1\sigma_3\sigma_2) = -2i$$
On the other hand, if two of $i,j,k \in \{1,2,3\}$ are equal then, from the the commutation relation mentioned above and the fact that $\sigma_r^2 = I$ for $r \in \{1,2,3\}$, you can conclude that $\sigma_i \sigma_j \sigma_k \in \{ \pm \sigma_1 ,\pm \sigma_2 , \pm \sigma_3\}$ and, in particular, $\mathrm{tr}(\sigma_i \sigma_j \sigma_k) = 0$.
This can be summarized by saying that, for $i,j,k \in \{1,2,3\}$,
$$\mathrm{tr}(\sigma_i \sigma_j \sigma_k) = \varepsilon_{ijk} 2i$$
where $\varepsilon_{ijk}$ is the Levi-Cevita symbol given by
$$\varepsilon_{ijk} = \begin{cases}
1 && \text{ if } ijk \text{ is an even permutation of } 123 \\
-1 && \text{ if } ijk \text{ is an odd permutation of } 123 \\
0 && \text{ if } ijk \text{ is not a permutation of } 123 \\
\end{cases}$$

A: First I note a few things about the defined matrices:
1) Commutation: $[\sigma_\mu,\sigma_\nu] = 2 i \epsilon_{0 \mu \nu \rho} \sigma_\rho$
2) Anti-commutation: $\{ \sigma_\mu ,\sigma_\nu \} = 2 \delta_{\{\mu \nu}  \sigma_{0\}} - 4 \delta_{\mu 0} \delta_{\nu 0} \sigma_0$
Where $a_{ \{b c} d_{i\}} = a_{bc} d_i + a_{ib} d_{c} + a_{ci}d_b$
This gives: $\sigma_\mu \sigma_\nu = i \epsilon_{0 \mu \nu \rho} \sigma_\rho + \delta_{\{\mu \nu} \sigma_{0\}}-\delta_{\mu 0} \delta_{\nu 0} \sigma_0$
Thus:
\begin{eqnarray}
\text{tr}(\sigma_\mu \sigma_\nu \sigma_\rho) &=& \text{tr}(i \epsilon_{0 \mu \nu \alpha} \sigma_\alpha\sigma_\rho + \delta_{\{\mu \nu} \sigma_{0\}}\sigma_\rho-2\delta_{\mu 0} \delta_{\nu 0} \sigma_\rho)\\
&=& 2 i \epsilon_{0\mu\nu\rho}+2\delta_{\{\mu \nu}\delta_{0\}\rho}-4\delta_{\mu0}\delta_{\nu 0} \delta_{\rho 0 }
\end{eqnarray}
where I have used the trace identity sketched out in the problem statement.
We can check the results of this expression by confirming that if one of the three, say $\mu=0$ then we get back the original identity.
We can also look at what happens if $\mu ,\nu,\rho \ne0$. In this case we would get $2i\epsilon_{0\mu \nu \rho}$ this matches the other answer.


text:
Q: configure liquibase rollback command from maven I am trying to perform a liquibase rollback command on an application
I have my changeset:
<changeSet id="dmsTestSQL" author="ahmed"
        dbms="mysql">
        <sqlFile path="db/changelog/sql/add.sql"
             encoding="UTF-8"
             splitStatements="true"
             stripComments="true"/>
        <rollback>
            <sqlFile path="db/changelog/sql/rollback.sql"/>
        </rollback>
    </changeSet>

and I have my configuration class:
@Configuration
public class LiquibaseConfiguration {

    @Value("${com.autogravity.dms.liquibase.changelog}")
    private String changelog;

    @Value("${spring.datasource.url}")
    private String url;

    @Value("${spring.datasource.username}")
    private String username;

    @Value("${spring.datasource.password}")
    private String password;

    /*@Value("${liquibase.rollback-file}")
    private String rollback;*/

    @Bean
    public SpringLiquibase liquibase()  {
        SpringLiquibase liquibase = new SpringLiquibase();
        liquibase.setDataSource(dataSource());
        liquibase.setChangeLog(changelog);
        //liquibase.setRollbackFile(new File(rollback));
        return liquibase;
    }

    public MysqlDataSource dataSource() {
        MysqlDataSource ds=new MysqlDataSource();
        ds.setURL(url);
        ds.setUser(username);
        ds.setPassword(password);
        ds.setAutoReconnect(true);
        ds.setCreateDatabaseIfNotExist(true);
        return ds;
    }

}

I also have created mvn plugin in my pom file:
<plugin>
            <groupId>org.liquibase</groupId>
            <artifactId>liquibase-maven-plugin</artifactId>
            <version>2.0.2</version>
            <executions>
                <execution>
                    <phase>process-resources</phase>
                    <configuration>
                        <tag>${project.version}</tag>
                        <dropFirst>false</dropFirst>
                        <changeLogFile>classpath:/db/changelog/db.changelog.xml</changeLogFile>
                        <driver>com.mysql.jdbc.Driver</driver>
                        <url>jdbc:mysql://localhost:3306/db</url>
                        <username>root</username>
                        <password>test</password>
                    </configuration>
                    <goals>
                        <goal>rollback</goal>
                        <goal>tag</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>

I try to run command liquibase:rollback -Dliquibase.rollbackTag=1.0 but then I get the error :
Failed to execute goal org.liquibase:liquibase-maven-plugin:2.0.2:rollback (default-cli) on project dealer-microservice: The driver has not been specified either as a parameter or in a properties file. -> [Help 1]

I don't understand the previous error and I tried to search it but found nothing. can I get help in interpreting this error


text:
Q: How to self reference a record in MySQL in the INSERT INTO SELECT statement I have a tree structure that I store in the table topic_nodes.  There is a table called holders that all topic node tree belongs to.
Now I need to insert a new ROOT topic node the statement looks like this:
        INSERT INTO topic_nodes
        (id, holder_id, name, level_number, parent_id)
        SELECT RIGHT(UUID_SHORT(), 10), id, '<ROOT>', -1, <value_of_id_that_was_just_generated>
        FROM holders;

How do I insert the proper value instead of <value_of_id_that_was_just_generated> placeholder?

A: Use a subquery that returns the UID, then you can reference that column twice in the main SELECT.
INSERT INTO topic_nodes
(id, holder_id, name, level_number, parent_id)
SELECT uid, id, '<ROOT>', -1, uid
FROM (SELECT RIGHT(UUID_SHORT(), 10) AS uid, id
      FROM holders) AS x


text:
Q: matplotlib plot() not working I am using a Raspberry Pi to create a simple graph that shows analog readings from a potentiometer via the GPIO pins. I created a small circuit that can overcome the RPi's inability to read analog signal. There is a small problem with the plotting itself. The code I use is shown below.
# include RPi libraries in to Python code
import RPi.GPIO as GPIO
import time
import matplotlib.pyplot as plt
from drawnow import drawnow

# instantiate GPIO as an object
GPIO.setmode(GPIO.BCM)

# define GPIO pins with variables a_pin and b_pin
a_pin = 18
b_pin = 23
gainF = []
gainString = 0
plt.ion()
x_axis = 0

def makeFig():
    plt.ylim(200,210)
    plt.xlim(0,100)
    plt.title('Readings')
    plt.grid(True)
    plt.ylabel('Gain')
    print(gainString)
    print(x_axis)
    plt.plot(gainString, x_axis)
    plt.show()
    #plt.plot(gainString, 'ro-', label='Gain dBm')

# create discharge function for reading capacitor data
def discharge():
    GPIO.setup(a_pin, GPIO.IN)
    GPIO.setup(b_pin, GPIO.OUT)
    GPIO.output(b_pin, False)
    time.sleep(0.005)

# create time function for capturing analog count value
def charge_time():
    GPIO.setup(b_pin, GPIO.IN)
    GPIO.setup(a_pin, GPIO.OUT)
    count = 0
    GPIO.output(a_pin, True)
    while not GPIO.input(b_pin):
        count = count +1
    return count

# create analog read function for reading charging and discharging data
def analog_read():
    discharge()
    return charge_time()

# provide a loop to display analog data count value on the screen
while True:
    print(analog_read())
    gainString = analog_read()
    x_axis = x_axis + 1
    #dataArray = gainString.split(',')
    #gain = float(dataArray[0])
    #gainF.append(gain)
    makeFig()
    plt.pause(.000001)
    time.sleep(1)

    #GPIO.cleanup()

This code displays the increasing x axis and the y axis readings from the makeFig() function, but the graph that opens up does not display anything. It remains the same. Anything I need to change in the code? Thanks.

A: You are attempting to plot a line plot of single values. This is the same as
plt.plot([1],[5])

which does not show up, because a line needs two points at least to become a line.
You may use a marker to display single points in case this is what you're after
plt.plot([1],[5], marker="o")


text:
Q: Calculate elapsed time in C I'm new to C and I'm using Linux. I got stuck on this uni task. I need to evaluate program and I need to make a program to show the time elapsed for execution. Here is origin program.
/*
 * Simple MPI program to sum the numbers from 1 to 1000
 *
 * The output of this program should look like this:
 *
 * $ mpirun -n 4 ./su
 * node 1 of 4 starting at 251 and ending at 500
 * node 2 of 4 starting at 501 and ending at 750
 * node 3 of 4 starting at 751 and ending at 1000
 * node 0 of 4 starting at 1 and ending at 250
 * The sum from 1 to 1000 is: 500500
 *
 * Author: Kevan Buckley
 */

#include <stdio.h>
#include <mpi/mpi.h>

int main(int argc, char **argv) {
    // Rank is which process this code is executing in.
    // Rank 0 is the initial process.
    int rank;
    int size;
    int sum = 0;
    int start, end, accum, i;

    // These lines must appear at the start of any
    // MPI program.
    MPI_Status status;
    MPI_Init(&argc, &argv);

    // These lines tell MPI that rank and size are values
    // that we want to communicate between processes.
    MPI_Comm_size(MPI_COMM_WORLD, &size);
    MPI_Comm_rank(MPI_COMM_WORLD, &rank);

    // Only compute part of the sum.
    // This splits the work over the different processes.
    start = (1000*rank/size)+1;
    end = 1000*(rank+1)/size;

    printf("node %d of %d start: %d end: at %d\n",\
           rank, size, start, end);

    for(i=start; i<=end; i++){
        sum = sum + i;
    }

    if(rank == 0) {
        for(i=1; i<size; i++){
            // Receive a message from another process.
            MPI_Recv(&accum, 1, MPI_INT, i, 1, \
                     MPI_COMM_WORLD,  &status);
            sum = sum + accum;
        }
        printf("The sum from 1 to 1000 is: %d\n", sum );
    }
    else {
       // Send data to the process at rank 0.
       MPI_Send(&sum, 1, MPI_INT, 0, 1, MPI_COMM_WORLD);
    }

    // This code must end any MPI program.
    MPI_Finalize();

    return 0;
}

This is my updated version of it - Gist. I took all time calculations from other code that I was working for. I'm tried a lot of things, but still can't get it working.
Any help would be helpful, thanks!

A: If I understand correctly you want to time a part of your program.
Here is a sample code to do just that for parallel programming using MPI_Wtime.
#include <mpi.h>

double start, finish;

MPI_Init (&argc, &argv);
start=MPI_Wtime(); /*start timer*/

/*put the code you want to time here*/

finish=MPI_Wtime(); /*stop timer*/
MPI_Finalize();

printf("Parallel Elapsed time: %f seconds\n", finish-start);


text:
Q: Vichuploader File is not saved with post request my project is actually to create a website that permit me to post gif, jpg etc..
I'm using VichuploaderBundler to upload a file and save it to a specific repository in my app

#vich uploader Configuration
vich_uploader:
     db_driver: orm
     mappings:
        product_image:
            uri_prefix:         /images/posts
            upload_destination: '%kernel.root_dir%/../web/images/posts'
            namer:              vich_uploader.namer_uniqid
            inject_on_load:     false
            delete_on_update:   true
            delete_on_remove:   true

I'm creating an API to create and render ressources.
I'm trying to create a Post with a post request with postman.
In this Post i want to save an image throw vichuploader.(this had worked with a classical form).
Here is my problem :
My post is created thx to my postman request. But the file that i upload is not saved in the
                 /**
                 * @Rest\View(statusCode=Response::HTTP_CREATED)
                 * @Rest\Post("/posts")
                 */
                public function postPostsAction(Request $request)
                {
                    $post = new Post();
                    $post->setTitle($request->get('title'))
                        ->setDescription($request->get('description'))
                        ->setImageName($request->get('image_name'))
                        ->setImageFile($request->get('imageFile'))

                        // It is required that at least one field changes if you are using doctrine
                        // otherwise the event listeners won't be called and the file is lost
                        ->setUpdatedAt(new \DateTime());

                    $em = $this->get('doctrine.orm.entity_manager');
                    $em->persist($post);
                    $em->flush();

                    return $post;
                }

Thx for helping and feedback about my post.

A: I find how to fixed this, it was very simply in fact !
public function postPostsAction(Request $request)
{
    $post = new Post();
    $post->setTitle($request->get('title'))
        ->setDescription($request->get('description'))
        ->setImageName($request->get('image_name'))
        ->setImageFile($request->files->get('imageFile'))
        // It is required that at least one field changes if you are using doctrine
        // otherwise the event listeners won't be called and the file is lost
        ->setUpdatedAt(new \DateTime());

    // On fait appel à doctrine pour seter un id lors de la création en base
    $em = $this->get('doctrine.orm.entity_manager');
    $em->persist($post);
    $em->flush();

    return $post;
}

Thanks to the ->files statement my pictures are saved in the right directory


text:
Q: Cypress Test intercept normal method I build a component with Angular 14 and this component uses an external service that provides user data (first name and last name). The service is imported as npm dependancy.
When implementing this service, we call its method get customer data and store the result in a variable that is used throughout our component.
The internal service looks like that:

import { UserData, UserService } from 'externalService'

@Injectable({
  providedIn: 'root'
})
export class InternalService {

  private userData?: UserData;

  constructor(private userService: UserSerice) {}

  public async getUserData(): Promise<UserData> {
    this.userData = await firstValueFrom(this.userService.getProfileData();

    return this.userData;
  }
}

The internal Service an d its variable then is used in different components where user data is required.
Now I would like to e2e test this component in cypress. In order to cover multiple test scenarios, I created different fixtures, that include different user datas.
How can I mock the result of the getUserData()-method, to return my fixtures.
None of the methods calls an API endpoint or does any kind of network communication that might be intercepted. The future goal is, to fetch data from a redux store, which as WIP, atm.
Hope someone can help me.

A: Unlike jasmine/karma, Cypress is a framework independent UI testing tool. This means it is not meant to stub actual services from angular. However, you can mock most of the browser behaviours. In this case, it will really depend on what your underlying userService.getProfileData() does.
If the userService fetches its data from the redux store, you should firstly dispatch the value you expect in your browser's store.
cy.window().then(win => {
  if (win.store) {
      win.store.dispatch(...));
  }
});

If your current service is a WIP and does not implement the redux store yet, you can always rely on another browser feature that you can prefill and read from, such as your localStorage. If you manage to get the userService.getProfileData() to read from your localStorage, you can then mock your expected output via the localStorage as following:
cy.window().then(win => {
   if (win.store) {
     win.localStorage.setItem('key', 'value');
   }
});

NB: you can easily embed local storage commands to Cypress via the cypress-localstorage-commands NPM package, if you don't want to access the local storage maually.


text:
Q: Select multiple checked values from dropdown and display those values with a textbox besides them I have a drop down with checkboxes besides it. First I want to add a search button in the dropdown. Second, once values are selected, a submit button on clicked should display the selected values with a textbox besides it.

A: Instead of checkboxes you could select with multiple option.
I would recommend you to use select2 library for your requirement.
It provides search box along with multiple value selection and different styles also which is very handy because it's very difficult to style option tag in html.
Find below the select2 url:
https://select2.org/getting-started/installation


text:
Q: How to find formal adjoint operators for operators $\Gamma(E) \to \Gamma(T^*M \otimes E)$ Let $(M,g)$ be a Riemannian manifold and let $E \to M$ be a real vector bundle over $M$. Let $d_A = d+A$ be a covariant derivative on $E$. It is an $\mathbb R$-linear map $d_A \colon \Gamma(E) \to \Gamma(T^*M \otimes E)$. Then the formal adjoint map $d_A^*$ acts from $\Gamma(T^*M \otimes E^*)$ to $\Gamma(E^*)$. But how to find explicitely this map? I know the answer but I don't know how to obtain it. If we had $\Gamma(T^*M \otimes E^*) \cong \Gamma(T^*M \otimes E)$ and $\Gamma(E^*) \cong \Gamma(E)$ and if we had scalar products defined on these two spaces then I could obtain the answer starting from the formula $\langle d_A s, \omega \rangle = \langle s, d_A^* \omega \rangle$, where $s \in \Gamma(E)$, $\omega \in \Gamma(T^*M \otimes E)$ and $\langle \cdot , \cdot \rangle$ are corresponding scalar products, but it's not so clear for me what to do in the case when we have no scalar products in these spaces. I think that we need to give some sense to $\langle \cdot, \cdot \rangle$. Given $(s,v) \in \Gamma(E) \times\Gamma(E^*)$ we can define $\bigl(v(s)\bigr)_x = v_x(s_x)$ to be a $C^\infty$-function on $M$ so we can define $\langle s, v \rangle = \langle v(s) \rangle_{L_2(M)}$. On the other hand, given $(\omega \otimes s, \eta \otimes v) \in \Gamma(T^*M \otimes E) \times \Gamma(T^* M \otimes E^*)$ (locally)  we can define $\langle \omega \otimes s, \eta \otimes v\rangle = \int_M v(s) \omega \wedge *\eta$ and using these two expressions for $\langle \cdot , \cdot \rangle$ we can find formal adjoints as in the case of scalar product spaces. But are these considerations correct or there is some other way to find formal adjoint to $d_A$?

A: What you say makes sense, I just think you need to be a little bit careful with the "duality pairings". You need duality pairings $\Gamma(E) \times\Gamma(E^*) \rightarrow \mathbb{R}$ and $\Gamma(T^*M \otimes E) \times \Gamma(T^* M \otimes E^*) \rightarrow \mathbb{R}$ indeed.
I think what people consider the "canonical" duality pairings to be in this context is:
$$
\begin{array}{ccc}
\Gamma(E) \times\Gamma(E^*) & \rightarrow &\mathbb{R} \\
(s, v) &\mapsto & \int_M v(s) \, dvol_g
\end{array}$$
and
$$
\begin{array}{ccc}
\Gamma(T^*M \otimes E) \times \Gamma(T^* M \otimes E^*) & \rightarrow &\mathbb{R} \\
\langle \omega \otimes s, \eta \otimes v\rangle &\mapsto &
\int_M \langle \omega, \eta\rangle_g \,v(s) \, dvol_g
\end{array}$$
where here $\langle \omega, \eta\rangle_g$ is just (pointwise) the inner product on $T^*M$ derived from the inner product $g$ on $TM$.


text:
Q: Counting the number of people working at a given time I have data the shows when employees log in and when they log out. I call the duration they are logged in "Ready" time and the time they are logged off as "Not Ready" time. What I want to do is have a continuous, gradient timeline that shows how many people are in the ready state.
Some notes about the data:

*

*The data has a start time and an end time. Each record is unique for the employee and the start time?

*I unfortunately cannot post this data as it does not belong to me.

A: Let's say that your data is something like this
employee    start_time  end_time
E1  7/7/2017  10:03:10 AM   7/7/2017  18:03:10 AM
E2  7/7/2017  10:10:10 AM   7/7/2017  18:03:10 AM
E3  7/7/2017  10:13:10 AM   7/7/2017  18:03:10 AM
E1  7/7/2017  11:03:10 AM   7/7/2017  19:03:10 AM
E2  7/7/2017  10:30:10 AM   7/7/2017  18:03:10 AM

In that case I would follow these steps:

*

*Check if start_time & end_time columns are not in 'timestamp' format then right click it and go to 'Change data type' to select 'Date & Time'

*Create a parameter Select_Report_DateTime. In parameter window select Data  type = 'Date & Time'; Display format = 'Automatic'; Allowable values = 'All'

*Right click this parameter and select 'Show parameter control'

*Create calculated field default_date_time as #1/1/1900 12:00:00 AM#. If it's not in 'timestamp' format then right click it and go to 'Change data type' to select 'Date & Time'

*Create calculated field Report_DateTime_formatted as

IF [Select_Report_DateTime] == [default_date_time] then now()
ELSE [Select_Report_DateTime]
END

*

*Create a calculated field Users(inReadyState) as

IF (([Report_DateTime_formatted] >= [start_time]) &
    ([Report_DateTime_formatted] < [end_time])) THEN "Yes"
ELSE "No"
END

*

*Now drag Users(inReadyState) in 'Columns', CNT[employee] in 'Rows' and 'Marks' as Bar.

*You can very well play around with this model to get the o/p as per your specific requirement.

Don't forget to let us know if it helped :)


text:
Q: How to insert image from image control into WPF to SQL Database using entity data model i am creating an app to save student information into SQL , I want to know how to insert image from image control in WPF using entity framework to SQL database
i made event to upload image into image control and now i need to save it to sql database using entity framework
image load button code :
private void uploadbt_Click(object sender, RoutedEventArgs e)
 {
     OpenFileDialog op = new OpenFileDialog();
     op.Title = "Select a picture";
     op.Filter = "All supported graphics|*.jpg;*.jpeg;*.png|" +
         "JPEG (*.jpg;*.jpeg)|*.jpg;*.jpeg|" +
         "Portable Network Graphic (*.png)|*.png";
     if (op.ShowDialog() == true)
     {
         photo.Source = new BitmapImage(new Uri(op.FileName));
     }
 }

this is my database named cv

this is my code to save some information into database this cose for save button
facultymakerEntities1 entity = new  facultymakerEntities1();

         cv CV = new cv();
         CV.Full_Name = fullnametb.Text;
         CV.Activities = activitestb.Text;
         CV.Address = addresstb.Text;
         CV.Birth_Day = bddate.SelectedDate.Value;
         CV.Courses = cousetb.Text;
         CV.E_Mail = emailtb.Text;

         entity.cvs.Add(CV);
         entity.SaveChanges();

how can i save image from image control into database ?
thanks;

A: You will most certainly store an encoded image as byte[]. The following method creates a PNG frame from a BitmapSource:
private byte[] BitmapSourceToByteArray(BitmapSource image)
{
    using (var stream = new MemoryStream())
    {
        var encoder = new PngBitmapEncoder(); // or some other encoder
        encoder.Frames.Add(BitmapFrame.Create(image));
        encoder.Save(stream);
        return stream.ToArray();
    }
}

As you put BitmapImages to your Image's Source, you may simply pass that to this method:
var imageBuffer = BitmapSourceToByteArray((BitmapSource)photo.Source);

A: Image in SqlServer is "Variable-length binary data from 0 through 2^31-1 (2,147,483,647) bytes". In EF you need to have a property of byte[] type which can be mapped to a column of image type in SqlServer. When you load your image from disk don't load it to the BitmapImage but to a byte array, set the property accordingly and .SaveChanges() to store it in the database. If you want to show the image to the user load it from the database as byte array and then create a BitmapImage instance. You probably would have to use BimatpImage.StreamSource property to do that.


text:
Q: Aggregating CSV Records Using Python My CSV file looks like this:
Mike,6
Mike,5
Bill,3
Bill,1
Sally,4
Sally,2

I would like to amend it so the counts are summed by name and looks like this:
Mike,11
Bill,4
Sally,6

A: Look at the pandas library.
df = pd.read_csv('data.csv')
df_grouped = df.groupby('name').sum()

More detail here
http://pandas.pydata.org/pandas-docs/stable/groupby.html

A: def records_from_file(fname, column_names):
    with open(fname,'r') as input_handler:
    for line in input_handler:
        line = line.strip('\n') #strip out newline
        x={} #this creates x as an empty dictionary
        for i in range(len(column_names)):
            x[column_names[i]] = line.split(",")[i]  #append each key and value to the dictionary
        yield x

record_stream = records_from_file('names.csv',['name', 'count'])

class Object:                   #Object to store unique data
    def __init__(self, name, count):
        self.name = name
        self.count = count

rownum = 0 #Row Number currently iterating over
list = []  #List to store objects

def checkList(name, count):
    for object in list:  #Iterate through list
        count=int(count)
        if object.name == name:  #Check if name and produce combination exists
            object.count += int(count) #If it does add to amount variable and break out
            return
    newObject = Object(name, count) #Create a new object with new name, produce, and amount
    list.append(newObject)  #Add to list and break out

for record in record_stream:  #Iterate through all the rows
    name = record['name']  #Store name
    count = int(record['count']) #Store count
    checkList(name, count)

rownum += 1

for each in list: #Print out result
    print each.name,each.count

A: import pandas as pd

df = pd.read_csv('names.csv')
df.columns = ['name','count']
df_grouped = df.groupby('name').sum()
print df_grouped