text:
Q: DNS sub-domain migration from Digitalocean to Amazon route 53 can't be reached Our DNS qianalysis.com is hosted in Digitalocean. I need to move the subdomain aws.qianalysis.com to Amazon route 53 and point this subdomain to an Amzaon elastic-loadbalancer instance http://a1626874f2f1011e7937712000d3b863-200559730.us-east-1.elb.amazonaws.com. I have done the below steps according to do this documentation of Amazon route 53:
http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/CreatingNewSubdomain.html

*

*Created a hosted zone for the subdomain aws.qianalysis.com in amazon route 53.

*Then, created an A record set which alias the ELB instance stated above.

*After that I added the 4 Name Servers of the Amazon route 53 hosted zone aws.qianalysis.com in our main domain at Digitalocean as NS records. The Name Servers are: ns-842.awsdns-41.net., ns-244.awsdns-30.com., ns-1514.awsdns-61.org., ns-2015.awsdns-59.co.uk.
But if I now try to access aws.qianalysis.com through browser, the result is:
site can't be reached

aws.qianalysis.com took too long to respond.

After that I tried to do some troubleshoot to find out if the DNS was configured properly and have run the below queries:
$ nslookup aws.qianalysis.com
Server:     127.0.1.1
Address:    127.0.1.1#53

Non-authoritative answer:
Name:   aws.qianalysis.com
Address: 52.207.24.56
Name:   aws.qianalysis.com
Address: 34.202.99.171

$ nslookup a1626874f2f1011e7937712000d3b863-200559730.us-east-1.elb.amazonaws.com
Server:     127.0.1.1
Address:    127.0.1.1#53

Non-authoritative answer:
Name:   a1626874f2f1011e7937712000d3b863-200559730.us-east-1.elb.amazonaws.com
Address: 52.207.24.56
Name:   a1626874f2f1011e7937712000d3b863-200559730.us-east-1.elb.amazonaws.com
Address: 34.202.99.171

$ host -t ns aws.qianalysis.com
aws.qianalysis.com name server ns-1514.awsdns-61.org.
aws.qianalysis.com name server ns-2015.awsdns-59.co.uk.
aws.qianalysis.com name server ns-244.awsdns-30.com.
aws.qianalysis.com name server ns-842.awsdns-41.net.

$ dig +trace aws.qianalysis.com

; <<>> DiG 9.9.5-3ubuntu0.14-Ubuntu <<>> +trace aws.qianalysis.com
;; global options: +cmd
.           27722   IN  NS  m.root-servers.net.
.           27722   IN  NS  l.root-servers.net.
.           27722   IN  NS  f.root-servers.net.
.           27722   IN  NS  b.root-servers.net.
.           27722   IN  NS  e.root-servers.net.
.           27722   IN  NS  h.root-servers.net.
.           27722   IN  NS  i.root-servers.net.
.           27722   IN  NS  j.root-servers.net.
.           27722   IN  NS  g.root-servers.net.
.           27722   IN  NS  c.root-servers.net.
.           27722   IN  NS  a.root-servers.net.
.           27722   IN  NS  d.root-servers.net.
.           27722   IN  NS  k.root-servers.net.
.           27722   IN  RRSIG   NS 8 0 518400 20170516050000 20170503040000 14796 . gCBRAPt6Mu2qkxfuwDohzVqCpvUeVKZmnNSYWtl/8w9oF5YKsFpyBrvE OvbTO7hcdlz6Vpz0VqEkUUTvRlzD+HTj/s4CD8lg+I2p+9+mbK/CRjx1 uPhgNhWg+/ZaLTa5CPLbZGYfoyJhYcNKItmYpzbDQK6BJuZUhTetbjtF 8JgakLBcO7ptWzaLA0XwF7mVbbYK4IeFa7Ue2QfdQbaTsqiNm/ijGOTE pFhKQfeKI/4XlwAN+87QkKoPNDAjIYVQFbX9BeQd3i4PXa6Q3gJ4HHAr Weg6fjp363c6V4VJzA7LCSARq/ry4fuG1CoaX8jtkmeM49BYpp8GzpcC 0VvcHA==
;; Received 525 bytes from 127.0.1.1#53(127.0.1.1) in 4566 ms

com.            172800  IN  NS  a.gtld-servers.net.
com.            172800  IN  NS  b.gtld-servers.net.
com.            172800  IN  NS  c.gtld-servers.net.
com.            172800  IN  NS  d.gtld-servers.net.
com.            172800  IN  NS  e.gtld-servers.net.
com.            172800  IN  NS  f.gtld-servers.net.
com.            172800  IN  NS  g.gtld-servers.net.
com.            172800  IN  NS  h.gtld-servers.net.
com.            172800  IN  NS  i.gtld-servers.net.
com.            172800  IN  NS  j.gtld-servers.net.
com.            172800  IN  NS  k.gtld-servers.net.
com.            172800  IN  NS  l.gtld-servers.net.
com.            172800  IN  NS  m.gtld-servers.net.
com.            86400   IN  DS  30909 8 2 E2D3C916F6DEEAC73294E8268FB5885044A833FC5459588F4A9184CF C41A5766
com.            86400   IN  RRSIG   DS 8 1 86400 20170516050000 20170503040000 14796 . Ge+3ma50QY0R9ekOoiDuzGxpx5eT7euTgFWbA3qmwf0RdY3bTGDWHSt4 pcOCnO7es7Fr8mTkBSsVQXwfzk9L7dOb4nQ8TUTykRsP7UdYxLn9gIb6 Z//gtpb/BIKhieYXQgCKLDueGinJPFT+0tBN+k+hdgG7rY5xoU0yn/lm 9Wc6v0ElTe563IDUMnoa1OMCIj+wIEWO9YuFOXaPUEz8Uk/S5pNcTvcb MoKXcQFOwlbZU5208+fteMGQ2S2J4DTyDtxK/Ir4qA3w6HwABxCJpmn2 DIFQK2VOppKBaaxiUXvZvNu76SgTYYNgvDXGITLNVaLGUDv6TuTm303y +FLDCA==
;; Received 870 bytes from 192.203.230.10#53(e.root-servers.net) in 4418 ms

qianalysis.com.     172800  IN  NS  ns1.digitalocean.com.
qianalysis.com.     172800  IN  NS  ns2.digitalocean.com.
qianalysis.com.     172800  IN  NS  ns3.digitalocean.com.
CK0POJMG874LJREF7EFN8430QVIT8BSM.com. 86400 IN NSEC3 1 1 0 - CK0Q1GIN43N1ARRC9OSM6QPQR81H5M9A NS SOA RRSIG DNSKEY NSEC3PARAM
CK0POJMG874LJREF7EFN8430QVIT8BSM.com. 86400 IN RRSIG NSEC3 8 2 86400 20170509044753 20170502033753 27302 com. nv2pLmsvfV0zhb2xG3WCHTVrVnGMA+6Eb6BeHy/+omyHt+d/6jTq9BzF e+xLLHGj7ddu8ugKRcEP0KawgsMYvgaxLFQfTJIis1SvdQdybpOMqCfT e1MQM/OCauaRhqM8XQZIWolPPgYEpfMELfvW8b+xqVs8YfWJnyCWXdJQ 94s=
LER81PJG42CMP2MD94DCJVIJMNNFLDL4.com. 86400 IN NSEC3 1 1 0 - LERCERUAETGQB9VTEU76H1KTP6J0607R NS DS RRSIG
LER81PJG42CMP2MD94DCJVIJMNNFLDL4.com. 86400 IN RRSIG NSEC3 8 2 86400 20170509041957 20170502030957 27302 com. Wvwv68vG1/oBfNUrnp+KvP8LYMAOgTIYnqbvOrWn48MrfDpokXNzbIvu PJ9N8w0RUTZh/H6VsdpSLNVnO+xcii4lX6b9HyJC4H8KFy3//N57STjn BJZEEqs977mYLzNWQnBth0CJndLZ2PilQqBkPnknAVoJPlDpzyBjF3nm IfE=
;; Received 731 bytes from 192.5.6.30#53(a.gtld-servers.net) in 6894 ms

aws.qianalysis.com. 1800    IN  NS  ns-842.awsdns-41.net.
aws.qianalysis.com. 1800    IN  NS  ns-244.awsdns-30.com.
aws.qianalysis.com. 1800    IN  NS  ns-1514.awsdns-61.org.
aws.qianalysis.com. 1800    IN  NS  ns-2015.awsdns-59.co.uk.
;; Received 184 bytes from 173.245.58.51#53(ns1.digitalocean.com) in 4818 ms

aws.qianalysis.com. 60  IN  A   52.207.24.56
aws.qianalysis.com. 60  IN  A   34.202.99.171
aws.qianalysis.com. 172800  IN  NS  ns-1514.awsdns-61.org.
aws.qianalysis.com. 172800  IN  NS  ns-2015.awsdns-59.co.uk.
aws.qianalysis.com. 172800  IN  NS  ns-244.awsdns-30.com.
aws.qianalysis.com. 172800  IN  NS  ns-842.awsdns-41.net.
;; Received 216 bytes from 205.251.192.244#53(ns-244.awsdns-30.com) in 104 ms

Seems like everything is configured properly. But can find out the main reason behind not being able to access the subdomain aws.qianalysis.com and how to solve this.


text:
Q: Getting Promise pending ..- ES6 I am trying to capture the response of two service calls within a function. Got to know that async and await will solve this purpose and tried below.
Here inside async function ex - I am making a call to users, companies end point and console log is displaying perfect, but while retrieving the same value by calling the async function is giving Promise Pending. I tried two options
1. by simply calling the async function - giving Promise Pending
2. by calling with await prefixed - giving await is a reserved word.
Please let me know how to capture the response from this...
  const service = {
    getUsers: () => axios.get(`http://localhost:3000/users`),
    getCompanies: () => axios.get('http://localhost:3000/companies')
  };

  let ex = async () => {
    let users = {};
    let companies = {};
    try {
       users =   await service.getUsers()
       companies = await  service.getCompanies()

      console.log('Example ', {
        users: users.data,
        companies: companies.data
      })

    } catch (err) {
      console.log(err);
    }
    return  { users, companies};
  };
  //let resp = await ex(); - Giving await is a key word
   let resp = ex(); - Giving Promise pending
  console.log(resp);

A: async/await doesn't magically allow you to perform asynchronous operations synchronously. Any way you cut it, you still wind up having to await the value at some point.
So you have two options.

*

*Put the stuff you want to do with the retrieved values in the asynchronous function:

