text:
Q: Regular expression to find and replace hyphened class name with a fixed suffix. I have this type of divs which similar class , now I wanted to replace all the class with "-type" at the end with regular expression. I have tried this so far http://regexr.com/3b7q3.
<div class="form-group form-row @styleProperty username-v-type" data-type="@templateName" data-prop="@styleProperty" data-is-validate="@isValidate">

</div>

A: Its better to do it by parsing HTML. But you can use this regex instead:
 /\b[\w\S]+-type/g

Demo


text:
Q: Why the return executes before the item is created and the console.log awaits and shows the correct id? I'm using node.js, express, and pnp (sharepoint) to insert a list item, the problem is that the id returned to console.log is correct but when i try to send back the id created it goes empty. how come thhe console.log awaits for the code and the return doesnt?
here is my code:
app.use(express.json());

//Método inserir emergencia
app.post('/inserirEmergencia', function(req, res){
    var retorno = inserirEmergencia(req);
    return res.json(retorno);
});

app.listen(3001);

async function inserirEmergencia(req) {

var retornoItemAdd;

const listAdd = await sp.web.lists.getByTitle("Emergências").items.add({
        Descricao: req.body.Descricao,
        NomeId: req.body.NomeId,
        DataEmergencia: req.body.DataEmergencia,
        TipoEmergenciaId: req.body.TipoEmergenciaId,
        SubtipoEmergenciaId: req.body.SubtipoEmergenciaId,
        Email: req.body.Email,
        Telefone: req.body.Telefone,
        LocalSetorEndereco: req.body.LocalSetorEndereco,
        Estado: req.body.Estado,
        Municipio: req.body.Municipio
    }).then((iar) => {
            console.log(iar); //waits for the creation
            return iar; //executes without waiting

    }).catch((err) => {
            retornoItemAdd = err;
            console.log(err);
            return err;
        });
  }

I update the code to:
so, thanks for the reply, i edited and removed the then..but still the same thing happens..
async function inserirEmergencia(req) {

    const listAdd = await sp.web.lists.getByTitle("Emergências").items.add({
        Descricao: req.body.Descricao,
        NomeId: req.body.NomeId,
        DataEmergencia: req.body.DataEmergencia,
        TipoEmergenciaId: req.body.TipoEmergenciaId,
        SubtipoEmergenciaId: req.body.SubtipoEmergenciaId,
        Email: req.body.Email,
        Telefone: req.body.Telefone,
        LocalSetorEndereco: req.body.LocalSetorEndereco,
        Estado: req.body.Estado,
        Municipio: req.body.Municipio
    });

    console.log(listAdd);
    return listAdd;

}

A: You should remove the call of function then and modify your approach and leave only await operators.
app.use(express.json());

//Método inserir emergencia
app.post('/inserirEmergencia', async function(req, res) {
  try {
    var retorno = await inserirEmergencia(req);
    return res.json(retorno);
  } catch (e) {
    //Error handling
  }
});

app.listen(3001);

async function inserirEmergencia(req) {
  const listAdd = await sp.web.lists.getByTitle("Emergências").items.add({
    Descricao: req.body.Descricao,
    NomeId: req.body.NomeId,
    DataEmergencia: req.body.DataEmergencia,
    TipoEmergenciaId: req.body.TipoEmergenciaId,
    SubtipoEmergenciaId: req.body.SubtipoEmergenciaId,
    Email: req.body.Email,
    Telefone: req.body.Telefone,
    LocalSetorEndereco: req.body.LocalSetorEndereco,
    Estado: req.body.Estado,
    Municipio: req.body.Municipio
  });

  return listAdd;
}

A: Finally, the code works.
it goes like this..
//Método inserir emergencia
app.post('/inserirEmergencia', function(req, res){
    let retorno = inserirEmergencia(req).then(
      iar => {
        console.log(iar);
        res.json(iar);
      }
    );
  });

app.listen(3001);

async function inserirEmergencia(req) {

    const listAdd = await sp.web.lists.getByTitle("Emergências").items.add({
        Descricao: req.body.Descricao,
        NomeId: req.body.NomeId,
        DataEmergencia: req.body.DataEmergencia,
        TipoEmergenciaId: req.body.TipoEmergenciaId,
        SubtipoEmergenciaId: req.body.SubtipoEmergenciaId,
        Email: req.body.Email,
        Telefone: req.body.Telefone,
        LocalSetorEndereco: req.body.LocalSetorEndereco,
        Estado: req.body.Estado,
        Municipio: req.body.Municipio
    });

    console.log(listAdd);
    return listAdd;

}

A: try it like that:
//Método inserir emergencia
app.post('/inserirEmergencia', function(req, res){
  let retorno = inserirEmergencia(req).then(
    iar => {
      console.log(iar);
      res.json(iar);
    }
  );
});

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why is my iMac (late 2013) HDD so slow? My iMac's hard disk has been slow from the start. But recently it is becoming unbearable. Disk read and write speeds are consistently below 50 MB per second, without any applications producing any CPU load.
I do see that mds uses lots of disk I/O. Could this be the problem? If so, what can I do to alleviate it? I tried turning off the indexing with sudo mdutil -a -i off, but it did not help much.
How else can I debug this?

A: To finish this question: I had opened a bug report with Apple. They determined that a botched Aperture photo library migration lead to excessive disk I/O. In the end, I reformatted the whole Mac. Plus to make the machine more useable, I attached a 256 GB Thunderbolt SSD and created a FusionDrive, as per this blog (in german). There are lots of howtos explaining how to create a FusionDrive. This really gave the machine an incredible performance boost.


text:
Q: spark.write.synapsesql options with Azure Synapse Spark Pool Within Azure Synapse, I am using the synapsesql function with the Scala language within a Spark Pool notebook to push the contents of a data frame into the SQL Pool
// Write data frame to sql table
df2.write.
option(Constants.SERVER,s"${pServerName}.sql.azuresynapse.net").
synapsesql(s"${pDatabaseName}.xtr.${pTableName}",Constants.INTERNAL)

This works successfully, however I would like to add some extra functionality

*

*How do I specify the index type to be HEAP instead of Clustered Column store Index. In Data Bricks it can be done through .option("tableOptions","heap,distribution=ROUND-ROBIN") however this doesn't work in the Spark Pool notebook.

*How do I overwrite the table in the SQL Pool if it already exists?
In Data Bricks you have SaveAsTable but I can't find anything similar in the Spark pool notebook.

A: Anyways, as per this official document,

When a table is created, by default the data structure has no indexes
and is called a heap.

To use the HEAP type index, while creating the table simply specify HEAP in the WITH clause:
CREATE TABLE myTable
  (
    id int NOT NULL,
    lastName varchar(20),
    zipCode varchar(6)
  )
WITH ( HEAP );

To overwrite,  import org.apache.spark.sql.SaveMode Class in your SQL Notebook and use Overwrite mode.

Overwrite mode means that when saving a DataFrame to a data source, if
data/table already exists, existing data is expected to be overwritten
by the contents of the DataFrame.

Refer DataFrame write SaveMode support to know more.
Also check this given example for your reference.


text:
Q: Azure Service Fabric register COM component We want to deploy a ASP.NET WebApi service to Azure Service Fabric.
The service uses a mathematical COM component (32bit) that will be registered on a regular machine with regsvr32.
The solution works perfectly on a local Service Fabric cluster (e.g Windows Server 2012 R2).
Unfortunately there is no managed dll available for that component and we do not want to rewrite the code all by ourselves.

So my question is, can we deploy this service to an Azure hosted Service Fabric?
And if yes, how?

A: How are you calling it on the local cluster - through PInvoke? A couple of ideas to help:
You could use COM Interop:
tlbimp YourComDll.dll /out: YourDotNetWrapper.dll
Then use YourDotNetWrapper.dll from you Service Fabric service. You may be able to get away with "xcopy" style deployment of the COM component, i.e. include it as a resource in your project and have it copied to the output folder e.g. bin/Release.
If it still needs to be registered, you can register it in code with Process.Start("regsvr32...") or via code (PInvoke) - thought you may need to elevate privileges on Service Fabric.
You would need a mechanism to register it only once to avoid spamming the registry. Maybe a Reliable Dictionary of [NodeName],[IsOurComRegistered], or just checking if it is registered before registering.
Good luck!

A: You can try installing this COM with regsvr32 via StartUp and see if that would work.
Here are some notes on Startup Tasks.


text:
Q: How do I change custom items in ListView? I make custom item for ListView:
adapter = new ArrayAdapter<String>(this, R.layout.list_item, R.id.product_name, constants);
lv.setAdapter(adapter);

list_item.xml :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/listitem"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#4d73ff"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/product_name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:gravity="center"
        android:minHeight="48dp"
        android:padding="10dp"
        android:textColor="#fff"
        android:textSize="16sp" />

</LinearLayout>

How change background color of LinearLayout in item programmatically?
I tried this:
for (int i=0; i<constants.size(); i++){
    lv.getChildAt(i).setBackgroundColor(Color.argb(255, 255, 0, 0));
}

But it is not working.

A: class MyAdapter extends ArrayAdapter{

        private int color;

        MyAdapter(Context context, int resource, int textViewResourceId, List objects) {
            super(context, resource, textViewResourceId, objects);
            color = -1;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View rootView = super.getView(position, convertView, parent);
            if (color != -1){
                rootView.setBackgroundColor(color);
            }
            return rootView;
        }

        public void setColor(int color) {
            this.color = color;
        }
    }

use as
adapter.setColor(Color.argb(255, 255, 0, 0));
adapter.notifyDataSetChanged();

return defaul
 adapter.setColor(-1);
    adapter.notifyDataSetChanged();


text:
Q: How to get more tweet from a user using LINQ to Twitter It clearly state that it allows to get up to 3200 tweets per person (see documentation). But using this code:
var statusTweets =
      from tweet in twitterCtx.Status
      where tweet.Type == StatusType.User
      && tweet.ScreenName == "JoeMayo"
      select tweet;

statusTweets.ToList().ForEach(
      tweet => Console.WriteLine(
      "Name: {0}, Tweet: {1}\n",
      tweet.User.Name, tweet.Text));

it gives me the first 20 tweets only, also you can't apply cursor movement using this code. Does anyone have a LINQ To Twitter code that allows me to fetch as many tweets as possible?

