text:
Q: slab classes and memory allocation in memcached I recently started going through memcached source code and i came across this structure. Based on my understanding, there are approximately 64 slabs and and each slab represents a unique chunk size. If we took the first slab class ( size 80 , say ) then the pages which are belongs to this slab will have it's memory broken into 80 bytes.
typedef struct {
  unsigned int size;      // sizes of items
  unsigned int perslab;   // how many items per slab

  void *slots;            // list of item ptrs
  unsigned int sl_curr;   // total free items in list

  unsigned int slabs;     // how many slabs were allocated for this class

  void **slab_list;       // array of slab pointers
  unsigned int list_size; // size of prev array

  size_t requested;       // The number of requested bytes

} slabclass_t;

I do not understand this line,
unsigned int slabs;     // how many slabs were allocated for this class

What does he mean by how many slabs were allocated for a slab class? Every slab class must be unique right? why will there be multiple slabs within one slab class? Am i missing something?

A: An allocated slab of class slabclass_t is basically a chunk of memory that hosts perslab number of items of size size. If all the items in that slab are used, Memcached allocates another chunk of memory and adds it to the slab_list. These chunks of memory are also referred to as pages or slab_pages.
So if you start a new Memcached server and store one item for a slab class (say size=80), then for this slab class slabs=1. Once you store perslab+1 items in that class you will have slabs=2 and the slab_list will contain 2 items.
Basically, you have a slab_list and slabs its length whereas list_size is its capacity.
I derived most of this from slabs.c so correct me if I got something wrong.


text:
Q: Range start unpicked I have a range selecting from five values in an html page. I want the range to start "unpicked", meaning that the user will have to click on it, and not start with a default value already selected.
I'm using javascript, AngularJS and CSS. I've tried manipulating the default value and even the css, but I can't find a good solution.
I tried adding another value and using it as a default, but then I can't hide it and is overall not a good solution to my problem.
This is my current range:

    <input id="rangeInput" type="range" min="1" max="5" steps="1" dir="rtl" ng-model="myIdealRate" ng-change="changeSelect()">

...

...

...

...

...

Now It automatically starts with the third value selected, but I want it to start with non selected.

redpajama_set_name: RedPajamaStackExchange


text:
Q: cpp file with a single global variable is ignored I'm trying to initialize a global map
std::map<long, std::string> Global_ID_Mapper;

with a number of "init" classes like:
struct AGlobalMapperInitializer
{
    AGlobalMapperInitializer()
    {
        Global_ID_Mapper.insert( std::make_pair(1, "Value1") );
        Global_ID_Mapper.insert( std::make_pair(2, "Value2") );
    }
};

I want to fill the map automatically during application start. So in one of my cpp files, I just define a global variable of that "init" class.
// AGlobalMapperInitializer.cpp

AGlobalMapperInitializer AGlobalMapperInitializer_Value;

The Mapper filling is a side effect of the AGlobalMapperInitializer_Value creation.
The problem is that the cpp is obviously ignored by linker if the cpp doesn't contain anything except this global variable. When I put some useful other code into the cpp (or define the global initializer in some non-empty cpp), the constructor is invoked and the global mapper is filled. But if the cpp contains only the global that isn't referenced in no other file, the cpp is compiled, the obj file contains the variable, but the linker doesn't mention it during the link and it is missed in the exe.
How can I insist on linking the cpp into exe?
Is there some pragma or dummy code to put into the cpp to get it non-ignored?
I use the Visual Studio 2012.

A: C++ does not require initialisation of a global variable x to take place if no function or variable from the same file (actually translation unit) as x is ever referenced.
See C++11 [basic.start.init]§4:

It is implementation-defined whether the dynamic initialization of a non-local variable with static storage duration is done before the first statement of main. If the initialization is deferred to some point in time after the first statement of main, it shall occur before the first odr-use (3.2) of any function or variable defined in the same translation unit as the variable to be initialized.

So to force the variable initialisation, you have to put it into a file whose other contents you actually use, or directly use the variable somewhere.

A: The linker doesn't include the variable and it's initializer when it is not referenced. You can create a reference to this variable inside your code:
int main()
{
    printf("", &AGlobalMapperInitializer_Value));
}

If you want to avoid this contamination of the source code you cause the same effect with the /INCLUDE argument of the linker. You have to add the decorated name that you can take from the .map file when you have tried the hack above.
The VS2010 offers this options as Force Symbol Reference in the project properties: Configuration Properies -> Linker -> Input. I hope it's the same for VS2012.

A: Thanks for both Angew and harper that helped to find the solution.
There are 2 possible solutions:

*

*The portable one (but not good because of its performance).
The initializer instance can be defined not in the dedicated cpp file, but in the h, using the word static.
// AGlobalMapperInitializer.h
// It wasn't mentioned before that this h file is included in many cpp files
struct AGlobalMapperInitializer
{
    AGlobalMapperInitializer()
    {
        if( !Global_ID_Mapper.insert( std::make_pair(1, "Value1") ).second )
            return;
        Global_ID_Mapper.insert( std::make_pair(2, "Value2") );
    }
};

static AGlobalMapperInitializer AGlobalMapperInitializer_Value;

Since the variable is static, the AGlobalMapperInitializer_Value is created separately in all the cpp files that include the h file. Each of these variables is trying to add values to the global mapper. Definitely, only one of them succeed. The performance problem is partially resolved by checking result of the first insert. If the first value was already inserted - no need to try other values.
Note: It is assumed that all these instances will be created within the same thread, otherwise the Global Mapper should implement synchronization of the insert calls.

*The compiler-specific solution (Visual Studio).
The linker can be forced to keep class by adding #pragma comment (linker, "/include:<decorated name>"). The decorated name can be a class constructor or any other function. The issue is that specifying decorated name hard-code isn't good nor convenient. The decoration method can change with compiler upgrade. So, here the __FUNCDNAME__ can be used.
struct AGlobalMapperInitializer
{
    AGlobalMapperInitializer()
    {
        // Make sure the class will not be threw away by linker
        #pragma comment (linker, "/include:"__FUNCDNAME__)

        Global_ID_Mapper.insert( std::make_pair(1, "Value1") );
        Global_ID_Mapper.insert( std::make_pair(2, "Value2") );
    }
};

Fortunately, the #pragma can be specified inside the class constructor.


text:
Q: How to give VM parameter to JBoss from command line? I am configuring JaCoCo code coverage tool to work with JBoss. This includes adding the JaCoCo agent as a VM parameter to JBoss. I have got it to work by adding the parameter to JAVA_OPTS straight in the JBoss run.config scripts, but because this needs to be quite dynamic, I would need to give the VM parameter at command line (executed by Jenkins). How do I do this? I know system properties can be given using the "D" before the key.
Also, is it possible to add the agent to the run.config file, and then pass a custom property to it? So I would add this to the run.config file:
JAVA_OPTS="$JAVA_OPTS -javaagent:/home/installations/jacoco/jacocoagent.jar=destfile=$path/jacoco.exec"

And then I would start JBoss like this:
./run.sh -Dpath=/home/workspace/jacoco

Does something like this work?

A: Since run.sh itself is a shell script file, which means it accepts parameters you pass in. Or, you can write another shell script to wrap up the run.sh, then you can handle the parameters you want in this outer script file and don't need to taint the original run.sh, which offers more portability.


text:
Q: yfR:Error in download.Error in `vec_slice()`: ! `x` must be a vector, not NULL I am sure I have installed the latest packages include "quantomd":(devtools::install_github("joshuaulrich/quantmod", ref = "358-getsymbols-new.session"))
But still fail to use yfR.I realized that the problem may be in the "quantmod" . When I use the functions of "quantmod" to get data, it will also report an error.
About fyR:
my_ticker <- 'FB'
first_date <- Sys.Date() - 30
last_date <- Sys.Date()
df_yf <- yf_get(tickers = my_ticker, first_date = first_date, last_date = last_date)

── Running yfR for 1 stocks | 2022-04-06 --> 2022-05-06 (30 days) ──
ℹ Downloading data for benchmark ticker ^GSPC
ℹ (1/1) Fetching data for FB
!       - not cached
✖       - error in download..
ℹ Binding price data
Error in vec_slice():
! x must be a vector, not NULL.
Run rlang::last_error() to see where the error occurred.
Warning messages:
1: Unknown or uninitialised column: ticker.
2: Unknown or uninitialised column: threshold_decision.
3: Unknown or uninitialised column: ticker.
4: Unknown or uninitialised column: price_adjusted.
####################################################

rlang::last_error()
<error/vctrs_error_scalar_type>
Error in vec_slice():
! x must be a vector, not NULL.

Backtrace:

*

*yfR::yf_get(tickers = my_ticker, first_date = first_date, last_date = last_date)

*yfR:::calc_ret(...)

*dplyr::lag(P)

*vctrs::vec_slice(inputs$x, seq_len(xlen - n))
Run rlang::last_trace() to see the full context.
##############################################

rlang::last_trace()
<error/vctrs_error_scalar_type>
Error in vec_slice():
! x must be a vector, not NULL.

Backtrace:
▆

*

*├─yfR::yf_get(tickers = my_ticker, first_date = first_date, last_date = last_date)

*│ └─yfR:::calc_ret(...)

*│   └─dplyr::lag(P)

*│     ├─vctrs::vec_c(...)

*│     └─vctrs::vec_slice(inputs$x, seq_len(xlen - n))

*└─vctrs:::stop_scalar_type(<fn>(NULL), "x", <env>)

*└─vctrs:::stop_vctrs(...)

*
└─rlang::abort(message, class = c(class, "vctrs_error"), ..., call = vctrs_error_call(call))

About quantmod:

