text:
Q: How to play small sound file continuously in Silverlight? I have two questions regarding Silverlight's SoundPlay action and properties. My scenario is like:
I have two story board:
The first story board has an image and a sound file; when the silverlight application gets loaded, the sound starts to play automatically, but if someone clicks the image,
the sound file will stop and the second storyboard will start with a new sound file.
1) My first question is how to stop the first sound file of first story board when the second story board starts with the second sound file.
2) My second question is how to play a sound file continuously; for example, in Silverlight we can play a story board continuously with RepeatBehavior="Forever"; but I cannot find a way to play my 10 second sound file forever or continuously.
Note: I have attached a small XAML file to show what I am talking about; I am also stating that if instead of an image file, if there were a button, then I can stop the first music file after I click the button and start my second story board with a new sound file, but I would like to use image file instead of a button. Is it possible? If it is, how to do it?
Therefore, please answer my following two questions or give big hint or website tutorial links on
1) How to stop the first sound file of first story board when the second story board starts with the second sound file ( When the clickable element is an image instead of a button)
2) How to play a 10 second sound file continuously?
............Code Snippet......................
XAML
............
<UserControl
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    x:Class="testPrj.MainPage"
    Width="640" Height="480">
    <UserControl.Resources>
        <Storyboard x:Name="Storyboard1" RepeatBehavior="Forever"/>
        <Storyboard x:Name="Storyboard2"/>
    </UserControl.Resources>

    <Grid x:Name="LayoutRoot" Background="Red">
        <Button HorizontalAlignment="Left" Margin="212,0,0,111" VerticalAlignment="Bottom" Width="75" Content="Button" Click="onClick"/>
        <MediaElement x:Name="sound2_mp3" Height="0" HorizontalAlignment="Left" Margin="105,230,0,0" VerticalAlignment="Top" Width="0" Source="/sound2.mp3" Stretch="Fill"/>
        <MediaElement x:Name="sound1_mp1" Height="0" HorizontalAlignment="Left" Margin="190,164,0,0" VerticalAlignment="Top" Width="0" Source="/sound1.mp3" Stretch="Fill" AutoPlay="False"/>
    </Grid>
</UserControl>

...............
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace testPrj
{
    public partial class MainPage : UserControl
    {
        public MainPage()
        {
            // Required to initialize variables
            InitializeComponent();
        }

        private void onClick(object sender, System.Windows.RoutedEventArgs e)
        {
            Storyboard1.Stop();
            sound2_mp3.Stop();
            sound1_mp1.Play();

        }
    }
}

A: Both of the problems got resolved:
2) My second question is how to play a sound file continuously; for example, in Silverlight we can play a story board continuously with RepeatBehavior="Forever"; but I cannot find a way to play my 10 second sound file forever or continuously.
The problem got solved after I have added MediaEnded event handler;
Now my changed XAML code is:
..
..
...
<MediaElement x:Name="sound2_mp3" Height="0" HorizontalAlignment="Left" Margin="105,230,0,0" VerticalAlignment="Top" Width="0" Source="/sound2.mp3" Stretch="Fill" DataContext="{Binding}" MediaEnded="start" AutoPlay="True" />
        <MediaElement x:Name="sound1_mp1" Height="0" HorizontalAlignment="Left" Margin="190,164,0,0" VerticalAlignment="Top" Width="0" Source="/sound1.mp3" Stretch="Fill" AutoPlay="False" MediaEnded="start1"/>

...
...
...
And my Code behind file has:
    private void start(object sender, RoutedEventArgs e)
    {
        sound2_mp3.Position = TimeSpan.FromSeconds(0);
        sound2_mp3.Play();
    }
    private void start1(object sender, RoutedEventArgs e)
    {
        sound1_mp1.Position = TimeSpan.FromSeconds(0);
        sound1_mp1.Play();
    }

And my first question was:
1) How to stop the first sound file of first story board when the second story board starts with the second sound file ( When the clickable element is an image instead of a button)
This is doable and got solved. I do not have any idea why I have not investigated and experimented with the event types of image element. So, the conclusion is:
If the click-able element were an image, an event can be fired; for example in the following code segment I am using MouseLeftButtonUp event.
XAML
    <Image HorizontalAlignment="Left" Margin="88,239,0,118" Width="95" Source="me1.png" Stretch="Fill" MouseLeftButtonUp="imgGotClicked"/>

Code  Behind File
    private void imgGotClicked(object sender, System.Windows.Input.MouseButtonEventArgs e)
    {
          MessageBox.Show("Hello World!");
          Storyboard1.Stop();
          Storyboard2.Begin();
    }

Therefore, problem # 1 and problem # 2 both got solved. This thread's problem got solved. Therefore, it should be closed.


text:
Q: Real Time Object detection using TensorFlow I have just started experimenting with Deep Learning and Computer Vision technologies. I came across this awesome tutorial. I have setup the TensorFlow environment using docker and trained my own sets of objects and it provided greater accuracy when I tested it out.
Now I want to make the same more real-time. For example, instead of giving an image of an object as the input, I want to utilize a webcam and make it recognize the object with the help of TensorFlow. Can you guys guide me with the right place to start with this work?

A: You may want to look at TensorFlow Serving so that you can decouple compute from sensors (and distribute the computation), or our C++ api. Beyond that, tensorflow was written emphasizing throughput rather than latency, so batch samples as much as you can. You don't need to run tensorflow at every frame, so input from a webcam should definitely be in the realm of possibilities. Making the network smaller, and buying better hardware are popular options.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Deamon, Threads o What I need to use with php I have an "email sending" in my application (web). The user sends his name, email, subject and some text, and I send an email back to him (with phpmailer). This takes 10 secons (the entire process), but the validation (and response) of the information submitted just takes 2 seconds (using ajax).
¿How I can response in 2 seconds and leave the server sends the email (8 seconds) even if the user refresh the page?
I speak english very bad, sorry.

A: The best solution would be using async process.
User's request would just publish the data to some kind of message queue. (Amazon SQS, RabbitMQ).
On the other side of the queue you would have daemon running all the time. This daemon would consume messages from the queue and send emails. It can also be run in multiple instances to increase performance. Nice way to keep that daemon alive would be Supervisor (http://supervisord.org/)

                    /--- sender
Producer ----->queue---- sender
                    \--- sender
                     \-- sender


text:
Q: only change z-index of a div and not each of it's children I have a div which is overlapped by another div with a higher z-index. Each div contains similarly layered images.
When I change the z-indexes of the parent divs so that now the other div is on top, I need all their layered children in both divs to remain in their same respective orders as before, but be layered as a group according to their parent's new position.
Right now, to accomplish this, I have to change a div's z-index from 5 to 1, and it's children from 6,7,8 to 2,3,4. AND change the other div's z-index from 1 to 5, and its children from 2,3,4 to 6,7,8....
How can I change only the div's z-index? It's children will never need to change order relative to the parent div. So it seems like I shouldn't need to set each one every time.
Maybe instead of divs, I should use iframes?

A: Child elements inherit the z-index of their parent. You might need to rethink your element hierarchy or positioning to accomplish your goal with those constraints. Post your code on jsFiddle so we can have a look.
Reference: Understanding CSS z-index


text:
Q: Ajax POST-Request gets cropped I'm using the following code to perform a POST-request:
function sendAjaxRequest(text) {
  var xmlhttp;

  if (window.XMLHttpRequest) {
    xmlhttp = new XMLHttpRequest();
  } else {
    xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
  }

  xmlhttp.onreadystatechange=function() {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
      document.getElementById('results').innerHTML = xmlhttp.responseText;
    }
  }

  xmlhttp.open('POST', 'generate.php', true);
  xmlhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
  xmlhttp.send('code=' + text);
}

Where generate.php looks like this:
<?php

echo isset($_POST['code']) ? $_POST['code'] : '';

The problem now is that if I send long texts they alway get cropped. I tried to increase post_max_size in php.ini but wasn't successful. Btw I'm using XAMPP.
I'd appreciate any guidance.

A: There are generally 3 ways (in the situation you described) in which content can be limited (assuming your AJAX request is correct) :

*

*Maybe your characters are of a different format so you will need to make sure they conform (escape them if needed) to the requirements of the libraries or scripts for them to be displayed in the browser.
In this case (as @Mark said): You will need to encode the & using encodeURIComponent(yourVar) to output it properly. This will cause it to transform the & to be encoded as %26 and lead to proper output.

*PHP is limiting your content - You need to change the post_max_size in php.ini file. But you have already tried it so you should try 2.

*Apache server is limiting your content - This you can manipulate with the LimitRequestBody directive. This can be set to a limit from 0 bytes to 2 GB.


text:
Q: How can I split data read from a json file? I have this json data in data.json file.
[
"1009 2000",
"1009 2001",
"1002 2002",
"1003 2002"
]

I am looping through this data and spliting the data based on , as in the following code
var show = function () {
    var span = $('.input');
    var c = $('ul');
    $.getJSON('data/data.json', function (id) {
        var j = id.split(',');
        var hsl = j[0];
        var ny = j[1];

        $('<li>' + id + '</li>').appendTo(c);
        $(c).appendTo(span);
        console.log(hsl);
    });
}

but this gives me this error in console
Object 1009 2000,1009 2001,1002 2002,1003 2002 has no method 'split'

How can I split this data so that I could display it like this
 1009 2000
 1009 2001
 1002 2002
 1003 2002

A: You don't need to split anything, simply loop:
$.getJSON('data/data.json', function (ids) {
    for (var i = 0; i < ids.length; i++) {
        var id = ids[i];
        console.log(id);
    }
});

jQuery will automatically parse the string returned from the server as a javascript array so that you could directly access its elements.
You could split each element by the space if you want to retrieve the 2 tokens.

A: The id variable is actually the array, since getJson parses it for you. Just loop over the array and print each item.

A: Seems like you mean to say that the data being returned is a string, and you need to convert it to an array.
$.getJSON('data/data.json', function(id) {

    id = JSON.parse(id);
    for(var i=0, len=id.length; i<len; i++){
        //do your stuff here
    }
});


text:
Q: Unable to Display Check Mark in Particular row in TableView and want to set a checkmark in a UITableView first time the table is loaded with data? I am new to coding, I have a mutable array that contains nearly 20 names and I loaded that in a table view. I want to show checkmark for a particular name row in table view based on ID but am unable to do that. Please help to fix that issue.
Here I give the code what I am tried.
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    if tableView == productListTableView {
        let cell:BillTableViewCell = tableView.dequeueReusableCell(withIdentifier: "BillTableViewCell") as! BillTableViewCell
        let productName:String = (productNameArray[indexPath.row] as? String)!
        cell.productNameLbl.text = productName

        print("addIdsMutArray :",addIdsMutArray)
        print(addIdsMutArray.count)
        print("oldSelectedIDStr :",oldSelectedIDStr)

        for i in (0..<addIdsMutArray.count)
        {   var arrayCheck = NSArray()
            arrayCheck = addIdsMutArray[i] as! NSArray
            print(self.addIdsMutArray)

            if arrayCheck.contains(oldSelectedIDStr)
            {
                print("Found")
                cell.accessoryType = .checkmark
                tableView.selectRow(at: indexPath, animated: false, scrollPosition: UITableViewScrollPosition.bottom)
            } else {
                print("Not Found")
                cell.accessoryType = .none
            }
        }return cell}

