text:
Q: Is it meaningful to optimize i++ as ++i to avoid the temporary variable? Someone told me that I can write
for (iterator it = somecontainer.begin(); it != somecontainer.end(); ++it)

instead of
for (iterator it = somecontainer.begin(); it != somecontainer.end(); it++)

...since the latter one has the cost of an extra unused temporary variable.   Is this optimization useful for modern compiler? Do I need to consider this optimization when writing code?

A: I don't normally consider the prefix ++ an optimization. It's just what I write by default, because it might be faster, it's just as easy to write, and there's no downside.
But I doubt it's worth going back and changing existing code to use the prefix version.

A: No. (Stylistically I prefer it, because my native language is English which is mostly a verb-precedes-noun language, and so "increment it" reads more easily than "it increment". But that's style and subjective.)
However, unless you're changing somecontainer's contents in your loop, you might consider grabbing the return value of somecontainer.end() into a temporary variable. What you're doing there will actually call the function on every loop.

A: Yes, that's conceptually the right thing to do. Do you care if it's i++ or ++i? No, you don't. Which one is better? The second one is better since it's potentially faster. So you choose the second (pre-increment).
In typical cases there will be no difference in emitted code, but the iterators can have whatever implementation. You can't control it and you can't control whether the compiler will emit good code. What you can control is how you conveys your intent. You don't need the post-increment here.

A: It's a good habit to get into, since iterators may be arbitrarily complex. For vector::iterator or int indexes, no, it won't make a difference.
The compiler can never eliminate (elide) the copy because copy elision only eliminates intermediate temporaries, not unused ones. For lightweight objects including most iterators, the compiler can optimize out the code implementing the copy. However, it isn't always obvious when it can't. For example, post-incrementing istream_iterator<string> is guaranteed to copy the last string object read. On a non-reference-counted string implementation, that will allocate, copy, and immediately free memory. The issue is even more likely to apply to heavier, non-iterator classes supporting post-increment.
There is certainly no disadvantage. It seems to have become the predominant style over the past decade or two.

A: It depends on the type to which you're applying operator++. If you are talking about a user defined type, that's going to involve copying the entire UDT, which can be very expensive.
However, if you are talking about a builtin type, then there's likely no difference at all.
It's probably good to get in the habit of using preincrement where possible even when postincrement is fine, simply to be in the habit and to give your code a consistent look. You should be leaning on the compiler to optimize some things for you, but there's no reason to make it's job harder than it has to be for no reason whatsoever.

A: Consider how post-increment is typically implemented in a user-defined type:
MyIterator operator++(int) {
    MyIterator retval(*this);
    ++*this;
    return retval;
}

So we have two questions: can my compiler optimise this in cases where the return value is unused, and will my compiler optimise this in cases where the return value is unused?
As for "can it?", there certainly are cases where it can't. If the code isn't inlined, we're out of luck. If the copy constructor of MyIterator has observable side effects then we're out of luck - copy constructor elision allows return values and copies of temporaries to be constructed in place, so at least the value might only be copied once. But it doesn't allow return values not to be constructed at all. Depending on your compiler, memory allocation might well be an observable side-effect.
Of course iterators usually are intended to be inlined, and iterators usually are lightweight and won't take any effort to copy. As long as we're OK on these two counts, I think we're in business - the compiler can inline the code, spot that retval is unused and that its creation is side-effect free, and remove it. This just leaves a pre-increment.
As for "will it?" - try it on your compiler. I can't be bothered, because I always use pre-increment where the two are equivalent ;-)
For "do I need to consider this optimization when writing code?", I would say not as such, but that premature pessimization is as bad a habit as premature optimization. Just because one is (at best) a waste of time does not mean that the other is noble - don't go out of your way to make your code slower just because you can. If someone genuinely prefers to see i++ in a loop then it's fairly unlikely ever to make their code slower, so they can optimise for aesthetics if they must. Personally I'd prefer that people improve their taste...

A: It will actually make a difference in unoptimized code, which is to say debug builds.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to make app UI to work 100% same on all devices? How to make sure that my App's popup or text appears exactly how I intended it to appear in all screen sizes? I want the aspect ratio of the popup to appear same and all the text that appears at the time of designing the popup to be same in all the devices.
Imagine an image who's size and content will be same across devices. But for some reason I can not use image here, the requirement is to use popup with text and butto. I dont want any screen to cut the popup or make the text of the popup disappear or turn to crap.
I can not do testing with one device at a time as I read on a site that there are over 10,000 android devices :|
Is there anyway or any tool part of Android Studio which can like quickly draw outlines of all the phones screen sizes to help me understand what aspect ratio is right for my popup?
Im a noob so my question may not make sense to you so please bear with me.

A: Unfortunately it's going to be nearly impossible to get things to appear 100% the same across all devices and browsers – Android runs on all sorts of devices and there are probably hundreds or thousands of different possible screen sizes, in addition to browser and operating system quirks.  Start with identifying specific devices and screen sizes you wish to support. See Android's screen compatibility overview for some good information on this topic.
If possible look at user analytics to narrow down the most common devices, operating system versions, and browsers, then test against those.


text:
Q: Does the 'WordPress Order' feature, within the WordPress Dashboard, have any impact on site architecture? As you can see, within the image below, WordPress offers us to numerically arrange our Pages via a feature entitled 'Order'.  I have been using this as a means to help organise my Pages, for my own personal benefit.

Does this feature have any impact on areas such as; Sitemaps, overall site architecture/hierarchy or even does it play an factor in search engine algorithms, when it comes to assigning 'Submission Priorities' etc or is this feature solely for the benefit for those who work on the website, as a means to help with organisation?
Simply put, does this feature have any impact on the site, regardless of if/how/when it is used?

A: Short answer: No, it does not have any impact at all.
Longer answer:
The 'Order' field is a remnant from the early days of WordPress. Its only purpose is to order the pages in the admin for easier content management. Plus, people can use it to display a list of pages in their preferred order, for example in the main navigation. Nowadays custom nav menus are being used everywhere though, so it's not really useful there. This means nothing in the front end of your website changes when you manipulate the order field.
None of the SEO plugins I know use the order field in any way. Why should they? The order in which URLs are listed in XML sitemaps (which you can submit to search engines) is a) not determined by the order field (none of the SEO plugins I checked use that field anywhere) and b) has no effect on their priority. XML sitemaps have a separate priority field for that, which would be determined by the importance of a page, the frequency of changes to it, and things like that — the menu order has nothing to do with that. And even if it would, Google is not even using the priority field for its ranking.
The only thing the order field really is good for is ordering your pages in the admin to make lives easier. Nothing more.

A: Yes, it will change the sitemap order and navigation of your site.
I hope this will help
How to change the Navigation and Sitemap order in WordPress


text:
Q: Send mail from command line? How I can send a simple mail from Ubuntu command line without giving the password for the email account which I'm sending to?

A: sudo apt-get install mailutils
mail -s "Subject" email@email.com

Press enter and write the subject of your email. Use Ctrl+D to continue.
You will be asked if you want to mark a copy of the mail to any other address - you can skip that with Ctrl+D.
The email will now be sent to your chosen address.

A: echo "Mail text" | mail -s "Subject" your@mail.com


text:
Q: What is the name of a "basis" in Boolean algebras So, a basis in linear algebra is the smallest set which generates a particular vector space. (More formally, a subset of the vector space which is linearly independent and spans the vector space)
Is there a name for a similar concept in Boolean algebra? The object I am describing is a subset A of the elements of the boolean algebra such that

*

*The set A generates the boolean algebra

*No proper subset of A generates the boolean algebra.

A: There is no particular name for this.  I would refer to it simply as a "minimal generating set".  Note that in contrast to the case of vector spaces, minimal generating sets for the same Boolean algebra can have different cardinalities, and they will not always freely generate the algebra, so the notion is much less useful than the notion of a basis for a vector space.
(In fact, I suspect some Boolean algebras don't even have a minimal generating set, though I don't know an example.)


text:
Q: Add image to website on Polymer 3.0 I am new at Polymer (started today :) ). I want to add an image to app-drawer, however using  is not working, I tried to install and use iron-image but I could not include because imports need to be js file and iron-image does not include js, only HTML.

A: Starting with polymer-3 may be a little confusing in the current state of development, since the documentation doesn't seem to be complete yet and the polymer-3-elements are only preview versions.
If you install the iron-image element via npm (npm install @polymer/iron-image@next --save) you will get the latest polymer-3 version of that element. That element is a js file and should be possible to be imported in your project.
Here is an example from the polymer docs on how to add elements: Polymer Docs


text:
Q: Moving a Div on Mouse Move I have jquery code that triggers the div to move on movement on a mouse wheel.
The code below works on mouse wheel movement.
What i am trying to implement is that i want the div to move when the mouse is moved to the left or right of the screen?
function scrollLeft() {
    var $left = Math.abs(Number($galleryList.css("margin-left").replace("px", "")))
    ;
    if ($left - itemWidth <= 0) {
        $galleryList.css({"margin-left": ""});
    }
    else {
        $galleryList.css({"margin-left": -1 * Number($left - itemWidth) + "px"});
    }
    $(document).trigger("mousemove");
}

