text:
Q: Does SQL server 2008 XML data type have performance issues Hi I have a need to store hundreds if not thousands of elements in the database as XML. I will not index anything in the XML field. I will simply select certain elements within the xml. I would like to know if there is any performance penalty for simply selecting fields in the XML. Here is example XML that will be stored in the database.
<fields>
    <field name="FirstName" type="text" value="Gary" sort="2" />
    <field name="LastName" type="text" value="Smith" sort="3" />
    <field name="City" type="text" value="Los Angeles" sort="4" />
    <field name="Age" type="number" value="12" sort="6" />
    <field name="Address" type="text" sort="2">
        <streetnumber value="1234" />
        <streetname value="sail" />
    </field>
</fields>

I will probably have more than 3000 field tags in one record. I simply want to get 10 fields in a single query. I will have a primary key on the table and will be selecting records based on the primary key but will be getting fields from the XML column. I am afraid the more field elements I put in the XML will compromise performance. Will there be a performance penalty for simply selecting 10 or more fields from the XML column? Also, I will not be using the xml column in a where clause I will use the primary in the where clause then I will select fields from the XML column. Will there be a performance penalty?

A: Based on my experience on XML in SQL Server Xml datatype, and on Indexes on XML Data Type Columns (the whole section deserves thorough reading)

Will there be a performance penalty for simply selecting 10 or more
  fields from the XML column ?

Yes, because your XML document is stored as a blob. Without a primary XML index, this blob will need to be exploded for query processing (filtering and projection)
As to XML, indexes can be seen as a relational representation of your document (pre-exploding the blob)

Without an index, these binary large objects are shredded at run time to evaluate a query. This shredding can be time-consuming

As to your second question

Also, I will not be using the xml column in a where clause I will use the primary in the where clause then I will select fields from the XML
  column. Will there be a performance penalty?

If you are going to project among 3000 field tags, you might benefit from a secondary XML index, though I'm not sure which one. PROPERTY secondary index seems fit for projection, but it seems to apply on value calls (the french documentation seems to imply more than just value calls but that may be some translation mistake)
For my part, I ended-up setting the three kind of secondary indexes on my XML column (1 million documents on 30 different schemas, 50-100 elements each) But my app requires a lot more filtering than projection.

A: [BEGIN EDIT]
jbl's direct answers to your questions, and Terror.Blade's answer re' XML being better than NVARCHAR(MAX) both make sense (I upvoted them :).
My experience was without storing an XML schema in SQL Server (Terror.Blade's tip), and without indexing (jbl gave the most, re' that)... but I'm leaving my answer, because I think my links could be very helpful... and it's still an example of worst case ;)
[END EDIT]
From experience, I'll say that the loading of an XML data type is quick, but as for using it -- I found that to be slow, but the personal example coming to mind involved updating, and using xQuery, and those may have been factors in my slowdown.
In that example, it took 1hr55mins to process only 127,861 rows.
(Terror.Blade's tip, of storing an XML schema in SQL Server, and jbl's link & share re' XML indexing both sound pretty slick ;) and might address that slowdown.)
RELATED:
Here's some tips re' optimizing XML in SQL... though some of them only apply if you have control over the format of the XML:
http://msdn.microsoft.com/en-us/library/ms345118.aspx
If you're using xQuery, check out these docs:
http://download.microsoft.com/download/0/F/B/0FBFAA46-2BFD-478F-8E56-7BF3C672DF9D/XQuery%20Language%20Reference.pdf
((And if you're using SQLXMLBulkLoad at all, consider using "overflow-field"s, to capture whatever is not defined in your schema.  There's some useful tips in this tangentially related TechNote:
http://social.technet.microsoft.com/Forums/sqlserver/en-US/393cf604-bf6e-488b-a1ea-2e984aa14500/how-do-i-redirect-xml-comments-that-sqlxmlbulkload-is-storing-in-the-overflowfield?forum=sqlxml ))
HTH.

A: I realize that this is not a direct answer to the OP's question (although, it's related to it), but I think this could really help many people that have been redirected here looking for some idea on how to deal with the poor performance of the XML data type on SQL Server. After many years struggling with this issue, I finally found a solution that, for some reason, is not that easy to come by:
SXI - Selective XML Indexes (starting with SQL 2008)
MS Docs link:
https://learn.microsoft.com/en-us/sql/relational-databases/xml/selective-xml-indexes-sxi?view=sql-server-2017
On my local tests with tables containing 3MM+ records, it worked amazingly well!


text:
Q: Cron job creates empty files I want to preface that I am a newbie that picked up shell scripting 2 weeks ago.
Hey guys I need help with something, hope someone can point me in the right direction. I have a script that works when I run it from the command line but every time I run it with a crontab, the output is a few empty files. Does anyone know why?
That's the code down there
#!/bin/bash

#Provide an IP address as an argument to use nmap
#make sure to add the full range with (0-225 or 0/24) at the end

IPADDRESS=$(hostname -I | awk '{print $1}')

network-scan(){
if [ $1 ]
then
  sudo nmap -sn $1
else
  sudo nmap -sn 192.168.1.0-255
fi
}

#Scan the whole network and only prints the IP addresses minus your own
#Sends the IP addresses to a file
network-scan | grep -i 'Nmap scan report' | \
    sed 's/\ /\n/g'|sed 's/(//g'|sed 's/)//g' | \
    grep '[0-9]*\.[0-9]*\.[0-9]*\.[0-9]*' | grep -v ${IPADDRESS} > ip_addresses

#Scan the whole network and only prints the MAC addresses
#Sends the MAC addresses to a file
network-scan | grep -i 'MAC Address:' | \
    awk '{print $3}' > mac_addresses

#Put the IP and MAC addresses in the same file
paste ip_addresses mac_addresses | \
    column -s $'\t' -t > "scan_$(date +%d-%m-%Y_%H:%M:%S)"

#Notify that a file with the IP and MAC addresses has been created on the Desktop
echo "A file containing the results of the scan has been created on the Desktop"

exit 0

A: You are using
network-scan | grep

without passing any parameter.
Hence network-scan function always using
sudo nmap -sn 192.168.1.0-255

*

*when you run it from command line are you passing any parameter ?

*echo $IPADDRESS inside the script when executing at cron and at command line for debugging.

*

network-scan | grep -i 'Nmap scan report' | \
    sed 's/\ /\n/g'|sed 's/(//g'|sed 's/)//g' | \
    grep '[0-9]*\.[0-9]*\.[0-9]*\.[0-9]*' | grep -v ${IPADDRESS}

Since you are obtaining empty output, validate each command and append(test) each OR operators to know where it is removing required output.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How I can disable some tests in Travis CI for python I would like to know. How I can disable some tests in Travis CI.
I am trying wrote something it but it didn't work
@pytest.mark.skipif("TRAVIS" in os.environ and os.environ["TRAVIS"] == "true",
reason="Skipping this test on Travis CI.")
@pytest.mark.asyncio
async def test_can_unwatch_remote_actor(remote_manager):

A: In Travis configuration you can add custom environment variable.
For example you can add in your .travis.yml file this line
env: TRAVIS=true

then use it in skipif.
If you would like to test it locally and you work on UNIX like system (eg. Linux, MacOS) you can test it locally with
TRAVIS=true pytest ..


text:
Q: (Processing) GROUP PShape getWidth() or width is 0.0 I want to get the width and the height of a GROUP PShape, but I only get 0.0.
For example:
// Example code from "https://processing.org/reference/PShape_addChild_.html"

PShape house;

void setup() {
  size(200, 200);

  // Make a group PShape
  house = createShape(GROUP);

  // Make three shapes
  PShape path = createShape();
  path.beginShape();
  path.vertex(-20, -20);
  path.vertex(0, -40);
  path.vertex(20, -20);
  path.endShape();
  PShape rectangle = createShape(RECT, -20, -20, 40, 40);
  PShape circle = createShape(ELLIPSE, 0, 0, 20, 20);

  // Add all three as children
  house.addChild(path);
  house.addChild(rectangle);
  house.addChild(circle);

  println(house.width, house.getWidth());
  println(house.height, house.getHeight());
}

void draw() {
  background(52);
  translate(mouseX, mouseY);
  shape(house);
}

In this code, println(house.width, house.getWidth()); and println(house.height, house.getHeight()); show 0.0 0.0
So, how can I get the width and the height of any PShape?

Edit
Following the advice from @Rabbid76, I have created a getBoundingBoxLimits() function:
float[][] getBoundingBoxLimits(PShape s){
  float[][] coords = {{1000000.0, -1000000.0}, {1000000.0, -1000000.0}};
  // coords represents {{min_x, max_x}, {min_y, max_y}}
  float ii, jj;

  for(int i=0; i<1000; i++){
    for(int j=0; i<1000; j++){
      ii = i*1.0;
      jj = j*1.0;
      if(s.contains(ii,jj)){ // contains() expects floats, not ints
        if(ii < coords[0][0]) { coords[0][0] = ii; }
        if(ii > coords[0][1]) { coords[0][1] = ii; }
        if(jj < coords[1][0]) { coords[1][0] = jj; }
        if(jj > coords[1][1]) { coords[1][1] = jj; }
       }
    }
  }

  return coords;
}

But it returns an IllegalArgumentException: The contains() method is only implemented for paths..
So, at first glance, it seems that I cannot determine if a (x, y) point is in any PShape other than a PATH PShape.
Anyway, I am expecting a more straightforward way of getting the width and the height of any PShape (as I am sure this information is stored inside any of these objects).


text:
Q: What does adding to a GLuint attribute index do? I'm currently reading some code (specifically example code for the Oculus Mobile SDK which just renders some coloured cubes floating around) where he retrieves a vertex shader attribute with glGetAttribLocation (in the shader it's a mat4, it's the transform matrix), then a little further down he does some stuff where he adds to that shader attribute index.
VertexTransformAttribute = glGetAttribLocation( Program.Program, "VertexTransform" );

//some stuff happens in between

for ( int i = 0; i < 4; i++ )
{
    GL( glEnableVertexAttribArray( VertexTransformAttribute + i ) );
    GL( glVertexAttribPointer( VertexTransformAttribute + i, 4, GL_FLOAT,
                            false, 4 * 4 * sizeof( float ), (void *)( i * 4 * sizeof( float ) ) ) );
    GL( glVertexAttribDivisor( VertexTransformAttribute + i, 1 ) );
}

To some extent, I understand that he's doing something with the transform matrix for all cubes, but I'm not sure what adding to the index does.
Any help explaining this part would be appreciated!

A: Every vertex attribute delivers 4 values to OpenGL, even if you don't use all 4 of them. But in GLSL, you can use matrices and arrays of types for the type of a vertex shader input variable. Since these take more than 4 values, you need more than 1 attribute to deliver the data, despite having only declared one actual variable.
So the attribute location for the input variable's name is the first attribute index. And OpenGL automatically assigns the next X attribute indices, consecutively, to fulfill the request for your variable. In the case of a mat4, that is a 4x4 matrix. So OpenGL needs to assign it 4 attributes total, with each attribute representing a single column of the matrix. These are assigned in order, starting from the attribute index associated with the variable name and ending 3 attribute indices later.


text:
Q: How do I change start up preferences for IPython console in PyCharm? I am trying to do what the user from this question is doing. I have it working for the separate IPython console but not the one integrated into PyCharm.
To sum up, I want IPython to import some modules when I start it. I have gone to the C:\Users\Name\.ipython\profile_default\startup directory and I have made a startup.py file which contains
from numpy import *
print 'NumPy imported succesfully!'

After setting PYTHONSTARTUP to point to the file, the IPython console outside of PyCharm works as intended, but the one in PyCharm does not.

A: You can go to File -> Settings -> Build, Execution, Deployment -> Console -> Python Console. There you have a field named "Starting script" which is executed when you launch the console.
I had to restart PyCharm for the changes to actually take place, but it worked.
Note : I use PyCharm 4.5.3 Community Edition.


text:
Q: Send multiply input field values to php by using ajax POST I am trying to send some dynamically created input field values to PHP to validate them and make some checks in the database in the background. I don't want to use submit form but just check the fields after click a button.
Html:
<input name="clockpick" class="input-mini timeinputfrom" data-format="hh:mm" type="text"></input>
<input name="clockpick" class="input-mini timeinputfrom" data-format="hh:mm" type="text"></input>
<button id="check" class="btn btn-primary">check</button></div>

The input boxes can be dynamically created depending how many are necessary. I get the values into jquery but don't find any possibility to send them via post to php.
Jquery:
$('#submit').on('click', function() {

var inputfield = $('input[name="clockpick"]');

 $('input[name="clockpick1"]').each(function( index, element ) {
    console.log( "Wert" + index + ": " + $( element ).val() );
});

$.ajax({
        type: "POST",
        url: "productiontimevalidate.php",
        data: ????

    });

How can I send the values / array to PHP?

A: Another way would be to add the values to an array, and convert it to json for sending.
var allClockPicks = [];
$('input[name="clockpick1"]').each(function( index, element ) {
  allClockPicks.push($(element).val());
});

Then, the ajax can send data as
data: {cp: JSON.stringify(allClockPicks)}

On the php side, you can json_decode them as below:
$cpArray = json_decode($_POST['cp'], true);

A: If your elements are inside <form class="my-form"> [elements...] </form>
You can use this short version:
<script>
$.post('/my/path/app.php', $('.my-form').serialize(), function(r) {
   console.log(r);
},'json'); // parse response as JSON
</script>

app.php
<?php
echo json_encode(array('success' => true, 'post', $_POST));
?>


text:
Q: How to crop images from camera How can I crop the camera images. Now it is showing the the image for crop and after selecting the crop section while tap on the "Save" button. Its showing as "saving image". After that nothing is happen. Here is my code.
Button click :
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, MediaStore.Images.Media.EXTERNAL_CONTENT_URI.toString());
intent.putExtra("crop", "true");
intent.putExtra("aspectX", 0);
intent.putExtra("aspectY", 0);
intent.putExtra("outputX", 200);
intent.putExtra("outputY", 150);
intent.putExtra("return-data", true);
startActivityForResult(intent, CAMERA_PIC_REQUEST);

onActivityResult :
Bundle extras = data.getExtras();
Bitmap bitmap = (Bitmap) extras.get("data");
if (bitmap != null) {
    Img_View.setImageBitmap(bitmap);
}

A: Save yourself a lot of time and use this library I was messing around with trying to do it myself and stumbled on this library and its really simple to use and you get a professional looking image cropping view that lets you choose camera or photo library.
Simple example:
Include the library in your gradle
implementation 'com.theartofdev.edmodo:android-image-cropper:2.7.+'

Add permissions to manifest
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

//add this under <application>
<activity android:name="com.theartofdev.edmodo.cropper.CropImageActivity"
  android:theme="@style/Base.Theme.AppCompat"/>

In your activity
//on button press or anywhere, this starts the image picking and cropping process
CropImage.activity()
  .setGuidelines(CropImageView.Guidelines.ON)
  .start(this);

//in your activity where you will get the result of your cropped image
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
  if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
    CropImage.ActivityResult result = CropImage.getActivityResult(data);
    if (resultCode == RESULT_OK) {
      Uri resultUri = result.getUri();

      //From here you can load the image however you need to, I recommend using the Glide library

    } else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
      Exception error = result.getError();
    }
  }
}

