text:
Q: Scrubbing Names via SQL Query/Batch We have sensitive information (names of people) and we're looking to put into place a script to "scrub" of the names.  Has anybody come up with a good algorithm to do this, something other than just making all of the last names "TEST" or something?
Thanks.

A: I had to do this for NPI (non-public information) reasons at a previous employer.  Ended up scrambling fields in a script, since a first name / last name pair isn't NPI unless it's tied to something else.
Here's a rough version of the script.  Season to taste.  Also, this assumes you have first and last names in separate fields.
CREATE TABLE #RandomData
(
    DataID int not null,
    ID int not null,
    FirstName varchar(50),
    LastName varchar(50)
)

INSERT INTO #RandomData (ID, DataID)
SELECT ROW_NUMBER() OVER (ORDER BY NEWID()), DataId FROM DataTable

UPDATE r SET r.FirstName = x.FirstName
FROM #RandomData r
INNER JOIN (
    SELECT ROW_NUMBER() OVER (ORDER BY NEWID()) AS ID, FirstName FROM DataTable
) x
    ON x.ID = r.ID

UPDATE r SET r.LastName = x.LastName
FROM #RandomData r
INNER JOIN (
    SELECT ROW_NUMBER() OVER (ORDER BY NEWID()) AS ID, LastName FROM DataTable
) x
    ON x.ID = r.ID

CREATE CLUSTERED INDEX PK_RandomData ON #RandomData
(
    DataID asc
)

ALTER TABLE DataTable DISABLE TRIGGER ALL

UPDATE dt
    SET dt.FirstName = r.FirstName,
    dt.LastName = r.LastName
FROM DataTable dt
INNER JOIN #RandomData r
    ON dt.DataId = r.DataId

ALTER TABLE DataTable ENABLE TRIGGER ALL

DROP TABLE #RandomData

A: If you don't want to know what the name is but for whatever reason you want to keep something in the table for that record, you can always just use a hash of the name:
UPDATE MyTable
SET Name = HASHBYTES('SHA1', Name)

This will keep a unique value for each name record, but you will have no way to know what the name is.  You can, however, see if a name matches a value by comparing an hashed input to the stored hash.
Cryptographic hashes like this are one way, so you can create an identical hash from an identical input string, but not determine the input string even if you know what the hash is.

A: Yes, thanks to this function name and surname like Jack Sparrow will become Dchv Dkiokmd and e-mail like Jack.Sparrow@pirate27.biz will become Ninj.Sdkpiqy@wywmky53.kdd:
-------------------------------------------------

--A view to give you Random Values
CREATE VIEW dbo.random(value) AS SELECT RAND();

GO
-------------------------------------------------

--Randomization Procedure
CREATE FUNCTION dbo.fnRandomizedText (
@OldValue AS VARCHAR(MAX)
)RETURNS VARCHAR(MAX)

BEGIN

  DECLARE @NewValue AS VARCHAR(MAX)
  DECLARE @nCount AS INT
  DECLARE @cCurrent AS CHAR(1)
  DECLARE @cScrambled AS CHAR(1)
  DECLARE @Random AS REAL

  SET @NewValue = ''
  SET @nCount = 0
   WHILE (@nCount <= LEN(@OldValue))
  BEGIN
    SELECT @Random = value FROM random
    SET @cCurrent = SUBSTRING(@OldValue, @nCount, 1)
     IF ASCII(@cCurrent) BETWEEN ASCII('a') AND ASCII('z')
       SET @cScrambled = CHAR(ROUND(((ASCII('z') - ASCII('a') - 1) * @Random + ASCII('a')), 0))
    ELSE IF ASCII(@cCurrent) BETWEEN ASCII('A') AND ASCII('Z')
       SET @cScrambled = CHAR(ROUND(((ASCII('Z') - ASCII('A') - 1) * @Random + ASCII('A')), 0))
    ELSE IF ASCII(@cCurrent) BETWEEN ASCII('0') AND ASCII('9')
       SET @cScrambled = CHAR(ROUND(((ASCII('9') - ASCII('0') - 1) * @Random + ASCII('0')), 0))
    ELSE
       SET @cScrambled = @cCurrent

    SET @NewValue = @NewValue + @cScrambled
    SET @nCount = @nCount + 1

  END
   RETURN LTRIM(RTRIM(@NewValue))
END
GO
-------------------------------------------------

You can then update your tables just like this.
UPDATE my_Users_table SET UserName = dbo.fnRandomizedText(UserName), LoweredUserName = dbo.fnRandomizedText(LoweredUserName)


text:
Q: Accessing tables inside connections database in R I am using this code to connect
library(dplyr)
library(DBI)

con <- dbConnect(odbc::odbc(), "SQLSERVERR") # Can't use this

con1 <- dbConnect(odbc::odbc(), "SQLSERVERR",database = "db1")
con2 <- dbConnect(odbc::odbc(), "SQLSERVERR",database = "db2")

tbx <- tbl(con1,"some_table")

But my connection has tables inside databases and I  would like to send sql queries to them using dplyr.
something like
tbx <- tbl(con, db = "db1", "some_table")

Thanks for the help.

A: It might depend on a few things. I had the best luck doing a similar task using the RODBC package. SQL Server RODBC Connection
I could access views within the database this way using the sqlFetch function but it is possible to do the query within the sqlQuery function as shown in the example.  If you're accessing a secure, live database, you may want to try the odbcConnect function (also within the same package), having added it as a datasource (https://turbofuture.com/computers/Connect-to-SQL-Server-from-R).

redpajama_set_name: RedPajamaStackExchange