function scrollRight() {
    var $left = Math.abs(Number($galleryList.css("margin-left").replace("px", "")))
    ;

    if ($galleryList.width() < itemWidth + $left + $window.width()) {
        $galleryList.css({"margin-left": -1 * Number($galleryList.width() - $window.width()) + "px"});
    }
    else {
        $galleryList.css({"margin-left": -1 * Number($left + itemWidth) + "px"});
    }
    $(document).trigger("mousemove");
}

$window.on("mousewheel", function (event) {
    if (stackedMode) {
        return true;
    }
    if (event.deltaY == 1) { // left
        scrollLeft();
    }
    else if (event.deltaY == -1) { // right
        scrollRight();
    }
    animating = true;
    setTimeout(function () {
        animating = false;
    }, 500);
})


text:
Q: Change currency depending on country I have a package table. I want to change automatically the currency of each amount depending on the location of the user. For example, if the user is from UK, it will change to pounds, if from Australia it will be AUD. I have looked for a tutorial in google but all I can see is a conversion table, like this one not. How will I do this using HTML and javascript?

            $100

            $200

            $300

            Package A

            <input type="checkbox" checked disabled/>

            <input type="checkbox" checked disabled/>

            <input type="checkbox" checked disabled/>

            Package B

            <input type="checkbox" disabled/>

            <input type="checkbox" checked disabled/>

            <input type="checkbox" checked disabled/>

            Package C

            <input type="checkbox" disabled/>

            <input type="checkbox" disabled/>

            <input type="checkbox" checked disabled/>

A: first, get the user's ip address
$ip =  $_SERVER['REMOTE_ADDR'];
echo $location = file_get_contents("http://api.hostip.info/country.php?ip=$ip");

it will echo the two letter country code of the user, if you will test it in your local host, replace the first line with this test ip
$ip = '121.1.11.166';

the test will echo 'PH' , meaning the ip of the user is from Philippines.
seen it here: link

A: You may want to take look at Globalize.js which can handle many different formats including currency.
https://github.com/jquery/globalize
https://github.com/jquery/globalize/blob/master/doc/api/currency/currency-formatter.md
Those formats are based on different language settings which are available here https://github.com/jquery/globalize/blob/master/doc/cldr.md.
Using this you can even handle currency symbols but also display format of your data.
To get the language of your visitor you can use something like this
Var language = window.navigator.userLanguage || window.navigator.language;
alert(language); //works IE/SAFARI/CHROME/FF

But keep in mind that one USD $ !== one Euro € ^^


text:
Q: Multiple remove selected items listview I'm going crazy to understand where is the problem in my code. I'm tring to remove multiple items from listview, more precisally, remove the selected items. I wrote this code.
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
    super.onActivityResult(requestCode, resultCode, intent);
    if(requestCode == 1) {
        try {
            for(int a=0; a<adapter.getArrayPositions().size(); a++) {
                applicationInfo = getPackageManager().getApplicationInfo(adapter.getList().get(a), a);
            }
        } catch(PackageManager.NameNotFoundException e) {
            for(int a=0; a<adapter.getArrayPositions().size(); a++) {
            appInfoArrayList.remove(adapter.getArrayPositions().get(a));
            adapter.notifyDataSetChanged();
            }
            }

    }
    else {

    }
}

My method getArrayPositions() return correctly the items position but it remain in the Listview. Why? why they are not removed?
public ArrayList<Integer> getArrayPositions() {
    return myArrayList;
}


text:
Q: Background color change on table view cell tap in IOS I have a view controller that has a UITableViewController as its main view. In the function - tableView:cellForRowAtIndexPath: I create a custom view for my cell with the following code.
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:
                                        CellIdentifier];

// Configure the cell...
if (cell == nil) {
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault      reuseIdentifier:CellIdentifier];
}

cell.backgroundView = [[UIView alloc] init];

I then add my own custom views to cell.backgroundView. However, when I tap a cell the cell becomes completely gray. No where in my code do I specify that this should happen. To do some testing I added some text to the standard part of a cell as follows.
cell.textLabel.text = @"TEST";

When I ran this I saw both my custom view and the 'TEST' label. When a cell was pressed, the gray screen appeared and this time 'TEST' was visible and my custom view still not visible. My guess is that some other measure has to be taken to ensure custom views are visible. I was using the tableView:didSelectRowAtIndexPath: function to register taps but oddly this function is called for all tap events except the first one. In addition, I tried to set the background color here but it didn't work.
- (void) tableView: (UITableView *) tableView didSelectRowAtIndexPath: (NSIndexPath *) indexPath {
    UITableViewCell *newCell = [tableView cellForRowAtIndexPath:indexPath];
    newCell.backgroundColor = [UIColor whiteColor];

}

Any help is appreciated.

A: In tableView:cellForRowAtIndexPath: change the selectionStyle property on each cell to UITableViewCellSelectionStyleNone.

A: You can do the same in storyboard by setting the Selection property of the Table View Cell to None

A: The accepted answer was not working for me. This problem driving me crazy for awhile because it would look like a "glitch" on any selection when the next view loaded..
My SOLUTION: I had to go to the .xib file of the actual TableViewCell (my custom cell that I built) select the cell and select the CellView. (Make sure you select the Cell, and NOT a subview within it. It will turn Blue like the picture shows). On the left side click "Selection" -> "None". This SHOULD be the exact same as doing it with code, but for some reason it just wasn't working...

A: One of the best way to keep background color unchanged is:

*

*Set  YOUR_VIEW.backgroundColor to clearColor

*Then set YOUR_VIEW.layer.backgroundColor to YOUR_COLOR
Let's see an Objective-C implementation:
self.YOUR_VIEW.backgroundColor = UIColor.clearColor;
self.YOUR_VIEW.layer.backgroundColor = UIColor.YOUR_COLOR.CGColor;

Note : It doesn't need to turn off beautiful selection or highlight animation.

A: Swift,
Set up cell.selectionStyle = .none in your cellForRowAt method from the UITableViewDataSource.


text:
Q: Data formatting of array in javascript I got an array like below -

const arr = [{
    name: 'Benefits',
    coverage: [{
      name: "item_one",
      interest: [{
        name: "interest_one",
        limit: [{
          value: 2000
        }]
      }],
      limit: [{
        value: "Y"
      }]
    }]
  },
  {
    name: 'Benefits',
    coverage: [{
      name: "item_two",
      interest: [{
        name: "interest_two",
        limit: [{
          value: 5000
        }]
      }],
      limit: [{
        value: "Y"
      }]
    }]
  }
]

I need to display benefit in the frontend. but the problem is when i'm mapping through this array the benefits prints twice. I know there are two objects that is why it is printing twice.
So i decided to convert this array to like below

const arr2 = [{
  name: 'Benefits',
  oneCoverage: [{
    name: "item_one",
    interest: [{
      name: "interest_one",
      limit: [{
        value: 2000
      }]
    }],
    oneLimit: [{
      value: "Y"
    }]
  }],
  twoCoverage: [{
    name: "item_two",
    interest: [{
      name: "interest_two",
      limit: [{
        value: 5000
      }]
    }],
    limit: [{
      value: "Y"
    }]
  }]
}]

But no success in getting the above data.
I want to convert arr to arr2 format.
How can i achieve this.
Thanks in advance

A: One approach using reduce. I treat this as grouping problem where I group by name. But here I had to assume that every coverage is an array of 1 element.
Maybe you were stuck with creating the key name like oneCoverage and so on.
That can be handled by ${coverage[0].name.split("_")[1]}Coverage
In the end I take the values array using Object.values

const arr = [{    name: 'Benefits',    coverage: [{      name: "item_one",      interest: [{        name: "interest_one",        limit: [{          value: 2000        }]      }],      limit: [{        value: "Y"      }]}]  },  {    name: 'Benefits',    coverage: [{      name: "item_two",      interest: [{        name: "interest_two",        limit: [{          value: 5000        }]      }],      limit: [{        value: "Y"      }]    }]  }]

const res = Object.values(arr.reduce((acc,{name,coverage}) => {
  acc[name] ??= {name}
  const keyName = `${coverage[0].name.split("_")[1]}Coverage`
  acc[name][keyName] = coverage
  return acc
}, {}))

console.log(res)
.as-console-wrapper { max-height: 100% !important; top: 0; }

A: Did you mean this?
const arr2 = [{
  name: 'Benefits', // or arr[0].name
  oneCoverage: arr[0].coverage,
  twoCoverage: arr[1].coverage,
}]

If you need deep clone, you can use:
const arr2 = [{
  name: 'Benefits', // or arr[0].name
  oneCoverage: structuredClone(arr[0].coverage),
  twoCoverage: structuredClone(arr[1].coverage),
}]

However, I can't see any "benefit" of arr2's structure, my advice is:
const benefits = [];
arr.filter((v) => v.name === 'Benefits').forEach((v) => {
  benefits.push(...structuredClone(v.coverage))
});
console.log(JSON.stringify(benefits));
/**
[
  {
    "name": "item_one",
    "interest": [{
      "name": "interest_one",
      "limit": [{ "value": 2000 }]
    }],
    "limit": [{ "value": "Y" }]
  },
  {
    "name": "item_two",
    "interest": [{
      "name": "interest_two",
      "limit": [{ "value": 5000 }]
    }],
    "limit": [{ "value": "Y" }]
  }
]
*/


text:
Q: AngularJS $scopes behave like a pointer I have something like:
$scope.array1_copy=$scope.array1[$scope.index];