getSymbols("AAPL", src = "yahoo")    # from yahoo financ
Warning: AAPL download failed; trying again.
Error in getSymbols.yahoo(Symbols = "AAPL", env = , verbose = FALSE,  :
Unable to import "AAPL".
AAPL download failed after two attempts. Error message:
Timeout was reached: [query2.finance.yahoo.com] Operation timed out after 10005 milliseconds with 0 out of 0 bytes received

getSymbols("AAPL", src = "yahoo")    # from yahoo financ
Warning: AAPL download failed; trying again.
Error in getSymbols.yahoo(Symbols = "AAPL", env = , verbose = FALSE,  :
Unable to import "AAPL".
AAPL download failed after two attempts. Error message:
HTTP error 403.


text:
Q: How to plot two equidistant moving points? Imagine a surface which has got 2 points which are moving over the surface (resulting into various lines and curves) while adhering to the following conditions.

*

*These two points are always and always at a constant C distance from each other.

*Each point has it's own velocity and direction vector. Of course both these parameters will be restricted based on condition 1.
Ex. if point 1 has 0 velocity and point 2 is moving it will result into a circle like shape with point one being it's center.

I am unable to express these conditions in programming constructs. Can someone help me with that?
I am using OpenGL but even a pseudo code will do for me.

A: vec3 center;

while(1):
    vec3 centerDirection = ...
    center += centerDirection
    float angle = ...
    vec3 dir(cos(angle), 0, sin(angle))
    vec3 p1 = center + (C/2) * dir
    vec3 p2 = center - (C/2) * dir
    draw p1
    draw p2

This is a solution where you move the center of a circle and make sure p1 and p2 are two diametrically opposed points
Another solution :
while 1:
    p1 += random
    p2 += random
    delta = p1-p2
    delta.normalize()
    p2 = p1 + C * delta

i.e you restrain p2, not both points.

A: In openGL I achieved is as below
PlotTwoPoints(-SPAN,0,+SPAN,0); //two points on x axis
Then I rotated the co-ordinate system and kept on drawing two points at above two locations.
Simple!


text:
Q: NSFetchedResultsController initWithFetchRequest throws EXE-BAD-ACCESS exception I have an NSFetchedResultsController inside a subclass of UITableViewController inside a UINavigationController.  When I run the app, everything works perfectly the first three times I access the view (going to it, then clicking 'Back', then going to it again), but on the fourth (always) it crashes with the following:
-[NSEntityDescription subentitiesByName]: message sent to deallocated instance 0x8b09c80
Any help would be much appreciated.

Here is my getter for the results controller:
- (NSFetchedResultsController*)eventsResultsController {

  if (eventsResultsController_ == nil) {

    NSFetchRequest *aFetchRequest = [[PADataContext sharedInstance] makeGetAllFetchRequestForEntity:@"PAEvent" sortedBy:@"when" ascending:NO];

    // NOTE: crashes on this next line
    NSFetchedResultsController *aFetchedResultsContorller = [[NSFetchedResultsController alloc] initWithFetchRequest:aFetchRequest managedObjectContext:[[PADataContext sharedInstance] managedObjectContext] sectionNameKeyPath:@"whenMonth" cacheName:@"AllEvent"];

    self.eventsResultsController = aFetchedResultsContorller;

    [aFetchedResultsContorller release];

  }

  return eventsResultsController_;

}

This is the code I use to create my NSFetchRequest:
- (NSFetchRequest*)makeGetAllFetchRequestForEntity:(NSString*)entityName sortedBy:(NSString*)sortString ascending:(BOOL)ascending {

  NSFetchRequest *fetchRequest = [[[NSFetchRequest alloc] init] autorelease];
  NSEntityDescription *entity = [NSEntityDescription entityForName:entityName inManagedObjectContext:[self managedObjectContext]];
  [fetchRequest setEntity:entity];

  if (sortString != nil) {

    // add sorting information
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:sortString ascending:ascending];
    NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];

    [fetchRequest setSortDescriptors:sortDescriptors];

    [sortDescriptors release];
    [sortDescriptor release];

  }

  [entity release];
  return fetchRequest;

}

The context object is created once and held throughout the lifetime of the app in a singleton.
I have checked the ensure the eventsResultsController_ gets released when the view controller gets dealloced.
In the stack, I'm told it crashed in the initWithFetchRequest:managedObjectContext:sectionNameKeyPath:cacheName method:
#0  0x00f04057 in ___forwarding___
#1  0x00f03f22 in __forwarding_prep_0___
#2  0x00da1b4d in -[NSFetchedResultsController initWithFetchRequest:managedObjectContext:sectionNameKeyPath:cacheName:]
#3  0x00008c94 in -[PAHistoryListTableView eventsResultsController] at PAHistoryListTableView.m:125
#4  0x00008a5b in -[PAHistoryListTableView loadData] at PAHistoryListTableView.m:52
#5  0x00008a2a in -[PAHistoryListTableView viewDidLoad] at PAHistoryListTableView.m:43
...

A: You created your entity with a non-retaining call:
NSEntityDescription *entity = [NSEntityDescription entityForName:entityName inManagedObjectContext:[self managedObjectContext]];

And then you released it:
[entity release];

Take out the release. This is trivial to find when you focus on the fact that it was the NSEntityDescription that was over-released. You only use that in one place, so it's easy to find the mistake.


text:
Q: Javascript function in asp.net Ok, having an issue withe the return value of a function always returning "undefined"
Heres my code:
//called here:
var res = comms(GENSET_SN);

//the function
function comms(genserial) {
     var Result;
     //Webservice called here
     MyServices.getCommsState(genserial, "S1", OnComplete1);

     function OnComplete1(args) {
          var Res = eval("(" + args + ")");

          if (Res == 1) {
               Result = 1;
          } else {
                Result = 0;
          }
      }
      return Result;
}

please help!!

A: Simple. You are not defining the value of Result before the function is returned. I assum getCommsState is an async function. If you need this "wrapper" function (comms) I would suggest adding a callback parameter for this too.

A: I'm guessing MyServices.getCommsState(genserial, "S1", OnComplete1); is an ajax request?
If so, the value of Result will be returned before it is actually set in the OnComplete1 callback, hence undefined.
You will need to pass in a callback function containing the code that will use the Result value.
You can change the code to do this instead, note that you pass in the function to comms and then call it in OnComplete1:
comms(GENSET_SN, function(res) {
    // do whatever you need with res here!
});

//the function
function comms(genserial, callback) {
     //Webservice called here
     MyServices.getCommsState(genserial, "S1", function(args) {
         var Res = eval("(" + args + ")"); // I would change this aswell, dont use eval!
         callback(Res == 1 ? 1 : 0);
     });
}

A: JavaScript is Asynchronous
                function OnComplete1(args) {

                    var Res = eval("(" + args + ")");

                    if (Res == 1) {
                        Result = 1;
                    }
                    else {
                        Result = 0;
                    }
                }
                return Result;

needs to be
              function OnComplete1(args) {

                    var Res = eval("(" + args + ")");

                    if (Res == 1) {
                        Result = 1;
                    }
                    else {
                        Result = 0;
                    }

                    // RIGHT NOW - do something with result
               }

Notes:
1 ) eval just isn't good. Modern browsers have JSON already defined or json2.js is widely available
2 ) You might have caught this error if you formatted you code better:
function OnComplete1(args) {
    var Res = JSON.parse(args);

    if (Res == 1) {
        Result = 1;
    }
    else {
        Result = 0;
    }
}
return Result;


text:
Q: How to use Channel instead of Group when using django channels? I 'm trying to make use of the channels project (http://channels.readthedocs.org/en/latest/index.html) on django.
While on the docs there is a good tutorial for building a Group-based websocket application(chat), I couldn't find something related to a simple push mechanism that will be client specific (so no need to use Group)
Let's say I want to build a feed aggregator with various news providers and when a user visits the homepage and waits for all the feeds to get parsed, I want to send him informational messages about which one is being parsed by the server, while he waits.
What I got now is:
consumers.py
from channels import Group, Channel
from .views import sort_articles_by_date
from .soup import ProviderParser
from .models import Provider

# Connected to websocket.connect and websocket.keepalive
def ws_add(message):
    Group("news_providers_loading").add(message.reply_channel)

def ws_message(message):
    providers = Provider.objects.all()

    articles = []
    for provider in providers:
        Group("news_providers_loading").send({'content': str(provider)})
        parser = ProviderParser(provider)
        articles.extend(parser.parse_articles())

     sort_articles_by_date(articles)

 # Connected to websocket.disconnect
 def ws_disconnect(message):
     Group("news_providers_loading").discard(message.reply_channel)

routing.py
channel_routing = {
    "websocket.connect": "news_providers.consumers.ws_add",
    "websocket.keepalive": "news_providers.consumers.ws_add",
    "websocket.receive": "news_providers.consumers.ws_message",
    "websocket.disconnect": "news_providers.consumers.ws_disconnect",
}

Though it works ok, I can't help it but feel that's a bit overkill(?)
Is there a way to just make use of the Channel constructor, instead of Group?
Thanks :)

A: Update:
channels version = 0.9
channels are 0.9 now so some changes are required for the client to receive the message from the server:
class Content:
    def __init__(self, reply_channel):
        self.reply_channel = reply_channel

    def send(self, json):
        self.reply_channel.send({
            'reply_channel': str(self.reply_channel),
            'text': dumps(json)
        })

def ws_message(message):
    content = Content(message.reply_channel)
    content.send({'hello': 'world'})

routing.py stays the same...

channels version < 0.9
Bah, it was a bit tricky but found it.
You have to use the message's reply_channel property.
So this:
Group("news_providers_loading").send({'content': str(provider)})

turns into this:
Channel(message.reply_channel).send({'content': str(provider)})

What I got now is:
from channels import Channel
from .soup import ProviderParser, sort_articles_by_date
from .models import Provider
from django.template.loader import render_to_string
from json import dumps

class Content:
    def __init__(self, reply_channel):
        self.reply_channel = reply_channel

    def send(self, json):
        Channel(self.reply_channel).send({'content': dumps(json)})

def ws_message(message):
    providers = Provider.objects.all()
    content = Content(message.reply_channel)

    content.send({'providers_length': len(providers)})

    articles = []
    for provider in providers:

        content.send({'provider': str(provider)})

        parser = ProviderParser(provider)
        articles.extend(parser.parse_articles())

    sort_articles_by_date(articles)
    html = render_to_string('news_providers/article.html', {'articles': articles})

    content.send({'html': html})

routing.py
channel_routing = {
     "websocket.receive": "news_providers.consumers.ws_message",
}

Seems lighter, though you might want to keep connect, keepalive and disconnect methods (as simple foo methods) -not entirely sure about that-!
# connect, keepalive and disconnect
def ws_foo(message):
    pass

routing.py
channel_routing = {
    "websocket.connect": "news_providers.consumers.ws_foo",
    "websocket.keepalive": "news_providers.consumers.ws_foo",
    "websocket.receive": "news_providers.consumers.ws_message",
    "websocket.disconnect": "news_providers.consumers.ws_foo",
}


text:
Q: Switch GeoJsonSource data in MapBox I want to replace the data behind an existing source. This is trivial in javascript:
map.getSource('trace').setData(data);

See https://docs.mapbox.com/mapbox-gl-js/example/live-update-feature/
That method does not exist in Android. Once I have set a value, I can't replace it (nothing changes if I do):
GeoJsonSource mySource;
mySource.setGeoJson("some json data");

To delete and readd the source, I'd have to remove the layer using the source first: https://github.com/mapbox/mapbox-gl-native/issues/12526
Since I'm getting a fully functioning Style object from the server, removing, recreating and readding the layer/source at the correct position is tedious to say the least.

A: Above code actually works, but to reset my layer I used:
mySource.setGeoJson("");

Setting the source to empty String breaks something. Afterwards the GeoJson can not be set to something meaningful again. So to reset data, I'll have to use the visibility attribute of a layer. Replacing meaningful GeoJson with meaningful GeoJson works just fine.

A: The setGeoJson methods work correctly with any valid Geometry to add data (e.g. Point, MultiPoint).
Then, to clear or initialize the source without "breaking" the layer you can use:
mySource.setGeoJson(FeatureCollection.fromFeatures(new ArrayList<Feature>()));


