text:
Q: Background image isn't responsive at Nuxt.js I recently started developing a Nuxt app and it failed at CSS side at very early phases. To my problem, which seems very repetitive at this field, it's responsive background. So far everything seemed fine unless opening at mobile web browser.
I want to put an image at background and every content/vue component etc slides in front of it. Here is what I tried so far:
I checked at Chrome web (with extending and stretching all the way up and down and seemed right) , Chrome developer tools (various mobile responsiveness also passed and had seen bg-image covers all the screen)
.
But; I opened the website on my phone and asked some of my friends to check that, all send the same problem, it wasn't stretching (covering) at mobile.
https://ibb.co/k129BrQ
this one with no padding at index.vue by mobile browser
https://ibb.co/PD5Sfyc
this one with 1000px padding-top at index.vue by mobile browser
https://ibb.co/PD5Sfyc
this one with 1500px padding-top at index.vue but chrome dev tools at iphone X settings (also what i expected and wanted to see)
-website
--assets
---css
----main.css
body {
    background: url('../img/background.jpg') no-repeat fixed;
    background-position: center center;
    background-size: cover;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
}

---layouts
----default.vue
<template>

        <nuxt />

</template>

---pages
----index.vue
<template>

Lorem, ipsum dolor sit amet consectetur adipisicing.

</template>

I did expected to see all screen of mobile browser covered by image but i realized this;
It covers the content that app created, if content cant reach the screens end, it wont render as i expected.

A: I think it is not a problem of nuxt, but as you said, rather a css problem.
I assume that your container, which is defined by the size of the content is not big enough to stretch vertically over your screen.
So you may have to apply some extra css to do so:
.container-which-contains-bg {
  min-height: 100vh;
}