text:
Q: Justification for "reducing integrals" in the virial expansion for gases I have been following this document (https://sites.chem.utoronto.ca/chemistry/jmschofi/chm427/gases.pdf) regarding the virial expansion of gases and on finding the virial coefficients.
On Page 7, they do the following:
$$Z_3 = \int _V d\mathbf{r}_1 d\mathbf{r}_2 d\mathbf{r}_3 f_{12}f_{23}$$
where $f_{ij} = f(|\mathbf{r}_i-\mathbf{r}_j|)$, the Meyer-f function. We are integrating over the entire phase space, with $\mathbf{r}$ being the 3D position vector.
They say that the above integral is reducible, and reduce it as,
$$Z_3 = \int _V d\mathbf{r}_1 d\mathbf{r}_2 d\mathbf{r}_3 f_{12}f_{23} = \int _V d\mathbf{r}_{12} d\mathbf{r}_{2} d\mathbf{r}_{23} f_{12}f_{23}\\=V\left(\int _V d\mathbf{r}_{12}f_{12}\right)\left( \int _Vd\mathbf{r}_{23}f_{23}\right)$$
My question is, why is this last step valid?
I understand substitution (like $u$-substitution, or trig substitution when we are learning basic integrals) of variables within an integral sign, but this seems to be a bit more than that, right?
I made the substitution, $$\mathbf{r}_1 \rightarrow \mathbf{r}_{12}\\ \mathbf{r}_{3} \rightarrow \mathbf{r}_{23}$$
But, if $r_{12} = r_1 - r_2$, then shouldn't $d\mathbf{r}_{12} = d\mathbf{r}_1 - d\mathbf{r}_2$? Furthermore, if $f_{12}$ and $f_{23}$ have a dependence on $\mathbf{r}_2$, why are we ignoring that dependence and just integrating it out?
I am really struggling to understand why that step is allowed.
I would appreciate any advice you have for me.

A: This is not a single variable integral and you should recall what you learn in multiple variable calculus --- the change of variable should follow by Jacobian. Obviously here the Jacobian is 1. Then after change of variable $f_{12}(r)=f_{12}(r_1-r_2)=f_{12}(r_{12})$ would depend on $r_{12}$ only and has nothing to do with $r_2$ and you could integrate $r_2$ out.


text:
Q: Is it possible to change Rich marker size by zoom? I am using the library Rich marker for google maps, now I want to resize the marker size while zooming I have something like this but i tested it with changing the bg color but is seems not to work:
locations[i][0].Smallsize  = $('.rich-marker').css({ 'width' : '5px', 'height' : '5px' });
locations[i][0].Normalsize  = $('.rich-marker').css('background-color',  'red' );

        if (map.getZoom() === 16) {
            marker.scaledSize = locations[i][0].Smallsize;
            console.log(marker.scaledSize);
        }

        if (map.getZoom() === 17) {
            marker.scaledSize = locations[i][0].Normalsize;
            console.log(marker.scaledSize);
        }

This is my second option which also doesn't work:
locations[i][0].Normalsize  = new google.maps.Size(20, 20);

and this is the array of locations:
var locations = [
    [{id: 1,  lat: 51.523903408094064, lng:  5.137792649612493,   content: 'Kids Jungalow Giraffe'}],
    [{id: 2,  lat: 51.52377991387855,  lng:  5.137905302391118,   content: 'Kids Jungalow Giraffe'}],
    [{id: 3,  lat: 51.523643068545915, lng:  5.138098421440191,   content: 'Kids Jungalow Giraffe'}],
    [{id: 4,  lat: 51.52347284572886,  lng:  5.1382003453827565,  content: 'Kids Jungalow Giraffe'}],
    [{id: 5,  lat: 51.52331931087756,  lng:  5.1383505490875905,  content: 'Kids Jungalow Giraffe'}],

and here i set the marker in a for loop:
for (i = 0; i < locations.length; i++) {
            var myLatLng = new google.maps.LatLng({lat: locations[i][0].lat, lng: locations[i][0].lng});
            var number = locations[i][0].id;

        var marker_html = '
'+'' + number + '' + '
';

        var marker = new RichMarker({
            position: myLatLng,
            scaledSize: new google.maps.Size(15, 15),
            draggable: true,
            map: map,
            flat: true,
            anchor: RichMarkerPosition.MIDDLE,
            content: marker_html
        });

A: Got the solution myself sorry for opening a question to quickly!:
if (map.getZoom() === 16) {
            $('.rich-marker').css({ 'width' : '5px', 'height' : '5px' });
            $('.number-id').css({ 'font-size' : '5px'});
        }

    if (map.getZoom() === 17) {
        $('.rich-marker').css({ 'width' : '16px', 'height' : '16px' });
        $('.number-id').css({ 'font-size' : '8px'});
    }

    if (map.getZoom() === 18) {
        $('.rich-marker').css({ 'width' : '20px', 'height' : '20px' });
        $('.number-id').css({ 'font-size' : '12px'});
    }


text:
Q: How to set HTML attribute in conditional rule with jQuery? I'm still confused about how to set other class attribute in an element according to other element attribute in dynamic number.
Here are my HTML & PHP:
<?php for($i=1;$i<=$total;$i++){ ?>
<a href="#no<?php echo $i;?>" id="shorcut<?php echo $i;?>" class"not-yet"><?php echo $i;?>
<?php } ?>

<div id="no<?php echo $no?>" class="<?php if(!empty($h->answer)){ echo 'answered';} else{ echo 'not-yet';} ?>">

And here are my javascript:
$(document).ready(function(){

 var i;
 var tot = <?php echo $jumlah;?>
 for (i=1; i< tot; i++){
    if($('#no'+i).hasClass('answered'){
       $('#shortcut'+i).attr('class', 'answered');
    }
 }
});

For example when
 has a class attribute "answered" then set  (change class from "not-yet" to "answered")
Help me and thanks for your attention

A: Use $(..).addClass('classname') and $(..).removeClass('classname') to change class attributes.
$(function(){
    var tot = <?php echo $jumlah;?>;
    var i;
    for (i=1; i<tot; i++) {
       if ($('#no'+i).hasClass('answered')) {
           $('#shortcut'+i).addClass('answered');
       }
    }
});

A: Here's a quick and dirty solution to your javascript
http://jsfiddle.net/w9uvR/
Basically you just want to do this for each div:
   $(document).ready(function() {
       $("[id^='no']").each(function() {
            if(this.className == "answered") {
               var myId = this.id.replace("no","");
                $("#shortcut" + myId).attr("class", "answered");
             }
        })
    });


text:
Q: Is there a way to preinstall ubuntu (so it shows the wizard to create an account, and orientation stuff, on first boot)? Is there some toolkit used by the OEMs of Ubuntu to install Ubuntu in such a way that it displays some wizard to create an account, and maybe show an orientation video. Also, is there a way to preinstall some packages, also?

A: You may want to look at the Ubuntu Customization Kit.

Ubuntu Customization Kit is a tool that helps you customizing official
  Ubuntu Live CDs (including Kubuntu/Xubuntu and Edubuntu) to your
  needs. You can add any package to the live system, for example
  language packs, or applications.1

To download see the UCK website.  For more information about customization, and other resources, see the Live CD Customization
1Source:UCK


text:
Q: How can I get the HBase table name from a Result object as the mapreduce parameter? HBASE-3996
Support multiple tables and scanners as input to the mapper in map/reduce job.
The map function always looks as follows:
public void map(ImmutableBytesWritable row, Result value, Context context)

In the map function, how can I distinguish which table the (Result)value comes from?

A: You can extract the TableSplit from the context, this should work for you (not tested):
public void map(ImmutableBytesWritable row, Result value, Context context) {
    TableSplit currentSplit = (TableSplit)context.getInputSplit();
    byte[] tableName = split.getTableName();
    ....
}


text:
Q: Integration Tests in grails: getting null in query string parameter I'm doing integration tests  for controllers in grails.I need to pass query string in test case and I'm passing it as controller.request.queryString for the same.
My tests is getting failed. It's giving me null value for the query String parameter.
Controller - UserExController
Foll is the action on which i'm doing integration testing.In this I'm reading query string parameter 'uid' and getting the userInstance using GORM method
def getUser() {
    //reading the query string parameter 'uid'
    def userId = request.getParameter("uid")
    User user = User.findByUsername(userId)
    render view:'edit', model:[userInstance:user]
}

This is the test for the above written action .In this I'm passing the query string parameter and calling the action
class UserInstanceTests extends GroovyTestCase {

    @Test
    void testPerfSummaryApi() {
        def userExController=new UserExController()
        userExController.request.queryString='uid=rp123'
        userExController.getUser()
        def model = userExController.modelAndView.model.userInstance
        assertNotNull model
    }
}

I'm getting groovy.lang.MissingMethod.Exception in the foll call:
User.findByUsername(userId) //userId is comming null

A: Change in Controller:
def userId = request.getParameter("uid")

to
def userId = params.uid

Change in int test:
userExController.request.queryString='uid=rp123'

to
userExController.params.uid='rp123'

Grails' dynamic binding helps in binding the query parameters to params and request to request in the controller.

A: This should make things work for you (tested on Grails 2.0.4):
 userExController.request.addParameter('uid', 'rp123')

However, I would recommend to turn to dmahapatro's suggestion and refactor your controller to use params.uid instead of request.getParameter("uid"). Or even introduce a command object.   The way you are doing it now just does not seem to be the standard Grails way.


text:
Q: Mysql limit with in statement I am writing a query
SELECT
   `user_bookmarks`.`id` as `user_bookmark_id`,
   `bookmark_id`,
   `user_bookmarks`.`user_id`,
   `bookmark_url`,
   `bookmark_website`,
   `bookmark_title`,
   `bookmark_preview_image`,
   `bookmark_popularity`,`category_id`,
   `category_name`,
   `pdf_txt_flag`,
   `youtube_video`,
   `content_preview`,
   `snapshot_preview_image`,
   `mode`
FROM
   `user_bookmarks`
   left join `bookmarks`
      on `user_bookmarks`.`bookmark_id` = `bookmarks`.`id`
   left join `categories`
      on `user_bookmarks`.`category_id` = `categories`.`id`
   WHERE
      `category_id` IN(164,170,172)
   LIMIT 0, 6

it is fetching  first 6 bookmarks. But i want it will fetch  6 bookmarks from each category. Can we do this in mysql itself.
Please adivce..
Thanks

A: You can use a rank query to give a rank for each category and filter it with your desired no of records per category below query will give you 6 records from each category
SELECT t.* FROM
(SELECT
  `user_bookmarks`.`id` AS `user_bookmark_id`,
  `bookmark_id`,
  `user_bookmarks`.`user_id`,
  `bookmark_url`,
  `bookmark_website`,
  `bookmark_title`,
  `bookmark_preview_image`,
  `bookmark_popularity`,
  `category_id`,
  `category_name`,
  `pdf_txt_flag`,
  `youtube_video`,
  `content_preview`,
  `snapshot_preview_image`,
  `mode` ,
   @r:= CASE WHEN category_id = @g THEN @r+1  ELSE @r:=1 END `rank` ,
   @g:=category_id
FROM
  `user_bookmarks`
  LEFT JOIN `bookmarks`
    ON `user_bookmarks`.`bookmark_id` = `bookmarks`.`id`
  LEFT JOIN `categories`
    ON `user_bookmarks`.`category_id` = `categories`.`id`
  JOIN (SELECT @r:=0,@g:=0) t1
WHERE `category_id` IN (164, 170, 172)
ORDER BY category_id
) t
WHERE t.rank <=6

A: You have to use the GROUP BY statement, but you cannot have a limit per each one of them.
I suggest you look at this question with answer in Old post and read the article mentioned in the post.


text:
Q: How do I scrape all the text in the //div[@class='body'] in this website? import scrapy

class ActScraper1Spider(scrapy.Spider):
    name = 'act_scraper_1'
    allowed_domains = ['sso.agc.gov.sg']
    start_urls = ['https://sso.agc.gov.sg/Act/AA2004']

def parse(self, response):

    info = response.xpath("//div[@class='body']//text()").getall()
    yield {
        'info': info
    }

So my code above does part of the job as it only scrapes the first table out of the 8 tables in the div[@class='body'] tag

How do I get my scraper to scrape all the text in all the tables? Thanks!

A: disable Javascript in the browser and reload the page. Then you see the valid newest xpath (you can use 'Quick Javascipt Switcher' on your chrome browser to disable js)


text:
Q: Change value of text input in flutter I do the following to change the value of the input field. Regarding documentation this should work but it don't. Purpose is to open a google location search if location input is tapped and write the result value back to the text field. The following code is a simple version to show my problem:
            TextFormField(
             key: locationKey,
                decoration:
                InputDecoration(labelText: 'Location'),
             // onTap: openLocationSearch,
              onTap: () {
                locationKey.currentState.didChange('test');
             },
          ),

A: This will do what you are looking for:
class TapTextFormIssue extends StatefulWidget {
  @override
  _TapTextFormIssueState createState() => _TapTextFormIssueState();
}

class _TapTextFormIssueState extends State<TapTextFormIssue> {
  TextEditingController _textEditingController = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Center(
      child: TextFormField(
        controller: _textEditingController,
        onTap: () {
          setState(() {
            _textEditingController.text = 'test';
          });
        },
      ),
    );
  }
}

A: Add a TextEditingController to your TextFormField like this
TextEditingController myTEC = TextEditingController('Location');

TextFormField(
  key: locationKey,
  controller: myTEC,
  onTap: () {
    locationKey.currentState.didChange('test');
  },
),


text:
Q: Can't use PutHiveQL in NiFi It gives me the following error :
2019-07-21 11:29:58,105 WARN [Timer-Driven Process Thread-7] o.a.n.controller.tasks.ConnectableTask Administratively Yielding PutHiveQL[id=f58fb42e-016b-1000-c1d4-199cdeb7bdb9] due to uncaught Exception:

java.lang.NoSuchMethodError: org.apache.hive.service.cli.operation.LogDivertAppender.setWriter(Ljava/io/Writer;)


text:
Q: Reflect property name from inside accessor? Using reflection can I get the name of the property from inside that property's accessor?
The quest :=
public string FindMyName
{
    get
    {
        string thisPropertyName = ??
    }
}

A: Simply: don't. You can get the compiler to tell you:
public static string WhoAmI([CallerMemberName] string caller=null)
{
    return caller;
}
...
public string FindMyName
{
    get
    {
        string thisPropertyName = WhoAmI();
        //...
    }
}

This is great for things like OnPropertyChanged:
protected virtual void OnPropertyChanged([CallerMemberName] string caller = null)
{
    var handler = PropertyChanged;
    if(handler != null) handler(this, new PropertyChangedEventArgs(caller));
}
...
public int Foo {
    get { return foo; }
    set { this.foo = value; OnPropertyChanged(); }
}
public string Bar {
    get { return bar; }
    set { this.bar = value; OnPropertyChanged(); }
}

A: class Program
{
    static void Main()
    {
        var propertyName = Nameof<SampleClass>.Property(e => e.Name);

        MessageBox.Show(propertyName);
    }
}

public class GetPropertyNameOf<T>
{
    public static string Property<TProp>(Expression<Func<T, TProp>> exp)
    {
        var body = exp.Body as MemberExpression;
        if(body == null)
            throw new ArgumentException("'exp' should be a member expression");
        return body.Member.Name;
    }
}

A: As CallerMemberName was introduced in.NET 4.5 I believe, you can use this workaround:
public static class StackHelper
{
    public static string GetCurrentPropertyName()
    {
        StackTrace st = new StackTrace();
        StackFrame sf = st.GetFrame(1);
        MethodBase currentMethodName = sf.GetMethod();
        return currentMethodName.Name.Replace("get_", "");
    }
}

with usage:
public class SomeClass
{
    public string SomeProperty
    {
        get
        {
            string s = StackHelper.GetCurrentPropertyName();
            return /* ... */;
        }
    }
}


text:
Q: how to lock a table for writing I would like to lock a table for writing during a period of time, while leaving it available for reading.
Is that possible ?
Ideally I would like to lock the table with a predicate (for example prevent writing rows "where country = france").

A: If you really want to lock against such inserts, i.e. the query should hang and only continue when you allow it, you would have to place a SHARE lock on the table and keep the transaction open.
This is usually not a good idea.
If you want to prevent any such inserts, i.e. throw an error when such an insert is attempted, create a BEFORE INSERT trigger that throws an exception if the NEW row satisfies the condition.

A: You can use FOR SHARE lock, which blocks other transactions from performing like UPDATE and DELETE, while allowing SELECT FOR SHARE. (Read the docs for details: https://www.postgresql.org/docs/9.4/explicit-locking.html [13.3.2])
For example, there are 2 processes accessing table user_table, in the following sequence:

*

*Process A: BEGIN;

*Process A: SELECT username FROM user_table WHERE country = france FOR SHARE;

*Process B: SELECT * FROM user_table FOR SHARE;  (In here, process B can still read all the rows of the table)

*Process B: UPDATE user_table SET username = 'test' WHERE country = france; (In here, process B is blocked and is waiting for process A to finish its transaction)


text:
Q: How to use dynamic variable into angular I have a form where I'm taking a input and according to that creating a number of input boxes. The javascript code is given below for that.
for(i = 1; i <= c; i++) { //c = total input count
    block = block + '
'+
            '
'+
                '<input id="name" ng-model="new.var'+i+'name" type="text" class="form-control">'+
                '<input id="type" ng-model="new.var'+i+'type" type="text" class="form-control">'+
            '
'+
            '
';
}
document.getElementById("vars").innerHTML = block;

Above code is working fine & ng-model are getting generated dynamically fine, like new.var1name , new.var1type , new.var2name , new.var2type and so on.
But how to get those variables in my controller?
If I generate those variables in my controller like below then its giving error that it cant find 'name'.
var var1 = [];
for(i = 1; i <= c; i++) { //c = total input count
    var item = {};
    console.log('var'+i+'name', 'var'+i+'unit');
    item['name'] = $scope.new.var+i+name;
    item['type'] = $scope.new.var+i+type;
    var1.push(item);
}
console.log(JSON.stringify(var1));

so I have used like below but now no error is there but the var1 is empty.
var var1 = [];
for(i = 1; i <= c; i++) {
    var item = {};
    console.log('var'+i+'name', 'var'+i+'type');
    item['name'] = $scope.new['var'+i+'name'];
    item['type'] = $scope.new['var'+i+'type'];
    var1.push(item);
}
console.log(JSON.stringify(var1));

Please anyone help me to find what I'm doing wrong or is it possible to do???

A: I would suggest that, rather than generate the html in your controller, you write this html in your view, and repeat it using angular's ng-repeat directive: https://docs.angularjs.org/api/ng/directive/ngRepeat. Something like this (not tested):

    <input id="name" ng-model="name[$index]" type="text" class="form-control">
    <input id="type" ng-model="type[$index]" type="text" class="form-control">

You should then be able to access the name and type arrays from $scope within your controller. If 'c' is the ng-model for your original input (which defines the number of times to repeat) then new fields should get added dynamically if this the desired functionality?
EDITED
in your controller
$scope.c = 5;
$scope.getNumber = function(num) {
  return new Array(num);
}

in your view

    <input id="name" ng-model="name[$index]" type="text" class="form-control">
    <input id="type" ng-model="type[$index]" type="text" class="form-control">

A: use $scope['new.var'+i+'name']
there are two ways accessing object property in JavaScript:

*

*if you know the name, you can do $scope.new.var1name

*if the name is dynamic, which is your case, you can use the bracket syntax $scope['new.var'+i+'name']


text:
Q: How do I distribute a Perl wxWidgets application to users who do not have Perl or wxWidgets installed? What is the best way to package a Perl wxWidgets application for distribution to Windows and Mac users who do not have Perl or wxWidgets installed?
The users in question are not very computer savvy, so they cannot be expected to install Perl or wxWidgets separately. I'd like to distribute one .exe/.msi and one .dmg installation file that will include the application and all dependencies. How do I do that?

A: Try with PAR::Packer Wx::Perl::Packager
Then you can use wxpar command to build the execution binary. e.g.
wxpar --gui --icon=myicon.ico -o myprog.exe myscript.pl

A: Your users never have to install wxWidgets to run your program.  You can include the wxWidgets DLLs in the .msi ( installer ).  I haven't used Perl in years, but I would think you can do the same with the Perl interpreter.


text:
Q: SAR ADC of Nucleo board changes conversion result to a wrong one randomly I am using a NUCLEO-L432KC board DATASHEET I am trying to configure the ADC conversion with a 10k potentiometer
However the ADC seems to give a wrong results
I set the pot to output 5v (asserted with a multimeter) and used the result to control PWM duty cylcle on an LED However the glowing of the led seemed constant (no changes in the duty cycle by varying the pot)
The gdb output of the ADC_DR register shows the result of the ADC conversion changes to a wrong value immediately after reading it and stays that way
(gdb) x/d &ADC_DR
0x50040040:     4095
(gdb) x/d &ADC_DR
0x50040040:     1703
(gdb)

The 4095 is the intended result for me as the multimeter shows 5v however the result goes back to arbitarly value under 2k without no instructions executed in between tried to raise the Sampling time to 24.5 clock cycles with no luck
The ADC_init function is as shown:
main:
    bl      clockInit80
    bl      TIM2_PWM_Init
    bl      ADC_Init
1:
    ldr     r1, =ADC_CR
    ldr     r0, [r1]
    orr     r0, #(1 << 2)       @ADCSTART = 1
    str     r0, [r1]
    @wait for the conversion to complete
    mov     r0, #30
    delay:
        subs    r0, #1
        bne     delay

    @read ADC_DR
    ldr     r1, =ADC_DR
    ldr     r0, [r1]
    ldr     r2, =5000
    mul     r0, r2
    ldr     r2, =4096
    sdiv    r0, r2

    @store the result in TIM2_CCR1
    ldr     r1, =TIM2_CCR1
    str     r0, [r1]

    ldr     r1, =TIM2_EGR
    ldr     r0, [r1]
    orr     r0, #(1 << 0)
    str     r0, [r1]

    b       1b

ADC_Init:
    @Select clock source for the ADC (Mandatory) else no clock
    ldr     r1, =RCC_CCIPR
    ldr     r0, [r1]
    orr     r0, #(3 << 28)  @ADCSEL Bits [29:28]
    str     r0, [r1]

    @Enable clock for ADC
    ldr     r1, =RCC_AHB2ENR
    ldr     r0, [r1]
    orr     r0, #(1 << 13)  @ADCEN Bit 13
    str     r0, [r1]

    @Disable deep down power mode Bit 29
    ldr     r1, =ADC_CR
    ldr     r0, [r1]
    mvn     r2, #(1 << 29)
    and     r0, r2
    str     r0, [r1]

    @Enable the ADC voltage regulator ADVREGEN
    ldr     r1, =ADC_CR
    ldr     r0, [r1]
    orr     r0, #(1 << 28)
    str     r0, [r1]
    @ADC voltage regulator average wake up time is 20us wait for 50us
    @waitStart
    ldr     r0, =4000
    1:
        subs    r0, #1
        bne     1b
    @waitEnd

    @set the number of ADC conversion to be single conversion
    ldr     r1, =ADC_SQR1
    ldr     r0, [r1]
    orr     r0, #(1 << 0)   @L (sequence legnth) Bits [3:0]
    str     r0, [r1]

    @set the first (and only channel to be channel 5 (ADC_IN5 = PA0)
    ldr     r1, =ADC_SQR1
    ldr     r0, [r1]
    orr     r0, #(5 << 6)   @SQ1[10:6]
    str     r0, [r1]

    @set channel 5 adc sampling time to be 24.5 clock cycles
    ldr     r1, =ADC_SMPR1
    ldr     r0, [r1]
    orr     r0, #(3 << 15)
    str     r0, [r1]

    @Enable ADC first clear the ADRDY bit
    ldr     r1, =ADC_ISR
    ldr     r0, [r1]
    orr     r0, #(1 << 0)
    str     r0, [r1]

    @Set the ADEN bit in ADC_CR
    ldr     r1, =ADC_CR
    ldr     r0, [r1]
    orr     r0, #(1 << 0)
    str     r0, [r1]

    @wait for ADRDY bit to be set
    1:
        ldr     r1, =ADC_ISR
        ldr     r0, [r1]
        tst     r0, #(1 << 0)
        beq     1b

    @return
    bx      lr

EDIT1: The PA0 is connected directly to the 5v output from the 10k pot (PA0 is 5v tolerant as indicated in the datasheet)
AGAIN it actually shows the correct value for the conversion for a sec but it changes immediately to a wrong one so I don't think the problem has anything to do with the connection and it's varying by hunderds of digits as shown above
EDIT2: The 5V is changed to 3.3V as suggested and the ADC is asserted to be working fine using cubeMX and HAL code (No damage from the 5V the ADC_DR in the HAL code is constant with the correct value)
The clock is configured to be the system clock at 80Mhz I suspect the problem is in my initialization code but I am already following the reference manual init sequence maybe there's some detail I am missing
Connection Schematic

A: Don't feed the ADC pin with 5V, it is wrong.
The ADC cannot read voltages beyond the Vref, which is most likely same as Vdd, which is most likely 3.3V.
The GPIO pin as digital input can tolerate 5V, but as and ADC input it is not 5V tolerant, and even if it were, it will still read 4095 when voltage is above 3.3V because that is what the analog circuitry can handle.
Please note that setting the pot to the 5V extreme end migh have already damaged the MCU.

A: After you've fed 5V to that ADC input pin, consider the MCU chip junk and replace it. It seems that the chip "works fine": you don't know that. After exceeding the absolute maximum ratings, the chip may misbehave in interesting ways, and you'll never be able to fully trust it. Just replace it.
Don't feed more than the ADC reference voltage, e.g. 3.3V. It should work fine then, assuming you've made no other mistakes. In many cases some initialization code, such as clock selection for the ADC, may have "interesting" side effects.
The ADC needs a clock signal, since it's a SAR, and that clock cannot be too fast or you'll be getting funky results. You also need to check in the datasheet whether the ADC data register allows multiple reads without starting another conversion, and make sure that you've set it for continuous conversion.
And most importantly: read the errata sheet for your chip. Datasheets document the wishes of the designers in ideal circumstances. Due to human mistakes, the actual chip you're using may not behave exactly as the datasheet would imply. On most complex MCUs I've seen, the A/D converter always has some errata.

A: I don't know what to say the problem was that the SQR1 register uses the Sequence 0000 for 1 conversion and I somehow saw and used it as 0001 after modification the Code works fine now and luckily the MCU isn't damaged from the earlier 5V mistake anyway thanks for your help..!!


text:
Q: Invalid Key Length After Upgrading to NodeJS 6 The following Code to encrypt and decrypt requests to our payment gateway service works correctly with Node Js 5.7.0
function Encrypt(plainText, workingKey) {
    var m = crypto.createHash('md5');
    m.update(workingKey);
    var key = m.digest('binary');
    var iv = '\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f';
    var cipher = crypto.createCipheriv('aes-128-cbc', key, iv);
    var encoded = cipher.update(plainText, 'utf8', 'hex');
    encoded += cipher.final('hex');
    return encoded;
};

function Decrypt(encText, workingKey) {
    var m = crypto.createHash('md5');
    m.update(workingKey)
    var key = m.digest('binary');
    var iv = '\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f';
    var decipher = crypto.createDecipheriv('aes-128-cbc', key, iv);
    var decoded = decipher.update(encText, 'hex', 'utf8');
    decoded += decipher.final('utf8');
    return decoded;
};

However after upgrading to NodeJS 6.0 (also tried 6.1) we get the following error.
Debug: internal, implementation, error
Error: Uncaught error: Invalid key length
at Error (native)
at new Cipheriv (crypto.js:184:16)
at Object.Cipheriv (crypto.js:182:12)

Our key length has always been 16 characters (i.e 128 bits) and was working before the upgrade. Why would this problem be happening now?

A: I am posting the answer here in the hope it might help someone.
The problem seems to be caused due to using 'binary' digest for the key.
The solution is to simply call the digest function and store the key as a buffer instead.
The fixed code reads as
function Encrypt(plainText, workingKey) {
    var m = crypto.createHash('md5');
    m.update(workingKey);
    var key = m.digest();
    var iv = '\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f';
    var cipher = crypto.createCipheriv('aes-128-cbc', key, iv);
    var encoded = cipher.update(plainText, 'utf8', 'hex');
    encoded += cipher.final('hex');
    return encoded;
};

My thanks to @Artjom-b for the answer.


text:
Q: Voisin's proof of the Hodge index theorem I'm afraid this question is specific to Voisin's proof of the hodge index thm in her book Hodge Theory and Complex Algebraic Geometry vol 1. Let $X$ be compact Kahler of even complex dimension $\dim_{\mathbf C}=n$. In particular, she states that the sign of the Hermitian form $H(\alpha,\beta)=\int_X\alpha\wedge\overline\beta$ on $L^rH_{\mathrm{prim}}^{a,b}$ is equal to $(-1)^a$, where $a+b=n-2r$ and $L$ denotes the Lefschetz operator on cohomology. To obtain this, she refers to prior results which state that (A) (for possibly $k\ne n$), the form $(-1)^{k(k-1)/2}i^{p-q-k}H_k$ is positive definite on $H_{\mathrm{prim}}^{p,q}:=H^k(X,\mathbf C)_{\mathrm{prim}}\cap H^{p,q}(X)$, where $H_n$ coincides with $H$ as denoted above, and (B) on $L^r H^{k-2r}(X,\mathbf C)_{\mathrm{prim}}$, $H_k$ induces the form $(-1)^rH_{k-2r}$ (here I have corrected what I believe is a typo in the book).
When I try to do this computation, I see that combining (A) and (B) above with $a+b=n-2r$, I get that $H$ ($=H_n$) has sign
$$(-1)^r(-1)^{(n-2r)(n-2r-1)/2}i^{a-b-(n-2r)}=(-1)^{r-r+n/2}i^{-2b}=(-1)^{n/2}(-1)^a$$
on $L^rH_{\mathrm{prim}}^{a,b}$. What have I misunderstood?

A: the reason is that the Hermitian form $H(\alpha,\beta)=\int_X \alpha\wedge\overline\beta$ she defines in the beginning of the proof only coincides with the Hermitian form $H_n(\alpha,\beta)=i^n\int_X\alpha\wedge\overline\beta$ defined earlier in the section (and about which the statements (A) and (B) are made) up to the omitted factor of $i^n=(-1)^{n/2}$.


text:
Q: scalar product vs projection The scalar  is defined as the length of the projection of A onto B.
Now suppose $A=(1,1)$ and $B=(2,1)$. The scalar would be 3, while the projection of A onto B would be the vector $(\frac{6}{5}, \frac{3}{5})$, which has a length of $3\sqrt{\frac{1}{5}} \ne 3$. How is it possible?
(Please excuse my stupid question)

A: Define $J(a,b):=(-b,a)$ the counterclockwise rotation of $(a,b)$ by $\pi/2$.  Then $\langle(a,b),(c,d)\rangle=\det\bigl((a,b),J(c,d)\bigr)\rangle$, which is the (orientated) area of the parallelogram spanned by $(a,b)$ and $J(c,d)$.  Hence your interpretation of the scalar product is wrong (unless one of the vectors is a unit vector and both vectors are positive orientated).


text:
Q: A question of chance. I'm having a bit of trouble with this problem.
Three cards are drawn from a pack of regular playing cards. What's the probability of getting different suits, as well as different denominations (number, face, etc.)?
Bonus question. In the above case, it isn't specified whether the cards are drawn simultaneously, or one by one. Would it make a difference?

A: first one is 'any card' P = 1
2nd drawing has to be 12 denominations out of 3 suits, so it is 36 out of 51 remaining p2 = 36 / 51
3rd drawing 11 denominations from 2 suits, 22 / 50
answer = (36 / 51) (22 / 50) = 132 / 425

bonus question - drawing method makes no difference, unless there is replacement and a reshuffle after each card, which changes things, it would make the denominator go back to 52 in each fraction, since you could redraw the same card - but I don't think they mean that - with my method you could take 3 straight off the top and check them, or deal them one-by-one, it makes no difference


text:
Q: When is it safe to free sockaddr passed to bind? Bind expects a pointer to struct sockaddr (https://man7.org/linux/man-pages/man2/bind.2.html). Is it safe to free this structure immediately after the call to bind or is it safe to free this only when the socket is closed?
If it is safe to free the structure immediately after the call to bind, does the kernel keep a copy of the address?

A: You can free it immediately after the call.
Usually the sockaddr or sockaddr_in is declared on the stack. But if you're passing addresses around by pointer, you're ok free it immediately after bind returns.  Same holds true for other socket functions like connect and sendto.

A: It is safe to free. As you can see in the comments to the Linux source for the syscall, the structure is copied by the kernel.

*

*We move the socket address to kernel space before we call  *    the
protocol layer (having also checked the address is ok).


text:
Q: Swift weak reference going nil even when self keeps existing I'm trying to figure out why is a weak reference losing its referenced object even after the object keeps existing.
My code looks like:
MyClass {
    deinit {
        print("I'm being deinited") // This never gets called
    }
    func doConnection(connection: Future<Data, ServerConnectionError>) {
        Future<Void, ServerConnectionError> { complete in
            connection.onSuccess {[weak self] data in
                guard let strongSelf = self else {
                    return // This line gets called
                }
                ...
            }
        }
    }
}

By inspecting the memory graph, I can see that the object referenced by self before the future completes is still alive (judging by the memory address).
Here's what the memory graph for the supposedly missing object looks like after finding its weak reference as nil (MyClass instance in far right):

The upper subtree is the one supposed to hold the object alive, while the bottom one has to do with the current stack execution. The object (blue box) that is referenced by many others in the 3rd level (from right to left) holds a strong reference to an array, which in turn holds a reference to the MyClass instance.
EDIT: Problem solved in answer below. Will mark as solved after cooldown passes.

A: Problem solved. Ok, so I don't know what was going on, but it fixed itself after multiple attempts to debug it. One thing that is still buggy is that the debugger show self as nil inside the closure (which added a significant time in the debugging process), but the guard let block executes successfully and I get a strong reference to the object.

A: Move any capture list containing self to the outer-most closure or else it may create a reference cycle:
MyClass {
    deinit {
        print("I'm being deinited") // This never gets called
    }
    doConnection(connection: Future<Data, ServerConnectionError>) { [weak self] in
        Future<Void, ServerConnectionError> { complete in
            connection.onSuccess { data in
                guard let strongSelf = self else {
                    return // This line gets called
                }
                ...
            }
        }
    }
}

A: By default, a closure expression captures the properties from its surrounding scope with strong references to those values. But you are defining self to be weak in your closure/promise. You may remove [weak self] use [unowned self] or move the closure list to the outer block. So long as your instance of MyClass is not deallocated while the promise is being fulfilled. Objects with no strong references are deallocated only when memory pressure triggers garbage collection. However, within ARC, values are deallocated as soon as their last strong reference is removed. By making self weak in your closure you are allowing ARC to remove the references to your instance of MyClass when no other strong reference exists, your weak reference will be removed after the instance of MyClass is deinitialized.


text:
Q: Non-linear relation of sec.axis to the primary axis I am trying to transform the secondary axis of a ggplot using the formula 1/10^x but I am not succeeding. Can someone help?
This is the reproducible code:
x <- as.factor(c(1,2,3,1,2,3,1,2,3,1,2,3))
y <- c(0.0541, 0.0706, 0.4803, 0.0151, 0.0729, 0.0689, 0.0986, 0.1949, 0.3323, 0.5166, 0.0988, 0.2321)
grupo <- as.factor(c(1,1,1,2,2,2,3,3,3,4,4,4))
br <- c(0,0.1, 0.2,0.3,0.4, 0.5, 0.6, 0.7)

df <- data.frame(x =x ,y = y, gr = grupo)

ggplot() +
  geom_point(data=df, aes(x=x, y=y, group=gr, color= gr, shape= gr))+
  geom_line(data=df, aes(x=x, y=y, group=gr, color= gr ))+
  scale_y_reverse(limits = c(0.7, -0.05), breaks = br,
              sec.axis = sec_axis(trans = ~.*10, breaks = br*10))

But I would like to show in the secondary axis the following numbers 1/10^br, that you can see in the image:

Thank you!!

A: br <- seq(0, 1, 0.1)

ggplot() +
  geom_point(data=df, aes(x=x, y=y, group=gr, color= gr, shape= gr))+
  geom_line(data=df, aes(x=x, y=y, group=gr, color= gr ))+
  scale_y_reverse(limits = c(0.7, -0.05), breaks = br,
                  sec.axis = sec_axis(trans = ~1/(10^.), breaks = br))

Verification of values:
t <- data.frame(x = seq(0, 0.7, 0.1))
t$pow_ten = 10^t$x
t$sec_ax = 1/t$pow_ten
t

    x  pow_ten    sec_ax
1 0.0 1.000000 1.0000000
2 0.1 1.258925 0.7943282
3 0.2 1.584893 0.6309573
4 0.3 1.995262 0.5011872
5 0.4 2.511886 0.3981072
6 0.5 3.162278 0.3162278
7 0.6 3.981072 0.2511886
8 0.7 5.011872 0.1995262


text:
Q: How to convert a .txt to .xml in python So the current problem I'm facing would be in converting a text file into a xml file.
The text file would be in this format.
Serial Number:      Operator ID:  test  Time:  00:03:47 Test Step 2      TP1:  17.25    TP2:  2.46
Serial Number:      Operator ID:  test  Time:  00:03:47 Test Step 2      TP1:  17.25    TP2:  2.46

I wanted to convert to convert it into a xml with this format:
<?xml version="1.0" encoding="utf-8"?>
<root>
 <filedata>
 </serialnumber>
 <operatorid>test</operatorid>
 <time>00:00:42 Test Step 2</time>
 <tp1>17.25</tp1>
 <tp2>2.46</tp2>
 </filedata>
...
</root>

I was using a code like this to convert my previous text file to xml...but right now I'm facing problems in splitting the lines.
import xml.etree.ElementTree as ET
import fileinput
import os
import itertools as it

root = ET.Element('root')
with open('text.txt') as f:
    lines = f.read().splitlines()
celldata = ET.SubElement(root, 'filedata')
for line in it.groupby(lines):
    line=line[0]
    if not line:
        celldata = ET.SubElement(root, 'filedata')
    else:
        tag = line.split(":")
        el=ET.SubElement(celldata,tag[0].replace(" ",""))
        tag=' '.join(tag[1:]).strip()
        if 'File Name' in line:
            tag = line.split("\\")[-1].strip()
        elif 'File Size' in line:
            splist =  filter(None,line.split(" "))
            tag = splist[splist.index('Low:')+1]
            #splist[splist.index('High:')+1]
        el.text = tag
import xml.dom.minidom as minidom
formatedXML = minidom.parseString(
                          ET.tostring(
                                      root)).toprettyxml(indent=" ",encoding='utf-8').strip()

with open("test.xml","wb") as f:
    f.write(formatedXML)

I saw a similar question in stackoverflow
" Python text file to xml "
but the problem is I couldn't change it into a .csv format as this file is generated by a certain machine.
If anyone know how to solve it, please do help.
Thank you.

A: Here is a better method of splitting the lines.
Notice that the text variable would technically be your .txt file, and that I purposely modified it so that we have a greater context of the output.
from collections import OrderedDict
from pprint import pprint

# Text would be our loaded .txt file.
text = """Serial Number:  test    Operator ID:  test1  Time:  00:03:47 Test Step 1      TP1:  17.25    TP2:  2.46
Serial Number:      Operator ID:  test2  Time:  00:03:48 Test Step 2      TP1:  17.24    TP2:  2.47"""

# Headers of the intended break-points in the text files.
headers = ["Serial Number:", "Operator ID:", "Time:", "TP1:", "TP2:"]

information = []

# Split our text by lines.
for line in text.split("\n"):

    # Split our text up so we only have the information per header.
    default_header = headers[0]
    for header in headers[1:]:
        line = line.replace(header, default_header)
    info = [i.strip() for i in line.split(default_header)][1:]

    # Compile our header+information together into OrderedDict's.
    compiled_information = OrderedDict()
    for header, info in zip(headers, info):
        compiled_information[header] = info

    # Append to our overall information list.
    information.append(compiled_information)

# Pretty print the information (not needed, only for better display of data.)
pprint(information)

Outputs:
[OrderedDict([('Serial Number:', 'test'),
              ('Operator ID:', 'test1'),
              ('Time:', '00:03:47 Test Step 1'),
              ('TP1:', '17.25'),
              ('TP2:', '2.46')]),
 OrderedDict([('Serial Number:', ''),
              ('Operator ID:', 'test2'),
              ('Time:', '00:03:48 Test Step 2'),
              ('TP1:', '17.24'),
              ('TP2:', '2.47')])]

This method should generalize better than what you are currently writing, and the idea of the code is something I've had saved from another project. I recommend you going through the code and understanding its logic.
From here you should be able to loop through the information list and create your custom .xml file. I would recommend you checking out dicttoxml as well, as it might make your life much easier on the final step.
In regards to your code, remember: breaking down fundamental tasks is easier than trying to incorporate them all into one. By trying to create the xml file while you split your txt file you've created a monster that is hard to tackle when it revolts back with bugs. Instead, take it one step at a time -- create "checkpoints" that you are 100% certain work, and then move on to the next task.


text:
Q: Automapper asp.net core Controller - Mapper Not Initialized Error I have been looking at this document https://automapper.readthedocs.io/en/stable/Getting-started.html to try to configure automapper to take away the pain of some manual attribute mapping.
I am coming up against the following error:
Message: System.InvalidOperationException : Mapper not initialized. Call Initialize with appropriate configuration. If you are trying to use mapper instances through a container or otherwise, make sure you do not have any calls to the static Mapper.Map methods, and if you're using ProjectTo or UseAsDataSource extension methods, make sure you pass in the appropriate IConfigurationProvider instance.
This bit - "Mapper not initialized. Call Initialize with appropriate configuration" - is concerning because I feel I have done that in my startup.cs file.
I have the following controller action:
[HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Index(NewCreditCardApplicationDetails applicationDetails)
    {
        if (!ModelState.IsValid)
        {
            return View(applicationDetails);
        }

        CreditCardApplication creditCardApplication = Mapper.Map<CreditCardApplication>(applicationDetails);

        //var creditCardApplication = new CreditCardApplication
        //{
        //    FirstName = applicationDetails.FirstName,
        //    LastName = applicationDetails.LastName,
        //    Age = applicationDetails.Age.Value,
        //    GrossAnnualIncome = applicationDetails.GrossAnnualIncome.Value,
        //    FrequentFlyerNumber = applicationDetails.FrequentFlyerNumber
        //};

        await _applicationRepository.AddAsync(creditCardApplication);

        return View("ApplicationComplete", creditCardApplication);
    }

The commented lines represent code that did work, but I want to remove.
My configure method in startup.cs file in my asp.net core web app looks like this:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, AppDbContext dbContext)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();

            dbContext.Database.EnsureCreated();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseStaticFiles();
        app.UseCookiePolicy();

        Mapper.Initialize(cfg =>
        {
            cfg.CreateMap<NewCreditCardApplicationDetails, CreditCardApplication>();
        });

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });
    }

NewCreditCardApplicationDetails.cs looks like this:
public class NewCreditCardApplicationDetails
{
    [Display(Name = "First Name")]
    [Required(ErrorMessage = "Please provide a first name")]
    public string FirstName { get; set; }

    [Display(Name = "Last Name")]
    [Required(ErrorMessage = "Please provide a last name")]
    public string LastName{ get; set; }

    [Display(Name = "Age (in years)")]
    [Required(ErrorMessage = "Please provide an age in years")]
    [Range(18,int.MaxValue, ErrorMessage = "You must be at least 18 years old")]
    public int? Age { get; set; }

    [Display(Name = "Gross Income")]
    [Required(ErrorMessage = "Please provide your gross income")]
    public decimal? GrossAnnualIncome { get; set; }
    public string FrequentFlyerNumber { get; set; }
}

CreditCardApplication.cs looks like this:
public class CreditCardApplication
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }
    public decimal GrossAnnualIncome { get; set; }
    public string FrequentFlyerNumber { get; set; }
}

Can anyone see what the issue is please?
Thanks.

A: Checkout this: https://medium.com/ps-its-huuti/how-to-get-started-with-automapper-and-asp-net-core-2-ecac60ef523f
You should inject the mapper to use it and don't use the static one.


text:
Q: Make js fire more than once? I have a set of radio buttons, and I want this code to fire every time I click the radio buttons, but it only displays the div with its content once, and then it's no longer working. I'm not sure what I'm doing wrong here.

A: Try setting the #adr div's innerHTML to nothing (' ') rather than its display to "nothing".
Change it to:
else if (document.getElementById('nothing').checked) {
    document.getElementById('adr').style.innerHTML = ''; // <-- here
}

Instead of:
else if (document.getElementById('nothing').checked) {
    document.getElementById('adr').style.display = 'none'; // <-- here
}

So instead of hiding the div (so when you next change its innerHTML nothing displays) you change the innerHTML to nothing, so that when you change it back it displays the content

A: This is because you set the display of the div to none in the block that is run if the nothing radio button is checked, and you don't set the display to block when it is set to the option that shows the div, so the display remains as none. My solution is this: Keep the contents of the street div the same, and only toggle its display value. Even better, toggle visibility instead, unless you MUST set display to none.


text:
Q: How to describe an unsmooth hill? I have a really quick and dumb question here. I need to describe a distribution. I have difficulty with explaining an unsmooth hill. If you see the picture, after the peak there is a hill but it doesn't go straight down. There is a flat place, but I don't know how to explain this flat place. I thought this can be explained as bump, but it is not accurate to explain as bump.
Thanks for any help!

A: After reaching a peak, the curve goes halfway down only to form a secondary plateau (mentioned in Edwin Ashworth's comment) before it moves down again.

plateau - (noun)  "a region of little or no change in a graphic representation" Meriam-Webster

A: You could call that flat place a ledge on the slope. One definition of "ledge" is "a flat surface that projects from a wall of rock." In your picture, the flat section certainly projects from the rock face above it.

A: I would just call the "bump" a foothill. I always thought that foothills were technically only at the foot of a mountain, but according to that definition, it can be at the "foot of higher hills".
Edit: I thought there was a mathematical term for that specific kind of curve, though I can't remember what it was.


text:
Q: Highchart.getSVG convert to png In Highchart to I use  Highchart.getSVG() get SVG code that svg code to convert to base64 becuase that base64 value to return bean to store png image in specify path.Is this possible or any other way?

A: PNG is a raster format, SVG is a vector format. You'll need to perform rasterisation to convert the SVG to PNG. You could use Apache Batik to do that. Specifically, the Transcoder API can be used to rasterize your SVG.


text:
Q: Выделение полей формы при валидации Подскажите как сделать, чтобы не валидные поля ввода выделялись только после нажатия на кнопку, а не изначально.
И еще, из-за чего может не работать маска ввода номера в попапе, форма абсолютно идентичная что и без него.

* {
  box-sizing: border-box;
}

.contact-form input {
  width: 100%;
  height: 50px;
  font-size: 17px;
  padding-left: 15px;
  border: none;
  margin-bottom: 30px;
}

.contact-form textarea {
  width: 100%;
  height: 200px;
  font-size: 17px;
  padding-left: 15px;
  border: none;
  padding-top: 15px;
}

.contact-form button {
  margin-top: 30px;
  padding: 20px 83px;
  font-size: 17px;
  color: #fff;
  font-weight: 300;
  border: none;
  background-color: #892531;
  cursor: pointer;
}

input:invalid {
  border: 1px solid red;
}

input:invalid::-webkit-input-placeholder {
  color: red;
}

input:invalid::-moz-placeholder {
  color: red;
}

input:invalid:-moz-placeholder {
  color: red;
}

input:invalid:-ms-input-placeholder {
  color: red;
}
<form action="#" class="contact-form">

      <input type="text" required name="" id="name" placeholder="Ваше имя *">
      <input type="text" required name="" id="phone" placeholder="Контактный телефон *">

      <input type="text" name="" id="" placeholder="Бюджет">
      <input type="email" name="" id="email" placeholder="Email">

      <textarea name="" required id="message" cols="" rows="" placeholder="Детали проекта *"></textarea>
      <button class="" type="submit">ОТПРАВИТЬ</button>

</form>

A:

* {
  box-sizing: border-box;
}

.contact-form input {
  width: 100%;
  height: 50px;
  font-size: 17px;
  padding-left: 15px;
  border: none;
  margin-bottom: 30px;
}

.contact-form textarea {
  width: 100%;
  height: 200px;
  font-size: 17px;
  padding-left: 15px;
  border: none;
  padding-top: 15px;
}

.contact-form button {
  margin-top: 30px;
  padding: 20px 83px;
  font-size: 17px;
  color: #fff;
  font-weight: 300;
  border: none;
  background-color: #892531;
  cursor: pointer;
}

input:invalid:focus {
  outline: none;
  border: 1px solid red;
}

input:invalid:focus::-webkit-input-placeholder {
  color: red;
}

input:invalid:focus::-moz-placeholder {
  color: red;
}

input:invalid:focus:-moz-placeholder {
  color: red;
}

input:invalid:focus:-ms-input-placeholder {
  color: red;
}
<form action="#" class="contact-form">

      <input type="text" required name="" id="name" placeholder="Ваше имя *">
      <input type="text" required name="" id="phone" placeholder="Контактный телефон *">

      <input type="text" name="" id="" placeholder="Бюджет">
      <input type="email" name="" id="email" placeholder="Email">

      <textarea name="" required id="message" cols="" rows="" placeholder="Детали проекта *"></textarea>
      <button class="" type="submit">ОТПРАВИТЬ</button>

</form>


text:
Q: How to detect the peak Values using Python SciPy, getting index error"arrays used as indices must be of integer (or boolean) type" I have the speed data in that I need to detect the values where threshold is greater than 20 and valley greater than 0. I used this code for peak detection but I am getting index error
import numpy as np
from scipy.signal import find_peaks, find_peaks_cwt
import matplotlib.pyplot as plt
import pandas as pd
import sys
np.set_printoptions(threshold=sys.maxsize)
zero_locs = np.where(x==0)
search_lims = np.append(zero_locs, len(x)) # limits for search area

diff_x = np.diff(x)
diff_x_mapped = diff_x > 0
peak_locs = []
x = np.array([1, 9, 18, 24, 26, 5, 26, 25, 26, 16, 20, 16, 23, 5, 1, 27,
22, 26, 27, 26, 25, 24, 25, 26, 3, 25, 26, 24, 23, 12, 22, 11, 15, 24, 11,
26, 26, 26, 24, 25, 24, 24, 22, 22, 22, 23, 24])

for i in range(len(search_lims)-1):
    peak_loc = search_lims[i] + np.where(diff_x_mapped[search_lims[i]:search_lims[i+1]]==0)[0][0]
    if x[peak_loc] > 20:
        peak_locs.append(peak_loc)
fig= plt.figure(figsize=(10,4))
plt.plot(x)
plt.plot(np.array(peak_locs), x[np.array(peak_locs)], "x", color = 'r')

I tried using peak detection algorithm where it is not detecting peaks where the peak value is above 20 i need to detect the peaks where x values is 0 and peak values is 20
expected output: the marked peaks has to be detected
by running the above script i am getting this error
IndexError: arrays used as indices must be of integer (or boolean) type

how to get ride of this error any suggestions thanks in regards

A: You found no peaks.
That is, len(peak_locs) is zero.
So you wind up with this array, whose type defaulted to float:
>>> np.array(peak_locs)
array([], dtype=float64)

To fix it?
Find more peaks!


text:
Q: CSS Fixed position property giving troubles I have the following div that I want to remain fixed at the top of the window:

  |
       |
       |

I was able to style the above 2 divs successfully, but when I try to add
.head{
 position:fixed;
 }

the div is thrown downwards, leaving quite some space above it.
I tried removing all the margin:top instances but that didn't help. What could be wrong?

A: You have to set a position too, so:
position: fixed; left: 0; top: 0;


text:
Q: Create duplicate buttons using Jquery live event Jquery live is calling in order to duplicate buttons. However this code doesnt give me expected output. Can someone help me to understand what's the wrong here. Im using Jquery version 1.10.2
//HTML
<body>

<input class="duplicate" type="button" value="Click" />

<script type="text/javascript" src="js/jquery-1.10.2.min.js"></script>
<script type="text/javascript" src="js/ext.js"></script>

</body>

//JQuery
$(document).ready(function(){
    $('.duplicate').live({
        click: function(){
            alert('you have clicked');
            $(this).after('<input class="duplicate" type="button" value="Click"/>');
        }
    });
});

A: First off, don't use live(), it's deprecated. Instead use the on()-method, and delegate the event to the .duplicate-element within a container.
Second you can use .clone() to make a copy of the element instead of typing all that markup again.
 $('.container').on('click', '.duplicate', function(e) {
    var $this = $(this),
        clone = $this.clone();

    $this.after(clone);

    e.preventDefault();
 });

fiddle: http://jsfiddle.net/W7ty8/2/


text:
Q: Exchanging the internal letters of words How can you implement the "old" trick of scrambling the internal letters of words?
For those of you who don't know it Wikipedia describes it well.
As mentioned in the comment to this question this has had some research into the "research" originally mentioned in the earliest form of this meme.

A: I implemented this in "one" line of VB:
Dim outText = Regex.Replace(inText, _
        "\b([a-zA-z])([a-zA-Z]+)([a-zA-Z])\b", _
        Function(g) (g.Groups(1).Value & String.Join("", _
            (g.Groups(2).Value.ToCharArray.OrderBy( _
                            Function(c) (Rnd(1))) _
                            )) & _
            g.Groups(3).Value))

A better solution would provide a 'more correct' Function for OrderBy that would return the same value for a particular character in a string, but in this case, simply setting the Rnd seed would do to get (somewhat) repeatable results.
(Note that setting the Function to be directly dependent upon the c provided means all internal characters are reordered according to some random ordering, so all internal repeated letters are always grouped together in the scrambled words.)
An example of the output:

(Note that sttenig the Fictunon to be drcteily dpeednent uopn
   the c previodd mnaes all inratnel cthcearras are roeerredd
   aindorccg to smoe ronadm oidrreng, so all ietnnarl reteaepd
   ltteers are awayls guorped tgtheoer in the srlmceabd wodrs.)

A: Answer by Mark Hurd is flawed. Even with the problem with duplicate letters corrected, the use of the sort algorithm does not yield a valid result.
// See http://okmij.org/ftp/Haskell/perfect-shuffle.txt
Here is my attempt, using recursion. Very simple and easy to understand, but performance could be improved. Obviously it does not use regex, vb.net or linq (see tags). I leave that to the reader.
Random _rng = new Random();

string Scramble(string text) {
  return String.Concat(text[0], Shuffle3(text.Substring(1, text.Length - 2)), text[text.Length - 1]);
}

string Shuffle3(string text) {
  return ShuffleStep(text, _rng.Next(text.Length));
}

string ShuffleStep(string text, int i) {
  return (text.Length == 1) ? text : text[i] + ShuffleStep(text.Remove(i, 1), _rng.Next(text.Length-1));
}


text:
Q: WP 8.1 MVVM light cannot instantiate constructor I have implemented the navigation service and the view model locator. I can open  my page using OnNavigatedTo correctly. But when the page initializes, it does not go through any of the constructors declared.
My implementation of the locator
INavigationService navigationService = new NavigationService();
navigationService.Configure("About", typeof(AboutPage));
return navigationService;

ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);
INavigationService navigationService = CreateNavigationService();
SimpleIoc.Default.Register<INavigationService>(() => navigationService);
SimpleIoc.Default.Register<MainViewModel>();

The constructor on my Page
public MainViewModel(INavigationService navigationService)
{
    _navigationService = navigationService;
}

Any hints?

A: Instead of passing it as argument of your constructor, you can use the following to retrieve the navigation service:
public MainViewModel()
{
    _navigationService = ServiceLocator.Current.GetInstance<INavigationService>();
}

The action of registering does not create any instance yet; the instantiation is on demand.
You can find details on the MVVM Light IOC class in this MSDN article:
https://msdn.microsoft.com/fr-fr/magazine/jj991965.aspx


text:
Q: How to build index in a single groovy script? When I have updated my janus graph schema, I have created a property key but forgot to build the index.If I run same piece of code with this buildIndex of that property then my data will get redundant data. So I am trying to build the index directly in the gremlin console.
What I have tried is
    :remote connect tinkerpop.server conf/remote.yaml
    // myScript = new File('/tmp/scripts/dbscripts/campaignTypeSchema/01_campaignTypeSchema.groovy').getText('UTF-8')
    // :> @myScript
    :> m = graph.openManagement()

    /** Getting Vertex Labels **/
    :> Campaign = m.getVertexLabel('Campaign')

    /** Vertex Properties creation **/
    :> campaignType = graph.openManagement().getPropertyKey('campaignType')

    /** Vertex supporting indexes **/
    :> graph.openManagement().buildIndex('campaignTypeByCampaign', Vertex.class).addKey(graph.openManagement().getPropertyKey('campaignType')).buildCompositeIndex()
    println "Finished updating schema"
    :remote close
    :x

But endedup with an error
    Error in /tmp/scripts/dbscripts/campaignTypeSchema/run.groovy at [9: :> Campaign = m.getVertexLabel('Campaign')] - No such property: m for class: Script36
    org.apache.tinkerpop.gremlin.jsr223.console.RemoteException: No such property: m for class: Script36
    at org.apache.tinkerpop.gremlin.console.jsr223.DriverRemoteAcceptor.submit(DriverRemoteAcceptor.java:178)
    at org.apache.tinkerpop.gremlin.console.commands.SubmitCommand.execute(SubmitCommand.groovy:41)
    at org.codehaus.groovy.tools.shell.Shell.execute(Shell.groovy:104)
    at org.codehaus.groovy.tools.shell.Groovysh.super$2$execute(Groovysh.groovy)
    at sun.reflect.GeneratedMethodAccessor15.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:98)
    at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:325)
    at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1225)
    at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.invokeMethodOnSuperN(ScriptBytecodeAdapter.java:145)
    at org.codehaus.groovy.tools.shell.Groovysh.executeCommand(Groovysh.groovy:273)
    at org.codehaus.groovy.tools.shell.Groovysh.execute(Groovysh.groovy:164)
    at org.apache.tinkerpop.gremlin.console.GremlinGroovysh.super$3$execute(GremlinGroovysh.groovy)
    at sun.reflect.GeneratedMethodAccessor14.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:98)
    at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:325)
    at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1225)
    at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.invokeMethodOnSuperN(ScriptBytecodeAdapter.java:145)
    at org.apache.tinkerpop.gremlin.console.GremlinGroovysh.execute(GremlinGroovysh.groovy:72)
    at org.apache.tinkerpop.gremlin.console.Console$_executeInShell_closure16.doCall(Console.groovy:371)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:98)
    at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:325)
    at org.codehaus.groovy.runtime.metaclass.ClosureMetaClass.invokeMethod(ClosureMetaClass.java:264)
    at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1034)
    at groovy.lang.Closure.call(Closure.java:418)
    at org.codehaus.groovy.runtime.DefaultGroovyMethods.eachWithIndex(DefaultGroovyMethods.java:2041)
    at org.codehaus.groovy.runtime.DefaultGroovyMethods.eachWithIndex(DefaultGroovyMethods.java:2021)
    at org.codehaus.groovy.runtime.DefaultGroovyMethods.eachWithIndex(DefaultGroovyMethods.java:2071)
    at org.codehaus.groovy.runtime.dgm$175.doMethodInvoke(Unknown Source)
    at org.codehaus.groovy.vmplugin.v7.IndyInterface.selectMethod(IndyInterface.java:236)
    at org.apache.tinkerpop.gremlin.console.Console.executeInShell(Console.groovy:348)
    at org.codehaus.groovy.vmplugin.v7.IndyInterface.selectMethod(IndyInterface.java:236)
    at org.apache.tinkerpop.gremlin.console.Console.<init>(Console.groovy:141)
    at org.codehaus.groovy.vmplugin.v7.IndyInterface.selectMethod(IndyInterface.java:236)
    at org.apache.tinkerpop.gremlin.console.Console.main(Console.groovy:453)