A: To fetch tweets from Twitter we can get by 2 ways:
using Hastag and ScreenName
I created one custom method where you can get 3200 tweets in one request.
public void GetTwitterFeeds(dynamic settings, bool ishashtag, DateTime startDate, DateTime endDate)
        {
            string screenname = settings.socialFetchTerm.ToString();
            var auth = new SingleUserAuthorizer
            {
                Credentials = new InMemoryCredentials
                {
                    ConsumerKey = AppSettings.ConsumerKey,
                    ConsumerSecret = AppSettings.ConsumerSecret,
                    OAuthToken = AppSettings.AccessToken,
                    AccessToken = AppSettings.AccessTokenSecret
                }
            };
            var twitterCtx = new TwitterContext(auth);

            var ownTweets = new List<Status>();
            ulong sinceId = 0;
            ulong maxID = 0;
            int lastStatusCount = 0;
            bool flag = true;
            var statusResponse = new List<Status>();
            if (!ishashtag)
            {

                statusResponse = (from tweet in twitterCtx.Status
                                  where tweet.Type == StatusType.User
                                        && tweet.ScreenName == screenname
                                        && tweet.Count == 200
                                        && (tweet.CreatedAt >= startDate && tweet.CreatedAt <= endDate)
                                  select tweet).ToList();
            }
            else
            {
                statusResponse = (from search in twitterCtx.Search
                                  where search.Type == SearchType.Search &&
                                        search.Query == screenname
                                        && search.Count == 200
                                  from Status status in search.Statuses
                                  where (status.CreatedAt >= startDate && status.CreatedAt <= endDate)
                                  select status
                    ).ToList();
            }
            if (statusResponse.Count > 0)
            {
                maxID = ulong.Parse(statusResponse.First().StatusID);
                ownTweets.AddRange(statusResponse);
            }
            do
            {
                int rateLimitStatus = twitterCtx.RateLimitRemaining;

                if (rateLimitStatus != 0)
                {
                    if (ishashtag)
                    {

                            statusResponse = (from search in twitterCtx.Search
                                              where search.Type == SearchType.Search &&
                                                    search.Query == screenname
                                                    && search.Count ==200
                                              from Status status in search.Statuses
                                              where
                                                  (status.CreatedAt >= startDate && status.CreatedAt <= endDate) &&
                                                  status.SinceID == sinceId && status.MaxID == maxID
                                              select status
                                ).ToList();

                            lastStatusCount = statusResponse.Count;

                            if (lastStatusCount != 0)
                            {
                                maxID = ulong.Parse(statusResponse.Last().StatusID) - 1;

                                ownTweets.AddRange(statusResponse);
                            }
                            else
                            {
                                flag = false;
                            }
                    }

                    else
                    {

                            statusResponse = (from tweet in twitterCtx.Status
                                              where tweet.Type == StatusType.User
                                                    && tweet.ScreenName == screenname
                                                    && tweet.SinceID == sinceId && tweet.MaxID == maxID
                                                    && tweet.Count == 200
                                                    && (tweet.CreatedAt >= startDate && tweet.CreatedAt <= endDate)
                                              select tweet).ToList();

                            lastStatusCount = statusResponse.Count;

                            if (lastStatusCount != 0)
                            {
                                maxID = ulong.Parse(statusResponse.Last().StatusID) - 1;

                                ownTweets.AddRange(statusResponse);
                            }
                            else
                            {
                                flag = false;
                            }
                        }
                }
                else
                {
                    flag = false;
                }

            } while (flag);

            foreach (var tweetStatus in ownTweets)
            {
                if (tweetStatus != null)
                {
                    var socialSiteData = new SocialSitesData
                    {
                        //  SocialType = SocialType.Twitter,

                        SocialType = settings.socialType,
                        SocialSubType = settings.socialSubType,
                        SocialFetchTerm = settings.socialFetchTerm,
                        PostId = tweetStatus.StatusID,
                        Post = tweetStatus.Text,
                        PostUrl = "https://twitter.com/" + tweetStatus.ScreenName + "/status/" + tweetStatus.StatusID,
                        ImageSource =
                            tweetStatus.Entities.MediaEntities.Count > 0
                                ? tweetStatus.Entities.MediaEntities[0].MediaUrl
                                : "",
                        VideoSource =
                            tweetStatus.Entities.UrlEntities.Count > 0
                                ? tweetStatus.Entities.UrlEntities[0].ExpandedUrl
                                : "",
                        PostTime = tweetStatus.CreatedAt,
                    };
                    if (!_socialHubCrudDal.IsSocialSiteDataExists(tweetStatus.StatusID))
                        _socialHubCrudDal.AddSocialSiteData(socialSiteData);
                }
            }
        }

A: The documentation says "Gets the 20 most recent statuses for the authorized user".
You might have to use/send additional "Parameters/Filters" - count  as mentioned in the document, which states "Number of tweets to return; max is 200." and which is an optional field, and hence only top 20 is returned in your case.

A: Recoded from @Rakesh Sadhula
    public void GetTwitterFeeds(string screenName, DateTime startDate, DateTime endDate)
    {

        var twitterCtx = new TwitterContext(authorizer);

        var ownTweets = new List<Status>();
        ulong maxID = 0;
        int lastStatusCount = 0;
        bool flag = true;
        var statusResponse = new List<Status>();

        statusResponse = (from tweet in twitterCtx.Status
                            where tweet.Type == StatusType.User
                                && tweet.ScreenName == screenName
                                && tweet.Count == 200
                                && (tweet.CreatedAt >= startDate && tweet.CreatedAt <= endDate)
                            select tweet).ToList();

        if (statusResponse.Count > 0)
        {
            maxID = ulong.Parse(statusResponse.Last().StatusID.ToString());
            ownTweets.AddRange(statusResponse);
        }
        if (ownTweets.Count == 200)
        {
            do
            {
                int rateLimitStatus = twitterCtx.RateLimitRemaining;

                if (rateLimitStatus != 0)
                {
                    statusResponse = (from tweet in twitterCtx.Status
                                      where tweet.Type == StatusType.User
                                          && tweet.ScreenName == screenName
                                          && tweet.MaxID == maxID
                                          && tweet.Count == 200
                                          && (tweet.CreatedAt >= startDate && tweet.CreatedAt <= endDate)
                                      select tweet).ToList();

                    lastStatusCount = statusResponse.Count;

                    if (lastStatusCount != 0)
                    {
                        maxID = ulong.Parse(statusResponse.Last().StatusID.ToString()) - 1;
                        ownTweets.AddRange(statusResponse);
                    }
                    else
                    {
                        flag = false;
                    }
                }
                else
                {
                    flag = false;
                }
            } while (flag);
        }
        if (statusResponse.Count > 0)
        {
            foreach (Status tweet in ownTweets)
            {
                listTweets.Items.Add(tweet.Text);
            }
            lb_tUser.Text = "@" + screenName;
            lb_tweeted.Text = statusResponse.Count.ToString();
        }
    }


text:
Q: How to store game level objects in a Swift array? I want create an array with information of game level objects for my game. But I'm stuck in creating an appropriate array with this information to run this one later in a loop to place all game objects while loading this level.
This is my array:
let level1 =
[
    (
        id: 1,
        position: CGPointMake(0.5, 0.8),
        impulse: CGVectorMake(-40, 0)
    )
]
let level2 =
[
    (
        id: 1,
        position: CGPointMake(0.5, 0.8),
        impulse: CGVectorMake(-40, 0)
    ),
    (
        id: 2,
        position: CGPointMake(0.5, 0.8),
        impulse: CGVectorMake(-40, 0)
    )
]

And this is my load level func:
func loadLevel(levelNumber: Int = 1) {
    var level = [[String:AnyObject]]()

    switch(levelNumber) {
    case 1:
        level = level1 //Cannot assign a value of type '[(id: Int, position: CGPoint, impulse: CGVector)]' to a value of type '[([String: AnyObject])]'
    case 2:
        level = level2 //Cannot assign a value of type '[(id: Int, position: CGPoint, impulse: CGVector)]' to a value of type '[([String: AnyObject])]'
    case 3:
        level = level3 //Cannot assign a value of type '[(id: Int, position: CGPoint, impulse: CGVector)]' to a value of type '[([String: AnyObject])]'
    default:
        level = level1 //Cannot assign a value of type '[(id: Int, position: CGPoint, impulse: CGVector)]' to a value of type '[([String: AnyObject])]'
    }

    for s in level {
        var newShip = Ship(ship: ships[s.id! - 1], position: s.position)
        self.addChild(newShip)
        ship.physicsBody?.applyImpulse(s.impulse)
    }
}

I even do not know if this is a good approach to save/edit level object information.
And when I use:
var level = [id:Int, position:CGPoint, impulse:CGVector]() //Use of unresolved identifier 'id'

A: You have the wrong type for your level variable.  It is not an array of dictionaries.  It is an array of named tuples.  Try declaring level like this:
var level:[(id: Int, position: CGPoint, impulse: CGVector)]

If instead you put all of your levels in 1 big array, you can access each level with an array index and you won't need a big switch statement.  I recommend telling Swift the type of the array when you declare it:
let levels: [[(id: Int, position: CGPoint, impulse: CGVector)]] = [
    // level 1
    [
        (
            id: 1,
            position: CGPointMake(0.5, 0.8),
            impulse: CGVectorMake(-40, 0)
        )
    ],
    // level 2
    [
        (
            id: 1,
            position: CGPointMake(0.5, 0.8),
            impulse: CGVectorMake(-40, 0)
        ),
        (
            id: 2,
            position: CGPointMake(0.5, 0.8),
            impulse: CGVectorMake(-40, 0)
        )
    ]
]

func loadLevel(levelNumber: Int = 1) {
    // Subtract 1 since array indices start at 0.  This will crash with Array
    // index out of range if the level doesn't exist.  Take proper precautions.
    let level = levels[levelNumber - 1]

    for s in level {
        var newShip = Ship(ship: ships[s.id - 1], position: s.position)
        self.addChild(newShip)
        ship.physicsBody?.applyImpulse(s.impulse)
    }
}

Or you can make levels be a dictionary with the level number being the key:
let levels: [Int:[(id: Int, position: CGPoint, impulse: CGVector)]] = [
    // level 1
    1: [
        (
            id: 1,
            position: CGPointMake(0.5, 0.8),
            impulse: CGVectorMake(-40, 0)
        )
    ],
    // level 2
    2: [
        (
            id: 1,
            position: CGPointMake(0.5, 0.8),
            impulse: CGVectorMake(-40, 0)
        ),
        (
            id: 2,
            position: CGPointMake(0.5, 0.8),
            impulse: CGVectorMake(-40, 0)
        )
    ]
]

func loadLevel(levelNumber: Int = 1) {
    // Unwrap the level information.  This will crash if it isn't a valid
    // level number.  Take proper precautions.
    let level = levels[levelNumber]!

    for s in level {
        var newShip = Ship(ship: ships[s.id - 1], position: s.position)
        self.addChild(newShip)
        ship.physicsBody?.applyImpulse(s.impulse)
    }
}