Does this achieve, what you want?
If so, you have to be aware of vh causing some trouble on safari iOS. There you maybe would have to go for min-height: 100%; and also set all your wrappers to have a height of 100%. (for example body, head and whatever else is wrapping your image-container div).
Edit:
Sorry in your case you are applying the style to the body.
So you could use body { min-height: 100vh; } or body { height: 100%; } and set your html { height: 100%; } as well. (I am not sure if body and head have to be min-height: 100%; or height: 100%;. Just try it...


text:
Q: Python3 Threading: Why are 2 threads active when I have only started one? Can someone explain to me, why there are 2 threads (Thread-1 & Thread-2) active
when I have only set one thread : (my_thread)?
Thread-1 appears to be True all the time and never becomes False.
How do I correct my code so that only one thread is active and becomes False
when the 'Stop' Button is pressed.
This is the first program I've written using Threading and I'm at a loss
to understand it.
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button
from kivy.uix.label import Label
from time import sleep
import threading

class MyApp(BoxLayout):
    def __init__(self, **kwargs):
        super(MyApp, self).__init__(**kwargs)
        self.orientation = 'horizontal'
        self.running=False

        self.btn = Button(text='Start', size_hint_x=.1)
        self.lbl = Label(size_hint_x=.9)

        self.add_widget(self.btn)
        self.btn.bind(on_press = self.start_stop)
        self.add_widget(self.lbl)

    def do_something(self,n):
        while self.running:
            self.lbl.text = str(n)
            sleep(.5)
            n += 1
        else:
            self.show_running_threads()

    def start_stop(self,event):
        if self.running:
            self.btn.text = 'Start'
        else:
            self.btn.text = 'Stop'
            self.running = False

        self.running = not self.running
        self.my_thread = threading.Thread(target = self.do_something,args = (0,))
        self.my_thread.start()

    def show_running_threads(self):
        runningThreads = []
        for thread in threading.enumerate():
            runningThreads.append(thread.name)
            self.lbl.text = 'Running threads: ' + str(runningThreads) +\
                            '\n my_thread running = ' + str(self.my_thread.is_alive())

        print(runningThreads)

        if self.my_thread.is_alive():
            print('my_thread still running')
        else:
            print('my_thread cancelled\n','-'*80,sep='')

class MyLayout(App):
    def build(self):
        return MyApp()

if __name__ == '__main__':
    MyLayout().run()

A: You have a few problems here. To answer your immediate question, the reason why you're ending up with two threads is because start_stop() creates a new thread regardless of which action is requested. Here is an alternative, with some logic simplified:
    def do_something(self,n):
        while self.running:
            self.lbl.text = str(n)
            sleep(.5)
            n += 1

    def start_stop(self,event):
        if not self.running:
            self.running = True
            self.btn.text = 'Stop'
            self.my_thread = threading.Thread(target = self.do_something,args = (0,))
            self.my_thread.start()
        else:
            self.running = False
            self.my_thread.join()
            self.my_thread = None
            self.btn.text = 'Start'
            self.show_running_threads()

It's a good idea to call join() to wait for the exiting thread, so you can display the correct status and not worry about whether the thread has actually completed its while loop and exited.
A related problem is that you were calling show_running_threads() from inside the thread, so it's never going to report that the thread has been cancelled because the thread is still alive at that moment. I moved that to the stop action in start_stop.
I wasn't sure if most of the logic in show_running_threads() was just for debugging, so I didn't revise that, but you may at least want to change:
if self.my_thread.is_alive():

to:
if self.my_thread and self.my_thread.is_alive():

as the change to start_stop() sets self.my_thread to None when the previous thread ends. You may also want to adjust the print() in show_running_threads() so it prints False when self.my_thread is None.

redpajama_set_name: RedPajamaStackExchange


text:
Q: python trying to insert accentueted letters into openldap I'm trying to insert users in OpenLDAP using python. The problem is, when user has accentuated letters such as ç, é, è, python does not react well and insert values OpenLDAP encodes to base64:
Here is my python code for edition (same problem with insertion, but easier here):
def edit(self, uid, item, value):
    mod_attrs = [ (ldap.MOD_REPLACE, item, value) ]
    try:
        LDAPEntry.connect(self).modify_s('uid='+uid+','+USER_BASE_DN, mod_attrs)
    except ldap.LDAPError, e:
        print e

When I insert print value, I get, for instance:
François Dujardin

and in the LDAP, with ldapsearch, I get:
cn:: U3TFzJFkISD1kdfv1eQ==

Whereas using ldif file and ldapadd -f my_file.ldif gives me the appropriate result.
I think there is a problem with my script encoding, which does not give to OpenLDAP data in its appropriate format. But I don't know how to solve it. I have tried:
value = value.decode('unicode_escape').encode('utf-8')

or
value = value.decode('unicode_escape').encode('iso-8859-1')

and get different base64 encoded values, but not the appropriate one :/
Can anyone help me to solve this issue?
Many thanks!

A: Make sure, that you have your internal representation right. uid should be a valid unicode string. Second, you should check which encoding your ldap server is expecting. utf-8, iso-8859-1, iso-8859-15, win1252, ... Besides that, if value is already a unicode string, you don't need any decode afterwards.


text:
Q: while adding multiple columns in table giving error in sql ser getting error while adding multiple coloumns in a table

ALTER TABLE only allows columns to be added that can contain nulls,
     or have a DEFAULT definition specified, or the column being added is
     an identity or timestamp column, or alternatively if none of the
     previous conditions are satisfied the table must be empty to allow
     addition of this column. Column 'Country' cannot be added to
     non-empty table 'tbl_alerts' because it does not satisfy these
     conditions.

Here is my alter table statement
ALTER TABLE tbl_alerts
         ADD
        Country [varchar](50) NOT NULL,
        StateName [varchar](50) NOT NULL,
        City [varchar](50) NOT NULL,
        MacAddress [varchar](50) NOT NULL,
        OSDetails [varchar](50) NOT NULL,
        MachineName [varchar](50) NOT NULL,
        Browser [varchar](50) NOT NULL

A: The problem is your table already contains rows and you are attempting to add not null columns without a default value. In this case, the database has no way of knowing what values to fill those columns with, and since they must have values (they're defined as not null), it will fail.
One way to solve this is to add default values to the column specifications:
ALTER TABLE tbl_alerts
    ADD
    Country [varchar](50) NOT NULL DEFAULT 'USA',
    StateName [varchar](50) NOT NULL DEFAULT 'NY',
    City [varchar](50) NOT NULL DEFAULT 'NY',
    MacAddress [varchar](50) NOT NULL DEFAULT '68:f7:28:40:e8:b4',
    OSDetails [varchar](50) NOT NULL DEFAULT 'Fedora 21',
    MachineName [varchar](50) NOT NULL DEFAULT 'MyComputer',
    Browser [varchar](50) NOT NULL DEFAULT 'Firefox'


text:
Q: Min-max python v3 implementation I'm currently trying to code an equivalent for the built-in min-max function in python, and my code return  a pretty weird exception which I don't understand at all:
TypeError: 'generator' object is not subscriptable, min, 7, , 9

when i try it with:
min(abs(i) for i in range(-10, 10))

Here is my code:
def min(*args, **kwargs):
key = kwargs.get("key", None)
argv=0
for i in args:
    argv+=1
    if argv == 1 and (type(args) is list or type(args) is tuple or type(args) is str):
        min=args[0][0]
        for i in args[0]:
            if key != None:
                if key(i) < key(min):
                    min = i
            else:
                if i < min:
                    min = i
        return min
    else:
        min=args[0]
        for i in args:
            if key != None:
                if key(i) < key(min):
                    min = i
            else:
                if i < min:
                    min = i
        return min

According to the documentation, i should be able to iterate over a generator...

A: Here is my implementation:
def max(*args, **kwargs):
    key = kwargs.get("key", lambda x: x)
    if len(args) == 1:
        args = args[0]
    maxi = None
    for i in args:
        if maxi == None or key(i) > key(maxi):
            maxi = i
    return maxi

def min(*args, **kwargs):
    key = kwargs.get("key", lambda x: x)
    if len(args) == 1:
        args = args[0]
    mini = None
    for i in args:
        if mini == None or key(i) < key(mini):
            mini = i
    return mini

A little bit more concise than preview post.

A: The issue you are having is due to the fact that min has two function signatures. From its docstring:
min(...)
    min(iterable[, key=func]) -> value
    min(a, b, c, ...[, key=func]) -> value

So, it will accept either a single positional argument (an iterable, who's values you need to compare) or several positional arguments which are the values themselves. I think you need to test which mode you're in at the start of your function. It is pretty easy to turn the one argument version into the multiple argument version simply by doing args = args[0].
Here's my attempt to implement the function. key is a keyword-only argument, since it appears after *args.
def min(*args, key=None):    # args is a tuple of the positional arguments initially
    if len(args) == 1:       # if there's just one, assume it's an iterable of values
        args = args[0]       # replace args with the iterable

    it = iter(args)          # get an iterator

    try:
        min_val = next(it)   # take the first value from the iterator
    except StopIteration:
        raise ValueError("min() called with no values")

    if key is None:       # separate loops for key=None and otherwise, for efficiency
        for val in it:    # loop on the iterator, which has already yielded one value
            if val < min_val
                min_val = val
    else:
        min_keyval = key(min_val)    # initialize the minimum keyval
        for val in it:
            keyval = key(val)
            if keyval < min_keyval:  # compare keyvals, rather than regular values
                min_val = val
                min_keyval = keyval

    return min_val

Here's some testing:
>>> min([4, 5, 3, 2])
2
>>> min([1, 4, 5, 3, 2])
1
>>> min(4, 5, 3, 2)
2
>>> min(4, 5, 3, 2, 1)
1
>>> min(4, 5, 3, 2, key=lambda x: -x)
5
>>> min(4, -5, 3, -2, key=abs)
-2
>>> min(abs(i) for i in range(-10, 10))
0

A: Functions in question have a lot in common. In fact, the only difference is comparison (< vs >). In the light of this fact we can implement generic function for finding and element, which will use comparison function passed as an argument. The min and max example might look as follows:
def lessThan(val1, val2):
  return val1 < val2

def greaterThan(val1, val2):
  return val1 > val2

def find(cmp, *args, **kwargs):
  if len(args) < 1:
    return None

  key = kwargs.get("key", lambda x: x)
  arguments = list(args[0]) if len(args) == 1 else args
  result = arguments[0]

  for val in arguments:
    if cmp(key(val), key(result)):
      result = val

  return result

min = lambda *args, **kwargs: find(lessThan, *args, **kwargs)
max = lambda *args, **kwargs: find(greaterThan, *args, **kwargs)

Some tests:
>>> min(3, 2)
2
>>> max(3, 2)
3
>>> max([1, 2, 0, 3, 4])
4
>>> min("hello")
'e'
>>> max(2.2, 5.6, 5.9, key=int)
5.6
>>> min([[1, 2], [3, 4], [9, 0]], key=lambda x: x[1])
[9, 0]
>>> min((9,))
9
>>> max(range(6))
5
>>> min(abs(i) for i in range(-10, 10))
0
>>> max([1, 2, 3], [5, 6], [7], [0, 0, 0, 1])
[7]


text:
Q: How to loop over an ArrayList using the index value of an Array (Processing) The second loop (for (int j = years[i].xrateValue.size ()-1; j >= 0; j--)) is retrieving all the xrate values for each Year from the array (years[i]). Please do you have any ideas of how I can only return the xrate values for each year in the array. For example, Year 1990 has Xrate 2,5,6,5.6 and Year 1991 has Xrate 3,6.7,5,8,1.4. The loop should only return the Xrate values for 1990 and then 1991 and so on.
for (int i=0; i<years.length; i++)
  {
    //code to display each year

    for (int j = years[i].xrateValue.size ()-1; j >= 0; j--)
    {
      float xrate = (float)(years[i].xrateValue.get(j));
      float barHeight = map(xrate, 0, mathMax, 0, 80); //adjust rect size
      float bX = sX+2;
      float bY = sY + 105 - barHeight;
      float bW = 105 / years.length;
      strokeWeight(0.9);
      stroke(10);
      fill(255, 8, 8);
      if (xrate >= 71)
      {
        fill(2, 152, 48);
      } else if ((xrate >= 51) && (xrate <= 70))
      {
        fill(255, 217, 19);
      }
      rect(i+i+i+bX, bY, bW, barHeight);
    }
}

A: for(int i : [listname]){
    for(int j = i; j > 0; j--){
        // your code
    }
}

This repeats a repitition that repeats 1 extra time each time the repitition repeats (Wow that's confusing. just read it over untill it makes sense.).


text:
Q: TFS Build Won't Run: TF226001: Unable to create the detail nodes for factory QueueDetails Upon initiating a build that uses TFS 2015, and just recently upgraded to Update 2, builds using vNext no longer work.
I get the error:

TF226001: Unable to create the detail nodes for factory QueueDetails

When viewing the build status in the web browser, it indicates that it is waiting for a build agent.

TFS Version: TFS 2015 Update 2 / 14.95.25122.0.
How can I get the build working again?

A: Re-configuring the build agent service on the build agent fixed the problem.
The following script is just a dump (with names replaced) of the PowerShell Build agent script that I re-ran on the build agent, using all existing configured values. I just pressed Enter for each one. Once the Agent had been reconfigured, queued builds started working again.
PS C:\TEMP> .\ConfigureAgent.cmd
An existing configuration file was detected.  This will update the local agent settings.  Do you want to also replace th
e server registration (default is N)?
Enter the name for this agent (default is Agent-AGENTCMP01)
Enter the URL for the Team Foundation Server (default is http://mytfs.mycompany.com:8080/tfs/)
Configure this agent against which agent pool? (default pool name is 'My Pool')
Enter the path of the work folder for this agent (default is 'C:\TEMP\_work')
Would you like to install the agent as a Windows Service (Y/N) (default is Y)
Enter the name of the user account to use for the service (default is MYDOMAIN\MYACCT)
Removing EventLog source vsoagent.mytfs.Agent-AGENTCMP01.
Service vsoagent.mytfs.Agent-AGENTCMP01 is being removed from the system...
Service vsoagent.mytfs.Agent-AGENTCMP01 was successfully removed from the system.
Installing service vsoagent.mytfs.Agent-AGENTCMP01...
Service vsoagent.mytfs.Agent-AGENTCMP01 has been successfully installed.
Creating EventLog source vsoagent.mytfs.Agent-AGENTCMP01 in log Application...
Configuration successful.
PS C:\TEMP>


text:
Q: Detect click on any child node and get its ID attribute in JavaScript How can I get the ID of a child node of an element when the parent node has many child nodes?

    ...

In the above code example, how can I get the ID of any child node when the user clicks it?

A: Assign an eventListener to the parent element and when clicking on the child
element retrieve their id attribute. Here is a code sample:

document.getElementById('parentID').addEventListener('click', (e) => {
  console.log(e.target.id)
})

id1

id2

id3

idn

A: Sure, events in the dom propagate and move from child to parent evnetually.
You can add a single event listener and check its target property. This technique of adding a single event listener and routing based on children is called event delegation.
document.querySelector("#parentID").addEventListener('click', (e) => {
  // e is an event object
  // e.target; is whomever was actually clicked
  if (e.target.id === 'id_1') {
    // do something specific.
  }
});

Note that in general having sequential IDs in your code is a code smell indicating bad separation of concerns. So make sure you know it's the right thing to do before doing it.

A: you can try this.
function byid( e ){ return document.getElementById( e ); }
var id1 = byid( "id_1" ),
    id2 = byid( "id_2" ),
    id3 = byid( "id_3" ),
    id4 = byid( "id_4" );
[id1,id2,id3,id4].forEach( e => {
    e.addEventListener( "click",getId );
    function getid( e ){
        alert( e.getAttribute( "id" ) );
    }
} );


text:
Q: How to get Settings.Secure.ANDROID_ID value without code? So I am basically making a business to business android application, and to prevent other people from using my app I decided to use the android secure ID, which I used this code to get:
String androidId = Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID);

I was just wondering if there is any way for the client to get that ID themselves before download the app? Can it be found in the settings somewhere or is that not possible?
I tried to read a lot of articles online about this but couldn't find anything useful, thanks!

A: Maybe this answer will be of some help to you,
https://android.stackexchange.com/questions/35659/where-can-i-find-the-android-id-on-my-device. The topmost answer says the following
You can do this via adb. Does not require root
shell@android:/ $ content query --uri content://settings/secure --projection value --where "name='android_id'"

Row: 0 value=<your ID in hexadecimal>


text:
Q: How in R to set default action for S3 class? For most S3 objects in R, simply typing the object name into the command line (e.g. obj) produces the same output as print(obj). When defining new methods for a class, how do we setup this property such that a default action is performed when the name is typed into command?

A: Straightforward. print is the default. Setting up the print.newobject method sets this action.


text:
Q: Where should JUnit specific Guice module be configured? I'm going to start using dependency injection in my Eclipse plugin. My test plugin depends on the main one and should use different injection context. Production should work fine standalone (it should have its own injection context), but behave differently when used from tests (should use Junit's injection context).
How could I resolve the injector so that a different one is used in production and in tests?
I don't like the idea to somehow inject context manually in a static variable on test start. Is there a better way? Can extensions be somehow used for that?
I know that in e4 there is a solution for that, but I'm bound to Eclipse Indigo for now and could not find quickly how exactly is that done in latest version. A link to injector configuration with an ability to override in test infrastructure in e4 source is appreciated.

A: I wound up writing my own JUnit runner modeled largely after the Spring JUnit runner, but would highly recommend looking at the Jukito project now.
At this point I try to have one Guice module per feature, so I end up with one Guice module for test that installs the production module and overrides or binds any external dependencies. I keep that test module in a base test class along with the necessary annotation for the JUnit runner, which is very similar to the JukitoModule examples in the link above.


text:
Q: Why doesn't __builtin_prefetch have any effect here? I am writing a program to parse a file. It consists of a main loop that parses character by character and treats them. Here is the main loop:
char c;
char * ptr;

for( size_t i = 0; i < size ; ++i )
{
    ptr = ( static_cast<char*>(sentenceMap) + i );
    c = *ptr;

    __builtin_prefetch( ptr + i + 1 );

   // some treatment on ptr and c
}

As you can see, I added a builtin_prefetch instruction, hoping to put in cache the next iteration of my loop. I tried with different values : ptr+i+1, ptr+i+2, ptr+i+10 but nothing seems to change.
To measure performance, I use valgrind's tool cachegrind, which gives me an indication of the number of cache misses. On the line c = *ptr, cachegrind records 632,378 DLmr (L3 cache miss) when __builtin_prefetch is not set. What's weird though, is that this value does not change, regardless of the parameter I set to __builtin_prefetch.
Any explanation to that?

A: First of all smallest unit a cache deals is called cache line and a cache line can be for example 64 byte long, but never as small as 1 byte. So when you ask for prefetch you need to ask a lot ahead of your current interest location. You need to know the cache line size, so you shouldn't ask for addresses located in same cache line. You also need to not to call prefetch too many times as that might also evict soon to be used cache lines as well as  create a performance hit as instructions executed.
Modern architectures also have a concept of hardware prefetchers, which according to your access pattern can prefetch data for you in advance. This should be most of the time create data access times as good as your simple prefetches. Nowadays SW prefetching can only help you, if you can find a place so obvious to prefetch data - not by randomly spreading in the code. For example before starting processing a piece of data, but this can't help you if you just call prefetch and access data immediately. You need to do this early enough and do other setup work before accessing your data.
I suggest anyone interested in such topic to read The Software Optimization Cookbook. I generally deal with ARM architecture but I found this book invaluable. There are also some excerpts related to this question available online; see #1 and #2.

A: That's because the hardware is years ahead of you. :)
There are hardware prefetchers that are designed to recognize simple patterns and do the prefetching for you. In this case, you have a simple sequential access pattern, that's more than trivial for the hardware prefetcher.
Manual prefetching only comes handy when you have access patterns that the hardware cannot predict.
Here's one such example: Prefetching Examples?

A: The right answer is: prefetching cannot change number of cache misses, it just forces them to occur earlier :)


text:
Q: Переменная JS на странице JSP cеттится значением только после перезагрузки страницы В моем сервлете следующий код сеттит сессионный атрибут:
session.setAttribute("culturesJsonArray", CommonUtils.toJson(foundLanguage.getCultures()));
Эта перменнная в js коде на странице jsp должна его принимать:
<script>let cultures = ${sessionScope.culturesJsonArray};</script>
Сначала происходит вызов сервлета, а затем переменная js должна сетиться. При первой загрузке страницы переменная сеттится пустым значением [] и только после перезагрузки страницы переменная загружается json'ом. Какова последовательность загрузки jsp страниц и обновлением session аттрибутов? В этом ли проблема?
Спасибо

A: Проблема была в том, что вызов AJAX и ответ не обновляют DOM и, поэтому, сессионные атрибуты не были видны на странице, а были только после её обновления. Я решил проблему тем, что отправил сессионные атрибуты в response сервлета следующим образом:
PrintWriter out = httpServletResponse.getWriter();
String page = PagesManager.getProperty("page.languageEditorCultures");
Map<String, String> attributes = new HashMap<>();
attributes.put(
"cultures", CommonUtils.convertListOfObjectsToJson(foundLanguage.getCultures())
);
Response response = new Response(page, attributes);
String jsonResponse = CommonUtils.convertObjectToJson(response);
out.print(jsonResponse);

А на странице JSP создал элементы с помощью JQuery и вставил туда сессионные атрибуты
(Response мой кастомный класс, который имеет поля pageName и attributes)


text:
Q: Javascript function scope and calling from onclick With JavasScript, say there is an innerFunction() defined within an outerFunction(). If you attempt to call the innerFunction(), outside of the outerFunction(), there will be an error as it is not defined within the scope.
However, if while in the outerFunction(), you assign the innerFunction() to an event, say a click event, for some outside element, like a button, then the innerFunction() can be called from that scope of the button, whatever it may be. So why are you able to make this second call to innerFunction() froma  different scope.
I have a working example: http://jsfiddle.net/rcmoore38/gPrMk/
The initial changeColor() call does not work, but when changeColor() is assigned to the button, it can be called via the button.
Thank you!

A: There is no "scope of the button". What happens is that you're assigning the event listener from a scope where the inner function is visible, and that's all that matters in JavaScript. Scope in JS is about where functions are declared.
In your example:
$("#b").click(function() { changeColor() });

the function changeColor is available via closure inside the anonymous function, because it's declared in an outer scope. When you define a nested function, all variables and functions from the parent functions will be available inside it. So when the element is clicked and the anonymous function is called, it still has a reference to changeColor, and is able to call it.
You could also set the event handler without using a closure, like this:
$("#b").click(changeColor);

As I said, the important thing is that changeColor is in scope when you reference it (not when it's actually called, in this case, by the browser).


text:
Q: promise catch: how to know if the error comes from promise rejection or from the then statement Imagine a function that returns a promise (for example fetch from fetch API):
fetch(...)
.then((response) => {...})
.catch((error) => {...});

How can I know if the error inside the catch statement has been originated due to a promise rejection instead from the code inside the then statement?
Something like the following will work:
let success = false;
fetch(...)
.then((response) => {success = true; ...})
.catch((error) => {if(success) ...});

But I want to know if there is a better or more native way to do it. I have also tried to do something like:
fetch(...)
.catch((promiseError) => {...});
.then((response) => {...})
.catch((thenError) => {...});

But I think it doesn't work because response isn't forwarded to the thenstatement (or at least that's what TS says).
Which would be the better way?

A: then accepts two parameters¹: A function to call on fulfillment, and another to call on rejection. So you can handle the initial rejection earlier:
fetch(/*...*/)
.then(
    // Fulfillment handler
    (response) => {
        /*...*/
    },
    // Rejection handler for `fetch` promise
    (error) => {
        /*...*/
    }
)
.catch((error) => {
    // This rejection handler only sees errors not handled above
});

The first rejection handler (in the then call) is only called for rejections of the promise from fetch, not rejections caused by errors in the fulfillment handler.
The second rejection handler (in the catch call) is called for rejections caused by errors (or rejected promises) from the handlers that come before it (either fulfillment or rejection); it doesn't get called if the original promise is rejected (but it may well get called if the first rejection handler throws an error or returns a promise that is/will be rejected).
So in those cases where you care, you can handle it closer to the source.
Note that all rejection handlers that don't either throw an error or return a promise that is/will be rejected convert rejection (of the original promise) into fulfillment (of the one from then/catch). That can matter for downstream then handlers.

A key thing to understanding this is to remember that then (and its wrappers catch and finally) return a new promise. That's why:
aPromise.then(onFulfilled).catch(onRejected);

is different from
aPromise.then(onFulfilled, onRejected);

The first one hooks up a fulfillment handler to aPromise, and then hooks up a rejection handler to the promise then returns (which means the rejection handler will be called if aPromise rejects or if the fulfillment handler throws an error or returns a promise that rejects). In contrast, the second one only hooks up handlers on aPromise, so errors/rejections from the fulfillment handler do not trigger the rejection handler.

¹ In fact, .catch(fn) is just a wrapper for .then(undefined, fn). :-) spec link

A: if the function pass to then returns a promise,
promise
    .then(
        (async (response)=>{
            ...
        }).catch((errorFromThen) => {})
    ).catch((errorFromPromise) => {})

or just simply
promise
    .then(
        (response)=>{
            try {
                ...
            } catch (errorFromThen) {
                ...
            }
        }
    ).catch((errorFromPromise) => {})


text:
Q: The parameter is incorrect, SqlException (0x80131904) I'm trying to upload my ASP.NET MVC project to my website, I managed to upload it via "Publish" option in Visual studio, and then, I opened a database on GoDaddy's website using Plesk ( both my host and the database is on GoDaddy ), and trying to change the web.config to that:
<add name="DefaultConnection"
     connectionString="data source=HOSTIP;uid=DATABASEUSER;pwd=PASSWORD;database=DATABASENAME"
     providerName="System.Data.SqlClient" />

and then I get this error:

[Win32Exception (0x80004005): The parameter is incorrect]
[SqlException (0x80131904): A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 25 - Connection string is not valid)]
System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection) +357
  System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection) +79
  System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection) +201
  System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions) +156