let ex = async () => {
    let users = {};
    let companies = {};
    try {
        users =   await service.getUsers()
        companies = await  service.getCompanies()

        // DO STUFF WITH users AND companies HERE

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

*Call .then on the promise that ex() returns and use the returned values:

ex().then(values => {
    console.log(values);
});

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to check if a row of the first column is similar to the second? I use the query
Select t1.name as first, t2.name as second From products t1, products t2

that creates two columns like below. (A,B are for explaining purposes)
Before the query
-name-
A
B
C
D
E

After the query
-first- -second-
A        A
B        A
C        A
D        A
E        A
A        B
B        B
C        B
D        B
E        B

How to check if a row of the first column is similar to the second ?
UPDATE
I run mySQL
With similar, I mean like to find their similarity percentage are more of a specified value. Like if the first contains this is a string and second i wear a string there is a percentage of similarity. If this % is more than 70 then they are similar.

A: there are many ways, here is one that will give you all the products that match your criteria (first = second)
SELECT
  t1.name AS first, t2.name AS second
FROM
  products t1, products t2
WHERE
  t1.name = t2.name

or, if you need all the values
Select
  t1.name as first t2.name as second, (if t1.name = t2.name THEN 1 ELSE 0) as match
From
  products t1, products t2

A: OK, here's what to do.

*

*run the select script like you do to get all possible
combinations you want to calculate.

*make a php script that loops
through each of these and calculates the percentage of similarity by
using similar_text function in php
(http://www.php.net/manual/en/function.similar-text.php)

*write all three values to a new table

*now just query the new table
getting all rows where the percent is greater than 70.


text:
Q: ClassCastException : cannot be cast to class and are in unnamed module of loader 'app' I am trying to build a simple email sending application in visual studio code.
The tutorial that I am following is this:
https://www.technicalkeeda.com/spring-boot-tutorials/how-to-send-email-using-spring-boot
When I run my project I am getting this exception error:
Exception in thread "main" java.lang.ClassCastException: class
MailServiceImplementation cannot be cast to class
MailService
MailServiceImplementation and
MailService are in unnamed module of loader 'app')

To see my MailService and MailServiceImplementation classes, please visit the above mentioned link. Kindly help me with this error.


text:
Q: Remember non-recursive function result I have a costly non-recursive function and I would like to memorize the result to a dictionary thus saving time by checking the result in the dictionary.
The function has 3 parameters:
def slow_func(a,b,c)

Currently, I'm saving an object in a deque:
memory = deque([], 1000)
...
{(a,b,c):result}, {(a,b,c):result}, {(a,b,c):result}

and I check if (a,b,c) is in the dictionary then show the result.
Is there a faster way to save the result?
Edit:

*

*The inputs are different almost 40% of the time.

*Inputs a and b are numpy.ndarray

*return is numpy.ndarray

A: Edit: OP has updated the question to include datatypes, but I am leaving the answer up as it can be useful for others.
If the datatypes of a,b,c are not mutable (tuples are ok, lists are not) there is a built in function decorator for this:
from functools import lru_cache

@lru_cache(maxsize=None)
def slow_func(a,b,c):
      ....

A: In order to use caching with types like numpy.array as function parameter, which is mutable and not hashable, one can use the following solution:
from functools import lru_cache, wraps
import numpy as np

def np_cache(*args, **kwargs):
    """LRU cache implementation for functions whose FIRST parameter is a numpy array"""
    def decorator(function):
        @wraps(function)
        def wrapper(np_array, *args, **kwargs):
            hashable_array = array_to_tuple(np_array)
            return cached_wrapper(hashable_array, *args, **kwargs)

        @lru_cache(*args, **kwargs)
        def cached_wrapper(hashable_array, *args, **kwargs):
            array = tuple(map(tuple, np_array))
            return function(array, *args, **kwargs)

        def array_to_tuple(np_array):
            """Iterates recursivelly."""
            try:
                return tuple(array_to_tuple(_) for _ in np_array)
            except TypeError:
                return np_array

        # copy lru_cache attributes over too
        wrapper.cache_info = cached_wrapper.cache_info
        wrapper.cache_clear = cached_wrapper.cache_clear

        return wrapper

    return decorator

Usage:
array = np.array([[1, 2, 3], [4, 5, 6]])

# use decorator to cache
@np_cache(maxsize=256)
def multiply(array, factor):
    print("Calculating...")
    return factor*array

# execute function once
multiply(array, 2)

Calculating...
array([[ 2,  4,  6], [ 8, 10, 12]])

# execute function twice
multiply(array, 2)

Calculating...
array([[ 2,  4,  6], [ 8, 10, 12]])

multiply.cache_info()

CacheInfo(hits=1, misses=1, maxsize=256, currsize=1)

git code here.


text:
Q: Order wordpress post by custom field value? Currently i have tried half internet codes ( :D ) to make this work, but with no luck.
I'm not a wordpress guru so it's quite bit hard. Basically what i want is to make plugin that will alter all post ordering across all wordpress blog based on date value in custom field.
For example i add custom field to each post (meta_key=bb_history) and (meta_value=2011-04-03).
So where i would hook or what filter should i use to get this working somehow? I guess you can use posts_where, posts_join, posts_orderby actions to make something?

A: You don't want a plug-in. Just edit your query_posts statement in the template in question.
query_posts($query_string . '&meta_key=YOURFIELDNAME');


text:
Q: Docker Running the Java -JAR file to create Cassandra KeySpaces. But its not creating I tried to run the CMD "java -jar /tmp/migration.jar update_schema atlas " to create the Keyspace in the cassandra.  But its not creating any keyspaces in cassandra.   But if i run same command in the command line its creating any idea whats the issue?
My dockerfile is as follows
    'FROM tomcat:8-jre8
ENV LANG en_US.UTF-8
ENV COMMAND="update"
ENV ARGS="--logLevel=debug"

WORKDIR  /usr/local/tomcat/

ADD /migration.jar /tmp
ADD atlas_migration.sh /usr/local/bin/atlas_migration.sh
CMD ["/bin/sh", "/usr/local/bin/atlas_migration.sh"]

CMD ENTRYPOINT ["java","-jar","/tmp/migration.jar","update_schema", "atlas"]
CMD java -jar /tmp/migration.jar update_schema atlas

ENV CATALINA_OPTS "-Xmx256m -Xms192m"

EXPOSE 8085

CMD ./bin/catalina.sh start  &&   tail -f ./logs/catalina.out'

A: CMD is for specifying the command the container should run when it starts. If you want to run a command during the build, so the state after execution is persisted in the image, you need to use RUN.
COPY is also preferable to ADD, so the relevant instructions should be:
COPY /migration.jar /tmp
COPY atlas_migration.sh /usr/local/bin/atlas_migration.sh
RUN /usr/local/bin/atlas_migration.sh
RUN ["java","-jar","/tmp/migration.jar","update_schema", "atlas"]


text:
Q: Exception with javascript_include_tag with Phusion Passenger in Rails In my Rails app. the javascript_include_tag seems to work fine in my localhost (mogrel) but I move to production(Phusion Passenger) it seems to behave differently and I get the following exception: (not sure what it's asking for all.js!!)
A ActionView::TemplateError occurred in posts#show:

  Permission denied - /var/www/war/releases/20091021160940/public/javascripts/all.js
  On line #9 of app/views/layouts/base_posts.html.erb

    6:     <%= stylesheet_link_tag 'prototube/prototube', :media => 'all' %>
    7:     <%= stylesheet_link_tag 'flowplayer', :media => 'all' %>
    8:
    9:    <%= javascript_include_tag :defaults, 'jquery','jquery.tools.min', 'thickbox', 'truncator', :cache=>true %>
    10:     <script type="text/javascript" src="/javascripts/prototube.js"></script>
    11:     <script type="text/javascript" src="/javascripts/swfobject.js"></script>
    12:     <script type="text/javascript" src="/javascripts/scriptaculous.js?load=effects"></script>

any ideas?
Thanks,
Tam

A: Check the permissions on that directory on your server. When :cache => true, Rails will create a combined javascript file to serve (to save client HTTP requests).
See http://api.rubyonrails.org/classes/ActionView/Helpers/AssetTagHelper.html#M001713


text:
Q: RoboVM: missing signing identity I have an app developed using libGDX and porting to iOS using robovm. This was working perfectly. I then updated my provisioning profile to allow export to another device. When doing this, I was now getting 2 provisioning profiles with the same name listed in robovm, so I used 'iPhone configuration utility' to delete them and then readded the provisioning profile. Now, when I look in xCode it shows my provisioning profile, my signing ID etc all perfectly fine. If I run the command "security find-identity -v -p codesigning" it lists my signing ID perfectly fine. But in eclipse when I go to RoboVM > Package for App STore/Ad Hoc distribution the Signing Identity dropdown no long contains my ID and if I try to enter it manually it can't find it.
I have checked my keychain and I have the certificate in there. I have tried restarting both xcode and eclipse multiple times. This was all working perfectly before I used iphone configuration utility.

A: If you are using the gradle setup (which you should) then open up your build.gradle file (in the ios project, NOT the root file) and put this at the bottom of the file:
robovm {
iosSignIdentity = "your signing identity"
iosProvisioningProfile = "your provisioning profile"
iosSkipSigning = false
stdoutFifo = ""
stderrFifo = ""

}
Just put in the names exactly as they are named in the developer center.
This might then work through eclipse's roboVM export option but if it doesn't then go to your project folder with the commandline and run:
gradlew ios:createIPA

or if on MacOSX
./gradlew ios:createIPA

and if you don't have permissions to use ./gradle you need to add permissions for it using:
chmod +x ./gradlew


text:
Q: Does output voltage of a boost converter depend on load current in CCM? In the thread below, there are different opinions whether output voltage of a boost converter operating in continuous conduction mode (CCM) depends on load current or not.
Boost Converter Output Voltage dependence
Opinion 1: output voltage only depends on input voltage and duty cycle
Vout = Vin/(1-D)
Opinion 2: output voltage depends on input voltage, duty cycle and load current.
For example, as load current increases the duty cycle should also increase to make up the extra energy delivered to load.
So which one is right?
If output voltage doesn't depend on load current, then why do we need controller?
When the load current increases, the averaged inductor current should also increases. So how do we do that?

A: With a boost converter you need to transfer energy to the load by charging an inductor with energy and then releasing that stored energy. In CCM, inductor current never falls to zero so the energy transferred is dependant on the peak current and the min current.
What the current peaks at during charging represents the maximum inductor stored energy and, what the current drops to (during load replenishment) represents the energy left in the inductor just as the cycle repeats.
The difference in energy is what is "given" to the load.
For a fixed value inductor and input power supply voltage, the rate at which current linearly rises (di/dt) is constant and depends entirely on V = L di/dt, that well-known formula. I'm assuming perfect lossless components of course!
So, Imax, for a given operating frequency will always end-up at some fixed-value above Iaverage and, Imin will be the same fixed-value below Iaverage. We could call that fixed value Ipeak.
So, energy given to the load, W is: -
\$\dfrac{L}{2}[I_{MAX}^2-I_{MIN}^2]\$
Re-arranging using \$I_A\$ and \$I_P\$
W = \$\dfrac{L}{2}[(I_A+I_P)^2-(I_A-I_P)^2]\$
where \$I_A\$ is average current and \$I_P\$ is the peak above (or below) \$I_A\$. You also might be able to get to this formula (hopefully): -
W = \$2L\cdot I_A\cdot I_P\$
This means that both the average current and the peak current determines the energy transfered to the load. But, for a given input supply voltage, operating frequency, duty cycle and inductor value you cannot control \$I_P\$.
So, if the load resistance increases in value BUT you wanted to keep the average output voltage the same, the only option (other than D) is to increase operating frequency to reduce the peak current attained by the inductor during charging. This of course reduces average current gradually over a few cycles and what you find, in some controllers, is that the average current becomes lower and the frequency slews back to the original value.
More load current means lower frequency, less load current means higher frequency.
At the end of the day, I believe you still need a "clever" controller (to alter frequency) so I'm not sure that this question and the optional answers have much bearing on the practical world.
That's the way I see it anyway. Good (but flawed) question!!

A: The answer is: it all depends.  Here is an easy way to determine everything.  We will assume perfection (no resistive or diode switching losses).
When you close the switch, it is easy to calculate the amount of current increase in the inductor.  Because V = L di/dt then di/dt = V/L.  di/dt is in amperes/second (dt is the amount of time the switch is open each cycle).  Similarly, assuming the output is a stable voltage, you can calculate the current decrease when you close the switch in the same manner, except this time the voltage is (Vin - Vout), and the time is the "off" time.
So the rules are: the current increase has to equal the current decrease, so input voltage, output load, and duty cycle all affect the output voltage at the point the load changes.  Consider that in discontinuous mode we are closing the switch and filling a bucket with energy, then opening the switch and pouring it all out into the load.  However, in continuous mode, we are filling up the bucket when the switch closes, then pouring out only a portion of it.  In continuous mode, there is always a partially full bucket (a partially charged inductor.)
To increase the load current, the switch will have to stay closed longer, so that the bucket will rise to a new level.  Once this occurs, the duty cycle will return to the original steady state value regardless of the load.
So in answer to your two questions:
Question 1. Opinion 1 is correct if you are considering the steady state condition with a theoretical device;  Opinion 2 is correct during startup, varying load, varying input voltage, and the effects of losses.
Question 2. Make sure you have a big enough bucket!  The inductor current will rise and fall as the switch opens and closes.  Remember that at the peak current, you must not saturate, and if the inductance sized incorrectly (too small value), the current will rise too quickly and you will go into discontinuous mode, or conversely (too large value), the system will not regulate well.

A: Ideally, the output voltage of a buck converter running in continuous mode is a multiple of the input voltage, with that multiple dependent only on the duty cycle.
However, back here in the real world it's hard to find those ideal diodes with no forward voltage drop, inductors with no series resistance, and capacitors with no losses.  The various non-idealities cause some voltage drop with higher current.
The usual solution is to close the loop to control the duty cycle to whatever it takes to achieve the desired output voltage.  With good parts, that duty cycle will remain largely constant for a particular combination of input and output voltage.  However, it will go up some with higher output current.  That's because the control loop has to push the circuit a little harder to compensate for the inevitable losses.
For a boost converter, it's more complicated.  Unlike with a buck converter, the duty cycle is a tradeoff between enough time to store energy in the inductor, and enough time to deliver the stored energy to the load.  100% duty cycle, for example, continuously charges up the inductor but never delivers anything to the output.
However, there is still a fixed voltage ratio between input and output that is only a function of the duty cycle with ideal components.  For a buck converter, if D is the fraction of the time the inductor is connected to the input voltage and the inductor is connected to ground the remaining time (1-D), then the ratio of output voltage to input voltage is simply D.
    Vout / Vin = D
Now think of a boost converter as the buck converter run in reverse.  That means Vout and Vin are swapped.  It also means with consider the "on" time of the inductor when it is connected to ground, not Vout.  Therefore D of a boost converter is 1-D of the same thing viewed as a buck converter.
Applying all this flipping from buck to boost to the equation above, yields the equation for a boost converter:
    Vin / Vout = 1 - D
Rearranging this to tell us what the output to input voltage ratio is yields:
    Vout / Vin = 1 / (1 - D)
This is easier to see by analyzing a simplified switching converter:

First let's consider this a buck converter.  You stipulated continuous mode, so the switch always either connects the left side of the inductor to VA or ground.  The result is a simple low pass filter.
However, this same circuit works in reverse as a boost converter.  With the switch always connected to one of the two choices and no diode, this is really a DC transformer.  It works the same way for either buck (input is VA, output is VB) or boost (input is VB, output is VA).  If we consider the duty cycle to be the fraction of time that the switch is connected to VA, then VB is simply the duty cycle times VA.  That's the buck converter view.
The relationship works identically in reverse.  VA is VB divided by the duty cycle.  The only difference for typical boost converter analysis is that we usually consider the duty cycle the fraction of the time the switch is connected to ground instead of VA.  In other words, we use 1-D relative to what we call "duty cycle" for a buck converter.
Now before you complain that this is unfair because the diode is missing and that current can run backwards thru the inductor, remember that you stipulated the converter was running in continuous mode.  The duty cycle, input and output voltage ratios, and output current demand are such that the current is always flowing in the inductor.  If you knew this was always true, you could remove the diode.
The circuit as shown, without a diode, does actually work both ways, and inductor current can flow either direction.  This is basically a "DC transformer", with the voltage ratio strictly a function of the duty cycle, no matter which way you define it.

A: I had a similar doubt regarding buck converter i.e., whether the output voltage is determined by the duty ratio alone.
The theory says, for an ideal buck converter under steady state conditions and in CCM mode, the output voltage is governed only by duty ratio and not on the load resistor (or load current).
I did a simulation to confirm this. The load is switched from 5 ohm to 1 ohm at 0.5 ms. Duty ratio is maintained constant at 0.5 throughout the simulation.
The simulation results are as follows:

It clearly proves that the inductor current gets modified as per the load current demand and reaches a new steady state accordingly. The output voltage also goes through a transient, but comes back to the original steady state values
The simulation model used is as follows. Please note there is no feedback controller employed and the variable loading is simulated using a voltage controlled switch having on and off resistance as desired.

When the load current increases, the averaged inductor current should
  also increases. So how do we do that?

All I can say is every power converter has a unique equilibrium condition ( also called steady state condition), where the energy inflow (in either Ton or Toff duration) becomes equal to energy outflow (in the other duration). As long as it is not in equilibrium, the system naturally drifts towards the equilibrium state. This is what happens when a load change happens. During transient time, the energy intake in an inductor is not matching with energy outflow, which results in a build of inductor energy.
I just want to caution, if you try to do the opposite action , ie, reduce the load current (increase load resistance) the above conclusion (constant o/p voltage independent of load current) need not hold good. The reason being as the load current decreases the converter may enter Discontinuous conduction mode (DCM) and  o/p voltage is dependent on load current in DCM.

A: I see that most of the people have answered your question in a very satisfactory way, at least for me. But, I can add here a more simplification toward your ambiguity. IN CCCM, it is assumed that in a lossless circuit, the relation between input/output is given by: Vout = Vin/(1-D)
Now, run any circuit simulator with an ideal circuit components (means that whatever the components you are using, switches, diodes, capacitors or even inductors are all ideal) and adjust your duty cycle for the given Vin and the required Vout. No mater how much you are loading your boost converter, the output will be more or less the same. Your hard day starts once you include a lossy component in your circuit, then the output load is becoming involved. That's simply because the relation Vout = Vin/(1-D) has originally been developed based on the assumption of a lossless circuit components, which means that the equation doesn't count for the losses. More current means more conduction loss (also known as: copper loss), it counts as (I·I·R) the square of the of your average output current. Here comes the importance of a controller to correct the duty-cycle to ensure a constant output voltage at any loading condition, provided that the controller is able to switch the converter from near 0% to near 100% of duty-cycle.

A: Clarification: "CCM" stands for Continous Conduction Mode, meaning that the current through the inductor of the boost converter never has a chance to decay to zero. This is in contrast with DCM (Discontinuous Conduction Mode), where there is no current flowing for a part of the cycle. Boost (and buck) converters with diode rectification operate in DCM under light loads, and transition into CCM as the load increases.

Opinion 1: output voltage only depends on input voltage and duty cycle
Vout = Vin/(1-D)

This is true, assuming an ideal boost converter in CCM. The output voltage (Vout) of an ideal boost converter operating in CCM is only dependant on the duty cycle (d) and input voltage(Vin), not current:
Vin / Vout = 1 - d
That said, reducing the load current enough will eventually cause the converter to operate in DCM (unless it employs synchronous rectification), where the load current has a great effect on the output voltage. Also, the output voltage of any practical boost converter will be slightly affected by the load current even in CCM, mainly due to the parasitic resistances in the circuit.


text:
Q: AWS, Express.js - Setting server to production I'm developing my app locally and running on an EC2 instance on AWS. I'm wanting to differentiate between production and development and added this to my main.js file:
switch (app.settings.env) {
  case 'production':
    app.locals.base = 'example1.com';
    break;
  case 'development':
    app.locals.base = 'example2.com:8081';
    break;
  default:
}

Both my local and remote install of the app use development's declaration for app.locals.base. How can I "mark" my AWS instance as the production environment so that my app recognizes it?
NOTE: I tried adding this in my AWS Console
$ echo export NODE_ENV=production >> ~/.bash_profile
$ source ~/.bash_profile

And the contents of .bash_profile
# .bash_profile

# Get the aliases and functions
if [ -f ~/.bashrc ]; then
    . ~/.bashrc
fi

# User specific environment and startup programs

PATH=$PATH:$HOME/bin

export PATH
export NODE_ENV=production


text:
Q: volumes not working with Datapower and docker I am using docker datapower image for local development. I am using this image
https://hub.docker.com/layers/ibmcom/datapower/latest/images/sha256-35b1a3fcb57d7e036d60480a25e2709e517901f69fab5407d70ccd4b985c2725?context=explore
Datapower version: IDG.10.0.1.0
System: Docker for mac
Docker version 19.03.13
I am running the container with the following config
docker run -it \
-v $PWD/config:/drouter/config \
-v $PWD/local:/drouter/local \
-e DATAPOWER_ACCEPT_LICENSE=true \
-e DATAPOWER_INTERACTIVE=true \
-p 9090:9090 \
-p 9022:22 \
-p 5554:5554 \
-p 8000-8010:8000-8010 \
ibmcom/datapower

when I create files in file management or save a DP object configuration I do not see the changes reflected in the directory on my machine
also I would expect to be able to create files on my host directory and see them reflected in /drouter/config + /drouter/local in the container as well as in the management GUI
the volume mounts don't seem to be working correctly or perhaps I misunderstand something about Datapower or Docker
I have tried mounting volumes in other docker containers under the same path and that works fine so I don't think its an issue with file sharing settings in docker.

A: The file system structure changed in version 10.0. There is some documentation in the IBM Knowledge Center showing the updated locations for config:, local:, etc., but the Dockerhub page is not updated to reflect that yet.

A: mounting the volumes like this fixed it for me
-v $PWD/config:/opt/ibm/datapower/drouter/config \
-v $PWD/local:/opt/ibm/datapower/drouter/local \

It seems the container is persisting configuration here instead. This is different than the instructions on dockerHub


text:
Q: pip install django timeout on MacOSX Lion On a MBP, following instructions (http://techblog.rosedu.org/python-environment.html), I installed Xcode 4.4.1, brew (brew doctor says all set), and then python. Next, I tried to setup virtualenv:
> $MYPYTHON/bin/python distribute_setup.py
> $MYPYTHON/bin/easy_install pip
> $MYPYTHON/bin/pip install virtualenv

I then created a virtual environment and tried to install django:
> $MYPYTHON/bin/virtualenv $MYENV
> $MYENV/bin/pip install Django

It downloads 98% and then hangs for a while, and finally I get a traceback indicating a timeout:
pcm@pcm-mac[302]% $MYENV/bin/pip install django
Downloading/unpacking django
  Downloading Django-1.4.1.tar.gz (7.7Mb): 7.5Mb downloaded
Exception:
Traceback (most recent call last):
  File "/Users/pcm/Documents/workspace/virtual/lib/python2.7/site-packages/pip-1.1-py2.7.egg/pip/basecommand.py", line 104, in main
    status = self.run(options, args)
  File "/Users/pcm/Documents/workspace/virtual/lib/python2.7/site-packages/pip-1.1-py2.7.egg/pip/commands/install.py", line 245, in run
    requirement_set.prepare_files(finder, force_root_egg_info=self.bundle, bundle=self.bundle)
  File "/Users/pcm/Documents/workspace/virtual/lib/python2.7/site-packages/pip-1.1-py2.7.egg/pip/req.py", line 985, in prepare_files
    self.unpack_url(url, location, self.is_download)
  File "/Users/pcm/Documents/workspace/virtual/lib/python2.7/site-packages/pip-1.1-py2.7.egg/pip/req.py", line 1109, in unpack_url
    retval = unpack_http_url(link, location, self.download_cache, self.download_dir)
  File "/Users/pcm/Documents/workspace/virtual/lib/python2.7/site-packages/pip-1.1-py2.7.egg/pip/download.py", line 451, in unpack_http_url
    download_hash = _download_url(resp, link, temp_location)
  File "/Users/pcm/Documents/workspace/virtual/lib/python2.7/site-packages/pip-1.1-py2.7.egg/pip/download.py", line 368, in _download_url
    chunk = resp.read(4096)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/socket.py", line 380, in read
    data = self._sock.recv(left)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/httplib.py", line 553, in read
    s = self.fp.read(amt)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/socket.py", line 380, in read
    data = self._sock.recv(left)
timeout: timed out

I see the same thing, if I just run the version of pip from /usr/local/bin/.  I tried other packages (selenium, mock) and they downloaded and installed fine.
I'm at a loss as to what I may be doing wrong, or if there is some issue with django installs via pip. Advice?

A: Use:
pip --default-timeout=60 install django


text:
Q: Shell Script: Passing Wrapper Parameters to Underlying Script I have created a wrapper which can execute a given script over SSH with following parameters
sshwrapper.sh <server> <script with path> <username> <password>

Now i want to invoke the following scripts:
start.sh param1 param2 param3 param4

stop.sh param1 param2 param3

using the same wrapper.
Is it possible to have a mechanism where after passing the essential parameters to wrapper script I can post remaining parameters to underlying script?
i.e. I would like to achieve following notation:
Examples:
sshwrapper.sh server start.sh username password param1 param2 param3 param4

should invoke
start.sh param1 param2 param3 param4

and
sshwrapper.sh server stop.sh username password param1 param2 param3

should invoke
stop.sh param1 param2 param3

in a generic manner.

A: Use shift and "$@":
SERVER="$1"
SCRIPT="$2"
USERNAME="$3"
PASSWORD="$4"
shift 4

"$SCRIPT" "$@"

Example:
$ cat sshwrapper.sh
#!/bin/sh

SERVER="$1"
SCRIPT="$2"
USERNAME="$3"
PASSWORD="$4"
shift 4

echo "$SCRIPT" "$@"

$ ./sshwrapper.sh server stop.sh username password param1 param2 param3
stop.sh param1 param2 param3

Using shift you can remove first arguments from command line and shift the rest:
$ set 1 2 3 4 5
$ echo "$@"
1 2 3 4 5
$ shift 3
$ echo "$@"
4 5

You see here that shift 3 removed first three arguments.

A: I have used ssh to execute scripts on remote servers previously, but to make my life easy I set up public-key authentication to allow password-less access.
See this article for reference
http://macnugget.org/projects/publickeys/
You can execute remote scripts with parameters using the default ssh tool from the command line as follows
$ ssh user@server "script.sh param1 param2 param3"

Multiple commands can be executed as follows
$ ssh user@server "script1.sh param1 param2 param3; script2.sh param1 param2 param3"

E.g - Loginto a remote server and print date and get a list of running processes
$ ssh user@server "echo date; ps -ef | grep hello"

You can add the above logic to your script, assuming you want to call this as part your ssh-wrapper, or execute directly from the command line.
Just ensure you use "double quotes" instead of 'single' in the ssh section.


text:
Q: facebook share doesn't work, when click share from the action bar I've used the below code to place a share button in the action bar, well to share particular text. When I click share, it works with messaging and email etc but when I click facebook. Facebook is opened on the create status bit, although the share text  from my below code is not there.
What have I done wrong? Or is there something I need to add or change?
XML:
 <?xml version="1.0" encoding="utf-8"?>
    <menu xmlns:android="http://schemas.android.com/apk/res/android" >
        <item android:id="@+id/menu_item_share"
            android:showAsAction="ifRoom"
            android:title="Share"
            android:actionProviderClass="android.widget.ShareActionProvider" />
    </menu>

ActivityMain:
   @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.action_bar_share_menu, menu);
        MenuItem item = menu.findItem(R.id.menu_item_share);
        ShareActionProvider myShareActionProvider = (ShareActionProvider) item.getActionProvider();
        Intent myIntent = new Intent();
        myIntent.setAction(Intent.ACTION_SEND);
        myIntent.putExtra(Intent.EXTRA_TEXT, "Whatever message you want to share");
        myIntent.setType("text/plain");
        myShareActionProvider.setShareIntent(myIntent);
        return true;
    }

A: Facebook might be looking for the EXTRA_SUBJECT.
Untested too many trolls on FB.
private Intent createShareIntent() {
    Intent shareIntent = new Intent(Intent.ACTION_SEND);
    shareIntent.setType("text/plain");
    String s = getString(R.string.shareText);
    shareIntent.putExtra(Intent.EXTRA_TEXT, s);
    s = getString(R.string.sharesubject);
    shareIntent.putExtra(Intent.EXTRA_SUBJECT, s);
    return shareIntent;
}

using appcompat actionbar.
    MenuItem menuItem = menu.findItem(R.id.menu_item_share);

    // Fetch and store ShareActionProvider
    mShareActionProvider = (ShareActionProvider) MenuItemCompat
            .getActionProvider(menuItem);

    mShareActionProvider.setShareIntent(createShareIntent());


text:
Q: Can we able to create a new Xamarin forms project using command line tool? I want to create a Xamarin Forms App using command line tool. I am new to Xamarin and need guidance. Thanks in advance.

A: If you want to do it in the command line you could use MvxScaffolding as it has a dotnet CLI version
Installation guide is here

dotnet new --install MvxScaffolding.Templates

Then use the Xamarin.forms mvvmcross template, detailed here

dotnet new mvxforms --help

Here are some other dotnet templates also here
The prism one is forms too

dotnet new -i "Prism.Forms.QuickstartTemplates::*"


text:
Q: Exception at the time of GWT compile When I Build the project with GWT Compiler then I found exception on console:
MyConsole:
Compiling module com.ems.EMSWeb
   Compiling 5 permutations
      Compiling permutation 0...
      Compiling permutation 1...
      Compiling permutation 2...
      Compiling permutation 3...
      Compiling permutation 4...
   Compile of permutations succeeded
Linking into D:\Workspace3\EMSWeb\war\emsweb
   Linking public artifacts into D:\Workspace3\EMSWeb\war
      Emitting resource 0A9476898799A150D840F0B1C3672921.cache.png
         [ERROR] Fatal error emitting this artifact
java.io.FileNotFoundException: D:\Workspace3\EMSWeb\war\emsweb\0A9476898799A150D840F0B1C3672921.cache.png (Access is denied)
    at java.io.FileOutputStream.open(Native Method)
    at java.io.FileOutputStream.<init>(FileOutputStream.java:194)
    at java.io.FileOutputStream.<init>(FileOutputStream.java:145)
    at com.google.gwt.dev.util.OutputFileSetOnDirectory$1.<init>(OutputFileSetOnDirectory.java:54)
    at com.google.gwt.dev.util.OutputFileSetOnDirectory.createNewOutputStream(OutputFileSetOnDirectory.java:54)
    at com.google.gwt.dev.util.OutputFileSet.openForWrite(OutputFileSet.java:57)
    at com.google.gwt.core.ext.linker.impl.StandardLinkerContext.produceOutput(StandardLinkerContext.java:496)
    at com.google.gwt.dev.Link.doProduceOutput(Link.java:393)
    at com.google.gwt.dev.Link.link(Link.java:177)
    at com.google.gwt.dev.Compiler.run(Compiler.java:235)
    at com.google.gwt.dev.Compiler.run(Compiler.java:177)
    at com.google.gwt.dev.Compiler$1.run(Compiler.java:149)
    at com.google.gwt.dev.CompileTaskRunner.doRun(CompileTaskRunner.java:87)
    at com.google.gwt.dev.CompileTaskRunner.runWithAppropriateLogger(CompileTaskRunner.java:81)
    at com.google.gwt.dev.Compiler.main(Compiler.java:156)
   Link succeeded
   Compilation succeeded -- 96.563s

Please give me suggestion, why this exception i am facing.
Any solution?

A: Probably some application using this file while you trying to write into.
Check if there any application reads this file or maybe you don't have administrative rights?
Or try to delete these cache files if nothing helps.


text:
Q: How to debug "Problems occurs on injecting env vars as a build wrap: null" I use Groovy to inject variables into the build process using "EnvInject Plugin" plugin:
https://wiki.jenkins-ci.org/display/JENKINS/EnvInject+Plugin
My script is saved under "Evaluated Groovy script" text area.
If the script is working, everything is fine. But if some error occurs, I always get the same error message:
[EnvInject] - [ERROR] - [EnvInject] - [ERROR] - Problems occurs on injecting env vars as a build wrap: null

Is there any way to get the actual exception or even exception message?

A: Another solution, that I found is to wrap your code into
try {

  // CODE HERE

} catch (Throwable t) {
  println(t)
  throw t;
}

A: If you put the script in the 'Prepare an environment for the run' section rather than down at the 'Build Environment' level in 'Inject environment variable to the build process' it will give you the exception error and the stack trace.


text:
Q: Existing Ubuntu 20.04 installation does not detect a newly added NVMe drive. BIOS is fine Installed Ubuntu 20.04 on a 256 GB, 2.5in  SSD in a system that also has a 2 TB HDD for data. Everything working fine. Added 256 GB NVMe drive. The BIOS found it correctly. SATA is set to AHCI. Ubuntu cannot find the NVMe drive. What do I do to get Ubuntu to see it. Do I need to mount it? If I do, how and what do I mount? Any help will be highly appreciated. Thank you.
Psagdeo


text:
Q: 64-bit kernel undefined behaviour with C calls Im working on my knowledge in lower level languages, and therefore decided to try out writing a insanely minimal kernel in x86_64. Just having some problems with optimization.
My bootloader (run from GRUB) looks like this.
.global start
.section .text
start:
    mov $stack_top, %esp
    call kernel_main
    hlt
.size start, . - start

.section .bss
.align 16
stack_bottom:
    .space 16384
stack_top:

My 'kernel' does the following things.
void kernel_main(void) {
    terminal_buffer = (uint16_t*) 0xB8000;
    uint16_t vga_char = ((VGA_BLACK << 4 | VGA_MAGENTA) << 8) | 'Y';
}

My problem is that using no optimization, the kernel_main doesn't even get called (or atleast, the behaviour within doesn't behave correctly). Im also having random off-by-one errors with the printed character, depending on what optimization i use.
I believe this could be because the processor still is in real/protected mode (GRUB ensures this), but i run C compiled with a x86_64-elf compiler. Is there a valid way to write C code for real/protected mode (i.e. 32-bit code) in a x86_64-elf compiler, so that i can write central bootup (checking long mode compat, switching to long mode, etc.). Or would i have to build another compiler? Or is this totally unreasonable, and "has" (and really should) to be done in assembly?

A: a) You say you kernel is for x86-64. If you intended to compile your kernel for such, then that is your issue. GRUB does not support booting into long mode. It boots you into 32-bit x86 protected mode; not 64-bit mode. You must tell your compiler to compile for 32-bit (by passing -m32).
b) I don't use GAS that often, but I think you need to put .extern kernel_main at the top of the assembly file, under your global statement. I am unsure, however. I would try my first suggestion, and if that does not work, add the extern line.


