text:
Q: How to conditionally remove items from a .NET collection I'm trying to write an extension method in .NET that will operate on a generic collection, and remove all items from the collection that match a given criteria.
This was my first attempt:
public static void RemoveWhere<T>(this ICollection<T> Coll, Func<T, bool> Criteria){
    foreach (T obj in Coll.Where(Criteria))
        Coll.Remove(obj);
}

However this throws an InvalidOperationException, "Collection was modified; enumeration operation may not execute". Which does make sense, so I made a second attempt with a second collection variable to hold the items that need to be removed and iterate through that instead:
public static void RemoveWhere<T>(this ICollection<T> Coll, Func<T, bool> Criteria){
    List<T> forRemoval = Coll.Where(Criteria).ToList();

    foreach (T obj in forRemoval)
        Coll.Remove(obj);
}

This throws the same exception; I'm not sure I really understand why as 'Coll' is no longer the collection being iterated over, so why can't it be modified?
If anyone has any suggestions as to how I can get this to work, or a better way to achieve the same, that'd be great.
Thanks.

A: As Marc said, List<T>.RemoveAll() is the way to go for lists.
I'm surprised your second version didn't work though, given that you've got the call to ToList() after the Where() call. Without the ToList() call it would certainly make sense (because it would be evaluated lazily), but it should be okay as it is. Could you show a short but complete example of this failing?
EDIT: Regarding your comment in the question, I still can't get it to fail. Here's a short but complete example which works:
using System;
using System.Collections.Generic;
using System.Linq;

public class Staff
{
    public int StaffId;
}

public static class Extensions
{
    public static void RemoveWhere<T>(this ICollection<T> Coll,
                                      Func<T, bool> Criteria)
    {
        List<T> forRemoval = Coll.Where(Criteria).ToList();

        foreach (T obj in forRemoval)
        {
            Coll.Remove(obj);
        }
    }
}

class Test
{
    static void Main(string[] args)
    {
        List<Staff> mockStaff = new List<Staff>
        {
            new Staff { StaffId = 3 },
            new Staff { StaffId = 7 }
        };

       Staff newStaff = new Staff{StaffId = 5};
       mockStaff.Add(newStaff);
       mockStaff.RemoveWhere(s => s.StaffId == 5);

       Console.WriteLine(mockStaff.Count);
    }
}

If you could provide a similar complete example which fails, I'm sure we can work out the reason.

A: For List<T>, this exists already, as RemoveAll(Predicate<T>). As such, I'd suggest that you keep the name (allowing familiarity, and precedence).
Basically, you can't remove while iterating. There are two common options:

*

*use indexer based iteration (for) and removal

*buffer the items to remove, and remove after the foreach (as you've already done)

So perhaps:
public static void RemoveAll<T>(this IList<T> list, Func<T, bool> predicate) {
    for (int i = 0; i < list.Count; i++) {
        if (predicate(list[i])) {
            list.RemoveAt(i--);
        }
    }
}

Or more generally for any ICollection<T>:
public static void RemoveAll<T>(this ICollection<T> collection, Func<T, bool> predicate) {
    T element;

    for (int i = 0; i < collection.Count; i++) {
        element = collection.ElementAt(i);
        if (predicate(element)) {
            collection.Remove(element);
            i--;
        }
    }
}

This approach has the advantage of avoiding lots of extra copies of the list.

A: I just tested it, and your second method works fine (as it should). Something else must be going wrong, can you provide a bit of sample code that shows the problem?
List<int> ints = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

ints.RemoveWhere(i => i > 5);
foreach (int i in ints)
{
    Console.WriteLine(i);
}

Gets:
1
2
3
4
5

A: I just tried your second example and it seems to work fine:
Collection<int> col = new Collection<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
col.RemoveWhere(x => x % 2 != 0);

foreach (var x in col)
    Console.WriteLine(x);
Console.ReadLine();

I didn't get an exception.

A: Another version of Marcs RemoveAll:
public static void RemoveAll<T>(this IList<T> list, Func<T, bool> predicate)
{
    int count = list.Count;
    for (int i = count-1; i > -1; i--)
    {
        if (predicate(list[i]))
        {
            list.RemoveAt(i);
        }
    }
}


text:
Q: Update the TextView of an home-screen widget on-clicking In my app I am keeping track of a counter, which can be incremented by clicking on a widget button.
I wanted to give the user some feedback that his clicking has added one to the counter - so i tried to add a textView above the widget button. Is there a way to update the presented number after clicking?
My code (currently shows an outdated value of the counter...):
for (int appWidgetId : appWidgetIds) {

    Intent incCounter = new Intent(context, WidgetBroadcastReceiver.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, incCounter, 0); //braodcasting to a counter changing module

    RemoteViews ButtonCounterView = new RemoteViews(context.getPackageName(), R.layout.home_screen_widget);
    ButtonCounterView.setOnClickPendingIntent(R.id.widgetCounterButton, pendingIntent);

    String updatedCounter = String.valueOf(countersMap.getInt(todaysDate.getDate(), 0));
    ButtonCounterView.setTextViewText(R.id.widgetCounter, updatedCounter);

    appWidgetManager.updateAppWidget(appWidgetId, ButtonCounterView);
}

A: You need to update remoteviews contents inside WidgetBroadcastReceiver and then refresh the widget as below:
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(getApplicationContext());
ComponentName thisWidget = new ComponentName(getApplication(), YourWidget.class);
int[] allWidgetIds = appWidgetManager.getAppWidgetIds(thisWidget);
for (int widgetId : allWidgetIds) {
  appWidgetManager.updateAppWidget(widgetId, remoteViews);
}

A: Yes, there is.
Add and onClickStatement to your button where the user clicks (in the xml folder):
<Button android:id="@+id/mybutton"
    android:text="Click me!"
    android:onClick="myMethod" />

Then on your actual class, just create the following:
Button btn = (Button) findViewById(R.id.mybutton);

btn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        myMethod();
    }
});

Then, myMethod() will basically do something like:
textView.setText("Enter text that says user has added one to the counter")

redpajama_set_name: RedPajamaStackExchange


text:
Q: R-spatstat im with square pixels? (for export to Arc raster) I'm having a problem exporting a density im from spatstat to a file format readable by ArcGIS.  Here's my code
library(raster)
library(spatstat)
library(maptools)
library(sp)
# make a spatstat ppp with California boundary as window
ca <- readShapePoly("ca.shp")
o3 <- readShapePoints("o3.shp")
o3 <- as(o3, "SpatialPoints")
o3p <- as.ppp(o3)
o3p$window <- as.owin(ca)
# calculate density
d.o3p <- density.ppp(o3p)

which all works fine. But when I attempt to export to an ascii raster file
writeRaster(raster(d.o3p), filename="grid.asc", format="ascii", NAflag=-9999)

I get this problem
Error in .startAsciiWriting(x, filename, ...) :
x has unequal horizontal and vertical resolutions. Such data cannot be
stored in arc-ascii format

The data I'm using are for the state of California, and so the aspect ratio is not 1.  So... how do I make the density im have square pixels?

A: Do you have to use the ascii format for ArcGIS? It may be difficult to obtain perfectly square pixels with an arbitrary window. The pixel resolution is controlled by either the argument eps or the argument dimyx (not both), which are sent to as.mask and you can read more in that help file. Basically eps is the pixelsize, so the easiest is to set that to a given value. However, if the window size doesn't fit exactly with the window in one direction the pixels might be slightly non-square. E.g. this works perfectly:
X <- runifpoint(100, win = owin(c(0,9),c(0,10)))
d <- density.ppp(X, eps = 1)

But this gives non-square pixels:
d2 <- density.ppp(X, eps = 2)


text:
Q: Joining without matching all rows of 'y' using dplyr The problems with the base function merge are well documented online yet still cause havoc. plyr::join solved many of these issues and works fantastically. The new kid on the block is dplyr. I'd like to know how to perform option 2 in the example below using dplyr. Anyone know if that's possible, and should it be a feature request?
Reproducible example
df1 <- data.frame(nm = c("y", "x", "z"), v2 = 10:12)
df2 <- data.frame(nm = c("x", "x", "y", "z", "x"), v1 = c(1, 1, 2, 3, 1))

Option 1: merge
merge(df1, df2, by = "nm", all.x = T, all.y = F)

This doesn't provide what I want and messes with the order:
##   nm v2 v1
## 1  x 11  1
## 2  x 11  1
## 3  x 11  1
## 4  y 10  2
## 5  z 12  3

Option 2: plyr - this is what I want, but it's a little slow
library(plyr)
join(df1, df2, match = "first")

Note: only rows from x are kept:
##   nm v2 v1
## 1  y 10  2
## 2  x 11  1
## 3  z 12  3

Option 3: dplyr:
library(dplyr)
inner_join(df1, df2)

This changes the order and keeps rows from y.
##   nm v2 v1
## 1  x 11  1
## 2  x 11  1
## 3  y 10  2
## 4  z 12  3
## 5  x 11  1

left_join(df1, df2)

The only difference here is the order:
##   nm v2 v1
## 1  y 10  2
## 2  x 11  1
## 3  x 11  1
## 4  x 11  1
## 5  z 12  3

This is a really useful feature so surprised option 2 is not even possible with dplyr, unless I've missed something.

A: I don't think what you are looking for is possible using dplyr. However, in this case you can get the desired output using the code below.
library(dplyr)
unique(inner_join(df1, df2))

Output:
  nm v2 v1
1  x 11  1
3  y 10  2
4  z 12  3


text:
Q: Security exception while fetching android device IMEI number I need to access the IMEI number of android device. I'm not going to publish this android app on playstore. It's for personal use in the organization. Is there any workaround to fetch the IMEI number? Right now I'm geting security exception while fetching IMEI. I have made device admin app. Though I'm not able to access IMEI number.
class MainActivity : AppCompatActivity() {
    val REQUEST_CODE = 101
    var imei: String? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // in the below line, we are initializing our variables.

        // in the below line, we are initializing our variables.
        val telephonyManager = getSystemService(TELEPHONY_SERVICE) as TelephonyManager
        val imeiTextView = findViewById<TextView>(R.id.idTVIMEI)

        // in the below line, we are checking for permissions

        // in the below line, we are checking for permissions
        if (ActivityCompat.checkSelfPermission(
                this,
                Manifest.permission.READ_PHONE_STATE
            ) != PackageManager.PERMISSION_GRANTED
        ) {
            // if permissions are not provided we are requesting for permissions.
            ActivityCompat.requestPermissions(
                this,
                arrayOf(Manifest.permission.READ_PHONE_STATE),
                REQUEST_CODE
            )
        }

        // in the below line, we are setting our imei to our text view.

        // in the below line, we are setting our imei to our text view.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            imei = telephonyManager.imei
        }
        imeiTextView.setText(imei)
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<String?>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == REQUEST_CODE) {
            // in the below line, we are checking if permission is granted.
            if (grantResults.size != 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // if permissions are granted we are displaying below toast message.
                Toast.makeText(this, "Permission granted.", Toast.LENGTH_SHORT).show()
            } else {
                // in the below line, we are displaying toast message
                // if permissions are not granted.
                Toast.makeText(this, "Permission denied.", Toast.LENGTH_SHORT).show()
            }
        }
    }
}


