text:
Q: Transient Fault Handling with SQL Azure using Entity Framework I currently use SQL Azure and Entity SQL in my application.
e.g.
Entities model = new Entities();
db_Item item = model.db_Item.First();

Now I want to use the Transient Fault Handling out of the Enterprise Library but there are no examples or solutions that I can find that would allow me to do something like override the Entities class, so I don't have to update my code in hundreds of places.
Could someone please provide more information on how this could be done?

A: Going through what I have so far.

*

*The Entity Framework does not provide access to the connection open and section where the SQL is sent to the server, hence it is currently impossibile to provide retry logic around this area.

*The EF team are aware of this shortfall and are planning on actually integrating retry logic into EF for possibily version 6.

*As per Case #3 of [1] you can send a SQL command to the database on the OnContextCreated. This however means for EVERY single DB call you make to the DB, you will have to make 2. I wouldn't recommend this in hardly any situation unless you don't care about performance.

*The only viable option so far is implementing retry logic in the form of the Enterprise Library Transient Fault Handling Application Block [2] around every call you make to the database. In existing applications this is extremely tedious.

*When I get time I am looking further into the source code of EF to see if anything further can be done, while we wait for EF 6. I would keep an eye on [3]

*Some hope, it is currently under review by the EF team. [4]
Update: 2013-11-14
Just thought I would update this post to let everyone know that EF6 has been released and supports connection resiliency out of the box. https://www.nuget.org/packages/EntityFramework/
No need for workarounds any more.
Update: 2013-03-23
EF 6 Alpha 3 released with Connection Resiliency - http://entityframework.codeplex.com/wikipage?title=Connection%20Resiliency%20Spec
Update: 2012-11-04
The EF team have officially announced it is planned for EF 6. [4]
[1] http://blogs.msdn.com/b/appfabriccat/archive/2010/12/11/sql-azure-and-entity-framework-connection-fault-handling.aspx
[2] http://msdn.microsoft.com/en-us/library/hh680934(v=pandp.50).aspx
[3] http://entityframework.codeplex.com/wikipage?title=Roadmap
[4] http://data.uservoice.com/forums/72025-entity-framework-feature-suggestions/suggestions/2426525-automatically-perform-retry-logic-for-sql-azure

A: Thankfully it is pretty simple with the new Transient Fault Handling Application block.  Everything you need can be found here:
http://geekswithblogs.net/ScottKlein/archive/2012/01/27/understanding-sql-azure-throttling-and-implementing-retry-logic.aspx
and in video form:
http://channel9.msdn.com/Shows/Cloud+Cover/Episode-68-Throttling-in-SQL-Azure-with-Scott-Klein
An example from the above links:
using (NorthwindEntities dc = new NorthwindEntities())
{
    RetryPolicy myPolicy = new RetryPolicy<SqlAzureTransientErrorDetectionStrategy>(3);
    Employee e1 = myPolicy.ExecuteAction<Employee>(() =>
        (from x in dc.Employees
            where x.LastName == "King"
            select x).First());
}

As you can see, all you need to do is create a RetryPolicy and call its ExecuteAction function with a query wrapped in an action.
**EDIT
Example context overrides:
private RetryPolicy m_RetryPolicy = new RetryPolicy<SqlAzureTransientErrorDetectionStrategy>(....

public override int SaveChanges()
{
    return m_RetryPolicy.ExecuteAction<int>(() =>
    {
        return base.SaveChanges();
    });
}

// Pass anonymous query func in here
public T AutoRetryQuery<T>(Func<T> query)
{
    return m_RetryPolicy.ExecuteAction<T>(query);
}

A: Since this seems one of the most popular questions on SO about Azure transient handling, I'll add this answer here.
Entity Framework does indeed have resiliency code built in (per Adam's answer)
BUT:
1) You must add code to activate it, manually
public class MyConfiguration : DbConfiguration
{
    public MyConfiguration()
    {
        this.SetExecutionStrategy(
            "System.Data.SqlClient",
            () => new SqlAzureExecutionStrategy());

        this.SetTransactionHandler(
            SqlProviderServices.ProviderInvariantName,
            () => new CommitFailureHandler());
    }
...

The first method call activates retries, the second call sets a handler to avoid duplicate updates when retries happen.
Note: This class will be found and instantiated automatically, as discussed here: https://msdn.microsoft.com/en-us/library/jj680699(v=vs.113).aspx. Just make sure the class is in the same assembly as your DbContext class and has a public constructor with no parameters.
2) The built-in SqlAzureExecutionStrategy is not good enough. It doesn't cover all the transient errors. This is not surprising when you consider that the SQL Server team is working independently of Entity Framework, so they are unlikely to ever be completely in synch on what transient errors are possible. It's also difficult to figure that out yourself.
The solution we used, backed by a suggestion from another software company, is to create our own Execution Strategy, which retries every SqlException and TimeoutException, except for a few that we whitelist as not worth retrying (such as permission denied).
public class WhiteListSqlAzureExecutionStrategy : DbExecutionStrategy
{
    public WhiteListSqlAzureExecutionStrategy()
    {
    }

    protected override bool ShouldRetryOn(Exception exception)
    {
        var sqlException = exception as SqlException;

        // If this is an SqlException then we want to always retry
        // Unless the all the exception types are in the white list.
        // With those errors there is no point in retrying.
        if (sqlException != null)
        {
            var retry = false;
            foreach (SqlError err in sqlException.Errors)
            {
                // Exception white list.
                switch (err.Number)
                {
                    // Primary Key violation
                    // https://msdn.microsoft.com/en-us/library/ms151757(v=sql.100).aspx
                    case 2627:

                    // Constraint violation
                    case 547:

                    // Invalid column name, We have seen this happen when the Snapshot helper runs for a column 'CreatedOn'
                    // This is not one of our columns and it appears to be using our execution strategy.
                    // An invalid column is also something that probably doesn't get resolved by retries.
                    case 207:
                        break;

                    // The server principal "username" is not able to access the database "dbname" under the current security context
                    // May occur when using restricted user - Entity Framework wants to access master for something
                    // probably not transient
                    case 916:
                        break;

                    // XXX permission denied on object. (XXX = select, etc)
                    // Should not occur if db access is correct, but occurred when using restricted user - EF accessing __MigrationHistory
                    case 229:
                        break;

                    // Invalid object name 'xxx'.
                    // Occurs at startup because Entity Framework looks for EdmMetadata, an old table
                    // (Perhaps only if it can't access __MigrationHistory?)
                    case 208:
                        break;

                    default:
                        retry = true;
                        break;
                }
            }
            return retry;
        }

        if (exception is TimeoutException)
        {
            return true;
        }

        return false;
    }
}

3) There used to be a kind of bug where EF would run the retries N^2 times instead of N, which made for much longer delays than you'd expect. (It's supposed to take up to about 26 seconds, but the bug made it take minutes.) However, this isn't so bad because in reality SQL Azure regularly has unavailability for more than a minute :(
https://entityframework.codeplex.com/workitem/2849
4) If you haven't been doing so already, you really need to dispose of your DbContext after it's used. It seems this is the point that the CommitFailureHandler runs it's purging to tidy up the __TransactionHistory table; if you don't dispose, this table will grow forever (although see next point).
5) You should probably call ClearTransactionHistory somewhere in your startup or in a background thread, to clear any leftovers in __TransactionHistory.

A: I was also having same issue, In my case I am using LINQ-To-SQL(I believe same applies to Entity framework also)and this is what I am planning to do.
Abstract the Linq-to-sql queries using repository pattern and wrap the Linq-to-sql code which generates database request with the retry mechanism.
For that I would suggest to create a method called ExecuteWithRetry(Action action) and then you invoke this method like this ExecuteWithRetry(()=> { db_Item item = model.db_Item.First(); });
The method could be implemented this way
private void  ExecuteWithRetry(Action action)
{
  var retryStrategy = new Incremental(5, TimeSpan.FromSeconds(1),
  TimeSpan.FromSeconds(2));

  // Define your retry policy using the retry strategy and the Windows Azure storage
  // transient fault detection strategy.
  var retryPolicy =
  new RetryPolicy<StorageTransientErrorDetectionStrategy>(retryStrategy);

  // Receive notifications about retries.
  retryPolicy.Retrying += (sender, args) =>
  {
    // Log details of the retry.
    var msg = String.Format("Retry - Count:{0}, Delay:{1}, Exception:{2}",
        args.CurrentRetryCount, args.Delay, args.LastException);
    Trace.WriteLine(msg, "Information");
  };

  try
  {
    this.retryPolicy.ExecuteAction(action);
  }
  catch (Exception ex)
  {
     Trace.TraceError(ex.TraceInformation());
    throw;
  }
 }

I am also going to try this approach, hoping that it will work

A: Actually you want to use extension methods provided by MS.  Ref: http://msdn.microsoft.com/en-us/library/hh680906(v=pandp.50).aspx
"In addition, the SqlCommandExtensions and SqlConnectionExtensions classes provide a set of extension methods that enable .NET developers to open SQL Azure database connections and invoke the SQL commands. These extension methods are useful in the event that you are unable to adapt your code to take advantage of the ReliableSqlConnection class. For example, you may be using the Enterprise Library Data Access Application Block or Entity Framework that use SqlConnection instances internally. In this case, the extension methods help you add the retry capabilities offered by the Transient Fault Handling Application Block to the existing code without major re-work.
"


text:
Q: How to get list of facebook contacts from Rails I'm writing a Ruby on Rails (3.1) app where a user can send emails from a form in the app as part of the workflow. At the moment the email field is just an html input where the user can type/paste in an email address. What I would like to do is, with the users permission, give them the option of a selector of their facebook contacts.

A: Facebook API reference
Rails specific: follow this guide.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Express stops queries after 3-4 times I'm creating a React game. In this game, the user can buy card packs. He has an amount of money (called essences) and can chose any type of packs he wants to purchase (mini packs cost 500, normal are 1500 and mega packs cost 3000).

For every type of pack, I have an onClick button that triggers a function (BuyPack) with a parameter (the cost of the selected pack).

⏫Here is the 500 essences pack.
The function then makes an axios call to my express server :
const BuyPack = (arg) => {

    let nb = (document.getElementById('essences').innerText) // that obviously sucks lol
    let nbInt = parseInt(nb) // converts innerText to int
    const newSolde = (nbInt - arg) // The calculated amount after the purchase

    // Update visually the amount of essences
    localStorage.setItem('essences', newSolde)
    document.getElementById('essences').innerHTML = newSolde; // Let's set the new amount

    let datas = {id: localStorage.getItem('id'), typeOfPack: arg}; // id = the user id / arg = 500, 1500 or 3000, it's basically the pack price.

    console.log('datas', datas) // Output : datas {id: '196', typeOfPack: 500}
    Axios.post('http://localhost:3001/buyPack', {data: datas}) // The axios call that doesn't work as expected

}

The axios call is :
app.post('/buyPack', function (req, res) {
  const userId = (req.body.data.id)
  const typeOfPack = (req.body.data.typeOfPack)
  console.log(typeOfPack)

  // I make a first request to get the "pre-buy" amount of money
  query("select essences FROM users WHERE id = ?", [userId], (err, rows) => {
    const actualEssences = (rows[0].essences);  // The amount we just got
    // Second query where we update and decrease the amount of money for the user
    query("update users set essences = " + (actualEssences - typeOfPack) + " where id = " + userId)
  })
})