text:
Q: MySQL 5.7 - Select JSON document as Table I have a following JSON data format which has simple Key/Value pair data.
CREATE TABLE test_table (id INT, jdoc JSON);

INSERT INTO test_table VALUES
  (1, '{"CS":15, "Physics":20,"Chemistry":10}'),
  (2, '{"CS":6, "Physics":8,"Chemistry":5}');

I need to select above data in following format. i.e. Key name (Key Name is dynamic) as column name and value as data.
id| CS | Physics | Chemistry
1 | 15 | 20      | 10
2 | 6  | 8       | 5

I got the following solution from senior SO member "Akina" using JSON_TABLE. But this function only supports in MySQL 8.0
https://stackoverflow.com/a/69673530/1791406
Is there any alternatives of JSON_TABLE function in MySQL 5.7. Or get any clue to get the required results.

A: Yes, the old fashioned way, using json_extract and paths:
https://dbfiddle.uk/?rdbms=mysql_5.7&fiddle=403c4a6fa81b514214d3f10ddb4cf50e
SELECT t.id,
  t.jdoc->'$.CS' as CS,
  t.jdoc->'$.Physics' as Physics,
  t.jdoc->'$.Chemistry' as Chemistry
FROM test_table t

Where -> is a shorthand operator for json_extract.  Depending on the format of the data you are getting out, you may need to use ->> which is the shorthand operator for json_unquote(json_extract()).
You can support unknown keys by building dynamic paths, but it becomes less readable:
https://dbfiddle.uk/?rdbms=mysql_5.7&fiddle=bb9bf699ace41e6dd0e475e60b60605b
SELECT t.id,
  json_extract(t.jdoc, concat('$.', json_extract(json_keys(t.jdoc), '$[0]'))) as k0,
  json_extract(t.jdoc, concat('$.', json_extract(json_keys(t.jdoc), '$[1]'))) as k1,
  json_extract(t.jdoc, concat('$.', json_extract(json_keys(t.jdoc), '$[2]'))) as k2