text:
Q: Unable to create instance variable and class variable of the same name The following code does not compile:
class object {
    class var myVar: String! {
        return "from class"
    }

    var myVar: String! {
        return "from instance"
    }
}

Error:

Invalid redeclaration of 'myVar'

Is this not possible with Swift or am I doing it wrong? This is totally legal in Objective-C (as functions rather than variables).

A: Currently, you can't. If you really want to do this, you can file a Bug Report with Apple.
I would advise against doing this. It's really bad practice, simply because having two different variables named the exact same thing, the only difference being how they are accessed, is a terrible code smell. And it's confusing.
So file a radar if you want to, and then change your variable names. I doubt Apple will "fix" this.


text:
Q: Extension working in layout pages but no longer working anywhere else I've developped a custom Extension with SPFX. This custom extension performs a Search. I deployed it. Everything worked totally fine during 6 months.
And now, out of the blue, my extension is only visible in Site Content, no more in all the other pages.
What i have :
Custom extension created following the documentation. gulp bundle --ship generated temp files that I uploaded to a folder in a Library called CDN (which has been activated and recorded as a CDN origin).
gulp package-solution --ship generated my .appkg that i've uploaded to the appCatalog.
The prompting errors :
Normally, as in my Site Content,  in the dev Console, in the Network tab, I find my postquery, with all my query sent to SP.
Now, in my pages, when I check the dev console,

*

*in the Network tab, my postquery is not appearing.

*In the console tab, I have the following error : "Uncaught (in promise) Error : Failed to create application customizer 'ClientSideExtension.ApplicationCustomizer.XXXXXXXX'.Error information is '***Extension failed to initialize for componentId "XXX".' "
What i tried :
I tried a gulp serve --nobrowser to see if I had any issues. I have none, and my Extension is well displayed.
So, is it a CDN issue ? -even if I don't think so, because the extension works on _layouts pages.
Is it another issue ? How to debug that ?
Please help me, I am really stuck there.
Thanks a lot ! :)

A: Check which master page is applied to the site /_layouts/15/ChangeSiteMasterPage.aspx.
There are 2 master pages as in Site Master Page and System Master Page.
In your case System Master Page may be seattle, hence extension is working there.


text:
Q: Как реализовать менеджер передачи данных по tcp? Добрый день стоит задача, реализовать менеджер который общается с сервером через tcp.
тут проблем нет, есть другая проблема. Менеджер должен работать в другом потоке. И так, есть 2 потока, поток main, и поток будем называть его manager. Поток main создает 2 поток (manager), оо (мэйн) управляет 2 потоком, и получает от него инфу.
У manager'a есть несколько функций:

*

*connect  - соединение с сервером

*call - позвонить абоненту (к примеру)

*waitEvent - получение event'a из очереди у manager'a ( как вы наверно поняли manager получает от сервера ответы и складывает их в очередь)

*hangDown - положить трубку

*close - разорвать соединение с сервером.
примерный алгоритм основного потока (main):

.
manager.connect();
try{
  manager.call();
  EventData eventData;
  while((eventData = manager.waitEvent()) != null) {
    // к примеру логируем eventDat'у
  }
} finally {
  manager.close();
}

Вопрос, точнее крик души, я хз как реализовать manager, имеется ввиду с точки зрения потоков, я могу без проблем отправлять данные на сервер, и получать ответы и складывать их в очередь. Но начитавшись статей, хз как вызывать несколько разных функций из другого потока. Везде что читал писалось, что надо сделать класс унаследованый к примеру от Thread, переопределить в нем функцию run - эта функция и будет крутиться в новом потоке.
А мне надо вызвать несколько функций ( поясню, функции просто выполняют запрос на сервер (отсулку нескольких байт инфы) и все) + постоянно обрабатывать ответы от сервера (получить несколько строк от сервера и складировать их в очередь)...
По чесноку не понятно вообще  как реализовать...
p.s. не прошу куски кода или чего то подобного, прошу лишь помочь с идеей по реализации.
p.p.s задачу надо сдавать еще вчера, а так получилось что не работал в java  ни с потоками ни с tcp.
p.p.p.s Заранее благодарен.
A: Исходим из того, что один поток может выполнять в единицу времени какую-то одну последовательность команд. В вашей терминологии это означает, что один поток может выполнять одновременно только одну функцию.
Т.к. вы хотите выполнять несколько разных функций, то вижу два подхода:

*

*Использовать очередь для разделения логики генерации задачи и выполнения (см. produce-consumer). Все лучае большого кол-ва задач в очереди вы сможете просто увеличить кол-во потребляющих потоков. Правда все еще остается проблема приема сообщений от удаленного сервера. Для этого вам все-равно понадобится как минимум один отдельный поток.

*Использовать множество потоков для выполнения ваших "функций" без использования очередей (напрмер создавать поток на каждую задачу).

Все это довольно легко делается с помощью Executor-фреймворка (см. Java Tutorials: Executors).


text:
Q: .NET / Oracle: How to execute a script with DDL statements programmatically I want to do some programmatical schema manipulation against an oracle database in C#. Therefore, I struggle with some basic issues.
The ddl sql statements are located in a script file. I do not want to use sqlplus.exe, but I want to use OracleCommand out of the ODP.NET assemblies (System.Oracle.DataAccess). Here's an example of my script file:
script.sql:
DROP TABLE ABCDEF;

DROP TABLE GHIJKL;

I want to point out:

*

*The script contains DDL statements (data definition language)

*The script contains empty lines

*The script contains more than one statement
The following code should execute my script:
var content = File.ReadAllText("script.sql");

using (var oracleConnection = new OracleConnection(_connectionString))
{
     oracleConnection.Open();

     using (var command = new OracleCommand(content) { Connection = oracleConnection })
     {
          command.CommandType = CommandType.Text;
          command.ExecuteNonQuery();
     }
}

Executing this code, I do get an oracle error:
Oracle.DataAccess.Client.OracleException: ORA-00911: invalid character
Maybe there is some issue with the formatting of the statements, I think. Any hint is appreciated. Thank you.
---EDIT---
To summarize my needs in a simple way: I search for an approach to execute any sql/ddl script, that is executable by SQL Plus, programmatically with C#.

A: Thanks for the semicolon tip!
My final code to run oracle scripts!
1) It accepts:
- empty lines / comment ( -- ) lines
- Multiline DDl / DML commands ending with ;
2) In case of error it throws an exception with the line number and sql command!
    public async Task ExecuteScript(string _connectionString, string script)
    {
        using (StringReader sr = new StringReader(script))
        {
            var connection = new OracleConnection(_connectionString);
            connection.Open();

            string sqlCommand = "";
            string sqlLine; byte lineNum = 0;

            while ((sqlLine = sr.ReadLine()) != null)
            {
                sqlLine = sqlLine.Trim(); ++lineNum;

                if (sqlLine.Length > 0 && !sqlLine.StartsWith("--"))
                {
                     sqlCommand += (sqlCommand.Length > 0 ? Environment.NewLine : "") + sqlLine;  // Accept multiline SQL

                    if (sqlCommand.EndsWith(";"))
                    {
                        sqlCommand = sqlCommand.Substring(0, sqlCommand.Length - 1);

                        var command = new OracleCommand(sqlCommand, connection);

                        try
                        {
                            await command.ExecuteNonQueryAsync();
                        }
                        catch (OracleException ex)
                        {
                            connection.Close();
                            var e2 = new Exception($"{lineNum} - {sqlCommand} <br/> {ex.Message}");
                            throw e2;
                        }
                    }
                }
            }

            connection.Close();

            return;
        }
    }

A: Simply wrap it inside BEGIN and END and it will work smoothly
var content =string.Format("BEGIN {0} END;", File.ReadAllText("script.sql"));
using (var oracleConnection = new OracleConnection(_connectionString))
{
  oracleConnection.Open();
  using (var command = new OracleCommand(content) { Connection = oracleConnection })
  {
       command.CommandType = CommandType.Text;
       command.ExecuteNonQuery();
  }
}

A: I will try to execute one line at time to see if you have any weird character that blocks the execution. (I am not sure also if you could send all of your commands  together on just one call).
Also you should remove the semicolon at the end of the lines
int lineNum = 0;
try
{
    string[] cmdTexts = File.ReadAllLines("script.sql");

    using (var oracleConnection = new OracleConnection(_connectionString))
    {
         oracleConnection.Open();
         OracleCommand command = new OracleCommand();
         command.Connection = oracleConnection;
         foreach(string cmd in cmdTexts)
         {
              lineNum++;
              if(cmd.Trim().Length > 0)
              {
                  if(cmd.EndsWith(";"))
                      cmd = cmd.Substring(0, cmd.Length - 1);

                  command.CommandText = cmd;
                  command.ExecuteNonQuery();
              }
         }
    }
}
catch(Exception ex)
{
    MessageBox.Show("Exception on line: " + lineNum + " message: " + ex.Message);
}

A: As @Steve said, the semicolons are causing your error. And you can't wrap the entire file into a single execute immediate command, since that can only execute one statement at a time. You will need to parse your file and execute each command on its own, removing the semicolon that delinates commands. Your parsing will have to deal with string literals, as you noted, which in addition to containing semicolons may also contain doubled single quotes ('') within the single quotes (') that begin and end the string literal.


text:
Q: add text to end of array items depending on the item number I've got a dropdown list of numbers which I intend to use to track my miles. I want to add the text 'miles' after the number but if the number is 1, I want to add 'mile'.
unit = miles |
arrayOfArrays = [0, 1, 2, 3, 4, 5, 6, 7, 8]
Here is my script
function showQtyNumbers(el, arrayOfArrays, unit) {
    alert(arrayOfArrays);
    el.innerHTML = '';
    arrayOfArrays.forEach(function(r) {
        var option = document.createElement('option');
        option.setAttribute('value', r);
        option.text = r + ' ' + unit;
        el.appendChild(option);
    });
  }

That gives me the results: 0 miles, 1 miles, 2 miles etc.
I've tried the following but it does not work.
function showQtyNumbers(el, arrayOfArrays, unit) {
    number1 = arrayOfArrays.find(e => e === 1)
    el.innerHTML = '';
    arrayOfArrays.forEach(function(r) {
        var option = document.createElement('option');
        if (r.find(e => e === 1)) {
          r + unit.substring(0, unit.length - 1)
        } else {
           option.text = r + unit;
        };
        option.setAttribute('value', r);

        el.appendChild(option);
    });
  }

I Know arrayOfArrays.find(e => e === 1) finds 1 but I don't know how to do it in forEach.

A: Why don't you pass the value for unit to the function as singular and append an 's' if the value is not 1?  Like this:
 if(r!=1){ option.text = r + unit +"s"; }else{ option.text = r + unit; }