A: The problem is the loop, here the solution:
  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    if tableView == productListTableView {
        let cell:BillTableViewCell = tableView.dequeueReusableCell(withIdentifier: "BillTableViewCell") as! BillTableViewCell
        let productName:String = (productNameArray[indexPath.row] as? String)!
        cell.productNameLbl.text = productName

        print("addIdsMutArray :",addIdsMutArray)
        print(addIdsMutArray.count)
        print("oldSelectedIDStr :",oldSelectedIDStr)
        //set not check for default
        cell.accessoryType = .none
        for i in (0..<addIdsMutArray.count)
        {   var arrayCheck = NSArray()
            arrayCheck = addIdsMutArray[i] as! NSArray
            print(self.addIdsMutArray)

            if arrayCheck.contains(oldSelectedIDStr)
            {
                print("Found")
                cell.accessoryType = .checkmark
                tableView.selectRow(at: indexPath, animated: false, scrollPosition: UITableViewScrollPosition.bottom)
                break;
            }
        }
        return cell
}

A: Consider this generic code that shows checkmark in every alternate cell. Edit the if condition to match yours.
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "cell")
    if indexPath.row % 2 == 0{
        cell.accessoryType = .checkmark
    }else{
        cell.accessoryType = .none
    }
    cell.textLabel?.text = dummyData[indexPath.row]
    return cell
}

This is how it looks:

The only difference is the lack of your call to selectRow(at: indexPath, animated: false, scrollPosition: UITableViewScrollPosition.bottom).
I'm not sure why this is done, but understand that at the end of the loop only the last matched cell will be selected.


text:
Q: Rails datetime_field how to remove specific weekday? I have a datetime field at my views:
 <%= form.datetime_field :start_time, selected: Date.today, min: 0.days.ago, max: 1.year.from_now%>

It allows user to select date and time only from today's day and go max to one year. So I have a question - if I can specify min and max for days in the year, can I do the same for the weekdays? For example - disable ability to choose Sundays on calendar.