Im not affiliated with this software

A: You can use this code to perform cropping:
.....
final int CAMERA_CAPTURE = 1;
final int CROP_PIC = 2;
private Uri picUri;
....
@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button captureBtn = (Button) findViewById(R.id.capture_btn);
        captureBtn.setOnClickListener(this);
    }

    public void onClick(View v) {
        if (v.getId() == R.id.capture_btn) {
            try {
                // use standard intent to capture an image
                Intent captureIntent = new Intent(
                        MediaStore.ACTION_IMAGE_CAPTURE);
                // we will handle the returned data in onActivityResult
                startActivityForResult(captureIntent, CAMERA_CAPTURE);
            } catch (ActivityNotFoundException anfe) {
                Toast toast = Toast.makeText(this, "This device doesn't support the crop action!",
                        Toast.LENGTH_SHORT);
                toast.show();
            }
        }
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            if (requestCode == CAMERA_CAPTURE) {
                // get the Uri for the captured image
                picUri = data.getData();
                performCrop();
            }
            // user is returning from cropping the image
            else if (requestCode == CROP_PIC) {
                // get the returned data
                Bundle extras = data.getExtras();
                // get the cropped bitmap
                Bitmap thePic = extras.getParcelable("data");
                ImageView picView = (ImageView) findViewById(R.id.picture);
                picView.setImageBitmap(thePic);
            }
        }
    }

    /**
     * this function does the crop operation.
     */
    private void performCrop() {
        // take care of exceptions
        try {
            // call the standard crop action intent (the user device may not
            // support it)
            Intent cropIntent = new Intent("com.android.camera.action.CROP");
            // indicate image type and Uri
            cropIntent.setDataAndType(picUri, "image/*");
            // set crop properties
            cropIntent.putExtra("crop", "true");
            // indicate aspect of desired crop
            cropIntent.putExtra("aspectX", 2);
            cropIntent.putExtra("aspectY", 1);
            // indicate output X and Y
            cropIntent.putExtra("outputX", 256);
            cropIntent.putExtra("outputY", 256);
            // retrieve data on return
            cropIntent.putExtra("return-data", true);
            // start the activity - we handle returning in onActivityResult
            startActivityForResult(cropIntent, CROP_PIC);
        }
        // respond to users whose devices do not support the crop action
        catch (ActivityNotFoundException anfe) {
            Toast toast = Toast
                    .makeText(this, "This device doesn't support the crop action!", Toast.LENGTH_SHORT);
            toast.show();
        }
    }

You can use following simple tutorial to perform cropping:

*

*http://khurramitdeveloper.blogspot.in/2013/07/capture-or-select-from-gallery-and-crop.html

*http://www.londatiga.net/featured-articles/how-to-select-and-crop-image-on-android/

*http://www.coderzheaven.com/2012/12/15/crop-image-android/

*http://shaikhhamadali.blogspot.in/2013/09/capture-images-and-crop-images-using.html

A: Try this
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

                mImageCaptureUri = Uri.fromFile(new File(Environment
                        .getExternalStorageDirectory(), "tmp_avatar_"
                        + String.valueOf(System.currentTimeMillis())
                        + ".jpg"));

                intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT,
                        mImageCaptureUri);

                intent.setData(mImageCaptureUri);
                intent.putExtra("outputX", 200);
                intent.putExtra("outputY", 200);
                intent.putExtra("aspectX", 1);
                intent.putExtra("aspectY", 1);
                intent.putExtra("scale", true);
                intent.putExtra("return-data", true);


text:
Q: Exception of type 'System.FormatException' on double.Parse
A first chance exception of type 'System.FormatException' occurred in mscorlib.dll
Additional information: Input string was not in a correct format.

Jumps to this code right after
double parts = double.Parse(partsTextBox.Text);

Nothing on textBox I'm supposed to input a number in the application
and I've tried Try.Parse and I get an error "No overload for method 'TryParse' takes 1 arguments"
which I have no clue what that means.
THis is the whole code
namespace Project03_18Mar15_Alan_Mederos_B
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

    private void calculateTotalButton_Click(object sender, EventArgs e)
    {
        double oil = 0, lube = 0, radiator = 0, trans = 0, inspection = 0; double muffler = 0,tire = 0;
        if (oilChangeBx.Checked == true)
        {
            oil = 26;
        }
        if (lubeJobBx.Checked == true)
        {
            lube = 18;
        }
        if (radiatorFlushBx.Checked == true)
        {
            radiator = 30;
        }
        if (transFlushBx.Checked == true)
        {
            trans = 80;
        }
        if (inspectionBx.Checked == true)
        {
            inspection = 15;
        }
        if (replaceMufflerBx.Checked == true)
        {
            muffler = 100;
        }
        if (tireRotationBx.Checked == true)
        {
            tire = 20;
        }

        // Convert all values to doubles
            double parts = double.Parse(partsTextBox.Text);
            double labor = double.Parse(laborTextBox.Text);
            double oillube = OilLubeCharges(oil, lube);
            double flush = FlushCharges(radiator, trans);
            double misc = MiscCharges(inspection, muffler, tire);
            double other = OtherCharges(parts, labor);
            double tax = TaxCharges(parts, labor, oillube, flush, misc, labor);
            double total = TotalCharges(oillube, flush, misc, other, tax);
            double services = oillube + flush + misc;
            servicesOutputLb.Text = services.ToString("c");
            partsOutputLb.Text = other.ToString("c");
            taxOutputLb.Text = tax.ToString("c");
            totalOutputLb.Text = total.ToString("c");
        }

    private double OilLubeCharges (double oil, double lube)
    {
        //return oil and lube charges
        return oil + lube;
    }
    private double FlushCharges(double radiator, double trans)
    {
    // returns radiator and transmission flush charges
        return radiator + trans;
    }
    private double MiscCharges(double inspection, double muffler, double tire)
    {
        //return inspection, muffler, and tire rotation charges
        return inspection + muffler + tire;

    }

    private double OtherCharges (double parts, double labor)
    {
        //return parts and labor
        return parts + labor;

    }

    private double TaxCharges (double parts, double labor, double oillube,
        double flush, double misc, double other)
    {
    //returns sales tax on parts only
        if (parts != 0 && labor != 0 && (oillube != 0
            && flush != 0 && misc != 0 && other != 0))
        {
            // sales on tax is 6%
            return (0.06 * parts);
        }
        else return 0;
    }

    private double TotalCharges(double oillube, double flush,
        double misc, double other, double tax)
    {
        return oillube + flush + misc + other + tax;
    }

    private void clearBtn_Click(object sender, EventArgs e)
    {
        // Clears all fields
        oilChangeBx.Checked = false;
        lubeJobBx.Checked = false;
        radiatorFlushBx.Checked = false;
        transFlushBx.Checked = false;
        inspectionBx.Checked = false;
        replaceMufflerBx.Checked = false;
        tireRotationBx.Checked = false;
        partsTextBox.Text = "";
        laborTextBox.Text = "";
        servicesOutputLb.Text = "";
        partsOutputLb.Text = "";
        taxOutputLb.Text = "";
        totalOutputLb.Text = "";
    }

    private void exitBtn_Click(object sender, EventArgs e)
    {
        //exits form
        this.Close();
    }

}

}