Then I have tried running directly in gremlin console
    gremlin> :> graph.openManagement().buildIndex('campaignTypeByCampaign', Vertex.class).addKey(graph.openManagement().getPropertyKey('campaignType')).buildCompositeIndex()

For this I got an error saying
    The vertex or type is not associated with this transaction [campaignType]

A: You need to create your remote connection as a session:
:remote connect tinkerpop.server conf/remote.yaml session

as described here or else variable state won't be persisted between commands.


text:
Q: Laravel change filesystem disks path on run time I am aware of the filesystems.php to create disks and I'm currently using it, having ~~ 20 disks configured.
I have a new problem with these, I'm currently trying to prefix to every disk, a string. The problem is that the paths are being saved when the php artisan config:cache is run but I need to change them on run time, as n example, for User Sergio it would need to append Sergio/ to the following disk for example:
//filesystems.php
'random' => [
   'driver' => 'local',
   'root' => storage_path('app/random'),
],

Then
Storage::disk("random")->getDriver()->getAdapter()->getPathPrefix();
//outputs /var/www/html/project/storage/app/random

and the goal is setting configurations in for example the middleware i'm currently setting the tentant database already like this
//Middleware
Config::set('database.connections.tenant.database', "Sergio");
DB::reconnect('tenant');

I can currently set the paths correctly with
Config::set('filesystems.disks.random.root',storage_path('app/Sergio/random'));