A: You will not be able to do this through HTML/rails, you need to add some javascript.
Using jQuery you can do something like:
$('input[name="datetime"]').on('input', function(e){
  let day = new Date($(this).val()).getDay();
  if([# of the weekday you want to avoid].includes(day)){
    $(this).val('');
  }
});

Checkout this doc for the days of the week in integers.


text:
Q: Show that $V=\text{Ker }(P)+{\rm Im}(P)$ and $\text{Ker }(P)\cap {\rm Im}(P)=\{0_v\}$ If $P:V\rightarrow V$ is a linear map such that $P^2=P$, show that show that $V=\text{Ker }(P) + \text{Im }(P)$ and $\text{Ker}(P)\cap \text{Im }(P)=\{0_v\}$.
So I know that $\text{Ker }(P)+\text{Im }(P)\subseteq V$, since each are subspaces of $V$ and their sum is a subspace as well. But I'm having trouble showing the other direction, that $V\subseteq \text{Ker }(P) + \text{Im }(P)$.

A: For all $x\in V$ we have
$$x=\underbrace{(x-p(x))}_{\in\text{Ker } p}+\underbrace{p(x)}_{\in \text{Im } p}$$
and if $y\in \text{Ker } p\cap \text{Im } p$ then $y=p(x)$ for some $x\in V$ so
$$0=p(y)=p^2(x)=p(x)=y$$
hence
$$\text{Ker } p\cap \text{Im } p=\{0\}$$

A: For $v \in V$ write
$$v = (v-P(v)) + P(v) \in {\rm Ker} P + {\rm Im} P$$
since $P(v-P(v)) = P(v) - P(P(v)) = P(v) - P(v) = 0$

A: Hint: prove that $\text{ker }(P)\cap \text{im }(P)=\{0_v\}$. Then use the relation:
$$
\text{dim }(A+B) = \text{dim }A + \text{dim }B - \text{dim }A\cap B
$$


text:
Q: Running code on import from dynamically generated module I have used this SO answer to dynamically generate a module x and register it in sys.modules. I want a piece of code to run automatically when an import is called on this module. so for example I want print "you just imported module x". So it behaves like:
>>> import x
you just imported module x

How do I get this behavior?

A: To simply extend the example given in the selected answer you could something like this.
print "You just imported module {}".format(foo.Foo.__module__)

A: Any "orphan" code (code that isn't written inside a class or a function, or inside an if __name__ == '__main__:' block) will be executed when you import the module.


text:
Q: Error with stripe webhooks not incoming in correct order I've been using the stripe_event gem for webhooks from stripe and today I found out that the webhooks seem to be not incoming in the right order. I'm storing a local copy of the charges made on stripe and I have the following setup
StripeEvent.configure do |events|
  events.subscribe 'payment_intent.created', CreateChargeRecord.new
  events.subscribe 'payment_intent.processing', UpdateChargeRecord.new
  events.subscribe 'payment_intent.succeeded', UpdateChargeRecord.new
end

Looking at the stripe dashboard the event payment_intent.created is always done before payment_intent.processing. Now I'm creating the charge record as follows
class CreateChargeRecord
  def call(event)
    charge_object = event.data.object
    Charge.create(
      user: User.find_by(stripe_id: charge_object.customer),
      receiver_id: User.find_by(merchant_id: charge_object.transfer_data.destination).id,
      amount: charge_object.amount / 100,
      currency: 'eur',
      application_fee_amount: charge_object.application_fee_amount / 100,
      status: charge_object.status,
      stripe_id: charge_object.id
    )
  end
end

and updating as follows
class UpdateChargeRecord
  def call(event)
    charge_object = event.data.object
    charge = Charge.find_by(stripe_id: charge_object.id)
    charge.update!(status: charge_object.status)
  end
end

the problem is that from the cli it seems that the webhook payment_intent.processing is being recieved before payment_intent.created
2021-10-10 22:08:50   --> payment_intent.processing
2021-10-10 22:08:51   --> payment_intent.created
2021-10-10 22:08:51  <--  [200] POST http://localhost:3000/webhooks/
2021-10-10 22:08:51  <--  [500] POST http://localhost:3000/webhooks/

which results in an error NoMethodError (undefined method update!' for nil:NilClass):` since I'm trying to update a record that doesn't exists yet.
Is there anything I can do here to prevent this since it seems that this is not a bug according to stripe?

A: This is expected and documented -- events might be delivered out-of-order from the order in which they are generated.
To account for this, your application should be aware that this is possible and, for example, instead of using the payload you retrieve the latest object state directly from the API when the event is received.


text:
Q: class-validator doesn't appear to do anything in NestJS application I'm setting up a new NestJS application, and I've just added class-validator in order to validate controller input, but it seems to be completely ignored. This is the DTO:
import {IsString} from 'class-validator';

export class CreateCompanyDto {
    @IsString()
    name: string | undefined;
}

This is the controller:
import {
    Body,
    Controller,
    InternalServerErrorException,
    Post,
    Request,
    UseGuards, ValidationPipe
} from '@nestjs/common';
import * as admin from 'firebase-admin';
import {User} from 'firebase';
import {AuthGuard} from '../auth/auth.guard';
import {CurrentUser} from '../auth/current-user.decorator';
import {CreateCompanyDto} from './dto/create-company.dto';

@Controller('vendor')
export class VendorController {

    @Post()
    @UseGuards(AuthGuard)
    async create(@CurrentUser() user: User, @Request() req: any, @Body(new ValidationPipe({ transform: true })) company: CreateCompanyDto) {
        console.log(JSON.stringify(company));
        throw new InternalServerErrorException('meh?');

         // irrelevant code
    }

}

I would expect the code to throw a validation error and never hit the method itself, but instead it runs into the exception, and the object is logged exactly as it came in.
package.json:
{
    "name": "functions",
    "scripts": {
        "lint": "tslint --project tsconfig.json",
        "prebuild": "(cd src && rm settings.json && ln -s ../configs/prod.json settings.json)",
        "build": "tsc",
        "prebuild:dev": "(cd src && rm settings.json && ln -s ../configs/dev.json settings.json)",
        "build:dev": "tsc",
        "serve": "concurrently \"npm run build:dev -- --watch\" \"firebase emulators:start --only functions\"",
        "shell": "npm run build && firebase functions:shell",
        "start": "npm run shell",
        "deploy": "firebase deploy --only functions",
        "logs": "firebase functions:log"
    },
    "engines": {
        "node": "8"
    },
    "main": "lib/functions/src/index.js",
    "dependencies": {
        "@elastic/elasticsearch": "^7.6.0",
        "@nestjs/common": "^6.11.11",
        "@nestjs/core": "^6.11.11",
        "@nestjs/platform-express": "^6.11.11",
        "@types/airtable": "^0.5.7",
        "@types/nodemailer": "^6.4.0",
        "airtable": "^0.8.1",
        "class-transformer": "^0.2.3",
        "class-validator": "^0.11.0",
        "cors": "^2.8.5",
        "express": "^4.17.1",
        "firebase": "^7.10.0",
        "firebase-admin": "^8.9.2",
        "firebase-functions": "^3.3.0",
        "nodemailer": "^6.4.4",
        "reflect-metadata": "^0.1.13",
        "rxjs": "^6.5.4",
        "slugify": "^1.4.0"
    },
    "devDependencies": {
        "concurrently": "^5.1.0",
        "tslint": "^6.0.0",
        "typescript": "~3.7.5"
    },
    "private": true
}

What am I missing here?
Update
I did a little debugging, and I can tell where it's going wrong, even though I still don't know why.
In the ValidationPipe.transform method, it returns the raw input, because metatype is undefined:
    async transform(value, metadata) {
        const { metatype } = metadata;
        if (!metatype || !this.toValidate(metadata)) {
            return value;
        }

        // ...
    }

A: Ok, the debugging gave me enough info to find the issue on Google, where I found this Github issue: https://github.com/nestjs/nest/issues/690
You need to enable "emitDecoratorMetadata": true in your tsconfig.json file for this to work.

A: in main.ts add app.useGlobalPipes(new ValidationPipe());:
import { ValidationPipe } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';

async function bootstrap() {
    const app = await NestFactory.create(AppModule);
    app.enableCors();
    app.useGlobalPipes(new ValidationPipe());
    await app.listen(process.env.PORT || 3000);
}

bootstrap();

A: In my case the validations did not work as I did not have the class-transformer dependency in my application. Hope this helps someone.
You need both class-validator and class-transformer

$ npm i --save class-validator class-transformer


text:
Q: change p tag class with multiple drop downs can someone tell me how to have multiple dropdown, consisting of size, weight, font clolor, and font family.
Once the user selects one from each drop down, the click submit and the p or div element is changed?
i have code for one, but not sure how to change multiple? i also need to changing to the button on click and the display appears in a p tag instead of the actual button.
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>JS Change Class</title>
<style type="text/css" media="screen">
.red { border: 1px solid red; }
.blue { border: 1px solid blue; }
.green { border: 1px solid green; }
</style>
</head>

<body>

<select id="colors">
    <option value="red">Red</option>
    <option value="blue">Blue</option>
    <option value="green">Green</option>
</select>

<input type="button" class="red" value="This is a button" id="button" />

<script type="text/javascript" charset="utf-8">

var colors = document.getElementById('colors');
var button = document.getElementById('button');

addEvent(colors, 'change', function() {
    button.className = colors.value;
});

// Based on the lessons from Nettuts
function addEvent(obj, evt, fn) {
    evt = evt.replace('on', '');
    if( obj.attachEvent )
        obj.attachEvent('on' + evt, fn);
    else
        obj.addEventListener(evt, fn, false);
}

</script>

</body>
</html>

**update:
i want to add, three more drop downs, size x3 options, font-family x3 options and font weight x3 options.
the user should be able to selct from each, then click the submit button and it will display in a p tag.

A: Using jQuery, change this line:
button.className = colors.value;

to this:
$(":button").each(function(){
   this.className = colors.value;
})


text:
Q: Genymotion increase internal storage space I'm running out of internal storage space on my Genymotion emulator.

Strange thing is when looking at properties of this emulator in virtual box I see that it has 16gb external memory.

 How can I increase the storage size so that I can install more apps without deleting existing ones.

A: Shortly, you can increase internal space. But it much more complicated than just resize virtual disk of your VM.
First of all, you increase the size of android_data_disk.vmdk. Here you need copying it several times to convert to vdi format (only vdi size can be changed) and vice versa to get large enough vmdk disk.
After that, you should use another VM to get access to a filesystem on vmdk and resize it. The easiest way is using Ubuntu.
Finally, you can replace android_data_disk.vmdk in your Android VM onto one which you resize.
I am the author of the original tutorial on the Reddit. Full tutorial too long to be placed here, because it contains a lot of screenshots. I leave the link onto this tutorial. Genymotion increase internal storage space


text:
Q: Hbase Testing Utility dependency issue with ZKTestingUtility Trying to use HbaseTestingUtility in Scala 2.12.8 and I get
Class org.apache.hadoop.hbase.HBaseZKTestingUtility not found - continuing with a stub.
      new HBaseTestingUtility()

sbt imports
val hbaseVersion = "2.1.3"
val hadoopVersion = "3.2.0"

libraryDependencies ++= Seq(
  "org.apache.hbase" % "hbase-common" % hbaseVersion % Test classifier "tests",
  "org.apache.hbase" % "hbase-client" % hbaseVersion % Test classifier "tests",
  "org.apache.hbase" % "hbase-server" % hbaseVersion % Test,
  "org.apache.hbase" % "hbase-server" % hbaseVersion % Test classifier "tests",
  "org.apache.hbase" % "hbase-hadoop-compat" % hbaseVersion % Test,
  "org.apache.hbase" % "hbase-hadoop2-compat" % hbaseVersion % Test,
  "org.apache.hbase" % "hbase-hadoop-compat" % hbaseVersion % Test classifier "tests",
  "org.apache.hbase" % "hbase-hadoop2-compat" % hbaseVersion % Test classifier "tests",
  "org.apache.hbase" % "hbase-testing-util" % hbaseVersion
)


text:
Q: How to I create Jira tickets for broken Jenkins pipelines? I want to automate the creation of Jira tickets for each broken pipeline build in Jenkins.
How can I do this? Does anyone has a working groovy example to to use inside Jenkinsfile?

A: One possible solution can be wrapping all sensitive steps in try-catch. And use Jira REST API for creating of a new tickets.


text:
Q: Analytically controlling sizes in modular arithmetic to demonstrate Dirichlet pigeonhole application Given $a,b,c,d\in\mathbb Z$ with $ad+bc=p$ a prime there is an $m\in\mathbb Z$ with $-\lceil1+\sqrt{p}\rceil<
r_1,r_2<\lceil1+\sqrt{p}\rceil$ and
$$r_1\equiv mac\bmod p$$
$$r_2\equiv mbd\bmod p$$
where $r_1,r_2$ are interpreted as in $[-\frac p2,\frac p2]$ by Dirichlet's pigeonhole principle.

*

*Is there any closed form for such an $m$ and hence $r_1$ and $r_2$ as well?

*Can we canonize an expression that provides an unique $m$ that works for a given $a,b,c,d$ at least under unimodular condition of $ad-bc=1$ (there may be multiple $m$'s however I am asking if we can isolate an expression that works always providing an unique $m$)?

*Say if 1. and 2. fails then at least is there a $\mathsf{polylog}(|a|+|b|+|c|+|d|)$ time algorithm to find such an $m$ that does not involve linear integer programming (with linear integer programming there is Lenstra's method which is not very practical)?

A: For 3. one might use the $LLL$ algorithm to find the shortest vector to the row space of the equations $$\begin{bmatrix}bd&-ac&-p\\1&0&0\\0&1&0\end{bmatrix}\begin{bmatrix}r_1\\r_2\\k\end{bmatrix}=\begin{bmatrix}0\\r_1\\r_2\end{bmatrix}.$$


text:
Q: Filter data based on Taxonomy value I am building a search web part in which, I am filtering the data from the SharePoint document library based on the value in the skillset column.
It is a managed metadata column.
Below is the structure of the single record.
ID: 746
OfficeLocation: {Label: "India", TermGuid: "7f1ef83c-0dbd-463d-8fda-5d1ea4506bb5", WssId: 5}
Skillset: (4) [{…}, {…}, {…}, {…}]
Title: null

The skillset is again an array of objects as below.

0: {Label: "ASP.Net", TermGuid: "0207fb4e-cff9-43b9-8c27-2225ff2bde78", WssId: 24}
1: {Label: "Java", TermGuid: "4b01e476-0864-434b-9dfe-d576b4451c3f", WssId: 7}
2: {Label: "Javascript", TermGuid: "1d0c4e05-c1f6-4f3a-accd-66e5f334d3f0", WssId: 32}
3: {Label: "SQL Server", TermGuid: "4626fe15-bc26-462a-bc6c-9d1701ba14ed", WssId: 30}

Here, I want to filter these records based on the skillset value.
So, if I enter "java" as my search keyword then only those records should come which has the skillset label value as "java".
Currently, I used the .some function which returns the records who has the skillset javascript because it contains the word java in it.
pdfItems.filter(
 (f) =>
  f.Skillset.length > 0 &&
  f.Skillset.some((s) => s.Label == element.name)
  )

Can anyone help here to filter the data with the exact skillset?

A: Please try the below code in browser console:
var pdfItems = [{ID:1,
Skills: [{Label: "ASP.Net", TermGuid: "0207fb4e-cff9-43b9-8c27-2225ff2bde78", WssId: 24},
{Label: "Java", TermGuid: "4b01e476-0864-434b-9dfe-d576b4451c3f", WssId: 7},
{Label: "Javascript", TermGuid: "1d0c4e05-c1f6-4f3a-accd-66e5f334d3f0", WssId: 32},
{Label: "SQL Server", TermGuid: "4626fe15-bc26-462a-bc6c-9d1701ba14ed", WssId: 30}]},
{ID: 2,Skills: [{Label: "ASP.Net", TermGuid: "0207fb4e-cff9-43b9-8c27-2225ff2bde78", WssId: 24}]}];

 console.log(pdfItems.filter( (f) => f.Skills.length > 0 && f.Skills.filter(s=>s.Label== "Java").length>0)));

It will return only one object in which skills have 'Java'.
I think this question rightfully belongs to stake overflow site. :)


text:
Q: Cocoa Interface Builder - Number Formatter Bug? I am trying to put in a range using a Number Formatter component added to a text file. The problem occurs when I input a consistent sequence of number '9'. The field will keep on adding to what is in there ( i .e. 99999999999) up to a 10th number, and then the field will be changed to a random 6 digit number?
Is that a bug with the Number Formatter? Any workarounds?
Also, can I create my own number formatter? That would be the best if a bug does exist I think.
Thanks!

A: I have tried the same thing on another version of Xcode and it seems to works fine.. Maybe a problem with that version's number formatter..
Thanks for your help.


text:
Q: How to determine if there are any event handlers for DataGridView.CellFormatting event? I'm writing a control which inherits from a DataGridView. One of the things I would like to do is to handle the bug whereby a column's format provider is not used without handling the CellFormatting event (and doing the formatting myself).
I thought I would write an "OnCellFormatting" method which says "if there's a column format provider, and there's no CellFormatting event handler(s), do the formatting".
The important bit (I thought) was "...and there's no CellFormatting event handler".
Now, in the past when I've written controls with events, I've done something like this:
  public event EventHandler SomethingHappened;

  protected void OnSomethingHappened(EventArgs e)
  {
     EventHandler handler = this.SomethingHappened;
     if (handler != null) handler(this, e);
  }

This works fine and my understanding is that this pattern determines if handlers are attached to the event and, if so, invoke those handlers. Fair enough, but why can't I do this:
  protected void OnCellFormatting(EventArgs e)
  {
     EventHandler handler = this.CellFormatting;
     if (handler == null) DoSomething();
  }

The error is "The event 'System.Windows.Forms.DataGridView.CellFormatting' can only appear on the left hand side of += or -="
What's different about this (type of) event ?
If I go to the definition of the event, and create my own, ie.
public event DataGridViewCellFormattingEventHandler CellFormatting2
...the compiler is quite happy to assign this to my "handler" variable, so my question is - what's different with the CellFormatting event (and, one presumes, many others) that I cannot determine if there are any event handlers for it ?
Thanks,
Ross

A: Only the class that declares the event has full access to it.
For instance, you cannot invoke an event from other classes - even derived ones.
You are in this situation, because you are deriving from DataGridView.

You may be able to use reflection:
How do I raise an event via reflection in .NET (c#)?
MSDN: Type.GetEvent Method

A: That shows the assignment can't be performed because it's read only. May be you can try declaring the handler private?


text:
Q: Express: while generating a pdf with pdfkit all other requests are blocked With the following code, when /pdf is requested, express stops serving all the other pages until the pdf is generated. How can I make the PDF generation synchronous? Thanks.
app.get('/pdf', function (req, res) {
  var publication_id = req.query['id'] // e.g. http://localhost:3000/pdf?id=I1519673917344
  var booklet = req.query['booklet'] // e.g. http://localhost:3000/pdf?id=I15196739173440&booklet=true

  const canvasWidth = 450
  const canvasHeight = 636
  const pageWidth = canvasWidth/1.34
  const pageHeight = canvasHeight/1.34

  var canvases = []
  var _publication

  const tasks = [
    function findPublication(callback) {
      Publication.findOne({ 'id': publication_id }, function (err, publication) {
        if (err) return console.error(err)
          _publication = publication
        console.log('found pub')
        callback(null)
      })
    },
    function makeCanvases(callback) {
      for (var i = 1; i < 9; i++) {
        var canvas = new fabric.StaticCanvas('c') // random name
        canvas.setWidth(canvasWidth)
        canvas.setHeight(canvasHeight)
        if ( _publication && _publication.pages.hasOwnProperty('p' + i) ) { // if not empty
          var pages = _publication.pages
          canvas.loadFromJSON(pages['p' + i]);
        }
        canvases.push(canvas)
      }
      console.log('made canvases')
      callback(null)
    },
    function makePdf(callback) {

      res.writeHead(200, {
        'Content-Type': 'application/pdf',
        'Access-Control-Allow-Origin': '*',
        'Content-Disposition': 'filename=' + publication_id + '.pdf'
      });

      if (booklet != 'true') {

        doc = new PDFDocument({size:[pageWidth, pageHeight]})
        var i = 0

        canvases.forEach(function(canvas) {
          SVGtoPDF(doc, canvas.toSVG(), 0, 0, {fontCallback: fonts })
          if (i != canvases.length - 1) {
            doc.addPage()
          }
          i++
        })

        doc.pipe(res).on('finish', function() {
          console.log('single page pdf was successfully created')
        })

        doc.end()

      } else {

        doc = new PDFDocument({size:[pageWidth*2, pageHeight]})

        // all the -1 to have a normal page number
        SVGtoPDF(doc, canvases[8-1].toSVG(), 0, 0, {fontCallback: fonts });
        SVGtoPDF(doc, canvases[1-1].toSVG(), pageWidth, 0, {fontCallback: fonts });
        doc.addPage()
        SVGtoPDF(doc, canvases[2-1].toSVG(), 0, 0, {fontCallback: fonts });
        SVGtoPDF(doc, canvases[7-1].toSVG(), pageWidth, 0, {fontCallback: fonts });
        doc.addPage()
        SVGtoPDF(doc, canvases[6-1].toSVG(), 0, 0, {fontCallback: fonts });
        SVGtoPDF(doc, canvases[3-1].toSVG(), pageWidth, 0, {fontCallback: fonts });
        doc.addPage()
        SVGtoPDF(doc, canvases[4-1].toSVG(), 0, 0, {fontCallback: fonts });
        SVGtoPDF(doc, canvases[5-1].toSVG(), pageWidth, 0, {fontCallback: fonts });

        doc.pipe(res).on('finish', function() {
          console.log('booklet pdf was successfully created')
        })

        doc.end()

      }
    }
  ]

  async.series(tasks, (err) => {
      if (err) {
          return next(err);
      }
  })

  console.log('serving pdf')

})


text:
Q: call php function on form submition Hi im trying to generate this a code from this php function
         <?php function generateRandomString($length = 6) {
    return substr(str_shuffle(str_repeat($x='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', ceil($length/strlen($x)) )),1,$length);
}

echo  generateRandomString(); ?>

when this   <button>Submit</button> is clicked. It is a submition button for a form in HTML
Many Thanks in advance :)

A: For help on the basics of setting up a form in HTML:
https://www.w3schools.com/html/html_forms.asp
You'll need to target your PHP script in the form action.
https://www.php.net/manual/en/tutorial.forms.php
Using the script exactly as you have it will simply send the plain text random string back to your browser.


text:
Q: .net Combining lists without a common ID Using .net/c#
I have two lists that need to be combined, one list has depths and the other list has lengths starting from the top. Both lists have many other parameters which i also need to combine into this new list. The lengths and depths do not match up.
The list needs to be ordered from top to bottom.
List 1:

Depth
Type

100
A

200
B

List 2:

Length
Size

50
1

150
2

Desired result:

StartDepth
EndDepth
Type
Size

0
50
A
1

50
100
A
2

100
200
B
2

I can come back and add code later, but i am not even sure where to begin. Every entry for combining two lists in .net talks about using a unique ID to join the lists, which i do not have.
I am hoping someone can provide me a link so that i can start researching this.


text:
Q: The fair meat bazaar: Who has right? In a local town the girl scouts have been selling tickets, and now it is the time to pick winners. The number of winners is yet to be decided. The names are collected in $3$ books. With respectively

*

*$1000$

*$ 600$

*$ 400$

names in them.
The question is without computer aid (eg the names are in physical books, too much hazzle to digitalize the results) how can one create a fair draw?
My solution is as follows (please try before looking)

 Note that all books are divisible by 200. Hence pick $5$ names from book 1, $3$ names from book $2$ and $2$ names from book $3$. Amongst these $10$ names do another draw. Note one apparent problem with this solution is if you want more than $2$ winners. Then the smallest book is at an disadvantage. If you need $n$ winners then draw $\lceil n/2 \rceil \cdot (5,3,2)$ names$...\phantom{..............}\\$ Another solution is to have the names 1-2000 ready, and then draw $n$ names from this list. But in a practical sense, is not my solution easier than writing up $2000$ notes? (Remember no fancy technology allowed, the villages does not believe in this).

The locals does not agree this is a fair solution. Instead they mean that it should not matter what book you are in. If a winner is picked from book 1 and you are in book 3, this should not affect you. They mean it is fair to draw between the books, then pick a a number in the range 1-1000. I think they are wrong in saying that is a fair draw.
Who is right? And how can one explain the correct solution in laymans terms?

A: Certainly a fair solution would be to pick $k$ numbers from $\{1,2,\ldots,2000\}$ and then
\begin{array}{c|c|c}
\text{number} & \text{book} & \text{person in the book} \\\hline
1-1000 & \mathrm{I} & n \\
1001-1600 & \mathrm{II} & n - 1000 \\
1601-2000 & \mathrm{III} & n - 1600
\end{array}
That is completely doable using pen and paper, if you don't have a way to pick a random number, throw a coin $11$ times: $2^{11} = 2048$ (if you happen to pick over $2000$ or a person picked previously, just try again; if you don't have a fair coin, throw the coin twice and interpret TH and HT as heads and tails respectively, while disregard any TT or HH as invalid throws).
As for whether you solution is fair: in general it is not. Assume there are to be two winners, and we would like to calculate the probability that some particular pair wins, which is $$\binom{2000}{2}^{-1} = \dfrac{2}{2000\cdot 1999}.$$
Observe that $1999$ is a prime number, so whatever calculation method we use, the denominator must has it as a factor. However, in your case the denominator can't have factors bigger than 1000 (unless you put it there artificially), so the prime number $1999$ does not happen, and so these numbers can't be equal.
I hope this helps $\ddot\smile$

A: dtldarek gave a good explenation why my logic was flawed. Here i present a slightly different view why I was wrong.
The good

The draw is fair under the assumption every person has bought exactly one ticket.

What do I mean by the last statement? Assume that the game only allows each person one ticket. Let $s$ be some integer. We pick then pick 2$s$ tickets from Book$_1$, $3s$ from book$_2$ and $5s$ from book$_3$. There will then be a total of $10s$ tickets picked. So you have a $1/10s$ chance of winning after getting picked out.
The chance of getting picked out is simply $s/200$. We can see this by thinking about the desired outcomes versus the possible outcomes. Eg
$$
  \frac{2s}{400}=\frac{3s}{600}=\frac{5s}{1000}=\frac{s}{200}
$$
For respectively book$_1$, book$_1$, and book$_3$. The chance of winning the final draw is done similarly. in total we have $2s+3s+5s = 10s$ tickets. You have one of those. So the chance of winning the final draw is $1/10s$. Combining these means that the total probability of winning is given as
$$
P_{1,2,3} \ = \hspace{-1.5cm}\overbrace{\frac{1}{10s}}^{\text{Chance of winning the final draw}}\hspace{-1.5cm} \cdot \hspace{-1.8cm} \underbrace{\frac{s}{200}}_{\text{Chance of getting picked from book$_n$}} \hspace{-1.6cm} = \ \ \frac{1}{2000}
$$
Which is independent of the scaling factor $s$. Picking $v$ winners instead of $1$ changes nothing. Everyone has an equal chance of getting in the final draw $s/200$. Changing the number of winners changes only the chance of winning the final draw. Say that we pick $v$ winners (note that we have $10s$ tickets in the final draw, hence $10s \geq v$. The total chance of winning will then be
$$
P_{1,2,4}(s,v) = \frac{s}{200} \binom{1}{1}\binom{10s-1}{v-1}\Big/\binom{10s}{v}
= \frac{s}{200} \cdot \frac{v}{10s}
= \frac{v}{2000}
$$
Hence the draw depends purely on the number of winners, and scales linearly.

The Bad

The draw is unfair as long as any player buys more than one ticket, and we have more than one winner.

In order of miniziming the error of this method assume that we want $s$ to be as small as possible. This is only logical. We do not want to do any more draws to get $v$ winners than neccecarily. Hence we want $10s$ to be the smalest integer larger than $v$. In other words
$$
    s \geq \left\lceil \frac{v}{10} \right\rceil
$$
Where $\lceil x \rceil$ denotes the greatest integer function (round up to nearest integer). From this point forward I define
$$
    s = \left\lceil \frac{v}{10} \right\rceil
$$
Note that for $v \in[1,10]$ then $s_v=1$. I doubt we will have more than $10$ winners with just $2000$ tickets.
This means the only variable to consider is $v$, for simplicity the notation $s_v$ is employed.To further simplify the notation we define
$$
    b_n = \frac12 x^2-\frac 12x+2
$$
Such that $b_1=2$, $b_2=3$ and $b_3=5$. Which means $200 \cdot b(n)$ gives the number of tickets in book$[n]$. Assume now that you are allowed to buy $\ell$ tickets. The chance of getting $k$ of your $\ell$ tickets picked from book $n$ kan be written as
$$
    P_n(v,\ell,k) = \binom{\ell}{k}\binom{200b_n - \ell}{s_v b_n - k}\Big/ \binom{200b_n}{s_v b_n}
$$
These probabilites can be explictly written as
$$
\begin{align*}
         P_1(v,\ell,k)
    & = \binom{\ell}{k}\binom{400 - \ell}{s_v b_n - k}\Big/ \binom{400}{2s_v} \\
         P_2(v,\ell,k)
    & = \binom{\ell}{k}\binom{600 - \ell}{s_v b_n - k}\Big/ \binom{600}{3s_v} \\
         P_3(v,\ell,k)
    & = \binom{\ell}{k}\binom{1000 - \ell}{s_v b_n - k}\Big/ \binom{1000}{5s_v}
\end{align*}
$$
Assume that you got $k$ out of $\ell$ tickets picked out. I now assume that you want to win on atleast one of these tickets. Assume that you got $k$ tickets into the final draw. The chance of winning on atleast one of these is given as
$$
      W(v,k)
    = 1 - \binom{k}{0}\binom{10s_v-k}{v}\Big/\binom{10s_v}{v}
    = 1 - \binom{10s_v-k}{v}\Big/\binom{10s_v}{v}
$$
The chance to win on $k$ out of $\ell$ tickets is therefore given as
$$
    t_n(v,\ell,k) = W(v,k) \cdot P_n(v,\ell,k)
$$
We are almost there.. This means that the chance to win on atleast one ticket is
$$
\begin{align*}
    T_n(v,\ell)
    & = \sum_{k=1}^{\large \ell} W(v,k) \cdot P_n(v,\ell,k) \cdot W(v,k) \\
    & = \sum_{k=1}^{\large \ell} \left[ 1 - \binom{10s_v-k}{v}\Big/\binom{10s_v}{v} \right] \binom{\ell}{k}\binom{200b_n - \ell}{s_v b_n - k}\Big/ \binom{200b_n}{s_v b_n}
\end{align*}
$$
This can of course also be written out explicitly for $n=1,2,3$. Without making it any prettier.
$$
\begin{align*}
    T_1(v,\ell)
    & = \sum_{k=1}^{\large \ell} \left[ 1 - \binom{10s_v-k}{v}\Big/\binom{10s_v}{v} \right] \binom{\ell}{k}\binom{400 - \ell}{2s_v - k}\Big/ \binom{400}{2s_v} \\
    T_2(v,\ell)
    & = \sum_{k=1}^{\large \ell} \left[ 1 - \binom{10s_v-k}{v}\Big/\binom{10s_v}{v} \right] \binom{\ell}{k}\binom{600 - \ell}{3s_v - k}\Big/ \binom{600}{3s_v} \\
    T_3(v,\ell)
    & = \sum_{k=1}^{\large \ell} \left[ 1 - \binom{10s_v-k}{v}\Big/\binom{10s_v}{v} \right] \binom{\ell}{k}\binom{1000 - \ell}{5s_v - k}\Big/ \binom{1000}{5s_v} \\
\end{align*}
$$
There are of course some restrictions on the variables. Obviously they must all be integers.
The probability

The draw is fair under the assumption every person has bought exactly one ticket. Otherwise the error scales with both the number of tickets bought $\ell$ and the number of prices.

As an thought experiment say you go crazy over the cute girl scouts and buy $400$ tickets. Which girl should you buy the tickets from, and does it matter how many prices there are? Say you buy the tickets from Book$[1]$, this means you are guaranteed to participate in the draw, but you only have $b_1 s_v = 3\lceil v/10\rceil$ tickets and there are $v= 10 \lceil v/10 \rceil$. Assume instead you buy from the biggest books, becuase bigger is better right? Now you only have a $400/1000$ chance to get the first ticket, but a better chance in the final draw.
The question is what weights more, being sure to get into the second round or being much better prepared if you get to the second round? Numerical analysis gives the following tables

Note that you can follow this link if the image is too small.
Conclusion
The draw is not fair, but in a normal lottery where the prices range from $1-10$, it does not matter how many tickets a person buys. Even if someone did go crazy and bought $400$ tickets the three books differ only by a couple percent. However the draw is only fair if each person is given one and only one ticket.
So if you want to have a infinitesmal better chance at winning go for the smallest book. Or if you want to be a smarty pants, suggest to pick numbers from 1-2000 instead.


text:
Q: Why does this not create a combobox? Sub Auto_Open()
Dim ComboBox2 As Object
Dim ws As Worksheet
Dim rng As Range
Const cCount As Long = 2

Set ws = ActiveSheet(1)

With ws
    Set rng = .Range("H10")

    Set ComboBox2 = .Shapes.AddFormControl(xlDropDown, _
                                          Left:=rng.Left, _
                                          Top:=rng.Top, _
                                          Width:=rng.Width, _
                                          Height:=rng.Height)
With ComboBox2
        .ControlFormat.DropDownLines = 100
        .Name = "myCombo"
End With
With Worksheets(5)
    Dim erg As Range: Set erg = .Range("D6", .Range("D" & .Rows.Count) _
        .End(xlUp)).Resize(, cCount)
    Worksheets(1).ComboBox2.ColumnCount = cCount
    Worksheets(1).ComboBox2.List = erg.Value
End With
End Sub

This code is in the workbook.
I am trying to create a combobox when someone opens this file and then have it to be populated from worsheet 5.
Its not happening, nothing is created and im also not getting any errors.

A: Try using Workbook_Open event instead of Auto_Open event (it exist for backwards compatibility), the code should be placed in ThisWorkbook object.
Private Sub Workbook_Open()
    Dim ComboBox2 As Object
    Dim ws As Worksheet
    Dim rng As Range
    Const cCount As Long = 2

    Set ws = ActiveSheet 'Avoid using ActiveSheet, replace this with the worksheet name instead

    With ws
        Set rng = .Range("H10")

        Set ComboBox2 = .Shapes.AddFormControl(xlDropDown, _
                                              Left:=rng.Left, _
                                              Top:=rng.Top, _
                                              Width:=rng.Width, _
                                              Height:=rng.Height)
    End With

    With ComboBox2
            .ControlFormat.DropDownLines = 100
            .Name = "myCombo"
    End With

    With Worksheets(5)
        Dim erg As Range
        Set erg = .Range("D6", .Range("D" & .Rows.Count) _
                    .End(xlUp)).Resize(, cCount)
    End With

    With Worksheets(1).ComboBox2
        .ColumnCount = cCount
        .List = erg.Value
    End With
End Sub


text:
Q: When I ran npm start in my terminal,I got this error error screenshot
I got this error! like this screenshot.please,thanks for your help...
I also tried npm run start, npm install, but it's does work!help me☺☺☺


text:
Q: Link Go against a static 32 bit 3rd party library I am using the flags below
#cgo CFLAGS: -I.
#cgo LDFLAGS: -L. -lcluto

#include <malloc.h>
#include "cluto.h"

and when I compile with
go build clutod.go

The compiler fails with error
/usr/bin/ld: pulando ../../../../gopkg/src/dawn/plugins/cluto/clutobot/libcluto.a incompatível ao pesquisar para -lcluto
/usr/bin/ld: não foi possível localizar -lcluto
collect2: error: ld returned 1 exit status

Which means that it finds that libcluto.a is incompatible because it is a 32 bit library and my system is compiling Go to amd64 architecture.
But when I compile with
GOARCH=386 go build clutod.go

The method defined in the same source file where 'import "C"' is defined is simply ignored.
I checked with reflect and the method does not exist:
Goose.New.Logf(5,"|methods|=%d",typ.NumMethod())
Goose.New.Logf(5,"type=%s.%s",typ.PkgPath(),typ.Name())
for j=0; j<typ.NumMethod(); j++ {
   mt := typ.Method(j)
   Goose.New.Logf(5,"%d: %s",j,mt.Name)
}

Goose.New.Logf(5,"*|methods|=%d",typPtr.NumMethod())
Goose.New.Logf(5,"*type=%s.%s",typPtr.PkgPath(),typPtr.Name())
for j=0; j<typPtr.NumMethod(); j++ {
   mt := typPtr.Method(j)
   Goose.New.Logf(5,"%d: *%s",j,mt.Name)
}

Goose.New.Logf(1,"Method not found: %s, Data: %#v",methodName,typ)
return nil, errors.New(fmt.Sprintf("Method not found: %s",methodName))

The code above produces the following output:
2021/02/21 14:33:50 {stonelizard}[New.go]<New>(296): |methods|=10
2021/02/21 14:33:50 {stonelizard}[New.go]<New>(297): type=dawn/plugins/cluto/clutobot.ServiceT
2021/02/21 14:33:50 {stonelizard}[New.go]<New>(300): 0: CRLListenAddress
2021/02/21 14:33:50 {stonelizard}[New.go]<New>(300): 1: CertKit
2021/02/21 14:33:50 {stonelizard}[New.go]<New>(300): 2: GetConfig
2021/02/21 14:33:50 {stonelizard}[New.go]<New>(300): 3: GetHost
2021/02/21 14:33:50 {stonelizard}[New.go]<New>(300): 4: GetMasterConfig
2021/02/21 14:33:50 {stonelizard}[New.go]<New>(300): 5: HttpsClient
2021/02/21 14:33:50 {stonelizard}[New.go]<New>(300): 6: ListenAddress
2021/02/21 14:33:50 {stonelizard}[New.go]<New>(300): 7: PageNotFound
2021/02/21 14:33:50 {stonelizard}[New.go]<New>(300): 8: SavePending
2021/02/21 14:33:50 {stonelizard}[New.go]<New>(300): 9: Stop
2021/02/21 14:33:50 {stonelizard}[New.go]<New>(303): *|methods|=21
2021/02/21 14:33:50 {stonelizard}[New.go]<New>(304): *type=.
2021/02/21 14:33:50 {stonelizard}[New.go]<New>(307): 0: *CRLListenAddress
2021/02/21 14:33:50 {stonelizard}[New.go]<New>(307): 1: *CertKit
2021/02/21 14:33:50 {stonelizard}[New.go]<New>(307): 2: *GetConfig
2021/02/21 14:33:50 {stonelizard}[New.go]<New>(307): 3: *GetHost
2021/02/21 14:33:50 {stonelizard}[New.go]<New>(307): 4: *GetId
2021/02/21 14:33:50 {stonelizard}[New.go]<New>(307): 5: *GetMasterConfig
2021/02/21 14:33:50 {stonelizard}[New.go]<New>(307): 6: *GetRest
2021/02/21 14:33:50 {stonelizard}[New.go]<New>(307): 7: *HttpsClient
2021/02/21 14:33:50 {stonelizard}[New.go]<New>(307): 8: *InitConn
2021/02/21 14:33:50 {stonelizard}[New.go]<New>(307): 9: *ListenAddress
2021/02/21 14:33:50 {stonelizard}[New.go]<New>(307): 10: *LoadClientCert
2021/02/21 14:33:50 {stonelizard}[New.go]<New>(307): 11: *LoadConfig
2021/02/21 14:33:50 {stonelizard}[New.go]<New>(307): 12: *NewCK
2021/02/21 14:33:50 {stonelizard}[New.go]<New>(307): 13: *NewSshClientConfig
2021/02/21 14:33:50 {stonelizard}[New.go]<New>(307): 14: *PageNotFound
2021/02/21 14:33:50 {stonelizard}[New.go]<New>(307): 15: *PingAt
2021/02/21 14:33:50 {stonelizard}[New.go]<New>(307): 16: *SavePending
2021/02/21 14:33:50 {stonelizard}[New.go]<New>(307): 17: *SetRest
2021/02/21 14:33:50 {stonelizard}[New.go]<New>(307): 18: *Start
2021/02/21 14:33:50 {stonelizard}[New.go]<New>(307): 19: *Stop
2021/02/21 14:33:50 {stonelizard}[New.go]<New>(307): 20: *Version
2021/02/21 14:33:50 {stonelizard}[New.go]<New>(310): Method not found: VP_ClusterDirect, Data: &reflect.rtype{size:0x100, ptrdata:0x100, hash:0xcfbeab05, tflag:0x7, align:0x4, fieldAlign:0x4, kind:0x19, equal:(func(unsafe.Pointer, unsafe.Pointer) bool)(nil), gcdata:(*uint8)(0x86467d8), str:85076, ptrToThis:937664}

That seems to me that when I set GOARCH=386 it disables CGO, silently ignoring any code that references to C symbols.
So, how can I statically link Go against a 32 bit (.a) library?

A: I also asked this question on Golang-nuts list and got a solution from Elias Naur:
"Go disables Cgo when cross-compiling (GOARCH is different from your native
GOARCH). You can enable Cgo manually with CGO_ENABLED=1."
So, the solution is
CGO_ENABLED=1 GOARCH=386 go build  clutod.go

After that I got some compiling errors because of missing headers, which I solved installing its 32 bit versions:
sudo apt-get install gcc-multilib

And then the linker complained about undefined reference to log (math logarith function found in libm.a).
At first I thought it was just a missing 32 bit library.
But then I found the library installed on my system.
So I thought the problem was how to show the linker how to find it. But not worked. Then I found this link linking 3rd party static libs in cgo library and realized that I it was not resolving the reference because the library that contains it was appearing first, then I switched places and it worked.
The LDFLAGS ended up this way:
#cgo LDFLAGS: -L/usr/lib32 -L . -lcluto -lm

So, the undefined references in libcluto.a got solved by put -lm after -lcluto.


text:
Q: How to only allow the current month in Month Calender I'm trying to get the month calender in my windows form to only allow the user to select days in the current month, my program uses the day selected to retrieve a line from a text file, but obviously it will read the line for day 1 or 20 etc. regardless of the month.
How do i set the properties so the monthcalender is locked to current month??
something along the lines of the below
monthCalendar.MinDate = DateTime.CurrentMonth.DaysInMonth.First;
monthCalender.MaxDate = DateTime.CurrentMonth.DaysInMonth.Last;

A: firstDayInMonth and lastDayInMonth you ccan get with this code:
DateTime today = DateTime.Today;
DateTime firstDayInMonth = new DateTime(today.Year, today.Month, 1);
DateTime lastDayInMonth = new DateTime(today.Year, today.Month, DateTime.DaysInMonth(today.Year, today.Month));


text: Q: Instalacion de Docker para Windows Hola he tratado de installar Docker en Windows pero siempre que trado de iniciarlo me sale error "Hyper-V feature is not enabled." Alguien me puede ayudar a solucionarlo?


text:
Q: Batch insertion using object mapper in Cassandra Using cassandra object mapper api wanted to do a batch persist.
for single object it's working fine.
Mapper<MyObj> mapper = new MappingManager(getSession()).mapper(MyObj.class);
mapper.save(myObj);

For batch update I tried in this way, but ideally Cassandra is thinking I am persisting a list so it's giving exception like @Table annotation was not found in List, which is the expected behavior
Mapper<List<MyObj>> mapper = new MappingManager(getSession()).mapper(List.class);
myObjList.add(myObj1)
myObjList.addd(myObj2)
mapper.save(myObjList);

Is there a way to achieve the same in cassandra using batch?
NOTE: Alternatively I can do this by repeating the first step using for loop, but I am looking for a Batch insertions @ObjectMapper.

A: There is no batch insertion utility in the Datastax object mapper framework.
You can either insert your entities one by one in a for loop, like you suggested, or look for a more advanced mapping framework, such as Achilles.

A: Here is the snippet that I wanted to summarize form @adutra discussion in the above thread.
You can take the advantage of BatchStatement which is coming with cassandra-core driver and it's very much compatible with cassandra-mapper.
Mapper<MyObj> mapper = new MappingManager(getSession()).mapper(MyObj.class);
BatchStatement batch = new BatchStatement();
batch.add(mapper.saveQuery(myObj1));
batch.add(mapper.saveQuery(myObj2));
session.execute(batch);


text:
Q: Inference in Dirichlet process mixtures via collapsed Gibbs sampling I need to cluster some data $\{x1, \ldots, x_n\}$ through a Dirichlet process mixture model.
Consider the following Dirichlet process mixture model, in which the base measure is a $NIW(\mu_0, \lambda_0, \nu_0, S)$ distribution and the random probability measure $G = \sum_{k=1}^{\infty} \pi_k \delta_{(\mu_k, \Sigma_k)}$ is constructed according to stick breaking:
$$\pi \sim GEM(\alpha)$$
$$ \{\mu_k, \Sigma_k\} \sim NIW(\mu_0, \lambda_0, \nu_0, S) $$
$$ z_i | \pi \sim \pi$$
$$x_i | Z_i, \{\mu_k, \Sigma_k\} \sim N(\mu_{z_i}, \Sigma_{z_i})$$
I need to design a collapsed Gibbs sampler. Also, I need to a posteriori estimate $\{\mu_k, \Sigma_k\}$ for all clusters in the data.
It is clear that this requires integrating out $\pi$ and $ \{\mu_k, \Sigma_k\}$, thus leading to sample only the $z_i$'s. However, it is not clear to me how to formally obtain the $\{\mu_k, \Sigma_k\}$ subsequently to the collapsed Gibbs sampling process. What about the $\pi_k$'s subsequently to the collapsed Gibbs sampling process?

A: I am not an expert in bayesian non-parametrics but I think I can help a little. Others please correct me If i am wrong.
Based on your model, you would have $\boldsymbol{\pi}, \mu, \Sigma, \boldsymbol{Z}$  as your latent variables and $\boldsymbol{X}$ as your observables. I use bold symbols to represent vectors. The objective is to find the posterior distribution $p(\boldsymbol{\pi}, \boldsymbol{Z}, \boldsymbol{\mu}, \boldsymbol{\Sigma}|\boldsymbol{X})$. Based on the Gibbs sampling procedure, you would have to sample for each latent variable
$$\pi_i \sim p(\pi_i|\boldsymbol{\pi_{-i}}, \boldsymbol{\mu},\boldsymbol{\Sigma},\ \boldsymbol{Z},\boldsymbol{X}) \\
(\mu_k, \Sigma_k) \sim p(\mu_k, \Sigma_k|\boldsymbol{\mu_{-k}},\boldsymbol{\Sigma_{-k}}, \boldsymbol{\pi},  \boldsymbol{Z}, \boldsymbol{X})\\
z_i \sim p(z_i | \boldsymbol{Z}_{-i}, \boldsymbol{\Sigma}, \boldsymbol{\mu},\boldsymbol{\pi}, \boldsymbol{X})
$$
where the $-i$, $-k$ subscript denotes the latent variables excluding the $i$-th and $k$-th variable for that vector.
Sampling $\pi_i$ is difficult because the Dirichlet Process defines an infinite number of clusters a priori. However, we don't actually need to know the mixture weights $\pi_i$ because we are interested in the cluster assignments and the parameters that define each cluster. Hence, we can do a collapsed gibbs sampling procedure by integrating out $\pi$ from the complete conditionals. Therefore, we now sample
$$
(\mu_k, \Sigma_k) \sim p(\mu_k, \Sigma_k|\boldsymbol{\mu_{-k}}, \boldsymbol{\Sigma_{-k}}, \boldsymbol{Z}, \boldsymbol{X})\\
z_i \sim p(z_i|\boldsymbol{Z}_{-i}, \boldsymbol{\mu}, \boldsymbol{\Sigma}, \boldsymbol{X})
$$
To sample from these conditional distributions, refer to Radford Neal's paper for a more detailed explanation on how to sample from dirichlet process mixture models.

*

*You can either use Gibbs sampling (if you are using Conjugate priors)
or Metropolis Hastings to sample from these conditional posteriors.

Gibbs Sampling for DPMM
Suppose that you are using conjugate priors, then when you sample $z_i$ there are two outcomes.
The first outcome is that you sample a $z_i = z$ where $z$ is already an existing cluster, the probability of this happening is given by the equation
$$
P(z_i = z|\boldsymbol{z}_{-i}, x_i, \boldsymbol{\Sigma}, \boldsymbol{\mu}) = b\frac{n_{-i,z}}{n - 1 + \alpha}F(x_i, (\mu_z, \Sigma_z))
$$
where $b$ is the normalizing constant that makes the conditional distributions sum to 1, $n_{-i,z}$ represents the number of points belonging to cluster $z$ excluding the $i$-th point $z_i$, and $F(x_i, (\mu_z,\Sigma_z))$ represents the likelihood of the point $x_i$ under the NIW distribution with parameters $\mu_z, \Sigma_z$.
The second outcome is when you sample a $z_i = z$ that is not part of an existing cluster, meaning that the point $x_i$ belongs to a new cluster.
The probability of sampling a new cluster is given by the equation
$$P(z_i = z|\boldsymbol{z}_{-i}, x_i, \boldsymbol{\mu}, \boldsymbol{\Sigma}) = b\frac{\alpha}{n - 1 + \alpha}\int F(x_i, \mu, \Sigma)dG_0(\mu, \Sigma)
$$
$\int F(x_i, \mu, \Sigma)dG_0(\mu, \sigma)$ is just the prior predictive distribution of the data point $x_i$. This integral can be computed exactly because of conjugacy in the likelihood and prior.
With these equations, you can form a complete probability distribution to sample the $z_i$'s.
To sample $(\mu_k, \Sigma_k)$, you need to sample from the posterior distribution of $\mu_k, \Sigma_k$ conditioned on all the data points belonging to cluster $k$.
Hope this helps, let me know if you have any questions and please correct me if I am wrong in some points.


text:
Q: Can`t reproduce the score after refitting TPOT regressor The exported pipeline of TPOT stating that the Average CV score on the training set was: -128.90187963562252 (neg_MAE).
However, refitting the pipeline with the same exact training set yields way smaller MAE around (35).
Moreover predicting unseen test set would yield an MAE around (140) which is in line with what the exported pipeline stating.
I am a bit confused and wondering how to reproduce the error score on the training set.
The pipeline seems to be overfitting right??
cv = RepeatedKFold(n_splits=4, n_repeats=1, random_state=1)
model = TPOTRegressor(generations=10, population_size=25, offspring_size=None, mutation_rate=0.9,
                      crossover_rate=0.1, scoring='neg_mean_absolute_error', cv=cv,
                      subsample=0.75,n_jobs=-1, max_time_mins=None,
                      max_eval_time_mins=5,random_state=42,config_dict=None, template=None,
                      warm_start=False, memory=None,
                      use_dask=False,periodic_checkpoint_folder=None, early_stop=3, verbosity=2,
                      disable_update_check=False, log_file=None)

model.fit(train_df[x], train_df[y])

# The Exported model
# Average CV score on the training set was: -128.90187963562252

exported_pipeline = make_pipeline(StackingEstimator(estimator=LassoLarsCV(normalize=True)),
                                  StackingEstimator(estimator=ExtraTreesRegressor(bootstrap=True,
                                   max_features=0.4, min_samples_leaf=1,
                                   min_samples_spli`enter code here`t=7, n_estimators=100)),
                                   PolynomialFeatures(degree=2, include_bias=False,
                                   interaction_only=False),
                                   ExtraTreesRegressor(bootstrap=True,
                                   max_features=0.15000000000000002, min_samples_leaf=9,
                                   min_samples_split=7,n_estimators=100))

# Fix random state for all the steps in exported pipeline

set_param_recursive(exported_pipeline.steps, 'random_state', 42)
exported_pipeline.fit(training_features, training_target)
results = exported_pipeline.predict(testing_features)

Thanks in advance


text:
Q: PHP dynamic previous/next links I have a table called "product".
I'm displaying all the data from PHP product view page by using the id parameter.
With my code:
if(isset($_GET['id'])) {
    $id = $_GET['id'];
}

$query = "SELECT * FROM product WHERE id = $id ";
$select_product = $db->query($query);

while($row = $db->fetch_object($select_product)) {
    $status = $row->status;

    if($status == 'published') {
        $title = $row->title;
        echo $title;
    }

}

I can pull all the data I need. In this example I can echo the title.
But how do I display a dynamic next page link? That goes same for previous link.
When I try with this code:
$query = "SELECT id FROM product";
$select_ids = $db->query($query);

while($row = $db->fetch_object($select_ids)) {
    $ids = $row->id;

    echo $ids;
}

I can see all the pages from that table. In my case they are 20,21,22...28
Next, I've tried like this:
$query = "SELECT id from product";
$select_ids = $db->query($query);

if($select_ids->num_rows > 0) {
    $next = $id + 1;
    echo 'Next';
} else {

}

With this code, my "next" link successfully goes to the next page. But, when it finishes with the result, in this case when I'm on page 28, the next dynamic link goes to empty page (29). Also this is not a good approach, because if some page, let's say 25 is deleted, the next link won't skip that page.
How can I improve that dynamic "next" link?

A: So first of all, you need two queries one for getting the data to display and another for counting the number of rows, also we'll need some additional variables.
Here comes the code:
$page = 1;
if(isset($_GET['page'])) {
    $page = $_GET['page'];
}

$numberOfResultsPerPage = 10;
$offset = $numberOfResultsPerPage * ($page - 1)

$count = $db->query("SELECT COUNT(id) as num FROM product");
while($row = $db->fetch_object($count)) {
    $numberOfRows = $row->num;
}

$query = "SELECT id FROM product LIMIT ". $offset.", ".$numberOfResultsPerPage;
$select_ids = $db->query($query);

while($row = $db->fetch_object($select_ids)) {
    $ids = $row->id;
    echo $ids;
}
if($page > 1) {
    echo 'Prev';
}
if($page < ceil($numberOfRows / $numberOfResultsPerPage)) {
    echo 'Next';
}

UPDATE:
In case you need to just find the next and previous product of the product this is the solution. It is not good if you'll have lots of products but in case the number of products is under 1000 there should not be any problems:
if(isset($_GET['id'])) {
    $id = $_GET['id'];
}

$query = "SELECT id from product";
$select_ids = $db->query($query);

$ids = array();
$i = 0;
while($row = $db->fetch_object($select_ids)) {
    $ids[$i] = $row->id;
    if($row->id == $id) {
        $index = $i;
    }
    $i++;
}
if(isset($ids[$index-1])) {
    echo 'Prev';
}
if(isset($ids[$index+1])) {
   echo 'Next';
}


text:
Q: Invalid XML in a varbinary(max) column in SQL Server 2005 So I got a varbinary(max) column in SQL Server 2005 and it's full of XML. A few records somewhere have truncated XML so they're invalid.
This means if I run a
SELECT CAST(myVarbinaryColumn as XML) ...

it blows chunks.
How can I filter out/skip invalid xml ?
When I've done similar with a varchar that supposedly has dates I could use ISDATE(blah) = 1. So an equivalent ISVALIDXML() would be nice.
Please don't comment about "Why isn't the column XML datatype anyway.." This happened in the past and I don't have a time machine.

A: I wish I had that IsValidXML() function, too..... unfortunately, I don't think there's anything like that.....
Just a thought: is there anything you could check for to filter out the invalid XML??
E.g. could you filter out all those strings that don't end in .....</data> or something like that?? (seeing that you say your invalid XML is typically truncated XML, so I would think the closing tag - </data> or whatever - would be missing in those cases).

A: I think your best bet would be to write a custom CLR function, perhaps using XmlDocument.Load. In the CLR you could trap the error on a failed load and return an appropriate result.
EDIT: The code below would also work although it's not as elegant as a UDF. Unfortunately, we can't use TRY/CATCH in a UDF.
create procedure dbo.usp_IsValidXML(@XMLCandidate varbinary(max), @Return bit output)
as
begin
    declare @x xml
    begin try
        set @x = cast(@XMLCandidate as xml)
        set @Return = 1
    end try
    begin catch
        set @Return = 0
    end catch
end
go

declare @test1 varbinary(max)
declare @test2 varbinary(max)
set @test1 = cast('<data>asdf</data>' as varbinary(max))
set @test2 = cast('<data>asdf</da' as varbinary(max))

declare @IsValid bit
exec dbo.usp_IsValidXML @test1, @IsValid output
select @IsValid
exec dbo.usp_IsValidXML @test2, @IsValid output
select @IsValid

drop procedure dbo.usp_IsValidXML


text:
Q: Earth orbit simulation has incorrect speed I'm very new to programming and I've gotten a school assignment for which I have to create a simulation of the earths orbit around the sun in p5.js . We were offered a simplified way to compute the gravitational pull but I wanted to use the actual formula (Fg = GMm/r^2). In my code, one pixel equals 10^9 meters or a million km. If I use the actual masses of both the sun and the earth, as well as the actual distance between them, I have to put the speed at which the earth travels at around 1 pixel per second or a million km/s, which is around 30,000 times the actual speed of the earth in orbit. My code:

x = 550;
y = 400;
vy = -1;
vx = 0;
dt = 1;
sunSize = 80;
planetSize = 10;
// 1 pixel equals 1 million km
canvasSize = 800;
starAmount = 600;

function setup() {
  frameRate(60);
  noStroke()
  solarXY = 0.5 * canvasSize;
  xSun = solarXY;
  ySun = solarXY;
  createCanvas(canvasSize, canvasSize);
  M = 1.989 * pow(10, 30);
  m = 5.972 * pow(10, 24);
  background(0);
  for (i = 0; i < starAmount; i++) {
    starX = Math.random() * canvasSize;
    starY = Math.random() * canvasSize;
    starSize = Math.random() * 3 + 1
    ellipse(starX, starY, starSize, starSize);
  }
  fill(255, 192, 0);
  ellipse(xSun, ySun, sunSize, sunSize);
}

function draw() {
  r = sqrt(sq(xSun - x) + sq(ySun - y)) * pow(10, 9);
  Fg = 6.67 * pow(10, -11) * m * M / sq(r);
  if (x >= xSun) {
    angle = atan((ySun - y) / (x - xSun));
  } else {
    angle = PI + atan((ySun - y) / (x - xSun));
  }
  xOld = x;
  yOld = y;
  Fgx = cos(angle) * Fg
  Fgy = sin(angle) * Fg
  ay = Fgy / m;
  ax = -Fgx / m;
  vy += ay * dt;
  vx += ax * dt;
  y += vy * dt;
  x += vx * dt;
  fill(30);
  ellipse(xOld, yOld, planetSize, planetSize);
  fill(0, 0, 192);
  ellipse(x, y, planetSize, planetSize);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.0.0/p5.min.js"></script>

Do you know what the cause could be? Thanks in advance.

A: You appear to have acceleration in meters per second 2, and velocity in pixels per second. Then you combine them:
vy += ay * dt;
vx += ax * dt;

Your gravitational accelerations are a billion times too strong. So your planet must move about 31,623 times faster than normal to keep a circular orbit.


text:
Q: Get lists of ID's and add on database using LINQ I have this method:
public ActionResult Complete(int id)
{
    // Validate customer owns this order
    bool isValid = storeDB.Orders.Any(
        o => o.OrderId == id &&
        o.Username == User.Identity.Name);

   bool CheckOrderValue = storeDB.Orders.Any(o => o.OrderId == id && o.Total == 0);
   int musicaID = storeDB.OrderDetails.Where(o => o.OrderId == id).Select(o => o.MusicaId).FirstOrDefault();

    if (isValid && CheckOrderValue)
    {
        int idUser = 0;
        if (Request.IsAuthenticated)
        {
            var membership = (WebMatrix.WebData.SimpleMembershipProvider)Membership.Provider;
            idUser = membership.GetUserId(User.Identity.Name);
        }

        var musicas = storeDB.Musicas.Where(x => x.MusicaId == musicaID)
                                     .Select(x => new { x.Nome, x.NomeArtista, x.genero, x.path })
                                     .ToList().First();

        var y = new UsuarioMusica()
        {
            UserId = idUser,
            MusicaId = musicaID,
            GeneroId = musicas.genero.GeneroId,
            genero = musicas.genero,
            Nome = musicas.Nome,
            NomeArtista = musicas.NomeArtista,
            path = musicas.path
        };
        if (ModelState.IsValid)
        {

            storeDB.UsuarioMusicas.Add(y);
            storeDB.SaveChanges();

        }

        return View(id);
    }
    else
    {
        return View("Error");
    }
}

I want to take a list of id's on this line:
int musicaID = storeDB.OrderDetails.Where(o => o.OrderId == id)
                                   .Select(o => o.MusicaId).FirstOrDefault();

And after this, I need to add each ID to the database.
I think that I need to make a foreach with the list musicaID, but I don't know how I'll pass each ID to add to the database.
Actually, the method is adding only the first element, I know why, is because the FirstOrDefault method.
How can I change this to add more than one ID?

A: You have to use foreach loop and save your changes when all the elements will be added. For example in this way:
public ActionResult Complete(int id)
{
    // Validate customer owns this order
    bool isValid = storeDB.Orders.Any(
        o => o.OrderId == id &&
        o.Username == User.Identity.Name);

    bool CheckOrderValue = storeDB.Orders.Any(o => o.OrderId == id && o.Total == 0);

    if (isValid && CheckOrderValue)
    {
        int idUser = 0;
        if (Request.IsAuthenticated)
        {
            var membership = (WebMatrix.WebData.SimpleMembershipProvider)Membership.Provider;
            idUser = membership.GetUserId(User.Identity.Name);
        }

        var musicaIDs = storeDB.OrderDetails.Where(o => o.OrderId == id).Select(o => o.MusicaId).ToList();

        foreach (var musicaId in musicaIDs)
        {
            var musicas = storeDB.Musicas.Where(x => x.MusicaId == musicaId)
                .Select(x => new { x.Nome, x.NomeArtista, x.genero, x.path }).ToList().First();

            var y = new UsuarioMusica()
            {
                UserId = idUser,
                MusicaId = musicaID,
                GeneroId = musicas.genero.GeneroId,
                genero = musicas.genero,
                Nome = musicas.Nome,
                NomeArtista = musicas.NomeArtista,
                path = musicas.path
            };

            if (ModelState.IsValid)
            {
                storeDB.UsuarioMusicas.Add(y);
            }
        }

        storeDB.SaveChanges();

        return View(id);
    }
    else
    {
        return View("Error");
    }
}


text:
Q: Using Social Authentication with Mobile SDK I have a hybrid mobile app that logs into a customer community.  The Community has a custom login page the provides the sso links to 3 Auth Providers i've configured (FB, Google, LinkedIn).  If the user clicks the link and successfully logs in to the social auth provider, my Reg handler is called; if the reg handler authenticates the user, everything works.
Where I have questions are where the process goes wrong:  if the login process fails, the system calls the Custom Error URL defined for the auth provider; in this case, it's a publicly accessible page within the community site that explains the login error and provides a link back to the login page - we don't want to show the OOB Salesforce error page.
It works, except as soon as the custom error page displays, it is replaced with a dialog, "Can't connect to Salesforce: the URL can't be shown".  Clicking Retry (only option) returns you to the login page.   I believe the auth manager sees that we've strayed outside the auth flow and interceeds; it works but it is ugly.  I'd like to just display the auth page.  Is there a way I can prevent this?  Some way to whitelist the error page with the auth manager?


text:
Q: Daily Reputation Limit Bug? I'm not sure if this is a duplicate or a bug / feature but looking at the following screenshot:

Shouldn't my reputation be 210 and get capped down to 200? Why 192?
I noticed this after seeing my rep going from 200 to 215 and suddenly it drops back to 192.
SO has some really strange behaviors sometimes.

A: If someone removed their upvote after you hit your cap, it would have brought it back down.
Chances are, you hit 202 rep through an accepted answer or some other uncapped reputation, and then someone removed an upvote.
Frankly, while it should be easy to explain how you got the reputation you did, due to the capping it is sometimes fairly random how much rep you get for certain answers.

A: If votes or questions/answers with them get removed after you hit the rep limit, the limit stays active, so that new upvotes still won't count. This might lead to a low limit for the day:

(This example is caused by an answer to this deleted question)

A: If an upvote is removed that affected the rep cap, after you hit the rep cap, your reputation will be adjusted correctly withing 5 minutes as part of the recent reputation changes.  So even with the rep cap in play, vote deletions will be accounted for.


text:
Q: What's the difference between jQuery's replaceWith() and html()? What's the difference between jQuery's replaceWith() and html() functions when HTML is being passed in as the parameter?

A: There are two ways of using html() and replaceWith() Jquery functions.

My Content

1.) html() vs replaceWith()
var html = $('#test_id p').html(); will return the "My Content"
But the
var replaceWith = $('#test_id p').replaceWith(); will return the whole DOM object of

My Content
.

2.) html('value') vs replaceWith('value')
$('#test_id p').html('
H1 content
'); will give you the following out put.

H1 content

But the
$('#test_id p').replaceWith('
H1 content
'); will give you the following out put.

H1 content

A: replaceWith() will replace the current element, whereas html() simply replaces the contents.
Note that the replaceWith() will not actually delete the element but simply remove it from the DOM and return it to you in the collection.
An example for Peter: http://jsbin.com/ofirip/2

A: Take this HTML code:

Hello World

Doing:
$('#mydiv').html('Aloha World');

Will result in:

Aloha World

Doing:
$('#mydiv').replaceWith('Aloha World');

Will result in:
Aloha World

So html() replaces the contents of the element, while replaceWith() replaces the actual element.

A: Old question but this may help someone.
There are some differences in how these functions operate in Internet Explorer and Chrome / Firefox IF your HTML is not valid.
Clean up your HTML and they'll work as documented.
(Not closing my  cost me my evening!)

A: It may also be useful to know that .empty().append() can also be used instead of .html(). In the benchmark shown below this is faster but only if you need to call this function many times.
See: https://jsperf.com/jquery-html-vs-empty-append-test


text:
Q: Grabbing Tumblr images and implementing the infinite scroll feature Evening,
I've come to a dead end with this, I've managed to import Tumblr post images to my theme and managed to get Infinite-Scroll function working aswell. The only problem the infinite scroll loops the tumblr images instead of getting the next set of images e.g getting offset 10 on each scroll instead of looping 10 images over and over.
Here is the code, pastebin URL: http://pastebin.com/8GTtaMeX
Any help on this would be great.

A: I did a fast example how you can do this easily with jQ
http://jsbin.com/ijehog/edit#preview
Edit: Wups failed with the offset :) http://jsbin.com/ijehog/2/edit#preview


text:
Q: Edit clipboard content with applescript in os x I'm copying a lot of source code from different projects to others and I always have to change the same terms. Is it possible to use an applescript which checks the text-content of the clipboard and replaces several keyword? I'm new to applescript so I'm not aware of how powerful applescript can be...

A: This is possible using get clipboard, set clipboard, and the text item delimiters.
get the clipboard
set the clipboard to (replacement of "this text" by "that text" for the result)

on replacement of oldDelim by newDelim for sourceString
    set oldTIDs to text item delimiters of AppleScript
    set text item delimiters of AppleScript to oldDelim
    set strtoks to text items of sourceString
    set text item delimiters of AppleScript to newDelim
    set joinedString to strtoks as string
    set text item delimiters of AppleScript to oldTIDs
    joinedString
end replacement

For more sophisticated text manipulation, I'd just call out to a shell script. The above becomes:
do shell script "pbpaste | sed 's/this text/that text/g' | pbcopy"

A: Not sure that I understood what you want to do. I reckon you want to replace multiple strings within the clipboard content, for example: "PS3 costs 200 dollars at Wallmart" to "XBox costs 180 dollars at Wallmart". The following code achieves this:
get the clipboard
set the clipboard to (replacement of "PS3" by "XBox" for the result)
on replacement of oldDelim by newDelim for sourceString
    set oldTIDs to text item delimiters of AppleScript
    set text item delimiters of AppleScript to oldDelim
    set strtoks to text items of sourceString
    set text item delimiters of AppleScript to newDelim
    set joinedString to strtoks as string
    set text item delimiters of AppleScript to oldTIDs
    joinedString
end replacement
get the clipboard
set the clipboard to (replacement of "200" by "180" for the result)
Kudos to Michael J. Barber for the original code. I know virtually nothing about coding. I just tried this modification it worked.


text:
Q: TypeError: data.map is not a function in reactjs while loading photos I've tried to create an image search application using unsplash api but it shows the error TypeError: data.map is not a function. It was working fine till last night but now it suddenly shows this error. It initially loaded the page with the images but it started showing this error when I searched for moon and went to last page. I then refreshed the page and it displays the images again but as soon as I did per_page items from 5 to 9 then it shows the error again and now it''s continously showing the error. Is it a problem with the api? but even if it was the api, it should show a blank page because I did photos: [] in the try catch block in the api call method but instead it shows the error. I'm not sure what is wrong with my code. Can someone help me please
App.js
import React, { Component } from "react";
import Pagination from "./Pagination";
import List from "./List";
import "./styles.css";
import axios from "axios";

const LOAD_STATE = {
  SUCCESS: "SUCCESS",
  ERROR: "ERROR",
  LOADING: "LOADING"
};

const appId = "N1ZIgf1m1v9gZJhledpAOTXqS8HqL2DuiEyXZI9Uhsk";

export default class App extends Component {
  constructor() {
    super();
    this.handleChange = this.handleChange.bind(this);
    this.fetchPhotos = this.fetchPhotos.bind(this);
    this.state = {
      photos: [],
      totalPhotos: 0,
      perPage: 5,
      currentPage: 1,
      loadState: LOAD_STATE.LOADING,
      search: ""
    };
  }
  handleChange(e) {
    this.setState({ search: e.target.value });
  }

  componentDidMount() {
    this.fetchPhotos(this.state.currentPage);
  }

  fetchPhotos(page = 1) {
    var self = this;
    const { search, perPage } = this.state;
    const url1 = `https://api.unsplash.com/photos?page=${page}&client_id=${appId}`;
    const url2 =
      `https://api.unsplash.com/search/photos?page=${page}&query=` +
      search +
      "&client_id=" +
      appId;
    const url = search ? url2 : url1;

    if (search) {
      const options = {
        params: {
          page: page,
          per_page: perPage,
          order_by: "popularity"
        }
      };

      this.setState({ loadState: LOAD_STATE.LOADING });
      axios
        .get(url, options)
        .then(response => {
          console.log(typeof response.data);
          let photos;
          try {
            photos = response.data.results;
          } catch {
            photos = [];
          }
          this.setState({
            photos,
            totalPhotos: parseInt(response.headers["x-total"]),
            currentPage: page,
            loadState: LOAD_STATE.SUCCESS
          });
        })
        .catch(() => {
          this.setState({ loadState: LOAD_STATE.ERROR });
        });
    } else {
      const options = {
        params: {
          client_id: appId,
          page: page,
          per_page: perPage,
          order_by: "popularity"
        }
      };

      this.setState({ loadState: LOAD_STATE.LOADING });
      axios
        .get(url, options)
        .then(response => {
          console.log(typeof response.data);
          let photos;
          try {
            photos = response.data;
          } catch {
            photos = [];
          }
          self.setState({
            photos,
            totalPhotos: parseInt(response.headers["x-total"]),
            currentPage: page,
            loadState: LOAD_STATE.SUCCESS
          });
        })
        .catch(() => {
          this.setState({ loadState: LOAD_STATE.ERROR });
        });
    }
  }

  render() {
    return (

        <input
          onChange={this.handleChange}
          type="text"
          name="search"
          placeholder="Enter query"
        />
        <button
          type="submit"
          onClick={() => this.fetchPhotos(1)}
          className="button"
        >
          Submit
        </button>
        <Pagination
          current={this.state.currentPage}
          total={this.state.totalPhotos}
          perPage={this.state.perPage}
          onPageChanged={this.fetchPhotos.bind(this)}
        />
        {this.state.loadState === LOAD_STATE.LOADING ? (

        ) : (
          <List data={this.state.photos} />
        )}
        <Pagination
          current={this.state.currentPage}
          total={this.state.totalPhotos}
          perPage={this.state.perPage}
          onPageChanged={this.fetchPhotos.bind(this)}
        />

    );
  }
}

