text:
Q: How do I hash my mongoose passport js passwords upon registrations? I am trying to figure out how to hash passwords upon user registration. I am using mongoose and passport js. Are there any node modules I can use to hash passwords that can be easily implemented with my current code? Here are my LocalStrategies:
// Passport login LocalStrategy
passport.use('login', new LocalStrategy({
    passReqToCallback : true
}, function(req, username, password, done) {
    // check in mongo if a user with username exists or not
    User.findOne({ 'username' :  username },
        function(err, user) {
            // In case of any error, return using the done method
            if (err)
                return done(err);
            // Username does not exist, log error & redirect back
            if (!user){
                console.log('User Not Found with username '+username);
                return done(null, false,
                    req.flash('message', 'User Not found.'));
            }
            // User exists but wrong password, log the error
            if (!user.validPassword(password)){
                console.log('Invalid Password');
                return done(null, false,
                    req.flash('message', 'Invalid Password'));
            }
            // User and password both match, return user from
            // done method which will be treated like success
            return done(null, user);
        }
    );
}));

passport.use('signup', new LocalStrategy({
        passReqToCallback : true
    },
    function(req, username, password, done) {
        findOrCreateUser = function(){
            // find a user in Mongo with provided username
            User.findOne({'username':username},function(err, user) {
                // In case of any error return
                if (err){
                    console.log('Error in SignUp: '+err);
                    return done(err);
                }
                // already exists
                if (user) {
                    console.log('User already exists');
                    return done(null, false,
                        req.flash('message','User Already Exists'));
                } else {
                    // if there is no user with that email
                    // create the user
                    var newUser = new User();
                    // set the user's local credentials
                    newUser.username = username;
                    newUser.password = password;
                    newUser.email = req.param('email');
                    // save the user
                    newUser.save(function(err) {
                        if (err){
                            console.log('Error in Saving user: '+err);
                            throw err;
                        }
                        console.log('User Registration succesful');
                        return done(null, newUser);
                    });
                }
            });
        };
    process.nextTick(findOrCreateUser);
}));

And here is my User model:
var mongoose = require("mongoose");

var UserSchema = new mongoose.Schema({
    username: String,
    email:  String,
    password: String,
    friends: [this]
});
UserSchema.methods.validPassword = function (pwd) {
    return (this.password === pwd);
}

module.exports = mongoose.model("User", UserSchema);

When I check my mongo dbs the passwords are not hashed. How do I hash them? Thanks so much!

A: You can use bcrypt-nodejs module for hashing passwords.
In your User Model
var mongoose = require("mongoose");
var bcrypt = require('bcrypt-nodejs'); // use const or import if you're using ES6

// store this funciton in some helper file, instead of storing it in this User Model.
var hash_password = function( password ) {
    let salt = bcrypt.genSaltSync(); // enter number of rounds, default: 10
    let hash = bcrypt.hashSync( password, salt );
    return hash;
},

var UserSchema = new mongoose.Schema({
    username: String,
    email:  String,
    password: String,
    friends: [this]
});

UserSchema.methods.comparePassword = function(password) {
    if ( ! this.password ) { return false; }
    return bcrypt.compareSync( password, this.password );
};

UserSchema.pre('save', function(next) {
    // check if password is present and is modified.
    if ( this.password && this.isModified('password') ) {
        this.password = hash_password(this.password);
    }
    next();
});

module.exports = mongoose.model("User", UserSchema);

In your LocalStrategies
You can remove the code for user.validPassword with code the block below.
...
// User exists but wrong password, log the error
// if (!user.validPassword(password)){
//  console.log('Invalid Password');
//      return done( null, false, req.flash('message', 'Invalid Password') );
// }
// // User and password both match, return user from
// // done method which will be treated like success
// return done(null, user);

if ( user && user.comparePassword( password ) ) {
    // user found, password is correct. do what you want to do
    return done(null, user);
} else {
    // user not found or wrong password.
    console.log('Invalid Password');
    return done( null, false, req.flash('message', 'Invalid Password') );
}
...


text:
Q: Hausdorff Distance Between Projective Varieties I wonder whether the following question was studied. Let $X,Y \subset \mathbb{P}^d(\mathbb{C})$ be two projective varieties, We can measure the Hausdorff distance $d_H(X,Y)$
between them in terms of the Fubini-Study metric. What happens if they are close to one another? For example, can one find an $\epsilon >0$ small enough, such that if $d_H(X,Y) < \epsilon$, then they have the same Hilbert polynomial? Are any results in this spirit known?

redpajama_set_name: RedPajamaStackExchange


