text:
Q: JAVA handling lots of JDBC pool connections I've a problem when creating a batch in JAVA, this is that i might have to call a certain connection every second to process one block of rows, reaching the limit of the pool size.
How can i handle lots of connections without increase pool size ?
using (var connection = ExternalDBConnectionManager.getConnection()){
        using (var prepStatement = connection.prepareStatement(queryToExecute)){
        ...
    }
}

This function is called every 100 rows or more, but for an example i'd like to run this every row (i.e 500 rows, one call for each) - (this means call this function 500 times with the same connection)

A: You should read up on connection pool to get an idea of how they work.  There's hundreds of topics here on SO that pertain to this.  A quick google search of "Understanding Java connection pools" brings up a small description of how one of the libraries might work: How Connection Pooling Works
Some more info on this SO thread: How to establish a connection pool
Basically, your client requests come in, you grab a connection from the pool, you do your sql operation, and when you close the connection, it returns it back to the pool.  That's the high level.
If you want to combine that with batching, it gets a little trickier, since you would grab the data, insert it into the batch and then trigger the send/commit when you have some predetermined amount of data in the batch.
It really depends on what you want your clients to see, do they need acknowledgement when the record is committed?
With pooling, it's less likely that you will need to use batching, you just need to adjust the connection pool size for your environment.
There's a number of standalone pool libraries (C3PO and DBCP), and a number of the various services (like websphere) already have pooling built in.  I believe the Oracle jdbc driver as the ability to do it for you.

A: Universal Connection Pool (UCP) is a Java connection pool which is rich in features and is tightly integrated with Oracle RAC, Oracle DG, Oracle ADG database architectures leveraging high availability, failover and performance features.
It is a standalone ucp.jar that needs to be used with JDBC driver.
There are some whitepapers on UCP and its capabilities on OTN.

A: You mentioned "batch". Usually batches don't use a connection pool which are reserved to OLTP applications. That's because a connection pool works well if connections are borrowed and released fairly quickly. Batches usually create their own connections which stay opened during the lifetime of the batch (which could be hours).


text:
Q: Find the parametric curver from points (2,1) and (5,4) I already found $x=2+3t$ and $y=1+3t$ but I don't know how to get the whole equation of $r(t)=$? and what the boundaries are $?<t<?$

A: You're done. Or maybe you want to write
$$
r(t) = (2 + 3t, 1 + 3t), 0 \le t \le 1,
$$
to make it a little more complete.

redpajama_set_name: RedPajamaStackExchange


text:
Q: What is the difference between module.exports=require('other') and the same with a temporary variable? reproduce link https://stackblitz.com/edit/node-sp5xay?file=index.mjs
Assume we have a project like this:
.
├── dep
│   ├── a.mjs
│   ├── b.js
│   └── c.js
└── entry.mjs

// entry.mjs
import { foo } from "./dep/a.mjs";
console.log(foo);

// dep/a.mjs
export * from './b.js'

// dep/b.js
module.exports = require("./c.js"); //

// why this not working ❌
// const m = require("./c.js");
// module.exports = m;

// dep/c.js
exports.foo = "foo";

and we run in terminal
node entry.mjs

it's very confuse it will throw error if in dep/b.js we use:
// why this not working ❌
const m = require("./c.js");
module.exports = m;

if in dep/b.js we use:
module.exports = require("./c.js");

it will work expect!

module.exports=require have something magic? like symlink? if any docs i miss?
The origin of this problem is that I saw the vue3 source code
vue3 core source code export

A:
module.exports=require have something magic?

Yes, it does have some magic. The problem is that you are importing a CommonJS module into an ES module. The latter require a static declaration of exported names, which the former do not provide. See the node.js documentation:

When importing CommonJS modules, the module.exports object is provided as the default export.

So just don't do export * from './b.js', rather import b from './b.js' then refer to b.foo on the CommonJS module object.
However,

For better compatibility with existing usage in the JS ecosystem, Node.js in addition attempts to determine the CommonJS named exports of every imported CommonJS module to provide them as separate ES module exports using a static analysis process.
[…]
The detection of named exports is based on common syntax patterns but does not always correctly detect named exports. In these cases, using the default import form described above can be a better option.
Named exports detection covers many common export patterns, reexport patterns and build tool and transpiler outputs. See cjs-module-lexer for the exact semantics implemented.
(emphasis mine)

And indeed,
module.exports = require("./c.js");

is one of the "reexport patterns" that is detected, but using a temporary variable
const m = require("./c.js");
module.exports = m;

is not. You just can't use named imports from a CommonJS module that does this. The proper solution to fix this is of course to rewrite the module to ESM syntax and use export * from "./c.js";, not any module.exports assignments.

A: In Node.js, the module.exports object is used to specify what a module should make available when it is imported using require.
The first statement , module.exports = require('module'), sets the module.exports object to the value of the module object that is imported using require. This means that anything that is exported by the module module will be made available to the code that imports it.
On the other hand, module.exports = {...} sets the module.exports object to an object literal containing the properties and values that should be made available to code that imports the module. This allows you to specify exactly what should be made available from the module, rather than relying on the exports of another module.
For example, suppose you have a module called myModule that exports a single function:
module.exports = {
  myFunction: () => {
  console.log('Hello, world!');
 }
};

This module can then be imported and used like this:
const myModule = require('myModule');
myModule.myFunction(); // prints 'Hello, world!'

On the other hand, if you set module.exports to the value of another module's exports, like this:
module.exports = require('anotherModule');

Then the exports of anotherModule will be made available to code that imports myModule. For example:
const myModule = require('myModule');
myModule.someFunction(); // calls a function exported by anotherModule


text:
Q: Как получить scrollTop в React? У меня есть contextMenu которое абсолютно спозиционированна. При клике правой кнопкой мыши на определенные компоненты. Меню должна вызываться там же где произошел клик мыши. Но дело в том что e.pageY при прокрутки страницы в низ выдает значение e.clienY . Вот я и думаю прибавить то что проскролилось к e.pageY.

A: Оказывается ответ был в том что у body и html стояло в css height и width 100% и из за этого js не могла посчитать высоту


text:
Q: How to get Flextable to output to pdf? I am having the same problem as Joe Crozier.  I cannot get flextables to show up in my pdf output.  I would have commented on his thread but I am not allowed to being new.  I actually tried the exact example that was given as his answer and flextable in that example did not print to the pdf file either.
---
title: "Untitled"
output:
  pdf_document:
    latex_engine: xelatex
---

knitr::opts_chunk$set(echo = TRUE)
library(flextable)

ft <- flextable(head(airquality))
ft <- autofit(ft)
theme_vader(ft)

Could it possibly be the LaTeX package that I am using?  Does this work for some and not others?  I was using MiKTeX and just uninstalled it and used Tinytex instead with the same result.  The code prints to the pdf but the table does not.

A: Nevermind, I figured it out.  I thought I would leave an answer in case someone else is struggling with this.  I needed to update my version of Flextable.  I had just reinstalled R Studio a couple of days ago on a new computer and figured most things should be up-to-date, but when I checked my Flextable package was prior to the one with the fix for this issue.  I installed version 0.6.1 and it now works.


text:
Q: size of character array and size of character pointer I have a piece of C code and I don't understand how the sizeof(...) function works:
#include <stdio.h>

int main(){
   const char  firstname[] = "bobby";
   const char* lastname = "eraserhead";
   printf("%lu\n", sizeof(firstname) + sizeof(lastname));
   return 0;
}

In the above code sizeof(firstname) is 6 and sizeof(lastname) is 8.
But bobby is 5 characters wide and eraserhead is 11 wide.  I expect 16.
Why is sizeof behaving differently for the character array and pointer to character?
Can any one clarify?

A: sizeof an array is the size of the total array, in the case of "bobby", it's 5 characters and one trailing \0 which equals 6.
sizeof a pointer is the size of the pointer, which is normally 4 bytes in 32-bit machine and 8 bytes in 64-bit machine.

A: The size of your first array is the size of bobby\0. \0 is the terminator character, so it is 6.
The second size is the size of a pointer, which is 8 byte in your 64bit system. Its size doesn't depends on the assigned string's length.

A:
how the sizeof(...) function works

sizeof() looks like a function but it's not a function. A function computes something at run-time.
sizeof() asks the compiler, at compile-time, how much memory it allocates for the argument. BTW sizeof() has no idea how much of it you actually use later at run time. In other words, you've "hardcoded" the printf arguments in your example.

Why is sizeof behaving differently for the character array and pointer
  to character?

A pointer rarely requires the same amount of memory as an array.
In general, the amount of memory allocated for a pointer is different to what is allocated for its pointee.

A: firstname is an array of 6 chars, including the terminating '\0' character at the end of the string.  That's why sizeof firstname is 6.
lastname is a pointer to char, and will have whatever size such a pointer has on your system.  Typical values are 4 and 8.  The size of lastname will be the same no matter what it is pointing to (or even if it is pointing to nothing at all).

A: firstname is a char array carrying a trailing 0-terminator. lastname is a pointer. On a 64bit system pointers are 8 byte wide.

A: firstname[] is null-terminated, which adds 1 to the length.
sizeof(lastname) is giving the size of the pointer instead of the actual value.


text:
Q: phpredis set() not storing the key, what am I missing? This is basic code that I pulled off the internet to test Redis. When setting or getting, I get nothing. I'm suspecting that there is something wrong with my php config, but not sure how to figure out what is going wrong. I've also tried using predis as a client and it too reacts the same way.

$connected= $redis->connect('localhost', 6379); //works

if(!$connected) {
    // some other code to handle connection problem
    die( "Cannot connect to redis server.\n" );
}

$redis->set('somekey', 'some value');  // fails

echo $redis->get('somekey'); //fails

A: Check if phpinfo() function displays redis client in the listing.
Also check in redis.conf if requirepass is set to some value, if yes you have to connect with redis using those credentials.


text:
Q: How to get focus from one textinput to another textinput? I have created a custom text input, suppose it to be
Now I want to make user to get focused from one textinput to another. Make it as from
let {login,pass}=useRef(null)
<MyTextInput placeholder'login' ref={login} onSubmitEditing={()=>pass.focus()}/>
<MyTextInput placeholder='password' ref={pass}/>

Now i am working with functional components in react native And I have tried adding ref to both of it as above. But I am getting error as cannot cannot read property focus of undefined.
Can anyone help me adding focus with this kind of textinputs?

A: Here is a simple snippet that should work in your case assuming your custom MyTextInput supports the same props as TextInput
export default function App() {
  const useranme = React.useRef(null)
  const password = React.useRef(null)
  return (
    <View>
      <MyTextInput onSubmitEditing={()=>password.current.focus()} ref={useranme} />
      <MyTextInput ref={password} />
    </View>
  );
}


text:
Q: Run a piece of code once before certain tests I am currently developing cleanup/migration code for our database. I want to run this code once when one or more of our database tests is ran (we have some non-database tests as well, and it is not needed run the cleanup/migration code).
I have already looked at the @BeforeClass annotation, but it runs for every class. So when I run 10 database tests, the cleanup/migration code will run 10 times as well, which is not really good for performance.
I was not able to find a good solution yet, so does anyone know a good solution?
Thanks.

A: Check out DBUnit - it provides exactly what you're looking for - database build & teardown, plus all sorts of cleanup.
http://dbunit.sourceforge.net/