FROM test_table t;

You can see that the outputs are identical, except for the column names.  If the column names are important, you can use a prepared statement to dynamically generate the query with field names, then prepare a statement from that and execute it.  See this fiddle:
https://dbfiddle.uk/?rdbms=mysql_5.7&fiddle=fb2ab27407789bdfad04e0a53d9a0257
SELECT json_keys(t.jdoc) INTO @keys FROM test_table t LIMIT 1;
SET @query = CONCAT("SELECT t.id, "
"t.jdoc->'$.", json_extract(@keys, '$[0]'), "' as ", json_extract(@keys, '$[0]'), ", ",
"t.jdoc->'$.", json_extract(@keys, '$[1]'), "' as ", json_extract(@keys, '$[1]'), ", ",
"t.jdoc->'$.", json_extract(@keys, '$[2]'), "' as ", json_extract(@keys, '$[2]'),
"FROM test_table t;");

PREPARE stmt FROM @query;
EXECUTE stmt;

Readability goes straight out the window, and maintaining will be a real chore.  I believe variables are deprecated, so there's no telling how long it will work, and it's generally recommended to avoid running dynamically generated sql.  But it will generate the desired result.
Bear in mind that executing dynamically generated sql opens you up to many possible harms.  You are essentially taking text from somewhere else and then executing it on your system.


