Q: Does the global keyword inline the global exactly as a local variable declaration in python? So are these two exactly equivalent vis a vis performance (that is, is the generated code exactly equivalent):
class A(object):
    const = 'abc'

    def lengthy_op(self):
        const = self.const
        for i in xrange(AVOGADRO):
            # do something which involves reading const

and:
const = 'abc'
class A(object):

    def lengthy_op(self):
        global const
        for i in xrange(AVOGADRO):
            # do something which involves reading const

A: No they are not exactly equivalent, although the difference is unlikely to be significant.
class A(object):
    const = 'abc'

    def lengthy_op(self):
        const = self.const
        for i in xrange(AVOGADRO):
            # do something which involves reading const

This creates a local variable so any access of const will use the LOAD_FAST opcode.
const = 'abc'
class A(object):

    def lengthy_op(self):
        # global const
        for i in xrange(AVOGADRO):
            # do something which involves reading const

This, with or without the redundant global const uses LOAD_GLOBAL to access the value of the global variables const, xrange, and AVOGADRO.
In C Python LOAD_GLOBAL will perform a fast dictionary lookup to access the variable (fast because the global variables are in a dictionary using only string keys and the hash values are pre-calculated). LOAD_FAST on the other hand simply accesses the first, second, third etc. local variables which is an array indexing operation.
Other versions of Python (e.g. PyPy) may be able to optimise accessing the global variable in which case there may not be any difference at all.
The first code (with n=i+const as the loop body) disassembles to:
>>> dis.dis(A.lengthy_op)
  5           0 LOAD_FAST                0 (self)
              3 LOAD_ATTR                0 (const)
              6 STORE_FAST               1 (const)

  6           9 SETUP_LOOP              30 (to 42)
             12 LOAD_GLOBAL              1 (xrange)
             15 LOAD_GLOBAL              2 (AVOGADRO)
             18 CALL_FUNCTION            1
             21 GET_ITER
        >>   22 FOR_ITER                16 (to 41)
             25 STORE_FAST               2 (i)

  8          28 LOAD_FAST                2 (i)
             31 LOAD_FAST                1 (const)
             34 BINARY_ADD
             35 STORE_FAST               3 (n)
             38 JUMP_ABSOLUTE           22
        >>   41 POP_BLOCK
        >>   42 LOAD_CONST               0 (None)
             45 RETURN_VALUE

while the second block gives:
>>> dis.dis(A.lengthy_op)
  5           0 SETUP_LOOP              30 (to 33)
              3 LOAD_GLOBAL              0 (xrange)
              6 LOAD_GLOBAL              1 (AVOGADRO)
              9 CALL_FUNCTION            1
             12 GET_ITER
        >>   13 FOR_ITER                16 (to 32)
             16 STORE_FAST               1 (i)

  7          19 LOAD_FAST                1 (i)
             22 LOAD_GLOBAL              2 (const)
             25 BINARY_ADD
             26 STORE_FAST               2 (n)
             29 JUMP_ABSOLUTE           13
        >>   32 POP_BLOCK
        >>   33 LOAD_CONST               0 (None)
             36 RETURN_VALUE

Python won't make a local copy of the global because there is no easy way to be sure that the global value won't change while the code is running. Anything, even another thread or a debugger, could modify the value while the loop is executing.

A: Whether it is faster or slower actually depends on your scope, the scopes are stored in dictionaries and the smaller the dictionary is the (marginally) faster the access will be. Since dictionaries are implemented as hashsets the lookup performance is O(1).
Whenever you try to access a variable Python will walk the scopes in this order:

*

*Local. The local namespace which is the current function scope.

*Enclosing function locals. Depending on the amount of nested functions/lambda's there can be more of these.

*Global. The global scope which is just another dictionary (which you can access through globals())

*Built-ins. The standard Python built-ins that are available in all scopes such as list, int, etc..

Accessing a function/class attribute works in a similar fashion but involves:

*

*__getattribute__

*__dict__

*__getattr__
And that over all inherited classes as well.
The rest of your question was answered perfectly by Duncan


Q: Instantiation of a template for local variable Is a template instantiated if a local automatic variable of that type is defined?
e.g.
template<typename T> class MyClass {
};

int main() {
  MyClass<int> var; // Does this cause instantiation?
}

Edit:
the reason why I'm asking this is the following code:
template<typename T> class get_false { public:
    static constexpr bool val = false;
};

template<typename T>
class MyClass_2 {
  static_assert(get_false<T>::val, "Failure");
};

template<typename T, typename U = MyClass_2<T>>
class MyClass {};

int main() {
    MyClass<bool> obj; // I suppose this isn't instantiated
}

A: Yes, it is instantiated.
#include <iostream>

template<typename T>
class MyClass {
    public:

    MyClass() {
        std::cout << "instantiated" << std::endl;
    }
};

int main() {
    MyClass<int> var;
}

The program outputs "instantiated"  ⇒  the MyClass constructor is called  ⇒  the var object is instantiated.


Q: Tensorflow with Keras: sparse_categorical_crossentropy I'm new on StackOverflow and I also recently started to work with Tensorflow and Keras. Currently I'm developing an architecture using LSTM units. My question was partially discussed here:
What does the implementation of keras.losses.sparse_categorical_crossentropy look like?
However, in my model I have a predicted tensor, y_hat, of size (batch_size, seq_length, vocabulary_dimension) and the true labels, y, of size (batch_size, seq_length).
I would like to know how the value of the loss is computed when I call
loss = sparse_categorical_crossentropy(y,y_hat): how does the sparse_crossentropy function calculate the loss value starting from two tensors of different dimensions?

A: The cross entropy is a way to compare two probability distributions. That is, it says how different or similar the two are. It is a mathematical function defined on two arrays or continuous distributions as shown here.
The 'sparse' part in 'sparse_categorical_crossentropy' indicates that the y_true value must have a single value per row, e.g. [0, 2, ...] that indicates which outcome (category) was the right choice. The model then outputs the y_pred that must be like [[.99, .01, 0], [.01, .5, .49], ...]. Here, model predicts that the 0th category has a chance of .99 in the first row. This is very close to the true value, that is [1,0,0]. The sparse_categorical_crossentropy would then calculate a single number with two distributions using the above mentioned formula and return that number.
If you used a 'categorical_crossentropy' it would expect the y_true to be a one-hot encoded vector, like [[0,0,1], [0,1,0], ...].
If you would like to know the details in depth, you can take a look at the source.


Q: Enhance Localization performances? (ComponentResourceManager.ApplyResources) After experiencing some performances issues on my client side, we decided to give a try to some of the performance profilers to try to find the bottleneck or identify the guilty parts of the code.
Of course, as many performance investigations, the problems comes from various things, but something I find out is that the ComponentResourceManager.ApplyResources of my user controls takes way too much time in the construction of my forms: more than 24% of the construction time is spent in the ApplyResources inside the InitializeComponent().
This seems rather a lot for only "finding a resource string and putting it in it's container".
What is exactly done in the ComponentResourceManager.ApplyResources ? I guess more than searching the string, if not it wouldn't take that long.
Is there a way to enhance the performances of the localization? Our software is localized in several languages, so we do need to keep this multi-lingual feature.
Any recommendations regarding this issue?
Thanks!
PS: We are coding in C#, .NET 3.5 SP1.

A: The ApplyResources method uses reflection to find the properties which will be updated with the resource values:

property = value.GetType().GetProperty(name, bindingAttr);

Reflection is notoriously slow. Assign the resource values by hand to the properties (e.g using ResourceManager.GetString(...)). This is tedious to code, but should improve the performance.

A: I would grab Reflector and take a look at the ApplyResources method to see what it actually does.
I would also recommend profiling using JetBrains dotTrace 4 (currently in EAP but trials can be downloaded), as it can also show times spent inside system classes. This makes it much more transparent where the time is actually spent. For instance, you can find out whether the time is spent looking up keys in a dictionary, accessing files, etc.
You could also do a micro benchmark and measure the time it takes to look up X keys in a Y-sized dictionary of strings, with X being the number of localized resources on a particular form and Y being the total resource pool. It will at least give you an idea of how fast you could look up the resources if you were to cache them in a dictionary, which may help you decide whether it is worthwhile to write your own resource provider.


Q: CSS problem with divs and inline components Imagine a code like this:

.div {
  width: 100%;
  height: 100px;
  background-color: green;
}

.div1 {
  width: 100px;
  height: 100px;
  background-color: red;
}

.div2 {
  width: 100px;
  height: 100px;
  background-color: blue;
}

.main {
  background-color: yellow;
}

It will render something like this:

I want that the blue div comes up and stay on the right of the red div. Imagine that I can´t change the divs from where they are, so I need to do it in css. How can I do it?

A: Without changing the markup, if you set float: left to the red
 then you could put the blue
 to its right side

.div {
  width: 100%;
  height: 100px;
  background-color: green;
}

.div1 {
  width: 100px;
  height: 100px;
  background-color: red;
  float: left;
}

.div2 {
  width: 100px;
  height: 100px;
  background-color: blue;
  display: inline-block;
  vertical-align: top;
}

.main {
  background-color: yellow;

}

A: The previous solution which uses float on the red div works well, but here is another possible solution:
Apply position: relative; to the blue div (to be able to move it in relation to its default position) and add top: -100px; left: 100px; to move it up next to the red div:

.div {
  width: 100%;
  height: 100px;
  background-color: green;
}

.div1 {
  width: 100px;
  height: 100px;
  background-color: red;
}

.div2 {
  width: 100px;
  height: 100px;
  background-color: blue;
  position: relative;
  top: -100px;
  left: 100px;
}

.main {
  background-color: yellow;
}

A: This can also be done with the grid CSS.  Here I used a named template box and then in the "chatty verbose" CSS I put the positional related for each "block".  I added classes to the CSS just for clarity but you could update to your classes.
I added some color and things just for clarity and visual references but kept the "position relate" in separate CSS chunks.

.main {
  font-size: 2rem;
  display: grid;
  grid-template: "box";
  background-color: yellow;
}

.main *,
.main::before {
  grid-area: box;
}

.green-block {
  place-self: start;
}

.red-block {
  width: 50%;
  place-self: end start;
}

.blue-block {
  width: 50%;
  place-self: end end;
}

.green-block {
  height: 3rem;
  background-color: green;
}

.red-block {
  height: 3rem;
  background-color: red;
}

.blue-block {
  background-color: blue;
}

.blue-block,
.green-block,
.red-block {
  /* color for clarity and just to super center the text in the blocks */
  display: grid;
  color: cyan;
  font-family: sans-serif;
  text-transform: uppercase;
  place-items: center;
}

green

red

blue


Q: Wordpress Customizer With External CSS File Is It possible Wordpress Customizer to create Dynamic CSS file and use it as external css file instead of Inlining it in header with function
add_action( 'wp_head', 'custom_css');

I need to make Header More Clean as it contains lots of CSS in header right now..

A: Some solution is to create PHP file which returns CSS code based on the variables provided via the GET parameters.
BUT:
1) You have to prepare a very strict sanitization as inproper value filtering can lead to security vulnerabilities,
2) The list of params cannot be too long as servers can have limits for the maximum URL length.


Q: drools can't get the data I need for the or condition rule "151"
    when
        $master:BusinessMaster()
        $map:HashMap() from $master.indexMap
        $mapads_mst_bas_info:HashMap() from $map.get("ads_mst_bas_info")
        $mapads_mst_order_mutl_stat4:HashMap() from $map.get("ads_mst_order_mutl_stat4")
        $resultMap:HashMap((( $mapads_mst_bas_info.get("mst_integral") >= 500 &&  <= 5000 ) || ( $mapads_mst_order_mutl_stat4.get("current_mon_bad_rate_num") >= 1 &&  <= 2 )) && ($mapads_mst_bas_info.get("remain_amount")>=5000)) from $master.indexMap
    then
        $master.getMasterLabel().add("151");
        insert($master);
