Need help to format the result page after searching

Question: I have built a small text based search engine on ROR which will display relevant records having a specified search word in it.since few of the records has more than 1000 words i have truncated each result set to 200 characters.My views file search.html.erb looks like this
 <% @results_with_ranks.each do |result| -%>

  <% content_id = rtable.find(result[0]).content_id %>
  <% content= Content.find(content_id) %>
  <%= truncate content.body, :length => 200 %>

 Record id <%= content.id %>

  <% end -%>

I want to provide an option so that whenever any truncated record is selected its entire body has to be displayed.
I also want to paginate the result page displaying some fixed number of records per page.Can any body help me in doing this?
Thanks in advance.
Answer: For pagination you have no better choice than https://github.com/mislav/will_paginate/wiki
I am not sure exactly what you mean by when the record is selected, but it appears like a Javascript toggle() (if using jquery http://api.jquery.com/toggle/).
Documentation on how to use both these features is very complete
Peer
Comment: This would have been my answer provided the information from kshama.. will_paginate is a great tool!
Answer: I'd approach this problem one of two ways.

Load the full text of a result and hide any extraneous text using CSS/javascript.
Only load the first 200 words, as you're doing now, and load the full text on a specific action from the user (in this case, probably on hover or click).

Option 1 is simpler, but option 2 would save you a fair amount of bandwidth/page load time.
Recommended starting points:

http://api.rubyonrails.org/classes/ActionView/Helpers/PrototypeHelper.html
http://guides.rubyonrails.org/layouts_and_rendering.html

Shouldn't be too hard to figure out once you've got a handle of how rendering works in rails and implement those javascript helpers into your application.


on_touch_up event recieved by canvas. Not sure why

Question: Not sure why on_touch_up is being fired when the button is released.  The other two events, on_touch_down and on_touch_move are not fired.
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.uix.button import Button

class MyPaintWidget(Widget):

    def on_touch_down(self, touch):
        print "on_touch_down"

    def on_touch_move(self, touch):
        print "on_touch_move"

    def on_touch_up(self, touch):
        print "on_touch_up"

class MyPaintApp(App):

    def build(self):
        parent = Widget()

        painter = MyPaintWidget()
        btn = Button(text='Click Me')

        parent.add_widget(painter)
        parent.add_widget(btn)

        return parent

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

Answer: You've overloaded the up, down and move methods of MyPainterWidget and they execute as defined when clicking on the widget.
A uix.Button doesn't have a on_touch_up method so the event propagates up the widget tree. You can investigate this a little further by changing the order of
parent.add_widget(painter)
parent.add_widget(btn)

to
parent.add_widget(btn)
parent.add_widget(painter)

We now see that the both "on_touch_up" and "on_touch_down" are printed to the console, even when clicking the uix.Button, rather than just "on_touch_up".
These are facets of how kivy handles events, the details of which can be found here


Will a covering index help if fields already indexed individually

Question: In a SQL Server 2005 database, I have lots of tables like this Products table
ProductID (PK)
ProductCategoryID (IX)
Description
Price
ExpiryDate
BreakableYN

...where there is a primary key, a foreign key and then a bunch of other fields. Another characteristic of this type of table is that lots of queries only use the 2 ID fields (ProductID, ProductCategoryID), e.g. Employees JOIN EmployeeProductJoin JOIN Products JOIN ProductCategories JOIN ProductDepartments.
If ProductID and ProductCategoryID are already indexed, is it worth adding another index for ProductID, ProductCategoryID?
I know it seems that I'm asking if adding a covering index will help, but what I'm really asking is whether a covering index will help if the fields in that covering index are already indexed individually.
These are definition tables that are not huge, so I'm not worried about adding extra time to INSERTs etc.
Answer: Yes it might. The point of a covering index is that a query can be served by the index alone, without having to access the table. So you include not only the fields on which you are searching but also the fields you want to return, and the query optimizer can avoid accessing the table at all.
You might not really mean "covering index" though...
Comment: Is it not a covering index? I thought as long as you build an index that contains all the fields that a query needs, you have a covering index.
Answer: Is the primary key clustered? If it is, then adding a new index will accomplish nothing, because the ProductCategoryID index will already contain the ProductID values, so it effectively "covers" both columns.
Comment: Downvoted: This new index may be much (maybe 100 times) smaller that the clustered one.
Comment: Alex, that is irrelevant. All nonclustered indexes contain the clustering key. A nonclustered index on PCID will contain PID+PCID data, and a nonclustered index on PID+PCID will also contain PID+PCID data, but the PID will be duplicated in the index key and also the row pointer. Therefore it's redundant.
Comment: Yes, the primary key (ProductID) is clustered. Just want to make sure I'm clear about your response. When I create an index on ProductCategoryID, that index will consist of ProductCategoryID AND ProductID (because ProductID is the clustered index). So, effectively, I already have my ProductID, ProductCategoryID index!
Comment: Sorry, I should have explained in more detail. If a clustered index (CI) exists on a table, then all nonclustered index (NCI) leaf nodes contain the CI value (plus a unique row ID *if* the CI is not itself unique). This means that, when SQL Server uses a NCI to find data, then it already knows the CI value without having to access the table or go to the CI directly. Hence there is no need to include the CI columns in any NCI.
Answer: Only the query plans (with and without the extra indices, and with tables containing realistic amounts and kinds of data) can tell you for sure if the extra indices will help; it's all about helping the query optimizer find a smarter plan, but you can only help so far, and it is conceivable that it may fail to find the plan you'd like (it's but a heuristic "let me try to optimize" engine, after all). That's why looking at query plans is so important (and you need to have realistic data, because that usually does influence the heuristics!).
Answer: I definitely may help, especially if your descriptions are large. It would be easy to benchmark and see for yourself. This new index may be much smaller that the clustered one.
But you only want to have this narrow index if you have highly important queries which you need to speed up no matter what.
Answer: Yes, it can help in one specific way.  The idea of a covering index is that it has some redundant fields that you are using in queries.  If the index can satisfy the data requirements of a query without the query having to hit the underlying table you can save on I/O by getting the data from the index.
Where you have two indexes as you show above the DBMS would have to hit the table as well as resolving two index seeks.
If your query results are widely scattered on the table but belong together on the index you could potentially save quite a lot of I/O on a large query.  In this way, covering indexes can also be used as a sort of 'second clustered index' on a table.
Comment: I'm confused by your answer so will presume I have misread it. The principle of a covering index is to incorporate all columns required by a query, within a single index. Why then would there be redundant columns in the query i.e. not satisfied by the index, as this would not be a covering index? Perhaps you are suggesting that a covering index may also contain additional columns as well as those that are required by the query and therefore still provide coverage?
Comment: The columns are redundant for indexing purposes - that is, the additional columns are not necessary to resolve the selection but contain data that is returned by the query.
Answer: In short Yes, it will improve query performance.
Using a covering index, all of the columns required in your query are present in the Index data structure. This means that SQL server need only query a single index in order to provide the results for your query.
Whereas when you have a scenario of multiple columns, that are indexed separately, in order to serve this query SQL Server will more than likely have to perform a seek/scan of numerous indexes as opposed to just the one. This of course potentially creates more I/O activity.
Make sense?


How to press shift + ctrl + s in Selenium

Question: How to press shift + ctrl + s in Selenium ?
I have used the code below:
Actions action = new Actions(driver);
action.sendKeys(Keys.chord(Keys.SHIFT + Keys.CONTROL + "s")).perform();

its Throwing error
Answer: If you simply send a series of keys, then Webdriver for each keycode first press a given key, then depress it.
So your code sendKeys(Keys.chord(Keys.SHIFT + Keys.CONTROL + "s") is equivalent to the below series of events in the time:

Press SHIFT
Depress SHIFT
Press CONTROL
Depress CONTROL
Press s
Depress s

This is not what you want, because you are excpecting that Ctrl and Shift have been pressed and are held at the moment of time when the S key is pressed.

You need to use Actions#keyDown method to press the key and leave it in the pressed state, and later Actions#keyUp to release the key. So the sequence of actions might be:

Press SHIFT - using keyDown
Press Ctrl - using keyDown
Press then release S (this key can be pressed and immediately released using sendKeys method)
Wait for an visible effect of pressing Ctrl-Shift-S
Release Ctrl - using keyUp
Release Shift - using keyUp

Points 5 and 6 (releasing keys) must be done in order to avoid unexpected effects later in the test code (don't leave Ctrl+Shift in a pressed state).

Here is a link to simple page on jsfiddle which help us to test our WebDriver code.

Press a key on the keyboard in the input field to find out if the Ctrl-SHIFT key was pressed or not.

<input id="ctrl_shift_s" type="text" onkeydown="isKeyPressed(event)">

If you move a cursor to INPUT field on this page (id="ctrl_shift_s" of this element), and then press Ctrl-SHIFT-S keys (holding SHIFT and Ctrl), then a message will appear The Ctrl-SHIFT-S keys were pressed!

Below is an example (working) code tested agaist the above test page using latest IE,Firefox and Chrome drivers. You must use requireWindowFocus(); option in order to run Actions in IE driver.
WebDriver driver= null;
try{

    System.setProperty("webdriver.ie.driver", "C:\\instalki\\IEDriverServer.exe");
    System.setProperty("webdriver.chrome.driver", "C:\\instalki\\chromedriver.exe");
    System.setProperty("webdriver.gecko.driver", "C:\\instalki\\geckodriver.exe");

    InternetExplorerOptions opt =  new InternetExplorerOptions();
                opt.requireWindowFocus();
    //          driver=new InternetExplorerDriver(opt);
    //          driver = new ChromeDriver();
    driver = new FirefoxDriver();

   driver.manage().window().maximize();

   WebDriverWait wait = new WebDriverWait( driver, 10);

   driver.get("https://jsfiddle.net/39850x27/2/");
   final By inputField = By.id("ctrl_shift_s");
   final By messageWeWaitFor = By.xpath("//*[text() = 'The Ctrl-SHIFT-S keys were pressed!' ]");
   final By frame = By.name("result");

   // Swift to a frame (our test page is within this frame)
   driver.switchTo().frame(driver.findElement(frame));

   // move a corsor to the field
   wait.until(ExpectedConditions.elementToBeClickable(inputField)).click();

   Actions a = new Actions(driver);

   // Press SHIFT-CTRL-S
   a.keyDown(Keys.SHIFT)
    .keyDown(Keys.CONTROL)
    .sendKeys("s")
    .build()
    .perform();

  //Wait for a message
 wait.until(ExpectedConditions.visibilityOfElementLocated(messageWeWaitFor));

   System.err.println("Success - Ctrl-Shift-S were pressed !!!");

   // Sleep some time (to see the message is really on the page)
   Thread.sleep(5000);

   // Release SHIFT+CTRL keys
   a.keyUp(Keys.CONTROL)
    .keyUp(Keys.SHIFT)
    .build()
    .perform();

}finally {
    if(driver!=null) {
        driver.quit();
    }
}


How to configure vimdiff

Question: I am getting error when I use vimdiff command.
E91: 'shell' option is empty
Is there any configuration I have to do in order to user this command like setting DISPLAY?
Can someone please help me?
Comment: What's the full command line when you call vimdiff?
Answer: You'll get the answer by typing:
:help E91

Vim is very well documented. You can generally find answers using :help or :helpgrep.
Answer: Try setting the shell option. I have
:set shell=/bin/bash

How to configure vimdiff


Create executable bash script that accepts drag & drop

Question: I compiled mplayer from source on Ubuntu. I didn't want to use a GUI but I wanted to make a executable bash file that gets the path from an file that gets dropped onto the bash file. How do I make such a thing possible?
I wanted to make it look something like this:
mplayer <get full path to file.file-ending>
I want the executable bash file to sit on my desktop ;)

If possible, I'd just like an rightclick -> start with mplayer function, but I don't know how to make one.
Comment: Sorry, not a programming question, voting to move to http://superuser.com/ OR you can 'flag' it and ask for a moderator to move it. (I didn't downvote your question). Good luck.
Comment: Which GUI environment are you using?
Comment: oh I'm sorry, I'm just used to posting in stackoverflow xD
I'm using gnome 3 instead of unity on ubuntu, still with lightdm.
Answer: You can access arguments passed to the script with $1 (for the first argument). And also you should make a .desktop file so Nautilus (or your desktop manager) know what to do and use %u to pass the dropped path to the script.
For example you can create a file named DropOverMe.desktop:
[Desktop Entry]
Encoding=UTF-8
Name=Drop Over Me
Comment=Execute the script with the file dropped
Exec=gnome-terminal -e "/folder/to/the/script/launchme.sh \"%u\""
Icon=utilities-terminal
Type=Application

I use gnome-terminal as I have Ubuntu on my PC, use your preferred terminal application.
And the script could be something like:
#! /bin/bash

echo "Launched with $1" >> /tmp/history.log

Comment: Thank you, just for those who come late like me ;-).
Comment: You're almost 6 years late to the party. Thanks for the thorough answer though!
Comment: I wonder how this could be done using WSL2, which until recently was headless.
Answer: Try:
#!/bin/bash
mplayer "$1"

The file path of the dropped file will be passed to the script file as the 1th command line argument.
Comment: @HitomiTenshi, it would help me greatly if you could share your .desktop file contents - I'm struggling with this one.
Comment: oh god finally I got it working! thanks for the code, it works! I just had to create a mplayer.desktop shortcut which starts the .sh file that can be used as a executeable. And I had to give full permissions to both files. Now it works flawless ;)
Comment: somehow I can't drag and drop on a .sh file. The files just get piled up or copied to the desktop.
Comment: @alfadog67, You might need ` %u` at the end on the Exec line (works for me in xfce), so it passes the args to the script.
Answer: In openned terminal
By using mate-terminal, gnome-terminal or konsole, you could use drag'n drop into oppened window.
This will send URL as tipped, with a space added, but without endline.
For this, run mplayer, I wrote this little loop function:
while IFS=$' \t\r\n' read -d '' -p "Wait for URL to play: " -rsn 1 str &&
    [ "$str" ];do
    while IFS= read -d '' -rsn 1 -t .02 char
    do str+="$char"
    done
    if [ "$str" ] ;then
        read -a req <<<"$str"
        echo $req
        mplayer $req
    fi
  done

First read will determine if something is comming or else end loop.
Second loop with very short timeout will read dropped URL as a single string
read -a req will split string to consider only 1st part
Comment: Since lubuntu doesn't seem to support drag'n'drop over scripts or desktop entries, this is a nice solution for any situation where you need to quickly run something in a given app (md5sum in my case).


Counting special characters in Oracle

Question: Looking for a SQL query in ORACLE that returns the count of all the special characters used in a particular column. Suppose in a column there are 5 rows and each uses two special characters. I am looking for some query that gives 10 as the result.
What I used is:
SELECT * FROM Customers WHERE REGEXP_LIKE(Employees, '[^]^A-Z^a-z^0-9^[^.^{^}^ ]' );

but it seems to not be working.
Tried a lot over the net but no luck.
Update: looking for a solution with 10g
Answer: This should work for you
with t as
(
select 'ar{un' name from dual
union
select 'a#;>' from dual
)

select sum(regexp_count(name,'[^[:alnum:]]')) from t;

For 10g we can use this, since regexp_count() is not available in earlier versions
with t as
(
select 'ar{un' name from dual
union
select 'a;<#' from dual

)
select count(distinct regexp_substr(name,'[^[:alnum:]]',level,1)) from t
connect by level <= LENGTH(regexp_replace(name,'[[:alnum:]]')) + 1;

Another approach in 10g as Peach suggested
with t as
(
select 'ar{}n' name from dual union
select 'a;<#'  from dual

)
select  sum(length(regexp_replace(name,'[[:alnum:]]'))) from t;

Comment: Oracle introduced REGEXP_COUNT() in 11g, so this solution won't work in earlier versions, but it is undoubtedly the most elegant approach.
Comment: @APC - Yeah sure. Actually am trying now another solution to work in the earlier versions, will update the answer in few minutes
Comment: @Saurabh - Since regexp_count is supported in oracle 11g, you can use this function to count the special characters in each row and you can sum it up with the aggregate function. And also you dont need to complicate your regexp like what you did in your query instead you can use [^[:alnum:]] (! of alphabets and digits) which will give you nothing but special chars
Comment: @arunb2w since I dont have deep knowledge of Oracle, I would highly appreciate if you could please provide an explanation along..
Comment: @arunb2w: I am sorry to say but I dont have 11g .I am with 10 g
Comment: @Saurabh - Updated the answer. Please try this
Comment: No need for hierarchical query. Use regexp_replace to remove alnum characters, find the length and sum it up.
Comment: @ arunb2w...  thanks a ton bud for ur quick rply..but also I wud like a bit explanation of terms used in ur query so that I can fit it with my table and also I could understand a bit more for future use...Plss
Comment: @EAT A Peach : Sorry but I didnt get what you mean by remove alnum characters. How can I edit my database to change some strings of name
Comment: @EatÅPeach - Yes that is very easy one to achieve the result. Thank you. Updated your approach in the answer
Comment: The two approaches shared by you guys are returning two different result.

Counting special characters in Oracle


Can't see my widget in frame in tkinter. I want to see button in bottom of the frame in on ceneter

Question: I don't see my buttons.
I want to get this:
enter image description here
I want to see button in bottom of the frame in on ceneter.
This is my code:
from tkinter import ttk
from tkinter import *
import tkinter as tk

root = tk.Tk()
root.geometry('900x650+0+0')
root.title("SV Configuration")
root.eval('tk::PlaceWindow . center')

frame_btn = Frame(root)
frame_btn.grid(row=4, column=1, sticky="nswe")
frame_center = Frame(frame_btn)
frame_center.place(relx=0.5, rely=0.5, anchor=CENTER)
ok_btn = Button(frame_center, text="Ok")
cancel_btn = Button(frame_center, text="Cancel")
cancel_btn.pack()
ok_btn.pack()
root.mainloop()

Answer: First, the size of frame_btn will be 1x1 because its only child frame_center is put inside the frame using .place() which does not adjust its size automatically.
You need to use root.rowconfigure(4, weight=1) and root.columnconfigure(1, weight=1) (as frame_center is put at row 4 and column 1) to let frame_center to fill the available space of frame_btn.
Second, the two buttons are put inside frame_center using .pack() so they will be by default packing vertically, not what you want them to be horizontally.  So specify side=LEFT on both .pack() to pack them horizontally.  Also it is better to specify the width and height options of the two buttons so that they have same size.
Third, the frame_center is put at the center of frame_btn because .place(relx=0.5, rely=0.5, anchor=CENTER). To put it at the bottom, use .place(relx=0.5, rely=0.9, anchor=S) instead.
Finally, you have imported tkinter twice:
from tkinter import *
import tkinter as tk

wildcard import is not recommended, so remove from tkinter import * and add prefix tk. to widget classes, like tk.Button.
Below is the modified code:
from tkinter import ttk
import tkinter as tk

root = tk.Tk()
root.geometry('900x650+0+0')
root.title("SV Configuration")
#root.eval('tk::PlaceWindow . center')

root.rowconfigure(4, weight=1)
root.columnconfigure(1, weight=1)

frame_btn = tk.Frame(root)
frame_btn.grid(row=4, column=1, sticky="nswe")

frame_center = tk.Frame(frame_btn)
frame_center.place(relx=0.5, rely=0.9, anchor=tk.S)

ok_btn = tk.Button(frame_center, text="Ok", width=20, height=3)
cancel_btn = tk.Button(frame_center, text="Cancel", width=20, height=3)

cancel_btn.pack(side=tk.LEFT, padx=10)
ok_btn.pack(side=tk.LEFT, padx=10)

root.mainloop()

And the result:
Comment: Why rely=0.9 ? How did you calculate it ? @acw1668
Comment: It is just an example, you can use another value to suit your requirement.
Comment: Or you can use `frame_center.pack(side=tk.BOTTOM, pady=20)` instead of `.place()`.  Change `pady` to any value that you want.


mysql Array in datatable shows 1 character

Question: I'm trying to fill a datatable via AJAX and Mysql with Ruby - Sinatra and Haml files.
I've finally found how to create my datatable working fine with static data but now I'm trying to change this to data from my mysql database working with AJAX statement.
The problem is my datatable returns only 1 character in each row and shows it only in 1 column like this:

I think the problem might be my array I return, who looks like this:

here is some code in my ruby file who returns the data:
<code>get '/allesites' do
  res = Array.new
  @alleSites = con2.query("SELECT * FROM dbportal.tblSites", :as => :array)
  @alleSites.each do |row|
  res.push(row)
  end
  return res.to_json
end
</code>
last but not least here is the jquery code:
<code>$.ajax({
  url: "/allesites",
  type: "get",
  success: function(data){
    $("#test").dataTable({
      "data": data,
      "columns": [
       { "title": "nummer"},
       { "title": "naam"},

      ]

    });

  },
</code>
Finally I'm also having an error like this:
Comment: Don't use screen shots and images to show us text. Instead, copy, paste and format the text. That allows us to reuse text if necessary without typing it in, plus it lets the search engines find the text, which they then use to help others find your question.
Answer: I just Changed something in my ajax-request and It seems to be fixed right now !
<code> "data": jQuery.parseJSON(data),
</code>
I just tried something and it worked, great !!


Dispatcher::applyFilter _callable - passing message to redirected page

Question: I followed the tutorial in http://li3.me/docs/manual/lithium-basics/filters.wiki
At the end of the tutorial, if the user is unauthorized, then they get redirected to a login page.
My question: I want to know how to display a message on the login page to explain why they got redirected.
I'm assuming I have to pass my message into the closure, but I'm not sure what to do in the closure itself.
Comment: Learn how HTTP redirection works first: http://en.wikipedia.org/wiki/URL_redirection#HTTP_status_codes_3xx
Answer: If you need to persist data between 2 requests, write to the Session.
In your case, before redirecting the user to a new location (login page), write to the Session a message (usually just called flash messages).
Session::write('Flash.auth', array('message' => '...'), array('name' => 'default'))

Then on your views, check if the Session is not empty, to display it or not.
Session::read('Flash.auth', array('name' => 'default'))

Since you'll need to do that in many parts of your application, take a look to li3_flash_message plugin, or roll your own
Comment: I was hoping I could pass it directly to the next page since I'm initiating the redirect myself. Or at least, that's what the closure is looking like its doing to me. I'm not very strong in terms of the plumbing in these things.
Comment: redirect() don't take a flash message param by default, but it's easily extensible to allow you pass it directly from redirect() with something like $this->redirect('/', array('error' => "I'm sorry, I can't seem to find your record.")); --- Come to IRC if you need help for doing that
Comment: if the session is the more natural thing to do, the cleanest, you can use anything else from a cookie to the query string.


How to determine if several players are standing in a certain zone

Question: I'm making my map in Minecraft and making it for several players, I want to make sure that all the players on the map could execute a command in a certain place, that is, all the players who are currently in the world could start the game when they enter a certain zone.
execute if entity @a[x=~,y=~,z=~,dx=~,dy=1,dz=~] <---- not working

Answer: If you want only certain players to execute "commands" in certain places, you have to use a trigger scoreboard. Then on loop you can run a similar following command to enable any players to /trigger that scoreboard.
scoreboard players enable @a[x=100,y=80,z=100,dx=9,dy=0,dz=9] trigger_scoreboard_name

This command enables a player to use the command "/trigger trigger_scoreboard_name" when they enter the bounding box of xyz(100-110, 80-81, 100-110).
Then you have to handle what happens when a player's trigger scoreboard changes.
Comment: If the players leave the region, they will remain enabled to trigger the objective. To disable their trigger, have them run `/trigger  add 0` when they leave. See https://gaming.stackexchange.com/a/382347
Comment: Note: if u leave the x,y,z arguments out of the selector, they default to the command's execution position. Meaning you can "execute positioned ~-10 ~-5 ~-10 run ..." to shift the bounding box in the opposite direction.


Why my hover effect does not animate?

Question: I am 100% sure I got lost with the jQuery selectors. My hover effect is out of order.
Here is my structure:

          <asp:HyperLink ID="HyperLink2" runat="server" NavigateUrl="~/Default.aspx">Start Page</asp:HyperLink>
          Animate this text

and here is the jQuery that should do the animation:
$(".menu_nav ul li a").hover(function () {
    $(this).next("em").animate({ opacity: "show", top: "-75" }, "slow");
}, function () {
    $(this).next("em").animate({ opacity: "hide", top: "-85" }, "fast");
});

and this one is the css:
.menu_nav ul li em {
    background: url(images/hover.png) no-repeat;
    width: 180px;
    height: 45px;
    position: absolute;
    top: -85px;
    left: -15px;
    text-align: center;
    padding: 20px 12px 10px;
    font-style: normal;
    z-index: 2;
    display: none;
}

What am I doing wrong here?
Comment: Nothing wrong with your selectors. See here: http://jsfiddle.net/cxQpt/. The problem is that you're trying to set opacity to display the item, which has no meaning. Look at `show`/`hide` or maybe `slideUp`.
Answer: I simplified your css but basically you need to change the opacity to 1 not show
Link to fiddle
Note the css change from display: none => opacity: 0
Answer: Here you go
http://jsfiddle.net/xygHB/
Change in css
.menu_nav ul li em {
    background: url(images/hover.png) no-repeat;
    width: 180px;
    height: 45px;
    top: -85px;
    left: -15px;
    text-align: center;
    padding: 20px 12px 10px;
    font-style: normal;
    z-index: 2;
    opacity:0;
}

Change in js
$(".menu_nav ul li a").hover(function () {
    $(this).next("em").animate({ opacity: 1, top: "-75px" }, "slow");
}, function () {
    $(this).next("em").animate({ opacity: 0, top: "-85px" }, "fast");
});

Why my hover effect does not animate?


Jquery Tabs using the list (li) tag

Question: Can anyone tell me how I can use li tag instead of using the a href attribute to define the tabs in the javascript and html?
Any help would be appreciated
<!doctype html>

<meta charset="utf-8" />
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />

<link rel="stylesheet" href="/resources/demos/style.css" />

Nunc tincidunt

Proin dolor

Aenean lacinia

 hendrerit.

 hendrerit.

 hendrerit.

Answer: This if i understood it right:
<!doctype html>

<meta charset="utf-8" />
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />

<link rel="stylesheet" href="/resources/demos/style.css" />

Nunc tincidunt

Proin dolor

Aenean lacinia

 hendrerit.

 hendrerit.

 hendrerit.

Answer: I think you're asking how to remove the  tags from the list items? I'm not sure why you'd want to do that. This is how I implement the vast majority of my navigation menus.
But, if you still would like to do this, there are multiple ways, of course. I'm not sure which is best. I'll propose one and let the community crush it if it's wrong. :)
You could do this:

Nunc tincidunt

And use jquery to handle the clicking of the tab:
$().ready({
    $('#tabs li').click(function() {
        var goto_id = $(this).attr('goto');
        var goto = $('#' + goto_id);
        $(window).scrollTop(goto.offset().top - $(window).offset().top + $(window).scrollTop());
    });
});

Seems like overkill, though, considering all of this is built-in with the  tags
Answer: jQuery UI Tabs API (that's a mouthful!) doesn't give you any options to modify the default  structure from above.
That being said, perhaps before calling $.tabs() you could use JavaScript to create the right  structure?
This example could be modified to whatever structure you have on your page, just use JS to rearrange and name items as necessary.
<!doctype html>

<meta charset="utf-8">
<title>jQuery Tabs Test</title>
  <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />

  <link rel="stylesheet" href="http://jqueryui.com/resources/demos/style.css" />

Regular Tabs

Nunc tincidunt

Proin dolor

Aenean lacinia

Proin elit arcu, rutrum commodo, vehicula tempus, commodo a, risus. Curabitur nec arcu. Donec sollicitudin mi sit amet mauris. Nam elementum quam ullamcorper ante. Etiam aliquet massa et lorem. Mauris dapibus lacus auctor risus. Aenean tempor ullamcorper leo. Vivamus sed magna quis ligula eleifend adipiscing. Duis orci. Aliquam sodales tortor vitae ipsum. Aliquam nulla. Duis aliquam molestie erat. Ut et mauris vel pede varius sollicitudin. Sed ut dolor nec orci tincidunt interdum. Phasellus ipsum. Nunc tristique tempus lectus.

Morbi tincidunt, dui sit amet facilisis feugiat, odio metus gravida ante, ut pharetra massa metus id nunc. Duis scelerisque molestie turpis. Sed fringilla, massa eget luctus malesuada, metus eros molestie lectus, ut tempus eros massa ut dolor. Aenean aliquet fringilla sem. Suspendisse sed ligula in ligula suscipit aliquam. Praesent in eros vestibulum mi adipiscing adipiscing. Morbi facilisis. Curabitur ornare consequat nunc. Aenean vel metus. Ut posuere viverra nulla. Aliquam erat volutpat. Pellentesque convallis. Maecenas feugiat, tellus pellentesque pretium posuere, felis lorem euismod felis, eu ornare leo nisi vel felis. Mauris consectetur tortor et purus.

Mauris eleifend est et turpis. Duis id erat. Suspendisse potenti. Aliquam vulputate, pede vel vehicula accumsan, mi neque rutrum erat, eu congue orci lorem eget lorem. Vestibulum non ante. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Fusce sodales. Quisque eu urna vel enim commodo pellentesque. Praesent eu risus hendrerit ligula tempus pretium. Curabitur lorem enim, pretium nec, feugiat nec, luctus a, lacus.

Duis cursus. Maecenas ligula eros, blandit nec, pharetra at, semper at, magna. Nullam ac lacus. Nulla facilisi. Praesent viverra justo vitae neque. Praesent blandit adipiscing velit. Suspendisse potenti. Donec mattis, pede vel pharetra blandit, magna ligula faucibus eros, id euismod lacus dolor eget odio. Nam scelerisque. Donec non libero sed nulla mattis commodo. Ut sagittis. Donec nisi lectus, feugiat porttitor, tempor ac, tempor vitae, pede. Aenean vehicula velit eu tellus interdum rutrum. Maecenas commodo. Pellentesque nec elit. Fusce in lacus. Vivamus a libero vitae lectus hendrerit hendrerit.

Tabs Test

Nunc tincidunt

Proin dolor

Aenean lacinia

Proin elit arcu, rutrum commodo, vehicula tempus, commodo a, risus. Curabitur nec arcu. Donec sollicitudin mi sit amet mauris. Nam elementum quam ullamcorper ante. Etiam aliquet massa et lorem. Mauris dapibus lacus auctor risus. Aenean tempor ullamcorper leo. Vivamus sed magna quis ligula eleifend adipiscing. Duis orci. Aliquam sodales tortor vitae ipsum. Aliquam nulla. Duis aliquam molestie erat. Ut et mauris vel pede varius sollicitudin. Sed ut dolor nec orci tincidunt interdum. Phasellus ipsum. Nunc tristique tempus lectus.

Morbi tincidunt, dui sit amet facilisis feugiat, odio metus gravida ante, ut pharetra massa metus id nunc. Duis scelerisque molestie turpis. Sed fringilla, massa eget luctus malesuada, metus eros molestie lectus, ut tempus eros massa ut dolor. Aenean aliquet fringilla sem. Suspendisse sed ligula in ligula suscipit aliquam. Praesent in eros vestibulum mi adipiscing adipiscing. Morbi facilisis. Curabitur ornare consequat nunc. Aenean vel metus. Ut posuere viverra nulla. Aliquam erat volutpat. Pellentesque convallis. Maecenas feugiat, tellus pellentesque pretium posuere, felis lorem euismod felis, eu ornare leo nisi vel felis. Mauris consectetur tortor et purus.

Mauris eleifend est et turpis. Duis id erat. Suspendisse potenti. Aliquam vulputate, pede vel vehicula accumsan, mi neque rutrum erat, eu congue orci lorem eget lorem. Vestibulum non ante. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Fusce sodales. Quisque eu urna vel enim commodo pellentesque. Praesent eu risus hendrerit ligula tempus pretium. Curabitur lorem enim, pretium nec, feugiat nec, luctus a, lacus.

Duis cursus. Maecenas ligula eros, blandit nec, pharetra at, semper at, magna. Nullam ac lacus. Nulla facilisi. Praesent viverra justo vitae neque. Praesent blandit adipiscing velit. Suspendisse potenti. Donec mattis, pede vel pharetra blandit, magna ligula faucibus eros, id euismod lacus dolor eget odio. Nam scelerisque. Donec non libero sed nulla mattis commodo. Ut sagittis. Donec nisi lectus, feugiat porttitor, tempor ac, tempor vitae, pede. Aenean vehicula velit eu tellus interdum rutrum. Maecenas commodo. Pellentesque nec elit. Fusce in lacus. Vivamus a libero vitae lectus hendrerit hendrerit.

Jquery Tabs using the list (li) tag


How recive data from SQL Server to Android Application, in autonomous manner?

Question: I have created a web service which, querying a SQL Server, retrives several tables.
I'm consuming this web service using KSoap2 package in Android application, and  I want maintain alligned the tables on SQL Server and tables on Android Application.
Many of the tables in SQL Server remain the same over time, but some others change frequently. I need an automatic mechanism for update the tables on Android Application, on the initiative of Server.
I think I need a socket on Android application, for listening a signal transmitted from SQL Server, the meaning of which is "the data in some tables are changed". So, then, I can use the web service call for retrieves new data.
Is this possible? anyone has suggestions?
Comment: maybe not the best solution but ... you can try [Ms Sync Framework](http://code.msdn.microsoft.com/silverlight/Sync-Framework-Toolkit-4dc10f0e) and [my Android implementation](http://selvinlistsyncsample.codeplex.com/) ... you can also use [GCM](http://developer.android.com/guide/google/gcm/index.html) to inform your application that data have change
Answer: The answer for you question is a Android Service class. It can sit behind the program and listen to changes going on your SQL server and update it in SQLite database (or whatever you have)


Why does this select field appear multiple times in my Rails form?

Question: I've got a Rails application that is using nested forms. Details follow and I tried this solution (Rails 3 Nested Models unknown attribute Error), but for some reason, the field is repeating multiple times instead of listing and saving the options correctly. Thanks in advance for your help!
Model information for Newsavedmaps
has_many :waypoints, :dependent => :destroy
accepts_nested_attributes_for :waypoints

Newsavedmap_controller
def new
  @newsavedmap = Newsavedmap.new
  waypoint = @newsavedmap.waypoints.build
  respond_to do |format|
    format.html # new.html.erb
    format.xml  { render :xml => @newsavedmap }
  end
end

def edit
  @newsavedmap = Newsavedmap.find(params[:id])
  if @newsavedmap.itinerary.user_id == current_user.id
    respond_to do |format|
      format.html # edit.html.erb
      format.xml  { render :xml => @activity }
    end
  else
    redirect_to '/'
  end
end

Maptry View
<% form_for @newsavedmap, :html=>{:id=>'createaMap'} do |f| %>
  <%= f.error_messages %>
  <% f.fields_for :waypoint do |w| %>
    <%= w.select :waypointaddress, options_for_select(Waypoint.find(:all, :conditions => {:newsavedmap_id => params[:newsavedmap_id]}).collect {|wp| [wp.waypointaddress, wp.waypointaddress] }), {:include_blank => true}, {:multiple => true, :class => "mobile-waypoints-remove", :id =>"waypoints"} %>
  <% end %>
<% end %>

When I use the above code, my form works correctly, but submitting it gives me this error:
UnknownAttributeError (unknown attribute: waypoint)

When I change ":waypoint do |w|" to ":waypoints do |w|" in the view, the select field disappears when the user is creating a new record, and in the edit view, the select field appears several times (however many waypoints the user saved in the record.)
How can I get this form field to work properly?
EDIT 1
Here is my latest attempt. For new records, the select field does not appear. However, in the edit view, the select field appears multiple times. This is a Rails 2 application, FYI. Taking a cue from the comments, I used a collection_select approach (not collection_for_select because I couldn't find documentation for that.) Again, I appreciate your help!
    <% f.fields_for :waypoints do |w| %>
        <%= w.collection_select( :waypointaddress, @newsavedmap.waypoints, :waypointaddress, :waypointaddress, {:include_blank => true}, {:id =>"waypoints"} ) %>
        <% end %>

Comment: First things first. If the name of the association is `waypoints`, then you **have to** use `f.fields_for :waypoints do |w|`. Of course you don't have an attribute named `waypoint` because that's not the name of the association.
Comment: Now what exactly do you mean by "the select field disappears"? That doesn't sound like a Rails issue.
Comment: Thanks, depa, but when I do that, the select field disappears when the user is creating a new record, and in the edit view, the select field appears several times (however many waypoints the user saved in the record.) By disappears, I mean that the select field does not show up in the source code for a new record or in the browser display. However, it appears several times in the edit view. Again, I appreciate your help!
Comment: Yes, I read it and it doesn't help if you repeat it, because it didn't help me the first time. Are you using JavaScript to create new selects or something like that?
Comment: Also, since you have a problem in the edit view, please post the content of your edit action in the controller.
Comment: There are three fields. There's a multi select field that is my actual fields_for (waypoints). Then, there's another multi select field (selectbox). Users can select options in addbox, click a button, and create them as options in the waypoints select using javascript. Finally, there's an input box users can use to add options to waypoints (inputbox). Added edit code above.
Comment: The waypoints multi select field that uses fields_for begins with zero waypoints inside of it, but it should at least have a blank option.
Comment: And this form you posted is exactly the same one you're using for both `#new` and `#edit`?
Comment: I've eliminated the fields for the @newsavedmap part of the form above, but the form_for part is a duplicate from my code. I don't know if it matters, but this is a Rails 2 app.
Comment: Try using `w.collection_select` instead of `w.select`.
Comment: Error `TemplateError ({:class=>"mobile-waypoints-remove", :id=>"waypoints", :multiple=>true} is not a symbol)`
Comment: Did you just use the same arguments? The API for `collection_select` is a bit different.
Comment: let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/37025/discussion-between-kdp-and-depa)
Answer: Your form has the following problems.

Use f.fields_for :waypoints since the argument needs to match the name of the association.
Use collection_select rather than select, since you have an ActiveRecord model behind that field.

So, taking that into account, you could try this for your form:
<% form_for @newsavedmap, :html => { :id => 'createaMap' } do |f| %>
  <%= f.error_messages %>
  <% f.fields_for :waypoints do |w| %>
    <%= w.collection_for_select :waypoint, :waypointaddress, @newsavedmap.waypoints, :waypointaddress, :waypointaddress, { :include_blank => true }, { :multiple => true, :class => "mobile-waypoints-remove", :id =>"waypoints" } %>
  <% end %>
<% end %>

The API for collection_select is a bit tricky to get right. I usually need a few attempts as well. This previous SO question may help clear things up: Can someone explain collection_select to me in clear, simple terms?
Comment: Thanks for your continued help. Unfortunately, when I tried the code above, the select field does not appear when the user is creating a new record or when the user is editing a record.


$(3y^2+4y)y'+2x+\cos x=0;\; y(0)=1$. Solve the initial value problem

Question: information

$(3y^2+4y)y'+2x+\cos x=0 ;\; y(0)=1$.
Solve the initial value problem

I am stuck at $$y^3+2y^2=-x^2+\sin x+c$$ how do  I isolate y
Answer: Find $c$ by using the initial condition.
As for isolating $y,$ you don't need that. It suffices to leave $y$ to be implicitly defined. Many times, this is what obtains. In fact, this is even better since most times you cannot get a closed form at all.


Is it a good design to use class style in material-ui react component?

Question: I am working on a react website and trying to use material-ui component. I found that material-ui suggests put styles in components' classes property. Each component can use className={...} to take the styles.
...
return (

 ...

Do I have to follow this design if I choose to use material-ui? Or can I create sass file separately and import them in each component? If I do that, is it against material-ui design? Or will I miss any material-ui features?
Comment: Answer to your all questions is **NO**. You can use `sass` file to separate out your `css` and hence your code will become ease to maintain. None of the `material-ui` feature will get missed.
Answer: If the styles are specific to the component, it is fine to keep the styles with that component and use classes as you have done.
If the styles or functionality are shared across components it may be best to import them.
Due to the rise in popularity of css-in-js Material UI has moved towards the material ui css in js approach.
The styled components library was one of the first to adopt this approach and has become popular since developers liked the approach of leveraging tagged template literals. It ties in nicely with React.
There are 3 different API's, it looks as though you are using the Hook API

import React from 'react';
import { makeStyles } from '@material-ui/styles';
import Button from '@material-ui/core/Button';

const useStyles = makeStyles({
  root: {
    background: 'linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)',
    border: 0,
    borderRadius: 3,
    boxShadow: '0 3px 5px 2px rgba(255, 105, 135, .3)',
    color: 'white',
    height: 48,
    padding: '0 30px',
  },
});

export default function Hook() {
  const classes = useStyles();
  return <Button className={classes.root}>Hook</Button>;
}

You can also use the Styled component API. An example is below for Material UI which applies the styles within the component, which is useful if the styles change based on conditions such as what props are passed in. In that case it is good design to encapsulate the logic within that component, rather than importing and external class.

import React from 'react';
import { styled } from '@material-ui/styles';
import Button from '@material-ui/core/Button';

// Like https://github.com/brunobertolini/styled-by
const styledBy = (property, mapping) => props => mapping[props[property]];

const MyButton = styled(({ color, ...other }) => <Button {...other} />)({
  background: styledBy('color', {
    red: 'linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)',
    blue: 'linear-gradient(45deg, #2196F3 30%, #21CBF3 90%)',
  }),
  border: 0,
  borderRadius: 3,
  boxShadow: styledBy('color', {
    red: '0 3px 5px 2px rgba(255, 105, 135, .3)',
    blue: '0 3px 5px 2px rgba(33, 203, 243, .3)',
  }),
  color: 'white',
  height: 48,
  padding: '0 30px',
});

function AdaptingStyledComponents() {
  return (

      <MyButton color="red">Red</MyButton>

      <MyButton color="blue">Blue</MyButton>

  );
}

export default AdaptingStyledComponents;

In that scenario, it is better to keep the styles within that component. So overall it is a balance between importing shared styles and applying local styles.


Scala 2.11 compilation for the Apache Bahir Library

Question: Not sure if this is the right place to post this question. (Apologies if it isn't. And if so, please point me in the right direction.)
I am attempting to compile Apache Bahir to generate scala 2.11 artifacts (as mvn clean install -P scala-2.11 -Dscala-2.11 -DskipTests). When attempting do so, I am running into the following build issues:
[INFO] Reactor Summary for Apache Bahir - Parent POM 3.0.0-SNAPSHOT:
[INFO]
[INFO] Apache Bahir - Parent POM .......................... SUCCESS [ 4.166 s]
[INFO] Apache Bahir - Common .............................. SUCCESS [ 20.276 s]
[INFO] Apache Bahir - Spark SQL Cloudant DataSource ....... FAILURE [ 0.147 s]
[INFO] Apache Bahir - Spark SQL Streaming Akka ............ SKIPPED
[INFO] Apache Bahir - Spark SQL Streaming MQTT ............ SKIPPED
[INFO] Apache Bahir - Spark SQL Streaming JDBC ............ SKIPPED
[INFO] Apache Bahir - Spark SQL Streaming SQS ............. SKIPPED
[INFO] Apache Bahir - Spark Streaming Akka ................ SKIPPED
[INFO] Apache Bahir - Spark Streaming MQTT ................ SKIPPED
[INFO] Apache Bahir - Spark Streaming PubNub .............. SKIPPED
[INFO] Apache Bahir - Spark Streaming Google PubSub ....... SKIPPED
[INFO] Apache Bahir - Spark Streaming Twitter ............. SKIPPED
[INFO] Apache Bahir - Spark Streaming ZeroMQ .............. SKIPPED
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 24.877 s
[INFO] Finished at: 2020-10-07T18:42:46-07:00
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal on project spark-sql-cloudant_2.12: Could not resolve
 dependencies for project org.apache.bahir:spark-sql-cloudant_2.12:jar:3.0.0-SNAPSHOT:
The following artifacts could not be resolved: org.apache.bahir:bahir-common_2.11:jar:3.0.0-
SNAPSHOT, org.apache.bahir:bahir-common_2.11:jar:tests:3.0.0-SNAPSHOT: Failure to find
org.apache.bahir:bahir-common_2.11:jar:3.0.0-SNAPSHOT in https://repository.apache.org/snapshots
 was cached in the local repository, resolution will not be reattempted until the update
interval of apache.snapshots has elapsed or updates are forced -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the
following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/DependencyResolutionException
[ERROR]
[ERROR] After correcting the problems, you can resume the build with the command
[ERROR] mvn <args> -rf :spark-sql-cloudant_2.12

Upon examining the common/target directory, I see that although there is a scala-2.11 sub-directory with compiled class files in there, I don't see the appropriate bahir-common_2.11-3.0.0-SNAPSHOT*.jar files being generated (while the bahir-common_2.12-3.0.0-SNAPSHOT*.jar seem to be generated just fine).
I was wondering if anyone here could potentially help with this. Thanks in advance!
Answer: I suppose this is one way to do it(?):
$ cd <project_root_dir>
$ ./dev/change-scala-version.sh 2.11
$ mvn clean package -Pscala-2.11 -Dscala-2.11 -DskipTest

PS: If anyone has an authoritative answer to this, please chime in. Thanks!


Force data sync with firebase server from Android

Question: I'm working on an Android app which has sqlite database. I wanted to add synchronisation for the db with some cloud service and across multiple devices of the same user. There will be login mechanism and data will be different for different users. The synchronisation will be for logged in users only. For others the data will reside locally only.
I found firebase very interesting and started adding it for the synchronisation. I cannot completely replace sqlite with firebase because I need to provide offline experience for users that are not logged in.
I implemented syncadapter for the sync operation. And I'm doing the sqlite<->firebase two way synchronisation there.
I'm using firebase transactions to avoid conflict from multiple devices. But I read that firebase Android initially writes on offline database and sync with server at a later time. This may cause transactions to fail sometimes creating inconsistencies in data. And also I think transactions are not maintained across app restarts.
If there was an option to disable offline feature for firebase and each request is sent to server instantly and finish with a successful completion or a failure I may be able to implement the synchronisation correctly here.
So is there any way to force to do write and read directly to and from server?
Is there a better way to do this ensuring good conflict handling across multiple devices?
Is firebase not suited for this purpose?
Comment: Too much text, not enough code. But a few things: "I need to provide offline experience for users that are not logged in". Firebase does not require the users to be logged in. If you're worried about identifying the users, you can use [anonymous authentication](https://www.firebase.com/docs/android/guide/login/anonymous.html).
Comment: "is there any way to force to do write and read directly to and from server?". [Detect if the user is connected to Firebase](https://www.firebase.com/docs/android/guide/offline-capabilities.html#section-connection-state), and only then write.
Comment: "If there was an option to disable offline feature for firebase and each request is sent to server instantly and finish with a successful completion or a failure" Sounds like you're looking for a [completion listener](https://www.firebase.com/docs/android/guide/saving-data.html#section-update#section-completion-callback).
Comment: Hey @FrankvanPuffelen thanks for your comments. Sorry for the long text. I didn't add code because I'm seeking solution to my design issues.

Will anonymous authentication work offline? Can I ensure all data for the anonymous user be available offline (just like sqlite) irrespective of whether the user connected to network or not. I think there is limit on amount of data that can be persisted offline in firebase.
Comment: Even if I check connected status and do the write, is it guaranteed that the connection persists till the operation is finished? Basically I don't want the data to saved offline (while using sqlite + firebase) it should either write to the server or fail and get callback on this so that I can keep track of it.

If a complete listener is invoked with no FirebaseError can I assume the data is written to the server by that time? Will it fail if there is no connectivity?
Answer: If someone is still looking for the solution.
While using firebaseRef.addValueEventListener() initially it loads data from available cache, then requests updated data from server.
In order to retrieve latest server side data, We made sure user is connected to internet and also connected to firebase server database.
<code>        DatabaseReference connectionRefrence;
        ValueEventListener connectionValueEventListener;

        connectionRefrence = FirebaseDatabase.getInstance().getReference(".info/connected");
        connectionValueEventListener = new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                boolean connected = dataSnapshot.getValue(Boolean.class);
                if (connected) {
                    printLog("connected");
                    // TODO :: Perform your operation here with live data

                } else {
                    printLog("not connected");
                }
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {
                printLog("connection cancelled");

            }
        };
</code>
I hope it helps.


White color not display proper using material3 in Card widgets

Question: I have used card widget and container both in one screen and set the white color in both and it's display correct in container but not correct in card widget. I have attache the screenshot. in this screenshot code and emulator both are show for compared.

Thank you in advanced
Note I have used the App them for Light theme and dark theme.
ThemeData lightTheme(){
return ThemeData.light(useMaterial3: true).copyWith(
scaffoldBackgroundColor: Colors.white,
primaryColor: Colors.black,
primaryColorDark: Colors.white,

appBarTheme: AppBarTheme(
    backgroundColor: Colors.white,
  shadowColor: Colors.black,
  elevation: 15,
  foregroundColor: Colors.black,
  titleTextStyle:TextStyle().copyWith(color: Colors.black,fontFamily: EAFontName.Muli,fontWeight: EAFontWeight.muliMedium),
),
textTheme: TextTheme(
  titleSmall: TextStyle().copyWith(color: Colors.black,fontFamily: EAFontName.Muli,fontWeight: EAFontWeight.muliRegular,fontSize: EAFontSize.size10),
  titleMedium: TextStyle().copyWith(color: Colors.black,fontFamily: EAFontName.Muli,fontWeight: EAFontWeight.muliSemiBold,fontSize: EAFontSize.size12),
  titleLarge: TextStyle().copyWith(color: Colors.black,fontFamily: EAFontName.Muli,fontWeight: EAFontWeight.muliBold,fontSize: EAFontSize.size16),
),
  bottomNavigationBarTheme: BottomNavigationBarThemeData(
      backgroundColor: Colors.white54,
      selectedItemColor: Colors.black,
      unselectedItemColor: Colors.black54,
    elevation: 16,
  ),
  cardColor: Colors.white,
  cardTheme: CardTheme(
      color: Colors.white,
      shadowColor: Colors.black,
      elevation: 6,
    shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(16),
       // side: BorderSide(color: Colors.black,width: 1)
    ),
  ),

 );
}

    ThemeData darkTheme(){
   return ThemeData.light(useMaterial3: true).copyWith(
scaffoldBackgroundColor: Colors.black,
primaryColor: Colors.white,
primaryColorDark: Colors.black,
appBarTheme: AppBarTheme(
  backgroundColor: Colors.black,
  shadowColor: Colors.white,
  elevation: 15,
  foregroundColor: Colors.white,
  titleTextStyle: TextStyle().copyWith(color: Colors.white,fontFamily: EAFontName.Muli,fontWeight: EAFontWeight.muliMedium),
),
textTheme: TextTheme(
  titleSmall: TextStyle().copyWith(color: Colors.white,fontFamily: EAFontName.Muli,fontWeight: EAFontWeight.muliRegular,fontSize: EAFontSize.size10),
  titleMedium: TextStyle().copyWith(color: Colors.white,fontFamily: EAFontName.Muli,fontWeight: EAFontWeight.muliSemiBold,fontSize: EAFontSize.size12),
  titleLarge: TextStyle().copyWith(color: Colors.white,fontFamily: EAFontName.Muli,fontWeight: EAFontWeight.muliBold,fontSize: EAFontSize.size16),
),
bottomNavigationBarTheme: BottomNavigationBarThemeData(
  backgroundColor: Colors.black54,
  selectedItemColor: Colors.white,
  unselectedItemColor: Colors.white54,
  elevation: 16,
),
cardColor: Colors.black,
cardTheme: CardTheme(
    color: Colors.black,
    shadowColor: Colors.white,
  shape: RoundedRectangleBorder(
      borderRadius: BorderRadius.circular(16),
    //  side: BorderSide(color: Colors.white,width: 1)
  ),
  elevation: 8
    ),
 );
}

I have also try add Theme color to card widegts but same result getting.
Thank in advanced
Answer: With material 3 there is new option for this which is surfaceTintColor add that to the card widget and set to what you want read more here for migrating to the material 3
return Card(
  // color: Colors.white,
  surfaceTintColor: Colors.white,
  elevation: 20,
  child: Padding(
    padding: const EdgeInsets.all(32.0),
    child: Text(
      'Hello, World!',
      style: Theme.of(context).textTheme.headlineMedium,
    ),
  ),
);

Answer: In Material3, the cards are displayed with their surfaceTintColor attribute's default color. So, if you want them to appear white, that's the attribute you should change.
If you want all the cards in the app to be white, you can modify the ThemeData as follows:
// Modify the ThemeData
ThemeData(
  // Other theme configurations...
  cardTheme: CardTheme(
    surfaceTintColor: Colors.white,
  ),
)

This will set the surfaceTintColor of the CardTheme to white, ensuring that all cards in the app have a white appearance. More here for migrating to the material 3!
Answer: I did a quick and dirty implementation of a Card widget using Material design and it seems to be working fine and shows the white color properly.
Here is my code:
//imported google's material design library
import 'package:flutter/material.dart';

void main() {
runApp(
    /**Our App Widget Tree Starts Here**/
    MaterialApp(
    home: Scaffold(
    appBar: AppBar(
        title: const Text('Card widget demo'),
        backgroundColor: Colors.white,
        centerTitle: true,
    ), //AppBar
    body: Center(
        /** Card Widget **/
        child: Card(
        elevation: 50,
        color: Colors.white,
        child: SizedBox(
            width: 300,
            height: 200,
            child: Padding(
            padding: const EdgeInsets.all(20.0),
            child: Column(
                children: [
                const Text(
                    'My card widget',
                    style: TextStyle(
                    fontSize: 15,
                    color: Colors.black,
                    ), //Textstyle
                 ), //Text
                ],
            ), //Column
            ), //Padding
        ), //SizedBox
        ), //Card
       ), //Center
      ), //Scaffold
      ) //MaterialApp
     );
   }

Output

Can you please check if any other Theme or color is getting applied to your Widget.
Comment: Thank you @inkredusk for the response but now I'm getting the issue. I have set the "true" in "useMaterial3: true" in my "ThemeData.light(useMaterial3: true).copyWith()". but after set to "false" it's working properly.
Comment: ok please accept my answer if it has helped you :)
Comment: If you set the `useMaterial3` to true, then widgets that have been migrated to Material 3 will use new colors, typography and other features of Material 3. If `false`, they will use the Material 2 look and feel.
Comment: Yes, But why white color loose his property means not display proper white in material3.
Comment: For that you need to check what is difference between `material3` and `material2`.  Please check this link https://blog.codemagic.io/migrating-a-flutter-app-to-material-3/
Answer: Set both surfaceTintColor & color properties of the Card to get the desired color.
Answer: For people who may still need the solution to this, set your theme this way:
theme: ThemeData.light().copyWith(
          cardTheme: CardTheme(
            surfaceTintColor: Color(0xFFFFFFFF)
          ),
          cardColor: Colors.white,
        ),

Then in any Card you want to set your color, you set the color: property, to be:
color: Theme.of(context).cardColor,

Then you have your Card color displayed as white in Material3 design.


How can I rename a file placed in remote location while it is getting streamed

Question: I want to add some temporary suffix to file while I am streaming the file from remote directory.
I am streaming the file from remote directory using spring integration dsl and I want to make sure that one file is getting read by single application at a time. So i am thinking to adding some temporary prefix to file while it is getting streamed. I am using outbound gateway to fetch the data.
Any pointers will be very helpful. Currently I am renaming the file before reading and after reading, I really don`t want to do that.
Answer: consider using file locking, instead of renaming. Here is the relevant part from the 13.2 Reading Files spring-integration documentation:

When multiple processes are reading from the same directory it can be desirable to lock files to prevent them from being picked up concurrently. To do this you can use a FileLocker. There is a java.nio based implementation available out of the box, but it is also possible to implement your own locking scheme. The nio locker can be injected as follows:

<int-file:inbound-channel-adapter id="filesIn"
    directory="file:${input.directory}" prevent-duplicates="true">
    <int-file:nio-locker/>
</int-file:inbound-channel-adapter>

A custom locker you can configure like this:
<int-file:inbound-channel-adapter id="filesIn"
    directory="file:${input.directory}" prevent-duplicates="true">
    <int-file:locker ref="customLocker"/>
</int-file:inbound-channel-adapter>

[Note]
  When a file inbound adapter is configured with a locker, it will take the responsibility to acquire a lock before the file is allowed to be received. It will not assume the responsibility to unlock the file. If you have processed the file and keeping the locks hanging around you have a memory leak. If this is a problem in your case you should call FileLocker.unlock(File file) yourself at the appropriate time.

Please see the docs for Interface FileLocker and Class NioFileLocker for more info.
Comment: I am using Sftp.outboundGateway(sftpSessionFactory(), GET, "payload.remoteDirectory + payload.filename").options(STREAM).temporaryFileSuffix("_reading"). How can I apply locking in this.
Comment: Please see the docs for [Interface FileLocker][2] and [Class NioFileLocker][3] for more info. (see links at the bottom of the above post)
Answer: I would use the Apache Commons FileUtils. https://commons.apache.org/proper/commons-io/javadocs/api-2.5/org/apache/commons/io/FileUtils.html#moveFile
Typically what I do is write the file during initial transfer to a temporary working directory. After the file is completely transferred I do a checksum to guarantee the file is correct. At this point I move the file to the final directory being used by the other applications logic. As long as the working directory and the final directory are on the same filesystem the move will be atomic. This will guarantee no race conditions between the different parts of the application using the file.


How to know if 'Unguarded Nomadic Frontier' event already fired?

Question: I'm at 1635 with over 1000 development and bordering Ming and I don't know if the 'Unguarded Nomadic Frontier' event has already fired or if it's brewing up. Is there anyway to figure out if it fired earlier in the run and maybe I missed the pop up?
Answer: Unguarded Nomadic Frontier is a disaster, not an event.
If you are China, you can see whether a disaster is brewing or not on the stability & expansion tab. Disasters are at the top next to your war exhaustion.
The requirements for unguarded nomadic frontier are the following:

Country must be Emperor of China
does not have an ongoing disaster.
has a neighboring country that:

has the Steppe Nomads government reform.
has a total development (including non-tributary subjects) of at least 300.
is not a subject.
does not have a truce with the Emperor of China.
does not have an alliance with the Emperor of China.

If you aren't China, you have to manually check whether the above conditions are fulfilled and the disaster progress starts. If the disaster happens, you will get a popup notification. The disaster can only happen once, so if you missed it, there is no way to know.
If you are the horde next to Ming and have the appropiate governemnt reform, the disaster should happen after around 8 years of establishing a border, unless another disaster is running in China.


retrieve users who are not blocked (many to many relationship)

Question: In my laravel app users can block other users (via many to many relationship), however when I retrieve users I still GET BLOCKED USERS in results.
I do know for certain users are getting blocked succesfully since I print $blockedUserIds results, so the problem might be in the query itself.
I retrieve non blocked users like this (still get blocked ones sadly):
$blockedUserIds = $user->blockedusers()->get()->pluck('id');

User::select('*')
->when(count($blockedUserIds)>0, function($query) use ($blockedUserIds)
        {
            $query->whereDoesntHave("blockedusers", function ($query) use ($blockedUserIds)
            {
                $query->whereIn("blocked_id",$blockedUserIds);
            });
        })
->get();

How I add a blocked user to users:
        $user = User::with('blockedusers')->findOrFail($request['reporter_id']);

        $blocked_id = $request['reported_id'];

        $user->blockedusers()->attach($blocked_id);

Blocked users migration (many to many relationship):
Schema::create('blockedusers', function (Blueprint $table) {
            $table->increments('id');
            $table->unsignedInteger('blocker_id')->index();
            $table->foreign('blocker_id')->references('id')->on('users')->onDelete('cascade')->onUpdate('cascade');
            $table->unsignedInteger('blocked_id')->index();
            $table->foreign('blocked_id')->references('id')->on('users')->onDelete('cascade')->onUpdate('cascade');
            $table->timestamps();
        });

Another question, should I call save after I attach?
Comment: Please share the relations you set on your `Model`. Also, is there a `friends` mechanism on your app where someone becomes *friend* with another ?
Answer: As ths said in their comment, it would have been useful if you included the blockedusers relationship in your question.
Nonetheless I had a look at your query, assuming the following relationship on the User model:
public function blockedusers()
    {
        return $this->belongsToMany(User::class, 'blockedusers', 'blocker_id', 'blocked_id');
    }

If your relationship is different then this might not be helpful to you. In that case please provide your relationship.
That being said.
One way to achieve what you want would be by replacing your entire query by:
$users = User::whereNotIn('id', $blockedUserIds)->get();

If you also want to check if the user has any blocked users, you can achieve that in a less verbose way:
count($blockedUserIds) ? $users = User::whereNotIn('id', $blockedUserIds)->get() : $users = User::all();

If you also want to exclude the current user, then you can do:
count($blockedUserIds) ? $users = User::whereNot('id',$user->id)->whereNotIn('id', $blockedUserIds)->get() : $users = User::whereNot('id',$user->id)->get();


cmake dependency between two projects at the same level

Question: In my CMake project I have two 3rd party libraries which are required.
The problem is that the second one requires the first one to be build first.
To be precise I have the following structure
   -project
      CMakeLists.txt // add_subdirectory(first_lib)
                     // add_subdirectory(second_lib)
      - first_lib
           CMakeLists.txt // ...
      - second_lib
           CMakeLists.txt // ..
                          // contains find_package(first_lib REQUIRED)
                          // ..

This project cannot build because the first library must be build first and installed to make available its package.
What's the best way to deal with this case in CMake?
Answer: I found an answere here using
add_dependencies()

Force building external project (with buildtools) before main project with CMake
Comment: Yes, that is surely easier way to force build order. But will find_package(first_lib) actually find anything? first_lib is not installed before second_lib building begins.
Comment: @ptrlukas unfortunately now. I've just found that there was an issue when I build that made me believe that tmy issue was sorted out. The question is still open I am afraid.
Answer: You can make second_lib depend on target name of first_lib. This will force first_lib to be build first.
To avoid modification of CMakeLists.txt of second_lib you can use the following solution:
Create a custom Findfirst_lib.cmake module. Set any first_lib-related variables expected by second_lib inside the module.
set(FIRST_LIB_LIBRARIES first_lib) #use *first_lib* target name here.
set(FIRST_LIB_INCLUDE_DIRS ${CMAKE_SOURCE_DIR}/first_lib/include)

Do not forget to add the module's directory to CMAKE_MODULE_PATH.
This solution assumes that second_lib uses the variables, set by Findfist_lib module, in target_link_libraries, target_include_directories etc. Like:
target_link_libraries(second_lib ${FIRST_LIB_LIBRARIES})

I have not found a way to make it work with imported targets.
Comment: hi ptrlukar, I found the answer and I post it. Works pretty well. Thanks for your help.


using super pom only for testing

Question: I have a lot of maven projects, which are dependent on each other.
I already have a super pom for the actual projects and this works pretty well.
Now I want to create a super pom for all my integrationtests projects. I did it the same, but every time I run maven test it failed.

[ERROR] Failed to execute goal on project *: Could not resolve
  dependencies for project ::jar:0.0.1-SNAPSHOT: The following
  artifacts could not be resolved: ::jar:0.0.1-SNAPSHOT,
  ::jar:0.0.1-SNAPSHOT, ::jar:0.0.1-SNAPSHOT, ::jar:0.0.1-SNAPSHOT: Could not find artifact *:***:jar:0.0.1-SNAPSHOT -> [Help 1]

The problem is that maven looks for jar files but my project consists of war projects. Here is my pom file:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>***</groupId>
    <artifactId>***-parent_IntegrationTests</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>pom</packaging>
<name>***_IntegrationTests</name>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>

<build>
    <pluginManagement>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.22.0</version>
            </plugin>
        </plugins>
    </pluginManagement>
</build>

<modules>
    <module>../***</module>
    <module>../***</module>
    <module>../***</module>
    <module>../***</module>
    <module>../***</module>
    <module>../***</module>
</modules>

<dependencies>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
        <scope>test</scope>
    </dependency>
</dependencies>

Is there a way to tell maven to use the war files instead of jars?
Edit: Sorry if it is not clear enough. I want a single maven project to run all my integrationtest projects. each one is a maven project. Therefor I want to use a pom with modules (all the integrationtest project) in it. But every integrationtest project contains dependencies to my other projects and the problem I want to fix is that maven does not find my compiled projects because it looks for jar files but my projects are war files.
Answer: You can reference WARs as dependencies by using <type>war</type> in the dependency.
Comment: Is there also a way to do this for all modules? Because the super pom has only junit as dependency and the modules have their own ones.
Comment: Can you edit your question and give an example of what you want?

using super pom only for testing


Finding Last row using usedrange

Question: I am creating a large macro code for automating my daily office report.
I am using following code for getting Last row.
Lrow = ActiveSheet.UsedRange.SpecialCells(xlLastCell).Row

in what cases this code will end up giving wrong results.
Like using "xlup from last cell of column" is useless when data is not in tabular form.
Eg. column 1 have 10 cells & column 2 have 25 cells.
Comment: @CallumDA Tag description says *THIS TAG IS PENDING REMOVAL. Instead, please use tags [excel] and [vba]. (More info: https://meta.stackoverflow.com/q/370095)*
Comment: I've found the range.Find with xlByRows and xlPrevious to be the most reliable method for ragged data.
Comment: @SiddharthRout, while the question isn't a duplicate -- the answer definitely covers this question too (nice answer btw). If only that other question was called something more like *"How to find the last row on a sheet"*
Comment: It took some time. But I read that complete thread. Thank you. Got what I needed. Have a nice day everyone.
Comment: @Pᴇʜ is there a reason you removed excel-vba tag?
Comment: Gaurav if you feel this is not a duplicate or the linked post doesn't provide a solution to your query then let me know and I will re-open it :)
Comment: @Pᴇʜ, thanks I didn't realise that
Comment: @SiddharthRout I am trying this code, which is not frequently used. I want you guys to let me know, in which situations my code can go wrong?
Comment: Did you go through the link that I sahred?
Comment: @SiddharthRout Yup, I saw your answer & also agree that it gives correct answer. But I am trying alternate options.
Comment: No I meant, Did you read about the "usedrange" part. I was referring to `I want you guys to let me know, in which situations my code can go wrong? – Gaurav Jain 7 mins ago`
Answer: You can find the last Row in a sheet using find. e.g.
LastRow = ActiveSheet.Cells.Find("*", LookIn:=xlFormulas, SearchOrder:=xlByRows, _
    SearchDirection:=xlPrevious).Row

Comment: I usually include something like an `After:=ActiveSheet.Cells(ActiveSheet.RowsCount, ActiveSheet.ColumnsCount)`  argument.
Comment: @user11246173 I don't think you need it - but doesn't hurt either
Comment: Can you try this code with a excel data in which column 1 have 10 cells & column 2 have 25 cells. It end up giving Row("10") as last row, while my last row is Row("25")
Comment: @GauravJain I've set up a workbook with 10 rows in column 1, and 25 rows in column 2 and it comes back with 25. Can you update your question with the code that you're trying and is failing?
Comment: Done its working. But can you tell me issues in my code.
Comment: Nothings wrong with your code. Just `UsedRange` can give unexpected results so is usually best to avoid when trying to get the last row of a sheet. Have a look at this answer - it explains it a bit more. [link](https://stackoverflow.com/a/50434593/3042759)

Finding Last row using usedrange


Use FusionCharts in sandbox solution

Question: Has anyone been successfully rendering charts using fusion charts in a sandboxed solution?
How would you get the SWF file onto SharePoint? I included it and deployed it via feature and the Elements.xml looks like the following:
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
   <Module Name="FusionCharts">
      <File Path="FusionCharts\FCF_Column2D.swf" Url="FusionCharts/FCF_Column2D.swf" />
      <File Path="FusionCharts\FCF_Gantt.swf" Url="FusionCharts/FCF_Gantt.swf" />
   </Module>
</Elements>
When the sandbox solution is deployed, you can access the SWF file from http://sharepointsite/FusionCharts/FCF_Gantt.swf, the browser will attempt to open/save the file. If this file is deployed via farm solution, and be deployed to _layouts folder, which I can access via http://sharepointsite/_layouts/FusionCharts/FCF_Gantt.swf, it renders with error message "invalid xml data". The farm solution deployment is correct because MIME type is properly set to "application/x-shockwave-flash" and thus my custom web part which renders chart using this SWF file works. But if my sandboxed web part is to use the SWF file deployed as site pages, it does not work. Any idea?
Thanks in advance.
Sean
Answer: The problem is resolved with help from DevExpress team. Though SWF can be deployed to SharePoint site document library, you would need Farm Administrator to go into Central Admin pages and set the property in Application Management for the Web application to allow "Permissive". Go to Central Admin -> Application Management -> Select Web Application -> General Settings (Ribbon button), change "Browser File Handling" from "Restrict" to "Permissive".

Use FusionCharts in sandbox solution


Deep freeze, shower water is just dripping

Question: We are going thru a deep freeze (-9F). The shower upstairs is just dripping hot water, should I leave it dripping in hope that it will eventually melt the blockage, or should I completely shut down water in the house.
Comment: let it drip''''
Answer: If you are having freezing-pipe problems, you should either keep water running or drain the pipes.
Running water, even running cold water, will generally be warm enough not to freeze easily. Underground usually settles at or near the yearly average temperature for the region, which for most of us is above freezing. As long as you keep that warmer water coming through, it can help keep the pipes warm enough not to freeze solid. A trickle may be sufficient for that. Hot water is better for this purpose, of course.
It's when the water stops moving and starts freezing all the way through -- and then continuing to expand -- that you get burst pipes.
The other solution is to drain the affected pipes so there isn't any water in them to freeze.
If your house is still heated, the pipes most at risk are going to be the ones that run outside the heat envelope -- pipes in outside walls and don't have much insulation between them and outside are a classic example.
Answer: Close the main valve to the house, turn off the water heater and open all faucets to give the water that's not yet frozen a "place to go".  When decent temps return, be sure to run all faucets until no more air comes out, (esp. important for hot water faucets), then turn on the WH ....it's been a continent event right now.


Adding a .xcassets file to an Xcode framework project

Question: I've got a framework project that uses a number of images. As it stands I just drag these images into the project so that they sit alongside my source files:

When I embed this project into a separate app project, I can access these resources as expected.
Ideally, I'd now like to organize my framework images with a .xcassets file. Unlike app projects, the framework project template doesn't provide one of these by default, so I've added one manually using the File > New menu. Unfortunately when I rebuild the framework and re-embed it, I can no longer access the images. Is what I'm trying to do possible?
Answer: If you want to access assets in a subproject (framework etc.) you need to make sure that you are collecting them from their own bundle since they are not part of the Main Bundle.
You can do that simply with this Swift 4 code:
let bundle = Bundle(for: type(of: self))
let image = UIImage(named: "imageName", in: bundle, compatibleWith: nil)

Comment: @TheNeil Storyboards will only see images in the main bundle. If you use CocoaPods you can use `resources` in your podspec and all your framework assets will eventually be included in the main bundle: https://guides.cocoapods.org/syntax/podspec.html#tab_resources.

Another way would be to create a `.bundle` file along with your framework but the consumer of your framework needs to *manually* drag the `.bundle` file in his project.
Comment: Hi Foti. Any suggestions how to use the image within a storyboard or xib? When I try, I get an error: **Could not load the "" image referenced from a nib in the bundle with identifier ""**
Answer: From what I can make out, the answer to my question is yes, sort of...
To make use of the NSImage(named: ...) API one of two things needs to be true: either the image should exist within the app's main bundle, or (to paraphrase the docs):

[there should be] an [NSImage] object whose name was set explicitly using the setName: method and currently resides in the image cache.

In the case where the image resides in an embedded framework, the first isn't true since the framework is a separate bundle, and there's no way of adding to the main bundle at runtime. This leaves the second approach.
Whenever your code is going to use NSImage(named: ...) make sure you've already loaded the image using some other way, then set its name:
let bundle = NSBundle(forClass: MyFrameworkClass.self)
let image = bundle.imageForResource(name) // image in the framework .xcassets
image.setName(name)

I don't know how much use this is, and you should definitely be aware of the notes in the docs about how the image cache operates, but it is at least one way of storing images in a .xcassets folder in one bundle, then accessing them from another.
Comment: Thanks for the info. Shame that Apple require such workarounds when reuse of resources should really be encouraged where possible, but at least it's achievable.
Comment: Hi Paul. Any suggestions how to use the image within a storyboard or xib? When I try, I get an error: **Could not load the "" image referenced from a nib in the bundle with identifier ""**


Display LIVE Preview Of Textarea Front End Javascript

Question: On my project I have a div which is a text area where I can wrap text in to code format.
I also have a button with a id="preview"
Is it possible in another div to display the output of the text area once click on preview button in a front end view like what it would be like on IE or FIREFOX.
Codepen Example: http://codepen.io/riwakawebsitedesigns/pen/lfpKF
HMTL Code

<textarea id="widget">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Temporibus repellendus inventore, voluptatum ipsa ipsum debitis voluptates, laudantium nulla odio sed, pariatur quaerat quae numquam beatae ad odit optio quasi magni explicabo tenetur. Consectetur, animi, autem? Non laboriosam ad nisi, commodi, dolores soluta. Dolorum error unde itaque ipsum a? Libero sapiente eligendi similique, itaque deserunt aliquid magnam ducimus nesciunt, iste ad nihil labore assumenda soluta earum. Rerum deserunt totam aperiam maiores facere eum sapiente modi non debitis consectetur voluptatum, voluptatibus labore repellendus tempora voluptate error nesciunt eaque possimus. Consectetur laborum ab ipsum, voluptate perspiciatis quos omnis delectus dicta mollitia atque voluptates!</textarea>

    <button id="code">Code</button>
    <button id="preview">Preview</button>

Javascript
function wrapText(elementID, openTag, closeTag) {
    var textArea = $('#' + elementID);
    var len = textArea.val().length;
    var start = textArea[0].selectionStart;
    var end = textArea[0].selectionEnd;
    var selectedText = textArea.val().substring(start, end);
    var replacement = openTag + selectedText + closeTag;
    textArea.val(textArea.val().substring(0, start) + replacement + textArea.val().substring(end, len));
}

$('#bold').click(function() {
    wrapText("widget", "", "");
});
$('#italic').click(function() {
    wrapText("widget", "", "");
});
$('#underline').click(function() {
    wrapText("widget", "", "");
});
$('#code').click(function() {
    wrapText("widget", "
", "
");
});

Comment: see http://codepen.io/anon/pen/yvcBj
Comment: http://codepen.io/anon/pen/rutDC Are you using
Comment: If I have wrapped the text in code tags and the click on preview not out putting it in code.
Answer: Change your ID of preview button, like this:
<button id="preview-btn">Preview</button>

And in your JS:
$('#preview-btn').on('click', function () {
    $('#preview').html($('#widget').val());
});

CodePen Demo
Comment: Does not allow me to wrap html and php code in pre/code tags
Comment: @acoderslife You should escape `<` and `>` with `<` and `>`. [See this question](http://stackoverflow.com/questions/11386586/how-to-show-div-tag-literally-in-code-pre-tag).
Comment: I tried that produces blank places the pre code tags at top of div does not wrap it when have other code even when use   > http://codepen.io/riwakawebsitedesigns/pen/lfpKF
Comment: @acoderslife Bypass `&` with `&`. See the [Pen](http://codepen.io/anon/pen/rbClB).
Comment: Still does not code tag button does not wrap div tags still even with that very strange show this  on top does not wrap it when div tags tried every thing I can think of.


iPhone app link : AppStore + Website or only Website

Question: I'm currently redesigning my personal web site and I want to link to my different iOS apps. I have currently two links for each of my apps : Website and AppStore.
But is the AppStore link is really necessary? We are making web sites for iOS apps to describe it in a better fashion then we can do on the AppStore itself. So why link to the AppStore.
I understand there will be people wanting to go to the AppStore directly, they will have 2 links to click. Is worth it?
Answer: What about only app store? The App store page has a description, reviews, and the ability to download the app. Not to mention I have found this to be common practice.
If you really think the website for these is amazing and describes it much better, than go for it. But I think you will find users appreciate just getting to business and going to the apps store page.
Comment: Note that Apple, themselves, encourage you to have a web page for your app. That, of course, is not a UX requirement, but rather an Apple requirement.
Comment: +1) My thoughts exactly. Why bother to "brag even more" if the user is ready to go for it...
Comment: I get the point and I may do that (I'll look at the traffic of my current web site). The main problem I see here is that I get a lot of support request from my site (even with a built-in support module in my app).
Comment: Just accepted your answer, I've decided to don't make an app web site. On my AppStore page I will point to my personal web page and I special support page I'll make.
Answer: You might also consider to create a clearer seperation between the two choices. On your current page, they look almost the same and the user must think twice before deciding what to do.  Create a bigger main icont hat takes you to the web-site and a smaller and clearer "take me directly to appstore" ikon that people can use. If the user wants to try it out, they will look for the shortcut immedeatly.
Remember to have an clear appstore button an the web page as well. Users that clicks the first and best should also find the appstore button right away on the web page.
Answer: Use a link to your site for it, and within that site have a link to the AppStore.
I think the way that you have done it on your site(not your link here, but on here is great. You have the description, which could easily overlap with what is offer on the AppStore link, but what is key here is your movie that shows the actual app in action, along with the little dot that simulates your finger moving through the application(very clever).
If they like what they see and want more, they click the AppStore icon. Without having this movie I would agree with Jon and say just go for the AppStore  link, but the video you provided is very helpful.
Answer: giving this answer without having found your personal website. (The name of your startup appears besides your own name everywhere online)
In general, you own an amount of mobile applications and now what?
First of all, I understand the need to present them somewhere, at your own online space to clarify the ownership and that this should be added to one more thing you have done in your life. If this was the only reason for displaying them, then just putting them all together in a list or any other similar format then why bother making it more complex?
However, if you have a specific audience in your mind and for what reasons this audience is visiting your personal website then you might consider alternative designs.
For example, if you own an awesome mobile application that would be interesting to your audience why not put it in a large section that covers the entire available width and have the rest underneath to occupy a much smaller screen real estate each. Other ideas could be valid always depending on the audience. So more information on whom you optimize for, would be necessary to elaborate.
Now if you don't have time for doing major changes and you are only concerned with the choice of the link then I would go with the App Store link because the user probably already knows what to expect, where to find the information that he is looking for etc. Unless the website for this mobile application tends to load faster and provides the most important information above the fold.


Can I cover junction boxes in the attic with insulation?

Question: This may be a duplicate of What are the codes for electrical wiring in attics?
I have an attic which is accessible via a ladder through an access panel in the garage and in a bedroom.  The trusses and joists are all open and there is blown in insulation up to the height of the joists.  In the future I need to have more insulation installed.  Is it safe (up to code) to cover the junction boxes with more insulation or is this considered concealing them?  Would I have to raise all of the junction boxes above the insulation for each light fixture, fan, etc.?
Comment: the junction boxes are available from the ceiling side though, correct? if so they are not concealed...
Comment: Not all of them.  Some of them lead to recessed lighting in bathroom soffits or are acting as splices.
Answer: Your best bet in this case is to contact the local inspector,  since this situation may be open to interpretation. The most fitting code states:

National Electrical Code 2008
ARTICLE 314 Outlet, Device, Pull, and Junction Boxes; Conduit Bodies; Fittings; and Handhole Enclosures
314.29 Boxes, Conduit Bodies, and Handhole Enclosures to Be Accessible. Boxes, conduit bodies, and handhole enclosures shall be
  installed so that the wiring contained in them can be rendered
  accessible without removing any part of the building or, in
  underground circuits, without excavating sidewalks, paving, earth, or
  other substance that is to be used to establish the finished grade.
Exception: Listed boxes and handhole enclosures shall be permitted where covered by gravel, light aggregate, or noncohesive
  granulated soil if their location is effectively identified and
  accessible for excavation.
Article 100 Definitions
Accessible (as applied to wiring methods). Capable of being removed or exposed without damaging the building structure or finish
  or not permanently closed in by the structure or finish of the
  building.

It may or may not be acceptable, depending on if the inspector considers insulation "part of the building".
If you do end up covering the boxes, it might be a nice idea to mark/flag them in some way. This way you; or any other future owner, will be able to locate them later if need be.
Comment: Even the professionals don't always give much thought; the original blown-in insulation in my attic covers every last inch of wiring and junction box. Each time I go up there, I bring a broom and sweep around a large area to simply find a cable, box, or wall penetration.
Comment: This has to be a common situation.  Do people just blindly insulate their attics without any thought of ever having to access the wiring up there again?
Comment: If it's done by the homeowner themselves, they would likely never give it a thought.  If it's done by professional insulation experts, they usually know how to handle this type of stuff.
Answer: The junction boxes that contain splices and are not accessible from the ceiling below should be exposed - not covered by insulation.  If enough slack is present in the cables between the boxes, you may be able to raise them up a bit and mount them on trusses or other exposed framing members without having to run new wire.
Comment: Is there a NEC code to reference on this?
Comment: Can you site a source for this information, or is this just your opinion?
Comment: All boxes shall be accessible. NEC 314.29 -The exact interpretation of this is up to the local inspector.  Some states / municipalities consider insulation covered boxes to be "accessible", and some do not.  As a practical matter, in my own opinion, it's a bad idea to hide junction boxes under insulation where finding them will be difficult when troubleshooting future problems or doing future modifications.
Comment: Would there be any benefit to running a piece of brightly-colored string or other such material between a each box or other item of interest and a sign which identifies it?
Answer: I would suggest that you install access panels in the ceiling for these concealed boxes, and then cover them with insulation.  Not covering them with insulation could lead to moisture problems because the cold attic air will hit warmer air around the un-insulated box which is warmer because the other side of it (ceiling) is a conditioned space.
Also, in the event you need to access the box, it is easier to access it from the conditioned space and not have to crawl around your attic.
Answer: If it wasn't done during original construction and with any additional penetrations of the attic envelope, fire caulk sealing of any gaps around the j-boxes or bare wire/plumbing stacks will greatly assist your insulation staying dry.  Be sure no additional vapor barrier is added over your existing insulation.
Answer: I am in the same situation adding some recess lighting. I chose to hold off the installation of the junction box and get some wood to raise it.  Reasoning, I was not sure about the code, it's easy to do and will be better for me or anyone who may want to add on later to the box.  Some wood, a nail gun or some plates, and some screws and you're ready to go.
Comment: I used those Tyco splices originally, but I replaced them with metal junction boxes and hung them on the underside of the roof rafters.  The insulation job was a whopping pain in a cape cod.
Answer: Caned / recessed lights have built in jboxes and are rated to be buried in insulation.   So no raising them above insulation or opening ceiling to ad exposed box covers.  Come on people.  Really.  Yes cover them
Comment: Hello, and welcome to Stack Exchange. Not all cans are rated insulation contact.


Converting War to .exe / Testing Restful Webservice

Question: I am a newbie to this Rest Web Services.
This question is already posted. But I cannot understand a thing. I have two questions here.

When we created a WebApp with soap web services, we generated a test client to test it. Is there a way we can test Rest Webservices? (Using Eclipse IDE, Generated test client in the following way.
File---> new---> other---> web service---> web service client.  So, now how can i test Restful web services? (I found one Rest Client tool, but I dont understand how to use that (Newbie :)  ).
I need to find a way to give our war file to client as .exe file. I  didn't understand what exactly that meant, but here is the requirement.
"We need to give our client this in the form of .exe file, like whenever we download some .exe file, it will ask us to Run, Accept license, Browse destination, and such things. And also he shouldn't be able to see our code."
This is what exactly our senior management told me and Is there a way we can make it possible??
(I showed him the InstallJammer and then he said the client shouldn't see the code.)
Answer: For Question 2:
See some packaging tool like NSIS or IzPack or InnoSetup