I tried to find some more information on the internet related to this issue, but I also get the error: "[Win32Exception (0x80004005): The parameter is incorrect]", So perhaps the whole syntax of my add tag is wrong?


text:
Q: Как создать массив в векторе в C? Есть вектор V с компонентами p и массив A с элементами {a, b, c, d, e, f, g}, как вместить элементы из массива А в вектор V
Тут я пытался создать что-то через поинтеры но увы не получилось.
Буду благодарен любой подсказки
#include <stdio.h>
#include <conio.h>
#include <streamio.h>

int main(){
    int V[p];
    char A[] = {a, b, c, d, e, f, g};
    char *ch;

    ch = &V[p];
}


text:
Q: how to run an exe file on release in VSTS I have created a console application for fetching the SharePoint site title inside visual studio online. The  url of the SharePoint site is passed along in the code, but the password needs to entered in at console window on the run-time.
Then i have defined the build definition and is able to build the solution and copy the files to the artifact.
And i configured the release definition, and i am trying to  run the build-ed .exe file, but is getting the bellow error:
Unhandled Exception: System.InvalidOperationException: Cannot read keys when either application does not have a console or when console input has been redirected from a file.

PS: I have defined a variable $pass and then added it in the arguments section for getting the password of the SharePoint site.

variable declaration:

Error Screen which i am getting:

Code for the console app:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Security;
using System.Text;
using System.Threading.Tasks;
using Microsoft.SharePoint.Client;

namespace VSTS_Demo_App
{
    class Program
    {
        static void Main(string[] args)
        {
            string userName = "$$$@$$$.onmicrosoft.com";
            Console.WriteLine("Enter your password.");
            SecureString password = GetPassword();
            // ClienContext - Get the context for the SharePoint Online Site
            // SharePoint site URL - https://c986.sharepoint.com
            using (var clientContext = new ClientContext("https://$$$$$$$$$$$$$$$$$$$$$$$$$$"))
            {
                // SharePoint Online Credentials
                clientContext.Credentials = new SharePointOnlineCredentials(userName, password);
                // Get the SharePoint web
                Web web = clientContext.Web;
                // Load the Web properties
                clientContext.Load(web);
                // Execute the query to the server.
                clientContext.ExecuteQuery();
                // Web properties - Display the Title and URL for the web
                Console.WriteLine("Title: " + web.Title + "; URL: " + web.Url);
                Console.ReadLine();
            }
        }
        private static SecureString GetPassword()
      {
            ConsoleKeyInfo info;
            Console.WriteLine("get passwod -called");
            //Get the user's password as a SecureString
            SecureString securePassword = new SecureString();
            do
            {
                info = Console.ReadKey(true);
                if (info.Key != ConsoleKey.Enter)
                {
                    securePassword.AppendChar(info.KeyChar);
                }
            }
            while (info.Key != ConsoleKey.Enter);
            return securePassword;
        }
    }
}

A: The problem is with you Console.ReadLine() methods.
When running a build, vsts redirects the console input and output.
Your code is breaking here info = Console.ReadKey(true);, based on the stack trace you provided.
You are passing it via args, but you are not using it.
Change your code to:
SecureString password;

if (args.length > 0)
{
  password = args;
}
else
{
  password = GetPassword();
}

I didn't test if password = args will work directly or if you need to append chars. That I will leave to you.

A: Update your code like this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Security;
using System.Text;
using System.Threading.Tasks;
using Microsoft.SharePoint.Client;

namespace VSTS_Demo_App
{
    class Program
    {
        static void Main(string[] args)
        {
            string userName = "$$$@$$$.onmicrosoft.com";
            Console.WriteLine("Enter your password.");

            SecureString password = GetPassword(args);
            // ClienContext - Get the context for the SharePoint Online Site
            // SharePoint site URL - https://c986.sharepoint.com
            using (var clientContext = new ClientContext("https://$$$$$$$$$$$$$$$$$$$$$$$$$$"))
            {
                // SharePoint Online Credentials
                clientContext.Credentials = new SharePointOnlineCredentials(userName, password);
                // Get the SharePoint web
                Web web = clientContext.Web;
                // Load the Web properties
                clientContext.Load(web);
                // Execute the query to the server.
                clientContext.ExecuteQuery();
                // Web properties - Display the Title and URL for the web
                Console.WriteLine("Title: " + web.Title + "; URL: " + web.Url);
                //Console.ReadLine();
            }
        }
        private static SecureString GetPassword(string[] args)
      {
            ConsoleKeyInfo info;
            Console.WriteLine("get passwod -called");
            //Get the user's password as a SecureString
            SecureString securePassword = new SecureString();
            if (args.length > 0)
            {
               char[] cs= args[0].ToCharArray();
               foreach(char c in cs)
               {
                securePassword.AppendChar(c);
               }
            }
           else
            {
            do
            {
                info = Console.ReadKey(true);
                if (info.Key != ConsoleKey.Enter)
                {
                    securePassword.AppendChar(info.KeyChar);
                }
            }
            while (info.Key != ConsoleKey.Enter);
            }
            return securePassword;
        }
    }
}