A: The message "No overload for method 'TryParse' takes 1 arguments" is self explanatory.
You can only call TryParse with two or more parameters.
To use TryParse, with two parameters, you must pass the output variable as reference. See the code below:
double output;
bool success = double.TryParse(partsTextBox.Text, out output);

Pay atention, output must be passed initialized. If success, output will have value.
Other way is catching the exception:
double parts;

try
{
    parts = double.Parse(partsTextBox.Text);
}
catch (FormatException fe)
{
    MessageBox.Show("Quantity of parts not informed");
}

EDIT2:
Look that in your code, you have two parsers:
        double parts = double.Parse(partsTextBox.Text);
        double labor = double.Parse(laborTextBox.Text);

And any of they can throw the FormatException. My sugestion is write something like that:
        double parts;
        double labor;
        if(
           double.TryParse(partsTextBox.Text, out parts)
           && double.TryParse(laborTextBox.Text, out labor))
        {
            double oillube = OilLubeCharges(oil, lube);
            double flush = FlushCharges(radiator, trans);
            double misc = MiscCharges(inspection, muffler, tire);
            double other = OtherCharges(parts, labor);
            double tax = TaxCharges(parts, labor, oillube, flush, misc, labor);
            double total = TotalCharges(oillube, flush, misc, other, tax);
            double services = oillube + flush + misc;
            servicesOutputLb.Text = services.ToString("c");
            partsOutputLb.Text = other.ToString("c");
            taxOutputLb.Text = tax.ToString("c");
            totalOutputLb.Text = total.ToString("c");
        }
        else
        {
            MessageBox.Show("Quantity of parts and quantity of labors must be informed and must be valid!");
        }


text:
Q: display 'welcome " customer_name"' at the top of the magento site when customer login to site, it should display "welcome customer" at top of the site.
assume customer will login to site. after customer login, in top of the site there
should be a some message to welcome customer.
how to display welcome " customer_name" at the top of the site.
please help me to find solution.
thanks in advance.

A: You can check following code must be there :
In header.phtml file
        <?php echo $this->getChildHtml('topSearch') ?>

<?php echo $this->getChildHtml('welcome') ?> <?php echo $this->getAdditionalHtml() ?>

        <?php echo $this->getChildHtml('topLinks') ?>

In page.xml file block should be there :
    <block type="page/html_header" name="header" as="header">
        ..........
        <block type="page/html_welcome" name="welcome" as="welcome"/>
    </block>

A:     //LOAD MAGENTO
require_once 'YOUR_PATH_TO_MAGENTO/app/Mage.php';
umask(0);
Mage::app('YOUR_WEBSITE_CODE', 'website');

//GET SESSION DATA
Mage::getSingleton('core/session', array('name'=>'frontend'));
$session = Mage::getSingleton('customer/session', array('name'=>'frontend'));

$customer_data = Mage::getModel('customer/customer')->$session->id);

//CHECK IF LOGGED IN
if($session->isLoggedIn()){
echo 'Welcome ' . $customer_data->firstname . " " . $customer_data->lastname;
} else {
echo "Welcome guest";
}

- See more at: https://www.jnorton.co.uk/blog/magento-check-if-customer-logged#sthash.bxeDgV9U.dpuf