text:
Q: SQL Cant change primary key column name after changing other column Can someone please tell me why this happens.  The original problem is as always much more complex, but I've created a simple test case to reproduce the issue.  First you need a table like so:
CREATE TABLE `test` (
  `test_a` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `test_b` int(11) DEFAULT NULL,
  PRIMARY KEY (`test_a`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Then you need to try to alter the table with this query:
ALTER TABLE `test`
    CHANGE COLUMN `test_b` `new_test_b` INT(11) NOT NULL AFTER `test_a`,
    CHANGE COLUMN `test_a` `new_test_a` INT(11) NOT NULL AUTO_INCREMENT FIRST;

and you get this result:
Unknown column 'test_a' in 'test'

I don't get it.  It works fine when you do each alteration separately but if you do them together it blows up.

Addendum...
After studying this a bit, i figured out a few things.  I took a guess that perhaps the compiler (or preprocessor or something) was evaluating the comma separated alter statements in reverse order, there-by changing the test_a column name before it got the the test_b (which would make the 'AFTER test_a' part not make sense..   This turned out to be wrong in testing because if you reverse the order of the statements like so:
ALTER TABLE `test
    CHANGE COLUMN `test_a` `new_test_a` INT(11) NOT NULL AUTO_INCREMENT FIRST,
    CHANGE COLUMN `test_b` `new_test_b` INT(11) NOT NULL AFTER `test_a`;

You end up with the same result.
Next I took the assumption that certain types of operations have precedence in a statement like this.  I assumed that all CHANGE COLUMN operations must be taking place before any column ordering operations such as 'AFTER test_a'  If this was the case, then it would make sense to reference the new column name in the ordering operation,  like so:
ALTER TABLE `test`
    CHANGE COLUMN `test_b` `new_test_b` INT(11) NOT NULL AFTER `new_test_a`,
    CHANGE COLUMN `test_a` `new_test_a` INT(11) NOT NULL AUTO_INCREMENT FIRST;

This worked.  So that must be the answer.  My question i guess has evolved now to what is the order of precedence of the various types of operations.
Note, sorry I am not going to mark any of the current answers correct as they do not actually answer the question, they simply offer alternative ways to do the same thing (or state the obvious).

A: You can do it this way:
ALTER TABLE `test`
    CHANGE COLUMN `test_b` `new_test_b` INT(11) NOT NULL AFTER `test_a`;
ALTER TABLE `test`
    CHANGE COLUMN `test_a` `new_test_a` INT(11) NOT NULL AUTO_INCREMENT FIRST;


text:
Q: Jquery get data for divs with attribute value I have a number of divs which have a id value of #result-1, #result-2 etc. So the divs have a prefix number at the end of them. I am getting the value of how many list items that divs has by doing the following:
$(document).ready(function () {

    var colorCount = $('#result-1 .item-result ul li');

    if (colorCount.length > 0)  {
       $('.test').html(colorCount.length + ' ' + 'Colours');
    }
    else {
       $('.test').hide();
    }
});

So at the moment I am targeting the first element only, How would I target the attribute based on the id or data-srch-position. The div has the following attributes:

So I would want to target either the div_id or the data-srch-position="1"
So the prefix number changes i.e id result-2 and data-srch-position="2" etc
The .test class is simply

 where the colorCount.length gets binded to for display.
JS Fiddle link:

A: First of .test will target every single .test element you have in the page, so in order to print a distinct and specific value it's not ideal since it will always be overwritten with the latest number found (...well unless that's your intent which is currently unclear)

*

*To read the data value you simple access the .data()

*Target distinct .test elements using .find() (if those are children elements)

$('[data-srch-position]').each((i, el) => {
  const n = $(el).data('srch-position');
  $(el).find('.test').text(n);
});

My srch:

My srch:

My srch:

My srch:

What is  anyways...

or you could go the other way around, target each child .test and than search the parent data-* attribute value using .closest('parent or self selector'):

$('.test').each((i, el) => {
  const n = $(el).closest('[data-srch-position]').data('srch-position');
  $(el).text(n);
});

My srch:

My srch:

My srch:

My srch:

What is  anyways...

Given your jsFiddle example, you could move the data-* selector into the desired elements instead and use a selector as target:

$('[data-count-li]').each(function() {
  const selector = $(this).data('count-li'); // Get the ID selector
  const $LI = $(selector).find('li');        // Find the selector's LI elements
  const LI_total = $LI.length;               // How many LI elements

  if(LI_total) { // If higher than 0
    $(this).show().text(`FOUND: ${LI_total} LI ELEMENTS`); // SHOW AND PRINT NUMBER
  }
});
[data-count-li] {
  display: none;  /* HIDE BY DEFAULT (SHOW USING JS) */
}

1

2

Test

1

2

3

Test

1

2

3

4

Test

A: Here is what I believe you want to happen.

$(document).ready(function () {
    var colorCount = $('.search-item[data-srch-position]');

    $(colorCount).each(function(i, value){
        ($(this).text().length > 0) ? console.log('true') : console.log('false');
    })
});

test1

test2


text:
Q: Comparison of experimental running time of algorithm vs. theoretical running time functions I'm writing simple algorithm for comparing if two vectors a1 and a2 of integers are anagrams (they contain the same elements in different orders). For example {2,3,1} and {3,2,1} are anagrams, {1,2,2} and {2,1,1} are not.
Here is my algorithm (it's very simple):
1. for ( i = 1; i <= a1.length; i++ )
 1.1. j = i
 1.2. while ( a1[i] != a2[j] )
  1.2.1. if ( j >= a1.length )
   1.2.1.1. return false
  1.2.2. j++
 1.3. tmp = a2[j]
 1.4. a2[j] = a2[i]
 1.5. a2[i] = tmp
2. return true

Representation of comparing two anagrams:

Lets consider function of running time dependent on vector sizes T(n) when they are anagrams in two situations: pesimistic and average.

*

*pessimistic

Occurs when vectors doesn't have duplicate elements and vectors are in reverse orders.

Multiplicity in c3, c4 and c6 are:

So the final function for pesimistic running time is:

Equation (3) can be written in a simpler form:

*

*average

Occurs when vectors doesn't have duplicate elements and vectors are in random orders. Critical assumption here is that: on average we find corresponding element from a1 in half of not sorted a2 (j/2 in c3, c4 and c6).

Multiplicity in c3, c4 and c6 are:

Final function for average running time is:

Written in simpler form:

Here is my final conclusion and question:
b2 in equation (8) is two times smaller than a2 in equation (4)

Am I right with (9)?
I thought that plotting running time of algorithm in function of vector sizes can proof equation (9) but it's not:

On the plot we can see that ratio a2/b2 is 1.11, not like in equation (9) where is 2. Ratio in above plot is far away from predicted.
Why is that?

A: I found my problem!
It wasn't as I thought in assumption for average case: "we find corresponding element from a1 in half of not sorted a2 (j/2)". It was hidden in pessimistic case.
Proper pessimistic scenario occurs when vector a2 is in the same order as a1 with shifted first element to the end. For example:
a1 = {1,2,3,4,5}
a2 = {2,3,4,5,1}
I measured experimentally once again running time of my algorithm with new assumption for pessimistic case. Here are results:

Finally experimental ratio for a2/b2 is: 2.03 +/- 0.09
And it's proof for my theoretical functions.
Thank for all of you for being with me and trying to solve my trivial mistake!

A: You cannot assume that the same instructions in the two cases will take same amount of time.
In particular, in your pessimistic case, the branches will always go the same way, hence branch predictors will do a great job and you won't pay the penalty of mis-prediction (which can be quite high).
In case of random order, the branches will be harder to predict and so your branch instructions will take much longer to execute. This could easily explain the difference you are see


text:
Q: thinking in C++, inline function feature? The following code is from Thinking in C++. The author mentioned that "Since operator[] is an inline, you could use this approach to guarantee that no array-bounds violations occur, then remove the require() for the shipping code." What feature of inline function is referred here? Thanks!
#include "../require.h"
#include <iostream>
using namespace std;

template<class T>
class Array {
  enum { size = 100 };
  T A[size];
public:
  T& operator[](int index) {
    require(index >= 0 && index < size,
      "Index out of range");
    return A[index];
  }
};

A: The author refers to the feature of inline functions to be expanded at the invocation site, as if you wrote their body in place of the invocation. This guarantees no loss of efficiency - not even the tiny one associated with invoking a function on modern hardware. In addition, the compiler could potentially optimize the code better when the indexing operator is expanded inline, because the nature of the code inside the function would be known to the optimizer.
As far as removing the require from the shipping code goes, you would need to do it manually in the current implementation. You could also use conditional compilation to remove bounds checking in production code.


text:
Q: Multiple testing adjustments in posthoc.quade.test In R, posthoc.quade.test (package PMCMR) or quadeAllPairsTest (the new variant, PMCMRplus) are posthoc tests for Quade test and offer the option for adjustments (i.a. Holm, BH etc.).
In my previous understanding, posthoc tests are applied after obtaining a significant omnibus test (unless already implemented in the posthoc test, but this does not seem the case from the PMCMRplus desription PDF, https://cran.r-project.org/web/packages/PMCMRplus/index.html), and are basically designed to avoid pairwise testing + correcting afterwards (may be wrong, see question):
"If no p-value adjustment is performed (p.adjust.method = "none"), than a simple protected test
is recommended, i.e. all-pairs comparisons should only be applied after a significant quade.test.".
My question: what is the advantage/difference of (1) test-specific (Quade) post-hoc test over (2) simple pairwise testing with any other test (e.g. Wilcoxon), if adjustments (Holm, BH) are required anyway? Wouldn't this only add unnecessary complexity to our statistical methods? Are these "basic conceptual" differences between (1) and (2) (i.e. test different questions), or rather "performance" differences (i.e. are more/less sensitive, error-prone, calculation time...)?
Maybe I completely miss the point, but happy to learn!

A: My understanding is that some post-hoc tests require that there be a significant omnibus test prior, and others don't. (See here for some discussion).
In general, it is better --- that is, statistically sounder --- to avoid pairwise tests, and instead to embrace post-hoc tests that are fashioned for the purpose.  The problem with pairwise tests, as I see it, is that each comparison between two groups ignores the rest of the data. In the case of pairwise Wilcoxon-Mann-Whitney tests, there can be a particular problem, exemplified by the Schwenk dice phenomenon, where, from a practical point of view, the results are incommensurate with each other.


text:
Q: Добавить вкладку в редакторе wp Здравствуйте. Каким образом можно добавить свою вкладку на странице создания новой страницы в CMS WordPress?
Пример на скрине (WR PageBuilder)

A: Можно использовать плагин Easy Responsive Tabs.


text:
Q: Change size of gold-email-input in polymer I am trying to style the height of a gold-email-input. I tried setting the height with:
gold-email-input {
    background-color: var(--light-theme-base-color);
    width: 100%;
    height: 48px;
    max-width: 670px;
    padding: 0px;

    --paper-input-container: {
        max-height: 48px;
    };
}

But what ever I try the paper-input-container stays 61px while the gold-email-input resizes to 48px. Is there anything I can do to fix this?

A: If you want the height of the paper-input-container to match the height of gold-email-input, you would set its height to 100%, and clear its margin and padding:
gold-email-input {
  --paper-input-container: {
    height: 100%;
    margin: 0;
    padding: 0;
  }
}

To style the gold-email-input outside of a custom element, make sure to use a custom-style:

<head>
  <base href="https://polygit.org/polymer+1.4.0/components/">
  <script src="webcomponentsjs/webcomponents-lite.min.js"></script>
  <link rel="import" href="gold-email-input/gold-email-input.html">
</head>
<body>
  <style is="custom-style">
    :root {
      --light-theme-base-color: rgba(0,112,0,0.4);
    }
    gold-email-input {
      background-color: var(--light-theme-base-color);
      width: 100%;
      height: 248px;
      max-width: 670px;
      padding: 0px;

      --paper-input-container: {
        outline: solid 3px red;
        height: 100%;
        margin: 0;
        padding: 0;
      };
    }
  </style>
  <gold-email-input></gold-email-input>
</body>

codepen
Within a custom element, you could use the style normally (i.e., without custom-style) inside the dom-module:

<head>
  <base href="https://polygit.org/polymer+1.4.0/components/">
  <script src="webcomponentsjs/webcomponents-lite.min.js"></script>
  <link rel="import" href="gold-email-input/gold-email-input.html">
</head>
<body>
  <style is="custom-style">
    :root {
      --light-theme-base-color: rgba(0,112,0,0.4);
    }
  </style>
  <x-foo></x-foo>

  <dom-module id="x-foo">
    <style>
      gold-email-input {
        background-color: var(--light-theme-base-color);
        width: 100%;
        height: 248px;
        max-width: 670px;
        padding: 0px;

        --paper-input-container: {
          outline: solid 3px red;
          height: 100%;
          margin: 0;
          padding: 0;
        };
      }
    </style>
    <template>
      <gold-email-input></gold-email-input>
    </template>
    <script>
      HTMLImports.whenReady(function() {
        Polymer({
          is: 'x-foo'
        });
      });
    </script>
  </dom-module>
</body>

codepen


text:
Q: Cannot track a form submission with Google Tag Manager I know the methods of tracking a form submission but in this case unfortunately I couldn't make it. Once the form is submitted, you can see in the debug mode that the exact same variables fire as in the case that the user tried to submit that form and it failed (because some fields weren't filled in). So the variables of GTM upon submitting don't help.
I tried another approach, with the url redirect. But the thing is that the redirection is to site.com/buy?add-to-cart, and this parameter causes adding to cart and then it redirects to the checkout page. This checkout page can be reached from many places so I can't track the form submission with page view either.
I don't know what to do already, is there another way that I didn't think of?
Thanks in advance


text:
Q: Notation of $\nabla_{ij}V_{ij}$ Referring to a Potential There's a brief section in Goldstein's Classical Mechanics book in chapter 1 that derives some useful basic mechanics things. In talking about the total internal energy of the system, there's a passage which I've had explained to me multiple times but which always confuses me when I want to refer to it, on the internal potential energy of a system. (ignore the first sentence fragment at the beginning of the passage!)

I'm very confused about what exactly "with respect to" means. Is the notation just imprecise? I'm almost sure I've used this notation before in a problem, but in everything else I do I make sure to write gradients as $\nabla V$. What's this $\nabla_i V$? Are we considering $V_{ij}$ as a function of six variables (supposing $\vec{r}_i$ and $\vec{r}_j$ are 3D vectors), so that $\nabla_i$ refers to the partial derivatives/gradient of (say) the first three arguments, and $\nabla_j$ refers to the second three?
[come to think of it, I'm almost sure that's the answer, but since I've written the question can anyone reaffirm it?]

A: $V_{ij}$ is indeed a function of six real variables, $\vec r_i$ and $\vec r_j$. $\nabla_i$ is the gradient with respect to $\vec r_i$.
For translationally invariant problems, $V_{ij}$ must be a function of $\vec r_j-\vec r_i$. $\nabla_{ij}$ is the gradient with respect to this vector. To make this a bit clearer, consider just the $x$ coordinate of that gradient, $\frac\partial{\partial x_{ij}}$. This is easier to calculate considering the components of $\nabla_i$, which need a second variable, say $\vec R=\vec r_i+\vec r_j$, to work with. You have
$$
\frac{\partial}{\partial x_{i}}
=
\frac{\partial x_{ij}}{\partial x_{i}}\frac{\partial}{\partial x_{ij}}+\frac{\partial X}{\partial x_{i}}\frac{\partial}{\partial X}=-\frac{\partial}{\partial x_{ij}}
$$
since $\frac{\partial}{\partial X}\equiv0$ for allowable potentials.
I hope this makes it clearer.


text:
Q: How to avoid / escape in JSONObject Hi I have small problem in escape sequence of JSONObject.
JSONObject imageObject = new JSONObject();
        JSONArray imageArray = new JSONArray();
        String imageId = "1/1";
        if (isPOD) {
            try {
                imageObject.put("docidx", imageId);
                imageObject.put("docapp", "LKM");
                imageObject.put("docentity", "DOS");
                imageObject.put("doctype", "PIC");
                imageObject.put("docname", imageTitle);
                imageObject.put("docsize", "" + imageSize);
                imageObject.put("docext", "jpg");
                imageObject.put("docdata64", "");
                imageObject.put("doctxt", documentText);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            imageArray.put(imageObject);
        }

The output of this is as follows:
12-11 17:49:31.437: I/Parameter(29959): [{"docdata64":"","docentity":"DOS","docsize":"3709","docapp":"LKM","docext":"jpg","doctxt":"fhuuhf","docname":"LKM-PIC_2014-12-11_17:49:31_1\/3","doctype":"PIC","docidx":"1\/1"}]

I convert this JSONArray to string and pass it as parameter to POST Method using
listLocal.add(22, new BasicNameValuePair("document", "" + imageArray));

When this is added to total request and sent to the WS, I get extra escape sequence need help on how to handle the escape sequence.
12-11 17:49:32.238: E/param(29959): {"root":{"os":"4.4.2","res":"1280x800","evttime":"17:49:31","gpslon":"79.7898222","dev":"samsung-SM-T231","evtnat":"A","nbcall":"5","ver":"2.0","net":"WIFI","evtctname":"vhhhff","lang":"EN","evtdate":"20141211","ttp":"1418300372","document":"[{\"docdata64\":\"\",\"docentity\":\"DOS\",\"docsize\":\"3709\",\"docapp\":\"LKM\",\"docext\":\"jpg\",\"doctxt\":\"fhuuhf\",\"docname\":\"LKM-PIC_2014-12-11_17:49:31_1\\\/3\",\"doctype\":\"PIC\",\"docidx\":\"1\\\/1\"}]","evttxt":"ghhhgg","shp":"80201\/L2\/74","evtctry":"BM","uuid":"77179677924A49A58FD16D2","evtfam":"G","evtcod":"DEL","evtloc":"dfggg","gpslat":"11.9402385"}}

Thanks in advance for the help.


text:
Q: Crash when passing string My code crashes when passing a string parameter.Can someone help me sort this? :
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {

    NSIndexPath *indexPath = (NSIndexPath *)sender;

    if ([[segue identifier] isEqualToString:@"abc"]) {

        MyVC *myvc = [segue destinationViewController];
        myvc.itemstring=@"dsdsds";

    }

}

ERROR

-[UIViewController itemstring:]: unrecognized selector sent to instance 0x7fc89b0028d0
2016-10-14 14:54:24.118 Myapp[7824:109039] *** Terminating app due to
  uncaught exception 'NSInvalidArgumentException', reason:
  '-[UIViewController itemstring:]: unrecognized selector sent to
  instance 0x7fc89b0028d0'

MyVC
#import <UIKit/UIKit.h>

@interface MyVC : UIViewController {
    NSString* itemstring;
}

@property (nonatomic, strong) NSString* itemstring;

@end

A: The line in the error...

-[UIViewController itemstring:]: unrecognized selector sent to instance 0x7fc89b0028d0

This suggests that the destination of the segue is a UIViewController and not a MyVC.
You probably haven't set the subclass correctly in the storyboard.
You can update it here...

by changing the Class to MyVC.


text:
Q: React native "Unexpected identifier 'React' import call expects exactly one argument" I have error in react native app
Unexpected identifier 'React' import call expects exactly one argument.
In metro there are no any errors. During compilation too.
I suddenly deleted 'Recent' folder on my Mac and now i am facing this errors.
I already removed node_modules folder and installed all modules again.
"react": "17.0.1", "react-native": "0.64.2",

A:
share your code when you get error App.js or any main file of project

may be you import wrong thing from "react"


text:
Q: How to create 3d text in MFC[CFormView] Now i'm try to search google but can't find how to create 3d text.I see it maybe use library such as OpenGL or freetype-gl,however it not say so much espicially step by step >.<.Thank for ur help.

A: http://nehe.gamedev.net/tutorial/lessons_11__15/28001/
The Demo named "outline fonts" maybe that's what you want,it has source code for windows.
you mentioned you want to draw it in CFormView,the source code above using it's own window that created by hand.
you just have to remove that part of the code,then pass CFormView's hwnd to the code that create opengl context, everything should work the same.
the source code defined this:
HWND        hWnd=NULL; //used by demo's window,

if (!(hDC=GetDC(hWnd))) /change hWnd to "yourCFormViewPointer"->m_hWnd

Also you might not want to use that loop from the source code,put the loop code inside CFormView::ondraw to check if code works until you implement 'real loop'


text:
Q: Configure Azure web role to start app domain on launch Azure has a fantastic ability to roll updates so that the entire system is not offline all at once. However, when Azure updates my web roles, the AppDomains are understandably recycled. Sometimes the ASP.NET startup code can take over a minute to finish initializing, and that's only once a user hits the new server.
Can I get Azure to start the AppDomain for the site and wait for it to come up before moving on to the next server? Perhaps using some magic in the OnStart method of WebRole?

A: See Azure Autoscale Restarts Running Instances which includes the following code:
public class WebRole : RoleEntryPoint
{
    public override bool OnStart()
    {
        // For information on handling configuration changes
        // see the MSDN topic at http://go.microsoft.com/fwlink/?LinkId=166357.
        IPHostEntry ipEntry = Dns.GetHostEntry(Dns.GetHostName());
        string ip = null;
        foreach (IPAddress ipaddress in ipEntry.AddressList)
        {
            if (ipaddress.AddressFamily.ToString() == "InterNetwork")
            {
                ip = ipaddress.ToString();
            }
        }

        string urlToPing = "http://" + ip;
        HttpWebRequest req = HttpWebRequest.Create(urlToPing) as HttpWebRequest;
        WebResponse resp = req.GetResponse();
        return base.OnStart();
    }
}


text:
Q: Copy files sequential with 60s queue in powershell The task is to copy files from one directory to another:
Copy-Item $source\*.pdf -Destination $target

The difficulty is that they should be copied sequentially, but each with a Time Offset of 60 seconds. Is there any way I can do this with PowerShell?
I am grateful for any help.Greetings, Irmi

A: Use Start-Sleep to wait in between copy operations in a loop:
foreach($file in Get-ChildItem path\to\source\folder -Filter *.pdf){
  # Wait 60s
  Start-Sleep -Seconds 60
  # Copy file
  $file |Copy-Item -Destination path\to\destination\folder
}


text:
Q: Mongodb version specified in package.json fails to install If I do npm install mongodb, the desired version of mongodb is installed without a problem:
- bson@0.1.5 node_modules/mongodb/node_modules/bson
mongo-invoices@0.0.0 /home/lorencm/Downloads/mongo-invoices
└─┬ mongodb@2.1.6
  ├── es6-promise@3.0.2
  ├─┬ mongodb-core@1.3.1
  │ ├── bson@0.4.21
  │ └─┬ require_optional@1.0.0
  │   ├── resolve-from@2.0.0
  │   └── semver@5.1.0
  └─┬ readable-stream@1.0.31
├── core-util-is@1.0.2
├── inherits@2.0.1
├── isarray@0.0.1
└── string_decoder@0.10.31

As soon as I have all my dependencies in package.json stored (see below) and I use npm install it fails (see below) to install mongodb@2.1.6 and instead installs mongodb@1.1.11:
{
  "name": "mongo-invoices",
  "version": "0.0.0",
  "description": "open-source invoice system build on node.js and mongodb",
  "main": "app.js",
  "dependencies": {
"accounting": "~0.4.1",
"bcrypt-nodejs": "0.0.3",
"emailjs": "~1.0.2",
"express": "~4.13.4",
"i18n": "^0.6.0",
"jade": "~1.11.0",
"moment": "~2.11.2",
"mongodb": "~2.1.6",
"stylus": "~0.53.0"
  },
  "devDependencies": {},
  "scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
  },
  "repository": {
"type": "git",
"url": "git://github.com/gianlucadelgobbo/mongo-invoices.git"
  },
  "keywords": [
"invoices",
"mongodb",
"node.js"
  ],
  "author": "Gianluca Del Gobbo <g.delgobbo@flyer.it>",
  "license": "BSD",
  "readmeFilename": "README.md",
  "private": true
}

.
make[1]: *** [Release/obj.target/bson/ext/bson.o] Error 1
make[1]: Leaving directory `/home/lorencm/Downloads/mongo-invoices/node_modules/mongodb/node_modules/bson/build'
gyp ERR! build error
gyp ERR! stack Error: `make` failed with exit code: 2
gyp ERR! stack     at ChildProcess.onExit (/usr/lib/node_modules/npm/node_modules/node-gyp/lib/build.js:270:23)
gyp ERR! stack     at emitTwo (events.js:100:13)
gyp ERR! stack     at ChildProcess.emit (events.js:185:7)
gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:200:12)
gyp ERR! System Linux 4.2.0-23-generic
gyp ERR! command "/usr/bin/nodejs" "/usr/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "configure" "build"
gyp ERR! cwd /home/lorencm/Downloads/mongo-invoices/node_modules/mongodb/node_modules/bson
gyp ERR! node -v v5.5.0
gyp ERR! node-gyp -v v3.0.3
gyp ERR! not ok
make: *** [node_gyp] Error 1
child process exited with code 2
- bson@0.4.21 node_modules/bson
- core-util-is@1.0.2 node_modules/core-util-is
- es6-promise@3.0.2 node_modules/es6-promise
- inherits@2.0.1 node_modules/inherits
- isarray@0.0.1 node_modules/isarray
- resolve-from@2.0.0 node_modules/resolve-from
- semver@5.1.0 node_modules/semver
- require_optional@1.0.0 node_modules/require_optional
- mongodb-core@1.3.1 node_modules/mongodb-core
- string_decoder@0.10.31 node_modules/string_decoder
- readable-stream@1.0.31 node_modules/readable-stream
mongo-invoices@0.0.0 /home/lorencm/Downloads/mongo-invoices
└─┬ mongodb@1.1.11
  └── bson@0.1.5

Why will it not install the version I specified in the package.json?

A: The application fails to install the 2.1.6 version because of a npm-shrinkwrap.json file which:

This command locks down the versions of a package's dependencies so that you can control exactly which versions of each dependency will be used when your package is installed.

If you inspect the npm-shrinkwrap.json for mongo-invoices, you'll find the specified version for mongodb is 1.1.11


text:
Q: Reversible math function that looks random I want a math function y = f(x) where x and y are 32 bit integers, such that

*

*it is reversible by some function x = g(y)

*the sequence f(1), f(2), f(3), ... looks random

I thought about XOR with some constant key, but that fails to look random.  Also I could use DES or AES.  But those seem like overkill.
Is there something simpler?

A: Try a block cipher such as Skip32. But note that this does always encrypt one value to another value, so you need to remember that repetition of the input leads to repetition of the output, possibly leaking information to the adversary.
Otherwise you can have a look at format preserving encryption. There are ways of halving the size of a block cipher such as 3DES, which has a significantly higher security margin (112 bits if you use three random keys), e.g. using a Feistel Network.
A weird cipher is the Hasty Pudding Cipher, which has a configurable block size. However, the security of that cipher is questionable and not researched enough at the very minimum.

A: After asking this question, I found a different solution (appending a hash to my sequential key).  But it's still an interesting question. And I think the best answer is to implement a simple block cipher algorithm. There are several examples here.


text: Q: Showing that a Boolean algebra is a Boolean ring I've proved that a Boolean ring is a Boolean algebra but I am having trouble with the converse. The operation for + is defined as the symmetric difference for elements $a$ and $b$ from the Boolean algebra and multiplication is standard juxtaposition for $\lor$, $\land$ respectively. I know I must show that under "addition" the Boolean algebra is an Abelian group and then show associativity for multiplication and then the distributive laws. I am stuck with how to show closure of "addition", is it even necessary? I just need a few hints to get on with the proof. Thanks.


text:
Q: How can I separate the String Array in Android I want to separate the String Arrays in another file or in a String.xml ,but how?
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
Here is my codes

MainActivity.class
   package com.skholingua.android.searchview;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater.Filter;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.SearchView;

public class MainActivity extends Activity implements
        SearchView.OnQueryTextListener {
    String[] stateList;
    String[] anotherStringArray;
    private SearchView searchView;
    private ListView listView;
    private ArrayAdapter<String> adapter;

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

        searchView = (SearchView) findViewById(R.id.searchView1);
        listView = (ListView) findViewById(R.id.listView1);
        adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, stateList);
        listView.setAdapter(adapter);
        listView.setTextFilterEnabled(true);

        // Sets the default or resting state of the search field.
        // If true, a single search icon is shown by default and
        // expands to show the text field and other buttons when pressed
        //searchView.setIconifiedByDefault(false);
        searchView.setOnQueryTextListener(this);

        // Sets the hint text to display in the query text field
        //searchView.setQueryHint("State Name");

        int searchPlateId = searchView.getContext().getResources()
                .getIdentifier("android:id/search_plate", null, null);
        View searchPlateView = searchView.findViewById(searchPlateId);
        if (searchPlateView != null) {
            searchPlateView.setBackgroundColor(Color.TRANSPARENT);
        }

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String stateName = listView.getAdapter().getItem(position).toString();
                //String stateName = stateList[position];
                //Log.e("Selected State Name", stateName);

                // Put selected state to intent.
                Intent intent = new Intent(MainActivity.this, NextActivity.class);
                intent.putExtra("selectedState", stateName);
                intent.putExtra("anotherStringArray",anotherStringArray[position]);
                startActivity(intent);
            }
        });

    }

    // Called when the query text is changed by the user.

     @Override
        public boolean onQueryTextChange(String newText) {
            android.widget.Filter filter = adapter.getFilter();
            if (TextUtils.isEmpty(newText)) {
                filter.filter("");
            } else {
                filter.filter(newText);
            }
            return true;
        }

    @Override
    public boolean onQueryTextSubmit(String query) {
        return false;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.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();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">SearchView</string>
    <string name="hello_world">Hello world!</string>
    <string name="action_settings">Settings</string>

    <string-array name="stateList">
        <item>Example</item>
        <item>Goa</item>
        <item>Karnataka</item>
        <item>Kerala</item>
        <item>Maharashtra</item>
        <item>Madhya Pradesh</item>
        <item>Tamil Nadu</item>
    </string-array>

     <string-array name="anotherStringArray">
        <item>Example_description</item>
        <item>Goa_description</item>
        <item>Karnataka_description</item>
        <item>Kerala_description</item>
        <item>Maharashtra_description</item>
        <item>Madhya Pradesh_description</item>
        <item>Tamil Nadu_description</item>

    </string-array>

</resources>

A: You can use something like
<resources>
    <string-array name="my_array">
        <item>Example</item>
        <item>Goa</item>
        <item>Karnataka</item>
    </string-array>
</resources>

A: in strings.xml as following :
<string-array name="stateList">
    <item>Example</item>
    <item>Goa</item>
    <item>Karnataka</item>
    ...
</string-array>

Edit:
Full code for adapter :
adapter = new ArrayAdapter<String>(this,
            android.R.layout.simple_list_item_1, getResources().getStringArray(R.array.stateList));

A: In your values folder keep your arrays

example : arrays.xml
<?xml version="1.0" encoding="utf-8"?>
<resources xmlns:android="http://schemas.android.com/apk/res/android">

   <string-array name="string_array_example">
        <item>"Name"</item>
        <item>"Address"</item>
        <item>"City"</item>
    </string-array>

</resources>

This is how you access them back in your class
String[] strings = getResources().getStringArray(R.array.string_array_example);
    Log.i("TAG", Arrays.toString(strings));

Make sure you use above lines and initialize your arrays before you try to set data !


text:
Q: Getting column number by vector value - R I have been stuck with this issue for some time now, without finding any help online.
I have two vectors of 1.314.000 entries, one indicating wind speeds and one indicating wind directions (values are 1-12 as the direction is consolidated into 12 directions).
I also have a matrix of 50001 rows and 13 columns, indicating power production of a turbine at a given wind speed (column 1) and wind direction (column 2-13)
Calculating the power production seemed obvious:
PowerkWh <- PCC[ws*1000+1,1+wd]

PCC is the 50001x13 matrix and ws and wd is the wind speed and wind direction variables. Note that i do not use match as it resulted in NA's for some reason.
Head of ws, wd and PCC:
ws:
[1]  2.327 16.971  3.469 23.558  7.882 10.619

wd:
[1]  5 10 10  9  1  1

PCC:
     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12] [,13]