end

This rule is the same as the following rule:
rule "151"
    when
        $master:BusinessMaster()
        $map:HashMap() from $master.indexMap
        $mapads_mst_bas_info:HashMap() from $map.get("ads_mst_bas_info")
        $mapads_mst_order_mutl_stat4:HashMap() from $map.get("ads_mst_order_mutl_stat4")
        $resultMap:HashMap((( $mapads_mst_bas_info.get("mst_integral") >= 500 &&  <= 5000 ) || $mapads_mst_order_mutl_stat4.get("current_mon_bad_rate_num") >= 1 && $mapads_mst_order_mutl_stat4.get("current_mon_bad_rate_num") <= 2 ) && ($mapads_mst_bas_info.get("remain_amount")>=5000)) from $master.indexMap
    then
        $master.getMasterLabel().add("151");
        insert($master);
end

Both rules have the same result

A: Your rules are identical. The only difference is a set of parentheses ( ) that don't actually matter because of order of operations / operator precedence rules.


Q: How does the SharePoint My Site display language feature work from a technical standpoint? I'm searching for a documentation of how SharePoint processes the display languages that users can configure in their My Site. Which components (services, timer jobs, caches...) of SharePoint are involved and how do they interact when changing this setting? How does a site "know" about the user's preferred language?
Here is a screenshot of the setting (sorry in German, because this darn feature does not work):

Currently I'm debugging a case where the language setting simply is not applied regardless of what the user configures. Language packs are installed, alternative site languages are enabled, we waited hours after changing the setting. No UI language change. So I want to understand the underlying mechanisms to know where to start looking.
My specific case is a SP 2013 on-prem environment but I assume the underlying architecture did not change much in SPO (at least for the classic experience) given that the classic My Site UI is still there. (It just got more complicated.)
Can anybody provide information or pointers to documentation/books where the architecture of this specific "display language" functionality is described? Or at least provide some insights as to why it might take an hour to apply this setting after making changes?

A: There are two timer jobs involved.  One synchronizes the language setting with Active Directory, or with a non-default user profile service in some cases.  That synchronization is typically not an issue.
The other is the one that controls what sites know, the "User Profile service application - User Profile to SharePoint language and region synchronization" timer job.  This goes to every site and updates the user-specific language setting on that site.  The timer job is typically once per minute but it sometimes doesn't get to it in time so it can take several minutes.
To see the current setting for the current user on that site, go to "_layouts/15/regionalsetng.aspx?Type=User"
SharePoint compares that setting, a ranked list, item by item with the list of alternate languages of the site, and uses the first one that matches, and if none match then it uses the list of browser languages, and if none of those match then it uses the site default language.  There is a bit of mapping for example if you have English (UK) rather than English (US).
In addition to that, SharePoint Online and SharePoint 2019 cache some menus and navigation so the language change can take a while, but you should be seeing a fair bit of the other languages right after the sync is done.

A: About the language settings in SharePoint, you could refer to this article:
https://support.microsoft.com/en-us/office/choose-the-languages-for-a-sharepoint-site-user-interface-16d3a83c-05ab-4b50-8fbb-ff576a3351e8
For it may take an hour to apply this setting after making changes, i think there should be a timer job running hourly to sync the language.


Q: How to fix this Node controller function and send data from 2 different models? There are 2 models booking and listing. The point is that for creating a booking we need to use listing details too and send all the details through the Nodemailer after the saving details in DB. here is the code:
Listing model:
const listingSchema = new Schema({
  bbusinessEmail: {
  type: String,
  },
  title: { type: String, required: true, max: [128, 'Too long, max is 128 characters']},
  city: { type: String, required: true, lowercase: true },
  street: { type: String, required: true, min: [4, 'Too short, min is 4 characters']},
  bookings: [{ type: Schema.Types.ObjectId, ref: 'Booking' }]
});
...

Booking model:
const bookingSchema = new Schema({
customerEmail: {
type: String,
match: [/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/]
},
  days: Number,
  listing: { type: Schema.Types.ObjectId, ref: 'Listing'},

Controller:
    exports.bookListing = async (req, res) => {
        if(!req.body.content) {
            return res.status(400).send({
                message: "Fields can not be empty"
            });
        }

        const smtpTransport = nodemailer.createTransport({
            service: 'Gmail',
            port: 465,
            auth: {
             user: 'email',
              pass: 'password'
            }
        });
        const { customerEmail, businessEmail, customerPhone, startAt, listing,
           totalPrice, days } = req.body;

  const booking = new Booking({
        customerEmail,
        customerPhone,
        startAt,
        totalPrice,
        days
    });

  let foundListing = await Listing.findById(listing._id).populate('bookings')
  if (err) {
      return res.status(422).send({message: "Error happened"});
    }

      booking.listing = foundListing;
      foundListing.bookings.push(booking);

    try {

      let data = await booking.save(), foundListing.save();

      var mailOptions = {
        from: data.customerEmail,
        to: data.businessEmail,
        subject: 'Listing Request',
        html: `
${data.startAt}

${data.totalPrice}

${data.customerPhone}

${data.days}
`
      };

      await smtpTransport.sendMail(mailOptions);

      smtpTransport.close();
      res.send(data);
    } catch(err) {
      res.status(500).send({
         essage: err.message || "Some error occurred while creating the listing."
        });
    }
    };

The controller gets data that includes fields from both Listing and booking models then it should save data inside the DB for both Listing and booking and then send the data through the email. How can this controller be fixed?


Q: Unexpected token '<' when loading coreui.bundle.min.js Every time I load the following:
<script src="~/vendor/@@coreui/coreui-pro/js/coreui.bundle.min.js"></script>

either before or after:
<script type="text/javascript"
                src="~/lib/jquery/dist/jquery.min.js"></script>

I got this:
Uncaught SyntaxError: Unexpected token '<'

any suggestion?


Q: How do I write minimal negations for the following statements? Write minimal negations for the following statements.  (In other words, if the statement below is $P,$ what would $¬P$ mean?)
a)  Everybody was kung-fu fighting for at least 10 hours.
b)  There is a river with at least two tributaries.
c)  No baboons wear bowler hats.
I get somewhat confused when it comes to negating the statement. I haven't fully grasped the concept. but this is what I was thinking and kinda feel like its wrong.
A) There is somebody who was kung-fu fighting for not 10 hours
B) There is not a river with at least two tributaries
C) All baboons wear bowler hats

A: Your reasoning is not quite correct. As it happens all of your answers are unsatisfactory in some way. Let's go through each:

A) There is somebody who was kung-fu fighting for not 10 hours

This is almost correct. If “$\neg$(Everybody is doing X)” then there has to be somebody who is not doing X. However, by saying “not 10 hours” you are mistaken: the correct negation is “less than 10 hours”.

B) There is not a river with at least two tributaries

Whilst this is a technically correct negation, it has not been simplified at all. You're likely expected to produce a sentence of the form “All rivers (...)”. I'll leave you to work this one out yourself; you can probably do so, maybe after reading the tips later on in this answer.

C) All baboons wear bowler hats

This is not a correct negation. To see why, try to negate the false statement “No cats are ginger”. By your logic, the negation, a true statement, should be “All cats are ginger”—a clearly false statement! The correct negation is “There is a baboon that wears a bowler hat”.

The general rules for solving this sort of problem can be written as so:

*

*$\neg(\text{All $X$s have property $Y$}) \Leftrightarrow (\text{There is an $X$ without property $Y$})$.

*$\neg(\text{There is an $X$ with property $Y$}) \Leftrightarrow (\text{All $X$s do not have property $Y$})$
Clearly, a) falls under rule 1, whereas b) falls under rule 2. It may be hard to see, but c) actually also falls under rule 1—can you see why? This should help you understand this kind of statement better.

If you'd like more justification, I recommend reading up on logical quantifiers. If these problems are part of a book or course on logic, you will likely encounter these very soon. Logical quantifiers allow rule 1, for instance, to be written as $\neg(\forall x, P(x)) \Leftrightarrow \exists x, \neg P(x)$.


Q: Ajax OnFailure function I have an AJAX.RouteLink which has the following AJAXOptions
new AjaxOptions
            {
                HttpMethod = "POST",
                OnFailure = "OnFailure",
                OnSuccess = "OnSuccess"
            })

My OnFailure method looks like this
function OnFailure(ajaxContext) {
        var response = ajaxContext.get_response();
        var statusCode = response.get_statusCode();

        var elem = document.getElementById('message');
        elem.innerHTML = 'Sorry, the request failed with status code' + statusCode;
    }

Problem is, when it gets called I get this error
TypeError: ajaxContext.get_response is not a function

In the watch list I can see that the responseText in ajaxContext is html.
What am I doing wrong here?

A: The problem was that ajaxContext doesn't have a get_response method.  It must be an old version of the object whose example I was looking at.
Since I wanted the status code, I just used the ajaxContext.status property.