text:
Q: Another question about how to learn algebraic geometry... I've been trying to learn some algebraic geometry (level of generality: working over an algebraically closed ground field but not afraid of using the language of sheaves and cohomology etc.)
The problem I'm having with it is that most of the references I'm using (Milne's notes on AG, Perrin's Algebraic Geometry, Mumford's Red Book etc.) just seem like endless streams of technical results and whilst I can appreciate most of the concrete examples ("oh look - that's a singularity"...), I'm not really sure what I'm supposed to be doing. On the other hand, books like Reid's Undergraduate AG makes me feel like I'm not sure what the definitions are (if that makes sense to someone!).
At the minute my approach is to check everything line by line (if I can!) and try to build up a picture of how the technicalities fit together into a bigger picture. I've also tried to do the exercises in Chapter 1 of Hartshorne but a lot of them seem too difficult for me at the moment (there feels a big gap between the technicalities of the chapters in the books and the concrete nature of the examples).
Does anyone have some magical book recommendation that I've missed or some other approach that helped them learn the subject?
Many thanks!

A: Learning Algebraic geometry is not a simple task and this is very logic that this gives you a nonsense impression .
I like two references to learn AG the first is Harris an first course (this book is more like a undergraduate book with a lot of context and example and intuition )
The second more advanced is kenji ueno Algebraic geometry
About Hartshorne exercises :
Some of Hartshorne exercises are very difficult and not adequate for learning student but there is Exercises that are very important and you must do but this is normal that get you time keep time to thinking I think that Algebraic geometry is a subject that you need to give time for it for example to learn chapter 1 can keep 2 months and this is okay .
So don't worry about it


text:
Q: Set field values to newly imported rows in PostgreSQL table with existing data I have a PostgreSQL table with existing data, and needs to import all the rows in a CSV file into that table. I am using pgadmin3's Import tool to do the import.

Question: For the newly imported rows, how do I set the values for a specific column (not found in the CSV)? I cant do UPDATE staging.tablename SET colname = 'somename' the way I could when importing into an empty table. Or is this approach wrong?

A: I'd recommend using the COPY command from psql. You can set a DEFAULT value for a column and omit that value from the COPY command, eg:
\copy tablename(col1,col2,col3) FROM 'thefile.csv' WITH (FORMAT CSV)

Alternately, you can create a new TEMPORARY table in PgAdmin-III wtih just the columns in the CSV, import the CSV into it, and use SQL like this to merge it into the main table:
INSERT INTO realtable (col1, col2, col3, colwithdefault)
SELECT
    col1, col2, col, 'some default value'
FROM tempcsvtable;

You can use this to calculate columns based on expressions, combine and split columns, omit some rows, etc.


text:
Q: MariaDB 10.3.28 slow performance on CentOS 8 Server I have a server running CentOS 8 with apache, php-fpm, and mariadb.
The last one is giving problems to me.
I tried to import a database of a site into phpmyadmin with the apposite interface and also with mysql command.
The test with interface has been as slow as the timeout of apache (600s) giving to me gateway timeout. The test with mysql command has taken over 6 minutes!
The dump was something like 2MB so it is really unacceptable.
Do you know something I could change in configuration in order to solve this situation?
Already tried this in /etc/my.cnf but nothing happened:
[mysqld]
slow_query_log = 1
long_query_time = 1
slow_query_log_file = /var/log/mariadb/slow-query.log

query_cache_type = 1
query_cache_limit = 8M
query_cache_size = 512M

max_connections = 500

tmp_table_size= 768M
max_heap_table_size= 768M

thread_cache_size = 12

join_buffer_size = 12M

The hardware of the machine I think it shouldn't be a problem, anyway:

*

*4 cpu

*5028 MB ram

A: yes, the individual configurations are in subdirectories. take a look at the subdirs of / etc / mysql e.g. ./mariadb.conf.d


text:
Q: Unity 2D персонаж не ходит Приветствую работаю с 2D объектом на Unity и не могу понять почему персонаж не ходит.
Код для того чтоб персонаж ходил прописан верно , в самом unity персонаж на секунду совершает рывок и положение тоже изменяется, и дальше он не ходит все остальные функции работают отлично (Jump и поворот головы)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerCTRL : MonoBehaviour
{
    public float speed = 20f;
    private Rigidbody2D rb;
    private bool faceRight = true;
    void Start()
    {
        rb = GetComponent <Rigidbody2D> ();
    }

    void Update()
    {
        // Speed
        float moveX = Input.GetAxis("Horizontal");
        rb.MovePosition(rb.position + Vector2.right * moveX * speed * Time.deltaTime);

        //Jump
        if (Input.GetKeyDown(KeyCode.Space))
            rb.AddForce(Vector2.up * 8000);

        //Поворот головы
        if (moveX > 0 && !faceRight)
            flip();
        else if (moveX < 0 && faceRight)
            flip();
    }
    // Поворот головы
    void flip()
    {
        faceRight = !faceRight;
        transform.localScale = new Vector3(transform.localScale.x * -1, transform.localScale.y,transform.localScale.z);
    }
}


text:
Q: Como corrigir mensagens de validação? Eu estou aprendendo a programar em Laravel com VueJs, sou iniciante, comecei a desenvolver um simples CRUD e consegui implementar todas as funcionalidade de um CRUD, inclusive validações de campo, meu problema é com as validações de campo, em suas mensagens de retorno como mostra abaixo

Esse código está aqui nesta pagina
<form method="POST" v-on:submit.prevent="createRegistro">

                      <button type="button" class="close" data-dismiss="modal">
                          &time;
                      </button>

Novo Imóvel

                            Criar Imóvel
                            <input type="text" name="descricao"placeholder="Descrição do imóvel" class="form-control" v-model="newDesc">
                            @{{ error }}

                                                  Preço
                                                  <input type="text" class="form-control" placeholder="Preço" name="preco" v-model="newPreco" >
                                                  @{{ error }}

                                                  Quantidade de Quartos
                                                  <input type="number" class="form-control" placeholder="Quantidade de Quartos" name="qtdQuartos" v-model="newQtdQuartos">
                                                  @{{ error }}

                                                      Tipo do Imóvel
                                                      <select class="form-control" name="tipos" v-model="newTipo">
                                                      <option selected>Apartamento</option>
                                                      <option>Casa</option>
                                                      <option>Kitnet</option>
                                                    </select>
                                                    @{{ error }}

                                                        Finalidade do imóvel
                                                        <select class="form-control" name="finalidade" v-model="newFinalidade">
                                                            <option>Venda</option>
                                                            <option>Locação</option>
                                                        </select>

                                                @{{ error }}

Endereço

                                              Logradouro
                                              <input type="text" class="form-control" placeholder="Logradouro" name="logradouroEndereco" v-model="newLogradouroEndereco">
                                              @{{ error }}

                                                  Bairro
                                                  <input type="text" class="form-control" placeholder="Bairro" name="bairroEndereco"  v-model="newBairroEndereco">
                                                  @{{ error }}

                        <input type="submit" class="btn btn-primary" value="Salvar">

</form>

Solicito por favor que vejam o meu repositório abaixo, e solicito também sugestões de como posso trocar essas mensagens por algo mais atrativo, estou perguntando porque eu nem sei por onde começar.
Repositório

A: Você pode criar mensagens de erro personalizadas para cada tipo de erro dentro da sua função de store, exemplo:
 public function store(Request $request){
        $dados = $request->except('_token');
        $dados['Status'] = 1;
        $mensagens = [
            'NomeFantasia.required'         => 'O campo NOME FANTASIA é obrigatório.',
            'NomeFantasia.min'              => 'O NOME FANTASIA não deve ter menos que 3 caracteres',
            'NomeFantasia.max'              => 'O NOME FANTASIA não deve exceder 100 caracteres',
            'RazaoSocial.required'          => 'O campo Razao Social é obrigatório.',
            'RazaoSocial.min'               => 'A Razão Social não deve ter menos que 3 caracteres',
            'RazaoSocial.max'               => 'A Razão Social não deve exceder 100 caracteres',
            'CNPJ.required'                 => 'O campo CNPJ é obrigatório.',
            'Logradouro.min'                => 'O LOGRADOURO não deve ter menos que 3 caracteres',
            'Complemento.min'               => 'O COMPLEMENTO não deve ter menos que 3 caracteres',
            'Telefone.required'             => 'O campo TELEFONE é obrigatório.',
            'Numero.numeric'                => 'O campo NUMERO deve conter somente numeros.',
            'Bairro.min'                    => 'O BAIRRO não deve ter menos que 3 caracteres',
            'Cep.required'                  => 'O CEP é obrigatório.'
        ];

        $this->validate($request, $this->empresa->regras, $mensagens);
        $this->validate($request,
                ['cnpj' => 'formato_cnpj|cnpj']

            );

        $insert = $this->empresa->create($dados);
        // dd($insert->EmpresaId);
        DB::table('EmpresaUsuario')->insert([
            'EmpresaId'     => $insert->EmpresaId,
            'UsuarioId'     => Auth::user()->UsuarioId,
            'Proprietario'  => 1
        ]);
        if($insert)
            return redirect()->route('empresa.definir_cnaes', $insert->EmpresaId);
        else
            return redirect()->back();

    }

Definindo suas regras de validação no próprio Model, exemplo:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Empresa extends Model
{
    protected $primaryKey = 'EmpresaId';
    protected $table = 'empresa';
    protected $fillable = [
        'NomeFantasia', 'RazaoSocial', 'CNPJ', 'InscEstadual', 'InscMunicipal', 'IEST', 'CRT', 'TpEndereco',
        'Logradouro', 'Complemento', 'Numero', 'Bairro', 'Estado', 'Cidade', 'Cep', 'Telefone', 'Site', 'Status'
    ];
    public $regras = [
        'NomeFantasia'  => 'required|min:3|max:100',
        'RazaoSocial'   => 'required|min:3|max:100',
        'CNPJ'          => 'required',
        'Cep'       => 'required',
        'Logradouro'    => 'min:3',
        'Complemento'   => 'min:3',
        'Numero'        => 'numeric',
        'Bairro'        => 'min:3',
        'Telefone'      => 'required',
    ];
}

Indico dar uma olhada na DOCUMENTAÇÃO DAS VALIDAÇÕES DO LARAVEL


text:
Q: Deploy source to org fails with "No authorization information found" I'm just getting started with developing in VS Code and have been following the steps here.
I was able to authorise my org with the default alias according to the steps here:

The authorised org also shows up in my auth:list:

And running sfdx force:org:display --targetusername vscodeOrg, confirms the org's Connected Status: Connected.
But when I try to deploy the component as per step 2 here with SFDX: Deploy Source to Org, I get the error message No authorization information found for vscodeOrg:

Would anyone know what's going on here? I can't find much information about this error and I'm worried I've broken something, so any help would be much appreciated.

EDIT: Updating the CLI with sfdx update seemed to resolve the issue for me.

A: I had the same issue. I restarted Vscode and after that it worked.

A: I am facing this kind of error a lot recently.
For me none of these update sfdx or restarting VScode works.
In my case, when I execute SFDX: Authorize an Org and then execute sfdx force:org:list, there is connected org but no default org.
if you are facing same problem, execute sfdx force:config:set defaultusername=xxx@abc.com, which works for me.

A: sfdx update took care of this issue for me.

A: In my situation, authorizing the org once again or switching the default org to a different one and switching back and then deploying the component worked

A: *

*If there is an update in sfdx kindly update it to the latest version

*Restart your VS Code

*Then type in force:org:display -a which would display the org details such as the connection status

*If disconnected then reconnect it again by using SFDX:Authorize and Org

A: In my case what helped was to run the following command from the VScode's terminal:
sfdx force:org:list --all

A: I ran into the same issue. What helped for me was configuring the path to JAVA in VSCode. https://developer.salesforce.com/tools/vscode/en/vscode-desktop/java-setup


text:
Q: How to use adb with genymotion on mac? I am using cordova to build apps for android, on Mac OS X 10.9.4.
I am using genymotion to create virtual devices.
Yesterday I was able to get 'cordova run android' to get my apps to run on a genymotion virtual device.
Today, I thought I repeated the steps I took yesterday, but I can't get it to work.
I start the adb server (with genymotion not running) with
adb start-server

adb server starts up fine:
* daemon not running. starting it now on port 5037 *
* daemon started successfully *

I can see it's there
lsof -i tcp:5037
adb     19131 bw    7u  IPv4 0x3c0bc54e449e35f5      0t0  TCP localhost:5037 (LISTEN)

There's no devices attached
adb devices

So far so good
Now when I start up genymotion, and start a virtual device, my adb seems to have been killed and cannot start because the virtual device has apparently killed it and started its own adb instance
unknown-6c-40-08-9b-25-2c:todo bw$ adb devices
adb server is out of date.  killing...
cannot bind 'tcp:5037'
ADB server didn't ACK
* failed to start daemon *
error:

This now gives me no way to add the device to adb so that I can access it by doing
cordova run android

This command now fails, because it can't find a running device.
I tried running adb start-server as root, so that genymotion couldn't kill it, but then the genymotion virtual device wouldn't start up.
What gives? Grateful for any ideas.. Thanks!

A: Well, it's not entirely satisfactory, but I have got it to work.
When I change the settings in genymotion under the settings->adb tab to reference my android sdk rather than the built-in genymotion android tools, everything works fine. That's great, but I don't understand how it can have been working yesterday before I changed that setting. Oh well. Hopefully this will help someone.


text:
Q: Scripted Data Source using JSON not working with BIRT while working in Java Class I will talking throw codes line with a few words, In alfresco I need to create a reports using its Workflows APIs that response as JSON, I found the solution for using JSON as a Data Source in this link (this will be good reference to full understand my issue) :
http://www.birt-exchange.org/org/devshare/designing-birt-reports/1053-scripted-data-source-using-json/
I downloaded the source and I understand how its works, and finally I was having a problem "authentication issue" and solved it by editing source file 'JSONParser.java', anyway I have another problem now, I have the following code in Java thats working:
package com.actuate.json.test;
import java.io.IOException;
import com.actuate.json.JSONParser;
public class TestJSONParse_OutBound {
    public static void main(String[] args) {
        try{
            JSONParser theParser = new JSONParser();
            theParser.loadData("http://localhost:8080/alfresco/service/api/workflow-definitions/activiti$CS-Outbound-WFPD:5:403/workflow-instances?state=active&format=json","admin","admin");
            System.out.println("Number of jobs found: " + theParser.getChildCount("data") + "\n");
            for(int i = 0; i < theParser.getChildCount("data"); i++){
                System.out.println(String.valueOf(i + 1) + ")  " + theParser.getValue("data", "description", i));
                System.out.println("\tID: " + theParser.getValue("data", "id", i));
                System.out.println("\tURL: " + theParser.getValue("data", "url", i));
                System.out.println("\tUsername: " + theParser.getValue("data", "initiator/firstName", i));
            }
        }catch (IOException ioe) {
            // TODO: handle exception
        }catch(Exception ex){

        }
    }
}

Result :
Number of jobs found: 2

1)  CS-Outbound-WFPD
    ID: activiti$499
    URL: api/workflow-instances/activiti$499
    Username: Administrator
2)  CS-Outbound-WFPD
    ID: activiti$404
    URL: api/workflow-instances/activiti$404
    Username: Administrator

BUT In BIRT Report in eclipse IDE no luck 1, in Scripted Data Source I put:
count = 0;
controller = new Packages.com.actuate.json.JSONParser();
controller.loadData(params["JSONURL"],params["USERNAME"],params["PASSWORD"]);
totalCount = controller.getChildCount("data");

and fetch rows in data set table like :
if(count < totalCount){
    row["id"] = controller.getValue("data", "id", count);
    row["url"] = controller.getValue("data", "url", count);

    count++;
    return true;
}
return false