text:
Q: Doubling slash with re.findall - Python I wonder why re.findall returns a string by adding a escape slash in front of each slash. Can we force it to return a raw string that is without this doubling slash ?
Example
src='on
essia \( de faire \)
'
src = re.findall(r'
(.*?)
',src)
print(src)

It returns:
['essia \\( de faire \\)']

But I would like to return:
['essia \( de faire \)']

A: It's because it prints entire list. Print its elements to get desired output.
In [1]: import re

In [2]: src='on
essia \( de faire \)
'
   ...:

In [3]: src = re.findall(r'
(.*?)
',src)

In [4]: print(src)
['essia \\( de faire \\)']

In [5]: print(src[0])
essia \( de faire \)


text:
Q: Add support for experimental syntax 'classProperties' in an npm package I would like to publish an npm package with some functions to use it with my create-react-app project. When I import the functions from the js file inside create-react-app project, it works fine. But when I install it as an npm package I get an error: Support for the experimental syntax 'classProperties' isn't currently enabled.
I tried to add the following code to a package.json file of the npm package:
"devDependencies": {
  "@babel/plugin-proposal-class-properties": "^7.8.3"
},
"babel": {
  "plugins": [
    "@babel/plugin-proposal-class-properties"
  ]
}

But it didn't solve the issue and I get the same error.
What else do I need to add as dependencies to my npm package to be able to use it in my create-react-app project? Or is it better to rewrite the functions without such experimental syntax?

A: You need to add plugin-proposal-class-properties in your build dependency
Working example with setup steps: https://github.com/hitsio/Node-JS-ES6
Here are the steps to Set up Babel for precompiling ES6 into JavaScript

*

*Install Babel

npm install --save-dev @babel/core @babel/cli

*Install Babel Preset & Class Properties Plugin

npm install @babel/preset-env --save-dev
npm install --save-dev @babel/plugin-proposal-class-properties

@babel/preset-env Allows you to use the latest JavaScript without needing to micromanage which syntax transforms (and optionally, browser polyfills) are needed by your target environment(s). This both makes your life easier and JavaScript bundles smaller!
@babel/plugin-proposal-class-properties transform ES6 class synthecic sugar into JavaScript __Prototype__

*Create .babelrc file in your project's root directory & add the following code in  .babelrc
 {
 "presets": ["@babel/preset-env"],
 "plugins": ["@babel/plugin-proposal-class-properties"]
 }

A: Based on this SO answer I did the following:
.npmignore
/src

.gitignore
/lib
/node_modules

Install Babel
$ npm install @babel/core @babel/cli @babel/preset-env --save-dev

Install @babel/plugin-proposal-class-properties
$ npm install --save-dev @babel/plugin-proposal-class-properties

package.json
"main": "lib/index.js",
"scripts": {
  "prepublish": "babel src -d lib"
},
"babel": {
  "presets": [
    "@babel/preset-env"
  ],
  "plugins": [
    "@babel/plugin-proposal-class-properties"
  ]
}

A: If someone is working with react-native-calendars and encounters this error, follow this link.


text:
Q: Should it be disallowed to flag deleted answers? I was going through the mod panel and I saw this:

It's an answer that's been deleted already. I thought that flags were handled automatically after deletion? Should this be fixed?

A: There is sometimes a race between users adding flags, and moderators wiping them out. Sometimes, this has resulted in a "not an answer" (etc) being added to a post that has actually just been deleted (note: it isn't a problem the other way around). In addition to leaving "false positives" for moderators, it can (based on evidence) also mean that 10k users are adding additional flags to a deleted post (in one case, 4 extra flags after deletion).
To stop this creating unnecessary work for everyone, from the next build only bespoke flag-for-moderator-attention flags will be accepted on deleted posts; otherwise, it'll just politely tell you that the post is now deleted. This still retains the ability to flag a deleted post for something out of the ordinary (undeletion, even-more-aggressive deletion, etc).

A: When a moderator closes or deletes a flagged post, pending flags on this post are cleared. There are two cases where you might see a flag on a deleted post.

*

*If a post is deleted by the author or the community, flags are not cleared. It would make sense to delete most canned flags when a post is deleted. Non-canned flags should stay until they're seen by a moderator, though.

*It's still possible to cast a "not an answer" or "low quality" flag on a deleted answer. Only users with 10k rep can see a deleted post, though it's also possible for lower-rep users to have flagged the post because they'd browsed to the page before the answer was deleted. These irrelevant canned flags should indeed be nullified on submission.

Note that it should still be possible to flag deleted posts to contact a moderator (for example to request undeletion).


text:
Q: Master -Slave Database Configuration With Hikari Pool I have two DataSource Beans one with @Primary annotation.
Individual Hikari pools are created for every DataSource.
I am trying to change the HikariDataSource from Pool 1(if connection is not available) to Pool 2 .
@Primary
@Bean(destroyMethod = "close", name = "dataSource")
public CustomHikariDataSource dataSource() throws SQLException {
    try {
        primaryDataSource = mainDataSource();
    } catch (Exception e) {
        primaryDataSource = secondaryDataSource();
    }
    HikariConfig config = new HikariConfig();
    config.setDataSource(primaryDataSource);
    config.setPoolName("POOL_PRIMARY");
    config.setAllowPoolSuspension(true);
    config.setIdleTimeout(10000);
    config.setMaxLifetime(30000);
    return new CustomHikariDataSource(config);
}

@Bean(destroyMethod = "close", name = "failoverDataSource")
public CustomHikariDataSource failoverDataSource() throws SQLException {
    secondaryDataSource = secondaryDataSource();
    HikariConfig config = new HikariConfig();
    config.setDataSource(secondaryDataSource);
    config.setPoolName("POOL_SECONDARY");
    config.setAllowPoolSuspension(true);
    return new CustomHikariDataSource(config);
}

private DataSource mainDataSource() {
    return dataSourceProperties().initializeDataSourceBuilder().build();

}

private DataSource secondaryDataSource() {
    return failoverDataSourceProperties().initializeDataSourceBuilder().build();

}

Where is the actual Problem?

A: Finally i am able to achieve it by Overriding getConnection() method from HikariDataSource.class
@Override
public Connection getConnection() throws SQLException {

    if (isClosed()) {
        throw new SQLException("HikariDataSource " + this + " has been closed.");
    }

    if (fastPathPool != null && (fastPathPool.poolState == 0 || fastPathPool.poolState == 1)) {
        try {
            fastPathPool.resumePool();
            con = fastPathPool.getConnection();
        } catch (Exception e) {

        }
        if (con.isClosed()) {
            config = pool.config;
            fastPathPool.suspendPool();
        } else
            return con;
    }

    config.setDataSource(dataSource);
    config.setAllowPoolSuspension(true);
    config.setMinimumIdle(minIdle);
    pool = new HikariPool(config);
    HikariPool result = pool;
    if (result == null) {
        synchronized (this) {
            result = pool;
            if (result == null) {
                validate();
                System.out.println("{} - Starting..." + getPoolName());
                try {
                    pool = result = new HikariPool(this);
                    this.seal();
                } catch (PoolInitializationException pie) {
                    if (pie.getCause() instanceof SQLException) {
                        throw (SQLException) pie.getCause();
                    } else {
                        throw pie;
                    }
                }
                System.out.println("{} - Start completed." + getPoolName());
            }
        }
    }

    return result.getConnection();

}

For complete class ,feel free to ping me.
Happy Coding ! :)


text:
Q: How to fix problem with usage: dirname path? I'm not too sure what caused the issue. I can't remember if this happened after I installed node or after I used time machine when setting up my new Mac. Either way, I'm getting this "usage: dirname path" in my terminal and I'm not too sure how set it back to normal.
I've gone through some stackoverflow solutions but I don't understand what I should do. I can code but I've never touched the bashprofile before.
When opening the terminal, I should see the following only:
Before:
usage: dirname path
usage: dirname path
(base) Shivas-MacBook-Pro:~ shivaSkanthan$

After:
(base) Shivas-MacBook-Pro:~ shivaSkanthan$

A: Okay so this link on stackoverflow solved my problem.
I basically typed this in terminal /usr/bin/nano .bash_profile and removed some junk and the terminal is looking well again.


text:
Q: $_GET variable cannot identify the first array element $_GET variable cannot identify the first array element.:
I have passed an array in url which looks like this

http://www.example.com/form.php?action=buy_now&ft=prf&Arrayproducts_id[]=431&products_id[]=432&Arraycart[]=1&cart[]=3&Arrayid[]=431&id[]=432

but when i print the array "products_id" and "cart" by using print_r($_GET), it just display me
Array
(
    [0] => 432
)
Array
(
    [0] => 3
)

now as u can see the url it also contains the value "431" for products_id and "3" for cart
I can see that due to the string "Array" appended to these they are not being accessed, So could someone suggest me how to fix this issue

EDIT as per Felix review

for($t=0;$t<4;$t++){

    $proid_30 .= "products_id[".$t."]=".$products_id."&";
        $bucket_30 .= "cart[".$t."]=".$_SESSION['qty_flex'][$t]."&";
        $idproid_30 .= "id[".$t."]=".$products_id."&";

        }
        $idproid_30.=" ";
$idproid_30 = str_replace("& ","",$idproid_30);
        echo "<script>window.location= '/print_ready_form.php?action=buy_now&ft=prf&".$proid_30.$bucket_30.$idproid_30."&osCsid=".$_GET['osCsid']."';</script>";

A: Looks like you echo an array to create your URL. This does not work:
$a = array(1,2);
echo $a;

prints
Array

Can you show the PHP code that generates the URL?
Update:
Without more code I can only assume, but I think that $proid_30, $bucket_30 and $idproid_30 are initialized as arrays. Now when you append a string, they are casted to strings:
$a = array(1,2);
$a .= 'test';
echo $a;

prints
Arraytest

Use new variables to build the URL or initialize them as strings:
E.g.:
$product = '';
$cart = '';
$id = '';
for($t=0;$t<4;$t++){
    $product .= "products_id[".$t."]=".$products_id."&";
    $cart .= "cart[".$t."]=".$_SESSION['qty_flex'][$t]."&";
    $id .= "id[".$t."]=".$products_id."&";
}

A: you can use variable names like "var[]" in a http form. do you need to use only get method? try post

A: Its only displaying the 432 for products_id because the only other products_id in the link is called Arrayproducts_id.
You will need to rename this back to products_id =)
Unless you want to call Arrayproducts_id ofcourse.

A: First product Id was named as "Arrayproducts_id". So you can get by printing "Arrayproducts_id"


text:
Q: Where are theme customizations in 11.10?
Possible Duplicate:
How do I change the theme?

I upgraded, and now I need to tweak my fonts for the Ambiance theme - and I can't find anyplace to do it - in fact, the whole preview dialog for themes is gone - I'm not sure why they did that, but it'd be nice of them to put it back.

A: Open a terminal and run the command:
sudo apt-get install gnome-tweak-tool

...then look for Advanced settings to run it.
http://www.installubuntulinux.com/2011/09/howto-change-system-font-sizes-in.html

A: use gnome tweek and dconf editor to change themes and stuff


text:
Q: Display Service Mark in Android Screen It seems as though the Service Mark UTF code is not supported by Android.  I have the below in my strings.xml file and I only get an empty box.  The copyright works fine. Any ideas?
<string name="test">Test\u2120</string>

A: An option would be to use a custom font which has Service Mark. Or perhaps easier would be to use superscript.


text:
Q: How do I grant all privileges for a database to a role in Snowflake I am trying to grant all privileges for a database to a role in snowflake
This includes all ability to read, create, update and delete schemas, stages, storage integrations, tables and so on.
Also should include any future objects created in the database.
    grant all on database test to developer;

This only grants view of the database and not the schema or any other objects within the database

A: Unfortunately in Snowflake, there is no as such command to grant all access via a single command.
Even with all privileges command, you have to grant one usage privilege against the object to be effective.
It's mentioned in the documentation on Schema Privileges as well.
For future grants, you can try following commands at schema and database level
SCHEMA LEVEL
grant usage on database SAMPLEDATABASE1 to role testrole12;
grant usage on schema SAMPLEDATABASE1.TEST to role testrole12;
grant select on future tables in schema SAMPLEDATABASE1.TEST to role testrole12;
grant role testrole12 to user SUJANT3;

DATABASE LEVEL
grant usage on database SAMPLEDATABASE1 to role testrole12;
grant usage on future schemas in database SAMPLEDATABASE1 to role testrole12;
grant select on future tables in database SAMPLEDATABASE1 to role testrole12;
grant role testrole12 to user SUJANT3;

A: There is no one single command to affect all the objects under the database, but you can run these set of SQL's per object:
GRANT ALL ON ALL schemas in database <DB> TO ROLE <role>;
GRANT ALL ON ALL TABLES IN SCHEMA <db.schema> TO ROLE <role>;

similarly for future grants:
grant all on future schemas in database <DB> TO ROLE <role>;

grant all on future tables in schema <db.schema> to ROLE <role>;

This can be extended to views and other objects too.

A: It sounds like you want to grant ownership? There can only be 1 owner per object, so I recommend you use this only when appropriate:
GRANT OWNERSHIP ON DATABASE TEST
   TO DEVELOPER
   COPY CURRENT GRANTS
;

Note: Copying current grants retains the current privileges, except ownership is transferred. Otherwise, all existing privileges will be dropped.


text:
Q: Traversing through a generic binary tree An abstract binary tree is to be created using a generic class. Each node has a string value as well as an initialCalculatedValue value. No changes should be made to the main class and a static inner class is to be included in the generic class. I'd like some advice on my code, as the main class is giving me error on accessing 'timesVisited' and 'values'. My code can't seem to access those variables.
Main class code:
public class Main{
    public static void main(String[] args) {
        WalkableTree<String, Integer> ast = new WalkableTree<>(0);

        WalkableTree.Node<String, Integer> plus = ast.setRoot("+");
        plus.setRightChild("20");

        WalkableTree.Node<String, Integer> multiply = plus.setLeftChild("*");
        multiply.setLeftChild("10");

        WalkableTree.Node<String, Integer> bracketedPlus = multiply.setRightChild("+");
        bracketedPlus.setLeftChild("3");
        bracketedPlus.setRightChild("4");

        // write visitor to display pre-order
        System.out.println("Pre-order traversal:");
        ast.walk(current -> {
            if(current.timesVisited == 2)
                System.out.print(current.value + " ");
        });
        System.out.println();

        // write visitor to display in-order
        System.out.println("In-order traversal:");
        ast.walk(current -> {
            if(current.timesVisited == 3)
                System.out.print(current.value + " ");
        });
        System.out.println();

        // write visitor to display post-order
        System.out.println("Post-order traversal:");
        ast.walk(current -> {
            if(current.timesVisited == 4)
                System.out.print(current.value + " ");
        });
        System.out.println();
    }
}

Functional interface:
@FunctionalInterface
public interface Visitor<N> {
    public void visit(N node);
}

Generic class:
public class WalkableTree <T, R> {

     private T root = null;
     private R initialCalculatedValue;
     public static Node current;

    public WalkableTree(R initialCalculatedValue) {
        this.initialCalculatedValue = initialCalculatedValue;
    }

    public Node getRoot() {
        return (Node) root;
    }

    public Node setRoot(T value) {
        current = new Node(null,null,null,value,null,0);
        return current;
    }

    public R getInitialCalculatedValue() {
        return initialCalculatedValue;
    }

    public void setInitialCalculatedValue(R initialCalculatedValue) {
        this.initialCalculatedValue = initialCalculatedValue;
    }

    protected void reset(Node node) {
        node.timesVisited = 0;
        node.calculatedValue = initialCalculatedValue;
        reset((Node) node.leftChild);
        reset((Node) node.rightChild);
    }

    public Node nextNode(Node node) {
        node.timesVisited++;
        if(node.timesVisited == 1)
            return node;

        if(node.timesVisited == 2)
            return (Node) node.leftChild;

        if(node.timesVisited == 3)
            return (Node) node.rightChild;

        if(node.timesVisited == 4)
            return (Node) node.getParent();

        return node;
    }

    public void walk(Visitor visitor) {
        //Reset all the nodes in the tree
        reset((Node) root);

        //Set the current node to visit at the root of the tree
        visitor.visit(root);

        //Walking through the tree as long as the current node still exists
            //If current node exists, let the visitor object visit the current node
            //Current node is set to the next node using nextNode() method
        while (this.current == current)
        {
            nextNode(current);
        }
    }

    public static class Node<T, R> {
        //Variables
        Object leftChild;
        Object rightChild;
        Object parent;
        T value;
        R calculatedValue;
        int timesVisited = 0;

        public Node(Object leftChild, Object rightChild, Object parent, T value, R calculatedValue, int timesVisited) {
            this.leftChild = leftChild;
            this.rightChild = rightChild;
            this.parent = parent;
            this.value = value;
            this.calculatedValue = calculatedValue;
            this.timesVisited = timesVisited;
        }

        public Object getLeftChild() {
            return leftChild;
        }

        public Node setLeftChild(T value) {
            Node newLeft = new Node(null,null, current,value,0,0);
            current = newLeft;
            return current;
        }

        public Object getRightChild() {
            return rightChild;
        }

        public Node setRightChild(T value) {
            Node newRight = new Node(null,null, current,value,0,0);
            current = newRight;
            return current;
        }

        public Object getParent() {
            return parent;
        }

        public void setParent(Node parent) {
            this.parent = parent;
        }

        public T getValue() {
            return value;
        }

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

        public R getCalculatedValue() {
            return calculatedValue;
        }

        public void setCalculatedValue(R calculatedValue) {
            this.calculatedValue = calculatedValue;
        }

        public int getTimesVisited() {
            return timesVisited;
        }

        public void setTimesVisited(int timesVisited) {
            this.timesVisited = timesVisited;
        }
    }
}

A: Update the method in WalkableTree as below:
 public void walk(Visitor<Node> visitor) {
        //Reset all the nodes in the tree
        reset((Node) root);

        //Set the current node to visit at the root of the tree
        visitor.visit((Node) root);

        //Walking through the tree as long as the current node still exists
        //If current node exists, let the visitor object visit the current node
        //Current node is set to the next node using nextNode() method
        while (this.current == current)
        {
            nextNode(current);
        }
    }


text:
Q: Refactoring to loop mySQL & PHP code I currently have an associative array called fields that stores all my  $_POST variables from my HTML input fields. The associative array variables are used when I try to bind my values to the mySQL database In the same manner, I also have the same names used as column headers for the mySQL database. So this is very tedious and long. Is there a way to perhaps loop through the columns and assign a value with another loop for the associative array? Please check the example below and thank you in advance for your help.
     try {
                $insertSql = "INSERT INTO tableExample";
                $sqlCols = " (
                    a,
                    b,
                    c,
                    d,
                    e,
                    f,
                    g,
                    h,
                    i,
                    j,
                    k,
                    l,
                    m,
                    n,
                    o,
                    p,
                    q,
                    r,
                    s,
                    t,
                    u,
                    v,
                    w,
                    x
                )";
                $result = $db->prepare($insertSql . $sqlCols . " VALUES (
                    ?,
                    ?,
                    ?,
                    ?,
                    ?,
                    ?,
                    ?,
                    ?,
                    ?,
                    ?,
                    ?,
                    ?,
                    ?,
                    ?,
                    ?,
                    ?,
                    ?,
                    ?,
                    ?,
                    ?,
                    ?,
                    ?,
                    ?,
                    ?)");
                $result->bindValue(1,$fields['a'],PDO::PARAM_STR);
                $result->bindValue(2,$fields['b'],PDO::PARAM_STR);
                $result->bindValue(3,$fields['c'],PDO::PARAM_STR);
                $result->bindValue(4,$fields['d'],PDO::PARAM_STR);
                $result->bindValue(5,$fields['e'],PDO::PARAM_STR);
                $result->bindValue(6,$fields['f'],PDO::PARAM_STR);
                $result->bindValue(7,$fields['g'],PDO::PARAM_STR);
                $result->bindValue(8,$fields['h'],PDO::PARAM_STR);
                $result->bindValue(9,$fields['i'],PDO::PARAM_STR);
                $result->bindValue(10,$fields['j'],PDO::PARAM_STR);
                $result->bindValue(11,$fields['k'],PDO::PARAM_STR);
                $result->bindValue(12,$fields['l'],PDO::PARAM_STR);
                $result->bindValue(13,$fields['m'],PDO::PARAM_STR);
                $result->bindValue(14,$fields['n'],PDO::PARAM_STR);
                $result->bindValue(15,$fields['o'],PDO::PARAM_STR);
                $result->bindValue(16,$fields['p'],PDO::PARAM_STR);
                $result->bindValue(17,$fields['q'],PDO::PARAM_STR);
                $result->bindValue(18,$fields['r'],PDO::PARAM_STR);
                $result->bindValue(19,$fields['s'],PDO::PARAM_STR);
                $result->bindValue(20,$fields['t'],PDO::PARAM_STR);
                $result->bindValue(21,$fields['u'],PDO::PARAM_STR);
                $result->bindValue(22,$fields['v'],PDO::PARAM_STR);
                $result->bindValue(23,$fields['w'],PDO::PARAM_STR);
                $result->bindValue(24,$fields['x'],PDO::PARAM_STR);
                $result->execute();
            } catch (Exception $e) {
                echo "Unable to store data";
                echo $e->getMessage();
                exit;
            }

