Q:

I need to test this code, but when writing a trigger, I get an invalid type

I need help. I am currently trying to test this code before uploading
public class CoreValuesExt
{
ApexPages.StandardController sc;
public boolean readonly {get; set;}
public Core_Values__c cv {get; set;}
public integer countEdit = 1;
public string buttonValue {get; set;}
public integer recordScan;

public CoreValuesExt(ApexPages.StandardController sc)
{
    this.sc = sc;
    cv = new Core_Values__c();
    cv.Account__c = sc.getid();

    readonly = true;
    buttonValue = 'Edit';
    recordScan = [SELECT COUNT() FROM Core_Values__c WHERE Account__c = :cv.Account__c];
   if (recordScan != 0){
   cv = [SELECT id, HSE__c, Professionalism_Integrity__c, Quality_Accuracy__c, Technology_Innovation__c, Timeliness__c, Value_for_money__c FROM Core_Values__c WHERE Account__c = :cv.Account__c];
    }

}

public ApexPages.PageReference Save()
{
    return sc.Save();
}

public void ApplyAction()
{
    countEdit++;
    Integer modolus = Math.mod(countEdit, 2);
    String total = cv.HSE__c + cv.Professionalism_Integrity__c + cv.Quality_Accuracy__c + cv.Technology_Innovation__c + cv.Value_for_Money__c + cv.Timeliness__c;
    if(modolus == 0)
    {
        readonly = false;
        buttonValue = 'Save';
    }
    else
    {
        if(total != 'nullnullnullnullnullnull')
           {
        if (recordScan == 0){
        insert cv;
        readonly = true;
        buttonValue = 'Edit';
        }
        else
        {
        update cv;
        readonly = true;
        buttonValue = 'Edit';
        }
        }
    }

}

}
With this trigger.
trigger CoreValuesTrigger on Core_Values__c (before insert) {

Core_Values__c cvs = Trigger.new;
CoreValuesExt.ApplyAction(cvs);

}

But when I try to save, I get a message saying:

Illegal assignment from List to
  CoreValuesExt__Core_Values__c at line 3 column 1

"
How do I go through with this? I need help. Thanks

A:

This is a bit odd of a construction

You have a trigger trying to use the constructor of a VF controller extension
Triggers get invoked when DML is done, and this can occur from many places, including clients that have nothing to do with user interaction though a VF page - such as Data Loader, REST/Web service clients, batch classes, future methods, etc. As such, certain VF context won;t be present and can lead to errors (such as using ApexPages methods).

Your specific error is because
trigger CoreValuesTrigger on Core_Values__c (before insert) {

Core_Values__c cvs = Trigger.new;
CoreValuesExt.ApplyAction(cvs);

}

Trigger.new is always a List<Core_Values__c>, never a singleton.
Hence assigning a list to a singleton generates the error.

Since a standardcontroller constructor would never be passed a list of sobjects, it can never accept Trigger.new.  And don't even think about passing Trigger.new[0] - all triggers need to be bulkified; avoiding this rule leads to a hole that you will inevitably have to dig yourself out of.. Use best practices from the get-go.
Lastly, SObject names ending in plural would be unusual (Core_Values__c). The object should represent one thing (Account, Contact, Opportunity, Order, Quote, Case, ...)
If the problem is testing -- then you do this with testmethods in test classes. See the Visualforce Developer Guide for examples on how to test controller extensions.  You don't write triggers.  Instead, you mock test data and pass to the controller class.
You are going to have to rethink your design and use of triggers versus controllers. More information is required to go further


Q:

How redirect the "no-route" cms page to home page after 10 second (not through server side)

How would be possible using js (in admin,cms-page) to redirect the 404 page to home page?

A:

you can add set setTimeout
<script type="text/javascript">
 function scr(){

  window.location = "http://www.yoururl.com";
 }

  setTimeout(scr,10000);
</script>


Q:

PHP display in minute only

Sorry for my bad english, im trying to convert duration from given date time range in minute only. There something weird when display only %I. My final out put using variable $durationDisplayMin. How how convert in minute only?
$startDate = "2018-01-20 15:10:10";
$end_datetime = "2018-07-29 11:11:05";
$start_datetime = new DateTime($startDate);
$end_datetime = new DateTime($endDate);
$diffr = $start_datetime->diff($end_datetime);
$durationDisplayMin = $diffr->format("%I");

A:

just found the answer:
$durationInMin = 0;
$start_datetime = new DateTime("2018-01-20 15:10:10");
$end_datetime = new DateTime("2018-07-29 11:11:05");
$Date1 = strtotime($start_datetime->format('Y-m-d H:i:s'));
$Date2 = strtotime($end_datetime->format('Y-m-d H:i:s'));
$durationInMin += round(abs($Date1 - $Date2)/ 60,2);


Q:

Is it necessary to eject an external drive before sleeping?

I have a question similar to a previous one about ejecting before shutting down.
Is it necessary or recommended practice to eject external drives before putting a Mac to sleep, whether it be via an explicit sleep command (e.g., from the Apple menu or other equivalent means), if Energy Saver puts the Mac to sleep, or the closing of a lid on a laptop Mac?
Edit: To add a clarifying point, I do not plan to physically disconnect the drive before waking the Mac from sleep?

A:

It's neither necessary nor recommended (at least from what I've read).
When you put the Mac to sleep, it will try and also put the external drive to sleep, thus parking its heads and turning off the drives. It won't eject it, however, so you can use it as soon as you wake your Mac again without having to mount it.
The benefit is that you don't have to worry about mounting it, as in most cases this would involve turning the drive off and on again, reconnecting the plug, or using diskutil from a Terminal—quite time consuming. Since I use my drive for Time Machine, I don't want to have to think about connecting it every time I wake my Mac.
The only downside I see is that you could accidentally plug the drive out. In that case, the Mac will wake up, and show you the error about a drive being disconnected without properly ejecting it. Since all data is written to the drive before going to sleep, this shouldn't cause any data loss though.
All in all, it's much more comfortable to just keep the drive mounted.


Q:

Prove $R \times R$ is NOT an integral domain

I have a question, and this is it in entirety:

Let R be a non-zero ring(that is, R contains at least one element other than the zero element). Prove that $R \times R$ is NOT an integral domain.

Now I haven't done a problem like this before, and it seems to be(from the Wikipedia definition) that this ring $R$ needs to be commutative to be an integral domain. Which it isn't stated to be here. What exactly am I meant to do? I haven't been given anything else than the area in grey.

A:

Hint:
Elements of $R \times R$ will look like $(x, y)$ such that $x, y \in R$.  Further, multiplication is defined as follows:
$$(a, b)(x, y) = (a \cdot x, b \cdot y)$$
Where $a \cdot x$ and $b \cdot y$ are computed in the original ring $R$.  Addition is defined similarly.
Next, the additive identity (traditionally called "zero") in $R \times R$ will be the element $(0, 0)$.  This is easy to see since $(x, y) + (0, 0) = (x+0, y+0) = (x, y)$.
Finally, to show that $R \times R$ is not an integral domain for any ring $R$, it is your task to think of at least two nonzero elements $(a, b)$ and $(c, d)$ in $R \times R$ such that $(a, b)(c, d) = (0, 0)$.

Some clarification:  It is true that all integral domains are commutative.  From this, if $R$ is not commutative, then $R \times R$ is not commutative (why?) and won't be an integral domain.  However, even if $R$ is a commutative ring, $R \times R$ is never an integral domain.  This follows from the work above, since the direct product will always have zero divisors.


Q:

Como criar um login com diferentes níveis de permissão?

Como criar um login com diferentes níveis de permissão? É necessário criar uma tabela no banco de dados para realizar login? Tenho lido sobre formsauthentication, cookies e etc, mas ainda não entendi muito bem.

A:

Vou explicar dois: ASP.NET Membership e ASP.NET Identity.
ASP.NET Membership
É uma arquitetura padrão de dados feita para lidar com os usuários de uma aplicação. No caso supõe-se que sua aplicação possuirá a própria base de usuários, e alguns outros sistemas de logins de outros sites podem ser integrados. Pode trabalhar com o Forms Authentication, que é outro padrão da Microsoft, muito mais simples, mas dirigido ao processo de autenticação do usuário em si.
Existe uma implementação (muito) simples de logins e senhas chamada Simple Membership em que não é necessário escrever código. Aqui tem um tutorial de como fazer.
Caso você queira implementar algo mais customizado, tem algumas respostas minhas em que ensino em detalhes como fazer:

Tela de login com membership e mvc5
Segurança e autorização usando Roles
Como criar uma página de login e senha no ASP.NET?

ASP.NET Identity
Sendo o Membership limitado para trabalhar com novos métodos de autenticação e permissão, foi criado o Identity, que basicamente traz agumas novidades como trabalhar com Claims e métodos mais sofisticados de identificação de usuários.
Algumas respostas minhas a respeito:

Exemplo do ASP.NET Identity usando o SQL Server
Asp.Net Identity, como usar apenas Roles ou Claims?


Q:

Nullpointerexception when adding to List "Edit source lookup path"