But i'm worried since that if before that line I try to reach to the path, the storage saves the initial path in memory instead of re-fetching it after it is altered.
For example. doing this without any middleware.
$fullPath1 = Storage::disk("random")->getDriver()->getAdapter()->getPathPrefix();

Config::set('filesystems.disks.random.root',storage_path('app/Sergio/random'));

$fullPath2 = Storage::disk("random")->getDriver()->getAdapter()->getPathPrefix();

What was intended to happen is that $fullPath1 would output the initial path which is /var/www/html/project/storage/app/random and then $fullPath2 would output /var/www/html/project/storage/app/Sergio/random
Is there any way of letting the Storage know that I've changed the disks local paths?

A: How about adding a new config instead of updating the already loaded one, something like this:
private function addNewDisk(string $diskName)
{
      config(['filesystems.disk.' . $diskName => [
          'driver' => 'local',
          'root' => storage_path('app/' . $diskName),
      ]]);
}

and prior to using the Storage facade, call above method that way the config will be updated and when you use new disk, it will try to resolve again based on updated config.
{
....
    $this->addNewDisk('new_random');
    Storage::disk('new_random')->get('abc.txt'); // or any another method
...

}


text:
Q: Ninject 3 InRequestScope not returning the same instance for the same request Recently, I upgraded one of my MVC3 projects from Ninject 2 to Ninject 3.
After a couple of minutes trying to find why InRequestScope was not anymore available, I found that this is now an extension of Ninject.Web.Common.
Now, when I try to run the application, Ninject works like if all types binded with a scope InRequest would be InTransientScope; a new instance was created each time.
In my class that inherits from NinjectModule, I have a simple bind like that:
Bind<ViewModel.Activity>().ToSelf().InRequestScope();