[1,] 0.000    0    0    0    0    0    0    0    0     0     0     0     0
[2,] 0.001    0    0    0    0    0    0    0    0     0     0     0     0
[3,] 0.002    0    0    0    0    0    0    0    0     0     0     0     0
[4,] 0.003    0    0    0    0    0    0    0    0     0     0     0     0
[5,] 0.004    0    0    0    0    0    0    0    0     0     0     0     0
[6,] 0.005    0    0    0    0    0    0    0    0     0     0     0     0

Note that PCC is 0 since wind turbines are usually only turned on when wind speeds are above 3.5 m/s
This code works fine to get the correct row (setting a constant column/direction, say 5), however my issue is getting the appropriate column, given the wind direction in wd. R simply outputs that its memory has been reached since in interprets it as a 1.314.000x1.314.000 matrix - I'm expecting a 1.314.000 vector with the production from the given wind speed and wind direction.
Hope you are able to see what I dont, as I dont want to resort to using loops due to time consumption - let me know if you need anymore information :)
Thanks!

A: My answer assumes that the same units for wind speed in ws are the units in the first column of PCC.
# ===============================
# = Quick Options for Fake Data =
# ===============================
n.dir <- 12 # number of wind directions
n.sample <- 50 # number of samples in the vectors

# ================================
# = Create Fake Data for Example =
# ================================
# create fake vectors and lookup tables
ws <- rlnorm(n.sample) # wind speeds
wd <- sample(1:n.dir, n.sample, replace=T) # wind directions
PCC <- matrix( # empty lookup table for power
    data=NA,
    nrow=length(unique(ceiling(ws)))+1,
    ncol=length(wd)+1
)
# note the +1 is so that the top row of PCC
# references values that are closest to 0;
# i.e., the starting row of the lookup matrix
# references the lowest possible wind speed