text:
Q: WordPress свое двухуровневое меню Есть проблема:
Нестандартное меню.
Есть простые ссылки, а есть dropdown

          Главная
          Новости

О центре

              Расписание занятий
              График занятости
              Направления

            Филиалы

Соревнования / Competitions

              Рейтинги
              График соревнований
              Итоги

Галерея
            Контакты
            Отзывы

Меню

Вывожу его через  без проблем
    <?php

if( $menu_items = wp_get_nav_menu_items('1') ) { // "Меню для шапки" - это название моего меню. Вы можете также использовать ID или ярлык
    $menu_list = '';
    foreach ( (array) $menu_items as $key => $menu_item ) {
        $title = $menu_item->title; // заголовок элемента меню (анкор ссылки)
        $idmen = $menu_item->ID; // id элемента меню
        $url = $menu_item->url; // URL ссылки
        $parentyn = $menu_item->menu_item_parent; // внутренняя

        $menu_list .= '' . $title . ' '. $parentyn  .' ';
    }
    echo $menu_list;
}
        ?>

Но нужно совсем иное меню.
Вопрос - есть ли какая функция, чтобы узнать, есть ли у пункта меню дочерние подпункты?

A: Выводите меню не своим кодом, а через wp_nav_menu(). Сформированное меню будет иметь класс menu-item-has-children у тех элементов, которые содержат подменю.
Используемая вами функция wp_get_nav_menu_items() не возвращает никаких признаков наличия подменю у элемента, только у его дочерних элементов menu_item_parent не равен нулю.