A: Quickly cooked up a possible solution. Before trying it, please bear in mind that it's untested and there may be several syntax errors here (no PDO on my end... Actually, no php either).
What this does is define two separate maps: one for "database columns to indexes" and other for "database columns to values".
I can't be sure that this solves your problem but it's a starting point.
<?php
try
{
    //Define your columns and indexes...
    $fields=['col_a' => 1, 'col_b' => 2, 'col_c' => 3, 'col_d' => 4];

    //Let this be your post data. Notice how the index are the same as above.
    $data=['col_a' => "Value a", "col_b" => 33, "col_c" => "Value C", "col_d" => 12];

    //Prepare the statement....
    $sqlCols=null;
    $sqlValues=null;

    foreach($fields as $key => $value)
    {
        $sqlCols.=$key.',';
        $sqlValues.='?,';
    }

    $result = $db->prepare("INSERT INTO tableExample (".substr($sqlCols, 0, -1).") VALUES (".substr($sqlValues, 0, -1).")";

    //Bind the values... Please, make sure the order of parameters is correct!.
    foreach($fields as $key => $index)
    {
        $result->bindValue($index, $data[$key], PDO::PARAM_STR);
    }

    $result->execute();
}
catch (Exception $e)
{
    echo "Unable to store data";
    echo $e->getMessage();
}
?>

Again, let me state that you're exposing your database structure through the names in your post variables. I doubt that's what you want to do.


text:
Q: Comma-separated list output for SQL Server 2012, with many JOINs I have been looking for this answer here in SO, but can't find it.
I have the following SQL:
SELECT DISTINCT RM.RegulatoryModel, AA.Agency
FROM Search_By_PartNumber SBPN
LEFT JOIN RegulatoryModels_PartNumbers RMPN ON SBPN.PartNumber = RMPN.PartNumber
LEFT JOIN RegulatoryModels RM ON RMPN.RegModID = RM.RegModID
LEFT JOIN Certifications C ON RM.RegModID = C.RegModID
LEFT JOIN Agencies AA ON AA.AgencyID = C.AgencyID
WHERE RMPN.Active = 1 AND RM.Active = 1
Order BY RegulatoryModel

which generates the following data:
RegulatoryModel Agency
DPS-750XB XX    BSMI
DPS-750XB XX    CE Self Declaration
DPS-750XB XX    CQC
DPS-750XB XX    KTC
DPS-750XB XX    Kvalitet
DPS-750XB XX    Nemko
DPS-750XB XX    UL

I'm trying to put all the Agencies in one line, like "BSMI, CE Self Declaration, ...", and I've found out how to do that with stuff and FOR XML PATH (code below), but it's returning EVERY Agency found in the Agencies table, not just the ones associated with this join.  Read about CROSS APPLY, but could not figure that one out either.
Not-quite-right code:
SELECT DISTINCT RM.RegulatoryModel,
   AgencyList = stuff((
    SELECT ', ' + A.Agency
    FROM Agencies A
    order by A.Agency
    FOR XML PATH('')
    ), 1, 2, '')
FROM Search_By_PartNumber SBPN
LEFT JOIN RegulatoryModels_PartNumbers RMPN ON SBPN.PartNumber = RMPN.PartNumber
LEFT JOIN RegulatoryModels RM ON RMPN.RegModID = RM.RegModID
LEFT JOIN Certifications C ON RM.RegModID = C.RegModID
WHERE RMPN.Active = 1 AND RM.Active = 1
Order BY RegulatoryModel

Suggestions on how to modify the above code to just give a comma-separated list of the Agencies that are matched in this multi-level JOIN?

A: try to wrap in CTE first then stuff it.
        ;
        WITH    CTE
                  AS (

                        SELECT DISTINCT RM.RegulatoryModel, AA.Agency
                        FROM Search_By_PartNumber SBPN
                        LEFT JOIN RegulatoryModels_PartNumbers RMPN ON SBPN.PartNumber = RMPN.PartNumber
                        LEFT JOIN RegulatoryModels RM ON RMPN.RegModID = RM.RegModID
                        LEFT JOIN Certifications C ON RM.RegModID = C.RegModID
                        LEFT JOIN Agencies AA ON AA.AgencyID = C.AgencyID
                        WHERE RMPN.Active = 1 AND RM.Active = 1
                        Order BY RegulatoryModel

                     )
                    SELECT DISTINCT
                    RM.RegulatoryModel ,
                    AgencyList = STUFF(( SELECT ', ' + A.Agency
                                         FROM   CTE A
                                         ORDER BY A.Agency
                                       FOR
                                         XML PATH('')
                                       ), 1, 2, '')
            FROM    CTE RM

UPDATED:
    ;
    WITH    CTE
              AS (

                    SELECT DISTINCT RM.RegulatoryModel, AA.Agency,SBPN.PartNumber
                    FROM Search_By_PartNumber SBPN
                    LEFT JOIN RegulatoryModels_PartNumbers RMPN ON SBPN.PartNumber = RMPN.PartNumber
                    LEFT JOIN RegulatoryModels RM ON RMPN.RegModID = RM.RegModID
                    LEFT JOIN Certifications C ON RM.RegModID = C.RegModID
                    LEFT JOIN Agencies AA ON AA.AgencyID = C.AgencyID
                    WHERE RMPN.Active = 1 AND RM.Active = 1

                 )
                SELECT DISTINCT
                RM.RegulatoryModel ,
                AgencyList = STUFF(( SELECT ', ' + A.Agency
                                     FROM   CTE A
                                     WHERE RM.PartNumber = A.PartNumber
                                     ORDER BY A.Agency
                                   FOR
                                     XML PATH('')
                                   ), 1, 2, '')
        FROM    CTE RM

A: Notice this ON clause in the original query:
SELECT DISTINCT RM.RegulatoryModel, AA.Agency
FROM Search_By_PartNumber SBPN
LEFT JOIN RegulatoryModels_PartNumbers RMPN ON SBPN.PartNumber = RMPN.PartNumber
LEFT JOIN RegulatoryModels RM ON RMPN.RegModID = RM.RegModID
LEFT JOIN Certifications C ON RM.RegModID = C.RegModID

LEFT JOIN Agencies AA ON AA.AgencyID = C.AgencyID
                       --^--This one

WHERE RMPN.Active = 1 AND RM.Active = 1
Order BY RegulatoryModel

And notice how there's no similar condition in your second query? We need to correlate your subquery, using this condition:
SELECT DISTINCT RM.RegulatoryModel,
   AgencyList = stuff((
    SELECT ', ' + A.Agency
    FROM Agencies A

    WHERE A.AgencyID = C.AgencyID

    order by A.Agency
    FOR XML PATH('')
    ), 1, 2, '')
FROM Search_By_PartNumber SBPN
LEFT JOIN RegulatoryModels_PartNumbers RMPN ON SBPN.PartNumber = RMPN.PartNumber
LEFT JOIN RegulatoryModels RM ON RMPN.RegModID = RM.RegModID
LEFT JOIN Certifications C ON RM.RegModID = C.RegModID
WHERE RMPN.Active = 1 AND RM.Active = 1
Order BY RegulatoryModel

If this isn't giving you the correct output (you still have more rows than you'd like and not enough items are being concatenated), it probably indicates that more of the tables/joins need to move up into the subquery. But bear in mind that you need to make sure that it remains correlated to the outer query.
Note that as Esperento57 mentioned in the comments, the outer WHERE clause is slightly suspect (forcing some of the joins to effectively become INNER joins).
Also, I'd insert my usual caveats around comma separated data - it's not a natural way to represent multiple values in T-SQL. There are types designed for holding multiple values (tables, xml, json from 2016 onwards) and CSV strings aren't one of them. Ideally, I'd leave this sort of transformation to a presentation layer rather than putting it in the database.