In my controller, I have 2 properties of the type ViewModel.Activity marked with Ninject attribute.
  [Inject]
  public ViewModel.Activity Activity { get; set; }

  [Inject]
  public ViewModel.Activity Activity1 { get; set; }

If I looked in debug mode the value of the HashCode of both the two properties, there all have different value but HttpContext is the same; I'm in the same request.
What I missed about how to use correctly the new Ninject.Web.Common.InRequestScope with the new version of Ninject 3?
Thank you very much.

A: Ninject.Web.Common can't be used standalone. You must use some additional web or wcf extension or implement InRequestScope yourself.

A: Added as an answer so this can be closed out
Don't use a custom factory. Just install Ninject.MVC3 and copy your bindings over to the NinjectWebCommon.cs file, then delete all your old code.


text:
Q: Probability that a randomly picked object is broken and it was made by machine #3 Three machines S1, S2, S3 are producing products with a ratio of 60:30:10. Machine S1 makes 2%, S2 makes 3% and S3 makes 4% of broken items. What is the probability that a randomly picked items is broken and it was made by machine S3?
My idea is to find the probability that a object picket at random was made by machine S3 and then find the probability that that item is broken and multiply those probabilites. Is this correct?
It would be 0.1*0.04 = 0.004
Second question: what is the probability that if a randomly picked object that is broken is made by machine S3. This one sounds the same as the first. I think this one is solved by finding the number of broken items made by machine S3 and dividing it by total number of broken items.
So like this 25/4 = 0.16