For some reason I don't get, after some purchases, my express server just doesn't respond anymore. (the 3000 below are the console.log(typeOfPack).

Client side, I have no problem, the money is decreasing and I get the console message that I clicked on the pack.

I've tryied many things, but I really can't see the the issue comes from.
Thanks a lot in advance.


text:
Q: Parameterised query breaks when doing LIKE condition. Why? So, I have a  method that performs a parametrised LIKE query. The method takes in the search parameter/value in and then it is added to the command ready for the query.
It is not working. It should work, and when I code the value to search for directly into the SQL string, sans parametrisation, it does work! When I have it as a parameter is does not! Any ideas.
Here is some (fake, I have changed the names) example code.
myDataReader = SQLExecute("SELECT * FROM TableOfAwesomeness WHERE BestTVShow LIKE 'Arrested Development%'")

Would work. However
Function MethodOfReturningHorror(ByVal TVShow as String) as SqlDataReader
{
dim command as new SQLCommand
command.connection = sqlconnection
command.CommandText = "SELECT * FROM TableOfAwesomeness WHERE BestTVShow LIKE '@tvShow%'"
command.Parameters.Add("tvShow",TVShow)

return command.ExecuteReader()
}

I have missed out code unrelated to the question for the sake of laziness/conciseness. So ignore the return bit and and stuff, all that is important is that the data reader contains nothing, while It does in the first example. I am sure it's to do with the parametrisation of the LIKE clause .
Thanks!

A: Try this:
command.CommandText = "SELECT * FROM TableOfAwesomeness WHERE BestTVShow LIKE @tvShow + '%'"

A: Try appending the '%' to the end of the parameter string rather than embedding it in the sql.

A: Try this, to ensure that the value that you're checking against is a varchar value, and not say an integer type:
command.CommandText = "SELECT * FROM TableOfAwesomeness WHERE BestTVShow LIKE convert(varchar(100), @tvShow) + '%'"

I've had some problems when T-SQL does native type conversion and string concatenation.
(Obviously change "varchar(100)" to be whatever works in your instance: your data types, your expected length)

A: @tvShow is a variable and you're using it inside of a string. It would be the equivalent of this in C#:
var tvShow = "5th Wheel";
var netwokAndShow = "Fox tvShow";
Console.WriteLine(networkAndShow); // Prints 'Fox tvShow', not 'Fox 5th Wheel'

You want it to look like:
LIKE @tvShow + '%'


text:
Q: Android ListView: Getting text of item without using click event Is there a way to get the value of TextView which is an item of a ListView without using any click event ?
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal">

    <TextView
        android:id="@+id/friendNoTv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:visibility="gone" />

    <ImageView
        android:id="@+id/friendImage"
        android:layout_width="80dp"
        android:layout_height="80dp"
        android:layout_alignParentLeft="true"
        android:layout_centerVertical="true" />

    <TextView
        android:id="@+id/friendFullName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_gravity="center_vertical"
        android:layout_marginLeft="10dp"
        android:layout_toRightOf="@+id/friendImage"
        android:textColor="#0D47A1" />

    <ImageButton
        android:id="@+id/addFriendButton"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_alignParentRight="true"
        android:layout_marginEnd="5dp"
        android:layout_marginRight="5dp"
        android:layout_marginTop="5dp"
        android:background="@drawable/add_friend" />

    <TextView
        android:id="@+id/addFriendTv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/addFriendButton"
        android:layout_marginTop="5dp"
        android:text="ADD FRIEND"
        android:textColor="#0D47A1"
        android:textSize="10sp" />

</RelativeLayout>

My custom row layout defined as above and i need to get the value of the friendNoTv TextViewwithout any click event. I tried it as
@Override
public View getView(int index, final View convertView, ViewGroup parent) {

    // check if we need to generate a new View from scratch or recycle one
    View InflatedView = convertView;
    if (InflatedView == null) {
        InflatedView = Inflater.inflate(R.layout.find_friends_result_row, parent, false);
    }

    // setup variables

    final TextView friendNo = (TextView) InflatedView.findViewById(R.id.friendNoTv);
    ImageView friendImage = (ImageView) InflatedView.findViewById(R.id.friendImage);
    TextView friendFullName = (TextView) InflatedView.findViewById(R.id.friendFullName);
    ImageButton addFriendButton = (ImageButton) InflatedView.findViewById(R.id.addFriendButton);

    //Exception here, friendNo.getText().toString() comes up NULL
    final int friendId = Integer.parseInt(friendNo.getText().toString());

    if(isFriend(friendId)){
        addFriendButton.setVisibility(View.GONE);
    }else{
        addFriendButton.setVisibility(View.VISIBLE);
    }

    //TODO

    Friend friend = friendList.get(index);

    DataFormatter dataFormatter = new DataFormatter();

    friendNo.setText(Integer.toString(friend.getBorNo()));
    dataFormatter.decodeimage(friend.getUserImage(),friendImage);
    friendFullName.setText(friend.getFullName());

    return InflatedView;

}

But value comes up Null which causes an Exception. How do i fix this ? Any help would be appreiated.

A: You are getting null because you just have inflated the view and you are trying to get the text before setting it. In your XML you haven't set any text value that's why you are getting nothing there.
Just replace that line which is giving null with below one,

    final int friendId = Integer.parseInt(friendList.get(index).getFriendId.toString());

A: Your code here:
//Exception here, friendNo.getText().toString() comes up NULL
 final int friendId = Integer.parseInt(friendNo.getText().toString());

will definitely be null as friendNo is not set yet. you should paste these line at last just before return statement with the conditional statement.


text:
Q: Distribute elements evenly using CSS A method to distribute elements evenly in a container using CSS appeared on Smashing Magazine today.
I recently had to use Javascript to achieve the same effect for elements of variable width, but the method presented on SM made me wonder if it was possible to do this without Javascript.
There's this question, where gargantaun says:

IMHO, and you probably don't want to hear this, but the design is probably flawed. It's common knowledge that distributing items evenly across a layout with CSS is a pain, so designers should avoid it.

But I can't tell the designer to change his design, and I don't agree that the shortcomings of CSS should limit designers.
Anyway, here's what I have in HTML (translated and simplified):

Home

News

Theme

Activities

Contact

in CSS (irrelevant properties removed and simplified):
#menu li { float: left; margin-right: 20px; }
#menu a  { display: block; padding: 0 1em; }

and in Javascript:
function justifyMenu() {
    var menuItems  = $$("#menu li");
    var menuWidth  = $("menu").getWidth();
    var totalWidth = 0;

    menuItems.each(function(e) {
        totalWidth += e.getWidth();
    });

    var margin = (menuWidth - 4 - totalWidth) / (menuItems.length - 1);
    margin = parseInt(margin);

    menuItems.each(function(e) {
        e.setStyle({ marginRight: margin + 'px' });
    });

    menuItems[menuItems.length - 1].setStyle({ marginRight: '0' });
}

And here's a scaled-down screenshot (see how the menu aligns with the header image):

Any idea how I can achieve this without Javascript?

A: This is what display:table-cell is supposed to achieve - however, the IE's just don't do it, and FF<3 has problems with it too, I believe.
These styles work in FF3, Chrome, Safari, and (I think) Opera 9:
#menu ul {display:table;padding:0;}
#menu li {display:table-cell;text-align:center;}

But you'll need a fair few hacks to get them working in the usual, commercial set of browsers.

A: Even though Colin Brogan's answer provides solid foundation to approach a "almost there" resolution to the problem, it still depends on text length. If text is too long, the "cell" will be wider and thus have more space on the left. I tried to address the problem based on the code presented in his answer, but I concluded that the problem has not a real possible solution with tables or fake-tables (display:table-cell).
So we'll have to wait for CSS3 flexible box model to be more widely supported (you can check updated support here). In the meantime, you can use the Flexie polyfill to patch browsers that don't support it.
If you want to check how it'll look like on WebKit now (without needing polyfill), you can try the following CSS:
#menu ul {
  display: -webkit-box;
  -webkit-box-orient: horizontal;
  -webkit-box-pack: justify;
  width: 940px;
  list-style: none;
  padding: 0;
  border: 1px solid gray;
}
#menu li {
  border: 1px solid silver;
}

Notice it only uses WebKit prefixes. You should add prefixes for the other browsers aswell if you decide to take it to production website.
This approach does accept an unknown amount of items and text-widths, without any knowledge of their actual widths, and distribute them evenly across their container (in this case, #menu ul).
If you decide to be conservative, the approach suggested by Colin Brogan is the most acceptable given that you keep your texts on the same approximately length. If not, wider spaces will start to show.

A: Of course this is exactly what the table element is for. It's sad and hilarious at the same time to see people twist themselves into a gordian knot with CSS, most of them not even knowing why they're avoiding tables.
Whatever reason you might have dreamed up to reject tables, it can't possibly be worse than depending on Javascript to layout your page.
Yes, I know this is not the answer you were looking for, but golly, it's so obvious.

A: There have been casual claims that tables are the obvious solution, however, there hasn't been any real discussion of how to implement it. I'll show you that displaying divs as a table is the right way to do this, but it is not as easy as centering all of the cells and setting an automatic width. The problem with this is that you have no control of the outer margins of the further-most left and right cell-contents. They both are inset from its containing box an arbitrary amount you cannot control. Here's a work around:
First, a slight modification of Guder's html:

Home

News

Theme

Activities

Contact

Now the css:
#menu {display:table; width:// some width in px //}
#menu ul {display:table-row; width: 100%}
#menu li.left {display: table-cell; text-align: left; width: 20px; white-space:nowrap;}
#menu li {display: table-cell; text-align: right; width: auto;}

Now, we have full control of the outer-most sides of the menu, which align with the far-left and far-right sides of the containing box, and the distance between each element is consistent. You'll notice that I used a trick to get the furthest left cell to be the exact-width of it's content. I set the width property to a small size obviously below what its contents would normally be. I then set the white-space to no-wrap, which stretches the cell the least amount to fit the text of the cell. You can see here an image which shows the effect of this (using different html elements):

The beauty of this code is that it can accept however many cells and text-widths, without any knowledge of their actual widths, and distribute them evenly across the page. All the while, left and right elements reaching their perimeters, and ofcourse we have all our html in divs, no browser or internet geek is mislead to believe we're presenting tabular data. No known compromises here!

A: Yes, you can do it, as long as the widths of the elements to be distributed are known in advance. But it's a bit messy.
The trick is, you want a spacing between each element of '(Wp-sum(Wc))/(Nc-1)', that is width of the parent element minus the total width of all the child elements, divided equally between the number of gaps between the elements.
Because CSS doesn't have the ability to do expressions, we have to hack it a bit. First we add a margin to the parent element of the size 'sum(Wc)', the total width of all child elements. So now the parent has width '(Wp-sum(Wc))', and we can use a padding value in % relative to that width.
So for example, for four images of sizes 10px, 20px, 40px and 80px respectively, our 'sum(Wc)' is 150px. Set that as the parent margin, then the children can have one-third of that width as padding between them.

The funny tag indentation is to avoid there being any whitespace between images. 'nowrap' is necessary because with the parent width set narrower than the page width, it wouldn't otherwise be possible to fit all the elements on the row. Finally, in IE you may need to add a wrapper div around the lot with 'width: 100%; overflow: hidden' to prevent unwanted scrollbars if you're spanning the whole page. And certainly you'll want to be in Standards Mode.
This can work with textual elements too, if you make them inline blocks so you can add padding, and you size them explicitly in ems. It won't work if the sizes of the child elements are not known in advance (eg. they contain dynamic content), as you won't know the 'sum(Wc)' value to use.
To be honest I would probably just use a table. The table layout algorithm copes very smoothly with calculating how to distribute spare table width. (Use 'table-layout: fixed' for best results with known-width cells, or 'auto' to respond to dynamic contents.) This way you also don't have to worry about pixel rounding errors.

A: If you were using text-based sizes (em, ex) it'd be a lot easier.  You can then deal in letters rather than pixels.
Example:  The whole thing is 30 capital letter Ms wide. You can then use the width of each nav element (based on its textual content) and do your math statically from there.

A: Here is the code in jQuery format for anyone who finds it useful
function justifyClients() {
                        var menuItems  = $("#clients-wrapper ul li").get();
                        var menuWidth  = $("#clients-wrapper ul").width();
                        var totalWidth = 0;

                        $("#clients-wrapper ul li").each(function(i,e)
                                        {
                                            totalWidth += $(e).width();
                                        });

                        var margin = (menuWidth - 4 - totalWidth) / ($("#clients-wrapper ul li").length - 1);
                        margin = parseInt(margin);

                        $("#clients-wrapper ul li").each(function(i,e) {

                            if(i < $("#clients-wrapper ul li").length - 1)
                            {
                                alert(i + " " + $("#clients-wrapper ul li").length);
                                $(e).css('margin-right',  margin);
                            }
                        });
                    }

                    $(document).ready(function() {
                      justifyClients();
                    });

A: The top answer didn't work for me, and GarciaWebDev's answer won't do it for me yet because I need to support a few other browsers, including IE8.
This method worked for me. The idea is to make a containing element text-align: justify and to make the elements to distribute display: inline-block.
HTML:

Home

News

Theme

Activities

Contact

CSS:
#menu {
    text-align: justify;
}