text:
Q: Async Symfony events I'm trying to use https://github.com/fervo/FervoDeferredEventBundle in order to have async events to store data in my DB. The event is added to the RabbitMQ Queue correctly but the event listener and the event itself is never executed.
I'm trying in both ways: first letting the listener to do the job and also dispatching manually the deferevent.
Any idea?
Thank you!
My code:
in my Controller:
$event = new DeferEvent('save.data', new SaveDataEvent($data));
$this->get('event_dispatcher')->dispatch('fervo.defer', $event);

SaveDataEvent.php
<?php

namespace AppBundle\Event;

use Symfony\Component\EventDispatcher\Event;

class SaveDataEvent extends Event
{
    protected $data;

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

    public function getData()
    {
        return $this->data;
    }

    public function saveData()
    {
        $data = $this->getData();
        // do more stuff
    }
}

SaveDataListener.php
<?php

namespace AppBundle\EventListener;

use AppBundle\Event\SaveDataEvent;

class SaveDataListener
{

    /**
     * @var SaveDataEvent
     */
    public function onSendData(SaveDataEvent $event)
    {

        $data = $event->saveData();
    }
}

services.yml
app.save_data_listener:
        class: AppBundle\EventListener\SaveDataListener
        tags:
            -
                name: kernel.event_listener #fervo_deferred_event.listener
                event: send.data

A: Reading the docs, you should fix the services.yml:
app.save_data_listener:
    class: AppBundle\EventListener\SaveDataListener
    tags:
        name: fervo_deferred_event.listener
        event: fervo.defer

Replace fervo.defer with the first value passed to dispatch() method if you want, it's the name of the dispatched event.


text:
Q: KNN based on distance instead of neighbours I have three columns and I need to find near by values like below
A            B        Distance

point_a    point_b      20

point_a    point_c      30

point_a    point_d      40

point_a    point_e      25

point_g    point_a      26

point_c    point_d      30

point_c    point_e      30

point_d    point_e      40

I need to find all the near by points
For ex -  If I want to find all near by points from point_a within 28 miles  it will be point_b, point e and point g

A: You can use for example a simple pandas query and don't need any machine learning algorithm:
result = df.query("(A == 'point_a' | B == 'point_a') & Distance < 28")

or
result = df[((df['A'] == 'point_a') | (df['B'] == 'point_a')) & (df['Distance'] < 28)]

Result:
         A        B  Distance
0  point_a  point_b        20
3  point_a  point_e        25
4  point_g  point_a        26

Get a set of nearest points:
result = result[['A', 'B']].stack().unique().tolist()
result = set(result)
result.remove('point_a')

Result:
{'point_e', 'point_g', 'point_b'}


text:
Q: losing connectivity in Linux with Dell blades and such So we have some dell blades and chassis (blades are M600's, chassis M1000's) and other systems (R710 with MD3000 array). The R710 exports a source tree via nfs for the blades to build and test with.
The problem is the blades loose the nfs mounts. Blades in the same chassis, with what seem like identical configurations, have their connections hang, they cannot even ping the server. They eventually come back.
It is mostly Dell, in fact, we have a cable running from the r710 to a switch in one of the chassis, and another to a switch and from there to the chassis, both can have issues.
We are running Centos5 or Fedora Core release 5 (Bordeaux). The nfs server is running CentOS release 5.4 (Final).
Any thoughts? troubleshooting tips?
These are all to the same host, but via different routes:
Through a switch
[root@b053 ~]# ping svnwatch-data
PING storage.rack1.rinera.int (10.1.1.54) 56(84) bytes of data.

--- storage.rack1.rinera.int ping statistics ---
9 packets transmitted, 0 received, 100% packet loss, time 7999ms