text:
Q: How to change decimal on x-axis (i.e. scatter graph), using VBA? I was searching for how to change decimal, using VBA and I found the excellent answer below.
https://stackoverflow.com/a/32462504/9653254
However, for my graph, it is a scatter graph. So I need to change decimal on x-axis. Above code only change y-axis. Could you let me know how to change deciaml on x-axis?
Thank you in advance.
Dim obj     As Object
For Each obj In ActiveSheet.ChartObjects
   With obj.Chart.Axes(xlValue)
      .TickLabels.NumberFormat = "0.00"
   End With
Next obj

End Sub

A: I found answer, thanks to @Ahmed AU
The code is the below. Thank you for your comment.
Sub xydecimal()

  Dim obj     As Object
For Each obj In ActiveSheet.ChartObjects
   With obj.Chart.Axes(xlValue)
   .TickLabels.NumberFormat = "0.00"
      End With
   With obj.Chart.Axes(xlCategory)
    .TickLabels.NumberFormat = "0.00"
   End With
Next obj

End Sub


text:
Q: disable menu based on value of a preference variable I have a menu item XYZ. I have a preference page MyPref which has a check box and a couple of text fields. When the check box in MyPref is check, I want menu XYZ to be enabled else it should be disabled. Is there a way to achieve this.

A: Yes, the way certainly exist.
1). Create an entry in your IPreferenceStore - just get the class which extends AbstractUIPlugin and do the following:
IPreferenceStore store = IExtendAbstractUIPlugin.getDefault()
      .getPreferenceStore();

then store some value which will reflect your checkbox state:
preferenceStore.setValue("XYZMenuPreference", false); // if disabled

or
preferenceStore.setValue("XYZMenuPreference", true); // if enabled

2). Create a Property Tester extention to your plugin.xml:
<extension point="org.eclipse.core.expressions.propertyTesters">
  <propertyTester
     class="org.xyz.PropertyTester"
     id="org.xyz.PropertyTester"
     type="java.lang.Object"
     namespace="org.xyz"
     properties="XYZmenu">
  </propertyTester>
</extension>

3). When declaring your menu handler in plugin.xml you should add the following:
<handler
 class="your-menu-handler-class"
 commandId="your-command-id">
     <enabledWhen>
     <with variable="selection">
     <test property="org.xyz.XYZmenu" value="true" forcePluginActivation="true"/>
     </with>
     </enabledWhen>
</handler>

4). Now you need a class "org.xyz.PropertyTester" (as defined in plugin.xml) which will extend the org.eclipse.core.expressions.PropertyTester and override method test(<some args>) where he must check the property value:
if (property.equals("XYZmenu"){
   IPreferenceStore store = IExtendAbstractUIPlugin.getDefault()
                    .getPreferenceStore();
   return store.getBoolean("XYZMenuPreference");
}

5). After that add a change listener to your checkbox and use it to re-evaluate a visibility of your menu item:
IEvaluationService service = (IEvaluationService) PlatformUI
   .getWorkbench().getService(IEvaluationService.class);
service.requestEvaluation("org.xyz.XYZmenu");

it will force the method test() from your org.xyz.PropertyTester class to be called and will enable your menu item if preference
"XYZMenuPreference" is set to true.
upd.
namespace - a unique id determining the name space the properties are added to
properties - a comma separated list of properties provided by this property tester

this is from official eclipse tutorial so you can feel free to define any namespace and property name, but the you should use it like in point 5.


text:
Q: Laravel Bulk Send Mail with Notification I read in laravel documentation :
Once the ShouldQueue interface has been added to your notification, you may send the notification like normal. Laravel will detect the ShouldQueue interface on the class and automatically queue the delivery of the notification:
Because of in notification do automatically queue,
if I use in my controller:
public function store(Request $request)
{
  $users = User::all()
  Notification::send($users, new MyFirstNotification());
}

and in my notification:
public function toMail($notifiable)
{
  return  new custome-emailTo("emails.welcome",$notifiable);
}

and in custom-mailTo, (it is a mailable class) :
public function __construct($view2,User $user)
{
  $this->user = $user;
  $this->view = $view2;
}

public function build()
{
  $this->to($this->user->email);
  return $this->view('emails.welcome');
}

for me, it work and send to many users,
but my questions are:
As stated in the documentation of Laravel,
1. Do it really do queuing for send notification?
2. Do I need queue in mailable laravel class for send bulk email?


text:
Q: Generate a string from a dictionary keys (combinations) and assing a boolean value based on values I have a structure similar, to a dictionary of dictionaries:
cont  = {

'perm': { 'r': False, 'rw': True}

'prig':  { 'sq': False, 'rot':False, 'rq':True}

'anon':  {'100': False, '500':True, '99':False; '400':False}

}

From this structure I need to generate a string from keys, and know if the string is False or True based on the values:
Example:
'perm', 'prig', 'anon' will become: 'r,sq,100' or 'rw,sq,100' or 'r,rq,100'.

*

*I need to generate all permutations of the second level keys.

*For each string, I need to associate a Boolean value using 'AND' are True or False.
For the example above:

False,False,False -> False;  True,False,False -> True,False,True, False -> False;

A: You can use itertools.product:
import itertools
cont = {'perm': {'r': False, 'rw': True}, 'prig': {'sq': False, 'rot': False, 'rq': True}, 'anon': {'100': False, '500': True, '99': False, '400': False}}
keys = {a:list(b) for a, b in cont.items()}
p = list(itertools.product(*_keys.values()))
result = [[cont[[a for a, b in keys.items() if c in b][0]][c] for c in i] for i in p]
new_result = [any(i) for i in result]

Output:
#result:
[[False, False, False], [False, False, True], [False, False, False], [False, False, False], [False, False, False], [False, False, True], [False, False, False], [False, False, False], [False, True, False], [False, True, True], [False, True, False], [False, True, False], [True, False, False], [True, False, True], [True, False, False], [True, False, False], [True, False, False], [True, False, True], [True, False, False], [True, False, False], [True, True, False], [True, True, True], [True, True, False], [True, True, False]]
#new_result
[False, True, False, False, False, True, False, False, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True]
#list(map(','.join, prod))
['r,sq,100', 'r,sq,500', 'r,sq,99', 'r,sq,400', 'r,rot,100', 'r,rot,500', 'r,rot,99', 'r,rot,400', 'r,rq,100', 'r,rq,500', 'r,rq,99', 'r,rq,400', 'rw,sq,100', 'rw,sq,500', 'rw,sq,99', 'rw,sq,400', 'rw,rot,100', 'rw,rot,500', 'rw,rot,99', 'rw,rot,400', 'rw,rq,100', 'rw,rq,500', 'rw,rq,99', 'rw,rq,400']

A: Here is my take on the assignment. It has a lot more code than the answer from @Ajax1234 but I hope it is easier to understand/read for some.
import itertools
data = {
    'test': {'a': False, 'b': True},
    'perm': {'r': False, 'rw': True},
    'prig': {'sq': False, 'rq': True},
    'anon': {'100': False, '500': True},
}

# define the order of the keys
key_order = ('perm', 'prig', 'anon', 'test')

# build a list of iterables for the 'product()' function
iterables = [
    sorted(data[k].keys())
    for k in key_order]
print(iterables)

print()
print('{:3s} {:20s} {:30s} {}'.format('i', 'elements', 'value of elements', 'AND'))

for i, elements in enumerate(itertools.product(*iterables)):
    # get the values for all the elements, in the correct order
    values = [
        data[k][sub_k]
        for k, sub_k in zip(key_order, elements)]

    print('{:3d} {:20s} {:30s} {}'.format(
        i+1,
        ','.join(elements),
        str(values),
        all(values)))

This code gives me the following output:
[['r', 'rw'], ['rq', 'sq'], ['100', '500'], ['a', 'b']]

i   elements             value of elements              AND
  1 r,rq,100,a           [False, True, False, False]    False
  2 r,rq,100,b           [False, True, False, True]     False
  3 r,rq,500,a           [False, True, True, False]     False
  4 r,rq,500,b           [False, True, True, True]      False
  5 r,sq,100,a           [False, False, False, False]   False
  6 r,sq,100,b           [False, False, False, True]    False
  7 r,sq,500,a           [False, False, True, False]    False
  8 r,sq,500,b           [False, False, True, True]     False
  9 rw,rq,100,a          [True, True, False, False]     False
 10 rw,rq,100,b          [True, True, False, True]      False
 11 rw,rq,500,a          [True, True, True, False]      False
 12 rw,rq,500,b          [True, True, True, True]       True
 13 rw,sq,100,a          [True, False, False, False]    False
 14 rw,sq,100,b          [True, False, False, True]     False
 15 rw,sq,500,a          [True, False, True, False]     False
 16 rw,sq,500,b          [True, False, True, True]      False


text:
Q: Subroutine argument not passed correctly from Python to Fortran I am using f2py to compile a numerical module for use by a Python script.  I have reduced my code to the minimal example below:
fd.f:
module fd
  ! Double precision real kind
  integer, parameter :: dp = selected_real_kind(15)

contains

subroutine lprsmf(th)
  implicit none
  real(dp) th
  write(*,*) 'th - fd',th
end subroutine lprsmf

end module fd

itimes.f:
subroutine itimes(th)
  use fd
  implicit none
  real(dp) th

  write(*,*) 'th - it',th
  call lprsmf(th)
end subroutine itimes

reprun.py:
import it

th = 200
it.itimes(th)

The commands used to compile and run are as follows (Note that I am using cmd under Windows):
gfortran -c fd.f
f2py.py -c -m it --compiler=mingw32 fd.o itimes.f
reprun.py

The output is:
th - it  1.50520876326836550E-163
th - fd  1.50520876326836550E-163

My first guess is that th is somehow not being passed correctly from reprun.py to subroutine itimes.  However, I do not understand this behavior, as the full version of the code includes other inputs, all of which are passed correctly.  I was not able to get it to do the same thing when calling itimes from Fortran, so I'm assuming it has something to do with the Python/Fortran interface.  Can anyone provide any insights into why this behavior occurs?
EDIT: Replacing th = 200 in reprun.py with th = 200.0 yields the following output:
th - it  1.19472349365371216E-298
th - fd  1.19472349365371216E-298

A: Wrap your itimes subroutine in a module as well. Here is what i did:
itimes.f90:
module itime

contains

subroutine itimes(th)
  use fd
  implicit none
  real(dp) th

  write(*,*) 'th - it',th
  call lprsmf(th)
end subroutine itimes

end module

compile & run:
gfortran -c fd.f90
c:\python27_w32\python.exe c:\python27_w32\scripts\f2py.py -c -m it --compiler=mingw32 fd.f90 itimes.f90

run reprun.py:
import it

th = 200
it.itime.itimes(th)

output:
 th - it   200.00000000000000
 th - fd   200.00000000000000


