text:
Q: From json file to String[] I am not able to find the error android app is forcefully stopped. When I use the general sample data which is commented in this program it works fine but when i use this code it gets crashed.
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Locale;

import android.os.Bundle;
import android.app.Activity;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.widget.EditText;
import android.widget.ListView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class MainActivity extends Activity {

    // Declare Variables
    ListView list;
    ListViewAdapter adapter;
    EditText editsearch;
    String[] rank;
    String[] country;
    String[] population;
    ArrayList<WorldPopulation> arraylist = new ArrayList<WorldPopulation>();

    public String loadJSONFromAsset() {
        String json = null;
        try {
            InputStream is = getAssets().open("data.json");
            int size = is.available();
            byte[] buffer = new byte[size];
            is.read(buffer);
            is.close();
            json = new String(buffer, "UTF-8");
        } catch (IOException ex) {
            ex.printStackTrace();
            return null;
        }
        return json;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.listview_main);

        try {
            JSONObject obj = new JSONObject(loadJSONFromAsset());
            JSONArray m_jArry = obj.getJSONArray("maindata");
            rank = new String[m_jArry.length()];
            country = new String[m_jArry.length()];
            population = new String[m_jArry.length()];
            for (int i = 0; i < m_jArry.length(); i++) {
                JSONObject jo_inside = m_jArry.getJSONObject(i);
                rank[i] = jo_inside.getString("rank");
                country[i] = jo_inside.getString("country");
                population[i] = jo_inside.getString("population");
                System.out.println(rank[i]);
            }
        }catch (JSONException e){
            e.printStackTrace();
        }
        // Generate sample data
        /*rank = new String[] { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10" };

        country = new String[] { "China", "India", "United States",
                "Indonesia", "Brazil", "Pakistan", "Nigeria", "Bangladesh",
                "Russia", "Japan" };

        population = new String[] { "1,354,040,000", "1,210,193,422",
                "315,761,000", "237,641,326", "193,946,886", "182,912,000",
                "170,901,000", "152,518,015", "143,369,806", "127,360,000" };*/

        // Locate the ListView in listview_main.xml
        list = (ListView) findViewById(R.id.listview);

        for (int i = 0; i < rank.length; i++)
        {
            WorldPopulation wp = new WorldPopulation(rank[i], country[i],
                    population[i]);
            // Binds all strings into an array
            arraylist.add(wp);
        }

        // Pass results to ListViewAdapter Class
        adapter = new ListViewAdapter(this, arraylist);

        // Binds the Adapter to the ListView
        list.setAdapter(adapter);

        // Locate the EditText in listview_main.xml
        editsearch = (EditText) findViewById(R.id.search);

        // Capture Text in EditText
        editsearch.addTextChangedListener(new TextWatcher() {

            @Override
            public void afterTextChanged(Editable arg0) {
                // TODO Auto-generated method stub
                String text = editsearch.getText().toString().toLowerCase(Locale.getDefault());
                adapter.filter(text);
            }

            @Override
            public void beforeTextChanged(CharSequence arg0, int arg1,
                                          int arg2, int arg3) {
                // TODO Auto-generated method stub
            }

            @Override
            public void onTextChanged(CharSequence arg0, int arg1, int arg2,
                                      int arg3) {
                // TODO Auto-generated method stub
            }
        });
    }
}

Json file contains :
{
    "maindata": [
        {
            "country": "rumbo",
            "rank": "45",
            "population": "45000"
        },
        {
            "country": "reck",
            "rank": "46",
            "population": "4500"
        }
    ]
}

01-13 06:22:27.024 2057-2057/? E/memtrack: Couldn't load memtrack module (No such file or directory)
01-13 06:22:27.024 2057-2057/? E/android.os.Debug: failed to load memtrack module: -2
01-13 06:22:27.045 2057-2070/? E/art: Thread attaching while runtime is shutting down: Binder_2
01-13 06:22:27.406 2073-2073/? E/memtrack: Couldn't load memtrack module (No such file or directory)
01-13 06:22:27.406 2073-2073/? E/android.os.Debug: failed to load memtrack module: -2
01-13 06:22:27.707 2086-2086/? E/AndroidRuntime: FATAL EXCEPTION: main
                                                 Process: com.robosoft.elections, PID: 2086
                                                 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.robosoft.elections/com.robosoft.elections.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.length()' on a null object reference
                                                     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
                                                     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
                                                     at android.app.ActivityThread.access$800(ActivityThread.java:144)
                                                     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
                                                     at android.os.Handler.dispatchMessage(Handler.java:102)
                                                     at android.os.Looper.loop(Looper.java:135)
                                                     at android.app.ActivityThread.main(ActivityThread.java:5221)
                                                     at java.lang.reflect.Method.invoke(Native Method)
                                                     at java.lang.reflect.Method.invoke(Method.java:372)
                                                     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
                                                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
                                                  Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.length()' on a null object reference
                                                     at org.json.JSONTokener.nextCleanInternal(JSONTokener.java:116)
                                                     at org.json.JSONTokener.nextValue(JSONTokener.java:94)
                                                     at org.json.JSONObject.<init>(JSONObject.java:156)
                                                     at org.json.JSONObject.<init>(JSONObject.java:173)
                                                     at com.robosoft.elections.MainActivity.onCreate(MainActivity.java:55)
                                                     at android.app.Activity.performCreate(Activity.java:5933)
                                                     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
                                                     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
                                                     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
                                                     at android.app.ActivityThread.access$800(ActivityThread.java:144)
                                                     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
                                                     at android.os.Handler.dispatchMessage(Handler.java:102)
                                                     at android.os.Looper.loop(Looper.java:135)
                                                     at android.app.ActivityThread.main(ActivityThread.java:5221)
                                                     at java.lang.reflect.Method.invoke(Native Method)
                                                     at java.lang.reflect.Method.invoke(Method.java:372)
                                                     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
                                                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
01-13 06:22:27.754 735-735/? E/EGL_emulation: tid 735: eglCreateSyncKHR(1181): error 0x3004 (EGL_BAD_ATTRIBUTE)

A: You need to create asset folder on right location in you project directory.
For that follow following direction:
1. switch to Project Files from dropdown on top of project tab.
2. Navigate to app > src/main.
3. Create asset directory in src/main directory and copy data.json file.
And you are good to go.


text:
Q: writing an if-else function which returns 2 values I am working with the below function, basically will return with both delta and gamma value, may I know between the calldelta & calleval, so is putdelta & puteval, how may I use operator to connect the 2 return values together? Tried & with no luck. Many thanks for your attention.
library(optionstrat)
library(quantmod)

x=160
sigma=0.25
t=0.25
r=0.05
    delta<-function(option_type,stock_price)
    {
      if (option_type=="c")
      calldelta(s,x,sigma,t,r)
      calleval(s,x,sigma,t,r)$Gamma
    else
      putdelta(s,x,sigma,t,r)
      puteval(s,x,sigma,t,r)$Gamma
    }

A: Looks like calldelta and calleval respectively are functions and not sure what these functions are returning (values or dataframes).
But, store the values in variable:
delta <- function(option_type,stock_price) {
  if (option_type=="c") {
  v1 <- calldelta(s,x,sigma,t,r)
  v2 <- calleval(s,x,sigma,t,r)$Gamma
  print(paste0(v1, ' and ', v2), collapse=NULL)
} else {
 v3 <-  putdelta(s,x,sigma,t,r)
 v4 <-  puteval(s,x,sigma,t,r)$Gamma
 print(paste0(v3, ' and ', v4), collapse=NULL)
}

}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Почему изменяется значение поля класса после его использования в цикле, который ни разу не исполнится? вот есть фрагмент кода на языке программирования Java:
public class TestClass{
    static int x = 10;
    public static void main(String[] args)
    {
        for(x = 5;x<5;x++){}
        System.out.println(x);
    }
}

..................................................
х=5.
// на выходе, после компиляции ,получается ответ х=5. Так вот объясните почему, я не понимаю.

A: В этом for предложении
for(x = 5;x<5;x++){}
    ^^^^^

вы явно присвоили значение 5 статическому члену класса x.
Это значение и выводится в следующей строке:
System.out.println(x);

Предложение for выполняется следующим образом. Сначала вычисляется его первая часть инициализации x = 5;, а лишь затем проверяется условие x < 5;
Так как условие будет равно false, то ни одной итерации цикла не выполнится. Тем не менее члену класса x уже будет присвоено новое значение.

A: Потому, что вот здесь for(x = 5;x<5;x++){} присваивается х число 5. И следовательно ответ  х=5.


text:
Q: 3 SVG's on the same page I'm trying to display 3 animated svg's on the homepage of our future website.
When animating the each svg separately (each on a single page) it works fine.
But, when animating them on the same page, they don't render prorperly, as the second svg displays some elements of the first one, and same thing for the third one taking elements from the second one.
I'm guessing it's due to the name of different masks, but I've tried renaming them, and the problem still happens.
I'm running out of solutions. Is there a SVG expert out there then can help? That would be super cool. Thank you!
Here is a test page with the 3 svg's. https://dl.dropboxusercontent.com/u/1699508/index.html
Each SVG has 3 states:

*

*State 1 is "S0" on page-1

*State 2 is "S0 SAnimStart" on page-1

*State 3 is "S1 visible" on page-2

Thank you all :)

A: All SVGs are part of the HTML-DOM and all keyframe definitions too. And so there is a multiple use of ids, for instance id="page-1". Use unique ids or bind your animations on the css classes of the layers.


text:
Q: Does Enumerable.AsEnumerable<>() force the evaluation of the expression? string[] fruits = { "apple", "passionfruit", "banana", "mango",
                  "orange", "blueberry", "grape", "strawberry" };
List<int> lengths = fruits.Select(fruit => fruit.Length).ToList();

Enumerable.ToList() or Enumerable.ToArray() performs eager evaluation, they force the evaluation.
Does Enumerable.AsEnumerable() do the same ?
Thanks

A: In short, no. It does absolute nothing at all, it just return the input collection, typed with a different interface.
It's only practical purpose it to switch from IQueryable<T> to IEnumerable<T>, so that further LINQ methods are performed with the enumerable version instead of the queryable, making evaluation to go to "client-side".
But, in itself, it doesn't do anything.


text:
Q: Why does this websocket client enter an infinite loop at the end of main()? #include <libwebsockets.h>
#include "src/libs/callback.h"
#include "src/libs/websocket_client.h"

class websocket : public websocket_client, public client_callback_t {
    bool run_ = true;
public:
    websocket() : websocket_client(this, "ws-feed.pro.coinbase.com") {}

    [[nodiscard]] bool working() const noexcept { return run_; }

    void on_connected() override {
        lwsl_user("client connected\n");
        std::string msg = R"({ "type": "subscribe", "product_ids": [ "ETH-USD", "ETH-EUR" ], "channels": [ "level2", "heartbeat", { "name": "ticker", "product_ids": [ "ETH-BTC", "ETH-USD" ] } ] })";
        send(msg.data(), msg.size());
    }