ul {
    margin: 0;
    padding: 0;
}

#menu li {
    display: inline-block;
}

.filler {
    width: 100%;
    height: 0;
}

A: AFAIK there is no way to achieve this just with CSS.
Anybody correct me if this is wrong, pls.

A: If you use the Yahoo! User Interface Library (YUI) grids.css, it might work.

A: Demo - http://codepen.io/vsync/pen/tFwxu
all you need if to make the list itself text-align:justify and then add some pseudo item top the end of it and make it fill all the width, to trick the list into justifying all it's items across it's total width.

A: Trevor Dixon's improved variant (without extra
)
HTML

Home

News

Theme

Activities

Contact

CSS
ul {
    margin: 0;
    padding: 0;
}
ul li {
    display: inline-block;
    text-align: justify;
}
ul:after{
    display: inline-block;
    content: '';
    width: 100%;
    height: 0;
}

A: Thanks to the CSS3 Flexbox module, this is possible with two lines of CSS.
Check the Browser compatibility table for Flexbox
HTML

Home

News

Theme

Activities

Contact

CSS
ul {
  display: flex;
}
li {
  flex: 1; /* Short hand for flex-grow: 1 and flex-shrink: 1 */
}

Output:

ul, li {
  margin: 0;
  padding: 0;
}
ul {
  display: flex;
  list-style: none;
}
li {
  flex: 1;
  text-align: center;
}

Home

News

Theme

Activities

Contact


text:
Q: How to replace a specific character in a substring using regex? My objective
This question is about Visual Studio Code search box.
I want to replace all the "spaces" by the character "_" inside the my substring with spaces of mystring
for example:
-> From
{
    "Show_details": mystring("my substring with spaces"),
    "Type_of_event": mystring("my substring with spaces2"),
}

-> To
{
    "Show_details": mystring("my_substring_with_spaces"),
    "Type_of_event": mystring("my_substring_with_spaces2"),
}

What I tried
I only managed to get the `my_substring_with_spaces`. But I do not understand how to proceed further.
Search: mystring\("([a-z]*?( )[a-z]*?)"\)

A: You can use
(?<=mystring\("[^"]*)\s+(?=[^"]*"\))

Details

*

*(?<=mystring\("[^"]*) - immediately to the left, there must be mystring(" and then 0 or more chars other than "

*\s+ - one or more whitespaces (remove + if two consecutive spaces must be converted to two consecutive _s)

*(?=[^"]*"\)) - immediately to the right, there must be 0 or more chars other than " and then ").

See the screenshot:


text:
Q: Using Dlookup in the Default Value field of a form control I am trying to populate a form controls default value based on the value of a combobox on that form. The combobox is called Title, and I want the control HIPAA to populate based on the value of HIPAA in my table tblTrainingEventTiles where the Title selected on the form matches the title in the table.
I was putting the following code into the default value of the control on the form:
=IIf(IsNull([Title]),0,DLookUp("HIPAA","tblTrainingEventTitles","[tblTrainingEventTitles].[Title]=[Title]"))

Access seems to ignore it however. It doesn't do anything and there are no error messages. I'm not sure if my problem is with my dlookup or with the fact that I'm trying to use this in the default value field. (or both?) Does anyone have any ideas?

A: Try this:
=Nz(DLookUp("HIPAA","tblTrainingEventTitles","[tblTrainingEventTitles].[Title]=[Title]"),0)