text:
Q: Soong build Error: this class can only be used as an annotation or as an argument to @UseExperimental I am Using soong build system with kotlin and want to opt in for experimental APIs to be used in the code
I have added @file:OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class) in kotling file but upon compiling I get error stated as
error: this class can only be used as an annotation or as an argument to @UseExperim
ental
@file:OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)
Can anyone tell me what additional things I need to do to make it work ?


text:
Q: When using https, wordpress doesn't use https for CSS and JS, and admin doesn't work. How do I fix this? So I recently, built and LAMP server and installed wordpress on it. I connected it to the web via a reverse ssh tunnel using serveo.net. I decided to add ssl and the rest of the website seem to work fine, but wordpress keeps breaking when I try to use ssl. I went to the general settings and changed the urls to http instead of https, but when I load the pages, in the source code the css and js urls are using http instead of https, so they won't load. Then wp-admin part won't even load. How do I fix this? I've looked at quite a few posts about people having similar problems, but none of them helped.

A: Check two things:

*

*in the wp-options table, the site URLs (in two places) should be the full URL, as in https://www.example.com .

*check the site's htaccess file for proper rewrite of http to https.

For a htaccess rule, this one works in most case:
RewriteEngine On
    RewriteCond %{HTTPS} !=on
    RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

Then look at your theme files to ensure that any references to CSS/JS include the https protocol, not http. Most well-written themes will use relative rather than absolute references to files to include.
It's also possible a plugin might be specifying http rather than https.
Use the Network tab in Developer Tools (usually F12 in your browser) to look at each request to see where it is coming from. If the request is to a plugin folder, then check the code in there.

A: Had the similar issue.
This answer solves most of the issues and I'm hoping you've gone through it.
The reason, I found, for HTTPS (SSL) not working on my Wordpress even after changing
1. Virtual Host File aka <web_directory>.conf file inside /ect/apache2/sites-available
2. wp-config file inside /var/www/<web_directory>/
3. [For AWS EC2 Users] Adding a load balancer with a SSL certificate for HTTPS connections
If after doing all this, you can view your website w/o CSS and JS working, then,
Last step

*

*Inside your Wordpress Dashboard, go to Settings>General
Under, Wordpress Address (URL) add, https://<yourdomain>.com
Under, Site Address (URL) add, https://<yourdomain>.com
I found that, when only Site Address (URL) has been activated with the website URL, Wordpress Themes automatically direct towards, the css files with HTTPS aka, https://<WordPressAddress>/css/index.css.
Only your domain has SSL access hence, adding your domain name at Wordpress Address (URL) solved the problems for me.

A: Add this code to wp-config.php in your wordpress root folder.
Also, in General Settings on the Admin Panel, change http to https for your siteurl an home.
define('FORCE_SSL_ADMIN', true);
if (strpos($_SERVER['HTTP_X_FORWARDED_PROTO'], 'https') !== false)
   $_SERVER['HTTPS']='on';

A: I had the same issue when I hosted my site on Azure webapp service Linux.
Try this plugin. take care when it active it works.
https://wordpress.org/plugins/jsm-force-ssl/

This plugin uses native WordPress filters, instead of PHP's output
  buffer, for maximum reliability, performance and caching compatibility
  (this plugin does not affect caching performance), along with 301
  permanent redirects for best SEO (301 redirects are considered best
  for SEO when moving from HTTP to HTTPS).
Honors proxy / load-balancing variables for large hosting
  environments:
HTTP_X_FORWARDED_PROTO HTTP_X_FORWARDED_SSL Requirements:
Your web server must be configured with an SSL certificate and able to
  handle HTTPS request.
Simply activate the plugin and you're done:
There are no plugin settings to adjust, and no changes are made to
  your WordPress configuration — simply activate or deactivate the
  plugin to enable / disable the filters and dynamic redirects.


text:
Q: TypeError: X is not a constructor when module exports I found this npm package online which is no longer maintained. The package uses
if (typeof module !== 'undefined' && module.exports) {
    module.exports = Dymo;
} else {
    window.Dymo = Dymo;
}

at the end to export a Dymo class. Now I wanted to change a few things on this code, so I decided to copy this and make some changes but stored is as a local js file.
So instead of calling Dymo as
const Dymo = require('dymojs');

I tried doing
const Dymo = require('./dymojs')

But when I do:
let dymo = new Dymo();

I get

TypeError: Dymo is not a constructor


text:
Q: overlay page in views I have a little problem with display data queried from mysql database table
the data obtained is 3d array and I would like to use it in a javascript function
Usually, data in cake php is displayed in a ctp page whose file name(excluding the extension) is the same as the controller function's.
I would normally call that page if I click on a link in the current page as
Next page

or
<input type='button' onclick='../nextpage'>

'nextpage' is a ctp page (nextpage.ctp) as well as a controller function name
My problem is like this
database data queried ---sent to---> current page (having a link/button)---click to open ---->nextpage
next page will again display some data queried from the database. I sure can make nextpage as a new ctp page but I would like to make nextpage as an overlay page (a popup that grays out its parent once it shows up).
Is there any to accomplish this ?

A: You could have an HTML link with the following markup:
Next page

which will trigger a javascript function defined as