I'm trying to create a gridView of images. I am copying this android developers tutorial however they hardcoded the drawables into an Integer[], whereas I have to set mine to what the user chooses. mListContents is populated with objects. path and pathA are both initiated with a value. This is all confirmed with the debugger. When it gets to mList.add(pathA) it throws a nullpointerexception. When debugging it says "source not found" in the ActivityThread and gives me the option to "Edit source lookup path". Any issues changing from the tutorials Integer[] to a List<Integer>?
    public class ImageAdapter extends BaseAdapter {
    private Context mContext;
    private int mMenuId;
    dbhelper db;

    List<ClothingItem> mListContents;
    List<Integer> mList;

    public ImageAdapter(Context c, int menuId) {
        mListContents = new ArrayList<ObjectGeneric>();
        mContext = c;
        mMenuId = menuId;
        db = new dbhelper(mContext);
        setList(mMenuId);
        setDrawableList();
    }

 private void setDrawableList(){
            for(ObjectGeneric item : mListContents){
                int path = item.getImagePath();
                Integer pathA = (Integer) path;
                mList.add(pathA);
            }
        }

    // create a new ImageView for each item referenced by the Adapter
        public View getView(int position, View convertView, ViewGroup parent) {
            ImageView imageView;
            if (convertView == null) {  // if it's not recycled, initialize some attributes
                imageView = new ImageView(mContext);
                imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
                imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
                imageView.setPadding(8, 8, 8, 8);
            } else {
                imageView = (ImageView) convertView;
            }

            imageView.setImageResource(mList.get(position));
            return imageView;
        }

A:

From first glance, it looks like you're not initializing mList, so a null pointer exception is correct. Try initializing it, like so:
public ImageAdapter(Context c, int menuId) {
    mListContents = new ArrayList<ClothingItem>();
    mList = new ArrayList<Integer>();  // <---  here

    mContext = c;
    mMenuId = menuId;
    db = new dbhelper(mContext);
    setList(mMenuId);
    setDrawableList();
}


Q:

Bash function that will make sure that a number (n) is divisible by two other numbers (x) and (y)

I'm trying to solve the following kata from codewars (link). But I keep getting the following error: expected: "false" got: "".
So somehow I'm missing the arguments or something, or maybe I'm not returning correctly?
Instructions:
# Create a function isDivisible(n, x, y) that checks if a number n is
# divisible by two numbers x AND y. All inputs are positive, non-zero
# digits.

# Expected output:
isDivisible(12,2,6)--> true because 12 is divisible by 2 and 6
isDivisible(100,5,3)--> false because 100 is not divisible by 3

My script:
#!/bin/bash

function isDivisible () {
  if [ $(1 / 2) ] && [ $(1 / 2) ]
  then
    echo "true"
  else
    echo "false"
  fi
}

A:

Use the modulo % operator and check for the remainder. If its 0 then the number is divisible.
#!/bin/bash

isDivisible() {
    if (($1 % $2 == 0 && $1 % $3 == 0)); then
        echo "true"
    else
        echo "false"
    fi
}

$ isDivisible 12 2 6
true

$ isDivisible 100 5 3
false


Q:

MySQL trigger works on one field, not on second field, in the same table

I have a MySQL database with a table inventory with multiple triggers set up to capture changes in a second table inventory_history. I'm updating two of the fields (both in a single query, and in two separate queries), and the trigger consistently works on only one of the two fields (qty but not on last_sale).
Here is the troublesome query:
UPDATE inventory SET last_sale = 321, qty = 0 WHERE id = 123;

Alternately, these query combinations don't work either:
UPDATE inventory SET last_sale = 321 WHERE id = 123;
UPDATE inventory SET qty = 0 WHERE id = 123;

Here are the table constructs and triggers:
CREATE TABLE `inventory` (
  `serial_no` varchar(255) DEFAULT NULL,
  `qty` mediumint(9) DEFAULT NULL,
  `partid` mediumint(9) unsigned DEFAULT NULL,
  `last_sale` mediumint(9) unsigned DEFAULT NULL,
  `date_created` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
  `id` mediumint(9) unsigned NOT NULL AUTO_INCREMENT,
  PRIMARY KEY (`id`),
  KEY `partid` (`partid`),
  KEY `date_created` (`date_created`),
  KEY `last_sale` (`last_sale`),
  KEY `last_rma` (`last_return`),
  KEY `last_purchase` (`last_purchase`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE `inventory_history` (
  `date` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `inventory_id` mediumint(9) unsigned NOT NULL,
  `field_changed` enum('serial_no','qty','partid','last_sale','new') NOT NULL,
  `changed_from` varchar(255) NOT NULL,
  KEY `inventory_id` (`inventory_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TRIGGER `inv_new` AFTER INSERT ON `inventory`
 FOR EACH ROW BEGIN
  SET
    @id = NEW.id,
    @userid = NEW.userid,
    @date = now();

  INSERT INTO inventory_history VALUES (@date,@userid, @id, 'new', 'new');
END
//
DELIMITER ;
DROP TRIGGER IF EXISTS `inv_update`;
DELIMITER //
CREATE TRIGGER `inv_update` AFTER UPDATE ON `inventory`
 FOR EACH ROW BEGIN
  SET @userid = OLD.userid;
  SET @inv_id = OLD.id;

  IF (OLD.serial_no <> NEW.serial_no) THEN
    INSERT INTO inventory_history VALUES (now(), @userid, @inv_id, 'serial_no', OLD.serial_no);
  END IF;

  IF (OLD.qty <> NEW.qty) THEN
    INSERT INTO inventory_history VALUES (now(), @userid, @inv_id, 'qty', OLD.qty);
  END IF;

  IF (OLD.partid <> NEW.partid) THEN
    INSERT INTO inventory_history VALUES (now(), @userid, @inv_id, 'partid', OLD.partid);
  END IF;

  IF (OLD.last_sale <> NEW.last_sale) THEN
    INSERT INTO inventory_history VALUES (now(), @userid, @inv_id, 'last_sale', OLD.last_sale);
  END IF;
END
//
DELIMITER ;

So again, the qty trigger works, but the last_sale does not.

A:

Days later, turns out to be a simple but profound explanation (isn't it always?).
The trigger statement I used above was:
  IF (OLD.last_sale <> NEW.last_sale) THEN
    INSERT INTO inventory_history VALUES (now(), @userid, @inv_id, 'last_sale', OLD.last_sale);
  END IF;

The problem with this statement is that it doesn't capture a value change from NULL to 0, for example. It only captures a value to another value. So I needed to ADD a second statement for the NULL scenarios:
  IF (OLD.last_sale IS NULL AND NEW.last_sale IS NOT NULL) THEN
    INSERT INTO inventory_history VALUES (now(), @userid, @inv_id, 'last_sale', OLD.last_sale);
  END IF;

And all the world is right. :)


Q:

Saving to User Defaults in Swift

I am currently trying to save an array to the user defaults.
Here is my code:
//where things will be stored
let defaults = NSUserDefaults.standardUserDefaults()
var taskNames = [String]()
var taskPriorities = [Float]()

//this is the function that saves tasks
func saveTask() {
    println(taskNames)
    println(taskPriorities)
    defaults.setObject(taskNames, forKey: "taskName")
    defaults.setObject(taskPriorities, forKey: "taskPriorities")
    defaults.synchronize()
}

//this is the function that loads tasks
func loadTasks() {
    var taskNamesLoad = defaults.dataForKey("taskName")

    println(defaults.dataForKey("taskName"))
    println(taskNamesLoad)
}

When I call the function to load the data (after saving some data with the other function of course) the output to the Console is nil and there is no data saved in the user defaults. How can I fix this?

A:

You should use arrayForKey or objectForKey instead dataForKey. Because you store the Array object, not NSData.
Like below:
func loadTasks() {
    var taskNamesLoad = defaults.arrayForKey("taskName")

    println(defaults.arrayForKey("taskName"))
    println(taskNamesLoad)
}


Q:

How do I fold in vim through blank lines (rspec example)?

I am trying to get vim to fold the way I want, but an having troubles.
I use blank spaces in some of my test code to make it more legible, and I can't get vim to fold through the blank lines.
What I have:
describe 'Troubles' do

  describe 'Home' do

    let( :troubles ) { be_over}

    describe 'Pain' do
      it "shouldn't be this hard" { puts "but it is" }
    end
  end
end

and it want it to fold like:
describe 'Troubles' do

  describe 'Home' do
+--- 6  lines: -------------------
  end
end

Any way to get that done?
Here is my .vim setup for folding
set tabstop=2
set shiftwidth=2
set expandtab

set foldmethod=indent
set foldnestmax=10
set nofoldable
set foldlevel=1

A:

what folding method are you using?  using an indent fold method works fine for me (well it folds 5 lines since that first one is a blank unindented line.
set foldmethod=indent


Q:

Getting undefined variable when using Phalcon filter?

I am unclear here! I got error Notice: Undefined variable: filter when running below code!
But when I remove declare public $filter line,It worked !!! Why ?
use Phalcon\Filter;

class Auth extends Component {
    public $filter;//remove this line is working
    public function initialize() {
        $this->db = $this->getDI()->getShared("db");
        $this->login_db = $this->getDI()->getShared("login_db");
        $this->filter = new Filter();
    }
    public function auth($name) {
    $name = $this->filter->sanitize($name,"string");
    }

    }

A:

I made a simple test and reproduced the issue. Let me explain what happens here.

auth($name) is a constructor for the Auth class. Yes, this is old constructor style. This method is called when the object is created. initialize() is not called before the object is created and thus the code $this->filter = new Filter(); is not called before auth() method.
If you comment out declaration public $filter and access the property in constructor then the magic __get() method is invoked from parent class \Phalcon\Di\Injectable and the property is taken from DI container. This is why no errors are shown.
If you specify the property public $filter and create the object the constructor (auth() method) is called before initialize() method and thus property is only defined but not initialized. In this case you get the error.

Fatal error: Call to a member function sanitize() on a non-object in
  /var/www/app/models/Auth.php on line 19

Let me know if you have any questions.


Q:

How to get USA states dropdown list magento2 custom phtml

I need to display the all the USA states as a select drop-down in magento2 custom phtml. Can anyone help me.

A:

Add following code in your block class
<?php
    ...

    private $directoryData;

    public function __construct(
        ...
        \Magento\Directory\Block\Data $directoryData
        ...
    ) {
        ...
        $this->directoryData = $directoryData;
        ...
    }

    public function getStates()
    {
        return $this->directoryData->getRegionHtmlSelect();
    }
}

Add following code in your PHTML file
<?php

echo $block->getStates();

Extra Notes:
You can use following code to get the complete data.
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$states = $objectManager->create('Magento\Directory\Model\RegionFactory')
        ->create()->getCollection()->addFieldToFilter('country_id','US');
echo "<pre>";
print_r($states->getData());


Q:

Why is the Ruby Time Zone Designator formatting in strftime not working?

I am building a sitemap for Google, and want to use Ruby to format the datetime in their recommended format using the W3C standard with the time zone, like this,
YYYY-MM-DDThh:mmTZD

where TZD is the Time Zone Designator. However the default format being exported from the last_updated field from an SQL database by Ruby on Rails has spaces in it, eg
2014-09-19 10:33:05 UTC

How do I format the datetime in ruby to remove spaces and include the time zone in the correct format?
TZD can be accessed in ruby using the strftime method, like this:
myobject.updated_at.strftime("%Y-%m-%dT%H:%M:%S%z")

This will format time with TZD in the following format
2014-09-26T07:53:14+0000

However I need to get the TZD in format +00:00
According to the Ruby docs I should be able to use
%:z

However this shows up as
2014-09-26T08:10:21%:z

ruby 1.8.7

A:

Yes, but the docs you are linking are for latest stable version (1.9.3), not 1.8.7 - which BTW - is no longer supported. And it seems that %:z option was not available in Ruby 1.8.7.
There are also stable versions: 2.0.0, and 2.1.3 - in any of them you will get required behaviour.


Q:

Приложение которое даёт информацию о телефоне

Как можно сделать такую программу которая будет давать информацию/характеристики о телефоне, похоже на программу AIDA64 или CPU-Z (не реклама).

A:

Log.i("TAG", "SERIAL: " + Build.SERIAL);
Log.i("TAG","MODEL: " + Build.MODEL);
Log.i("TAG","ID: " + Build.ID);
Log.i("TAG","Manufacture: " + Build.MANUFACTURER);
Log.i("TAG","brand: " + Build.BRAND);
Log.i("TAG","type: " + Build.TYPE);
Log.i("TAG","user: " + Build.USER);
Log.i("TAG","BASE: " + Build.VERSION_CODES.BASE);
Log.i("TAG","INCREMENTAL " + Build.VERSION.INCREMENTAL);
Log.i("TAG","SDK  " + Build.VERSION.SDK);
Log.i("TAG","BOARD: " + Build.BOARD);
Log.i("TAG","BRAND " + Build.BRAND);
Log.i("TAG","HOST " + Build.HOST);
Log.i("TAG","FINGERPRINT: "+Build.FINGERPRINT);
Log.i("TAG","Version Code: " + Build.VERSION.RELEASE);

более подробно можно посмотреть здесь: https://developer.android.com/reference/android/os/Build.html


Q:

How Do I 'Restore' MS Word's Document Window Using Automation

I would like to be able to 'restore' MS Word's document window using Automation.
I already have the application object and I have tried calling App.Activate. Activate will bring the window to the top of the Window stack but not if Word is minimized. I can set the WindowState to Maximized, Minimized and Normal but what I really need to do is restore the window to the state it was in before the user minimized it (this would be equivalent to the user clicking on the application's button in the taskbar).
Is this possible using Word automation?
I am actually using C++ to to the automation so I am able to call Win32 API functions if required.
If there is not direct way to restore the window then the question becomes, 'how can I get the window handle of the ActiveWindow?'

A:

The best way I have come up with so far is as follows.
Get the active window using Application.ActiveWindow
This window object has a property named Caption. The caption appears in the document window's title.
I then use the Win32 function EnumWindows() to search for the Win32 window. I get the window text for each window returned by EnumWindows() using the Win32 function GetWindowText(). I attempt to find the caption in the window text and as an extra check I make sure the window text also contains the string 'Microsoft Word'.
Once I find the window, I then have it's Win32 window handle which I can then pass to the Win32 function ShowWindow(hWnd, SW_RESTORE).
You also have to call Application.Activate.
This solution is not perfect, for example I don't really like to assume that the window title will always contain the text 'Microsoft Word' but I also don't want to pick the wrong window.


Q:

Chrome - createMediaElementSource not working

I have a simple audio analyzer for my website:
var analyser = document.getElementById('analyzer');
var beat = document.getElementById('track_meta')
var canvas, ctx, source, context, analyser, fbc_array, bars, bar_x,
bar_width, bar_height;

function playAnalyzer() {
    context = new AudioContext();
    analyser = context.createAnalyser();
    canvas = document.getElementById('analyzer');
    ctx = canvas.getContext('2d');
    source = context.createMediaElementSource(playerE);
    source.connect(analyser);
    analyser.connect(context.destination);
    frameLooper();
}

function frameLooper() {
    canvas.width  = canwidth;
    canvas.height = canheight;
    ctx.imageSmoothingEnabled = false;
    window.requestAnimationFrame(frameLooper);
    fbc_array = new Uint8Array(analyser.frequencyBinCount);
    analyser.getByteFrequencyData(fbc_array);
    ctx.clearRect(0, 0, canvas.width, canvas.height); // Clear the canvas
    ctx.fillStyle = "white"; // Color of the bars
    function valBetween(v, min, max) {
    return (Math.min(max, Math.max(min, v)));
    }
    var beatc = fbc_array[2] / 4;
    var beatround = Math.round(beatc);
    //if (beatround < 10) {
    //    ctx.globalAlpha = '0.1125';
    //}
    //else {
    //    ctx.globalAlpha = '0.' + beatround;
    //}
    bars = canbars;
    for (var i = 0; i < bars; i += canmultiplier) {
        bar_x = i * canspace;
        bar_width = 2;
        bar_height = -3 - (fbc_array[i] / 2);
        ctx.fillRect(bar_x, canvas.height, bar_width, bar_height);
    }
}

My issue is that this does not work unless I am in incognito mode on chrome, otherwise I get this error:

Uncaught InvalidStateError: Failed to execute 'createMediaElementSource' on 'AudioContext': HTMLMediaElement already connected previously to a different MediaElementSourceNode.

I've tested this in Edge, Firefox and Opera and there it works fine. I've even reinstalled chrome to see if that would fix the issue to no avail. I just don't understand why it works fine in incognito mode but not otherwise.
So my question is, is it possible instead of using the <audio> element, connect the analyzer to a var audio = new Audio instead? If so, how would I do this?

A:

So for me, this worked:
Instead of using the <audio> element, use HTMLMediaElement using javascript. And then the only thing you need to do in order to connect the analyzer to your var audio = new Audio() is simply reference your audio variable in the source = context.createMediaElementSource(audio); variable.
This also fixed my errors.


Q:

Adding custom objects to NSMutable array not working, addObject returns empty array

I am making a number of custom objects. I want to add each object to an array, but after the code below is run the array is still empty.
for (int i = 0; i<= numberOfObjectsWanted; i++) {
     CustomClass *object = [[CustomClass alloc]init];
     [objectsArray addObject:object];
}

objectsArray is an NSMutableArray

A:

So if your array is nil, no message sends will have any effect on it...
objectsArray = [[NSMutableArray alloc] init];

beforehand.


Q:

"TANTO o más importante" vs "TAN o más importante"

Estaba haciendo ejercicios para el examen DELE C1 y había una pregunta de hueco:

Pues bien, resulta que contemplar el mundo en tres dimensiones espaciales resulta que es ______ o más importante.

Hay alternativas de "tan", "mucho" y "tanto". Yo elegí "tan" pero la respuesta correcta sale "tanto". Por qué? Pensaba que "tan" se usa para adjetivos y "tanto" se usa para sustantivos?

A:

La palabra tanto se apocopa en tan exclusivamente cuando va seguida inmediatamente por un adjetivo, sin importar lo que venga después en la frase. No es el caso del ejemplo, ya que se interpone la construcción o más; por consiguiente, la respuesta correcta es tanto. Obsérvese la diferencia entre estas dos formas de construir la misma frase:

Pues bien, resulta que contemplar el mundo en tres dimensiones
  espaciales es tanto o más importante.
Pues bien, resulta que contemplar el mundo en tres dimensiones
  espaciales es tan importante o más.

(He quitado el segundo resulta que porque me ha parecido evidente que uno de los dos sobra; podríamos haber quitado el primero y dejado el segundo sin cambiar el sentido de la frase).
Ocurre algo parecido en otros casos de apócopes. Por ejemplo, mucho se apocopa a muy en condiciones similares a las de tanto y tan:

Este coche es muy grande.
Este coche es mucho más grande.


Q:

Step function of Poisson distributed number of uniformly distributed RVs is Poisson process

I want to proof this:
Let $N,X_1,X_2,\dots$ be independent RVs, $N$ Poisson distributed and the $X_k\sim\text{Unif}([0,1])$. Then
$$
N_t:=\sum_{k=1}^N 1_{[0,t]}(X_k)\quad (t\in [0,1])
$$
is a Poisson process (restricted to $t\in[0,1]$), i.e. $N_t(\omega)$ is an increasing and right-continuous step-function with jumps of size one and $N_t-N_s\sim\text{Pois}(\lambda(t-s))$ for some parameter $\lambda$.
I don't know how to show that the increments are Poisson distributed. I've tried this, but I don't know how to proceed or if this is even the right approach:
$$
N_t-N_s=\sum_{k=1}^N 1_{[0,t]}(X_k)-\sum_{k=1}^N 1_{[0,s]}(X_k)=\sum_{k=1}^N 1_{(s,t]}(X_k)
$$
It's obvious that
$$
P(X_k\in(s,t])=t-s\ \text{ and } P(X_k\in[0,s])=s
$$
So to calculate $P(N_t-N_s=n)$, $n\in\mathbb{N}$, we need to calculate the probability that exactly $n$ of the $X_k$ are in $(s,t]$ and $N-n$ of the $X_k$ are in $[0,s]$, which is
$$
P(|\{k\leq N : X_k\in (s,t]\}|=n,\ |\{k\leq N : X_k\in[0,s]\}|=N-n) \\
= \binom{N}{n}(t-s)^ns^{N-n}
$$
So somehow I ended up with an binomial distribution and there is also missing the probability that $N\geq n$ and I don't know how to combine that and receive a Poisson distribution as result.
Thanks for any help!

A:

In the understanding that $\binom{k}{n}=0$ if $n$ exceeds $k$ we have:$$P\left(N_{t}-N_{s}=n\mid N=k\right)=\binom{k}{n}\left(t-s\right)^{n}\left(1-t+s\right)^{k-n}$$
Note that you should take $1-t+s$ here (and not $s$).
Also be aware that $N$ is a random variable.
Working this out we find:
$\begin{aligned}P\left(N_{t}-N_{s}=n\right) & =\sum_{k=n}^{\infty}P\left(N=k\right)P\left(N_{t}-N_{s}=n\mid N=k\right)\\
 & =\sum_{k=n}^{\infty}e^{-\lambda}\frac{\lambda^{k}}{k!}\binom{k}{n}\left(t-s\right)^{n}\left(1-t+s\right)^{k-n}\\
 & =\sum_{k=n}^{\infty}e^{-\lambda}\frac{\lambda^{k}}{n!\left(k-n\right)!}\left(t-s\right)^{n}\left(1-t+s\right)^{k-n}\\
 & =\sum_{k=0}^{\infty}e^{-\lambda}\frac{\lambda^{k+n}}{n!k!}\left(t-s\right)^{n}\left(1-t+s\right)^{k}\\
 & =e^{-\lambda}\frac{\lambda^{n}}{n!}\left(t-s\right)^{n}\sum_{k=0}^{\infty}\frac{\lambda^{k}\left(1-t+s\right)^{k}}{k!}\\
 & =e^{-\lambda\left(t-s\right)}\frac{\left[\lambda\left(t-s\right)\right]^{n}}{n!}
\end{aligned}
$


Q:

Rotate x-axis labels at a given degree for boxplot in R

I generate a boxplot with code below:
boxplot(top10threads$affect ~ top10threads$ThreadID[], data = top10threads, xlab = "10 biggest Threads", ylab = "Affect", col=(c("gold","darkgreen")), srt=45)

But as you may notice that some labels in x-axis are missing, so I want to rotate them into 45 degrees. I added srt=45, but it doesn't work.
By setting las=2 can rotate them vertically, but it's not exactly I need.
How could I do that? Thanks.

A:

First, store the output of boxplot() as a object. It contains names of the groups. You can use $names to get them. Then use text() to add labels of the axis. The argument srt works on text().
tmp <- boxplot(y ~ x, data = df, col = c("gold","darkgreen"), xaxt = "n")
tick <- seq_along(tmp$names)
axis(1, at = tick, labels = F)
text(tick, par("usr")[3] - 0.3, tmp$names, srt = 45, xpd = T)

Data
df <- data.frame(x = sample(100:110, 100, T), y = rnorm(100))


Q:

How can personal and place names be extracted from text using C#?

Is there any C# algorithm by which personal and place names can be extracted from text?
e.g., given the following text:
St. Mark died at Alexandria, in Egypt.  He was martyred, I think.
However, that has nothing to do with my legend.  About the founding of
the city of Venice--

(taken from "The Innocents Abroad" by Mark Twain)
...is there any way to extract:
St. Mark
Alexandria (or better yet, "Alexandria, Egypt")
Venice

?
I realize that there is no way to get 100% accuracy (where all place names and personal names are captured, and no "false positives" are added), but 80% accuracy could be very valuable.
I understand that each word could be compared with an encyclopedia or some such, but there must be a better way. Also, how could the algorithm know to combine "St." and "Mark" and to see "Alexandria, in Egypt" as "Alexandria, Egypt"?

A:

I noticed that the links provided here are a bit dated. One project that is still active (and free [correction: GPL, so free for non-commercial]) is the Stanford Natural Language Processing (NLP) libraries (https://nlp.stanford.edu/software/). You can demo their Named Entity Recognition (NER) here. It even has a .NET wrapper (http://sergey-tihon.github.io/Stanford.NLP.NET/StanfordNER.html).
Microsoft also offers many similar algorithms through Azure Cognitive Services. You would be most interested in Entity Linking (https://azure.microsoft.com/en-us/services/cognitive-services/entity-linking-intelligence-service/)
I hope helps future viewers.

A:

You are best off using some kind of API that will be able to perform this kind of entity matching, as what you are asking is potentially very complex and requires some degree of semantic textual analysis backed up by a large database. I'd recommend at looking at APIs such as:
OpenCalais - English Semantic Metadata: Entity/Fact/Event Definitions and Descriptions web-service

Calais supports a rich set of semantic metadata, including entities, events and facts.

Alchemy API - Entity Extraction API

AlchemyAPI is capable of identifying people, companies, organizations, cities, geographic features, and other typed entities within your HTML, text, or web-based content. We employ sophisticated statistical algorithms and natural language processing technology to analyze your information, extracting the semantic richness embedded within.


Q:

transitionend event not firing when there's no transition

check it out:
http://jsfiddle.net/jqs4yy0p/
JS
$('div').addClass('switch').on('transitionend', function(e){
    alert('end');
});

CSS
div {
    background-color: red;
    /*transition: background-color 1s;    */
}

div.switch{
    background-color: blue;
}

if you uncomment the transition property it works, but without it no event is being fired!!
So if I make a slider thing, and want to preload next image after the transition effect completes I have to rely on the fact that there is a transition effect in the css. if there isn't the whole thing will break.
Doesn't this make transitions useless because you still have to mix them with javascript code in order to control them?

A:

Just to get things straight - the event transitionend (or any related javascript) is in no way needed to use or control CSS transitions/animations (which makes them completely independent, although, as a sidenote, CSS transitions/animations can be triggered using js, which can again sometimes be a very useful addition to the basic possibilities offered by the CSS interface).
Listening in on transitionend events can serve as a great tool when you are adding javascript functionality to your page as it makes your javascript aware of transition events triggered by the CSS.
E.g.: "I want to execute some javascript, but if there is a transition (triggered by the CSS), i want to wait for it to finish first."
Using something like
$('div').css('transitionDuration') !== '0s'

you can check if your object has a transition set.
QUICK DEMO (based on your jsfiddel)
And to get back to your "slider thing" example ... just swapping the images with js (will work just fine, already without the smooth transition effect) and adding CSS transitions for a reacher UX. Living the transitions out of the equation will probably effect the functionality less than living out some other parts of the CSS (position,width,height,opacity...).
Maybe I am failing to see your question here ... but IMHO the existence of events/listeners that give you the possibility to detect (or manipulate) CSS transitions/animations does in no way make these useless or redundant. To me it sounds similar to saying CSS pseudo elements are redundant as you can just add additional elements to your markup ... of course you can do it either way ... but I just like to keep my content (html), styling (CSS) and logic (JS) layers separate (but in the end it comes down to the specific problem at hand and of course to your personal preferences).


Q:

How to calculate the actual drag force on a wing?

I want to calculate the actual drag force that a NACA 63-412 wing would experience at a given planform area and relative wind speed. Airfoiltools gives a drag coefficient of 0.01676 for the optimal angle of attack. The drag equation states that $$F_D = \frac{1}{2} \rho*V^{2}*C_D*A.$$
What is the reference area associated with the drag coefficient above? Is it the planform area of the wing? If so, can I use the wing's planform area for $A$ in the drag equation and 0.01676 as the value for $C_D$?

A:

Yes, the reference area is commonly the projection of the exposed wing area on the wing's X-Y plane, the plane spanned by the wing chord and the wing span.
However, at the low Reynolds number you should find other airfoils more suitable. The NACA 6-digit range is more commonly used at Reynolds numbers > 10$^6$.


Q:

Action Listeners

I have rows and columns of jbuttons, and when each button is clicked they should turn red, and when clicked a second time they should return to their original color. So far, the code I have written is as follows:
public class MainPanel extends JPanel
{

    private JButton[][] btn1 = new JButton[3][5];

    public MainPanel()
    {
        JPanel MainPanel= new JPanel();
        MainPanel.setPreferredSize(new Dimension(700,700));

        JPanel p1 = new JPanel();
        {
            p1.setLayout(new GridLayout(3,5,10,10));
            p1.setBackground(Color.WHITE);
            for(int i = 0; i < 3; i++)
                for(int j = 0; j < 5; j++)
                {
                    btn1[i][j] = new JButton();
                    btn1[i][j].setBackground(Color.YELLOW);
                    p1.add(btn1[i][j]);

                    btn1[i][j].addActionListener
                    (
                        new ActionListener()
                        {
                            public void actionPerformed(ActionEvent e)
                            {
                                btn1[i][j].setBackground(Color.RED);
                            }
                        }
                    );
                }
        }
    }
}

The line btn1[i][j].setBackground(Color.RED); is stating 'local variables referenced from an inner class must be final or effectively final'. Does anyone know how to fix this?

A:

Add listeners in loop:
for(int i = 0; i < 3; i++)
    for(int j = 0; j < 5; j++) {
        final JButton btn = btn1[i][j];
        btn1[i][j].addActionListener(
            new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    btn.setBackground(Color.RED);
                }
            }
        );
    }

You added listener only to the first button.


Q:

Anchor doesn't work in chrome and safari browsers

I have a problem: an html anchor doesn't work in chrome and safari. The page goes down instead of up.
I have this HTML:

Вверх

And this JavaScript code:
var topScreen = window.pageYOffset ? window.pageYOffset : document.body.scrollTop;
        var myScreen = screen.availHeight;
        if(topScreen > (myScreen / 3)) {
            $(".toTop").fadeTo(0, 1.0);
        }
        else {
            $(".toTop").fadeTo(0, 0);

SCSS:
.toTop {
        display: none;
        position: fixed;
        bottom: 20px;
        right: 20px;
        z-index: 999999;
        transition: opacity 1s ease-out;
        outline: none;
        &:hover {
            transition-delay:0s;
        }
        a {
            color: #fff;
            text-decoration: none;
            &:hover {
                color: #000;
            }
        }
    }

What is wrong? Besides, this element stays focused after click.

A:

Now, since you have not set up a JSFiddle, it's difficult for us to exactly figure out what is happening in your project and what is expected. However, I have made a small fiddle that, I think, solves your problem.
HTML

Вверх

CSS
#to-top {
    height: 200vh;
}

The problem in your project is probably that you are trying to jump to another -tag, while the anchor-jump only seems to work with divs that contain an id. Please try the fiddle I've added and see if changing the element of to-top to div works for you.
In the future, you should really add your own fiddle to a question though.


Q:

What's the source of a custom not to eat meat at seudo shlishis?

Recently I hosted a traveller for Shabbos meals who follows a custom of not eating meat at seudo shlishis. (He would usually eat fish instead.)
What is the origin/source of this custom and how widespread is it?

A:

R. Pinchas Zavichi quotes a source for this custom. He begins by quoting R. Yissachar Dov Rokeach who proved that the post-Shabbat meal must have been dairy in the times of Israel's wanderings in the wilderness, because based on various legal rules there would have been no meat available for consumption on Saturday night. R. Zavichi then goes on to quote from R. Shalom of Belz that one should not eat meat at the third Shabbat meal in order to be able to drink coffee with milk at the post-Shabbat meal:
Tashit L'Rosho, Halachot V'Hanhagot Motzaei Shabat Kodesh

ועי' בס' חי וקיים בענין סעודה רביעית (עמוד קלג) שהביא שם כי פעם אחת
  האדמו"ר מהרי"ד מבעלז זיע"א ראה כמה אנשים שיושבים ואוכלים סעודה רביעית
  וראה שהם אוכלים מאכלי חלב בסעודה זאת ואמר להם תאמרו לי מהיכן מרומז
  בתורה הקדושה שבמדבר אכלו סעודת מלוה מלכה במאכלי חלב ולא ידעו לענות לו
  ואמר להם היות שבשר תאוה נאסר לישראל לאכול במדבר על כן היו מוכרחים
  לאכול בשר שלמים ושלמים הרי נאכלים לשני ימים ולילה אחד ונמצא ששלמים
  שנשחטו בערב שבת קודש אכלו אותם כל יום ערב שבת קודש ובליל שבת קודש קודש
  וביום שבת קודש עד הלילה והיות שאין שוחטין קודשים בלילה לא היה להם שום
  בשר לאכול במוצאי שבת קודש ועל כרחם אכלו מאכלי חלב עכד"ק יעו"ש ואכן
  כעין זה הובא עוד נמי בס' מקור חיים (אות ל) בשם הגאון הקדוש רבי מאיר
  יחיאל הלוי מאוסטרובצה זיע"א יעו"ש ובס' י"ג אורות ח"ב (עמוד רלה) הביא
  דהגה"ק רבינו שלום מבעלז זיע"א אמר שלא לאכול בשר בסעודה שלישית כדי
  שיוכלו לשתות קפה עם חלב במוצאי שבת בסעודת מלוה מלכה יעו"ש

This custom is also mentioned by R. Yisrael Chaim Friedman. He says that he has seen many righteous people and holy people who did not eat meat at the third meal, but instead ate fish.
Likutei Maharich, Seder Seudah Shelishit

וכן ראיתי אצל כמה צדיקים וקדושים שלא אבלו בשר בסעודה זו רק דגים

R. Yechezkel Shraga Frankel also mentions from R. Yechezkel Shraga Halberstam that the custom in Sieniawa was to not eat meat at the third meal, but no reason is given.
Rabbeinu Hakadosh M'Sieniawa p. 662

הגה"ק מציעשנוב דבק בכל ישותו באביו וכל דרכיו והליכותיו היו בהתאם
  למנהגיו אולם היו מעט דברים בהם שינה ממנהגי אביו כגון  אבילת דגים
  בסעודת יום שב"ק מנהג שבשינאווא לא נהגו בו ואף רבינו הורה לו להדיא שאין
  אוכלים אז דגים והוסיף דטעם הדבר כאותה סיבה שאין אוכלין בשר בסעודה
  שלישית


Q:

shortest code to center a number of columns

I'm working on a data set with a number of variables, some of which I want to center. The colnames which I want to center are stored in a list:
cols <- c('mahalanobis', 'response.sd')
df <- data.frame(subject = c(1,2,3), mahalanobis = c(4,3,1), response.time = c(4,1,5), random.var = c(2,5,7), response.sd = c(3,2,1))

> df
  subject mahalanobis response.time random.var response.sd
1       1           4             4          2           3
2       2           3             1          5           2
3       3           1             5          7           1

The code i'm currently using is:
df <- df %>%
   group_by(subject) %>%
   mutate(mahalanobis.c = mahalanobis - mean(mahalanobis),
          response.sd.c = response.sd - mean(response.sd))

Now, i'm wondering if there is a way to skip writing the same calculation within that mutate() function, but just with different variable names. So for instance type the centering line once and use the names within the cols list to do the rest.
Or are there more efficient ways of tackling this problem?

A:

You can use mutate_at to apply the function to multiple columns.
library(dplyr)
df %>% group_by(subject) %>%  mutate_at(vars(cols), list(c = ~. - mean(.)))


Q:

Issue with UIImagePickerControllerEditedImage

I need edit my Images before they import to the app but after editing the image reduces some quality how can avoid this ?
- (void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {

    [self dismissModalViewControllerAnimated:YES];
    imgEdited.image = [info objectForKey:UIImagePickerControllerEditedImage];

}

A:

You can crop UIImagePickerControllerOriginalImage manually by using the value provided via  UIImagePickerControllerCropRect.
Untested quick and dirty example:
static UIImage *my_croppedImage(UIImage *image, CGRect cropRect)
{
    UIGraphicsBeginImageContext(cropRect.size);
    [image drawAtPoint:CGPointMake(-cropRect.origin.x, -cropRect.origin.y)];
    UIImage *cropped = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return cropped;
}

- (void) imagePickerController:(UIImagePickerController *)picker
 didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    // …

    UIImage *originalImage = info[UIImagePickerControllerOriginalImage];
    CGRect cropRect = [info[UIImagePickerControllerCropRect] CGRectValue];
    UIImage *croppedImage = my_croppedImage(originalImage, cropRect);

    // …
}

A:

- (void)imagePickerController:(UIImagePickerController *)picker
                      didFinishPickingMediaWithInfo:(NSDictionary *)info {

  [picker dismissModalViewControllerAnimated:YES];
  [picker release];

          // Edited image works great (if you allowed editing)
  myUIImageView.image = [info objectForKey:UIImagePickerControllerEditedImage];
          // AND the original image works great
  myUIImageView.image = [info objectForKey:UIImagePickerControllerOriginalImage];
          // AND do whatever you want with it, (NSDictionary *)info is fine now
  UIImage *myImage = [info objectForKey:UIImagePickerControllerEditedImage];
}

You can edit ur image. Try this it may work for your application.Thanks!


Q:

MessageBoxResult vs. DialogResult

Two questions here, hope that is OK.
First, and mainly, I am trying to prompt the user when they exit my application whether or not they really want to exit. My code is as follows:
private void exitToolStrip_Click(object sender, EventArgs e)
{
    DialogResult mBoxResult = MessageBox.Show("Would you like to exit the program?", "Exit Program", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
    switch (mBoxResult)
    {
        case DialogResult.Yes:
            this.Close();
            break;
        case DialogResult.No:
            break;
    }
}

According to MSDN, I should be using MessageBoxResult mBoxResult  rather than DialogResult mBoxResult.
I am using .NET Framework 3.5. I read here that pre-3.0 should use DialogResult, but if I’m using 3.5, shouldn't MessageBoxResult work?
When I try to call it, I get

The type or namespace name MessageBoxResult could not be found (are
  you missing a using directive or an assembly reference?).

However, it works fine when I use DialogResult. Why is this?
My second question is regarding this piece of code:
case DialogResult.No:
break;

If somebody hits the Cancel button on the dialog, would it be proper to put anything in there besides the break? Or will everything function fine without it?

A:

DialogResult is for WinForms. MessageBoxResult is for SilverLight.
Just the break statement is fine for the No case. But using a switch statement is overkill here. if (response == yes) Close(); would suffice.
Note however that this isn't an ideal way to do what you want. What if the user clicks the close button on the window border, or presses ALT+F4? Instead, you should handle the FormClosing event:
private void MyForm_FormClosing(object sender, FormClosingEventArgs e)
{
    if (MessageBox.Show("Would you like to exit the program?", "Exit Program", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
        e.Cancel = true;
}

By setting e.Cancel to true, you cancel the closure of the form. By doing nothing, you allow the form to close.

A:

Use DialogResult if your application is a WinForms application
Use MessageBoxResult if your application is a WPF/Silverlight application

As you can see, namespaces are different: System.Windows.Forms (Winforms) vs System.Windows (WPF).


Q:

Why does Diablo stop attacking at extremely low life?

I noticed that when Diablo's life gets really low (not sure the exact %, but it's below 5%) during the final stage of fighting him, he will simply stop attacking and sit there, usually in some strange "I'm dying" position
Is there a reason for this?
The only thing I've used it for so far is to res dead players before killing him, and to remove my weapons/skills and punch him (for the Punch Diablo achievement)

A:

It's just a hard-coded 'cinematic' death - my friends and I like to call it 'beating the loot pinata'. If he starts doing it, you've won - celebrate (and make inventory space for the terrible loot he's about to drop)!


Q:

how to remove top links from some .phtml pages

visit the link : http://2.kidsdial.com/
on top right you can see :
"My account, My wishlist...etc"
I want to hide these links from some .phtml pages.
for example from this page : http://2.kidsdial.com/marketplace/

A:

fro example if you want to remove for product view page you can simply add you in local.xml
<marketplace_index_index>
<reference name="top.links">
   <remove name="wishlist_link"/>
   <remove name="checkout_cart_link"/>
</reference>
</marketplace_index_index>


Q:

Deploy ASP.NET Core Razor page to Azure App Service

I'm trying to host a ASP.NET Core RazorPages project in Azure App Service.
As an example I've created a new project and that's the app I want to publish.
At first: the publish function from VS2019 (CE) failed with an exception. It is a common exception and I'm not investigate more time in in.
So I thought: I publish it using the portal. So i have a Free account of Azure, create a Resource Group, a Hosting Plan and a Web App. Then i've upload my website using OneDrive and that works.
I've add the ASP.NET Core 3.1 (x86) Runtime to the extensions and the stack is .NET Core (32 bit, because of free plan). I've build the app also for x86.
But the application doesn't work. When I add a default Index.html to the application it works (but not the Razor Pages).
Who can solve this problem??
Regards
Donovan

A:

Looks like you copied too many files to your App Service. The bin/debug and/or bin/release folders should not be there. You need to prepare the website for deployment. In Visual Studio, you can do so by doing a right-click on the ASP.NET project and selecting 'Publish'. On the page that opens, configure a local publish to a folder. The contents of that folder should then be copied to the App Service.
For more information, see Deploy an app to a local folder using Visual Studio.
Also interesting: Host and deploy ASP.NET Core

The dotnet publish command compiles app code and copies the files required to run the app into a publish folder. When deploying from Visual Studio, the dotnet publish step occurs automatically before the files are copied to the deployment destination.
Folder contents
  The publish folder contains one or more app assembly files, dependencies, and optionally the .NET runtime.
A .NET Core app can be published as self-contained deployment or framework-dependent deployment. If the app is self-contained, the assembly files that contain the .NET runtime are included in the publish folder. If the app is framework-dependent, the .NET runtime files aren't included because the app has a reference to a version of .NET that's installed on the server. The default deployment model is framework-dependent. For more information, see .NET Core application deployment.
In addition to .exe and .dll files, the publish folder for an ASP.NET Core app typically contains configuration files, static assets, and MVC views. For more information, see ASP.NET Core directory structure.


Q:

SQLFiddle: must declare the scalar variable error

I'm trying to execute next SQL statement (SQL Server 2008 Profile)
DECLARE @fun int;
SET @fun = 40;

select cast(@fun as varchar(10)) + 'hello'

and SQLFiddle gives me the error: Must declare the scalar variable @fun
Where I'm wrong?

http://sqlfiddle.com/#!3/d41d8/42156

A:

You need to select the [Go] from last dropdown.

A:

I think the semicolons are introducing the problem here.
As described here: http://www.sql-server-helper.com/error-messages/msg-137.aspx and here: SQL Server - Variable declared but still says "Must declare the scalar variable", the problem arises when the statements are executed individually instead of as a “unit”, and the semicolons seem to trigger that.
When I remove the semicolons from your statement, it works: http://sqlfiddle.com/#!3/d41d8/42159


Q:

perl way of getting a value expressed with the memory unit

I'm searching a way to reduce the following piece of code to a single regexp statement:
if( $current_value =~ /(\d+)(MB)*/ ){
        $current_value = $1 * 1024 * 1024;
    }
    elsif( $current_value =~ /(\d+)(GB)*/ ){
        $current_value = $1 * 1024 * 1024 * 1024;
    }
    elsif( $current_value =~ /(\d+)(KB)*/ ){
        $current_value = $1 * 1024;
    }

The code performs an evaluation of the value that can be expressed as a single number (bytes), a number and KB (kilobytes), with megabytes (MB) and so on. Any idea on how to reduce the block code?

A:

Number::Format
use warnings;
use strict;

use Number::Format qw(format_bytes);
print format_bytes(1024), "\n";
print format_bytes(2535116549), "\n";

__END__

1K
2.36G

A:

You could set up a hash like this:
my %FACTORS = ( 'KB' => 1024, 'MB' => 1024**2, 'GB' => 1024**3 );

And then parse the text like this:
if ( $current_value =~ /(\d+)(KB|MB|GB)/ ) {
    $current_value = $1 * $FACTORS{$2};
}

In your example the regex has a * which I'm not sure you intend, because * means "zero or more" and so (+\d)(MB)* would match 10 or 10MB or 10MBMB or 10MBMBMBMBMBMBMB.


Q:

Is "closing for duplicates" still relevant/realistic on Stack Overflow?

Disclaimer: I only use SO from time to time, so this is only based on a "light" view of it.
Also, this is not a question about "should we close as a duplicate?". The answer is obviously yes. This question is more about the feasibility of managing all duplicates, and the implications of that.

SO generates a lot of traffic. Questions on the front page stay for about 15-30 minutes max, during which most of them get around 3 answers. It is hard to answer a question without checking new questions very often, since they get answers so fast.
It works well this way; most questions (apart from exotic ones) get correct answers, very fast.
Many questions are duplicates, but only a few seem to be "regular" or obvious ones. In most cases, it will take longer for someone to find a duplicate question, and vote for it, than for someone else to give a correct answer in the meantime.
This is a question only about Stack Overflow, because the other trilogy sites don't have such a large volume of users. On the other sites, typically Super User, duplicates are found, and closed quite fast, most of the time before an answer falls on them. But this is possible only because of the much smaller volume of users and questions.
So the question is: are these duplicates a problem which is out of control when these sites are gaining such volume?
Is it something to really worry about, or does it work fine this way? People can come and get an answer very quickly, without prior searching, just by asking. For most questions, there will always be people to answer. So from the point of view of someone coming to ask, it is not an issue. For obvious reasons, it is also not a problem for people answering, they get reputation this way.
It may be an issue from a storage point of view, since clearly duplication means more redundant data. But more importantly, it can be an issue to find an answer without asking a question yourself. With many duplicates, multiple useful answers become distributed over different questions, and it becomes harder to find most of them.
Extra question following on from these thoughts: should we be worried that the volume of users is finally pushing the site to be much easier to get duplicate answers from, than to search from?

A:

Should we be concerned? Yes. Here's an example:
How can I achieve jQuery animation queuing?
This is a fairly common question. I found 3 duplicates within minutes of it being asked, and posted them in comments. Note that the first two links I gave have well over 1000 views, hinting at their popularity...
The question was answered, and not closed. And... The answer is reasonably good - I might even recommend it in the future. But since it's attached to yet another question on the same topic, it adds still more overhead to the process of finding an answer for anyone who goes looking for one. If the answer had been posted to (or merged into) one of the previous questions, then it could be viewed much more easily by future readers.
This has the potential to get completely out of hand... Good answers can get less attention than they might have otherwise, mediocre answers can get accepted, and direct comparisons between alternate solutions become more difficult.
But asking people to not answer questions is futile. I think Lance has the right idea here: we need more merging.

A:

I think closing duplicates is fine, but we shouldn't stress about people answering them.  As Koper pointed out (and the logic that's always been touted), it just gives us more ways to find the relevant question in a search.
It would be nice if there was more active merging of answers to questions (on real exact duplicates).  I think for a high enough level of rep (15k?) there should be the ability to migrate answers from one question to another.
I've put in a feature-request for this.

A:

I think this is a potentially undesirable result of the reputation system. Would it be possible to add a new feature to the reputation system and answer system where a user could choose to answer a question OR below the text box with an answer, provide the link to a duplicate question. Then if that "answer" get's upvoted, they would receive 15 instead of 10 reputation points. This would theoretically encourage regular users to help moderate duplicates more carefully.
Just a shot in the dark. I find SO an extremely fascinating psychology case in results based on different kinds of encouragement.


Q:

Does MMA have a maximum likelihood estimation function?

I want to use MMA to solve question 23 in this post:

The English translation of this question is as follows:
Let the probability density function of population $X$ be $f\left(x, \sigma^{2}\right)=\left\{\begin{array}{cc}
\frac{\mathrm{A}}{\sigma} e^{-\frac{(x-\mu)^{2}}{2 \sigma^{2}}} & x \geq \mu \\
0 & x<\mu
\end{array}\right.$, where $\mu$ is a known parameter, $\sigma$ is an unknown parameter, and $\sigma>0$, $A$ is constant $\sqrt{\frac{2}{\pi}}$ (I've got the value of $A$ in advance). $X1$, $X2$,...,$Xn$ are simple random samples from $X$.
How to use the built-in probability theory function of MMA to calculate the maximum likelihood estimator of $\sigma^2$.

A:

This is done with EstimatedDistribution and the ParameterEstimator -> "MaximumLikelihood" option:
data = RandomVariate[NormalDistribution[], 100];
EstimatedDistribution[data, NormalDistribution[0, σ],
  ParameterEstimator -> "MaximumLikelihood"
]

NormalDistribution[0, 0.918944]

Use ProbabilityDistribution if you need to define a distribution from a custom probability density function.


Q:

Верстка и метод anti-aliasing Crisp

Здравствуйте

Шрифт Myriad Pro. Метод anti-aliasing Crisp.
Как можно при помощи css сверстать такое?
Спасибо.

A:

С помощью CSS можно только в браузерах на движке webkit( Safari, Chrome ), с помощью свойства -webkit-font-smoothing. В FF раньше была поддержка свойства font-smooth, однако потом была удалена. Про поддержку в IE говорить не приходится и так всё понятно.


Q:

moving files from subfolders to one folder

I have a folder with 5 steps deep folders and every folder has only one file. i want to move all files out to the main folder. ( i mean i want to get rid of subfolders completely, i need only the files in them) . like this:
folder/folder1/folder11/folder111/folder1111/folder11111/file-1.html
folder/folder2/folder22/folder222/folder2222/folder22222/file-2.html
folder/folder3/folder33/folder333/folder3333/folder33333/file-3.html
.
.
.
i want all .html files out in the "folder"
folder/file-1.html,file-2.html,.....
what is the batch file for this issue.
thanks in advance if anyone can help me with this.

A:

you can use this small batch file (create a foo.bat file):
@echo off
set dest=dest_dir
for /F %%a in ('dir /B /S /A-D folder') do move /-Y %%a %dest%\%%~na%%~xa

it scans the files (not directories) contained in the folder directory and moves them to dest_dir
Note: there's a safety to avoid overwriting files with the same name (/-Y) option. You are prompted if it happens.


Q:

How Do I Set A Style On A UserControl Dependency Property?

I have created a UserControl with a dependency property named HighlightedBorderBrush.
I registered the dependency property as follows:
    public static readonly DependencyProperty HighlightedBorderBrushProperty =
    DependencyProperty.Register("Highlighted_BorderBrush", typeof(Brush),
                                typeof(MyUserControl),
                                new FrameworkPropertyMetadata(Brushes.Black));

    public Brush HighlightedBorderBrush
    {
        get { return (Brush)GetValue(HighlightedBorderBrushProperty); }
        set {SetValue(HighlightedBorderBrushProperty, value); }
    }

In the code where I use the UserControl I am able to set the HighlightedBorderBrush property directly in XAML as follows:
    <local:MyUserControl HighlightedBorderBrush="Red" />

This works fine.  However, when I attempt to use a style I get an error:  "Exception has been thrown by the target of an invocation."
Here is the code where I attempt to use a style:
    <!-- Define a style for the user control -->
    <Window.Resources>
        <Style x:Key="UserControlStyle" TargetType="{x:Type local:MyUserControl}">
            <Setter Property="HighlightedBorderBrush" Value="Red"/>
        </Style
    </Window.Resources>

    .
    .
    .

    <!-- Use a Style to set the HighlightedBorderBrush property -->
    <local:MyUserControl Style="{StaticResource UserControlStyle}" />

I'm guessing that I am missing something obvious but cannot figure it out.  Help!

A:

As mentioned property name is incorrect in DependencyProperty registration.
Property name in DP registration should be HighlightedBorderBrush instead of Highlighted_BorderBrush.


Q:

CTreeCtrl SelectItem is not selecting item

I have 3 HTREEITEMs in MyCTreeCtrl tree control, a rootHti and two children, hti1 and hti2. I want to hightlight rootHti so I call myTreeCtrl.SelectItem(rootHti);. However, there is no change in the tree item. I also tried the long-hand way with the same results. That is, the item is not highlighted.
TVITEM item;
item.hItem = rootHti;
item.mask = TVIF_STATE;
item.state = TVIS_EXPANDED | TVIS_SELECTED;
item.stateMask = TVIS_EXPANDED | TVIS_SELECTED;
result = myTreeCtrl.SetItem(&item);

Is my assumption that selecting and highlighting incorrect? Clicking on the item highlights the item fine.

A:

I think rtischer8277's highlighted means it seems like mouse select a tree item.
So, when program start, 'root item' looks like below,

Without TVS_SHOWSELALWAYS style, even if SelectItem() is called, 'root item' will be different.
If I correct(I hope so), it is available by using TVS_SHOWSELALWAYS style. Setting TVS_SHOWSELALWAYS is available by using GetWindowLong() & SetWindowLong(), as well as by using 'Properties' window of 'Tree Control'.
EDIT
Here is code which shows how to change the tree control style by using GetWindowLong(), SetWindowLong().
CTreeCtrl* tree_ctrl = static_cast<CTreeCtrl*>(GetDlgItem(IDC_TREE1));

LONG tree_ctrl_style = GetWindowLongPtr(tree_ctrl->GetSafeHwnd(), GWL_STYLE);
if(!tree_ctrl_style)
{
    //FAIL
    AfxMessageBox(L"fail to get tree ctrl style");

    //GetLastError
    //

    return FALSE;
}

tree_ctrl_style |= TVS_SHOWSELALWAYS;

if(!SetWindowLongPtr(tree_ctrl->GetSafeHwnd(), GWL_STYLE, tree_ctrl_style))
{
    //FAIL
    AfxMessageBox(L"fail to set tree ctrl style");

    //GetLastError
    //

    return FALSE;
}

HTREEITEM root_item = tree_ctrl->InsertItem(L"Root");
tree_ctrl->InsertItem(L"Child1", 0, 0, root_item);
tree_ctrl->InsertItem(L"Child2", 0, 0, root_item);

tree_ctrl->SelectItem(root_item);

I used GetWindowLongPtr(), SetWindowLongPtr(), since MSDN says,

To write code that is compatible with both 32-bit and 64-bit versions
  of Windows, use GetWindowLongPtr.

However, if your program is just sample or test, you don't care about that.


Q:

Rails связь между двумя моделями

Есть две модели Uploads и Products
class Products < ActiveRecord::Base
  belongs_to :upload
  attr_accessible :article, :cost, :id_category, :name, :quantity
end

class Upload < ActiveRecord::Base
  has_one :products
  attr_accessible :upload
  has_attached_file :upload, :path => ":rails_root/public/images/:id/:style/:basename.:extension"
  include Rails.application.routes.url_helpers

  def to_jq_upload
    {
      "name" => read_attribute(:upload_file_name),
      "size" => read_attribute(:upload_file_size),
      "url" => upload.url(:original),
      "delete_url" => upload_path(self),
      "delete_type" => "DELETE"
    }
  end

end

Как связать эти две модели между собой, что бы можно было через Products (id = 1) достать все изображения из Uploads ?

A:

Мне немного непонятны ваши намерения, так как вы объявляете "has one" и "belongs to", что предполагает связь "один-к-одному", но в вопросе хотите достать "все изображения для product (id = 1)". Тем не менее попробую ответить вам, возможно это что-то для вас прояснит:
Вам нужно более внимательно погуглить "Rails ассоциации" и почитать про отношения "has one - belongs to", а я отвечу своими словами:
Вот правильная расстановка ассоциаций для ваших моделей (я исключил остальные ваши строки для читабельности):
class Products < ActiveRecord::Base
  has_one :upload
end

class Upload < ActiveRecord::Base
  belongs_to :product
end

То есть смысл тут такой, что "Upload принадлежит продукту, а Product имеет один Upload", а не наоборот.
Предлагаю для иллюстрации изучить скрипт (он ниже), который я сделал основе How to write an awesome Active Record bug report (это скрипт, который весь цивилизованный мир, в том числе ребята из Rails core, использует для моделирования простейших тестовых ситуаций, возникающих при работе с ActiveRecord).
Я изменил его немного для того, чтобы изобразить ваш случай. Вам нужно положить какую-нибудь картинку с именем image.jpg и этот скрипт в одну папку и убедиться в том, что у вас есть установленные гемы rails и paperclip
gem install rails
gem install paperclip

Ниже приведён сам скрипт, сохраните его как script.rb и запустите из директории, в которой лежат скрипт и картинка:
ruby script.rb

Сам скрипт:
gem 'rails', '>=3.1.0'
gem 'paperclip'

require 'active_record'
require 'paperclip'

# Print out what version we're running
puts "Active Record #{ActiveRecord::VERSION::STRING}"

# Connect to an in-memory sqlite3 database (more on this in a moment)
ActiveRecord::Base.establish_connection(
  :adapter  => 'sqlite3',
  :database => ':memory:'
)

# Create the minimal database schema necessary to reproduce the bug
ActiveRecord::Schema.define do
  create_table :products, :force => true do |t|
  end

  create_table :uploads, :force => true do |t|
    t.belongs_to :product

    t.string :upload_file_name
    t.integer :upload_file_size
    t.string :upload_content_type
    t.datetime :upload_updated_at
  end
end

class ActiveRecord::Base
  # Это описано на https://github.com/thoughtbot/paperclip/:
  # У нас нет полных Rails, поэтому мы подключаем Paperclip вручную
  include Paperclip::Glue
end

# Create the minimal set of models to reproduce the bug
class Product < ActiveRecord::Base
  has_one :upload
end

class Upload < ActiveRecord::Base
  belongs_to :product

  has_attached_file :upload, :path => ":id/:style/:basename.:extension"
end

# Create some test data
#
# If you're demonstrating an exception, then this is probably not necessary,
# but if your bug is to do with the wrong data being returned from the database,
# then you'll probably need some test data to show that.

product = Product.create
upload = Upload.new

image = File.open("image.jpg")
puts image.inspect

upload.upload = image

product.upload = upload
product.save

product = Product.find(1)
puts product.inspect
puts product.upload.inspect

Если вдруг окажется, что для вас эта информация имеет слишком продвинутый уровень, задавайте вопросы.


Q:

multithreading error with ABAddressBookRef

I have problems with the threads at the recorer for, I have a contact list of 600 and 6 shows me the following error.
Thread 1: EXC_BAD_ACCESS (code = 1, address = 0x29)
is the following code
-(void) actualizarContactos
{
    CFErrorRef *error = nil;

    ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, error);

    __block BOOL accessGranted = NO;
    if (ABAddressBookRequestAccessWithCompletion != NULL) { // we're on iOS 6
        dispatch_semaphore_t sema = dispatch_semaphore_create(0);
        ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error) {
            accessGranted = granted;
            dispatch_semaphore_signal(sema);
        });
        dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);

    }
    else { // we're on iOS 5 or older
        accessGranted = YES;
    }

    if (accessGranted) {
        //ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, error);
        ABRecordRef source = ABAddressBookCopyDefaultSource(addressBook);
        CFArrayRef allPeople = ABAddressBookCopyArrayOfAllPeopleInSourceWithSortOrdering(addressBook, source, kABPersonSortByFirstName);
        CFIndex nPeople = ABAddressBookGetPersonCount(addressBook);
       // NSMutableArray* items = [NSMutableArray arrayWithCapacity:nPeople];

        NSMutableArray *TodosContactos = [[NSMutableArray alloc]init];

        //consultar numero de contactos anteriores

        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];

        NSString *numeroContactos = [userDefaults objectForKey:@"numeroContactos"];

        int numContactos = [numeroContactos intValue];

        //validar si hay contactos nuevos
        if(numContactos != nPeople)
        {

        for (int i = 0; i < nPeople; i++)
        {
            //  NSMutableArray *contacto = [[NSMutableArray alloc]init];

            ContactsData *contacts = [ContactsData new];

            ABRecordRef person = CFArrayGetValueAtIndex(allPeople, i);

            //get First Name and Last Name

            // NSMutableArray *name = [[NSMutableArray alloc]init];

            if((__bridge_transfer NSString*)ABRecordCopyValue(person, kABPersonFirstNameProperty))
            {
            contacts.firstName = (__bridge_transfer NSString*)ABRecordCopyValue(person, kABPersonFirstNameProperty);
            }
            if((__bridge_transfer NSString*)ABRecordCopyValue(person, kABPersonLastNameProperty))
            {
            contacts.lastName =  (__bridge_transfer NSString*)ABRecordCopyValue(person, kABPersonLastNameProperty);
            }

            if (!contacts.firstName) {
                contacts.firstName = @"";
            }
            if (!contacts.lastName) {
                contacts.lastName = @"";
            }

            contacts.compositeName = [NSString stringWithFormat:@"%@ %@",contacts.firstName,contacts.lastName];

            // get contacts picture, if pic doesn't exists, show standart one

            Boolean sw = true;

               NSData  *imgData = (__bridge_transfer NSData *)ABPersonCopyImageData(person);
               contacts.photo = [UIImage imageWithData:imgData];
               if (!contacts.photo) {
                   sw = false;
                   contacts.photo = [UIImage imageNamed:@"contacts-ico@2x.png"];
            }
            //get Phone Numbers

                NSMutableArray *phoneNumbers = [[NSMutableArray alloc] init];

            Boolean swContactoSiguiente = true;

                ABMultiValueRef multiPhones = ABRecordCopyValue(person, kABPersonPhoneProperty);
               for(CFIndex i=0;i<ABMultiValueGetCount(multiPhones);i++)
               {

                   CFStringRef phoneNumberRef = ABMultiValueCopyValueAtIndex(multiPhones, i);
                   NSString *phoneNumber = (__bridge_transfer NSString *) phoneNumberRef;

                   //prueba
                  // NSLog([NSString stringWithFormat:@"name: %@ tel: %@",contacts.compositeName,phoneNumbers]);

                   if(![phoneNumber hasPrefix:@"+"] && ![phoneNumber hasPrefix:@"00"] && ![phoneNumber hasPrefix:@"011"])
                   {
                       swContactoSiguiente = true;
                   }
                   else
                   {
                       swContactoSiguiente = false;
                       [phoneNumbers addObject:phoneNumber];
                   }

               }

            if(swContactoSiguiente)
            {
               continue;
            }

            contacts.phones = phoneNumbers;

            //get Contact email

               NSMutableArray *contactEmails = [NSMutableArray new];
               ABMultiValueRef multiEmails = ABRecordCopyValue(person, kABPersonEmailProperty);

                for (CFIndex i=0; i<ABMultiValueGetCount(multiEmails); i++) {
                   CFStringRef contactEmailRef = ABMultiValueCopyValueAtIndex(multiEmails, i);
                NSString *contactEmail = (__bridge_transfer NSString *)contactEmailRef;

           [contactEmails addObject:contactEmail];
            // NSLog(@"All emails are:%@", contactEmails);

              }

            //  [contacts setEmails:contactEmails];
            contacts.emails = contactEmails;

            //guardar en CoreData

            if(contacts.phones.count != 0)
            {
                contacts.phone = [self deleteSpace:contacts.phones[0]];
            }

            //se valida existencia del phone en la base de datos
            if([self consultarTelefono:contacts.phone])
            {

            AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];

            NSManagedObjectContext *context = [appDelegate managedObjectContext];
            NSManagedObject *newContact;
            newContact = [NSEntityDescription insertNewObjectForEntityForName:@"Contacts" inManagedObjectContext:context];

            [newContact setValue: contacts.compositeName forKey:@"compositeName"];
            [newContact setValue: contacts.firstName forKey:@"firstName"];
            [newContact setValue: contacts.lastName forKey:@"lastName"];
            [newContact setValue: contacts.phone forKey:@"phone"];

            NSNumber *fv = [NSNumber numberWithBool:false];
            [newContact setValue:fv forKey:@"favorite"];
            if(sw)
            {
            [newContact setValue: imgData forKey:@"photo"];
            }

            NSError *error;
            [context save:&error];

          //  [items addObject:contacts];
            }

            //ABRecordRef
           // CFRelease(addressBook2);
          //  CFRelease(person);
          //  CFRelease(source2);
           // CFRelease(allPeople2);
           // NSLog([NSString stringWithFormat:@"%d",i]);
          }

            // se guarda en memoria numero de contactos
            NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

            [defaults setObject:[NSString stringWithFormat:@"%d",(int)nPeople] forKey:@"numeroContactos"];

            [defaults synchronize];

        }

    }
    else
    {
        UIAlertView *alertFailSave = [[UIAlertView alloc] initWithTitle:@"Error"
                                                                message:NSLocalizedString(@"TEXT_ACCESS", nil)
                                                               delegate:nil
                                                      cancelButtonTitle:NSLocalizedString(@"LO_BUTTON_OK", nil)
                                                      otherButtonTitles:nil];
        [alertFailSave show];
    }

}

A:

la corrección fue cambiar el siguiente codigo:
// ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, error);
       // ABRecordRef source = ABAddressBookCopyDefaultSource(addressBook);
       // CFArrayRef allPeople = ABAddressBookCopyArrayOfAllPeopleInSourceWithSortOrdering(addressBook, source, kABPersonSortByFirstName);
       // CFIndex nPeople = ABAddressBookGetPersonCount(addressBook);
       // NSMutableArray* items = [NSMutableArray arrayWithCapacity:nPeople];
por este.
    ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, error);
    CFArrayRef allPeople = ABAddressBookCopyArrayOfAllPeople(addressBook);
    CFIndex numberOfPeople = ABAddressBookGetPersonCount(addressBook);


Q:

Xcode Discarded All Changes without commiting

I accidentally hit discard all changes without having "committed". It seems to have wiped all the info from the app when I open Xcode but when I go to the project file all the .swift files and icons are still there. I have tried what the other posts have said about all of the git commands but this seems to be different. Since discarding changes brought me to the starting part of the project but I still have all the files from before is there an alternative way I can restore my program?

A:

Can't you just re-add the files in Xcode?
Xcode > File > Add files to...
... and reselect the .swift files / icons that you mentioned that are still there.


Q:

How to aggregate functions with groupby in SQL

I have tables like this.
I would like to groupbyand aggregate this in diffrent aggregate functions.
product sex  age
A        M    10
B        F    20
A        F    30
C        M    40

my desired result is like below.
Now I can group in productkey, but in this case, I must group them byproductandsex.
Are there any way to achieve it?
   count(M) count(F) avarage(M) average(F)
A   1         1         10       30
B   0         1         NA       20
C   1         0         40       NA

Thanks

A:

With conditional aggregation:
select product,
  sum(case when sex = 'M' then 1 else 0 end),
  sum(case when sex = 'F' then 1 else 0 end),
  avg(case when sex = 'M' then age end),
  avg(case when sex = 'F' then age end)
from tablename
group by product


Q:

How to permanently check in files into Visual Studio 2010?

I'm using Clearcase for source control, and when I right-click on my solution file, there's an option for checking in the files.
Trouble is that immediately after checking in the files, it automatically does a check-out.
How do I keep the files checked in for good?

A:

There should be an option in Visual Studio to prevent an "auto-checkout" after checkins.
However, check also the exact version of ClearCase you are using, because other bugs around checkout/chekin files also exist.

Sure enough, the OP Nav reports in the comment:

The checkbox is in:
Tools > Options > Source Control > Environment > Keep items checked out when checking in

You can see the setting in this article (which was for Team Foundation Server, but which is still relevant for this particular question)


Q:

Public static variables and Android activity life cycle management

According to the documentation the Android OS can kill the activity at the rear of the backstack.
So, say for example I have an app and open the Main Activity (let's call it Activity A). In this public activity class I declare and initialize a public static variable (let's call it "foo"). In Activity A's onCreate() method I then change the value of "foo." From Activity A the user starts another activity within my app called Activity B. Variable "foo" is used in Activity B. Activity B is then paused after the user navigates to some other activities in other apps. Eventually, after a memory shortage occurs, Activity A then Activity B can be killed. After the user navigates back to my app it restarts (actually "recreates") activity B.
What happens:

Will variable "foo" at this point have the value that was set to it when Activity A's onCreate() method ran?
Variable "foo" does not exist ?
Variable "foo" exists and but is now the initialized value and not the value set in Activity A's onCreate() method ?

A:

If the process is killed then all static variables will be reinitialized to their default values.
So whatever value you have set in Activity A will not persist

A:

Good explanation can be viewed here from 2:50
http://www.infoq.com/presentations/Android-Design
Here are some instructions for those who want to test this issue manually:
Create android v.4 emulator, then go to settings -> developer settings -> disable background tasks.
Then create sample android project with 2 activities,
declare static variable in activity A, initialize it in onCreate() method.
Place a button in activity A that starts activity B.
In Activity B's onCreate() method print the value of A.staticVar to logcat.
Launch the project - activity A appears. Hit the button - activity B appears, value of static variable is printed to logcat. Press the home button and launch any other program - your sample project process will be killed (because you have disabled background processes).
Now long-press on home button - you will see the list of recently launched programs. Select your sample project - OS will try to recover your project's activities back-stack and recreate last running activity B. But at this step program will crash with NullPointerException because A.staticVar will be null, and we are trying to print it to logcat.

A:

The answer is (3). If you need to keep values, persist them in shared preferences when each activity pauses and restore them when it resumes. Alternatively, you can also maintain an "initialized" static flag and re-initialize the static variables from any activity's onCreate() method if it is false.


Q:

nested sql sorting

I have three fields as below:
f1  f2  f3
b   x   100.22
c   y   150.15
a   x   240.35
a   y   130.25
b   y   789.34
c   x   199.89

I want to sort them like this:
f1  f2  f3
b   y   789.34
b   x   100.22
a   x   240.35
a   y   130.25
c   x   199.89
c   y   150.15

The main sort should be done based on f3, so the group of f1 values that have bigger sum value in f3 should be upper (descending order).
Also the values of f3 should be ordered descending in their own group.

A:

You can calculate the sum using a subquery and then use this for the order by:
select f1, f2, f3
from (select t.*, sum(f3) over (partition by f1) as sumf1
      from table t
     ) t
order by sumf1 desc, f1, f3 desc;

Actually, you don't need the subquery (although I prefer to use them with window functions):
select f1, f2, f3
from table t
order by sum(f3) over (partition by f1) desc, f1, f3 desc;


Q:

Add prefix to all filenames in all subfolders with a batch file

thanks in advance for your help.
I have a folder with a ton of randomly named subfolders. Within those subfolders are a number of files with numbered file names. For example..
\ParentFolder\UniqueFolderName\0001.ogg
\ParentFolder\UniqueFolderName\0002.ogg
\ParentFolder\UniqueFolderName\0003.ogg
\ParentFolder\DifferentFolderName\0001.ogg
\ParentFolder\DifferentFolderName\0002.ogg
\ParentFolder\DifferentFolderName\0003.ogg

I'd like to run a batch file from \ParentFolder\ that can rename the .ogg files to inherit the unique folder name and end up with something like this...
\ParentFolder\UniqueFolderName\UniqueFolderName - 0001.ogg
\ParentFolder\UniqueFolderName\UniqueFolderName - 0002.ogg
\ParentFolder\UniqueFolderName\UniqueFolderName - 0003.ogg
\ParentFolder\DifferentFolderName\DifferentFolderName - 0001.ogg
\ParentFolder\DifferentFolderName\DifferentFolderName - 0002.ogg
\ParentFolder\DifferentFolderName\DifferentFolderName - 0003.ogg

This is probably super simple stuff. But my tiny brain can't figure out how to do it without putting the batch file in every single subfolder.

A:

This could be done with following commented batch code:
@echo off
setlocal EnableExtensions DisableDelayedExpansion

rem Run in a separate command process started by FOR with cmd.exe /C the
rem command DIR to get a list of non-hidden *.ogg files in bare format
rem with just full qualified file name (drive + path + name + extension)
rem in specified directory and all its subdirectories.

rem This list is captured by FOR and processed line by line with disabling
rem the default line splitting behavior of __FOR__. The subroutine RenameFile
rem is called with each full qualified file name enclosed in double quotes.

for /F "delims=" %%I in ('dir "\ParentFolder\*.ogg" /A-D-H /B /S 2^>nul') do call :RenameFile "%%I"

rem Restore initial environment resulting in deletion of all
rem environment variables used in the subroutine below.
endlocal

rem Exit processing of this batch file if command extensions
rem are enabled as by default and expected by this command line.
rem Secure would be the usage of command EXIT. But that makes it impossible
rem to see error messages on running this batch file from within a command
rem prompt window and makes it also impossible to call this batch file from
rem another batch file. Secure would be also to jump with GOTO to a label
rem at end of the batch file below the subroutine RenameFile.
goto :EOF

:RenameFile
rem Get just file name without drive, path and extension.
set "FileName=%~n1"

rem Get just drive and path of file name ending with a backslash.
set "FilePath=%~dp1"

rem Get name of folder containing the file.
for %%J in ("%FilePath:~0,-1%") do set "FolderName=%%~nxJ"

rem Exit the subroutine if file name contains already the folder name.
echo "%FileName%" | %SystemRoot%\System32\find.exe /I "%FolderName% - " >nul 2>nul
if not errorlevel 1 goto :EOF

rem Exit the subroutine if there is already a file or folder
rem with new file name in the folder of the current file.
if exist "%FilePath%%FolderName% - %FileName%%~x1" goto :EOF

rem Rename the file by prepending it with folder name, space, hyphen, space.
ren %1 "%FolderName% - %FileName%%~x1"
goto :EOF

For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.

call /?
dir /?
echo /?
endlocal /?
find /?
for /?
goto /?
if /?
rem /?
ren /?
setlocal /?


Q:

Normalizing Excel Grid Intersection data into a flat list

I am trying to get Excel data, which was mapped using a grid/matrix mapping into a de-normalized for so that i can enter the data into a database.
How do you copy data in a grid from one excel sheet to the other as follow illustrated below.

I was trying something like this... but as you can see, i am far off!
Sub NormaliseList(mySelection As Range)
Dim cell As Range
Dim i As Long
i = 1
    For Each cell In mySelection
        If cell <> "" Then
                Sheets(2).Range("A" & i).Value = cell(cell.Row, 1).Value
                Sheets(2).Range("B" & i).Value = cell.Value
                Sheets(2).Range("C" & i).Value = cell(1, cell.Column).Value
                i = i + 1

    Next cell
End Sub

A:

I've got two posts, with usable code and downloadable workbook, on doing this in Excel/VBA on my blog:
http://yoursumbuddy.com/data-normalizer
http://yoursumbuddy.com/data-normalizer-the-sql/
Here's the code:
'Arguments
'List: The range to be normalized.
'RepeatingColsCount: The number of columns, starting with the leftmost,
'   whose headings remain the same.
'NormalizedColHeader: The column header for the rolled-up category.
'DataColHeader: The column header for the normalized data.
'NewWorkbook: Put the sheet with the data in a new workbook?
'
'NOTE: The data must be in a contiguous range and the
'rows that will be repeated must be to the left,
'with the rows to be normalized to the right.

Sub NormalizeList(List As Excel.Range, RepeatingColsCount As Long, _
    NormalizedColHeader As String, DataColHeader As String, _
    Optional NewWorkbook As Boolean = False)

Dim FirstNormalizingCol As Long, NormalizingColsCount As Long
Dim ColsToRepeat As Excel.Range, ColsToNormalize As Excel.Range
Dim NormalizedRowsCount As Long
Dim RepeatingList() As String
Dim NormalizedList() As Variant
Dim ListIndex As Long, i As Long, j As Long
Dim wbSource As Excel.Workbook, wbTarget As Excel.Workbook
Dim wsTarget As Excel.Worksheet

With List
    'If the normalized list won't fit, you must quit.
   If .Rows.Count * (.Columns.Count - RepeatingColsCount) > .Parent.Rows.Count Then
        MsgBox "The normalized list will be too many rows.", _
               vbExclamation + vbOKOnly, "Sorry"
        Exit Sub
    End If

    'You have the range to be normalized and the count of leftmost rows to be repeated.
   'This section uses those arguments to set the two ranges to parse
   'and the two corresponding arrays to fill
   FirstNormalizingCol = RepeatingColsCount + 1
    NormalizingColsCount = .Columns.Count - RepeatingColsCount
    Set ColsToRepeat = .Cells(1).Resize(.Rows.Count, RepeatingColsCount)
    Set ColsToNormalize = .Cells(1, FirstNormalizingCol).Resize(.Rows.Count, NormalizingColsCount)
    NormalizedRowsCount = ColsToNormalize.Columns.Count * .Rows.Count
    ReDim RepeatingList(1 To NormalizedRowsCount, 1 To RepeatingColsCount)
    ReDim NormalizedList(1 To NormalizedRowsCount, 1 To 2)
End With

'Fill in every i elements of the repeating array with the repeating row labels.
For i = 1 To NormalizedRowsCount Step NormalizingColsCount
    ListIndex = ListIndex + 1
    For j = 1 To RepeatingColsCount
        RepeatingList(i, j) = List.Cells(ListIndex, j).Value2
    Next j
Next i

'We stepped over most rows above, so fill in other repeating array elements.
For i = 1 To NormalizedRowsCount
    For j = 1 To RepeatingColsCount
        If RepeatingList(i, j) = "" Then
            RepeatingList(i, j) = RepeatingList(i - 1, j)
        End If
    Next j
Next i

'Fill in each element of the first dimension of the normalizing array
'with the former column header (which is now another row label) and the data.
With ColsToNormalize
    For i = 1 To .Rows.Count
        For j = 1 To .Columns.Count
            NormalizedList(((i - 1) * NormalizingColsCount) + j, 1) = .Cells(1, j)
            NormalizedList(((i - 1) * NormalizingColsCount) + j, 2) = .Cells(i, j)
        Next j
    Next i
End With

'Put the normal data in the same workbook, or a new one.
If NewWorkbook Then
    Set wbTarget = Workbooks.Add
    Set wsTarget = wbTarget.Worksheets(1)
Else
    Set wbSource = List.Parent.Parent
    With wbSource.Worksheets
        Set wsTarget = .Add(after:=.Item(.Count))
    End With
End If

With wsTarget
    'Put the data from the two arrays in the new worksheet.
   .Range("A1").Resize(NormalizedRowsCount, RepeatingColsCount) = RepeatingList
    .Cells(1, FirstNormalizingCol).Resize(NormalizedRowsCount, 2) = NormalizedList

    'At this point there will be repeated header rows, so delete all but one.
   .Range("1:" & NormalizingColsCount - 1).EntireRow.Delete

    'Add the headers for the new label column and the data column.
   .Cells(1, FirstNormalizingCol).Value = NormalizedColHeader
    .Cells(1, FirstNormalizingCol + 1).Value = DataColHeader
End With
End Sub

You’d call it like this:
Sub TestIt()
NormalizeList ActiveSheet.UsedRange, 1, "Name", "Count", False
End Sub


Q:

Local notification in Phonegap/Cordova

I am trying to use local notification on Phonegap. I use phonegap-plugin-local-notification 1.0.1 "phonegap-plugin-local-notification" and following code to test it (on device ready state):
        if ("Notification" in window) {
        Notification.requestPermission(function (permission) {
            // If the user accepts, let's create a notification
            if (permission === 'granted') {
                var notification = new Notification("My title", {
                    tag: 'message1',
                    body: "My body"
                });
                notification.onshow  = function() { console.log('show'); };
                notification.onclose = function() { console.log('close'); };
                notification.onclick = function() { console.log('click'); };
            }
        });
    }

What I got is Notification is NOT in window. Does anybody know how to use this plugin or am I supposed to add anything to config.xml.
Or is there any other solution to send local notification

A:

I used following plugin:
https://github.com/katzer/cordova-plugin-local-notifications
While I tested the plugin over Phonegap application it did not work but after building the android apk it works quite fine.


Q:

have an issue with undefined function with nodejs and geddy

ok its gose like this i have this code:
var PMP_Abstract = new JS.Class({});
var PMP = new JS.Singleton(PMP_Abstract,{
    //on Application Start
    initialize: function() {
    }
});

in short here i want put the main logic but... this just defines,
now i have this error:
[Mon, 26 Mar 2012 08:09:01 GMT] INFO Creating 1 worker process.

node.js:201
        throw e; // process.nextTick error, or 'error' event on first tick
              ^
TypeError: undefined is not a function
    at Object.<anonymous> (/Users/sivan/appTest/Testing/lib/PMP.js:1:82)
    at Module._compile (module.js:441:26)
    at Object..js (module.js:459:10)
    at Module.load (module.js:348:31)
    at Function._load (module.js:308:12)
    at Module.require (module.js:354:17)
    at require (module.js:370:17)
    at Object.<anonymous> (/Users/sivan/appTest/Testing/app/controllers/main.js:20:1)
    at Module._compile (module.js:441:26)
    at Object..js (module.js:459:10)
[Mon, 26 Mar 2012 08:09:01 GMT] ERROR Worker 4442 died.

now how do i fixed this ??
like have not idea what this function its talking about...

A:

You are using JS.Class without referencing it.
In your console type npm install jsclass then change your file to read
require("jsclass");

var PMP_Abstract = new JS.Class({});