Routed through another host:
[root@b053 ~]# ping svnwatch-data2
PING storage2.rack1.rinera.int (172.16.100.25) 56(84) bytes of data.
64 bytes from 172.16.100.25: icmp_seq=1 ttl=64 time=0.260 ms
64 bytes from 172.16.100.25: icmp_seq=2 ttl=64 time=0.217 ms
64 bytes from 172.16.100.25: icmp_seq=3 ttl=64 time=0.201 ms
64 bytes from 172.16.100.25: icmp_seq=4 ttl=64 time=0.264 ms

--- storage2.rack1.rinera.int ping statistics ---
4 packets transmitted, 4 received, 0% packet loss, time 2999ms
rtt min/avg/max/mdev = 0.201/0.235/0.264/0.031 ms

With the host connected to a different chassis's switch (they are daisy chained)
[root@b053 ~]# ping svnwatch-data-eth2
PING svnwatch-data-eth2.rack1.rinera.int (10.1.1.56) 56(84) bytes of data.
64 bytes from 10.1.1.56: icmp_seq=1 ttl=64 time=0.598 ms
64 bytes from 10.1.1.56: icmp_seq=2 ttl=64 time=0.096 ms
64 bytes from 10.1.1.56: icmp_seq=3 ttl=64 time=0.168 ms

--- svnwatch-data-eth2.rack1.rinera.int ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time 2000ms
rtt min/avg/max/mdev = 0.096/0.287/0.598/0.222 ms
[root@b053 ~]#

A: Here is what I would check.

*

*route tables: ip route show

*route cache: ip route show cache

*check for any wierd iptables rules. iptables -t nat -L -n -v; iptables -L -n -v; iptables -t mangle -L -n -v

*check log files.

*check kernel version.

*check sysctl/proc settings such as rp_filter, which important in routed / multi-interface configuration

*check ARP tables for IP conflicts etc.

*and of course: tcpdump and tcpflow...


text:
Q: Does dynamically updating a div with JS/jQuery rely on the click of an element on the same page? I have a div, or more specifically a
 tag with id="routineInfo" I want to dynamically update on document.ready, but for some reason it does not seem to work:
$(function() {
  $("#routineInfo").html("Routine: Full Body");
});

I started troubleshooting and I could get the desired effect by attaching an onclick handle to an element to trigger the function:
$(".playIt").click(function() {
  $("#routineInfo").html("Routine: Full Body");
});

However, I wanted the function to happen on load of the desired page, so to simulate this I attached the handle to the element, found on a different page, that links to the page in question:
$(".linkElementOnDifferentPage").click(function() {
  $("#routineInfo").html("Routine: Full Body");
});

Did not work. Can anybody explain this to me please?
EDIT: adding html.

A: If your div(or p tag) is loaded dynamically, then it cannot be guarantied that its available at the document ready function(mostly in case of rendering views asynchronously).

$(function() {
  setTimeout(function() {
    $("#info").append($('

'));
  }, 3000);
});
var DivPopulateIntervel = window.setInterval(function() {
  if ($("#routineInfo").length > 0) {
    $("#routineInfo").html("Routine: Full Body");
    window.clearInterval(DivPopulateIntervel);
  }
}, 100);

here
setTimeout(function() {
    $("#info").append($('

'));
}, 3000);

simply adds your #routineInfo to document after 3 seconds to create a lazy loading or asynchronous effect(just for demo purpose).
var DivPopulateIntervel = window.setInterval(function() {
  if ($("#routineInfo").length > 0) {
    $("#routineInfo").html("Routine: Full Body");
    window.clearInterval(DivPopulateIntervel);
  }
}, 100);

is the setInterval function which gets called after every 100 milliseconds, until the required div gets rendered.
window.clearInterval(DivPopulateIntervel);

removes the DivPopulateIntervel intervel function once the html is set(or the required div is available).


text:
Q: Table causing too many re-renders, React I am trying to get this table to populate on my inspection page--but I am getting an error that states too many re-renders, I tried moving the component to a different component. I removed the useEffect from it, but I am still getting that error. I know it's definitely something in my InspectionSearch, as as soon as I render it, that's when it throws the error. Any help would be greatly appreciated.
import { useState, React } from "react";
import { useTable } from 'react-table'
import 'bootstrap/dist/css/bootstrap.min.css';

const SearchInspections = ({inspections}) => {

    const [chartData, setChartData] = useState([]);

        let inspectionData = inspections.map(inspection => {
            return [
                inspection.inspection_date,
                inspection.eggs,
                inspection.larvae,
                inspection.sealed_brood,
                inspection.covered_bees,
                inspection.nectar_honey,
                inspection.pollen,
            ]
        });
        setChartData(inspectionData);

    const columns = [
        {
            Header: 'Frames',
            columns: [
                {
                    Header: 'W/Eggs',
                    accessor: 'eggs',
                },
                {
                    Header: 'W/Larvae',
                    accessor: 'larvae',
                },
                {
                    Header: 'W/Sealed Brood',
                    accessor: 'sealed_brood',
                },
                {
                    Header: 'Covered in Bees',
                    accessor: 'covered_bees',
                },
                {
                    Header: 'W/Nectar and/or Honey',
                    accessor: 'nectar_honey',
                },
                {
                    Header: 'W/Pollen',
                    accessor: 'pollen',
                },
                {
                    Header: 'Pest Spotted',
                    accessor: 'pest_spotted',
                },
                {
                    Header: 'Pest Action',
                    accessor: 'pest_action',
                },
                {
                    Header: 'Notes or Concerns',
                    accessor: 'notes_concerns',
                },
                {
                    Header: 'Inspection Date',
                    accessor: 'inspection_date',
                },
            ],
        },

    ];

    const data = [
        ...chartData
    ]

    const {
        getTableProps,
        getTableBodyProps,
        headerGroups,
        rows,
        prepareRow,
    } = useTable({
        columns,
        data,
    })

    return (<>

                {headerGroups.map(headerGroup => (

                        {headerGroup.headers.map(column => (
                            {column.render('Header')}
                        ))}

                ))}

                {rows.map((row, i) => {
                    prepareRow(row)
                    return (

                            {row.cells.map(cell => {
                                return {cell.render('Cell')}
                            })}

                    )
                })}

    </>);
}

export default SearchInspections;

Here is where it's rendering
import { React, useState, useEffect } from "react";
import { useParams } from "react-router-dom";
import axios from "axios";
import useAuth from "../../hooks/useAuth";
import DisplayInspections from "../../components/DisplayInspections/DisplayInspections";
import InspectionTracker from "../../components/InspectionTracker/InspectionTracker";
import SearchInspections from "../../components/InspectionSearch/InspectionSearch"

const InspectionPage = (props) => {
  const [user, token] = useAuth();
  const [inspections, setInspections] = useState([]);
  const { id } = useParams();

  useEffect(() => {
    fetchInspections();
  }, [token]);

  const fetchInspections = async () => {
    try {
      let response = await axios.get(
        `http://127.0.0.1:8000/api/inspections/all/${id}`,
        {
          headers: {
            Authorization: "Bearer " + token,
          },
        }
      );
      setInspections(response.data);
    } catch (error) {
      console.log(error.response.data);
    }
  };

  return (

      <InspectionTracker inspections={inspections} />
      <DisplayInspections
        inspections={inspections}
        setSelectedHive={props.setSelectedHive}
        setSelectedInspection={props.setSelectedInspection}
      />
      <SearchInspections inspections={inspections} />

  );
};

export default InspectionPage;

A: Put your logic inside an update useEffect
const SearchInspections = ({inspections}) => {

   const [chartData, setChartData] = useState([]);

   useEffect(() => {
    let inspectionData = inspections.map(inspection => {
        return [
            inspection.inspection_date,
            inspection.eggs,
            inspection.larvae,
            inspection.sealed_brood,
            inspection.covered_bees,
            inspection.nectar_honey,
            inspection.pollen,
        ]
    });
    setChartData(inspectionData);
  }, [inspections])

   const columns = [
   /** end of your code */

A: I was able to get an instructor to help me out. Data Format was return as an array, it should have been formated to the table see updated and working code in case anyone wants to try their hand at using react-tables!
import { useEffect, useState } from "react";
import React from "react";
import { useTable } from "react-table";

import "bootstrap/dist/css/bootstrap.min.css";

const SearchInspections = ({ inspections }) => {
  const [chartData, setChartData] = useState([]);

  useEffect(() => {
    const inspectionData = inspections.map((inspection) => {

        return{
            "eggs": inspection.eggs,
            "larvae": inspection.larvae,
            "sealed_brood": inspection.sealed_brood,
            "covered_bees": inspection.covered_bees,
            "nectar_honey": inspection.nectar_honey,
            "pollen": inspection.pollen,
            "pest_spotted": inspection.pest_spotted,
            "pest_action": inspection.pest_action,
            "notes_concerns": inspection.notes_concerns,
            "inspection_date": inspection.inspection_date,

        }

      ;
    });
    setChartData(inspectionData);
  }, [inspections]);

  const columns = React.useMemo(
      () =>[
    {
      Header: "Frames",
      columns: [
        {
          Header: "W/Eggs",
          accessor: "eggs",
        },
        {
          Header: "W/Larvae",
          accessor: "larvae",
        },
        {
          Header: "W/Sealed Brood",
          accessor: "sealed_brood",
        },
        {
          Header: "Covered in Bees",
          accessor: "covered_bees",
        },
        {
          Header: "W/Nectar and/or Honey",
          accessor: "nectar_honey",
        },
        {
          Header: "W/Pollen",
          accessor: "pollen",
        },
        {
          Header: "Pest Spotted",
          accessor: "pest_spotted",
        },
        {
          Header: "Pest Action",
          accessor: "pest_action",
        },
        {
          Header: "Notes or Concerns",
          accessor: "notes_concerns",
        },
        {
          Header: "Inspection Date",
          accessor: "inspection_date",
        },
      ],
    },
  ], []);

  const data = React.useMemo(() => {
    return  [...chartData]
    }, [chartData]);

    const Table = ({ columns, data }) => {
        // Use the state and functions returned from useTable to build your UI
        const {
          getTableProps,
          getTableBodyProps,
          headerGroups,
          rows,
          prepareRow,
        } = useTable({
          columns,
          data,
        })

        return(

              {headerGroups.map((headerGroup) => (

                  {headerGroup.headers.map((column) => (
                    {column.render("Header")}
                  ))}

              ))}

              {rows.map((row) => {
                prepareRow(row);
                return (

                    {row.cells.map((cell) => {
                      return (
                        {cell.render("Cell")}
                      );
                    })}

                );
              })}

        )
    }

  return (
    <>

    {console.log(columns)}
    {console.log(data)}
    </>
  );
};

export default SearchInspections;```


text:
Q: Printing file input. System.out.println(); So i have a file called input that contains the following: A B C D Foo . I already created a program that prints each of the elements on a separate line, but for  the life of me, i can't seem to print the elements in the file like they are. I tried numerous approaches, but haven't gotten it.
Here's my program:
import java.util.*;
import java.io.*;
class EchoLetters {
   public static void main(String[] args) throws IO Exception {
       String word;
       Scanner dataFile = new Scanner(new File("input"));

       System.out.println() //where I'm stuck. Should printout "A B C D Foo"

       while ( dataFile.hasNext() ) {
               word = dataFile.next();
               System.out.println(word);
              }
           }
       }

A: System.out.println() expects a parameter to be printed. If you don't pass it any parameters, it will only call newLine().
Here's one way of printing the file content:
public static void main(String[] args) throws FileNotFoundException {
    StringBuilder s = new StringBuilder();
    Scanner dataFile = new Scanner(new File("file"));
    while (dataFile.hasNextLine()) {
        s.append(dataFile.nextLine()).append(System.lineSeparator());
    }
    System.out.println(s.toString()); //where I'm stuck. Should printout "A B C D Foo"
}