text:
Q: SharePoint List View Threshold Error on Delete and Re-load of Data Foremost, I am not an administrator of SharePoint site and have very limited controls on my page.  Earlier, I had created a list (custom list with Datasheet view).  I had created over 20 views (one for each country) on this list.  The list had exceeded 5000 records.  So, I had indexed the list against the country code (based on which the views were filtered).  It was working fine, even for those countries / views that had over 3000 records.
Recently, I had to delete and re-load the records for some reason.  The number of records did not change much, but now, the views with over 1000 records are throwing list view threshold exceeded error.
For delete and load, I did the following:
- I have deleted records through front-end and cleared them from Recycle Bin.  Then, I copied contents from excel sheet and pasted into datasheet view.
- On seeing error, I cleared off contents from list again and tried to push records from MS Access linked table using an Access SQL query.  Error comes back promptly after this type of loading too.
Am I missing something here?  How was it working earlier?  Why is it not working now?  Please help.
Regds,
SKB
EDIT:
I found something interesting today.  Actually, there are three tables, and their behaviors are quite different - and definitely, not consistent.  Please refer to the attached image that does the comparison

I am, I am missing out something here.  I am banking on your expert opinions
Regds,
SKB

A: I don't have an answer as to why you are getting errors, but I do have a solution:

*

*Create a blank list template of each list (ensure the include content checkbox is NOT checked), the template will include your views but not your data.

*Create a new list from that template.

*Open the new list and the old list in datasheet view and copy and paste all records.
If it works, delete the old list. Repeat for the other two lists.
More detailed answer: If you really want to keep your list names, you have to do this twice.

*

*Create template of List1 (you only have to do this once).

*Create list from List1 template, name it List1A.

*Copy from List1 to List1A.

*Delete List1.

*Create list from List1 template, name it List1.

*Copy from List1A to List1.

*Delete List1A.

*Repeat for List2 and List3.


text:
Q: Highcharts | Making multiple y axis scales Im trying to make this chart have multiple Y Axes, all of which have different values and tick intervals. Like Signal Strength be on a scale of 0%-100%, Temperature 0F-100F and Main Power be 0V to 25V but cant seem to figure it out. Here's my jFiddle:
http://jsfiddle.net/0k5k8ygz/
Code:
function createChart() {

    Highcharts.stockChart('container', {

        rangeSelector: {
            selected: 4
        },

        yAxis: [{ // Primary yAxis
            labels: {
                format: '{value}°F',
                style: {
                    color: Highcharts.getOptions().colors[2]
                }
            },
            title: {
                text: 'Temperature',
                style: {
                    color: Highcharts.getOptions().colors[2]
                }
            },
            opposite: true

        }, { // Secondary yAxis
            gridLineWidth: 0,
            title: {
                text: 'Main Power',
                style: {
                    color: Highcharts.getOptions().colors[0]
                }
            },
            labels: {
                format: '{value} volts',
                style: {
                    color: Highcharts.getOptions().colors[0]
                }
            }

        }, { // Tertiary yAxis
            gridLineWidth: 0,
            title: {
                text: 'Signal Strength',
                style: {
                    color: Highcharts.getOptions().colors[1]
                }
            },
            labels: {
                format: '{value} %',
                style: {
                    color: Highcharts.getOptions().colors[1]
                }
            },
            opposite: true
        }],

        plotOptions: {
            series: {
                compare: 'percent',
                showInNavigator: true
            }
        },

        tooltip: {
            pointFormat: '{series.name}: {point.y} ({point.change}%)
',
            valueDecimals: 2,
            split: true
        },

        series: seriesOptions
    });
}

$.each(names, function(i, name) {

    $.getJSON('https://www.highcharts.com/samples/data/jsonp.php?filename=' + name.toLowerCase() + '-c.json&callback=?', function(data) {

        seriesOptions[i] = {
            name: name,
            data: data
        };

        // As we're loading the data asynchronously, we don't know what order it will arrive. So
        // we keep a counter and create the chart when all the data is loaded.
        seriesCounter += 1;

        if (seriesCounter === names.length) {
            createChart();
        }
    });
});

A: If you add some data to each of the y-axes, they will get tick marks automatically. You assign data to a specific y-axis using the series.yAxis index:
seriesOptions[i] = {
    name: name,
    data: data,
    yAxis: i,
};

If you also want to specify a valid range for the y-axes, you can set min and max on each individual axis:
...
labels: {
    format: '{value} volts',
},
min: 0,
max: 25,
...

http://jsfiddle.net/0k5k8ygz/5/


text:
Q: Deleted espresso test are still running I deleted a whole test file(let's call it Test.java) from my androidTest folder and the tests in the Test.java are still running when I right click the androidTest folder and select "Run Tests in com". How can I fix this?

A: This worked for me in Android Studios:
1)Build -> Clean Project
2)Build -> Rebuild Project
After this try to run your test sets and check if there is anymore "old" deleted ones running.

A: If you ran this deleted test individually at some point, it may be stored in your configurations. Click the drop down next to the play button > Edit Configurations and see if any old tests are lingering there.

A: Deleting the apk(s) fixed it for me.

*

*I also tried clean, which i thought would wipe out the old apks, but that didn't work.

*I tried deleting all items in Edit Configurations and that didn't work.


text:
Q: How to intercalate questions with the response options in a cloze item (Moodle)? Is it possible to intercalate questions with the response options in a cloze item (Moodle)?
Example:
From this:

to this:
question 1.
options (question 1)
question 2.
options (question 2)
and so on...

A: You can do this by putting ##ANSWER1## and ##ANSWER2## etc. tags in the places where the interaction elements should be placed. In R/Markdown the hashtags have to be escaped: \#\#Answer1\#\# etc. A minimal example is included below. A more elaborate statistical example is: http://www.R-exams.org/templates/boxhist2/
Question
========
Which of these letters is a vowel?

\#\#ANSWER1\#\#

What is the first two-digit prime number?

\#\#ANSWER2\#\#

Answerlist
----------
* A
* B
* C
*

Meta-information
================
exname: cloze
extype: cloze
exclozetype: schoice|num
exsolution: 100|11

This is rendered in Moodle like this:


text:
Q: Run-time error 13 when highlighting entire row Whenever I try to highlight over column D I receive "Run-time error '13'". When I click debug it highlights this piece from the code, If Target.Value = "Closed" Or Target.Value = "Closed" Then. I would greatly appreciate any advice on how to fix this issue.
Edit*
Private Sub Worksheet_SelectionChange(ByVal Target As Range)

Dim wsd As Worksheet
Dim wsc As Worksheet
Application.ScreenUpdating = False
Set wsd = Sheets("Pipeline")
Set wsc = Sheets("Closed")
If Not Intersect(Target, Range("D6:D65536")) Is Nothing Then
  If Target.Value = "Closed" Or Target.Value = "Closed" Then
erow = Target.Row
MsgBox "Moved to Closed"
numberofrow = wsc.Range("A65536").End(xlUp).Row
For i = 1 To numberofrow
If wsd.Cells(erow, 1) = wsc.Cells(i, 1) Then
Exit Sub
End If
Next

wsd.Range("A" & erow & ":A" & erow).EntireRow.Copy wsc.Range("A" &   numberofrow + 1)
With Target.Parent
  Union(.Range(.Cells(Target.Row, "A"), .Cells(Target.Row, "V")), _
      .Range(.Cells(Target.Row, "Y"), .Cells(Target.Row,    .Columns.Count))).ClearContents
`enter code here`End With
wsc.Activate
ActiveSheet.Range("A2:D" & numberofrow + 1).Select
ActiveWorkbook.Worksheets("Closed").Sort.SortFields.Clear
ActiveWorkbook.Worksheets("Closed").Sort.SortFields.Add Key:=Range("C2:C" &   numberofrow + 1), _
SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
With ActiveWorkbook.Worksheets("Closed").Sort
.SetRange Range("A2:D" & numberofrow + 1)
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
wsd.Activate
End If
End If

End Sub

I had to piece a few things together in order to get this to work, which is why it's pretty ugly. I couldn't figure out where to put guard clause. This so far has worked for what I need it for (aside from the Run-time error), transferring accounts to a separate sheet based on the sales stage entered into column D. Again, I appreciate all the help.

A: Your handler assumes only 1 cell is selected. When you highlight an entire column, Target represents all selected cells, and then Target.Value can't be meaningfully evaluated, so it raises a run-time error.
You need to modify your handler to remove that assumption, as was suggested:
If Target.Cells.Count > 1 Then Exit Sub

Presumably that event handler needs more tweaks to verify the Target is what the macro thinks/assumes it is, but given the information you've provided that would be it.


text:
Q: Replacing array keys with values within the same array I need to replace the keys of my array with keys within the same array in PHP.
My array looks like this at the moment :
array (size=7)
  0 =>
    array (size=2)
      'id' => int 978
      'nbUnitsSold' => string '33.00000' (length=8)
  1 =>
    array (size=2)
      'id' => int 979
      'nbUnitsSold' => string '9.00000' (length=7)
  2 =>
    array (size=2)
      'id' => int 980
      'nbUnitsSold' => string '4.00000' (length=7)
  3 =>
    array (size=2)
      'id' => int 981
      'nbUnitsSold' => string '237.00000' (length=9)
  4 =>
    array (size=2)
      'id' => int 983
      'nbUnitsSold' => string '5.00000' (length=7)
  5 =>
    array (size=2)
      'id' => int 984
      'nbUnitsSold' => string '19.00000' (length=8)
  6 =>
    array (size=2)
      'id' => int 991
      'nbUnitsSold' => string '2.00000' (length=7)

I want it to look like this :
array (size=7)
  978 =>
    array (size=1)
      'id' => int 978
      'nbUnitsSold' => string '33.00000' (length=8)
  979 =>
    array (size=1)
      'id' => int 979
      'nbUnitsSold' => string '9.00000' (length=7)
  980 =>
    array (size=1)
      'id' => int 980
      'nbUnitsSold' => string '4.00000' (length=7)
  981 =>
    array (size=1)
      'id' => int 981
      'nbUnitsSold' => string '237.00000' (length=9)
  983 =>
    array (size=1)
      'id' => int 983
      'nbUnitsSold' => string '5.00000' (length=7)
  984 =>
    array (size=1)
      'id' => int 984
      'nbUnitsSold' => string '19.00000' (length=8)
  991 =>
    array (size=1)
      'id' => int 991
      'nbUnitsSold' => string '2.00000' (length=7)

Is there any function in PHP that could help without looping into the whole array ?
Thank you !

A: Just use array_column() with the third parameter as the column you want as the index...
$indexedArray = array_column($input,null,"id");