# generate fake power values;
# absolute values to make realistic
# data are also sorted so that more wind is more power
# beyond that, it is not realistic
dataExprsn <- expression(sort(abs(rnorm(nrow(PCC)))))
PCC[] <- replicate(ncol(PCC), eval(dataExprsn))
PCC[,1] <- c(0,sort(unique(ceiling(ws))))

# =============================
# = Approach to be Used by OP =
# =============================
power <- rep(NA, length=length(ws)) # to store output
for(i in 1:n.dir){ # do it by direction to save time
    t.index <- wd==i
    t.fun <- approxfun(x=PCC[,1], y=PCC[,i+1])
    power[t.index] <- t.fun(ws[t.index])

}

# ==============
# = The Answer =
# ==============
power

A: You can try - if the first columns of PCC contains all element of ws:
PCC[cbind(which(PCC[,1] %in% ws), wd + 1)]


text:
Q: Smarty - PHP if / else Hello I am using smarty and  trying to to get if / else working in tpl which display {$Code}
Php File
$this->_Smarty->assign("License_Key", TRUE);

$Value = '
License Key :
{if $License_Key}
Valid
{else}
Not Valid
{/if}';

$this->_Smarty->assign("Code", $Value);

In Tpl File :
{$Code}

OutPut Is
License Key :
{if $License_Key}
Valid
{else}
Not Valid
{/if}

OutPut should be :
License Key : Valid

A: You have to put content of $Value into .tpl file, not into PHP. So content of .tpl will be:
License Key :
{if $License_Key}
   Valid
{else}
   Not Valid
{/if}

In PHP, assign only $License_Key:
$this->_Smarty->assign("License_Key", TRUE);

EDIT: But if you need to do it exactly how you write it, you can use {eval}, try it like this:
{eval var=$Code}

But I still suggest you to use it with Smarty tags in Smarty templates, not in PHP files.

A: I think this is what you're looking for:
$Value = 'License Key : '.($License_Key) ? 'Valid' : 'Not Valid';

The ? is basically if and the : is basically else.