List.js
import React from "react";
import ListItem from "./ListItem";
const List = ({ data }) => {
  var items = data.map(photo => <ListItem key={photo.id} photo={photo} />); //error here
  return
{items}
;
};

export default List;

A: I found out the problem that you are facing, the issue is when there is empty data from the API response the photos variable stays like photos = {} where in expected is photos = [], which you did in catch block but it never goes to catch block because having empty data is not error, also I have solved your issue here Demo.


text:
Q: 3 column query in DynamoDB using DynamooseJs My table is (device, type, value, timestamp), where (device,type,timestamp) makes a unique combination ( a candidate for composite key in non-DynamoDB DBMS).
My queries can range between any of these three attributes, such as
GET (value)s from (device) with (type) having (timestamp) greater than <some-timestamp>
I'm using dynamoosejs/dynamoose. And from most of the searches, I believe I'm supposed to use a combination of the three fields (as a single field ; device-type-timestamp) as id. However the set: function of Schema doesn't let me use the object properties (such as this.device) and due to some reasons, I cannot do it externally.
The closest I got (id:uuidv4:hashKey, device:string:GlobalSecIndex, type:string:LocalSecIndex, timestamp:Date:LocalSecIndex)
and
(id:uuidv4:rangeKey, device:string:hashKey, type:string:LocalSecIndex, timestamp:Date:LocalSecIndex)
and so on..
However, while using a Query, it becomes difficult to fetch results of particular device,type as the id, (hashKey or rangeKey) keeps missing from the scene.
So the question. How would you do it for such kind of table?
And point to be noted, this table is meant to gather content from IoT devices, which is generated every 5 mins by each device on an average.

