text:
Q: Complexity order f(x) = x vs g(x) = log (x)^(log (x)) What is Big-O complexity order for: f(x) = x  vs  g(x) =  log (x)^(log (x)) ?

A: It might be easier to understand this with example. Consider log represents 2 based logarithm. We can ignore constant as we want behavior at asymptote. Running time f(x) vs g(x) as x follows:
x=2^1: f(x) = 2^1 = 2    ; g(x) = log(2^1)^log(2^1) = 1^1 = 1     ;f(x) > g(x)
x=2^2: f(x) = 2^2 = 4    ; g(x) = log(2^2)^log(2^2) = 2^2 = 4     ;f(x) = g(x)
x=2^3: f(x) = 2^3 = 8    ; g(x) = log(2^3)^log(2^3) = 3^3 = 27    ;f(x) < g(x)
x=2^4: f(x) = 2^4 = 16   ; g(x) = log(2^4)^log(2^4) = 4^4 = 256   ;f(x) < g(x)
...
x=2^100: f(x) = 2^100    ; g(x) = log(2^100)^log(2^100) = 100^100 ;f(x) << g(x)

So as x approaches infinity running time of f(x) is way less than g(x).

A: Assume x > 0 because g(x) is only well defined for those x. This means we are allowed to make the substitution x = e^t, which gives us
 f(x) = e^t
 g(x) = t^t

and it becomes immediately clear that g(x) > f(x) for all t > e, that is, for all x > e^e. In particular, this means that f(x) = O(g(x)), and in fact it would be easy to prove that f(x) = o(g(x)).


text:
Q: get the unique number from an array, remove the duplicates completly int a[5] = {5,2,3,2,4}

If i have an array like this, i want to get uniques
Not

5,2,3,4

but

5,3,4

Any number repeated will be removed.
I have tried using std::<set>
const size_t len = sizeof(a) / sizeof(a[0]);
std::set<int> s(a, a + len);

However, it does not work as it will produce uniques:

5,2,3,4

A: You can use std::multiset with std::multiset::count, and obtain the elements only when the number of elements with the same key equals to 1 exactly. e.g.
int a[5] = {5,2,3,2,4};
const size_t len = sizeof(a) / sizeof(a[0]);
multiset<int> m(a, a + len);

vector<int> v;

copy_if(begin(a), end(a), back_inserter(v), [&m](auto i) { return m.count(i) == 1; });

copy(v.begin(), v.end(), ostream_iterator<int>(cout, " "));

Result:
5 3 4

LIVE
If you can't use lambda, you can write a functor instead, or write the loop directly instead of copy_if.
for (int i = 0; i < len; i++) {
    if (m.count(a[i]) == 1)
        v.push_back(a[i]);
}

A: *

*Sort the array. Use std::sort

*Swap duplicate elements to end. Use std::unique

*

*Now you have 2 partitions. First partition contains uniques (but includes onces that have duplicates), second contains all the duplicates. std::unique returns an iterator to the boundary of the partition (one past the last unique element).

*Result will be uniques \ duplicates. Use std::set_difference with ranges [begin,boundary[ and [boundary, end[

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I remove both index.php and ? from my urls that are coming in from indexed google search results? I have thousands of URLs indexed by Google from my old ecommerce system. I'm adding redirect rules on my new system, but none of them work as long as index.php? is in the URL.
I added these rules into my .htaccess file, but when I click on a URL on Google, it takes me to the homepage of my new site, and the index.php? is still in the URL.
Is there any way to have both the index.php and the ? removed from an incoming URL?
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule (.*) /index.php/$1 [L]

A: I needed to turn this
https://example.com/index.php?route=product/product&product_id=<id>
into this https://example.com/index.php?route=product/product&product_id=<id>
This was what worked in the end
RewriteEngine On
RewriteBase "/"
RewriteCond %{REQUEST_URI} ^/index\.php$
RewriteCond %{QUERY_STRING} (route.*)
RewriteRule "(.*)index.php" $1%1? [R=301,L]


text:
Q: Android Login button stops working Hi I am developing an android app, but my login button not working properly, as I am able to signup with web service but after in login page its stopped working, as I can navigate from signup to other page but login button does not let me login, please help me, below is my code for login functionality
thanks
public class Login extends ActionBarActivity {
Button btnLogin;
Button fbbutton;
Button gpbutton;
Button twbutton;
Button btnRegister;

EditText username, password;
String uname, pass;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.login);
    username = (EditText) findViewById(R.id.username);
    password = (EditText) findViewById(R.id.password);
    Button btnLogin = (Button) findViewById(R.id.btnLogin);

    //import button
    Button btnRegister = (Button) findViewById(R.id.btnRegister);

    btnRegister.setOnClickListener(new View.OnClickListener(){
        public void onClick(View view){
            Intent i = new Intent(getApplicationContext(),
                    Signup.class);
            startActivity(i);
            finish();
        }
    });

}

public void send(View v) {
    try {

        // CALL post method to make post method call
        post();
    } catch (Exception ex) {
        String error = ex.getMessage();
    }

}

//Method to get list value pair and form the query
private String getQuery(List<NameValuePair> params) throws UnsupportedEncodingException {
    StringBuilder result = new StringBuilder();
    boolean first = true;

    for (NameValuePair pair : params) {
        if (first)
            first = false;
        else
            result.append("&");

        result.append(URLEncoder.encode(pair.getName(), "UTF-8"));
        result.append("=");
        result.append(URLEncoder.encode(pair.getValue(), "UTF-8"));
    }

    return result.toString();
}

//Method to post data to webservice
public void post() throws UnsupportedEncodingException {
    try {
        // Calling async task to get json
        new DownloadOperation().execute();

    } catch (Exception e) {
        e.printStackTrace();
    }
}

//Handle popout messages
public void error(boolean flag, String etext) {
    if (flag == true) {
        Toast.makeText(getBaseContext(), etext, Toast.LENGTH_SHORT).show();
        //Code to handle failure
        username.setText("");
        password.setText("");

    } else {
        Toast.makeText(getBaseContext(), etext, Toast.LENGTH_SHORT).show();
        setContentView(R.layout.welcome);

    }
}

private class DownloadOperation extends AsyncTask<Void, Void, String> {
    String uname = "";
    String pass = "";

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // Get user defined values
        uname = username.getText().toString();
        pass = password.getText().toString();

    }

    @Override
    protected String doInBackground(Void... params) {
        String response = "";
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://rgbpallete.in/led/api/login");
        HttpEntity httpEntity = null;
        HttpResponse httpResponse = null;
        try {
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
            nameValuePairs.add(new BasicNameValuePair("uname", uname));
            nameValuePairs.add(new BasicNameValuePair("pass", pass));
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            httpResponse = httpclient.execute(httppost);
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            httpEntity = httpResponse.getEntity();
            response = EntityUtils.toString(httpEntity);
            return response;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(String jsonStr) {
        super.onPostExecute(jsonStr);
        Log.d("tag", "Result:\n" + jsonStr);
        if (jsonStr != null) {
            try {
                JSONObject jsonObj = new JSONObject(jsonStr);
                String message = jsonObj.getString("message");
                boolean error = jsonObj.getBoolean("error");

                error(error, message);

            } catch (JSONException e) {
                e.printStackTrace();
            }
        } else {
            Log.e("ServiceHandler", "Couldn't get any data from the url");
        }
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement

    return super.onOptionsItemSelected(item);
}

layout code of btnLogin Button
<Button
   android:id="@+id/btnLogin"
   style="@android:style/Widget.Material.Button.Borderless"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:layout_below="@+id/password"
   android:layout_centerHorizontal="true"
   android:layout_marginTop="20dp"
   android:background="@drawable/button"
   android:text="Login"
   android:textColor="#ffffff"
   android:textSize="20sp"
   android:onClick="welcome" />

A: change this line to
Button btnLogin = (Button) findViewById(R.id.btnLogin);

to this
btnLogin = (Button) findViewById(R.id.btnLogin);

you are not initialize it properly.you are creating new variable.if you are getting null pointer exception that would be the reason

A: Your application is crashing because in xml you have set onClick as welcome(as per your comment). But you haven't implement it in Activity. So, when you click on that Button you are getting java.lang.NoSuchMethodException. In Activity welcome method is required add this in Activity
public void welcome(View v) {
   //do your action i.e call AsyncTask
}

A: *

*make sure you have registered onclick listener to your login button, you haven't registered any click listener with btnLogin and also not set any action to be performed onClick to btnLogin!! just implemented those in btnRegister! I think you forgot it!!

*if you are using onclick attribute of xml; then make sure these things are correct regarding your method:
a. your method is public and is the member of the Activity.
b. corresponding method should have one parameter, whose type should match the XML object. eg: View

A: You are missing
Button  btnLogin = (Button) findViewById(R.id.btnLogin);
    btnLogin .setOnClickListener(new View.OnClickListener(){
        public void onClick(View view){
            //all your stuff here
        }
    });

Add and test.. Actually for each button you have to use OnClickListener


text:
Q: Pay with a like on iOS & Android How can I allow my iOS & Android user to use premium features if they liked a facebook page or if they twitted a message.
In other word how to implement Pay With A Tweet or Pay With A Like in mobile apps?

A: You can either build this functionality natively, using various social media platforms' SDKs (if they offer one) or by redirecting to something like a UIWebView and retrieving the success callback to ensure they did what they were supposed to do.
Alternatively, you could use a 3rd party platform such as TapJoy or ChartBoost that implements this concept using a pre-built SDK.


text:
Q: Rmarkdown footnote not rendering properly when using sendmailR and viewed in Office365 I've built a HTML document in Rmarkdown and used some footnotes.
In R the rendering occurs correctly and I get nice tasty foonotes.
However when i send using sendmailR...the footnote return symbol is garbled...

Is this fixable? Any ideas why it's happening?


text:
Q: How to retrieve image or 'imagePath' through Dialog-Activity Communication? I have an ImageView opens a dialog with 2 options

*

*to select photo from External Memory

*or take new one using Camera
it opens the dialog and the dialog takes permissions successfully then open the camera or memory
but it gives me an error when i select photo from the memory or approve taken photo by camera
I am using OnPhotoReceivedListener interface in the dialog fragment to retrieve the photo and imagePath
Here is How i call the Dialog from the Activity
public class EditNoteActivity extends AppCompatActivity implements ChoosePhotoDialog.OnPhotoReceivedListener{
private String mSelectedImagePath;

private static final int REQUEST_CODE = 1;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_edit_note);

      mSelectedImagePath = null;

    ImageView addImageIV = (ImageView) findViewById(R.id.ivAddImage);
    addImageIV.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            /*
            Make sure all permissions have been verified before opening the dialog
             */
            for(int i = 0; i < Permissions.PERMISSIONS.length; i++){
                String[] permission = {Permissions.PERMISSIONS[i]};
                if(checkPermission(permission)){
                    if(i == Permissions.PERMISSIONS.length - 1){
                        Log.d(TAG, "onClick: opening the 'image selection dialog box'.");
                        ChoosePhotoDialog dialog = new ChoosePhotoDialog();
                        dialog.show(getSupportFragmentManager(), "ChoosePhotoDialog");
                    }
                }else{
                    verifyPermissions(permission);
                }
            }
        }
    });

/**
 * Retrieves the selected image from the bundle (coming from ChoosePhotoDialog)
 * @param bitmap
 */
@Override
public void getBitmapImage(Bitmap bitmap) {
    Log.d(TAG, "getBitmapImage: got the bitmap: " + bitmap);
    //get the bitmap from 'ChangePhotoDialog'
    if(bitmap != null) {
        compressBitmap(bitmap, 70);
        //TODO: Save Image and get It's Url
    }
}

@Override
public void getImagePath(String imagePath) {
    Log.d(TAG, "getImagePath: got the image path: " + imagePath);

    if( !imagePath.equals("")){
        imagePath = imagePath.replace(":/", "://");
        mSelectedImagePath = imagePath;
        mImgUrls += StringManipulation.imgSerialize(new String[]{imagePath, "Description"});
        initRecyclerView(mImgUrls);
    }
}

public Bitmap compressBitmap(Bitmap bitmap, int quality){
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG, quality, stream);
    return bitmap;
}

and Here is my Dialog class
public class ChoosePhotoDialog extends DialogFragment {

private static final String TAG = "ChoosePhotoDialog";

public interface OnPhotoReceivedListener{
    public void getBitmapImage(Bitmap bitmap);
    public void getImagePath(String imagePath);
}

OnPhotoReceivedListener mOnPhotoReceived;

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.dialog_camera_or_memory, container, false);

    //initalize the textview for starting the camera
    TextView takePhoto = (TextView) view.findViewById(R.id.tvTakeCameraPhoto);
    takePhoto.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Log.d(TAG, "onClick: starting camera.");
            Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            startActivityForResult(cameraIntent, Permissions.CAMERA_REQUEST_CODE);
        }
    });

    //Initialize the textview for choosing an image from memory
    TextView selectPhoto = (TextView) view.findViewById(R.id.tvChoosePhotoFromMemory);
    selectPhoto.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Log.d(TAG, "onClick: accessing phones memory.");
            Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("image/*");
            startActivityForResult(intent, Permissions.PICK_FILE_REQUEST_CODE);
        }
    });

    // Cancel button for closing the dialog
    TextView cancelDialog = (TextView) view.findViewById(R.id.tvCancelTakingPhoto);
    cancelDialog.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Log.d(TAG, "onClick: closing dialog.");
            getDialog().dismiss();
        }
    });

    return view;
}