But still giving me white page with head titles only, empty cells !!.
To get exception I uploaded it to Alfresco integrated with BIRT, and I got :
WARNING: Fail to execute script in function __bm_OPEN(). Source:
------
" + count = 0;
controller = new Packages.com.actuate.json.JSONParser();
controller.loadData(params["JSONURL"],params["USERNAME"],params["PASSWORD"]);
totalCount = controller.getChildCount("data"); + "
-----
A BIRT exception occurred. See next exception for more information.
Error evaluating Javascript expression. Script engine error: TypeError: [JavaPackage com.actuate.json.JSONParser] is not a function, it is object. (/report/data-sources/script-data-source[@id="8"]/method[@name="open"]#2)
 Script source: /report/data-sources/script-data-source[@id="8"]/method[@name="open"], line: 0, text:
__bm_OPEN()
org.eclipse.birt.data.engine.core.DataException: Fail to execute script in function __bm_OPEN(). Source:
------
" + count = 0;
controller = new Packages.com.actuate.json.JSONParser();
controller.loadData(params["JSONURL"],params["USERNAME"],params["PASSWORD"]);
totalCount = controller.getChildCount("data"); + "
-----
A BIRT exception occurred. See next exception for more information.
Error evaluating Javascript expression. Script engine error: TypeError: [JavaPackage com.actuate.json.JSONParser] is not a function, it is object. (/report/data-sources/script-data-source[@id="8"]/method[@name="open"]#2)
 Script source: /report/data-sources/script-data-source[@id="8"]/method[@name="open"], line: 0, text:
__bm_OPEN()
    at org.eclipse.birt.data.engine.script.JSMethodRunner.runScript(JSMethodRunner.java:147)
.
.
.
Caused by: org.mozilla.javascript.EcmaError: TypeError: [JavaPackage com.actuate.json.JSONParser] is not a function, it is object. (/report/data-sources/script-data-source[@id="8"]/method[@name="open"]#2)
.
.
.

Really I don't know what the problem is, and how to solve, if anybody have any idea for It, I spent about 1 week on it with no solution ...


text:
Q: Looking for an episode In the Batman Animated Series where Batman copies himself Did Batman ever copy himself to fight an enemy, and trick that enemy into doing the same?
https://en.wikipedia.org/wiki/Batman:_The_Animated_Series

A: It happens in the episode "What is reality" . Commissioner Gordon gets captured in the virtual world by Riddler. There's puzzle cube he has to solve. Batman knew he couldn't solve the cube in time, so he multiplied himself predicting Riddler would do the same, on the assumption that he could not sustain a collective consciousness and the entire virtual world; destroying the cube and letting Batman and Commissioner Gordon escape. More details here.
It starts at 2 minutes 24 seconds at this video here:

A: I don't know that he copies himself, but there was an episode that otherwise fits: His Silicon Soul. Batman stops some guys from robbing a warehouse, but gets hit in the process... and realizes he's a robot

Although injured, the fake Batman makes it to Wayne Manor and explores the estate. Alfred catches him and is fooled for a moment. However, when he sees the circuitry he realizes that what he's seeing is one of Karl Rossum's duplicants. Though the robot recognizes him and appears to be docile, Alfred is frightened.

Turns out he's a HARDAC replicant. A robot implanted with Bruce Wayne's memories.
Eventually HARDAC takes over and makes the robot turn the Batcave computer into a reborn HARDAC. The real Batman shows up to stop him

During the fight, the robot thinks he's killed the real one. Overcome with remorse, he smashes the computer before HARDAC can take over, killing himself in the process.

A: Not that I know of- there was an episode featuring a robot version of Batman created by the AI HARDAC, but they were on opposing sides, that's the closest I'm aware of.


text:
Q: Amazon S3 secure bucket Sorry if this is the incorrect place to ask.
Is they a way to secure a AWS S3 bucket so direct access to the files is denied but signed access is allowed?
I am new to all this, I have looked at Policies and Permissions but nothing seems to work.
Thanks in advance.

A: Follow this steps for Amazon S3 secure bucket:

*

*Give only full permission to owner only for all the objects in that bucket. You can try any third party tool like bucket Explorer to set ACL on all the objects exist in Amazon S3 Bucket.

*Just make sure that there is no policy set on that Bucket as Bucket policy has higher priority then ACL.

*Generate there signed url and provide the users, if you want that user can access your files.

[Disclosure : Bucket Explorer]

A: You will need to change the ACLs for all the objects in the bucket and remove access for the Everyone user. You will also need to make sure that you don't have a bucket policy that overrides those ACLs and allows public access to your files.
These links should help:
http://docs.aws.amazon.com/AmazonS3/latest/UG/EditingPermissionsonanObject.html
http://docs.aws.amazon.com/AmazonS3/latest/UG/EditingBucketPermissions.html
http://docs.aws.amazon.com/AmazonS3/latest/dev/UsingBucketPolicies.html
For the bucket policy, you need to look for any statements that give anonymous access to your objects and change those. These will contain a "Principal": { "AWS": "*" } in the policy.

A: FYI: S3 buckets are secure by default. You can open them up by:
1) setting the ACL on the bucket to "public read"
2) setting a policy for "everyone" via Principal: {AWS: * }
3) Uploading an object with ACL of "public read"
3) setting the ACL on an object to "public read" after upload


text:
Q: Given a linear operator $T$ and a linear functional $\phi_n(x)=(T(x))(n)$, show that $T$ is continuous iff $\phi \in X^*$ Given $X$ a Banach space, and $T:X \rightarrow l_p$ a linear operator, with $1 \leq p \leq \infty$, for all $n \in \mathbb{N}$ consider the linear functional $\phi_n:X \rightarrow \mathbb{K}$, defined by:
$\phi_n(x)=(T(x))(n)\,$ $\,\forall \, x \in X$.
Show that $T$ is continuous if and only if $\phi_n(x) \, \in \, X^*$, for all $n \in \mathbb {N}$.
$\mathbb{K}=\mathbb{R},\mathbb{C}$. Any suggestion?
There are different ways to see the continuity of a linear operator (for example, the continuity in zero, the acotation in the unit circle,...), right? But how can I get this "iff" with the given functional?

A: I think the 'if' part matters to you. To prove that $T$ is continuous, show that
$$
x_k \to x,\;Tx_k \to y \Rightarrow Tx= y.
$$ Then by closed graph theorem, we know that $T$ is continuous.
Now, since $Tx_k \to y$, we have
$$
Tx_k(n) \to y(n)
$$ for all $n$. Also by the assumption that $\phi_n$ is continuous, we also have $\phi_n(x_k) =Tx_k(n) \to \phi_n(x) = Tx(n)$ for each $n$. This establishes $Tx(n) = y(n)$ for all $n$, and therefore the claim follows.


text:
Q: Can't set .data() for an element I'm not able to add data to a dynamically added element:
var newItem = "
" + poi.Title + "
";
$(newItem).data('poiID', poi.ID);
$(newItem).data('poiTitle', poi.Title);

I've tried to add this:
alert($(newItem).data('poiID'));

right after the above line, but I keep getting "undefined".