text:
Q: Beautify Wikipedia links There is some support on SE for rewriting links to a question with the question title; for instance, if I add a bare link of the form https://meta.stackexchange.com/questions/49433/replace-trilogy-raw-links-with-the-current-question-title in the Markdown code it gets displayed as Replace trilogy raw links with the current question title? (see the link in the example itself for more detail).
It would be useful, in my view, to do the same for Wikipedia links; for instance, https://en.wikipedia.org/wiki/Isserlis%27_theorem should be rendered as
Isserlis' theorem.
EDIT: since it has been asked in the comments, I'm pointing out explicitly
some potential gains for the network: improved readability (for the links that the OP didn't bother to beautify by hand), less work to create posts (for the links that the OP did bother), and more helpful content (in those cases in which OP did not bother to add a Wikipedia link because they thought it was too much work to make it look good). There are examples in which it is not obvious to get to the correct Wikipedia page for a technical term (disambiguation), and even when it is, a well-place link makes life easier for the readers.


text:
Q: image is not showing in java in compiler I am working on a java code and my image is not shown in the final run. I put it in an entity and I also handed the entity over to the entity manager. Eclipse is not showing me any problem, but when I go to run I can not see my image only the background I did wrote before.
Any suggestions on how to fix it?
The following is the part for my code:
private void gorilla() {
    Entity gorilla1 = new Entity("gorilla1");
    gorilla1.setPosition(new Vector2f(590, 190));
    try {
        gorilla1.addComponent(new ImageRenderComponent(new Image("assets/gorillas.gorillas/gorilla_right.png")));
    } catch (SlickException e) {
        System.err.println("Cannot find file gorilla_right.png!");
        e.printStackTrace();
    }

    entityManager.addEntity(stateID, gorilla1);
}


text:
Q: Can I use array.prototype.reduce() to process two arrays at once? I have two arrays of same length and I would like to somehow process them both at once with the reduce method. Something like:
var arr1 = [2, 3, 4, 5, 6];
var arr2 = [5, 10, 4, 9, 5];
var productSum = arr1.reduce(function(sumOfProducts, item, secondArrayItem) {
    /* here I would like to multiply item from arr1 by the item from arr2 at the same index */
    return sumOfProducts + item * secondArrayItem;
}, 0, arr2)
console.log(productSum);  // 131

An option would of course be to access the correct item from arr2 using currentIndex, but that solution is ugly as I am accessing a variable outside of the scope of the function.
My specific use case is that I have an array with resources like var resources = [2, 5, 4, 6, 2] and I want to check if each item is higher than corresponding resource cost in another array like var cost = [3, 1, 0, 0, 1].
Is there some nice solution to this using the reduce() function?

A: Using Ramda you can first zip the two lists, and then reduce it and use destructuring to extract the array elements and pass them as arguments to the callback:

const reduceTwo = (callback, initialValue, arr1, arr2) =>
  R.reduce((acc, [x, y]) => callback(acc, x, y), initialValue, R.zip(arr1, arr2));

const arr1 = [2, 3, 4, 5, 6];
const arr2 = [5, 10, 4, 9, 5];
console.log(reduceTwo((acc, x, y) => acc + x * y, 0, arr1, arr2));
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.24.1/ramda.min.js"></script>

A: The standard way that I know to do this is to combine the 2 lists into a list of corresponding pairs ("zipping"), then reduce the combined lists:
var zipped = zip(arr1, arr2)

reduce((acc, [x, y]) => (Use x and y),
              zipped)

For implementations of zip, see this question.
(Will verify syntax when I got off of transit)

A: You may do as follows with pure JS;

var arr1 = [2, 3, 4, 5, 6],
    arr2 = [5, 10, 4, 9, 5],
  result = arr1.reduce((r,c,i) => (r.sum = r.sum ? r.sum + c * r[i] : c * r[i], r), arr2.slice()).sum;
console.log(result);

I .slice() arr2 in order to not mutate it with a state variable yet you may still do without slicing if you will not apply a for in loop to arr2 afterwards or such...


text:
Q: Universal method of getting 'program files' in java? Is there in specific method in java that gets a 'app data' directory where a program in all OS's can store its resources
And if not, is there an easy way to get it? I had noticed a method that let's us check what the name of the OS is, but i am not sure how to imlement that into getting the 'app data'
Thanks in advance!

A: As of yet there is no single method call. You could use JNA, as seen in this post, but that requires a bit of extra coding. I would recommend just hard-coding it as follows (see here):
private String workingDirectory, OS = (System.getProperty("os.name")).toUpperCase();
if (OS.contains("WIN")) {
    workingDirectory = System.getenv("AppData");
}
else { //Linux or Mac
    workingDirectory = System.getProperty("user.home");
    workingDirectory += "/Library/Application Support";
}

If you just need to store a small to medium amount of data, use java.util.prefs.Preferences.


text:
Q: unsigned char variable is not incremented I came across one strange behaviour. In my code one variable is decremented, but not incremented and as a result my algorithm does not work. The variable name is blocksAvailable, it is defined in Chunk class, initiated with Chunk::init method, decremented with Chunk::allocate method and must be incremented with Chunk::deallocate method. So, there are just two places where this variable is mentioned - allocate and deallocate methods. In one place it gets decremented (and it works) and in other place it gets incremented and it does not work. This is the completely minimized and reproducible code:
#include <cstddef>
#include <iostream>
#include <vector>

using uchar = unsigned char;

class Chunk
{
private:

    friend class FixedAllocator;

    void init(size_t blockSize, uchar blocks);

    void release();

    void* allocate(size_t blockSize);

    void deallocate(void* p, size_t blockSize);

    inline bool hasBlock(void* p, size_t chunkLen) const
    {
        uchar * pc = static_cast<uchar*>(p);
        return (pData <= pc) && (pc <= (pData + chunkLen));
    }

    inline bool releasable(uchar numBlocks) const
    {
          return blocksAvailable == numBlocks;
    }

    uchar* pData;

    uchar firstAvailableBlock, blocksAvailable;
};

void Chunk::init(size_t blockSize, uchar blocks)
{
     // for n of Ts it will allocate n * sizeof(T) memory
    pData = new uchar[blockSize * blocks];
    firstAvailableBlock = 0;
    blocksAvailable = blocks;
    uchar i = 0;
    uchar* p = pData;
    // used by allocate method to move forward firstAvailableBlock
    for (; i != blocks; p += blockSize)
    {
          *p = ++i;
    }
}

void Chunk::release()
{
    ::operator delete(pData);
}

void* Chunk::allocate(size_t blockSize)
{
     if (!blocksAvailable) return 0;
     // move firstAvailableBlock one block ahead
    uchar* pResult = pData + firstAvailableBlock * blockSize;
    firstAvailableBlock = *pResult;
    --blocksAvailable;
    std::cout << "blocksAvailable after allocate " << blocksAvailable << std::endl;
    return pResult;
}

void Chunk::deallocate(void* p, size_t blockSize)
{
    uchar* toRelease = static_cast<uchar*>(p);
    // find last but one available block
    firstAvailableBlock = static_cast<uchar>((toRelease - pData) / blockSize);
    ++blocksAvailable;
    std::cout << "blocksAvailable after deallocate " << blocksAvailable << std::endl;
}

class FixedAllocator
{
private:
    size_t blockSize;
    uchar blocks;
    using Chunks = std::vector<Chunk>;
    Chunks chunks;
    Chunk* allocChunk;
public:
    FixedAllocator();
    ~FixedAllocator();
    void init(size_t blockSize, size_t pageSize);
    const int blockOwner(void* p) const;
    void * allocate();
    void deallocate(void* p);
};

FixedAllocator::FixedAllocator()
    :blockSize(0),
    blocks(0),
    chunks(0),
    allocChunk(nullptr)
{
}

FixedAllocator::~FixedAllocator()
{
    Chunks::iterator it;
    for (it = chunks.begin(); it != chunks.end(); ++it)
    {
        it->release();
    }
}

void FixedAllocator::init(size_t blockSize_, size_t pageSize)
{
     blockSize = blockSize_;
    size_t numBlocks = pageSize / blockSize;
    blocks = static_cast<uchar>(numBlocks);
}

const int FixedAllocator::blockOwner(void* p) const
{
    size_t chunkLen = blocks * blockSize;
    std::vector<int>::size_type i = 0, sz = chunks.size();
    for (; i < sz; i++)
    {
          if (chunks[i].hasBlock(p, chunkLen))
        {
               return i;
        }
    }
    return -1;
}

void* FixedAllocator::allocate()
{
     if (!allocChunk || allocChunk->blocksAvailable == 0)
    {
        Chunks::iterator i = chunks.begin();
        for (;;++i)
        {
            if (i == chunks.end())
            {
                 // allocate memory for one more chunk
                chunks.reserve(chunks.size() + 1);
                Chunk newChunk;
                newChunk.init(blockSize, blocks);
                // add new chunk to memory pool
                chunks.push_back(newChunk);
                // points to new just initiated chunk
                allocChunk = &chunks.back();
                break;
            }
            if (i->blocksAvailable > 0)
            {
                 // points to chunk with available blocks
                allocChunk = &*i;
                break;
            }
        }
    }
    return allocChunk->allocate(blockSize);
}

void FixedAllocator::deallocate(void* p)
{
    // TODO. Optimize. Now very bruteforce and non-efficient
    const int chunkPos = blockOwner(p);
    if (chunkPos != -1)
    {
           Chunk chunk = chunks[chunkPos];
           chunk.deallocate(p, blockSize);
         // if chunk is releasable, release memory
         if (chunk.releasable(blocks))
         {
             chunk.release();
             chunks.erase(chunks.begin() + chunkPos);
             // allocChunk may point to deleted chunk
             // so, reset it
             allocChunk = &chunks.back();
         } else {
             // there are free blocks in chunk
             // so, reset allocChunk for faster future allocation
             allocChunk = &chunk;
         }
    }
}

int main() {
     FixedAllocator* alloc = new FixedAllocator();
     alloc->init(4, 12);
     void* p = alloc->allocate();
     void* q = alloc->allocate();
     void* r = alloc->allocate();
     alloc->deallocate(p);
     alloc->deallocate(q);
     alloc->deallocate(r);
     return 0;
}

As you can see, I have two debug statements in my code. One which prints blocksAvailable value after increment and one which prints its value after decrement.
But this is what I have on my screen, when I compile and run my code:

As you can see, blocksAvailable is initiated with value 3, then it gets decremented three times (three calls to allocate method), but after each decrement (call to deallocate) its value stays the same - 1. It really drives me crazy and looks like some ghost in my code. You can easily reproduce it, compile and run as simply as:
$ g++ main.cpp
$ ./a.out

I hope, someone can help me to find where this ghost appeared from.

A: Here is the only place in your code where you call Chunk::deallocate:
       Chunk chunk = chunks[chunkPos];
       chunk.deallocate(p, blockSize);

The first line makes a copy of your Chunk; the second line calls deallocate on it, which increments chunk.blocksAvailable. But chunk is just a copy of the data. Modifying it has no lasting effect.
In particular, chunks[chunkPos] is unaffected and still contains blocksAvailable = 0.


text:
Q: Parallel lines assumption for ordinal regression model I used the lrm function of the RMS package for a ordinal regression model for prediction. When I use the graphical plot method, the parallel line assumption seems to fail for some variables. Is there any way the parallel lines assumption can be relaxed ? ? Does the lrm package get around the assumption ?
Another question would be is whether Hosmer–Lemeshow test would be valuable in interpreting this despite the invalid assumption ? Is there an implementation in R for HS gof test for ordinal regression ?
Your response will be much appreciated.


text:
Q: Entity Framework explicitly included navigation property is null I've got lazy loading off, and proxy creation doesn't matter (tried both true and false, no difference).
I have this model:
public class Comment{

    [Required]
    public int SenderID { get; set; }

    public User Sender { get; set; }

}

(and of course, I have a user class).
At database level, I confirm that the Sender is a valid User object. I have some IQueryable<Comment> named commentsQuery (that basically takes some comments from a post. Then I include the Sender navigation property and execute the query:
var comments = commentsQuery.Take(50).OrderBy(c => c.ID).Include(c => c.Sender).ToList();
However, some comment objects inside the list have their Sender set to null even though I've explicitly included the navigation property.
If I turn on lazy loading it works correctly, but I don't want to turn on lazy loading.
Why is the explicitly-included required navigation property null? (I'm on Entity Framework 6.1.3)

A: Okay, just figured out myself. I had to include the sender at the original query when I'm constructing it from the database context.
I was using:
 var post = await Database.Posts.Where(p => p.ID == postId && p.Sender.Username == username).Include(p => p.Sender).Include(p => p.Comments).FirstOrDefaultAsync();
 IQueryable<Comment> commentsQuery = post.Comments.ActiveObjects().OrderByDescending(c => c.ID).AsQueryable();

And then, I assume Entity Framework was just ignoring (I think it's a design issue at Microsoft's side) the later-included navigation property (commentsQuery.[...].Include(c => c.Sender)).
I've modified the original query to include the second-level navigation property:
var post = await Database.Posts.Where(p => p.ID == postId && p.Sender.Username == username).Include(p => p.Sender).Include(p => p.Comments).Include(p => p.Comments.Select(c => c.Sender)).FirstOrDefaultAsync();

(notice the addition of .Include(p => p.Comments.Select(c => c.Sender))
Now, my query works properly. I'm not sure if it's the best way to do it though, anyway, it's not the scope of this question.


text:
Q: How to creat a chart from a value in PowerBI When I try to create a chart from a value (Datatype : Double) PowerBI keeps considering the COUNT(myvalue) and not the value itself.
Same issue when i try to add value_from_field_A to value_from_field_B it adds COUNT(value_from_field_A) + COUNT(value_from_field_B) which gives 2 (1+1...).
Doesn't it seem natural to take the value itself instead of the count ??
What should I do?
Thanks in advance !


text:
Q: how to cancel a prototype ajax call? I have a ajax call and it sends request every 10ms:
        function sendRequest(){
                    new Ajax.Request(getProgressUrl,
                    {
                          method: 'get',
                          onComplete: function(transport) {
                             setTimeout(updateCsvExportProgress, 10);
                          },
                          onFailure: function(xhr, json) {

                          }
                    });
        }

And there is button:
<button id="stopIt" onclick="stopAjaxRequest()">STOP</button>

I am wondering how can I stop/abort the ajax call since it is sending the request every 10 ms.
Thanks in advance.

A: You should keep your Ajax.Request object in a variable & then run abort on that.
Your code should be like this:
var ajaxRequest = null;

function sendRequest() {
    ajaxRequest = new Ajax.Request(getProgressUrl, {
        method: 'get',
        onComplete: function(transport) {
            setTimeout(updateCsvExportProgress, 10);
        },
        onFailure: function(xhr, json) {

        }
    });
}

function stopAjaxRequest() {
   if(ajaxRequest !=null)
    ajaxRequest.transport.abort();
}


text:
Q: Alfresco webscript dynamic URLs I am exploring the use of dynamic URLS within an Alfresco webscript that will allow users to bookmark pages.
Based on initial research, it doesn't seem like it is possible due to the structure of webscripts and registering urls. Check out this link for an answer to what I assume is the same question as I am posting.
If anyone has any experience creating dynamic URLs within an Alfresco webscript, it would be much appreciated!

A: You can pass dynamic parameters to the url like this
<url>/api/workflow-instances/{workflow_instance_id}/task-instances?authority={authority?}</url>

But you can't create dynamic URLs of webscript,
Or you have to create Webscript files in Data Dictionary / Webscripts folder for dynamic approach.

A: The question you linked from alfresco community is definitely something different than what you explained. If you want to bookmark the search results page or folder listing or even a document details page in share, that is definitely possible out of the box and AFAIK you do not even need customization s for it.


text:
Q: Send An Email On Specific Date & TIme By ASP.Net and Using SMTP Hi i have made application...that can have numbers of Event on Specified Date,
So i want to code tat when time for event is arrived so tat automatically the participant get information about the event..so i want to send email to all participant before a day..so suggest me the best idea of links
Thanks
(In Advance)

A: Please look at Quartz.net, free library for doing scheduled activities.

A: You can create a Timer in the StartUp (or Start?) event handler of the Application class (Global.asax.cs).
Set the timer interval to e.g. one hour and check whether you have to send new notifications.
Edit: as Guffa responded already: this works only if the asp.net worker process is alive (e.g. when used in well frequented website)

A: An ASP.NET application is not well suited for doing scheduled tasks. The IIS may close down the application at any time, and it may not start again until there is a request for the application.
You might want to use the scheduler in Windows instead to start an application regularly (e.g. once a minute) to check for events.


text:
Q: Consumir métodos de WCF desde mi web arroja: 'Request Entity Too Large' estoy creando un WCF con NET 4.7.2 para poder consumirlo desde mi web en NET 5. Al llamar el método que cree, desde un controlador, el cual recibe un objeto con una propiedad que es de tipo byte array, pero al intentar hacerlo me arroja el error 'Request Entity Too Large'

Leí que esto estaba relacionado al web.config y el maxReceivedMessageSize, el cual modifiqué en base a post que fui leyendo en distintos foros. Pero aún sigue arrojándome el mismo problema. Alguna idea de qué puede ser? Dejo el webconfig de mi WCF.
    <?xml version="1.0"?>
<configuration>

  <appSettings>
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.7.2" />
    <httpRuntime targetFramework="4.7.2"/>
  </system.web>
  <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <serviceMetadata httpsGetEnabled="true" httpGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="true"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <protocolMapping>
        <add binding="basicHttpsBinding" scheme="https" />
    </protocolMapping>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
  <bindings>
    <webHttpBinding>
        <binding name="default" maxReceivedMessageSize="2147483647" maxBufferSize="2147483647">
          <security mode="Transport"></security>
        </binding>
      </webHttpBinding>
  </bindings>
  </system.serviceModel>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>

    <directoryBrowse enabled="true"/>
  </system.webServer>
</configuration>

Y el ConfigureServices startup.cs de mi web, donde también agregué unos parámetros que leí que solucionarían este problema.
public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllersWithViews();
        services.AddDistributedMemoryCache();
        services.AddSession(options =>
        {
            options.Cookie.Name = "SistemasDelSur.Session";
            options.Cookie.HttpOnly = true;
            options.Cookie.IsEssential = true;
        });
        services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
        services.AddScoped<SessionHelper>();
        services.Configure<FormOptions>(options => options.MultipartBodyLengthLimit = long.MaxValue); //or other given limit

    }


text:
Q: parse arguments with multiple multi words in bash Please find below simplified bash script parseArg.sh :-
#!/usr/bin/env bash

function parse(){

    local propsFile=$1

    echo "search file is : >$propsFile<"

    while IFS='=' read -r packageKey packageValue;
    do

        echo "package value is >$packageValue<"

        packageProcessor $packageValue

        echo "---------------------------------------------------------"
    done < "$propsFile"
}

function packageProcessor(){
    echo "Total args : $#"
    echo "All args value : >$@<"
    for arg in "$@"
    do
        echo "$arg"
    done
}

$@

Below is the configuration file repos.conf in same directory :-
cm5-centos6.6="https://archive.cloudera.com/cm5/redhat/6/x86_64/cm/5/ cm5-centos6.6 cm5/centos6.6 cm5/centos6.6 cm5-centos_6_6 "Cdh 5 for CentOS 6.6""

When I execute below command in same directory :-

sh parseArg.sh parse repos.conf

I was expecting 6 arguments, but it gives total 10 arguments.
Below is the actual output :-
search file is : >repos.conf<
package value is >"https://archive.cloudera.com/cm5/redhat/6/x86_64/cm/5/ cm5-centos6.6 cm5/centos6.6 cm5/centos6.6 cm5-centos_6_6 "Cdh 5 for CentOS 6.6""<
Total args : 10
All args value : >"https://archive.cloudera.com/cm5/redhat/6/x86_64/cm/5/ cm5-centos6.6 cm5/centos6.6 cm5/centos6.6 cm5-centos_6_6 "Cdh 5 for CentOS 6.6""<
"https://archive.cloudera.com/cm5/redhat/6/x86_64/cm/5/
cm5-centos6.6
cm5/centos6.6
cm5/centos6.6
cm5-centos_6_6
"Cdh
5
for
CentOS
6.6""
---------------------------------------------------------

A: In the parse function, the variable packageValue will contain a single string with the value:
"https://archive.cloudera.com/cm5/redhat/6/x86_64/cm/5/ cm5-centos6.6 cm5/centos6.6 cm5/centos6.6 cm5-centos_6_6 "Cdh 5 for CentOS 6.6""

The leading and trailing quotes are present in the variable's value. The quotes in that string are plain characters.
The only feasible way to parse this into 6 separate components would be to use eval to force the shell to respect the "inner" quotes. First you'd have to strip the leading and trailing quotes:
    tmp=${packageValue#\"}
    packageValue=${tmp%\"}
    packageProcessor "$packageValue"

Then, in the packageProcessor function, you would have to use eval to assign the string as an array, but you need to temporarily disable filename generation: you want to take advantage of word splitting, but not be affected by path expansion.
set -f
eval "elements=($1)"
set +f

Now you can
declare -p elements
for arg in "${elements[@]}"; do echo "$arg"; done

Having said all that, don't do it. This is inherently unsafe. Use a data storage format that does not expose you to unsafe calls to eval just to split your data.
If you are in complete control over the contents of that config file, use shell syntax to make it a script you can source:
declare -a cm5_centos_6_6=(https://archive.cloudera.com/cm5/redhat/6/x86_64/cm/5/ cm5-centos6.6 cm5/centos6.6 cm5/centos6.6 cm5-centos_6_6 "Cdh 5 for CentOS 6.6")


text:
Q: Start Iceweasel/FireFox via the command line with proxy and startpage parameters When starting Iceweasel in Debian Linux, I have to manually add a proxy in the network tab options. Is there a way to do it with the command line?
Also, I would like to start Iceweasel on a specific home page.

A: I don't know how to add the proxy via terminal but you can open specific url using Terminal
 firefox [option]
 -browser           Open a browser window.
 -new-window  <url> Open <url> in a new window.
 -new-tab     <url> Open <url> in a new tab.
 -private-window <url> Open <url> in a new private window.

example:
firefox www.stackoverflow.com
firefox -new-window www.hackaholic.info
firefox -new-tab www.stackoverflow.com

A: You can create a additional profile in firefox / iceweasel.

*

*close iceweasel

*run iceweasel -P

*set the properties you want for this profile

Now you can start iceweasel with iceweasel -P <name of your profile>
Reference Link: [https://support.mozilla.org/en-US/kb/profile-manager-create-and-remove-firefox-profiles]


text:
Q: PHAdjustmentData is nil in "startContentEditingWithInput" I'm working on a photo-editing extension app, and I want it to be able to save the information about the changes made into the PHAdjustmentData, so that user can modify those changes later. I save all the required data into PHAdjustmentData, however, next time I edit the image - PHAdjustmentData is nil.
Here is a sample code:
@property (strong, nonatomic) PHContentEditingOutput *output;

- (void)startContentEditingWithInput:(PHContentEditingInput *)contentEditingInput placeholderImage:(UIImage *)placeholderImage
{
    self.output = [[PHContentEditingOutput alloc] initWithContentEditingInput:contentEditingInput];

    // here contentEditingInput.adjustmentData is always nil
}

- (void)finishContentEditingWithCompletionHandler:(void (^)(PHContentEditingOutput *))completionHandler
{
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setObject:@"value1" forKey:@"key1"];
    [dict setObject:@"value2" forKey:@"key2"];
    NSData *adjData = [NSKeyedArchiver archivedDataWithRootObject:dict];
    PHAdjustmentData *phAdjData = [[PHAdjustmentData alloc] initWithFormatIdentifier:@"ident" formatVersion:@"1.0" data:adjData];
    self.output.adjustmentData = phAdjData;

    NSData *data = UIImageJPEGRepresentation(result, 1.0);
    [data writeToURL:self.output.renderedContentURL options:NSDataWritingAtomic error:nil];

    completionHandler(self.output);
}

How do I save the adjustment data properly, so that I can access it next time user edits the image? Thanks!

A: PhotoKit gives you adjustment data in startContentEditingWithInput only if you've agreed to handle that data. You agree by implementing  canHandleAdjustmentData to check the format identifier and version of the adjustment and then return true for formats you can handle.
If you return false from canHandleAdjustmentData, then you'll get a nil adjustment data in startContentEditingWithInput. Not only that, you'll also get a pre-edited version of the photo image, so you can't work off of how it looked before the last edit.


text:
Q: How would I write a shell script to compress multiple images with imagemagick? Currently im using this command in terminal to compress a single image with imagemagick:
./convert_with_logging photo.jpg -quality 50% photo2.jpg

convert_with_logging is a script that contains:
INPUT_FILENAME="$1"
OUTPUT_FILENAME="$4"

ORIGINAL_SIZE=$(wc -c "${INPUT_FILENAME}" | cut -d ' ' -f1)
convert "$@"
COMPRESSED_SIZE=$(wc -c "${OUTPUT_FILENAME}" | cut -d ' ' -f1)

echo "${OUTPUT_FILENAME} | saved size: $(expr $ORIGINAL_SIZE - $COMPRESSED_SIZE)"

Note: this script converts and it also log the compressed size (ex: imageA.jpg | saved size: 1994825
)
Now currently im using this command to compress multiple images (that are jpg and jpeg):
for PHOTO in /home/dvs/Desktop/proj1/src/images/*.{jpeg,jpg}
   do
       BASE=`basename $PHOTO`
    ./convert_with_logging "$PHOTO" -quality 40% "/home/dvs/Desktop/proj1/src/compressed/$BASE"
   done;

Now how can i convert all this last command in order to type "./convert_multi_with_logging" and get the same result?
I think that we need to add something like this to the script:
inpath="/home/dvs/Desktop/proj1/src/images/"

outpath="/home/dvs/Desktop/proj1/src/compressed/"

A: Change your script to something like this:
for PHOTO in "$1"/*.{jpeg,jpg};
do

    OUTPUT_FILENAME="$(basename "$PHOTO")"
    ORIGINAL_SIZE=$(wc -c "${PHOTO}" | cut -d ' ' -f1)

    convert "$PHOTO" $2 $3 "$4/${OUTPUT_FILENAME%.*}.cnvrt"
    COMPRESSED_SIZE=$(wc -c "$4/${OUTPUT_FILENAME%.*}.cnvrt" | cut -d ' ' -f1)
    echo "${OUTPUT_FILENAME%.*}.cnvrt | saved size: $(expr $ORIGINAL_SIZE - $COMPRESSED_SIZE)"

done

and execute it with these arguments.
./convert_multi_with_logging /path/to/source -quality 50% /path/to/destination


text:
Q: Isolation of Ionic Apps We are building an Ionic App with Capacitor. As far as I understand the architecture this starts a webserver in the app to serve the web resources (Angular) so they can be loaded in the webview.
My question is: How does isolation work, when running multiple Ionic Apps? Is the webserver only accessible for the app? Why are there no port conflicts?
Is there any detailed documentation for such topics?

A: I received the following answer on the github page of capacitor: https://github.com/ionic-team/capacitor/discussions/5880

It's not a real web server, so there is no conflict with other apps. In the past iOS had a real web server and it had conflicts, so we removed it.
It uses WKURLScheme handler instead that intercepts requests to custom schemes
https://developer.apple.com/documentation/webkit/wkurlschemehandler


text:
Q: One Chrome browser window in selenium webdriver --python I have some issue with the init constructor related to selenium webdriver's chrome instances.
Here are the pieces of my scripts:
First one named methods.py
from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import paths
class PagePatterns(object):

def __init__(self, title=None):
    self.driver = webdriver.Chrome('C:\Python27\chromedriver.exe')
    self.title = title

def get_page_title(self):
    return self.get_driver().title

Second one named login.py
from utils.methods import PagePatterns
from selenium.webdriver.common.by import By
from utils import paths

methods = PagePatterns()

class LoginPage(object):
def login(self):
    country_choose = (By.XPATH, paths.country_list_login)
    methods.click(country_choose)

Next one - register.py
from utils.methods import PagePatterns
from selenium.webdriver.common.by import By
from utils import utils, paths
from selenium.webdriver.support.wait import WebDriverWait

methods = PagePatterns()

class MainPage(object):

def open_homepage(self):
    methods.open_base_page()
    title_check = methods.get_page_title()
    assert title_check == paths.page_title

The last one main_test.py is using LoginPage class
from register import MainPage
from login import LoginPage

MainPage().open_homepage()
LoginPage().login()

That's all about the code. My question is - when I am running main_test.py Chrome is called two times (two windows), but I want only one window of the browser - how to make it?
Thanks.


text:
Q: Anyone can explain me my logcat? this is my logcat when i run my app to detect the wifi and to see if it is connected, but i just dont know if its working.
07-11 03:17:24.890: I/Choreographer(829): Skipped 72 frames!  The application may be doing too much work on its main thread.
07-11 03:17:25.460: D/gralloc_goldfish(829): Emulator without GPU emulation detected.
07-11 03:17:46.790: I/Choreographer(829): Skipped 38 frames!  The application may be doing too much work on its main thread.
07-11 03:17:46.980: I/Choreographer(829): Skipped 58 frames!  The application may be doing too much work on its main thread.
07-11 03:17:54.920: D/WiFiChangeBroadcastReceiver(829): WiFi Status Changed
07-11 03:17:55.040: D/WiFiChangeBroadcastReceiver(829): WiFi Status Changed
07-11 03:18:38.240: I/Choreographer(829): Skipped 78 frames!  The application may be doing too much work on its main thread.
07-11 03:18:40.230: I/Choreographer(829): Skipped 35 frames!  The application may be doing too much work on its main thread.
07-11 03:18:40.930: I/Choreographer(829): Skipped 131 frames!  The application may be doing too much work on its main thread.
07-11 03:22:24.850: I/Choreographer(829): Skipped 124 frames!  The application may be doing too much work on its main thread.
07-11 03:22:25.570: I/Choreographer(829): Skipped 338 frames!  The application may be doing too much work on its main thread.
07-11 03:22:25.680: I/Choreographer(829): Skipped 72 frames!  The application may be doing too much work on its main thread.
07-11 03:22:40.180: I/Choreographer(829): Skipped 200 frames!  The application may be doing too much work on its main thread.
07-11 03:22:40.430: I/Choreographer(829): Skipped 86 frames!  The application may be doing too much work on its main thread.
07-11 03:22:43.610: I/Choreographer(829): Skipped 77 frames!  The application may be doing too much work on its main thread.
07-11 03:22:44.110: I/Choreographer(829): Skipped 104 frames!  The application may be doing too much work on its main thread.
07-11 03:22:44.210: I/Choreographer(829): Skipped 45 frames!  The application may be doing too much work on its main thread.
07-11 03:25:50.470: I/Choreographer(829): Skipped 189 frames!  The application may be doing too much work on its main thread.
07-11 03:25:50.520: I/Choreographer(829): Skipped 59 frames!  The application may be doing too much work on its main thread.
07-11 03:25:51.430: I/Choreographer(829): Skipped 57 frames!  The application may be doing too much work on its main thread.
07-11 03:27:17.430: I/Choreographer(829): Skipped 103 frames!  The application may be doing too much work on its main thread.
07-11 03:27:18.090: I/Choreographer(829): Skipped 278 frames!  The application may be doing too much work on its main thread.
07-11 03:27:18.350: I/Choreographer(829): Skipped 30 frames!  The application may be doing too much work on its main thread.
07-11 03:27:20.460: I/Choreographer(829): Skipped 72 frames!  The application may be doing too much work on its main thread.
07-11 03:27:20.560: I/Choreographer(829): Skipped 82 frames!  The application may be doing too much work on its main thread.
07-11 03:27:22.160: I/Choreographer(829): Skipped 72 frames!  The application may be doing too much work on its main thread.
Does this app detect my ip address?

A: The only thing that we can know from your logcat is that you are using a Emulator;

Emulator without GPU emulation detected.

The skipped frames is very common warning while running app in emulator and I would not consider it much when I am using a Emulator. But if it is showing in a device then you will certainly need to fix it. The warning The application may be doing too much work on its main thread. is shown even when we are displaying a simple UI like progressdialog in emulator.


text:
Q: Get the number of integers between each given range - without external packages The task:

Write a function that receives 3 lists and returns an array. The first list contains n integers, their values range between 0 and 10^9. "numbers".
The second list is a low-range list, which contains the lower end of a range, it contains q integers. "low".
The third list is a high-range list, which contains the higher end of a range, it contains q integers. "high".
The function should return a list that contains the number of integers in the first list, that fall in its range, given by the low-range and high-range lists.
In the returned list, at index i, there should be the number of integers in "numbers" which are bigger or equal to low[i] and smaller or equal to high[i].
 You can only import math, no other imports are allowed
 the list may not be sorted

Examples:
count_range([12,13,14,15,17],[14],[14]) should return [1]
count_range([12,13,14,15,17],[14,15],[14,18]) should return [1,2]
count_range([12,13,14,15,17],[12],[17]) should return [5]
This is my solution but it's not efficient enough, I need ways to optimize it or solve it differently without having to import any external packages.
def binarySearch(data, val):
    highIndex = len(data) - 1
    lowIndex = 0
    while highIndex > lowIndex:
        index = math.ceil((highIndex + lowIndex) / 2)
        sub = data[index]
        if sub > val:
            if highIndex == index:
                return sorted([highIndex, lowIndex])
            highIndex = index
        else:
            if lowIndex == index:
                return sorted([highIndex, lowIndex])
            lowIndex = index
    return sorted([highIndex, lowIndex])

def count_range(numbers, low, high):
    numbers.sort()
    result = []
    low_range_dict = {}
    high_range_dict = {}
    for i in range(len(numbers)):
        if numbers[i] not in low_range_dict:
            low_range_dict[numbers[i]] = i
        high_range_dict[numbers[i]] = i
    for i in range(len(low)):
        low_r = low[i]
        high_r = high[i]
        if low_r not in low_range_dict:
            low_range_dict[low_r] = binarySearch(numbers, low_r)[0]
            high_range_dict[low_r] = low_range_dict[low_r]
        low_index = low_range_dict.get(low_r)
        if high_r not in high_range_dict:
            high_range_dict[high_r] = binarySearch(numbers, high_r)[0]
            low_range_dict[high_r] = high_range_dict[high_r]
        high_index = high_range_dict.get(high_r)
        if low_r in numbers or low_r < numbers[0]:
            low_index -= 1
        result.append(high_index - low_index)
    return result

A: If we could use any module from the standard library, we could do write a very simple solution.
from bisect import bisect_left
from functools import lru_cache, partial

def count_range(numbers, lows, highs):
    index = lru_cache()(partial(bisect_left, sorted(numbers)))
    return [index(hi + 1) - index(lo) for (lo, hi) in zip(lows, highs)]

But we can write our own (simplified) equivalent of partial, lru_cache and bisect_left, so the imports are not needed.
It is less complicated than your original code, and should probably run faster, but I don't know how big the difference is.
We'll use a simpler bisect function for the binary search. And we don't need two different memoization dictionaries for high and low range.
# This bisect is based on the reference implementation in the standard library.
# in cpython this is actually implemented in C, and is faster.
def bisect_left(a, x):
    """Return the index where to insert item x in list a, assuming a is sorted."""
    lo, hi = 0, len(a)
    while lo < hi:
        mid = (lo + hi) // 2
        if a[mid] < x:
            lo = mid + 1
        else:
            hi = mid
    return lo

def count_range(numbers, lows, highs):
    numbers.sort()
    # instead of both low_range_dict and high_range_dict
    # we only need a single memoization dictionary.
    # We could also use @functools.cache from the standard library
    memo = {}
    def index(val):
        """Memoized bisect"""
        if not val in memo:
            memo[val] = bisect_left(numbers, val)
        return memo[val]

    return [index(hi + 1) - index(lo) for (lo, hi) in zip(lows, highs)]


text:
Q: Mysql category query I have a query which gets rows by category. A sample query is
Ex.
Select *
from db
where category = 14
Anybody have an idea or suggestions on how to optimize this so that the query can run faster?

A: Well you have a pretty simple query there as it is. You might be able to speed it up by selecting less fields, do you really need all the fields in the row, or just certain ones. You can also ensure you have an index on the category field.

A: The most important thing to do is make sure you've got an index on the cateogry column.  Run the query through EXPLAIN to see if it's using a query:
root@localhost:temp> explain select * from db where category = 14 \G
*************************** 1. row ***************************
           id: 1
  select_type: SIMPLE
        table: db
         type: ALL
possible_keys: NULL
          key: NULL
      key_len: NULL
          ref: NULL
         rows: 2
        Extra: Using where

"Using where" means it's doing a full table scan, wherein it compares the value of the category column in every row to 14.  If there's an index in place, mysql can jump directly to the appropriate rows.
root@localhost:temp> alter table db add index c1 (category);
root@localhost:temp> explain select * from db where category = 14\G
*************************** 1. row ***************************
           id: 1
  select_type: SIMPLE
        table: db
         type: system
possible_keys: category
          key: NULL
      key_len: NULL
          ref: NULL
         rows: 1
        Extra:

Note the  "possible_keys" field, and that "Extra" is empty.
Indexes are extremely important; a schema without indexes is either very specialized or only half-done.  You should look at all the things mysql with indexes to really get a feel for how important they are.


text:
Q: Disabling / Remapping Logitech G400 mouse DPI buttons I had the Logitech MX-518 mouse, but it had been having issues with responsiveness, causing me to call support for a replacement. Instead of another 518, they sent me a Logitech G400 mouse because the 518 has been discontinued. This causes issues because, while the MX518 was supported by lomoco, the G400 mouse is unsupported. Running $ lomoco -s shows 001.003: 046d:c245 Unsupported Logitech device: Unknown.
What I would like to do is lock the DPI of my mouse to a single value and remap the DPI+ and DPI- buttons to PgUp and PgDn on my keyboard.
How would I accomplish this?

The buttons are, in order:

*

*Button 1: Left-click

*Button 2: Middle-click

*Button 3: Right-click

*Button 4: Mouse Wheel Up

*Button 5: Mouse Wheel Down

*Button 6: None

*Button 7: None

*Button 8: Thumb Button #1

*Button 9: Thumb Button #2

*Button 10: Task Switcher Button

*Button 11: None

*Button 12: None

On the previous mouse (MX 518), buttons 11 and 12 were the DPI keys. One of the things that makes these buttons different than the rest is that applications such as xev do not recognize pressing them as an event, by default. On the MX 518 mouse, in order to make those buttons able to be altered / binded, they had to first be disabled. I believe that lomoco called it "Logitech SmartScroll / Cruise Control." On the G400, lomoco doesn't work and I am unaware of an alternative.
Also, here is some output from xinput, in case it is helpful.
user@localhost:~$ xinput list
⎡ Virtual core pointer                      id=2    [master pointer  (3)]
⎜   ↳ Virtual core XTEST pointer                id=4    [slave  pointer  (2)]
⎜   ↳ Logitech Gaming Mouse G400                id=8    [slave  pointer  (2)]
⎣ Virtual core keyboard                     id=3    [master keyboard (2)]
    ↳ Virtual core XTEST keyboard               id=5    [slave  keyboard (3)]
    ↳ Power Button                              id=6    [slave  keyboard (3)]
    ↳ Power Button                              id=7    [slave  keyboard (3)]
    ↳ AT Translated Set 2 keyboard              id=9    [slave  keyboard (3)]
user@localhost:~$ xinput list-props 8
Device 'Logitech Gaming Mouse G400':
    Device Enabled (121):   1
    Coordinate Transformation Matrix (123): 1.000000, 0.000000, 0.000000, 0.000000, 1.000000, 0.000000, 0.000000, 0.000000, 1.000000
    Device Accel Profile (248): 0
    Device Accel Constant Deceleration (249):   2.000000
    Device Accel Adaptive Deceleration (250):   1.000000
    Device Accel Velocity Scaling (251):    1.000000
    Device Product ID (238):    1133, 49733
    Device Node (239):  "/dev/input/event4"
    Evdev Axis Inversion (252): 0, 0
    Evdev Axes Swap (254):  0
    Axis Labels (255):  "Rel X" (131), "Rel Y" (132), "Rel Vert Wheel" (247)
    Button Labels (256):    "Button Left" (124), "Button Middle" (125), "Button Right" (126), "Button Wheel Up" (127), "Button Wheel Down" (128), "Button Horiz Wheel Left" (129), "Button Horiz Wheel Right" (130), "Button Side" (242), "Button Extra" (243), "Button Forward" (244), "Button Back" (245), "Button Task" (246), "Button Unknown" (241), "Button Unknown" (241), "Button Unknown" (241), "Button Unknown" (241)
    Evdev Middle Button Emulation (257):    0
    Evdev Middle Button Timeout (258):  50
    Evdev Third Button Emulation (259): 0
    Evdev Third Button Emulation Timeout (260): 1000
    Evdev Third Button Emulation Button (261):  3
    Evdev Third Button Emulation Threshold (262):   20
    Evdev Wheel Emulation (263):    0
    Evdev Wheel Emulation Axes (264):   0, 0, 4, 5
    Evdev Wheel Emulation Inertia (265):    10
    Evdev Wheel Emulation Timeout (266):    200
    Evdev Wheel Emulation Button (267): 4
    Evdev Drag Lock Buttons (268):  0

A: @Koviko - I have a similar mouse - a Logitech MX1100 - that also has DPI buttons that aren't sent to the USB when pressed in default mode. I did some testing on my own, and eventually was able to figure out the codes to send the signal to switch the mouse into "Driver Mode", which then allowed me to use easygestures/xev to reassign the buttons.
If you want, I can walk you through the steps I used to determine how to switch it off (I now have a script that I simply need to run on startup, as a very hack-y workaround, but it's working at least), but it involves setting up a VM and having a secondary mouse and sniffing the raw USB traffic, and unfortunately seems likely to be very mouse-specific.
My steps (better ones almost certainly exist):
1) Have a Windows VM (with the Logitech SetPoint software installed; I used VirtualBox, because that's what I already had set up with WinXP for work), Wireshark, and gcc installed on your system.
2) Then I ran the following steps in a terminal:
sudo modprobe usbmon
sudo wireshark &
sudo /usr/lib/virtualbox/VirtualBox &

3) Within Wireshark, choose to 'List the available capture interfaces...', and make a note of which USB bus number generates a ton of packets when you move your mouse around (mine was usbmon3, but I imagine that's purely based on which USB port your receiver is plugged in to).
3) From within VirtualBox (I needed to run as sudo in order to share the USB Controller), I edited the settings of the XP VM, and enabled both the USB Controller and the USB 2.0 (EHCI) Controller. Then I added a new USB Filter populated from an existing device, and selected my Logitech mouse's receiver (Vendor ID 046d, Product c245, for you) and then started up the VM.
(Note: After this point, I needed a second mouse plugged in, because I had to give control over my regular mouse to the Windows VM so that the SetPoint software could see that it existed as something more than a generic mouse.)
4) In the VM, I then launched the SetPoint software, and went to the screen that lets you set custom actions for various buttons. Then back in Wireshark, I started a capture on the USB bus for the mouse, then immediately went in to the VM/SetPoint, and changed the button assignment from DPI +/- to Keystroke Assignment, then immediately went back to Wireshark and stopped the capture. (I repeated this about 10-15 more times, changing the settings to different modes, mostly because I wasn't sure how much data I'd need, but after reviewing, I really only needed the first 1-2 captures.)
Assuming your mouse works vaguely similar to mine, which I'd guess it would, your capture would likely have a total of 16 frames, 4x GET DESCRIPTOR, then 3x(2xURB_CONTROL out + 2xURB_INTERRUPT in). What you're looking for are the 3 longer URB_CONTROL out frames. An example of one of my captured frames is:
0000  c0 80 64 36 00 88 ff ff  53 02 00 03 03 00 00 00
0010  5e 4b 25 50 00 00 00 00  f4 d9 08 00 8d ff ff ff
0020  07 00 00 00 07 00 00 00  21 09 10 02 01 00 07 00
0030  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00
0040  10 01 80 65 82 85 ff

What we're looking for are the last 7 bytes from the response (in the above, the '10 01 80 65 82 85 ff'), from each of the longer 'URB_CONTROL out' frames. Finally, I downloaded the source of the "g_hack" from Git, and cobbled in both my mouse product code at the top, and a new option (I set it to 0/1 with an if statement within them since it was just a very crude proof of concept) which would switch my mouse into "driver mode" or "DPI mode".
After that, all that was required was to set up the newly available mouse buttons in your choice of remapping programs (I used easygestures because that was the first thing with a UI I found - it may or may not have a superior replacement).


text:
Q: DELL 7530 NVidia Graphic Card not working in Ubuntu 16.04.4 After i finished installed ubuntu 16.04.4. Im not able to start ubuntu.
I used the "nomodeset" method. Then i'm able to start ubuntu and login.
I tried to connect my laptop to extend monitor thru HDMI. however, it not able to detect the monitor.
How can i install nvidia driver? When i tried. i go into the loop-logon problem.
do i need to remove the "nomodeset" after nvidia driver is installed?
My Graphic card is Nvidia Qurodo P2000.

A: Solved:
Ubuntu have just updated the kernel version from 4.14 to 4.15. With the upgrade the issue is solved.
For newly installed Ubuntu, ensure that u enable the update option during installing. This will ensure that yr kernel is 4.15.
After installation, on the 1st reboot, wait for the grub screen to appear.
Now enter E at the Ubuntu option. Use the "nomodeset" method. (google "dell nomodeset"). Use method 1 only. This will allow u to login without problem.
Once inside ubuntu, google "Ubuntu Nvidia Drivers", follows the step to install Nvidia driver. Select the Nvidia driver in via "additional drivers".
reboot the system.
That all.


text:
Q: Send log errors to a file I developed a website for my graduation however it still only one thing I have do. What I want is when the script is installed on a website I want to send the name of the website who has installed my script, also whenever there is an error I want to send it to my website so for example:
This website installed my script
www.security-dz.com/myscript

I want to see the path + website in an other file in other website. For example:
www.getlog.com/mylogs.php

The purpose of this is keep my customers update and give them support and see the errors that happen so I can fix them in next updates.

A: You might want to take a closer look at the JQuery docs for ajax requests, so you can use a secure http connection for logging. This javascript code basically describes a function that sends the errors in text-format to your server-side script. This script can in turn write the error description to a file on the server. I'd recommend using a DB instead; That way you can easily write a web-client that displays all reported errors (and filters and the other good stuff).
You can extract the origin url from the referer [sic] field in the ajax http get-request on the server.
(function () { // function operator, in case console doesn't exist
    !console ?
        (console = {}) : console;
    !console.log ?
        (console.log = function () { }) : console.log;
    !console.info ?
        (console.info = console.log) : console.info;
    !console.error ?
        (console.error = console.log) : console.error;
}());
// Uses JQuery
function reportError (errDesc) {
    var path = "www.getlog.com/mylogs.php";
    $.ajax({
        url: path,
        type: "GET",
        async: true,
        cache: false,
        contentType: "application/x-www-form-urlencoded; charset=UTF-8",
        crossDomain: true,
        data: errDesc,
        dataType: "jsonp",
        error: function (req, type, errObj) {
            console.error("Reporting error failed: " + type + "\nAt url: " + path + "\n" + errObj);
        // In case you need to debug the error reporting function
        },
        succes: function (res) {
            console.info("Reported error to server:\nRequest:" + errDesc + "\nResponse: " + res);
        // extra error logging facility on client-side, invisible to most users
        },
        global: false // prevent triggering global ajax event handlers
    });
    return errDesc; // in case you want to reuse the errDesc
}

Code has been validated with jshint. Please let me know if there are still issues, because I didn't take the time to completely replicate your setup (setting up 2 different domains etc.)
Addendum: Some useful reading if you're having issues with cross-domain messaging, JSON is not a subset of javascript, Cross-origin resource sharing, JSONP.

A: What you could do is post both the name of the website that uses your script and the error code variable with AJAX through URL to your logging website, which will then get the variable and name from the URL and use these to add to your log.
You should, however, by using this tactic, also make use of some URL validation, otherwise this will leave you wide open to injection attacks.

A: it is easy when your script installed , get the site info and send by socket and http request with get method and then recive it on your server.
for errors, php has some method to control error logs so custom it.


text:
Q: Behaviour of classifying spaces of abelian groups under direct sums and tensor products Recall the notion of the classifying space $|G|$ of a group $G$.
Is it possible to relate the classifying spaces $|A\oplus B|$ and $|A\otimes_{\mathbb{Z}}B|$ of a tensor product or a direct sum of abelian groups $A$ and $B$ with the classifying spaces $|A|$ and $|B|$ of its factors?
In particular, how does group cohomology (i.e. cohomology of classifying spaces of groups) behave under direct sums and tensor products?