$scope.array1 ist an array, made out from smaller arrays filled with objects.
Now, when I take changes to $scope.array1_copy the changes get reflected in $scope.array1.
I've read of using angular.copy(), but whats the reason for this behaviour?
Kind regards;
Force0234

A: It has nothing to do with Angular, the reason it happens is because objects and arrays are passed by reference in JavaScript.
you could use slice() to clone the array.
$scope.array1_copy = $scope.array1[$scope.index].slice();

Read more here: http://orizens.com/wp/topics/javascript-arrays-passing-by-reference-or-by-value/

A: In javascript when you assign a object to another, is passing the reference of this object, the angular copy create a new object and copy de primitive values inside and return this reference. Example:
var object = {
    value: "value",
    value2: "value2",
    ...
}

var object2 = object;
object2.value = "change this value";
console.log(object.value) // must print "change this value"

var value = object.value;
value = "another value";
console.log(object.value) // must print "change this value" mantain the old value

//Deep copy
var object2 = {}
object2.value = object.value;
object2.value2 = object.value2;
object2.value = "another change to this value";
console.log(object.value) // must print "change this value" mantain the old value


text:
Q: Bind event handler to "console.log" JavaScript event My script sends text to the console output from several places in Javascript (see examples), how do I bind an event handler function to the log function itself so that a function is executed each time the event is triggered?
try {
    //some code
} catch(e) {
    console.log("error: "+e)
}

function x(n) {
    //some code
    console.log(str)
}

A: I would override console.log (but store it in a different variable, in case we want to use it) like so:
var nativeLog = console.log.bind(console) //store native function

console.log = function(text){ //override
    nativeLog("<<<" + text)
}

Abbreviating console.log in JavaScript


text:
Q: Python. Криптография Подскажите пожалуйста где ошибся или неправильно написал код. Код работает, но 5-е чувство подсказывает что он неправильный.
Буду очень признателен за любую помощь.
Если возможно, был бы рад коду с комментариями. P.S.
Условие задачи:
Реализуйте атакующую грубую нагрузку на текст, зашифрованный AES.
В качестве возможности получения трехзначного числа.

Код:

    from Crypto.Cipher import AES
    from Crypto import Random
    import hashlib
    import random

    BS = AES.block_size
    pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS)

    plain_text = """We are Anonymous.
    We are Legion.
    We do not forgive.
    We do not forget.
    Expect us.
    """
    key = hashlib.sha256(b"357").digest()
    print("Key:", key)
    plain_text = pad(plain_text)
    iv = Random.new().read(BS)
    cipher = AES.new(key, AES.MODE_CBC, iv)
    cipher_text = (iv + cipher.encrypt(plain_text.encode()))
    print("\nCiphered text:", cipher_text)
    correctPassword = "357"
    wrongPasswords = []
    password = ""
    length = 3
    chars = "1234567890"
    run = True
    while run:
    password = ""
    for i in range(length):
    password += random.choice(chars)
    if password not in wrongPasswords:
    if password != correctPassword:
    print(password)
    wrongPasswords.append(password)
    else:
    run = False
    break
    print(password + "is correct")
    unpad = lambda s : s[:-ord(s[len(s)-1:])]
    cipher_text = cipher_text
    iv = cipher_text[:BS]
    cipher = AES.new(key, AES.MODE_CBC, iv)
    plain_text = unpad(cipher.decrypt(cipher_text[BS:]))
    print("\nPlain text:", plain_text)


text:
Q: Changing the word "password" at login Wanted to know if there was a way to change the word password here to say passcode? We use a custom application that authenticates users through passcodes and to not confuse users, I wanted to change the text.
user@192.168.0.5's password:
I found some articles on the sshd_config and PM files but I cannot figure it out. Any help would be great.


text:
Q: How do I catch this exception in Swing? I have a Swing application, and even though I have everything in a try/block, the exception isn't caught.
public static void main(String[] args) {

    try {
        App app = new App();
        app.setVisible(true);

    } catch (Throwable e) {
       System.err.println("never printed");
    }
}

all I get is this stack trace:
Exception in thread "AWT-EventQueue-0"
java.lang.ArrayIndexOutOfBoundsException:
9 >= 9
at java.util.Vector.elementAt(Vector.java:427)
at javax.swing.table.DefaultTableModel.getValueAt(DefaultTableModel.java:633)
at javax.swing.JTable.getValueAt(JTable.java:2695)
at javax.swing.JTable.prepareRenderer(JTable.java:5712)
at javax.swing.plaf.basic.BasicTableUI.paintCell(BasicTableUI.java:2075)
at javax.swing.plaf.basic.BasicTableUI.paintCells(BasicTableUI.java:1977)
at javax.swing.plaf.basic.BasicTableUI.paint(BasicTableUI.java:1773)
at javax.swing.plaf.ComponentUI.update(ComponentUI.java:143)
at javax.swing.JComponent.paintComponent(JComponent.java:763)
at javax.swing.JComponent.paint(JComponent.java:1027)
at javax.swing.JComponent.paintChildren(JComponent.java:864)
at javax.swing.JComponent.paint(JComponent.java:1036)
at javax.swing.JViewport.paint(JViewport.java:747)
at javax.swing.JComponent.paintChildren(JComponent.java:864)
at javax.swing.JComponent.paint(JComponent.java:1036)
at javax.swing.JComponent.paintChildren(JComponent.java:864)
at javax.swing.JComponent.paint(JComponent.java:1036)
at javax.swing.JComponent.paintChildren(JComponent.java:864)
at javax.swing.JComponent.paint(JComponent.java:1036)
at javax.swing.JLayeredPane.paint(JLayeredPane.java:564)
at javax.swing.JComponent.paintChildren(JComponent.java:864)
at javax.swing.JComponent.paintToOffscreen(JComponent.java:5129)
at javax.swing.BufferStrategyPaintManager.paint
(BufferStrategyPaintManager.java:277)
at javax.swing.RepaintManager.paint(RepaintManager.java:1217)
at javax.swing.JComponent.paint(JComponent.java:1013)
at java.awt.GraphicsCallback$PaintCallback.run(GraphicsCallback.java:21)
at sun.awt.SunGraphicsCallback.runOneComponent(SunGraphicsCallback.java:60)
at sun.awt.SunGraphicsCallback.runComponents(SunGraphicsCallback.java:97)
at java.awt.Container.paint(Container.java:1780)
at javax.swing.RepaintManager.paintDirtyRegions(RepaintManager.java:814)
at javax.swing.RepaintManager.paintDirtyRegions(RepaintManager.java:714)
at javax.swing.RepaintManager.seqPaintDirtyRegions(RepaintManager.java:694)
at javax.swing.SystemEventQueueUtilities$ComponentWorkRequest.run
(SystemEventQueueUtilities.java:128)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:597)
at java.awt.EventDispatchThread.pumpOneEventForFilters
(EventDispatchThread.java:269)
at java.awt.EventDispatchThread.pumpEventsForFilter
(EventDispatchThread.java:184)
at java.awt.EventDispatchThread.pumpEventsForHierarchy
(EventDispatchThread.java:174)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)

A: Swing runs things in the event dispatching thread. You are trying to catch it in the main thread.
And note that swing is not thread safe, you too should be doing things in event dispatching thread.
To catch the exception, you can override some method from that stack trace, like the paint method from your component.
And for me that exception does look like a bug you should fix, not something you should hide by catching.

A: Runtime exceptions like ArrayIndexOutOfBoundsException shows a programmer mistake. So it might be better to fix them rather catching and silently chewing it.
Just a wild guess for the cause of exception. Something concurrently remove rows from the table model's datavector once the JTable starts to draw the data on screen.

A: As mentioned by another poster, your problem is that the exception is being thrown in another thread, the event dispatch thread. A couple of solutions:

*

*put a try/catch around the actual code where the exception is occurring: e.g. if it's in response to a button click handled by an ActionListener, put the try/catch inside your actionPerformed() method;

*or, leave the exception as an uncaught exception, and add an uncaught exception handler. For example:

    Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
      public void uncaughtException(Thread t, Throwable e) {
        // ... do something with exception here ...
      }
    });

On a side-note, you should in principle but your UI startup code in a SwingUtilities.invokeLater().

A: The only suitable ways that I am aware of, in order to catch exceptions thrown from inside the EDT are:

*

*write your own EventQueue (I woudln't
advise it in general)

*use Swing internal property "sun.awt.exception.handler" (I use
it and it works on all Sun JDK 1.4,
1.5 and 1.6 at least, plus on IBM JDK 1.4 and 1.5 at least; I didn;t check it on other JDK though)

You should take a look at this thread to have a more complete overview of the solutions with their pros and cons.

A: As mentioned above, the problem is where the exception is being thrown - on the event dispatch thread.
If you want to set up a try/catch block to catch this particular problem, I would throw one into the App class's paint method.  Override it and put a call to super.paint in a try catch block there.
If you want a generic way to catch uncaught exceptions, take a look at Thread.setUncaughtExceptionHandler.  You call that method with an exception handler and you can deal with all the exceptions which don't get caught in your application.


text:
Q: Display different data if the page URL matches address's in an array? I have a HTML table which has various data in but upon reaching a certain address, I need to display some different data.
Now, this is easy enough when just checking against 1 URL with the following data I have setup as:
{$page_details.URL}