A: Change your code like so:
var newItem = $("
" + poi.Title + "
");
newItem.data('poiID', poi.ID);
newItem.data('poiTitle', poi.Title);

...

alert(newItem.data('poiID'));

Example fiddle : http://jsfiddle.net/P4HWb/

A: That's because everytime you do $(newItem) you're creating a new element and you're not actually storing a reference to it.
Try:
var newItem = $("
" + poi.Title + "
");  /* create element as newItem */
newItem.data('poiID', poi.ID);                  /* add data to existing elem */
alert(newItem.data('poiID'));                   /* peek at your data */

Do note that at this point your new element is not yet attached to your DOM. To have it appear on the page, you'll need attach newItem using methods such as append(), prepend(), etc.

A: Your newItem is not in the DOM yet. Append it and then you can add .data() to it.
Or you can do something like this.
var newItem = $("
" + poi.Title + "
");
$(newItem).data('poi', poi); //That way the whole object is added to the element.

Then append it to the DOM.


text:
Q: Haskell trying to make class Matrix show instance I am a beginner in haskell, please, tell me what I am doing wrong.
    newtype (Matrix a) = Matr [[a]]
    instance Show (Matrix a) where
        show (Matr d) = print d
            where print [] = []
                print (x:xs) = show x ++ "\n" ++ print xs

    No instance for (Show a) arising from a use of `print'
    Possible fix:
    add (Show a) to the context of the instance declaration

A: The error message says "you need a Show instance for the element type of your matrix".
Also print is the wrong function to call here - show is equivalent to toString in languages like java - whereas print is an IO-operation that puts a String to stdout, you are using a name that has already a meaning.
newtype Matrix a = Matr [[a]]

instance Show a => Show (Matrix a) where
    show (Matr xx) = showlines xx
      where showlines [] = ""
            showlines (x:xs) = showelems x ++ "\n" ++ showlines xs
            showelems [] = ""
            showelems (x:xs) = show x ++ " " ++ showelems xs

now this showline/showelems pattern is already a common one the functions are unlines and unwords but the elements need to be strings already so
    show (Matr xx) = let strs = map (map show) xx
                     in unlines $ map unwords xx

or a bit terser
    show (Matr xx) = unlines $ map (unwords . map show) xx

here is some example usage of unlines/unwords
$ > ghci
GHCi, version 7.10.3: http://www.haskell.org/ghc/  :? for help
Prelude> putStrLn $ unlines ["a","b"]
a
b

Prelude> putStrLn $ unlines $ map unwords [["a","b"],["c","d"]]
a b
c d

Prelude> putStrLn $ unlines $ map (unwords . map show ) [[1,2],[3,4]]
1 2
3 4

@lisyarus' answer shows a lot more what happens behind the scene - but note the output of that show function is different from mine.
Prelude> import Data.List
Prelude Data.List> putStrLn $ concat . intersperse "\n" . map show $ [[1,2],[3,4]]
[1,2]
[3,4]

A: print (x:xs) = show x ++ "\n" ++ print xs

Here, x has type [a]. The instance Show [a] needs an instance of Show a. In other words, you have to tell how to show a in order to be able to show [a].
Add a dependency on Show a in your instance declaration:
instance (Show a) => Show (Matrix a) where
    ...

By the way, your code can be written using standard library like this:
show (Matr d) = concat . intersperse "\n" . map show $ d

Note: You need to import Data.List in your matrix module for the intersperse function!


text:
Q: CKEditor erase the content of tag (div) inline mode - Angular2 When I add the CKEditor in my tag (div) it crush the content of this tag
why it erase the content !!
this is my Directive CKEditor
import {Component, ElementRef, Input, OnInit,Directive} from '@angular/core';

@Directive({

    selector: 'div[ckeditorContent]'
})
export class CKEditor implements OnInit {
    @Input() ckeditorContent:string;

    constructor(private _elm:ElementRef) {

        CKEDITOR.inline(_elm.nativeElement);
    }

    ngOnInit() {

    }
}


text:
Q: ngxDaterangepickerMd Open datepicker from outside in angular I struggle to open ngxDaterangepickerMd from outside. I need two single-datepickers, one for the "from date" and one for the "to date". When I click on the from-button the from-datepicker should open and when I click on the to-button the to-datepicker should show up. Yet in my case when I click on the to-datepicker, the from-datepicker opens instead.
This is the code for my from-button:
 <input type="text" class="datepicker-calendar-icon"  ngxDaterangepickerMd  [locale]="{ format: 'DD/MM/YYYY' }" [(ngModel)]="startDate" [singleDatePicker]="true"
                        [autoApply]="true" [minDate]="minDate" (change)="setStartDate()" />
<button>from</button>

This is the code for my to-button:
 <input type="text" class="datepicker-calendar-icon"  ngxDaterangepickerMd  [locale]="{ format: 'DD/MM/YYYY' }" [(ngModel)]="endDate" [singleDatePicker]="true"
                        [autoApply]="true" [minDate]="minDate" (change)="setStartDate()" />
<button>to</button>

I followed this as reference  https://github.com/fetrarij/ngx-daterangepicker-material#open-datepicker-from-outside
Do you have any idea how I can solve this problem?


text:
Q: Modal window does not open to confirm deletion, js I am trying to integrate into my site in bootstrap 5, a modal window to confirm the deletions, but for some reason the modal sale is not shown and therefore the link is not executed. What is wrong? Maybe you know something better for it... Thank you
This is link href
<button class="btn btn-outline-danger waves-effect waves-light btn-sm" type="button">Eliminar</button>

Js code
$(document).ready(function(){
$('a[data-confirm]').click(function(ev){
    var href = $(this).attr('href');
    if(!$('#confirm-delete').length){

        $('body').append('

ELIMINAR REGISTRO<button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

¿Está seguro de que desea eliminar el elemento seleccionado?

<button type="button" class="btn btn-success" data-dismiss="modal">Cancelar</button>Borrar cliente

');
    }
    $('#dataComfirmOK').attr('href', href);
    $('#confirm-delete').modal({show: true});
    return false;
 });
});

edit, I've been doing no tests and the part that doesn't work is .append
edit again: Im solved
Edit again, in case someone has the same problem, I have changed this part of the code
$('#confirm-delete').modal({show: true});

to
$("#confirm-delete").modal("show");

A: In your javascript, if you change
$('#confirm-delete').modal({
    show: true
});

to
$('#confirm-delete').modal('show');

then it should trigger showing the modal. Tested on the latest Bootstrap (v5.2).

A: Your link was going to the href it has. You should cancel that.

$(document).ready(function() {
  $('a[data-confirm]').click(function(ev) {
    var href = $(this).attr('href');
    if (!$('#confirm-delete').length) {

      $('body').append('

ELIMINAR REGISTRO<button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

¿Está seguro de que desea eliminar el elemento seleccionado?

<button type="button" class="btn btn-success" data-dismiss="modal">Cancelar</button>Borrar cliente

');
    }
    $('#dataComfirmOK').attr('href', href);
    $('#confirm-delete').modal({
      show: true
    });
    return false;
  });
});

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">

  <button class="btn btn-outline-danger waves-effect waves-light btn-sm" type="button">

    Eliminar
  </button>


text:
Q: Select and Populate function in mongoose is not working I am trying to get the Movie field with movie title and populating the genre collection.
But the response I am getting is the movies collection with all properties.
const movies = await Movie.find()
    .populate("genre", "name")
    .sort("name")
    .select("title");

Response I got
[
{
"_id": "623724b0bdb7598002f04b83",
"title": "Titanic",
"numberInStock": 10,
"dailyRentalRate": 5,
"genre": {
"_id": "61e923f6860764ef514a64b5",
"name": "romantic",
"__v": 0
}
},
{
"_id": "623724d6bdb7598002f04b85",
"title": "Harry Potter",
"numberInStock": 15,
"dailyRentalRate": 5,
"genre": {
"_id": "61e923da860764ef514a64aa",
"name": "action",
"__v": 0
}
}
]

A: You can using (-) sign in front of the select field.
Ex:
const movies = await Movie.find()
  .populate("genre", "name")
  .sort("name")
  .select("title -numberInStock -dailyRentalRate");


text:
Q: CoreData - Update model class instead of creating new I am using CoreData in my iOS application. I face a problem most of the times while creating NSManagedObject classes.
This is what I do:

*

*I create an Entity in .xcdatamodeld file.

*Create attributes and relationships.

*Choose option Editor->Create NSManagedObject Class to create .h and .m classes.

*In .h and .m classes, I create some of my custom methods for fetching/saving objects.

So far so good. But afterwards in future if I have to change some attributes, I repeat step 2 and 3. But this time all of my custom code written in step 4 are removed automatically.
So my question is how can I update the existing classes? Instead of using option Editor->Create NSManagedObject Class which removes all my custom code.
Any help is appreciated.
Update:
Tested both approaches (Categories and Mogernator) and looks fine to me. But I have choosen Categories  of being a pure Xcode approach. I don't want to take the risk of any 3rd party which may break in future due to XCode updates or can cause problem of data migration.
Thanks to @Tom Harrington, and @Valentin Shamardin for guiding me :)

A: The best way to handle this is to use mogenerator to generate your model classes instead of having Xcode do it. With mogenerator you get two classes for each entity:

*

*One that is re-generated every time you rebuild the model classes

*One that is a subclass of the other, which is only generated the first time you build model classes and which mogenerator never changes afterward.

As a result you can put all your custom code in the subclass, and no matter how many times you re-generate your model classes, your code is never overwritten.

A: To make some additional methods or other stuff for your Core Data model classes you have to create Categories. This approach is used by Paul Hegarty in Core Data lections.

A: Whenever yo change or update your core data object model it becomes incompatible and cannot be open and as a result it gives crashes.
For this you need to perform Core Data Model Versioning and Data Migration.
Versioning is nothing just only provides you which model version is application going to use. Changes and update in core data model like modifying any attribute of entity or adding new entity. It is related with Core database model. Consider your application going to use 1.0 ver and using database model of 1. if u have some changes in database model its version increases and now you application going to use next version ie 2 of core database model
The details refer to this Apple Doc for Core Data Versioning
Also this will result in old Data loss. For this you need to perform Migration Process.
During migration, Core Data creates two stacks, one for the source store and one for the destination store. Core Data then fetches objects from the source stack and inserts the appropriate corresponding objects into the destination stack".
Please refer to Migration Process details on Migration on Raywenderlich
You need to use NSMigrationManager class and


text:
Q: Return an event.object to another function during collision - Corona SDK In my collision, I am detecting which spawns collide with my castle object at the bottom of the screen using event.object1.name and event.object2.name. this works fine but I would like to return that specific spawn (that collided with that castle) and use its event.object within another function if possible. How can I do this?
Cheers
My collision is as follows:
local function onCollision(event)
if event.phase == "began" and gameIsActive == true then

if event.object1 ~= nil and event.object1.name == "Blue" and event.object2 ~= nil and event.object2.name == "arrow" or event.object1 ~= nil and event.object1.name == "arrow" and event.object2 ~= nil and event.object2.name == "Blue" then
    if event.object2.name == "arrow" then display.remove(event.object2) event.object2 = nil; onHit()

    elseif event.object1.name == "arrow" then display.remove(event.object1) event.object1 = nil; onHit()

    end
end

A: you can simply use the object befor you delete it.
display.remove(event.object1) removes object1 from the display.
event.object.1 = nil deletes it
function doSomethingWithTheObject(obj)
  -- do something fancy here
  print(obj.name)
end

Then befor you delete the object call your function:
doSomethingWithTheObject(event.object1)


text:
Q: how to Access javascript Varibale in Angular js with HTML I have following code

and following HTML

Now my Source URL is not coming here..
Any idea how to do this
Thanks

A: You need to place your sourceUrl variable on the $scope object inside an angular controller, then tell your html element to be bound to the scope of that controller.


text:
Q: Compare volume levels between to mp3/wav files I have two audio recordings that are going to be recorded and saved in mp3 format. The content of the mp3's will be short, only a couple seconds, will be the same audio, but recorded at 2 different volume levels. I would like to use java, or preferably jsp so I can run it on a server, to tell me if there is a difference in volume between these two files. If anyone has any suggestions, I would greatly appreciate it!
Thank you.

A: Look at Java Sound API http://www.jsresources.org/faq_audio.html#compare_files

 Port lineIn;
        FloatControl volCtrl;
        try {
          mixer = AudioSystem.getMixer(null);
          lineIn = (Port)mixer.getLine(Port.Info.LINE_IN);
          lineIn.open();
          volCtrl = (FloatControl) lineIn.getControl(

              FloatControl.Type.VOLUME);
// Assuming getControl call succeeds,
  // we now have a way to detect volume calls
} catch (Exception e) {
  System.out.println("Failed trying to find LINE_IN"
    + " VOLUME control: exception = " + e);
}


text:
Q: Array.map function isn't applying to Object value I'm attempting to re-map an Object that comes from an API call.
The format of the response is the following:
data: {
    foo: [{
        id: "1",
        name: "joe",
        info: "whatever"
    }, {
        id: "2",
        name: "anna",
        info: "whatever"
    },...],
    bar: [...]
}

The code I'm using to re-map the object inside each response array is:
const DATA = response.data;
const entries = Object.entries(DATA);

for (const entry of entries) {
    entry[1].map(entry => ({
        id: entry["id"],
        mixed_info: entry["name"] + ", " + entry["info"]
    }));
}

When I console.log the data after this, it shows the same as the initial response, as if it completly ignored the map function.
What am I doing wrong? Thanks for the attention.

A: map returns a new array, you are ignoring the result of the call.

A: Assign the result of the map call:
entry[1] = entry[1].map(...);

Array.prototype.map returns a new array - it doesn't modify the original.

A: You have to reassign the entry:
  entry[1] = entry[1].map(/*...*/);

However that will only get reflected to the array inside entries, it won't change DATA. To change that, you have to either turn the key value pairs back into an object at the end:
  DATA = Object.fromEntries(entries);

Or you have to reassign the DATA properties while iterating:
   DATA[ entry[0] ] = entry[1].map(/*...*/);

I'd do:
  const { data } = response;

  for(const [key, value] of Object.entries(data)) {
     data[key] = value.map(/*...*/);
  }

A:     let result = {};
    for (const entry of entries) {
        result[entry[0]] = entry[1].map(entry => ({
            id: entry.id,
            mixed_info: `${entry["name"]  }, ${  entry["info"]}`,
        }));
    }

'result' contains exact remapped object.


text:
Q: Combinatorial approach to an inequality. Prove that $$\left(\frac{2^{10}}{11}\right)^{11} \gt \binom{10}{1}^2\binom{10}{2}^2\binom{10}{3}^2\binom{10}{4}^2\binom{10}{5} $$
I am practicing for an upcoming exam, and this question got me stuck. The $2^{10}$ and the binomial coefficients really beg for a combinatorial approach here, but I can't think of a good way.
I came up with an algebraic approach though, which I am going to post as an answer. I am looking for a combinatorial method right now.
Note: I am tagging this as combinatorics because that is what I am looking for, but you can answer if it is something significantly different from my algebra approach.

A: My first observation was that the right hand side is $$\prod_{i=0}^{10}\binom{10}{i}$$ and the left hand side is $$\left(\frac{\sum_{i=0}^{10} \binom{10}{i}}{11}\right)^{11}$$
Applying the $A.M \gt G.M$ inequality,
$${a_0+a_1 + a_2+a_3+\ldots +a_{10}\over 11} \geqslant \sqrt[11]{a_0a_1a_2a_3\ldots a_{10}}$$
yields the desired result immediately, inequality holding since all $a_i$'s are not equal.


text:
Q: php - how to make event queue working in offline mode in browser games While thinking about making browser games i met a disturbing trouble. Many games has something called 'event queue' that works like this. I have an "army" and send it to my opponent. I takes some amount of time. When my "army" gets oponent "army's" location there is a fight calculated so my "army" looses or wins. Everything is fine when me or my oponent is in the game. Some kind of ajax work can manage php script to be called and calculate fight - then save it's result to database. But how can it work if neither me, nor opponent is logged in when battle occurs? The good example of such game is Ogame when you are sending ships to another planet and it can meet it's destination when you are logged out, perform fight, get sources of your enemy and comeback, so it caluculates not only starships on planet but also amount of resources in that particular moment.
I've been thinking that i can save time of attack both attacker and his opponent in database rows and calculate the fight while any of player logs into the game, but this solution has many disadvantages. For example if there is third player that will attack before i will attack my oponent it will change hist army statistics (because he can kill part of his army) and i has many consequences. Also if none of the players would logout for a long time they would appear in game as they were not fighting and that would not be true..
Do you have any idea how to make such event queue? I guess using cron is also not good idea - it can be sometimes used to rarely and if there is thousands of players thousands of cron instances could be a killer for performance. Any concept would be appreciated - hope i described my problem good enough :)

A: In your database, create a "job" table (whatever contents you need, plus an EXPIRE date - which is when the job is finished) and everytime a user causes a job creation (e.g. moving ships from one cluster to another), make a new entry in this table with EXPIRE set to the time when the ships have arrived in the target cluster.
Then, everytime anyone (!) loads any site (even the startpage), the script checks for jobs in the queue which should have been done by now. If there are any jobs where EXPIRE is lower than NOW, then it does the job (or, for larger jobs, forks off a php cli process to do the job).
Assuming the case that it is 2012-12-28 12:00, the game has two players A and B, where A launches an attack on B that takes 6 hours. A job is created with EXPIRE=2012-12-28 18:00 and the content "Fleet foobar attacks B".
Case A:
Now, A logs out and nothing happens until 19:00. B logs in, and before anything other happens (this is important to ensure that "notifications" or inboxes don't appear out of sync), the script sees that a job is in the table and overdue. The script executes the jobs and creates the notification to B that he got overrun by a huge fleet from A. Job done, all is fine (except the mood of B).
Case B:
A logs out. At 18:30, an anonymous user visits the startpage. The script again looks in the jobtable and executes the job. B logs in at 19:00 and sees the notification of his loss. Job done.

A: The idea behind CRON-less event queue in my project is simply following:

*

*All events have "end" time. I'm using raw UNIX time() timestamps for easy compare operations.

*When user "clicks" (open any game page) queue engine fetches all events which are "ended" <= current time(), according to priority.
Events which are happened at same second are executed from high priority to low.

*If there are no users in game - no one need events. Just that simple :) Game sleeps until someone login the game and roll-back event queue, as described in second step.
You can add the same functionality on any web-site, which has periodic events and decent daily site traffic.
(Actually I also made cron.php backend by demand)


text:
Q: Unable to distribute archive after Adding AudioKit v5 as Swift Package When archiving my app using AudioKit v5 as Swift Package, I cant distribute it.
I see no version and identifier in the archive detail view.
Also there is no armv7 architecture, maybe it is related.
see attached images.
Any idea?

A: This is fixed and will available in a few minutes.


text:
Q: Get selected items of menubutton I have 3 MenuButtons in my JavaFX-Application, each one filled with CheckMenuItems.
I want to get the Text of every selected Item of the MenuButton. How shall i proceed?

A: Take all MenuItems, filter selected and map them to String.
MenuButton mb = new MenuButton();
mb.getItems().addAll(new CheckMenuItem("One"), new CheckMenuItem("Two"), new CheckMenuItem("Three"));
mb.getItems().stream().forEach((MenuItem menuItem) -> menuItem.setOnAction(ev -> {
    final List<String> selectedItems = mb.getItems().stream()
            .filter(item -> CheckMenuItem.class.isInstance(item) && CheckMenuItem.class.cast(item).isSelected())
            .map(MenuItem::getText)
            .collect(Collectors.toList());
    System.out.println(selectedItems);
}));


text:
Q: Find the max of a list in a Pandas dataframe column I am reading data from an RSS feed into a dataframe, and am trying to convert words (toddlers,kids,adults) to integers that represent min/max ages.  I have gotten as far as replacing the words with numerical strings:
df['audience_max'].head(10)

0          10
1       2,4,3
2       2,4,3
3        10,3
4         2,3
5           4
6         4,3
7         4,3
8     10,4,12
9    2,10,4,3
Name: audience_max, dtype: string

Next, I am running a for loop on this column to find the maximum value in each list and create a new column in the data frame.  I used str.split to change the string into a list:
maxlist=[]
for x in df['audience_max'].str.split(','):
    maxlist.append(max(x))

df['max_age']=maxlist

With the following result.  You can see that line 3,8 and 9 are not showing the maximum value:
0    10
1     4
2     4
3     3
4     3
5     4
6     4
7     4
8     4
9     4
Name: max_age, dtype: object

When I checked the line of code in the for loop that creates the list, it appears to create the list correctly:
(df['audience_max'].str.split(',')).head(10)
0             [10]
1        [2, 4, 3]
2        [2, 4, 3]
3          [10, 3]
4           [2, 3]
5              [4]
6           [4, 3]
7           [4, 3]
8      [10, 4, 12]
9    [2, 10, 4, 3]
Name: audience_max, dtype: object

But the max(x) for some reason does not seem to be returning the max consistently.  Is there a different function that I should be using?

A: You need also convert values to integers from strings after split:
df['max_age'] = df['audience_max'].apply(lambda x: max(map(int, x.split(','))))
#alternative
#df['max_age'] = df['audience_max'].apply(lambda x: max(int(y) for y in x.split(',')))
print (df)
  audience_max  max_age
0           10       10
1        2,4,3        4
2        2,4,3        4
3         10,3       10
4          2,3        3
5            4        4
6          4,3        4
7          4,3        4
8      10,4,12       12
9     2,10,4,3       10

Or convert splitted values to DataFrame by expand=True, convert to floats, because also NaNs, get max values and last convert to integers:
df['max_age'] = (df['audience_max'].str.split(',', expand=True)
                                  .astype(float)
                                  .max(axis=1)
                                  .astype(int))
print (df)
  audience_max  max_age
0           10       10
1        2,4,3        4
2        2,4,3        4
3         10,3       10
4          2,3        3
5            4        4
6          4,3        4
7          4,3        4
8      10,4,12       12
9     2,10,4,3       10

A: Based on this answer, I was able to use Series.str.extractall to get the max without having to use the for loop:
df['max_age_test'] = df.audience_max.astype(str).str.extractall('(\d+)').astype(int).max(level=0)

Which returned the correct max ages:
0     10
1      4
2      4
3     10
4      3
5      4
6      4
7      4
8     12
9     10


text:
Q: LWC: Slide an element in and out I'm building a Lightning Web Component for a standalone Aura app where ShowToastEvent isn't available.  I've seen an example of a custom LWC toast component that shows and hides itself using slds-show and slds-hide.
This component works OK, but it seems to appear and disappear kind of abruptly. What I'd like to do is have the element gracefully slide down from the top when it's shown, and slide up and out of view when it's hidden.  I'm not expert enough in CSS to know the most elegant way to accomplish this that would play well with the existing SLDS framework.
Here's a playground link to get folks started.  Thanks in advance!

2022 update
Since this post is frequently viewed and the LWC playground is no longer available, here is some code folks can use to get started with their custom animated toast components:
toast.html
<template>

                {variant}

                    <lightning-icon
                        icon-name={iconName}
                        size="small"
                        variant="inverse"
                    ></lightning-icon>

                        {title}

                    <template if:true={message}>
                        <lightning-formatted-rich-text
                            data-id="message"
                            value={message}
                        ></lightning-formatted-rich-text>
                    </template>

                    <button
                        class="
                            slds-button
                            slds-button_icon
                            slds-button_icon-inverse
                        "
                        title="Close"
                        onclick={closeModel}
                    >
                        <lightning-icon
                            icon-name="utility:close"
                            size="small"
                            variant="inverse"
                        >
                        </lightning-icon>
                        Close
                    </button>

</template>

toast.js
import { LightningElement, api } from "lwc";

export default class Toast extends LightningElement {
    title;
    message;
    variant;
    className = "slds-hide";

    /**
     * Shows a toast message
     * @param {string} title - The title of the message
     * @param {string} message - The body of the message; can include HTML tags that are supported for lightning-formatted-rich-text
     * @param {string} variant - The theme of the message; available values include "error", "warning", "success", and "info"
     * @param {boolean} [autoClose=false] - (Optional) Determines whether the toast should close automatically after the default or
     * specified amount of time. Defaults to false.
     * @param {number} [autoCloseTime=5000] - (Optional) Amount of time in milliseconds before the toast auto-closes. Defaults
     * to 5000 ms.
     */
    @api
    showToast(
        title,
        message,
        variant,
        autoClose = false,
        autoCloseTime = 5000
    ) {
        this.title = title;
        this.message = message;
        this.variant = variant;
        this.className = "slds-show";

        if (autoClose) {
            // eslint-disable-next-line @lwc/lwc/no-async-operation
            setTimeout(() => {
                this.closeModel();
            }, autoCloseTime);
        }
    }

    closeModel() {
        this.className = "slds-hide";
    }

    get mainDivClass() {
        return "slds-notify slds-notify_toast slds-theme_" + this.variant;
    }

    get messageDivClass() {
        return (
            "slds-icon_container slds-icon-utility-" +
            this.variant +
            " slds-icon-utility-success slds-m-right_small slds-no-flex slds-align-top"
        );
    }
    get iconName() {
        return "utility:" + this.variant;
    }
}

toast.css
.slds-show .slds-notify_container {
    animation: 0.5s forwards enter;
}

@keyframes enter {
    from {
        top: 0rem;
        opacity: 0;
    }
    to {
        top: 1rem;
        opacity: 1;
    }
}

A: Taake a look at the changes I've made here: https://developer.salesforce.com/docs/component-library/tools/playground/c_TB0R6b/13/edit
I've removed the slds-is-relative class on line 3 of toast.html, and added a few rules to toast.css. Cheers!

A: If anyone is still looking for this https://avionsalesforce.blogspot.com/2020/05/custom-toast-message-in-lwc.html


text:
Q: Trying to connect to a hosted runtime on Google Colab I've been trying to connect to a hosted runtime on Google Colab as usual. Until now, it worked perfectly, but for some reason right now everytime I press 'CONNECT' it shows up 'Unable to connect to runtime'.
Did anyone have the same issue?

A: I have the same issue sometimes, then I found it happened when I run large work or my running time is pretty long. Colab will prohibit your account to connect. The first time, your account can work after 24 hours. The second time, you will have a longer time penalty.


text:
Q: Cordova showing white screen when appis installed in 4.4.2 android version Cordova   showing white screen  when app is installed in  4.4.2  android version devices and it is working  fine in ios devices and 4.4.2 android version device and in 4.4.2 it was  showing error in console Channel not fired: onDOMContentLoaded
<?xml version='1.0' encoding='utf-8'?>
<manifest android:hardwareAccelerated="true" android:versionCode="1" android:versionName="0.0.1" android:windowSoftInputMode="adjustPan" package="com.Webstation.Osmosys" xmlns:android="http://schemas.android.com/apk/res/android">
    <supports-screens android:anyDensity="true" android:largeScreens="true" android:normalScreens="true" android:resizeable="true" android:smallScreens="true" android:xlargeScreens="true" />
    <uses-permission android:name="android.permission.INTERNET" />
    <application android:hardwareAccelerated="true" android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale" android:label="@string/app_name" android:name="WebstationApp" android:screenOrientation="userPortrait" android:theme="@android:style/Theme.Black.NoTitleBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
    <uses-sdk android:minSdkVersion="10" android:targetSdkVersion="19" />
</manifest>


text:
Q: Pandas add unique count column Given the following data frame:
import pandas as pd
df = pd.DataFrame(
    {'A' : ['foo', 'foo', 'foo', 'foo',
            'bar', 'bar', 'bar', 'bar'],
     'B' : [2, 4, 4, 2, 5, 4, 3, 2]})
df

    A       B
0   foo     2
1   foo     4
2   foo     4
3   foo     2
4   bar     5
5   bar     4
6   bar     3
7   bar     2

I would like a column ('C') of the count of unique values for 'B' per group of 'A' like this via a lambda x function:
    A       B    C
0   foo     2    2
1   foo     4    2
2   foo     4    2
3   foo     2    2
4   bar     5    1
5   bar     4    1
6   bar     3    1
7   bar     2    1

Thanks in advance!

A: If PC is right about your goal, maybe
>>> df["C"] = df.groupby(["A","B"])["A"].transform("count")
>>> df
     A  B  C
0  foo  2  2
1  foo  4  2
2  foo  4  2
3  foo  2  2
4  bar  5  1
5  bar  4  1
6  bar  3  1
7  bar  2  1

would give you what you want?  We're grouping on (A,B) pairs.

Cute bit of history: this is originally what I'd done, but then I tried it again and found I didn't need the ["A"].  But the reason it worked the second time without it is that I had the C column then, so there was something for the code to act on.. (sigh)


text:
Q: Haskell Map and Filter Here is my issue: I have two lists as follows: [(Float, Integer)] and [(String, Integer)]. Now I need to define a function that takes these two Lists and two Float values and returns a list of Strings. The two Float values correspond to a range given (min and max). I have to filter the first list so it only contains elements that are within the min and max range. Then, I need to use the filtered list and take it's Integer values, match them with the Integer values in the second list and return all the String values that match.
I have already defined a function for use as a filter condition that takes a (Float,Integer) and checks the Float value to see if it is within the given range.
And I have defined a function to take a (String,Integer) element and return the String.
I'm just having problems linking everything together, or maybe I am missing something!

A: You need (for example, there are different ways)
integersFromRange :: Float -> Float -> [(Float,Integer)] -> [Integer]
stringsFromInteger :: Integer -> [(String,Integer)] -> [String]

integersFromRange is basically map snd . filter condition, with condition constructed from the two Floats (you have that). stringsFromInteger could be implemented as map fst . filter condition. Then you combine the functions with
result = concatMap (`stringsFromInteger` stringList) (integerFromRange mini maxi floatList)

Using a set of Integers instead of a list would be more efficient since membership test in a Set is faster than in a list.


text:
Q: SEO friendly URLs - from blog.php?articleId=26 to blog/$articleTitle After finally getting my code to post a URL-friendly title to my db (for later use as the SEO optimised URL) I am now looking at how to get my blog script to accept said URL.
Ideally I would like my URLS to appear in a similar way to stack overflows.
Currently my URLs are like this:
blog.php?action=viewArticle&articleId=26

I want it to appear like this:
/blog/responsive-layout-design/

I have sorted out one side of the script - the side that create the new URL, and saves it in the database but I'm struggling to work out how to implement that on the front end.
I have looked at a few guides and examples dotted around but they only show how to create a URL such as:
store.php?action=viewItem&itemID=34 to store/item/34

Obviously, I could do this fairly easily with my URLs, but it's still just going to be displaying an article id, rather than the article title.
This is my current code for pulling articles from the database by ID - how would this be modified to gain the functionality I'm looking for?
function viewArticle() {
   if ( !isset($_GET["articleId"]) || !$_GET["articleId"] ) { homepage(); return; }
   $results = array();
   $results['article'] = Article::getById( (int)$_GET["articleId"] );
   $results['pageTitle'] = $results['article']->title . " | Blog";
   require( TEMPLATE_PATH . "/viewArticle.php" );
}

A: The way I've always done it is set the URL slug in the database.
So you'll store something like:
tblBlog
blogID | blogTitle | blogContent | blogURLSlug

You'd then set up pretty URLs using .htaccess
RewriteRule   ^/(blog)/(.*)/$   /blog.php?slug=$2

When selecting the page content out, select using the URLSlug instead
$stmt = $dbh->prepare("SELECT `blogTitle`, `blogContent` FROM `tblBlog` WHERE `blogURLSlug` = :slug");
$stmt->bindParam(':slug', $_GET['slug']);
$stmt->execute();
$blogData = $stmt->fetch();

This way, you can visit /blog/RWD-is-cool/ and it will select from the DB where the URLSlug = RWD-is-cool

A: You do not need databases to do that. All php frameworks ( that I know of ) support this type of urls and the method used to recognize what is what is called routing. Basically the structure of an url is the following www.website.com/controller(page)/method/getparameters. What you use to access this as such is a single entry point. In other words you only have 1 index.php file in the root directory and you redirect all calls to it, then break down the URL into its given components and decide what to do from there on. A simple example with apache:
.htaccess
RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^.*$ index.php [L,NS]

index.php
$page = str_replace('index.php','', $_SERVER['PHP_SELF']);
$page = str_replace($page,'',$_SERVER['REQUEST_URI']);
$page = explode('/',$page );
$controller = array_shift($page );
$parameters = array();
foreach ($page as $val){
    $parameters[] = urldecode($val);
}

Then in the url www.website.com/blog/responsive-layout-design/ you will have
$controller => 'blog'
$parameters => array(
    0 => 'responsive-layout-design',
    1 => ''
)

Hope that was helpful.


text:
Q: updating value in $scope in a sub state not working angularjs I have a parent state which shows the list of apartments, on clicking any apartment a sub state is loaded which shows all the images for it. But value of $scope is not passing to ng-repeat. What possible mistake i have made here.
app.js :
state('projects', {
    url: '/projects',
    templateUrl : 'resources/partials/projectsNew.html',
    controller : 'ProjectsController'
}).state('projects.project', {
    url: '/project/:param',
    templateUrl : 'resources/partials/projectImages.html',
    controller : 'ProjectController'
})

Controllers :
decorpotCtrls.controller('ProjectsController', [ '$scope', 'cart', 'projects', '$rootScope',
    function($scope, cart, projects, $rootScope) {
        projects.getAllProjects().success(function(data) {
            for (var i = 0; i < data.length; i++) {
                data[i].APARTMENT = data[i].APARTMENT.replace(/\s+/g, '-');
            }
            $scope.projects = data;
        });

    } ]);

decorpotCtrls.controller('ProjectController', [
    '$scope',
    'cart',
    'projects',
    '$stateParams',
    '$rootScope',
    function($scope, cart, projects, $stateParams, $rootScope) {
        var project = $stateParams.param;
        projects.getImagesByAppartment(project).success(function(data) {

            $scope.images = data;
            console.log($scope.images);
        });
    } ]);

html :
ProjectsNew.html :-

{{project.APARTMENT}}

        Bangalore

projectImages.html :-

when i am navigating from parent state projects to project ng-repeat doesnt works. I put a console log in ProjectController for the value of images its being populated correctly.


text:
Q: How to Run App in Background in Xamarin forms Cross platform I have developed a xamarin cross platform application and it is working fine in both iOS and Android.
Now we need to add a new feature: Keep the app open in the background even when it's closed. There is an action (email sending) that should happen every 5 minutes.

A: Background services (when app is in a background mode, not closed) is your solution, take a look:
iOS - Updating an Application in the Background: https://developer.xamarin.com/guides/ios/application_fundamentals/backgrounding/ios_backgrounding_techniques/updating_an_application_in_the_background/#background_fetch
Android - Creating Android Services:
https://developer.xamarin.com/guides/android/application_fundamentals/services/


text:
Q: Linux - Change permissions of all files & directories except 1 directory? This has stumped me for a bit now after working on it for a while. I need to change the permission settings of all files and directories so that group and others have no read, write, or execute access except for one specific directory. So far I have tried variations of `
chmod go-rwx | chmod go+rwx 'filename'

Any tips?`

A: I don't believe there's a solution shorter than a 2 steps pipeline.
Otherwise, you might want to check umask.
umask changes the default permissions on a file on creation (sadly only on file created by the same shell, but you can add this to the .bash_rc/.bash_profile, so that every shell you'll open will do this by default)
umask 077

will set the mask so that every new file will have permissions like 700.
So you might want to just use this so that in the future you won't need to re-launch that pipeline.
EDIT
if the problem was the pipeline itself, then I'd do
cd && chmod -R 700 && cd 'path/to/that/directory' && chmod -R 777

with the double '&' instead of the pipe just because there's not output to pipe, so an && might do the trick


text:
Q: How to write query to cloud search to get result on partial text match I'm adding a search by name options in my current CloudSeach integration. I'm searching for a key name by passing phrase field=name 'Stratosphere Hotel, Casino' for filter_query. This is working fine if I have an exact name match. But my search input for name is coming from google maps API and the data in my CloudSeach may not have an exact match with values in name key.
ie.
search input: DoubleTree by Hilton Hotel Irvine - Spectrum
CloudSeach value: DoubleTree by Hilton Irvine - Spectrum

search input: Candlewood Suites OC Airport- Irvine West Extended Stay Hotel
CloudSeach value: Candlewood Suites OC Airport-Irvine West

I have looked into near, fuzzy logic docks but I'm fairly new to CloudSeach.
https://docs.aws.amazon.com/cloudsearch/latest/developerguide/searching-text.html
https://docs.aws.amazon.com/cloudsearch/latest/developerguide/filtering-results.html
Is there any way to do a partial word search and match it and return those data. BTW 80% the data is matching names with CloudSeach's uploaded data, it's just around 20% data I'm having a problem searching with.


text:
Q: Is there anyway to make an executable compatible by using matlab mex? The executable is created by using mex. Currently I tried it on windows, but eventually I will need it for windows, linux, and mac os x.
The problem is it can only be used with the same version of matlab which I used to create it.
The main reason I think is if different version of matlab is used, then the path for libraries used by the executable will be different.
Is there any way that I can create an executable from mex which can be compatible with different versions of matlab?
Is possible that I set paths for libraries and header files associated with multiple versions of matlab?
Please correct me if I understand anything wrong above. Thanks a lot.
More detail information:
The way to generate my executable is to call:
mex('-v', '-f', [matlabroot '\bin\win32\mexopts\msvc90engmatopts.bat'], 'myexecutable.cpp');

In the msvc90engmatopts.bat file, paths are set for librarires and header files and etc.
msvc90engmatopts.bat is from matlab.