text:
Q: Is it bad practice to use triggers to increment revision number? I'm building a commenting function and struggles a bit with the database design. The goal is to keep all history when a user decides to amend/delete a comment.
The columns that I imagine are
`commentID` int(11) NOT NULL,
`referencetype` char(1) NOT NULL,
`referenceID` int(11) NOT NULL,
`revision` tinyint(3) unsigned NOT NULL,
`comment` text NOT NULL,
`userID` int(11) NOT NULL,
`deleted` tinyint(1) NOT NULL DEFAULT '0',
`timestamp` int(11) NOT NULL,

When adding a new comment I want commentID to increment and when adding a revision to that same commentID I want the revision number to increment.
A possible solution would be

*

*Add a non-unique index on commentID and set it to auto_increment

*Add a unique index on (commentID, revision)

*Create a trigger that increment revision when inserting on existing commentID

Is this a reasonable solution? What might be a better way?
Edit: Sample data for some important columns
+-----------+---------------+-------------+----------+-----------------------+--+
| commentID | referencetype | referenceID | revision |        comment        |  |
+-----------+---------------+-------------+----------+-----------------------+--+
|         1 | A             |         123 |        1 | Comment1              |  |
|         1 | A             |         123 |        2 | Comment1 first edit   |  |
|         2 | A             |         123 |        1 | Comment2              |  |
|         1 | A             |         123 |        3 | Comment1 second edit  |  |
+-----------+---------------+-------------+----------+-----------------------+--+

A: According to the comment @daker put to the first version of this answer, I'd like to change the focus of this solution.
Instead of use an integer revision number, you could use the timestamp field as revision. Doing that, you can define your table like this:
`commentID` int(11) NOT NULL AUTO_INCREMENT,
`referencetype` char(1) NOT NULL,
`referenceID` int(11) NOT NULL,
`comment` text NOT NULL,
`userID` int(11) NOT NULL,
`deleted` tinyint(1) NOT NULL DEFAULT '0',
`timestamp` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
...
PRIMARY KEY(commentID, timestamp)

And then you will get these benefits:

*

*Your commentID is autoincremented

*You avoid to use an unecessary field, revision

*Every time an user modify a comment you will create a new entry into this table

*Every new registered will keep automatically the moment of the modification


text:
Q: SSO Implementation ColdFusion This is a very basic question. I want to do an SSO integration using ColdFusion but do not know where to start. I found the website ssoeasy.com through a google search, but am very confused about how to use it and where to find documentation.
I think it has something related with cfldap or cfhttp but not sure what and where:
<cfhttp method="get" url="http://testsso.com/login.cfm">
</cfhttp>