text:
Q: How to detect a tab bar being double tapped? Using NSNotification within Tabbar DidSelectItem like so to call a scroll up method.
-(void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item
{
   [[NSNotificationCenter defaultCenter] postNotificationName:@"homeScrollUp" object:nil];
}

It works nicely but how can i detect it by tapping index tab 0 twice for example?

A: How about something link this? Make sure you invalidate the timer when you're cleaning up the class.
-(void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item
{
   NSUInteger indexOfTab = [[theTabBar items] indexOfObject:item];
   if(indexOfTab==0) {
      self.chosenIndexTapped++
   }
  self.tabPressTimer = [NSTimer scheduledTimerWithTimeInterval:smallTimeToAllowTap
                                                              target:self
                                                            selector:@selector(handleRecognisedTap)
                                                            userInfo:nil
                                                             repeats:NO];
  [[NSRunLoop currentRunLoop] addTimer:self.tabPressTimer forMode:NSRunLoopCommonModes];
}

-(void)handleRecognisedTap {
    if(self.chosenIndexTapped>1){
        //Scroll to top
    }
    self.chosenIndexTapped = 0 //Reset the taps on your chosen index
}


text:
Q: Why segment fault in recursion in C I have the following piece of C code for implementing quick sort algorithm by myself.
unsigned int mid_pos = FIND_MID(start, end);
unsigned int piv_pos;

/* Medium of three partitioning pivot picking */
if ((data[start] <= data[mid_pos] && data[mid_pos] <= data[end]) ||
        (data[mid_pos] >= data[end] && data[mid_pos] <= data[start]))
    piv_pos = mid_pos;
else
{
    if ((data[start] <= data[end] && data[mid_pos] >= data[end]) ||
        (data[start] >= data[end] && data[mid_pos] <= data[end]))
        piv_pos = end;
    else if ((data[start] <= data[end] && data[start] >= data[mid_pos]) ||
            (data[start] <= data[mid_pos] && data[start] >= data[end]))
        piv_pos = start;
    else
    {
        srand(time(NULL));
        piv_pos = rand() % (end - start) + start;
    }
}

pivot = data[piv_pos];

while (i < j)
{
    while (data[i] < pivot)
        i++;
    while (data[j] > pivot)
        j--;
    if (i < j)
    {
        swap(&data[i], &data[j]);
        i++;
        j--;
    }
}

/* recursion */
quick_sort(data, start, j);
quick_sort(data, i, end);

For 1 set of test case (1M numbers) it hangs. Not so sure about why.

I have found the problem, the testing data set was not good if use median of three algorithm. I changed the pivot picking to completely random and it was OK then.
unsigned int piv_pos = rand() % (end - start) + start;
pivot = data[piv_pos];

A: Some environments are easier to debug than others. If you are using an OS which gives you a core file when you get a segmentation fault that core file can be used to quickly pinpoint the problem. You might have to enable core dump by allowing a limit at the shell prompt, something like:
ulimit -c 500000
(in bash)
or:
limit coredumpsize 500M
(in tcsh)
Assuming that your program was compiled with debug flag and without too much optimization you can easily pinpoint the problem with something like:
ddd myprogram core
Ddd is a graphical debugger, you could also use gdb if you feel familiar with that command line debugger.
Another very useful tool to pinpoint problems like this is valgrind, example:
valgrind myprogram
Valgrind might give warnings about uninitialized memory or memory leaks. It might also suggest some options to give more warnings.
However, which tools you have depends very much on your OS and installed programs. Valgrind and ddd are both Linux programs.


text:
Q: Textarea displaying data from mysql database with headings I wonder if anyone could help me out..I have a textarea (disabled) in which I want to display the headings "Name", "Type", "Dosage", "Time Interval", "Amount Collected" and "Date Of Entry" (all underlined if possible) and then underneath I want to display the relevant data from the mysql database based on the date that the user has selected. Any ideas? I can't for the life of me figure it out.
Thanks in advance.

A: Do you mean you need a table inside textarea?
You can't, instead just create a div with fixed width/height and overflow: auto, put your table inside of it, apply some styling and it will look just the same as it would in textearea.


text:
Q: Cordova build fails with "Cannot find module lodash/object/assign" After adding Android to an iOS-only Cordova project, cordova build fails with
Error: Cannot find module 'lodash/object/assign'
I am aware of this question, but there is no xmlbuilder in my plist directory in the globally installed cordova module (/usr/local). So I am unable to try that quick and dirty solution.
The problem persists even after removing Android and re-running cordova build. I'm not aware of having made any changes to the project since last running cordova build except for a tiny change to a js file in www.
Versions: cordova -v: 5.4.1, node -v: v4.2.4, npm -v lodash: 2.14.12 (if that's even the one used here),
cordova plugins list: cordova-hot-code-push-plugin 1.2.5 "Hot Code Push Plugin"
cordova-media-with-compression 2.0.15 "Media With Compression: Alpha Software Edition"
cordova-plugin-customurlscheme 4.1.3 "Custom URL scheme"
cordova-plugin-device 1.1.1 "Device"
cordova-plugin-dialogs 1.2.0 "Notification"
cordova-plugin-file 4.1.1 "File"
cordova-plugin-inappbrowser 1.3.0 "InAppBrowser"
cordova-plugin-iosrtc 2.2.2 "iosrtc"
cordova-plugin-media-capture 1.2.1-dev "Capture"
cordova-plugin-whitelist 1.2.1 "Whitelist"
cordova-plugin-x-socialsharing 5.0.10 "SocialSharing"
cordova-universal-links-plugin 1.1.0 "Universal Links Plugin"
ionic-plugin-keyboard 1.0.8 "Keyboard"
phonegap-plugin-push 1.5.3 "PushPlugin"

A: Turns out it seems to be an issue with a plugin.
I created a separate blank project, added all plugins, added the android platform, then "cordova build" and – boom – the same response again. I then removed them one by one and always removed and added android afterwards, and built again until the error message disappeared.
Then, I just uninstalled that plugin in my main project, added android, and installed the plugin again. The error message has since disappeared.
Maybe this is helpful for someone.


text:
Q: No namespace in nested tags in SOAP message with JAX-WS I am trying to write a Java application that consumes a given web service, using JAX-WS and wsimport. The SOAP message that it sends to the service is mostly correct. However, on of the parameters passed to the service function is an array of strings. Although the array itself is given the proper namespace in the SOAP XML, elements ('parm' in the message below) have no namespace. This causes the service to fail.
<?xml version="1.0" ?>
<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
    <S:Body>
        <ns2:Submit xmlns:ns2="http://www.acme.com/service/wsdl">
            <ns2:service>SomeJob</ns2:service>
            <ns2:parms>
                <parm>someparam</parm>
                <parm>anotherparam</parm>
            </ns2:parms>
        </ns2:Submit>
    </S:Body>
</S:Envelope>

The <parm> elements should have read <ns2:parm>, or alternatively the <Submit> tag could have defined a default namespace <Submit xmlns="http://www.acme.com/service/wsdl"> (that is what the service suggests in an example SOAP message).
This question does resemble the one in JAX-WS: why nested elements are in "" namespace?. However there changing the style from RPC/Literal to Document/Wrapped solved the issue, while in my case the service is Document/Wrapped to begin with.
How can I convince the JAX-WS library to generate namespaces on the nested elements in the array?
TIA,
Jeroen
Update: Editing the generated code appears to work. Someone suggested adding a namespace attribute to the @XmlElement line preceeding the definition of 'parm' in the generated array type:
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "ArrayOfString", propOrder = {
    "parm"
})
public class ArrayOfString {

@XmlElement(nillable = true, namespace="http://www.acme.com/service/wsdl")
protected List<String> parm;
...
}

This causes JAX-WS to add the namespace and will probably solve the issue. As code generation is, in this case, done only once, editing the generated code is acceptable. Still I wonder whether there isn't a better solution.

A: You can also influence the namespace creation by adding
elementFormDefault="qualified"

either to your Java @XmlSchema annotation - or in your case - to the XSD defining the service.


text:
Q: Why does a Pewter mug keep a beverage hot better than a foam cup? I know my subject sounds improbable and that's why I posted it.  I helped my daughter with a science project for school.  We tested five different materials to determine which would keep hot water hot, glass, ceramic, plastic, pewter and foam.  To may amazement, the pewter did the best, though only slighter better than foam.  I was so surprised I re-did the tests for the foam and pewter and got the same results.  We placed boiling water in the cup and measured the temperature over a five minute period.  The temp in the foam cup dropped about 24 degrees and in the pewter it dropped about 23 over the five minute period.  All the others were a degree or two over that.  I can't explain this and I am a chemical engineer.  Can't find much about it on the Internet either.

A: The cup that insulates the best will minimize convention and present the hottest liquid at the surface, where the delta T between liquid and air will determine cooling.
The cup that conducts heat the best will carry heat from the top to the bottom and cause convection currents. The heat will spread more evenly throughout the liquid and the surface liquid will have a slightly lower temperature than with the best insulating cup. The delta T between liquid and air will be lower, even though heat content of the two cups of liquid were the same.
I would expect the insulated cup to cool faster if the mouth is the same size and shape and the liquid level is the same. A small change in air currents will have a big effect. Can you test with a lid? A floating disk of foam to fit each cup would do, and make measurements for 30 minutes.
That's my theory and I'm sticking to it!

A: The metal mug will equilibrate with the water much faster than the foam mug will— but after that the heat has no place to go$^\dagger$ except to be transferred away through radiation or be lost as steam via natural convection (which does not depend on the material of the mug). It turns out that radiation plays a very small role as shown below:
Say each mug is a cylinder with diameter $10\ cm$ and height $10\ cm$. Inputting the temperature of boiling water ($373\ K$) and the surface area of the mug ($150 \pi\ cm^2$) into the Stefan-Boltzmann Law gives an approximation of the heat radiated away by the cup of 15 Watts. 5 minutes at 15 Watts = 4,500 J of energy radiated away, which we will call $Q$. Assuming you filled the mugs to the top, there is $250 \pi\ cm^3$ of water or a mass $m$ of $250 \pi\ g$. Since water's heat capacity $C$ is $4.18\ J/g\cdot K$ you can calculate the temperature drop $\Delta T$ due to radiation using the definition of heat capacity:
$$\Delta T= \frac{Q}{mC} =\ \frac{4,500\ J}{\left(250 \pi\ g\right)\left(4.18\ J/g\cdot K\right)}=1.3\ K$$
That is much less than the 23 degrees temperature drop you report, so the majority of the heat loss comes from evaporative cooling as suggested by Martin Beckett. That means the cooling rate is relatively unaffected by the material of the mug and instead depends mostly on the area of the water surface exposed to air. A great teaching opportunity about the different mechanisms of heat transfer!

$^\dagger$This is assuming no additional conduction to the table. If the table was made of metal you might see the effect you were expecting, since the heat would be able to conduct quickly through the pewter mug into the table.

A: The heat loss from an open cup was probably dominated by evaporation so the material didn't have very much effect and was within the limits of your experiment.


text:
Q: Add Unique values from a specific range(column) into a listbox I am trying to add values from a specific range(column) into a listbox. However, the range has blank  cells and duplicates that I am trying to get rid of. The following code works (no error msg) and does populate the listbox, but it does not get rid of the duplicates.
Can someone help?
Private Sub UserForm_Initialize()
Dim rang, rang1 As Range
Dim lstrow As Long
Dim list(), ListUniq() As Variant
Dim iRw As Integer
Dim wb As Workbook
Dim ws As Worksheet
Dim x As Long

    Set wb = ThisWorkbook
    Set ws = wb.Sheets("Paramed Verification Grid")
    Set rang = ws.Range("E3").CurrentRegion
    lstrow = rang.Rows.Count + 1
    Set rang1 = Range("E3:E" & lstrow)
    'list = ws.Range("E3:E" & lstrow).SpecialCells(xlCellTypeConstants)

    'Resize Array prior to loading data
    ReDim list(WorksheetFunction.CountA(rang1))
    'Loop through each cell in Range and store value in Array
    x = 0
    For Each cell In rang1
        If cell <> "" Then
            list(x) = cell.Value
        x = x + 1
        End If
    Next cell
    ListUniq = WorksheetFunction.Unique(list)

    ListUniq = WorksheetFunction.Sort(ListUniq)
    ProviderListBx.list = ListUniq

End Sub


text:
Q: Word for "repeat giver" or "repeat giving"? My clergyman asked me whether there exists a single word for a person or thing "that keeps on giving," that is, gives over and over again.  I couldn't come up with such a word, but I volunteered the spontaneous coinages, "palindoric" or "palindotic" (for the adjectives, obviously).  Can anyone suggest a better word or coinage? Thank you.
POSTSCRIPTUM:  I should probably clarify a bit more:  he wanted the word to be value-neutral, one that could cover equally sinning and blessing, for example, or a long-deceased beloved grandparent and an abusive ex-spouse.  The idea behind this, I suppose, is that some events and persons in our lives can be reverberative either positively or negatively:  they continue to 'give' to us in some sense regardless of whether we want to accept.

A: Maybe you would like "fount".

fount - A source of a desirable quality or commodity.

It should be a familiar word to a clergyman because of the hymn "Come Thou Fount of Every Blessing".

A: How about "cornucopian"?  A cornucopia, literally meaning "horn of plenty", is a mythical object that could produce as much food as was desired, or, in some tellings, anything that was desired.  The word is defined by Merriam-Webster as "an inexhaustible store".


text:
Q: Nodejs not returning promise properly I'm working on a NodeJS + Express + Mongoose + MongoDB project.
This code works fine:
var findRecord = function(id) {
  // find record by id
  return User.findOne({
    _id: id
  }).then(function(record) {
      // if record not found
      if (!record) {
        return Promise.reject(constant.NOT_FOUND);
      } else {
        // return found object
        return Promise.resolve({
            data: record,
            status: constant.READ_SUCCESS
        });
      }
    }, function() {
        // if there is error reading record
        return Promise.reject(constant.READ_ERROR);
    });
};

Don't know what is wrong with this one:
var allRecords = function(skip, limit) {
  // find all records
  return User.find({}).limit(limit).skip(skip)
    .then(function(records) {
        console.log('executed');
        // if records found
        return Promise.resolve({
            data: records,
            status: constant.READ_SUCCESS,
        });
    }, function() {
        return Promise.reject(constant.READ_ERROR);
    });
};

executed never prints on console
Even this one also don't work:
var allRecords = function(skip, limit) {
  // find all records
  return User.find({}).limit(limit).skip(skip)
    .exec(function(records) {
        console.log('executed');
        // if records found
        return Promise.resolve({
            data: records,
            status: constant.READ_SUCCESS,
        });
    }, function() {
        return Promise.reject(constant.READ_ERROR);
    });
};

A: You need to run exec method:
User.find({}).limit(limit).skip(skip).exec();

Besides of this you shouldn't use Promise.resolve to return result from a promise, just return an object. Also, it's better to use catch callback, instead of second callback of then:
var allRecords = function(skip, limit) {
  return User.find({})
    .limit(limit)
    .skip(skip)
    .exec()
    .then(records => {
        console.log('executed');
        // if records found
        return {
            data: records,
            status: constant.READ_SUCCESS,
        };
    })
    .catch(err => Promise.reject(constant.READ_ERROR));
};


text:
Q: How to find a pattern in a specific column in a dataframe? I'm working on a Shiny app and I need some help.
I have a dataframe (loaded from a file). I want the user to be able to extract the rows for which a specific regex appears in a specific column of that dataframe. Let me rephrase: I want the user to select a column from the database and to search for values inside that specific column.
Let me show you an example.

*

*the user selects the column "Nutrient"

*the user types the world "iron"
Result: the function returns all lines in which the column "nutrient" contains "iron".
With a fixed column, that's easy: you just use grepl and extract all the rows that contain the expression you want. But I can't manage to make it work with a specific column. I have looked at countless questions and answer but none of them take the two inputs (patter and column).
This is my dataframe:

fileTable <- structure(list(
  omg = c("tomato", "domestic cat", "zebrafish", "giraffe", "common cougar", "fawn", "daim", "wild cat", "domestic cat",
          "muren", "jaguar", "green turtle", "dave grohl", "zebra", "tortoise", "dinosaur", "apex mellifera"),
  nutrient = c("iron", "iron", "zing", "nitrate", "manganese", "nitrogen", "bromure", "iron", "calcium",
               "calcium", "iron", "sodium", "metal", "nitrates", "sodium", "calcium", "sodium"),
  data3 = c(0.03, 0.02, 0.02, 0.09, 0.05, 0.04, 0.08, 0.05, 0.02, 0.07, 0.02, 0.01, 0.09, 0.12, 0.16, 0.08, 0.15)),
  row.names = c(NA, -17L),
  class = "data.frame")

fileTable
#>               omg  nutrient data3
#> 1          tomato      iron  0.03
#> 2    domestic cat      iron  0.02
#> 3       zebrafish      zing  0.02
#> 4         giraffe   nitrate  0.09
#> 5   common cougar manganese  0.05
#> 6            fawn  nitrogen  0.04
#> 7            daim   bromure  0.08
#> 8        wild cat      iron  0.05
#> 9    domestic cat   calcium  0.02
#> 10          muren   calcium  0.07
#> 11         jaguar      iron  0.02
#> 12   green turtle    sodium  0.01
#> 13     dave grohl     metal  0.09
#> 14          zebra  nitrates  0.12
#> 15       tortoise    sodium  0.16
#> 16       dinosaur   calcium  0.08
#> 17 apex mellifera    sodium  0.15

Here is my UI:
#The user uses this input to select the column in which he wants to look
choices <- names(fileTable)
selectInput('column', 'From column:', choices , selected = choices[1])

#Here, he types the value he is looking for
filter <- textInput(inputId = "filter", label = "Filter" )

#And this button validates.
actionButton(inputId = "filterButton", label = "Filter")

And here is my server:
 observeEvent(input$filterButton , {
    values <<- subset(theFile, grepl(input$filter, input$column, ignore.case = TRUE))
    print(values)
  })

This doesn't seem to work. Apparently, greplcan't find the column named input$column inside my dataframe. I end up with this:
OGM    Nutrient     data3
<0 rows> (or 0-length row.names)

Thank you for your help. I've been stuck on this for a while. If you need me to rephrase, don't hesitate (non-native English speaker here).

A: You are doing some mistakes: 1. Do not use <<-. It does not work this way. Modify data inside reactive statements. 2. To create a dataframe based on a click, always use eventReactive. Attached you find an app, which should solve your problem.
df <- data.frame(
    OGM = c("tomato", "domesticcat", "zebrafish", "giraffe", "common cougar", "fawn", "daim", "wild cat", "domestic cat", "muren", "jaguar", "green turtle", "dave grohl", "zebra", "tortoise", "dinosaur", "apex mellifera"),
    Nutrient = c("iron", "iron", "zing", "nitrate", "manganese", "nitrogen", "bromure", "iron", "calcium", "calcium", "iron", "sodium", "metal", "nitrates", "sodium", "calcium", "sodium"),
    data3 = c(0.03, 0.02, 0.02,  0.09, 0.05, 0.04, 0.08, 0.05, 0.02, 0.07, 0.02, 0.01, 0.09, 0.12, 0.16, 0.08, 0.15)
)

library(shiny)

# Define UI for application that draws a histogram
ui <- fluidPage(

   # Application title
   titlePanel("Match my data"),

   # Sidebar with a slider input for number of bins
   sidebarLayout(
      sidebarPanel(
        selectizeInput("column", "From column:", choices = colnames(df), selected = colnames(df)[1], multiple = FALSE),
        textInput(inputId = "filter", label = "Filter"),
        actionButton(inputId = "filterButton", label = "Filter")
      ),
      # Show a plot of the generated distribution
      mainPanel(
         tableOutput("table")
      )
   )
)

# Define server logic required to draw a histogram
server <- function(input, output) {

    filtereddf <- eventReactive(input$filterButton, {

        df[grepl(input$filter, df[[input$column]]), ]

            # filter(grepl(input$filter, input$column, ignore.case = TRUE))
    })

    output$table <- renderTable({

        if(input$filterButton == 0) {
            return(df)
        } else {
            return(filtereddf())
        }
    })
}

shinyApp(ui = ui, server = server)

A: Would something like this help you?
df <- structure(list(
  omg = c("tomato", "domestic cat", "zebrafish", "giraffe", "common cougar", "fawn", "daim", "wild cat", "domestic cat",
          "muren", "jaguar", "green turtle", "dave grohl", "zebra", "tortoise", "dinosaur", "apex mellifera"),
  nutrient = c("iron", "iron", "zing", "nitrate", "manganese", "nitrogen", "bromure", "iron", "calcium",
               "calcium", "iron", "sodium", "metal", "nitrates", "sodium", "calcium", "sodium"),
  data3 = c(0.03, 0.02, 0.02, 0.09, 0.05, 0.04, 0.08, 0.05, 0.02, 0.07, 0.02, 0.01, 0.09, 0.12, 0.16, 0.08, 0.15)),
  row.names = c(NA, -17L),
  class = "data.frame")

col_select <- "nut"
row_match <- "iron"

col_to_match <- grep(col_select, colnames(df))
rows_to_take <- df[, col_to_match] %in% row_match

df[rows_to_take, ]
#>             omg nutrient data3
#> 1        tomato     iron  0.03
#> 2  domestic cat     iron  0.02
#> 8      wild cat     iron  0.05
#> 11       jaguar     iron  0.02

Created on 2019-06-18 by the reprex package (v0.3.0)

A: you can try something like this?
library(shiny)
data <- structure(list(OGM = c("tomato", "domestic cat", "zebrafish",
                               "giraffe", "common cougar", "fawn", "daim", "wild cat", "domestic cat",
                               "muren", "jaguar", "green turtle", "dave grohl", "zebra", "tortoise",
                               "dinosaur", "apex mellifera"), Nutrient = c("iron", "iron", "zing",
                                                                           "nitrate", "manganese", "nitrogen", "bromure", "iron", "calcium",
                                                                           "calcium", "iron", "sodium", "metal", "nitrates", "sodium", "calcium",
                                                                           "sodium"), data3 = c("0.03", "0.02", "0.02", "0.09", "0.05",
                                                                                "0.04", "0.08", "0.05", "0.02", "0.07", "0.02", "0.01", "0.09",
                                                                                "0.12", "0.16", "0.08", "0.15")), class = "data.frame", row.names = c(NA,
                                                                                -17L))
ui <- fluidPage(
    titlePanel("This app"),
    sidebarLayout(
        sidebarPanel(

         selectInput('column', 'From column:', choices = names(data)),
         uiOutput("COLUMN_VALUES")
        ),
    mainPanel(
        tableOutput("filtered_data"),
        h3("you also can try DT::datatable"),
        #DT::datatable(data)
        )
    ))

server <- function(input, output) {
 output$COLUMN_VALUES <- renderUI({
     selectInput("row", "From Row", choices = unique(sort(data[,input$column])), multiple = T)
 })

 output$filtered_data <- renderTable({
     req(input$row)
     data[grep(paste(input$row, collapse ="|"), data[,input$column]),]
     })
}
# Run the application
shinyApp(ui = ui, server = server)


text:
Q: Formula for determinant of sum of matrices Some time ago I came across this apparently quite obscure formula that expands the determinant of a sum of two matrices that I had put on my notes (assuming that I made no errors in my writing):
$$\det(A+B)=\det(A)+\det(B)+\text{Tr}(\text{adj}(A)B)$$
Where $\text{adj}()$ denotes the adjugate of the matrix. I cannot seem to find any mention of this formula online. Does anyone know of the name (and maybe a proof) of it? Furthermore, is there any more info on it, like conditions that $A$ and $B$ must obey for it to hold?

A: It seems to me that you are asking for is a sort of "Taylor expansion" keeping track of the "errors" of various weights. So perhaps the generalisation you want is this, which is not hard to check:
$$
\det(A+xB)=
\det A \sum_{s} x^s\ \textrm{tr}\left( (A^{-1})^{(s)} B^{(s)}\right)
$$
where $X^{(s)}$ is the matrix of $s\times s$
cofactors.
There are variants got by expressing $A^{-1}$ in terms of the determinant and adjugate, or replacing $(A^{-1})^{(s)}$ by $(A^{(s)})^{-1}$

A: For $2 \times 2$ matrices, the following holds
$$\det (\mathrm I_2 +  \mathrm M) = 1 + \det(\mathrm M) + \mbox{tr}(\mathrm M)$$
If $\rm A, B$ are $2 \times 2$ matrices, and temporarily assuming that $\rm  A$ is invertible, then
$$\begin{array}{rl} \det (\mathrm A +  \mathrm B) &= \det \left( \mathrm A \left( \mathrm I_2 +  \mathrm A^{-1} \mathrm B \right) \right)\\ &= \det (\mathrm A) \cdot \det \left(\mathrm I_2 +  \mathrm A^{-1} \mathrm B \right)\\ &= \det (\mathrm A) \cdot \left( 1 + \det(\mathrm A^{-1} \mathrm B) + \mbox{tr}(\mathrm A^{-1} \mathrm B) \right)\\ &= \det (\mathrm A) + \det (\mathrm A) \cdot \det(\mathrm A^{-1} \mathrm B) +  \mbox{tr} \left( \det (\mathrm A) \, \mathrm A^{-1} \mathrm B \right)\\ &= \det (\mathrm A) +  \det (\mathrm B) + \mbox{tr} \left( \mbox{adj}(\mathrm A) \mathrm B \right)\end{array}$$

A: Given two $2 \times 2$ matrices $A$ and $B$,
$$\det(A + B) = 2(\det(A) + \det(B)) - \det(A - B)$$
This can be proven directly via the formula for the determinant of a $2 \times 2$ matrix, and therefore applies whether the matrices are invertible or not.
If $A = \begin{bmatrix}a&c\\b&d\end{bmatrix}$ and
$B = \begin{bmatrix}e&g\\f&h\end{bmatrix}$,
$$\text{tr}(\text{adj}(A)B) = \text{tr}\left(\begin{bmatrix}d&-c\\-b&a\end{bmatrix} \begin{bmatrix}e&g\\f&h\end{bmatrix}\right) = \text{tr}\left(\begin{bmatrix}de-cf&dg-ch\\af-be&ah-bg\end{bmatrix}\right) = de-cf+ah-bg$$
$$\det(A) + \det(B) - \det(A-B) = ad - bc + eh - fg - (a-e)(d-h) + (b-f)(c-g)\\$$
Combining like terms shows that $$\text{tr}(\text{adj}(A)B) = \det(A) + \det(B) - \det(A - B)$$
and therefore that $$\det(A) + \det(B) + \text{tr}(\text{adj}(A)B) = 2(\det(A) + \det(B)) - \det(A - B) = \det(A + B)$$
To answer your other questions, I don't know the name of either formula (I discovered the one I used independently, though I doubt I'm the first). And like I said, my formula applies to all $2\times2$ matrices, invertible or not, and your formula is equivalent to mine, so the matrices need not be of a special form.


text:
Q: Create a constant for "this" in Lightning helper Is there any possibility to create a constant for "this" in Lightning helper?
I have tried the following syntaxis:
self : this,

initializeInputs : function(component, webLeadData) {}

But I receive the following error message:

Error:(1, 1) c.ddcm_quote:
  org.auraframework.util.json.JsonStreamReader$JsonStreamParseException:
  Invalid literal value [6, 12]: 'this'

A: The reason you cannot do that is because that this will directly point to window. This is not allowed in lightning because of locker service.
Further Explanation:
helper or controller in lightning component are actually a part of closure function which would render like below in client machine:
(function () {
        const { $A } = window;

        return {
            "meta": {
                "name": "c$MyAuraComponent",
                "extends": "markup://aura:component"
            },
            "controller": {
                "doInit": function (component, event, helper) {

                }
            },
            "helper": {
                "helperMethod": function () {

                },
                "helperMethod2": function () {

                }
            }
        };

    }())

So here when you add variable pointing to this in helper, it will directly refer to window. Hence it will not even compile.
Note: However, when you define this inside helper function, its not a problem as function is scoped and lightning framework will take care of referring to helper functions.


text:
Q: Does a faster hard drive cause a laptop's battery to drain faster? I currently have a slow 5400 rpm drive in my laptop and I am looking at installing a 7200rpm drive.
The new drive is reported to be 100 times faster than the old drive. The traditional advice would say that a 7200rpm drive, drain laptop batteries faster, however if you compare the specifications this appears not to be the case is this correct? For example:
My current 5400rpm drive:

*

*spin up power: 4.5w

*seek power: 2.2w

*read/write: 1.9w

Replacement 7200rpm drive:

*

*seek power: 2.3w

*read/write: 2.1w

*spin up power: 5.5w

If I read this correctly, does this mean switching to a 7200rpm drive will have a negligible power drain impact? For those interested, I am comparing the following two drives:

*

*5400 RPM Toshiba MK2553GSX

*7200 RPM MKxx61GSY Series

A: I think you will find that those 'small' differences will have a significant impact on battery life.  It's not going to halve it but it will be noticable.

A: Better materials will reduce the friction in the spindle once it has spun up, leading to lowered power use while spinning. Do note the difference in the spin-up power of the drives though; the drive that spins faster needs more power to get spun up.

A: 7200rpm drives use slightly more power but usually not enough to be noticeable. The optimal solution is an SSD drive if you don't need a huge amount of storage space, ie: less than 500gb.

A: It's actually the opposite.
After replacing my laptop HDD with SDD my laptop works faster and the battery lasts longer.
So no HDD. Use only SSD.


text:
Q: How to create programmatically an AWS Console enabled user I'm trying to add programmatically a "working" AWS account via API.
Actually I'm performing this operations:

*

*Authentication

*CreateUser (login)

*CreateLoginProfile (password)

When I go on "AWS" console I get an error an if I look to the Accounts linked to the Organization I can't find my new account.
But if I go on https://console.aws.amazon.com/iam/home#/home the user is there.
Do I'm missing something? Is there any difference between USER and ACCOUNT?

A: Of course USER and ACCOUNT are different. An account contains users and other resources (S3 bucket, EC2 instance).
If you want to create new AWS account, you need to use Organizations API.
See:

*

*create-account in the AWS CLI

*CreateAccount documentation


text:
Q: babel-node --presets node '.' is not recognized as an internal or external command, this is the dependencies in package.json
{
  "name": "whatsapp",
  "version": "1.0.0",
  "description": "whatsapp-clone-in-mern-stack",
  "main": "server.js",
  "scripts": {
    "start": "./node_modules/babel-cli/bin/babel-node.js --presets node8 ./server.js",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "someone",
  "license": "ISC",
  "dependencies": {
    "babel": "^6.23.0",
    "babel-cli": "^6.26.0",
    "babel-preset-node8": "^1.2.0",
    "body-parser": "^1.19.0",
    "compression": "^1.7.4",
    "cors": "^2.8.5",
    "express": "^4.17.1",
    "moment": "^2.29.1",
    "mongoose": "^6.0.14"
  }
}

code in server.js file
    import App from "express";
    import connectDB from "./dbConnection";
     const app = new App();

     const PORT = 3001;

     const startServer = () => {
         Promise.all([connectDB()]).then(() => {
             app.listen(PORT);
             console.log(`Server started on port ${PORT}`);
         });
     };

     startServer();

code in index.js file
import mongoose from "mongoose";

const DB_CONNECTION_URL = "mongodb://localhost:27017/test";

const connectDB = () => {
    console.log("DB trying to connect on " + new Date());
    const options = {
        keepAlive: 1,
        autoReconnect: true,
        poolSize: 10,
        useNewUrlParser: true,
        useUnifiedTopology: true,
    };
    return mongoose.connect(DB_CONNECTION_URL, options);
};

export default connectDB;

error in console
    whatsapp@1.0.0 start C:\Users\krish\onedrive\desktop\whatsapp_clone-mern_Stack\whatsapp-clone\server
    > ./node_modules/babel-cli/bin/babel-node.js --presets node8 ./server.js

    '.' is not recognized as an internal or external command,
    operable program or batch file.
    npm ERR! code ELIFECYCLE
    npm ERR! errno 1
    npm ERR! whatsapp@1.0.0 start: `./node_modules/babel-cli/bin/babel-node.js --presets node8 ./server.js`
    npm ERR! Exit status 1
    npm ERR!
    npm ERR! Failed at the whatsapp@1.0.0 start script.
    npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

    npm ERR! A complete log of this run can be found in:
    npm ERR!     C:\Users\krish\AppData\Roaming\npm-cache\_logs\2021-11-30T

09_26_47_364Z-debug.log

Learning from YouTube tutorials, I tried to make a whatsapp clone. I wanted to use babel cli and babel node to start the server in order to connect the database, so I wrote this code { "./node_modules/babel-cli/bin/babel-node.js --presets node8 ./server.js" } in the scripts, but it displays the above error. Please help me.

A: The error you are encountering is due to using *nix path syntax in Windows. Try writing the path with windows backslashes or try
babel-node --presets node8 .\server.js

A: write this
"scripts": {
    "start": "node ./node_modules/babel-cli/bin/babel-node.js --presets node8 ./server.js",
    "test": "echo \"Error: no test specified\" && exit 1"
  },

instead of this
"scripts": {
        "start": "./node_modules/babel-cli/bin/babel-node.js --presets node8 ./server.js",
        "test": "echo \"Error: no test specified\" && exit 1"
      },


text:
Q: Using ActiveObjects in JIRA Plugin development in abstractIssueAction I am using Active Objects in Jira Plugin Development.
For a JiraWebActionSupport created with the webwork plugin module type it works perfectly fine.
@Named
public class IssueConfigAction extends JiraWebActionSupport
{
private static final Logger log =
LoggerFactory.getLogger(IssueConfigAction.class);

@ComponentImport
private final ActiveObjects ao;
private String issueId;

@Inject
public IssueConfigAction(ActiveObjects ao){
    this.ao=ao;
}

@Override
protected String doExecute() throws Exception {

    IssueConfig ic = ao.create(IssueConfig.class);
    ic.setIssueId(issueId);
    ic.save();
    return SUCCESS;

}

public String getIssueId() {
    return issueId;
}

public void setIssueId(String issueId) {
    this.issueId = issueId;
}
}

But how can i use active objects in any other class like abstract issue action?
public class IssueTabAction extends AbstractIssueAction {

@ComponentImport
private final ActiveObjects ao;

@Inject
public IssueTabAction(IssueTabPanelModuleDescriptor descriptor) {
    super(descriptor);
}

@Inject
public IssueTabAction(ActiveObjects ao) {
    super();
    this.ao=ao;
}

@Override
public Date getTimePerformed() {
    // TODO Auto-generated method stub
    return new Date();
}

@Override
protected void populateVelocityParams(Map params) {
    params.put("user", ComponentAccessor.getJiraAuthenticationContext().getLoggedInUser().getDisplayName());
    params.put("strings", new String[]{"1","2","3","4"});
}

}

I don't know how to inject the constructor correctly?
Or is there a better way to do this?


text:
Q: How to make Makefile generated by qmake on windows? (nmake and mingw-make) OS: Windows 10, x64
I have a simple demo of qt console project, which simply print hello world.
This project can be built and run correctly(with MSVC kit), but I want to separate the process.
First, I click "execute qmake" in the right-click menu on the project in Qt Creator, I got a make file in the release and debug directory
build-hello-Desktop_Qt_5_12_3_MSVC2017_64bit-Release\makefile
open cmd, cd to this directory, and then the story ends.
If I use nmake, I got error C1083, which tell me can not find stdio.h
If I use make on windows or mingw-make32, I still got an error   missing separator.
I have 2 questions:
1.Can someone give a full instruction of how to make this makefile both with mingw-make32 and nmake?
2.The makefile generated by qmake looks very complex and illegible, not like those makefiles in tutorial. Is it just the same as a normal makefile, or it's special?
I search for a lot but still can get the clear solution so please help.
the Makefile looks like this:
#############################################################################
# Makefile for building: hello
# Generated by qmake (3.1) (Qt 5.12.3)
# Project:  ..\name\hello.pro
# Template: app
# Command: C:\Qt\Qt5.12.3\5.12.3\msvc2017_64\bin\qmake.exe -o Makefile ..\name\hello.pro -spec win32-msvc "CONFIG+=qtquickcompiler"
#############################################################################

MAKEFILE      = Makefile

EQ            = =

first: release
install: release-install
uninstall: release-uninstall
QMAKE         = C:\Qt\Qt5.12.3\5.12.3\msvc2017_64\bin\qmake.exe
DEL_FILE      = del
CHK_DIR_EXISTS= if not exist
MKDIR         = mkdir
COPY          = copy /y
COPY_FILE     = copy /y
COPY_DIR      = xcopy /s /q /y /i
INSTALL_FILE  = copy /y
INSTALL_PROGRAM = copy /y
INSTALL_DIR   = xcopy /s /q /y /i
QINSTALL      = C:\Qt\Qt5.12.3\5.12.3\msvc2017_64\bin\qmake.exe -install qinstall
QINSTALL_PROGRAM = C:\Qt\Qt5.12.3\5.12.3\msvc2017_64\bin\qmake.exe -install qinstall -exe
DEL_FILE      = del
SYMLINK       = $(QMAKE) -install ln -f -s
DEL_DIR       = rmdir
MOVE          = move
SUBTARGETS    =  \
        release \
        debug

A: full instruction of how to make this makefile with nmake
run visual studio command prompt and then run nmake inside it rather than run nmake in common cmd, because vs command prompt has already set the specific environment variables such as the path of includes and c++ standard library, whichout which cl.exe and link.exe can not work.
This is the reason exacly why can not find stdio.h.


text:
Q: Optimally searching for 2D points in the given area (webservice) I've got a kind of algorithmic & performance problem to solve with Java. I've got a large collection of 2D points (let's say there are about 100 000 of them). I want to get a set of them that are in the given area around the search point SP(X_sp, Y_sp), so that I'd like to get the points P(x y) that meets the criteria:
x is between X_sp - constValue and X_sp + constValue AND y is between Y_sp - constValue and Y_sp + constValue
To give you an idea of the number relations, constValue will be like 2, 5 or 10, and x, y will range between 0  and 1000. It's meant to be a webservice, so a possibility of searching around many different points at the same time must be taken into account.
As these are fixed points (not to change due to calculations or something), I thought that it would be optimal to provide one list of objects sorted by X and another one, but sorted by Y. Then, I'll first get the points within the X range, and, using references, get the set of this points from another list (sorted by Y). Then I'll narrow this selection by Y and in result get the points in the given area.
I don't know Java inside-out, so I'd like to consult with you the most optimized approach. Which objects should I use to store sorted points, which allow for fast search of objects within range? Or maybe I have to implement my custom algorithm for this task? Also, when it comes to storing the points in the database, are SQL queries sufficiently fast to deliver the results? Or maybe NoSQL dbs are better for this?
I'm going to perform my own tests, but I'm looking for a starting candidates.

A: I'd probably use a TreeMap<Integer, TreeSet<Integer>>, where the key to the map is the x coordinate and for each x coordinate, you have a list of y coordinates. You can then use floorEntry and ceilingEntry to find the x coordinates that fall within your range. Then for each TreeSet<Integer> set that you get, you can use ceiling and floor to get the appropriate entries.
Of course, this only gives you the coordinates of the bounds of your box (the four corners). But TreeSet also has a subset that will give you a range of values. You will have to use this twice; once for the list of x coordinates (you can get the key set using the keySet method of the map) that are within your bounds, then for each x coordinate, the y coordinates that are within the bounds. So the pseudocode would be sort of like this:
List<Point> result = new ArrayList<>();
int lowerX = points.ceilingKey(x - c);
int upperX = points.floorKey(x + c);
for each x coordinate in points.entrySet().subset(lowerX, upperX)
    TreeSet<Integer> yCoordinates = points.get(x);
    lowerY = yCoordinates.ceiling(y - c);
    upperY = yCoordinates.ceiling(y + c);

    for each y coordinate in yCoordinates.subset(lowerY, upperY)
       result.add(new Point(x, y))

I haven't tested this out, so there are probably some bugs or something I've missed. Let me know and I'll correct the answer.
The floor and ceiling calls are log(n) I believe -- this is where you get the performance benefit because if you use a list, it would be O(n) to look that up.
Note: I don't know if this is the most performant. SO is typically not the place for such an open-ended question so you might have more luck elsewhere.


text:
Q: How to specifiy both a method argument and part of a data frame in corr In the below code, I wish to specifiy 'pearson' as method but this does not seem possible if I am at the same time defining an argument with a dataframe's column. Therefore, I am not able to simply do corr(method='pearson'), any solution or way around this?
df_dataframe1['Food'].corr(df_dataframe1['Ingredient'])

A: You can use DataFrame.corrwith with method='pearson':
df_dataframe[['Food']].corrwith(df_dataframe1[['Ingredient']], method='pearson')


text:
Q: C++ fabs(long double) compiler warning I want to have the absolute value of a long double.
According to <cmath> or <math.h>, the following is available:
     double fabs (double x);
     float fabs (float x);
     long double fabs (long double x);

However, when doing long double ld = fabs(static_cast<long double>(0));, I get the following warning (LLVM 7.1):
Absolute value function 'fabs' given an argument of type 'long double' but has parameter of type 'double' which may cause truncation of value
How come?
What other ways are there to get the absolute value of a long double?
Edit:
std::abs eventually did the job. However, std::fabs didn't. As was pointed out in the comments, this may be due to a non-conforming implementation.

A: According to cppreference http://en.cppreference.com/w/c/numeric/math/fabs and http://en.cppreference.com/w/cpp/numeric/math/fabs the C version of fabs in the global namespace only accepts a double argument and you would need to use fabsl. However std::fabs or std::abs should have the proper long double overloads for you.


text:
Q: How can I download and install refind bootloader (0.7.7.1)? I've seen an answer on installing Ubuntu on MSI-GT60 laptop on this site. It suggests that I should install rEFInd bootloader but I can't find it anywhere.
How can I install this?

A: Download rEFInd Boot Manager for Ubuntu from its page here or the current version 0.7.8 from  Sourceforge.
Since it is .deb file installation is as easy as double clicking the .deb file which will open the installer to install it.
or from the terminal you can do
dpkg -i name_of_file_you_downloaded.deb

to install it.

A: Instructions for refind are here:
http://www.rodsbooks.com/refind/
http://www.rodsbooks.com/linux-uefi/#troubleshooting


text:
Q: Nginx with ssl_verify_client = on doesn't fail the TLS handshake I have Nginx 1.10 with ssl_verify_client = on. Everything works fine, except that the server finishes TLS handshake and proceeds to parse the headers even though the certificate hasn't been sent by the client.
It can be verified by sending http request without client certificate and extremely big http header, nginx returns "400 Request Header Or Cookie Too Large".
According to our security auditor, the server should fail the TLS handshake, because parsing the headers "increases the possible attack surface.
My nginx config:
server {
    listen 443 ssl default_server;
    listen [::]:443 ssl default_server;

    server_name myserver.com;

    ssl_certificate /etc/letsencrypt/live/myserver.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/myserver.com/privkey.pem;

    ssl_verify_client on;
    ssl_client_certificate /etc/nginx/ssl/ca.pem;

    location / {
            proxy_pass       http://127.0.0.1:8001;
            proxy_set_header Host      $host;
            proxy_set_header X-Real-IP $remote_addr;
    } }

A: I think you need to require SNI use to avoid header inspection. Nginx must determine if a server block matches the request and to do that, it needs a hostname. It can get a hostname from SNI during the TLS handshake, but if SNI is not used, it needs to read host information from the http headers.
You can require SNI use by setting up a default server-block handler for non-SNI client requests that refuses these connections. To do that, remove the default_server directive from your main ssl server block and add an explicit default server above it that 1) listens on 443, 2) matches requests with no host name, and 3) always returns 444. Example:
server {
  listen 443 ssl default_server;
  listen [::]:443 ssl default_server;
  server_name   "";

  ssl_ciphers aNULL;
  ssl_certificate /path/to/dummy.crt;
  ssl_certificate_key /path/to/dummy.key;

  return 444;
}