A: I'm curious why you are choosing DynamoDB for this task. Advanced queries like this seem to be much better suited for a SQL based database as opposed to a NoSQL database. Due to the advanced nature of SQL queries, this task in my experience is a lot easier in SQL databases. So I would encourage you to think about if DynamoDB is truly the right system for what you are trying to do here.
If you determine it is, you might have to restructure your data a little bit. You could do something like having a property that is device-type and that will be the device and type values combined. Then set that as an index, and query based on that and sort by the timestamp, and filter out the results that are not greater than the value you want.
You are correct that currently, Dynamoose does not pass in the entire object into the set function. This is something that personally I'm open to exploring. I'm a member on the GitHub project, and if you would like to submit a PR adding that feature I would be more than happy to help explore that option with you and get that into the codebase.
The other thing you might want to explore is having a DynamoDB stream, that will set that device-type property whenever it gets added to your DynamoDB table. That would abstract that logic out of DynamoDB and your application. I'm not sure if it's necessary for what you are doing to decouple it to that level, but it might be something you want to explore.
Finally, depending on your setup, you could figure out which item will be more unique, device or type, and setup an index on that property. Then just query based on that, and filter out the results of the other property that you don't want. I'm not sure if that is what you are looking for, it will of course work, but I'm not sure how many items you will have in your table, and there get to be questions about scalability at a certain level. One way to solve some of those scalability questions might be to set the TTL of your items if you know that you the timestamp you are querying for is constant, or predictable ahead of time.
Overall there are a lot of ways to achieve what you are looking to do. Without more detail about how many items, what exactly those properties will be doing, the amount of scalability you require, which of those properties will be most unique, etc. it's hard to give a good solution. I would highly encourage you to think about if NoSQL is truly the best way to go. That query you are looking to do seems a LOT more like a SQL query. Not saying it's impossible in DynamoDB, but it will require some thought about how you want to structure your data model, and such.