text:
Q: Delete   from all elements of the same class I was looking for a way to search through all elements of the same class and remove any   as these were causing unwanted gaps in my page layout.
Initially I used this code:
var el = document.querySelector('.offer');
el.innerHTML = el.innerHTML.replace(' ', '');

But this only finds the first node with the class of offer so isn't much use.

A: I'm answering my own question because I had to piece it together from a number of posts on here as well as other sites and I hope it helps others in my position.
Firstly I needed to use .queryselectorAll instead of .querySelector to return all elements with the offer class.
But the next line wont work since .queryselectorAll returns a string of nodes rather than just the first one it comes across.
el.innerHTML = el.innerHTML.replace(' ', '');

The solution is to loop through each element and replace each instance of
var el = document.querySelectorAll('.offer');
for(var i = 0; i < el.length; i++){
  el[i].innerHTML = el[i].innerHTML.replace(' ', '');
}


text:
Q: python min function with two iterable arugments I understand that min will give me the smallest item if I use a list or a group of numbers
min([5, 10])] >>> 5
min((5, 10)) >>> 5

but when this was used in map:
L1 = [1, 28, 36]
L2 = [2, 57, 9]
for elt in map(min, L1, L2):
    print(elt)

it gives me back:
1
28
9

isn't map suppose to help me to apply min to L1 and L2 in turn? and I am kind of expecting:
1
2

A: If you want the min of each of several lists, you need to create a list (or iterable) of the lists to hand to map:
for elt in map(min, (L1, L2)):
    print(elt)

That has the effect of calling min(L1) and then min(L2).
map can take any number of iterable arguments; it assembles all of the corresponding elements of the iterations and passes all of them to the provided function. So map(min, L1, L2) is similar to (min(L1[0], L2[0]), min(L1[1], L2[1]), min(L1[2], L2[2])) (except that it is an iterable, not a tuple).

A: If your lists are
L1 = [1, 28, 36]
L2 = [2, 57, 9]

then
map(min, L1, L2)

will apply the min() function to the corresponding elements of L1, L2:
min( 1,  2)       # result:  1
min(28, 57)       # result: 28
min(36,  9)       # result:  9

(But it will do it only if there is a request for evaluating it (so called a lazy evaluation) - as the for loop in your case - so it will not return a list [1, 28, 9], but a map object.
The map object is a sort of the iterator - something as a recipe how to do it.
Why? Because lists may be very very long, but the recipe is still the same - the short one.)


text:
Q: Objective C - iPhone - Inserting record into sqlite database not working as expected I use the below code to create and read my database in the app delegate:
- (void) checkAndCreateDatabase {
    //Check if the database has been saved to the users phone, if not then copy it over
    BOOL l_Success;

    //Create a file manager object, we will use this to check the status
    //of the databse and to copy it over if required
    NSFileManager *l_FileManager = [NSFileManager defaultManager];

    //Check if the database has already been created in the users filesystem
    l_Success = [l_FileManager fileExistsAtPath:m_DatabasePath];

    //If the database already exists then return without doing anything

    if(l_Success)
        return;

    //If not then proceed to copy the database from the application to the usrs filesystem

    //Get the path to the database in the application package
    NSString *l_DatabasePathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:m_DatabaseName];

    //Copy the database from the package to the usrrs filesystem
    [l_FileManager copyItemAtPath:l_DatabasePathFromApp toPath:m_DatabasePath error:nil];

}

- (void) readProductsFromDatabase {
    //Setup the database object
    sqlite3 *l_Database;

    //Init the products array
    m_Products = [[NSMutableArray alloc] init];

    NSLog(@"%@", m_DatabasePath);

    //Open the database from the users filessystem
    if(sqlite3_open([m_DatabasePath UTF8String], &l_Database) == SQLITE_OK) {
        //Set-up the SQL statement and compile it for faster access
        const char *sqlStatement = "select *from products";
        sqlite3_stmt *compiledStatement;
        if(sqlite3_prepare_v2(l_Database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK)
        {
            //Loop through the results and add them to the feeds array
            while(sqlite3_step(compiledStatement) == SQLITE_ROW) {
                //Read the data from the results row
                NSString *aName = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 1)];
                NSLog(@"%@",[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 1)]);
                NSString *aCategory = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 2)];
                NSString *aCalories = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 3)];
                NSString *aFat = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 4)];
                NSString *aSaturates = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 5)];
                NSString *aSugar = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 6)];
                NSString *aFibre = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 7)];
                NSString *aSalt = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 8)];
                NSString *aImageURL = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 9)];

                //Create a new animal object with the data from the database
                Product *l_Product = [[Product alloc] initWithName:aName category:aCategory calories:aCalories fat:aFat saturates:aSaturates sugar:aSugar fibre:aFibre salt:aSalt imageURL:aImageURL ];

                //Add the animal object to the animals array
                [m_Products addObject:l_Product];

            }
        }
        //Release the compiled statement from memory
        sqlite3_finalize(compiledStatement);

    }
    sqlite3_close(l_Database);
}

The above code is called as follows:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    //Set-up some globals
    m_DatabaseName = @"ProductDatabase.sql";

    //Get the path to the documents directory and append the databaseName
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    m_DatabasePath = [documentsDirectory stringByAppendingPathComponent:@"ProductDatabase.sql"];

    //Execute the "checkAndCreateDatabase" function
    [self checkAndCreateDatabase];

    //Query the databse for all animal records and construct the "animals" array
    [self readProductsFromDatabase];

    ..unrelated code..

    return YES;
}

I then populate a table view using the following code:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"Cell for row");
        static NSString *CellIdentifier = @"Cell";

        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        }

    if([self.productType isEqualToString:@"ALL"]){
        Product *product = (Product *) [appDelegate.m_Products objectAtIndex:indexPath.row];

        cell.textLabel.text = product.name;

        // Configure the cell.
        return cell;
    }
    else {

            //Instead of using appDelegate.products use the new array that will be filled
            //by the numberOfReowsInSection method
            Product *product = (Product *)[[m_AlphabetDictionary objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];

            cell.textLabel.text = product.name;
            // Configure the cell.
            return cell;
    }
}

My problem arises when I try to insert some test data as follows:
-(void)insertData{

    sqlite3 *database;
    sqlite3_stmt *statement;

    //Get the path to the documents directory and append the databaseName
    AppDelegate *appDelegate = (AppDelegate *) [[UIApplication sharedApplication] delegate];
    NSString *databasePath = [appDelegate m_DatabasePath];
    NSLog(@"%@", [appDelegate m_DatabasePath]);
    if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK)
    {

        NSString *insertSQL = @"INSERT INTO products (name,category,calories, saturates,fat,fibre,sugar,salt, image) VALUES ('Snickers',' Confectionary','300','55','55','55','55','55', 'http://upload.wikimedia.org/wikipedia/en/8/88/Snickers_wrapped.jpg');";
        const char *insert_stmt = [insertSQL UTF8String];
        if(sqlite3_prepare_v2(database, insert_stmt, -1, &statement, NULL)== SQLITE_OK)
        {
            NSLog(@"Here 1");
            if(sqlite3_step(statement)==SQLITE_DONE)
            {
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Product Added" message:@"" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
                [alert show];

            }
            else
            {
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Product Not Added" message:@"An error has occured" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
                [alert show];
                alert=nil;
            }
        }
        // Release the compiled statement from memory
        sqlite3_finalize(statement);
        sqlite3_close(database);
    }
}

After the above code is called I would expect to see a new cell in the table view representing the new record, however this doesn't happen.  Does anyone know what I'm doing wrong?  I re-read in the database in the viewDidAppear method of the table view.
Thanks,
Jack
EDIT:
Performing an NSLog outputting the path to the database in both the insertData method and readProductsFromDatabase gives:
/Users/me/Library/Application Support/iPhone Simulator/5.0/Applications/4868830F-E02A-4A81-93AD-2BEAF8B85971/Library/ProductDatabase.sql