Q: Javascript: using a while loop to repeat a function Let's say I have a collection of divs with the class "Foo" and I want to change the colors of the text incrementally over and over.  Each forEach should run this change one time but I need to run the function again to change them again.
If I want to repeat to continually run this function, what are my best options?   Should I throw it in a while loop?
    function colorWords() {
        let textBoxes = document.querySelectorAll(".foo");
        let colors = ["yellow","blue","green","red"];

        textBoxes.forEach((word, index) => {
           setTimeout(() => {
             word.style.color = colors[Math.floor(Math.rand()*colors.length)]
          }, 500 + index*250);

        },

    }

A: You may need setInterval.
Also replace Math.rand() with Math.random()

let colors = ["yellow", "blue", "green", "red"];
let interval
setInterval(() => {
  let textBoxes = document.querySelectorAll(".foo");
  textBoxes.forEach((word, index) => {
    interval = index;
    word.style.color = colors[Math.floor(Math.random() * colors.length)]
  }, 500 + interval * 250)
})

1

1

1

1

1

A: You can use setInterval to control the loop segment time.  Below I've set intervals to 250ms to get an idea of how frequent the updates occur:

let INTERVAL_IDS = []
document.querySelector('#start').addEventListener('click',start)
document.querySelector('#stop').addEventListener('click',stop)

function start(){
  let colors = ["yellow", "blue", "green", "red"];
  let textBoxes = document.querySelectorAll(".foo");

  INTERVAL_IDS.push(setInterval(function(){
    textBoxes.forEach(word =>
      word.style.color = colors[Math.floor(Math.random() * colors.length)]
    )
  },250))
}

function stop(){
  clearInterval(INTERVAL_IDS.pop())
}
<button id="start">start</button><button id="stop">stop</button>
H
e
l
l
o

A: Yeah, a while loop with a counter sounds reasonable. All inside of a setInterval function to fire at so many seconds.
let counter = 0
while( counter >= 10){
*your code*;
counter++
}```


Q: Last-Of Type and Last-Of-Child HTML:

...

...

...

...

CSS:
.plan-box:last-of-type {
    ...
}

In the above CSS code if I use last-of-type or last-child css selector on .plan-box will that select the last-child in both the .plan-box div which is the paragraph or will it select the second .plan-box div in the HTML code?

A: .plan-box:last-child Selects last of plan.box element
.plan-box :last-child Selects last elements in all of plan.box elements
Css Selectors

A: It will select second .plan-box div in the HTML code.
See the Link here
Again you can easily select any child div with CSS .Example is Here
I have used here .plan-box:nth-child(2) {} for select second div.


Q: SVG does not fit on Iphone - (.htaccess is the problem) I am getting crazy with the animated SVG of my website ( https://finbizimpactinvesting.com ). On the desktop it works well and the SVG fits in the middle of the monitor (chrome, safari, mac, windows all the combination) as well as android devices, but on Iphone mobile devices it does not fit whatever the browser it is.
I tried to play with the viewBox but it is almost impossible to make it fit on different devices with the same output.

<div class = "logo">

          <svg version="1.1" xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 100 100">
              <circle class="r" cx="41%" cy="41%" r="8" ></circle>
              <circle class="r" cx="59%" cy="41%" r="8" ></circle>
              <circle class="r" cx="41%" cy="59%" r="8" ></circle>
              <circle class="r" cx="59%" cy="59%" r="8" ></circle></svg>
                      </div>

.logo {
   position: absolute;
  top: -150px;
  z-index: -1;
  display: inline-block;
  max-width: 1225px;
  height: 250px;
  bottom: 0;
  right: 0;
  left: 0;
  margin: auto;
}

.logo svg {
  position: relative;
  left: 0px;
  top: -150px;
  right: 0;
  bottom: 0;
  width: 250px;
  margin: auto;
  fill: transparent;
  overflow: overlay;
}

.r {
  opacity: 0;
  stroke: #000000;
  stroke-width: 1px;
  stroke-dasharray: 130;
  -webkit-animation-name: vladi;
       -o-animation-name: vladi;
          animation-name: vladi;
  -webkit-animation-duration: 3s;
       -o-animation-duration: 3s;
          animation-duration: 3s;
  -webkit-animation-iteration-count: 1;
       -o-animation-iteration-count: 1;
          animation-iteration-count: 1;
  -webkit-animation-direction: alternate;
       -o-animation-direction: alternate;
          animation-direction: alternate;
  -webkit-animation-timing-function: ease-in;
       -o-animation-timing-function: ease-in;
          animation-timing-function: ease-in;
  -webkit-transform-origin: center center;
       -o-transform-origin: center center;
          transform-origin: center center;
}

@keyframes vladi {
  0% {
    stroke-dashoffset: 130;
    stroke: #000000;
    opacity: 1;
  }

  60% {
    fill: transparent;
    stroke-dashoffset: 0;
    stroke: #000000;
    stroke-width: 1px;
    opacity: 1;
  }

  70% {
    fill: #000000;
  }

  91% {
    -webkit-transform: scale(1);
         -o-transform: scale(1);
            transform: scale(1);
    opacity: 1;
  }

  92% {
    -webkit-transform: scale(0.9);
         -o-transform: scale(0.9);
            transform: scale(0.9);
  }

  100% {
    -webkit-transform: scale(2);
         -o-transform: scale(2);
            transform: scale(2);
    fill: #000000;
  }
}

Many Thanks!!!

A: I got the problem!! the issue is the .htaccess file that i am using to force the http into htpps. I don't know why but with it the Svg does not work and without it the SVG works great.


Q: TypeError: config.headers.has is not a function Getting errors when executing test cases in Redux Tool Kit query,

*

*Used React Native Testing Library for rendering components.

An unhandled error occurred processing a request for the endpoint "getProducts".
    In the case of an unhandled error, no tags will be "provided" or "invalidated". TypeError: config.headers.has is not a function

jestSetup.ts:
jest.useFakeTimers()
jest.mock('react-native/Libraries/Animated/NativeAnimatedHelper');
jest.mock('node-fetch');
require('jest-fetch-mock').enableMocks()

Tried with mocking node-fetch


Q: How to create multiple links from a single array of strings Rails - Ruby I know it might seem simple but I've tried to create multiple links from this array in Rails
array = ["/uploads/content/attachment/folder/file1.pdf/file2.pdf/file3.pdf"]

What I want to do is create a link for file1 and another for file2 and so on.
I've tried to use the join and separate method, image_tag, content_tag and many many different cycles in Rails but every single one ends up like the link above.

A: Something like this if I understood correctly:
array = ["/uploads/content/attachment/folder/file1.pdf/file2.pdf/file3.pdf"]
base = "https://www.example.com/" #the first part of the link, that's same for all links

links = array.first[1..-1].split("/").map{|a| base + a}
puts links
#=>  "https://www.example.com/uploads",
#    "https://www.example.com/content",
#    "https://www.example.com/attachment",
#    "https://www.example.com/folder",
#    "https://www.example.com/file1.pdf",
#    "https://www.example.com/file2.pdf",
#    "https://www.example.com/file3.pdf"

A: The question is not clear.
I assume the array will be like this:
array = [
  "/uploads/content/attachment/folder/file1.pdf/file2.pdf/file3.pdf",
  "/uploads/content/attachment/folder/file12.pdf/file23.pdf/fildf34.pdf",
  "/foo/boo/folder/file1.doc/file2.docx/file11.pdf"
]

It splits links for folder/
links = array.map{ |a| a.split('folder/') }.flat_map do |path, files|
  files.split('/').map{ |file| path + "folder/" + file }
end

p links
#=> [
      "/uploads/content/attachment/folder/file1.pdf",
      "/uploads/content/attachment/folder/file2.pdf",
      "/uploads/content/attachment/folder/file3.pdf",
      "/uploads/content/attachment/folder/file12.pdf",
      "/uploads/content/attachment/folder/file23.pdf",
      "/uploads/content/attachment/folder/fildf34.pdf",
      "/foo/boo/folder/file1.doc",
      "/foo/boo/folder/file2.docx",
      "/foo/boo/folder/file11.pdf"
    ]


Q: Bitmap 16bpp A1R5G5B5 to 32bpp I need to read the values R, G and B image with a bit mask for 16bpp A1R5G5B5 in PHP, I know you have to understand Bitwise, but I'm not very good in this matter, so does anyone could show me how to do this?
Sorry for the English, is that I am Brazilian and I am using a translator.

A: A1R5G5B5 Bitmasks:
       ARRR RRGG  GGGB BBBB

ALPHA: 1000 0000  0000 0000 - 0x8000
RED:   0111 1100  0000 0000 - 0x7c00
GREEN: 0000 0011  1110 0000 - 0x3e0
BLUE:  0000 0000  0001 1111 - 0x1f

Use the bitmask with the bitwise AND operator to obtain the value:
$word  = /* two-byte (two octets) value per pixel */
$alpha = $word & 0x8000;
$red   = $word & 0x7c00;
...

Hope this helps. A PHP function that gives you the integer value for a binary number in PHP is bindec, a function to convert an integer to a hexadecimal number is dechex. Those functions are helpful to create a hexadecimal bitmask number from within PHP.
You can use as well a calculator to convert between binary, decimal and hexadecimal numbers, e.g. with a calculator like gcalctool.
Example code:
/**
 * unpack a binary string word of a
 * A1R5G5B5 color into an array of
 * RGBA integer 8bit values.
 *
 * @param string $word
 * @return array('red' => int, 'green' => int, 'blue' => int, 'alpha' => int)
 */
function wordA1R5G5B5ToArrayRGBA($word)
{
    // unpack values from bit-fields
    list(, $dec) = unpack('n', $word);
    $blue  = ($dec & 0x1F);
    $green = ($dec & 0x3E0) >> 5;
    $red   = ($dec & 0x7C00) >> 10;
    $alpha = ($dec & 0x8000) >> 15;

    // map 5bit to 8bit (alpha: 1bit to 8bit)
    $blue = ($blue << 3) | ($blue * 0x7 / 0x1F);
    $green = ($green << 3) | ($green * 0x7 / 0x1F);
    $red = ($red << 3) | ($red * 0x7 / 0x1F);
    $alpha && $alpha = 0xFF;

    return compact('red', 'green', 'blue', 'alpha');
}


Q: use  tags only body part on Newsletter Email template in PHP I have been sending a Newsletter using Email Template, and it's working fine.
But I have a problem with Body part in my newsletter.
Because I have used strip_tags PHP function for removing
 tags from Template,
Now I need
 tags only for body parts, so any way I will use
 tags for only body part?


Q: Javascript - Change page style without showing previous one I have a website that I want to add different styles to. The user may choose any style he wants, I store it in localStorage and display it. I have this code:
<link href="default.css" type="text/css" rel="stylesheet" onload="this.href = window.localStorage['webpage_style'];"/>
This works OK, but I have a problem with buttons. The default.css is white style - just like here on stack overflow. But the new one is dark style, with dark gray background and so on. My problem with the button is: on every page load with that new dark style, the button is white and then changes to dark rapidly, but the white moment is clearly visible and it looks awful. What can I do to stop the effect on page load?
Here are both CSS:

button {
  width: 88%;
  padding: 1.5em;
  background-color: white;
  border: 1px solid black;
  margin: 1.8%;
  margin-bottom: 0.2%;
  cursor: pointer;
  transition: background-color 0.3s ease-in-out;
}

button:hover {
  background-color: #e8e8e8;
}

button:focus {
  outline: none;
}
<button>Sample - Default CSS</button>

button {
  width: 88%;
  padding: 1.5em;
  background-color: white;
  border: 1px solid #c8c8c8;
  /* Change here */
  margin: 1.8%;
  margin-bottom: 0.2%;
  cursor: pointer;
  transition: background-color 0.3s ease-in-out;
  background-color: #272323;
  /* Change here */
  color: #c8c8c8;
  /* Change here */
}

button:hover {
  background-color: #3b3636;
  /* Change here */
}

button:focus {
  outline: none;
}
<button>Sample - Dark CSS</button>

What can I do to not show that effect? The button turns from white to black in like 0.3s. Is there any way to do it? Or should I just remove the transition line in CSS (that stops the effect, but is there any other way)?

A: You're telling the browser to wait for the load-event, this (from the aforementioned MDN-docs):

...fires at the end of the document loading process. At this point, all of the objects in the document are in the DOM, and all the images, scripts, links and sub-frames have finished loading.

Hence, don't use onload if you don't need to wait for the DOM to be ready.
<link href="default.css" type="text/css" rel="stylesheet" id="dynamic_stylesheet" />
<script>
if (window.localStorage['webpage_style']) {
  var styleLink = document.getElementById("dynamic_stylesheet");
  styleLink.href = window.localStorage['webpage_style'];
}
</script>

Or if that still introduces a flash you could write the style link conditionally in JS.
<script>
    if (window.localStorage['webpage_style']) {
        document.write("<link href=\""+window.localStorage['webpage_style']+"\" type=\"text/css\" rel=\"stylesheet\" />");
    } else {
        document.write("<link href=\"default.css\" type=\"text/css\" rel=\"stylesheet\" />");
    }
</script>
<noscript>
    <link href="default.css" type="text/css" rel="stylesheet" />
</noscript>


Q: Instability of DNS with bind9 I've setup a DNS with bind9 (9.9.5) on Ubuntu 14.04/trusty (kernel 4.4.0-59) for my local network.  It is working, but sometimes it fails to find an IP of a host (e.g. ping says: ping: unknown host aypi1.bxlab).
My setup is as follows.
/etc/bind/named.conf.options:
options {
        directory "/var/cache/bind";
        dnssec-validation auto;

        auth-nxdomain no;
        listen-on-v6 { none; };

        allow-query {
          127.0.0.1;
          192.168.0.0/24;
        };
};

/etc/bind/named.conf.local:
zone "bxlab" IN {
  type master;
  file "/etc/bind/db.intra";
};

zone "0.168.192.in-addr.arpa" IN {
  type master;
  file "/etc/bind/db.0.168.192";
};

/etc/bind/db.intra:
$TTL 1D    ;

@ IN SOA bxlab. root.bxlab (
  2011102401 ; Serial
  3H         ; Refresh
  1H         ; Retry
  1W         ; Expire
  1D )       ; Minimum

                  IN NS  aypi1.bxlab. ;
aypi0              IN A   192.168.0.10 ;
aypi1              IN A   192.168.0.11 ;
aypi2              IN A   192.168.0.12 ;

ns                 IN CNAME aypi1  ;

/etc/bind/db.0.168.192:
$TTL 1D    ;

@ IN SOA ns.bxlab.  root.ns.bxlab (
  2011102301 ; Serial
  3H         ; Refresh
  1H         ; Retry
  1W         ; Expire
  1D )       ; Minimum

    IN NS  ns.bxlab.
    IN PTR bxlab.
    IN A 255.255.255.0
10  IN PTR aypi0        ;
11  IN PTR aypi1        ;
12  IN PTR aypi2        ;

I also changed my router configurations as follows:
Primary DNS: 192.168.0.11
Secondary: xxx.xxx.xxx.xxx  (DNS IP Provided by ISP)

The trouble is:

*

*After restarting bind9, nslookup worked with aypi1.bxlab.

*After 30 min (?), ping aypi1.bxlab returned ping: unknown host aypi1.bxlab.

*But waiting some seconds (maybe 6 sec?), ping became to work.

*2 and 3 are repeated.

Do anybody have an idea to figure this out?
Many thanks!

A: As @pete pointed out in the comments above, the issue was the router configuration.
I modified the router DNS setting as:
Primary DNS: 192.168.0.11
Secondary: 0.0.0.0

Then I modified /etc/bind/named.conf.options as:
options {
        [...]

        forwarders {xx.xx.xx.xx; xx.xx.xx.yy; xx.xx.xx.zz;};
        forward first;
};

The IPs in forwarders are DNS from ISP.


Q: Escaping quotes and html in a data- attribute JSON object Using the HTML5 data- attribute, one can store JSON in HTML as shown in the HTML below. This works great with string key:value pairs but I can't figure out how to make the values include special characters or HTML.
The part of the JSON object that is giving problems is this: Can't vote on own review (also interested in more complicated HTML chunks like this: <span style="text-decoration:underline" own. Here's a JSFiddle for the code below.
JS:
$('button').on('click', function () {
  var $this=$(this), data=$this.data('data');
     $('#output').html(data.message);
});

HTML:
<button type='button' data-data='{"type": "voting", "message": "Can't vote on <span style="text-decoration:underline" own review"}'></button>

A: You need to escape the HTML and specifically in this example, & and the character used to quote the attribute value (either " or '):
<button type='button' data-data='{"type": "voting", "message": "Can't vote on own review"}'></button>

or:
<button type='button' data-data='{"type": "voting", "message": "Can't vote on own review"}'></button>


Q: Why does this binding display a class name? What might cause the value of a Silverlight 4 DataGridTextColumn.Header to display as System.Windows.Data.Binding rather than the resolved bound value? It seems like a ToString is happening somewhere that displays a class name rather than the formatted value of the class.
The binding looks like this
Header="{Binding Path=Dummy,Source={StaticResource languagingSource},Converter={StaticResource languagingConverter},ConverterParameter=vehicleDescription}"

and the problem doesn't lie anywhere within the binding as identical bindings, with different ConverterParameter values, work fine for Button.Content and TextBlock.Text properties within the same XAML page.
Even creating a simple string property like this within the local data context has the same result.
public string DataGridHeaderDescription { get { return "Description"; } }

Header="{Binding DataGridHeaderDescription}"

I've even tried adding a string format
Header="{Binding DataGridHeaderDescription,StringFormat=\{0\}}"

but this has no effect either.

A: It is now possible to using bindings even on elements that aren't derived from FrameworkElement however the property of the element being bound must be defined as a DependencyProperty which Header is not.
Since Header is simply a place marker for any content to be placed in the header you could simply do this:-
<DataGridTextColumn.Header>
  <TextBlock Text="{Binding Path=Dummy,Source={StaticResource languagingSource},Converter={StaticResource languagingConverter},ConverterParameter=vehicleDescription}" />
</DataGridTextColumn.Header>

A: After some further searching I found this thread that answers the question and gives some suggested solutions.
Dynamically setting the Header text of a Silverlight DataGrid Column


Q: Conditional count based on second variable I'm still somewhat new to  R, so please bear with me. I'm trying to summarize the results of the variable riskT0. However, because I have some missing values in the variable riskT2 I would like to only include participant values if they have also a value for the riskT2 variable.
reproducible example:
ID <- c(1:300) #participants
group <- c(1:2) #there are two groups
riskT0 <- c(1:2) #value of 1st measurement
riskT2 <- c(1:3) #value of 2nd measurement
df<- data.frame(ID,group,riskT0,riskT2) #create df
df["riskT2"][df["riskT2"] == 3] <- "NA" #create NAs (I'm sure there are better ways)

What is the simplest way to summarize the riskT0 variable if a riskT2 value is available?
Also how to do the same but then do it separately for group 1 and 2?
The way I was trying to get the results so far was the following:
"count(df$riskT0[df$riskT2 !=NA])

which doesn't work. Also I wouldn't know how to filter for group.
Thank you in advance.

A: If you want to summarize riskT0 you can do
with(subset(df, df$riskT2 != "NA"), summary(riskT0))

subset creates new dataframe out from df by eliminating all the rows of df where riskT2 takes NA. Passing this temporary dataframe to with hepls at making the variable riskT0 available for summary.

A: Don't set "NA" as a string. Set it as its own type NA:
df["riskT2"][df["riskT2"] == 3] <- NA
This does not change the type of the other values: as you have it, riskT2 changes type from integer to character after assignment of "NA".
Then, to address your question, you need to use is.na(x) to check for NA values in a variable x.
For a count of all riskT0 values conditioned on the riskT2 being NA you would write:
table(df$riskT0[!is.na(df$riskT2)])


Q: How to use IF and ELSE statement for MS query
Databasename: PEMS
Table name: AccountInfo
columns: AccountID, SubscriberID, Location,Passwords,AccountStatus

AccountStatus values inside are 'Activated' and 'Deactivated'
Accepts or rejects an accountID based on their AccountStatus.
Example: if an account has an AccountStatus of 'Deactivated' it will prompt that AccountID is blocked.
AcctID  48 and AccountStatus Deactivated it will reject when attempting to log in


Q: My Ajax is trying to render a view that it shouldn't So everything works. But if a user has firebug's console open, they'll see a bug. :D
When my AJAX is sent :
$(".remove_qf").live("click", function(){
  $.ajax({type: "POST", url: $(this).attr("href"), data: { '_method': 'delete' }, dataType: "script"});
  return false;
})

And my controller fires it :
def destroy
  @quick_fact = @organization.quick_facts.find(params[:id])
  @quick_fact.destroy
end

A view is fired and errors out on a 500 :
Missing template quick_facts/destroy.erb in view path app/views:vendor/plugins/rails-ckeditor/app/views

Strange though, because I don't need a destroy view, and I shouldn't add any code to what I have already to tell it to render false. I say this because I have something similar working my project with the same premise.
Anyone know what might be causing this?
 Update
Routes.rb
map.resources :organizations,
  :collection => {:live_validation => :post, :search => :get, :send_invitation_code_request => :post} do |organization|
    organization.resources :quick_facts

A: I am not an expert in this area, however, I think that 1.) you need to add a handler to your ajax call to determine if the delete was successful & 2.) you may need to add some sort of success status message from the controller's destroy action.

A: The following solved the same problem for me.
respond_to do |format|
    format.js { head :ok }
end

I'm unsure if this is better practice than using render :nothing => true or render :text => "".


Q: grails JSON binding to LinkedHashSet instead of JSONArray for deeply nested relation I have three levels deep of a hierarchy that I am binding in a JSON request:
Group -> Zone -> Segment
(1) -> (n) -> (n)

In my command object I have:
class GroupCommand {
    Long id
    Set zones

}

When binding the JSON request the zones get bound properly and I get a LinkedHashSet that I can get the properties of and use with my domain object. However when I get to iterating over the segments in my service:
groupCommand.zones.each { zone ->
    zone.segments.each { segment ->
        //Would like to get LinkedHashMap here also
        //but get JSONArray
    }
}

As noted above, I'd ideally like the deeply nested Segments to also bind to a LinkedHashMap but it's bound to a JSONArray.
Any suggestions how to get it bound to a LinkedHashMap as I'd like to avoid having to manipulate JSONArray in my service and thereby coupling my service with the JSON format.
If there's a way to do the conversion at the command level using a getter I'm all for that also.
thanks
EDIT:
Using
List zones = org.apache.commons.collections.list.LazyList.decorate(new ArrayList(), new org.apache.commons.collections.functors.InstantiateFactory(ZoneCommand.class))

appears to work but the underlying objects are still JSON elements. I then tried using:
List<RateZoneCommand> zones = org.apache.commons.collections.list.LazyList.decorate(new ArrayList(), new org.apache.commons.collections.functors.InstantiateFactory(ZoneCommand.class))

and at least I got an error indicating it trying to convert:
Validation error: ... org.codehaus.groovy.grails.web.json.JSONArray to required type java.util.List for property zones; nested exception is java.lang.IllegalStateException: Cannot convert value of type [org..JSONObject] to required type [ZoneCommand] for property zones[0]: no matching editors or conversion strategy found.

A: Create a command class for each level. Mark Zone- and Segment-command as @Validateable.
To your GroupCommand, add:
List zones = org.apache.commons.collections.list.LazyList.decorate(new ArrayList(), new org.apache.commons.collections.functors.InstantiateFactory(ZoneCommand.class))

To your ZoneCommand, add:
List segments = org.apache.commons.collections.list.LazyList.decorate(new ArrayList(), new org.apache.commons.collections.functors.InstantiateFactory(SegmentCommand.class))

In your form just use group.zones[0].segments[0]. If you change a field type of your command class, remember to restart the grails server.


Q: Clock not updating every second using moment.js First time using moment.js and I am struggling to implement a clock to show the time in CET and PST. My code is as follows:
function cetClock() {
    var cet = moment.tz("Europe/London");
    var today = new Date(cet);
    var h = today.getHours();
    var m = today.getMinutes();
    var s = today.getSeconds();
    m = checkCetTime(m);
    s = checkCetTime(s);
    $rootScope.cetTime =  h + ":" + m + ":" + s;
    var t = setTimeout(cetClock, 300);
}
function checkCetTime(i) {
    if (i < 10) {i = "0" + i};  // add zero in front of numbers < 10
    return i;
}

cetClock()

CET: {{$root.cetTime}}

The issue I have is that the time in the view is only being updated every 4-5 seconds. If I log the h, m, s within the function, it shows every 500 milliseconds the time being updated.
Question
Why is the clock in the viiew failing to update every second?

A: I suggest using $timeout instead of setTimeout which will automatically trigger a digest cycle.


Q: how to convert the topics into just a list of the top 20 words in each topic in LDA in python I am currently working on LDA logarithm in python. I want to covert the topics into just a list of the top 20 words in each topic. I tried below code but got different output.
I want my output in following format: topic=2,words=20.
['men', 'kill', 'soldier', 'order', 'patient', 'night', 'priest', 'becom', 'new', 'speech', 'friend', 'decid', 'young', 'ward', 'state', 'front', 'would', 'home', 'two', 'father']

["n't", 'go', 'fight', 'doe', 'home', 'famili', 'car', 'night', 'say', 'next', 'ask', 'day', 'want', 'show', 'goe', 'friend', 'two', 'polic', 'name', 'meet']

I got below output:
["(u'ngma', 0.034841332255132154)", "(u'video', 0.0073756817356584745)", "(u'youtube', 0.006524039676605746)", "(u'liked', 0.0065240394176856644)",]
["(u'ngma', 0.024537057880333127)", "(u'photography', 0.0068263432438681482)", "(u'tvallwhite', 0.0029535361359022566)", "(u'3', 0.0029252727655122079)"]

My code:
`ldamodel = Lda(doc_term_matrix, num_topics=2, id2word = dictionary,passes=50)
lda=ldamodel.print_topics(num_topics=2, num_words=3)

f=open('LDA.txt','w')
f.write(str(lda))
f.close()

topics_matrix = ldamodel.show_topics(formatted=False,num_words=10)
topics_matrix = np.array((topics_matrix),dtype=list)
topic_words = topics_matrix[:, 1]
for i in topic_words:
    print([str(word) for word in i])
    print()`

edit-1:
topic_words = []
for i in range(3):
    tt = ldamodel.get_topic_terms(i,10)
    topic_words.append([pair[0] for pair in tt])
    print topic_words

resulted in non expected output:
[[1897, 135, 130, 127, 70, 162, 445, 656, 608, 1019], [1897, 364, 56, 1236, 181, 172, 449, 48, 15, 18], [1897, 163, 11, 70, 166, 345, 480, 9, 60, 351]]

A: Try this-
from gensim import corpora
import gensim
from gensim.models.ldamodel import LdaModel
from gensim.parsing.preprocessing import STOPWORDS

# example docs
doc1 = """
Java (Indonesian: Jawa; Javanese: ꦗꦮ; Sundanese: ᮏᮝ) is an island of Indonesia.\
 With a population of over 141 million (the island itself) or 145 million (the \
 administrative region), Java is home to 56.7 percent of the Indonesian population \
 and is the most populous island on Earth.[1] The Indonesian capital city, Jakarta, \
 is located on western Java. Much of Indonesian history took place on Java. It was \
 the center of powerful Hindu-Buddhist empires, the Islamic sultanates, and the core \
 of the colonial Dutch East Indies. Java was also the center of the Indonesian struggle \
 for independence during the 1930s and 1940s. Java dominates Indonesia politically, \
 economically and culturally.
 """
doc2 = """
Hydrogen fuel is a zero-emission fuel when burned with oxygen, if one considers water \
not to be an emission. It often uses electrochemical cells, or combustion in internal \
engines, to power vehicles and electric devices. It is also used in the propulsion of \
spacecraft and might potentially be mass-produced and commercialized for passenger vehicles \
and aircraft.Hydrogen lies in the first group and first period in the periodic table, i.e. \
it is the first element on the periodic table, making it the lightest element. Since \
hydrogen gas is so light, it rises in the atmosphere and is therefore rarely found in \
its pure form, H2."""

doc3 = """
The giraffe (Giraffa) is a genus of African even-toed ungulate mammals, the tallest living \
terrestrial animals and the largest ruminants. The genus currently consists of one species, \
Giraffa camelopardalis, the type species. Seven other species are extinct, prehistoric \
species known from fossils. Taxonomic classifications of one to eight extant giraffe species\
 have been described, based upon research into the mitochondrial and nuclear DNA, as well \
 as morphological measurements of Giraffa, but the IUCN currently recognizes only one \
 species with nine subspecies.
"""

documents = [doc1, doc2, doc3]
document_wrd_splt = [[word for word in document.lower().split() if word not in STOPWORDS] \
for document in documents]

dictionary = corpora.Dictionary(document_wrd_splt)
print(dictionary.token2id)

corpus = [dictionary.doc2bow(text) for text in texts]

lda = LdaModel(corpus, num_topics=3, id2word = dictionary, passes=50)

num_topics = 3
topic_words = []
for i in range(num_topics):
    tt = lda.get_topic_terms(i,20)
    topic_words.append([dictionary[pair[0]] for pair in tt])

# output
>>> topic_words[0]
['indonesian', 'java', 'species', 'island', 'population', 'million', '(the', 'java.', 'center', 'giraffe', 'currently', 'genus', 'city,', 'economically', 'administrative', 'east', 'sundanese:', 'itself)', 'took', '1940s.']
>>> topic_words[1]
['vehicles', 'fuel', 'hydrogen', 'periodic', 'table,', 'i.e.', 'uses', 'form,', 'considers', 'zero-emission', 'internal', 'period', 'burned', 'cells,', 'rises', 'pure', 'atmosphere', 'aircraft.hydrogen', 'water', 'engines,']
>>> topic_words[2]
['giraffa,', 'even-toed', 'living', 'described,', 'camelopardalis,', 'consists', 'extinct,', 'seven', 'fossils.', 'morphological', 'terrestrial', '(giraffa)', 'dna,', 'mitochondrial', 'nuclear', 'ruminants.', 'classifications', 'species,', 'prehistoric', 'known']


Q: How to make SELECT more faster without NESTED LOOP Hello i'm making a website for webshop for t-shirts. Every product (from all 1400) has own ID (idedro), but every ID has different colors, sometimes one, sometimes twenty.
I need to show every product in own picture with all colors it has below, but i think a loop inside of a loop takes too much CPU time. Is there any way to make it with one loop may or enter image description herebe with JOIN or prepared statments?
$querycount = mysqli_query($link,"SELECT DISTINCT (idedro)
    FROM megadb WHERE catteniskiipotnici=1 ORDER BY idedro ASC");

  while ($rowcounts = mysqli_fetch_assoc($querycount)) {

  $result1 = mysqli_query($link,"SELECT color
    FROM megadb WHERE idedro='$rowcounts[idedro]'");

       while ($row1=mysqli_fetch_array($result1)) { echo $row1[color]; }
      }

A: This should do what you want using GROUP_CONCAT():
SELECT idedro, group_concat(color)
FROM megadb
WHERE catteniskiipotnici=1
GROUP BY idedro
ORDER BY idedro ASC

SQL Fiddle
MySQL 5.6 Schema Setup:
CREATE TABLE megadb
    (`idedro` int, `color` varchar(5), `catteniskiipotnici` int)
;

INSERT INTO megadb
    (`idedro`, `color`, `catteniskiipotnici`)
VALUES
    (1, 'blue', 1),
    (2, 'blue', 1),
    (2, 'red', 1),
    (3, 'blue', 1),
    (3, 'red', 1),
    (3, 'white', 1),
    (4, 'blue', 0)
;

Query 1:
    SELECT idedro, group_concat(color)
    FROM megadb
    WHERE catteniskiipotnici=1
    GROUP BY idedro
    ORDER BY idedro ASC

Results:
| idedro | group_concat(color) |
|--------|---------------------|
|      1 |                blue |
|      2 |            blue,red |
|      3 |      blue,red,white |


Q: React firebase doesn't await I want to get data from firebase and map it and render a table with it but the firebase function returns data after the page loads.
    const [datas, setData] = useState();
    var ref = db.ref("something");

    useEffect(() => {
      const fetchData = async () => {
        await ref.once("value").then((snapshot) => {
          const fetched = snapshot.val();
          var feed = {'name':'shoe','remark':'remarka','price':'pricea','photo':'photo','amount':'350'};
          console.log('fetched', fetched)
          setData(feed);
        });
      };
      fetchData();
    }, []);

now if I make a var here
let's say var text= datas
and console.log it it will return undefined
the feed var is just some dummy text
{dummy.map((data, key) => {
//render table
})

is there any way to make the page wait for the function to finish the useState ?

A: Use the AND operator (&&) which only executes the right operand when the left operand is truthy. It is not necessary to make a variable called dummy.
{
  datas && datas.map(data=>{
     console.log(data);
  });
}


Q: how to show numpy array imshow plotly as frames? Create an array and make a picture out of it
xg = np.random.rand(100, 22400)
fig = px.imshow(a,aspect="auto", color_continuous_scale='gray')
out1.show()

The problem is that the array is long and the graph does not work correctly, is it possible to display the array in frames (since each value is already a pixel)?

A: *

*you can use animations to split into frames

*have sliced numpy array to create frames

import numpy as np
import plotly.graph_objects as go
import plotly.express as px

xg = np.random.rand(100, 22400)
# xg = np.random.rand(10, 1200)

base = px.imshow(xg, aspect="auto", color_continuous_scale="gray")
frameSize = 400

frames = [
    go.Frame(
        data=px.imshow(
            xg[:, x : x + frameSize], aspect="auto", color_continuous_scale="gray"
        ).data,
        name=x,
    )
    for x in range(0, xg.shape[1], frameSize)
]

go.Figure(data=frames[0].data, frames=frames, layout=base.layout).update_layout(
    updatemenus=[{
        "buttons": [{"args": [None, {"frame": {"duration": 500, "redraw": True}}],
                    "label": "▶",
                    "method": "animate",
                },],
        "type": "buttons",
        }],
    sliders=[{
        "steps": [{"args": [[d],
                            {"frame": {"duration": 0, "redraw": True},
                             "mode": "immediate",},],
                    "label": d,
                    "method": "animate",
                  }
                  for d in range(0, xg.shape[1], frameSize)
                 ],
        }],
)


Q: Prevent css media types from changing the print version Currently developing a website that uses responsive css to change it's layout for smaller devices / screens etc.
The client has asked to be able to print the website from anywhere how it appears on desktop, so whichever style of print you do then it would always print the desktop version.
We have thousands of lines of css (4,000+) so it's not as simple as just making a media print{}.
The following is an example of the current layout:
div.container{
    font-size:16px;
}

@media (min-width: 991px) {
    div.container{
        font-size:18px;
    }
}

@media (max-width: 991px) and (min-width: 768px){
    div.container{
        font-size:20px;
    }
}

@media (max-width: 991px)  {
    div.container{
        font-size:22px;
    }
}

The problem is when you press ctrl + p for your print preview, the print area is smaller and thus the smaller media css is applied and we don't see the website as we do on a desktop screen.
Is there anyway to apply the @media css but prevent it from affecting the print version?
@media (max-width: 991px),
!print{

}

A: You could use @media screen instead of just @media so that the codes will work in screen but not in the print version.
Example:
@media screen and (min-width: 991px) {
    div.container{
        font-size:18px;
    }
}


Q: Groupby multiple row and keep two columns in pandas I have dataframe in format name, actor_link, movie_link and I want to group it by actor link to format name, actor_link, list_of_movies_where_actor_appears
example input
Tom Hanks,https://www.csfd.cz/tvurce/330-tom-hanks/,https://www.csfd.cz/film/10135-forrest-gump/
Tom Hanks,https://www.csfd.cz/tvurce/330-tom-hanks/,https://www.csfd.cz/film/2292-zelena-mile/

example output
Tom Hanks,https://www.csfd.cz/tvurce/330-tom-hanks/,[https://www.csfd.cz/film/10135-forrest-gump/,https://www.csfd.cz/film/2292-zelena-mile/]

my code is giving output
Tom Hanks,https://www.csfd.cz/tvurce/330-tom-hanks/,"['Tom Hanks', 'https://www.csfd.cz/film/10135-forrest-gump/', 'Tom Hanks', 'https://www.csfd.cz/film/2292-zelena-mile/']

code
original_actor_df = pd.read_csv('actors.csv')
actor_movies_df = original_actor_df.set_index("actor_link").stack().groupby(level=0).apply(list).reset_index(name="movies")
original_actor_df.drop(['movie_link'], axis=1, inplace=True)
original_actor_df.drop_duplicates(inplace=True)
actor_df = pd.merge(original_actor_df, actor_movies_df, on="actor_link")

How can I get rid of actor name in column with movie links? Can I simplify this process with dataframe without so many steps? I think it could be possible with adjusting
original_actor_df.set_index("actor_link").stack().groupby(level=0).apply(list).reset_index(name="movies")

I tried, I failed ...

A: Hey there fellow Czech programmer! <3
This might get the job done, i think...
import pandas as pd

df = pd.read_csv('MOCK_DATA.csv')

# group by actor_link and count the number of movies
g = df.groupby(['actor','actor_link'])['movie'].apply(list).reset_index(name='list_of_movies')
# output res to a csv file
g.to_csv('actor_movies.csv', header=False, index=False)

Tested on this file:
actor,actor_link,movie
Yardley McGilroy,www.csfd/Yardley McGilroy.cz,Sharknado 2: The Second One
Woodman Meese,www.csfd/Woodman Meese.cz,The Amazing Catfish
Marijo Thorburn,www.csfd/Marijo Thorburn.cz,"Soldier, The"
Arron Rosenfield,www.csfd/Arron Rosenfield.cz,Barcelona
Olga Wainscot,www.csfd/Olga Wainscot.cz,Addicted
Bradan Ivashev,www.csfd/Bradan Ivashev.cz,Fury
Lu Manjin,www.csfd/Lu Manjin.cz,"Sea Inside, The (Mar adentro)"
Shelby Kitt,www.csfd/Shelby Kitt.cz,"Set-Up, The"
Barbaraanne Yakushkin,www.csfd/Barbaraanne Yakushkin.cz,"Princess Blade, The (Shura Yukihime)"
Abbey Munkton,www.csfd/Abbey Munkton.cz,Twin Peaks: Fire Walk with Me
Vittoria Clayal,www.csfd/Vittoria Clayal.cz,"Cider House Rules, The"
Vickie Ormrod,www.csfd/Vickie Ormrod.cz,Hustler White
Artemas Solomonides,www.csfd/Artemas Solomonides.cz,Satyricon
Lucita Whittick,www.csfd/Lucita Whittick.cz,"Exterminator, The"
Cullen Kear,www.csfd/Cullen Kear.cz,Non-Stop
Tine Slaney,www.csfd/Tine Slaney.cz,Measuring the World (Die Vermessung der Welt)
Allister Caulcott,www.csfd/Allister Caulcott.cz,Beat the Devil
Dannie Sheara,www.csfd/Dannie Sheara.cz,Casanova's Big Night
Montague Casetti,www.csfd/Montague Casetti.cz,Someone Like Him (Einer wie Bruno)
Dara French,www.csfd/Dara French.cz,Gozu (Gokudô kyôfu dai-gekijô: Gozu)
Debby Winterson,www.csfd/Debby Winterson.cz,Dr. Jekyll and Mr. Hyde
Phaedra Eneas,www.csfd/Phaedra Eneas.cz,Edges of the Lord
Obidiah Bastiman,www.csfd/Obidiah Bastiman.cz,Rendezvous
Lindy Lilbourne,www.csfd/Lindy Lilbourne.cz,Night Moves
Devon Obert,www.csfd/Devon Obert.cz,Rabbit Without Ears 2 (Zweiohrküken)
Conrade Urrey,www.csfd/Conrade Urrey.cz,Heavens Fall
Jaine Chasson,www.csfd/Jaine Chasson.cz,Jimi Hendrix: Hear My Train A Comin'
Filberte Southerton,www.csfd/Filberte Southerton.cz,"Capture of Bigfoot, The"
Ulric Hargitt,www.csfd/Ulric Hargitt.cz,Pilgrimage
Gal Pavia,www.csfd/Gal Pavia.cz,Big Hero 6
Niels Dannell,www.csfd/Niels Dannell.cz,More Than a Game
Kari Jobe,www.csfd/Kari Jobe.cz,Jimi: All Is by My Side
Tonia Hatton,www.csfd/Tonia Hatton.cz,Star Trek: Nemesis
Rozele Kaas,www.csfd/Rozele Kaas.cz,Captive (Cautiva)
Urson Bourdel,www.csfd/Urson Bourdel.cz,RKO 281
Teddi Mohammed,www.csfd/Teddi Mohammed.cz,Canvas
Blair Mosedale,www.csfd/Blair Mosedale.cz,Escape from Fort Bravo
Cleon Sloley,www.csfd/Cleon Sloley.cz,Survival Quest
Yasmin Snap,www.csfd/Yasmin Snap.cz,Strictly Sexual
Audy Rubinfeld,www.csfd/Audy Rubinfeld.cz,Queen of Montreuil
Shepperd Matusiak,www.csfd/Shepperd Matusiak.cz,"Dark Side of the Heart, The (Lado oscuro del corazón, El)"
Storm Harrowing,www.csfd/Storm Harrowing.cz,"Artist, The"
Vlad Geare,www.csfd/Vlad Geare.cz,Pleasure at Her Majesty's
Stacey Kiff,www.csfd/Stacey Kiff.cz,Marilyn in Manhattan
Darla Dongall,www.csfd/Darla Dongall.cz,Hometown Legend
Nathan Lythgoe,www.csfd/Nathan Lythgoe.cz,Tales of Terror
Krishnah Bernet,www.csfd/Krishnah Bernet.cz,Circus of Horrors
Elnore Haggett,www.csfd/Elnore Haggett.cz,"Thing About My Folks, The"

Wasn't able to get rid of the quotation marks because that would break the csv parsing, hope that's not too big of a problem...

A: I think you can get desired output using group by aggregation as follows.
import pandas as pd
import io

string = """name,actor_link,movie_link
Tom Hanks,https://www.csfd.cz/tvurce/330-tom-hanks/,https://www.csfd.cz/film/10135-forrest-gump/
Tom Hanks,https://www.csfd.cz/tvurce/330-tom-hanks/,https://www.csfd.cz/film/2292-zelena-mile/"""

df = pd.read_csv(io.StringIO(string), sep=",")
df = df.groupby(['name','actor_link']).agg(list_of_movies=('movie_link',list)).reset_index()


Q: LuaLaTeX: How to speed up PDF generation? With pdflatex, I used to write \pdfcompresslevel 0 and \pdfobjcompresslevel 0 before the \documentclass command. This would disable the PDF compression which in turn speeds up the generation of the PDF file.
However, these commands do not seem to work with LuaLaTeX. Is there a way to speed up the generation of the PDF file, e.g., by also disabling compression?

A: I use (in texlive 2022)
\RequirePackage{expl3}
\ExplSyntaxOn
\pdf_uncompress:
\ExplSyntaxOff
\documentclass{article}
 ....

or (with the new pdfmanagement + latex-dev 2022-06-01)
\DocumentMetadata{uncompress}
\documentclass{article}

to get uncompressed pdf. That works for all engines.

A: After \edef\pdfcompresslevel{\pdfvariable compresslevel} \edef\pdfobjcompresslevel{\pdfvariable objcompresslevel} you have the mentioned commands as in pdfTeX.
However, the speed problem is in LaTeX itself, no in compression PDF. I am using OpTeX with LuaTeX and I don't have problems with speed.


Q: JPG picture preview is in color, but all image viewers and editors open the full picture in black and while I encountered a really bizarre phenomenon today on my Windows 10. I found and saved a black and white picture on DeviantArt, but when I look at the folder containing that picture along with the other pictures, its small preview appears to be in color. Opening it in Windows Photos, in IrfanView, in Paint, or even in Photoshop results in the full picture being black and while. But where does the color on the preview come from then?
Google search seems to indicate that this might have something to do with "embedded color profile", whatever that is. Is there any way to get more info on that picture's metadata to see where the color comes from? Is there any way to open a full picture in color too?
EDIT: even more bizarrely, the color from the preview fails to appear when the picture is saved, cut or copied into some existing folder with non-picture files. The preview has color only if it is saved in the existing folder with other pictures, in the empty folder where pictures used to be, or in the new empty folder. I suspect it has something to do with the folder type.
The picture in question is below, but fair warning that it has a slightly erotic nature (no explicit nudity though): https://www.deviantart.com/robert-james/art/090411-D04-060a-BW-120499557

A: Many picture formats have an embedded 'thumbnail', which has been created by the writing program. It could be that your file has a colored thumbnail, but a b/w full picture - whichever tool was used to create it seem to support this behavior.
If this is the case, there is nothing you can do, except go back to the source for the full color picture - it simply is not inside your file. Only that small preview thumbnail will be available in color.
Without seeing and analyzing your file, that's my best guess, and it could be wrong of course...


Q: C# + WPF : text mode equivalent of old DOS libraries or curses The goal: For a personal project, I'd like to simulate an old-fashioned computer interface with full screen command line, hex editor, text editor, etc.  All text, no graphics.  (For a simulator/emulator of a hypothetical computer.)
The starting point:  I've figured out that console mode can't be full-screened anymore but that I can easily go fullscreen in WPF with WindowState=Maximized and WindowStyle=None.  So I can make a full-screen TextBox.
The problem: Is there an existing control, pattern, or library for basic writing to a screen of text and reading from the keyboard (not filling out and submitting a field on a form, like a TextBox is geared toward)?
I assume that I'll need to make my own custom control instead of a textbox, and build a large class of low-level methods to position the cursor, output characters, react to input, etc.  But if there's a tried-and-true method or standard approach, I'd rather use that than burn time reinventing a commonly-used wheel.
In the olden DOS days, I would've used a library based off of direct BIOS video calls, PEEKs and POKEs to video RAM, and keyboard and mouse polling.  Of course that doesn't apply anymore, but neither do the standard console routines.  Is there something already out there that fills that niche?
[edit]
To clarify. In DOS days, we had libraries for things like:
Scroll(3);
Write(24,1, "Your command has been queued for execution");
input = Prompt(25, 1, "Enter a command>");

and in document edit mode we would do things like
key = WaitKey();
switch (key) {
  case PGUP: Scroll(-24);
  case PGDN: Scroll(24);
  case LEFT: MoveCursor(-1,0);
  case DOWN: MoveCursor(0,1);
  // ...
}

etc... That's the sort of thing that I'm looking for.  Something with functions like Write, Scroll, Prompt, etc.

A: It sounds like what you are developing is closer to a game than a standard Windows forms application - using a game development library (such as SDL or Microsoft XNA) might make things more straightfoward.
If you are already experienced with the way that the console functioned in the days of old then implementing this should be pretty straightforward - you have your behind-the-sceenes array of characters displayed on the screen + cursor position structure which should be easy to print to the screen each frame, plus a game library will give you the ability to intercept and handle all keyboard events.
If you were planning on routing the output of another process onto this "screen" then things might start to become a little more tricky - if this is the case then this might not be the best idea.

A: Trying to achieve the look and feel (and responsiveness) of a text mode application using a WPF TextBox will have disappointing results. Take a look at what Pete Brown did when he created a Commodore 64 emulator in WPF and Silverlight.
I believe his implementation actually used a writable bitmap to emulate a video card. So the peeks and pokes you refer to would actually take place in a memory buffer instead of the screen and then that would be turned into a screen image frame by frame.


Q: translating from base 10 to base X: an easy method I've studied binary-- a number represented by $1$'s and $0$'s. (like $1010_2=10_{10}$) i know you can represent numbers in other bases(base 3, base 16, base 36) I was wondering--is there an easy way to convert between bases? as an example, convert 12045732 to base-37 (i used a random number generator)

A: To convert $12045732$ to base $37$:

*

*Compute the remainder of $12045732$ divided by $37$.  The remainder is $12$.  This is your ones element.

*Subtract the remainder of $12$ from $12045732$ and divide by $37$.  The result is $325560$.

*Go back to $1$. with this new number and continue to get the $37$'s digit, and so on.
In this case, you get $(6)(15)(29)(34)(12)$.  In other words,
$$
12045732=6\cdot 37^4+15\cdot37^3+29\cdot37^2+34\cdot 37+12.
$$


Q: How to use grundy numbers in this SPOJ problem? I read yesterday this question https://www.spoj.com/problems/GAME3/
and I realise that this problem looks like Nim game and by that similar method of solving can be used.
I do this:
Let's take example with $N=3$.
I want to use Grundy numbers because if the grundy numbers of some state is zero the position is losing. $G(n)$ is mex of all grundy number of position that I can go to.
 Because of that $G(3)=0$.
$G(2)=mex(G(3))=1$
$G(1)=mex(G(2))=0$
 But Ivica the first player won that game?

A: With $N=3$, I (move 1) goes to $2$ (both types of moves are equivalent)
and move two goes to $3$ ($4$ is disallowed) so the player making that move (Marica) loses and Ivica wins. This is accordance with the output.
$G(3)$ is irrelevant, we cannot reach $3$ as the game is then over, and so $G(2)=0$ by definition: the first mover loses.
So $G(1) = \textrm{mex}(G(2)) = 1$, a first player win. So the base case is at $G(N-1)$, as the only legal move loses, it always has value $0$.


Q: Comparison method violates its general contract in sorting method I get an error in my sorting method.

Comparison method violates its general contract

This is my sorting object with sort method
public abstract class ComparablePerson extends IDValueItem implements
        Comparable<ComparablePerson> {

    private int score;
    private String itemID,itemName;

    //setters and getters

    public int compareTo(ComparablePerson another) {
    if (score == another.getScore())
        return this.getItemName().compareToIgnoreCase(another.getItemName());
    else if ((score) > another.getScore())
        return 1;
    else
        return -1;
}

@Override
public boolean equals(Object o) {
    final ComparablePerson other = (ComparablePerson) o;

    if (score == other.getScore() && this.getItemName().equalsIgnoreCase(other.getItemName()))
        return true;
    else
        return false;
}

I just call
                Collections.sort(ComparablePersonCollection);
What can be the cause of this?

A: The compareTo and equals method implementations seem to be inconsistent, the error is telling you that for the same two objects equals gives true while compareTo does not produce zero, which is incorrect. I suggest you invoke compareTo from equals to ensure consistency or otherwise define a custom Comparator<T>.
Simply do:
public abstract class ComparablePerson extends IDValueItem implements Comparable<ComparablePerson> {

    private int score;
    private String itemID,itemName;

    //setters and getters

    public int compareTo(ComparablePerson another) {
    if (score == another.getScore())
        return this.getItemName().compareToIgnoreCase(another.getItemName());
    else if ((score) > another.getScore())
        return 1;
    else
        return -1;
    }

    @Override
    public boolean equals(Object o) {
        return compareTo(o) == 0;
    }
}

A: ComparablePerson is abstract, the comparison method is probably overloaded elsewhere...
Can you post the client (which owns the collection) and the concrete classes?
This code works well:
public class ComparablePerson implements Comparable< ComparablePerson > {
   public ComparablePerson( int score, String name ) {
      _score    = score;
      _itemName = name;
   }

   @Override public int compareTo( ComparablePerson another ) {
      int delta = _score - another._score;
      if( delta != 0 ) return delta;
      return _itemName.compareToIgnoreCase( another._itemName );
   }

   @Override public boolean equals( Object o ) {
      return 0 == compareTo((ComparablePerson)o);
   }

   @Override public int hashCode() {
      return super.hashCode();
   }

   private final int    _score;
   private final String _itemName;

   public static void main( String[] args ) {
      List< ComparablePerson > oSet = new LinkedList<>();
      oSet.add( new ComparablePerson( 5, "x" ));
      oSet.add( new ComparablePerson( 5, "y" ));
      oSet.add( new ComparablePerson( 5, "z" ));
      oSet.add( new ComparablePerson( 6, "x" ));
      oSet.add( new ComparablePerson( 6, "y" ));
      oSet.add( new ComparablePerson( 6, "z" ));
      Collections.sort( oSet );
      System.err.println( "Ok" );
   }
}


Q: Web services error trapping(Jquery + asp.net web service) I am on the look out for an accepted solution for trapping errors in the following scenario:
i have an asp.net web services that interacts with the database.  I interact with the web service through jquery's $ajax function.
I would like to know what is the accepted stable methodology for error trapping. When the data is received from the the web service there are two types of errors in my scenario:

*

*db errors

*ajax errors

Ajax errors can trapped inside error portion of $ajax function. I trap the database errors inside the web service and so far I could only come up with one idea how to pass them on to the user - pack them in the results array. But this solution is awkward. Are there any better ideas?
Here is the sample of code I use for accessing asp.net web service:
$.ajax({
  type: "POST",
  url: "http://localhost/WebServices/Service.asmx/GetBillingEntities",
  data: "{}",
  contentType: "application/json; charset=utf-8",
  dataType: "json",
  success: function(response) {
    var results = (typeof response.d) == 'string' ? eval('(' + response.d + ')') : response.d;

    DisplayResults();
  },

  error: function(xhr, status, error) {
    // Display a generic error for now.
    alert("AJAX Error!");
  }
});

So should the database results go in to results array and unpacked there manually? Is there a better system?
Thanks!

A: got it:
$(document).ready(function() {
02      $.ajax({
03          type: "GET",
04          url: "AJAX/DivideByZero",
05          dataType: "json",
06          success: function(data) {
07              if (data) {
08                  alert("Success!!!");
09              }
10          }, error: function(xhr, status, error) {
11              DisplayError(xhr);
12          }
13      });
14  });
15
16  function DisplayError(xhr) {
17      var msg = JSON.parse(xhr.responseText);
18      alert(msg.Message);
19  }

A: What you can do is throw an exception in your GetBillingEntities method of your webservice.  Catch the exception, log some details and then re-throw it.  If your method throws an exception it should get caught in the "error:" block.
So basically you handle the error data in your service and handle how to display an error to the user in your "error:" block.


Q: How to access a webelement in other class in POM - Selenium I have 2 pages (landing page and registration page). In landing page, I am storing webelements using @FindBy annotations. I need to use the Webelements oflanding page in the registration page. How can I proceed?

A: You just need to create an object of the class and access it like variable
Suppose class A having @FindBy function and variable is suppose myelement
Then use (it is Java, try similar in whatever lang you are using):
A aobject= new A();
A.myelement;


Q: Замена SVG при нажатии на неё Товарищи, доброго дня, вечера, у кого как. Следующий вопрос: как заменить svg на другую при нажатии на неё? Нужно максимально просто.

<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" data-testid="checkbox-icon" class="css-8s785g">
<rect width="24" height="24" rx="4" fill="#151418"></rect>
<path fill-rule="evenodd" clip-rule="evenodd" d="M18.707 8.707L10 17.414l-4.707-4.707 1.414-1.414L10 14.586l7.293-7.293 1.414 1.414z" fill="#fff"></path>
</svg>
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" data-testid="checkbox-icon" class="css-8s785g">
<rect x="1" y="1" width="22" height="22" rx="3" stroke="#151418" stroke-width="2"></rect>
</svg>

Буду благодарен.

A:

const checkbox = document.querySelector('.checkbox');
const imgChecked = document.querySelector('.checked');
const imgNotChecked = document.querySelector('.not-checked');

const showCheckbox = () => {
  imgChecked.classList.toggle('visible');
  imgNotChecked.classList.toggle('visible');
  if (!checkbox.checked) {
    checkbox.checked = true;
  } else {
    checkbox.checked = false;
  }

}

imgChecked.addEventListener('click', showCheckbox);
imgNotChecked.addEventListener('click', showCheckbox)
.img {
  display: none;
  cursor: pointer;
}

.visible {
  display: inline-block;
}
<input class="checkbox" type="checkbox">
<svg class="img checked visible" width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" data-testid="checkbox-icon" class="css-8s785g">
            <rect x="1" y="1" width="22" height="22" rx="3" stroke="#151418" stroke-width="2"></rect>
        </svg>
<svg class="img not-checked " width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" data-testid="checkbox-icon" class="css-8s785g">
            <rect width="24" height="24" rx="4" fill="#151418"></rect>
            <path fill-rule="evenodd" clip-rule="evenodd" d="M18.707 8.707L10 17.414l-4.707-4.707 1.414-1.414L10 14.586l7.293-7.293 1.414 1.414z" fill="#fff"></path>
        </svg>


Q: logstash kv filter, converting strings to integers using dynamic mapping I have a log with a format similar to:
name=johnny amount=30 uuid=2039248934

The problem is I am using this parser on multiple log files with each basically containing numerous kv pairs.
Is there a way to recognize when values are integers and cast them as such without having to use mutate on every single key value pair?(Rather than a string)
I found this link but it was very vague in where the template json file was suppose to go and how I was to go about using it.
Can kv be told to auto-detect numeric values and emit them as numeric JSON values?

A: You can use ruby plugin to do it.
input {
    stdin {}
}

filter {
    ruby {
        code => "
            fieldArray = event['message'].split(' ');
            for field in fieldArray
                name = field.split('=')[0];
                value = field.split('=')[1];
                if value =~ /\A\d+\Z/
                    event[name] = value.to_i
                else
                    event[name] = value
                end
            end
        "
    }
}
output {
    stdout { codec => rubydebug }
}

First, split the message to an array by SPACE.
Then, for each k,v mapping, check whether the value is numberic, if YES, convert it to Integer.
Here is the sample output for your input:
{
       "message" => "name=johnny amount=30 uuid=2039248934",
      "@version" => "1",
    "@timestamp" => "2015-06-25T08:24:39.755Z",
          "host" => "BEN_LIM",
          "name" => "johnny",
        "amount" => 30,
          "uuid" => 2039248934
}

Update Solution for Logstash 5:
input {
    stdin {}
}

filter {
    ruby {
        code => "
            fieldArray = event['message'].split(' ');
            for field in fieldArray
                name = field.split('=')[0];
                value = field.split('=')[1];
                if value =~ /\A\d+\Z/
                    event.set(name, value.to_i)
                else
                    event.set(name, value)
                end
            end
        "
    }
}
output {
    stdout { codec => rubydebug }
}

A: Note, if you decide to upgrade to Logstash 5, there are some breaking changes:
https://www.elastic.co/guide/en/logstash/5.0/breaking-changes.html
In particular, it is the event that needs to be modified to use either event.get or event.set. Here is what I used to get it working (based on Ben Lim's example):
input {
    stdin {}
}

filter {
    ruby {
        code => "
            fieldArray = event.get('message').split(' ');
            for field in fieldArray
                name = field.split('=')[0];
                value = field.split('=')[1];
                if value =~ /\A\d+\Z/
                    event.set(name, value.to_i)
                else
                    event.set(name, value)
                end
            end
        "
    }
}
output {
    stdout { codec => rubydebug }
}


Q: Dataflow reading using PubSubIO is really slow I'm having some trouble with a Dataflow pipeline that reads from PubSub and writes to BigQuery.
I had to drain it to perform some more complex updates. When I rerun the pipeline it started reading fom PubSub at a normal rate, but then after some minutes it stopped and now it is not reading messages from PubSub anymore! Data watermark is almost one week delayed and not progressing. There are more than 300k messages in the subscription to be read, according to Stackdriver.
It was running normally before the update, and now even if I downgrade my pipeline to the previous version (the one running before update), I still doesn't get it to work.
I tried several configurations:
1) We use Dataflow autoscaling, and I tried starting the pipeline with more powerful workers (n1-standard-64), and limiting it to ten workers, but it won't improve performance neither autoscale (it keeps only the initial worker).
2) I tried providing more disk through diskSizeGb (2048) and diskType (pd-ssd), but still no improvement.
3) Checked PubSub quotas and pull/push rates, but it's absolutely normal.
Pipeline shows no errors or warnings, and just won't progress.
I checked instances resources and CPU, RAM, disk read/write rates are all okay, compared to other pipelines. The only thing a little higher is network rates: about 400k bytes/sec (2000 packets/sec) outgoing and 300k bytes/sec incoming (1800 packets/sec).
What would you suggest I do?

A: The Dataflow SDK 2.x for Java and the Dataflow SDK for Python are based on Apache Beam. Make sure you are following the documentation as a reference when you update. Quotas can be an issue for slow running pipeline and lack of output but you mentioned those are fine.
It seems there is a need to look at the job. I recommend to open an issue on the PIT here and we’ll take a look. Make sure to provide your project id, job id and all the necessary details.


Q: java.io.IOException: Cannot run program "/bin/bash": error=24, Too many open files I am connecting wmic via terminal for every 5 seconds by using thread. But I got "java.io.IOException: Cannot run program "/bin/bash": error=24, Too many open files"
after 1 day.
Thread program:
    public void run() {
    try {
        while (true) {

            if (isStopIssued()) {
                break;
            }
            setStatus("SLEEP");

            Thread.sleep(5000);
            if (isStopIssued()) {
                break;
            }
            setStatus("ACTIVE");

            process();

            if (isStopIssued()) {
                break;
            }
        }

    }
    catch (InterruptedException e) {
        logger.error(this.getClass().getName() + ": " + e.getMessage(), e);
    }
}

Process Method:
private void process() {
ProcessBuilder builder = new ProcessBuilder("/bin/bash");
    Process p = null;
    int exit = 0;
    BufferedWriter p_stdin = null;
    OutputStreamWriter osw = null;
    String inDir = inputDir + "/" + inputFile;
    String errDir = errorDir + "/" + errorFile;
    String outDir = outputDir + "/" + outputFile;
    logger.debug("[JWMILoader] - Input Directory ---> " + inDir);
    logger.debug("[JWMILoader] - Output Directory ---> " + outDir);
    logger.debug("[JWMILoader] - Error Directory ---> " + errDir);
    File inFile = new File(inDir);
    File errFile = new File(errDir);
    try {
        p = builder.redirectOutput(inFile).start();  **// Line Number : 194 **
        p = builder.redirectError(errFile).start();
    }
    catch (IOException e) {
        logger.error(this.getClass().getName() + ": " + e.getMessage(), e);
    }
    osw = new OutputStreamWriter(p.getOutputStream());
    // get standard input of shell

    p_stdin = new BufferedWriter(osw);

    // execute the desired command (here: wmic) n times
    try {
        // single execution
        p_stdin.write(wmiQuery);
        p_stdin.newLine();
        p_stdin.flush();
    }
    catch (IOException e) {
        logger.error(this.getClass().getName() + ": " + e.getMessage(), e);
    }

    // finally close the shell by execution exit command
    try {
        p_stdin.write("exit");
        p_stdin.newLine();
        p_stdin.flush();
    }
    catch (IOException e) {
        logger.error(this.getClass().getName() + ": " + e.getMessage(), e);
    }
    finally {
        try {
            p_stdin.close();
            exit = p.waitFor();
            logger.debug("[JWMILoader] - WQL Query Successfully Executed. Process Exit ---> " + exit);

        }
        catch (IOException | InterruptedException e) {
            logger.error(this.getClass().getName() + ": " + e.getMessage(), e);
        }
    }
if (p != null) {
                p.destroy();
            }
}

Exception :
java.io.IOException: Cannot run program "/bin/bash": error=24, Too many open files
at java.lang.ProcessBuilder.start(ProcessBuilder.java:1041)
at mavens.imlog.etl.loader.JWMILoader.remoteConnection(JWMILoader.java:194)
at mavens.imlog.etl.loader.JWMILoader.process(JWMILoader.java:156)
at mavens.imlog.etl.loader.JWMILoader.run(JWMILoader.java:64)
Caused by: java.io.IOException: error=24, Too many open files
at java.lang.UNIXProcess.forkAndExec(Native Method)
at java.lang.UNIXProcess.<init>(UNIXProcess.java:135)
at java.lang.ProcessImpl.start(ProcessImpl.java:130)
at java.lang.ProcessBuilder.start(ProcessBuilder.java:1022)
... 3 more

I am using CENT OS.
Please friends help me, how to solve this problem.

A: You start processes twice,

*

*First one running with output inFile,

*Second one running with output inFile & error errFile

Was it your original intension?
try {
    p = builder.redirectOutput(inFile).**start()**;  **// Line Number : 194 **
    p = builder.redirectError(errFile).**start()**;
}
catch (IOException e) {
    logger.error(this.getClass().getName() + ": " + e.getMessage(), e);
}

And destroy only the last one created.
  if (p != null) {
            p.destroy();
  }

Fix this, and this should fix your error.
P.S.
Start it only once:
try {
    builder = builder.redirectOutput(inFile);
    p = builder.redirectError(errFile).start();
}


Q: How to get the layer from namespace? I have a code with namespace like this:
namespace nameFile.Common.otherParameters
{
public interface IEntityManager : **ICommon**
{
}

}
And I want to get the layer name to a property (in C#).
How can I do that?
(see the interface inherit from the layer name + I)


Q: How to add csv row to array in powershell I'm looking to import a csv file. Take the first row(with headers) and add it to an array in powershell.
$csv = Import-CSV "test.csv"
$array = @()

A: Would you need an explicit conversion to array when import-csv is giving you a nice enumerable array of System.Object instances?
When you use import-csv , PowerShell will read the header row and give you back an array of custom objects. Each of these objects will have properties which match the Header column.
Example of test.csv
Id,FirstName
1,Name001
2,Name002

Results after import-csv
You can iterate through the collection as shown below
$csv = Import-CSV "test.csv"
foreach($item in $csv)
{
    $msg=("Id={0}  , Name={1}" -f $item.Id, $item.FirstName)
    Write-Host $msg
}
#Add the first item to your own array
$arrMy=@()
$arrMy+=$csv[0]
$arrMy

Output
Id=1  , Name=Name001
Id=2  , Name=Name002

Id FirstName
-- ---------
1  Name001

MSDN
https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/import-csv?view=powershell-6
Getting deeper - what does import-csv actually return?
It returns an array with N objects of type System.Management.Automation.PSCustomObject. Here N=no of rows in the CSV file.

A: I'm not quite sure what you are asking here, but it looks to me that you want to get the headers of a CSV file as array:  (Take the first row(with headers) and add it to an array in powershell)
If that is the case, here's a small function that can do that for you:
function Get-CsvHeaders {
    # returns an array with the names of the headers in a csv file in the correct order
    [CmdletBinding(DefaultParameterSetName = 'ByDelimiter')]
    param(
        [Parameter(ValueFromPipeline = $true, Mandatory = $true, Position = 0)]
        [ValidateScript({Test-Path -Path $_ -PathType Leaf})]
        [string]$Path,

        [Parameter(Mandatory = $false)]
        [ValidateSet ('ASCII', 'BigEndianUnicode', 'Default', 'OEM', 'Unicode', 'UTF32', 'UTF7', 'UTF8')]
        [string]$Encoding = $null,

        [Parameter(Mandatory = $false, ParameterSetName = 'ByDelimiter')]
        [char]$Delimiter = ',',

        [Parameter(Mandatory = $false, ParameterSetName = 'ByCulture')]
        [switch]$UseCulture
    )
    $splatParams = @{ 'Path' = $Path }
    switch ($PSCmdlet.ParameterSetName) {
        'ByDelimiter' { $splatParams.Delimiter  = $Delimiter; break }
        'ByCulture'   { $splatParams.UseCulture = $true; break }
    }
    if ($Encoding)    { $splatParams.Encoding = $Encoding }

    $data = Import-Csv @splatParams -ErrorAction SilentlyContinue
    $data[0].PSObject.properties.name
}

Usage:
$headersArray = Get-CsvHeaders -Path 'test.csv'


Q: How to calculate the average of the selected attribute in Power BI I am working on the Fifa 19 Kaggle Dataset. I want to create a Gauge chart that compares the Overall stat for a Player compared with the Overall Average of the club(target value) he plays for.
I tried to create a calculated column:
Club Overall = calculate(Average(data[Overall]); data[Club]= "FC Barcelona")

Instead of "FC Barcelona", I want it to be the Club the selected player plays in.

A: This measure should do what you want, by filtering all players, but leaving the club filter in place:
Club Overall Average =
IF (
    HASONEVALUE ( data[Club] ),
    CALCULATE (
        AVERAGE ( data[Overall] ),
        ALL ( data[Name] ),
        data[Club] = VALUES ( data[Club] )
    ),
    BLANK()
)

See https://pwrbi.com/2019/05/stack-overflow-56128872/ for worked example


Q: Triggering an output task with NIDAQmx I'm having trouble carrying out what I think should be a pretty straightforward task on a NIDAQ usb6002: I have a low frequency sine wave that I'm measuring at an analog input channel, and when it crosses zero I would like to light an LED for 1 second. I'm trying to use the nidaqmx Python API, but haven't been able to clear up some of my basic questions with the documentation. https://nidaqmx-python.readthedocs.io/en/latest/
If anyone can offer any thoughts about the code or the basic logic of my setup, that would be hugely helpful.
Here's what I have tried so far. I start with some imports and the definition of my channels:
import matplotlib.pyplot as plt
from math import *
import nidaqmx
from nidaqmx import *
from nidaqmx.constants import *
import time

V_PIN = "Dev1/ai6"
LED_PIN = "Dev1/ao0"

I understand how tasks and things work generally- I can read and plot a signal of a given sampling rate and number of samples using task.ai_channels methods without any trouble. But here's my best guess at how to carry out "detect zero and trigger output":
writeLED = nidaqmx.Task('LED')
writeLED.ao_channels.add_ao_voltage_chan(LED_PIN)
writeLED.timing.cfg_samp_clk_timing(1)
writeLED.triggers.start_trigger.cfg_anlg_edge_start_trig(V_PIN,trigger_level = 0)
writeLED.write([5], auto_start=True)

This gives me the error below at the cfg_anlg_edge line
DaqError: Requested value is not a supported value for this property. The property value may be invalid because it conflicts with another property.
Property: DAQmx_StartTrig_Type
Requested Value: DAQmx_Val_AnlgEdge
Possible Values: DAQmx_Val_DigEdge, DAQmx_Val_None

I don't know why an analog input channel wouldn't be supported here. Page 245 of this document makes it sound like it should be: https://media.readthedocs.org/pdf/nidaqmx-python/latest/nidaqmx-python.pdf
I'm sure there are other problems with the code, too. For example, it seems like the sample clock manipulations are quite a bit more complicated than what I've written above, but I haven't been able to find anything that explains how it would work in this situation.
Thanks in advance for any help!

A: With NI, it's "RTFMs"
When programming NI devices, you usually need two manuals.

*

*NI-DAQmx Help (for the programming part)

*the device specification (for the device part)

You need both because the NI-DAQmx API supports every DAQ device NI makes, but not every device has the same capabilities. "Capabilities" includes more than how many channels of each kind, but also the timing and triggering subsystems as well as internal signal routing. A DAQmx application that runs with one device is not guaranteed to run with another because the application might use the API in a way the second device cannot support.
Finally, on the documentation front, any given NI DAQ device typically belongs to family of related devices and these families also have a manual called User Guide. These User Guides act as a bridge between the API and device spec, helping you understand how the device responds to commands. For the 6002, the family is "Low-Cost DAQ USB Device".
Analog trigger for analog output on NI 6002
Your determination is correct that
writeLED.triggers.start_trigger.cfg_anlg_edge_start_trig(V_PIN,trigger_level = 0)

is possible, just not for the USB 6002. This line is asking the analog output subsystem to use an analog edge trigger, but the analog output subsystem for the 6002 only has these trigger capabilities:

*

*software

*PFI 0

*PFI 1

For this device, you're only option is the software trigger because the PFI lines are digital triggers and their trigger level is specified to be between 0.8 V and 2.3 V.
Change your Python program to detect a zero-crossing from the analog input stream and, when it does, make it call stop() and then start() on the AO task.
The reason for the stop-start sequence is retriggering: you want to light the LED for each zero crossing, but a task cannot be restarted unless it has either been stopped (by the API or by completing its task) or configured for retriggering. Because the 6002 is in the low-cost family, this hardware feature isn't available, so you must use the API to stop the AO task or wait for the AO generation to complete before restarting the pulse for the LED
6002 AO Specification

A: Software triggering is not real-time, you will have non-deterministic delay before the led turns on. This depends on your program, interfaces, usb latencies, pc performances...
Otherwise, you can use a comparator (like lm393) to trigger a digital input (PFI0 or PFI1).
Though it's just an LED, it is probably not critical if the delay varies within milliseconds.