    void on_disconnected() override {
        lwsl_user("client disconnected\n");
    }

    void on_error(const char *msg, size_t len) override {
        lwsl_user("client error\n");
    }

    void on_data(const char *data, size_t len, size_t remaining) override {
        std::string msg(data, len);
        lwsl_user("data from server: %s\n", msg.c_str());
    }
};

int main() {
    lws_set_log_level(LLL_USER | LLL_ERR | LLL_WARN | LLL_NOTICE, nullptr);
    websocket client;
    client.connect();
    while (client.working()) {
    }
    return 0;
}

Source
What is the purpose of the while loop inside the main function?
If I delete it, the program segfaults.

A: @user2994219 found the issue in comments.

I found the content inside stop() function cause the segfault when the main function exit. The stop() function was called inside the ~websocket_client(). Move stop() to the beginning of the destructor solve the problem.

This allows the program to exit cleanly without a segmentation violation.


text:
Q: Jquery Error - Switch on / off link I have a link text that acts as a switch on/off button and I'm trying to use it without any page reload.
When turned off, the link has a certain class, url and text value different from the turned-on state. (ie turned on it appears green / turned off it appears red )
A little below you have the jquery code I'm using for the moment.
$('.off').click(function() {
    var element = $(this);
    var link = $(this).attr('href');
    var newlink = link.replace('off','on');
    $.get(link, function(data) {
    $('#front').html(data);
    $('#front').center().show();
    $('#background').show();
    if( data == "Button switched." ) { element.attr('href', newlink); element.text('on'); element.attr('class', 'on'); }
    });
    return false;
            });

$('.on').click(function() {
    var element = $(this);
    var link = $(this).attr('href');
    var newlink = link.replace('on','off');
    $.get(link, function(data) {
    $('#front').html(data);
    $('#front').center().show();
    $('#background').show();
    if( data == "Button switched off." ) { element.attr('href', newlink); element.text('off'); element.attr('class', 'off'); }
    });
    return false;

          });

and the HTML element I'm talking about looks like this:
on
So, if the element that looks exactly like above is being clicked, the button is being switched to off and all the links attributes are being changed, but when I click the second time ( on the link with the new attributes ) it makes the ajax request and it's giving me the result in #front but it wont change the link's attributes again, as it should.
What's the problem?

A: You are switching the classes so when it initially loads .on doesn't exist yet so no events are registered for that. You can solve this by using event delegation.
$(document).on('click', '.off', function() {
    var element = $(this);
    var link = $(this).attr('href');
    var newlink = link.replace('off','on');
    $.get(link, function(data) {
    $('#front').html(data);
    $('#front').center().show();
    $('#background').show();
    if( data == "Button switched." ) { element.attr('href', newlink); element.text('on'); element.attr('class', 'on'); }
    });
    return false;
            });

$(document).on('click', '.on', function() {
    var element = $(this);
    var link = $(this).attr('href');
    var newlink = link.replace('on','off');
    $.get(link, function(data) {
    $('#front').html(data);
    $('#front').center().show();
    $('#background').show();
    if( data == "Button switched off." ) { element.attr('href', newlink); element.text('off'); element.attr('class', 'off'); }
    });
    return false;

   });