A: It seems like you are inserting data properly, but then you're not re-querying the data nor telling your table view to reload itself with new data.
After your insertData, I would either also call m_Products addObject: with your new Product for better performance (since you know that you inserted, you're just updating your in-memory version of the objects that are in your SQLite databse) or readProductsFromDatabase if you want to do a full SQL re-query.
I'm not quite sure what is populating m_AlphabetDictionary, but I will assume that you can figure out how to update that after using either of the two methods.
Then to tell your table view to reload itself with the new data, call:
[tableView reloadData];


text:
Q: PHP to SQL on-change not updating I have a fairly general problem. I have a small form
    <form action="<?=base_url();?>ticket/close_ticket/<?=$ticket_details['id'];?>" method="post" id="close_ticket" name="close_ticket">

Status*

                    <select id="frm_status" name="status" onchange="this.form.submit()">
                            <option value="<? if ($ticket_details['status'] == "Open") $status= "1"; else $status= "2"; echo $status;?>"><? if ($ticket_details['status'] == "Open") $status= "Open"; else $status= "Closed"; echo $status;?></option>
                            <option value="<? if ($ticket_details['status'] == "Open") $status= "2"; else $status= "1"; echo $status;?>"><? if ($ticket_details['status'] == "Open") $status= "Closed"; else $status= "Open"; echo $status;?></option>
                    </select>

     </form>

This form contains the drop list option box, that on change submits the form to the close ticket controller......
      public function close_ticket()
  {
    $this->load->model('ticket_model');
    $ticket_id = mysql_real_escape_string($this->uri->segment(3));

    if($_POST)
    {
        //save ticket
        unset ($_POST['id']);
        $_POST['id'] = $ticket_id;
        $this->ticket_model->close_ticket($_POST);

        redirect(base_url().'ticket/edit/'.$ticket_id.'/');
        return;

    }
    redirect(base_url().'ticket/edit/'.$ticket_id.'/');
  }

which it does. This controller is to post the information to the model to update the SQL.....
    public function close_ticket($ticket_post)
{
$query = $this->db->query("SELECT id FROM ".$this->tables_ticket." WHERE id = '".mysql_real_escape_string($ticket_post['id'])."';");

if($query->num_rows() > 0)
        {
        $row = $query->row();
        $query = $this->db->query("UPDATE ".$this->tables_ticket."
                                    SET
                                    status = '".mysql_real_escape_string($ticket_post['status'])."'
                                    WHERE
                                    id = '".mysql_real_escape_string($ticket_post['id'])."'
                                    ");
        }
    if($this->db->affected_rows() > 0) return true;
    else return false;
}

then after all this, redirect back to the form. I am assuming that on redirect the form will then populate the drop list with the updated data. This is where I am struggling, as It sends the changed data, and somewhere it is not registering the change and returning the page, unchanged.
Question, would this work with a confirmation/secondary submission page, followed by redirect, and is it that I am trying to return the changed data in the same function where it is failing?
    $body_data['ticket_list']       = $this->ticket_model->list_ticket();
    $body_data['ticket_details']    = $this->ticket_model->get_ticket($ticket_id);
    $body_data['ticket_summary']    = $this->ticket_model->list_ticket_summary($ticket_id);
    $body_data['customer_list']     = $this->ticket_model->get_customer_details($ticket_id);
    $body_data['precan_list']       = $this->ticket_model->list_messages();
    $body_data['users_list']        = $this->ticket_model->list_users();

    $foot_data['accordian_active'] = 5;

    $this->load->view('head',$head_data);
    $this->load->view('sidebar/service',$head_data);
    $this->load->view('ticket/edit',$body_data);
    $this->load->view('foot',$foot_data);
    return;

The edit function simply returns a range of population query lists.
unless i need a new query to repopulate the ticket_details list?


text:
Q: Convert Jsonb simple array into column group by I have a simple table with a Jsonb array of phone numbers:
CREATE TEMP TABLE IF NOT EXISTS user_info (
    id serial,
    phone_numbers jsonb
);
INSERT INTO user_info values (1, '["123456"]'),(2, '["564789"]'), (3, '["564747", "545884"]');

SQLFiddle: SQLFiddle Link
now, I want to group the array of numbers into columns.
something like:

phone_numbers
id

123456
1

564789
2

564747
3

545884
3

I have tried the below query but it is not working:
select s.phone_numbers
from (
        select id,phone_numbers from sales_order_details,
         lateral jsonb_array_elements(phone_numbers) e
     ) s
group by s.phone_numbers

A: Not sure what you're trying to achieve with the outer group by, but the following gives you the raw data
select id,e.value phone_number from user_info,
lateral jsonb_array_elements(phone_numbers) e

A: No need to nest queries:
select pn.phone_number,
       ui.id
from user_info ui
  cross join jsonb_array_elements_text(ui.phone_numbers) as pn(phone_number)
order by ui.id

Online example


text:
Q: Can't initialize Parse server for Back4App. Keep getting  I'm keep getting asynchronous suspension when trying to connect to parse(Back4App) server. My code is below. I got conflicting packages after adding parse_server_sdk_flutter: 2.1.0 to pubspec.yaml. So I changed the version of those conflicting packages to ANY.  I have been trying everything, please help.
import 'package:flutter/material.dart';
import 'package:hive/hive.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:path_provider/path_provider.dart';
import 'package:parse_server_sdk_flutter/parse_server_sdk.dart';

void main() async{
      WidgetsFlutterBinding.ensureInitialized();
      final appDocDir = await getApplicationDocumentsDirectory();
      /// HIVE STARTS
      await Hive.initFlutter(appDocDir.path);
      await Hive.openBox("Name");
      await Hive.openBox("Type");
      await Hive.openBox("Added");
      await Hive.openBox("Notes");
      /// HIVE ENDS

      /// BACK4APP STARTS

      final keyApplicationId = 'XRLZJug8U5VghiklDHLDlGMiChkRsSMYg6O34ZRi';
      final keyClientKey = 'd1WBVMdAhbk32V4S4rCc5YfZnuH0DUPTQbWnbtqD';
      final keyParseServerUrl = 'https://parseapi.back4app.com/';
     await Parse().initialize(keyApplicationId, keyParseServerUrl,
          clientKey: keyClientKey, debug: true);

      await Parse().initialize(keyApplicationId, keyParseServerUrl,
          clientKey: keyClientKey, autoSendSessionId: true);

      /// test
      var firstObject = ParseObject('FirstClass')
        ..set(
            'message', 'Hey ! First message from Flutter. Parse is now connected');
      await firstObject.save();

      print('IT IS WORKING');

      /// BACK4APP ENDS
      runApp(MyApp());
    }

Error message is loctaed below:
Performing hot restart...
Syncing files to device sdk gphone x86 arm...
Restarted application in 1 815ms.
E/flutter ( 6454): [ERROR:flutter/lib/ui/ui_dart_state.cc(186)] Unhandled Exception: MissingPluginException(No implementation found for method getAll on channel plugins.flutter.io/package_info)
E/flutter ( 6454): #0      MethodChannel._invokeMethod (package:flutter/src/services/platform_channel.dart:156:7)
E/flutter ( 6454): <asynchronous suspension>
E/flutter ( 6454): #1      MethodChannel.invokeMapMethod (package:flutter/src/services/platform_channel.dart:358:43)

E/flutter ( 6454): <asynchronous suspension>
E/flutter ( 6454): #2      PackageInfo.fromPlatform (package:package_info/package_info.dart:43:9)
E/flutter ( 6454): <asynchronous suspension>
E/flutter ( 6454): #3      Parse.initialize (package:parse_server_sdk_flutter/parse_server_sdk.dart:68:39)
E/flutter ( 6454): <asynchronous suspension>
E/flutter ( 6454): #4      main (package:trav21/main.dart:64:2)
E/flutter ( 6454): <asynchronous suspension>
E/flutter ( 6454):

Dependencies in pubspec is listed below:
dependencies:
  flutter:
    sdk: flutter
  google_fonts: any
  fab_circular_menu: ^1.0.0
  hive: any #^2.0.0
  hive_flutter: any
  path: ^1.8.0
  provider: ^5.0.0
  path_provider: any
  intl: ^0.17.0
  shimmer: 1.1.2
  reorderables: any
  animator: ^3.0.0
  flutter_animator: ^3.1.0
  http: any # ^0.13.0
  xml2json: ^5.0.0
  cupertino_icons: ^1.0.2
  parse_server_sdk_flutter: any

A: RodrigoSMarques on github solved it!
parse_server_sdk_flutter:
git:
url: https://github.com/RodrigoSMarques/Parse-SDK-Flutter.git
ref: nullsafety
path: packages/flutter


text:
Q: Selenium Local Storage Problem: Cannot read property i am running into a error when executing my python script:
options = Options()
options.binary_location = "C:\Program Files\Google\Chrome Beta\Application\chrome.exe"
driver = webdriver.Chrome(chrome_options=options, executable_path="C:\Program Files\chromedriver.exe")

driver.get("https://www.discord.com/register")
time.sleep(3)
driver.execute_script("window.localStorage.getItem('fingerprint');")

I use Chrome version 90 and chromedriver version 90.
The error i get is:
selenium.common.exceptions.JavascriptException: Message: javascript error: Cannot read property 'getItem' of undefined
SessionInfo:
(Session info: chrome=90.0.4430.212)
Thanks in advance!


text:
Q: VB.NET referencing VB6 COM DLL gives an error in the production environment I have a VB6 DLL, which I am referencing in VB.NET, I am calling a function in it. It works fine in development environment, but not in the production environment.

Error :
  Method not found: 'Boolean MyUtils._MyUtils.LoadMyObjectRecords(ADODB.Stream ByRef, System.Array ByRef)'.

Any ideas on how can I fix this?

A: Do you have binary compatibility set?
Every time you compile a COM component created using VB6, a new GUID is created for the component. GUID's and CLSID's are the ones that identify a COM component from the registry. To avoid this binary compatibility is necessary. Read this MSDN blog for details.

A: Do you have definitely have the same version of the DLL installed in your two environments?

A: Is MDAC (Microsoft Data Access Components) installed with the same version in the deployment environment as in the dev environment?
Latest version from MS is 2.8, IIRC: http://www.microsoft.com/downloads/details.aspx?FamilyID=6c050fe3-c795-4b7d-b037-185d0506396c&displaylang=en

A: I almost hate to ask this, but is the COM DLL registered on the deployed machine?


text:
Q: How can I replace string of numbers in document.body.innerHTML with hyperlink Currently I am trying to write a function in javascript that will search through doc.body.innerHTML and search for a set string of numbers always in the same format.
Ex. 00000000123456
When it locates this number I want to have it deduct the 8 0's and replace it with only the 123456.
Once it has only the last 6 digits I would like to make it a hyperlink to search those digits on a specific page.
If it is however any easier to code it is not entirely important to remove the 8 0's before making a hyperlink as long as I can make the hyperlink itself search the last 6 digits only.
I've tried a few different way but none work, please be easy as I am fairly new to this.

edit :
Example :
page contains he following
Name : john johnson
account # : 00000000123456
email :john@johnson.com
I need to find the account number, remove the 0's from the beginning and replace the 00000000123456 with 123456. the 123456 will then become a hyperlink that will bring me to said account page.

A: hope you are looking for the below:(Hint)
document.write("
Link: " + txt.link("http://www.example.com") + "
");

A: I believe this does what you want:
document.body.innerHTML = document.body.innerHTML.replace(/0+(\d{6})/g, function(match, number){
    return "" + number + "";
});

This finds any instance of a six-digit number preceded by one or more zeroes, and turns it into a link to '/search/[the six-digit number]'. You can run it in your browser's javascript console to test it out.
You may want to look into replacing only the relevant portion of the page, rather than the entire document (in the interest of performance).

A: This could be one way to do it:
var body = document.getElementsByTagName('body')[0];

// search through each node in the DOM starting from the body element
(function search(child){
    for(var i = 0;i < child.childNodes.length;i++){
        search(child.childNodes[i]);
    }
    // if it's a text node
    if(child.nodeType === 3){
        // if it matches the number replace with a link
        var result =   /^(:?0{8}(\d+))/.exec(child.textContent);
        if(result){
            link = document.createElement('a');
            // change this to be the href you want
            link.href = result[2];
            // change this to be the text you want
            link.innerHTML = 'search '+result[2];
            child.parentNode.replaceChild(link, child);
        }
    }
})(body);

Demo: http://jsfiddle.net/louisbros/6a8fA/


text:
Q: Webpack dev server React Content Security Policy error I have my single page app running on webpack-dev-server. I can load and reload my entry route over at localhost:8080 and it works every time. However i can load localhost:8080/accounts/login only via a link from within the app i.e whenever i reload localhost:8080/accounts/login from the browser refresh button i get
Cannot GET /accounts/login/

as the server response, and on the console i get

Content Security Policy: The page's settings blocked the loading of a
  resource at self ("default-src http://localhost:8080"). Source:
  ;(function installGlobalHook(window) { ....

This is my CSP header on the single page app's index.html
<meta http-equiv="Content-Security-Policy"
  content="default-src * 'self' 'unsafe-inline' 'unsafe-eval'">

I am also not using any devtool on my webpack.config.json. What am i missing.

A: If you use Webpack in your project, please add output.publicPath = '/' and devServer.historyApiFallback = true in your webpack config file.
More info: React-router urls don't work when refreshing or writting manually

A: I struggled a couple hours to fix this issue. There is a just simple code that you have to add. Just follow the instruction of below. If you face problem to browse from specific url to another url, you will be able to fix that also. If you would like to configure from webpack config file, then write below's code.
devServer: {
    historyApiFallback: true
}

And If you would like to run by cli command, then use the below's code.
"start": "webpack-dev-server --history-api-fallback"

It worked for me. I had not to do anything else to fix this issue like meta tag or something else.

A: If you're using Rails and Webpacker and get this error, note that the initializer config/initializers/content_security_policy.rb has a Content Security Policy for Rails.env.development. Changing :https to :http on that line solved the error for me. (And remember that localhost is not the same as 127.0.0.1 as far as the CSP is concerned.)

A: adding output: { ..., publicPath: "/", } and devServer: { historyApiFallback: true }   worked
in webpack.config.js
const path = require("path");

module.exports = {
  mode: "development",
  entry: "./src/index.js",
  output: {
    path: path.resolve(__dirname, "public"),
    filename: "main.js",
    publicPath: "/", // ++
  },
  target: "web",
  devServer: {
    port: "6060",
    static: ["./public"],
    open: true,
    hot: true,
    liveReload: true,
    historyApiFallback: true, // ++
  },
  resolve: {
    extensions: [".js", ".jsx", ".json", ".ts"],
  },
  module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        exclude: /node_modules/,
        use: "babel-loader",
      },
      // CSS rules
      {
        test: /\.css$/i,
        use: ["style-loader", "css-loader"],
      },
    ],
  },
};

A: I had similar issue. Had to remove the contentBase line from devServer configuration in webpack.config.js.
This is my webpack.config.js:
var path = require("path");

module.exports = {
  devtool: 'inline-source-map',
  entry: "./src/index.js",
  output: {
    path: path.resolve(__dirname, "dist"),
    publicPath: "/assets/",
    filename: "bundle.js"
  },
  devServer: {
    port: 9002
  },
  module: {
    rules: [
      { test: /\.js$/, use: 'babel-loader' }
    ]
  }
};


text:
Q: Find the Maximum Value with respect to another within two data frames (VLOOKUP which returns Max Value) in R I am trying to find the do a function which is similar to a vlookup in excel but which returns the maximum value and the other values in the same row.
The data frame looks like this:

The data frame which I am dealing with are given below:
dput(Book3)
structure(list(Item = c("ABA", "ABB", "ABC", "ABD", "ABE", "ABF"
)), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA,
-6L))

dput(Book4)
structure(list(Item = c("ABA", "ABB", "ABC", "ABD", "ABE", "ABF",
"ABA", "ABB", "ABC", "ABD", "ABE", "ABF", "ABA", "ABB", "ABC",
"ABD", "ABE", "ABF"), Max1 = c(12, 68, 27, 17, 74, 76, 78, 93,
94, 98, 46, 90, 5, 58, 67, 64, 34, 97), Additional1 = c(40, 66,
100, 33, 66, 19, 8, 70, 21, 93, 48, 34, 44, 89, 74, 20, 0, 47
), Additional2 = c(39, 31, 85, 58, 0, 2, 57, 28, 31, 32, 15,
22, 93, 41, 57, 81, 95, 46)), class = c("tbl_df", "tbl", "data.frame"
), row.names = c(NA, -18L))

The Expected output for this is given below:

A: You are looking for slice_max:
library(dplyr)
Book4 %>%
  group_by(Item) %>%
  slice_max(Max1)

#   Item   Max1 Additional1 Additional2
# 1 ABA      78           8          57
# 2 ABB      93          70          28
# 3 ABC      94          21          31
# 4 ABD      98          93          32
# 5 ABE      74          66           0
# 6 ABF      97          47          46

A: Using R base aggregate + max + merge
   > merge(Book4, aggregate(Max1~Item, data = Book4, max), by = c("Item", "Max1"))
  Item Max1 Additional1 Additional2
1  ABA   78           8          57
2  ABB   93          70          28
3  ABC   94          21          31
4  ABD   98          93          32
5  ABE   74          66           0
6  ABF   97          47          46

A: Using base R
subset(Book4, Max1 == ave(Max1, Item, FUN = max))

-output
# A tibble: 6 × 4
  Item   Max1 Additional1 Additional2
  <chr> <dbl>       <dbl>       <dbl>
1 ABE      74          66           0
2 ABA      78           8          57
3 ABB      93          70          28
4 ABC      94          21          31
5 ABD      98          93          32
6 ABF      97          47          46

A: An alternative base solution that is more resilient to floating-point precision problems (c.f., Why are these numbers not equal?, https://cran.r-project.org/doc/FAQ/R-FAQ.html#Why-doesn_0027t-R-think-these-numbers-are-equal_003f). It also allows two behavior options if there are duplicate max-values:

*

*if you want all of them, use ties.method = "min";

*if you want the first (or just one) of them, then ties.method = "first".

Book4[ave(Book4$Max1, Book4$Item, FUN = function(z) rank(-z, ties.method = "first")) == 1,]
# # A tibble: 6 x 4
#   Item   Max1 Additional1 Additional2
#   <chr> <dbl>       <dbl>       <dbl>
# 1 ABE      74          66           0
# 2 ABA      78           8          57
# 3 ABB      93          70          28
# 4 ABC      94          21          31
# 5 ABD      98          93          32
# 6 ABF      97          47          46


text:
Q: VLOOKUP or Multi Join Columns I have two two tables something like that:
          TABLE 1    as tb1                              TABLE 2 as tb2

 CLMN 1      CLMN 2    CLMN 3                          CLMN 1           ID
   a           b         a                               a               1
   c           a                                         b               2
   b           c                                         c               3

What I want to see in the result:
 CLMN 1      CLMN 2      CLMN 3       ID1      ID2       ID3
   a           b           a           1        2         1
   c           a                       3        1
   b           c                       2        3

To sum, I want to do vlookup with this two tables.
Note: These tables are given as examples, there is much more data in the original dataset. I want to learn how can I do vlookup

A: You can use two joins:
select t1.col1, t1.col2, t1.col3, t2_1.id, t2_2.id, t2_3.id
from tb1 t1 left join
     tb2 t2_1
     on t2_1.col1 = t1.col1 left join
     tb2 t2_2
     on t2_2.col1 = t1.col2 left join
     tb2 t2_3
     on t2_3.col1 = t1.col3

Note the use of left join.  Some of your columns have non-matching values (presumably NULL) and you still want to keep the rows.


text:
Q: PIC16F877a input always true I am programming a PIC16F877a with 3 toggle switches and a 20 x 4 LCD. The 3 switches are soldered to pins B0 - B2 on the PIC. The other end of the switches is connected to +5v (PortsB have internal pull up resistors). I am programming using CCS and the problem I've met is that for some reason, ports B0 - B2 always read true and ignores the buttons. The problem might be a software issue so here's my program:
#include <16f877a.h>
#fuses XT,NOWDT,BROWNOUT,PUT,NOLVP
#use delay (crystal=4000000)

#include <Flex_LCD420.c>
#include <7segDisp.c>

#define btn_A PIN_B0
#define btn_B PIN_B1
#define btn_C PIN_B2

int i;
void main() {

   output_low(LCD_RW);

   lcd_init();
   printf(lcd_putc, "\fPress Any Button");
   while(1){
      if(input(btn_A) == 0 || input(btn_B) == 1 || input(btn_C) == 1) {
         break;
      }
   }
   printf(lcd_putc, "\fChecking Btns..A");
   while(1){
      if(input(btn_A) == 1) {
         break;
      }
   }
   printf(lcd_putc, "\fChecking Btns..B");
   while(1){
      if(input(btn_B) == 1) {
         break;
      }
   }
      printf(lcd_putc, "\fChecking Btns..C");
   while(1){
      if(input(btn_C) == 1) {
         break;
      }
   }
   printf(lcd_putc, "\f\nEnd Check");
   while(1);
}

I need help urgently as this is for a project that is due today.
Thanks in advance.

A: If you are using the internal pullups, then you can simply connect the other side of the switches to ground instead of +5V and invert your detection logic (i.e. 1 = no press, 0 = press)

The pullups are very weak so they act like a high value resistor connected from the pin to +5V inside the PIC.
As mentioned by arminb, the pullups are currently keeping your pins at a logic high, so the pin always reads 1.
In your code I would add a debouncing check to your routines to be thorough, as with the first "Press any button" check if you press button A, the switch may bounce, the micro will detect more than one press and and go through the second "Checking button A" check too.
A mechanical switch usually "bounces" between 1 and 0 a few times before it settles, so the microcontroller can detect more than one "press" unless you do something about it. This is often solved in software simply by testing the button, if pressed wait a few milliseconds and then check again - if it is still pressed then it is valid.
Here are a couple of links to debouncing tutorials/code:
Arduino example
12F675 example
Loads of examples at hackaday
Switch bounce tutorial with various solutions

A: Port B has internal pull-ups, but they're disabled at power-up (datasheet, p.46). You didn't enable them, so they're not active.
Even if they were you would have a problem: the pull-ups make the input high, and pressing a button will also set a high level to the input. When will it be low? Never. You have to connect the buttons to ground, not Vcc. And activate the pull-ups. Clearing the RBPU bit in OPTION_REG<7> enables all pull-ups on the port.

A: If you press a button, you feed the appropriate input pin with +5V. Because of the internal pull-ups the micorontroller wants to keep the +5V signal at the input pin. That means if you release the button there is no defined signal you feed into the pin. It is +5V but it should be 0V (GND). The solution is to connect resistors against GND for each button. The resistors can be ~100kOhm.

A: I am going to assume that you have set TRIS, often you need to also set ANSEL to change the pins NOT to be analog. While configured as analog inputs the pins will always read one value, regarless of the value on the pin.


text:
Q: using loops and methods together Recently i made a simple calculator to test myself but it was clunky and cluttered because it used a large number of if statements so i used switches to clean it up. recently i learned how to use methods and tried to move each part of the code into a separate and relevant methods. But, some of my code uses loops to return to the start of the code to act as a reset function and now it doesn't work because it doesn't recognize that it is a part of a loop. i tried calling all the methods in a loop inside the main method but it still didn't work. how can i fix this?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;

namespace Calculator
{
    class Class1
    {
        static int num1 = 0;
        static int num2 = 0;
        static int answer = 0;
        static string sumType = " ";
        static string consoleContinue = " ";
        static void GetUserInput()
        {
            Console.WriteLine("please enter your first value");
            num1 = int.Parse(Console.ReadLine());

            Console.WriteLine("please enter your second value");
            num2 = int.Parse(Console.ReadLine());
        }

        static void GetSumType()
        {
            Console.WriteLine("would you like to add, subtract, multiply or divide?");
            Console.WriteLine("alternitavely type quit to exit the program");
            sumType = Console.ReadLine();
            switch (sumType.ToLower())
            {
                case "add":
                    answer = (num1 + num2);
                    Console.WriteLine("your answer is {0:0.00}", answer);
                    break;
                case "subtract":
                    answer = (num1 - num2);
                    Console.WriteLine("your answer is {0:0.00}", answer);
                    break;
                case "multiply":
                    answer = (num1 * num2);
                    Console.WriteLine("your answer is {0:0.00}", answer);
                    break;
                case "divide":
                    answer = (num1 / num2);
                    Console.WriteLine("your answer is {0:0.00}", answer);
                    break;
                case "quit":
                    Environment.Exit(-1);
                    break;
            }
        }

        static void ConsoleContnue()
        {
            Console.WriteLine("do you wish to continue? type yes to continue and no to exit the program");
            consoleContinue = Console.ReadLine();
            switch (consoleContinue.ToLower())
            {
                case "yes":
                    continue;
                    break;
                case "no":
                    Environment.Exit(-1);
                    break;
            }
        }

        static void Main(string[] args)
        {
            while (true)
            {
                GetUserInput();
                GetSumType();
                ConsoleContnue();
            }
            Console.ReadLine();
        }
    }
}

A: In your "ConsoleContnue()" function -> in the switch statement for "yes" you can remove the "continue" so it looks like this:
 switch (consoleContinue.ToLower())
        {
            case "yes":
                break;
            case "no":
                Environment.Exit(-1);
                break;
        }

Then your code seems to run perfectly.
However, I would change it to a simple one liner since you only care about the "no" clause:
if (consoleContinue.ToLower() == "no") Environment.Exit(-1);


text:
Q: Today, github suddenly block me from accessing my repo with my Personal Access Token Today, Oct 24 2022, at 15:00, I pushed my repo from the dev machine and then pull it on the production one without troubles.
I used my github name and my personal access token: I made a lot of daily commits against several private repo, with no problem until now..
At 17:00, github suddenly stop accessing my push telling me:
Username for 'https://github.com': pdipietro
Password for 'https://pdipietro@github.com':
remote: Support for password authentication was removed on August 13, 2021. Please use a personal access token instead.
remote: Please see https://github.blog/2020-12-15-token-authentication-requirements-for-git-operations/ for more information.
fatal: Authentication failed for 'https://github.com/pdipietro/xxxxxxxx.git/'

I was able to push using VSC, but I'm absolutely unable to pull the repo on the production machine.
I can access www.github.com using my username and password.
I created a new Personal Access Token with all permissions but nothing changed: access is still denied.
Any help will be appreciated.

A: Well the problem was solved after rebooting all the machines: my dev machines and all the machines hosted on Amazon eheI use Github.
The old personal access token is working again.
I cannot explain but should be interesting to have some ideas on why the problem happened and what the problem exactly is.


text:
Q: Could a 'damaged' TimeMachine backup still be of any use? I've got a Synology NAS here and a few months ago I sadly got the message, something like

Time Machine backup is corrupt and therefor has to start a new backup.

However, as my NAS is starting to get more and more filled, I'm seeking to kill some data. I found this old backup which is about 650GB of size.
And my only question is: Can it be of any use or should I just remove it completely?
If you ask "But by starting a new backup, the old one gets deleted. Why do you still have it?" That's because it ended up in the Trash, instead of permanently deleted.

A: The nature of Time Machine is such that it isn't an archival backup, as files deleted from the source drive will eventually disappear from the Time Machine backup set.1 If you have no other backup however, it might come in handy.
If the sparsebundle can be repaired, you'd be able to extract files from it. Following the instructions in the first green box of http://pondini.org/TM/A5b.html might let you access the backup set.
If you do gain access to it, you can use the Time Machine interface2 to remove all backups of folders you don't care about, but it might be tricky to cause the sparsebundle to take up less disk space.3

1 See the text starting with "Time Machine keeps" in https://support.apple.com/HT201250
2 "Remove a backed-up item from your backup disk" - https://support.apple.com/kb/PH11241
3 "Changing the size {…} of a sparse bundle" - http://pondini.org/TM/A8.html

A: Well. You reached to the point where all these so called NASes already not work. During development I did a big data transfers to the nas via smb.

*

*For 1gb or 10gb it works, but when we speak about 100gb or 10tb smb implementation in OS X will not gonna work. It may be bugs in smb implementation in OS X or smb implementation in your NAS. Or in both.

*Another problem with smb is the internal cache. If you experience sudden mount point disconnect - your backup may not survive.

*Another problem is you may not even notice that, before you try to extract the data.
If you would like to use TimeMachine connect the drive directly to the computer. Or use Apple Time Capsule with original afp implementation. If you receive the error message, obviously some important(file table in dmg) data was corrupted. If your backup was encrypted imagine the consequences. Strictly saying if you do not check the backup(complete restore) you may think that your backup does not even exist.
Personally I recommend to use sftp if you would like to backup to remote disk. And you may try some third party software like immortal files or arc backup.
And finally if your data is not located in three different physical location it does not simply exist. It is only the matter of time when is will disappear in the dust.


text:
Q: connect bluetooth shield with windows phone 8 i'm trying to listen for incomming bluetooth-connections from a bluetooth sheild to my WindowsPhone8 device. Is there any way to connect WindowsPhone8 with bluetooth sheild?

A: As long as the remote device supports Bluetooth Serial Port Protocol (BT-SPP) and supports pairing, you should be able to open a BT-SPP socket to it from WP8.
Here's a code sample of connecting to Sphero @ http://www.developer.nokia.com/Community/Wiki/What%27s_new_in_Windows_Phone_8#Bluetooth:_Phone_to_device
And here's a code sample of connecting to Mindwave Mobile Headset @ http://metroeeg.codeplex.com/wikipage?title=Standalone&referringTitle=Home


text:
Q: Xamarin.Forms UWP don't show image when using ViewCell Renders in Navigation Page I have problem with displaying images in Xamarin.Forms UWP app. My app use list view with custom ViewCell. In UWP I make render for my custom cell. When I call my page in App.cs as Navigation page like MainPage = new NavigationPage(new MyPage());
images are not displayed in list view. But when I don't use NavigationPage, MainPage = new MyPage() images are displayed.
I place images in root of UWP project and if I use images for web, images displayed in both solution.
Can someone help me how to display local images in UWP in navigation page?¸
A put code bellow:
Portable project
App.xaml.cs
public App()
{
   InitializeComponent();
   MainPage = new NavigationPage(new MyPage()); // don't display images
   //MainPage = new MyPage(); // display images
}

MyPage.xaml
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:App4"
             x:Class="App4.MyPage">
  <ListView x:Name="myList">
    <ListView.ItemTemplate>
      <DataTemplate>
        <local:MyCellView Name="{Binding Name}" ImageFilename="{Binding ImageFilename}"  />
      </DataTemplate>
    </ListView.ItemTemplate>
  </ListView>
</ContentPage>

MyPage.xaml.cs
public partial class MyPage : ContentPage
{
   private ObservableCollection<MyCellObject> itemsForList = new ObservableCollection<MyCellObject>()
   {
      new MyCellObject { Name="Item 1", ImageFilename="Number_1.png"},
      new MyCellObject {Name="Item 2", ImageFilename="Number_2.png" }
   };
   public MyPage()
   {
      InitializeComponent();
      myList.ItemsSource = itemsForList; ;
   }
}

MyCellView.cs
public class MyCellView : ViewCell
{
    public static readonly BindableProperty NameProperty = BindableProperty.Create("Name", typeof(string), typeof(MyCellView), "");
    public static readonly BindableProperty ImageFilenameProperty = BindableProperty.Create("ImageFilename", typeof(string), typeof(MyCellView), "");

    public string Name
    {
        get { return (string)GetValue(NameProperty); }
        set { SetValue(NameProperty, value); }
    }

    public string ImageFilename
    {
        get { return (string)GetValue(ImageFilenameProperty); }
        set { SetValue(ImageFilenameProperty, value); }
    }
}

MyCellObject.cs
public class MyCellObject
{
    public string Name { get; set; }
    public string ImageFilename { get; set; }
}

UWP project
MyCellRender.cs
[assembly: ExportRenderer(typeof(MyCellView), typeof(MyCellRender))]
namespace App4.UWP
{
    public class MyCellRender : ViewCellRenderer
    {
        public override Windows.UI.Xaml.DataTemplate GetTemplate(Cell cell)
        {
            return Windows.UI.Xaml.Application.Current.Resources["MyCellTemplate"] as Windows.UI.Xaml.DataTemplate;
        }
    }
}

App.xaml
<Application
    x:Class="App4.UWP.App"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:App4.UWP"
    RequestedTheme="Light">
    <Application.Resources>
        <ResourceDictionary>
            <DataTemplate x:Key="MyCellTemplate">
                <StackPanel>
                    <Grid>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="0.2*" />
                            <ColumnDefinition Width="*" />
                        </Grid.ColumnDefinitions>
                        <Grid.RowDefinitions>
                            <RowDefinition Height="35" />
                        </Grid.RowDefinitions>
                        <TextBlock Grid.Column="1" Text="{Binding Name}" FontSize="18" />
                        <Image Grid.Column="0" Source="{Binding ImageFilename}" Height="30" />
                    </Grid>
                </StackPanel>
            </DataTemplate>
        </ResourceDictionary>
    </Application.Resources>
</Application>

A: On UWP I make IValueConverter
ImageExtensionConverter.cs
public class ImageExtensionConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, string language)
    {
        var fileName = value as string;
        if (fileName == null)
            return null;
            return string.Concat("ms-appx:///", fileName);
    }

    public object ConvertBack(object value, Type targetType, object parameter, string language)
    {
        throw new NotImplementedException();
    }
}