text:
Q: Stretch and rotate a Movieclip without distortion i'm building a flash desktop app, where the user needs to link two Movieclips on stage (a computer and a router) using a line (or whatever can do the job), i want to achieve this same exact effect: image1. I searched and found this solution, i tried the code and did some modifications:
link.addEventListener(MouseEvent.CLICK, linkOnClick);
function linkOnClick(e:MouseEvent){

this.addEventListener(Event.ENTER_FRAME, enterFrame);

var linkPoint:Point = new Point(link.x, link.y);
var mousePoint:Point = new Point();
var distance:Number;
var radians:Number;

function enterFrame(e:Event):void {

    //Distance
    mousePoint.x = stage.mouseX;
    mousePoint.y = stage.mouseY;
    distance = Point.distance(linkPoint, mousePoint);
    link.width = distance;

    //Rotation
    radians = Math.atan2(stage.mouseY - link.y, stage.mouseX - link.x);
    link.rotation = radians * (180/ Math.PI);

    if(link.hitTestObject(router)){trace("Success");}
}

When i compiled the code i got this: image2, so as you may remark, the problems i found are:
1-the edge of the line follows the direction of the mouse, but sometimes it goes beyond the cursor, i want the cursor to drag the edge of the line.
2-the line changes it's width, if it's 90° degrees the line width is so remarkable, i want the line to have a constant width.
how can i acheive the same exact effect shown in image1 ?

A: // First, lets create mouse-transparent container for drawing.
var DrawingLayer:Shape = new Shape;
addChild(DrawingLayer);

// Hook the event for starting.
stage.addEventListener(MouseEvent.MOUSE_DOWN, onDown);

// Define a storage for keeping the initial coordinates.
var mouseOrigin:Point = new Point;

function onDown(e:MouseEvent):void
{
    // Save the initial coordinates.
    mouseOrigin.x = DrawingLayer.mouseX;
    mouseOrigin.y = DrawingLayer.mouseY;

    // Hook the events for drawing and finishing.
    stage.addEventListener(MouseEvent.MOUSE_UP, onUp);
    stage.addEventListener(MouseEvent.MOUSE_MOVE, onDraw);
}

function onDraw(e:MouseEvent):void
{
    // Remove the previous line.
    DrawingLayer.graphics.clear();

    // Draw a new line.
    DrawingLayer.graphics.lineStyle(5, 0xFF6600);
    DrawingLayer.graphics.moveTo(mouseOrigin.x, mouseOrigin.y);
    DrawingLayer.graphics.lineTo(DrawingLayer.mouseX, DrawingLayer.mouseY);
}

function onUp(e:MouseEvent):void
{
    // Unhook the events for drawing and finishing.
    stage.removeEventListener(MouseEvent.MOUSE_UP, onUp);
    stage.removeEventListener(MouseEvent.MOUSE_MOVE, onDraw);
}

A: It's because of that the actionscript is trying to stretch the line thickness by changing its container MovieClip's scale. But you can prevent this by setting the line Scale option to None.

To do that, select your line and open the properties menu and then select None from the drop down menu of the Scale option.
But,
I recommend you to draw a line by a code: Draw line from object to Mouse (AS3)
Write below code:
this.graphic.clear ();
this.graphic.lineStyle(0x000000);
this.moveTo(startPoint.x,startPoint.y);
this.lineTo(endpoint.X,endpoint.y);


text:
Q: Segmentation fault 11 - network program This is my first attempt at writing a network program. It compiles without problems but when I run it it gives me a 'segmentation fault 11'. I'm hoping somebody could give me clue what in the code could be causing this problem.
I am new at C.
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <string.h>
#include <netdb.h>
#include <netinet/in.h>

int main()
{
    ////////////      GETADDRINFO   \\\\\\\\\\\\\\\\

    struct addrinfo hints, *res;
    memset(&hints, 0 , sizeof hints);

    hints.ai_family     = AF_UNSPEC;    //define the 'hints' strucure
    hints.ai_socktype   = SOCK_STREAM;  //define the 'hints' strucure
    hints.ai_protocol   = AI_PASSIVE;   //define the 'hints' strucure

    char *ipaddr = "127.0.0.1";
    getaddrinfo(ipaddr, "ftp", &hints, &res);

    //////////////     SOCKET     \\\\\\\\\\\\\\\\

    int sock = socket(AF_INET, SOCK_STREAM, 0);

    struct sockaddr_in info;
    int bnd  = bind( sock , res->ai_addr, res->ai_addrlen);

    info.sin_family         = AF_INET;
    info.sin_port           = htons(10000);
    info.sin_addr.s_addr    = INADDR_ANY;
    bzero(&(info.sin_zero),8);

    ///////////////    CONNECT   \\\\\\\\\\\\\\\\\\\\\\

    int conct = connect( sock, res->ai_addr, res->ai_addrlen);

    //////////////     LISTEN     \\\\\\\\\\\\\\\\\\

    int lstn = listen( sock , 4 );

    //////////////    ACCEPT    \\\\\\\\\\\\\\\\\\\\\\\

    int new_fd;
    struct sockaddr_storage client_addr;
    socklen_t addr_size;
    addr_size = sizeof(client_addr);
    new_fd = accept(sock, (struct sockaddr *)&client_addr, &addr_size);

    /////////////////   SEND   \\\\\\\\\\\\\\\\\\\\\\

    char *msg = "HI!";
    int len, bytes_sent;
    len = strlen(msg);
    bytes_sent = send(sock, msg, len, 0);

    //////////////// RECEIVE \\\\\\\\\\\\\\\\\

    char burr[254];
    int cat = sizeof(burr);

    recv( sock, burr , cat , 0 );

    printf("%s", burr);
    return 0;
}

A: The segfault occurs at the time of first bind because getaddrinfo returns error this the res structure is not valid.
The error returned by getaddrinfo is

EAI_SOCKTYPE
The  requested socket type is not supported.  This could occur, for example, if hints.ai_socktype and hints.ai_protocol are inconsistent (e.g., SOCK_DGRAM and IPPROTO_TCP, respectively).

you have set in hints.ai_protocol = AI_PASSIVE which is not correct. The manual says:

ai_protocol This field specifies the protocol for the returned socket addresses.  Specifying 0 in this field indicates that socket addresses with any protocol can be returned by getaddrinfo().

So you should set it to 0 if you want to get any protocol.
This although removes the segfault but the program is messy and not correct.
Also to note:
You are using the listener socket to send and receive. You should use the socket returned by accept which is new_fd in your code to send and recv as that is the channel established between.
You have defined and initialized the structure info and never used it.
Have a look at this this might help you to get quickly into sockets: http://beej.us/guide/bgnet/


text:
Q: Simple Algorithm For Line Curving I'm looking for a simple algorithm for line curving (much like fireworks freeform tool).
In my C++ program, a line is a set of ordered points, each point is of (x,y) form.
Assume I have straight line of 5 (just for simplicity) ordered points (the line isn't necessarily parallel to any axis). I pinch the 3rd point and drag it up. I'm expecting to have a new, gaussian-like, curved line. It doesn't really matter how I implement the "Points" and "Lines", but keep in mind I should add more points to the new expected line so it'll be curved, refined and flowing (and not with line breaks).
I thought of using a gaussian function but I need the ability of moving the curved part (see picture below).
Thanks in advance!

A: You need a B-spline or a Bezier curve to approximate your shape.
There is a nice interactive demo of Bezier splines so you can play with to see the effect. A sample screenshot below:

Depending on your OS and development environment, there are probably already a number of tools or APIs available.


text:
Q: Update state of a Product while submitting a form React/NextJS I'm trying to update my product object when the submit button is clicked but it doesn't update in that render.
const handleSubmit = async (e) => {
    e.preventDefault();
    const media = await imageUpload(files); // function  returns an array of links
    setProduct((prev) => ({ ...prev, images: media })); // Here where I want to update the images but it doesn't work
    await createProduct();
    setProduct(initialState); // reset to default
  };

I tried using an useEffect to detect when the button is clicked and then update the product but it doesn't work too.
Hope I made myself clear.
Thank you in advance.

A: may be exctracting your CreateProduct function like so :
const handleSubmit = async (e) => {
    e.preventDefault();
    const media = await imageUpload(files); // function  returns an array of links
    setProduct((prev) => ({ ...prev, images: media }));
  };

useEffect(()=>{
 if(product){
  createProduct();
  setProduct(initialState);
 }
},[product])


text:
Q: Force Stack to use an existing Stack/GHC installation instead of re-creating one from scratch When pulling the most recent Docker Stack LTS image from Dockerhub, a full Stack installation with GHC can be found in /home/stackage/.stack.
However, when doing stack path --stack-root, Stack will forcefully rebuild an entire Stack/GHC installation into a global-project subdirectory. Even if we previously set the STACK_ROOT env variable to /home/stackage/.stack.
$ docker run --rm -it fpco/stack-build:lts-17.13 sh
$ export STACK_ROOT=/home/stackage/.stack
$ echo $(stack path --stack-root)

Writing implicit global project config file to: /home/stackage/.stack/global-project/stack.yaml
Note: You can change the snapshot via the resolver field there.
Using latest snapshot resolver: lts-17.13
Preparing to install GHC to an isolated location.
This will not interfere with any system-level installation.
Preparing to download ghc-8.10.4 ...
ghc-8.10.4: download has begun
...

How can we force Stack to recognise the existing installation in /home/stackage/.stack and not have it create another one in /home/stackage/.stack/global-project ? Nothing in the Stack documentation seems to mention this aspect.


text:
Q: Set up sign-in with a Google account using custom policies in Azure Active Directory B2C and fetch profile picture How can I fetch a profile picture from Google identity provider using Azure Active directory B2C?
I've successfully implemented Sign In with Google Account in Azure B2C following the procedure described in this link.
but I am not sure how to fetch the profile picture.

A: You could use the Microsoft Graph API to fetch the profile picture.
The required permissions:

Request:
Get https://graph.microsoft.com/beta/users/{id}/photo/$value

Note: for the email account, you could only use the object id, cannot
  use the username.

Response:

For the details, you could refer to here.


text:
Q: I am trying to decode and extract octet string from the extension of X509Certificate, but I did not get any valid string I have been trying to decode the octet string as per steps mentioned in
https://developer.apple.com/documentation/devicecheck/validating_apps_that_connect_to_your_server?language=objc
Here is what I have tried:
        X509Certificate cert1 = getParentCertificate(new String(decodedCredCert));
        System.out.println(cert1);
        cert1.checkValidity(); // verify against apple app attest root ca
        byte[] ext = cert1.getExtensionValue("1.2.840.113635.100.8.2");
        ASN1InputStream bIn = new ASN1InputStream(ext);
        ASN1Primitive obj = bIn.readObject();
        ASN1OctetString string = (ASN1OctetString) obj;
        byte[] octs = string.getOctets();
        ASN1InputStream dIn = new ASN1InputStream(octs);
        String octetString = ASN1Dump.dumpAsString(dIn.readObject());

I got the output as: "[[1]#8333585e692916d8cbcdce3c6aa2bd71617d54fed758957cfd6b50a2093fd506]"

A: "Octet string" is just a spec phrase that modern languages call "byte array".  You've extracted the value as of octs, and should compare that value to whatever nonce you're supposed to compare it against.

A: For Ios AppAttestation, follow as below to get the extension value and it's corresponding octet string. As mentioned in that page,

Obtain the value of the credCert extension with OID
1.2.840.113635.100.8.2, which is a DER-encoded ASN.1 sequence. Decode the sequence and extract the single octet string that it contains.

Here is the sample code:
byte[] oidValue = credCert.getExtensionValue(ooid);
DEROctetString envelope = (DEROctetString) new ASN1InputStream(oidValue).readObject();
DLSequence sequence = (DLSequence) new ASN1InputStream(envelope.getOctetStream()).readObject();
DLTaggedObject taggedObject = (DLTaggedObject) sequence.getObjectAt(0);
DEROctetString taggedObjectOctet = (DEROctetString) taggedObject.getObject();
log.debug("Octet String : {}", taggedObjectOctet.getOctets());


text:
Q: How to implement Unit Of Work pattern with Dapper? Currently, I am trying to use Dapper ORM with Unit Of Work + Repository Pattern.
I want to use Unit of Work as opposed to a simple dapper Repository due to the fact that my insert and updates require a degree of transaction processing. I have been unable to find any useful examples as most seem to use Entity Framework and have leakage issue within the Unit of Work.
Could someone please point me in the right direction?

A: There is no need for a hand-rolled solution for this. What you want can be achieved very simply using the classes already in the framework.
/// <summary>
/// Register a single instance using whatever DI system you like.
/// </summary>
class ConnectionFactory
{
    private string _connectionString;

    public ConnectionFactory(string connectionString)
    {
        _connectionString = connectionString;
    }

    public IDbConnection CreateConnection()
    {
        return new SqlConnection(_connectionString);
    }
}

/// <summary>
/// Generally, in a properly normalized database, your repos wouldn't map to a single table,
/// but be an aggregate of data from several tables.
/// </summary>
class ProductRepo
{
    private ConnectionFactory _connectionFactory;

    public ProductRepo(ConnectionFactory connectionFactory)
    {
        _connectionFactory = connectionFactory;
    }

    public Product Get(int id)
    {
        // Allow connection pooling to worry about connection lifetime, that's its job.
        using (var con = _connectionFactory.CreateConnection())
        {
            return con.Get<Product>(id);
        }
    }

    // ...
}

class OrderRepo
{
    // As above.
    // ...
}

class ProductController : ControllerBase
{
    private ProductRepo _productRepo;
    private OrderRepo _orderRepo;

    public ProductController(ProductRepo productRepo, OrderRepo orderRepo)
    {
        _productRepo = productRepo;
        _orderRepo = orderRepo;
    }

    [HttpGet]
    public Task<IAsyncResult> Get(int id)
    {
        // This establishes your transaction.
        // Default isolation level is 'serializable' which is generally desirable and is configurable.
        // Enable async flow option in case subordinate async code results in a thread continuation switch.
        // If you don't need this transaction here, don't use it, or put it where it is needed.
        using (var trn = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
        {
            Product product = _productRepo.Get(id);

            // Use additional repositories and do something that actually requires an explicit transaction.
            // A single SQL statement does not require a transaction on SQL Server due to default autocommit mode.
            // ...

            return Ok(product);
        }
    }
}

A: This Git project is very helpful. I started from the same and did some changes as per my need.
public sealed class DalSession : IDisposable
{
    public DalSession()
    {
        _connection = new OleDbConnection(DalCommon.ConnectionString);
        _connection.Open();
        _unitOfWork = new UnitOfWork(_connection);
    }

    IDbConnection _connection = null;
    UnitOfWork _unitOfWork = null;

    public UnitOfWork UnitOfWork
    {
        get { return _unitOfWork; }
    }

    public void Dispose()
    {
        _unitOfWork.Dispose();
        _connection.Dispose();
    }
}

public sealed class UnitOfWork : IUnitOfWork
{
    internal UnitOfWork(IDbConnection connection)
    {
        _id = Guid.NewGuid();
        _connection = connection;
    }

    IDbConnection _connection = null;
    IDbTransaction _transaction = null;
    Guid _id = Guid.Empty;

    IDbConnection IUnitOfWork.Connection
    {
        get { return _connection; }
    }
    IDbTransaction IUnitOfWork.Transaction
    {
        get { return _transaction; }
    }
    Guid IUnitOfWork.Id
    {
        get { return _id; }
    }

    public void Begin()
    {
        _transaction = _connection.BeginTransaction();
    }

    public void Commit()
    {
        _transaction.Commit();
        Dispose();
    }

    public void Rollback()
    {
        _transaction.Rollback();
        Dispose();
    }

    public void Dispose()
    {
        if(_transaction != null)
            _transaction.Dispose();
        _transaction = null;
    }
}

interface IUnitOfWork : IDisposable
{
    Guid Id { get; }
    IDbConnection Connection { get; }
    IDbTransaction Transaction { get; }
    void Begin();
    void Commit();
    void Rollback();
}

Now, your repositories should accept this UnitOfWork in some way. I choose Dependency Injection with Constructor.
public sealed class MyRepository
{
    public MyRepository(IUnitOfWork unitOfWork)
    {
        this.unitOfWork = unitOfWork;
    }

    IUnitOfWork unitOfWork = null;

    //You also need to handle other parameters like 'sql', 'param' ect. This is out of scope of this answer.
    public MyPoco Get()
    {
        return unitOfWork.Connection.Query(sql, param, unitOfWork.Transaction, .......);
    }

    public void Insert(MyPoco poco)
    {
        return unitOfWork.Connection.Execute(sql, param, unitOfWork.Transaction, .........);
    }
}

And then you call it like this:
With transaction:
using(DalSession dalSession = new DalSession())
{
    UnitOfWork unitOfWork = dalSession.UnitOfWork;
    unitOfWork.Begin();
    try
    {
        //Your database code here
        MyRepository myRepository = new MyRepository(unitOfWork);
        myRepository.Insert(myPoco);
        //You may create other repositories in similar way in same scope of UoW.

        unitOfWork.Commit();
    }
    catch
    {
        unitOfWork.Rollback();
        throw;
    }
}

Without Transaction:
using(DalSession dalSession = new DalSession())
{
    //Your database code here
    MyRepository myRepository = new MyRepository(dalSession.UnitOfWork);//UoW have no effect here as Begin() is not called.
    myRepository.Insert(myPoco);
}

Please note that, UnitOfWork is more than DBTransaction.
More details about Repository in above code could be found here.

I have already post this code here. But this question looks more relevant to me for this code; so I am posting again instead of just link to original answer.

A: I'd like to share my solution. I was experimenting with UnitOfWork implementation for multiple ORMs, including Dapper. Here's full project: https://github.com/pkirilin/UnitOfWorkExample
Base unit of work and repository abstractions:
public interface IUnitOfWork
{
    Task SaveChangesAsync(CancellationToken cancellationToken);
}

public interface IRepository<TEntity, in TId> where TEntity : EntityBase<TId> where TId : IComparable<TId>
{
    Task<TEntity> GetByIdAsync(TId id, CancellationToken cancellationToken);

    TEntity Add(TEntity entity);

    void Update(TEntity entity);

    void Remove(TEntity entity);
}

Domain model:
public abstract class EntityBase<TId> where TId : IComparable<TId>
{
    public TId Id { get; }

    protected EntityBase()
    {
    }

    protected EntityBase(TId id)
    {
        Id = id;
    }
}

public class WeatherForecast : EntityBase<int>
{
    // ...
}

Specific repository interface:
public interface IWeatherForecastsRepository : IRepository<WeatherForecast, int>
{
    Task<List<WeatherForecast>> GetForecastsAsync(CancellationToken cancellationToken);
}

Specific unit of work interface:
public interface IAppUnitOfWork : IUnitOfWork
{
    IWeatherForecastsRepository WeatherForecasts { get; }
}

You can have multiple data contexts in your application, so creating specific unit of works with strong boundary seems reasonable to me.
The implementation of unit of work will look like this:
internal class AppUnitOfWork : IAppUnitOfWork, IDisposable
{
    private readonly IDbConnection _connection;
    private IDbTransaction _transaction;

    public IWeatherForecastsRepository WeatherForecasts { get; private set; }

    // Example for using in ASP.NET Core
    // IAppUnitOfWork should be registered as scoped in DI container
    public AppUnitOfWork(IConfiguration configuration)
    {
        // I was using MySql in my project, the connection will be different for different DBMS
        _connection = new MySqlConnection(configuration["ConnectionStrings:MySql"]);
        _connection.Open();
        _transaction = _connection.BeginTransaction();
        WeatherForecasts = new WeatherForecastsRepository(_connection, _transaction);
    }

    public Task SaveChangesAsync(CancellationToken cancellationToken)
    {
        try
        {
            _transaction.Commit();
        }
        catch
        {
            _transaction.Rollback();
            throw;
        }
        finally
        {
            _transaction.Dispose();
            _transaction = _connection.BeginTransaction();
            WeatherForecasts = new WeatherForecastsRepository(_connection, _transaction);
        }

        return Task.CompletedTask;
    }

    public void Dispose()
    {
        _transaction.Dispose();
        _connection.Dispose();
    }
}

Quite simple. But when I tried to implement specific repository interface, I faced a problem. My domain model was rich (no public setters, some properties were wrapped in value objects etc.). Dapper is unable to handle such classes as-is. It doesn't know how to map value objects to db columns and when you try to select some value from db, it throws error and says it can't instantiate entity object. One option is to create private constructor with parameters matching your db column names and types, but it's very bad decision, because your domain layer shouldn't know anything about your database.
So I've splitted entities into different types:

*

*Domain entity: contains your domain logic, is used by other parts of application. You can use everything you want here, including private setters and value objects

*Persistent entity: contains all properties matching your database columns, is used only in repository implementation. All properties are public

The idea is that repository works with Dapper only via persistent entity and, when nessesary, maps persistent entity to or from domain entity.
There is also an official library called Dapper.Contrib, which can construct basic (CRUD) SQL queries for you, and I'm using it in my implementation, because it really makes life easier.
So, my final repository implementation:
// Dapper.Contrib annotations for SQL query generation
[Table("WeatherForecasts")]
public class WeatherForecastPersistentEntity
{
    [Key]
    public int Id { get; set; }

    public DateTime Date { get; set; }

    public int TemperatureC { get; set; }

    public string? Summary { get; set; }
}

internal abstract class Repository<TDomainEntity, TPersistentEntity, TId> : IRepository<TDomainEntity, TId>
    where TDomainEntity : EntityBase<TId>
    where TPersistentEntity : class
    where TId : IComparable<TId>
{
    protected readonly IDbConnection Connection;
    protected readonly IDbTransaction Transaction;

    // Helper that looks for [Table(...)] annotation in persistent entity and gets table name to use it in custom SQL queries
    protected static readonly string TableName = ReflectionHelper.GetTableName<TPersistentEntity>();

    protected Repository(IDbConnection connection, IDbTransaction transaction)
    {
        Connection = connection;
        Transaction = transaction;
    }

    public async Task<TDomainEntity> GetByIdAsync(TId id, CancellationToken cancellationToken)
    {
        var persistentEntity = await Connection.GetAsync<TPersistentEntity>(id, transaction: Transaction);
        return (persistentEntity == null ? null : MapToDomainEntity(persistentEntity))!;
    }

    public TDomainEntity Add(TDomainEntity entity)
    {
        var persistentEntity = MapToPersistentEntity(entity);
        Connection.Insert(persistentEntity, transaction: Transaction);
        var id = Connection.ExecuteScalar<TId>("select LAST_INSERT_ID()", transaction: Transaction);
        SetPersistentEntityId(persistentEntity, id);
        return MapToDomainEntity(persistentEntity);
    }

    public void Update(TDomainEntity entity)
    {
        var persistentEntity = MapToPersistentEntity(entity);
        Connection.Update(persistentEntity, transaction: Transaction);
    }

    public void Remove(TDomainEntity entity)
    {
        var persistentEntity = MapToPersistentEntity(entity);
        Connection.Delete(persistentEntity, transaction: Transaction);
    }

    protected abstract TPersistentEntity MapToPersistentEntity(TDomainEntity entity);

    protected abstract TDomainEntity MapToDomainEntity(TPersistentEntity entity);

    protected abstract void SetPersistentEntityId(TPersistentEntity entity, TId id);
}

internal class WeatherForecastsRepository : Repository<WeatherForecast, WeatherForecastPersistentEntity, int>, IWeatherForecastsRepository
{
    public WeatherForecastsRepository(IDbConnection connection, IDbTransaction transaction)
        : base(connection, transaction)
    {
    }

    public async Task<List<WeatherForecast>> GetForecastsAsync(CancellationToken cancellationToken)
    {
        var cmd = new CommandDefinition($"select * from {TableName} limit 100",
            transaction: Transaction,
            cancellationToken: cancellationToken);

        var forecasts = await Connection.QueryAsync<WeatherForecastPersistentEntity>(cmd);

        return forecasts
            .Select(MapToDomainEntity)
            .ToList();
    }

    protected override WeatherForecastPersistentEntity MapToPersistentEntity(WeatherForecast entity)
    {
        return new WeatherForecastPersistentEntity
        {
            Id = entity.Id,
            Date = entity.Date,
            Summary = entity.Summary.Text,
            TemperatureC = entity.TemperatureC
        };
    }

    protected override WeatherForecast MapToDomainEntity(WeatherForecastPersistentEntity entity)
    {
        return new WeatherForecast(entity.Id)
            .SetDate(entity.Date)
            .SetSummary(entity.Summary)
            .SetCelciusTemperature(entity.TemperatureC);
    }

    protected override void SetPersistentEntityId(WeatherForecastPersistentEntity entity, int id)
    {
        entity.Id = id;
    }
}

internal static class ReflectionHelper
{
    public static string GetTableName<TPersistentEntity>()
    {
        var persistentEntityType = typeof(TPersistentEntity);
        var tableAttributeType = typeof(TableAttribute);
        var tableAttribute = persistentEntityType.CustomAttributes
            .FirstOrDefault(a => a.AttributeType == tableAttributeType);

        if (tableAttribute == null)
        {
            throw new InvalidOperationException(
                $"Could not find attribute '{tableAttributeType.FullName}' " +
                $"with table name for entity type '{persistentEntityType.FullName}'. " +
                "Table attribute is required for all entity types");
        }

        return tableAttribute.ConstructorArguments
            .First()
            .Value
            .ToString();
    }
}

Example usage:
class SomeService
{
    private readonly IAppUnitOfWork _unitOfWork;

    public SomeService(IAppUnitOfWork unitOfWork)
    {
        _unitOfWork = unitOfWork;
    }

    public async Task DoSomethingAsync(CancellationToken cancellationToken)
    {
        var entity = await _unitOfWork.WeatherForecasts.GetByIdAsync(..., cancellationToken);
        _unitOfWork.WeatherForecasts.Delete(entity);

        var newEntity = new WeatherForecast(...);
        _unitOfWork.WeatherForecasts.Add(newEntity);

        await _unitOfWork.SaveChangesAsync(cancellationToken);
    }
}

A:
Edit 2018-08-03: Amit's comment really got me thinking, and made me realize that the repository's don't in fact NEED to be properties on the context itself. But rather, repositories could have a dependency on the context. Rather than continue to make incremental changes to the code samples below. I will simply reference a git repo I've put together to contain this concept.

Standing on the shoulders of others here.
Considering this answer is top in most Google searches pertaining to "dapper" and "unit of work". I wanted to provide my approach, which I've used to great effect several times now.
Using a ficitious (and overly simplified) example:
public interface IUnitOfWorkFactory
{
    UnitOfWork Create();
}

public interface IDbContext
{
    IProductRepository Product { get; set; }

    void Commit();
    void Rollback();
}

public interface IUnitOfWork
{
    IDbTransaction Transaction { get;set; }

    void Commit();
    void Rollback();
}

public interface IProductRepository
{
    Product Read(int id);
}

Note how neither IDbContext or IUnitOfWorkFactory implements IDisposable. This is purposefully done to avoid a leaky abstraction. Instead the reliance is on Commit()/Rollback() to take care of cleanup and disposal.

A couple of points before sharing implementations.

*

*IUnitOfWorkFactory is responsible for instantiating the UnitOfWork and brokering the database connection.

*IDbContext is the repository backbone.

*IUnitOfWork is an encapsulation of IDbTransaction, and ensures that when working with multiple repositories, they share a single database context.

Implementation of IUnitOfWorkFactory
public class UnitOfWorkFactory<TConnection> : IUnitOfWorkFactory where TConnection : IDbConnection, new()
{
    private string connectionString;

    public UnitOfWorkFactory(string connectionString)
    {
        if (string.IsNullOrWhiteSpace(connectionString))
        {
            throw new ArgumentNullException("connectionString cannot be null");
        }

        this.connectionString = connectionString;
    }

    public UnitOfWork Create()
    {
        return new UnitOfWork(CreateOpenConnection());
    }

    private IDbConnection CreateOpenConnection()
    {
        var conn = new TConnection();
        conn.ConnectionString = connectionString;

        try
        {
            if (conn.State != ConnectionState.Open)
            {
                conn.Open();
            }
        }
        catch (Exception exception)
        {
            throw new Exception("An error occured while connecting to the database. See innerException for details.", exception);
        }

        return conn;
    }
}

Implementation of IDbContext
public class DbContext : IDbContext
{
    private IUnitOfWorkFactory unitOfWorkFactory;

    private UnitOfWork unitOfWork;

    private IProductRepository product;

    public DbContext(IUnitOfWorkFactory unitOfWorkFactory)
    {
        this.unitOfWorkFactory = unitOfWorkFactory;
    }

    public ProductRepository Product =>
        product ?? (product = new ProductRepository(UnitOfWork));

    protected UnitOfWork UnitOfWork =>
        unitOfWork ?? (unitOfWork = unitOfWorkFactory.Create());

    public void Commit()
    {
        try
        {
            UnitOfWork.Commit();
        }
        finally
        {
            Reset();
        }
    }

    public void Rollback()
    {
        try
        {
            UnitOfWork.Rollback();
        }
        finally
        {
            Reset();
        }
    }

    private void Reset()
    {
        unitOfWork = null;
        product = null;
    }
}

Implementation of IUnitOfWork
public class UnitOfWork : IUnitOfWork
{
    private IDbTransaction transaction;

    public UnitOfWork(IDbConnection connection)
    {
        transaction = connection.BeginTransaction();
    }

    public IDbTransaction Transaction =>
        transaction;

    public void Commit()
    {
        try
        {
            transaction.Commit();
            transaction.Connection?.Close();
        }
        catch
        {
            transaction.Rollback();
            throw;
        }
        finally
        {
            transaction?.Dispose();
            transaction.Connection?.Dispose();
            transaction = null;
        }
    }

    public void Rollback()
    {
        try
        {
            transaction.Rollback();
            transaction.Connection?.Close();
        }
        catch
        {
            throw;
        }
        finally
        {
            transaction?.Dispose();
            transaction.Connection?.Dispose();
            transaction = null;
        }
    }
}

Implementation of IProductRepository
public class ProductRepository : IProductRepository
{
    protected readonly IDbConnection connection;
    protected readonly IDbTransaction transaction;

    public ProductRepository(UnitOfWork unitOfWork)
    {
      connection = unitOfWork.Transaction.Connection;
      transaction = unitOfWork.Transaction;
    }

    public Product Read(int id)
    {
        return connection.QuerySingleOrDefault<Product>("select * from dbo.Product where Id = @id", new { id }, transaction: Transaction);
    }
}

To access the database, simply instantiate DbContext or inject using the IoC container of your choice (I personnally use the IoC container provided by .NET Core).
var unitOfWorkFactory = new UnitOfWorkFactory<SqlConnection>("your connection string");
var db = new DbContext(unitOfWorkFactory);

Product product = null;

try
{
    product = db.Product.Read(1);
    db.Commit();
}
catch (SqlException ex)
{
    //log exception
    db.Rollback();
}

The explicit need for Commit() for this simple read-only operation seems excessive, but pays dividends as the system grows. And apparently, offers a minor performance benefit according to Sam Saffron. You "can" also omit the db.Commit() on simple read operations, by doing this though you leaving the connection hanging open and put the onus of cleaning things up onto the garbage collector. So this isn't recommended.
I typically bring the DbContext into the fold at the service-tier, where it works in unison with other services to form the "ServiceContext". I then reference this ServiceContext in the actual MVC layer.
As another point of mention, it's recommended to use async throughout the stack if you can. It is omitted here for simplicity.

A: Okay, it's been half a decade since the OP asked, but as I keep coming across this question when I develop with Dapper (or anything really, this isn't really very Dapper specific). Here's my two cents.
First Let's talk about the other answers:
pimbrouwers' answer IDbContext manages Unit of Work in a very similar way to how entity framework does it. It's perfectly sensible and easy to understand. But the major drawback is that you end up passing a IDbContext to all your business code. It's a bit of a god object. Just like in EF. I prefer to inject individual repositories and make it explicit what database stuff I'm going to be doing, instead of having everything in my domain model always just one . away. However, if you don't agree with my 'god object' objection, pim's answer sounds like the right one for you.
Amit Joshi's answer has the MyRepository take the unit of work as a constructor parameter. This means you can't inject Repositories anymore. This can be solved by injecting repository factories instead, but this is certainly its own level of hassle.
A quick aside: In some of these answers the word "transaction" and "unit of work" are used interchangeably. In practice here they have a 1:1 relationship, but they aren't the same thing. The "transaction" is the db implementation, the "unit of work" is more of a higher level conceptual thing. If we had more persistence that just one database, there would be a difference, and the UOW would contain more than just one transaction. So, to avoid confusion, "Transaction" is probably not a great word to use in our UOW interface.
So here's my way:
I'll start with the Usage
// Business code. I'm going to write a method, but a class with dependencies is more realistic
static async Task MyBusinessCode(IUnitOfWorkContext context, EntityRepoitory repo)
{
    var expectedEntity = new Entity {Id = null, Value = 10};

    using (var uow = context.Create())
    {
        expectedEntity.Id = await repo.CreateAsync(expectedEntity.Value);
        await uow.CommitAsync();
    }

    using (context.Create())
    {
         var entity = await repo.GetOrDefaultAsync(expectedEntity.Id.Value);
         entity.Should().NotBeNull();
         entity.Value.Should().Be(expectedEntity.Value);
    }
}

The unit of work just wraps a transaction and is shortlived:
public class UnitOfWork : IDisposable
{

    private readonly SQLiteTransaction _transaction;
    public SQLiteConnection Connection { get; }

    public bool IsDisposed { get; private set; } = false;

    public UnitOfWork(SQLiteConnection connection)
    {
        Connection = connection;
        _transaction = Connection.BeginTransaction();
    }

    public async Task RollBackAsync()
    {
        await _transaction.RollbackAsync();
    }

    public async Task CommitAsync()
    {
        await _transaction.CommitAsync();
    }

    public void Dispose()
    {
        _transaction?.Dispose();

        IsDisposed = true;
    }
}

The Context is more interesting. It's the way in which the repos and the unit of works communicate behind the scenes.
There's one interface for the business code to manage a unit of work, and one for the repo to abide by that unit of work.
public class UnitOfWorkContext : IUnitOfWorkContext, IConnectionContext
{
    private readonly SQLiteConnection _connection;
    private UnitOfWork _unitOfWork;

    private bool IsUnitOfWorkOpen => !(_unitOfWork == null || _unitOfWork.IsDisposed);

    public UnitOfWorkContext(SQLiteConnection connection)
    {
        _connection = connection;
    }

    public SQLiteConnection GetConnection()
    {
        if (!IsUnitOfWorkOpen)
        {
            throw new InvalidOperationException(
                "There is not current unit of work from which to get a connection. Call BeginTransaction first");
        }

        return _unitOfWork.Connection;
    }

    public UnitOfWork Create()
    {
        if (IsUnitOfWorkOpen)
        {
            throw new InvalidOperationException(
                "Cannot begin a transaction before the unit of work from the last one is disposed");
        }

        _unitOfWork = new UnitOfWork(_connection);
        return _unitOfWork;
    }
}

public interface IConnectionContext
{
    SQLiteConnection GetConnection();
}

public interface IUnitOfWorkContext
{
    UnitOfWork Create();
}

Here's how the repo does that:
public class EntityRepository
{
    private readonly IConnectionContext _context;

    public EntityRepository(IConnectionContext context)
    {
        _context = context;
    }

    public async Task<int> CreateAsync(int value)
    {
        return await _context.GetConnection().QuerySingleAsync<int>(
            @"
insert into Entity (Value) values (@value);
select last_insert_rowid();
", new { value });
    }

    public async Task<Entity> GetOrDefaultAsync(int id)
    {
        return await _context.GetConnection().QuerySingleOrDefaultAsync<Entity>(
            @"
select * from Entity where Id = @id
", new { id });
    }
}

And finally here's DI. Do the setup. Here's a single threaded console application Example. I imagine it would be sensible to make it a singleton or per request. The implementation of UnitOfWorkContext can be changed to match your threading choices anyway (Eg by using a UnitOfWorkContext with a thread static UOW).
public static void Main(string[] args)
{
    using (var connection = new SQLiteConnection("Data Source=:memory:"))
    {
        connection.Open();
        Setup(connection);
        var context = new UnitOfWorkContextContext(connection);
        var repo = new EntityRepository(context);

        MyBusinessCode(repo, context).ConfigureAwait(false).GetAwaiter().GetResult();
    }
}

Full version on Github: https://github.com/NathanLBCooper/unit-of-work-example
Analysis:
We've eliminated god objects and don't need to create factories for all our repositories. the cost is that we've got a little bit more of a subtle non-obvious link between our repos and the Unit of Work stuff. There's no boiler plate, but we do need to be careful about what lifetime we give our context object, especially when multithreading.
I think this is a trade-off that's worth it, but that's me.
PS
I'll add one thing. Maybe you've looked up this answer because you've started using dapper. Right now all your repository methods are separate atomic operations and you feel no need to combine them into transactions yet. Then for the time being you don't need to do any of this. Close this browser window, write your repositories in the most simple and obvious way and be happy.

A: I noticed in your github repo you removed the UnitOfWorkFactory and instead instantiate it when accessing the Connection
Problem with this approach that i can't wrap my head around is.
Imagine the following scenario, if i register DBContext as Scoped and Repositories as Transient
1. UserService CreateUserProfile
    a. UserRepositoryGetByEmail("some@email.com")
    b. UserRepository.Add(user)
    c. AddressRepository.Add(new address)
2. UserService Commit?

In this case all of (1.) above is a single transaction and then I want to commit in (2.)
With a large business layer with multiple services using the same scoped instance of dbcontext I can see transactions overlapping
Now I could set dbcontext as Transient but then UnitOfWork would be different on each injection and it wouldn't work.

A: I've created a simple unit of work implementation on top of Dapper, with some basic CQS in mind. https://github.com/giangcoi48k/Dapper.CQS. Please take a look and see if it can apply to your project.
Use IUnitOfWork to execute the corresponding Query or Command, defined SQL query, or Stored Procedure name in that Query or Command.
For example, here is a simple controller:
namespace Dapper.CQS.Example.Controllers
{
    [ApiController]
    [Route("[controller]/[action]")]
    public class PropertyController : ControllerBase
    {
        private readonly IUnitOfWork _unitOfWork;

        public PropertyController(IUnitOfWork unitOfWork)
        {
            _unitOfWork = unitOfWork;
        }

        [HttpGet]
        public async Task<ActionResult<Property>> GetById([FromQuery] int id)
        {
            var property = await _unitOfWork.QueryAsync(new PropertyGetByIdQuery(id));
            return property == null ? NoContent() : Ok(property);
        }

        [HttpGet]
        public async Task<ActionResult<List<Property>>> Filter([FromQuery] string? name)
        {
            var properties = await _unitOfWork.QueryAsync(new PropertyFilterQuery(name));
            return Ok(properties);
        }

        [HttpGet]
        public async Task<ActionResult<PagedList<Property>>> PagedFilter([FromQuery] string? name, int page = 1, int pageSize = 5)
        {
            var properties = await _unitOfWork.QueryAsync(new PropertyPagedFilterQuery(name, page, pageSize));
            return Ok(properties);
        }

        [HttpPost]
        public async Task<ActionResult<Property>> Create([FromBody] Property property)
        {
            var createdId = await _unitOfWork.ExecuteAsync(new PropertyCreateCommand(property));
            await _unitOfWork.CommitAsync();
            property.Id = createdId;
            return Ok(property);
        }

        [HttpDelete]
        public async Task<ActionResult> Delete([FromQuery] int id)
        {
            await _unitOfWork.ExecuteAsync(new PropertyDeleteCommand(id));
            await _unitOfWork.CommitAsync();
            return Ok();
        }
    }
}

And here is a Query:
namespace Dapper.CQS.Example.CommandQueries
{
    public class PropertyPagedFilterQuery : QueryPagedBase<Property>
    {
        [Parameter]
        public string? Name { get; set; }
        protected override CommandType CommandType => CommandType.Text;
        protected override string Procedure => @"
SELECT *, COUNT(*) OVER() [COUNT]
FROM Properties WHERE Name = @Name OR @Name IS NULL
ORDER BY [Name]
OFFSET (@page -1 ) * @pageSize ROWS
FETCH NEXT @pageSize ROWS ONLY
";

        public PropertyPagedFilterQuery(string? name, int page, int pageSize)
        {
            Name = name;
            Page = page;
            PageSize = pageSize;
        }
    }
}

QueryBase will use Dapper
public abstract class QueryPagedBase<T> : CommandQuery, IQuery<PagedList<T>>, IQueryAsync<PagedList<T>>
    {
        [Parameter]
        public int Page { get; set; }

        [Parameter]
        public int PageSize { get; set; }

        protected virtual string FieldCount => "COUNT";

        public virtual PagedList<T> Query(IDbConnection connection, IDbTransaction? transaction)
        {
            var result = connection.Query<T, int, (T Item, int Count)>(Procedure, (a, b) => (a, b), GetParams(), transaction, commandType: CommandType, splitOn: FieldCount);
            return ToPagedList(result);
        }

        public virtual async Task<PagedList<T>?> QueryAsync(IDbConnection connection, IDbTransaction? transaction, CancellationToken cancellationToken = default)
        {
            var result = await connection.QueryAsync<T, int, (T Item, int Count)>(Procedure, (a, b) => (a, b), GetParams(), transaction, commandType: CommandType, splitOn: FieldCount);
            return ToPagedList(result!);
        }

        private PagedList<T> ToPagedList(IEnumerable<(T Item, int Count)> result)
        {
            return new PagedList<T>
            {
                PageSize = PageSize,
                Page = Page,
                TotalRecords = result.Select(t => t.Count).FirstOrDefault(),
                Items = result.Select(t => t.Item).ToList()
            };
        }
    }


text:
Q: Trying to optimize a subquery in Postgres sql I've been working on this query for a while now and I've finally gotten it to produce the results I want.  However, it is taking a long time to run.  I was hoping there were some optimization tips to make it run a little faster?
LEFT OUTER JOIN
                 (
SELECT testschedule."asset_id" as asset_id,
testschedule."test_id" as    test_id,
testresult."id" as testresult_id,
testschedule."testtaken",
testresult."testdate" as testdate,
testschedule."testdate" as scheduledate,
verify."testresult_id" as scheduleresult_id,
testschedule."testresult_id" as rankidtest,

ROW_NUMBER() OVER (PARTITION BY
testschedule."asset_id",  testschedule."test_id",
testschedule."testdate"

ORDER BY testresult."testdate" ASC) as ranking

FROM
                    "public"."testresult" testresult
LEFT OUTER JOIN "public"."testschedule" testschedule
ON
testschedule."asset_id" = testresult."asset_id"
and testschedule."test_id" = testresult."test_id"

   LEFT OUTER JOIN
               (SELECT testschedule."testresult_id",
      testschedule."asset_id"
      as asset_id,
      testschedule."test_id" as test_id from
      "public"."testschedule" testschedule

    where
      testschedule."client_id" = 25368272
      and testschedule."testdate" > '2016-06-01'
      and testschedule."testdate" < '2016-10-20' ) verify
    ON verify."testresult_id" = testresult."id"
      and verify."test_id" = testschedule."test_id" and
      verify."asset_id" = testschedule."asset_id"

 WHERE

     testschedule."client_id" = 25368272

     and testresult."testdate" >
     testschedule."maxtolerancedate"
     and testresult."testdate" > '2016-06-01'
     and testschedule."testdate" > '2016-06-01'
     and testschedule."testdate" < '2016-10-20'
   ) rank
 ON rank.asset_id = asset."id"
   and rank.test_id = test."id"
   and testschedule."testdate" = rank.scheduledate
   and rank.ranking = 1

Currently this runs in about 39 seconds for 20900 plus rows (varies per client).  That's a little longer that I would like obviously. The sub query within the "rank" sub query with the alias "verify" is there to link the correct testchedule."testresult_id" to go along with the 1st row number for testresult."testdate". Is there an obvious fix that I am missing?


text:
Q: How can I modify the Beamer footline in a way that doesn't change positioning of contents/sidebar? I've started with the basic Berkeley theme in Beamer. I wanted to modify the footer to include the page numbers that are centered on the slide. However, the modified footline element seems to be "stacked" at the bottom of the slide, which shifts slide content up and cuts off the bottom corner of the sidebar.
I want the slide to look exactly like the basic theme with just the page numbers pasted at the bottom, centered. I want the sidebar to extend all the way to the bottom of the slide. What do I have to modify to get this done?
Example code:
\documentclass{beamer}
\usetheme[width=2.0cm]{Berkeley}

%% **this part modifies footline to include slide numbers**

\setbeamertemplate{footline}{%
 \leavevmode%
 \hbox{\begin{beamercolorbox}[wd=\paperwidth,ht=2.25ex,dp=1ex,center]{frame number}%
 \vskip0pt
   \usebeamerfont{footline}\usebeamercolor[fg]{footline}\insertframenumber/\inserttotalframenumber
 \vskip0pt
\end{beamercolorbox}%
}%
 \vskip0pt%
}

\usepackage[utf8]{inputenc}

\title{Sample title}
\author{Anonymous}
\institute{ShareLaTeX}
\date{2013}

\begin{document}

\frame{\titlepage}

\begin{frame}
\frametitle{Sample frame title}
This is a text in first frame. This is a text in first frame. This is a text in first frame.
\end{frame}

\end{document}

A: You can set ht=0pt, dp=0pt so that the beamercolorbox has zero height. Then, adjust the second \vskip to raise the page numbers from the bottom edge. To remove navigation bar, simply use \setbeamertemplate{navigation symbols}{}, and this does not affect the page numbering.
Code
\documentclass{beamer}
\usetheme[width=2.0cm]{Berkeley}

%% **this part modifies footline to include slide numbers**
\setbeamertemplate{footline}{%
  \leavevmode%
  \hbox{\begin{beamercolorbox}[wd=\paperwidth,ht=0ex,dp=0ex,center]{frame number}%
    \vskip0pt
    \usebeamerfont{footline}\usebeamercolor[fg]{footline}
    \insertframenumber/\inserttotalframenumber
    \vskip.5ex
    \end{beamercolorbox}%
  }%
  \vskip0pt%
}
% \setbeamertemplate{navigation symbols}{} % to remove navigation bar

\usepackage[utf8]{inputenc}

\title{Sample title}
\author{Anonymous}
\institute{ShareLaTeX}
\date{2013}

\begin{document}

\frame{\titlepage}

\begin{frame}
\frametitle{Sample frame title}
This is a text in first frame. This is a text in first frame. This is a text in first frame.
\end{frame}

\end{document}

Output