A: Considering opinion of @charlie-fish, I decided to jump into Dynamoose and improvise the code to pass the model to the set function of the attribute. However, I discovered that the model is already being passed to default parameter of the attribute. So I changed my Schema to the following:
  id:hashKey;default: function(model){ return model.device + "" + model.type; }
  timestamp:rangeKey

For anyone landing here on this answer, please note that the default & set functions can access attribute options & schema instance using this . However both those functions should be regular functions, rather than arrow functions.
Keeping this here as an answer, but I won't accept it as an answer to my question for sometime, as I want to wait for someone else to hit out a better approach.
I also want to make sure that if a value is passed for id field, it shouldn't be set. For this I can use set to ignore the actual incoming value, which I don't know how, as of yet.


text:
Q: Load Javascript with Magento Block template I have put javascript into a custom payment method block template .phtml like so:
<ul class="form-list" id="payment_form_<?php echo $this->getMethodCode() ?>" style="display:none;">

the Javascript controls the disabling and showing of input fields in my custom payment method form.
But the script does not load when my payment method custom form appears.
I was able to place the script into the head of the checkout html page using layout block reference.
But that does not work since the payment method custom form is loaded after the JS is loaded.
I'm just trying to load the JS with the form, but that does not work. How can I do this?

A: You can try:

*

*alert('here') / console.log('here') in the script to make sure it got called.

*wrap your script in:
document.observe("dom:loaded", function() {
// your scripts
}
To make sure it load last.


text:
Q: Unhandled Rejection (SyntaxError): Unexpected token < in JSON at position 0 React I keep getting the "Unhandled Rejection (SyntaxError): Unexpected token < in JSON at position 0" error whenever I try to use the global variable from a different component, in this case when I use the global variable from Brewery.js in Random.js
Brewery.js
  componentDidMount() {
    window.url = "https://api.openbrewerydb.org/breweries";
    fetch(window.url)
      .then(response => response.json())
      .then((data) => {
        this.setState({
          breweries: data,
        })
      })
  }

Random.js
  componentDidMount() {
    fetch(window.url)
      .then(response => response.json())
      .then((data) => {
        this.setState({
          breweries: data,
        })
      })
  }

A: You've said that the first block (Brewery.js) works, but the second (Random.js) doesn't.
It's certainly poor practice to create a global variable in componentDidMount and rely on it in another component. Clearly, what's happening is the second component is mounting before the first, so window.url is undefined, and so you end up requesting "undefined" instead of the correct URL.
First, don't repeat yourself. Instead, have a single function that gets breweries, and reuse it:
function getBreweries() {
  return fetch(window.url)
    .then(response => {
        if (!response.ok) {
            throw new Error("HTTP error " + response.status);
        });
        return response.json();
    });
}

You might even make it handle setting state:
function loadBreweriesIntoState() {
  return fetch(window.url)
    .then(response => {
        if (!response.ok) {
            throw new Error("HTTP error " + response.status);
        });
        return response.json();
    })
    .then(breweries => {
        component.setState({breweries});
    })
    .catch(error => {
        component.setState({error: "Error loading the list of breweries."});
    });
}

Then, in the two components (Random.js and Brewery.js), use that function rather than repeating the logic.
Which brings us to: How do you make that function available to both components?
Two answers:

*

*If you're using modules (which I strongly recommend), put it in a module they both use:
loadBreweriesIntoState.js:
export default function loadBreweriesIntoState() {
    // ...
}

Brewery.js:
import loadBreweriesIntoState from "./loadBreweriesIntoState.js";

// ...

    componentDidMount() {
        loadBreweriesIntoState(this);
    }

Random.js:
import loadBreweriesIntoState from "./loadBreweriesIntoState.js";

// ...

    componentDidMount() {
        loadBreweriesIntoState(this);
    }

*If you're not using modules, put it in a script that you include prior to the two component scripts (in development) and set up to be included before them in your bundle (for production).
Those two options apply if you want to keep the logic in the components instead, too: Just make url an export in some kind of Config.js (or a global that it creates).