and change App.xaml in UWP:
<Application
    x:Class="App4.UWP.App"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:App4.UWP"
    RequestedTheme="Light">
    <Application.Resources>
        <ResourceDictionary>
            <DataTemplate x:Key="MyCellTemplate">
                <StackPanel>
                    <Grid>
                        <Grid.Resources>
                            <local:ImageExtensionConverter x:Name="ImageExtensionConverter" />
                        </Grid.Resources>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="0.2*" />
                            <ColumnDefinition Width="*" />
                        </Grid.ColumnDefinitions>
                        <Grid.RowDefinitions>
                            <RowDefinition Height="35" />
                        </Grid.RowDefinitions>
                        <TextBlock Grid.Column="1" Text="{Binding Name}" FontSize="18" />
                        <Image Grid.Column="0" Source="{Binding ImageFilename, Converter={StaticResource ImageExtensionConverter}}" Height="30" />
                    </Grid>
                </StackPanel>
            </DataTemplate>
        </ResourceDictionary>
    </Application.Resources>
</Application>


text:
Q: Call ASP from Javascript I'm trying to figure out, how can i call ASP (NOT asp.net) site/page/etc with javascript.
The ASP is external file and JS is inside of HTML code.
ASP function is intended to use delete function, which deletes selected row from database.
How can i do it without changing the page in browser?
And PLEASE, tell me, if you know some another way to do this, i'm still learning ASP.
Thank You!