A: If your combobox's bound column is text you should use ' around it's content. And you should concatenate value of combobox to filter part of dlookup.
=IIf(nz([Title],"")="",0,DLookUp("HIPAA","tblTrainingEventTitles","[tblTrainingEventTitles].[Title]='" & [Title] & '"))


text:
Q: Remove double quotes from ruby loop in rails I am working on a ruby on rails web app and in my view I have the following code:

 <textarea id="glmol02_src" style="display: none;">
<% @name.coords.each_with_index do |coord, i| %>
  <%= coord.atom %>
<% end %>
END
</textarea>

When I look at my web page, there are double quotes around the whole for loop, how can I remove those double quotes?

<textarea>
" entry1
  entry2
  ...
  entry100 "
</textarea>

Thanks so much!

A: Chrome's inspector (for example, other browsers might do this too) adds pseudo-quotes to elements if they're beginning or ending with a whitespace/tabs/etc to indicate their presence. Similar behaviour can apply to
 and
.
Have you checked the website's actual source with CTRL+U, or are you just using the inspector?


text:
Q: Azure ACS with JWT/WIF and Symmetric Keys I am using Azure ACS with my MVC4 client using passive redirection.  I've configured Azure to issue JWT, and I'm using the new WIF JWT library for validating the token.  This is all working just fine.
The problem that I am encountering is that Azure signs the JWT with the X.509 Certificate, rather than the Symmetric Key, which requires my MVC application to have the Certificate, which is annoying at the moment.
I know that the JWT support is in Beta, and that there are security issues with using a Symmetric Key (in that anyone with the Key could fake a token).
Is there some setting that I am missing?  I tried making the Certificate the "Secondary" signing key in Azure, but this had no effect.

A: ACS chooses keys to sign a JWT in the following precedence order:

*

*Relying party symmetric key

*Relying party certificate

*Service-wide certificate

What you don't see anywhere on this list is a Symmetric service key, because there are security issues with using a symmetric key between more than two entities.
What this means is that your key needs to be associated with the relying party, not the namespace, as in the following screenshot.


text:
Q: Working with abstract mathematical Operators/Objects in Sympy I am wondering if there is an easy way to implement abstract mathematical Operators in Sympy. With operators I simply mean some objects that have 3 values as an input or 3 indices, something like "Operator(a,b,c)". Please note that I am refering to a mathematical operator (over a hilbert space) and not an operator in the context of programming. Depending on these values I want to teach Sympy how to multiply two Operators of this kind and how to multiply it with a float and so on. At some point of the calculation I want to replace these Operators with some others...
So far I couldn't figure out if sympy provides such an abstract calculation. Therefore I started to write a new Python-class for these objects, but this went beyond the scope of my limited knowledge in Python very fast... Is there a more easy way to implement that then creating a new class?

A: You may also want to look at SageMath, in addition to SymPy, since Sage goes to great lengths to come with prebuilt mathematical structures. However, it's been development more with eyes towards algebraic geometry, various areas of algebra, and combinatorics. I'm not sure to what extent it implements any operator algebra.

A: Yes, you can do this. Just create a subclass of sympy.Function. You can specify the number of arguments with nargs
class Operator(Function):
    nargs = 3

If you want the function to evaluate for certain arguments, define the class function eval. It should return None for when it should remain unevaluated. For instance, to evaluate to 0 when all three arguments are 0, you might use
class Operator(Function):
    @classmethod
    def eval(cls, a, b, c):
        if a == b == c == 0:
            return Integer(0)

(note that nargs is not required if you define eval).


text:
Q: How do I setup connection to a Redshift cluster inside a VPC? I createad a Redshift cluster inside a Public subnet inside a VPC. The VPC is connected to an Internet Gateway
Configured IPs for inbound/oubound traffic in cluster security group.
Configured IPs for inbound/oubound traffic in VPC security group.
Configured IPs for inbound/oubound traffic in Network ACL.
Configured IPs for inbound/oubound traffic in Main route table.
Still when I try to connect using a client, I get connection refused. Am I missing step here ?


text:
Q: Exporting Comments from Word to Excel I am getting an error when I try to run the following code in word to extract comments. The yellow highlight is over Public Sub PrintFirstColumnOnActiveSheetToSheetName(), which then says I have a compile error: variable not defined and highlights "Activesheet" within the Activesheet.range("A1") at the bottom of the code
Option Explicit

Public Sub FindWordComments()

Dim objExcelApp As Object
Dim wb As Object
Set objExcelApp = CreateObject("Excel.Application")
Set wb = objExcelApp.Workbooks.Open("C:\Desktop\Book11")

Dim myWord              As Word.Application
Dim myDoc               As Word.Document
Dim thisComment         As Word.Comment

Dim fDialog             As Office.FileDialog
Dim varFile             As Variant

Dim destSheet           As Worksheet
Dim rowToUse            As Integer
Dim colToUse            As Long

Set fDialog = Application.FileDialog(msoFileDialogFilePicker)
Set destSheet = wb.Sheets("Book11")
colToUse = 1

With fDialog
    .AllowMultiSelect = True
    .Title = "Import Files"
    .Filters.Clear
    .Filters.Add "Word Documents", "*.docx"
    .Filters.Add "Word Macro Documents", "*.docm"
    .Filters.Add "All Files", "*.*"
End With

If fDialog.Show Then

    For Each varFile In fDialog.SelectedItems

        rowToUse = 2

    Set myWord = New Word.Application
    Set myDoc = myWord.Documents.Open(varFile)

    For Each thisComment In myDoc.Comments

        With thisComment
            destSheet.Cells(rowToUse, colToUse).Value = .Range.Text
            destSheet.Cells(rowToUse, colToUse + 1).Value = .Scope.Text
            destSheet.Columns(2).AutoFit
        End With

        rowToUse = rowToUse + 1

    Next thisComment

    destSheet.Cells(1, colToUse).Value = Left(myDoc.Name, 4)
    'Put name of interview object in cell A1

    destSheet.Cells(1, colToUse + 1).Value = ActiveDocument.Words.Count
    'Put the number of words in cell B1

    Set myDoc = Nothing
    myWord.Quit

    colToUse = colToUse + 2

Next varFile

End If

End Sub

Public Sub PrintFirstColumnOnActiveSheetToSheetName()

ActiveSheet.Name = ActiveSheet.Range("A1")

End Sub

A: Perhaps you should be using destSheet rather than Activesheet, since Activesheet isn't defined. Otherwise, you should prefix Activesheet with objExcelApp, thus:
objExcelApp.Activesheet

A: Since you're running this in Word, VBA only "knows" things that belong to the Word object model unless the code specifically indicates a different object model is the source. Word knows nothing about "Sheets" - only Excel knows what ActiveSheet is.
Even though the code you show us doesn't call the procedure PrintFirstColumnOnActiveSheetToSheetName(), where ActiveSheet is used, VBA sees it when it compiles the code. So you need to pass a reference to the Excel application to this procedure and use it. For example:
Public Sub PrintFirstColumnOnActiveSheetToSheetName(objExcel as Object)
  objExcel.ActiveSheet.Name = objExcel.ActiveSheet.Range("A1")
End Sub

To call this elsewhere in your code it would look something like the following line. Notice that the variable names for the same object do not need to be the same in different procedures - they can be, but it's not necessary. VBA "remembers" that the Excel application started previously is what's been passed to another procedure.
PrintFirstColumnOnActiveSheetToSheetName objExcelApp


text:
Q: How to write this query MYSQL I have this database:
| id | name  | email           | control_number | created    |   |   |   |   |          |
|:--:|-------|-----------------|----------------|------------|---|---|---|---|---|
| 1  | john  | john@gmail.com  | 1              | 14/09/2016 |   |   |   |   |   |
| 2  | carl  | carl@gmail.com  | 1              | 13/08/2016 |   |   |   |   |   |
| 3  | frank | frank@gmail.com | 2              | 12/08/2016 |   |   |   |   |   |

And i want to get the COUNT in the last 12 months by the control_number.
basicly is a COUNT where control_number = 1 but by month.
So if the query is done today, its september, it should start from september to October 2015 and display the count of records for each month.
Result should be:
09/2016 = 50
08/2016 = 35
07/2016 = 20
06/2016 = 50
05/2016 = 21
04/2016 = 33
03/2016 = 60
02/2016 = 36
01/2016 = 11
12/2015 = 0
11/2015 = 0
10/2015 = 0

A: Hmmm.  Getting the 0 values can be tricky.  Assuming that you have some data each month (even if not for "1"), th en you can do:
select extract(year_month from created) as yyyymm,
       sum(control_number = 1)
from t
where created >= date_sub(curdate(), interval 12 month)
group by extract(year_month from created)
order by yyyymm;

If you don't have at least one record for each month, then you'll need a left join and a table with one row per month.

A: Try this:
select CONCAT(SUBSTRING(ym, 5, 2), '/', SUBSTRING(ym, 1, 4)) Month, Count from (
  select EXTRACT(YEAR_MONTH FROM created) ym, count(*) Count
  from mytable
  where EXTRACT(YEAR_MONTH FROM created) > (EXTRACT(YEAR_MONTH FROM SUBDATE(NOW(), INTERVAL 1 YEAR))
  group by 1
  order by 1 desc) x

A: Try:
select concat(month(created),'/',year(created)) as period, count(*) as cnt
from mytable
where control_number=1 and TIMESTAMPDIFF(year, created, now())=0
group by (month(created));


text:
Q: I want to be able to define (a(x) d/dx + b(x))^n I want to be able to define an operator
$(a(x) d/dx + b(x))^n$
where $d/dx$ is the derivative operator and $a(x)$ and $b(x)$ are known functions and $n$ is a positive integer.
Related Query: How about defining
$ \prod_{i=1,...,n} (a_i(x) d/dx + b_i(x) )  $
where $a_i(x)$ and $b_i(x)$ are known functions and $n$ is a positive integer ?

A: This can be done with Nest:
abderiv[n_] =
  Function[f, Nest[(a[x] D[#, x] + b[x]) &, f, n]];

abderiv[0][f[x]]

(* ==> f[x] *)

abderiv[1][f[x]]

(* ==> b[x] + a[x] Derivative[1][f][x] *)

abderiv[2][f[x]]

(*
==> b[x] +
 a[x] (Derivative[1][b][x] + Derivative[1][a][x] Derivative[1][f][x] +
     a[x] (f^\[Prime]\[Prime])[x])
*)

Here the order n is provided as the argument to a function that is itself a function acting on an arbitrary expression f. The assumption in the question seems to be that the differentiation variable is always x, so I don't specify this variable as an additional argument.


text:
Q: quickly Remove row from datatable which not find in another datatable here i have two datatable dtPartMaster([Part Number Exported]) and dtPartBackUp([Part Number Backup],[weight])
now i want to remove the rows in dtPartBackUp which [part Number Backup] not exists in dtPartMaster([Part Number Exported])
my logic is this but it take long time to process billon record
 button1_click()
    {  int count = 0;
//line remove for clearity

    foreach (DataRow dr in dtPartBackUp.Rows)
    {
      if (!CheckPartNumber(dr["Part Number Backup"].ToString(), dtPartMaster))
       {
           dtPartBackUp.Rows[count].Delete();
       }

    count++;
    }

    dtPartBackUp.AcceptChanges();// to accept changes

    }

 private bool CheckPartNumber(string PartNumber, DataTable dt)
        {
            bool flag = false;
            DataRow dr = dt.Select("[Part Number Exported] Like '" + PartNumber + "'").FirstOrDefault();
            if (dr != null)
                flag = true;

            dr = null;
            return flag;

        }

thanks in advance
Amrit

A: Try this (not tested),
This should return you the list of rows those are both in dt1 and dt2 on the basis of id column (I am considering your id and id2 column is of type string)
var rows = (from r1 in dt1.AsEnumerable()
            join  r2 in dt2.AsEnumerable() on r1.Field<string>("id") equals r2.Field<string>("id2")
            select r1).ToList();

A: for (i = 0;i< dtPartBackUp.Rows.count;i++)
    {
      if (!CheckPartNumber(dr["Part Number Backup"].ToString(), dtPartMaster))
       {
           dtPartBackUp.Rows.removeat(i);
i--;
       }

    }

    dtPartBackUp.AcceptChanges();// to accept changes

    }

 private bool CheckPartNumber(string PartNumber, DataTable dt)
        {
            bool flag = false;
            DataRow dr = dt.Select("[Part Number Exported] Like '" + PartNumber + "'").FirstOrDefault();
            if (dr != null)
                flag = true;

            dr = null;
            return flag;

        }


text:
Q: Bootstrap Control Layout Offset Issue I have the following fiddle which is a cut down sample of a page I am working on utilising bootstrap for the styling.
NOTE: When viewing the fiddle, make sure the Result pane is wide enough to have the first 3 controls on a single row!
The issue that I have is that the 'Free Text Search' row of controls seem to be offset to the right more than I would like. I want the 'Free Text Search' label to be directly under the 'Store Number' label and the same width. Along with that I wand the corresponding input to start at the beginning of the 'Store Number' input and finish at the end of the 'Parent Category' select.
I can't quite see where I have gone wrong with the bootstrap classes.
Here is my html:
<form class="form-horizontal">

A pointless title

            Store Number

                <input id="storeNumber" class="form-control" type="text"
                 name="storeNumber" placeholder="Store Number" />

            Actioned To

                <select id="actionedTo" class="form-control"></select>

            Parent Category

                <select id="parentCategory" class="form-control"></select>

            Free Text Search

                <input id="freeTextSearch" class="form-control" type="text"
                 name="requestNumber" placeholder="Free Text Search" />

</form>

A: Your general structure is counter to your classes. You're structuring for your inputs to position inline but you're using form-horizontal and you're nesting columns.
You don't need any of that markup for this. Just use the form-group class and columns.
See working Snippet.
*The CSS I've added isn't needed to make everything work but I believe it looks better on larger viewports with it.

@media (min-width: 768px) {
  .lg-group {
    margin-top: 25px;
  }
  h3.form-title {
    margin-bottom: 40px;
  }
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet" />

 Bootstrap 3 Header

A Pointless Title

  <form class="myForm">

      Store Number

        <input id="storeNumber" class="form-control" type="text" name="storeNumber" placeholder="Store Number" />

      Actioned To

        <select id="actionedTo" class="form-control" name="actionedTo"></select>

      Parent Category

        <select id="parentCategory" class="form-control" name="parentCategory"></select>

      Free Text Search

        <input id="freeTextSearch" class="form-control" type="text" name="requestNumber" placeholder="Free Text Search" />

  </form>

Alternative Layout for Multiple Controls

@media (min-width: 768px) {
  .lg-group {
    margin-top: 25px;
  }
  h3.form-title {
    margin-bottom: 40px;
  }
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet"/>

 Bootstrap 3 Header

A Pointless Title

  <form class="myForm">

            Store Number

              <input id="storeNumber" class="form-control" type="text" name="storeNumber" placeholder="Store Number" />

            Actioned To

              <select id="actionedTo" class="form-control" name="actionedTo"></select>

            Parent Category

              <select id="parentCategory" class="form-control" name="parentCategory"></select>

            Store Number

              <input id="storeNumber" class="form-control" type="text" name="storeNumber" placeholder="Store Number" />

            Actioned To

              <select id="actionedTo" class="form-control" name="actionedTo"></select>

            Parent Category

              <select id="parentCategory" class="form-control" name="parentCategory"></select>

          Free Text Search

            <input id="freeTextSearch" class="form-control" type="text" name="requestNumber" placeholder="Free Text Search" />

  </form>


text:
Q: Failing to do Projection in JPA query Sorry for the messy SQL query.
I have this data structure
@Entity
public class Stock {

//Composite PK?
@Id
@NotNull
private String id;
@NotNull
private String product_id;
@NotNull
private Integer quantity;
@NotNull
private LocalDateTime timestamp;

And
public class ProductSold {

    private String productId;
    private Integer itemsSold;

Both classes with proper constructors.
I have the according repository for the Stock
public interface StockRepository extends JpaRepository<Stock, String> {

What I'm trying to do is a tricky SQL query (the comment is easier to visualise the query) where it should return me a List of ProductSold instead of Stock
 /*
SELECT (t1.quantity - t2.quantity) as itemsSold, t1.product_id as pd
FROM stock t1 CROSS JOIN
 stock t2
WHERE MONTH(t1.timestamp) = 8 AND DAY(t1.timestamp) = 26
AND MONTH(t2.timestamp) = 8 AND DAY(t2.timestamp) = 27
AND t1.product_id = t2.product_id
ORDER BY itemsSold DESC
LIMIT 3;
 */

//Not working, not too sure why, says it can't find column quantity. In my view it should be working since it's a valid SQL Query.
@Query(value = "SELECT  new com.stock.stock.model.ProductSold(t1.product_id as productId, (t1.quantity - t2.quantity) as itemsSold )" +
        "    FROM Stock t1 CROSS JOIN Stock t2" +
        "    WHERE MONTH(t1.timestamp) = ?1 AND DAY(t1.timestamp) = ?2" +
        "    AND MONTH(t2.timestamp) = ?3 AND DAY(t2.timestamp) = ?4" +
        "    AND t1.product_id = t2.product_id" +
        "    ORDER BY itemsSold DESC" +
        "    LIMIT 3", nativeQuery = true)
List<ProductSold> findItemsSoldByTimestamp(int month1, int day1, int month2, int day2);

But I'm getting this:
org.h2.jdbc.JdbcSQLSyntaxErrorException: Syntax error in SQL statement "SELECT  NEW COM.[*]STOCK.STOCK.MODEL.PRODUCTSOLD(T1.PRODUCT_ID AS PRODUCTID, (T1.QUANTITY - T2.QUANTITY) AS ITEMSSOLD ) ....
Any idea what is wrong? I've tried not construction in the SQL expression but I get a ConverterNotFoundException

A: You are using a constructor expression which is only available in JPQL, but you also mark you query as native, i.e. SQL which it isn't.


text:
Q: How to add elements in a multi dimensional array I am scraping details of a website and I need to create a JSON object dynamically.How can I achieve this like the example I have provided.If not JSON then how can I make a multi-dimensional array from my code as well.
import requests
import bs4 as bs

urls = 'http://dl5.lavinmovie.net/Series/'
url = requests.get(urls).text
soup = bs.BeautifulSoup(url, 'lxml')
title = soup.find_all('a')

for i in title:

    if(i.text != '../' and ".mp4" not in i.text):
        urll = urls+i.text
    # arr.append(i.text)
        urll1 = requests.get(urll).text
        soupp1 = bs.BeautifulSoup(urll1, 'lxml')
        season = soupp1.find_all('a')
        print(i.text)
        for j in season:

            if(j.text != '../'and ".mp4" not in j.text):

                urlla = urll+j.text
                urll2 = requests.get(urlla).text
                soupp2 = bs.BeautifulSoup(urll2, 'lxml')
                quality = soupp2.find_all('a')
                print(j.text)
                for k in quality:
                    if(k.text != '../' and ".mp4" not in k.text):

                        urllb = urlla+k.text
                        urll3 = requests.get(urllb).text
                        soupp3 = bs.BeautifulSoup(urll3, 'lxml')
                        episode = soupp3.find_all('a')
                        print(k.text)
                        for m in episode:
                            if(m.text != '../' and ".mp4" not in m.text):
                                print(m.text)

Series->Seasons->Quality->Episodes.
This is the flow chart of the JSON file that I wish to have.
The code I have written goes through nested links and finds all of the data that I need,I am not being able to make a multi-dimensional array out of it.
My code recursively opens all of the links and scrapes the text that I want. All I need to solve is how to add all of it in a nested fashion.

A: In python any sort of data can be stored into list and dictionaries, there is almost never a need for making multi-dimensional arrays or vectors.
Series->Seasons->Quality->Episodes.
Just by looking at your flowchart(as you call it), you can workaround as follows:
episodes will be a list within Quality(dict) within Seasons(dict) within Series(dict)
You have to give a read to making dicts of dicts and dicts of lists and how to store data in them in Python.

A: *

*endswith() method returns True if a string ends with the specified suffix. If not, it returns False.

*strip() in-built function of Python is used to remove all the leading and trailing spaces from a string.

Ex.
import requests
import bs4 as bs

def _parse_website_text(url):
  res = requests.get(url).text
  soup = bs.BeautifulSoup(res, 'lxml')
  return soup

main_url='http://dl5.lavinmovie.net/Series/'
soup = _parse_website_text(main_url)
series = soup.find_all('a',href=True)

seriesJson = {}

for s in series:
  if ('../' in s.text or ".mp4" in s.text):
    continue

  series_key = s.text.strip().replace('/','')
  seriesJson[series_key] = {}
  soup1 = _parse_website_text(main_url+s['href'])
  seasons = soup1.find_all('a', href=True)

  for season in seasons:
    if ('../' in season['href'] or season.text.endswith(".mp4")):
      continue

    season_key = season.text.strip().replace('/','')
    seriesJson[series_key][season_key] = {}
    soup2 = _parse_website_text(main_url + s['href']+ season['href'])
    quality = soup2.find_all('a', href=True)

    for q in quality:
      if ('../' in q['href'] or q.text.endswith(".mp4")):
        continue

      quality_key = q.text.strip().replace('/','')
      seriesJson[series_key][season_key][quality_key] = []
      soup2 = _parse_website_text(main_url + s['href'] + season['href']+q['href'])
      episodes = soup2.find_all('a', href=True)

      for e in episodes:
        if '../' in e['href']:
          continue

        es_dict = dict(url=main_url + s['href'] + season['href']+q['href']+e['href'],title=e.text)
        seriesJson[series_key][season_key][quality_key].append(es_dict)

  print(seriesJson)

O/P:
{'12 Monkeys': {'S01': {'480p': [{'url': 'http://dl5.lavinmovie.net/Series/12 Monkeys/S01/480p/12.Monkeys.S01E01.480p.HDTV.LavinMovie.mkv', 'title': '12.Monkeys.S01E01.480p.HDTV.LavinMovie.mkv'}, {'url': 'http://dl5.lavinmovie.net/Series/12 Monkeys/S01/480p/12.Monkeys.S01E02.480p.HDTV.LavinMovie.mkv', 'title': '12.Monkeys.S01E02.480p.HDTV.LavinMovie.mkv'}, {'url': 'http://dl5.lavinmovie.net/Series/12 Monkeys/S01/480p/12.Monkeys.S01E03.480p.HDTV.LavinMovie.mkv', 'title': '12.Monkeys.S01E03.480p.HDTV.LavinMovie.mkv'}, {'url': 'http://dl5.lavinmovie.net/Series/12 Monkeys/S01/480p/12.Monkeys.S01E04.480p.HDTV.LavinMovie.mkv', 'title': '12.Monkeys.S01E04.480p.HDTV.LavinMovie.mkv'}, {'url': 'http://dl5.lavinmovie.net/Series/12 Monkeys/S01/480p/12.Monkeys.S01E05.480p.HDTV.LavinMovie.mkv', 'title': '12.Monkeys.S01E05.480p.HDTV.LavinMovie.mkv'}, {'url': 'http://dl5.lavinmovie.net/Series/12 Monkeys/S01/480p/12.Monkeys.S01E06.480p.HDTV.LavinMovie.mkv', 'title': '12.Monkeys.S01E06.480p.HDTV.LavinMovie.mkv'}, {'url': 'http://dl5.lavinmovie.net/Series/12 Monkeys/S01/480p/12.Monkeys.S01E07.480p.HDTV.LavinMovie.mkv', 'title': '12.Monkeys.S01E07.480p.HDTV.LavinMovie.mkv'}]}}}
....

A: So I have solved my problem myself here is what I did.
    import requests
    import bs4 as bs
    import json
    urls = 'http://dl5.lavinmovie.net/Series/'
    url = requests.get(urls).text
    soup = bs.BeautifulSoup(url, 'lxml')
    title = soup.find_all('a')

    series = {}
    for i in title:

        if(i.text != '../' and ".mp4" not in i.text):
            urll = urls+i.text
        # arr.append(i.text)
            urll1 = requests.get(urll).text
            soupp1 = bs.BeautifulSoup(urll1, 'lxml')
            season = soupp1.find_all('a')
            Series = (i.text).replace("/", "")
            series[Series] = {}
          #  print(i.text)

            for j in season:

                if(j.text != '../'and ".mp4" not in j.text):

                    urlla = urll+j.text
                    urll2 = requests.get(urlla).text
                    soupp2 = bs.BeautifulSoup(urll2, 'lxml')
                    quality = soupp2.find_all('a')
                    Seasons = (j.text).replace("/", "")

                    series[Series][Seasons] = {}
                   # print(j.text)
                    for k in quality:
                        if(k.text != '../' and ".mp4" not in k.text):

                            urllb = urlla+k.text
                            urll3 = requests.get(urllb).text
                            soupp3 = bs.BeautifulSoup(urll3, 'lxml')
                            episode = soupp3.find_all('a')
                            Quality = (k.text).replace("/", "")
                            series[Series][Seasons][Quality] = []
                          #  print(k.text)
                            for m in episode:

                                if(m.text != '../' and ".mp4" not in m.text):
                                    series[Series][Seasons][Quality].append(urllb)

                            jsonfinal = json.dumps(series)
                            with open('data.txt', 'w') as outfile:
                                json.dump(jsonfinal, outfile)

Thanks falco97.


text:
Q: how to get python to print different responses to similar input I need python to go through a list of names and print the following:
first time it sees a name it prints "welcome name" (got that)
second time it sees a name it prints "welcome back name".
What I have so far is that if the name appears more than once, it will be appended to a second list. How can I get python to print welcome the first time it sees the name and welcome back the second?
guests=input("What are the names of the guests? ")
guests=guests.split(",")
m=()
for i in guests:
  if guests.count(i)>1:
   m.append(i)
        for i in m:
   else:
    print ("Welcome, ", i)

A: If I understand your problem, I think this is what you are looking for
guests=input("What are the names of the guests? ")
guests=guests.split(",")

other = []

for person in guests:
  if person in other:
    print('Welcome back, ', person)
  else:
    print('Welcome, ', person)
    other.append(person)

If I put in the names:
craig, smith, smith, john, sarah, vicky, jenny, john

The output is:
Welcome, craig
Welcome, smith
Welcome back, smith
Welcome, john
Welcome, sarah
Welcome, vicky
Welcome, jenny
Welcome back, john


text:
Q: why ambiguity does not apply in int and float varArgs overload? I have been learning java basics for quite a while now and I am still learning it. I am learning ambiguity with varArgs in function overloading. But when I tried to write a program to see it happen, I first made a float and int overload, but this does not give me ambiguity error and executes the int function!! And then just to test, I changed one functions argument to String and it totally gives me the error!!
    class VarArgsOverlodingAndIssues {
      public static void main(String[] com) {

          Compiler a = new Compiler();
          Compiler b = new Compiler();

          a.setYearlyRatings(1,1,1,1,1);
          b.setYearlyRatings(1f,1f,1f,1f);

          b.setYearlyRatings(); /* this is not giving me the error in int and float*/
      }

}

class Compiler {

    void setYearlyRatings(int ... data) { // Changed this to boolean and it gave me the error

        if(data.length < 1)
            System.err.println("The data list passed is emptyf");

        for( int i = 0; i < data.length; i++)
            System.out.println("Ratings of year " + (i + 1) + ": " + data[i]);
    }

    void setYearlyRatings(float ... data) {

        if(data.length < 1)
            System.err.println("The data list passed is emptyint");

        for( int i = 0; i < data.length; i++)
            System.out.println("Ratings of yearf " + (i + 1) + ": " + data[i]);
    }
}

why does it not give me an error in float and int overload?? I have absolutely no idea!! and I am mostly not confident with my questions, I may be asking a wrong question. But i am very very confused .... plzz help!!


text:
Q: Dynamically link libgnat I'm trying to compile a very simple ADA code. Everything works like a charm but on one computer my executable is link dynamically to libgnat whereas on the other computer it's linked statically. In both cases I use gnatmake tool.
Any idea why it's happening?
Do you know a way to force GNAT to dynamically link libraries?

A: That would be the binder's -shared switch. If you are using project files, you can use:
project Foo is
    ...
    package Binder is
       for Switches ("Ada") use ("-shared");
    end Binder;

end Foo;


text:
Q: Calculate gradients of intermediate nodes in tensorflow eager execution I use tensorflow eager execution to do the following calculation:
y = x^2
z = y + 2.

My goal is to calculate dz/dx and dz/dy (the gradients of z over y and z)
dx, dy = GradientTape.gradient(z, [x, y]).

However, only dy is calculated and dx is None. Namely, only the gradients of tensors that directly rely on z can be calculated.
[None, <tf.Tensor: id=11, shape=(), dtype=float32, numpy=1.0>]
[None, <tf.Tensor: id=11, shape=(), dtype=float32, numpy=1.0>]
[None, <tf.Tensor: id=11, shape=(), dtype=float32, numpy=1.0>]
[None, <tf.Tensor: id=11, shape=(), dtype=float32, numpy=1.0>]
[None, <tf.Tensor: id=11, shape=(), dtype=float32, numpy=1.0>]

The following is the full code.
from __future__ import absolute_import, division, print_function
import tensorflow as tf

tf.enable_eager_execution()
tfe = tf.contrib.eager

import os

os.environ["CUDA_VISIBLE_DEVICES"] = "6"
import warnings

warnings.filterwarnings('ignore')

train_steps = 5

for i in range(train_steps):

    x = tf.contrib.eager.Variable(0.)
    with tf.GradientTape() as tape:
        y = tf.square(x)
        z = y + 2

    print(tape.gradient(z, [x,y]))

Any solution?


text:
Q: Using a variable when specifying formatting options in string.format I am trying to write a function that produces a string of a fixed length. There are two cases I think I need to consider:

*

*The string is too long and must be cropped

*The string is too short and must be padded with whitespace

To do this, I have written the following:
foo = "testtesttesttest"
bar = "test"

function fixed_width_a(s)
  return string.format("%-6s", string.sub(s, 1, 6))
end

print(fixed_width_a(foo))
print(fixed_width_a(bar))

-- testte
-- test__ (Using underscores to denote spaces)

While I don't know if this is the best way, it works. Great!
Now, I'd like to be able to specify the width of the string as a parameter. For example,
function fixed_width_b(s, w)
  w = w or 6
  return string.format("%-ws", string.sub(s, 1, w))
end

Of course, this naive attempt doesn't work because "%-ws" isn't parsed correctly. Another attempt might be to specify,
string.format("%-{%d}s", w, string.sub(s, 1, w))

but obviously this makes no sense either.
Question: how do I specify formatting options using a variable in string.format?

A: print(("%-_._s"):gsub("_", 6):format("teststring"))

print(("%-"+6+"."+"s"):format("teststring"))

print(("%%-%d.%ds"):format(6,6):format("teststring"))

A: Okay, so this seems to work okay, although I don't know if it's the best option.
function fixed_width_b(s, w)
  w = w or 6
  tmp = string.format("%%-%ds", w)
  return string.format(tmp, string.sub(s, 1, w))
end

Here, I construct the first argument to the crop/pad part of the code as a string called tmp. If w = 5, for example, then tmp = "%-5s".

Edit
For brevity, I suppose I could just write,
function fixed_width_b(s, w)
  w = w or 6
  return string.format(string.format("%%-%ds", w), string.sub(s, 1, w))
end

and avoid an intermediate variable.


text:
Q: jQuery animate .prepend Rather than simply dumping the HTML into the page I want it to be animated, how can I change the jQuery below to either animate or slide down as the HTML is inserted?
$('.button').click(function() {

j('.tweets ul').prepend(j('.refreshMe ul').html());

});

A: You can .hide() the content before doing a .prependTo(), then call .slideDown() on the element, like this:
$('.button').click(function() {
 j('.refreshMe ul > *').clone().hide().prependTo('.tweets ul').slideDown();
});

This does .clone() of the children to move, rather than doing an innerHTML style copy, hides the cloned elements before moving them, then slides them down.


text:
Q: Manual change of one attribute dependant on another before updating I am following this guidance over here: Update params in Ruby on Rails controller
... but it's not entirely working. Full code of my "update" method in the corresponding controller below - but what is happening is that

*

*the FIRST time I go into the form and change "my_bool_attr" to false, "my_int_attr" does not change

*the SECOND time I go into the form and do NOTHING (my_bool_attr already shows as false/unticked, my_int_attr still shows the previous value) but submit - my_int_attr gets set to 0

Same the other way round: if my_bool_attr is false and I tick it on (and enter a number for my_int_attr), my_bool_attr reflects properly as TRUE but my_int_attr doesn't change. I have to go to the form AGAIN and set the number for my_int_attr again - then it updates in the database.
Why do I have to go through this routine twice? Thank you!
My controller's update method:
def update

    attributes = model_params.clone

    attributes[:my_int_attr] = 0 unless @my_model.my_bool_attr

    if @my_model.update(attributes)
      redirect_to @my_model, notice: "Update was was successful."
    else
      render :edit, status: :unprocessable_entity
    end
  end

EDIT: FULL CODE:
Here is the full schema of the DB as per db/schema.rb:
ActiveRecord::Schema.define(version: 2021_05_17_135523) do

  create_table "movies", charset: "utf8", force: :cascade do |t|
    t.string "title"
    t.integer "runtime"
    t.integer "release_year"
    t.integer "rating"
    t.boolean "seen"
    t.string "file_path"
    t.string "poster"
    t.datetime "created_at", precision: 6, null: false
    t.datetime "updated_at", precision: 6, null: false
    t.string "sort_title"
    t.string "hr_poster"
  end

end

Here is the full view partial (the form); it has some placeholders for later additions (actor checkboxes, genre checkboxes, and what I call "movie-groups" - which will be a way to sort movies into different groups by the user), don't worry about these :)
<%= form_with(model: movie) do |form| %>
  <% if movie.errors.any? %>

<%= pluralize(movie.errors.count, "error") %> prohibited this movie from being saved:

        <% movie.errors.each do |error| %>

<%= error.full_message %>

        <% end %>

  <% end %>

<%= form.label :title, class: 'form-label mb-0' %>

<%= form.text_field :title, class: 'form-control', id: 'input_title' %>

<%= form.label :sort_title, class: 'form-label' %>

<%= form.text_field :sort_title, class: 'form-control' %>

<%= form.label :runtime, class: 'form-label mb-0' %>

<%= form.number_field :runtime, class: 'form-control' %>

<%= form.label :release_year, class: 'form-label mb-0' %>

<%= form.number_field :release_year, class: 'form-control' %>

                Studio Select

<%= form.label :poster, class: 'form-label mb-0' %>

<%= form.text_field :poster, class: 'form-control' %>

<%= form.label :hr_poster, class: 'form-label mb-0' %>

<%= form.text_field :hr_poster, class: 'form-control' %>

            Moviegroup Select

<%= form.check_box :seen, class: 'form-check-input' %> <%= form.label :seen, class: 'form-check-label' %>

<%= form.label :rating, class: 'form-label mb-0' %>

<%= form.number_field :rating, class: 'form-control' %>

Actors

                Actors Checkboxes

Genre

          Genre Checkboxes

<%= @movie.poster ? image_tag(@movie.poster, class: 'rounded movie_poster_form') : raw("X") %>

<%= form.submit class: 'btn btn-outline-primary' %>

<% end %>

And here is the full controller code. The
class MoviesController < ApplicationController

  before_action :set_movie, only: %i[ show edit update destroy ]
  before_action :all_movies

  # GET /movies
  def index
    @pagy, @movies = pagy(Movie.order(:sort_title))
  end

  # GET /movies/1
  def show
  end

  # GET /movies/new
  def new
    @movie = Movie.new
  end

  # GET /movies/1/edit
  def edit
  end

  # POST /movies
  def create
    @movie = Movie.new(movie_params)

    if @movie.sort_title.length == 0
      @movie.sort_title = create_sort_title(@movie.title)
    end

    # The HR Version of the Poster is the same as the low-res one - but stops after the "_V1_" part of the string

    if @movie.poster?
      @movie.hr_poster = @movie.poster.gsub(/_V1_.*/,'.jpg')
    end

    if !@movie.seen?
      @movie.rating = 0
    end

    if @movie.save
      redirect_to @movie, notice: "Movie was successfully created."
    else
      render :new, status: :unprocessable_entity
    end
  end

  # PATCH/PUT /movies/1
  def update

    attributes = movie_params.clone

    attributes = attributes.merge(rating: 0) if !@movie.seen

    if @movie.update(attributes)
      redirect_to @movie, notice: "Movie was successfully updated."
    else
      render :edit, status: :unprocessable_entity
    end
  end

  # DELETE /movies/1
  def destroy
    @movie.destroy
    redirect_to movies_url, notice: "Movie was successfully removed."
  end

  private

    def create_sort_title(current_title)
      # The Regex is case-insensitive and looks for any string beginning with the, a, an (followed by a space) and replaces with "nothing"
      # then it removes any special characters
      # and finally it removes excess whitespace (found here: https://stackoverflow.com/questions/4846638/how-to-remove-excess-whitespace-in-string-using-regex)
      @sortable_title = current_title.gsub(/^the | a | an /i, '').gsub(/'|"|!|\?|-/, '').gsub(/(?<!\w) /,'')
    end

    # get all movies - needed in all sidebars
    def all_movies
      @all_movies = Movie.order(:sort_title)
    end

    # Use callbacks to share common setup or constraints between actions.
    def set_movie
      @movie = Movie.find(params[:id])
    end

    # Only allow a list of trusted parameters through.
    def movie_params
      params.require(:movie).permit(:title, :sort_title, :runtime, :release_year, :rating, :seen, :file_path, :poster, :hr_poster)
    end
end

asdf

A: The attributes var is not being updating. Try with this code
def update
  attributes = model_params.clone
  attributes = attributes.merge(my_int_attr: 0) if !@my_model.my_bool_attr
  if @my_model.update(attributes)
    redirect_to @my_model, notice: "Update was was successful."
  else
    render :edit, status: :unprocessable_entity
  end
end


text:
Q: What was the story reason behind making Carnelion IV so far behind? In the canon Star Wars comic, Obi-Wan & Anakin, the Jedi pair travel to the planet Carnelion IV, where a distress signal has been sounded. The planet is ravaged by war, with its most advanced technology being a walking tank or something. The people use bullets and airships. All I want to know is why. Have Charles Soule or some member of the Lucasfilm Story Group said anything regarding this and its story purpose?

A: In an interview on StarWars.com, the writer Charles Soule explained his approach towards the story. It does not give a direct answer to the question, but helps out in reasoning the background.

"They're going to meet up with a diplomatic fleet and then they hear a distress call from a planet that's supposed to be completely dead,
  there's not supposed to be anything on it. So, they answer the
  distress call and that's where the adventure begins."

Like Obi-Wan told Anakin in the beginning of the story, the people of Carnelion IV destroyed themselves in a war generations ago. The genocide and hypothetical destruction of hi-tech blasters and vessels at same time justifies the existence of the backwater world. Firearms and airships seem to be a visualization of that to us readers.
Also, in order to keep the planet isolated and the destinies of its people unknown, they must not have anything hi-tech for interstellar communication or travel in large scale.

"That's how I broke into it, and then from there, it was fleshing out a world and a planet that hopefully would seem fresh, that we hadn't
  seen before, and a type of Star Wars story that we hadn't seen
  before."

Soule wanted to create a unique world and probably thought a low-tech world would be more of the kind. Of course, there has been such planets in Star Wars media before, but they're still the minority.

"The series is set on a planet with mountain peaks over this huge rolling sea of green mist that obscures everything below because it's
  a planet full of secrets. It gives you some opportunity to do some
  really cool visuals with Jedi hopping around, using their lightsabers
  in the snow, stuff like that."

The comic book creators were after good-looking visuals. In order to justify such vessels as the Zeppelin-type airships, they thought they needed a low-tech world. And the airships did look pretty cool.
You can read the full interview here.


text:
Q: Is there a easy way to get week number array by month and year? I try to get week numbers of year in specific month and year with javascript.

function getWeekNumbers(month, year) {
  var first, last, weeks = [];

  if (month < 10)
    month = "0" + month;

  var date = "01." + month + "." + year;
  first = moment(date, 'dd.MM.yyyy').startOf('month').week();
  last = moment(date, 'dd.MM.yyyy').endOf('month').week();

  for (i = first; i < last; i++) {
    weeks.push(i);
  }

  return weeks;
}

var result = getWeekNumbers(3, 2021);
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js" integrity="sha512-qTXRIMyZIFb8iQcfjXWCO8+M5Tbc38Qi5WzdPOYZHIlZpzBHG3L3by84BBBOiRGiEb7KKtAOAs5qYdUiZiQNNQ==" crossorigin="anonymous"></script>

I need the result like; [9,10,11,12,13]
But the code is not work properly.
It will also cause problems in the 12th month.

A: Your solution is very close, I made some small tweaks to my own liking but you can change that back if you want.
First of all, I recommend using isoWeek instead of week, isoWeek conforms to week numbering according to ISO 8601 (https://momentjs.com/docs/#/get-set/iso-week/).
Your other error lies in not including last as part of the for loop, in this case you want to include it unlike normally where you just loop to the end of a list. Thus <= is what you need in the for-loop.
function getWeekNumbers(month,year) {
    var first, last, weeks=[];

    first = moment().month(month - 1).year(year).startOf('month').isoWeek();
    last = moment().month(month - 1).year(year).endOf('month').isoWeek();

    for(var i = first; i <= last; i++){
      weeks.push(i);
    }

    return weeks;
}

A: Would this satisfy what you're looking for? I used some array chunking and date functions to break the dates of any given month into their respective weeks:
const getWeeks = (month, year) => Array(new Date(year, month, 0).getDate()).fill(0).map((_,i) => new Date(year, month-1, i+1)).map((d,i,a) => !i && d.getDay() ? [Array(d.getDay()).fill(null), d.getDate()] : d.getDate() === a.length && d.getDay() < 6 ? [d.getDate(), Array(6-d.getDay()).fill(null)] : d.getDate()).flat(2).map((d,i,a) => a.length ? a.splice(0,7) : null).filter(w => w);

// February 2021

getWeeks(2, 2021); // -> returns array below ↓↓↓

[
    [null,    1,    2,    3,    4,    5,    6],
    [   7,    8,    9,   10,   11,   12,   13],
    [  14,   15,   16,   17,   18,   19,   20],
    [  21,   22,   23,   24,   25,   26,   27],
    [  28, null, null, null, null, null, null]
]

If you'd prefer not have the null placeholders, but just have shorter arrays when a week has fewer days, we can achieve this using an additional filter. We can even include an optional parameter for this value, that when left empty (or set to undefined) will yield the trimmed arrays:
const getWeeks = (month, year, nullVal) => Array(new Date(year, month, 0).getDate()).fill(0).map((_,i) => new Date(year, month-1, i+1)).map((d,i,a) => !i && d.getDay() ? [Array(d.getDay()).fill(nullVal), d.getDate()] : d.getDate() === a.length && d.getDay() < 6 ? [d.getDate(), Array(6-d.getDay()).fill(nullVal)] : d.getDate()).flat(2).map((d,i,a) => a.length ? a.splice(0,7) : null).filter(w => w).map(w => nullVal !== undefined ? w : w.filter(d => d));

// December 2021

getWeeks(12, 2021); // -> bullish value blank :: trimming weeks, returns array below ↓↓↓

[
    [             1,  2,  3,  4],
    [ 5,  6,  7,  8,  9, 10, 11],
    [12, 13, 14, 15, 16, 17, 18],
    [19, 20, 21, 22, 23, 24, 25],
    [26, 27, 28, 29, 30, 31    ]
]

getWeeks(12, 2021, 0); // -> using 0 as nullish value, returns array below ↓↓↓

[
    [ 0,  0,  0,  1,  2,  3,  4],
    [ 5,  6,  7,  8,  9, 10, 11],
    [12, 13, 14, 15, 16, 17, 18],
    [19, 20, 21, 22, 23, 24, 25],
    [26, 27, 28, 29, 30, 31,  0]
]

You can also use this function to get the number of weeks in a month or the dates in a particular week by the week's index value:
// Get number of weeks in month
getWeeks(12, 2021).length // -> 5

// Get dates in a week by index value
getWeeks(5, 2021)[2] // -> [9, 10, 11, 12, 13, 14, 15]


text:
Q: Java Scanner Reading an input line I was wondering how can I make a scanner in java that will read a line that you input.  For example:
package first.test;
import java.util.Scanner;

public class FirstTest {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int binaryout;

        System.out.println("This converts base 10 numbers to binary numbers.");
        System.out.println("Please enter your Base 10 Number:");
        //I WANT THE INPUT TO GO HERE!!!!!!!!

       }
}

Any help would be great!
EDIT: Well, looking back at this question, the answer is blatantly obvious, do a google search. yes i did, but the problem is that i was such a noob, i couldnt modify or apply ideas to my projects. sorry for the inconvenience. if there are any ideas on how to edit the question to make it relevant, that would be great. because its just so bad, i dont know how.

A: I believe you're looking for input.nextLine();? Or if you know it's base 10 then input.nextInt() or if it's longer input.nextLong(). In the future your best starting place is the java documentation especially since you already knew the class that you were trying to make use of. If you look at the docs for Scanner (and maybe search the page for 'line') you'll find what you were looking for:
https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#nextLine()


text:
Q: Conditional row read of csv in pandas I have large CSVs where I'm only interested in a subset of the rows.  In particular, I'd like to read in all the rows which occur before a particular condition is met.
For example, if read_csv would yield the dataframe:
     A    B      C
1   34   3.20   'b'
2   24   9.21   'b'
3   34   3.32   'c'
4   24   24.3   'c'
5   35   1.12   'a'
...
1e9 42   2.15   'd'

is there some way to read all the rows in the csv until col B exceeds 10.  In the above example, I'd like to read in:
     A    B      C
1   34   3.20   'b'
2   24   9.21   'b'
3   34   3.32   'c'
4   24   24.3   'c'

I know how to throw these rows out once I've read the dataframe in, but at this point I've already spent all that computation reading them in.  I do not have access to the index of the final row before reading the csv (no skipfooter please)

A: Building on @joanwa answer:
df = (pd.read_csv("filename.csv")
      [lambda x: x['B'] > 10])

From Wes McKinney's "Python for Data Analysis" chapter
on "Advanced pandas":
We cannot refer to the result of load_data until it has been assigned to the temporary variable df. To help with this, assign and many other pandas functions accept function-like arguments, also known as callables.
To show callables in action, consider ...
df = load_data()
df2 = df[df['col2'] < 0]

Can be rewritten as:
df = (load_data()
      [lambda x: x['col2'] < 0])

A: You could read the csv in chunks. Since pd.read_csv will return an iterator when the chunksize parameter is specified, you can use itertools.takewhile to read only as many chunks as you need, without reading the whole file.
import itertools as IT
import pandas as pd

chunksize = 10 ** 5
chunks = pd.read_csv(filename, chunksize=chunksize, header=None)
chunks = IT.takewhile(lambda chunk: chunk['B'].iloc[-1] < 10, chunks)
df = pd.concat(chunks)
mask = df['B'] < 10
df = df.loc[mask]

Or, to avoid having to use df.loc[mask] to remove unwanted rows from the last chunk, perhaps a cleaner solution would be to define a custom generator:
import itertools as IT
import pandas as pd

def valid(chunks):
    for chunk in chunks:
        mask = chunk['B'] < 10
        if mask.all():
            yield chunk
        else:
            yield chunk.loc[mask]
            break

chunksize = 10 ** 5
chunks = pd.read_csv(filename, chunksize=chunksize, header=None)
df = pd.concat(valid(chunks))

A: You can use the built-in csv module to calculate the appropriate row number. Then use pd.read_csv with the nrows argument:
from io import StringIO
import pandas as pd
import csv, copy

mycsv = StringIO(""" A      B     C
34   3.20   'b'
24   9.21   'b'
34   3.32   'c'
24   24.3   'c'
35   1.12   'a'""")

mycsv2 = copy.copy(mycsv)  # copying StringIO object [for demonstration purposes]

with mycsv as fin:
    reader = csv.reader(fin, delimiter=' ', skipinitialspace=True)
    header = next(reader)
    counter = next(idx for idx, row in enumerate(reader) if float(row[1]) > 10)

df = pd.read_csv(mycsv2, delim_whitespace=True, nrows=counter+1)

print(df)

    A      B    C
0  34   3.20  'b'
1  24   9.21  'b'
2  34   3.32  'c'
3  24  24.30  'c'

A: I would go the easy route described here:
http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing
df[df['B'] > 10]


text:
Q: Maven build is not generating class files inside the jar file I have a Java project, and I need to compile that using Maven and place the jar file inside Nexus path. so I have used below pom in the project level
<?xml version="1.0" encoding="UTF-8"?>
<project
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
    xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>MyParentGroupId</groupId>
        <artifactId>MyParentArtifactId</artifactId>
        <version>1.0.0-SNAPSHOT</version>
        <relativePath>../MyRelativePath/</relativePath>
    </parent>
    <groupId>MyGroupId</groupId>
    <artifactId>MyArtifactId</artifactId>
    <version>1.2.3-SNAPSHOT</version>
    <packaging>jar</packaging>
    <build>
        <pluginManagement>
            <plugins>
                <plugin>
                    <artifactId>maven-jar-plugin</artifactId>
                    <configuration>
                        <classesDirectory>src</classesDirectory>
                        <includes>
                            <include>src</include>

                        </includes>
                    </configuration>
                </plugin>
            </plugins>
        </pluginManagement>
    </build>
    <properties>
        <maven.skip.deploy>false</maven.skip.deploy>
    </properties>
</project>

After executing this project in Jenkins it goes through successfully and the jar file is generated in Nexus as expected. But the problem here is it does not contains the class files of the project and shows only the things which is shown in below screenshot:

I'm not sure what exactly its missing here. Can someone provide your inputs if faced such issues ? Thank you !


text:
Q: What is the fastest way to set an arbitrary range of elements in a Java array to null? I know I can simply iterate from start to end and clear those cells but I was wondering if it was possible in any faster way (perhaps using JNI-ed System.arrayCopy)?

A: If I got it right, you need to nullify an array, or a sub-range of an array containing references to objects to make them eligible for GC. And you have a regular Java array, which stores data on-heap.
Answering your question, System.arrayCopy is the fastest way to null a sub-range of an array. It is worse memory-wise than Arrays.fill though, since you would have to allocate twice as much memory to hold references at worst case for an array of nulls you can copy from. Though if you need to fully null an array, even faster would be just to create a new empty array (e.g. new Object[desiredLength]) and replace the one you want to nullify with it.
Unsafe, DirectByteBuffer, DirectLongBuffer implementations doesn't provide any performance gain in a naive straight-forward implementation (i.e. if you just replace the Array with DirectByteBuffer or Unsafe). They are slower then bulk System.arrayCopy as well. Since those implementations have nothing to do with Java Array, they're out of scope of your question anyway.
Here's my JMH benchmark (full benchmark code available via gist) snippet for those including unsafe.setMemory case as per @apangin comment; and including ByteBuffer.put(long[] src, int srcOffset, int longCount) as per @jan-chaefer; and an equivalent of Arrays.fill loop as per @scott-carey to check if Arrays.fill could be an intrinsic in JDK 8.
@Benchmark
@BenchmarkMode(Mode.SampleTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public void arrayFill() {
    Arrays.fill(objectHolderForFill, null);
}

@Benchmark
@BenchmarkMode(Mode.SampleTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public void arrayFillManualLoop() {
    for (int i = 0, len = objectHolderForFill.length; i < len; i++) {
        objectHolderForLoop[i] = null;
    }
}

@Benchmark
@BenchmarkMode(Mode.SampleTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public void arrayCopy() {
    System.arraycopy(nullsArray, 0, objectHolderForArrayCopy, 0,
                              objectHolderForArrayCopy.length);
}

@Benchmark
@BenchmarkMode(Mode.SampleTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public void directByteBufferManualLoop() {
    while (referenceHolderByteBuffer.hasRemaining()) {
        referenceHolderByteBuffer.putLong(0);
    }
}

@Benchmark
@BenchmarkMode(Mode.SampleTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public void directByteBufferBatch() {
    referenceHolderByteBuffer.put(nullBytes, 0, nullBytes.length);
}

@Benchmark
@BenchmarkMode(Mode.SampleTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public void directLongBufferManualLoop() {
    while (referenceHolderLongBuffer.hasRemaining()) {
        referenceHolderLongBuffer.put(0L);
    }
}

@Benchmark
@BenchmarkMode(Mode.SampleTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public void directLongBufferBatch() {
    referenceHolderLongBuffer.put(nullLongs, 0, nullLongs.length);
}

@Benchmark
@BenchmarkMode(Mode.SampleTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public void unsafeArrayManualLoop() {
    long addr = referenceHolderUnsafe;
    long pos = 0;
    for (int i = 0; i < size; i++) {
        unsafe.putLong(addr + pos, 0L);
        pos += 1 << 3;
    }
}

@Benchmark
@BenchmarkMode(Mode.SampleTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public void unsafeArraySetMemory() {
    unsafe.setMemory(referenceHolderUnsafe, size*8, (byte) 0);
}

Here's what I got (Java 1.8, JMH 1.13, Core i3-6100U 2.30 GHz, Win10):
100 elements
Benchmark                                       Mode      Cnt   Score   Error    Units
ArrayNullFillBench.arrayCopy                   sample  5234029  39,518 ± 0,991   ns/op
ArrayNullFillBench.directByteBufferBatch       sample  6271334  43,646 ± 1,523   ns/op
ArrayNullFillBench.directLongBufferBatch       sample  4615974  45,252 ± 2,352   ns/op
ArrayNullFillBench.arrayFill                   sample  4745406  76,997 ± 3,547   ns/op
ArrayNullFillBench.arrayFillManualLoop         sample  5549216  78,677 ± 13,013  ns/op
ArrayNullFillBench.unsafeArrayManualLoop       sample  5980381  78,811 ± 2,870   ns/op
ArrayNullFillBench.unsafeArraySetMemory        sample  5985884  85,062 ± 2,096   ns/op
ArrayNullFillBench.directLongBufferManualLoop  sample  4697023  116,242 ±  2,579  ns/op <-- wow
ArrayNullFillBench.directByteBufferManualLoop  sample  7504629  208,440 ± 10,651  ns/op <-- wow

I skipped all** the loop implementations from further tests
** - except arrayFill and arrayFillManualLoop for scale

1000 elements
Benchmark                                 Mode      Cnt    Score   Error    Units
ArrayNullFillBench.arrayCopy              sample  6780681  184,516 ± 14,036  ns/op
ArrayNullFillBench.directLongBufferBatch  sample  4018778  293,325 ± 4,074   ns/op
ArrayNullFillBench.directByteBufferBatch  sample  4063969  313,171 ± 4,861   ns/op
ArrayNullFillBench.arrayFillManualLoop    sample  6270397  543,801 ± 20,325  ns/op
ArrayNullFillBench.arrayFill              sample  6590416  548,250 ± 13,475  ns/op

10000 elements
Benchmark                                 Mode      Cnt     Score   Error    Units
ArrayNullFillBench.arrayCopy              sample  2551851  2024,543 ± 12,533  ns/op
ArrayNullFillBench.directLongBufferBatch  sample  2958517  4469,210 ± 10,376  ns/op
ArrayNullFillBench.directByteBufferBatch  sample  2892258  4526,945 ± 33,443  ns/op
ArrayNullFillBench.arrayFill              sample  2578580  5532,063 ± 20,705  ns/op
ArrayNullFillBench.arrayFillManualLoop    sample  2562569  5550,195 ± 40,666  ns/op

P.S.
Speaking of ByteBuffer and Unsafe - their main benefits in your case is that they store data off-heap, and you can implement your own memory deallocation alghorithm which would siut your data-structure better than regular GC. So you won't need to nullify them, and could compact memory as you please. Most likely the efforts won't worth much, since it would be much easier to get a less performant and more error-prone code then you have now.


text:
Q: triggering a dblclick event in angular I'm trying to trigger a double click event on an element in angular.
        $timeout(function () {
                var elem = document.getElementById(id);
                angular.element(elem).trigger("dblclick")
        }, 1);

the element that has the event listener:
        var nodeEnter = node.enter().append("g")
        .attr("id", function (d) {
            if (d.id)
              return d.id;
            else
              return Math.random();
        })
        .on("dblclick", function () {
            console.log("dblclick");
        });

Nothing happens. What am I doing wrong here?
BTW, it enters the function that invokes the trigger.
The trigger doesn't invoke the dblclick.

A: You have to wrap lines in $timeout function.
$timeout(function() {
    var elem = document.getElementById(id);
    angular.element(elem).triggerHandler("dblclick");
},0);

The $timeout() process is the regular Javascript setTimeout function
 which by default, at the end of it, triggers $apply(). You can also
 instruct $timeout() not to invoke the $apply() function.

A:
If you want to fire a double click element just do the following.

Welcome

A: The problem was that the ".on" method in my code is of the d3 library, that uses a different naming convention for events "__ontype".
See this link:
https://github.com/d3/d3-3.x-api-reference/blob/master/Selections.md#on
This convention does not correspond with the jquery or angular's jqlite "trigger()" or "triggerHandler()".
Using native javascript solved the problem:
        var elem = document.getElementById(id);
        var event = new MouseEvent("dblclick");
        elem.dispatchEvent(event);

In addition, in d3 version 4 there is a designated api for dispatching an event:
https://github.com/d3/d3-selection#selection_dispatch


text:
Q: I am trying to implement a react-slick in my index page to aid in scrolling(dealing with an overflow) and i keep getting error about the "render" I am trying to implement a react-slick in my index page to aid in scrolling(dealing with an overflow) and i keep getting the error: "Property 'render' in type 'VerticalMode' is not assignable to the same property in base type 'Component<{}, {}, any>'.
Type '() => void' is not assignable to type '() => ReactNode'.
Type 'void' is not assignable to type 'ReactNode'."
export class VerticalMode extends Component {
render() {
  const settings = {
    dots: true,
    infinite: true,
    slidesToShow: 3,
    slidesToScroll: 1,
    vertical: true,
    verticalSwiping: true,
    beforeChange: function(currentSlide, nextSlide) {
      console.log("before change", currentSlide, nextSlide);
    },
    afterChange: function(currentSlide) {
      console.log("after change", currentSlide);
    }
  };


text:
Q: Calculating IV60, and IV90 on interactive brokers I am trading options, but I need to calculate the historical implied volatility in the last year. I am using Interactive Broker's TWS. Unfortunately they only calculate V30 (the implied volatility of the stock using options that will expire in 30 days). I need to calculate the implied volatility of the stock using options that will expire in 60 days, and 90 days.
The problem: Calculate the implied volatility of at least a whole year of an individual stock using options that will expire in 60 days and 90 days giving that:

*

*TWS does not provide V60 or V90.

*TWS does not provide historical pricing data for individual options for more than 3 months.

The attempted solution:

*

*Use the V30 that TWS provide too come up with V60 and V90 giving the fact that usually option prices will behave like a skew (horizontal skew). However, the problem to this attempted solution is that the skew does not always have a positive slope, so I can't come up with a mathematical solution to always correctly estimate IV60 and IV90 as this can have a positive or negative slope like in the picture below.

Any ideas?

A: Your question is either confusing or isn't about programming.  This is what IB says.

The IB 30-day volatility is the at-market volatility estimated for a
  maturity thirty calendar days forward of the current trading day, and
  is based on option prices from two consecutive expiration months.

It makes no sense to me and I can't even get those ticks to arrive (generic type 24).  But even if you get them, they don't seem to be useful.  My guess is it's an average to estimate what the IV would be for an option expiring exactly 30 days in the future.  I can't imagine the purpose for this.  The data would be impossible to trade with and doesn't represent reality.  Imagine an earnings report at 29 or 31 days!
If you'd like the IV about 60 or 90 days in the future call reqMktData with an option contract that expires around then and an empty generic tick list.  You will get tick types 10, 11, 12, and 13 which all have an IV.  That's how you build the IV surface.  If you'd like to build it with a weighted average to estimate 60 days, it's possible.
This is python but should be self explanatory
tickerId = 1
optCont = Contract()
optCont.m_localSymbol = "AAPL  170120C00130000"
optCont.m_exchange = "SMART"
optCont.m_currency = "USD"
optCont.m_secType = "OPT"
tws.reqMktData(tickerId, optCont, "", False)

Then I get data like
<tickOptionComputation tickerId=1, field=10, impliedVol=0.20363398519176756, delta=0.0186015418248492, optPrice=0.03999999910593033, pvDividend=0.0, gamma=0.007611155331932943, vega=0.012855970569816431, theta=-0.005936076573849303, undPrice=116.735001>

If there's something I'm missing about options, you should ask this at https://quant.stackexchange.com/


text:
Q: Jssor Slider Adjust Speed After Initialized Im using Jssor Slider but I need to adjust the speed ($SlideDuration) during some events, Is possible to do that? How?

A: I created this method inside the jssor.slider.js.

   function NewSpeed(speed){
       _SlideDuration = speed;
   }

   _SelfSlider.$NewSpeed = NewSpeed;

Then I can use it as follow:

instance.$NewSpeed(integer);


text:
Q: Extract and Apply, Using Apply to set NAs to 0 or revert to NA conditions unmet. I'm playing around with my test dataset, trying to mirror real-world problems or tasks that I encounter with data.
Currently, I'm attempting to set NAs to 0 across multiple variables(columns) that I've extracted from a larger dataset, which i'll then sum, and if the result is zero, revert the columns back to NA. Below is my line of thinking/way I've attempted to do this on my own, but if any of you can think of a preferred or easier to read way I'd love to see it!
Here's what I've come up with, so far.
#Play Data
v1 <- c("Blue","Red","Blue","Red","Purple")
v2 <- c(1,NA,3,4,NA)
v3 <- c(NA,NA,3,4,5)
v4 <- c(1,NA,1,2,2)
v5 <- c(1,NA,3,NA,5)

x = data.frame (v1,v2,v3,v4,v5)

I'm extracting the columns that I'll need for this operation and using sapply to determine NAs.
Extract<- sapply(x[,c("v2","v3","v4","v5")], is.na)

Followed by a custom function (That I've recycled from other previous operations). Which is where my error crops up...
x[Extract] <- lapply(x[Extract], function(k) replace(k, is.na(k), 0))

# I get the below error
Error in `[<-.data.frame`(`*tmp*`, Extract, value = list("Red", "Purple",  :
  unsupported matrix index in replacement

I've given different kinds of apply functions a shot, to no avail. But, i'm almost positive therein lies my problems. If I were to continue my script and complete the aforementioned task, my next two lines of code would be...
x$vcheck <- rowSums(x[, c("v2","v3","v4","v5")], na.rm=TRUE)
x[x$vcheck == 0, c("v2","v3","v4","v5")] <- NA # For rows without any values

Hopefully, together, this script would take rows where a number/answer is present and put 0s in place of any NAs in that row. However, if there are no numbers/answers in the row then it will convert the row back to all NAs.
If anyone could point me in the right direction or think of a better way I'd appreciate it.
Thanks again all!