By the way try not to use document, instead use any container's selector that exists in DOM at any point in time. i.e $('.somContainerSelector').on('click', '.off', function() {..
You can try to simplify from having duplicate code in 2 handlers to one handler $(document).on('click', '.on, .off', function() { as the difference is all about the text on and off.

A: When you do $('.off').click(function() {..., the click handler is attached to all .off element which exist at the time the code is executed.  When this code executes, there are no .off elements.
You should probably just use a single click handler and then have some logic to determine which state it is currently in, or store the state in a variable.

A: The probleme is that even if you change the class, it still have the binding of off and never actually get the binding of on.
The binding are aplied on DOM ready. Since your tag only have off class, on is not applied and off will alvays trigger.
Use .on() binding like that:
$(document).on('click', '.off', function(){...})
$(document).on('click', '.on', function(){...})
//Document should be a selector of the closest non-dynamic parent.

and it will work.
Also, since the code is almost the same, you can wrap it in 1 function :
$('.off').click(function() {
    var element = $(this);
    var link = element.attr('href');
    var isOff = element.hasClass('off')
    var newlink = isOff ? link.replace('off','on') : link.replace('on','of')
    $.get(link, function(data) {
        $('#front').html(data);
        $('#front').center().show();
        $('#background').show();
        if( data == "Button switched." ) {
            element.attr('href', newlink);
            element.text(isOff ? 'on' : 'off');
            element.toggleClass('on off');
        }
    });
    return false;
});

A: Try and see if this works
$(document).on('click', '.on, .off', function() {
        var element = $(this);
        var link = $(this).attr('href');
        var newlink = link.replace('on','off');

        $.get(link, function(data) {
           $('#front').html(data).center().show();
           $('#background').show();
              if( data == "Button switched off." ) { element.attr('href', newlink); element.text('off'); element.removeClass('on').addClass('off'); }
              else if( data == "Button switched." ) { element.attr('href', newlink); element.text('on'); element.removeClass('off').addClass('on'); }
        });

        return false;

     });

A: Give this code a try. Replace your two click functions with this single one:
$(document).on('click', '.on, .off', function () {
        var $element = $(this);
        var newmode = $element.hasClass('on') ? "off" : "on";
        var link = $(this).attr('href');
        var newlink = (link.match('on')) ? link.replace('on','off') : link.replace('off', 'on');
        $.get(link, function (data) {
                $('#front').html(data);
                $('#front').center().show();
                $('#background').show();
                if (data == "Button switched" + ((newmode == "off") ? " off" : "") + ".") {
                    element.attr('href', newlink);
                    element.text(newmode);
                    element.removeClass('on off').addClass(newmode);
                }
            });
        return false;
    });

Here's what this accomplishes:

*

*Changes the click function to a $.on() function. I think switching the class back and forth was causing the $.click() function to lose its binding to the element. $.on() should prevent that

*Removes the duplicate code you had in both click functions and unifies it all together.


text: Q: Is it possible to keep the indexing of a project in eclipse? I haven't used eclipse in a long time, and I'm not very familiar with it, so this question may sound silly. I have a big project, and indexing takes a long time in eclipse. The problem is every time I close eclipse, I should rebuild the indexer. This process takes more than 3 or 4 hours, and I don't want to keep eclipse open all the time. Is it possible to not need reindexing after closing eclipse?


text:
Q: iAD doesn't show on 3.5" screen? I built my app for a 4" screen. In order for everything to show up on a 3.5" screen I checked the option Use Autolayout.
I have a iAD Banner view at the bottom of my 4" Storyboard screen. Whether or not I check the Use Autolayout button, the Ad doesn't show up when I run my app on 3.5" simulator.
If I move my banner view up so it shows on the 3.5" it also moves it up on the 4" simulator.
How do I get it so the iAD shows at the bottom of both 3.5" and 4" screens and hopefully with the AutoLayout still checked which saves me a lot of time.

A: set constraints on your iAd banner


text:
Q: Should I use weak self inside a computed property's closure? I am confused about using self inside a closure.
When should we declare [weak self] ? An obvious case that I understand is
class Foo{

    var closure: ( Void -> Void )?
    var x = 0

    func doSomething(){
        closure = { [weak self] in
            if let x = self?.x{
                println(x)
            }
        }
    }
}

However, if I want to create a computed property bar, which it has a closure, and it captures self inside. Like this,
extension Foo{

    var bar: Bar{
        let bar = Bar()
        bar.completionHandler = {
            println(self.x)
        }
        return bar
    }
}

Should I use [weak self] inside this closure?

A: Consider:
extension Foo {
    var bar: Bar {
        let bar = Bar()
        bar.completionHandler = {
            print(self.x)
        }
        return bar
    }
}

Should I use [weak self] inside this closure?

Usually when people ask this question, the real concern is "do I need [weak self] to avoid strong reference cycle?" The answer to that is, no, there is no strong reference cycle here.
If bar were a stored property, the absence of [weak self] would raise red flags. It could easily be problematic if we had a Foo that stored a reference to a Bar which, itself, had a closure with a self reference back to the original Foo. But with this computed property, Foo doesn't have any strong reference to bar, so the strong reference cycle concerns are largely diminished.
That having been said, I have a hard time imaging where I wouldn't want to use [weak self]. If bar has a completionHandler, that means it's likely used in some asynchronous scenario, and the question is whether Foo needs to be retained during this process.
So, the real question of "should" you use [weak self] comes down to what Bar is, and whether it has any reasonably claim of ownership over Foo.
Let's try to come up with a practical example. (The following is a bit contrived, because I have a hard time imaging a good use-case for this pattern, but bear with me.)
For example, let's assume that Foo was a Person object and Bar was some URLSessionTask for the image download task:
class Person {
    let name: String
    private(set) var image: UIImage?

    ...
}

extension Person {
    var imageTask: URLSessionTask {
        let url = ...
        return session.dataTask(with: url) { [weak self] data, _, _ in
            guard let data = data, let image = UIImage(data: data) else { return }

            self?.image = image
        }
    }
}

So a controller might say
let person = Person(...)
let task = person.imageTask
task.resume()

In the above example, I happened to use [weak self] in imageTask closure, not because I was worried about any strong reference cycle, but simply because a network task generally has no business claiming a strong reference over the model object. (Then, again, I wouldn't personally bury network interfaces in model objects, either.) But in this example, one could omit [weak self] reference for this closure if, for example, you wanted to make sure that the Person object was retained until the network request was done (e.g. maybe you wanted to save the results of the network request in some local persistent storage).
All of this having been said, I have a really hard time imaging where I would use the above pattern at all. But the bottom line is that there is no strong reference cycle here, so you theoretically could omit the [weak self] without concern. But in most practical scenarios, you generally would end up using [weak self].


text:
Q: What is the Incoming Radiation on the Earth's Surface? Why is it that the incoming radiation is spread over an area of a disc = πr^2 rather than half the surface area of the earth?

A: The Earth intercepts an amount of solar radiation equivalent to that falling on a disc with its same radius, facing the Sun, but the Earth itself is (roughly) spherical, so that radiation will spread over half its surface area.

A: The shadow of the Earth indicates the light area that it absorbs. The shadow is a disk. Remember that light that strikes at an angle (like sunlight that strikes the Earth at dawn or dusk) is less intense.

A: First assume the light source is far enough away that all light rays are parallel. Then the shadow would be the disk you refer to. This means that that much light struck the Earth. However, that light is not distributed evenly over the lit half of the Earth. (That is why we have seasons).


text:
Q: Use XML to retrieve/insert data into SQL database I have some spare time so I was reading about xml
it says here:
XML can be generated from a database
with this code:
<%
response.ContentType = "text/xml"
set conn=Server.CreateObject("ADODB.Connection")
conn.provider="Microsoft.Jet.OLEDB.4.0;"
conn.open server.mappath("/db/database.mdb")

sql="select fname,lname from tblGuestBook"
set rs=Conn.Execute(sql)

response.write("<?xml version='1.0' encoding='ISO-8859-1'?>")
response.write("<guestbook>")
while (not rs.EOF)
response.write("<guest>")
response.write("<fname>" & rs("fname") & "</fname>")
response.write("<lname>" & rs("lname") & "</lname>")
response.write("</guest>")
rs.MoveNext()
wend

rs.close()
conn.close()
response.write("</guestbook>")
%>

after I read from the table and change data that I want, can I add the new data in the sql table again?


text:
Q: Not able to get text for an element using Selenium I am trying to fetch text from an element using WebDriver.getText() method but I am getting an empty string always.
Following are the details:
Environment:
Web Browser: Chrome
Version: 48.0
Chrome Driver Version: 2.20
Application:
On my home page I click on a menu option that creates a drop down menu on the screen and the element, I am trying to get text from, is one of the element in this drop down menu.
DOM:

some data

          <li ng-repeat="profile in data | filter: { userType : 'RegularUser'} | orderBy : 'displayName' : profileOrdering" ng-click="togglePanel($index, profile);" class="profile-titles ng-scope setting-dropDown-firstP" id="selectProfile_0" ng-class="{'activeProfile':(profile.isActive && !showProfileOption),'clickedProfile':($index == currentIndex && showProfileOption),'setting-dropDown-firstP':(($index == 0) && (data.length <= 3))}">

T

Test Profile

I am interested in getting the text "Test Profile" from above code.
XPATH:
I am using the following XPATH to reference the element:
//div[@id="showProfile"]//li[@id="selectProfile_0"]/div[contains(@class, "profileName")]

XPath Helper extension in chrome is telling me that my xpath is unique but when I try to do a getText on element identified by this xpath I get an empty string.
Java Code:
List<WebElement>list  = getProfileList();  //this function checks if element is visible and if it is visible it adds it in to the list and returns it.
for(Webelement e : list)
{
    System.out.println(e.getText());
}

Further to this I have tried getAttribute("innerHTML"), getAttribute("innerText") and few java scripts as suggested in this answer (to be honest I do not understand them but I have still tried them) and I did not find success.
I will really appreciate any help.
Thanks

A: Try below code :
WebElement element = driver.findElement(By.xpath("//div[contains(text(),'Test Profile')]"));
String text = element.getText();

A: Try with click the "select" dropdown and try to get
Note: Make sure You are in correct frame

A: First open the drop down, find the parent WebElement and in parent WebElement find WebElement profileName and use getText() method.
Try below code:
WebElement parentElement = driver.findElement(By.className("settingsDropDown"));
WebElement profileName = parentElement.findElement(By.className("profileName ));
String text = profileName.getText();


text:
Q: Scheduling with variable Resources (First of all, sorry for my english, it's not my first language)
I have a list of tasks/jobs, each task must start after a specific start time, needs to run for a certain time and has to be finished after a certain end time.
I can dynamically add and remove workers, so it is possible to execute 2 or more tasks at the same time if I have to. My Goal is to find a scheduling plan that executes each job successfully and uses the minimal amount of workers possible.
I'm currently using an EDF (http://en.wikipedia.org/wiki/Earliest_deadline_first_scheduling) Algorithm and recursively call the function with a higher Worker Limit if it can't schedule all jobs correctly, but I think this doesn't work right because I don't have a real way to measure when I can lower the ressource limit again.
Are there any Algorithms that work for my problem, or any other clever ideas?
Thanks for your help.

A: A scheduling problem can often be solved very effectively by formulating it either as mixed-integer program (MIP)
http://en.wikipedia.org/wiki/Mixed_integer_programming#Integer_unknowns
or expressing it using constraint programming (CP)
http://en.wikipedia.org/wiki/Constraint_programming
For either MIP or CP, you will find both free and commercial solvers that can address your problem.
In both of these approaches, you put your effort into stating the properties that the solution must have, and the hard work of applying an appropriate algorithm is left to a specialized solver.


text:
Q: Mounting Mac OS X RAID at mountpoint on startup? I typically use the following in /etc/fstab to get volumes to mount in standard places on the Mac (these mimic our setup on other OSes for local volumes):
UUID=655DCDDB-15BA-37BF-A7F8-EB3D57C610F5 /local hfs rw
UUID=52B32A78-4AE6-3338-ADF7-B2284A7A89F1 /local/scratch hfs rw

On one machine (a Mac Pro running 10.5.7) I striped the scratch partition for performance, but now it won't mount on startup any more.
Is this just a bug/missing feature or am I doing something wrong?  If the former, any workarounds that do not involve hard-coding the device node would be appreciated.
diskutil info output is the following, if it's helpful:
   Device Identifier:        disk4
   Device Node:              /dev/disk4
   Part Of Whole:            disk4
   Device / Media Name:

   Volume Name:              scratch
   Mount Point:              /local/scratch
   File System:              Journaled HFS+
                             Journal size 40960 KB at offset 0xe8b000
   Owners:                   Enabled

   Partition Type:           Apple_HFS
   Bootable:                 Is bootable
   Media Type:
   Protocol:
   Volume UUID:              52B32A78-4AE6-3338-ADF7-B2284A7A89F1

   Total Size:               465.0 Gi (499312033792 B) (975218816 512-byte blocks)
   Free Space:               455.1 Gi (488632147968 B) (954359664 512-byte blocks)

   Read Only:                No
   Ejectable:                No
   Whole:                    Yes
   Internal:                 No
   OS 9 Drivers:             No
   Low Level Format:         Not Supported

   This disk is a RAID Set.  RAID Set Information:
      Set Name:          scratchy
      RAID Set UUID:     1C8FBA63-A780-4576-82D6-1AF4F2CE5266
      Level Type:        Stripe
      Status:            Online
      Chunk Size:        32768

A: Just discovered one workaround: diskutil will let you mount a RAID set via its UUID (but if you put this UUID in /etc/fstab, it does not work).  I made this work on startup by putting the following in /Library/LaunchAgents:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
        <key>KeepAlive</key>
        <false/>
        <key>RunAtLoad</key>
        <true/>
        <key>Label</key>
        <string>mount-striped-scratch</string>
        <key>ProgramArguments</key>
        <array>
                <string>/usr/sbin/diskutil</string>
                <string>mount</string>
                <string>1C8FBA63-A780-4576-82D6-1AF4F2CE5266</string>
        </array>
</dict>
</plist>


text:
Q: How to subtract collections with Comparator interface instead of overriding equals I want to compute differences between collections. When using CollectionUtils.subtract() for custom comparison I need to override the object's equals() method. But what if I need to compare collections of objects of the same type but different comparison criterion? What about the Comparator interface, it seems perfectly suited here? AFAIK Comparator is mainly used for sorting. Isn't there a method that uses Comparators for subtracting?

A: static <Type> Collection<Type> subtract(Collection<Type> a, Collection<Type> b, Comparator<Type> c) {
    Set<Type> subtrahend = new TreeSet<Type>(c);
    subtrahend.addAll(b);
    Collection<Type> result = new ArrayList<Type>();
    for (Type item: a) {
        if (!subtrahend.contains(item)) result.add(item);
    }
    return result;
}

The subtrahent tree-set is not necessary, but will improve performance for large b.

A: If you have an ArrayList, multiple removes can be more expensive than taking a copy.
List<Type> list = /* ArrayList */
Set<Type> toRemove = /* HashSet */
List<Type> copy = new ArrayList<Type>(list.size());
for(Type t: list)
  if(!toRemove.contains(t))
    copy.add(t);
list = copy;

Personally I would use a loop. Its likely to be shorter and clearer.
Collection<Type> collection =

for(Iterator<Type> i=collection.iterator(); i.hasNext();)
   if (i.next() is to be removed)
       i.remove();

The reason an Iterator is used explicitly is to use the Iterator.remove() which avoids a ConcurrentModificationException.  Another way to avoid it is to use a copy of the collection which might be preferred.
for(Type t : new ArrayList<Type>(collection))
   if (t is to be removed)
       collection.remove(t);

This doesn't perform as well but may perform well enough.


text:
Q: jQuery auto increment number on td table How to add increment number on table if new row added using jQuery?

  No.
  Name

  1

  2

Here is the code for add new row
var num = 1;
$('table').prepend('
'+(num+1)+'	'+jsonStr.departmentName+'
');

So the new row added will show on top.
Before:
No | Name
1  | David
2  | Mark

After new row added:
No   | Name
auto | based on added
2    | David
3    | Mark

A: You can work out your html a little bit to ease your task:

      No.
      Name

         1
         David

         2
         Mark

After that manipulating the number becomes easy:
var jsonStr = {
    departmentName : "Sales"
};
var newrow = $('
	'+jsonStr.departmentName+'
');
$("tbody").prepend(newrow);

$("td.number").each(function(i,v) {
    $(v).text(i + 1);
});

Demo
https://jsfiddle.net/w7csmhwk/

A: If you wish to do that then first create one input field with type hidden like this and store you row number on that hidden input's as a value
<input type="hidden" name="rowNum" value="">

And finally whenever you add row throught jQuery change its value by jQuery like this
 $('rowNum').val("your latest row")

and get set the value of your row

A: First you would need to know about the previously existing rows, then insert, then correct all of the row numbers for the existing rows:
// Find existing rows first
var $trs = $('table').children("tr");

// Then do your prepend/insert, I'm assuming your first row always get the value of 1
$('table').prepend('
1	'+jsonStr.departmentName+'
');

// Then update all the existing values
$trs.each(function (index) {
    var $tdNumber = $(this).first("td.number");
    $tdNumber.text(index + 2 /* Offset by the number of rows inserted plus 1 to make it ordinal */);
});

A:

$(document).ready(function(){
  $(".btnAdd").click(function(){

    $("table tr").each(function(){
      var tr=$(this);
      var ftd=tr.find("td:first");
      var std=tr.find("td:last");
      var tmpvalue=parseInt(ftd.text());
      tr.html("
"+(tmpvalue+1)+"	"+std.text()+"
");
    });
    $("table").prepend("
1	Michael
");
  });
});

    1
    David

    2
    Roy

<input type="button" class="btnAdd" value="Add" />

The main logic should be,
1 - The new record inserted will always be number 1, so you can statically put 1 for first td
2 - Iterate through each tr and then settle the Id by incrementing it by one

A: var jsonStr = {
    departmentName : "Sales"
};

What does this code snippet mean in this code :
var jsonStr = {
    departmentName : "Sales"
};

var newrow = $('
	' + jsonStr.departmentName + '
');
$("tbody").prepend(newrow);

$("td.number").each(function(i,v) {
    $(v).text(i + 1);
});


text:
Q: How to access drawable file from NDK in Android In my Android project, I want to access a drawable file using c/c++ from the android-ndk, like R.drawable.some_drawable.xml.
How can I achieve such functionality ?

A: AFAIK, using JNI you are limited to some primitive data types:

The mapping between Java data types and data types used in native code is pretty straightforward. The naming scheme remains the same: the native data type name is preceded by the character 'j', followed by all lowercase data type name equivalent to Java. JNI also includes another data type named jsize, which stores the length or an array or string.

void -> void : None
byte -> jbyte : 8-bit signed. Range is -27 to 27 - 1
int -> jint : 32-bit signed. Range is -231 to 231 - 1
float -> jfloat : 32 bits. Represent a real number as small as 1.4 x 10-45 and as big as 3.4 x 1038 (approx.), positive or negative
double -> jdouble : 64 bits. Represent a real number as small as 4.9 x 10-324 and as big as 1.7 x 10308 (approx.), positive or negative
char -> jchar : 16-bit unsigned. Range is 0 to 65535
long -> jlong : 64-bit signed. Range -263 to 263 - 1
short -> jshort : 16-bit signed. Range is -215 to 215 - 1
boolean -> jboolean : Unsigned 8 bits. true and false

Your solution would be saving your Drawable in cache folder and pass file address to your NDK code and read it in C/C++.
How can I write a Drawable resource to a File?


text:
Q: Definitive -- Get TableViewCell Images to Stop Flickering I have struggled with this problem for AEONS, and I thought I finally came across the solution. But no. I am trying to make a tableview where the images are loaded into the correct cells and persisted, without flickering.
Here is my solution:
extension SearchViewController : BookDataProcessorDelegate  {

    func didFetchSmall(image: UIImage?, for indexPath: IndexPath, in tableView: UITableView) {
        if tableView == resultsTableView {
            if let cell = tableView.cellForRow(at: indexPath) as? BookTableViewCell {
                cell.imageView?.image = image
            }
        }
    }

    func bookSearchDidFinish(with books: [Book]?) {
        self.books = books == nil ?  [] : Array(books!.prefix(MAX_BOOK_COUNT))
        resultsTableView.reloadData()
    }
}

extension SearchViewController : UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.books.count
    }

    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        BookDataProcessor.shared.fetchSmallImage(for: books[indexPath.row], at:indexPath, in:resultsTableView)
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "bookCell", for: indexPath) as! BookTableViewCell
        cell.authorLabel.text = books[indexPath.row].authorName?[0] ?? ""
        cell.titleLabel.text = books[indexPath.row].title ?? ""
        cell.delegate = self
        cell.indexPath = indexPath

        return cell
    }

It is pretty self explanatory. Basically, the BookDataProcessor.shared.fetchSmallImage triggers the didFetchSmall method, which should set the correct tableView cell. However, the cells flicker and disappear half the time. I am extremely interested to know what I am doing wrong.


text:
Q: Is there a Sorting Algorithm that sorts in O(∞) permutations? After reading this question and through the various Phone Book sorting scenarios put forth in the answer, I found the concept of the BOGO sort to be quite interesting.  Certainly there is no use for this type of sorting algorithm but it did raise an interesting question in my mind-- could their be a sorting algorithm that is infinitely impossible to complete?
In other words, is there a process where one could attempt to compare and re-order a fixed set of data and can yet never achieve an actual sorted list?
This is much more of a theoretical/philosophical question than a practical one and if I was more of a mathematician I'd probably be able to prove/disprove such a possibility.  Has anyone asked this question before and if so, what can be said about it?

A: [edit:] no deterministic process with a finite amount of state takes "O(infinity)" since the slowest it can be is to progress through all possible states.  this includes sorting.
[earlier, more specific answer:]
no.  for a list of size n you only have state space of size n! in which to store progress (assuming that the entire state of the sort is stored in the ordering of the elements and it really is "doing something," deterministically).
so the worst possible behaviour would cycle through all available states before terminating and take time proportional to n!  (at the risk of confusing matters, there must be a single path through the state - since that is "all the state" you cannot have a process move from state X to Y, and then later from state X to Z, since that requires additional state, or is non-deterministic)

A: Idea 1:
function sort( int[] arr ) {
    int[] sorted = quicksort( arr ); // compare and reorder data
    while(true); // where'd this come from???
    return sorted; // return answer
}

Idea 2
How do you define O(infinity)? The formal definition of Big-O merely states that f(x)=O(g(x)) implies that M*g(x) is an upper bound of f(x) given sufficiently large x and some constant M.
Typically when you talking about "infinity", you are talking about some sort of unbounded limit. So in this case, the only reasonable definition is saying that O(infinity) is O(function that's larger than every function). Obviously a function that's larger than every function is an upper bound. Thus technically everything is "O(infinity)"
Idea 3
Assuming you mean theta notation (tight bound)...
If you impose the additional restriction that the algorithm is smart (returns when it finds a sorted permutation) and every permutation of the list must be visited in a finite amount of time, then the answer no. There are only N! permutations of a list. The upper bound for such a sorting algorithm is then a finite over finite numbers, which is finite.

A: Your question doesn't really have much to do with sorting.  An algorithm which is guaranteed never to complete would be pretty dull.  Indeed, even an algorithm which would might or might not ever complete would be pretty dull.  Much more interesting would be an algorithm which would be guaranteed to complete, eventually, but whose worst-case computation time with respect to the size of the input would not be expressible as O(F(N)) for any function F that could itself be computed in bounded time.  My hunch would be that such an algorithm could be devised, but I'm not sure how.

A: How about this one:

*

*Start at the first item.

*Flip a coin.

*If it's heads, switch it with the next item.

*If it's tails, don't switch them.

*If list is sorted, stop.

*If not, move onto the next pair ...

It's a sorting algorithm -- the kind a monkey might do.  Is there any guarantee that you'll arrive at a sorted list?  I don't think so!

A: Yes -
SortNumbers(collectionOfNumbers)
{
  If IsSorted(collectionOfNumbers){
     reverse(collectionOfNumbers(1:end/2))
  }

  return SortNumbers(collectionOfNumbers)
}

A:   Input:      A[1..n] : n unique integers in arbitrary order
  Output:     A'[1..n] : reordering of the elements of A
              such that A'[i] R(A') A'[j] if i < j.
  Comparator: a R(A') b iff A'[i] = a, A'[j] = b and i > j

More generally, make the comparator something that's either (a) impossible to reconcile with the output specification, so that no solution can exist, or (b) uncomputable (e.g., sort these (input, turing machine) pairs in order of the number of steps needed for the machine to halt on the input).
Even more generally, if you have a procedure that fails to halt on a valid input, the procedure is not an algorithm which solves the problem on that input/output domain... which means you don't have an algorithm at all, or that what you have is only an algorithm if you appropriately restrict the domain.

A: Let's suppose that you have a random coin flipper, infinite arithmetic, and infinite rationals.  Then the answer is yes.  You can write a sorting algorithm which has 100% chance of successfully sorting your data (so it really is a sorting function), but which on average will take infinite time to do so.
Here is an emulation of this in Python.
# We'll pretend that these are true random numbers.
import random
import fractions

def flip ():
    return 0.5 < random.random()

# This tests whether a number is less than an infinite precision number in the range
# [0, 1].  It has a 100% probability of returning an answer.
def number_less_than_rand (x):
    high = fractions.Fraction(1, 1)
    low = fractions.Fraction(0, 1)

    while low < x and x < high:
        if flip():
            low = (low + high) / 2
        else:
            high = (low + high) / 2

    return high < x

def slow_sort (some_array):
    n = fractions.Fraction(100, 1)
    # This loop has a 100% chance of finishing, but its average time to complete
    # is also infinite.  If you haven't studied infinite series and products, you'll
    # just have to take this on faith.  Otherwise proving that is a fun exercise.
    while not number_less_than_rand(1/n):
        n += 1
    print n
    some_array.sort()


text:
Q: SAP Business Object As we are moving to BO XI 4.0 from BO XI R2, uninstalled BOXI R2 from DEV server (WIN2003 server, 32 bit) and installed new BO XI 4.0, After that when I open my web application. I am getting below error:

Retrieving the COM class factory for component with CLSID {C0C99FA5-E1D3-494E-BE0C-73C19424F91C} failed due to the following error: 80040154 Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG)).
  Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
  Exception Details: System.Runtime.InteropServices.COMException: Retrieving the COM class factory for component with CLSID {C0C99FA5-E1D3-494E-BE0C-73C19424F91C} failed due to the following error: 80040154 Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG)).

I tried to register the dll manually..

regsvr32  "C:\Program Files\SAP BusinessObjects\SAP BusinessObjects Enterprise XI 4.0\win32_x86\ClientDoc.dll"

Got below error:

LoadLibrary ("C:\Program Files\SAP BusinessObjects\SAP BusinessObjects Enterprise XI 4.0\win32_x86\ClientDoc.dll")failed - Invalid access to memory location.

Request any help regarding this.
Note: In local machine(winxp), the webapp is working fine without any issue.

A: Cause of the issue:  Conflict with usage of different versions of "cryptocme2.dll" by CA's (Computer Associates) Autosys and SAP Business Objects XI 4.0.
Location of CA's file:  C:\Program Files\CA\SC\ETPKI\lib\cryptocme2.dll [Additional Info: File Version: Not Available, Timestamp: 2/29/2012 9:43 PM, size 3,188 KB]
Location of SAP's file : D:\Program Files\SAP BusinessObjects\SAP BusinessObjects Enterprise XI 4.0\win32_x86\cryptocme2.dll  [ Additional Info:  File Version 3.0.0.0 , TimeStamp: 2/25/2011 6:55 PM, size: 1704 KB]
Solution:

*

*Renamed the dll C:\Program Files\CA\SC\ETPKI\lib\cryptocme2.dll to cryptocme2_ca.dll

*Copied the  D:\Program Files\SAP BusinessObjects\SAP BusinessObjects Enterprise XI 4.0\win32_x86\cryptocme2.dll to  C:\Program Files\CA\SC\ETPKI\lib\

*Uninstalled the BO XI 4.0 SDK (thru Control Panel) as it was not properly installed before.

*Restarted the Box.

*Stopped IIS Admin Server.

*Then Installed BO XI 4.0 RAS 32 bit Dot Net SDK to D:\Program Files\SAP BusinessObjects

Now webapp is working fine.


text:
Q: Any concise way to calculate n * (n+1) / 2 and handling overflow at the same time I am trying to implement n * (n + 1) / 2 knowing that n is an int <= 2^16 - 1 (this guarantees that n * (n + 1) / 2 <= 2^31 - 1 so there is no overflow).
Then we know that n * (n + 1) / 2 is guaranteed to be non-negative integer. When calculating this value in a program, though, if we do multiplication n *(n + 1) first, we might get into integer overflow problem. My idea is to use a clumsy condition:
int m;
if (n % 2 == 0) {
    m = (n / 2) * (n + 1);
} else {
    m = n * ((n + 1) / 2);
}

Is there any more concise way of doing this?

A: There is a more concise way to write your test using the ternary operator:
int m = (n % 2 == 0) ? (n / 2) * (n + 1) : n * ((n + 1) / 2);

But it is likely to generate the exact same code.
You could take advantage of the extra precision long long is guaranteed to provide (at least 63 value bits):
int m = (long long)n * (n + 1) / 2;

Whether this is more or less efficient than the test version will depend on the target CPU and the compiler version and options. This version is simpler to read and understand, which is valuable.  Adding a comment to explain why the result will be in range would be useful.
Derived from a suggestion by Amadeus, here is a more concise, but much less readable alternative, that does not use 64-bit arithmetics:
int m = (n + (n & 1)) / 2 * (n + 1 - (n & 1));

Demonstration:

*

*if n is odd, we get m = (n + 1) / 2 * n;

*if n is even, we get: m = n / 2 * (n + 1);.

A: What do you think about:
m = ((n + (n & 1)) >> 1) * ( n + !(n & 1));

Explanation:
This solution try to achieve two objectives:

*

*Do not overflow

*Avoid to use if then else condition, and be pipeline friendly

To avoid overflow we first divide and the multiply. Once division is done to half the number (by 2) it has an interesting property: if number is odd the division is exact and can be done by a simple right sifting by 1.
So, to guarantee that the number is odd without if then else condition, we use the following trick:
If number is odd, it means that it lower bit is zero (captured by anding it with 1), otherwise it is even. Therefore if number is odd, we divide it by 2, otherwise, we first add 1, to make sure that it is odd and the divide.
In other words, this solution is equivalent to:
if ( n is odd )
    m = (n >> 1) * (n + 1);
else
    m = ( (n + 1) >> 1) * n;

A: The simplest solution is perhaps to use a larger intermediate type:
int m = (int)((long long)n * (n + 1) / 2) ;

It is not necessary to cast all operands since automatic type promotion will apply.

A: and one more:
  int m =  (n/2 * n)  + ((n%2) * (n/2)) + (n/2) + (n%2);

A: maybe
result = (n) * (n / 2) + (n & 1) * (n) + n / 2 ;


text:
Q: Java 9, Set.of() and Map.of() varargs overloads I'm studying the factory methods for Immutable collections.
I see the Set.of() method has 10 varargs overloading (same for Map.of()). I really can't understand why there are so many. In the end the function ImmutableCollections.SetN<>(elements) gets called anyway.
In the documentation I found this:

While this introduces some clutter in the API, it avoids array allocation, initialization, and garbage collection overhead that is incurred by varargs calls.

Is the clutter indeed worth the performance gain? If yes, would that ideally do create a separate method for any N elements?

A: I guess it depends on the scope of the API you are working with. When talking about those Immutable classes you are talking about stuff included as part of the jdk; so scope is very broad.
So you have:

*

*in one side that these Immutable classes might be used by applications where every bit counts (and every nanosecond wasted in allocation/deallocation).

*in other side, that applications without those needs are not negatively impacted

*the only 'negative' side is for the implementors of that API that will have more clutter to deal with, so it affects maintanability (but not a big thing in this case).

If you were implementing your own stuff i would not care so much about that (but be cautious with varargs arguments) unless you really need to worry about those extra bits (and extra performance etcetc).

A: At the moment that method is called anyway - this could change. For example it could be that it creates a Set with only three elements, 4 and so on.
Also not all of them delegate to SetN - the ones that have zero, one and two elements have actual classes of ImmutableCollections.Set0,  ImmutableCollections.Set1 and ImmutableCollections.Set2
Or you can read the actual question regarding this ... here Read the comments from Stuart Marks in that question -as he is the person that created these Collections.

A: Some aspects of this may be a form of future proofing.
If you evolve an API, you need to pay attention to how the method signature will change, so if we have
public class API {
  public static final <T> Set<T> of(T... elements) { ... }
}

We could say that the varargs is good enough... except that the varargs forces the allocation of an object array, which - while reasonably cheap - does actually impact the performance. See for example this microbenchmark which shows a 50% loss of throughput for a no-op logging (i.e. the log level is lower than loggable) when switching to the varargs form.
Ok, so we do some analysis and say the most common case is the singleton, so we decide to refactor...
public class API {
  public static final <T> Set<T> of(T first) { ... }
  public static final <T> Set<T> of(T first, T... others) { ... }
}

Ooops... that's not binary compatible... it's source compatible, but not binary compatible... to retain binary compatibility we need to keep the previous signature, e.g.
public class API {
  public static final <T> Set<T> of(T first) { ... }
  @Deprecated public static final <T> Set<T> of(T... elements) { ... }
  public static final <T> Set<T> of(T first, T... others) { ... }
}

Ugh... IDE code complete is a mess now... plus how do I create a set of arrays? (probably more relevant if I was using a list) API.of(new Object[0]) is ambiguous... if only we had not added the vararg at the start...
So I think what they did was add enough explicit args to reach the point where the extra stack size meets the cost of vararg creation, which is probably about 10 arguments (at least based on the measurements that Log4J2 did when adding their varargs to the version 2 API)... but you are doing this for evidence based future-proofing...
In other words, we can cheat for all the cases that we do not have evidence requiring a specialized implementation and just fall-through to the vararg variant:
public class API {
  private static final <T> Set<T> internalOf(T... elements) { ... }
  public static final <T> Set<T> of(T first) { return internalOf(first); }
  public static final <T> Set<T> of(T first, T second) { return internalOf(first, second); }
  ...
  public static final <T> Set<T> of(T t1, T t2, T t3, T t4, T t5, T... rest) { ... }
}

Then we can profile and look at real world usage patterns and if we then see significant usage up to the 4 arg form and benchmarks showing there to be a reasonable perf gain, then at that point, behind the scenes, we change the method impl and everyone gets a win... no recompilation required


text:
Q: Conftest Fails For a Valid Kubernetets YAML File I have the following simple Kubernetes YAML Deployment:
apiVersion: apps/v1
kind: Deployment
metadata:
  name: {{ .Values.app.name }}
  namespace: {{ .Values.app.namespace }}
spec:
  selector:
    matchLabels:
      app: {{ .Values.app.name }}
  replicas: 1
  template:
    metadata:
      labels:
        app: {{ .Values.app.name }}
    spec:
      securityContext:
        runAsUser: 1000
        runAsGroup: 3000
        fsGroup: 2000
      containers:
        - name: {{ .Values.app.name }}
          image: {{ .Values.plantSimulatorService.image.repository }}:{{ .Values.plantSimulatorService.image.tag }}
          ports:
            - containerPort: {{ .Values.plantSimulatorService.ports.containerPort }} # Get this value from ConfigMap

I have the following in my test.rego:
package main

import data.kubernetes

name = input.metadata.name

deny[msg] {
  kubernetes.is_deployment
  not input.spec.template.spec.securityContext.runAsNonRoot

  msg = sprintf("Containers must not run as root in Deployment %s", [name])
}

When I ran this using the following command:
joesan@joesan-InfinityBook-S-14-v5:~/Projects/Private/infrastructure-projects/plant-simulator-deployment$ helm conftest helm-k8s -p test
WARN - Found service plant-simulator-service but services are not allowed
WARN - Found service plant-simulator-grafana but services are not allowed
WARN - Found service plant-simulator-prometheus but services are not allowed
FAIL - Containers must not run as root in Deployment plant-simulator
FAIL - Deployment plant-simulator must provide app/release labels for pod selectors

As you can see I'm indeed not running the container as root, but despite that I get this error message - Containers must not run as root in Deployment plant-simulator
Any ideas what the reason could be?

A: You need to add runAsNonRoot to your securityContext:
  securityContext:
    runAsUser: 1000
    runAsGroup: 3000
    fsGroup: 2000
    runAsNonRoot: true

The rego rule is only able to validate Yaml structure - it is not clever enough to work out that your configuration is effectively running a non-root user.


text:
Q: XCode 4.6.3 crash when opening one project I keep two versions of Xcode, 4.6.3 and 5.0.2, and worked for some days, there was nothing wrong. But today when I opened one of my projects with Xcode 4.6.3, it crashed several seconds later. Repeated many times, but other projects that are open with Xcode 5.0.2 not.
I have uninstalled both versions of Xcode, re-installed Xcode 4.6.3, but the problem still exists. That reason why I do not use Xcode 5.0.2 is because I use a library that Xcode 5.0.2 does not support.
Could someone help? Thanks very much!
Crash report below:
Process:         Xcode [696]
Path:            /Applications/Xcode.app/Contents/MacOS/Xcode
Identifier:      com.apple.dt.Xcode
Version:         4.6.3 (2068)
Build Info:      IDEApplication-2068000000000000~3
Code Type:       X86-64 (Native)
Parent Process:  launchd [258]
Responsible:     Xcode [696]
User ID:         501

Date/Time:       2013-11-21 17:19:39.479 +0800
OS Version:      Mac OS X 10.9 (13A603)
Report Version:  11
Anonymous UUID:  053ABB38-41BB-9CC2-9E8F-6691450D069B

Crashed Thread:  0  Dispatch queue: com.apple.main-thread

Exception Type:  EXC_BAD_ACCESS (SIGSEGV)
Exception Codes: KERN_INVALID_ADDRESS at 0x0000000000000028

VM Regions Near 0x28:
-->
    __TEXT                 00000001060ed000-00000001060f0000 [   12K] r-x/rwx SM=COW  /Applications/Xcode.app/Contents/MacOS/Xcode

Application Specific Information:
ProductBuildVersion: 4H1503
objc[696]: garbage collection is ON

Thread 0 Crashed:: Dispatch queue: com.apple.main-thread
0   com.apple.CoreText              0x00007fff8e73a0cb TLine::AppendRun(TCFRef<CTRun const*>&&) + 75
1   com.apple.CoreText              0x00007fff8e74d959 TLine::AppendPartialRun(CTRun const*, CFRange) + 53
2   com.apple.CoreText              0x00007fff8e74d8eb TLine::CopyStringRange(TLine const&, CFRange) + 257
3   com.apple.CoreText              0x00007fff8e783b27 TTypesetter::FindGraphicalBreakInconsistent(std::__1::tuple<TLine const*, TCharStream const*, void const* (*)(__CTRun const*, __CFString const*, void*), void*, std::__1::shared_ptr<TBidiLevelsProvider>*, unsigned int, unsigned char> const&, TLine const&, CFRange, double, double, unsigned char, long&, double&) + 245
4   com.apple.CoreText              0x00007fff8e782e08 TTypesetter::FindGraphicalBreak(std::__1::tuple<TLine const*, TCharStream const*, void const* (*)(__CTRun const*, __CFString const*, void*), void*, std::__1::shared_ptr<TBidiLevelsProvider>*, unsigned int, unsigned char> const&, long, double, double, std::__1::function<unsigned char (long)>) + 490
5   com.apple.CoreText              0x00007fff8e782b14 TTypesetter::SuggestClusterBreak(std::__1::tuple<TLine const*, TCharStream const*, void const* (*)(__CTRun const*, __CFString const*, void*), void*, std::__1::shared_ptr<TBidiLevelsProvider>*, unsigned int, unsigned char> const&, long, double, double, std::__1::function<unsigned char (long)>) + 112
6   com.apple.CoreText              0x00007fff8e74f75a TTypesetter::SuggestClusterBreak(long, double, double, std::__1::function<unsigned char (long)>) const + 176
7   com.apple.CoreText              0x00007fff8e74f66d CTTypesetterSuggestClusterBreak + 71
8   com.apple.AppKit                0x00007fff8d4afcaa -[NSATSLineFragment layoutForStartingGlyphAtIndex:characterIndex:minPosition:maxPosition:lineFragmentRect:] + 518
9   com.apple.AppKit                0x00007fff8d4ae64e -[NSATSTypesetter _layoutLineFragmentStartingWithGlyphAtIndex:characterIndex:atPoint:renderingContext:] + 2777
10  com.apple.AppKit                0x00007fff8d4e1c79 -[NSATSTypesetter layoutParagraphAtPoint:] + 149
11  com.apple.AppKit                0x00007fff8db59b45 -[NSTypesetter _layoutGlyphsInLayoutManager:startingAtGlyphIndex:maxNumberOfLineFragments:maxCharacterIndex:nextGlyphIndex:nextCharacterIndex:] + 4043
12  com.apple.AppKit                0x00007fff8d4e0c9d -[NSTypesetter layoutCharactersInRange:forLayoutManager:maximumNumberOfLineFragments:] + 202
13  com.apple.AppKit                0x00007fff8d4e0b81 -[NSATSTypesetter layoutCharactersInRange:forLayoutManager:maximumNumberOfLineFragments:] + 1107
14  com.apple.AppKit                0x00007fff8d4df219 -[NSLayoutManager(NSPrivate) _fillLayoutHoleForCharacterRange:desiredNumberOfLines:isSoft:] + 1306
15  com.apple.AppKit                0x00007fff8d588ad9 _NSFastFillAllLayoutHolesForGlyphRange + 1435
16  com.apple.AppKit                0x00007fff8db17199 -[NSTextView(NSPrivate) _ensureLayoutCompleteForRect:withExtensionFactor:minimumExtensionDistance:repetitions:] + 568
17  com.apple.AppKit                0x00007fff8db1722c -[NSTextView(NSPrivate) _ensureLayoutCompleteForRect:withExtension:] + 84
18  com.apple.AppKit                0x00007fff8dae83ed -[NSTextView prepareContentInRect:] + 203
19  com.apple.AppKit                0x00007fff8d5f0758 __48-[NSView _pullInTilesByDrawingAndAddingSubviews]_block_invoke + 599
20  com.apple.AppKit                0x00007fff8d5efe90 -[NSView _performWorkOnTilesFromRect:renderedContentRect:maximumRect:scrollVelocity:handler:] + 2411
21  com.apple.AppKit                0x00007fff8d5ef41a -[NSView _pullInTilesByDrawingAndAddingSubviews] + 1007
22  com.apple.AppKit                0x00007fff8d5ef012 -[NSView _pullInExtraTilesForOverdraw] + 87
23  com.apple.AppKit                0x00007fff8d5eef7e -[NSView _doIdlePrefetch] + 59
24  com.apple.AppKit                0x00007fff8d5eca8a __CreateIdleRunLoopObserverWithHandler_block_invoke + 237
25  com.apple.CoreFoundation        0x00007fff85ba10a7 __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 23
26  com.apple.CoreFoundation        0x00007fff85ba1017 __CFRunLoopDoObservers + 391
27  com.apple.CoreFoundation        0x00007fff85b92893 __CFRunLoopRun + 995
28  com.apple.CoreFoundation        0x00007fff85b92275 CFRunLoopRunSpecific + 309
29  com.apple.HIToolbox             0x00007fff80c74f0d RunCurrentEventLoopInMode + 226
30  com.apple.HIToolbox             0x00007fff80c74cb7 ReceiveNextEventCommon + 479
31  com.apple.HIToolbox             0x00007fff80c74abc _BlockUntilNextEventMatchingListInModeWithFilter + 65
32  com.apple.AppKit                0x00007fff8d40928e _DPSNextEvent + 1434
33  com.apple.AppKit                0x00007fff8d4088db -[NSApplication nextEventMatchingMask:untilDate:inMode:dequeue:] + 122
34  com.apple.AppKit                0x00007fff8d3fc9cc -[NSApplication run] + 553
35  com.apple.AppKit                0x00007fff8d3e7803 NSApplicationMain + 940
36  com.apple.dt.Xcode              0x00000001060eeb6f 0x1060ed000 + 7023
37  com.apple.dt.Xcode              0x00000001060eeb00 0x1060ed000 + 6912


text:
Q: Is it possible to restrict allowed filenames on a NFS share? In our mixed network the OSX clients like to create resource fork junk on our Linux NFS shares. What I'd like is a server setting much like Sambas veto files-directive to disallow creation of ._* folders.
I can't find anything like it in NFS man-pages (export, nfs, nfsd, exportfs), maybe it could be configured on the underlying filesystem?
ps.
I am aware of defaults write com.apple.desktopservices DSDontWriteNetworkStores true to make OSX not create .DS_Store-files on network disks.

A: It turns out that you should be able to remove these directories very soon as they are created using inotify feature. I would check out incron or fsniper, they look very promising.

A: Generally preventing the creation of files/directories matching a certain path is a tiny part of an elephant called mandatory access control (MAC). It is a main part of SELinux. MAC integrated into NFS is not here yet, but for your needs it is indeed sufficient to act on filesystem level.
But it's most certainly too cumbersome solution for your problem :)


text:
Q: angular2-material2 using ES6: is there any way to start with angular2 material2 using ES6?
I have tried to find the way but Failed.
Also checked the git repo where found that all code exist for now with TS
so does it mean we can't able to use it with ES6
is there atlernative to overcome it?

A: Yes, with Angular you can use vanilla JavaScript - either es5 or es6 - your choice. You can also use Typescript or Dart. Many of the tutorials you see use Typescript, because it works so well with Angular, and because the Angular team use it as their default. But you're certainly not tied to having to use that. If you prefer to use vanilla JS you certainly can -- because, remember, it all gets compiled down to JS, regardless of what you use for your coding.
Also, you can use Material2 regardless of what language and language version you're using to code with in your Angular app.
More info here: https://angular.io/docs/js/latest/quickstart.html
And to use Material in your Angular app, see this: https://material.angular.io/guide/getting-started


text:
Q: How do I name my build? What is the proper way to name my revisions?
v1.0.3.20 Alpha

or
Alpha v1.0.3.20

A: There isn't really any "proper" way. While most people use the dot pattern "x.x.x", it isn't necessarily the proper way to do it. Likewise with your question, it is up to you.
I would suppose that the former is more natural to say, and I would prefer it, but it doesn't really matter either way.

A: You have two pieces of information there: version number and release state/quality.  The two might be tied together, but don't have to be.  For example, you could have multiple "releases" for a single version number: v1.1-alpha, v1.1-beta, v1.1-final, and so forth; or you could break those down into individual numbers: v1.0.1-alpha, v1.0.2-beta, v1.1.0-final; or something entirely different!
This is really a question of branding more than anything; due to the wide interpretation of version info across different products, you already have to know how each different product uses them to make sense of it.  Of course, if you're contributing to, working with, or emulating another project: do what they do.  It'll be simpler and lead to less confusion.
As used in my examples, I'd prefer "n.n...-quality", but it's only syntax.


text: Q: ngx-joyride with animation effect I am working on angular 7. I have implemented ngx-joyride in my project and it's working fine. But I want that all joyride popup should show with slide animation effect. How can I do it? I tried with transition css but it's not working.


text:
Q: RMagick can't crop a cropped image? I'm working on a ruby project with RMagick where I load an image from a file, initialize objects with cropped parts, and then try to re-crop those sub-images.  For the crop-of-a-crop image, it creates an image with 1x1 dimensions.
However, it works in the toy, trivial versions I create:
i = Image.read('sample.png')[0]
=> sample.png PNG 1000x800 1000x800+0+0 DirectClass 8-bit 47kb
si = i.crop(50, 50, 900, 700)
=> sample.png PNG 1000x800=>900x700 1000x800+50+50 DirectClass 8-bit
ssi = i.crop(50, 50, 800, 600)
=> sample.png PNG 1000x800=>800x600 1000x800+100+100 DirectClass 8-bit

etc., etc.
It seems to work indefinitely, at least out 4 generations.
However, my code definitely does not work.  I've been unable to construct a trivial version that doesn't work, but this is the simplified relevant portion of my actual code.
https://gist.github.com/mikaylathompson/9ca5db7569d6bfba6008
doc = Document.new('sample.png')
doc.split
doc.sort

# This image is just fine
doc.tables[0].image
=> sample.png PNG 1000x800=>745x150 1000x800+125+350
doc.tables[0].divide_rows

# and this image failed
doc.tables[0].rows[0].image
=> sample.png PNG 1000x800=>1x1 1000x800-1-1 DirectClass 8-bit

# this fails too, so it's based on the image, not the dimensions
doc.tables[0].image.crop(50, 50, 100, 100)
=> sample.png PNG 1000x800=>1x1 1000x800-1-1 DirectClass 8-bit

A: You can tell crop() to not include the metadata dimensions (these seem to interfere with crops of crops) from the source image in the derived image by passing 'true' as the last parameter like so:
doc.tables[0].image.crop(50, 50, 100, 100, true)


text:
Q: Bash conditional fails when run in Jenkins pipeline script The following conditional works as expected when run from the bash command line on my Jenkins server:
if (($BRANCH_COUNT > 0)); then .....

But when running in the context of a Jenkins pipeline step (calling sh ''' .... '''), it writes an error and always evaluates to false. The error message (below) suggests maybe it's interpreting the value of $BRANCH_COUNT (in this case it is 1) as a command, which is then not found?
/var/jenkins/workspace/deploy-config-db-update@tmp/durable-baa54bb3/script.sh: 16:
/var/jenkins/workspace/deploy-config-db-update@tmp/durable-baa54bb3/script.sh: 1: not found

Is there something different about the bash environment when run by the Jenkins sh command? Some special escaping or quoting needed?

A: if you use sh'''...''', the pipeline script variable will not be expanded in your shell script. You need to use sh """..."""

A: Moving William Pursell's comment into an answer, because it solved the problem.

Using (()) is a bashism. Try if test "$BRANCH_COUNT" -gt 0; then ...


text:
Q: Isomorphism theorems for topological groups I know that the second isomorphism theorem for groups doesn't hold for topological groups, the version that I have for the second isomorphism theorem is:

*

*If $G$ is a group, $H$ a subgroup of $G$ and $N$ a normal subgroup of $G$, Then $ (HN)/N \cong H/(H\cap N)$.

Under wich conditions we have that the theorem holds for topological groups?,
On the other side the third isomorphism theorem holds for topological groups.

*

*If $H$ and $K$ are normal subgroups of a topological group $G$ and $K$ is a subgroup of $H$, then $G/H \cong (G/K) /(H/K)$

In the prove for ordinary groups, the homomorphism $\phi: G \longrightarrow (G/K)/(H/K)$ defined by $ \phi (a)= aK(H/K)$   is surjective with kernel $H$, then by the first isomorphism theorem we have the isomorphism.
In the case for topological groups, we need to have that the homomorphism is an open map to use the first isomorphism theorem, how can I prove that the homomorphism is open?.

A: Quotient maps $f:G\to G/N$ are always open. Let $V\subseteq G$ be open; we need to show $f(V)$ is open. By definition this is equivalent to $f^{-1}(f(V))$ being open. But $f^{-1}(f(V))=VN=\bigcup_{n\in N}Vn$, which is a union of open sets (since each $Vn$ is open, as a shift of an open sets), hence open.
Therefore the third isomorphism theorem holds for topological groups.


text:
Q: dbpedia resource for wiki portals I have two questions:
1) Whats the corresponding dbpedia resource for http://en.wikipedia.org/wiki/Portal:Current_events/Sports
2) How could I find that information myself in future. I know for regular wiki articles, I just need to make an underscore string for the resource. I dont know how to do it for "Portals" as in the link above
Thanks!

A: The general pattern to get the DBpedia URI for a Wikipedia URI is very simple: replace /wiki/ by /resource/ and .wikipedia.org by .dbpedia.org, except for English replace en.wikipedia.org by dbpedia.org.
Examples:
http://it.wikipedia.org/wiki/Berlino -> http://it.dbpedia.org/resource/Berlino
http://en.wikipedia.org/wiki/Berlin -> http://dbpedia.org/resource/Berlin
(Note that the distinction between IRIs and URIs in RDF adds a little more complexity, but that's for a different question...)
DBpedia only generates URIs for some Wikipedia namespaces - currently only for the main article namespace and the Category: namespace, I think. URIs for Portal: and other namespaces occur only as targets of links (in files like page_links_en.nt). If such DBpedia URIs were extracted, they would look very similar to the others. In your example, the DBpedia URI would be
http://dbpedia.org/resource/Portal:Current_events/Sports
But would it make sense to have Linked Data URIs for Wikipedia portals? I don't know. It seems there is not much data to be extracted from these pages. And they don't seem to be a good match for Linked Data resource URIs. Such URIs usually represent a thing in the real world. Or maybe not so real, but still a thing...


text: Q: Walking Dead - Corpses in Cars not zombified. Why? In season 2, episode 1 of the Waking Dead, there is a scene in which dead people are shown in their cars, not having been zombified. However, we know from a later revelation that everyone is infected and will turn in to zombies when they die. Taking that into consideration, it would seem that those who had died in their cars would have turned in their cars and walked away. However, they are simply rotting corpses sitting in their seats without apparent head trauma to indicate prevention of the zombification process.


text:
Q: Hibernate Association Mapping I am working with Hibernate.
RelationShip Details:

*

*One USER belongs to Many COMMUNITY

*One FACULTY can handle One COMMUNITY

*FACULTY is a USER

So here FACULTY is a weak entity and I need to create Faculty.java without any primary key attribute like:
private Integer facultyId;

and only with the fields
User user; Community community;

Is there a better way to approach rather than creating facultyId which is redudant here?

A: Your relationship details are confusing me:
Practically thinking, If One USER belongs to Many COMMUNITY, One COMMUNITY will definitely have Many USERS. Don't you think SO?? You got to re-think about this..
Still... Considering you defined relationship
As long as faculty has no other attributes assigned to it other than community.What I suggest is that instead of creating a separate table for faculty(which I think is not required) you can add extra column in COMMUNITY TABLE as COMMUNITY_ROLE and define role as FACULTY in it for required users.
Advantage:
Since USER-COMMUNITY are 1 to MANY in relationship, We will have user in COMMUNITY and COMMUNITY_ROLE will define the for FACULTY or NULL.
Still I strongly feel USER-COMMUNITY will be many to many, which will overthrow my workaround solution above which is based on you relationship details provided above which I think are wrong.


text:
Q: For loop vs jquery-after My aim is to make an ascending number list between two green squares. Right now I have a descending list (I presume because of jquery-after) --> how to make it ascending?
My jsFiddle: https://jsfiddle.net/h85conn6/
            var ile = $("div.pagination").find('div').length;

            $("div.pagination div").hide();
            $("div.pagination div").first().show();

            for(i=0; i<ile;i++){
                $("ul.pagination .green:nth-child(1)").after("
"+i+"
");
      }

A: Here you go with a solution https://jsfiddle.net/h85conn6/1/

var ile = $("div.pagination").find('div').length;
$("div.pagination div").hide();
$("div.pagination div").first().show();

var item = "";
for(i=0; i<ile;i++){
   item += "
"+i+"
";
}

$("ul.pagination .green:nth-child(1)").after(item);
body{
   padding-top:80px;
}

.green {
   width:100px;
   height:100px;
   background: green;
   border:1px solid black;
   margin:2px;
}

 PG 1
 Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum ex tortor, vulputate at lectus nec, dapibus ultricies sem. Phasellus in suscipit arcu. Maecenas dictum lorem magna, eget interdum augue convallis vel. Morbi id dui semper, euismod enim at, scelerisque sem. Aenean varius nunc non ante scelerisque tempor. Suspendisse a ipsum vel sem sollicitudin rutrum a nec massa. Pellentesque accumsan tincidunt erat, eget faucibus metus maximus at. Duis volutpat volutpat tortor et mollis. Fusce libero lorem, ullamcorper eget sollicitudin vehicula, dignissim sed sem. Nunc sollicitudin venenatis justo non mollis. Etiam placerat sed metus non vestibulum.

PG 2
 Suspendisse et mi non elit posuere scelerisque et ac ipsum. Aliquam maximus eros laoreet porta cursus. Integer at ornare justo. Nulla purus nibh, bibendum sit amet sapien eu, blandit euismod arcu. Nulla tincidunt interdum eros vel viverra. Donec rhoncus sed ligula ac fringilla. Praesent eros massa, vestibulum eget egestas at, scelerisque ut velit. Suspendisse a est vel felis facilisis molestie sit amet eu metus. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Nulla vel justo vitae eros hendrerit elementum sed id erat. Phasellus lacinia nisi in fermentum laoreet. Morbi vestibulum sem vitae justo imperdiet, eget cursus felis rutrum. Proin facilisis urna at ipsum varius feugiat. Sed interdum tristique turpis sed facilisis. Mauris lacus diam, vehicula eget pharetra at, laoreet quis dolor.

PG 2
 Suspendisse et mi non elit posuere scelerisque et ac ipsum. Aliquam maximus eros laoreet porta cursus. Integer at ornare justo. Nulla purus nibh, bibendum sit amet sapien eu, blandit euismod arcu. Nulla tincidunt interdum eros vel viverra. Donec rhoncus sed ligula ac fringilla. Praesent eros massa, vestibulum eget egestas at, scelerisque ut velit. Suspendisse a est vel felis facilisis molestie sit amet eu metus. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Nulla vel justo vitae eros hendrerit elementum sed id erat. Phasellus lacinia nisi in fermentum laoreet. Morbi vestibulum sem vitae justo imperdiet, eget cursus felis rutrum. Proin facilisis urna at ipsum varius feugiat. Sed interdum tristique turpis sed facilisis. Mauris lacus diam, vehicula eget pharetra at, laoreet quis dolor.

PG 2
 Suspendisse et mi non elit posuere scelerisque et ac ipsum. Aliquam maximus eros laoreet porta cursus. Integer at ornare justo. Nulla purus nibh, bibendum sit amet sapien eu, blandit euismod arcu. Nulla tincidunt interdum eros vel viverra. Donec rhoncus sed ligula ac fringilla. Praesent eros massa, vestibulum eget egestas at, scelerisque ut velit. Suspendisse a est vel felis facilisis molestie sit amet eu metus. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Nulla vel justo vitae eros hendrerit elementum sed id erat. Phasellus lacinia nisi in fermentum laoreet. Morbi vestibulum sem vitae justo imperdiet, eget cursus felis rutrum. Proin facilisis urna at ipsum varius feugiat. Sed interdum tristique turpis sed facilisis. Mauris lacus diam, vehicula eget pharetra at, laoreet quis dolor.

A: Replace:
for(i=0; i<ile; i++){

With:
for(i=ile-1; i>=0; i--){


text:
Q: Adding an XML Node with a namespace to an existing document using Groovy How do I add an xml node with a namespace prefix to an existing document?  I would like to build off of what I have so far, if possible:
def rss = new XmlParser().parse(xmlFile)

rss.channel + {
item {
    title("My super atom feed")
    link(href:"http://www.thecoderscorner.com")
    description("content of rss item goes here")
    guid(isPermaLink: "false", "8452")
}
}

I want to add the following to the item above:
<event:startDate>Tue, 8 Apr 2014 15:00:00 PDT</event:startDate>
<event:endDate>Tue, 8 Apr 2014 18:00:00 PDT</event:endDate>
<event:location>1234 Mrak Hall</event:location>
<event:isAllDay>false</event:isAllDay>

A: You should be able to do something like this:
def rss = new XmlParser().parseText( xml )
rss.channel.item + {
    item {
        title("My super atom feed")
        link(href:"http://www.thecoderscorner.com")
        description("content of rss item goes here")
        guid(isPermaLink: "false", "8452")
        'event:startDate'( "Tue, 8 Apr 2014 15:00:00 PDT" )
        'event:endDate'( "Tue, 8 Apr 2014 18:00:00 PDT" )
        'event:location'( "1234 Mrak Hall" )
        'event:isAllDay'( false )
    }
}
String output = new StringWriter().with { xmlOutput ->
    new XmlNodePrinter( new PrintWriter( xmlOutput ) ).with { printer ->
        preserveWhitespace = true
        expandEmptyElements = true
        printer.print( rss )
    }
    xmlOutput.toString()
}

println output


text:
Q: How to replace template parameters having double type? I have a template class that worked perfectly in Visual Studio 6 but fails in a more modern version.
template<double B, double C>
class MyClass
{
    double k(double x) const
    {
        x = fabs(x);
        if (x < 1.0)
            return ((2.0 - 1.5*B - C) * x*x*x) + ((-3.0 + 2.0*B + C) * x*x) + (1.0 - 0.33333333*B);
        if (x < 2.0)
            return ((-0.16666667*B - C) * x*x*x) + ((B + 5.0*C) * x*x) + ((-2.0*B - 8.0*C) * x) + (1.3333333*B + 4.0*C);
        return 0.0;
    }
};

error C2993: 'double' : illegal type for non-type template parameter 'B'

I get it, the standard disallowed using double constants as template parameters and VC++ is finally conforming. But what should I use instead? The expression is evaluated repeatedly and is a true bottleneck, and I'd like the constants to be computed at compile time rather than run time.

A: The problem is that matching template arguments to the program-wide set of instantiations depends on exact equality, which based on the machine's particular representation of floating-point values may vary from platform to platform. (And since the compiler is not required to provide compile-time emulation of the target machine, may vary between compile time and runtime.)
The solution is to replace double with some other kind of unambiguous representation, such as ratios, fractions over a fixed amount such as a million, or your own floating-point style with integer mantissa and exponent.
In C++11, you could apply constexpr function evaluation, which in this case would eliminate the templates:
struct MyClass {
    constexpr MyClass( double b, double c )
        : b15( b * 1.5 ), b20( b * 2.0 ), b03( b * 0.33333333 ),
        /* etc */

    double b15, b20, b03, /* etc */

    double k( double x ) const {
        x = fabs(x);
        if (x < 1.0)
            return ((2.0 - b15 - C) * x*x*x) + ((-3.0 + b20 + C) * x*x) + (1.0 - b03);
        /* etc */
    }
};

This precomputes the constant subexpressions and effectively makes them runtime parameters to a single common function. But the parameter/member object accesses could slow it down.
If the function can always be inlined, that alternative will probably produce similar results to the original template at less effort.

A: if you use a constexpr function it should do everything you want at the minimal cost of having to use ?: operator since you can only have one return statement:
constexpr double k(double B, double C, double x) const
{
    x = fabs(x);
    return
          (x < 1.0) ?
               ((2.0 - 1.5*B - C) * x*x*x) + ((-3.0 + 2.0*B + C) * x*x) + (1.0 - 0.33333333*B)
        : (x < 2.0) ?
           ((-0.16666667*B - C) * x*x*x) + ((B + 5.0*C) * x*x) + ((-2.0*B - 8.0*C) * x)
           + 1.3333333*B + 4.0*C)
        : 0.0;
}

but that requires that x is a literal (known at compiletime)
It also unfortunately requires that you do not use VS as per
http://msdn.microsoft.com/en-us/library/vstudio/hh567368.aspx
if x is a variable (changes at runtime) or you use VS:
just remove the constexpr keyword above. It is likely that most of the optimizations will occur simply from the fact that B and C are known at compiletime - check the asm to verify. (upgrading not only increases strictness, it also likely improved optimization)


text:
Q: How can I make sure the return is an array? I am using the COALESCE operator to make sure I return a consistent data set.
The query looks as follows
SELECT c.id, c.ItemLevel, c.ItemNo, bv.variantId, bv.variantDescription, c.DetailedData.locales[0].images ?? c.BasicData.asset.assets[0].locations[1].path AS images, c.PriceData.WhitePrice, c.PriceData.RedPrice, c.PriceData.DiscountPercentage, c.PriceData.TypeOfDiscount
FROM c
JOIN bv IN c.BasicData.base.sales.variants
WHERE c.brand = 'XXX'
AND c.Consumer = 'YYY'
AND bv.variantId = 'TTT'
AND c.Season = 'XXX'

My challenge is that c.DetailedData.locales[0].images is an array but c.BasicData.asset.assets[0].locations[1].path is not.
I need the c.BasicData.asset.assets[0].locations[1].path to be an array so that the JSON returned is consistent so I can loop the array in my mobile app directly.
How can this be done?

A: I may get your points.
For example, you have below 2 sample documents:
[
    {
        "DetailedData": {
            "locales": [
                {
                    "images": [
                        {
                            "image": "pic1"
                        },
                        {
                            "image": "pic2"
                        }
                    ]
                }
            ]
        }
    },
    {
        "DetailedData": {},
        "BasicData": {
            "asset": {
                "assets": [
                    {
                        "locations": [
                            {
                                "path": "AAA"
                            },
                            {
                                "path": "BBB"
                            }
                        ]
                    }
                ]
            }
        }
    }
]

If you execute your sql,you will get different format:
SELECT c.DetailedData.locales[0].images ?? c.BasicData.asset.assets[0].locations[1].path AS images
FROM c

You could add [] to reset the column,like:
SELECT c.DetailedData.locales[0].images ?? [{"image": c.BasicData.asset.assets[0].locations[1].path}] AS images
FROM c

Output:


text:
Q: Is there a comprehensive list of attributes and properties for the default Shiny slider? Shiny makes use of the ion-rangeslider. I figured out how to modify some of its attributes. The code below changes the button color and the background color of the label above the button, and also removes the slider bar. I need to make additional changes, but am not sure which other slider attributes I can change--and how they should be referred to.
Is there a comprehensive list of this slider's attributes (such as ".irs-slider") and their properties? (E.g., for the attribute .irs-slider: "width"; "height"; "top"; "background", etc.)
Update: GJPLatten's suggestion to right-click the slider in the browser and select "Inspect Element" saved my day. However, I'm still interested in finding a comprehensive list of attribute and property names which also provides descriptive information, since this would be easier to navigate and work with.

library(shiny)

ui <- fluidPage(
  sliderInput("default",
              "Default slider",
              min = 0,
              max = 50,
              value = 20),
  sliderInput("modified",
              "Modified slider",
              min = 0,
              max = 50,
              value = 20),
  tags$style(type = "text/css",
             HTML(".js-irs-1 .irs-slider { width: 8px; height: 20px; top: 20px; background: green }",
                  ".js-irs-1 .irs-bar { display: none }",
                  ".js-irs-1 .irs-bar-edge { display: none }",
                  ".js-irs-1 .irs-single { color: black; background: transparent }"))
)

server <- function(input, output) {
}

shinyApp(ui = ui, server = server)

A: The parts within the HTML() function are all css. W3schools have a great tutorial on this at https://www.w3schools.com/css/default.asp. You can get the element name by right clicking on the element in your browser and clicking inspect element.


text:
Q: Why is a newline inside a heredoc inside a command substitution lost by bash (but not dash)? When run in bash, this command:
cat <<EOF
hello \\
world
EOF

will output as I expect:
hello \
world

But this one outputs hello \world (without the newline), and is unexpected:
echo "$(cat <<EOF
hello \\
world
EOF
)"

If I run the second command with dash, then the output is as expected (with a newline).
Why is the newline removed in 2nd command in bash?

A: Because you are re-parsing the output again, so the double-backslash has already been parsed, and the now-single backslash is quoting the newline, making it a continuation line.
Take them both out and it works as you'd expect.

EDIT
See comments below.
I'd delete the answer, but the useful comments would go as well.


text:
Q: How to include third party library or some CDN's in production mode angular2 CLI ? As far as i know when we run the project in the production mode angular will create one bundle file named as commonly main.js which includes all the js files from the dist folder including dependencies like angular,RxJs etc....
Now my problem is i am using CDN for jQuery and one seprate js file named xyz.js whihc is in my public folder, and i put the entry for both xyz.js and CDN in index.html file but these files not getting included and throw error not found while running the project.
upto my knowledge at the time of production mode all entry's of index.html are ignored then where i have to define those files ?
errors are like
$ is not defined

http://localhost:4200/abc/XYZ.js --not found

at the time of errors project gets crash :(
what should i do ?


text:
Q: Is there any connector to run code in logic app? I am new to Azure.
Is there any connector to run code snippet instead of inline code and azure function?

A: Those are the two ways in which you can have your custom logic/code to run. Another way is to create custom connectors and publish them. You can utilize it in the pipeline created with logic apps


text:
Q: Python: Pandas Timedelta for one month Is there a way to do a Timedelta for one month?
Applying pd.Timedelta('1M') yields Timedelta('0 days 00:01:00').
Is there a code word for month?

A: Timedelta is for absolute offsets. A month "offset", by definition, might have different lengths depending on the value it's applied to.
For those cases, you should use DateOffset:
pandas.DateOffset(months=1)
Functional example:
import pandas as pd
pd.Timestamp('2022-09-29 00:27:00') + pd.DateOffset(months=1)
>>> Timestamp('2022-10-29 00:27:00')


text:
Q: Is there a 2 or 3-bit checksum algorithm Is there a 2 or 3 bit checksum algorithm that I can use to check my 6 bits of data for errors which I am reading in from an optical sensor that detects 8 bit patterns? I was not able to find anything.

A: You can xor the first three bits with the second ones and append the result, then xor them again to check it on the other side.

A: You could possibly use two 3b/4b codes to validate the result:
https://en.wikipedia.org/wiki/8b/10b_encoding

A: Not alot you can do with 0, 1, 2 or 3. Maybe get an integer value from your 6 bits and then do mod 4.


text:
Q: (parser) syntax error on "array: .word 2,5,3,7,9,(some random numbers)" I´m writing a MIPS code trying to find a random given number on my array(vector).
I have a problem when i try to assemble it in QtSpim but it declare an error "spin:(parser)syntax error.....                                     vector:                    .word 2,3,5,6,8,1,3,2,5,9"
    size = 4
    N = 10
                            .data

             vector:                    .word   2,3,5,6,8,1,3,2,5,9
             Tofind:                    .word   6
             Finded:                    .word   0

Any ideas?

A: Ironically, I just tripped over this yesterday in my own code. I normally use mars instead of spim, but used spim. mars will accept this just fine, but spim doesn't like it.
Change:
vector:                    .word   2,3,5,6,8,1,3,2,5,9

Into:
vector:                    .word   2 3 5 6 8 1 3 2 5 9


text:
Q: WSO2 ESB unable to un-deploy endpoints, localentries with CAR undeployment Scenario to replicate the issue with wso2 esb 4.8.0
create the CAR file by selecting all the proxy services, sequences, endpoints, and local entries.
Deploy the car on to WSO2 ESB with console.
This makes deployment of all the artifacts into server.
Now try to un-deploy the car from the console.
Except endpoints, local-entries, everything will be un-deployed.
Please let us know the way to resolve this issue without server restart.

A: I think this is a bug in WSO2, if u try same thing from wso2 web management console it shows similar behaviour, As far i have researched on the topic WSO2 by default does not un-deploy the Registry Artifacts like endpoints or local-entries. Every time you re-deploy the CAR file it overwrites the contents of all the registry artifacts.


text:
Q: How to use the xpath to parse the director part from the html with python 3 I intend to extract the the director's name(such as  tom) from the following html (this just a part example of my html, the whole html, please access http://movie.walkerplus.com/list/2015/12/) with python 3 xpath.
please give your hand to help me solve this issue.
 Thanks in advance!
  <title> ufffff</title>

2015
Dec 1st

007

director

  bruce

wind love

director

   tom

river war

director

   July

o

1月

2月

3月

4月

5月

6月

7月

8月

9月

10月

11月

12月

..................

A: Definitively use lxml for this instead. Like this:
from lxml import etree
f = StringIO(your_html_text)
tree = etree.parse(f)
what_you_are_looking_for = tree.xpath('//*[contains(concat(' ', @class, ' '), ' movies')]')

This is a very robust way of getting the data you want and will tolerate messy life (missing tags in the html, data moving around, etc.) much better than a regular expression.
You can read more about it here. Cheers!

A: Read the link provided by alecxe.  You are having that issue.

*

*You have spaces in your raw string that do not occur in the
sample html

*Quotes are special characters and need to be escaped
or replaced by '.'

*You need to set the re.M flag for multiline
strings  '.' by default does not match newlines

Regex and HTML are a match destined for madness.