A: There are a few ways to do this, but by far the most common way is to use XMLHttpRequest, often called AJAX. For example:
var xhr = new XMLHttpRequest();
xhr.open("POST", "delete.asp", true);
xhr.send("id=" + rowID);


text:
Q: Control isn't getting the Selected value from DropDownListFor I got the following Model:
public class ViewBloqueioNotaFiscal
{

   public ViewComboStatus ComboStatus = new ViewComboStatus();

   public class ViewComboStatus
   {
      public int? IdStatusSelecionado { get; set; }
      public IEnumerable<SelectListItem> ComboStatus { get; set; }
   }
}

The following controller method:
public ViewBloqueioNotaFiscal.ViewComboStatus geraComboStatus(int? statusSelecionado)
{
   ViewBloqueioNotaFiscal.ViewComboStatus combo = new ViewBloqueioNotaFiscal.ViewComboStatus
   {
       IdStatusSelecionado = statusSelecionado,
       ComboStatus = new[]{
                     new SelectListItem { Value = 1, Text = "Op1"},
                     new SelectListItem { Value = 2, Text = "Op2"}
        }
   };
   return combo;
}

And my aspx is like:
<%: Html.DropDownListFor(x => x.ComboStatus.IdStatusSelecionado, Model.ComboStatus.ComboStatus) %>