A: Correct.
Let $B$ be the event of an item being broken, and $S_1,S_2,S_3$ the events of the items coming from those machines.
So, yes, $\mathsf P(B\cap S_3)$ $= \mathsf P(B\mid S_3)\mathsf P(S_3)\\=(0.04)\cdot(0.10)\\=0.004$
Then you seek $\mathsf P(S_3\mid B)$ $= \mathsf P(B\mid S_3)\mathsf P(S_3)\div\left(\sum_{k=1}^3\mathsf P(B\mid S_k)\mathsf P(S_k)\right)\\=(4\cdot 1)\div(2\cdot 6+3\cdot 3+4\cdot 1)\\=4/25$


text:
Q: onmousemouve work but hover effetc and click doesn't work in reatcjs app i working on my project and  i would like to do the mouse effect like on this wordpress template, http://preview.themeforest.net/item/consultio-consulting-business-wordpress/full_screen_preview/25376496?_ga=2.61545708.1311804999.1617452015-579954703.1617357573
But in my projetc i have that :

let circle = document.getElementById("ct-mouse-move");

const onMouseMove = (e) =>{
    circle.style.left = e.pageX + "px";
    circle.style.top = e.pageY + "px";
};
document.addEventListener("mousemove", onMouseMove)
#ct-mouse-move {
    position: fixed;
    z-index: 9999;
}