server {
  listen 443 ssl;
  listen [::]:443 ssl;

  server_name myserver.com;

  ssl_certificate /etc/letsencrypt/live/myserver.com/fullchain.pem;
  ssl_certificate_key /etc/letsencrypt/live/myserver.com/privkey.pem;

  ssl_verify_client on;
  ssl_client_certificate /etc/nginx/ssl/ca.pem;

  location / {
        proxy_pass       http://127.0.0.1:8001;
        proxy_set_header Host      $host;
        proxy_set_header X-Real-IP $remote_addr;
} }

The default server then handles any SSL requests that do not use SNI. The 444 return is an nginx non-standard code that closes the connection. This structure also closes a potential security hole in which a default-server's certificate can expose resources in unexpected ways. Now nginx will only process requests  that use SNI and that have a hostname matching one of your other server blocks.


text:
Q: Use column alias in dataProvider In my model I have a relation() like this.
        'notRelUser' => array(
            self::HAS_MANY,
            'LocationUser',
            'location_id',
            'condition' => 'notRelUser.status is null',
            'on' => 'notRelUser.user_id = ' . Yii::app()->user->getId(),
            'with' => array('parent_location'),
            'select' => array('*', 'name AS canApply'),
        ),

and this
public $canApply;

In my controller I have this
    $regions = Location::model()->with('notRelUser')->findAll();
    $arrayCanApply = new CArrayDataProvider($regions);