A: It really depends on what role you want to play in an SSO ecosystem. Are you an app in a larger federation (Service Provider), or are you trying to implement an SSO style login across multiple applications that you control, or are you looking to setup so that your users can log in with Google or Facebook or such other identity registers?
A few years back we did an implementation with Shibboleth (https://shibboleth.net/) and CF where our intended place in the system would be that of a Service Provider to other companies Identity Providers.  It works pretty straight forward as we let Shibboleth handle all the SAML federation grunt work and then when it's completed we get an e-mail address (the unique identifier we decided on) back from Shibboleth saying that the user has been authenticated via the Identity Provider.
Other 'SSO' implementations are around for other types of integrations.
From CFCs to handle OAuth -- https://github.com/coldfumonkeh/oauth2
To integrated oauth support if you're running a new enough version of ColdFusion https://helpx.adobe.com/coldfusion/cfml-reference/coldfusion-tags/tags-m-o/cfoauth.html
Hope this is of assistance to you.

A: If I understand your SSO use case, the application will be a cloud service provider (SP). There are three things you need to determine to help in the selection of the appropriate technology, mainly (1) SSO protocol to integrate, mainly SAML, OAuth, OpenID Connect (OIDC), etc. (2) Hosting, mainly Cloud, On-Prem, or hybrid, and (3) whether or not IdP discovery is needed for your business partners.
Being ColdFusion based as well as working to be a cloud SP web application, my experience is that the application is to be hosted by your organization, such that an on premise SSO capability is desired, as well as IdP Discovery will be needed for your partners.
As noted in your question there are some options for integration. I have found the most popular approach to being a SP website is to utilize a vendor product that handles the SSO protocol (e.g. SAML, OIDC) where the integration with your ColdFusion application is based upon a simple REST API integration. With this design pattern, the vendor product manages all the security of the SSO protocol and then simplifies integration to your application as a secure REST API exchange of identity information.  This will minimize the impact to your application and also give the most support for modern identity. One product that offers this capability is PingFederate via the Agentless integration (also referred to as Reference ID integration).  I have had much success integrating ColdFusion applications following this type of approach.

A: SAML seemed to be the easiest to implement for our team. Phil Duba's 2013 Beyond Encrypt() presentation is a good starting place. His website is down right now, but I'm sure you can find the downloadable file somewhere. Learning about SAML in general would be a good idea. Also, you can use Java, so maybe look at SAML/OAUTH Java examples and try doing that for Coldfusion since it is based on Java.


text:
Q: Deploying existing Console Application to Azure I have a C# program (I'll call it ProgramA) running on an azure VM running windows server, and it references my MVC site. Currently when I make changes to my MVC sites database structure the program on the VM runs into errors as the database structure has changed.
In order to resolve these errors I simply need to stop the service, update the dll, and restart the service. Currently I do this manually, which is awful as it causes downtime. I am looking to automate this deployment.
UPDATED - DEPLOYING CONSOLE APPLICATION IN CLOUD WITH DEPLOYMENT FROM VS2013
I was thinking of achieving this by creating a small app to run on the VM to check for updates and perform them, but I am now aware there are easier ways to achieve my goal by deploying my application from VS to run as a service in the cloud.
My app is a console app. I simply want it running in the cloud in a way that makes it easier to deploy. I have found https://azure.microsoft.com/en-us/documentation/articles/websites-dotnet-deploy-webjobs/#convert, but following the steps leads me to deploying a website and I'm not sure that's what I want. This isn't a website it is simply a console application.
What is the best way of achieving this?


text:
Q: Is there a way to get the Title of the selected item from another component in React Native I have two different components "HomePage" & "ListItemCA"
In HomePage, I have a FlatList and a modal popup
<FlatList
data={ listData}
keyExtractor={list => list.Title}
renderItem={({ item }) => <ListItemCA data={item} onLongPress={openModal} />}
/>

and each list item is called from another component ListItemCA
function ListItemCA({data, onLongPress}) {

    return (
        <TouchableOpacity onLongPress={onLongPress} >
        <View style={styles.container}>
            <Text style={styles.title}>{data.Title}</Text>
            <View style={styles.metaContainer}>
                <Text style={styles.meta}>{( data.totalMonths != null ? data.totalMonths : '0' )} Months</Text>
                <Text style={styles.meta}>{( data.members != null ? data.members.length : '0' )} Members</Text>
            </View>
        </View>
        </TouchableOpacity>
    );
}

What I want to acheive?
I want to get the selected list item title on my HomePage component. When a user longpress on a list item that title should be displayed on a modal popup. How do I pass the selected list item title to the HomePage component using longpress?

A: If your goal is to display data from the long pressed item in the modal, you could add the data as a parameter of your openModal function:
function openModal(data) {
    // your function
    return (
        <Text>{data.Title}</Text>
    )
}

Then, in your FlatList, modify the props of ListItemCA to call openModal for the selected item:
renderItem={({ item }) => <ListItemCA data={item} onLongPress={openModal(item)} />}

If you also want to save the data from the long pressed item in your HomePage component for other uses, you could save it in the state. In your HomePage component:
import React, { useState } from 'react'

function HomePage() {
    const [itemData, setItemData] = useState()

    // your code
}

Then, in your flatlist:
<FlatList
        data={listData}
        keyExtractor={list => list.Title}
        renderItem={({ item }) =>
            <ListItemCA
                data={item}
                onLongPress={ () => {
                    setItemData(item)
                    openModal(item)
                }}
            />
        }
    />

A: You can achieve this by passing(return) parameter from your component like this -
function ListItemCA({data, onLongPress}) {
    return (
      <TouchableOpacity onLongPress={() => {
        onLongPress(data.Title);
        //return data.Title when onLongPressed clicked
      }}>
        <View style={styles.container}>
          ...
        </View>
      </TouchableOpacity>
    );
}

then get it in props -
<FlatList
   data={listData}
   keyExtractor={list => list.Title}
   renderItem={({ item }) =>
      <ListItemCA
        data={item}
        onLongPress={(title) => {//this **title** return from **onLongPress(data.Title)**
          openModal();
          setTitle(title);// or directly can pass that title in openModal func.
        }}
      />
   }
/>


text:
Q: How do I send MetaData HTTP POST Request Suppose i want to send these type of Requests which has "meta":{} inside the json data, how do I go about it?
I have this as json data
{
  "amount": 500,
  "narration": "Test Int'l bank transfers",
  "currency": "USD",
 "beneficiary_name": "Mark Cuban",
  "meta":
    {
     "AccountNumber": "09182972BH",
     "RoutingNumber": "0000000002993",
     "SwiftCode": "ABJG190",
     "BankName": "BANK OF AMERICA, N.A., SAN FRANCISCO, CA",
     "BeneficiaryName": "Mark Cuban",
     "BeneficiaryAddress": "San Francisco, 4 Newton",
     "BeneficiaryCountry": "US"
    }
}

If i try to send this in Postman , i get an Error , like this

Then when I send this as a normal request like below, say something like this
{
  "account_bank":"044",
  "account_number":"09182972BH",
  "RoutingNumber":"0000000002993",
  "SwiftCode": "ABJG190",
  "amount":"450.40",
  "email":"john_kross2@yopmail.com",
  "narration":"test USD transfer",
  "currency":"NGN",
  "reference":"akhlm-pstmnpyt-rfxx007_PMCKDU_6876677",
  "debit_currency":"USD"
}

, it gives me this with HTTP 200, but does not work as I expect it to

The code in Question that is supposed to work is Looking thus :
router.post("/us-transfer", async (req, res, next) => {
  try {
    if (
      !req.headers.authorization ||
      !req.headers.authorization.startsWith("Bearer ") ||
      !req.headers.authorization.split(" ")[1]
    ) {
      return res.status(422).json({ message: "Please Provide Token!" });
    }

    var AccountNumber = req.body.AccountNumber;
    var RoutingNumber = req.body.RoutingNumber;
    var SwiftCode = req.body.SwiftCode;
    var amount = req.body.amount;
    var narration = req.body.narration;
    var email = req.body.email;
    var currency = req.body.currency;
    var reference = req.body.refernce;
    var debit_currency = req.body.debit_currency;
    var beneficiary_name = req.body.beneficiary_name;

    url = "https://api.flutterwave.com/v3/transfers";
    await fetch(url, {
      method: "POST",
      headers: {
        "Accept": "application/json",
        "Content-type": "application/json",
        "Authorization": "Bearer FLWSECK_TEST-153740d351951b5f6d5ae8b903e0c467-X",
      },
      body: JSON.stringify({
        AccountNumber: AccountNumber,
        RoutingNumber : RoutingNumber,
        SwiftCode : SwiftCode,
        amount: amount,
        narration: narration,
        currency: currency,
        reference: reference,
        debit_currency: debit_currency,
        beneficiary_name: beneficiary_name,
      }),
    })
      .then((response) => response.json())
      .then(async (json) => {

        const debit = await User.find({ email: email});
        const debit_balance = parseInt(debit[0].balance);
        const debit_amt = debit_balance - amount;
        await User.findOneAndUpdate({email : email}, {$set: {balance: debit_amt}});

        const transactions = new Trans({
          email: email,
          narration: narration,
          credit: 0.0,
          debit: amount,
          amount: amount,
        });
        try {
          transactions.save();
          //res.send(savedUser);
          console.log("transaction saved");
        } catch (err) {
          //res.status(400).send(err);
          console.log(err);
        }

        //sendTransferConfirmation(email);
        return res.send({ error: false, data: json, message: "US Bank Transfer Complete" });
      })
      .catch((err) => {
        throw err;
      });
  } catch (err) {
    next(err);
  }
});

I do not seem to know what is going on. Kindly help.


text:
Q: How can i change the text background blur padding? I tried to get a background blur effect to a text using:
backdrop-filter: blur;

It works, but I want the padding to be smaller. How can I do that?
P.S: I'm new to all that things

A: Use the CSS padding property on the same element that you've applied backdrop-filter to. You can set the amount of padding in pixels. The following will apply 20 pixels of padding to each side of your element:
padding: 20px;


text:
Q: IgGrid - How to connect custom feature chooser to the grid? In my project I use igGrid from ignite-ui. In headers of columns there are gears. If user clicks gear then a popover apears (feature chooser). My task is to implement custom feature chooser - when user clicks on the gear then my custom feature chooser should apear instead of the built-in feature chooser.
I know how to implement the custom feature chooser and options like sorting, grouping, column moving etc. The problem is that I can't find out how to overwrite the gear click event.

A: You'll have to find the gear icons and unbind mousedown event to prevent feature chooser to pop up.
After that you can bind to mousedown using custom handler to show the custom feature chooser.
rendered: function(e, ui) {
    ui.owner.headersTable()
    .find("a[data-fc-button]")
    .off("mousedown")
    .on("mousedown", (e) => {
        //open your own featurechooser here
    });
},

Here's a fiddle to demonstrate this - http://jsfiddle.net/dkamburov/da276b5w


text:
Q: Is it good to store static data in db - C#? I have this problem and I don't know what is the best solution for it.
I have table called Employees and there is column called LastWork, this column should only have custom values I choose for example:
value 1
value 2

and I want the user to select the value from ComboBox control so I have 2 ideas for it but I don't know what is the best for it.
A - add these value to Combobox as string in Items property and store them as string in DB.
B - create separate table in my db called for example 'LastWork' with 2 columns 'LastWorkID', 'LastWorkName' and insert my values in it, and then I can add binding source control and I can use data bound items to store the id as integer in my main table and show the LastWorkName for users.
I prefer to use the B method because in some forms I have DataGridView control with edit permission, and I want to display Combobox in it instead of Textbox to select from these custom values.
I hope you understood my questions.

A: Normally data normalization is a good thing, so I too would go with your option B.
By having a separate table and a foreign key relationship to it, you can enforce data integrity; easily get a list of all available (not just all selected) options; have a single place in which to change the text of an option (what if someone decides to call it "value one" instead of "value 1", for example?); and so on and so forth.
These might not be huge benefits in a small application and with only two possible options, but we all know that applications very often tend to grow in scope over time.

A: In a normalized database, your "option B" is usually the way to go because it eliminates duplicate data. It will potentially introduce an additional join into your queries when you need the name (and not just the ID), but it also allows you to rename lookup names easily without altering their underlying IDs.
For performance reasons, it's often a good idea to cache lookup values such as you describe in the business tier so that your lookup table is not hit over and over again (such as when building many rows of a grid).

A: I would always save them in the db. If you have to localize your app, this helps alot. Additonally, it let you to apply the referential integrity checks of the database.


text:
Q: Why are the contravariant and covariant basis perpendicular? Studying tensors, I get the concept of a contravariant and covariant vector, but my understanding is that a contra/covariant basis is different. Why are they perpendicular to each other or what is the motivation? Shouldn't the idea of the variance of a vector apply the same way to a basis vector?
On a similar note, why is it that the contravariant components are described by adding together the basis to form a vector, but covariant components are found by a dot product? What makes the dot product significant here?

A: Maybe you are confusing three kind of pairing (dot products) among vectors and covectors.
If you pair a pair of vectors $v\cdot w$ is not the same if you pair a pair of covectors $\langle f,g\rangle$. But
in mixed case of pairing a pair, $f$ a covector and $v$ a vector, one can choose $f\bullet v=f(v)$.
But in case of choosing basis $b_k$ for $V$ and $\beta^l$ for $V^*$, is then when we have
$$\beta^k(b_l)=\delta^k{}_l,$$
which the important device to access to the concepts and techniques about tensors.
Pairings enjoy the property of been bilinear maps i.e. rank two tensors.


text:
Q: How to run gulpfile.babel.js(ES6) tasks from subfolder?
Works if run from file root folder but on the subfolder, I get a syntax error.
The error is regarding import syntax, failing at first import which is gulp.
If I change to require it works but I need the setup in ES6.
I need to mention again, it works fine if I run the command from a terminal from the folder where gulfile is.
PS: I've updated some babel to 7 - I did not have this problem with babel 6.
Looks like if failing to use .babelrc from the outside root folder.
Everything I could find online.
'use strict';
/**
* Note: I updated most of the theme npm deps including gulp@4
*/
import gulp from 'gulp';
import babel from 'gulp-babel';
import uglify from 'gulp-uglify';
import sass from 'gulp-sass';
import sourcemaps from 'gulp-sourcemaps';
import autoprefixer from 'gulp-autoprefixer';
import revAll from 'gulp-rev-all';
import cleanCSS from 'gulp-clean-css';
import svgSprite from 'gulp-svg-sprite';
import del from 'del';
import merge from 'merge-stream';
import browserify from 'browserify';
import browserSync from 'browser-sync';
import source from 'vinyl-source-stream';
import buffer from "vinyl-buffer";
import babelify from 'babelify';

It should work the same as the task is run from root directory even if is run from the subfolder.

A: I believe you should update the main parameter of your package.json file.
Please refer to Node.js package.json main parameter for further info.
Hope it helps.


text:
Q: Cant run a php file from var folder I installed LAMP but still when i try to access a folder in var it says 404 not found I want to start "php" but it is stopping me can any one help. Actually when I type 127.0.0.1 I don't get page saying I works I get a page saying
Index of /
index.php.save

A: Localhost is in var/www/..
if still can't locate check your  in apache default.conf file..!


text:
Q: How do i force links in a dynamic object to open in a new tab? I'm trying to load up a styled RSS feed from my WordPress blog on another site, and I can load it up just fine, but the security of WordPress does not allow you to open their site in a frame. So can anyone tell me how to change the target attribute of the links in the styled RSS feed, so that they don't try to open the wordpress site in the frame it was loaded into, but a new tab instead?
    <!doctype html>

    <meta charset="utf-8">
    <title>Load remote content into object element</title>

Article Feed:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>

View RSS feed

Help is much appreciated.

A: You can use this structure:
$("#content a").attr('target','_blank');

A: Use inside articlefeed.html the targ-parameter for the script:
http://www.feedroll.com/rssviewer/feed2js.php?src=http%3A%2F%2Fnyhederwp.oneclick.holdbarhest.dk%2Fcategory%2Fartikler%2Ffeed%2F&chan=y&num=5&desc=200&au=y&date=y&utf=y&targ=_blank


text:
Q: Plot a long Stop Loss ONLY if a "Go Long" position is active I'm getting to grips with the basics of Pine Script Version 5.
Basically, I'm looking to plot a Stop Loss on the chart, but ONLY if a long position (moving average crossover) is open and active.
The Stop Loss itself is the longer Exponential Moving Average minus 2 x average true range.
Any help would be massively appreciated, and thank you in advance
Here's the simple coding I've done so far (and I know that it's a simple tweak that is needed):
    //@version=5
    strategy("EMA Crossover", overlay=true, margin_long=100, margin_short=100)

    //Indicators
    SEMA = ta.ema(close, 24)
    LEMA = ta.ema(close, 48)
    STOP = ta.atr(24)

    //Plot them
    plot(SEMA,"SEMA", color.black)
    plot(LEMA,"LEMA",color.blue)
    plot(LEMA+STOP, "Short Stop", color.red)
    plot(LEMA-STOP, "Long Stop", color.green)

    //Enter long
    longCondition = ta.crossover(SEMA,LEMA)
    if (longCondition)
        strategy.entry("Go Long", strategy.long)

    //Enter short
    shortCondition = ta.crossunder(SEMA,LEMA)
    if (shortCondition)
        strategy.entry("Go Short", strategy.short)

A: You can use the strategy.position_size built-in variable to figure out your market position.

Direction and size of the current market position. If the value is >
0, the market position is long. If the value is < 0, the market
position is short. The absolute value is the number of
contracts/shares/lots/units in trade (position size).

is_long = strategy.position_size > 0
is_short = strategy.position_size < 0
is_not_in_position = strategy.position_size == 0


text:
Q: three20 error after adding it to my project I have been trying to add the Three20 framework to my app. But I always end up getting this error:
Undefined symbols:
"___restore_vfp_d8_d15_regs", referenced from:
+[TTEntityTables(TTSingleton) sharedInstance] in libThree20Core.a(TTEntityTables.o)
+[TTEntityTables(TTSingleton) releaseSharedInstance] in libThree20Core.a(TTEntityTables.o)
+[TTEntityTables(TTSingleton) allocWithZone:] in libThree20Core.a(TTEntityTables.o)
"___save_vfp_d8_d15_regs", referenced from:
+[TTEntityTables(TTSingleton) sharedInstance] in libThree20Core.a(TTEntityTables.o)
+[TTEntityTables(TTSingleton) releaseSharedInstance] in libThree20Core.a(TTEntityTables.o)
+[TTEntityTables(TTSingleton) allocWithZone:] in libThree20Core.a(TTEntityTables.o)
ld: symbol(s) not found

collect2: ld returned 1 exit status

it seems like some kind of linker error to me, but I'm rather shure I followed all instructions on how to install the framework.
Somehow I get the suspicion, that it is a bug within the framework, but I'm not shure. Any ideas?

A: Make sure that, in the build settings, you've selected 'Standard' for the architectures and that 'Build Active Architecture Only' is unchecked.


text:
Q: programmatically connect to USB devices from USB-over-IP hub Digi AnywhereUSB Is it possible and how to connect specifically to USB devices, connected to the Digi AnywhereUSB 8 Plus hub, via https, tcp/ip?
Our first idea was to connect USB devices to the USB-over-IP hub and connect to each of the device via IP:Port programmatically with a script locally or e.g. from Jenkins.
I found a document:
Digi International Anywhere USB Library API Specification
https://www.digi.com/support/knowledge-base/anywhereusb-api-information
when installing their driver in following paths.
https://hub.digi.com/support/products/infrastructure-management/digi-anywhereusb/?path=/support/asset-collection/os-specific-drivers-anywhere-usb/
driver install path and files:
C:\Program Files\Digi\AnywhereUSB\Advanced
AwUsbApi.dll
AwUsbApi.pdf
Apparently there are some functions provided e.g. :
AWUSB_STATUS
AwUsbConnect (
    IN LPCWSTR Hub,
    IN PAWUSB_STATUS Status,
    IN DWORD Timeout,
IN HANDLE hEvent OPTIONAL
);

The task at hand is now, how to script a connection to plugged-in USB devices? What language /environment would you suggest?


text:
Q: Examples of functions summables in $\mathbb{Z}^d$. I know that $f_0(x)={ 1 \over \vert \vert x\vert \vert^\alpha}$, $f_0(0)=1$ , $\alpha>d$, $d\in   \mathbb{N}$ is summable in $\mathbb{Z}^d$, i.e.
$$
\sum_{x \in \mathbb{Z}^d} f(x)<\infty.
$$
I am searching for other examples of  $f(x)>{ 1 \over \vert \vert x\vert \vert^\alpha}$ (except maybe for a finite numbers of 'x's)  that  are summables in $\mathbb{Z}^d$  or $V_n= [1,n]^d \bigcap \mathbb{Z}^d$.


text:
Q: WPF Change property from codebehind I have a property being set as follows:
<ListBox Grid.Row="1" Name="lstDrop" Background="Transparent" GUICommon:ListBoxSelector.Enabled="True"

Could someone tell me if its possible to change the GUICommon:ListBoxSelector.Enabled="True" property to false in the codebehind?

A: ListBoxSelector.Enabled seems to be an attached property.
You should be able to set it by calling
ListBoxSelector.SetEnabled(lstDrop, true);


text:
Q: Use of unresolved identifier 'PHPhotoLibrary' I am working on a Photos extension for Mac OS X (10.11).
I have the Photos and PhotosUI frameworks imported.
Everything is ok apart from when I try to make a call to PHPhotoLibrary.sharedPhotoLibrary().
This results in an error in Xcode 7.3.1 (7D1014):
Use of unresolved identifier 'PHPhotoLibrary'

Has anyone else experienced this or know what could be causing the issue?

A: You don't need the PHPhotoLibrary class to make a photo editing extension in either iOS or OS X, and in OS X you can't use it.
The entire workflow for a photo editing extension goes through the PHContentEditingController protocol. On both platforms, the main view controller of a photo editing extension implements this protocol. It provides the asset to be edited in the startContentEditingWithInput:placeholderImage: method, and when the user is done editing it calls your finishContentEditingWithCompletionHandler: method so you can apply your final-quality edits and provide output.
Notice I say "when the user is done editing". Saving to the photo library isn't something you do in your extension code — instead Photos asks you for final rendered output, and Photos handles saving it to the library.
In your finishContentEditingWithCompletionHandler: method, you should:

*

*Create a PHContentEditingOutput from the PHContentEditingInput (which you received in startContentEditingWithInput:placeholderImage:).

*Save your output as a JPEG file (or QuickTime movie file, for video assets) to the renderedContentURL that the PHContentEditingOutput specifies

*Call the completionHandler block that was passed to you, passing it your PHContentEditingOutput.

You calling that completion handler is what triggers Photos saving the edited asset to the library.


text:
Q: hook_menu issues I have a hook menu
$items['node/%/delete'] = array(
        'title' => 'Delete',
        'load arguments' => array(3),
        'description' => 'Confirm the action.',
        'page callback' => 'drupal_get_form',
        'page arguments' => array('_mymodule_delete', 1),
        'type' => MENU_CALLBACK,
        'weight' => -4,
    );
return $items;

What do I need to do to make sure the following function gets to work (and the variables get their values):
function _mymodule_delete ($form, $form_state, $node) {
          ...
}
In orther words, how do I get values in the three arguments given ($form, $form_state and $node)

A: EDIT
I'll have another go...
The only argument(s) you need to pass to drupal_get_form, other than the name of the form itself, are arguments specific to that form function; $form and $form_state are automatically added for you. So if you want to call a form with a signature of _mymodule_delete($form, $form_state, $node) you would use this code:
$form = drupal_get_form('_mymodule_delete', $the_node);

When you apply this to the menu router, all you're looking to do is pass the loaded $node through as an argument to drupal_get_form in the same way. Your router item would look like this:
$items['node/%node/delete'] = array(
  'title' => 'Title',
  'page callback' => 'drupal_get_form',
  'page arguments' => array('_mymodule_delete', 1),
  'access arguments' => array('access content'),
  'type' => MENU_CALLBACK,
  'weight' => -4,
);

Your original example is missing the access arguments/access callback attribute which would make your page inaccessible (403 status) so I've added in the 'standard' access arguments of access content. You'll probably want to change this for your own needs.
The string node/%node/delete (the router path) and the page arguments array are the bits you're probably interested in here. When you want to pass an argument from the URL to a callback function you simply include it's 'index' as one of the page arguments. This index comes from a zero-based array of the router path when split by the separator (/).
In this example the three parts of the path are:
0 => 'node',
1 => '%node',
2 => 'delete'

As the variable element of the path is in index position 1, that's the number we pass to the page arguments array.
Just to make it a little more complicated, the variable passed in through the path can also be passed to a load function before it's passed to the page callback function. For some reason the naming convention in Drupal is that a function with the name of the variable with _load appended to it will be the name of the function called.
So in this case, node_load is called. If your router path was, for example, books/%book then a function called book_load would be called to prepare the variable to be passed to the page callback function.
The load function is optional, if your path was node/%/delete then the argument passed to your form callback would be the exact string (in this case a node ID) from the URL.
I'm sure you've seen it but the hook_menu() documentation tries its best to explain all this, I can understand why it would be difficult to comprehend though.
Hope that helps.


text:
Q: "Servlet" (server-side) initialization code in GWT How can I have a single time initialization on a server side of GWT app?
I may be thinking to much like HttpServlet where you can override init(), but old habits are long to lose ;)
What I am trying to do is:

*

*load a bunch of properties

*establish a connection to the database

A:
load a bunch of properties?

Register ServletContextListener to load Init parameters at server start-up.
Load properties and make it visible to other classes statically.
I have already posted a sample code Retrieve Init parameters outside servlet

establish a connection to the database?

Use JNDI to bind the data source.
Use Connection Utility class to get the connection as well as close the connection as soon as its done.
Here is the sample code.
import java.sql.Connection;
import java.sql.SQLException;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

import com.woodmac.datavisualizer.shared.DVConstants;

public class ConnectionUtil {

    private DataSource dataSource;

    private static ConnectionUtil instance = new ConnectionUtil();

    private ConnectionUtil() {
        try {
            Context initContext = new InitialContext();
            dataSource = (DataSource) initContext.lookup(JNDI_LOOKUP_NAME);

        } catch (NamingException e) {
            e.printStackTrace();
        }
    }

    public static ConnectionUtil getInstance() {
        return instance;
    }

    public Connection getConnection() throws SQLException {
        Connection connection = dataSource.getConnection();
        return connection;
    }

    public void close(Connection connection) throws SQLException {
        if (connection != null && !connection.isClosed()) {
            connection.close();
        }
        connection = null;
    }
}

If you are using JBOSS in standalone mode. Then just do some entries in standalone.xml to create a data source. Just update some of its value as per your database connection such as connection-url, user-name and password.
In this case JNDI_LOOKUP_NAME will be java:jboss/datasources/oracle
<datasource jta="true" jndi-name="java:jboss/datasources/oracle" pool-name="OracleDS" enabled="true" use-java-context="true" use-ccm="true">
    <connection-url>jdbc:oracle:thin:@ipaddress:1521/sid</connection-url>
    <driver>oracle</driver>
    <new-connection-sql>select * from dual</new-connection-sql>
    <pool>
        <min-pool-size>20</min-pool-size>
        <max-pool-size>50</max-pool-size>
        <prefill>true</prefill>
    </pool>
    <security>
        <user-name>username</user-name>
        <password>password</password>
    </security>
    <validation>
        <check-valid-connection-sql>select * from dual</check-valid-connection-sql>
        <background-validation>true</background-validation>
    </validation>
    <timeout>
        <blocking-timeout-millis>30000</blocking-timeout-millis>
        <idle-timeout-minutes>1</idle-timeout-minutes>
        <use-try-lock>60</use-try-lock>
        <allocation-retry>1</allocation-retry>
    </timeout>
</datasource>

A: You can add like mentioned in a comment a  ServletContextListener.
public class ServerConfig implements ServletContextListener {

    public void contextInitialized(ServletContextEvent event) {
    // Do stuff on startup.
    }

    public void contextDestroyed(ServletContextEvent event) {
    // Do stuff on shutdown.
    }
}

Now put the new class on the server side, you also ave to register the Listener in your web.xml file :
<listener>
<listener-class>path.to.class.ServerConfig</listener-class>
</listener>


text:
Q: Multi threading Process for Audio Applications I'm currently trying to design an audio sampler that takes many audio files, adds filters, mixes them together and then outputs the result to the speakers. I'm hoping to multithread this process to make it go faster, but I'm not sure which of two routes I should take:

*

*One function that runs on multiple threads that does everything (input file, add filter, output)

*Multiple threads that do different tasks ie. Thread 1 gets input samples and adds them to an array to be processed, Thread 2 gets the items in the first array, filters each one and then adds them to a second array Thread 3 takes the processed samples in the second array and outputs them to the speakers

Which of these approaches would be best, or is there a better approach that I'm missing? I'm hoping to do Float32 output at 192khz.


text:
Q: Python Pandas concatenate two multi index dataframe into one with another level of multi index I am dealing with Multi Index again. This time, I am concating two dataframes with same types Multi-indexed index and columns. However, the values are different, and there will be come index.level(0) values are different. I want to concate two dataframe into one. Please take a look at below example.
In [13]: df_ver1
Out[13]:
key  nm         0         1         2         3
bar one -0.424972  0.567020  0.276232 -1.087401
    two -0.673690  0.113648 -1.478427  0.524988
baz one  0.404705  0.577046 -1.715002 -1.039268
    two -0.370647 -1.157892 -1.344312  0.844885
foo one  1.075770 -0.109050  1.643563 -1.469388
    two  0.357021 -0.674600 -1.776904 -0.968914
qux one -1.294524  0.413738  0.276662 -0.472035
    two -0.013960 -0.362543 -0.006154 -0.923061

In [14]: df_ver2
Out[14]:
key  nm         0         1         2         3
bar one  0.895717  0.410835 -1.413681 -1.236269
    two  0.805244  0.813850  1.607920  0.896171
baz one -1.206412  0.132003  1.024180 -0.487602
    two  2.565646 -0.827317  0.569605 -0.082240
oof one  1.431256 -0.076467  0.875906 -2.182937
    two  1.340309 -1.187678 -2.211372  0.380396
qux one -1.170299  1.130127  0.974466  0.084844
    two -0.226169 -1.436737 -2.006747  0.432390

In [15]: df_total
out[15]:
key  nm  ver            0         1         2         3
bar one ver1    -0.424972  0.567020  0.276232 -1.087401
        ver2     0.895717  0.410835 -1.413681 -1.236269
    two ver1    -0.673690  0.113648 -1.478427  0.524988
        ver2     0.805244  0.813850  1.607920  0.896171
baz one ver1     0.404705  0.577046 -1.715002 -1.039268
        ver2    -1.206412  0.132003  1.024180 -0.487602
    two ver1    -0.370647 -1.157892 -1.344312  0.844885
        ver2     2.565646 -0.827317  0.569605 -0.082240
qux one ver1    -1.294524  0.413738  0.276662 -0.472035
        ver2    -1.170299  1.130127  0.974466  0.084844
    two ver1    -0.013960 -0.362543 -0.006154 -0.923061
        ver2    -0.226169 -1.436737 -2.006747  0.432390

As you can already see, two levels of Multi-index and the third level would indicate the dataframe version as ver1 or ver2. Each values are layed in respect to columns. One thing to keep in mind is that in df_ver1, there are foo index and in df_ver2, there are oof index. These indexes does not have matching index to other dataframe, so it is concatenated in inner frames. I hope I explained well enough, and let me know if you have any questions. Thanks for the help!

A: Take the intersection two dataframe's index, concat and sort_index i.e
idx = d1.index.intersection(d2.index)
one = pd.concat([d1.loc[idx],d2.loc[idx]],keys=['ver1','ver2'])

one.reset_index().set_index(['key','nm','level_0']).sort_index(level=['key','nm'])

                      0         1         2         3
key nm  level_0
bar one ver1    -0.424972  0.567020  0.276232 -1.087401
        ver2     0.895717  0.410835 -1.413681 -1.236269
    two ver1    -0.673690  0.113648 -1.478427  0.524988
        ver2     0.805244  0.813850  1.607920  0.896171
baz one ver1     0.404705  0.577046 -1.715002 -1.039268
        ver2    -1.206412  0.132003  1.024180 -0.487602
    two ver1    -0.370647 -1.157892 -1.344312  0.844885
        ver2     2.565646 -0.827317  0.569605 -0.082240
qux one ver1    -1.294524  0.413738  0.276662 -0.472035
        ver2    -1.170299  1.130127  0.974466  0.084844
    two ver1    -0.013960 -0.362543 -0.006154 -0.923061
        ver2    -0.226169 -1.436737 -2.006747  0.432390


text:
Q: How to install APK from local server URL in phone without prompt to install screen? I am creating app like play store and will publish all our applications on this application. so our internal employee will get all our application in one place and then they can install or update app from this app. I have created the following code with the help of URL mentioned below. Code running successfully but nothing happening. Am I doing something wrong ?
I call below function on install button click like below
installPackage(getApplicationContext() , app_url);

https://stackoverflow.com/a/50548442/7223676
public static boolean installPackage(final Context context, final String url)
            throws IOException {
        //Use an async task to run the install package method
        AsyncTask<Void,Void,Void> task = new AsyncTask<Void, Void, Void>() {
            @Override
            protected Void doInBackground(Void... voids) {
                try {
                    PackageInstaller packageInstaller = null;
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                        packageInstaller = context.getPackageManager().getPackageInstaller();
                    }
                    PackageInstaller.SessionParams params = null;
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                        params = new PackageInstaller.SessionParams(
                                PackageInstaller.SessionParams.MODE_FULL_INSTALL);
                    }

                    // set params
                    int sessionId = 0;
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                        sessionId = packageInstaller.createSession(params);
                    }
                    PackageInstaller.Session session = null;
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                        session = packageInstaller.openSession(sessionId);
                    }
                    OutputStream out = null;
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                        out = session.openWrite("COSU", 0, -1);
                    }
                    //get the input stream from the url
                    HttpURLConnection apkConn = (HttpURLConnection) new URL(url).openConnection();
                    InputStream in = apkConn.getInputStream();
                    byte[] buffer = new byte[65536];
                    int c;
                    while ((c = in.read(buffer)) != -1) {
                        out.write(buffer, 0, c);
                    }
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                        session.fsync(out);
                    }
                    in.close();
                    out.close();
                    //you can replace this intent with whatever intent you want to be run when the applicaiton is finished installing
                    //I assume you have an activity called InstallComplete
                    Intent intent = new Intent(context, AppActivity.class);
                    intent.putExtra("info", "somedata");  // for extra data if needed..
                    Random generator = new Random();
                    PendingIntent i = PendingIntent.getActivity(context, generator.nextInt(), intent, PendingIntent.FLAG_UPDATE_CURRENT);
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                        session.commit(i.getIntentSender());
                    }
                } catch (Exception ex){
                    Log.e("AppStore","Error when installing application. Error is " + ex.getMessage());
                }

                return null;
            }
        };
        task.execute(null,null);
        return true;
    }