@Override
public void onAttach(Context context) {
    super.onAttach(context);
    try{
        mOnPhotoReceived = (OnPhotoReceivedListener) getTargetFragment();
    }catch (ClassCastException e){
        Log.e(TAG, "onAttach: ClassCastException: " + e.getMessage() );
    }
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    /*
    Results when taking a new image with camera
     */
    if(requestCode == Permissions.CAMERA_REQUEST_CODE && resultCode == Activity.RESULT_OK){
        Log.d(TAG, "onActivityResult: done taking a picture.");

        //get the new image bitmap
        Bitmap bitmap = (Bitmap) data.getExtras().get("data");
        Log.d(TAG, "onActivityResult: received bitmap: " + bitmap);

        //send the bitmap and fragment to the interface
        mOnPhotoReceived.getBitmapImage(bitmap);
        getDialog().dismiss();
    }

    /*
    Results when selecting new image from phone memory
     */
    if(requestCode == Permissions.PICK_FILE_REQUEST_CODE && resultCode == Activity.RESULT_OK){
        Uri selectedImageUri = data.getData();
        File file = new File(selectedImageUri.toString());
        Log.d(TAG, "onActivityResult: images: " + file.getPath());

        //send the bitmap and fragment to the interface
        mOnPhotoReceived.getImagePath(file.getPath());
        getDialog().dismiss();

    }
}
}

And this is the Error
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=65544, result=-1, data=Intent { dat=content://com.android.providers.media.documents/document/image:14786 flg=0x1 launchParam=MultiScreenLaunchParams { mDisplayId=0 mFlags=0 } }} to activity {com.ahmed_smae.everynote/com.ahmed_smae.everynote.EditNoteActivity}: java.lang.NullPointerException: Attempt to invoke interface method 'void com.ahmed_smae.everynote.Utils.ChoosePhotoDialog$OnPhotoReceivedListener.getImagePath(java.lang.String)' on a null object reference

Do you think the problem with the interface ?
How Can I solve it ?

A: The error is in your On your ActivityResult method. You are accessing a method on the interface of a null object.
Please set your debugger
@Override
public void onAttach(Context context) {
    super.onAttach(context);
    try{
        mOnPhotoReceived = (OnPhotoReceivedListener) getTargetFragment();
    }catch (ClassCastException e){
        Log.e(TAG, "onAttach: ClassCastException: " + e.getMessage() );
    }
}

Then confirm the getTargetFragment() is working.
As I suspect that this is returning null or it is getting nulled out at some point before you are accessing it.
mOnPhotoReceived appears to be null in your error, so then you should set a breakpoint at the point of which you are calling getImagePath() and see the object is null. Next you just need to see where/how it is set to null.


text:
Q: MongoError: Cannot apply $addToSet to non-array field. Field named 'trackTime' has non-array type string Here i'm trying to update with the userid, trackTime fields. Evertime userid and trackTime will be different so i'm using $addToSetbut here i'm facing an error
like this i'm passing the data in postman:-
{
 "courseId":"61001184afeacb22ac1668e0",
 "userId":"60f6fe96a1a44a1fb4a59573",
 "trackingTime":"4"
}

this is the schema:-
 usersEnrolled : [{
    iscourseenrolled : { type:Boolean, default: false },
    userId: {type: String },
    trackTime: {type:String}
 }],

code:-
const updatedTrackTime = await Courses.updateOne({ "_id" : req.body.courseId},{
  $addToSet:{
    "usersEnrolled.0.userId" : req.body.userId,
    "usersEnrolled.0.trackTime": req.body.trackingTime
 }})

A: The reason for that error is probably because you didn't specify the array field (Actually you didn't specify any field at all). Try to add your usersEnrolled field like this:
const updatedTrackTime = await Courses.updateOne({ "_id" : req.body.courseId},{
  $addToSet:{
    usersEnrolled: {
      "usersEnrolled.0.userId" : req.body.userId,
      "usersEnrolled.0.trackTime": req.body.trackingTime
    }
 }});

To get more details on $addToSet use MongoDB Manual
https://docs.mongodb.com/manual/reference/operator/update/addToSet/