But a scenario as come up where I need to apply this change of data on a collection of page URLS and without writing lots of {if} {else} statements I am hoping there is another way of achieving this?
I was thinking of something along these lines...
Having an array stored on the template which has the URLs stored within and then write 1 {if} statement checking to see if any of the values in the array is true and then apply the new data like so:
{assign var="pages" value=[URL-1,URL-2,URL-3]}

{if $pages}
    {* display special data *}
{else}
    {* Display normal data *}
{/if}

And if you landed on the web page with an URL of any of the values in the array, ie. /URL-3/ it would display the special data instead.
Could this be possible with Smarty, Or PHP?
Any help would be greatly appreciated.
Thanks

A: I believe what you're looking for is this:
http://php.net/manual/en/reserved.variables.server.php
I imagine all the URLs are all for the same domain as the script?  In which case you can get the current page's path with:
var current_page = $_SERVER['REQUEST_URI']; // would be something like "/index.html"

Then based on your example you could do the following to display your special data:
if in_array(current_page, $pages)

You could always just use this javascript inside the table:
var currentPage = document.URL;
var pages       = [url1, url2, url2];

if (pages.indexOf(currentPage) != -1) {
  document.write('Your special data');
} else {
  document.write('Your normal data');
}


text:
Q: Problem with adding JavaScript code to similar elements I tried to add JavaScript function to similar element but unfortunately it doesn't work.
I also tried modifying JavaScript code by using querySelectorAll and Foreach but it didn't worked, It add the class but when it come to removing class it broke down and console just kept throwing undefined errors.

const containerDivs = document.querySelectorAll('.box.center');
containerDivs.forEach(containerDiv => {
    const leftContainer = containerDiv.querySelector('.left_container');
    const arrow = containerDiv.querySelector('.arr_container');
    const cancel =  containerDiv.querySelector('.cancel');

    arrow.addEventListener("click", ({ target: arrow }) => {
        arrow.classList.add("active_arr");
        if (leftContainer.classList.contains("off")) {
            leftContainer.classList.remove("off");
            leftContainer.classList.add("active");
        }

    });

    cancel.addEventListener("click", ({ target: cancel }) => {
        cancel.classList.add("active_arr");
        if (leftContainer.classList.contains("active")) {
            leftContainer.classList.remove("active");
            leftContainer.classList.add("off")
        }

    });
});
*{
 margin: 0;
 padding: 0;
 box-sizing: border-box;
}