#ct-mouse-move .circle-cursor--outer {
    width: 30px;
    height: 30px;
    border: 1px solid rgba(14, 128, 246, 0.5);
    -webkit-border-radius: 30px;
    -khtml-border-radius: 30px;
    -moz-border-radius: 30px;
    -ms-border-radius: 30px;
    -o-border-radius: 30px;
    border-radius: 30px;
    margin-top: -17px;
    margin-left: -16px;
    -webkit-transition: all 50ms linear 0ms;
    -khtml-transition: all 50ms linear 0ms;
    -moz-transition: all 50ms linear 0ms;
    -ms-transition: all 50ms linear 0ms;
    -o-transition: all 50ms linear 0ms;
    transition: all 50ms linear 0ms;
}

#ct-mouse-move .circle-cursor--inner {
    width: 6px;
    height: 6px;
    background-color: #0e80f6;
    -webkit-border-radius: 6px;
    -khtml-border-radius: 6px;
    -moz-border-radius: 6px;
    -ms-border-radius: 6px;
    -o-border-radius: 6px;
    border-radius: 6px;
    margin-top: -18px;
    margin-left: -4px;
}

so the onmousemouve work but de hover effect and click action doesn't work
how can i solve my problem ?

A: Okay can you explain me a bit more cause I don't see react anywhere here and if you're doing this in react it's way too wrong and you should consider reading documentation.


text:
Q: Plone: How to sort folder items I have a folder called myfolder, that has some items inside, like: item1, item2, item3, and etc.
When I added the portlet Navigation to the left column of the page, and entered on the folder myfolder, it showed me the links on the portlet like this:

*

*item1

*item2

*item3

I want that the Navigation portlet shows me links on this exact sort:

*

*item2

*item1

*item3

I know that I can go on the Content tab of myfolderenter code here, and drag each item to the position that I want.
But using this way, if I reinstall all my product on a new Plone Site, I lost my configuration. So I want to have this navigation order configured on my product, instead of only on a installed plone site, so that this change stays forever.
How can I do that?

A: Solved: I could solve this by doing under the installation of the product:
#file: Extensions/Install.py
def install(portal):

    #...another steps from install

    portal = getToolByName(portal, 'portal_url')
    portal = portal.getPortalObject()

    portal.moveObjectsToTop(['item2', 'item1', 'item3', ])
    portal.plone_utils.reindexOnReorder(portal)

Just this.


text:
Q: How to get rid of ' characters in JSON Serialization? I want to serialize an object using Jackson.
Here's the json :
[
    {
        "texte": "Quel sont les trois grands principes de la POO ?",
        "topic": "Java",
        "reponses": [
            {
                "texte": "L\\'encapsulation, l\\'héritage et le polymorphisme.",
                "isTrue": true
            },
            {
                "texte": "L\\'encapsulation, l\\'héritage multiple et le polymorphisme.",
                "isTrue": false
            },
            {
                "texte": "Le multi-threading, l\\'accès aux données et le polymorphisme.",
                "isTrue": false
            }
        ]
    },
    {
        "texte": "Quel interface implémente la classe ArrayList ?",
        "topic": "Java",
        "reponses": [
            {
                "texte": "List",
                "isTrue": true
            },
            {
                "texte": "Queue",
                "isTrue": false
            },
            {
                "texte": "Serializable",
                "isTrue": false
            }
        ]
    }
]

Here's the Java code :
public static void main(String[] args) throws IOException {
        FileReader reader = new FileReader();
        File jsonFile = reader.getFile("questions/datas.json");

        ObjectMapper mapper = new ObjectMapper();

        List<Question> questions = mapper.reader()
                  .forType(new TypeReference<List<Question>>() {})
                  .readValue(jsonFile);

        System.out.println(questions);

    }

Finally I have this error :

Invalid UTF-8 middle byte 0x72 at [Source:
C:\Users\josselin.douineau\projects\quizz-java-generator\target\classes\questions\datas.json;
line: 7, column: 41] (through reference chain:
java.util.ArrayList[0]->com.douineau.entity.Question["reponses"]->java.util.ArrayList[0]-com.douineau.entity.Reponse["texte"])

Does anybody know what is it about ?
I'm not coming from the IT, so I'm not very good to understand this type of message.

A: Error is caused by escape character \\' in l\\'héritage et. you can configure object mapper to allow escape characters.
ObjectMapper mapper = new ObjectMapper();
mapper.configure(JsonParser.Feature.ALLOW_BACKSLASH_ESCAPING_ANY_CHARACTER, true);


text:
Q: Google App Engine local instance started from Eclipse does not stop I recently started building applications on Google App Engine. I use an Eclipse plugin to start and stop the server and deploy applications to run on Google App Engine.
I had created a new project and tried to stop and start it as suggested in the tutorials and in Stack Overflow. My old project is still running and hitting the data source successfully. I even removed the old projects from my Eclipse workspace and tried a fresh deploy of the new project with no luck.
How do I stop the server (the RED dot in my Eclipse has no effect)? Is uninstalling the App Engine the only solution?

A: When you launch the server, a new Java process is started.  You can find and kill it independently of Eclipse.

A: I too ran into this problem and found the solution at Stop or restart a previously started Google App Engine local server in Eclipse
Just in case the link breaks, the key steps are:

*

*In Eclipse, find the Eclipse Console view (looks like below).

*Select the arrow next to the small computer and find the server's name

*Select the red square to stop the server

*Go to http://localhost:8888 to see if the page is still showing (it shouldn't be)

*If you are visiting something like http://yourAppId.appspot.com and the server is still running, that's because it's still deployed on App Engine, not locally. In this case, go to Google Developer's Console and stop the service there

A: The server can be stopped by clicking red square icon in the console window. If this icon is missing or disabled, you may see wrong console window. You must select the javaw console using the drop-down button on the far right of the console window.

A: Go to Run/Debug Configurations -> Select your project configuration -> Common tab -> Uncheck "Launch in background"
Now, when you terminate the server on Server's console, it will stops the server.


text:
Q: How to prevent function to double animation In my plugin I handle animations by passing methods in external functions.
Firstly I have to check if the sidebars exists:
var left  = cfg.left.selector,
    right = cft.right.selector;