I then am trying to print out the value of canApply in a widget for datagrid
<?php $this->widget('bootstrap.widgets.TbGridView', array(
'dataProvider'=>$arrayCanApply,
'columns'=>array(
    array('name'=>'name', 'header'=>'Name'),
    array('name' => 'canApply', 'value'=>'$data->canApply', 'header'=>'CanApply'),
 ),
 ));

But the column with canApply is empty.
I have also tried without the $data-> part.
How can I print this alias?
(I know the value of the alias i trivial, but I will change that later)
UPDATE:
I can get the value by using select in CDbCriteria - but I want to do it in relation.
This does work.
$criteria = new CDbCriteria;
$criteria->select = '("foobar") AS canApply';
$regions = Location::model()->with('notRelUser')->findAll($criteria);

but it seems odd that I have to create a $criteria on everytime

A: you need to declare can canApply as an attribute of the model
in your model decalare canApply as an attribute
public $canApply;

A: I also had the same problem. Try 'value'=>'$data->notRelUser->canApply'
instead of 'value'=>'$data->canApply'. Also, you need to declare attribute
public $canApply;

in your LocationUser model, not in Location model.


text:
Q: Unable to make a vector of pointers For the last two or three hours I have been wrestling with this problem without any luck. I am reading in the text and then trying to make an adjacency list with all vertices having a link to the adjacent vertices in the list. The vertex class look like this:
class Vertex {
private:
  std::vector<Vertex*> connPtrVertices;  // vector of vertices adjacent to this one
public:
  void addVertex(Vertex* vert) { connPtrVertices.push_back(vert); }

And in main.cpp I am trying to connect the vertices to each other like this:
Vertex *v1, *v2;
v2->addVertex(v1);    // connect v2 to v1
v1->addVertex(v2);    // connect v1 to v2

I am getting a Debug Assertion Failed message which is:
Debug Assertion Failed!

Program: C:\Windows\system32\MSVCP110D.dll
File: c:\program files (x86)\microsoft visual studio 11.0\vc\include\vector
Line: 240

Expression: vector iterators incompatible

I have no clue what to do, any help will be greatly appreciated.
Edit:
The first time through the loop I am assigning v1 and v2 with new but then the second time I check if they exist and if they do I assign a pointer to Vertex like this:
v1 = &(p_graph->getVertex(vert1));

The method that is called is this:
Vertex Graph::getVertex(std::string v) {         // gets the vertex
  for (std::vector<Vertex>::iterator it = vertices.begin(); it != vertices.end(); it++) {
     if ((it->getName()).compare(v) == 0)
        return *it;  // if strings are the same return vertex
    }
    exit(1);
 }

Is this where the mistake is?

A: *

*Its seems that you are just trying to compile this code. Now, if you build the project, does it Build without a compiler error? What about debugging? you can try, "Start without Debugging". This will execute your code without debugging.

*The error message you are getting says: "vector iterators incompatible"

*This error is coming from where you wrote an iterator and its seems to be in Graph::getVertex(std::string v) function. To confirm it`s this function, you can comment out the whole Graph::getVertex(std::string v) function definition and see if the error disappears.

*To fix the iterator error "incompatible type" you can declare your iterator with typedef like this:

*typedef std::vector "<"Vertex">" VertexType;

*VertexType vertices;

*Vertex Graph::getVertex(std::string v) {

*VertexType::iterator it;

*for (it = vertices.begin(); it != vertices.end(); ++it){

*return *it;

*}

*exit(1);

*}

*Make sure your iterator is pointing to Vertex object type.


text:
Q: WPF how to reference application resource from merged dictionary? So if I have a converter in the resource dictionary for my app like so:
<Application.Resources>
    <ResourceDictionary>
      <Converters:ColorToBrushConverter x:Key="ColorToBrushConverter" />

      <ResourceDictionary.MergedDictionaries>
        <ResourceDictionary Source="ResourceDictionaries/GraphViewerBrushes.xaml" />
        <ResourceDictionary Source="ResourceDictionaries/ColorPickerResources.xaml" />
      </ResourceDictionary.MergedDictionaries>

    </ResourceDictionary>
  </Application.Resources>

How can I reference the converter from within one of the external xaml files? or is this not possible? i know i could just reinstance another converter there, but that seems wasteful.

A: You can use DynamicResource instead of StaticResource to reference the converter.  This will cause it to look up the resource dynamically, which should succeed as it's part of the Application resources.
That being said, I typically just create another instance, as it is simpler, and a converter has very, very little overhead to create (since it should have no state).


text:
Q: Homeomorphism between positive rationals and non-negative rationals Professor told me the two spaces are homeomorphic if we consider them as subspaces of R equipped with the standard topology.
It's a bit surprising for me since I have already found Q is homeomorphic to the positive rationals and I know that the two spaces in the main question are homeomorphic, so how can the positive rationals and non-negative rationals be homeomorphic?


text:
Q: How can I select row of a given CurrentRegion without using Selection.EntireRow.Select using VBA? I know I can Select a Range, let's say I have a currentRegion between Range("A3") to Range("E3")
Range("A3").Select then continue with Selection.EntireRow.Select. But the issue I am facing now is that the later code is taking so much time to run while The range I am only interest into is only the row in the CurrentRegion, that is I want a code would select on from Range("A3:E3") basing on my CurrentRegion. I want the code to be dynamic as I am dealing with more than 700 sheets and their respective CurrentRegion will be changing as I loop through the sheets.
Any help is much appreciated, thank you!


text:
Q: special eclipse hotkey Does eclipse have a hotkey to change the name of the function in all places, if I changed it in one place?

A: ALT + SHIFT + R, than enter the new name and press Enter. Every reference in your workspace will be updated!


text:
Q: What is graphical addition? "Use the graphs of f and g and the method of graphical addition to sketch the graph of $f + g$".
$f(x) = x, g(x) = \frac{1}{x}$

A: You plot each function on the same pair of axes.  Then for each $x$ value of interest, you plot $(f+g)(x)$ by measuring $g(x)$ above the $f(x)$ line.  It results in the same thing as making a table of values of $(f+g)(x)$ and plotting them.  I believe "graphical addition" refers to the process of adding the functions on the graph paper.

A: Graphical addition means $(f+g)(x)=f(x)+g(x)$ for all domain elements.
So you need to graph $(f+g)(x)=x+\frac{1}{x}$.


text:
Q: How to properly set up a decimal mask using jQuery MaskedInput 1.3 I am using jQuery 1.7.1 and jQuery maskedinput 1.3 in my ASP.NET MVC 3 app.
How would I set up a masked item that accepts a decimal value (SQL decimal 10,2).  What I have works but it looks horrible:
$('#AnnualIncome').mask('9?9999999.99', { placeholder: ' ' });

When I go to my page and click on the textbox then there is space for numeric values with a . further on for the decimal part.  This looks horrible and it doesn't seem to work well.  I will type in 9 for the left part of the decimal and then 99 for the right part of the decimal.  So if the textbox still has the focus then it looks something like this:
9___________.99

I don't want it like this, I want the user to be able to type in a decimal anytime, I want something like:
9.99

Also, if the textbox looses focus, then it now looks like:
999

I need it to display:
9.99

Can someone please help me set this up properly?

A: The Masked Input jQuery Plugin is meant for fixed width input, like formatting phone numbers. Have a look at e.g. the numeric Plugin or the autoNumeric Plugin instead.

A: The Masked Input jQuery Plugin can be configured to support variable width decimal places.
Firstly add a mask definition that supports your local decimal place separator or numeric characters:
$.mask.definitions['d'] = '[0-9.]';

Then define the mask:
$('#AnnualIncome').mask('9?dddddddd', ' ');

Decimal places are optional and you cannot control the number of decimal places but still useful in certain scenarios and saves adding another plugin.


text:
Q: Cannot read property 'parentNode' of null of a jquery selector element I need to make an editable combobox for a list, I use _ to load a template into the js file. While making a new ComboBox object I use use jquery selector to select the element but I get a Cannot read property 'parentNode' of null error.
Here is the Javascript:
var deps = [
'jquery', 'underscore', 'lib/combobox', 'dialogs/FlowNode',
'text!dialogs/choose-feature.html'
];

define(deps, function($, _, combobox, FlowNode, ChooseFeatureTmpl) {

var ChooseFeatureTemplate = _.template(ChooseFeatureTmpl);
    return {
    create: function(transition) {
        var node = FlowNode.create(ChooseFeatureTemplate, transition);
        // add the controls onto the FlowNode for displaying
        // the limiting of features

        $(node).on('render', function() {
            var typecombo = new ComboBox($('input[name="select-type"]'));
            var organism_selector = '#' + node.uid() + ' select[name="select-organism"]';
            var type_selector = '#' + node.uid() + ' input[name="select-type"]';
            var feature_selector = '#' + node.uid() + ' select[name="select-feature"]';

            var changeFn = function() {
                var organism = $.parseJSON(
                    unescape($(organism_selector + ' option:selected').data('organism'))
                );
                var type = $.parseJSON(
                    unescape($(type_selector + ' option:selected').data('type'))
                );

                // clear out the feature select box
                var $featureselect = $(feature_selector);
                $featureselect.empty();

                // refill the feature select box

                $.each(node.data().features, function(id, feature) {
                    if (feature.organism == organism.id && feature.type == type.name) {
                        var $option = $('<option />').text(feature.name + " - " + feature.uniquename)
                            .attr('data-feature', escape(JSON.stringify(feature)));
                        $featureselect.append($option);
                    }
                });
            };

            $(document).on('change', organism_selector, changeFn);
            $(document).on('change', type_selector, changeFn);
        });

        return node;
    }
};

Here is the portion of html associated with this combobox:
<div id="<%= uuid %>" class="center-block">

      Type
      <input type="text" name="select-type" class="select-type form-control" id="type">
      ▼

      <% _.each(types, function(type, id) { %>
         <option data-type="<%= escape(JSON.stringify(type)) %>"><%= type.name %></option>
      <% }); %>

My question is how do I select the input box with jquery selector so that it returns the correct tag associated with it?

A: I don't see where in your code you are attempting to access parentNode. Either way, jQuery returns jQuery objects. You either need to use jQuery's parent() function
$(selector).parent();

or grab the actual node then call parentNode
$(selector).get(0).parentNode


text:
Q: How do Desktop Only items get into my Mobile world? While digging, I found a long tunnel that went straight down. I fell to the bottom, where it had a sword. I realized this was an enchanted sword shrine. I am pretty sure those are only on desktop, and I checked the Wikipedia. How did this end up on my Mobile World??

A: Unless you got an Enchanted Sword from it (which is not possible), it wasn't an enchanted sword shrine, but just the generic "sword in stone" breakable object.


text:
Q: Fractal dimension of a trajectory In this paper, the author uses fractal dimension to measure the tortuosity of two-dimensional trajectory -
Using Complexity Measures of Movement for Automatically Detecting Movement Types of Unknown GPS Trajectories
Here are some links about fractal dimension:
(1) An introduction to fractals
(2) Fractal dimension
How do I calculate the fractal dimension of below trajectory?


text:
Q: ModuleNotFoundError: No module named 'object_detection' while training objects images I downloaded Tensorflow object_detection API. I was  able to run the tutorial and see the results (Everything went well I followed this video: TensorFlow Object Detection API Tutorial p.1).
When I tried to train my own object I got this error:
ModuleNotFoundError: No module named 'object_detection'

while running this command:
python3 generate_tfrecord.py --csv_input=data/train_labels.csv  --output_path=data/train.record

Note: I ran all these commands but did not work
export PYTHONPATH=$PYTHONPATH:`pwd`:`pwd`/slim

sudo python3 setup.py build

sudo python3 setup.py install

sudo pip install -e .

Info:
I am using Ubuntu 18, Tensorflow 1.8.0


text:
Q: How to correct this text processing programme? import java.util.Scanner;

public class TextProcessing
{
    public static void main(String[] args)
    {
        String sentence, wordToBeTargeted, wordToBeReplaced, output;
        boolean wordToCheck;

        Scanner myInput = new Scanner(System.in);
        sentence = myInput.nextLine();

        do
        {
            wordToCheck = true;
            System.out.println("Please enter the word for replacement:");
            wordToBeTargeted = myInput.nextLine;

            if(sentence.toLowerCase().indexOf(wordToBeTargeted.toLowerCase()) == -1)
            {
                wordToCheck = false;
                System.out.println("This word cannot be found in the sentence!")
            }
            else
            {
                System.out.println("Please enter the word you would like to replace with:");
                wordToBeReplaced = myInput.nextLine();

            }
            }while(wordToCheck = false);
        }
    }
}

Write a file named TextProcessing.java that will replace all occurrences of a word in a string with another word
The expected outcome is like this:

A: I won't write the code out - you should still get something out of the exercise, but will give some direction. The first approach that comes to mind:

*

*Split the first input on ' ' into a list

*Iterate through the list, conditionally changing values based based on two input strings

*As you're iterating you can either output into a new string / stringbuilder, or directly write to console depending on the requirements


text:
Q: Getting error trying to use Moti on React Native (Expo) Render Error |
null is not an object (evaluating 'dispatcher.useContext)
Console Warning | Invalid Hook call
I followed all the instructions do Install Moti.

*

*Install Moti

*Install Reanimated v2

*import 'react-native-reanimated' on App.js

*add plugins: ['react-native-reanimated/plugin'], on Babel

*Plug Reanimated in MainApplication.java

I dont know what I can do.
my code

import React from "react";
import {
    View,
    StyleSheet,
    Text,
    StatusBar,
    TouchableOpacity
} from 'react-native'

import { Feather } from '@expo/vector-icons'
import { MotiView, MotiText } from "moti";

const statusbarHeight = StatusBar.currentHeight ? StatusBar.currentHeight + 22 : 64;

export default function Header({name}){
    return(
        <View style={styles.container}>
            <MotiView
                style={styles.content}
                from = {{
                    translateY: -150,
                    opacity: 1
                }}
                animate = {{
                    translateY: 0,
                    opacity: 1
                }}
                >

                <Text style={styles.username}>{name}</Text>

                <TouchableOpacity activeOpacity={0.9} style={styles.buttonUser}>
                    <Feather name="user" size={27} color="#FFF"/>
                </TouchableOpacity>
            </MotiView>
        </View>
    )

}

const styles = StyleSheet.create({
    container:{
        backgroundColor: '#8000ff',
        paddingTop: statusbarHeight,
        flexDirection: 'row',
        paddingStart: 16,
        paddingEnd: 16,
        paddingBottom: 44,
    },
    content:{
        flex: 1,
        alignItems: 'center',
        flexDirection: 'row',
        justifyContent: 'space-between',
    },
    username:{
        fontSize: 18,
        color: '#FFF',
        fontWeight: 'bold'
    },
    buttonUser:{
        width: 44,
        height: 44,
        backgroundColor: 'rgba(255,255,255,0.5)',
        justifyContent: 'center',
        alignItems: 'center',
        borderRadius: 44/2,

    }
})

A: This issue can happen if you have multiple versions of React installed.
If you're using Yarn:
Can you try running yarn why react? If you see multiple versions, I recommend trying a yarn resolution in your package.json:
{
  "resolutions": {
    "react": "your-version-here"
  }
}

Then run yarn install --force and restart your app with expo start -c.
If you're using npm
Can you try running npm install --legacy-peer-deps?


text:
Q: How can I use Apache's mod_rewrite to redirect requests that do not go to the home/index page? I have two websites. One is a Django App. The other is just a static site.
If someone were to submit https://example.com/more_info
I need to redirect them to https://example.co/more_info
Note the .com vs .co
But if they just request https://example.com then I serve them the index page.
I've unsuccessfully tried the code below in my .htaccess file:
RewriteEngine On
RewriteCond %{REQUEST_URI} !^(|/)$
Rewriterule (.*) https://example.com/$1

A: I think you want to redirect every page to https://example.co other than the home/index page. You can do this by:
RewriteEngine On
RewriteRule (.+) https://example.co/$1 [R=301,L,NE]


text:
Q: Flask RuntimeError: Working outside of application context when using multithreading with g module I have an API endpoint which spawns two independent threads which use the module g to access an object and perform some operations. I'm writing my endpoint in a blueprint object and using before_request to generate an instance of a class which I wish to send to the thread. This is how my code looks -
from flask import g
from multithreading import Thread

@bp.before_request
def bef_request():
    g.obj = someAPI()

@bp.route("/")
def endpoint():
   thread_a = Thread(target=funcA, args=(g.obj, some_data,))
   thread_a.start()

   thread_b = Thread(target=funcB, args=(g.obj, some_data,))
   thread_b.start()

   thread_a.join()
   thread_b.join()

but I get the following error -
return self.__local()  # type: ignore
  File "/Users/user/Library/lib/python3.9/site-packages/flask/globals.py", line 47, in _find_app
    raise RuntimeError(_app_ctx_err_msg)
RuntimeError: Working outside of application context.

This typically means that you attempted to use functionality that needed
to interface with the current application object in some way. To solve
this, set up an application context with app.app_context().  See the
documentation for more information.

I've tried the solutions available online but it doesn't work.
Please help.


text:
Q: Change Text Color of Selected Option in a Select Box I have a select box. The options have been styled with different colors via a CSS file that has been referenced. I want to be able to select an option and change the text color of the closed select box to the color of the chosen option.
<select id="mySelect" class="yellowText">
    <option class="greenText" value="apple" >Apple</option>
    <option class="redText" value="banana" >Banana</option>
    <option class="blueText" value="grape" >Grape</option>
</select>

So if I select Banana, the text should change from yellow to red.
I have tried:
onchange="this.style.color = this.options[this.selectedIndex].style.color;"

But this only works if I define my styles within the option tags inside html document.
I have also tried JavaScript:
function setSelectColor(thisElement){
    var thisElem = document.getElementById(thisElement);
    var thisOption = thisElem.options[thisElem.selectedIndex];
    var newColor = getStyle(thisOption,"color");
    alert("New Color: "+ newColor);
}

But this always returns the color: white. The getStyle function works everywhere else I use it so I do not believe that's the problem.
I got getStyle from this very website:
function getStyle(oElm, strCssRule){
    var strValue = "";
    if(document.defaultView && document.defaultView.getComputedStyle){
        strValue = document.defaultView.getComputedStyle(oElm, "").getPropertyValue(strCssRule);
    }
    else if(oElm.currentStyle){
        strCssRule = strCssRule.replace(/\-(\w)/g, function (strMatch, p1){
            return p1.toUpperCase();
        });
        strValue = oElm.currentStyle[strCssRule];
    }
    return strValue;
}

How can I solve this with JavaScript?

A: You could do it like this.
jsFiddle
JS
var select = document.getElementById('mySelect');
select.onchange = function () {
    select.className = this.options[this.selectedIndex].className;
}

CSS
.redText {
    background-color:#F00;
}
.greenText {
    background-color:#0F0;
}
.blueText {
    background-color:#00F;
}

You could use option { background-color: #FFF; } if you want the list to be white.
HTML
<select id="mySelect" class="greenText">
    <option class="greenText" value="apple" >Apple</option>
    <option class="redText"   value="banana" >Banana</option>
    <option class="blueText" value="grape" >Grape</option>
</select>

Since this is a select it doesn't really make sense to use .yellowText as none selected if that's what you were getting at as something must be selected.

A: Try this:

.greenText{ background-color:green; }

.blueText{ background-color:blue; }

.redText{ background-color:red; }
<select
    onchange="this.className=this.options[this.selectedIndex].className"
    class="greenText">
     <option class="greenText" value="apple" >Apple</option>
    <option class="redText"   value="banana" >Banana</option>
    <option class="blueText" value="grape" >Grape</option>
</select>

A: JQuery Code:
$('#mySelect').change(function () {
    $('#mySelect').css("background", $("select option:selected").css("background-color"));
});

This will replace the select's background-color with selected option's background-color.
Here is an example fiddle.

A: ONE COLOR CASE - CSS only
Just to register my experience, where I wanted to set only the color of the selected option to a specific one.
I first tried to set by css only the color of the selected option with no success.
Then, after trying some combinations, this has worked for me with SCSS:
select {
      color: white; // color of the selected option

      option {
        color: black; // color of all the other options
      }
 }

Take a look at a working example with only CSS:

select {
  color: yellow; // color of the selected option
 }

select option {
  color: black; // color of all the other options
}
<select id="mySelect">
    <option value="apple" >Apple</option>
    <option value="banana" >Banana</option>
    <option value="grape" >Grape</option>
</select>

For different colors, depending on the selected option, you'll have to deal with js.

A: CSS
select{
  color:red;
 }

HTML
<select id="sel" onclick="document.getElementById('sel').style.color='green';">
 <option>Select Your Option</option>
 <option value="">INDIA</option>
 <option value="">USA</option>
</select>

The above code will change the colour of text on click of the select box.
and if you want every option different colour, give separate class or id to all options.

A: <html>
  <style>
.selectBox{
 color:White;
}
.optionBox{
  color:black;
}

</style>
<body>
<select class = "selectBox">
  <option class = "optionBox">One</option>
  <option class = "optionBox">Two</option>
  <option class = "optionBox">Three</option>
</select>


text:
Q: Scala SetBuffer I am trying to update my project from Scala 2.12 to Scala 2.13. I see that the Scala team has done a lot of changes on the collection side.
I have a SetBuffer that looks like this in Scala 2.12
object SetBuffer extends MutableSetFactory[SetBuffer] {
  override def empty[Elem] = new SetBuffer[Elem](Set.empty)

  def apply[Elem](initialSet: Iterable[Elem]): SetBuffer[Elem] =
    new SetBuffer[Elem](initialSet.toSet)

  override def newBuilder[Elem] = new SetBufferBuilder[Elem]()

  class SetBufferBuilder[Elem] extends mutable.GrowingBuilder[Elem, SetBuffer[Elem]](SetBuffer.empty) {
    override def result(): SetBuffer[Elem] =
      new SetBuffer[Elem](elems.getDelta)
  }
}

class SetBuffer[ElemType](initialSet: Set[ElemType])
  extends mutable.HashSet[ElemType]
    with mutable.SetLike[ElemType, SetBuffer[ElemType]]
    with GenericSetTemplate[ElemType, SetBuffer] {

  initialSet.map(+=)

  override def companion: SetBuffer.type = SetBuffer

  def getDeltaBuffer: SetBuffer[ElemType] = {
    SetBuffer[ElemType]((this -- initialSet).toSeq:_*)
  }

  def getDelta: immutable.Set[ElemType] = {
    val deltaElements = (this -- initialSet).toSeq
    immutable.Set[ElemType](deltaElements: _*)
  }

  def ++(that: Iterable[ElemType]): SetBuffer[ElemType] =
    SetBuffer(toIterable ++ that)

  def append(that: Iterable[ElemType]): Unit = this ++= that

  def ++=(that: Iterable[ElemType]): Unit = that.map(+=)
}

Scala 2.13 removed mutable.SetLike[ElemType, SetBuffer[ElemType]] and GenericSetTemplate[ElemType, SetBuffer] and made mutable.HashSet final. Is there a way to rewrite the code in the class SetBuffer[ElemType](initialSet: Set[ElemType]) so it will behave the same and have the same performances?

A: Two ideas come to my mind.
First - you can try to use https://www.scala-lang.org/api/current/scala/collection/mutable/LinkedHashSet.html that seems to not be final. I am not sure if it's possible and I didn't search for performance characteristics.
Second, you go for composition over inheritance. Wrap the instance of HashSet and delegate all calls to it. You would have to implement quite a few interfaces to achieve the same behaviour though.


text:
Q: Is there any kind of authoritative guide to Apple's Volume Purchase Program, Device Enrollment Program, and Mobile Device Management? I'm fairly new to the whole world of Apple and macOS. As I'm currently writing my thesis about the possible enrollment of macOS devices via Device Enrollment Program (DEP) (in connecting with some other stuff), I searched the Web, books and the Apple's Developer documentation, but I have not found a reliable guide on how to use Volume Purchase Program (VPP) and DEP (or at least a "quotable" description), only the handbook for ABM (which is pretty good, but does not answer all my questions).
Am I just blind or are there some "hidden" gems that i seem to overlook? Maybe there is a guide in Apple Business Manager (ABM) directly, to which i don't have access - yet - ?

A: I'm sure if you'd searched the Web just with the keywords that you have listed, you'd get a lot of official resources right on the first page of the search results.
But nonetheless, here are some links to get you started:

*

*Apple Deployment Programs - Volume Purchase Program Guide

*Apple Deployment Programs - Device Enrollment Program Guide

*Apple Deployment Reference - Mac

*Apple Deployment Reference - iPhone and iPad

*Mobile Device Management Settings

*Apple Deployment Programs

*Upgrade from Apple Deployment Programs

*Volume Purchase Program

*Apple Business Manager User Guide

*Business Support

*Getting Started Guide - Apple Business Manager

*Upgrade your organization to Apple Business Manager


text:
Q: Add WP permalink to PHP function The code below adds an image into my wordpress RSS feed. I am wanting to make it so that the image is automatically hyperlinked back to the corresponding post. The code is in my theme's functions.php
    function wcs_post_thumbnails_in_feeds( $content ) {
    global $post;
    if( has_post_thumbnail( $post->ID ) ) {
        $content = get_the_post_thumbnail( $post->ID ) . '' . $content . '';
    }
    return $content;
}
add_filter( 'the_excerpt_rss', 'wcs_post_thumbnails_in_feeds' );
add_filter( 'the_content_feed', 'wcs_post_thumbnails_in_feeds' );
Can I change this so that the post_thumbnail is automatically wrapped with a link to the post?

How can I wrap the get_the_post_thumbnail( $post->ID ) part of the code with a link? Thanks

A: You can use the get_permalink function and pass it the post ID.
function wcs_post_thumbnails_in_feeds( $content ) {
        global $post;
        if( has_post_thumbnail( $post->ID ) ) {
            $content = 'ID ) . '">' . get_the_post_thumbnail( $post->ID ) . '' . $content . '';
        }
        return $content;
    }


text:
Q: show the txt content in a realtime manner in html( my web server doesn't support php) I have a file named log.txt, it is always being written new content by another process ( here is a telnet session by pexpect ), I want to display the whole contents in pages, and when new contents comes in, the page content also show the new contents too, it's a little like tail -f, but a little different, because  I want to show the whole content  besides the new contents just came in

A: The simplest (and probably worst) way is to download whole each time using ajax request. One of possible implementations using jQuery would be for instance:
var logDownloader = {

    fileContents:"",

    init: function () {
        $.ajax({
            url: "./logfile.txt",
            async: false,
            success: function (data){
                pageExecute.fileContents = data;
            }
        });
    }
};

Another way would be calling php script which would return only the "fresh" part of text from your log file. For reading file line by line you can use for example:
if ($file = fopen("file.txt", "r")) {
    while(!feof($file)) {
        $line = fgets($file);
        //send your line
    }
    fclose($file);
}

You should also send the number of last sent line in order not to send whole file each time.
On the other hand if you're not limited to PHP I would recommend to use nodeJS and socket.io or some python script. In my opinion it would be more efficient.


text:
Q: Can the code written in visual studio for mobile development could be executed in xcode MAC? I'm planning to develop a mobile application using Xamarin for iOS and android in visual studio 2015. Could i compile and run the code written in visual studio, in Xcode MAC.

A: The same code can be viewed and debugged on Mac with Xamarin Studio, not Xcode.
http://developer.xamarin.com/guides/ios/
http://developer.xamarin.com/guides/android/


text:
Q: How to make SDK my code safe from other developers when i give them AAR file in Android? I am creating one SDK for android which include the Activity, Services and Broadcast receivers.
Problem is when i generate the AAR file from my project and import it to other sample project my All the Activity, Services and Receivers names are visible from Manifest of my AAR file.
I don't want to expose any of my class name to users of My AAR file, Please provide proper way to hide my confidential code and classes.

A: Remember one thing "Everything is hackable" and java classes are decompilabel.
You can use the Proguard to Obfuscate your code
Have a look
https://developer.android.com/studio/build/shrink-code
With Proguard, it will also shrink your code and reduces the size of you AAR file
and change the names of the classes, then it is hard to recognize the functionality of your lib file.
Learn more about Obfuscation: https://en.wikipedia.org/wiki/Obfuscation_(software)


text: Q: Where do you store the result of a MIPS program? I've written a code generator for the 32-bit MIPS architecture. To test it, I've written an algorithm that returns the Nth number in the Fibonacci sequence. Does it matter where the result is returned to?


text:
Q: css less font-size addition or subtraction Using LESS is there a way I can set a base font-size and then reference it later and output it say 1em smaller? Ex:
@font-size: 3.025em;

And then in a media query or something:
@media only screen and (max-width: 959px) {
    .box {
        font-size: @font-size - 1em;
    }
}

I tried googling this but wasn't coming up with anything.

A: Yes, you can. You must set the baseline font size as LESS won't be able to infer what the default is:
@font-size: 3.025em;

And then in a media query:
@media only screen and (max-width: 959px) {
    .box {
        font-size: @font-size - 1em;
    }
}

;)


text:
Q: How to get the Month from date string in sql server As stated in the Title of the question , i have different days in different accounts, How to get the date part of these

A: Just change the date formats below depending on your date format:
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
try {
    Date date = (Date)formatter.parse(str);
    DateFormat df = new SimpleDateFormat("MM"); // you can use 'dd' for date
    return df.format(date);
} catch (ParseException e) {
    e.printStackTrace();
    return null;
}


text:
Q: how to make a selection from multiple fields? help please make a selection from the fields "nickname" and "family".
in the database have the following table. I do sample the field "nickname" as follows:
views.py:
from django.db.models import Q

@login_required
def friends_search(request):
    search_result = None

    if request.method == 'POST':
        if request.POST.get('fld_name'):
            try:
                fld_name = request.POST.get('fld_name')
                search_result = UserProfile.objects.filter(Q(nickname__icontains=fld_name))
                if not search_result:
                    search_result = 'По вашему запросу ничего не найдено.'
            except Exception as exc:
                search_result = 'В данный момент доступ к базе данных невозможен. Попробуйте повторить ваш запрос позже.'

    t = loader.get_template('friends_search.html')
    c = RequestContext(request, {
        'search_result': search_result,
    }, [custom_proc])
    return HttpResponse(t.render(c))

the problem is that I need to take a sample at the same time in the fields "nickname", "family". following method does not work:
search_result = UserProfile.objects.filter(Q(nickname__icontains=fld_name), Q(family__icontains=fld_name))

A: Revise Complex lookups with Q objects ,
You should use the OR operator | .
It can look like this:
from django.db.models import Q

@login_required
def friends_search(request):
    search_result = None

    if request.method == 'POST':
        if request.POST.get('fld_name'):
            try:
                fld_name = request.POST.get('fld_name')
                q = Q(nickname__icontains=fld_name) | Q(family__icontains=fld_name)
                search_result = UserProfile.objects.filter(q)
                if not search_result:
                    search_result = 'По вашему запросу ничего не найдено.'
            except Exception as exc:
                search_result = 'В данный момент доступ к базе данных невозможен. Попробуйте повторить ваш запрос позже.'

    t = loader.get_template('friends_search.html')
    c = RequestContext(request, {
    'search_result': search_result,
}, [custom_proc])
    return HttpResponse(t.render(c))

A: If you want to do an AND query, just append filters, like this:
UserProfile.objects.filter(Q(nickname__icontains=fld_name)).filter(Q(family__icontains=fld_name))