Its getting perfectly displayed for selection but when I submit my form, my post method from controller gets the model perfectly with the values except for this combo that Im recieving null value into the model. As its the first one that I try, I think that something is wrong.
Could you guys check that for me? If you have any better solution for this I d like to know too.
thanks for the help !

A: You are not binding to the correct property of your view model. You are binding to some complex object (ComboStatus) which doesn't make sense.
You should bind the drop down list to the IdStatusSelecionado property:
<%: Html.DropDownListFor(
    x => x.ComboStatus.IdStatusSelecionado,
    Model.ComboStatus.ComboStatus
) %>

A strongly typed DropDownListFor helper requires at least 2 things on your view model:

*

*A scalar property (int, decimal, string, ...) which will be used to bind to

*A collection of value/text pairs.

If the collection of value/text pairs contains an item whose value is equal to the scalar property you used as first argument, this item will be preselected. For example if you wanted to preselect the second item in your example you would set IdStatusSelecionado=2 on your view model.
Side note: Model.ComboStatus.ComboStatus looks terrible. Please rename.


text:
Q: Where does CUDA allocate the stack frame for kernels? My kernel call fails with "out of memory". It makes significant usage of the stack frame and I was wondering if this is the reason for its failure.
When invoking nvcc with --ptxas-options=-v it print the following profile information:
    150352 bytes stack frame, 0 bytes spill stores, 0 bytes spill loads
ptxas info    : Used 59 registers, 40 bytes cmem[0]

Hardware: GTX480, sm20, 1.5GB device memory, 48KB shared memory/multiprocessor.
My question is where is the stack frame allocated: In shared, global memory, constant memory, ..?
I tried with 1 thread per block, as well as with 32 threads per block. Same "out of memory".
Another issue: One can only enlarge the number of threads resident to one multiprocessor if the total numbers of registers do not exceed the number of available registers at the multiprocessor (32k for my card). Does something similar apply to the stack frame size?

A: Stack is allocated in local memory. Allocation is per physical thread (GTX480: 15 SM * 1536 threads/SM = 23040 threads). You are requesting 150,352 bytes/thread => ~3.4 GB of stack space. CUDA may reduce the maximum physical threads per launch if the size is that high. The CUDA language is not designed to have a large per thread stack.
In terms of registers GTX480 is limited to 63 registers per thread and 32K registers per SM.

A: Stack frame is most likely in the local memory.
I believe there is some limitation of the local memory usage, but even without it, I think CUDA driver might allocate more local memory than just for one thread in your <<<1,1>>> launch configuration.
One way or another, even if you manage to actually run your code, I fear it may be actually quite slow because of all those stack operations. Try to reduce the number of function calls (e.g. by inlining those functions).


text:
Q: When editing the question, option to notify all answer-authors? Hello, I recently added a question to the site and then after getting 3 answers realized I wanted to ask another question in the same context that was so similar that I'd prefer the two to stay together. (Kinda like "how does Foo affect Bar" and then thinking "How does Bar affect Foo")
I have seen a feature request for a notification to be sent to all answer-authors when the question is changed. This can add a lot of noise notifications though. For instance, on the Books About Unicorns question with 80 answers, if all you want to do is make a slight spelling correction on the question it would notify 80 people. These 80 people of course do not care.
So I suggest a new feature. The "Notify Answer-Authors" checkbox. When editing, you can check this box and it will give a notification to all answer-authors that the question has changed so that they can update their answers accordingly.
I suggest these rules though:

*

*Only the question-author can check it (or maybe a new 5k rep power?)

*If an question is owned by the community, then it is not available

*If the question has more than 15 answers total, or more than 5 answers with 2 or more votes then the box is not available(which implies that they should make a new question since there are "good" answers on this one already)

*Answers owned by the community do not get notified.

*Possibly provide an opt-out checkbox for answer-authors(either per-answer or in their profile). I can't see any real use for this though other than people like Jon Skeet who would get 10 of these notifications per hour.

A: Not just "No.", but "Hell, No!".
This is a matter of etiquette: you owe the authors of the existing answers a reasonable chance to profit from their efforts. Providing a tool to facilitate bad manners is strongly counter-indicated.
If you wrote the wrong question and don't fix it instantly, you have two choices:

*

*If the change is small, go ahead and change it. But, don't change the text so that the original question is no longer evident, and do admit to the change upfront. Plus, you are now obligated to defend the people who answered you original question from spurious downvotes.

*If the change is large or would render some answers completely wrong, you're stuck with the original version. Let that be a lesson to you on the value of asking questions carefully in the future. You can ask a followup, though you'd be well advised to link the first version and explain that you asked the wrong variant the first time.

A: I completely agree. I have often edited a question slightly, enough to change the meaning a bit, and wished the answerers would change their answers.
I'd upvote this question except I have no up button.


text:
Q: Why is this constructor code getting hit? I have a class with some definitions in the constructor:
public class Card
{
    public Card()
    {
        DateCreated = DateTime.Now;
    }
    public virtual DateTime DateCreated { get; set; }

}

If I call the following:
_repository.GetCard(cardId);

Where _repository contains this:
public Card GetCard(int cardId)
    {
        var card = _db.Cards.FirstOrDefault(s => s.CardId == cardId);  // happens immediately after this is hit
        if (card != null) return card;
        return null;
    }

The constructor code is getting hit (I set a breakpoint).  Why is this?  I'm new to C# - I was expecting the constructor to get hit only when objects are created via something like var newCard = new Card();.
This is causing problems for me right now because with some objects, I create new objects in the constructor (like history entries to log entity creation) - way too many objects are getting created right now because the constructor code is getting hit so often.
_db code:
public class AppDbContext : DbContext, IAppDbContext
{

    public AppDbContext() : base("name=TestConnection")
    {

    }

    public AppDbContext(string connectionString) : base(connectionString)
    {

    }

    public DbSet<Card> Cards { get; set; }

    void IAppDbContext.Save()
    {
        SaveChanges();
    }

    IQueryable<Card> IAppDbContext.Cards
    {
        get { return Cards; }
    }

 }

A: You are using EntityFramework for retrieving your items from the database. When retrieving them, EF has to create instances of your class to return the data to you. When it creates the instances, it obviously will trigger your constructor. How else could it return instances of your class to you? So somewhere deep inside EF it will call var entity = new TEntity();, where TEntity being your Card class.
That's also why EF requires your model objects to have a parameterless constructor.


text:
Q: How to bind to array objects in vue? I have a data array that I want to bind input element entry (integers) into data fields, and then total them.  This is akin to a spreadsheet where it can compute the sum or difference of different values specified in the same column.
I don't understand from vue.js documentation, what it takes to make two-way data binding work on these array objects.  I can't tell if the values are updating in the array.  Either they aren't updating the array, or the summation link is not being updated.  Do you have a recommendation for determining if the data binding is broken, or why the expression is not getting updated?

    {{ row.name }}

            <input :class="poweritemclass(row)" type="number" :tabindex="tabindex(powerIndex, turn)" :value="calculatepower(powerIndex, turn)" />

            <input :class="poweritemclass(row)" type="number" :tabindex="tabindex(powerIndex, turn)" :value="row.turns[turn]" />

Here is the js fiddle: https://jsfiddle.net/ledlogic/fst561by/

A: You need to use v-model instead of :value for 2 way binding
I assume you want to calculate total value automatically. You only need to change:

     <input :class="poweritemclass(row)" type="number" :tabindex="tabindex(powerIndex, turn)" v-model="row.turns[turn]" />

Demo https://jsfiddle.net/ittus/1z6qu43y/

A: Fisrt of all - you are missing v-model which is necessary for two way binding.
I suggest you try and understand the concept of v-model first:

You can use the v-model directive to create two-way data bindings on
form input, textarea, and select elements.

Please note that:
-

v-model will ignore the initial value, checked or selected attributes
found on any form elements. It will always treat the Vue instance
data as the source of truth. You should declare the initial value on
the JavaScript side, inside the data option of your component.

*

*

For languages that require an IME (Chinese, Japanese, Korean etc.),
you'll notice that v-model doesn't get updated during IME composition.
If you want to cater for these updates as well, use input event
instead.

Now for your example:
What it should look like is:

    {{ row.name }}

            <input :class="poweritemclass(row)" type="number" :tabindex="tabindex(powerIndex, turn)" v-model="calculatepower(powerIndex, turn)" />

            <input :class="poweritemclass(row)" type="number" :tabindex="tabindex(powerIndex, turn)" v-model="row.turns[turn]" />

I'd suggest you to look at this post for better context.


text:
Q: access variable from index.ts to a component I am new to electron and making one desktop application. In the index.ts file i am creating a window using this code.
  function createWindow(){

  win = new BrowserWindow();
  win.loadURL(`file://${__dirname}/index_beta.html`);
  win.setFullScreen(true);
  win.setMenu(null);
  return win;

  }

I have one more component where i have to resize this window object and I am struggling a lot in passing the BrowserWindow handle to the component. Is there any way using react that i can resize the window with the 'win' handle in the other component

A: Handle Browser Window Resize in React