function Sidebar( e ) {
        if ( e == undefined ) {
            console.log( "WARNING: A (or more) sidebar(s) has been left behind" );
        } else {
            var align, sbw, marginA, marginB, $sbRight, $sbLeft,
                $sidebar = $( e );

Once I'm sure that the sidebars (or maybe just one ) exists I define the variables I need to animate all elements:
            switch ( e == cfg.right.selector ) {
                case true:
                    align    = "right";
                    marginA  = "margin-right";
                    marginB  = "margin-left";
                    $sbRight = $( cfg.right.selector );
                    break;
                case false:
                    align    = "left";
                    marginA  = "margin-left";
                    marginB  = "margin-right";
                    $sbLeft  = $( cfg.left.selector );
                    break;
            }

        var def       = cfg[align], //new path to options
            $opener   = $( def.opener ),
            sbMaxW    = def.width,
            gap       = def.gap,
            winMaxW   = sbMaxW + gap,
            $elements = //a very long selector,
            w         = $( window ).width();

        //defining sbw variable
        if ( w < winMaxW ) {
            sbw = w - gap;
        } else {
            sbw = sbMaxW;
        }

        //setting $sidebar initial position and style
        var initialPosition = {
            width: sbw,
            zIndex: cfg.zIndex
        };
        initialPosition[marginA] = -sbw;
        $sidebar.css( initialPosition );

And here are the animations. They are handled as external functions. The first animation works really good. It does its job:
        //Animate $elements to open the $sidebar
        var animateStart = function() {
            var ssbw = $sidebar.width();
                animation = {};

            animation[marginA] = '+=' + ssbw;
            animation[marginB] = '-=' + ssbw;

            $elements.each(function() {
                $( this ).animate( animation, {
                    duration: duration,
                    easing: easing,
                    complete: function() {
                        $( 'body, html' ).attr( 'data-' + dataName, 'overflow' );
                        maskDiv.fadeIn();
                    }
                });
            });
        },

but the second one is doubled when two sidebars exist!! I need to retrieve the .wrapper offset and then move $elements according to its value. So I thought that it works as in the first animation function, and that it would be as simple as there:
            animationReset = function() {
                var offset = $wrapper.offset().left;
                    reset = {};

                console.log( offset );

Console returns two time the value so the animation in doubled.
                reset[marginA] = '-=' + offset;
                reset[marginB] = '+=' + offset;

                $elements.each(function() {
                    $( this ).animate( reset, {
                        duration: duration,
                        easing: easing,
                        complete: function() {
                            maskDiv.fadeOut(function() {
                                $( 'body, html' ).removeAttr( 'data-' + dataName );
                            });
                        }
                    });
                });
            };

So now I run the animations on click functions.
        $( $opener ).click( animateStart );
        maskDiv.click( animationReset );

    }
}

And finally I pass the values running the main function two times.
Sidebar( left );
Sidebar( right );

Why it worked on the first animation and then it is doubled in the second animation?
DEMO: http://dcdeiv.github.io/amazing-sidebar/
FULL CODE: https://github.com/dcdeiv/amazing-sidebar/blob/master/development/jquery.amazingsidebar.js

A: I think the problem is that you are adding two times the click event at
maskDiv.click( animationReset );

since maskDiv is the main div of the website and there is only one, but the looping is doing it twice.
Try to take that out of the loops definitions and do it only once, but maybe it is difficult because it is defined inside the Sidebar function, so you can try to create a global variable at the top and, after the first click event is added, not add any more:
At the top:
var notAdded = true;

In the sidebar function:
$( $opener ).click( animateStart );
if(notAdded){
    maskDiv.click( animationReset );
    notAdded = false;
}

Hope it helps!

A: Here is the cause :
var maskDiv = $( 'body' ).children().filter(function(){
                return $( this ).data( dataName ) === 'mask' ;
            });

and
 maskDiv.click( animationReset );

You have two data-named 'mask' elements on the body.
So the click action is setup on both when you call the Sidebar function.
As you call it twice, you got the reset action run twice ...

EDIT : I was wrong : you have only one mask, but as it is used by both sidebars, you still have a double setup on it.


text:
Q: Nested get or create functionality - DRF There have been some posts about nested create functionalities however none seem to have helped me out.
You can see here what my json post request looks like:
{
  "games": [
    {
      "company": {
        "name": "Google",
        "website": "https://google.com",
        "trustedpilot": "5"
      },
      "genres": [],
      "formats": [],
      "platforms": [],
      "title": "Call of duty modern warfare",
      "cover": "https::cover.jpg",
      "link": "https://google.com",
      "prev_price": "60.00",
      "price": "40.00"
    }
  ],
  "company": {
    "name": "Google",
    "website": "https://google.com",
    "trustedpilot": "5"
  },
  "name": "Bundle name",
  "prev_price": "50.00",
  "price": "20.00"
}

The game serializer seems the work fine when creating a single game:
class GameSerializer(serializers.HyperlinkedModelSerializer):
    company = CompanySerializer(many=False)
    genres = GenreSerializer(many=True)
    formats = FormatSerializer(many=True)
    platforms = PlatformSerializer(many=True)

    class Meta:
        model = Game
        fields = '__all__'

    def create(self, validated_data):
        # Many to one
        company_data = validated_data.pop('company')
        # Many to Many
        genres_data = validated_data.pop('genres')
        formats_data = validated_data.pop('formats')
        platforms_data = validated_data.pop('platforms')

        # Company
        company, created = Company.objects.get_or_create(**company_data)

        # Get the game or created a new one if it doesn't exist yet
        game, created = Game.objects.get_or_create(**validated_data, company=company)

        # Platform
        for platform_data in platforms_data:
            platform, create = Platform.objects.get_or_create(**platform_data)
            game.platforms.add(platform)

        # Format
        for format_data in formats_data:
            format, create = Format.objects.get_or_create(**format_data)
            game.formats.add(format)

        # Genre
        for genre_data in genres_data:
            genre, create = Genre.objects.get_or_create(**genre_data)
            game.genres.add(genre)
        return game

This is the current bundle serializer:
class BundleSerializer(serializers.HyperlinkedModelSerializer):
    games = GameSerializer(many=True)
    company = CompanySerializer(many=False)

    class Meta:
        model = Bundle
        fields = '__all__'

    def create(self, validated_data):
        # Many to one
        company_data = validated_data.pop('company')
        # Many to Many
        games_data = validated_data.pop('games')
        # Company
        company, created = Company.objects.get_or_create(**company_data)

        # Bundle
        bundle, created = Bundle.objects.get_or_create(**validated_data, company=company)

        # Games
        for game_data in games_data:
            company2 = game_data.pop('company')
            company3, created = Company.objects.get_or_create(**company2)

            game, created = Game.objects.get_or_create(**game_data, company=company3)
            bundle.games.add(game)

        return bundle

In the region: Games (inside BundleSerializer) I get the following error:

TypeError at /bundles/ int() argument must be a string, a bytes-like
  object or a number, not 'list'

This is what what I already tried:
for game_data in games_data:
    # first attempt
    game, created = Game.objects.get_or_create(**game_data)
    # second attempt
    company = game_data.pop('company')
    game, created = Game.objects.get_or_create(**game_data, company=company)
    bundle.games.add(game)

The error seems to come from:
game, created = Game.objects.get_or_create(**game_data, company=company)

Any suggestions? (extra question: does Game.objects.create go to the serializers create method?)
Edited
urls
router = DefaultRouter()
router.register(r'users', views.UserViewSet, 'user')
router.register(r'games', views.GameViewSet, 'game')
router.register(r'genres', views.GenreViewSet, 'genre')
router.register(r'formats', views.FormatViewSet, 'format')
router.register(r'platforms', views.PlatformViewSet, 'platform')
router.register(r'bundles', views.BundleViewSet, 'bundle')
router.register(r'companies', views.CompanyViewSet, 'company')

urlpatterns = [
    path('', include(router.urls)),
]

views
class GameViewSet(viewsets.ModelViewSet):
    queryset = Game.objects.all()
    serializer_class = GameSerializer

class BundleViewSet(viewsets.ModelViewSet):
    queryset = Bundle.objects.all()
    serializer_class = BundleSerializer


text:
Q: Attach commands to TreeView in wpf using prism How do I use a DelegateCommand in a TreeView to get the Expanded event?
Should I be using the DelegateCommand or is there another way?
Thanks

A: Since you are mentioning Prism, I assume you have a controller or ViewModel attached to the view containing your TreeView...
That being the case, expose a boolean property IsExpanded
    private bool _isExpanded;
    public bool IsExpanded
    {
        get { return _isExpanded; }
        set
        {
            if (value != _isExpanded)
            {
                _isExpanded = value;
                RaisePropertyChanged("IsExpanded");
                //  Apply custom logic here...
            }
        }
    }

Now to hook this property up to the TreeView, you need to apply the following style in the TreeView's resources (or further up the Visual tree as appropriate)
<Style TargetType="{x:Type TreeViewItem}">
    <Setter Property="IsExpanded" Value="{Binding Path=IsExpanded, Mode=TwoWay}" />
</Style>

NB: You can also use a similar technique to hook up the IsSelected property - also very useful!!


text:
Q: Can I use Zend Modules to "white label" my Zend Application I work on this Facebook application that has to be "white labeled" for different "brands".
The "white labeled" version will use the same domain and the same DB as the current one. The layout and styling of the pages will change, but the most part of the business logic will be common between the "white labeled" and the current application.
I thought that a smart way to do that would be to make a Zend Module of my current application, and to make another module for the white labeled application. This second module would "inherit" from the first one, so I won't have to duplicate the whole code. The logic specific to "white labeled" will be coded in the second module, and global features in the first one.
But from what a read about modules, the global feeling is that they must correspond to independent features, that's why I'm thinking my approach is not good...
What do you think of it and, more generally, what do you think is the good approach to white label a Zend Application ?

A: Perhaps the easiest way for you to create a white label for this application is to provide a different layout on the same module.
It would be important to keep all urls relative, including any related to theme information (css, js, images).


text:
Q: C++ template code resulting in error with delete being called on an object that apparently wasn't properly allocated I am teaching myself c++ templates. I wrote the following code, and I am getting a weird error about a pointer being freed that wasn't allocated. I am guessing that something in my class template constructor isn't actually calling new on the int when I ask for an <int> type of this class. The code is being compiled and run automatically by CodeRunner for mac which I set up to use the clang++ compiler for c++ files.
#include <vector>
#include <iostream>

template <typename T>
class HeapVal
{
    public:
        HeapVal(T val) {ptr = new T(val);}
        ~HeapVal() {delete ptr;}
        T get() {return *ptr;}
    private:
        T* ptr;
};

int main(){
  std::vector< ::HeapVal<int> > vec;
  for(int i = 0; i < 1000; ++i){
    ::HeapVal<int> h(i);
    vec.push_back(h);
  }
  for(int i = 0; i < 1000; ++i){
    std::cout << vec[i].get() << std::endl;
  }
  return( 0 );
}

That code results in the following error either during compilation or execution (looks to me like a run-time kind of error).
Untitled(30214) malloc: *** error for object 0x7f82f24007c0: pointer being freed was not allocated
*** set a breakpoint in malloc_error_break to debug
Run Command: line 1: 30214 Abort trap: 6           ./"$2" "${@:3}"

A: You're missing a copy constructor and assignment operator for HeapVal. The implication of that is that you'll ultimately end up trying to delete the same memory more than once, because you have multiple pointers to it - that's what causes the crash.
Try something like this:
template <typename T>
class HeapVal
{
public:
    explicit HeapVal(T val)
    :   ptr(new T(val))
    {}

    ~HeapVal()
    {
        delete ptr;
    }

    HeapVal(const HeapVal& rhs)
    :   ptr(new T(*rhs.ptr))
    {}

    HeapVal& operator=(const HeapVal& rhs)
    {
        HeapVal(rhs).swap(*this);
        return *this;
    }

    T get() const
    {
        return *ptr;
    }

private:
    T* ptr;

    void swap(HeapVal& rhs)
    {
        std::swap(ptr, rhs.ptr);
    }
};

A: Anytime a HeapVal is copied (or assigned, for that matter) you'll end up with two HeapVal objects, both containing pointers to the same place. When the first of those is destroyed, it'll delete the pointed-to object. When the second is destroyed, it'll try to delete the same object again -- leading to undefined behavior.
In your case, you were fortunate enough that the run-time library detected and reported the problem.
Googling for "C++ law of the big three" or something similar should yield quite a bit of discussion on the subject.

A: The problem is when u push the HeapVal object you end up doing a shallow copy of the ptr so this is prone to double delete.
You need to override the default copy constructor and assignment operator or you could use smart pointers instead of raw ptr . Boost::shared_ptr maybe an overkill in your case but its something good to learn.