A: Do you have root access of the device? From the link which you are following
How to Install android app programatically without prompt,
It is clearly mentioned that
"Another way to install an app programatically without prompts assuming you have root access would be as follows"
Try getting the root access of your device first and then do what you are doing.
On a side not, if you succeed with the method you are following, it will not help you in any way. You will not be able to root every employ's device and this method will not work from them, unless you have some links with OEMs which by default add your application with the Android Os.
ALSO : For Implementing Google Play Application Silent Install Feature On Android

Silent install on Google Experience devices is only possible by Google
  Play. More generally, only stores that come preloaded on your hardware
  can accomplish this, since they need to use the operating system's
  signing key.
This is for security reasons. Users need to be able to accept
  permissions for new installations. The OS has no way to verify whether
  non-official stores have properly done this.
Third-party applications must use PackageManager to install new apps,
  which will display permissions on your behalf and require an explicit
  user approval.
Attempting to circumvent this may fall under the "prohibited actions"
  clause of the Google Play DDA, which puts your developer account at
  risk for suspension. Don't do it.

A: As far as I know, the only way to "skip" prompts without setting your device in Factory testing-mode. It varies from device to device how that is achieved and usually requires factory reset.
What I would recommend is to have a look at ADB-solution. By using ADB, you can install what ever program you want into the device as long it is in developer mode (which I assume is not a problem) easily from the computer. I know, this is not the solution to solve your specific problem, but I would have a look on that.