A: I just changed in to these and it worked for me
const updatedTrackTime = await Courses.updateOne({ "_id" : req.body.courseId},{ $addToSet:{
usersEnrolled : {
   userId : req.body.userId,
   trackTime: req.body.trackingTime
}


text:
Q: Is it possible to create a named "fat-arrow" lambda in typescript? Using the traditional function syntax, it's possible to create named functions inline.
var fn = function myName(arg) {
    // whatever
};
// fn.name === "myName"

Can names be specified in typescript using the lambda syntax?
var fn = (arg) => {
    // whatever
};
// fn.name not set

A: Doesn't look like you can do that, as the spec doesn't cover it, only at the end under "deferred" it states "Optional leading Identifier for named arrow function expressions."

A: Yes, but it's a little bit tricky.
The arrow function acquires the name from the variable where it's being assigned. It's called that name is inferred from that variable (in your case fn.name === "fn"). There are some limitations because such name doesn't work as a regular identifier and therefore it can't be used from within the function itself (for the recursion or the events unbinding).
If you use the following code:
const joeThrows = (thing: string):never => {
  throw new Error(`Joe took ${thing} and throwed it at you.`);
}

const simonThrows = ({
  simonSays: (what: string):never => {
    throw new Error(`Simon said ${what} and throwed you out.`);
  }
})["simonSays"];

try {
  console.log("== joeThrows fat-arrow %s has name '%s' ==", typeof joeThrows, joeThrows.name);
  joeThrows("hammer");
} catch(ex) { console.log(ex.stack); }

try {
  console.log("=== simonThrows fat-arrow %s has name '%s' ==", typeof simonThrows, simonThrows.name);
  simonThrows("I have a name!");
} catch(ex) { console.log(ex.stack); }

Then you will get this output:
=== joeThrows fat-arrow function has name 'joeThrows' ==
Joe took hammer and throwed it at you.
Error: Joe took hammer and throwed it at you.
    at joeThrows (/code-demo/named.js:2:11)
    at Object.<anonymous> (/code-demo/named.js:11:5)
    at Module._compile (internal/modules/cjs/loader.js:778:30)
    ...
=== simonThrows fat-arrow function has name 'simonSays' ==
Error: Simon said I have a name! and throwed you out.
    at simonSays (/code-demo/named.js:6:15)
    at Object.<anonymous> (/code-demo/named.js:18:5)
    at Module._compile (internal/modules/cjs/loader.js:778:30)
    ...

I use the second technique with an object field assign and read expression rarely.
It can be handy when you want to create more functions that will act as callbacks with the same functionality for a different setup and you want to visualize source of exception more precisely then with just a generic name. For example, to dynamically create Redux selectors or FeatherJS hooks that are very generic and can be customized by parameters of the function creator:
// Let's suppose we have the types
type HookContext = Record<string, any>;
type ServiceHook = (context: HookContext) => HookContext;

// Then we can define service hook factory function
export const createServiceHook = (purpose: string): ServiceHook => {
    const fn = `serviceHook$${purpose}`;
    return ({
        [fn]: (context: HookContext): HookContext => {
            // Do something here with the context which may throw exception
            return context;
        }
    })[fn];
};

// Later we can create a specific hook function instance that:
// * will have lookoutForSummer.name equal to "serviceHook$summer"
// * will show that name in call-stack in case exception is throw
export const lookoutForSummer = createServiceHook("summer");


text:
Q: Changing input type from file to text My requirement is initially my input type should be "file" but its read only. So along with choose file I should be able to write the file name in the textbox.
Can anyone help? I should write the file name like writing text in textbox.

A:

var change = document.getElementById("change");

    //Do whatever then call when you need it
$('#changer').click(function(){
  change.type = 'text';
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" id="change">
<br>
<button type="button" id="changer">Change Type</button>


text:
Q: Find $\int\frac{1}{(x^2-1)^2}dx$ I'm trying to find $\displaystyle\int\frac{1}{(x^2-1)^2}dx$. Partial fractions just gives me the same fraction. When I try trig substitution, I end up with $\dfrac{\cos^2(x)}{\sin^3(x)}$. What am I doing wrong? What can I do?

A: We have:
$$ \frac{1}{1+x}+\frac{1}{1-x} = \frac{2}{1-x^2} \tag{1}$$
so, by squaring both sides:
$$ \frac{1}{(1+x)^2}+\frac{1}{(1-x)^2}+\frac{1}{1+x}+\frac{1}{1-x} = \frac{4}{(1-x^2)^2}.\tag{2} $$
It follows that:
$$ \int \frac{dx}{(1-x^2)^2} = C+\frac{1}{4}\left(-\frac{1}{1+x}+\frac{1}{1-x}+\log(1+x)-\log(1-x)\right).\tag{3}$$

A: Integrating by part,
$$\int\dfrac1x\cdot\dfrac x{(x^2-1)^2}dx=\dfrac1x\cdot\int\dfrac x{(x^2-1)^2}dx-\int\left(\dfrac{d(1/x)}{dx}\cdot\int\dfrac x{(x^2-1)^2}dx\right)dx$$
Now $\displaystyle\int\dfrac x{(x^2-1)^2}dx=?$
Can you take it from here?

A: Then you have done the partial fractions wrong.  Partial fractions can't "give the same thing" here.  Since $x^2- 1= (x- 1)(x+ 1)$, $(x^2- 1)^2= (x- 1)^2(x+ 1)^2$ so the partial fractions form is $\frac{1}{(x^2- 1)^2}= \frac{A}{x- 1}+ \frac{B}{(x- 1)^2}+ \frac{C}{x+ 1}+ \frac{D}{(x+ 1)^2}$.

A: Hint:
By educated guess, let us try
$$F(x)=\frac x{x^2-1}.$$
Taking the derivative, we find
$$F'(x)=\frac{x^2-1-2x^2}{(x^2-1)^2}=-\frac1{x^2-1}-\frac2{(x^2-1)^2}.$$
The antiderivative of $\dfrac1{1-x^2}$ is known to be the inverse hyperbolic tangent.

A: $$\dfrac4{(x^2-1)^2}=\dfrac{\{(x+1)-(x-1)\}^2}{(x-1)^2\cdot(x+1)^2}=\dfrac1{(x-1)^2}+\dfrac1{(x+1)^2}-\dfrac2{(x+1)(x-1)}$$
Use $2=(x+1)-(x-1)$ for the last case

A: Let $x=\sec t$ and $dx=\sec t\tan t dt$
$$\int\frac{1}{(x^2-1)^2}dx=\int\frac{\sec t\tan t}{(\sec^2t-1)^2}dt=\int\frac{\sec t\tan t}{\tan^4t}dt=\int\frac{\sec t}{\tan^3t}dt=\int\frac{\cos^2t}{\sin^3t}dt=\int\frac{1-\sin^2t}{\sin^3t}dt=\int\frac{1}{\sin^3t}dt-\int\frac{1}{\sin t}dt$$
You can use trigonometric identities and commonly known integrals for the final steps.


text:
Q: Refactor Express Router in node js Howe to i prevent using this middleware repeatedly on each endpoint. is there a way i can use the isUserAuth and isAdminAuth just once and it will apply on the other routes without repeating it on each route/endpoints?
const { createBranch, getAllBranch, getBranch } = require('../controllers/user')
const { isUserAuth, isAdminAuth } = require('../middlewares/auth')

const router = require('express').Router()

// branch
router.post('/', isUserAuth, isAdminAuth, createBranch)
router.get('/', isUserAuth, isAdminAuth, getAllBranch)
router.get('/:id', isUserAuth, isAdminAuth, getBranch)
router.put('/:id', isUserAuth, isAdminAuth, getBranch)

module.exports = router

A: Consider using router.use(isUserAuth);. You can find the documentation here


text:
Q: Space for initials for procedural compliance I am a noob when it comes to coding so this is my first attempt. I have a procedure that I want an initial block to show up in the margin for text with the Heading 4,5,6 and 7 styles.
Currently my document looks like this:

*

*COMPLETE the first step

*Then COMPLETE the second step.

a. This is a sub-step
What I would like to do is have something that looks like this:
_______ 1. COMPLETE the first step
_______ 2. Then COMPLETE the second step.
_______      a. This is a sub-step.
I've tried formatting and style writing but cannot consistently get a line that doesn't mess up the ability to cross reference. I'm hoping that having used the styles to identify the steps themselves can help with the macro. I know how to access the VB for apps writing screen and that's about where my ability hits a roadblock.


text:
Q: Should I use htmlentities() on all output? (preventing XSS attacks)
Possible Duplicate:
What are the best practices for avoiding xss attacks in a PHP site
What are the common defenses against XSS?

I'm trying to make a PHP application I've written secure and have a question about escaping output. I switched to using prepared statements with PDO once I learned doing so would prevent SQL injections, and it seems that the other main type of attack is XSS. I build the output for my pages like this (assume the variables have data from the database in them):
$output = '';

$output .= '

    Name: ' . $name . '
    Address:' . $addr . '
    Time:' . time() . '

';

$output .='[lots more html]';

So, my question is, should I use htmlentities() around every piece of data from the database being output (a typical page has dozens, some possibly hundreds, of variables from the database being output)?

A: There are two benefits to using htmlentities():

*

*XSS prevention

*Converting special characters to proper HTML entities, for example it converts the copyright character to ©. In HTML content you should use the appropriate HTML entity instead of inserting a raw special character.

For XSS prevention, you could use htmlspecialchars() instead, but it will only convert some basic characters to HTML entities, namely quotes, ampersand and the less than/greater than characters.
In answer to your question, you should use htmlentities() when outputting any content that could contain user input or special characters.

A: htmlspecialchars() is more than enough. htmlentities is for different use, not preventing XSS.


text:
Q: Nginx Cannot Find OpenSSL Development Headers When I run: rvmsudo passenger-install-nginx-module on my El Capitan Mac to install nginx, the terminal prints:
Checking for OpenSSL development headers...
  Found: no

But I am certain I have openssl installed. which openssl returns /usr/local/openssl/bin/openssl and /usr/local/openssl/bin: is the first entry in my $PATH. My questions are:

*

*Are the OpenSSL development headers included with the regular openssl install through homebrew?

*If they aren't, where should I download them from?

A: The trick was to run brew link openssl --force in order to link the development headers from xcode to openssl. To clarify, I ran:
brew install openssl
brew link openssl --force
And it worked fine.


text:
Q: Installing an OS on My Intel Mac Mini I have an old (2006) Intel Mac Mini Core Duo, 1.67 Ghz, model A1176. I wanted to single-boot Linux, so I made a bootable USB Gentoo install, which I booted with the help of rEFIT (installed on my OS X) and used gdisk to wipe my hard drive and write a new partition table. Yes, I realize that removing OS X was risky and stubborn.
But I accidentally shut down my computer without configuring the bootloader.
Now I can't boot my computer because there's no bootloader. I put Ubuntu on a USB flash drive (MBR format, FAT filesystem), but the computer doesn't recognize it as bootable.
I can't use the CD/DVD drive either, because a blank CD is already in there. The drive can't eject the disk because there's no operating system to control it.
Note: I don't have the Mac OS X install discs.
I have two questions:

*

*How can I most painlessly install an operating system (probably Linux) on this computer?

2a. Assuming the answer to #1 is "put distro xyz on a DVD and boot from that", how can I eject the current disc?
2b. Assuming the answer is "install rEFIT on one partition of a USB flash drive and a distro on another partition", what's my best bet to get this to work?
I really appreciate any help you can provide

A: According to Apple support, pressing the Eject or F12 key or holding the mouse or trackpad button at boot time will eject any removable media, such as an optical disc.
There should also be a small hole next to the drive into which you can stick a paperclip to eject the disk.


text:
Q: C# Custom Scrolling Cartesian graph I would like to ask for some insight/guidance on the following issue:
I am creating a custom scrolling graph in C#. I DEFINITELY not wanting to use the graph control in Visual Studio. Period. I want this completely original code.
A little background:
I have a function that returns a float value representing a signal amplitude.
I sample these values at an arbitrary interval set at runtime by the user.
I place these values into an Array of PointF.
A new value is pushed into the bottom of the array and the top value is removed. Thereby creating a buffer.
The length of the array is determined by the width of the "plot".
As the "plot rectangle decreases in width, the array is resized and leading values are dropped, as the "plot" is widened the array is resized and the missing values are added to the top of the array as "zeroed" points (as in the 0 points on my Cartesian graph).
I draw these points onto the plot and this produces a trace on the graph.
Each time a value is entered into the bottom of the array, I repaint the entire "plot" rectangle area and the result is a moving graph that represents the signal as a function of time.
Now, there is no minimum and maximum values preset for the signal power. If I set an upper or lower bound, then any signal level outside of the bounds of the graph will not show (it will clip).
To remedy this, I calculate the scale of the "plot" on the x-axis and scale the Points in the array to the same factor. I do this by finding the max and min values for upper and lower in the array and use those values to auto-scale the graph.
This all works great - sort of. It's usually fast to render, but sometimes my values still go outside of bounds (I know why this is happening and will fix it later). It also uses more code than I would like.
Here is an image graph so far:

Would it be neater and cleaner / easier to draw the trace on a graphics path directly (instead of using a buffer) in 1:1 scaling, then somehow clip the region I am interested in, render it, add a new value, draw the new line from the newest point I added, clip it, render it, repeat?
Instead of calculating scale, I could just use a matrix to transform the clip to the proper size for my "plot"?
Thereby my "plot" rectangle would actually be a window I could move horizontally along the plot of the entire value and I could zoom in / or zoom out in time (y-axis) and signal level (x-axis) by using a matrix to transform the scale and offset?
I have never used the graphics path or matrix before in GDI+ and have always manually drawn everything by using a double buffer, overriding the OnPaint() method and the OnPaintBackGround() method and drawing my objects from there.
Any help would be appreciated.  If you need the code I can provide it here as well.


text:
Q: for-loops doesn't work inside if-statement in python The if-statement and the for-loops works fine singularly but it doen't work when the loop is inside the if-statement, better detailed in code section.
keyword = input("search here: ")

with open("listaUni.txt") as lista_uni:
    if keyword in lista_uni.read():
        print("there is")
    else:
        print("there is not")
#this works fine

with open("listaUni.txt") as lista_uni:
  for uni in lista_uni.readlines():
    if keyword.lower() in uni.lower():
      print(uni)
# also this works fine, it prints out all the strings in the list
#containing the keyword

keyword = input("search here: ")

with open("listaUni.txt") as lista_uni:
    if keyword in lista_uni.read():
      for uni in lista_uni.readlines():
        if keyword.lower() in uni.lower():
          print(uni)
    else:
          print("there is not")
#this doesn't work

lista_uni.close()

When the keyword is in the list, it should check every string of the list and print the ones with the keyword in it, if the keyword is not in the list it should print "there is no". It asked for the keyword and then do nothing. Since the 2 pieces of the code actually work separately, what I'm doing wrong? thanks to everybody.

A: if keyword in lista_uni.read():
      for uni in lista_uni.readlines():
        if keyword.lower() in uni.lower():
          print(uni)

Here you are trying to read the file twice.

*

*During read()

*During readlines()
After the first read. You are already at the end of the file, so readlines() returns an empty list.
To get around it you can add a seek(0)
if keyword in lista_uni.read():
      list_uni.seek(0)
      for uni in lista_uni.readlines():
        if keyword.lower() in uni.lower():
          print(uni)


text:
Q: Why wont bash script run by Maven SCP my file? I have a bash script, amongst other things, attempts to SCP a file from current host (Windows/Cygwin) to a remote host (Suse).
When I run the script in Cygwin myself, the script performs perfectly. Transfers the file via SCP, then SSH to the remote machine to run some further commands (to do with deploying the file to application server).
When the script is run by Maven as part of a Jenkins CI build it fails with an error about the key pair being rejected.
From the Jenkins job log:
Host key verification failed.
lost connection

A: Let your job run once with StrictHostKeyChecking:
scp -o 'StrictHostKeyChecking no' ...

This will log something like:
Warning: Permanently added '<host>, <ipaddr>' (<keytype>) to the list of known hosts.

After that, remove the StrictHostKeyChecking.


text:
Q: The type or namespace name 'function' could not be found? I am writing a function proc in my C# 2008 ASP.Net application and I get the following error:

The type or namespace name 'function'
  could not be found (are you missing a
  using directive or an assembly
  reference) ?

Any idea what this means?

A: If i understand you correctly, you have written something like this:
private function ValidateData() {}

If that is correct, then you need to change it to something like this:
private bool ValidateData() {}

where bool in this example, is your return type (boolean).  If you have no return (then it is not a function).  Here is what you would do then:
private void ValidateData() {}

A: "function" is a JavaScript keyword, not a C# keyword. Maybe the compiler thinks your JavaScript is meant to be C#.

A: private function ValidateData() { }

you need to replace "function" with the return type of the function. In this case it would be void meaning that there is no return value.
private void ValidateData() { }


text: Q: Tinkers Construct Mod Not Making Casts in Smeltery I am playing on Tinkers Construct in mincraft 1.5.2 because some of my other mods are not supported past that. I have correctly set up the smeltery and am trying to make part cast so I can make tools out of the metals, but when I set a part on the casting table and right click on the seared faucet no Aluminum-Bronze comes out to make the cast. By the way I have also tried to use gold instead and it did not work.


text:
Q: How to create a CSV file if it doesn't exist? I'm trying to get excel to check for the existence of a CSV file, and if it doesn't exist, create it.  I've tried doing this several ways, but I can't seem to get anything working.  Here's my code so far.
If Dir("C:\Users\" & sUserName & "\Desktop\DataDump\") = "" Then
                MkDir "C:\Users\" & sUserName & "\Desktop\DataDump\"
                Dim ws As Worksheet
                For Each ws In ActiveWorkbook.Worksheets
                    If ws.Name = MyCell.Value Then
                        ws.SaveAs "C:\Users\" & sUserName & "\Desktop\DataDump\DataDump.csv", xlCSV
                        Workbooks.Open Filename:="C:\Users\" & sUserName & "\Desktop\DataDump\DataDump.csv"
                        Cells.Select
                        Selection.Delete
                        ActiveWorkbook.Close True

                        LastRowCusip = ActiveSheet.Cells(ActiveSheet.Rows.Count, "BW").End(xlUp).Row
                        Set Rng = Range("BG5:BW" & LastRowCusip)
                        Workbooks.Open Filename:="C:\Users\" & sUserName & "\Desktop\DataDump\DataDump.csv"
                        LR = Cells(Rows.Count, "A").End(xlUp).Row + 3 'last used row
                        Rng.Copy Range("A" & LR)
                        ActiveWorkbook.Close True

                    End If
                Next
            End If

As soon as I get to this line:
Workbooks.Open Filename:="C:\Users\" & sUserName & "\Desktop\DataDump\DataDump.csv"
Excel shuts down!!
All I want to do is test for the existence of a CSV file and it it doesn't exist, create it on a user's desktop, based on each user's sUserName, which comes from here.
sUserName = Environ$("username")

Can someone please help me get this working?
Thanks!!!

A: You need to copy the sheet out of the workbook first.
Change these lines:
ws.SaveAs "C:\Users\" & sUserName & "\Desktop\DataDump\DataDump.csv", xlCSV
Workbooks.Open Filename:="C:\Users\" & sUserName & "\Desktop\DataDump\DataDump.csv"

To the following lines
   ws.Copy
   ActiveWorkbook.SaveAs "C:\Users\" & sUserName & "\Desktop\DataDump\DataDump.csv", xlCSV

When saving a worksheet as CSV it saves the entire active workbook to the file and leaves it open. So, in your code, you are trying to open a file that is already open.
The code above will pull the worksheet into a new workbook and save it as a CSV (with only 1 sheet, which is required for a CSV).


text:
Q: Angular with npm or visual studio? I want to to create a UI project using angular 6,
What approach is better, do I have to create angular project using npm or go with visual studio angular template?
This UI is consuming Web API's written using Dot net Core 2.1
I created sample UI project using both I couldn't find out any great difference.

A: I think, best of all to use VisualStudio. It's more comfortable for me, but use the one, that you like better, as it's only the tool.


text:
Q: Jupyter notebook not opening from Centos 7 I have recently installed jupyter notebook on Centos 7. I have been trying to get it launched on my browser from past 2 days and have tried every answer on stack overflow. It stopped showing " No web browser found " when i type it on the command terminal. But when i copy and paste the link onto the google chrome browser it's showing, This site can't be reached.
How will i resolve this issue?

A: If you follow carefully the instructions on this post, you'll solve your problem.
I went through the same situation and followed these steps.
https://techknight.eu/2016/01/03/setup-jupyter-notebook-centosrhel-7/
The key is to :

*

*Modify the configuration .py file with your desired values (specially the IP on wich the notebook will run).

*Allow the port you're gonna use throug the CentOS firewall

In any case, if you break the configuration and you need a fresh start, you can always do:
jupyter notebook --generate-config

And the file will regenerate with default values.
Good Luck


text:
Q: TypeError : #1010 A term is undefined and has no properties at MethodInfo-258() please help me, i'm new at AS3
I have an Error when I compile my project, this is summary of my error

TypeError: Error #1009: Cannot access a property or method of a null object reference.
      at com.greensock::TweenLite/init()
      at com.greensock::TweenMax/init()
      at com.greensock::TweenMax/renderTime()
      at com.greensock.core::SimpleTimeline/renderTime()
      at com.greensock::TweenLite$/updateAll()
TypeError: Error #1010: A term is undefined and has no properties.
      at MethodInfo-258()

and this is my complete code that I use
import com.greensock.*;
import com.greensock.easing.*;
import flash.display.MovieClip;
import flash.events.MouseEvent;

var tombolMenu:Array = [menu1, menu2, menu3, menu4, menu5, menu6, menu7, menu8, menu9];
var judulMateri:Array = [title_1,title_2, title_3, title_4, title_5, title_6, title_7, title_8, title_9]
var isiMateri:Array = [materi_1, materi_2, materi_3, materi_4, materi_5, materi_6,
                       materi_7, materi_8, materi_9]
var jumlahFrame:Array = [10, 5, 6, 8, 4, 9,5, 5, 5];
    TweenLite.from(bar_mc, 0.5, {x:5000});
    TweenLite.from(subject_mc, 0.5, {delay:1, x:1000});
    navi_mc.visible=false;
for (var i:int = 0; i< tombolMenu.length; i++){
    var gap:Number = i/4;
    var tombolMenunya = tombolMenu[i];
    tombolMenunya.buttonMode = true;
    //muncul menu
    TweenLite.from(tombolMenu[i], 0.5, {delay:gap, scaleX:0, scaleY:0, ease:Circ.easeOut});
    tombolMenunya.addEventListener(MouseEvent.CLICK, fl_menu_0);
    function fl_menu_0(e:MouseEvent):void{
        TweenLite.to(bar_mc, 0.5, {delay:1,x:5000});
        TweenLite.to(subject_mc, 0.5, { x:1000});
        for (var i:int = 0; i<= tombolMenu.length; i++){
            var gaps:Number = i/4;
            //menu hilang
            TweenMax.to(tombolMenu[i], 1,{delay:gaps,scaleX:0, scaleY:0, ease:Circ.easeIn});

            //munculkan materi
            if (e.currentTarget == tombolMenu[i]){
                trace(jumlahFrame[i]);
                navi_mc.visible=true;
                TweenLite.from(navi_mc, 1, {delay:4, y:700});
                TweenLite.to(judulMateri[i], 1, {delay:3, x:89.45, y:36.45, ease:Back.easeOut});
                TweenLite.to(isiMateri[i], 1, {delay:3.4, x:392.45, y:246.95, ease:Back.easeOut});
                navi_mc.next_mc.addEventListener(MouseEvent.CLICK, fl_next);
                navi_mc.prev_mc.addEventListener(MouseEvent.CLICK, fl_prev);
                //navi_mc.home_mc.addEventListener(MouseEvent.CLICK, fl_home);
                navi_mc.prev_mc.alpha = 0.4;
                navi_mc.home_mc.alpha = 0.4;
                navi_mc.prev_mc.mouseEnabled = false;
                navi_mc.home_mc.mouseEnabled = false;
                //tombol next
                function fl_next(e:MouseEvent):void{
                    for(var i:int = 0; i<= isiMateri.length; i++){
                        isiMateri[i].nextFrame();
                        if(isiMateri[i].currentFrame == 2 ){
                            navi_mc.prev_mc.alpha = 1;
                            navi_mc.prev_mc.mouseEnabled = true;
                        }
                        if(isiMateri[i].currentFrame == jumlahFrame[i]){
                            trace(isiMateri[i].currentFrame);
                            navi_mc.next_mc.alpha = 0.4;
                            navi_mc.next_mc.mouseEnabled = false;
                            navi_mc.home_mc.alpha = 1;
                            navi_mc.home_mc.mouseEnabled = true;
                        }
                    }
                }
                //tombol prev
                function fl_prev(e:MouseEvent):void{
                    for(var i:int = 0; i<= isiMateri.length; i++){
                        isiMateri[i].prevFrame();
                        if(isiMateri[i].currentFrame == 1){
                            navi_mc.prev_mc.alpha = 0.4;
                            navi_mc.prev_mc.mouseEnabled = false;
                            navi_mc.next_mc.alpha = 1;
                            navi_mc.next_mc.mouseEnabled = true;
                        }
                        if(isiMateri[i].currentFrame==(jumlahFrame[i] - 1)){
                            navi_mc.next_mc.alpha = 1;
                            navi_mc.next_mc.mouseEnabled = true;
                            navi_mc.home_mc.alpha = 0.4;
                            navi_mc.home_mc.mouseEnabled = false;
                        }
                    }
                }
                //tombol home
            }
        }
    }
}

I would be very grateful if anyone helps :)
thank you everyone

A: sorry for slow respon :D
finally I found the problematic code
here it is, I get this error
TypeError: Error #1009: Cannot access a property or method of a null object reference. at com.greensock::TweenLite/init() at com.greensock::TweenMax/init() at com.greensock::TweenMax/renderTime() at com.greensock.core::SimpleTimeline/renderTime() at com.greensock::TweenLite$/updateAll()

when I run this script
for (var i:int = 0; i<= tombolMenu.length; i++){
            var gaps:Number = i/4;
            //menu hilang
            TweenMax.to(tombolMenu[i], 1,{delay:gaps,scaleX:0, scaleY:0, ease:Circ.easeIn});

            //munculkan materi
            if (e.currentTarget == tombolMenu[i]){
                trace(jumlahFrame[i]);
                navi_mc.visible=true;
                TweenLite.from(navi_mc, 1, {delay:4, y:700});
                TweenLite.to(judulMateri[i], 1, {delay:3, x:89.45, y:36.45, ease:Back.easeOut});
                TweenLite.to(isiMateri[i], 1, {delay:3.4, x:392.45, y:246.95, ease:Back.easeOut});
                navi_mc.next_mc.addEventListener(MouseEvent.CLICK, fl_next);
                navi_mc.prev_mc.addEventListener(MouseEvent.CLICK, fl_prev);
                //navi_mc.home_mc.addEventListener(MouseEvent.CLICK, fl_home);
                navi_mc.prev_mc.alpha = 0.4;
                navi_mc.home_mc.alpha = 0.4;
                navi_mc.prev_mc.mouseEnabled = false;
                navi_mc.home_mc.mouseEnabled = false;

and get this error
TypeError: Error #1010: A term is undefined and has no properties. at MethodInfo-258()

when run
function fl_next(e:MouseEvent):void{
                    for(var i:int = 0; i<= isiMateri.length; i++){
                        isiMateri[i].nextFrame();
                        if(isiMateri[i].currentFrame == 2 ){
                            navi_mc.prev_mc.alpha = 1;
                            navi_mc.prev_mc.mouseEnabled = true;
                        }
                        if(isiMateri[i].currentFrame == jumlahFrame[i]){
                            trace(isiMateri[i].currentFrame);
                            navi_mc.next_mc.alpha = 0.4;
                            navi_mc.next_mc.mouseEnabled = false;
                            navi_mc.home_mc.alpha = 1;
                            navi_mc.home_mc.mouseEnabled = true;
                        }

the full code is in first post.
is something wrong with my array function to thw TweenLite action?


text:
Q: Sum specific properties values of objects in array if they have same property name and return unique array as result using java script my problem is to map two array of objects and sum their specifics properties if they have same name value.
For example if I would like to sum x and y of all objects where property name is 'v' etc.
Here is my code
var arr = [{name:'v', x:1, b:2, c:3},{name:'r', x:2, b:0, c:3},{name:'v', x:4, b:3, c:3}, {name:'v', x:1, b:1, c:3}];
let arr2 = []
let obj = {name:null, x:null, b: null, c:null}
arr.map(item => {
for(let i=0; i<= arr.length; i++){

    if(item.name === arr[i].name){
     let a = arr.reduce((a, b) => ({x: a.x + b.x, b: a.b + b.b}));
      obj.name = item.name, obj.x = a.x, obj.b = a.b, obj.c = item.c
    } else {
    obj.name = item.name, obj.x=item.x, obj.b=item.b, obj.c=item.c
        }
  arr2.push(obj)
        }
  }
)

console.log(arr2)

As result i would like to return array like this
arr2 = [{name: 'v', x: 6, b: 6, c: 3}, {name: 'r', x:2, b:0, c:1}]

A: const sumProperties = (arr) => {
  const result = [];
  const map = new Map();
  for (const obj of arr) {
    const key = obj.name;
    if (!map.has(key)) {
      map.set(key, obj);
    } else {
      const oldObj = map.get(key);
      const newObj = { ...oldObj, ...obj };
      map.set(key, newObj);
    }
  }
  map.forEach((value) => {
    result.push(value);
  });
  return result;
}
console.log(sumProperties(arr));

A: Here is the answer for my question
var arr = [{v:'v', x:1, b:2, c:3},{v:'r', x:2, b:0, c:3},{v:'v', x:4, b:3, c:3},{v:'v', x:10, b:3, c:3},{v:'r', x:1, b:1, c:3},{v:'v', x:11, b:2, c:3},{v:'r', x:22, b:0, c:3}];
let arr2 = []
for(let j=0; j< arr.length;j++){
    for(let i=j+1; i< arr.length; i++){
        let obj = {v:null, x:null, b: null, c:null}
        if(arr[j].v === arr[i].v ){
          let a =  arr.filter(({v})=> v === arr[j].v).reduce((a, b) => ({x: a.x + b.x, b: a.b + b.b}));
        obj.v = arr[j].v
        obj.x = a.x
        obj.b = a.b
        obj.c = arr[j].c
        i= arr.length
        console.log("DA", obj)
        if(!arr2.some(item=> item.v === obj.v)){
            arr2.push(obj)
        }
    } else if(i+1 === arr.length){
        obj.v = arr[j].v
        obj.x = arr[j].x
        obj.b = arr[j].b
        obj.c = arr[j].c
        console.log("NE", obj)
        if(!arr2.some(item=> item.v === obj.v)){
            arr2.push(obj)
            }
        }
    }
}
console.log(arr2, "REZ")

A: var arr = [{name:'v', x:1, b:2, c:3},{name:'r', x:2, b:0, c:3},{name:'v', x:4, b:3, c:3}, {name:'v', x:1, b:1, c:3}];

arr.reduce((acc,curr)=>{
     if(!acc[curr.name])
     {
         acc[curr.name] = {name:curr.name, x:0, b:0, c:0};
     }
     acc[curr.name].x +=curr.x;
     acc[curr.name].b +=curr.b;
     acc[curr.name].c +=curr.c;

     return acc;

    },{})

Expected Output:
{
    "v": {
        "name": "v",
        "x": 6,
        "b": 6,
        "c": 9
    },
    "r": {
        "name": "r",
        "x": 2,
        "b": 0,
        "c": 3
    } }


text:
Q: How do i check my object permissions in spring security acl instead of using hasPermission annotation Is there a way to check my class object permissions directly from my code instead of having the annotation model,
@PostAuthorize("hasPermission(returnObject, 'WRITE')")
public BaseData getSingle(Long id);

A: Assuming you're intending to use the ACL module, the expression is implemented in AclPermissionEvaluator. So you can wire up an instance of that with an AclService, inject it into the classes that need it and call the hasPermission method directly.

A: At-last after several tries i could achieve to get the solution, following is the code
acl-conf.xml
...
<bean class="org.springframework.security.acls.AclPermissionEvaluator" id="permissionEvaluator">
        <constructor-arg ref="aclService"/>
</bean>
...

samplecontroller.java
 @Autowired
    private PermissionEvaluator permissionEvaluator ;

    Permission permission = BasePermission.WRITE;
   permissionEvaluator.hasPermission(authentication,aclObject,permission);
....

Hope this is helpful.


text:
Q: Oracle dialect for Oracle12c database So far we have been using the dialect org.hibernate.dialect.Oracle9Dialect
for hibernate.dialect property for all Oracle versions (10g/11g). We plan
to use Oracle12c as well. Our initial tests indicate that continuing with
Oracle9Dialect for Oracle12c will work. Does anyone have any suggestions/
recommendations/use cases where we would need to use a different dialect for
Oracle12c while maintaining backward compatibility with earlier Oracle versions
(10g/11g) ?
It would be great if some one can point me to an existing wiki/documentation
which I might have missed on oversight.

A: I was using the Oracle10gDialect, but Jboss 6.1 failed to start properly.  I had to remove Hibernate 3.6.6 and install Hibernate 4.2.15 and make a few code changes to properly support 12c.  To be clear, I think the old dialect would work, but JBoss didn't seem to like it.


text:
Q: Failed to init entropy source hwrng https://bugzilla.redhat.com/show_bug.cgi?id=1679010
seeing this log:
Failed to init entropy source hwrng

Does Intel or AMD CPU contain a hwrng device? or it need extra chip/card/device?

A: No, a CPU typically does not contain a hwrng device. Instead, modern x86 CPUs with hardware RNG capabilities typically have a RDRAND instruction. It was introduced by Intel in the Ivy Bridge generation (in 2012) and AMD copied it in 2015.
A hwrng device is typically a feature of the system chipset, to provide a hardware RNG even if a processor that doesn't have the RDRAND instruction is installed, or of a security module or cryptographic accelerator card that provides a hardware RNG as an adjunct to their main functionality. There are also dedicated hardware RNG devices, like the LavaCan of the LavaRNG project.
Since RDRAND is now ubiquitous in modern x86 CPUs, the chipset designers might as well start omitting the hwrng device in new chipsets to simplify their designs.


text:
Q: Dafny: Violation of precondition in must-be-true constant case Dafny cannot validate the m method for the following code:
predicate p(k: int)
requires k >= 0
{
    true
}

method m() returns (k: int)
    ensures p(k) //<-
{
    k := 0;
}

It reports possible violation of function precondition for the ensure line, which is k>=0. This certainly cannot be a violation as the parameter is literally a constant 0 (0=0), why does dafny think this is not in compliance? And how do I fix it?

A: Good question! In Dafny, all expressions have what is called a "well-formedness condition", which checks things like function preconditions, sequence indices in bounds, etc. All expressions are required to be well formed, and this is checked by Dafny conceptually before verifying the program.
For expressions used as part of a method specification, they have to be well formed in isolation, independently of the method body. So in your example, Dafny tries to check the expression p(k) is well formed without looking at the body of the method, which is why it fails.
The typical way to fix this error is to change the postcondition to guarantee well formedness in isolation. In your example, you can do this by changing your postcondition to
ensures k >= 0 && p(k)


text:
Q: Как можно сверстать данную картинку Что нужно использовать, что бы сверстать такую картинку с шестиугольной обводкой вместе с еще более мелками картинками

A: Видео о том как я рисовал это

.svg {
  width: 600px;
  margin: auto;
}

.red {
  fill: red;
}

.green {
  fill: green;
}

.blue {
  fill: blue;
}

.yellow {
  fill: yellow;
}

.pink {
  fill: pink;
}

.parent {
  stroke-width: 1.6;
  stroke: #d90000;
  stroke-linecap: round;
  stroke-linejoin: round;
  fill: none;
}
<div class="svg">
  <svg viewBox="-3 193 150 106" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
   <defs>
     <clipPath id="clip">
       <path  d="m31.972691 296.86328 23.906994-13.60714 0.0945-27.11979-24.190476-14.17411-23.906994 13.51265 0.1889881 27.87574s23.151042 13.41816 23.906994 13.51265z"/>
     </clipPath>
    </defs>
   <path  class="red" d="m0.5061738 223.81938 15.874999-9.16592 15.40253 8.88245v18.42633l-15.886812 8.98875-15.674199-8.98875z" />
    <image xlink:href="https://s.tb.ru/uploads/site232863/6a476d28-ef4b-49c7-a9f9-88218979d244/6a476d28-ef4b-49c7-a9f9-88218979d244-1560866832327.jpeg" x="0" y="242" width="60" height="60"  clip-path="url(#clip)"/>

  <path  class="blue" d="m64.48339 260.97847 16.342722-9.47233-0.188987-18.42634-15.591517-8.97694-15.969496 9.26042 0.0945 18.70982z"/>
   <path  class="yellow" d="m80.637125 233.0798 15.308035-9.26042-0.283482-17.76488-15.024553-8.88244-15.875 9.07143 0.283483 17.85937z"/>
   <path  class="pink" d="m95.94516 223.81938 23.52902-13.32366 23.907 13.60714v27.1198l-24.37947 13.98511-23.434526-13.89062z"/>
   <path  class="parent" d="m0.5061738 223.81938 15.874999-9.16592 15.40253 8.88245v18.42633l17.386909 10.11086-0.0945-18.70982 15.969496-9.26042-0.283483-17.85937 15.875-9.07143 15.024553 8.88244 0.283482 17.76488 23.52902-13.32366 23.907 13.60714v27.1198l-24.37947 13.98511"/>
  </svg>
</div>


text:
Q: Implementing onData in 'dart:html' dispatchEvent I am developing an application but I noticed that each class has a lot of similar code to the one below addRace method in the class below:
@CustomTag( 'race-view' )
class RaceViewForm extends PolymerElement
{
  RaceViewForm.created() : super.created();

  void addRace( Event e, var detail, Element target )
  {
     var raceElem = $['race'];

    if( raceElem.children.length < 1 )
    {
      raceElem.children.add( new Element.tag( 'race-form' ) );
    }

    raceElem.on[ DELETE_BUTTON_FORM_EVENT ]
            .listen( (Event e)
                {
                   (e.target as Element).remove();
                   dispatchEvent( new CustomEvent( RACE_VIEW_EVENT, detail:new Race() ));
                });

  }

}

I have attempted to move the repeating code into a library called shared.dart with the following refactoring:
  import 'dart:html';
  import 'package:observe/observe.dart';
  ...

  void addForm( Element target, String eventName, String dispatchEventName, dynamic instance )
  {
    var element = target;

    if( element.children.length < 1 )
    {
      element.children.add( new Element.tag( 'race-form' ) );
    }

    element.on[ eventName ]
            .listen( (Event e)
                {
                   (e.target as Element).remove();
                  dispatchEvent( new CustomEvent( dispatchEventName, detail:instance ));
                });

  }

However, the dart IDE flags the dispatchEvent method in the addForm method as being not defined with parameter onData (dynamic) -> void. Given that dispatchEvent is in the 'dart:html' package, I am uncertain as to what to do next.

A: I didn't find a dispatchEvent() in dart:html (top level) only as method of the Node class. You need to pass your Polymer element instance to the library method.
You could implement it as a mixin to make it easier to reuse.
See https://github.com/donny-dont/Pixelate/blob/master/lib/components/expander/expander.dart#L41 (Expandable, Customizeable) for an example.


text:
Q: Can we validate the primary key field for uniqueness in cakephp validation? I am doing form validation using cakephp validation method. My form has product_id field which is primary key in database.I am validating my product_id field for uniqueness but it is not getting validate. I could not able to find the root cause. what might be the case?
Thanks
Pushpa

A: Here is where it specifies the details of isUnique model validation:
http://book.cakephp.org/view/1166/isUnique
If you're doing it per the instructions, it should work just fine.  Beyond that, there's nothing we can do to help.

A: primaries should be per definition unique and therefore checking for this is superfluous.
the framework provides you with unique keys both for AIIDs and UUIDs
in your case it seems this is actually a foreign_key is this relation.
so your question was wrongly stated.
you want to check on a simple isUnique for a single row.
isUnique is the validation rule you are looking for.
http://book.cakephp.org/view/1166/isUnique


text:
Q: How to check and limit length of a video in the app I have recently built an application where user could able to sell their used items. In my current design, I have limited my app to post a single app per product. However, I am getting complaints from the user with this limitations.
Now I am trying to add new features, one of them is a video support. I wonder how to check and limit a video with certain seconds. The instagram or Vime allows 15 and 5 sec video accordingly. I wonder how could I able to check the duration of the video?


text:
Q: Wait till I receive signal in Java multi thread I have a multi threaded application which receives asynchronous messages. How to wait till message is received (or timeout)?Is there a better way to do this with wait() and notify()?
I tried to do this with raw thread sleep with atomic references.
class SignalReceiver{
    String message;
    Boolean messageReceived; // used AtomicBoolean

    void receive(String message){
        this.message = message;
        messageReceived = true; // set message flag
    }

    void waitTillMessageReceived(long timeout){
       if(!messageReceived){ // message could be received before
          while(!messageReceived){
              Thread.sleep(100);
              // wait only till timeout
          }
       }
       messageReceived = false; // reset message flag
    }
}

A: This is an exampre with wait / notify
public class SignalReceiver{
String message;
public static void main(String[] args) {
    final SignalReceiver sr=new SignalReceiver();

    new Thread(() -> {
        try {
            Thread.sleep(2000L);
        } catch (InterruptedException e) {
        }
        System.out.println("message sent");
        sr.receive("hello");
    }).start();;

    System.out.println("waiting...");
    String mess=sr.waitTillMessageReceived(5000L);

    System.out.println("message: "+mess);
}

public synchronized  void receive(String message){
    this.message = message;
    notify();
}

public synchronized String waitTillMessageReceived(long timeout){
   try {
       wait(timeout);
   }
   catch (InterruptedException e) {

   }
   return message;
}

}
The example presents some problems. For example it does not handle properly the arrival of many simultaneous messages.
As suggested in comments, it is better to use proper synchronised classes like java.util.concurrent.LinkedBlockingDeque.

A: BlockingQueue
I followed the lead provided by Louis Wasserman and by markspace, suggesting the use of a queue.
I went with a BlockingQueue which is (a) thread-safe, and (b) can block when adding & removing elements. I started with the example code given on the Javadoc for that interface.
For an implementation of the BlockingQueue interface, I chose ArrayBlockingQueue.
I created a pair of producer-consumer classes. They produce and consume a randomly-generated UUID value via the UUID class.
Here is the producer class. In an endless loop, the run method attempts to add a UUID object to the queue. The attempt to add blocks if the queue is currently busy, continuing when the queue becomes available. If interrupted, such as by the closure of the executor service, this run method completes, thereby ending the submitted task.
package work.basil.example.async;

import java.time.Duration;
import java.time.Instant;
import java.util.UUID;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ThreadLocalRandom;

public class Producer implements Runnable
{
    // Member fields.
    private final BlockingQueue < UUID > queue;

    // Constructor.
    Producer ( BlockingQueue < UUID > q ) { queue = q; }

    public void run ( )
    {
        System.out.println( "`Producer` object is starting its `run` method. " + Instant.now() );
        try
        {
            while ( true )
            {
                // Sleep, to simulate some lengthy work.
                Duration timeToSleep = Duration.ofMillis( ThreadLocalRandom.current().nextInt( 1_000 , 3_000 ) );
                try { Thread.sleep( timeToSleep ); } catch ( InterruptedException e ) { break; }
                queue.put( produce() );  // Post a new value to our BlockingQueue.
            }
        }
        catch ( InterruptedException e )
        {
            // Could be interrupted by an executor service closing, or other reasons.
            // Simply let this `Runnable` object end its `run` method.
            // No code needed here.
        }
        System.out.println( "`Producer` object is ending its `run` method, after being interrupted. " + Instant.now() );
    }

    // Logic
    UUID produce ( )
    {
        UUID uuid = UUID.randomUUID();
        System.out.println( "Producing UUID = " + uuid + " at " + Instant.now() );
        return uuid;
    }
}

And the consumer class. The run method asks for the next available element from the queue. The call blocks until an element becomes available. While waiting, if an interrupt happens such as when the executor service closes, the run method completes, thereby ending the submitted task.
package work.basil.example.async;

import java.time.Instant;
import java.util.UUID;
import java.util.concurrent.BlockingQueue;

public class Consumer implements Runnable
{
    private final BlockingQueue < UUID > queue;

    Consumer ( BlockingQueue < UUID > q ) { queue = q; }

    public void run ( )
    {
        System.out.println( "`Consumer` object is starting its `run` method. " + Instant.now() );
        try
        {
            while ( true ) { consume( queue.take() ); }
        }
        catch ( InterruptedException e )
        {
            // Could be interrupted by an executor service closing, or other reasons.
            // Simply let this `Runnable` object end its `run` method.
            // No code needed here.
        }
        System.out.println( "`Consumer` object is ending its `run` method, after being interrupted. " + Instant.now() );
    }

    void consume ( UUID uuid )
    {
        System.out.println( "Consuming UUID: " + uuid + " at " + Instant.now() );
    }
}

And an app class to demonstrate the queue in action.
Be aware that you are responsible for gracefully closing your executor service at some point, at least by the end of your app's execution. Otherwise the backing pool of threads may run indefinitely, like a zombie ♂.
package work.basil.example.async;

import java.time.Duration;
import java.time.Instant;
import java.util.concurrent.*;

public class App
{
    public static void main ( String[] args )
    {
        System.out.println( "INFO - Demo start. " + Instant.now() );

        BlockingQueue q = new ArrayBlockingQueue( 10 , true );
        Consumer c = new Consumer( q );
        Producer p = new Producer( q );

        ExecutorService executorService = Executors.newFixedThreadPool( 2 );
        executorService.submit( c );
        executorService.submit( p );

        // Let the background threads do their work for a while.
        try { Thread.sleep( Duration.ofSeconds( 8 ) ); } catch ( InterruptedException e ) { throw new RuntimeException( e ); }
        System.out.println( "INFO - Main thread is interrupting tasks run by executor service." );
        executorService.shutdownNow();
        try
        {
            if ( ! executorService.awaitTermination( 30 , TimeUnit.SECONDS ) )
            {
                System.err.println( "Executor service failed to terminate. " + Instant.now() );
            }
        }
        catch ( InterruptedException e ) { throw new RuntimeException( e ); }

        System.out.println( "INFO - Demo end. " + Instant.now() );
    }
}

This seems to be working.
INFO - Demo start. 2023-02-28T07:24:03.603169Z
`Consumer` object is starting its `run` method. 2023-02-28T07:24:03.614092Z
`Producer` object is starting its `run` method. 2023-02-28T07:24:03.614092Z
Producing UUID = 5fe7dd8a-9cc1-47b8-93aa-87bc031c2534 at 2023-02-28T07:24:04.855110Z
Consuming UUID: 5fe7dd8a-9cc1-47b8-93aa-87bc031c2534 at 2023-02-28T07:24:04.863520Z
Producing UUID = 97a31391-8c5c-4430-9737-b967a8c63987 at 2023-02-28T07:24:06.678767Z
Consuming UUID: 97a31391-8c5c-4430-9737-b967a8c63987 at 2023-02-28T07:24:06.679680Z
Producing UUID = af485e45-5dd5-4b68-82c8-41e1443c4566 at 2023-02-28T07:24:08.337011Z
Consuming UUID: af485e45-5dd5-4b68-82c8-41e1443c4566 at 2023-02-28T07:24:08.337917Z
Producing UUID = 4853a43c-feb6-41ec-91b0-1520c9f67347 at 2023-02-28T07:24:10.927173Z
Consuming UUID: 4853a43c-feb6-41ec-91b0-1520c9f67347 at 2023-02-28T07:24:10.928794Z
INFO - Main thread is interrupting tasks run by executor service.
`Consumer` object is ending its `run` method, after being interrupted. 2023-02-28T07:24:11.619844Z
`Producer` object is ending its `run` method, after being interrupted. 2023-02-28T07:24:11.619725Z
INFO - Demo end. 2023-02-28T07:24:11.621988Z

Caveat: I am no expert on concurrency matters. Use at your own risk.


text:
Q: javascript indexof issue I have the following code on datatables
var colData = table.column(0).data({
    order: 'index'
}).toArray();
var pos;

for (var j = 0; j < csv.length; j++) {
    pos = colData.indexOf(csv[j][PKField]);

    console.log(pos)
    if (pos === -1) {
        // it exists, so we need to add to update list
        // toUpdate.push(csv[j]);
        // toUpdateIds.push(pos);
        console.log("ID found: "+ csv[j][PKField]);
        delete colData.splice(pos);
        continue;
    } else {
        // doesn't exist, so add to create list
        console.log("New ID to import "+ csv[j][PKField]);
        toCreate.push(csv[j]);
    }
...
}

I have a csv with 4 rows. 3 entries exists in the database. The 4th is new.
When I import the csv I get the below results
POS: -1 ID found: 1371
POS: -1 ID found: 1450
POS: -1 ID found: 1485
POS: -1 ID found: 99999

What is wrong with the IF statement and the last row (99999) cannot be inserted on the table?


text:
Q: MVC3 Custon Validation Attribute Using Two Properties I'm trying to write a custom validation class that validates that an email is not already is use.  To do this, I have a method that counts the userprofiles that have the email address in question.  Simple enough, but if the user is updating their profile, I need to exclude their profile from the count I mentioned about.  So to do that, I have written the following method:
public static bool IsEmailUnique(string email, int userprofileId)
{
    int count = -1;

    using (var db = new TRDataContext())
    {
        count = (from u in db.Userprofiles
                 where u.email == email &&
                       (userprofileId == 0 || u.userprofile_id != userprofileId)
                 select u).Count();
    }

    return count == 0;
}

This works well in the custom validator class for new users as all I need to do is pass a 0 in for the userprofile_id.
public class EmailValidatorAttribute : ValidationAttribute
{
    public override bool IsValid(object value)
    {
        if (value == null)
            return false;

        return Userprofile.IsEmailUnique(value.ToString(), 0);
    }
}

and implemented like this
[DisplayName("Email Address")]
[Required(ErrorMessage = "Required")]
[RegularExpression(EmailRegex, ErrorMessage = "Invalid email address")]
[EmailValidator(ErrorMessage = "Already in use")]
public string email { get; set; }

However, I now need to pass into the EmailValidator the userprofile_id of that current user.  I am having a difficult time figuring this one out.
Any help would be greatly appreciated.
Thanks!

A: You could fetch this from the HttpContext:
string currentUsername = HttpContext.Current.User.Identity.Name;

and before I am sentenced for proposing the usage of HttpContext.Current in a method, you could use a provider:
public class EmailValidatorAttribute : ValidationAttribute
{
    public Func<HttpContextBase> ContextProvider = () => new HttpContextWrapper(HttpContext.Current);

    public override bool IsValid(object value)
    {
        if (value == null)
            return false;

        string currentUsername = ContextProvider().User.Identity.Name;

        ...
    }
}

which could now be easily mocked in a unit test.

A: I have had a similar issue. Firstly I implemented a 'CurrentUser' method in my user repository that looks a little something like this:
        //Gets the current user
        public U_USER CurrentUser()
        {
            return GetUser(HttpContext.Current.User.Identity.Name);
        }

        public U_USER GetUser(string u)
        {
            return (from us in db.U_USER
                    where us.UserName == u
                    select us).FirstOrDefault();
        }

You can then use this to get the id from inside your validation attribute in a manner similar to the below:
public class EmailValidatorAttribute : ValidationAttribute
{
    public override bool IsValid(object value)
    {
        using(UserRepository ur = new UserRepository())
        {
           if (value == null)
               return false;

           var user = ur.CurrentUser();
           return Userprofile.IsEmailUnique(value.ToString(), user.userprofile_id);
        }
    }
}


text:
Q: Improper integral: $\int_1^{+\infty}\frac{\mathrm dx}{x(x+1)(x+2)\cdots(x+n)}$ I've tried many ways, but it seems that it didn't work:
$$
   \int_1^{+\infty}\frac{\mathrm dx}{x(x+1)(x+2)\cdots(x+n)}
    = \int_0^1\frac{x^{n-1}}{(x+1)(2x+1)\cdots(nx+1)}\mathrm dx
    = \cdots
$$
Any help would be appreciated!

A: If you sub $x=u+1$ then you get
$$\int_0^{\infty} \frac{dx}{(x+1)(x+2)\cdots(x+n+1)} $$
Try evaluating via residue theorem.  Consider the contour integral
$$\oint_C dz\frac{\log{z}}{(z+1)(z+2)\cdots(z+n+1)} $$
where $C$ is a keyhole contour about the positive real axis of outer radius $R$ and inner radius $\epsilon$.  Take the limits $R\to \infty$ and $\epsilon \to 0$ and get that the contour integral is
$$-i 2 \pi \int_0^{\infty} \frac{dx}{(x+1)(x+2)\cdots(x+n+1)} $$
This is equal to $i 2 \pi$ times the sum of the residues of the poles of the integrand.  In this case, we obviously have poles at $-1 \ldots-n$.  Keep in mind the branch cut we took using $C$ so the negative is actually $e^{i \pi}$.  The integral is then, taking respective real parts,
$$\begin{align} \int_0^{\infty} \frac{dx}{(x+1)(x+2)\cdots(x+n+1)} &= -\sum_{k=1}^{n+1} \frac{\log{k}}{\displaystyle \prod_{j=1 \cap j \ne k}^{n+1} (-j+k)}\\ &= \sum_{k=2}^{n+1} (-1)^{k} \frac{\log{k}}{(k-1)!(n+1-k)! } \\ &= \frac1{(n+1)!} \sum_{k=2}^{n+1} (-1)^{k} \binom{n+1}{k}k \log{k}\end{align}$$

A: We have the partial fraction decomposition
$$\frac{1}{x(x+1)(x+2)\cdots(x+n)}=\frac{a_0}{x}+\frac{a_1}{x+1}+\frac{a_2}{x+2}+\ldots+\frac{a_n}{x+n}$$
Now as $x\to 0$, the part with $a_0$ dominates, and we have
$$a_0=\lim_{x\to0}\frac{x}{x(x+1)(x+2)\cdots(x+n)}=\frac1{n!}$$
Similarily, as $x\to -1$, the part with $a_1$ dominates, and we have
$$a_1=\lim_{x\to-1}\frac{x+1}{x(x+1)(x+2)\cdots(x+n)}=-\frac1{(n-1)!}$$
and if you were to continue this idea, you'd find that
$$a_k=\lim_{x\to -k}\frac{x+k}{x(x+1)(x+2)\cdots(x+n)}= \frac{(-1)^k}{k!(n-k)!}=\frac{(-1)^k {n\choose k}}{n!}$$
so that
$$\frac{1}{x(x+1)(x+2)\cdots(x+n)}=\frac1{n!}\sum_{k=0}^n\frac{(-1)^k {n\choose k}}{(x+k)} $$
and so
$$\int_1^{\infty}\frac{\mathrm dx}{x(x+1)(x+2)\cdots(x+n)}
=\frac{1}{n!}\int_1^{\infty}\sum_{k=0}^n\frac{(-1)^k {n\choose k}}{(x+k)}\\
=\frac1{n!}\left(\sum_{k=0}^n(-1)^k {n\choose k}\ln(x+k)\right)\left. \right|_1^\infty$$
For $x=\infty$, consider the binomial expansion of $(1-1)^k$. It implies that the sum of the positive binomial terms is equal to the sum of the negative binomial terms, and so if we combine all the logs into one, we get the logarithm of a polynomial divided by a polynomial of the same degree, so the limit to infinity is hence $\ln(1) = 0$. So then the integral is thus equal to the negative of the antiderivative above at $x=1$, so
$$\frac{1}{x(x+1)(x+2)\cdots(x+n)}=\frac1{n!}\sum_{k=0}^n(-1)^{k+1} {n\choose k}\ln(k+1)\\=\frac1{n!}\sum_{k=2}^{n+1}(-1)^{k} {n\choose k-1}\ln(k)$$


text:
Q: Nginx proxy_set_header Host for RPC management We're experimenting with an RPC service (linkerd) that acts as a glue between our microservices – reading off their locations from a local Consul cluster etc. Now Linkerd expects to see the Host header on an incoming request to figure out which service to hit.
In our topology, we have nginx running as the edge which is then supposed to proxy to Linkerd and set the Host header depending on the path.
So a simple configuration we're testing looks like this;
    location /api/v1/services/service-x {
            proxy_set_header Host service-x;
            proxy_pass http://linkerd:4140;
    }

Which is nothing fancy. It matches the paths that are the paths of service-x, then attempts to proxy_pass those requests to linkerd with the name of the service set in the header Linkerd is supposed to receive.
What we're seeing is that the Host header is never set. The service is reachable via Linkerd if I curl -H "Host: service-x" linkerd:4140/some/x/path.
How are we supposed to set headers for upstreams with nginx? Or am I doing something stupid?
Thanks!

A: This was actually something I had missed – linkerd supports HTTP/1.1 out of the box and nginx was using 1.0 to forward to the linkerd service.
Adding
proxy_http_version 1.1

Fixed the issue for me.


text:
Q: Changing field type with ArcPy? What I need to do is change data type of a field of a table or feature class. If there are some data,  then I need to transfer it, if its possible, if not possible then just set null for that data. I need to do it using python script.
Problems:

*

*Because of before and after changing the data type, field name is same, I can not add new field with same name using arcpy.AddField_management method.

*Because of I need to transfer field values from first field to second one, I need to map both data types.

It will be good for me if I can find any ArcPy procedure similar to artwork21's answer to Renaming field using ArcPy?

A: There are essentially three options for making field schema changes in ArcGIS.

*

*Dropping the whole feature class/table and replacing it completely

*Dropping the field/column and replacing it -- this always puts the new column at the end, so not good if field order is important to you.

*Modifying column definitions in the underlying DBMS (dangerous, may cause corruption). This last one I wouldn't even go near unless you are in Oracle, and even then you have to be very careful (see this post).

It sounds like you want to go with option 2. The simplest way I can think of to do that is to add an intermediate/temporary column and calculate it from your original column. Then delete the original column, add a new column with the desired field type, calculate the new column from the intermediate column and finally delete the intermediate column.

A: You could do a simple "Feature Class to Feature Class" conversion. During this you can change field names and types, after that delete the original FC.

A: Depending on your ArcGIS for Desktop version and where you are storing your data, there is a tool called Alter Field (available at all license levels from 10.2.2; only Advanced at 10.2.1) that may be able to help you because it is designed to:

Rename fields and field aliases, or alter field properties.

However, be aware that if you only change the name, and not the alias too, then when you look at the attribute table, what is displayed as that field's heading will be the alias (i.e. the old field name).
To avoid this, which I find confusing, I always change both the name and the alias .
For example, if I want to change the OLDFIELD to be named NEWFIELD then I use something like:
# AlterField_management (in_table, field, {new_field_name}, {new_field_alias})
AlterField_management (r"C:\temp\test.gdb\testFC", "OLDFIELD", "NEWFIELD", "NEWFIELD")


text:
Q: Unchecked cast from Object, generic class and wildcards Here is my code:
public class ArrayTaskList<E> {
    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        ArrayTaskList<E> other = (ArrayTaskList<E>) obj;
        if (!Arrays.equals(db, other.db))
            return false;
        return true;
    }
}

And compiler says:

Type safety: Unchecked cast from object to arraytasklist

I understand, that it's jst an warning, but if i try this code, there are no warnings:
ArrayTaskList<?> other = (ArrayTaskList<?>) obj;

Is it more convenient solution?

A: The difference is that the raw type object is not typesafe while the unbounded wildcard gives you type safety.
For example with a raw type you can have code like this:
List list = new ArrayList<String>();
list.add(42); // integer
list.add(true); // boolean
list.add(whateverYouWant); // whatever you want

while this code:
List<?> list2 = new ArrayList<String>();
list2.add(42);
list2.add(true);

will cause a compiler error.

A: You could use the following implementation instead:
@Override
public boolean equals(Object obj) {
    return obj instanceof ArrayTaskList && obj.hashCode() == hashCode();
}

@Override
public int hashCode() {
    return Arrays.hashCode(db);
}

That way, there's no unchecked cast problem anymore ;)
But please note that due to type erasure,
new ArrayTaskList<String>().equals(new ArrayTaskList<Integer>())

will return true if both have the same db array, even if one used String while the other one Integer as class parameter.

A: When execution reaches that line, you know that obj is an instance of ArrayTaskList.
However, you don't know whether it is an ArrayTaskList<Integer> or ArrayTaskList<String> etc.
Thus, the cast generates a warning (you could try to cast a ArrayTaskList<Integer> to ArrayTaskList<String>).
However, you don't need the type information here, so using ArrayTaskList<?> would indeed be the better solution here.
EDIT:
I had some misconception here, since even using type's boundary would cause the warning.
As @svz pointed out, ArrayTaskList<?> won't add any assumptions and just enables type checking.
The compiler trusts you that the cast to ArrayTaskList is ok, while the warning is generated because you make the assumption of obj also having the type E. The compiler can't check that and thus issues the warning. With <?> or <? extends XYZ> the compiler will ignore the type but will raise errors if any method that might fail is invoked.
Consider the following example:
Your class is ArrayTaskList<E extends Number> and thus you'd cast to ArrayTaskList<Number> or ArrayTaskList<E> (where E could be Long for example).
In that case the compiler doesn't know whether E is of type Number, Long etc. and thus warns you, since obj could be a ArrayTaskList<Double> and casting that to ArrayTaskList<Number> would allow you to add Longs to a list of Doubles (ouch).
Hence the compiler warns you of that cast.
Casting to ArrayTaskList<?> would tell the compiler to ignore the type but raise errors if you called other.add(...), preventing you from accidential inconstencies.
Edit 2:
I still have some misconception here (I'll think more about this), but so far, here's a way to cast without a warning and still use any upper bound that E might provide:
public boolean equals(Object obj) {
  ...
  return equals_((ArrayTaskList<?>)obj);
}

protected boolean equals_(ArrayTaskList<? extends Number> other)
{
  if (!Arrays.equals(db, other.db))
        return false;
  return true;
}

A: You could also pass in the ArrayTaskList constructor an inscance of Class<E> clazz and then the cast can be done clazz.cast(...):
public class ArrayTaskList<E> {
    Class<ArrayTaskList<E>> clazz;

    public ArrayTaskList(Class<ArrayTaskList<E>> c) {
        clazz = c;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        ArrayTaskList<E> other = clazz.cast(obj);
        if (!Arrays.equals(db, other.db))
            return false;
        return true;
    }
}


text:
Q: How does the closest point change with respect to variation of the set Consider a one-parameter family of convex bodies $\Sigma_\varepsilon$ in $\mathbb{R}^n$, $-1 < \varepsilon < 1$. Let $z$ be a point not contained in $\Sigma_0$, and let $\pi^{\Sigma_\varepsilon}(z)$ be the unique point in $\Sigma_\varepsilon$ closest to $z$. How does $\pi^{\Sigma_\varepsilon}(z)$ change with respect to $\varepsilon$? I'm mostly interested in $d\pi^{\Sigma_\varepsilon}(z)/d\varepsilon |_{\varepsilon = 0}$, if the derivative exists.
I have not specified how $\Sigma_\varepsilon$ is parametrized. To make the question precise, assume $\Sigma_\varepsilon = \{x | f(\varepsilon, x) \leq 0\}$, where each $f(\varepsilon, \cdot)$ is a convex function, and the dependence on $\varepsilon$ is smooth. If other forms of parametrization give more meaningful results, please suggest.
My thoughts: If $f(\varepsilon, x)$ is sufficiently smooth, then $z - \pi^{\Sigma_\varepsilon}(z)$ should be parallel to $\nabla_x f$. This leads to a family of equations involving $x, \varepsilon$, and I could perform implicit differentiation.


text:
Q: Dedekind modular law Dedekind modular law. If $A,B,C$ are subgroups of a group $G$ with $A \subseteq B$ then $A(B \cap C) = B \cap AC$.
Below is what I want to prove.
Let K be a finite group with $K = LH$, where $L,H$ are subgroups of $K$ with relatively prime orders. If $U$ is a maximal subgroup of $L$ then $UH = HU$.
Proof:
$HU = HU \cap LH = (HU \cap L)H = (H \cap L)UH = UH$
Is my proof true?

A: There is a mistake in your proof.  When you state Dedekind's rule above, you assume $A, B, C$ are subgroups of a group.  So, to get your second equality using Dedekind's rule you assume $B= HU$ is a group, but that's what you are trying to prove. (Recall, $UH = HU$ if and only if $UH$ is a group.)


text:
Q: Ping Failure Without IPv6 Our user interface is communicating with another application on a different machine, often connecting using domain names.
On our network, when IPv6 is installed, DNS name resolution works great, all machines can be pinged and contacted fine.
When IPv6 is uninstalled, pinging the same DNS names returns an IP address on some distant subnet (24.28.193.9; local subnet is 192.168.1.1); our application is then unable to communicate. When IPv6 is reinstalled, the DNS resolution corrects itself.
Even without IPv6 when ping is not working, I can still browse other machines using Windows Explorer by entering \\\\MACHINE_NAME\\. I'm not sure why the name resolution seems to work here. We are working in the Windows XP SP2 environment.
The IPs of the machines can be pinged successfully. It is only the DNS names that do not resolve properly.
I looked for the address of our DNS server. All of our computers are pointing at the network gateway, which is a wireless router. The router has the same DNS server address listed when IPv6 is installed as it does when it isn't installed.
The strangest thing is that I just discovered that it does not matter what DNS name I ping. All pings to DNS names return the same address: "24.28.193.9".
I tried flushing the DNS Resolver Cache and registering DNS on the target machine and the source machine. All to no avail. The only DNS name that I can ping is the name of the current machine.
Any thoughts as to why our software can't communicate without IPv6 installed?

UPDATE:
OK, I've done a little more research now.
I looked for the address of our DNS server. All of our computers are pointing at the network gateway, which is a wireless router. The router has the same DNS server address listed when IPv6 is installed as it does when it isn't installed.
The strangest thing is that I just discovered that it does not matter what DNS name I ping. All pings to DNS names return the same address: "24.28.193.9".
I tried flushing the DNS Resolver Cache and registering DNS on the target machine and the source machine. All to no avail. The only DNS name that I can ping is the name of the current machine.
Any other suggestions? Thanks so much for your help.

A: You've got multiple things going on here

*

*DNS Name resolution

*Windows Name resolution

*IP-IP ICMP communication

You've written your question as if there's a problem with #3, but everything you describe points to the problem actually being with #1.  If you take resolution out of the question, can you ping the correct IPs with our without IPv6 installed?
It sounds like maybe you have an IPv6 name server installed that has correct information and the IPv4 name server is incorrect?  Are you receiving name servers via DHCP or hard coding?  What are the IPs of the name servers you are using when IPv6 is installed and when it isn't?

A: I know this is a late answer, but in case someone else has the same problem, the key is the IP address, "24.28.193.9". A quick Google search reveals it seems to be related to your ISP completely breaking the DNS protocol by returning a fixed IP address for all non-existent domain names (the correct answer would be NXDOMAIN). Your network gateway is most probably just forwarding your queries to your ISP's name servers.
Your systems are relying on the correct operation of the DNS protocol. They are expecting a NXDOMAIN answer before querying the name via other methods (most probably NetBIOS name resolution). Since the DNS server is completely broken and returning an incorrect answer, the correct address is never looked up.
The reason installing or uninstalling IPv6 changes the situation is most probably because something related to it is changing the name resolution order (to look up using other methods before trying DNS). So, a workaround would be to change the name resolution order yourself.
The real fix would be to either change to a better ISP (one which does not break established protocols) or run your own DNS server (which is what I started doing on all systems I administer ever since VeriSign pulled a similar stunt; theirs was even worse in that changing ISPs made no difference at all).
References:

*

* Warning: Road Runner DNS says nonexistent domains exist


text:
Q: SQLite Update or overwrite duplicates Here is how I create the table:
c.execute("""CREATE TABLE Campaigns (
            day text,
            firstname text,
            lastname, text)""")

Here is my sqlite insert method:
def insert_campaign(Day, FirstName, LastName):
        with conn:
                c.execute("INSERT INTO Campaigns VALUES (:day, :firstname, :lastname)",
                {'day':Day,'firstname':FirstName, 'lastname':LastName})

What I want is for this insert function to overwrite existing records.
For example if I already inserted:
3/25/2019 | John | Doe
3/26/2019 | Jane | Doe
3/27/2019 | Bob | Dylan

And I want to insert:
3/26/2019 | Jane | Doe
3/27/2019 | Bob | Dylan
3/28/2019 | Greg | Rogers

I want the result to be:
3/25/2019 | John | Doe
3/26/2019 | Jane | Doe
3/27/2019 | Bob | Dylan
3/28/2019 | Greg | Rogers

Right now it is adding everything, resulting in 6 rows, with duplicates.

A: First, if you do not want duplicates, you need to define the combination of all three columns as a unique or primay key:
c.execute("""CREATE TABLE Campaigns (
            day TEXT NOT NULL,
            firstname TEXT NOT NULL,
            lastname TEXT NOT NULL,
            PRIMARY KEY (day, firstname, lastname))""")

Then, you could use the replace statement:
def insert_campaign(Day, FirstName, LastName):
    with conn:
            c.execute("REPLACE INTO Campaigns VALUES (:day, :firstname, :lastname)",
            {'day':Day,'firstname':FirstName, 'lastname':LastName})


text:
Q: Override full mysql table Recently I stuck with a problem such that mysql table with memory engine got full, and an insertion failed (really really long php script). I quickly got rid of it, by checking before I insert whether there's already many rows and deleting them
if (query("Select count(*) As c From my_table")['c'] > $N)
{
    query("Delete from my_table Order by ID Limit " . round($N/2));
}

But that doesn't feel cool. Actually, I want mysql to do it for me. Now, the question:
is there a standard alternative to AUTO_INCREMENT, but which would return not LAST+1 every time, but LAST+1 (mod N). And which would let to just override lines with old ID column value. Is there such mechanism, or I have to implement it myself?
Thank you.


text: Q: MediaRecorder doesn't save mp4 until device turns off - android I wrote an Android application using MediaRecorder to record and save an Mp4. The code works, but the video will not appear in my gallery until I have turned my device off and back on again. The file doesn't save until the tablet, phone, etc. is turned off. It doesn't throw any type of error. Does anyone have any suggestions to why this issue may be occurring? I've looked everywhere and it seems like I am the only one with this issue. I have tried it on many devices and the problem remains.


text:
Q: Ext js editable grid I made a grid. How I can edit selected row in a modal window using ext js 4? This is my code:
Ext.create('Ext.grid.Panel', {
    title: 'Users',
    height: 200,
    width: 400,
    store: store,
    columns: [{
        header: 'Name',
        dataIndex: 'name'
    }, {
        header: 'Surname',
        dataIndex: 'surname'
    }, {
        header: 'Date of birth',
        dataIndex: 'date',
        xtype:'datecolumn',
        format: 'd/m/Y',
        flex:1
    }],
    renderTo: Ext.getBody()
});

A: @k_b
Check if this helps you, it is just one first step for you understand the logic.
Ext.define('User', {
    extend: 'Ext.data.Model',
    fields: [
        {name: 'name',  type: 'string'},
        {name: 'surname',  type: 'string'},
        {name: 'date',  type: 'date'}
    ]
});

var data = {
    users: [
        {
            name: 'Ed Spencer',
            surname : 'Jobs'
        },
        {
            name: 'Ed Spencer2',
            surname : 'Jobs2'
        }
    ]
};

var store = Ext.create('Ext.data.Store', {
    autoLoad: true,
    model: 'User',
    data : data,
    proxy: {
        type: 'memory',
        reader: {
            type: 'json',
            root: 'users'
        }
    }
});

Ext.create('Ext.grid.Panel', {
    title: 'Users',
    height: 200,
    width: 400,
    store: store,
    columns: [{
        header: 'Name',
        dataIndex: 'name'
    }, {
        header: 'Surname',
        dataIndex: 'surname'
    }, {
        header: 'Date of birth',
        dataIndex: 'date',
        xtype:'datecolumn',
        format: 'd/m/Y',
        flex:1
    }],
    listeners:
    {
       scope: this,
       selectionchange: function(model, records){
          var rec = records[0];
          if (rec) {

               var editform =   Ext.create('Ext.form.Panel', {
                  width: 390,
                  bodyPadding: 10,
                  renderTo: Ext.getBody(),
                  items: [{
                      xtype: 'textfield',
                      name: 'name',
                      fieldLabel: 'Name'
                   },
                   {
                      xtype: 'textfield',
                      name: 'surname',
                      fieldLabel: 'Surname'
                   }
                   ],
              buttons: [{
                text: 'Save',
                handler: function() {
                 var form = this.up('form');
                 form.updateRecord();
                 var record = form.getForm().getRecord();

                  Ext.Msg.alert('Record',record.get('name'));
                  record.save();
               }}]
              });

              Ext.create('Ext.window.Window', {
                  title: 'Edit',
                  height: 200,
                  width: 400,
                  layout: 'fit',
                  items: [
                  editform]
                  }).show();

              editform.getForm().loadRecord(rec);
          }
       }
    },
    renderTo: Ext.getBody()
});

https://jsfiddle.net/ep24cc30/4/