body{
    background: linear-gradient(to right, #2c5346, #203a43, #0f2027);
}

.center{
    display: flex;
    justify-content: center;
    align-items: center;
}

.main{
    height: 100vh;
}

.box{
    width: 250px;
    height: 250px;
    box-shadow: 0 10px 20px rgba(0,0,0,0.288);
    border-radius: 23px;
    flex-direction: column;
    color: white;
    position: relative;
    overflow: hidden;
}

.box img{
    width: 100px;
    height: 100px;
    border-radius: 50px;
}

.user_name{
    margin-bottom: 5px;
    font-size: 2rem;
}

.skill{
    color: rgba(225,225,225,0.555);
}
/*arrow*/
.arr_container .cancel{
    position: absolute;
    width: 50px;
    height: 50px;
    background: white;
    bottom: 0;
    right: 0;
    border-radius: 23px 0 23px 0;
    color: rgb(70,70,70);
    font-size: 1.6rem;
    cursor: pointer;
    transition: all .4s;
}

.arr_container{
    position: absolute;
    width: 50px;
    height: 50px;
    background: white;
    bottom: 0;
    right: 0;
    border-radius: 23px 0 23px 0;
    color: rgb(70,70,70);
    font-size: 1.6rem;
    cursor: pointer;
    transition: all .4s;
}
.arr_container i{
    transform: rotate(45deg);
}
.active_arr{
    transform: translate(80%, 80%);
}
.left_container{
    position: absolute;
    background: #0f2027;
    width: 100%;
    height: 100%;
    border-radius: 23px;
    padding: 40px 0 0 20px;
    transition: all .4s;
}
.off{
    transform: translate(-80%,-80%) rotate(90deg);
}
.active{
    transform: translate(0) rotate(0);
}
.left_container p{
    margin-bottom: 15px;
    font-size: 1.2rem
}
.left_container .skill div{
    display: inline-block;
    color: rgb(155,155,155);
    border:1px solid rgb(155,155,155);
    padding: 5px 10px;
    font-size: .9rem;
    margin: 4px 4px 4px 0;
}
.left_container .icons{
    font-size: 1.6rem;
    margin-top: 10px;
}
.left_container .icons i{
    color: #cfcfcf;
    cursor: pointer;
    margin-right: 10px;
    transition: all .4s;
}
.left_container .icons i:hover{
    color: #2c5346;
}
.cancel{
        right: 0px;
    bottom: 0px;
    font-size: 1.5rem;
    color: rgb(70,70,70);
    position: absolute;
    width: 50px;
    height: 50px;
    background: white;
    justify-content: center;
    align-items: center;
    border-radius: 23px 0 23px 0;
}
.cancel .fas{
    position: absolute;
    right: 1rem;
    bottom: 1rem;
}
<!DOCTYPE html>

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    <link rel="stylesheet" type="text/css" href="cards.css">
    <title>cards</title>

Mor Maz

Front-end Developer

Skill

Html

Css

React

Node Js

Mor Maz

Front-end Developer

Skill

Html

Css

React

Node Js

I will appreciate any kind of help
thank you

A: The classnames and CSS are a mess and you're only adding active_arr to ar and you're only removing active_arr from cl. You're also only selecting one left_container
You should not reach up to change parents if possible; you should iterate parents, iterate their children, etc
This should get you started.
const containerDivs = document.querySelectorAll('.box.center');
containerDivs.forEach(containerDiv => {
    const leftContainer = containerDiv.querySelector('.left_container');
    const arrow = containerDiv.querySelector('.arr_container');
    const cancel =  containerDiv.querySelector('.cancel');

    arrow.addEventListener("click", ({ target: arrow }) => {

    });

    cancel.addEventListener("click", ({ target: cancel }) => {

    });
});


text:
Q: Google Sheets API - Formatting inserted values Through this code I've update a bunch of rows in Google Spreadsheet.
The request goes well and returns me the updatedRange below.
result = service.spreadsheets().values().append(
    spreadsheetId=spreadsheetId,
    range=rangeName,
    valueInputOption="RAW",
    insertDataOption="INSERT_ROWS",
    body=body
).execute()
print(result)
print("Range updated")
updateRange = result['updates']['updatedRange']

Now I would like to do a batchUpdate request to set the formatting or set a protected range, but those API require a range specified as startRowIndex, endRowIndex and so on.
How could I retrieve the rows index from the updatedRange?

A: Waiting for a native or better answer, I'll post a function I've created to translate a namedRange into a gridRange.
The function is far from perfect and does not translate the sheet name to a sheet id (I left that task to another specific function), but accept named ranges in the form:

*

*sheet!A:B

*sheet!A1:B

*sheet!A:B5

*sheet!A1:B5
Here is the code
    import re

    def namedRange2Grid(self, rangeName):
        ascii_uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
        match = re.match(".*?\!([A-Z0-9]+)\:([A-Z0-9]+)", rangeName)
        if match:
            start = match.group(1)
            end = match.group(2)
            matchStart = re.match("([A-Z]{1,})([1-9]+){0,}", start)
            matchEnd = re.match("([A-Z]{1,})([1-9]+){0,}", end)
            if matchStart and matchEnd:
                GridRange = {}
                letterStart = matchStart.group(1)
                letterEnd = matchEnd.group(1)
                if matchStart.group(2):
                    numberStart = int(matchStart.group(2))
                    GridRange['startRowIndex'] = numberStart - 1
                if matchEnd.group(2):
                    numberEnd = int(matchEnd.group(2))
                    GridRange['endRowIndex'] = numberEnd

                i = 0
                for l in range(0, len(letterStart)):
                    i = i + (l * len(ascii_uppercase))
                    i = i + ascii_uppercase.index(letterStart[l])
                GridRange['startColumnIndex'] = i

                i = 0
                for l in range(0, len(letterEnd)):
                    i = i + (l * len(ascii_uppercase))
                    i = i + ascii_uppercase.index(letterEnd[l])
                GridRange['endColumnIndex'] = i + 1

                return GridRange


text:
Q: How two arrays that look exactly the same can be different? Look at this JS code:

var st, ary, ary1, ary2;
ary  = [["a","b","c"], ["d","e","f"]]; // 2D array
ary1 = ary[1];
st   = "d,e,f"; ary2 = st.split(',');
st   = typeof(ary1) + " " + ary1.length + " " + ary1 + '\n';  // I put all output into a string
st  += typeof(ary2) + " " + ary2.length + " " + ary2 + '\n'; // for a single display
st  += (ary1[0]==ary2[0])+'\n';
st  += (ary1==ary2);

console.log(st);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Output:

object 3 d,e,f
object 3 d,e,f
true
false

... Same but different! Why's that?

A: Because == checks if its actually the same object by checking the reference. It does not care about the content of the object. You could even deep clone the array to another array, it would still be different.
Consider this:
Person object1 = new Person("1", "Thomas", "Meier");
Person object2 = new Person("1", "Thomas", "Meier");
Person object3 = object1;

System.out.println(object1 == object2);
// Output: false
System.out.println(object1 == object3);
// Output: true

A: Because they have different links. When you have created an array the var got a link. When you try to compare two arrays, js compares links.


text:
Q: How do I add a php statement to a jQuery string I want to insert a php statement into a jQuery String to update the user profile dynamically.
Here is my not working code so far:
jQueryVarWP("#kreis1").append("<option value=\""+array_list[i]+"\"<?php selected("+array_list[i]+", get_the_author_meta( \"kreis\", \$user->ID ) );?> >"+array_list[i]+"</option>");

My problem is somewhere here:
"<?php selected("+array_list[i]+", get_the_author_meta( \"kreis\", \$user->ID ) );?>

Maybe someone can help me to build this string.

A: You might want to try to use wp_localize_script() to allow your javascript to use data that are normally only available using php. Here is the link in the codex that will help you do what you need:
https://codex.wordpress.org/Function_Reference/wp_localize_script
Another way is to use a php to output your entire javascript code (in a php file, that is, and not a js file). That way you can use php the way you would normally do.


text:
Q: Python Pandas Split Column String Values into Separate Columns I have a DataFrame like this:

With the lineup column in the format 'QB Aaron Rodgers RB Josh Jacobs RB Boston Scott FLEX Antonio Gibson WR Davante Adams WR Adam Thielen WR Allen Lazard TE Mark Andrews DST Patriots'
I need to break up the lineup column into separate columns based on position.
Final DataFrame will look like this:

I have tried this line of code:
df = pd.DataFrame(df.Lineup.str.split(' ').tolist(), columns = ['DST','FLEX','QB','RB1','RB2','TE','WR1','WR2','WR3'])

But I am getting an error.

A: Realistically, having the Lineup column be formatted in such a way that the difference between your keys and the content would be really helpful. Commas in between roles, or something could really help make the parsing easier.
I'm sure there is a more elegant way to solve this type of problem, however, I setup a dictionary keyed with your indicator characters ['DST','FLEX','QB','RB','TE','WR']. In my code below, I assume that your data is always in groups of 3 and one group of 2 which is the last one. If this is an incorrect assumption you'll need to correct that portion of the program.
import pandas as pd

df = pd.DataFrame({
    "Rank": [1],
    "EntryId": ["2210633437"],
    "EntryName": ["180DegreesMiami (2/3)"],
    "TimeRemaining": [0],
    "Points": [214.06],
    "Lineup": ["QB Aaron Rodgers "
               "RB Josh Jacobs "
               "RB Boston Scott "
               "FLEX Antonio Gibson "
               "WR Davante Adams "
               "WR Adam Thielen "
               "WR Allen Lazard "
               "TE Mark Andrews "
               "DST Patriots"],
    "WeekSeason": ["12020"],
    "Player": ["Boston Scott"],
    "Roster Position": ["RB"],
    "FPTS": [7.4]
})

def process_column(s):
    splits = s.split(' ')
    d = {}
    for key, *rest in [splits[i:i + 3] for i in range(0, len(splits), 3)]:
        d.setdefault(key, []).append(' '.join(rest))

    d2 = {}
    for key, values in d.items():
        if len(values) > 1:
            for i, value in enumerate(values):
                d2[f'{key}{i + 1}'] = value
        else:
            d2[key] = values[0]
    return pd.Series(d2)

df = pd.merge(df, df.Lineup.apply(process_column), left_index=True, right_index=True).drop(columns=['Lineup'])

The program produced the following output:

Index
Rank
EntryId
EntryName
TimeRemaining
Points
WeekSeason
Player
Roster Position
FPTS
QB
RB1
RB2
FLEX
WR1
WR2
WR3
TE
DST

0
1
2210633437
180DegreesMiami (2/3)
0
214.06
12020
Boston Scott
RB
7.4
Aaron Rodgers
Josh Jacobs
Boston Scott
Antonio Gibson
Davante Adams
Adam Thielen
Allen Lazard
Mark Andrews
Patriots

Feel free to rearrange the columns as desired.

A: You can extract the names with regex by splitting on the positions. Then create a dictionary by zipping the positions and the names. The result can be turned into a dataframe which is then concatenated with the existing dataframe. To use your sample string:
import re
import pandas as pd

def get_names(text):
    names = [i.strip() for i in re.split('QB |RB |FLEX |WR |TE |DST ', text) if i]
    positions = ['QB', 'RB1', 'RB2', 'FLEX', 'WR1', 'WR2', 'WR3', 'TE', 'DST']
    return dict(zip(positions, names))

df = pd.DataFrame(['QB Aaron Rodgers RB Josh Jacobs RB Boston Scott FLEX Antonio Gibson WR Davante Adams WR Adam Thielen WR Allen Lazard TE Mark Andrews DST Patriots'], columns=['Lineup'])
d = df['Lineup'].apply(get_names)

df = pd.concat([df, pd.DataFrame(d.tolist())], axis = 1)

Output:

Lineup
QB
RB1
RB2
FLEX
WR1
WR2
WR3
TE
DST

0
QB Aaron Rodgers RB Josh Jacobs RB Boston Scott FLEX Antonio Gibson WR Davante Adams WR Adam Thielen WR Allen Lazard TE Mark Andrews DST Patriots
Aaron Rodgers
Josh Jacobs
Boston Scott
Antonio Gibson
Davante Adams
Adam Thielen
Allen Lazard
Mark Andrews
Patriots


text:
Q: Is there a way to print a string-type variable in C++ via the ncurses library? I have been constantly trying to print out a string type variable via ncurses' functions since "cout" is not working by the time I am typing in the "initscr()" command. I have created an array of string variables and I am trying to print each and every single one of the strings out on a window. The result I am getting is some nonsense words. Here's the most critical parts of my code:
string *filetypes = new string[4];
filetypes[0] = ".png";
filetypes[1] = ".jpeg";
filetypes[2] = ".jpg";
filetypes[3] = ".gif";
initscr();
WINDOW *menu = newwin(height, width, y, x);
box(menu, 0, 0);
keypad(menu, true);
selection = menuShow(filetypes, 4, menu);
endwin();

I am printing the array's values via the "menuShow" function. Here is the function's code as well:
int menuShow(string *choices, int opt, WINDOW *menu)
{

int i, highlight = 0;
system("clear");
noecho();
wchar_t buttonPress;
do
{
    refresh();
    wrefresh(menu);
    for(i = 0; i < opt; i++)
    {
        //xrwmatizei thn epilegmenh praksh sthn opoia vrisketai o cursor
        if(i == highlight)
        {
            wattron(menu, A_REVERSE);
            mvwprintw(menu, i + 1, 1, "%s", choices[i]);
            wattroff(menu, A_REVERSE);
        }
        else
        {
            mvwprintw(menu, i + 1, 1, "%s", choices[i]);
        }

    }
    wrefresh(menu);
    refresh();
    buttonPress = wgetch(menu);
    switch(buttonPress)
    {
        case KEY_UP:
            highlight--;
            if(highlight == -1)
                highlight++;
           break;
        case KEY_DOWN:
            highlight++;
            if(highlight > (opt - 1))
                highlight--;
            break;
        default:
            break;
    }

}while(buttonPress != 10);

return highlight;

The output I am getting is:
~P/~[#�^?
~P/~[#�^?
~P/~[#�^?
~P/~[#�^?

Any idea?
By the way, note that after the "endwin();" line, I am printing out the array's strings using cout and they are being printed normally. I think that the reason why this happens is due to the fact that "printw()" and ncurses' functions in general do not support "string" formats. So, my question is: Is there any possible method to print out a string type variable after the "initscr();" line?

A: The menuShow  uses the same type formatters as printf().
So "%s" is expecting a C-String (or char*).
You are proividing a std::string which is not the same.
int menuShow(string *choices, int opt, WINDOW *menu)

    ... STUFF

    mvwprintw(menu, i + 1, 1, "%s", choices[i]);
                                    ^^^^^^^^^^ this is a std::string

What you want to do is convert the std::string into a char* you can do this by calling c_str().
    mvwprintw(menu, i + 1, 1, "%s", choices[i].c_str());
                                           // ^^^^^^^^

You are using ncurses a (very cool but) C library. The problem here is the C language is not ss type safe as C++. In this case the C language provides variable number of arguments to mvwprintw() unfortunately the types of these arguments are not specified so the compiler does not check if you are passing a valid type (and thus no warning or error).
Note: C++ still provides this old style interface for backwards compatibility with C but in more modern C++ libraries you would use template varargs so that we can explicitly make sure the types are correct.

A: The format "%s" expects char*, not std::string. Try
mvwprintw(menu, i + 1, 1, "%s", choices[i].c_str());

Why do you do so
string *filetypes = new string[4];
filetypes[0] = ".png";
filetypes[1] = ".jpeg";
filetypes[2] = ".jpg";
filetypes[3] = ".gif";

Why not
string filetypes[4] = {
  ".png",
  ".jpeg",
  ".jpg",
  ".gif",
};


text:
Q: Can't enable GCloud debugger for Java 11 with App Engine standard environment We are not able to debug our Appengine Standard Java 11 project using Google cloud debugger
The debugger could not find a debug target for the application name (project-test).

Taking into consideration that The debugger is enabled by default; no configuration is required in App Engine standard environment, as mentioned in this document
So what could be the problem and how can I enable the GCloud debugger?

A: As per the App Engine documentation regarding issuing HTTP requests,  if you use URL Fetch, it will cause requests to cloud client libraries (and that includes the Google Cloud Debugger Client for Java) to fail.
Are you using an appengine-web.xml file?
If so, does it include the following?
<url-stream-handler>urlfetch</url-stream-handler>
If that is the case, could you try it without that line?


text:
Q: Create Custom Easing using Javascript I am trying to create a custom easing function and I am experiencing a few difficulties. In other words, the maths is confusing me...
I would like my function to increment the width of a some elements within my page, and the increment value needs to decrease as the index of the element increases.
Consider these values:
50, 150, 230, 280, 310, 330

Whilst I appreciate it is likely to be impossible to generate these exact values, I essentially want a function that will come close to those values.
Here is what I have so far:
$('.something').each(function(i){
    var scale = Math.round(30*(i/10)*(2-(i/10)));
    dimension = scale*dimension;
    console.log(dimension);
});

This may be extremely easy but I am struggling to get my head around the maths today so any help would be much appreciated

A: Here's a live demo that shows how you can use a quadratic ease-out function to achieve a curve similar to the one you describe.

var out = document.getElementById("output");

// t: current time, b: beginning value, c: change in value, d: duration

function easeOutQuad(t, b, c, d) {
  return -c *(t/=d)*(t-2) + b;
}

for (var i = 0; i < 1; i+=0.1) {
  out.innerHTML += Math.round(easeOutQuad(i, 50, 280, 1)) + "
";
}

Shout-out to @c-smile for linking the jQuery easeOutQuad function in the comments, which this demo is based on.

A: You could look through the Easing Functions Generator by Robert Penner. It may be very useful for creating custom easing functions:
// generated example
function(t, b, c, d) {
    var ts=(t/=d)*t;
    var tc=ts*t;
    return b+c*(63.2425*tc*ts + -185.23*ts*ts + 198.58*tc + -93.89*ts + 18.2975*t);
};


text:
Q: node.js module.export I'm struggling to understand what I am missing here:
FILE: Sprite.js
function Sprite() {
}

Sprite.prototype.move = function () {
}

module.exports = Sprite;

FILE: Ship.js
function Ship() {
}

Ship.prototype = new Sprite();

Ship.prototype.enable = function() {
}

FILE: Server.js
var util    = require('util'),
io  = require('socket.io'),
Sprite  = require('./sprite.js'),
Ship    = require('./ship.js');

var boo = new Ship(Sprite);

Outside of Node.js this works fine. In Node.js however it won't recognise Sprite in the ship file. I've tried using module.export = Sprite at the end of the sprite file with no success.
Cheers

A: Export Sprite in FILE: Sprite.js like this :
function Sprite() {
}

Sprite.prototype.move = function () {
}
exports.Sprite = Sprite;

Then inside FILE: Ship.js ( this is the tricky part you're missing ) use require to require the Sprite like this:
var Sprite = require('/path/to/Sprite');
function Ship() {
}

Ship.prototype = new Sprite();

Ship.prototype.enable = function() {
}

If a module exports smth, if you whant to use it then you need to require it (in the module you're trying to play with it, not in the main module) don't you?, how else is nodejs going to know where the ship ''class'' is ?
more info here

Edit, see this working ( all files need to be in the same directory or you'll need to change the require path )
File sprite.js :
var Sprite = function () {
}
Sprite.prototype.move = function () {
    console.log('move');
}
module.exports = Sprite;

File ship.js :
var Sprite = require('./sprite');
function Ship() {
}

Ship.prototype = new Sprite();

Ship.prototype.enable = function() {
    console.log('enable');
}

module.exports = Ship;

File main.js :
var Ship = require('./ship');

var boo = new Ship();

boo.move();
boo.enable();

Run the example using node main.js and you should see :
C:\testrequire>node main.js
move
enable

A: The problem is you didn't include module.exports = Sprite; at the end of the Sprite.js file. Note that I wrote exports and not export, so that typo must have been the problem.


text:
Q: how can the current flow if the potential difference is 0 volts? I have read so many articles on so many websites about transistors and everywhere it says that when transistor is acting as a closed switch and conducting the voltage across collector-emitter is 0 volts, so how can the current flow if the applied voltage across two points is 0 volts?

A: This is one of those situations where "ideal model" and "real physical system" differ; all real physical conductors (except superconductors, which are weird) have ohmic properties and a non-zero resistance. So the voltage won't be zero, it'll be nearly zero.
Educational models and many simulators round "nearly zero" to zero to reduce clutter.

A: In reality the voltage difference will seldom be zero.  If the transistor is switched fully on then the voltage drop will be small (much less than 1 volt).  To say that it's zero is an over-simplification

A: If the voltage is zero and the resistance is zero then: -
$$\text{Current} = \dfrac{0}{0}$$
In other words, you cannot determine what current is flowing by simple ohm's law.
Think about a pure inductor; you apply a voltage across it and current ramps up at a rate of: -
$$\dfrac{V}{L} \hspace{1cm}\text{amps per second}$$
After a short time you disconnect the voltage and instantly apply a short across the pure inductor. Current continues to flow indefinitely. It's not magic.

everywhere it says that when transistor is acting as a closed switch
and conducting the voltage across collector-emitter is 0 volts

Everywhere you have read that is either incorrect or, you have misread that information because it's a physical impossibility.


text:
Q: cleaning an inspiron 500 m
Possible Duplicate:
How do you clean your laptop?

I have been running my inspiron 500 m in a very dusty (plaster dust) environment. I would like to remove the bottom cover and clean the filter etc. Can you help?


text:
Q: X-Axis labels in excel graph are showing sequence of numbers instead of actual labels I have a chart as part of a template which gets plotted based on source data. Data seem to be fine but labels in x-axis are shown as sequence of numbers 1,2,3,4,etc., instead of actual labels(these change with source data).

A: I assume that the chart range was correct. In that case, change the chart range (i.e. change from A2:A5 to B2:B5), hit ok, than change the datasource back to the correct row / line.
This has solved the problem every time so far for me. Not sure what the source of the issue is, but it might be the "hide" feature.

A: For anyone else coming here for doing scatter plots, I discovered that since scatter plots are meant to correlate two numeric axes, you have to convert to a line chart, and then just delete the lines, and then you can set the Horizontal (Category) axis labels.

A: Edit the chart data and check the entries for "Horizontal (Category) Axis Labels". If you see numbers there instead of the desired text, click Edit and select the range where the text labels are.

A: I see the same issue with incorrect horizontal axis data being displayed. Excel will show the correct data for the horizontal axis from the data source when source data is initially chosen but then when checked in the future it reverts back to a integer sequence starting at 1. Maybe related to hide data which hides the horizontal axis but when un-hidden again, the data reverts to an integer sequence starting at 1 (not matching selected data source)


text:
Q: Enviar POST a PHP por medio de AJAX Necesito que al hacer clic en un botón por medio de POST me envíe un dato a un archivo PHP donde hago una consulta con ese parámetro que recibo para generar una gráfica. Lo he hecho por medio de un form, pero surge un inconveniente al hacer clic en ese botón: se debe abrir un modal con la gráfica adentro. Por lo tanto no se puede recargar la pagina.
He leído que se puede hacer con AJAX, pero nunca lo he usado y no lo entiendo mucho. No sé de qué otras maneras pueda realizar un POST sin necesidad de recargar la página.
Mi proyecto usa jQuery.

A: Hace tiempo escribí un post en un blog acerca de esto, si quieres probarlo es mas o menos asi:
Este seria tu html:
<!DOCTYPE html>

    <meta charset="UTF-8" />
    <title> Acción onclick en js </title>
    // Aquí esta la referencia a jquery

    <form method="post" id="formulario">
        <input type="text" name="usuario" placeholder="Usuario" autofocus/>
        <input type="password" name="contrasena" placeholder="Contraseña"/>
        <input type="button" id="btn-ingresar" value="Ingresar" />
    </form>
    // Este div nos servirá para cachar la respuesta enviada
    // por el backend en caso de que sea necesario.

y aquí tienes la acción del botón que enviará los datos de tu formulario a tu archivo php:
$(document).on('ready',function(){
    $('#btn-ingresar').click(function(){
        var url = "datos_login.php";
        $.ajax({
           type: "POST",
           url: url,
           data: $("#formulario").serialize(),
           success: function(data)
           {
             $('#resp').html(data);
           }
       });
    });
});

Esta es una parte de lo que vendría siendo tu archivo php llamada en este ejemplo como datos_login.php:
<?php
    $usuario = $_POST['usuario'];
    $contra  = $_POST['contrasena'];

    echo "tu usuario es: ".$usuario;
    echo "contraseña es: ".$contrsena;
?>

checalo y si tienes dudas puedes consultar la referencia del post que escribí aquí.
El código completo quedaría mas o menos así:
<!DOCTYPE html>

    <meta charset="UTF-8" />
    <title> Acción onclick en js </title>
    // Aquí esta la referencia a jquery

    <form method="post" id="formulario">
        <input type="text" name="usuario" placeholder="Usuario" autofocus/>
        <input type="password" name="contrasena" placeholder="Contraseña"/>
        <input type="button" id="btn-ingresar" value="Ingresar" />
    </form>
    // Este div nos servirá para cachar la respuesta enviada
    // por el backend en caso de que sea necesario.

Saludos.

A: Usando jquery es relativamente sencillo usar ajax, a continuación te coloco un ejemplo sencillo:
Este sería tu archivo HTML donde haces la llamada ajax

<title>Ejemplo sencillo de AJAX</title>

Introduce valor 1
<input type="text" name="caja_texto" id="valor1" value="0"/>
Introduce valor 2
<input type="text" name="caja_texto" id="valor2" value="0"/>
Realiza suma
<input type="button" href="javascript:;" onclick="realizaProceso($('#valor1').val(), $('#valor2').val());return false;" value="Calcula"/>

Resultado: 0

Ademas de este archivo tiene que tener un archivo que procese la petición ajax, este caso se llama ejemplo_ajax_proceso.php, este archivo contendrá lo siguiente:
<?php
$resultado = $_POST['valorCaja1'] + $_POST['valorCaja2'];
echo $resultado; //haciendo este echo estas respondiendo la solicitud ajax
?>

Intenta probando ese código, así tendrás una idea de como funciona ajax.

A: lo que necesitas es detectar tanto el click del que hace 2 acciones enviar formulario y detectar que se envie el form en todo caso primero desactivas el form de esta manera.
//detectamos el envio
$(document).on("submit","#idform",function(e){
    e.preventDefault();//detenemos el envio
    $("#myModal").modal();//dispara el modal equivale-> [ data-toggle="modal" data-target="#myModal" ]
    $.post("api/ruta/post.php",$("#idform").serialize(),function(res){
        $("#cargapost").html(res);//cargamos todo el resultado de la peticion en el 'div' que queremos, donde [id="cargapost"] se encuenta en el cuerpo del 'modal'
    });
    //$.post -> envia como POST, $.get -> envia GET
    //$("#idform").serialize() -> toma todos los campos del formulario identificando por el nombre [name="nombre"]
    //
})

esto detecta que el formulario se esta enviando y lo cancela, ya no se recarga la pagina.

  <form action="" id="idform">
   nombre
   <input type="text" name="nombre" class="form-control">
   valor
   <input type="text" name="valor" class="form-control">

   <input type="submit" class="btn btn-primary">
  </form>

Modal Heading

           <button type="button" class="close" data-dismiss="modal">×</button>

           <button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>

A: var url = 'aqui la url';
    $(document).ready(function () {
        load();

$('form').submit(function (e) {
                $.post(url, {mivariable: $('#clasedelinput').val(),  });
                $('#clasedelinput').val('');
                return false;

Ya es muy tarde pero seguro le puede servir a quien vino buscando una respuesta. Saludos.


text:
Q: Active Navbar State in React is Resetting I am trying to make the actively selected navbar element change the background color via react state. However it does not fully work. When I click on an element in my navbar, it briefly gets styled correctly, but after a moment is reverted and my homepage element in the navbar becomes styled once more.
I have my (simplified) navbar code below:
function Navbar(props) {
  const [clickedNavbarItem, setClickedNavbarItem] = React.useState("/");

  return (

         setClickedNavbarItem("/")}
          className={clickedNavbarItem === "/" && "active"}
          href="/"
          >Solve

         setClickedNavbarItem("/about")}
          className={clickedNavbarItem === "/about" && "active"}
          href="/about"
        >About

  )
}

To my understanding: When the user clicks a given anchor tag, it should run the onClick handler, which will re-assign the state. The navbar should then re-render, and the classname for the appropriately clicked item should have the "active" class, which should change the styling.
Additionally, the href should redirect the page as such (this is my React router code):
function App() {

  return (
    <>
      <Navbar />
      <Routes>
        <Route path="/" element={<Solve />} />
        <Route path="/about" element={<About />} />
        <Route path="/explain" element={<Explain />} />
      </Routes>
    </>
  )
}

I believe there is some interaction where the Navbar is getting reset perhaps when the href is activated, but I'm not entirely sure. Any help is appreciated.


text:
Q: Notify user when app is closed with no cloud service Is there any similar way to "Push Notification" but without the need to connect to a cloud service like azure? I want to notify user when countdown in my app is less than a day left but also I want to be able to notify him while app is closed.
I'm not sure how to use cloud services yet and so I'd like to know if there is a different way to do this. If not could you tell me what I need to do If I'd go with push notification?

A: A push notification by definition is pushed from off system, but you can schedule local notifications without a network.
Since the countdown has a predictable time you can calculate when that is and schedule tile notifications to fire appropriately.
I'd skip toasts for this unless the user authorized them. If the countdown is an app feature the user wants then toasts are probably good. If the countdown is to the end of a trial or such then something less in-your-face is more polite. Either way, you should update the Tile even if you show the Toast since Toasts can easily be missed.
The app schedules tiles and toasts essentially the same way: create a TileUpdateManager or ToastNotificationManager , create a ScheduledTileNotification or ScheduledToastNotificaiton with the tile or toast information to show and the due date, then call the manager's AddToSchedule with the scheduled notification. When the due date arrives the tile and toast will be delivered even if the app is closed.
See How to schedule a tile notification and How to schedule a toast notification for walkthroughs.


text:
Q: I am not able to see Click Wrap option all the time from my DocuSign sandbox account DocuSign have recently released Click Wraps at their Momentum. I would like to take advantage of this new feature and was exploring this a little.
 Once, I was able to add a few click wrap templates using my DocuSign sandbox account but at times, I do not see them when I click on "Manage" button once I login to my DocuSign demo account.
Please advise,
Thanks,
Minal

A: Hmmm. I suggest checking that you're logged into your DocuSign demo account (Developer Sandbox) as the administrator. Login via https://demo.docusign.net
Sometimes people login to a trial version of the DocuSign production systems by mistake (https://www.docusign.net). While Click agreements are provided in all demo accounts, they are only provided for some customer pricing plans on the production systems.
If the problem continues, you can create a demo account. Or contact DocuSign customer service.

A: We had a similar issue here and as a workaround after we logged into our demo account we were able to enter the url for the clickwraps directly to navigate to the clickwraps page.
https://appdemo.docusign.com/documents?view=active&type=clickwraps


text:
Q: Netbeans JGit github password authentication deprecated,. how to reset? I am using netbeans 8.2 to push to github but now get messages saying

You recently used a password to access the repository at XXX with git using JGit/3.6.2.201501210735-r.
Basic authentication using a password to Git is deprecated and will soon no longer work. Visit > https://github.blog/2020-12-15-token-authentication-requirements-for-git-operations/ for more > information around suggested workarounds and removal dates.
Thanks,
The GitHub Team

How can I reset my authentication to enter a github token (https://github.com/settings/tokens) instead of my password?

A: I've just faced with it.
Just generate token and use inplace of password.

A: See also https://issues.apache.org/jira/browse/NETBEANS-5252
To reset the password, I followed the instructions at Change Git remote password used by NetBeans, and entered my new github token to the password field. Copied from that answer:

Right click your project and go to Git -> Remote -> Push... Select 'Specify Git Repository Location', update your password, click Next. It may give you error again. Close the popup and try pushing again. You should be able to push now.

For my new token, since I only want to pull and push to the project, I used the default repo options.


text:
Q: Can solutions to the time-independent Schrodinger equation give solutions to the general equation if the potential is time dependent? I am reading through Griffiths Intro to Quantum, and he outlines how one can find solutions to the Schrodinger equation, by assuming the potential is constant in time (no time dependence), thus you can use separation of variables to get a time-independent equation, and find solutions to that equation as 'stationary states'. Then you use these stationary states in a linear combination to construct a general solution to the time dependent equation.
My question is, can you use these stationary states or some method of this form to construct a solution to the Schrodinger equation with a time-dependent potential (not constant in time). Griffiths says how his assumption in the book will be mostly just dealing with constant potentials, I want to know if you can use this method for non-constant potentials. If not, how do you solve it?

A: The general answer to your final question,

How do you solve the Schrödinger equation for a generic time-dependent Hamiltonian?

is somewhere between "it depends", "it's complicated", "good luck", "with brute-force numerics", and "you don't".
But if the question is: are there commonly-used settings in which the solutions of the time-independent Schrödinger equation are useful for understanding the behaviour driven by a time-dependent Hamiltonian? then the answer is yes.
It happens very frequently that we have systems with Hamiltonians of the form
$$
\hat H(t) = \hat H_0 + \hat V_I(t),
$$
where $\hat H_0$ is (i) very complicated but (ii) time-independent, and $\hat V_I(t)$ is time-dependent but much simpler, and typically represents some form of interaction. One good example of such a setting is that of a many-electron atom driven by a laser field, where $\hat H_0$ is a complex multi-electron beast which involves lots of kinetic energies, spin-orbit couplings, and electrostatic interactions, plus a lot of correlation involved in its eigenstates, and where $\hat V_I(t)$ is just the dipole moment operator of each electron taken separately from the others, and multiplied by a simple sinusoidal function of time.
In this case, there is going to be a lot of hard work involved in solving for the eigenstates of $\hat H_0$, but this only needs to be done once, typically in advance. And once you have that, then you can have a much easier time in treating the effect that $\hat V_I(t)$ has in promoting transitions between the different eigenstates of $\hat H_0$.
If you want to see how this works in a general setting, then you should look up Time-Dependent Perturbation Theory in your favourite advanced-QM textbook.
Of course, it bears mentioning that this is not the only approach that fits the description you've given but that is too broad to provide an exhaustive list.


text:
Q: Convert Byte Array to Image: Parameter is not valid I am storing images in a database and would like to convert them from byte array to image. I have no problem converting an object to byte array but I get an error of "Parameter is not valid" when trying to convert from byte array to image. The object I am passing to my method is from a dataset row.
Stored procedure
USE [----------------]
GO
/****** Object:  StoredProcedure [dbo].[usp_imageloader_add_test]    Script Date: 01/16/2012    09:19:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER   procedure [dbo].[usp_imageloader_add_test]
@p_Image Image

as

INSERT into Test_Images VALUES(@p_Image)

Upload File control /convert Image file to byte array and save data to database
 protected void btnUpload_Click(object sender, EventArgs e)
    {
        if (ctrlUpload.PostedFile != null)
        {
            if (ctrlUpload.PostedFile.ContentLength > 0)
            {
                // Get Posted File
                HttpPostedFile objHttpPostedFile = ctrlUpload.PostedFile;

                // Find its length and convert it to byte array
                int ContentLength = objHttpPostedFile.ContentLength;

                // Create Byte Array
                byte[] bytImg = new byte[ContentLength];

                // Read Uploaded file in Byte Array
                objHttpPostedFile.InputStream.Read(bytImg, 0, ContentLength);

                using (SqlConnection dbConnection = new SqlConnection(app_settings.sql_conn_string_db))
                {
                    try
                    {
                        string sql = "usp_imageloader_add_test";
                        SqlCommand cmd = new SqlCommand(sql, dbConnection);
                        cmd.CommandType = System.Data.CommandType.StoredProcedure;
                        cmd.Parameters.AddWithValue("@p_Image", bytImg).SqlDbType = SqlDbType.Image;
                        cmd.Connection.Open();
                        cmd.ExecuteNonQuery();
                        cmd.Connection.Close();
                    }

                    catch (Exception ex)
                    {
                        ex.Message.ToString();
                    }
                }
            }
        }
    }

Convert object to byte array and to image
 private System.Drawing.Image ObjToImg(object obj)
    {
        byte[] byteArray;
        if (obj == null)
            return null;
        else
        {
            BinaryFormatter bf = new BinaryFormatter();
            MemoryStream ms = new MemoryStream();
            bf.Serialize(ms, obj);
            byteArray = ms.ToArray(); // Byte Array
            ms.Close();

            ms = new MemoryStream(byteArray, 0, byteArray.Length);
            ms.Seek(0, SeekOrigin.Begin);
            System.Drawing.Image returnImage = System.Drawing.Image.FromStream(ms);
            return returnImage;
        }

Any ideas would be helpful.

A: Image.FromStream is probably throwing an ArgumentException because the image format is invalid.  Expecting a random serialized object to be formatted as a valid image is not reasonable.

A: Try the following, your stream may not be initialized to the beginning:
ms = new MemoryStream(byteArray, 0, byteArray.Length);
ms.Seek(0, SeekOrigin.Begin);
System.Drawing.Image returnImage = System.Drawing.Image.FromStream(ms);

What type of image is it?  Are you sure the image that is stored is valid?
Also just a comment on usage (won't affect your issue), it is good practice to use a using statement when working with streams.  Eg:
using (MemoryStream ms = new MemoryStream())
{
    // your code here
}

A: Is the data you're using raw RGB data?  If so, there's a user comment in the docs for FromStream() that mentions that the method will throw if the stream contains raw RGB data: http://msdn.microsoft.com/en-us/library/93z9ee4x.aspx (see the bottom of the page); it recommends using a Bitmap instead (http://msdn.microsoft.com/en-us/library/zy1a2d14.aspx).

A: The solution by Kelsey should work. This is because, when you read data from byteArray to memory stream, the pointer is placed at the end of the stream, and now when you try to read data from this memory stream, it tries to read head of this pointer, and as there is no data after this, you get an error. Now if you do ms.Seek(0, SeekOrigin.Begin);, the reader pointer is placed at the beginning of the memory stream. And dispose the memory stream when you are done using it ms.Dispose(). Hope this helps.

A: You don't need the binary formatter, that's what's messing with your data, it's for serializing objects really.
The key thing to note is that the object is a byte array already so you can just cast it and use that.
Try this:-
    private System.Drawing.Image ObjToImg(object obj)
    {
        if (obj == null)
            return null;
        else
        {
            byte[] byteArray = (byte[])obj;
            System.Drawing.Image returnImage;
            using (var ms = new MemoryStream(byteArray, 0, byteArray.Length))
            {
                returnImage = System.Drawing.Image.FromStream(ms);
            }
            return returnImage;
        }
    }


text:
Q: Pass data to previous viewcontroller VIPER I am using VIPER architecture in iOS swift. I have 2 viewcontrollers, let's say A and B. At first I'm going from A to B, performing some tasks and coming back from B to A. With MVC or MVVM, we can create protocols and transfer data from B to A. But for VIPER, i am confused. Here's my VIPER code B, while Back button is tapped:
View:
@IBAction func backButtonTapped(_ sender: UIButton) {
    presenter?.goBack()
}

Presenter:
func goBack() {
    router.back()
}

Router:
func back() {
    viewController?.navigationController?.popViewController(animated: true)
    //here I want to send data back to previous viewcontroller
}

I have tried creating one method in the Router of previous controller and sending the data through that method but it is not working as router doesn't have any instance of presenter or anything else, except view.

A: Note:-  In Viper Router is Unidirectional.
So this might help you.

*

*Implement ProtocolDelegate in Current Module's VC

*Create a delegate variable in the Next Module's Router

*Then Simply Send Delegate Dependancy to Next Module's Router

*And Call your delegate method from Next Module's Router.

Module A
final class VCA: SomeProtocolDelegate {
 fund someMethod() {
      //Your task Action From Module B
    }
 }

final class ModuleARouter: WireFrameProtocol {
    fund gotoModuleB(withView vc: VCA) {
       ModuleBRouter.load(onView: vc)
    }
}

Module B
final class ModuleBRouter: WireframeProtocol {
    internal weak var delegate: SomeProtocolDelegate?
    // Here you  can add more argument on load method for delegate
    // since in this example i'm send data back ViewController So I didn't create
    class func load(onView VC: UIViewController) {
        //setup your VIPER protocol and class
        if let vCA = VC as? VCA {
            router.delegate = vCA
        }
    }

   func backToPreviousModule() {
      self.delegate?. someMethod()
   }
}


text:
Q: Excel VBA code to return weekday name from a date then autofilters for userdefined weekdays and copies autofiltered data to new sheet I spent last night looking for an answer to my question but i didn't find anything specific to my ask.
I have a huge sheet that contains lots of data.  In Column A, I have the Date and time. I would like to have a VBA code that does few actions.
1) Insert a column B next to column A that gives the weekday name. For example if the date in column A is January 10, 2016 8:30  then column B will have "Sunday"
2) Then the VBA code to filter this sheet based on Column B. For instance given a user input of a particular day (example Friday), the autofilter will filter for 4 days ahead ( Friday, Saturday, Sunday, Monday ).
3) The result of the autofilter then is copied to new blank sheet.
4) In the new sheet I want the vba to delete any row data for the same user defined day ( example Friday ) that has time of less than user defined time (example 8:00 am) in Column A. Finally shifting cells up to remove any blank rows.
Hope I am not overwhelming you with this problem, but I hope I get feedback from one of the brilliant minds in here
Here it the code attempted for part 1
Sub sbInsertingColumns()
Worksheets("Imported").Activate
'Inserting a Column at Column B
If Range("B1").Value = "Weekday" Then
Range("B1").Value = "Weekday1"
Else
Range("B1").EntireColumn.Insert
Range("B1").Value = "Weekday"
Worksheets("Imported").Range("B2").Formula = "=choose(weekday(A2),""Sunday"",""Monday"",""Tuesday"",""Wednesday"",""Thursday"",""Friday"",""Saturday"")"
LastRow = Range("A" & Rows.Count).End(xlUp).Row
Range("B2").Copy Range("B2:B" & LastRow)
End If
End Sub

A: This is only to get you started.
If A2 contains a genuine Excel date/time, then in B1 enter:
=TEXT(A2,"dddd")

If you want a VBA macro to accomplish your project, start by turning on the macro recorder and performing the task once manually.
You will then have a macro that you can begin to optimize and generalize.


text:
Q: Can I use a JSP tag library with FreeMarker for a non-web context? I was investigating FreeMarker (and also Velocity), and one of the things I liked about FreeMarker was that I could use it with my existing JSP tags.  However, it's become my understanding that this will only work when using FreeMarker as a view for servlets.  Is there a way to use these JSP tag libraries with either FreeMarker or Velocity in a non-servlet context, i.e. for generating email messages?

A: There is a way, but it's not exactly pretty :)
FreemarkerServlet (or Spring's view resolver, if you're using Spring MVC) exposes JspTaglibs hash that you need in order to use tags in templates and emulates JSP environment used by tags (scopes in particular). You'll have to do it yourself in your email processor.
See details here: Using JSP custom tags in FTL