text:
Q: Redux form validation is not trigger for input or select component I am new to react and redux world and any help is really appreciated.
I have a form which is used to add some data. On that form I am trying to validate the fieldsif user did not enter any value on the fields before submitting the form. But validation is not working and empty values are being submitted. When I debug the validate method is never get called .Below is my form:
AddProduct.JS

import React from 'react';
import {Field, reduxForm} from 'redux-form';
import {connect} from 'react-redux';
import * as actions from '../../actions/product';

class AddProduct extends React.Component {

    renderInput=({input, label, type, meta: {touched, error}})=>{
        const className = `field ${error && touched ? 'error' : ''}`;
        return(

                {label}
                <input{...input} placeholder={label} type={type} autoComplete="off"/>
                {touched && error &&

{error}

}

        );
    }
    renderSelectField = ({ input, label, type, meta: {touched, error}, children }) => {
        const className = `field ${touched && error ? 'error' : ''}`;
        return (

      {label}

        <select {...input}>
          {children}
        </select>
        {touched && error &&

{error}

}

        )
    }

    onSubmit=(formValues) =>{
        console.log(formValues)
        /*this.props.createProduct(formValues,(res)=> {
            //OnSuccess
            if(res.status === 201) {
                //Redirect to previous page
                this.props.history.goBack();
            }
        })*/
    }

    onCancel = () => {
        //Redirect to previous page
        this.props.history.goBack();
    }

    render() {
        return(

Please enter the information below:

                    <form onSubmit={this.props.handleSubmit(this.onSubmit)} className="ui form error">
                        <Field name="Name" component={this.renderInput} label="Name" type="text" />
                        <Field name="Description" component={this.renderInput} label="Description" type="text"/>
                        <Field name="Price" component={this.renderInput} label="Price" type="number"/>
                        <Field name="ImageURL" component={this.renderInput} label="Image" type="text"/>
                        <Field name="CategoriesID" component={this.renderSelectField} label="Category">
                        <option></option>
                            <option value="3">Books</option>
                            <option value="4">Electronics</option>
                            <option value="5">BeautyAndHealth</option>
                        </Field>

                        <button className="ui button primary" type="submit"> Create</button>
                        <button className="ui button secondary" type="button" onClick={()=> this.onCancel()} > Cancel</button>
                    </form>

        )
    }
}

const validate = formValues => {
    const errors = {};

    if (!formValues.Name) {
      errors.title = 'You must enter a name.';
    }

    if (!formValues.Description) {
      errors.description = 'You must enter a description';
    }
    if (!formValues.Price) {
        errors.price= 'You must enter a price';
    }

    if (!formValues.ImageUrl) {
        errors.imageUrl = 'You must enter a image location.';
    }
    if (!formValues.CategoriesID) {
        errors.category = 'You must enter a category.';
    }

    return errors;
  };

const mapStateToProps = state => ({
    productList: state.product.list
});

const mapActionToProps = {
    createProduct: actions.create
}

export default connect(mapStateToProps, mapActionToProps) (reduxForm({form:'addProduct',validate})(AddProduct));

index.js

import {combineReducers} from 'redux';
import {product} from './product';
import {reducer as formReducer} from 'redux-form';

export const reducers = combineReducers({
    form: formReducer,
    product

})


text:
Q: Partitioning a totally ordered set into three subsets according to the order Consider a set $S$, and a total order $R$ over that set.
Part (a)
Given some element $e \in S$, explain why it is possible to partition $S$
into the following three sets:
    $$S_1 = \{ x \in S \mid (x,e) \in R \} $$
    $$\{e\}$$
    $$S_2 = \{ x \in S\mid (e,x) \in R \} $$
Why can you? I totally lost on this.
Part (b)
Given a partitioning of $S$ as stated in Part (a), explain why, for any
$e_1 \in S_1$ and $e_2 \in S_2$, we know that both of the following are
true:
    $$(e_1,e_2)     \in R $$
    $$ (e_2,e_1) \not\in R $$
Remember: You cannot use your intuitive understanding of ``less than,''
since the members of $S$ might not be numbers.  Instead, use the formal
definition of a total order, and argue that the statements above must
be true!
Also how would not using inequalities work?

A: The partitioning follows directly from the definition of a total order (specifically, this is a strict total order, like < on the integers).  Strict total orders exhibit trichotomy: any pair of objects is either in order one way, or the other, or else it is the same object.  These three categories are exclusive, thus it partitions the set.
For the second part, assume that either case is not true, and apply transitivity of a total order at $e$.
EDIT: When I say "this is a strict total order" I am assuming that this is what you meant to say because it makes no sense otherwise.  A (non-strict) total order does not imply the set can be partitioned, because it is reflexive (for all $a$, $a R a$ holds) therefore $e$ would be in all three sets and thus would not partition the set.  (Reflexivity follows from antisymmetry and transitivity which are properties of a non-strict total order.)


text:
Q: Reactive Function Parameters My goal is to make a reactive shiny function in R. There are multiple outputs (e.g. tables) which can be bind to a similar function. However I need the function to react on some parameter, specific to one table. Here is some simple sample code, which isn't working but it makes my idea clear - I hope:
output$tableOne <- DT::renderDataTable({
  getData(foo)
})

getData <- reactive(function(funParameter){
  corrStartDate <- input$StartDate
  corrEndDate <- input$EndDate

  return(someData(corrStartDate, corrEndDate, funParameter))
})

In all tables (if there is more then one) I wan't to show data with different base parameter (getData(x, y, foo)). So the second table could use "getData(x, y, bar)". I don't want to write every time the same function for another table.
The solution above is not working, since reactive functions do not support parameters.
How would you solve this?

A: This should work instead:
getData <- eventReactive(input$funParameter, {
  corrStartDate <- input$StartDate
  corrEndDate <- input$EndDate

  return(someData(corrStartDate, corrEndDate, input$funParameter))
})

eventReactive only updates if arguments stated up front change. Practically speaking, this reactive will not trigger if input$StartDate or input$EndDate changes.
If this is not what you want, normal reactive functions should work. I.e.:
getData <- reactive({

  funParameter <- input$funParameter
  corrStartDate <- input$StartDate
  corrEndDate <- input$EndDate

  return(someData(corrStartDate, corrEndDate, funParameter))
})

which will trigger if any of the inputs change


text:
Q: Django-CMS AppHooks with conflicting urls? I'm trying to use django-cms app hooks in a different way. I have only an app, with different website pages. For each page, i created an AppHook, since i want to have control of all of them with the cms.
To do that, inside the app, i did a package, with urls.py file for each of the page, example:
/urls
   /home_urls.py
   /portfolio_urls.py
   /contacts_urls.py

Here are the definition of some app hooks:
class WebsiteHome(CMSApp):
    name = _("cms-home")
    urls = ["website.urls.home_urls"]

apphook_pool.register(WebsiteHome)

class WebsiteServices(CMSApp):
    name = _("cms-services")
    urls = ["website.urls.services_urls"]

apphook_pool.register(WebsiteServices)

Anyway, the problem is: i don't have any control on the regular expressions. Each one, is entering on the first regular expression that it founds, in this case, the urlpattern in the

website.urls.home_urls

Despite, having different apphHooks.
Example:
if i write a slug contacts (that has an apphook to WebsiteContacts), it still goes to the home_urls.py file, associated with the WebsiteHome (app hook).
Did anyone had a similiar problem?

Basically, what I'm trying to say is that it's something wrong with the regular expression. I can't make:
url(r'^$', [...]),

only:
url(r'^', [...]),

If I put the '$', it doesn't enter on any regex. If I take it, it enters always on the

website.urls.home_urls.py

Despite the slugs having different Apphooks, associated with different urls.py files.

A: Have you tried r'^/$'?  I'm using r'^/?$' in some app-hook urls, but I wonder if r'^$' is failing for you because of a '/'?

A: As you've defined each of those URL files as individual app hooks in CMS then they'll each get attached to a certain page in the CMS e.g.
www.mysite.com/home
www.mysite.com/contacts
www.mysite.com/services
etc

Because those URL files are attached to pages this should prevent conflict between urlpatterns. For example, I've got an URLs file attached to a CMS app called News which looks like this;
urlpatterns = patterns(
    '',
    url(r'^(?P<slug>[-_\w]+)/$', NewsDetailView.as_view(), name='news_detail'),
    url(r'^$', NewsListView.as_view(), name='news_list'),
)

Which is attached to a page at mysite.com/news so if I go to mysite.com/news/myslug I hit that NewsDetailView and if I go to mysite.com/news I hit NewListView.
Using this example, if you had a slug for a contact you'd go to mysite.com/contacts/contact-slug to hit that NewsDetailView.
And just a sidenote on the urlpatterns in case you're not aware, the ^ in the regex signifies the start of a pattern to match, and the $ signifies the end. URL dispatcher docs


text:
Q: Assign values from SQL Server procedure to variable in c#? Here is my code in Microsoft Visual Studio ASP.NET MVC4 using C#
int numRows = new SqlCommand("execute getRows", con);

Error message:

Cannot implicitly convert type
  'System.Data.SqlClient.SqlCommand' to 'int'

Am I missing a step? Like do I have to do an ExecuteReader() type of thing?
I can't find a good resource on using SQL commands in ASP.NET MVC 4.
I know NOT to use string concatenation b/c of SQL injection, so I'm trying to use SQL Server stored procedure.
Here is the procedure:
CREATE PROCEDURE getRows
AS
BEGIN
    select COUNT(*)
    from myTable
    where Status = 1
END

Note: I have tried casting with (int) and with Int.Parse. I assume it has something to do with reading it? Or with making getRows procedure have an output?

A: It's a little more complicated:
SqlConnection sqlConnection1 = new SqlConnection("Your Connection String");
SqlCommand cmd = new SqlCommand();
SqlDataReader reader;

cmd.CommandText = "StoredProcedureName";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = sqlConnection1;

sqlConnection1.Open();

int numRows = (int)cmd.ExecuteScalar();

sqlConnection1.Close();

More information.


text:
Q: is_front_page() doesnt work in ajax theme i am trying to add the below code in an ajax wordpress theme in order to show a div only in front page
<?php wp_reset_query(); ?>
<?php if(is_home() || is_front_page()): ?>
 <!-- Do the things here... -->
<?php else: ?>
 <!-- Else part goes here...  -->
<?php endif;  ?>

unfortonatly it doesnt work when accessing from menu to other pages for example :
HOME-->SECOND PAGE--> THIRD PAGE
it works only if i access direct to an other page : for example :
www.example.com/secondpage
do you know any solution on this ?

A: Check this article on how to properly use is_front_page and is_home functions.
Basically you should use this code:
if ( is_front_page() && is_home() ){
    // Default homepage
} elseif ( is_front_page()){
    //Static homepage
} elseif ( is_home()){
    //Blog page
} else {
    //everything else
}


text:
Q: Why can't I bind javascript submit() with variables together? I created a variable targetForm and tried to bind it with submit(). However, the bound function doesn't catch submit event when I call a function and trigger variable to submit form.
var targetForm;

function Add_Notice_Message(evt){

    alert('set up form');

    targetForm = document.notification_form;
    targetForm.classname= 'TTWForm';
    targetForm.method = "post";
    targetForm.action = '';
    targetForm.novalidate = '';

    alert('beforesubmmit');
    targetForm.submit();
}

$( targetForm ).bind(
    "submit",
    function( event ){
        alert('submit');

        var $form = $(this), type;
        type = $form.find('#type').val();

        var options = {
            category:'projects',
            message: 'Sample Notification'
        };

        notifications.createNotification(options);
        return false;
    }
);