text:
Q: Error establishing a database connection in wordpress site , website not opening i had my website using wordpress in cpanel with PHP 7.4 version ,
mysql 5.6.41-84.1 version , i got Error establishing a database connection
tried enable
define('WP_DEBUG', true);

got
Warning: mysqli_real_connect(): The server requested authentication method unknown to the client [mysql_old_password] in /home/user/public_html/abc/wp-includes/wp-db.php on line 1612
Warning: mysqli_real_connect(): (HY000/2054): The server requested authentication method unknown to the client in /home/user/public_html/abc/wp-includes/wp-db.php on line 1612
Warning: mysql_connect(): The server requested authentication method unknown to the client [mysql_old_password] in /home/user/public_html/abc/wp-includes/wp-db.php on line 1643
Warning: mysql_connect(): The server requested authentication method unknown to the client in /home/user/public_html/abc/wp-includes/wp-db.php on line 1643
The server requested authentication method unknown to the client
any clues to resolve this issue


text:
Q: How to avoid postback while clicking the asp imagebutton? How to avoid postback while clicking the asp imagebutton from click event.
When i clicking the button its take postback but i don't want the postback from everyclick event. So, how to write the javascript function while avoiding button click.
ASP:
<asp:ImageButton ID="btnproductadd" runat="server" ImageAlign="AbsMiddle" ToolTip="Add a Product" OnClientClick="return myFunc();"
ImageUrl="../../images/add-icon.gif" CausesValidation="false" Width="15px" Height="15px" />

Vb.Net
Private Sub btnproductadd_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles btnproductadd.Click
    If cboproductgroup.SelectedValue = "" Then
        radnote.Text = "Select the product group."
        radnote.Show()
        Exit Sub
    End If

    If cboproductname.SelectedValue = "" Then
        radnote.Text = "Select the product."
        radnote.Show()
        Exit Sub
    End If

    objdbconn.OpenConn()

    msSQL = " select product_gid from crm_tmp_tproductrequest where product_gid='" & cboproductname.SelectedValue & "'"
    objtbl = objdbconn.GetDatatable(msSQL)
    If objtbl.Rows.Count > 0 Then
        ScriptManager.RegisterStartupScript(Me, [GetType](), "showalert", "alert('This product already added.');", True)
        popwindow(radcalllog)
        Exit Sub
    End If

    msGetcalproductgid = objcmnfunctions.getMasterGID("BCLP")
    If msGetcalproductgid = "E" Then
        objdbconn.CloseConn()
        radnote.Text = "Create sequence code BCLP for product details"
        radnote.Show()
        Exit Sub
    End If

    msSQL = " Insert into crm_tmp_tproductrequest " & _
                    " (tmpproductrequest_gid," & _
                    " product_gid," & _
                    " productuom_gid," & _
                    " productgroup_gid," & _
                    " created_by ) " & _
                    " values (" & _
                    "'" & msGetcalproductgid & "'," & _
                    "'" & hdnproduct_gid.Value & "'," & _
                    "'" & hdnproductuom_gid.Value & "'," & _
                    "'" & cboproductgroup.SelectedValue & "'," & _
                    "'" & Session("user_gid") & "')"
    mnResult = objdbconn.ExecuteNonQuerySQL(msSQL)
    If mnResult = 1 Then
        radnote.Text = "Product added successfully."
        radnote.Show()
        cboproductname.Text = ""
        cboproductgroup.ClearSelection()
    End If
    objdbconn.CloseConn()
    popwindow(radcalllog)
End Sub

I have tried to JavaScript:
<script language="javascript" type="text/javascript">
        function myFunc() {
            alert("My New Function");
            return false;
        }
</script>

But, this function is not working.

A: Replace your <asp:imagebutton> with a normal <img> element and bind and handle a click event on the image. This is done fairly simply with jQuery.
<script>
    $(document).ready(function() {
        $("#imageToClick").on("click", function() {
            alert("Clicked!");
        });
    });
</script>
<img id="imageToClick" />

Obviously you can replace the alert with whatever you want to do with the click.
Regarding the code-behind function, you can't fire that without a postback. Like said in comments, use an ajax call and web api for that.