A: You're binding the variable before it gets the value.
you should set the variable once (maybe outside the Add_Notice... function) and then bind it.


text:
Q: charCodeAt is not behaving as expected How can this be possible:
var string1 = "", string2 = "";

//comparing the charCode
console.log(string1.charCodeAt(0) === string2.charCodeAt(0)); //true

//comparing the character
console.log(string1 === string2.substring(0,1));              //false

//This is giving me a headache.

http://jsfiddle.net/DerekL/B9Xdk/
If their char codes are the same in both strings, by comparing the character itself should return true. It is true when I put in a and ab. But when I put in these strings, it simply breaks.
Some said that it might be the encoding that is causing the problem. But since it works perfectly fine when there's only one character in the string literal, I assume encoding has nothing to do with it.
(This question addresses the core problem in my previous questions. Don't worry I deleted them already.)

A: In JavaScript, strings are treated by characters instead of bytes, but only if they can be expressed in 16-bit code points.
A majority of the characters will cause no issues, but in this case they don't "fit" and so they occupy 2 characters as far as JavaScript is concerned.
In this case you need to do:
string2.substring(0, 2) // ""

For more information on Unicode quirkiness, see UTF-8 Everywhere.

A: You can use the method to compare 2 strings:
string1.localeCompare(string2);

A: Substring parameters are the index where he starts, and the end, where as if you change it to substr, the parameters are index where to start and how many characters.


text:
Q: How to take care of inner tag in regex? I try to parse CSS by regex (PHP preg_match_all) like
([^{]+)\s*\{\s*([^}]+)\s*}

but the problem is when there is an inner { tag. For example,
table {
    border-collapse: collapse;
    border-spacing: 0
}

@keyframes blinking {
    from {
        background: #f4a83d
    }
    to {
        background: rgba(244, 168, 61, 0)
    }
}

I need to parse it to two elements, but the result is
Array
(
    [0] => Array
        (
            [0] =>
table {
    border-collapse: collapse;
    border-spacing: 0
}
            [1] =>

@keyframes blinking {
    from {
        background: #f4a83d
    }
            [2] =>
    to {
        background: rgba(244, 168, 61, 0)
    }
        )

    [1] => Array
        (
            [0] =>
table
            [1] =>

@keyframes blinking
            [2] =>
    to
        )

    [2] => Array
        (
            [0] => border-collapse: collapse;
    border-spacing: 0

            [1] => from {
        background: #f4a83d

            [2] => background: rgba(244, 168, 61, 0)

        )

)

NOTE: There are several classes and programs for parsing CSS, but they are an overkill for what I need to just capture the selector and the rules. They parse all the rules, which I need to re-join. Therefore, it is more convenient to use a simple regex approach instead.

A: Use
([^{]+)\s*({\s*((?:[^{}]++|(?2))*)\s*})

See proof
Explanation
--------------------------------------------------------------------------------
  (                        group and capture to \1:
--------------------------------------------------------------------------------
    [^{]+                    any character except: '{' (1 or more
                             times (matching the most amount
                             possible))
--------------------------------------------------------------------------------
  )                        end of \1
--------------------------------------------------------------------------------
  \s*                      whitespace (\n, \r, \t, \f, and " ") (0 or
                           more times (matching the most amount
                           possible))
--------------------------------------------------------------------------------
  (                        group and capture to \2:
--------------------------------------------------------------------------------
    {                        '{'
--------------------------------------------------------------------------------
    \s*                      whitespace (\n, \r, \t, \f, and " ") (0
                             or more times (matching the most amount
                             possible))
--------------------------------------------------------------------------------
    (                        group and capture to \3:
--------------------------------------------------------------------------------
      (?:                      group, but do not capture (0 or more
                               times (matching the most amount
                               possible)):
--------------------------------------------------------------------------------
        [^{}]++                   any character except: '{', '}' (1 or
                                 more times (matching the most amount
                                 possible possessively))
--------------------------------------------------------------------------------
       |                        OR
--------------------------------------------------------------------------------
        (                        group and capture to \4:
--------------------------------------------------------------------------------
          (?2)                   Capturing group 2 pattern recursed
--------------------------------------------------------------------------------
        )                        end of \4
--------------------------------------------------------------------------------
      )*                       end of grouping
--------------------------------------------------------------------------------
    )                        end of \3
--------------------------------------------------------------------------------
    \s*                      whitespace (\n, \r, \t, \f, and " ") (0
                             or more times (matching the most amount
                             possible))
--------------------------------------------------------------------------------
    }                        '}'
--------------------------------------------------------------------------------
  )                        end of \2


text:
Q: Структура автоматического удаления элементов Хелло. Я только учусь, так что не судите строго) У меня стоит задача спроектировать такую структуру, в которую можно добавлять какие-то элементы, и при этом они автоматически удаляются через 30 сек. Подскажите пожалуйста как это реализовать. Использовать Observer, Observerable? Или можно в тупую написать метод проверки времени существования всех элементов и запускать его каждую секунду, но это будет как-то уж совсем не эффективно. Подскажите с какой стороны подойти. Заранее спасибо.

A: *

*Наследуешь любой контейнер элементов из стандартных, метод добавления перекрываешь добавляя получение текущего времени.

*Если контейнер не является очередью, добавляешь в него дополнительную очередь FIFO в которую скидываешь ссылку (индекс в массиве или ключ, или что нибудь ещё) на объект + время, т.е.

*При добавлении стартуешь отдельный поток, который проверяет очередь и в случае пустоты уходит в wait

*При добавлении элемента будишь поток notify

*При наличии элемента, поток проверяет сколько времени прошло с момента добавления, если меньше 30 секунд, дальше засыпает на разницу времени, если больше то удаляет элемент и проверяет следующий.
Особенности:
а) придется заниматься синхронизацией, если родительский контейнер не синхронизованный
Примеры писать надеюсь не надо? :)

A: Очередь приоритетов по дате и времени, нужно сравнивать текущее время с датой только самого первого элемента в очереди.


text:
Q: Google External Login in MVC 5 C# (.Net Framework) I'm trying to add the Google External Login feature for one of my Web Applications using Visual Studio 2017 (MVC 5 .Net Framework). By following the exact steps given before, I'm not able to make it work. And after signing in with google account (previously assigned in test users), it always redirects to the login page. In debugging mode all the variables and properties are null.
Further, on my issue, I have tried each of the following steps (based on previous solutions from StackOverflow:-

*

*Updating all related NuGet packages to the latest version.

*Configuring Authorized Javascript and redirect URL based on my project
(HTTP://localhost:{port number})

*The application is in Test Mode (Test users were added).

*The Code for Google authentication in (App_Start-> Startup.Auth.cs)
looks something like this:
app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);
app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
        {

            ClientId = "My Client ID Given in Google Developer Console",

            ClientSecret = "My Client Secret Given in Google Developer Console"
        });

I don't know if someone else has faced the same issue recently. And I tested this on Asp.Net Core project, and it works fine. But it does not work in MVC 5 Framework.
Please advise if any.
Best

A: It seems the issue is related to HTTP , so you need to use HTTPs instead. Please, follow these steps:-

*

*Right Click on your project name-> Properties.

*In Properties window enable SSL.

*Copy the entire SSL URL (the port number is different than HTTP).

*paste your new SSL URL to Authorized Redirect URL in Google Developer Console. e.g

*When you run your application in visual studio. Don't forget to change HTTP to HTTPs and change the port number before trying to singing via google.

*The complete Authorized Redirect URL is as below:
Authorized Redirect URL : https://localhost:{new port number}/signin-google

A: From the Google APIs API Manager, visit the Credentials tab to obtain the Client ID. Download to save a JSON file with application secrets. Copy and paste the ClientId and ClientSecret into the UseGoogleAuthentication method found in the Startup.Auth.cs file in the App_Start folder. If ClientId and ClientSecret values are not valid it doesn't work.
For example,
app.UseGoogleAuthentication(
         clientId: "001-010.apps.googleusercontent.com",
         clientSecret: "01000100000");


text:
Q: Determining Limits of Integration - Multiple Integrals I was wondering whether someone could refresh my memory of something I think I remember learning when taking Calculus II or some similar class. Say, for example, that one has a function of a couple of variables, with respect to each of which one intends to integrate. Suppose there are also multiple conditions for the variables to satisfy. What method is used to convert the conditions into something that can be used to construct an integral?
In the event that this is not entirely clear, allow me to provide an example. Suppose one wishes to sum the function $f(x, y)$ with the conditions that $0 < x < 1$, $0 < y < 1$, and $x + y = 1$. If, for example, we solve this last condition for $y$, we find that $y = 1 - x$. Since the value of $(1 - x)$ is nonnegative for all $x \in \left(0, 1\right)$, can we simply integrate as
$$\int_{0}^{1}{\int_{0}^{1-x}{f(x,y)} \hspace{5 px} dy} \hspace{5 px} dx?$$

A: Note that the following integral
$$\int_{0}^{1}{\int_{0}^{1-x}{f(x,y)} \hspace{5 px} dy} \hspace{5 px} dx$$
corresponds to the triangular region

*

*$0\le x\le 1$

*$0\le y\le 1-x$

A: The integral that you wrote has conditions $0\le x\le1$ and $0\le y\le 1-x$.
If you put the condition $x+y=1$, then the integral is one dimensional, and can be written as $\int_0^1f(x,1-x)dx$, or using delta functions


text:
Q: What is the average thickness of an eccentric annulus? I have a small circle of radius $r$ entirely contained in a large circle of radius $R\gt r$, these two circles are not concentric and so they define an eccentric annulus.
The center of the small circle is in $\left(0,0\right)$; a point $A=\left(r\cos\left(\alpha\right),r\sin\left(\alpha\right)\right)$ is on the small circle; $A$ and the center of the small circle define a line; this line intersects the large circle in two points, the farthest point from the small circle is $B$ and it is depicted in the following figure; I define the thickness $t$ as a function of the angle $\alpha$ as the length of the line segment $\overline{AB}$.
What is the average value of $\overline{AB}$ when $\alpha$ goes from $0$ to $2\pi$?
If I had to guess, I would say the average value is $R-r$, i.e. the thickness of an annulus.

Using the formulae1 I derived an (horrible) expression for $t(\alpha)$ but I have no idea on how to integrate it in order to compute its mean value.
1Weisstein, Eric W. "Circle-Line Intersection." From MathWorld--A Wolfram Web Resource. http://mathworld.wolfram.com/Circle-LineIntersection.html

A: Hint:
WLOG, $R=1$. In polar coordinates, the equation of a circle centered at $(k,0)$ is
$$(\rho\cos\theta-k)^2+\rho\sin^2\theta=1$$
or
$$\rho=k\cos\theta+\sqrt{1-k^2\sin^2\theta}.$$
So you need to compute the half of
$$\int_0^{2\pi}(k\cos\theta+\sqrt{1-k^2\sin^2\theta}-r)^2\,d\theta=\\
\int_0^{2\pi}(k^2\cos^2\theta+1-k^2\sin^2\theta+r^2+2k\cos\theta\sqrt{1-k^2\sin^2\theta}-2r\sqrt{1-k^2\sin^2\theta}-2rk\cos\theta)\,d\theta$$ where $r$ is the inner radius.
Unfortunately, all the terms are integrable but $2r\sqrt{1-k^2\sin^2\theta}$ which can only be solved via a complete elliptic integral of the second kind $E(k)$, and this is a sure sign that no simpler solution is possible.


text:
Q: finding a list of perfect integers from a range of integer numbers the user will input a arbitrary range where the end number is the number up to what the user wants perfect numbers from those numbers and append the numbers in a list and print the list or the list elements...
Sample CODE:
sum_1=0
sum_2=0
b=[]
a=range(1,int(input('enter_num_upto you want perfect num')))

for i in a:
    for items in range(1,i):
        if(i%items)==0:
            sum_1=sum_1+items
            sum_2=sum_2+items+i

        if sum_1==i and (sum_2//2)==i:
                   b.append(i)

    for j in b:
         print(j)

the code runs without errors but it doesn't display any outputs..... please mark my mistakes and explain the correct logics
THANKS IN ADVANCE

A: I think the problem is that you haven't defined the list "b". I'd suggest that after you define
a=range(1,int(input('enter_num_upto you want perfect num')))

define b as
b=[]

This will tell the program that a list "b" exists, which you can then append items to. You can't append items to a list that doesn't exist yet.
The same thing should go for the 2 variables sum_1 and sum_2, you cannot define them conditionally in an "if statement", therefore you should define them at the beginning of your program, right after you define b
sum_1 = 0
sum_2 = 0

As for the logic of your code, I suggest you don't need a sum_2, after going through the for loop that makes sum_1, check if sum_1 is equal to i. But make sure whenever you use "range", you set the end as the number after you want to end it at. For example if you want the range to start at 1 and end at I, use range(1,i+1). This is only for your input. Make sure to set sum_1 back to 0 after every iteration aswell.
so:
a=range(1,int(input('enter_num_upto you want perfect num'))+1)
b=[]
sum_1=0

for i in a:
    for item in range(1,i):
       if (i%item)==0:
          sum_1= sum_1+item

    if sum_1==i:
        b.append(i)

    sum_1=0

for j in b:
   print(j)


text:
Q: How to Download Data in Android using completion handler? My background is from iOS.
I use AFNetworking to download data. I make completion handler to let me know as downloading finishes. The completion handler returns me NSData, which I subsequently parse.
I keep all stuff of downloading into a separate class. I simply pass URL, parameters and it downloads and returns me data.
How can I achieve such strategy in Android.
MY STUDY:
I read from
http://developer.android.com/training/basics/network-ops/connecting.html#http-client
where I found that I do it inside Activity, If I use it in a separate class. it creates issue of context and other stuff.
When I read in detail whole document, I found that I can put stuff in other class, but I can't find any COMPLETION HANDLER, to sent data back to Activity class.
So, Major portion of my class, how to download using COMPLETION HANDLER.
Thanks.

A: *

*In case you'd like to try Retrofit, here are some good examples to get started with and answering your question, they do have a callback for when your data is downloaded:
User user = new User(123, "John Doe");
Call<User> call = apiService.createuser(user);
call.enqueue(new Callback<User>() {
    @Override
    public void onResponse(Response<User> response,
      Retrofit retrofit) {
        // THIS is where you get a successful callback when your data is downloaded
    }

    @Override
    public void onFailure(Throwable t) {
        // Callback for error cases
    }

*If you'd prefer volley, here is their documentation and an example on how to do a basic network call with callbacks:
// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(this);
String url ="http://www.google.com";

// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
        new Response.Listener<String>() {
    @Override
    public void onResponse(String response) {
        // THIS is the successful callback
    }
}, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        // Error callback
    }
});
// Add the request to the RequestQueue.
queue.add(stringRequest);


text:
Q: How can we split the contents of a whole column into separate columns within the same table? Say I use pandas to read in datatable.csv, and the table looks like this:

How could we split Column 3 such that datatable subsequently looks like this:

I've read plenty of answers to similar questions and tried using the likes of .str.rpartition('-'), .split('-') and .apply() combinations, but I haven't managed to extract the separated values into columns.

A: Use split with expand=True:
df[['Column 3','Column 4','Column 5']] = df['Column 3'].str.split('-', expand=True)

Example
df = pd.DataFrame({'Column 3':['X-X-0','1-0-X','X-Y-X','X-0-0','1-X-Y']})
df[['Column 3','Column 4','Column 5']] = df['Column 3'].str.split('-', expand=True)

Output:
  Column 3 Column 4 Column 5
0        X        X        0
1        1        0        X
2        X        Y        X
3        X        0        0
4        1        X        Y

A: You can use this
df['col3']= ['1-d-w','s-3-q']

df
Out[4]:
     col
0  1-d-w
1  s-3-q
df['col4']= df['col3'].apply((lambda x: x.split('-'))).apply((lambda x:x[0]))
df['col5']= df['col3'].apply((lambda x: x.split('-'))).apply((lambda x:x[1]))
df['col6']= df['col3'].apply((lambda x: x.split('-'))).apply((lambda x:x[2]))
df
Out[33]:
    col3  col4  col5  col6
0  1-d-w     1     d     w
1  s-3-q     s     3     q


text:
Q: No matching constructor when I overload operator for dynamic string class I get a problem with my String class.
Constructor and copy constructor:
private:
    char * buf;
public:
    String( const char * s = "")
    {
        buf = strdup(s);
    }
    String( String &s)
    : buf(strdup(s.buf))
    {
    }

The operator:
String operator + ( const String &s )
{
    char* tmp = new char[strlen(buf) + strlen(s.buf) + 1]; // +1 for the terminating '\0'
    strcpy(tmp,buf);
    strcat(tmp,s.buf);
    String result;
    delete[] result.buf;
    result.buf = tmp;
    return result;
}
String operator += ( const String s )
{
    delete_char_array(buf);
    char* tmp = new char[strlen(buf) + strlen(s.buf) + 1];
    strcpy(tmp,buf);
    strcat(tmp,s.buf);
    buf = strdup(tmp);
    delete_char_array(tmp);
    return *this;
}
void print( ostream & out )
{
    char *p = buf;
    out << p;
}

and I have implemented the << operator
ostream & operator << ( ostream & out,  String str )
{
    str.print(out);
    return out;
}

My main() function is:
int main()
{
    String firstString("First");
    String secondString("Second");
    cout << firstString + secondString << endl;
    (firstString+=secondString).print(cout);
}

I can correctly get the output by the String.print(cout) but the g++ will tell me that
cout << firstString + secondString << endl;` does not have the matching
constructor for `String::String(String)`

and there are two options, 1. String::String( char * c) and 2. String::String(String &s).

A: This should be the copy constructor signature:
String(String const& s)

so the reference can bind to an r-value returned by operator+. Additionally, you should also use this signature for operator<<:
ostream &operator<<(ostream &out, String const& str)

Any of these snippets will fix the error, however (1) is a crucial practice (as you see) and (2) avoids making a copy.
You'll also need to make void print(ostream &out) const, because you want to call it with String const&, even operator+ should be const. Please, don't forget the const...
You don't modify a reference - make it a reference-to-const. A member function does not modify *this - make it const. It's that simple.
You also forgot an & here: String operator+=(const String s).
We're still not finished, there's also a number of things to fix, as pointed out in PaulMcKenzie's comments.

A: There are a few things wrong with your String class.
First, usage of strdup returns an allocated buffer that should be deallocated using free().  However in your overloaded += and + functions, you're using new [] and delete [].   You're using C++, so pretend that strdup() doesn't exist.
Even though you're trying to be careful about it, it is undefined behavior to mix allocation functions like this.  Instead, use new [] and delete [] throughout your class code.
Second, the copy constructor signature should be:
    String(const String &s);

So your constructors should now look like this:
private:
    char * buf;
public:
    String( const char* s = "") : buf(new char[strlen(s) + 1]())
    {
        strcpy(buf, s);
    }

    String(const String &s) : buf(new char[strlen(s.buf) + 1]())
    {
        strcpy(buf, s.buf);
    }

You now need to add a destructor, if you haven't done so already:
String::~String() { delete [] buf; }

Next is your operator += and operator +.  The operator += should be returning a reference to the current object, not a brand new object.
String& operator += ( const String& s )
{
    char* tmp = new char[strlen(buf) + strlen(s.buf) + 1];
    strcpy(tmp,buf);
    strcat(tmp,s.buf);
    delete [] buf;
    buf = tmp;
    return *this;
}

Note that the return type is a reference to String.  Also, note that the memory for the concatenated string is allocated first before any attempt is made to delete the old buffer.  This needs to be done to ensure that your buffer will not become invalidated if operator new throws an exception.
Given this, operator + can be written this way:
String operator + ( const String& s )
{
    String tmp(*this);
    return tmp += s;
}

We use operator += as a helper function.  All that was done was to create a temporary String that was the same as *this.  Then we just return the result of operator += on the passed in String.  Short and simple.
The last thing you're missing is an assignment operator. Without an assignment operator, you cannot safely do things like this:
String s1("abc");
String s2;
s2 = s1; // <-- assignment operator here

To implement an assignment operator is very easy, provided you have a copy constructor and working destructor.  Please go to this link as to how to implement this function:
copy / swap idiom.


text:
Q: JSFiddle CSS and Result text areas squeezed I am using Chrome on OSX and have encountered an infuriating bug which makes JSFiddle unusable:

As the screenshot shows the CSS and Result text areas are squeezed off the screen with no handle to pull them back. How can I make them visible and usable?
It hasn't always rendered like this, but I'm not sure what has caused it.

What I've tried

*

*Disabling all chrome extensions

*Resizing the browser to a ridiculous width

*Clearing local, session and cookie storage for JSFiddle on Chrome

*Removing secondary screens

*Changing my screen resolution

None of which have changed anything.

Update
The bug is not replicated when using safari.

A: very likely you can restore the areas by running
Layout.setWindowSizes(null)
from console. it's a well known issue
https://stackoverflow.com/questions/24388509/jsfiddle-js-panel-size-is-stuck-how-do-i-reset-it


text:
Q: DuplicateKeyException: error code 11000 and error message 'E11000' i want to update/replace document using id field only, i am using mongoTemplate.save(p, collection) method but i am getting DuplicateKeyException: error code 11000 and error message 'E11000'

public class MongoDAO {

 @Autowired
 @Qualifier("mongoTemplate")
 private MongoTemplate mongoTemplate;

 private static final String PERSON_COLLECTION = "person";

 public MongoTemplate getMongoTemplate() {
  return mongoTemplate;
 }

  public void update(Object p) {
  this.mongoTemplate.save(p, PERSON_COLLECTION);
 }

 }

This is my person DAO

    public class PersonDAO{
      @Autowired
     MongoDAO mongoDAO;

      public void updatePerson(){

         //read
      Person p1 = mongoDAO.readById("1234");

      //update
      p1.setName("David");
        mongoDAO.update(p1);

     }
}

Person.java class

package com.mongo.andy;

import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Field;

public class Person {

 @Id
 private String id;
 @Field
 private String name;

 public String getId() {
  return id;
 }
 public void setId(String id) {
  this.id = id;
 }
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }

}

I simply want to get the object from mongodb change the values and update the document based on _id
Using mongooperation.save() or mongotemplate.save() i am getting below error

com.mongodb.DuplicateKeyException: Write failed with error code 11000 and error message 'E11000 duplicate key error collection: Person.person index: _id_ dup key: { : "5996f1d43b6af5c797a1cf4g" }'
 at com.mongodb.operation.BaseWriteOperation.convertBulkWriteException(BaseWriteOperation.java:236)
 at com.mongodb.operation.BaseWriteOperation.access$300(BaseWriteOperation.java:60)
 at com.mongodb.operation.BaseWriteOperation$1.call(BaseWriteOperation.java:146)
 at com.mongodb.operation.BaseWriteOperation$1.call(BaseWriteOperation.java:133)
 at com.mongodb.operation.OperationHelper.withConnectionSource(OperationHelper.java:230)
 at com.mongodb.operation.OperationHelper.withConnection(OperationHelper.java:221)
 at com.mongodb.operation.BaseWriteOperation.execute(BaseWriteOperation.java:133)
 at com.mongodb.operation.BaseWriteOperation.execute(BaseWriteOperation.java:60)
 at com.mongodb.Mongo.execute(Mongo.java:781)
 at com.mongodb.Mongo$2.execute(Mongo.java:764)
 at com.mongodb.DBCollection.executeWriteOperation(DBCollection.java:333)
 at com.mongodb.DBCollection.insert(DBCollection.java:328)
 at com.mongodb.DBCollection.insert(DBCollection.java:319)
 at com.mongodb.DBCollection.insert(DBCollection.java:289)
 at com.mongodb.DBCollection.insert(DBCollection.java:255)
 at com.mongodb.DBCollection.insert(DBCollection.java:192)
 at org.springframework.data.mongodb.core.MongoTemplate$9.doInCollection(MongoTemplate.java:1051)
 at org.springframework.data.mongodb.core.MongoTemplate.execute(MongoTemplate.java:479)
 at org.springframework.data.mongodb.core.MongoTemplate.insertDBObject(MongoTemplate.java:1046)
 at org.springframework.data.mongodb.core.MongoTemplate.doInsert(MongoTemplate.java:855)
 at org.springframework.data.mongodb.core.MongoTemplate.doSaveVersioned(MongoTemplate.java:1001)
 at org.springframework.data.mongodb.core.MongoTemplate.save(MongoTemplate.java:985)
 at com.mcmcg.dia.account.metadata.dao.MongoDAO.update(MongoDAO.java:105)
 at com.mcmcg.dia.account.metadata.service.AccountOALDService.mongotestapi(AccountOALDService.java:265)
 at com.mcmcg.dia.account.metadata.service.AccountOALDService$$FastClassBySpringCGLIB$$7f85f843.invoke(<generated>)

Please provide the solution and suggest if there is any other way to update/replace documents in mongodb using spring-data on the basis of id field only. I have large custom object and not interesting writing any queries for update.
I was able to do so in couchbase db using upsert(), finding similar way in mongodb.

A: Instead of this.mongoTemplate.save(p, PERSON_COLLECTION); try with:
public void update(Object p) {
  BasicDBObject dbObject = new BasicDBObject();
  mongoTemplate.getConverter().write(p, dbObject);
  mongoTemplate.upsert(new Query(Criteria.where("_id").is(((Person) p).getId())),
      Update.fromDBObject(dbObject, "_id"), PERSON_COLLECTION);
}

The solution is similar to how the upsert method it is implemented in MongoTemplate.


text:
Q: Oracle: How do I get the sequence number of the row just inserted? How do I get the sequence number of the row just inserted?

A: Edit: as Mark Harrison pointed out, this assumes that you have control over how the id of your inserted record is created. If you have full control and responsibility for it, this should work...

Use a stored procedure to perform your insert and return the id.
eg: for a table of names with ids:
PROCEDURE insert_name(new_name    IN   names.name%TYPE,
                      new_name_id OUT  names.id%TYPE)
IS
    new_id names.id%TYPE;
BEGIN
    SELECT names_sequence.nextVal INTO new_id FROM dual;
    INSERT INTO names(id, name) VALUES(new_id, new_name);
    new_name_id := new_id;
END;

Using stored procedures for CRUD operations is a good idea regardless if you're not using an ORM layer, as it makes your code more database-agnostic, helps against injection attacks and so on.

A: My answer in C#, considering that table "testtable" has an "ID" collumn as PK with an autoinc sequence and field "testname" is a varchar field.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Oracle.DataAccess.Client;
using System.Data;

namespace ConsoleApplication3
{
class Program
{

    public static void Main(string[] args)
    {

        OracleConnection cn = new OracleConnection("your connection string here");

        string sql = "INSERT INTO testtable(testname) VALUES('testing2') RETURNING id INTO :LASTID";
        OracleParameter lastId = new OracleParameter(":LASTID", OracleDbType.Int32);

        lastId.Direction = ParameterDirection.Output;

        using (OracleCommand cmd = new OracleCommand(sql, cn))
        {
            cn.Open();
            cmd.Parameters.Add(lastId);
            cmd.ExecuteNonQuery();
            Console.WriteLine("Last ID: " + lastId.Value.ToString());
            cn.Close();
        }
        Console.WriteLine();
        Console.ReadKey(false);

    }
}
}

A: insert ... returning.
declare
   s2 number;
 begin
   insert into seqtest2(x) values ('aaa') returning seq into s2;
   dbms_output.put_line(s2);
 end;

"seq" here refers to the name of the column whose value you want to store into variable s2.
in python:
myseq=curs.var(cx_Oracle.NUMBER)
curs.prepare("insert into seqtest2(x) values('bbb') returning seq into :x")
curs.execute(None, x=myseq)
print int(myseq.getvalue())


text:
Q: Any way to restrict properties which can be used in an odata filter? Does anyone know of a way to restrict the properties which can be used in an OData query?
The documentation shows how to implement a FilterQueryValidator: https://learn.microsoft.com/en-us/odata/webapi/odata-security
I can't find any documentation which describes how you'd actually use this validator.
Anyone else have any experience with this?

A: When creating your EDM model, add a restriction to the property you don't want someone filtering on.
var employee = builder.EntitySet<Employee>("Employees").EntityType;
employee.Property(e => e.FirstName).IsNotFilterable();

There are similar methods to restrict expanding, sorting, counting, and navigating.

A: You can use $select to allow the clients to select specific properties from the server:
$select=

Attach it to your url, like
http://****/odata/Customers?$select=property1,Property2.....

You can check the results:

More details, you can check this tutorial:
$select Enhancement in ASP.NET Core OData


text:
Q: (C++) How do you generate a seven digit number, whose digits, when added together, equal to a multiple of seven? I know this sounds like a very specific question, but I am making a key generator for a program, and one part of the key has seven digits that need to be a multiple of seven when added together. How do you achieve this?

A: Generate a random 6-digit number then choose the number for the 7th digit that makes the algorithm work.
See any example of how to use std::rand for generating the random digits.

A: Once you have generated the 7 numbers for the key. You could than try a %7.
If the result is 0, than it mean that your number generated is a multiple of 7.
If the result is not 0, than you just have to regenerate another key or add 1 to the last number until modulo 7 (%7) equal 0.


text:
Q: Split string into substring over '\n' in Python I am reading string extracts of a long DNA data file in Python. Some string extracts run over a new line in the .txt file. Python prints these string extracts with the '\n' character in the string.

My problem is that I don't know how to detect substrings that fall on either side of the newline character '\n'.
IE: in the code below, 'gca' is found, but 'taa' is not. What's the proper solution to this?
l = 'gcaacacgactta\naccaagctgt'

for i in range(0, len(l), 3):

    if l[i:i+3] == 'taa':
        print(l[i:i+3])

    elif l[i:i+3] == 'gca':
        print((l[i:i+3]))

>>>gca

EDIT: I intended to search for 'aac' and not 'taa'. Regardless, .replace() works. Thanks guys!

A: 1) Replace the '\n' to ""
2) Change range(0, len(l), 3) to range(len(l)-3),
l = 'gcaacacgactta\naccaagctgt'

l=l.replace("\n","")

for i in range(len(l)-3):

    if l[i:i+3] == 'aac':
        print(l[i:i+3])

    elif l[i:i+3] == 'gca':
        print((l[i:i+3]))

A: You are iterating every 3 characters, in this case: gca aca cga ctt aac caa gct gt. You cannot find taa because it is not in one of the above elements. To have both gca and taa you can do so:
l = 'gcaacacgactta\naccaagctgt'
l = l.replace("\n","")

for i in range(len(l)):

    if l[i:i+3] == 'taa':
        print(l[i:i+3])

    elif l[i:i+3] == 'gca':
        print((l[i:i+3]))

Output:
gca
taa

Edit
If you want gca and aac, and all your sequence is in triple, just replace is enough and this is will be output:
gca
aac

A: I hope this may help
l = 'gcaacacgactta\nataaccaagctgt'
l=l.replace("\n","")
taa_index=l.find('taa')
while(True):
    print(l[taa_index:taa_index+3])
    p=(l[taa_index+3:]).find('taa')
    if p!=-1:
        taa_index = p+taa_index+3
    else:
        break

Similarly you can do for 'gca'. Now this would work for multiple 'taa'


text:
Q: Custom JSON deserialization only if certain field is present (using Jackson) When deserializing MyEntity (which is an interface) I either have

*

*the following input:
{ "id": 123 }

in which case I would like to deserialize it into a
new MyEntityRef(123)

*or I have the following input:
{
    "id": 123,
    "message": "Hello world",
    "otherEntity": {
        "field": "value",
        ...
    }
}

in which case I would like to deserialize it as
new MyEntityImpl(123, "Hello world", otherEntity);

where otherEntity is deserialized the same way as if it was found outside the context of MyEntity.
I've figured out how to register my own custom deserializer through a SimpleModule but I don't know how to

*

*Choose a custom deserializer based on the presense of some field (such as message above).

*Fallback on the "default" serializer for certain fields (such as otherEntity above).

A: Finally solved it by configuring my ObjectMapper as follows:
ObjectMapper mapper = new ObjectMapper();

SimpleModule idAsRefModule = new SimpleModule("ID-to-ref",
                                              new Version(1, 0, 0, null));

idAsRefModule.addDeserializer(TestEntity.class,
                              new JsonDeserializer<TestEntity>() {
    @Override
    public TestEntity deserialize(JsonParser jp, DeserializationContext dc)
            throws IOException, JsonProcessingException {

        ObjectCodec codec = jp.getCodec();
        JsonNode node = codec.readTree(jp);
        boolean isFullImpl = node.has("message");
        Class<? extends TestEntity> cls = isFullImpl ? TestEntityImpl.class
                                                     : TestEntityRef.class;
        return codec.treeToValue(node, cls);
    }
});

mapper.registerModule(idAsRefModule);

return mapper;


text:
Q: Add new Table in sqlite database I have an question.
I have only one table in my database
@Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL( "CREATE TABLE books (_id INTEGER PRIMARY KEY AUTOINCREMENT,title TEXT, author TEXT,isbn TEXT,city TEXT);");
        Log.v("onCreate-------","called onCreate");

    }

here:-
sqlite> select * from books;

also working fine.
but i want to add new table so i am trying to add here :-
@Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        android.util.Log.w("books",
        "Upgrading database, which will destroy all old data");

        //db.execSQL("ALTER TABLE myallbooks ADD COLUMN city2");
        db.execSQL("CREATE TABLE myfields (author TEXT,isbn TEXT,city TEXT);");

        Log.v("onUpgrade-------","called onUpgrade with alter");
    }

after changing the version number i run the app but i did not found the table any where.

sqlite> select * from myfields;

Error:-no such table :myfield...................why it is not creating

A: onUpgrade() will be called when you have Database version changes to Higher version. It looks like you are not increasing the version and trying to select the columns of myfields table.
Please check whether you are updated the version number to a higher number compared to earlier one.

A: @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL( "CREATE TABLE books (_id INTEGER PRIMARY KEY AUTOINCREMENT,title TEXT, author TEXT,isbn TEXT,city TEXT);");
        Log.v("onCreate-------","called onCreate");

   db.execSQL("CREATE TABLE myfields (author TEXT,isbn TEXT,city TEXT);");

    }

@Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        android.util.Log.w("books",
        "Upgrading database, which will destroy all old data");

        //db.execSQL("ALTER TABLE myallbooks ADD COLUMN city2");
       // db.execSQL("CREATE TABLE myfields (author TEXT,isbn TEXT,city TEXT);");

          //delete tables
                db.execSQL("DROP TABLE IF EXISTS books");
          // Create tables again`enter code here`
        onCreate(db);

        Log.v("onUpgrade-------","called onUpgrade with alter");
    }


text:
Q: Core data not saving my data I'm using core data to save some integer (rate) and then I call save in the context:
HeartRateBeat * beat = [HeartRateBeat heartRateWithHeartRate:rate
                            ofRecordTitle:self.recordTitle
                   inManagedObjectContext:document.managedObjectContext];

NSError * error;
[document.managedObjectContext save:&error];

Inside that convenient method I create the object using NSEntityDescription like this:
heartRateBeat = [NSEntityDescription insertNewObjectForEntityForName:@"HeartRateBeat" inManagedObjectContext:context];

(I only copied some important code, just to show what I did.)
I immediately execute a fetch request after every single heart beat inserted and managed object context saved (I save immediately), and the request shows that heart beat does appear to be stored inside Core Data (with growing array of heart beats), but if I restart my app (I'm using simulator BTW) I know things aren't actually getting saved to disk because it starts anew. Checking with SQLite3 command line shows empty tables. What am I missing here?

A: I get the same problem but I think its just because, I assume, like me you are just stopping the app through xcode and not actually closing it down. I use this code to force a write. Im using a UIManagedDocument, shared through appdelegate, rather than setting everything up manually.
NSError *error = nil;

if (![self.managedObjectContext save:&error]) {
    NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
    abort();
}

[[AppDelegate sharedAppDelegate].userDatabase saveToURL:[AppDelegate sharedAppDelegate].userDatabase.fileURL forSaveOperation:UIDocumentSaveForOverwriting completionHandler:nil];

A: I don't know about you guys, but when I want my Core Data to save, my Core Data better save.
Here's some code that will for sure save all of your Core Datas.
-(void)forceSave {
        NSManagedObjectContext * context = self.managedObjectContext; //Get your context here.
    if (!context) {
        NSLog(@"NO CONTEXT!");
        return;
    }

    NSError * error;
    BOOL success = [context save:&error];
    if (error || !success) {
        NSLog(@"success: %@ - error: %@", success ? @"true" : @"false", error);
    }

    [context performSelectorOnMainThread:@selector(save:) withObject:nil waitUntilDone:YES];
    [context performSelector:@selector(save:) withObject:nil afterDelay:1.0];
    [context setStalenessInterval:6.0];
    while (context) {
        [context performBlock:^(){
            NSError * error;
            bool success =  [context save:&error];
            if (error || !success)
                NSLog(@"success: %@ - error: %@", success ? @"true" : @"false", error);

        }];
        context = context.parentContext;
    }

    NSLog(@"successful save!");

}

Note that this is BAD CODE. Among other problems, it's not thread-safe and takes too long. However, try using this and deleting some parts of it to your satisfaction :)


text:
Q: how to load images from excel to datagridview I want to load images in the datagridview, but so far I am getting only text.
CODE
private void button1_Click(object sender, EventArgs e)
        {
            String name = "LOTUS";
            OleDbConnection con = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Users\\xy\\Downloads\\SCA.xls;Extended Properties='Excel 8.0;HDR=YES;IMEX=1;';");

            OleDbCommand oconn = new OleDbCommand("Select * From [" + name + "$]", con);
            con.Open();

            OleDbDataAdapter sda = new OleDbDataAdapter(oconn);
            DataTable data = new DataTable();
            sda.Fill(data);
            dataGridView1.DataSource = data;
        }

A: From this Blog, there is a Solution with the Clipboard.
Something like this way:
string shapeName = "";

for (int i = 0; i < sheet.Shapes.Count;i++ )
{
   Microsoft.Office.Interop.Excel.Shape shape=sheet.Shapes.Item(i);
   if (shape.Type == MsoShapeType.msoPicture)
   {
      shapeName = shape.Name;
   }
}

Worksheet sheet = GetFirstSheet();
if (sheet != null)
{
    Picture pict = sheet.Pictures(shapeName ) as Picture;
    pict.CopyPicture(XlPictureAppearance.xlScreen, XlCopyPictureFormat.xlBitmap);
}

if (Clipboard.ContainsImage())
{
   Image img=Clipboard.GetImage();
   pbPicture.Image = img;
}


text:
Q: at least one class field is not null I've a class:
public class A
{
   public string field1 {get;set;}
   public string field2 {get;set;}
}

I want to check if at least one property is not null.
How to do this?
Thanks.

A: Reflection can help you:
A myInstance = new A();
Type myType = myInstance.GetType();
if (myType.GetProperties(BindingFlags.Public | BindingFlags.NonPublic |
                            BindingFlags.Static | BindingFlags.Instance)
   .Any(property => propoerty.CanRead && property.GetValue(myInstance, null) != null))
{ /* something is not null in myInstance */}

Doesn't matter how many properties your class have.
Note: as comments pointed out, this won't check non-public and set-only properties would blow it up. Code has been tweaked.

A: It can be 1 line.. like this:
if (instanceOfA.field1 != null || instanceOfA.field2 != null)

..in fact, for strings, it might be best to test like this:
if (string.IsNullOrEmpty(instanceOfA.field1) ||
    string.IsNullOrEmpty(instanceOfA.field2))

A: if(obj.field1 != null || obj.field2 != null)


text:
Q: Microsoft Natural Ergonomic Keyboard 4000 favorite keys don't work This is a problem that emerged a few months ago and couldn't find a solution for, the favorite keys do not work anymore in their normal use.
By normal use, I mean pressing the key to open the program in task bar; if you hold the key to show pinned items or hold Shift to start the program as administrator, they all work.
So it is definitely not a hardware issue, the keys are all working.
Here's a screenshot showing the faulty keys in blue:

I have tried the following without success:

*

*un-install, reboot and re-install the software

*disable all startup programs to see if any are conflicting

*fresh install of Windows 10 (April update)

By looking at mskey.exe, there is definitely something wrong as Ctrl is being emitted by the key, obviously this won't work even when tried for real:

Has anyone experienced the same issue and found a fix for it ?

A: EDIT
Microsoft® Mouse and Keyboard Center 10.4 finally solves the problem !!!

I ultimately ended up with five AutoHotKey scripts that work rather well. I've lost the functionality of pinned items but since they require both hands for selection, I guess it's okay to press an extra key with the hand.
The most important part is working and that's a good thing, because switching hundreds of time per day to different programming software, you can imagine that typing thrice as much keys is extremely boring to say the least.
For ones who might have the same issue, here's the first script:
#SingleInstance force

SendInput {LWin up}{Alt up}{1 up}{2 up}{3 up}{4 up}{5 up}
Sleep 100

SendInput {LWin down}{1 down}
Sleep 100
SendInput {1 up}{LWin up}

return

Change the last block key for the four other scripts, compile as EXE with Ahk2Exe and you're set !
Edit:
After trying to track down the cause of the problem, to me, Windows Version 1709 (Fall Creators Update) has introduced a regression inducing this problem. It is roughly at this time that I've started encountering this problem (I do install updates as soon as they become available).
Tried on Windows 7 and they effectively work as expected, one mystery though, the Ctrl key is also emitted but seems to not be ignored anymore on a recent Windows 10 version, therefore causing these keys to fail.


text:
Q: OpenShift use import-image to result into custom image tag I'm trying to import image from docker repository and tag it with custom tag. Found a command import-image but it results image with tag latest
(example command: oc import-image docker-repo --from=target-image-with-tag --confirm=true)
Is there other oc commands I could use in this case?

A: The usage for oc import-image is documented as follows:
oc import-image IMAGESTREAM[:TAG] [flags]

As you do not specify a tag for the ImageStream, "latest" is used. So try something like:
oc import-image docker-repo:mytag --from=target-image-with-tag --confirm=true


text:
Q: Selenium: Click on element in div container doesn't work Fyi: I'm using the selenium package for R, the selection code is equal to javascript or python so I'm asking a general selenium question.
I have a container which I have to make visible by a click, this works.
Then I try to select an element inside this container, I think I find it correctly but the click on the element only makes the popup window disappear.
Example code:

Benutzerdefinierter Zeitraum

Heute

...

Element I try to find is "top dateOption CUSTOM".
My different tries which all failed:
remDr$findElement(using = 'xpath','//a[contains(@class,"top")]')$clickElement()

remDr$findElement(value = '//a[@class = "top dateOption CUSTOM"]')$clickElement()

remDr$findElements(using = 'css selector','a[class="top dateOption CUSTOM"]')[[1]]$clickElement()

I don't get any error message, the click seems to happen as the popup disappears, but the effect of the button does not.
I tried to save the object, wait a few seconds and click afterwards with no different effect.
I also tried different approaches with "idc4" with the same outcome.
Would appreciate any help, thank you.


text:
Q: get height from the highest div and apply it to others Basically
i have few divs with flexible height and fixed paddings so its being pretty difficult to have them all with same height,
i am trying like this:
$(document).ready(function(){
    $('.LevelCnt_2,.LevelCnt_2 .content,.LevelCnt_1,.LevelCnt_1 .content').outerHeight( $('header:eq(0)').outerHeight() );

    console.log($('header:eq(0)').outerHeight(true));
});

But the problem is that header is not allways the highest, so i need to

*

*check wich one is higher (considering that there are more than one .content elements)

*apply outerHeight
to all of them
but i can't find a good/beautifull way (have one solution but i need to many if's and variables) to do this
any clue?
-EDIT-
while waiting i came up with this
$(document).ready(function(){

    var height = 0;
    $('.LevelCnt_2,.LevelCnt_2 .content,.LevelCnt_1,.LevelCnt_1 .content,header').each(function(){
         if($(this).outerHeight() > height){
            height = $(this).outerHeight();
         }
    });
    $('.LevelCnt_2,.LevelCnt_2 .content,.LevelCnt_1,.LevelCnt_1 .content,header').each(function(){

             $(this).outerHeight(height);

    });

    console.log('highest height is '+height); //it doesn't output the highest value
});

but the most of those divs are in display:none is that the problem?

A: Instead of adding display none, give them the class "hide" and use this.
$(function(){
    var height = 0;
    $('.hide').show();
    $('header').each(function(){
        height = Math.max( height, $(this).outerHeight() )
    });
    $('.hide').hide();
    $('.LevelCnt_2,.LevelCnt_2 .content,.LevelCnt_1,.LevelCnt_1 .content').outerHeight(height);
    console.log($('header:eq(0)').outerHeight(true));
});

A: Bit late to the game, but you could use an array:
var arr = $.makeArray()
$('div').each(function(){
    arr.push($(this).outerHeight());
});
$('div').css('height', Math.max.apply( Math, arr ));
console.log('highest height is '+Math.max.apply( Math, arr ));

Check out my example - http://jsfiddle.net/ZhG2S/

A: Try this:
$(document).ready(function(){
    var headerHeight = getTallestHeaderHeight()
    $('.LevelCnt_2,.LevelCnt_2 .content,.LevelCnt_1,.LevelCnt_1 .content').outerHeight(headerHeight);

    console.log(headerHeight);
});

function getTallestHeaderHeight() {
    var maxHeight = 0;
    $("HEADER").each(function() {
        if ($(this).outerHeight() > maxHeight)
            maxHeight = $(this).outerHeight()
    })

    return maxHeight;
}


text:
Q: How to show a popup when the checkbox is ticked in Magento using ajax Just needed to add a popup modal when the checkbox is ticked and post the values to the controller.

A: this is the code which open the popup modal on the view button click you can change it according to your checkbox.

    Pop up Stuff

<button id="button">
    <?= $block->escapeHtml(__('View')) ?>
</button>


text:
Q: WSUS SUSDB SQL processes blocking during reset I've hunted high and low over the years about WSUS and all anyone says is it is slow when doing things like a reset and there's no way to gauge progress, stop it (without the update to singleton data) and so on.
My own WSUS has always had major SQL blocking issues whenever I reset it.
Digging deeper, the SQL server appears to be seriously struggling with process blocking see pic.
When you look at what is causing the blocking, it is a variety of CREATE PROC statements with the ChildEulas one being a major culprit.
So is it that the reason resets are soooooo slow is that the reset is having to drop/re-create the stored procedures for each and every update in the DB and throwing in blocking makes it absolutely ridiculous.
Can we re-write the reset routine to stop it dropping/creating the stored procs and make it lightning fast?
I tried killing the blocking process whenever it was a create proc statement (as the proc was already actually still there, presumably in a transaction) but it keeps halting the WSUS service altogether.


text:
Q: SQLite: Using MAX of GROUP BY averages to compute percentage of all the other averages relative to that MAX I have four groups of people, and they each have an average for a given metric. The following query would yield four values, one for each group.
SELECT group, AVG(metric) AS 'avg_metric'
FROM table
GROUP BY group

Now one of those averages will be the max. I want to also capture the avg_metric / MAX(avg_metric) in my SELECT statement. Since I can't use MAX and AVG(MAX...) in the same query, I thought something like this would work:
SELECT group, (100 * sub.avg_metric / MAX(sub.avg_metric)) AS 'percentage'
FROM table
JOIN (SELECT AVG(metric) AS 'avg_metric'
      FROM table
      GROUP BY group
      ON table.group = sub.group) AS sub

Unfortunately, I can't seem to get the syntax right. (I'm using SQLite.) Additionally, it would be much nicer to have
GROUP       AVG_METRIC     PERCENTAGE
group 1      57               45
group 2 ....

In that order, but I don't see how to do that either.


text:
Q: PHP: echo number of duplicates in a table by most common I am trying to echo the most common duplicates in a table. I have been able to echo the name of the duplicates but what I'm looking for is a separate column in the table that shows how many times the duplicate occurs. Is there a way of echoing the COUNT(*) value? Also a way of organizing the values by size would be helpful.
My php:
$interests = "SELECT name, COUNT(*) FROM pageinterests WHERE pageid = '$id' GROUP BY name HAVING COUNT(*) > 1";
$interestresults = mysqli_query($conn, $interests);

My html:

Interests

                            <?php
                                if(mysqli_num_rows($interestresults) > 0){
                                    $rim = mysqli_num_rows($interestresults);
                                    echo "

                                       Name

'";

                                    for($x = 1; $x <= $rim; $x++){
                                        $rat = mysqli_fetch_assoc($interestresults);
                                        echo "

                                            ".$rat['name']."

";

                                    }

                                    echo '

                                      ';
                                }else{
                                    echo " There doesn't seem to be any common interests yet";
                                }
                            ?>

A: Use an alias  and order by for correct count sequence
    $interests = "SELECT name, COUNT(*) AS my_count
          FROM pageinterests
          WHERE pageid = '$id'
          GROUP BY name HAVING COUNT(*) > 1
          ORDER BY my_count";

    .......

   for($x = 1; $x <= $rim; $x++){
       $rat = mysqli_fetch_assoc($interestresults);
       echo "

        ".$rat['name']."
        ".$rat['my_count']."

";

    }

A: You could use an alias like this:
SELECT name, COUNT() as The_Count
FROM pageinterests
WHERE pageid = '$id'
GROUP BY name HAVING COUNT() > 1
ORDER BY The_Count DESC;

A: SELECT name, COUNT(*) as mycount FROM ...

A: you need to use an alias for count(*).Then you can use it for order and echo.
$interests = "SELECT name, COUNT(*) as count_alias FROM pageinterests WHERE pageid = '$id' GROUP BY name HAVING COUNT(*) > 1 ORDER BY count_alias DESC";


text:
Q: How to return an existing object with FactoryGirl For the sake of example, I have a model for chemical elements
class Element < ActiveRecord::Base
  validates :name, presence: true, uniqueness: true
  validates :symbol, presence: true, uniqueness: true
end

In seeds.rb I define all the known elements
Element.where(name: "hydrogen" symbol: "H").first_or_create
...
Element.where(name: "ununoctium" symbol: "Uuo").first_or_create

I define a factory
FactoryGirl.define do
  factory :element do
    name "hydrogen"
    symbol "H"
  end
end

Since the codebease depends on the presence of all seed elements, I prepare the test database with
rake db:seed RAILS_ENV=test

Now my factory will never work
FactoryGirl.create(:element) #=> validation failed error

How do I write a factory in a way that first tries to find the creatable object in the database?
FactoryGirl.create(:element) #=> returns Element from db || Factory invocation

A: For sake of posterity, answering my own question with half a decade of experience under the belt.
Try using FactoryBot's initialize_with hook as described in docs.
factory :element do
  initialize_with do
    where(name: name, symbol: symbol).first_or_initialize
  end

  name "hydrogen"
  symbol "H"
end

A spin on the idea is to forego the general factory and only have named factories for countable, uniqueness-constrained resources like chemical elements:
factory :element_hydrogen do
  initialize_with do
    where(name: "hydrogen", symbol: "H").first_or_initialize
  end
end

A: Why not doing this:
element = Element.find_by(name: "hydrogen") || FactoryGirl.create(:element, name: "hydrogen", symbol: "H")


text:
Q: How to change jquery parameter with a submit form? I am a newbie at jQuery. I was trying some things but I need some help.
I have the following script
jQuery(function($){
        $("#query").whatever({
          parameter1: 32,
          parameter2: 4,
          query: "something"
        });
      });

I need a script to change query: "something" to query: "something else" by a submit form. Is it possible?
ps: i change $("#query").something to $("#query").whatever to dont confused with the parameter query: "something"
Actualy i use jquery code from http://tweet.seaofclouds.com/ I want to change the "query" parameter in example 2 as i told before, by a submit form.

A: take a look at : http://api.jquery.com/jQuery.extend/
with a form :
    <form>
        <input name="newvalue" id="newvalue" type="text"/>
        <input type="button" id="onclickUpdate" value="update" name="update"/>
    </form>
    <script>
        var obj = {
            parameter1 : 32,
            parameter2 : 4,
            query : "something"
        };
        $(function() {
            $('#onclickUpdate').click(function(e) {
                e.preventDefault();
                console.log('old : ' + obj.query);
                $.extend(obj, {
                    query : $('#newvalue').val()
                });
                console.log('new : ' + obj.query);
                $("#query").something(obj);
            });
        });
    </script>

A: Well, suppose you are using $.ajax() to submit the form. While submitting the form, you might pass 3 to 4 keys as well as their values as data, right? In one of these key-pair values, you want a default value, so instead of building a hash from scratch, start with the default one, add to it the other ones you want to send:
initdata = {query:"something-else"}; //not needed if you don't include the "query" key while populating tobesent
tobesent = {}; //may be through serializing a form through serializeArray or something
tobesent = $.extend(tobesent,initdata);
$.ajax({
url : "foo.php",
data: tobesent,success: function() {}
});

Is this what you were looking for?

A: Yeah, enclose the options as a dictionary, and preset the query key with the value something else, and pass the options dictionary as the parameter to be passed.


text:
Q: Adjusting height in scrollView I created scrollView contains multiple surfaces, i'd like them to be aligned under each other without declaring static height for them as "fa-size="[undefined, 100]", the app is resizeable on different mobile devices (that's why i made the width "undefined"), so the true parameter in fa-size should do, but unfortunately it doesn't work.
code:
     <fa-app  style="height:570px;" >
        <fa-scroll-view  fa-pipe-from="eventHandler"
                fa-options="options.myScrollView">

        <fa-modifier  fa-size="[undefined,true]">
          <fa-surface fa-pipe-to="eventHandler" >

Content1

          </fa-surface>
        </fa-modifier>

        <fa-modifier  fa-size="[undefined,true]">
          <fa-surface fa-pipe-to="eventHandler" >

Content2

          </fa-surface>
        </fa-modifier>

       </fa-scroll-view>
     </fa-app>

that's the result :

I made another approach, i created on surface contains all the divs contents and the "fa-size="[undefined, undefined]"" in order to show all the contents contained and under each other smoothly, they're relative to each other now but the height overflows at the end of the scrollView, height as "true" should make this work fine but it doesn't work too.
code :
     <fa-app  style="height:570px;" >
        <fa-scroll-view  fa-pipe-from="eventHandler"
                 fa-options="options.myScrollView">

        <fa-modifier  fa-size="[undefined,undefined]">
          <fa-surface fa-pipe-to="eventHandler" >

Content1

Content2

          </fa-surface>
        </fa-modifier>

        </fa-scroll-view>
     </fa-app>

Note : I tried to change the clipSize and using sequentialLayout but still the same.

A: They're overlapping because you need to apply Translate to each surface you want moved


text:
Q: Custom: My Printer This is the link of the Bluetooth mobile printer i used for Printing

Does anyone here tried it implementing it in the Android Application? I already using it right now but im having problem with the Printing font Sizes.

Here's my code from the SDK.
//Fill class: LEFT X2
            fntPrinterX2NormalLeft.setCharHeight(PrinterFont.FONT_SIZE_X1);                 //Height x1
            fntPrinterX2NormalLeft.setCharWidth(PrinterFont.FONT_SIZE_X1);                  //Width x1
            fntPrinterX2NormalLeft.setEmphasized(false);                                        //No Bold
            fntPrinterX2NormalLeft.setItalic(false);                                            //No Italic
            fntPrinterX2NormalLeft.setUnderline(false);                                     //No Underline
            fntPrinterX2NormalLeft.setJustification(PrinterFont.FONT_JUSTIFICATION_LEFT);
            fntPrinterX2NormalLeft.setInternationalCharSet(PrinterFont.FONT_CS_DEFAULT);        //Default International Chars

The PrinterFont.FONT_SIZE_X1 is large as the default and the maximum size is up to FONT_SIZE_X8.
Could anyone tell me the limit of the size of printing, or this size was the default?
Is there anyone here from the Custom Printer?
Their SDK has lack of information.. Not like Bixolon Printer It's detailed and Informative..


text:
Q: Figuring out Mechanics of How Chain Rule was Applied How do I go from system $(1)$ to system $(2)$ below?
\begin{gather}
\begin{aligned}
S &= K e^{x}\\[7pt]
V(S,t) &= K v(x, \tau)\\
\tau &= (T-t) \frac{\sigma^{2}}{2}
\end{aligned}\tag{1}
\end{gather}
\begin{gather}
\begin{aligned}
\frac{d}{dt}V &= -K \frac{\sigma^{2}}{2} \frac{d}{d \tau} v\\
\frac{d}{dS}V &= \frac{K}{S} \frac{d}{dx} v
\end{aligned}\tag{2}
\end{gather}

A: Let's start with the first one:
$$V(S,t) = K v(x, \tau).\tag{1}$$
Differentiating each side, using the chain rule:
$$
\frac{d}{dt}V(S,t) = \frac{d}{dt}Kv(x,\tau)= K\frac{dv}{d\tau}(x,\tau)\cdot\frac{d\tau}{dt}(t).\tag{2}\\
$$
Note that $x$ does not depend on $t$, which is why we only have to consider $\frac{dv}{d\tau}$ above.  Now, using $$\tau= (T-t) \frac{\sigma^{2}}{2}$$ we can obtain $$\frac{d\tau}{dt} = -\frac{\sigma^{2}}{2},$$ and so $(2)$ becomes $$\boxed{\frac{d}{dt}V(S,t) = -K\frac{\sigma^{2}}{2}\frac{dv}{d\tau}(v,\tau).}$$
For the second, we differentiate $(1)$ with respect to $S$, again using the chain rule.  This time we only have to consider $\frac{dv}{dS}$ because $\tau$ does not depend on $S$.
$$\frac{d}{dS}V(S,t) = \frac{d}{dS}Kv(x,\tau) = K\frac{dv}{dx}(x,\tau)\cdot \frac{dx}{dS}(S).\tag{3}$$  Now, to compute $\frac{dx}{dS}$ we differentiate implicitly:
\begin{align}
S &= Ke^{x}\\
1 &= Ke^{x}\frac{dx}{dS}\\
\end{align}
Solving for $\frac{dx}{dS}$, making using of $S = Ke^{x}$, we get $$\frac{dx}{dS} = \frac{1}{Ke^{x}}=\frac{1}{S}.\tag{4}$$  Plugging $(4)$ into $(3)$ gives us $$\boxed{\frac{d}{dS}V(S,t) = \frac{K}{S}\frac{dv}{dx}(x,\tau).}$$


text:
Q: Animated Ios Splash screen I'm trying to make my splash screen display 3 images after each other.
Ive tried multiple things but keep running into errors if anyone could see what i'm doing wrong in my code here?
@interface CydiaLoadingViewController : UIViewController
@end

%hook CydiaLoadingViewController
-(void)loadView {
%orig;
UIView *xiView = [[UIView alloc]initWithFrame:[UIScreen mainScreen].bounds];
xiView.backgroundColor = [UIColor whiteColor];
UIImage *image1 = [UIImage imageNamed:@"image1.png"];
UIImage *image2 = [UIImage imageNamed:@"image2.png"];
UIImage *image3 = [UIImage imageNamed:@"image3.png"];
UIImageView *logo =[[NSArray alloc] initWithObjects:image1,image2,image3, nil];
logo.imageView.animationRepeatCount = 7;
[logo.imageView startAnimating];
logo.frame = CGRectMake([UIScreen mainScreen].bounds.size.width / 2 - 60, [UIScreen mainScreen].bounds.size.height / 2 - 90, 120, 120);
logo.layer.masksToBounds = YES;
logo.layer.cornerRadius = 10;
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, [UIScreen mainScreen].bounds.size.height / 2 + 60, [UIScreen mainScreen].bounds.size.width, 40)];
label.text = @"Cydia";
label.textAlignment = NSTextAlignmentCenter;
[label setFont:[UIFont boldSystemFontOfSize:30]];\
[xiView addSubview:logo];
[xiView addSubview:label];
[[self view] addSubview:xiView];
}

-(BOOL)hidesNavigationBar {
    return YES;
}
%end

the error
Tweak.xm:92:14: error: cannot initialize a variable of type 'UIImageView *' with an
      rvalue of type 'NSArray *'
UIImageView *logo =[[NSArray alloc] initWithObjects:image1,image2,image3, nil];

A: The error is because you assigned an instance of NSArray to an UIImageView variable at this line.
UIImageView *logo =[[NSArray alloc] initWithObjects:image1,image2,image3, nil];

As I understand, you want to use UIImageView to present these 3 images one by one. In this case, you should create UIImageView normally and use UIImageView's animationImages property.
For example
UIImageView *logo = [[UIImageView alloc] init];
logo.animationImages = [[NSArray alloc] initWithObjects:image1,image2,image3, nil];


text:
Q: Is it legal to define a piecewise define a function like this? I'm trying to piecewise define a function $h$ using two other functions $f$ and $g$. I want to use $h$ to draw conclusions on a certain set $T$ that's a union of two other sets $A$ & $B$.
$ h(n_z) = \begin{cases} f(n_z), & \mbox{if } f(n_z) \in A \wedge f(n_z) \notin B \wedge g(n_z) \notin A \\ g(n_z), & \mbox{if } g(n_z) \in B \wedge g(n_z) \notin A \wedge f(n_z) \notin B \\ f(n_z), & \mbox{if } f(n_z) \in A \wedge \exists n_y \in \mathbb N, g(n_y) \in B \end{cases} $
My question is, is it legal to do such a definition? Keep in mind that I've already defined $f$ & $g$ in the proof I'm doing and I'm not simply pulling them out of thin air.

A: Such an definition is legal, or - how it's usually called - well-defined, if

*

*the cases do not overlap

*each possible condition is regarded by one of the cases

In other words, for each possible state, exactly one of the conditions must be fulfilled.

It is difficult to evalute this in this case, as we don't know the context. It seems, that the case $f(n_z)\notin A, g(n_z)\notin B$ is not considered, but maybe this case does not occur?


text:
Q: AVPlayerLayer blank after entering background while being in a hidden controller and entering foreground and being shown I have an App in which I use AVPlayerLayer (used within a subclass of UIView just like Apples  AV Foundation Programming Guide). Ihave a couple of view controllers witch are held in the View Controller that is resonsible for the menu (JASidePanels are used). The problem is as follows:
Everything works ok until the view controller with the AVPlayers does'nt get hidden (some other view is presented) and the the app enters background, gets back again and returns to the view. This Causes the AVPlayerLayer to display blank/transparent. The item is loaded as well as i can try playing it and indeed it is played but no video is seen.
What is the solution to this behaviour (and what is the cause of it)? Thx in advance.

A: player?.seek(to: .zero) triggers AVPlayerLayer to render preview.
To smoothly update and pause the video on closing/opening the app in my case I've added the following:
private func setupObservers() {
    NotificationCenter.default.addObserver(self, selector: #selector(willResignActive), name: UIApplication.willResignActiveNotification, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(didBecomeActive), name: UIApplication.didBecomeActiveNotification, object: nil)
}

@objc
private func willResignActive() {
    player?.pause()
}

@objc
private func didBecomeActive() {
    player?.seek(to: .zero)
}

A: I'm not sure what causes it but a solution that worked for me was to reset the player on the AVPlayerLayer
   avPlayerLayer = AVPlayerLayer(player: currentAvPlayer)

A: SWIFT 3
I had the same problem. Each time my app went into the background and then back into the foreground, my AVPlayer would disappear. Below is a simpler version of the code that works for me ... I needed to reset the player on UIApplicationWillEnterForeground. I can add more code if you need it, just let me know. It seems to be working for now. Cheers!
import UIKit
import AVFoundation

class ViewController: UIViewController {

    var avPlayer: AVPlayer!
    var avPlayerLayer: AVPlayerLayer!
    var paused: Bool = false

    override func viewDidLoad() {
        super.viewDidLoad()

        // Be sure to add your file to your app (not in the assets folder) and add it to your target
        let theURL = Bundle.main.url(forResource:"yourVideoFile", withExtension: "mp4")

        avPlayer = AVPlayer(url: theURL!)
        avPlayerLayer = AVPlayerLayer(player: avPlayer)

        avPlayerLayer.frame = view.layer.bounds
        avPlayerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill

        // .none is for looping videos if you uncomment "p: AVPlayerItem" below.
        // .pause is to pause at the end of the video and hold the last frame
        avPlayer.actionAtItemEnd = .pause
        view.layer.insertSublayer(avPlayerLayer, at: 0)

        NotificationCenter.default.addObserver(self, selector: #selector(playerItemDidReachEnd(notification:)), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime,object: avPlayer.currentItem)

        NotificationCenter.default.addObserver(self, selector: #selector(appMovingToForeground), name: Notification.Name.UIApplicationWillEnterForeground, object: nil)

    }

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        avPlayer.play()
        paused = false
    }

    func playerItemDidReachEnd(notification: Notification) {
        print("THE END")

        // uncomment the following line for a looping video
        // let p: AVPlayerItem = notification.object as! AVPlayerItem
        // p.seek(to: kCMTimeZero)

    }

    func appMovingToForeground() {
        print("App moved to foreground!")
        avPlayerLayer = AVPlayerLayer(player: avPlayer)
        view.layer.insertSublayer(avPlayerLayer, at: 0)

        // If you want your video or video loop to continue playing when app moves to foreground add:
        // avPlayer.play()
        // paused = false

    }

}

A: Finally I just went with reloading the video file in the player.


text:
Q: Var(S) = E(Var(S|T)) + Var(E(S|T)) Let $S$ and $T$ be any statistics.
Given that $\mathsf {Var}(S)$ is finite, prove that
$$\mathsf {Var}(S) = \mathsf {E}(\mathsf {Var}(S\mid T)) + \mathsf {Var}(\mathsf {E}(S\mid T))$$
Any hints?   Suggestions?

A: Note that $Var(X|Y)=E((X-E(X|Y))^2|Y)=E(X^2|Y)-E(X|Y)^2$, $Var(X)=E((X-E(X))^2)=E(X^2)-E(X)^2$ and $E(E(X|Y))=E(X)$.

A: To begin: use the definition of variance, and the Law of Iterated Expectation.
$$\begin{align}\mathsf {Var}(S) =&~ \mathsf E(S^2)-\mathsf {E}(S)^2\\ =&~\mathsf E(\mathsf E(S^2\mid T))-\mathsf E(\mathsf E(S\mid T))^2 \\=&~ ... \end{align}$$
To do: the rest.  Can you?


text:
Q: Modify an HTML value with JS variable I have this function, that takes the value of "count", prints it and save it in a variable
<input type="number" id="count" min="1" value="1" style="text-align:center">

and i want to take $hello and put it in a value in a input tag, something like this
<input name="x" type="hidden" value="//here would be $hello">

How can I do that?
Thanks.

A: Try this,it will work
 $('#count').bind('click keyup', function(){
                   alert($(this).val());
                   var hello = $(this).val();
                   $("#check").val(hello);
                });

    <input name="x" id="check" type="hidden" value="//here would be hello">

A: jQuery's .val() method is both a getter and a setter.
Try this:
$('input[name="x"]').val($hello);

A: User setter variable after $hello
     <input type="number" id="count" min="1" value="1" style="text-align:center">

A: jQuery val() method is used to apply the value to input element:
<input type="number" id="count" min="1" value="1" style="text-align:center">

<input name="x" type="hidden" value="//here would be $hello">

demo link