Q:

Publish MVC Web App to Azure using VSTS

I am learning CI/CD using VSTS and Azure for my MVC Web App.  The build is successful, the deployment (to a specific slot in Azure) is successful, but when I navigate to the web app URL I'm still presented with the default home page.

2017-11-01T17:25:09.6208009Z ==============================================================================
2017-11-01T17:25:09.6218009Z Task         : Azure App Service Deploy
2017-11-01T17:25:09.6218009Z Description  : Update Azure WebApp Services On Windows, Web App On Linux with built-in images or docker containers, ASP.NET, .NET Core, PHP, Python or Node based Web applications, Function Apps, Mobile Apps, Api applications, Web Jobs using Web Deploy / Kudu REST APIs
2017-11-01T17:25:09.6218009Z Version      : 3.3.19
2017-11-01T17:25:09.6218009Z Author       : Microsoft Corporation
2017-11-01T17:25:09.6218009Z Help         : [More Information](https://aka.ms/azurermwebdeployreadme)
2017-11-01T17:25:09.6218009Z ==============================================================================
2017-11-01T17:25:13.2363661Z Got connection details for Azure App Service:'rsbi'
2017-11-01T17:25:22.3031769Z [command]"C:\Program Files\IIS\Microsoft Web Deploy V3\msdeploy.exe" -verb:sync -source:package='d:\a\r1\a\myapp-ASP.NET (PREVIEW)-CI\drop\myapp.zip' -dest:auto,ComputerName='https://myapp.scm.azurewebsites.net:443/msdeploy.axd?site=myapp',UserName='********',Password='********',AuthType='Basic' -setParam:name='IIS Web Application Name',value='myapp' -enableRule:AppOffline -enableRule:DoNotDeleteRule -userAgent:VSTS_945126af-40d2-8ab2-c875fd19e0af_release_1_1_1_1
2017-11-01T17:25:23.2157103Z Info: Using ID '8cb6f243-2593-4653-abd3-6666df1d45d4' for connections to the remote server.
2017-11-01T17:25:41.2558582Z Info: Adding ACL's for path (myapp)
2017-11-01T17:25:41.2558582Z Info: Adding ACL's for path (myapp)
2017-11-01T17:25:41.3594685Z Total changes: 2 (0 added, 0 deleted, 2 updated, 0 parameters changed, 0 bytes copied)
2017-11-01T17:25:41.3714688Z Successfully deployed web package to App Service.
2017-11-01T17:25:45.0533462Z Successfully updated deployment History at https://myapp.scm.azurewebsites.net/api/deployments/11509557141986
2017-11-01T17:25:45.0703260Z ##[section]Finishing: Deploy Azure App Service to Slot
2017-11-01T17:25:45.0793254Z ##[section]Finishing: Release

If I look at the Web App debug console in Kudu, I can see all of my content has been deployed:
11/01/2017  05:25 PM    <DIR>          .
11/01/2017  05:25 PM    <DIR>          ..
11/01/2017  02:12 PM    <DIR>          bin
11/01/2017  02:12 PM    <DIR>          Content
11/01/2017  02:12 PM    <DIR>          ExternalAssemblies
11/01/2017  02:12 PM    <DIR>          fonts
11/01/2017  02:12 PM    <DIR>          Scripts
11/01/2017  02:12 PM    <DIR>          Views
11/01/2017  10:31 AM    <DIR>          webapps
11/01/2017  02:11 PM             7,293 ApplicationInsights.config
11/01/2017  02:11 PM            32,038 favicon.ico
11/01/2017  02:11 PM               114 Global.asax
11/01/2017  02:11 PM             6,432 Web.config
               6 File(s)         50,508 bytes
               9 Dir(s)  53,635,162,112 bytes free

D:\home\site\wwwroot>

A:

The reason the home page related to JAVA is that there is webapps folder in wwwroot folder and you specify the Java Version in Application Settings page, more information, you can check There's nothing here yet after deploying Java Web App on Azure thread.
So, you need to remove this folder and turn off Java version.
Regarding java web job, you don’t need to specify Java Version in Application Settings, you can create batch file and set Path environment variable, then call java command, for example (include package folders into zip file, and specify the full name of main class):
set PATH=%PATH%;%JAVA_HOME%/bin
java [package].[main class name]

A related blog: Executing Java Web Jobs on Azure


Q:

Subject.create() Not working in RoR

I'm trying to use the Rails Console to create object instances of my models.
It is possible to create and save an instance to the database using the manual methods like so:
1.9.3p125 :003 > subject = Subject.new
 => #<Subject id: nil, name: nil, position: nil, visible: false, created_at: nil, updated_at: nil>
1.9.3p125 :004 > subject.name = "First Name"
 => "First Name"
1.9.3p125 :005 > subject.position = 1
 => 1
1.9.3p125 :006 > subject.visible = 'true'
 => "true"
1.9.3p125 :007 > subject.save
(0.2ms)  BEGIN
SQL (0.6ms)  INSERT INTO `subjects` (`created_at`, `name`, `position`, `updated_at`, `visible`) VALUES ('2012-06-21 13:28:35', 'First Name', 1, '2012-06-21 13:28:35', 1)
(20.4ms)  COMMIT
 => true
1.9.3p125 :008 > subject.id
 => 1
1.9.3p125 :009 > subject.new_record?
 => false

I'm totally new to RoR so I've got no idea where to begin trouble shooting this error:
1.9.3p125 :010 > subject = Subject.create(:name => "Second name", :position => 2)
ActiveModel::MassAssignmentSecurity::Error: Can't mass-assign protected attributes: name, position from /Users/Nick/.rvm/gems/ruby-1.9.3-p125/gems/activemodel-3.2.3/lib/active_model/mass_assignment_security/sanitizer.rb:48:in `process_removed_attributes'
from /Users/Nick/.rvm/gems/ruby-1.9.3-p125/gems/activemodel-3.2.3/lib/active_model/mass_assignment_security/sanitizer.rb:20:in `debug_protected_attribute_removal'
from /Users/Nick/.rvm/gems/ruby-1.9.3-p125/gems/activemodel-3.2.3/lib/active_model/mass_assignment_security/sanitizer.rb:12:in `sanitize'
from /Users/Nick/.rvm/gems/ruby-1.9.3-p125/gems/activemodel-3.2.3/lib/active_model/mass_assignment_security.rb:230:in `sanitize_for_mass_assignment'
from /Users/Nick/.rvm/gems/ruby-1.9.3-p125/gems/activerecord-3.2.3/lib/active_record/attribute_assignment.rb:75:in `assign_attributes'
from /Users/Nick/.rvm/gems/ruby-1.9.3-p125/gems/activerecord-3.2.3/lib/active_record/base.rb:498:in `initialize'
from /Users/Nick/.rvm/gems/ruby-1.9.3-p125/gems/activerecord-3.2.3/lib/active_record/persistence.rb:44:in `new'
from /Users/Nick/.rvm/gems/ruby-1.9.3-p125/gems/activerecord-3.2.3/lib/active_record/persistence.rb:44:in `create'
from (irb):10
from /Users/Nick/.rvm/gems/ruby-1.9.3-p125/gems/railties-3.2.3/lib/rails/commands/console.rb:47:in `start'
from /Users/Nick/.rvm/gems/ruby-1.9.3-p125/gems/railties-3.2.3/lib/rails/commands/console.rb:8:in `start'
from /Users/Nick/.rvm/gems/ruby-1.9.3-p125/gems/railties-3.2.3/lib/rails/commands.rb:41:in `<top (required)>'
from script/rails:6:in `require'
from script/rails:6:in `<main>'

Here is my Subject model:
class Subject < ActiveRecord::Base
  attr_accessible :title, :body, :name, :position
end

Thanks!
Things I've tried so far:

Exiting and reentering rails c.
Typing "reload!" into rails c
Reopening terminal

A:

You need to add
attr_accessible :name, :position

To your Subject model so you can create this in one step. Its a thing of security. You can read about this here:
http://api.rubyonrails.org/classes/ActiveModel/MassAssignmentSecurity/ClassMethods.html#method-i-attr_accessible
hf,..


Q:

Trying to get the validate command to work with multiple inputs

I'm not at all familiar with Tkinter's validatecommands, but I have done some research and would like to implement it in a widget that creates a tree graph from a bunch of entries. I want to restrict each entry so that the user can create lists of numbers from 0 to the highest row, not including the same row. So, for example, Row 0 entry can't have 0 in it or 12. So far I have only attempted to restrict the input from being the same value as the row, but I haven't been able to get that to work. I must be implementing the validate command incorrectly.

Any help would be much appreciated.
import tkinter as tk

class widget:
    def __init__(self,master):
        # vcmd = (master.register(self.validate),
                # '%d', '%i', '%P', '%s', '%S', '%v', '%V', '%W')
        self.master = master
        self.entryNumbers = tk.Entry(master,justify = tk.CENTER)
        self.entryNumbers.insert(0, "5")
        self.entryNumbers.grid(row = 0,column = 0,columnspan =2,sticky="EW")
        self.createEntriesButton = tk.Button(master,text = "Create Entries",command = self.createEntries)
        self.createEntriesButton.grid(row = 1, column = 0,columnspan = 2,sticky="EW")

    def createEntries(self):
        self.entryNumbers.grid_forget()
        self.createEntriesButton.grid_forget()

        self.entries = []
        self.entryLabels = []

        vcmd = self.master.register(self.validateEntry)

        for i in range(int(self.entryNumbers.get())):
            self.entryLabels.append(tk.Label(self.master,text = "Row {}".format(i)))
            self.entryLabels[-1].grid(row = i,column = 0)
            self.entries.append(tk.Entry(self.master, validatecommand=(vcmd,'%P',i)))
            self.entries[-1].grid(row = i,column = 1)

        self.addEntriesButton = tk.Button(self.master,text = "Add Entries",command = self.addEntry)
        self.addEntriesButton.grid(row = i+1, column = 0,columnspan = 2,sticky="EW")

    def addEntry(self):
        count = len(self.entries)

        vcmd = self.master.register(self.validateEntry)

        self.entryLabels.append(tk.Label(self.master,text = "Row {}".format(count)))
        self.entryLabels[-1].grid(row = count+1,column = 0)
        self.entries.append(tk.Entry(self.master, validatecommand=(vcmd,'%P',count)))
        self.entries[-1].grid(row = count+1,column = 1)
        self.addEntriesButton.grid(row = count+2, column = 0,columnspan = 2,sticky="EW")

    def validateEntry(self,P,row):
        if P != row:
            return True
        else:
            return False

root1=tk.Tk()
widget(root1)
root1.mainloop()

Also, can vcmd be a member variable? I would like to only initialize it once?

A:

I figured it out using a lambda function:
vcmd = lambda row:(self.master.register(self.validateEntry),'%P',row)

        for i in range(int(self.entryNumbers.get())):
            self.entryLabels.append(tk.Label(self.master,text = "Row {}".format(i)))
            self.entryLabels[-1].grid(row = i,column = 0)
            self.entries.append(tk.Entry(self.master, validate = "all", validatecommand=vcmd(i)))


Q:

System of equations, problem about angles

I'm solving a problem (about circles and geometric fiqures), during a project I came up with this system, and in contains all my work, I'm not be able to solve it further so I need some help.
$$
\begin{cases}
\theta_3+\theta_5+\theta_8+\theta_{11}+\theta_{13}=360\\
\theta_1+\theta_2+\theta_3=180\\
\theta_4+\theta_5+\theta_6=180\\
\theta_7+\theta_8+\theta_9=180\\
\theta_{10}+\theta_{11}+\theta_{12}=180\\
\theta_{13}+\theta_{14}+\theta_{15}=180\\
\theta_8+\theta_{11}+\theta_{13}=180\\
\theta_5+\theta_8+\theta_{11}=180\\
\theta_3+\theta_{13}=180\\
\theta_3+\theta_5=180\\
2\theta_1+\theta_3=180\\
2\theta_7+\theta_8=180\\
2\theta_8+\theta_{13}=180\\
\theta_9+\theta_{10}=2\theta_8\\
\theta_3=2\theta_4\\
\theta_5=2\theta_1\\
\theta_1+\theta_4=90\\
\theta_2+\theta_{15}=90\\
\theta_9+\theta_{10}=\theta_8+\theta_{11}\\
\theta_3=\theta_8+\theta_{11}\\
\theta_7=\theta_{12}\\
\theta_5=\theta_{13}\\
\theta_6=\theta_{14}\\
\theta_4=\theta_{15}\\
\theta_1=\theta_2\\
\theta_7=\theta_9\\
\theta_8=\theta_{11}
\end{cases}
$$
Thanks fo any help.

A:

I plugged your equations in a matrix calculator and got:
$$
\theta_{1}=\theta_{2}=30,\\
\theta_{3}=120,\\
\theta_{4}=\theta_{5}=\theta_{6}=\theta_{7}=\theta_{8}=\theta_{9}=\theta_{10}=\theta_{11}=\theta_{12}=\theta_{13}=\theta_{14}=\theta_{15}=60.
$$


Q:

постоянно крашится Unreal Engine 4.25.1

Скачал недавно Unreal Engine 4. Как только создаю или открываю проект (даже пустой) (для разработки игр) открывается нормально не лагает, но через несколько секунд/минут (даже когда я ничего не делаю) он виснет. Сначала виснет сам анриал а потом и весь ноут так что даже диспетчер не открывается, приходится перезагружать кнопкой Power. Ноут по параметрам подходит (12 оперативки, geforce 1050, i5-8300H 2.3 GHz)
Что пробовал:

Менял IDE по умолчанию (думал может вижуалка грузит)
Запускал от админа (и не от админа тоже). + Савил галку отключить оптимизацию на весь екран как в гайдах в гугле.
Переустанавлявал
Ставил раннюю версию (Может попробовать скачать более более ранние? но качать и так уже надоело все равно не работает)
Ставил галку чтобы принудительно запускалось через видюху
Обновлял дрова
Нажимал проверить в лаунчере епиков

A:

Проблема решилась при открытии редактора не на полный экран


Q:

Run jQuery slideDown complete function only after last item has completed

I understand that you can pass a function to slideUp/slideDown that will run once the transition has completed:
$('li').slideUp({
    complete: function(){
        alert('done');
    }
});

With this HTML an alert is shown 3 times.

[content here]

[content here]

[content here]

Is there some way to have the complete function fire only once, when the last list item has completed the slideUp? (fiddle)

A:

You can "redo" your selector and check if this is the last :
$('li').slideUp({
    complete: function(){
        if($('li:last').is(this)){
            alert('done');
        }
    }
});

Fiddle : http://jsfiddle.net/5NQsU/
Caching your selector would be even better :
var $li = $('li');
$li.slideUp({
    complete: function(){
        if($li.last().is(this)){
            alert('done');
        }
    }
});


Q:

Efficient way to detect peak value changes in a list

ListPlot[list, Joined -> True, PlotRange -> Full]

I would like a simple method to get the positions within the list where the values deviate a lot from their previous values. If I just use a threshold, I might miss some peaks or introduce wrong results as the values before a peak can vary.
Here is the list:
list = Import["https://pastebin.com/raw/ncJDt0L4", "List"]

I was thinking of using a numeric gradient, but I don't know if Mathematica has a build in function and also if this is really the best method.
EDIT:
I forgot to mention: A peak should always be chosen with respect to the previous points which lie after the last detected peak, or in other terms: All values before the last detected peak should not be considered in evaluating the next peak. Only the values after the last detected peak are of importance.
The first small peaks before the first big peak should not be detexted as peaks since the data fluctuates a lot there
...and the last little peak should not be counted as peaks, because there cannot be two peaks when the distance (x) between the peak position is less than 3.

A:

Using FindPeaks is a fine solution. This answer responds to the following OP statements/questions.

I would like a simple method to get the positions within the list where the values deviate a lot from their previous values. If I just use a threshold, I might miss some peaks or introduce wrong results as the values before a peak can vary.
I was thinking of using a numeric gradient, but I don't know if Mathematica has a build in function

Get the (consecutive) differences:
ds = Differences[list];
Through[{Min, Max, Mean, Median, StandardDeviation}[ds]]

(* {-24958.8, 25131.1, 0.526443, -1.1353, 2896.09} *)

Pick peak positions with a threshold (0.06 here):
ds2 = Select[ds, # > 0 &];
pos = Pick[Range[2, Length[list]],
  Map[ # > Mean[ds2] + 0.06*StandardDeviation[ds2] &, ds]]

Plot data and peaks:
list2 = Transpose[{Range[Length[list]], list}];
ListLinePlot[list2, PlotRange -> Full,
 Epilog -> {Red, PointSize[Large], Point[list2[[pos]]]}]

A:

FindPeaks is the perfect solution as it has all the options to fine tune the condition you require for a peak:
list = Import["https://pastebin.com/raw/ncJDt0L4", "List"];

peaks = FindPeaks[list, 3, 12];
ListLogPlot[{list, peaks}, PlotRange -> Full, Joined -> {True, False},
  PlotStyle -> {Thin, Directive[Red, PointSize[Large]]}]

Just play around with the values for Gaussain blurring, minimum sharpness and threshold until you get the performance you want.
Edit
The log-plot is very useful for highlighting the reason, why the smallest peaks are also considered a peak. In case you do not consider it a peak, you can easily eliminate the very small but sharp features by also using the threshold, the fourth argument of FindPeaks.
For a direct comparison with other solutions, here is a linear plot:
ListPlot[{list, peaks}, PlotRange -> Full, Joined -> {True, False},
 PlotStyle -> {Thin, Directive[Red, PointSize[Large]]}]

A:

I think that you are likely looking for some combination of the parameters of the FindPeak function, for example:
list = Import["https://pastebin.com/raw/ncJDt0L4", "List"];

peaks = FindPeaks[list, Automatic, Automatic, 500];
ListLinePlot[
 list,
 PlotRange -> Full,
 Epilog -> {Red, PointSize[Large], Point[peaks]}
 ]


Q:

SSH vs/and Password

I have a VPS that I am logging to root via SSH keys.
Now, I created another user user1 with the command adduser and I assigned a password to it. However, whenever I try to login to the server via winSCP using user1 I still get the error that I need to enter the private key and can't login using the password for user 1.
My questions are as follows:

Can a user have the possibility to login via the 2 methods? That is, using the SSH keys and a password?
If SSH is used, are all the users of the system bound to use the keys to login?

A:

You can add rules for that particular user on the /etc/ssh/sshd_config file like the example at the end of this answer. But before be warned, allowing password login via SSH is somewhat unsafe in terms of brute-force attempts possible to the server. So the safest way to go is to create another SSH key on the VPS or another Linux machine with the following line. best is to switch to user1 on that machine before you start using the following commands with su - user1. (Note: you should change into the directory where you want the key-pair to be created as the -f has a hard time with paths):
ssh-keygen -t rsa -C "user1_email@example.com" -f user1_key

The user can change the passphrase himself later by copying his key-pair for a short time onto the VPS or on another Linux machine with:
ssh-keygen -p -f user1_key

Then give the private key (user1_key) to user1 and place the public key (user1_key.pub) in the users home directory under ~/.ssh/authorized_keys on the VPS then change ownership to user1 or you do su - user1 before doing that to prevent undesired wrong ownership inside the home directory of user1.
mkdir -p /home/user1/.ssh
cat user1_key.pub >> /home/user1/.ssh/authorized_keys
# The next line is only needed if you have done the two above as 'root'
chown -Rv user1:user1 /home/user1/.ssh

The key-pair creation process can be done on Windows too using WinScp, see here for reference. You might then want to make sure the public and the private key have the right permissions set, which is 0600 for the users private key and 0644 for the users public key. (Note: copying the key to a windows formatted USB stick or drive lets the key loose its set permissions, so you want to double check on that.
If you however really want to make this user able to log in via password, you can change the following line in /etc/ssh/sshd_config:
AllowUsers mainuser user1

And add the following at the end:
For enabling password only:
Match User user1
    PubkeyAuthentication no
    PasswordAuthentication yes

For enabling both:
Match User user1
    PubkeyAuthentication yes
    PasswordAuthentication yes

For enabling ssh only you can remove that part or set it to:
Match User user1
    PubkeyAuthentication yes
    PasswordAuthentication no

More reading material which might not necessarily related to the question but to SSH in general you can find here, just be aware that some information is specified for digital-ocean but still useful. See as well the manpage for the ssh-keygen command and the manpage for the ssh command.
Thanks to @Eliah-Kagan for proofreading and suggesting corrections and additions.


Q:

hook_form being called twice

hook_form being called twice
/**
* Implements hook_form_alter().
*/
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'user_register_form') {
    $form_state['redirect'] = false;
    my_function();
  }
}

my_function() calls twice and I need only one.
I read this post:
https://drupal.stackexchange.com/questions/22881/hook-form-being-called-twice
And I try use $form_state['redirect'] = false but don't work forme.
Anyone know any clean way to do it? Thanks

A:

It looks to me like you should be doing whatever it is you doing in your own submit function.
Add your own submit function by adding your function name to the submit array in your form_alter.
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'user_register_form') {
    $form['#submit'][] = 'MYMODULE_submit_function';
  }
}

function MYMODULE_submit_function(&$form, &$form_state) {
  $form_state['redirect'] = false;
  my_function();
}


Q:

Table column with headers change column width

HTML viewable at jsfiddle.net (it's a lot of code to post here)
The method to change the column width escapes me, I'd like the "Produkt" column to be wider.

A:

Add this attribute to your header of that cell, it should force the entire column to be at least 100px:
Produkt


Q:

Optimal method to display Entities plus additional information?

Let's say I have an Entity in my Entity Framework Model that is named Server, and has a string property named Address.
When my View is loaded, I need to:

Get a list of Addresses from the Model
(simple enough).
Run out and get some data from
each of the Addresses via JSON.
Display a DataGrid that has the
server address, with all the info it
fetched.

NO saving functionality is needed, this is just displaying information. Do I need to make an all-new object and populate a list of these to bind to? If so, would it be bad to inherit from my POCO Entities, add more fields, and populate/bind to a list of those? Or would it be better to do a Linq query to my database, generate an anonymously-typed collection on the fly, and bind to that? Or is there another better way I'm not aware of?
As you may tell from my question history, I'm new to .NET4/WPF and learning as I go on this project, but I'm trying to learn how to do it right and not brute-force it, so sorry if it's an obvious question to you pros here. :)

A:

If you know you will need the data for sure every time I would recommend to load it together. Assuming you model looks something like this: Server -> ServerAddresses -> AddressDetail then I think you would be best off populating all the info in one shot.
When loading your data do something like this:
using (var context in new EntityContext())
{
  var model = context.Servers.Include("ServerAddresses.AddressDetail").Where(s => s.Foo == "Bar")
}

and bind your view to that model rather than lazy loading this for each item later. And yes it would be best to load this model into a custom structure for serialization (which I am assuming you are doing since you are referring to JSON.


Q:

Enable BCMath using php.ini?

I need to enable BC Math, but I don't want to do it using --enable-bcmath, primarily because I don't understand that route.
Is there a way to do this using php.ini only?

A:

To the best of my knowledge you must compile php with the --enable-bcmath option. Without it, the required code won't exist in the binary. Therefore, there is nothing that you can set in php.ini

A:

Before recompiling, check the php.ini file and search for "bcmath".  You may find bcmath.scale=0.  If so, change the 0 to a 2.


Q:

pthread_sigmask not working properly with aio callback threads

My application is sometimes terminating from SIGIO or SIGUSR1 signals even though I have blocked these signals.
My main thread starts off with blocking SIGIO and SIGUSR1, then makes 2 AIO read operations. These operations use threads to get notification about operation status. The notify functions (invoked as detached threads) start another AIO operation (they manipulate the data that has been read and start writing it back to the file) and notification is handled by sending signal (one operation uses SIGIO, the other uses SIGUSR1) to this process. I am receiving these signals synchronously by calling sigwait in the main thread. Unfortunately, sometimes my program crashes, being stopped by SIGUSR1 or SIGIO signal (which should be blocked by a sigmask).
One possible solution is to set SIG_IGN handlers for them but this doesn't solve the problem. Their handlers shouldn't be invoked, rather should they be retrieved from pending signals by sigwait in the next iteration of the main program loop.
I have no idea which thread handles this signal in this manner. Maybe it's the init who receives this signal? Or some shell thread? I have no idea.

A:

I'd hazard a guess that the signal is being received by one of your AIO callback threads, or by the very thread which generates the signal.  (Prove me wrong and I'll delete this answer.)
Unfortunately per the standard, "[t]he signal mask of [a SIGEV_THREAD] thread is implementation-defined."  For example, on Linux (glibc 2.12), if I block SIGUSR1 in main, then contrive to run a SIGEV_THREAD handler from an aio_read call, the handler runs with SIGUSR1 unblocked.
This makes SIGEV_THREAD handlers unsuitable for an application that must reliably and portably handle signals.


Q:

crystal reports : not recognizing Null value in record select

I have the custom forumla in my record seletion formula editor in Crystal reports 8.5

{_v_hardware.groupName} =
  {?companyname} and
  ({_v_hardware.DriveLetter} = "C" or
  isNull({_v_hardware.Driveletter})

I'm trying to list all records with a drive letter C or has a Null value and it currently lists all records with the drive letter C but not the ones with null.  Am I handling the null values incorrectly?  I have also tried setting the {_v_hardware.DriveLetter} = NULL and that does not work either.
I should add the report is talking to SQL Server. the records are reading NULL in the table.
Update:
If I use the query

{_v_hardware.groupName} =
  {?companyname} and
  isNull({_v_hardware.Driveletter})

it will list the records with just the Null values in the DriveLetter field and the companyname
If I use the query

{_v_hardware.groupName} =
  {?companyname} and
  {_v_hardware.DriveLetter} = "C"

this also lists all records with the driveletter "c"
thanks in advance
Solution by heather:
if IsNull({_v_hardware.Driveletter) then
  {_v_hardware.groupName} = {?companyname}
else
 (if {_v_hardware.DriveLetter} = "C" then
  {_v_hardware.groupName} = {?companyname}
   )

A:

I've seen Crystal do funny things depending on the order you evaluate your fields.  Sometimes I've had to break field checks into blocks when a NULL value is possible:
if IsNull({_v_hardware.Driveletter) then
  {_v_hardware.groupName} = {?companyname}
else if {_v_hardware.DriveLetter} = "C" then
  {_v_hardware.groupName} = {?companyname}
else
  false;
Its ugly, but it may work if that is the case.


Q:

Is science inherently naturalistic?

For an assignment, my philosophy of science professor had us read Phillip E. Johnson's "Evolution as Dogma: The Establishment of Naturalism" and then answer the following question:

What is Johnson's support for asserting that evolutionists who claim that God did not intervene in the creation of the variety of biological species are making a philosophical claim?

While he does initially argue that the evidence in support of evolution is minimal, Johnson focuses his attack on naturalism, which is, of course, the root of the sort of evolution he is arguing against. Throughout the paper, he repeatedly refers to the fact that the theory of evolution would crumble if naturalism were called into question because it would supposedly allow room for the possibility of a creator. This led me to ask myself: is science, which evolution is presented as a manifestation of, inherently naturalistic? Can science be science exclusive of naturalism? Perhaps as a result of the very dogmatism Johnson describes, I simply cannot imagine science without the properties of naturalism.

A:

There are a number of strategies that scientists and philosophers of science have used to avoid (or at least decrease) tensions between religion and scientific naturalism.  You can read more about several of these in the Stanford Encyclopedia entry on religion and science.
As a preliminary point, it's important to recognize that the conflict thesis — the idea that there's a deep and longstanding tension between religion and science — was a specifically nineteenth century development, and it's generally not regarded as good history by historians of science today.  (More on Wikipedia.)
That said, here are five argument strategies to avoid the apparent conflict, in no particular order.

Non-Overlapping Magisteria, or NOMA.  The term comes from a Stephen Jay Gould essay, and his book Rock of Ages.  The basic idea is that science and religion have different spheres, topics, or domains — the "magisteria" — and that these domains don't overlap.  The purpose of science is to describe the observable, natural world; the purpose of religion is to provide moral guidance on how we live our lives; and the two domains are logically irrelevant to each other, so that claims in one domain simply can't conflict with claims in the other.  (More on Wikipedia.)
Constructive empiricism and other varieties of scientific anti-realism.  Constructive empiricism comes from philosopher of science Bas van Fraassen, who is Catholic.  On van Fraassen's view, scientific models don't need to be literally true; instead, they only need to accurately represent the parts of the world that we can observe.  (More on the Stanford Encyclopedia.)  Then, if we understand the long history of life as something that we can't observe, models of evolution by natural selection don't need to be literally true about that history.  Instead, they only need to accurately represent the parts of the history of life that we can observe.  (To be clear, I don't think van Fraassen himself would endorse this argument, because I think he would say that this history is something that we could observe in principle.  My point here is that someone could avoid conflict between religion and science by taking this kind of approach.)
The Doctrine of Two Books was important in medieval and Renaissance Christianity.  (I learned about it writing a paper on Galileo as an undergraduate, and it's also relevant to understanding how Aquinas reconciled Christianity with Aristotle's more "naturalistic" philosophy.)  The idea here is that God has "written" two books, Scripture and Nature, and that humans are called to study and learn from both books.  So far this might sound like NOMA.  The key difference is that, according to the doctrine, the two books are relevant to each other, and cannot conflict.  Apparent conflicts are the product of limited human understanding, and so reconciling the apparent conflicts is an important task for scholars of both books.  Importantly, the books don't relate to each other hierarchically.  It's not that Scripture takes priority over Nature.  A theologian's understanding of Scripture should be informed by a scientific understanding of Nature, and a scientist's understanding of Nature should be informed by a theological understanding of Scripture.  Both theologians and scientists are working to understand God's two books, and they should work together.  I believe something like this is the position of the Catholic Church today.  Of course, all of this assumes that Scripture is a reliable source of knowledge — though your question more or less assumes a religious scientist.  (I haven't been able to find a good source of more information.  This Wikipedia article goes into a little more detail, but is incomplete and messy.  This essay by Ernan McMullin, a philosopher of physics and Catholic priest, works through a highly qualified version of this strategy.  McMullin's essay was also published in this anthology.)
Another strategy is to offer what I've heard called a guided interpretation of evolution.  The basic idea is that God sets up evolutionary scenarios that, as a result of the operation of natural selection and other evolutionary forces, produce the results that God desires.  One way to think about this is that, using divine foreknowledge, the Big Bang was configured precisely to result in humans here on Earth (or whatever the desired goal happens to be).  Another, somewhat different idea is that God has occasionally (or maybe more often) "nudged" history — killing off this organism, ensuring that this other one survives and reproduces — to result in humans here on Earth (or whatever the desired goal happens to be).  I believe something like this was the view of Asa Gray, a botanist who corresponded with Darwin.  (There are some scattered remarks on Gray in the Stanford Encylopedia entry.)
The final argument strategy that I'll discuss here is to understand scientific naturalism as methodological naturalism rather than ontological naturalism.  Roughly the idea is that science proceeds under the assumptions of naturalism (that there are no supernatural entities or causal influences, that the only forms of causation are efficient-material, that observation provides the only way of gaining knowledge about natural causal relations, and so on), but that there's no deep commitment to these assumptions being true.  From a methodological naturalist perspective, there might very well be supernatural stuff; but the assumption is that any supernatural stuff that might exist can be ignored for the purposes of investigating the natural stuff.  Somewhat like NOMA, methodological naturalism regards religion as a "separate domain"; but it allows for the possibility that this domain is about much more than just morality.  Unlike scientific anti-realism, methodological naturalism is compatible with scientific claims being true — so long as they're understood to be true about nature and not "supernature."  (This Stanford Encyclopedia entry is mostly about naturalism and philosophy, but in many places the discussion of methodological naturalism also applies to science.)


Q:

Swapping column elements individually (2D Array) C++

I need to swap elements of multidimensional array (2D Array) columns individually so that number closest to that column average is in the end(back) example:
1 5 8
4 8 7
8 6 2

First column average is 4.(3) so ~4, it means that i need for 4 to be in 3rd row
Second column average is 6.(3) so ~6 it means that i need for 6 to be in 3rd row
Third column average is 5.(6) so ~6, it means that i need for 7 to be in 3rd row, cause it is closest number to ~6.
Expected result
  1 5 8
  8 8 2
  4 6 7

And i was thinking for a while how to do that, but unsuccessfully. I manage to calculate average of every column and thats it.
So i need help with swapping of elements in columns
Thanks in advance  (if you need any extra information just ask)
More Examples
Input              Input
1 2 3              4 8 9
4 5 6              3 1 7
7 8 9              7 3 2

Output             Output
1 2 3              7 8 9
7 8 9              3 1 2
4 5 6              4 3 7

1st col avg=4           1st col avg=~4
2nd col avg=5           2nd col avg=4
3rd col avg=6           3rd col avg=~7
(Swapping number so that number that is closes to column average is in back, sorting can also do the job because i dont care about position as long as that number which is closest to column average is in back)

A:

Since you already know the averages (thus, the positions) and you're using C++, you may use std::swap to swap any two elements on an array:
std::swap(array[e1], array[e2]);

The internal std::swap implementation is something like:
template <class T> void swap ( T& a, T& b )
{
  T c(a); a=b; b=c;
}


Q:

xcode format numbers with spaces

How can i convert price's in format like:
from this

1000000

to this

1 000 000

?
Thanks.

A:

Here it is :
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setNumberStyle: NSNumberFormatterCurrencyStyle];
NSString *numberAsString = [numberFormatter stringFromNumber:[NSNumber numberWithDouble:[currency doubleValue]]];
self.label.text = numberAsString;

and if you want to show with symbol


Q:

Autodesk Viewer Markup extension - can't compile from sources

I'm trying to achieve similar viewer annotations like official demo:
lvm-react
I read official blog post and use files from Autodesk Extensions github:
http://adndevblog.typepad.com/cloud_and_mobile/2016/04/markup3d-sample-for-view-data-api.html
But I can't compile extensions from sources (create bundle.js). Tried just npm install, but there are many errors like:
ERROR in ./src/Viewing.Extension.VisualReport/PieChart/PieChart.js
Module not found: Error: Cannot resolve module 'EventsEmitter' in MY_FILES

and
ERROR in ./src/Viewing.Extension.StateManager/Viewing.Extension.StateManager.scss
Module parse failed: /MY_PATH/library-javascript-viewer-extensions-master/src/Viewing.Extension.StateManager/Viewing.Extension.StateManager.scss Unexpected token (2:0)
You may need an appropriate loader to handle this file type.

I also installed webpack using npm, but without result, there are still many errors.

A:

There was a few loaders missing from the webpack build production config. It is fixed now and you should be able to build all extensions. Please use the latest version from the repo.
When testing your extensions, I recommend you use npm run build-dev command, so the generated extensions files will not be minified and have source-map enabled, so you can easily debug them in browser console. When building for production, you can use npm run build-prod.
You can also remove the various entries from the webpack config to build only the extensions you are interested in, for example:
module.exports = {

    devtool: 'eval-source-map',

    entry: {

      'Viewing.Extension.Markup3D':
        './src/Viewing.Extension.Markup3D/Viewing.Extension.Markup3D.js',
    },

    // ... rest of the config ...

You may also want to change the output path, in my config the output is outside of the extensions directory, directly in the project using them:
output: {
    path: path.join(__dirname, '../../App/dynamic/extensions'),
    filename: "[name]/[name].js",
    libraryTarget: "umd",
    library: "[name]",
    watch: true
  },

In addition to including the extension file to your project, you should also make sure that you include the babel polyfill (from node_modules/babel-polyfill/dist/polyfill.min.js) before any extension script.
Hope that helps, let me know if you have any further trouble using those extensions.


Q:

Special Characters Causing MySQL Failures

For my current project, I'd like to make a browser for a dictionary database I have in MySQL. These words contain special characters, and I'm using UTF-8 encoding. So far, I've made a functioning "search" that looks up the user's input and outputs the relevant information.
Here's where I run into an issue. If the user inputs all normal characters, the code works properly. However, if they put in something with any special characters, the query always returns null.
Here's the relevant code:
HTML Page:

        <form action="test.php" method="get">
            Search dictionary: <input type="text" name="search">
            <input type="submit" value="Submit">
        </form>

PHP Script (Excerpt):
<?php
    $q=$_GET['search'];
    $id = "";
    if (strlen($q) > 0) {
        // connects to DB
        $db = new PDO('mysql:host=localhost;dbname=***', '***', '***');
        $db->setAttribute(PDO::MYSQL_ATTR_INIT_COMMAND, "SET NAMES 'utf8'");

        $query="SELECT DISTINCT e.lexeme_id, l.posc
        FROM entry e
        INNER JOIN lexeme l
        USING (lexeme_id)
        WHERE e.lemma = '".$q."'";

        $stmt=$db->prepare($query);
        $stmt->execute();

        foreach ($stmt as $row) {
            $id = $row['lexeme_id'];
            $posc = $row['posc'];
            //output results here
            echo "
".$q."

";
            echo "
".$posc."

";
        }
    }
?>

If I input "man" into the search box, the appropriate data is pulled up. However, if I search for "maðr" I get no results. However, if I try the same query in MySQL Workbench, I get the correct output. I've had the script print out the query it uses, and it matches what it should be.
TL;DR: The following query runs file in MySQL Workbench, but not when I call it on my HTML page through a PHP script-
SELECT DISTINCT e.lemma
FROM entry e
INNER JOIN lexeme l
USING (lexeme_id)
WHERE e.lexeme_id = "maðr"

Any idea what might be going wrong? Thanks!

A:

header('Content-type: text/plain; charset=utf-8');

In your PHP script to make it UTF8


Q:

MX Notify Control: multiple php errors when saving an entry

I just updated to EE2.7, and I'm getting this error when I try to save an entry:

A PHP Error was encountered Severity: Notice Message: Undefined index:
  From Filename: libraries/Email.php Line Number: 1588
A PHP Error was encountered Severity: Notice Message: Undefined index:
  From Filename: libraries/Email.php Line Number: 1194
A PHP Error was encountered Severity: Notice Message: Undefined index:
  Return-Path Filename: libraries/Email.php Line Number: 889
A PHP Error was encountered Severity: Notice Message: Undefined index:
  From Filename: libraries/Email.php Line Number: 1588
A PHP Error was encountered Severity: Notice Message: Undefined index:
  From Filename: libraries/Email.php Line Number: 1194
A PHP Error was encountered Severity: Notice Message: Undefined index:
  Return-Path Filename: libraries/Email.php Line Number: 889
A PHP Error was encountered
  Severity: Notice Message: Undefined index: From Filename:
  libraries/Email.php Line Number: 1588
A PHP Error was encountered Severity: Notice Message: Undefined index:
  From Filename: libraries/Email.php Line Number: 1194
A PHP Error was encountered Severity: Notice Message: Undefined index:
  Return-Path Filename: libraries/Email.php Line Number: 889
A PHP Error was encountered Severity: Notice Message: Undefined index:
  From Filename: libraries/Email.php Line Number: 1588
A PHP Error was encountered Severity: Notice Message: Undefined index:
  From Filename: libraries/Email.php Line Number: 1194
A PHP Error was encountered Severity: Notice Message: Undefined index:
  Return-Path Filename: libraries/Email.php Line Number: 889
A PHP Error was encountered Severity: Notice Message: Undefined index:
  From Filename: libraries/Email.php Line Number: 1588
A PHP Error was encountered Severity: Notice Message: Undefined index:
  From Filename: libraries/Email.php Line Number: 1194
A PHP Error was encountered Severity: Notice Message: Undefined index:
  Return-Path Filename: libraries/Email.php Line Number: 889
A PHP Error was encountered Severity: Warning Message: Cannot modify
  header information - headers already sent by (output started at
  /home/content/19/5501119/html/system/codeigniter/system/core/Exceptions.php:170)
  Filename: libraries/Functions.php Line Number: 809
A PHP Error was encountered Severity: Warning Message: Cannot modify
  header information - headers already sent by (output started at
  /home/content/19/5501119/html/system/codeigniter/system/core/Exceptions.php:170)
  Filename: libraries/Functions.php Line Number: 809
A PHP Error was encountered Severity: Warning Message: Cannot modify
  header information - headers already sent by (output started at
  /home/content/19/5501119/html/system/codeigniter/system/core/Exceptions.php:170)
  Filename: libraries/Functions.php Line Number: 414

I'm using MX Notify Control to notify users when an entry they've authored is updated, and it looks like trying to fire off the emails is causing this error. I've updated to the latest version of every add-on I'm using, including MX Notify, and I can't find any info on these errors. Any thoughts?

A:

As error messages indicate, its due to FROM value which doesn't get by Email library. Can you check the MX Notify Control setting for that channel entry notification if having "From Name" and "From Name".

A:

I have chance to make test - the reason of this can be wrong tag in TO field.
For example, for Entry Update/Create trigger needs to use *author_email* instead of *mbr_email*.
I will try soon make better example in docs (and with additional notifications inside the add-on to prevent such situation).


Q:

Oracle SQL: How to show empty weeks / weeks without data?

Similar to this question, but my dataset has an additional column with many IDs. Each ID has a dataset that goes back by a constant timeframe, and some of the weeks may be missing data - I would like to fill in values for missing weeks.
For example, I want this:
ID      WEEKEND_DAY     VALUE
A00     2012-01-01      1
A00     2012-01-08      7
B00     2012-01-08      4
B00     2012-01-15      3

to expand to this:
ID      WEEKEND_DAY     VALUE
A00     2012-01-01      1
A00     2012-01-08      7
A00     2012-01-15      0
B00     2012-01-01      0
B00     2012-01-08      4
B00     2012-01-15      3

where I already have a known range of WEEKEND_DAYs (in the above case, weekly from 2012-01-01 to 2012-01-15) that I want to fill in. How can I go about doing this?

A:

Use a partitioned outer join:
select data.id, weeks.weekend_day, nvl(value, 0) value
from
(
    select date '2012-01-01' weekend_day from dual union all
    select date '2012-01-08' weekend_day from dual union all
    select date '2012-01-15' weekend_day from dual
) weeks
left join
(
    select 'A00' id, date '2012-01-01' weekend_day, 1 value from dual union all
    select 'A00' id, date '2012-01-08' weekend_day, 7 value from dual union all
    select 'B00' id, date '2012-01-08' weekend_day, 4 value from dual union all
    select 'B00' id, date '2012-01-15' weekend_day, 3 value from dual
) data
    partition by (data.id)
    on weeks.weekend_day = data.weekend_day


Q:

Overlapping numbers and titles in toc with hausarbeit-jura

I'm using the document class hausarbeit-jura (a document class for jura student papers).
The number of my 8th section (roman numbering "VIII") overlaps with the title of the section in the table of contents.
I already had a look at Overlapping numbers and titles in toc but when I add \addtolength{\cftsecnumwidth}{10pt} to my document I get the error message:
Undefined control sequence \addtolength{\cftsecnumwidth}{10pt}
Missing number, treated as zero \section
Illegal unit of measure (pt inserted) \section

Minimal working example:
\documentclass[12pt,utf8,headline,headlinetitlepageleft,nosuperscriptedition]{hausarbeit-jura}

\begin{document}
\tableofcontents
\addtolength{\cftsecnumwidth}{10pt}
\section{TEXT}
\section{TEXT}
\section{TEXT}
\section{TEXT}
\section{TEXT}
\section{TEXT}
\section{TEXT}
\section{TEXT}
\section{TEXT}

\end{document}

Result looks like this:

Any ideas how to fix this? Thanks to everyone in advance! :-)

A:

The class does
\settowidth{\sectionnumwidth}{III.\ }

which is insufficient for accommodating VIII. You can use VIII instead.
%\UseRawInputEncoding % uncomment for TeX Live 2018

\documentclass[
  12pt,
  utf8,
  headline,
  headlinetitlepageleft,
  nosuperscriptedition
]{hausarbeit-jura}

\AtBeginDocument{\settowidth{\sectionnumwidth}{VIII.\ }}

\begin{document}
\tableofcontents
\section{TEXT}
\section{TEXT}
\section{TEXT}
\section{TEXT}
\section{TEXT}
\section{TEXT}
\section{TEXT}
\section{TEXT}
\section{TEXT}

\end{document}

The first line should be uncommented if TeX Live 2018 (more precisely LaTeX 2018-04-01), as the class has not yet been updated for UTF-8 support by default.


Q:

IOS NSString decode not working

I am receiving a string from the internet but i cant find a way to transform the special char and them show in on an alert box.
This is the string:
@"Sorry, your search doesn\u0027t have any result"

i know i could do something like this to work around
[response stringByReplacingOccurrencesOfString:@"\u0027" withString:@"'"];

but i wanted a solution that would work for any character
i have already tried several solution but none seam to work, and i don't know why

A:

You can do it like this:
NSString *escapedStr = @"Sorry, your search doesn\\u0027t have any result";
NSString *unescapedStr = [NSString
            stringWithCString:[escapedStr cStringUsingEncoding:NSUTF8StringEncoding]
            encoding:NSNonLossyASCIIStringEncoding];
NSLog(@"unescapedStr = %@", unescapedStr);


Q:

Change Validation Function

I have a situation where the validation function I want to use depends on a choice that the user made earlier in the form. The page loads with a default validator, like so.
CustomValidator cv = new CustomValidator();
cv.ErrorMessage = "You must learn to follow instructions.";
cv.ControlToValidate = "myTextBox";
cv.EnableClientScript = true;
cv.CssClass = "Validator";
cv.ServerValidate += new ServerValidateEventHandler(cv_TextValidator);
cv.ClientValidationFunction = "textValidate";
u.ContentTemplateContainer.Controls.Add(cv);

When the user makes choice X, something like timeInterval_SelectedIndexChanged(object sender, EventArgs e) is called. When they make that choice, I need to swap out the validation that is attached to some of my controls. In pseudo-code, I need something like this:
if user chose the first option {
    myControl.clientValidation = "textValidate";
    myControl.serverValidation = "cv_TextValidator";
} else {
    myControl.clientValidation = "alternateTextValidate";
    myControl.serverValidation = "cv_AlternateTextValidator";
}

How can I swap out validation functions in code-behind?
I know this can be accomplished with an if-else block inside of a single validation function. It could also be accomplished by hiding and showing other boxes that already have alternate validation attached. "If-else validation" and "hiding things" seem like non-elegant ways to solve the problem. I would rather rewire my functions to the proper ones.

A:

ClientValidationFunction is a string, so just change it to whatever you want like so:
if (SomeDDL.SelectedValue == "A")
   cv.ClientValidationFunction = "ValidateA";
else
   cv.ClientValidationFunction = "ValidateB";

It may not be tracked in ViewState, so you may have to set it on every postback to the server, in the Page_load or similar event (most likely PreRender or before).
For the other, simply attach to the correct handler:
if (SomeDDL.SelectedValue == "A")
   cv.ServerValidate += cv_FirstHandler;
else
   cv.ServerValidate += cv_SecondHandler;

For that, you'd have to do it on every postback too, and always do it from code, not markup.


Q:

AIR, load image stored locally

I package an IPA file including some assets (images). Once installed, I want to load an image in my swf: which is the path of this image? How can I load it?

A:

If you packaged your assets folder, the installation should contain its contents in the File.applicationDirectory.resolvePath("./assets/") folder.
You can reference the image file by File.applicationDirectory.resolvePath("./assets/myImage.png")
To read the file to a byteArray,
var f:File=File.applicationDirectory.resolvePath("./assets/myImage.png");
var fs:FileStream=new FileStream();
var ba:ByteArray=new ByteArray();

fs.open(f, FileMode.READ);
fs.readBytes(ba);
//unsure about this, also try CompressionAlgorithm.DEFLATE
ba.uncompress(CompressionAlgorithm.ZLIB); //uncompresses the byteArray
fs.close();

You will now have the bytes of the image file in the byteArray.


Q:

Have location of grouped objects relative to parent object

I am creating a wall section which will be a wall with a hole and in the hole's place a couple of doors and so on.
For ease of putting things in place I first create an empty node. Then add a wall and doors as children of the empty node. If I relocate the empty node, the meshes of the wall and doors follow along.
What bugs me is I want to locate the doors and wall relative to the location of the parent, empty node. How do I do this? It seems that even though an object has a parent node, the Location in X/Y/Z is specified in the global world. It would be easier to specify this relative to the parent node. So with a pair of doors I could just set something like X: -0.5 for the left door and the right door would get 0.5. Is there any way?

A:

A child always lives in the local space of its parent. You can easily check that by noting the current coordinates of a child that show up in the properties panel ("N"), moving the parent, and then comparing the new coordinates of the child with the first set. They shouldn't have changed, i.e. they can't be global).
At the time of parenting, the child object takes note of the parent's current state (location, rotation, scale) and stores it in child_object.matrix_parent_inverse. Blender applies this correction matrix to the parent's origin before calculating the child's effective global coordinates. (As it is the inverse of the original parent's matrix, it will "negate" the effect the parent had at the time of parenting, thus seemingly keeping the child in the global coordinate system.) Here is a nice official description:
http://wiki.blender.org/index.php/User:Pepribal/Ref/Appendices/ParentInverse
Or if you prefer it mathematically (at least this is how I interpret blender's behavior):
parent.matrix_world * child.matrix_parent_inverse * child.matrix_local

(where parent.matrix_world can of course be influenced by other parents and such).
Now to get rid of the correction matrix, and to be able to place your doors at x = +-0.5 of the parent, simply select the children in question, press "alt+p" and select "Clear parent inverse" (Or in the 3D View, go to "Object"->"Parent"->"Clear parent inverse"). This will set the matrix_parent_inverse to the identity matrix and place the children in the parent's coordinate system according to the children's local coordinates. (You could get the same effect by parenting while the parent is still at the origin with no rotation and scale==1.)


Q:

How do I get this Cisco VPN client to connect?

I've got Ubuntu 10.10 64 bit and installed network-manager-vpnc and configured the connection but I keep getting this:
NetworkManager[1217]: <info> Starting VPN service 'org.freedesktop.NetworkManager.vpnc'...
NetworkManager[1217]: <info> VPN service 'org.freedesktop.NetworkManager.vpnc' started (org.freedesktop.NetworkManager.vpnc), PID 4420
NetworkManager[1217]: <info> VPN service 'org.freedesktop.NetworkManager.vpnc' appeared, activating connections
NetworkManager[1217]: <info> VPN plugin state changed: 1
NetworkManager[1217]: <info> VPN plugin state changed: 3
NetworkManager[1217]: <info> VPN connection 'CSI' (Connect) reply received.
modem-manager: (net/tun0): could not get port's parent device
NetworkManager[1217]:    SCPlugin-Ifupdown: devices added (path: /sys/devices/virtual/net/tun0, iface: tun0)
NetworkManager[1217]:    SCPlugin-Ifupdown: device added (path: /sys/devices/virtual/net/tun0, iface: tun0): no ifupdown configuration found.
kernel: [ 2281.723506] tun0: Disabled Privacy Extensions
avahi-daemon[1109]: Withdrawing workstation service for tun0.
NetworkManager[1217]:    SCPlugin-Ifupdown: devices removed (path: /sys/devices/virtual/net/tun0, iface: tun0)
NetworkManager[1217]: <warn> VPN plugin failed: 1
NetworkManager[1217]: <info> VPN plugin state changed: 6
NetworkManager[1217]: <info> VPN plugin state change reason: 0
NetworkManager[1217]: <warn> error disconnecting VPN: Could not process the request because no VPN connection was active.
NetworkManager[1217]: <info> Policy set 'Auto eth0' (eth0) as default for IPv4 routing and DNS.
NetworkManager[1217]: <info> Starting VPN service 'org.freedesktop.NetworkManager.vpnc'...
NetworkManager[1217]: <info> VPN service 'org.freedesktop.NetworkManager.vpnc' started (org.freedesktop.NetworkManager.vpnc), PID 4547
NetworkManager[1217]: <info> VPN service 'org.freedesktop.NetworkManager.vpnc' appeared, activating connections
NetworkManager[1217]: <info> VPN plugin state changed: 1
NetworkManager[1217]: <info> VPN plugin state changed: 3

I've seen a couple of bugs on Launchpad that could be the same thing or have I done something wrong?

A:

Install vpnc
package:
sudo apt-get install vpnc

Create the connect script, copy the contents below into a file called vpn-connect and place it on the path somewhere:
#!/bin/sh

sudo vpnc --local-port 0 --enable-1des /etc/vpnc/vpn.conf

Copy over the .pcf file used by the Windows Cisco VPN client and use this as a basis for step 4.
Now you need to create the vpn.conf file in the /etc/vpnc directory. The content of this file are as follows:
IPSec ID <your ipsec id>
IPSec gateway <your gateway address>
IPSec secret <your ipsec secret>

Xauth username <your username>
Xauth password <your password>
IKE Authmode psk

<your username> and <your password> should be obvious.

You now have everything required to connect, so run the script:
vpn-connect

After a few seconds it should come back with the message:
VPNC started in background

And give you a process id.
You should now be connected to the VPN.

A:

I found that in my case the plugin was failing because vpnc was not happy about the encryption method
peer selected (single) DES as "encryption" method.
This algorithm is considered too weak today
If your vpn concentrator admin still insists on using DES
use the "--enable-1des" option.

This message could be only discovered by stracing the vpnc process.
In order to add --enable-1des option to vpnc command line I performed the following:
sudo -s
mv /usr/sbin/vpnc /usr/sbin/vpnc.real
cat <<EOF > /usr/sbin/vpnc
#!/bin/sh
exec /usr/sbin/vpnc.real --enable-1des $*
EOF
chmod +x /usr/sbin/vpnc

Basically I replaced the vpnc binary with a wrapper script that supplied the necessary parameter.
Now NetworkManager VPNC plugin can connect properly.


Q:

What does "get personal" mean in this article?

Does it mean "have personal relationships", "getting to know them more", or something like that?

"Get personal.
  Lauren Mauro, the director of both consumer PR and influencer relations at Dell, echoes Hartman’s statements. In the past six years, she’s developed a multi-tier influencer approach for Dell that scales from celebrity name brands to small regional bloggers. With all of them, she puts the relationship at the heart of the tactic.
“You must invest in introductory calls, face-to-face meetings, follow-up emails, planning and more,” Mauro said. “It is a full-time job and difficult to do well if you have another full-time role. If you are looking at starting a program, I suggest investing in dedicated headcount and even a team if budgets and resources allow.”
While a full team may not be achievable for a fledgling company, ensuring that a member on the team has at least partial time to allocate specifically to growing and creating relationships can help your business exponentially in the long run."

Source: Coca-Cola, Dell and PayPal Share Their Influencer Marketing Secrets

A:

The phrase "get personal" (or "get up-close and personal") can vary with context, but in general you are correct and it refers to building a more direct relationship with a person outside business, to encourage trust and open communication.
Again, depending on the context, this can involve knowing about their families, their hobbies, their goals and inspirations, and so on, or it can just mean that you are on a "first-name basis".
Because "get personal" does not have a fixed meaning, the ambiguity can be funny or uncomfortable, depending on how it's used.

The VP of Sales advised his employees to "get personal" with each other, in order to build team spirit and trust -- but I don't think he meant that the sales manager should have an affair with the top salesperson.


Q:

How can I customize the CSS generated by LESS to include Font Awesome?

I want to customize Bootstrap's CSS by layering in Font Awesome as a replacement for Bootstrap's default Glyphicons.
How can I customize the CSS generated by LESS to include Font Awesome in a way that won't break if I update the core Bootstrap files? Note: Font Awesome suggests altering the core Bootstrap 'bootstrap.less' file to replace @import "sprites.less"; with @import "path/to/font-awesome/less/font-awesome.less";, but this change would get overwritten if the Boostrap core were to be replaced (by a version upgrade, for example).
Similar to my earlier question ("How can I customize Twitter Bootstrap's CSS using LESSCSS variables?"), we can assume I have this file structure:
/html
    /bootstrap
       ...etc...
       /js
       /less
    /Font-Awesome
       /css
       /font
       /less
       ...etc...
    /MyApp
       ...etc...
       /common_files
          /less
             style.less

A:

Following the pattern suggested in Font Awesome's "getting started" section, edit the MyApp/common_files/less/style.less file to

import the font-awesome/less/font-awesome.less file, then
define the LESS variable '@fa-font-path' (for Font Awesome 4+) or '@FontAwesomePath' (for Font Awesome < 4)

So, given the directory structure in the question:
@import "../../../bootstrap/less/bootstrap.less";
@import "../../../bootstrap/less/responsive.less";
/* include the Font Awesome CSS */
@import "../../../Font-Awesome/less/font-awesome.less";

/* define path to Font Awesome 4's font folder*/
@fa-font-path:   "../../../Font-Awesome/fonts";

Or
/* or define path to Font Awesome 3's font folder*/
@FontAwesomePath:   "../../../Font-Awesome/font";


Q:

gm Error in aws lambda: string yields empty buffer

I'm trying to upload a buffer to s3 after doing an auto-orient transformation using amazon lambda.
I'm sending the buffer from a Nodejs api like so:

var data = request.payload;
          if (data.file) {
            var Media = request.server.plugins.dogwater.media;

            var name = data.file.hapi.filename;
            var local_path = "./uploads/" + name;
            var file = fs.createWriteStream(local_path);
            console.log('adding media...')
            file.on('error', function(err) {
              console.error(err)
            });

            data.file.pipe(file);

            data.file.on('end', function(err) {
              var pic = {
                gallery_id: request.params.gallery_id,
                type: 1
              };
              console.log("\n\n\ndata.file = ",data.file)

              Media.create(pic)
                .then(function(media) {
                  httpRequest({
                      url: 'secret',
                      method: 'POST',
                      json: {
                          media_id: media._id,
                          file_name: data.file.hapi.filename,
                          bucket: 'secret',
                          file: data.file
                      },
                      headers: {
                        'x-api-key': 'someapikey'
                      }

When I console log data.file._data in the api I get something like so:
  _data: <Buffer ff d8 ff e0 00 10 4a 46 49 46 00 01 01 01 00 48 00 48 00 00 ff e2 0b f8 49 43 43 5f 50 52 4f 46 49 4c 45 00 01 01 00 00 0b e8 00 00 00 00 02 00 00 00 ... >,

In the lambda (also nodejs) I have this code:

// dependencies
var async = require('async');
var AWS = require('aws-sdk');
var gm = require('gm').subClass({
    imageMagick: true
});
var util = require('util');
var path = require('path');

// get reference to S3 client
var s3 = new AWS.S3();
exports.handler = function(event, context) {

    // payload data
    var mediaId = event.media_id;
    var filename = event.file_name;
    var bucket = event.bucket;
    var file = event.file._data;

    console.log("file = ",file);

    // Infer the image type.
    var typeMatch = filename.match(/\.([^.]*)$/);
    if (!typeMatch) {
        console.error('unable to infer image type for file ' + filename);
        return;
    }
    var imageType = typeMatch[1].toLowerCase();

    var acceptedTypes = ['jpg','gif','png','eps','jpeg'];
    if (acceptedTypes.indexOf(imageType)===-1) {
        console.log('skipping non-image ');
        return;
    }

    async.waterfall([
        function process(next) {
            // Transform the image buffer in memory.
            gm(file).autoOrient().toBuffer(
                imageType.toUpperCase(), function(err,
                    buffer) {
                    if (err) {
                        //newly added line below:
                        console.log(err);
                        console.log("hit");
                        next(err);
                    } else {
                        console.log("buffer = ",buffer);
                        next(null,buffer);
                    }
                }
            );
        },
        function upload(data, next) {
            // Stream the image to folder.
            s3.putObject({
                Bucket: bucket,
                Key: mediaId + "/" + filename,
                Body: data,
                ContentType: imageType.toUpperCase()
            }, next);
        }
        ], function(err, result) {
            if (err) {
                console.error(err);
            }
            // return data to api here
            context.done();
        }
    )// end async waterfall
}// end exports handler

So. When I try to upload an image this is what file._data prints as before gm command:
 {type:'Buffer',data:[234,234,234,random numbers etc ...]}

But within the gm command this prints as the err:

Error: Stream yields empty buffer

A:

Found out the issue-
Data passed in to the aws lambda had to be remade into a buffer object to be accepted by gm. Changed one line of code (Inside exports.handler, where I'm defining file)

// dependencies
var async = require('async');
var AWS = require('aws-sdk');
var gm = require('gm').subClass({
    imageMagick: true
});
var util = require('util');
var path = require('path');

// get reference to S3 client
var s3 = new AWS.S3();
exports.handler = function(event, context) {

    // payload data
    var mediaId = event.media_id;
    var filename = event.file_name;
    var bucket = event.bucket;
    var file = new Buffer(event.file._data);

    console.log("file = ",file);

    // Infer the image type.
    var typeMatch = filename.match(/\.([^.]*)$/);
    if (!typeMatch) {
        console.error('unable to infer image type for file ' + filename);
        return;
    }
    var imageType = typeMatch[1].toLowerCase();

    var acceptedTypes = ['jpg','gif','png','eps','jpeg'];
    if (acceptedTypes.indexOf(imageType)===-1) {
        console.log('skipping non-image ');
        return;
    }

    async.waterfall([
        function process(next) {
            // Transform the image buffer in memory.
            gm(file).autoOrient().toBuffer(
                imageType.toUpperCase(), function(err,
                    buffer) {
                    if (err) {
                        //newly added line below:
                        console.log(err);
                        console.log("hit");
                        next(err);
                    } else {
                        console.log("buffer = ",buffer);
                        next(null,buffer);
                        //next(null, 'done');
                    }
                }
            );
        },
        function upload(data, next) {
            // Stream the image to folder.
            s3.putObject({
                Bucket: bucket,
                Key: mediaId + "/" + filename,
                Body: data,
                ContentType: imageType.toUpperCase()
            }, next);
        }
        ], function(err, result) {
            if (err) {
                console.error(err);
            }
            // return data to api here
            context.done();
        }
    )// end async waterfall
}// end exports handler


Q:

Проверка наличия изображения по ссылке

Например, есть 2 ссылки:
https://new.vk.com/images/icons/head_icons.png (ссылка на изображение)
https://vk.com/images/icons/head_icons.png (битая ссылка, 404-ая страница)

В программе надо загрузить 30000 изображений, некоторые ссылки будут битыми. Как сделать проверку на наличие изображения по ссылке? Можно, конечно же, загрузить 1-ый раз как страницу и проверить на любой html тег (например, <html>), и если нет этого тега - загрузить 2-ой раз как изображение, но этот костыль не поможет при таких больших объёмах, ибо придётся дважды загружать одно и тоже, в большинстве случаев.

A:

Например, можно так:
static async Task<byte[]> GetContentOrNull(Uri uri)
{
    using (var client = new HttpClient())
    using (var response = await client.GetAsync(uri))
    {
        if (!response.IsSuccessStatusCode) // если вернулся плохой статус
            return null;                   // возвращаем null
        using (var content = response.Content) // иначе читаем контент
            return await content.ReadAsByteArrayAsync();
    }
}

Вы можете проверить более точно код возврата responce.HttpStatusCode, если хотите.
Если нужно сохранить в файл, используйте content.CopyToAsync вместо content.ReadAsByteArrayAsync.

Для запроса лишь существования файла можно было бы использовать HEAD вместо GET:
static async Task<bool> CheckContent(Uri uri)
{
    using (var client = new HttpClient())
    using (var response = await client.SendAsync(new HttpRequestMessage(HttpMethod.Head, uri)))
        return response.IsSuccessStatusCode;
}

но для обеих ваших ссылок сервер возвращает 501 Not implemented.


Q:

How much are Or How much do?

I know that we usually say "how much does it cost" when asking for a price.
But today, I heard someone said "how much are the kidney beans?" in a store, and I don't think it's correct.
Does "How much are the kidney beans?" equal "How much do the kidney beans cost?"?

A:

Yes.
The Oxford English Dictionary, in its definition of be, has:

3 [as copular verb] Having the state, quality, identity, nature, role, etc., specified.
…
3.1 Cost.

‘the tickets were £25’

In the Oxford Advanced American Dictionary, the definition of be includes:

13 linking verb + noun to cost

“How much is that dress?” “Eighty dollars.”

The first popular culture reference that springs to mind is “(How Much Is) That Doggie in the Window?”.


Q:

The constructor FragmentPagerAdapter(FragmentManager) is undefined

I can't figure out what is going on with the constructor for the tabs Adapter.
 public TabsAdapter(Activity activity, ViewPager pager) {
         super(activity.getSupportFragmentManager());

This is giving me the error message: The method getSupportFragmentManager() is undefined for the type Activity
I think I am using the correct imports.  Below is the code that is pretty much copied straight from Android at this point.
 import android.app.ActionBar;
 import android.app.ActionBar.Tab;
 import android.app.Activity;
 import android.app.FragmentTransaction;
 import android.content.Context;
 import android.os.Bundle;
 import android.support.v4.app.Fragment;import android.support.v4.app.FragmentManager;
 import android.support.v4.app.FragmentPagerAdapter;
 import android.support.v4.view.ViewPager;
 import android.support.v4.app.FragmentActivity;
 import android.support.v4.view.ViewPager.OnPageChangeListener;

public class TabsAdapter extends FragmentPagerAdapter
     implements ActionBar.TabListener, ViewPager.OnPageChangeListener {

     private final Context mContext;
     private final ActionBar mActionBar;
     private final ViewPager mViewPager;
     private final ArrayList<TabInfo> mTabs = new ArrayList<TabInfo>();

     static final class TabInfo {

         private final Class<?> clss;
         private final Bundle args;

        TabInfo(Class<?> _class, Bundle _args) {
           clss = _class;
           args = _args;
        }
}

public TabsAdapter(Activity activity, ViewPager pager) {
    super(activity.getSupportFragmentManager());

    mContext = activity;
    mActionBar = activity.getActionBar();
    mViewPager = pager;
    mViewPager.setAdapter(this);
    mViewPager.setOnPageChangeListener(this);
}

public void addTab(ActionBar.Tab tab, Class<?> clss, Bundle args) {

    TabInfo info = new TabInfo(clss, args);
    tab.setTag(info);
    tab.setTabListener(this);
    mTabs.add(info);
    mActionBar.addTab(tab);
    notifyDataSetChanged();
}

@Override
public int getCount() {

    return mTabs.size();
}

@Override
public Fragment getItem(int position) {

    TabInfo info = mTabs.get(position);
    return Fragment.instantiate(mContext, info.clss.getName(), info.args);
}

@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

}

@Override
public void onPageSelected(int position) {

    mActionBar.setSelectedNavigationItem(position);
}

@Override
public void onPageScrollStateChanged(int state) {

}
@Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {

}

@Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
    // TODO Auto-generated method stub

}

@Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
    Object tag = tab.getTag();
    for (int i=0; i<mTabs.size(); i++) {
        if (mTabs.get(i) == tag) {
            mViewPager.setCurrentItem(i);
        }
    }

}

 }

Thanks to anyone taking a look at this!

A:

change
import android.app.Activity;

to
android.support.v4.app.FragmentActivity

you must use support library.


Q:

Subquery returned more than 1 value while inserting statement with multiple select statements

When I try to run the insert statement with multiple select statements, I am getting error

Msg 512, Level 16, State 1, Line 3 Subquery returned more than 1
  value. This is not permitted when the subquery follows =, !=, <, <= ,>, >= or when the subquery is used as an expression. The statement has been terminated.

My query
insert into zzz_fkp_tbl2 (fname,lname) values
(
    (select top 20 percent [FNAME] from ZZZ_FKP_NEW_PATIENT order by newid())
    ,(select top 20 percent lname from ZZZ_FKP_NEW_PATIENT order by newid())
);

But when I run the insert statement with single statement, this query is runnig successfully, like:
insert into zzz_fkp_tbl2 (lname)
select top 20 percent lname from ZZZ_FKP_NEW_PATIENT order by newid();

Why I am getting error Subquery returned more than 1 value while using multiple select statements. But the insert statement is working fine with single select statement. How can I use multiple select statements in this case?
My requirement is to select separate random rows for fname and lname, but not together i.e. fname should be selected randomly and lname should be selected randomly.
target table
create table zzz_fkp_tbl2
(
    zzz_fkp_tbl2_id int identity(1,1) not null
    ,name varchar(200)
    ,fname varchar(200)
    ,lname varchar(200)
    ,gender int
    ,address int
    ,age varchar(10)
);

A:

You are looking for this
INSERT INTO zzz_fkp_tbl2
            (fname,
             lname)
SELECT TOP 20 PERCENT [FNAME],
                      lname
FROM   ZZZ_FKP_NEW_PATIENT
ORDER  BY Newid()

Update :
SELECT TOP 20 PERCENT a.FNAME,
                      b.lname
FROM   ZZZ_FKP_NEW_PATIENT
       OUTER apply (SELECT TOP 1 [FNAME] ZZZ_FKP_NEW_PATIENT
                    ORDER  BY Newid()) a ([FNAME])
       OUTER apply (SELECT TOP 1 lname ZZZ_FKP_NEW_PATIENT
                    ORDER  BY Newid()) b (lname)


Q:

Build is disappearing from itunes connect

When I upload a build from xcode I'm able to see the build is processing on itunesconnect.apple.com, the image below is the screen I initially see:
build processing
But after I refresh the page the build disappears and doesn't reappear. It's been over an hour and I still don't see the build anymore. I've tried rearchiving but I get the same result--I see it initially but then it disappears. This is the "empty" screen I see after my build has disappeared:
empty build
Should I keep on waiting, contact support, or is this normal?

A:

Most probably you are missing some key in the plist.
Please check your email for the developer account.
App Store review may send you a email for the above issue.
Make sure you have the key
" NSPhotoLibraryUsageDescription " also added in your plist


Q:

How does % wildcard exactly work in sql when searching

I saw a select statement with something like this in the where part 'LIKE %Blabla%Another%', now I tried it myself and I don't clearly understand how it works. The thing I'm confused about is the % in the middle, I understand how '%Blabla Another%' works, but with the % as a replacement for the space, I got confused.

A:

% means "any sequence of characters, including an empty one". So LIKE '%Blabla%Another%' will match, for example 'XYZBlablaABCAnotherPQR', 'BlablaAnother' and '    Blabla Another           '


Q:

Error 2002 : The EntityContainer 'X' for the storage model specified as part of this MSL does not exist in MetadataWorkspace

I'm trying to integrate my Oracle Database into my ASP.NET app, but I keep getting this error :

Error 2002: The EntityContainer 'OracleDBTargetContainer' for the
  storage model specified as part of this MSL does not exist in
  MetadataWorkspace.

I've tried everything I could think of but still can't figure out what's wrong.
What can I do to diagnose the root cause of this?
This is still new to me so I might miss something very obvious.
I'm assuming it my not like my database as the Diagram displayed when I integrated another DB. I've checked the foreign keys, primary keys, ... but to no good.
Using VS2013 with ODP.NET 12c Release 3.
EDIT : My EntityContainerMapping is empty, is that normal?
<EntityContainerMapping CdmEntityContainer="PMModelContainer" StorageEntityContainer="PMModelTargetContainer"></EntityContainerMapping>

A:

I found what was wrong.
One of my foreign key didn't match the primary key (Number 20 instead of Number 10)
I saw on stack overflow that it could be a problem and checked my tables but I missed that one obviously.
How did I realize it ? Well because rather than creating the EF Designer, I chose the Code First from database option, and, oh, what do you know, the error message now tells you EXACTLY what the problem is ! (Table names and columns).


Q:

MKPinAnnotationView subview doens't update

I'm working on an application that uses custom AnnotationViews. It has a custom image and an background with a label in it. The background and label are subViews of the annotationView.
if ([annotation isKindOfClass:[VehicleAnnotation class]]) {
    VehicleAnnotation *vehicleAnnotation = annotation;

    MKPinAnnotationView *pinView = (MKPinAnnotationView*)[mapView dequeueReusableAnnotationViewWithIdentifier:driverAnnotationIdentifier];
    if(!pinView)
    {
        pinView = [[MKPinAnnotationView alloc]initWithAnnotation:annotation reuseIdentifier:driverAnnotationIdentifier];
    }

    pinView.annotation = annotation;

    pinView.canShowCallout = NO;
    pinView.image = [ImageHelper imageForStatus:vehicleAnnotation.vehicle.driver.driverStatus];

    // Add a label with the name of the driver
    CGRect pinFrame = pinView.frame;
    UILabel *label = [[UILabel alloc] init];
    [label setBackgroundColor:[UIColor clearColor]];
    [label setTextColor:[UIColor whiteColor]];
    [label setNumberOfLines:2];
    [label setLineBreakMode:NSLineBreakByWordWrapping];
    [label setFont:[UIFont systemFontOfSize:12]];
    label.text = vehicleAnnotation.vehicle.driver.description;

    CGSize maximumSize = CGSizeMake(100, 50);
    CGSize myStringSize = [label.text sizeWithFont:label.font
                                 constrainedToSize:maximumSize
                                     lineBreakMode:label.lineBreakMode];

    CGRect labelFrame = CGRectMake(pinFrame.origin.x, pinFrame.origin.y + pinFrame.size.height * 2 + 2, myStringSize.width, myStringSize.height);
    [label setFrame:labelFrame];

    // Add a background to the label.
    CGFloat offset = 5;
    CGRect backgroundFrame = CGRectMake(labelFrame.origin.x - offset, labelFrame.origin.y - offset , labelFrame.size.width + 2 * offset, labelFrame.size.height + 2 * offset);
    UIView *backgroundView = [[UIView alloc] initWithFrame:backgroundFrame];
    backgroundView.layer.cornerRadius = 5;
    backgroundView.layer.masksToBounds = YES;
    [backgroundView setBackgroundColor:[UIColor darkGrayColor]];
    [backgroundView setAlpha:0.8];
    [pinView addSubview:backgroundView];

    [label setUserInteractionEnabled:YES];
    [label setMultipleTouchEnabled:YES];
    [pinView addSubview:label];

    return pinView;
}

This code is performed each time new positions are received. The problem is that the old label and old background are still there. So I tought i put this code:
MKPinAnnotationView *pinView = (MKPinAnnotationView*)[mapView dequeueReusableAnnotationViewWithIdentifier:driverAnnotationIdentifier];
if(!pinView)
{
    pinView = [[MKPinAnnotationView alloc]initWithAnnotation:annotation reuseIdentifier:driverAnnotationIdentifier];
}
for(UIView *view in [pinView subviews])
{
    [view removeFromSuperview];
}
pinView.annotation = annotation;

But then no label or background is shown. Can somebody help me to replace or remove in a proper way the background and label?
Thank you!

A:

I suggest to make your own custom MKAnnotatinView. Otherwise using the above code, try adding Label and background view inside the bock in which you alloc init the MKAnnotationView. Set the frame and text and other properties which change for different annotations outside the block like below.
if ([annotation isKindOfClass:[VehicleAnnotation class]]) {
    VehicleAnnotation *vehicleAnnotation = annotation;

    MKPinAnnotationView *pinView = (MKPinAnnotationView*)[mapView dequeueReusableAnnotationViewWithIdentifier:driverAnnotationIdentifier];
    if(!pinView)
    {
        pinView = [[MKPinAnnotationView alloc]initWithAnnotation:annotation reuseIdentifier:driverAnnotationIdentifier];
    UILabel *label = [[UILabel alloc] init];
    [label setBackgroundColor:[UIColor clearColor]];
    [label setTextColor:[UIColor whiteColor]];
    [label setNumberOfLines:2];
    [label setLineBreakMode:NSLineBreakByWordWrapping];
    [label setFont:[UIFont systemFontOfSize:12]];
    [label setUserInteractionEnabled:YES];
    [label setMultipleTouchEnabled:YES];
    [label setTag:101];

    UIView *backgroundView = [[UIView alloc]init];
    [backgroundView setTag:102];
    backgroundView.layer.cornerRadius = 5;
    backgroundView.layer.masksToBounds = YES;
    [backgroundView setBackgroundColor:[UIColor darkGrayColor]];
    [backgroundView setAlpha:0.8];
    [pinView addSubView:backgroundView];
    [pinView addSubview:label];

    }

    pinView.annotation = annotation;

    pinView.canShowCallout = NO;
    pinView.image = [ImageHelper imageForStatus:vehicleAnnotation.vehicle.driver.driverStatus];

    // set frame of Label
    CGRect pinFrame = pinView.frame;
   UILabel *label = (UILabel *)[pinView viewWithTag:101];
    label.text = vehicleAnnotation.vehicle.driver.description;

    CGSize maximumSize = CGSizeMake(100, 50);
    CGSize myStringSize = [label.text sizeWithFont:label.font
                                 constrainedToSize:maximumSize
                                     lineBreakMode:label.lineBreakMode];

    CGRect labelFrame = CGRectMake(pinFrame.origin.x, pinFrame.origin.y + pinFrame.size.height * 2 + 2, myStringSize.width, myStringSize.height);
    [label setFrame:labelFrame];

    // set backgroundView frame.
    CGFloat offset = 5;
    CGRect backgroundFrame = CGRectMake(labelFrame.origin.x - offset, labelFrame.origin.y - offset , labelFrame.size.width + 2 * offset, labelFrame.size.height + 2 * offset);
    UIView *backgroundView = [pinView viewWithTag:102];
    [backgroundView setFrame:backgroundFrame];

    return pinView;
}


Q:

Can't write duplicate key, using combined primary key

I have two tables and I just want to keep a relation between them, users and combines, defined by the below
CREATE TABLE `shocase`.`combineScorers` (
  `combineId` INT NOT NULL,
  `userId` INT NOT NULL,
  `createdAt` DATETIME NOT NULL,
  `updatedAt` DATETIME NOT NULL,
  PRIMARY KEY (`combineId`, `userId`),
  INDEX `combineId_idx` (`combineId` ASC),
  INDEX `userId_idx` (`userId` ASC),
  CONSTRAINT `fk_combines_combineId`
    FOREIGN KEY (`combineId`)
    REFERENCES `shocase`.`combines` (`combineId`)
    ON DELETE NO ACTION
    ON UPDATE CASCADE,
  CONSTRAINT `fk_users_userId`
    FOREIGN KEY (`userId`)
    REFERENCES `shocase`.`users` (`userId`)
    ON DELETE NO ACTION
    ON UPDATE CASCADE);

Nothing too fancy, combineId and userId. Both are foreign keys to their respective tables, and I'm trying to create a combined primary key as (combineId, userId)
When ran I'm getting the below error

Error Code: 1022. Can't write; duplicate key in table 'combineScorers'

A:

You are probably using a constraint with the name combineId or userId in your database. They should be unique for the entire database. If so rename them.
Search for where the constraints are currently in use:
SELECT `TABLE_SCHEMA`, `TABLE_NAME`
FROM `information_schema`.`KEY_COLUMN_USAGE`
WHERE `CONSTRAINT_NAME` IN ('combineId', 'userId');


Q:

Running monero in its own virtualbox, performance issues?

I'm looking to run monero inside a ubuntu virtualbox vs having it run in the open with other apps around. From a security perspective, this should be safer. Since I'm not mining, what performance issues would I run into? I can see the vbox image would be over 30gb due to the blockchain size. Any way to reduce this aswell?

A:

Running any program inside a VM comes with a slight-to-moderate hit in performance. It really depends on how you set things up both on the host computer and inside the client OS. You say you want to use VirtualBox so I am going to assume you're going to run and configure the VM via the GUI and not do anything special with it.
If you're going to run Ubuntu (Desktop I'm assuming again) you're going to need at least 2 CPU cores and 2GBs of RAM for a decent user experience. On top of that you will need to have a big virtual hard drive to contain the blockchain. As of 20 september 2017 my chain is 28.5GB and still growing (I was a bit late with updating the daemon). You would need at least another 10GB for Ubuntu itself. That number includes spare space for future updates/patches and a small swap space). I would recommend to make a virtual disk file of at least a 100GB so that you won't have to do anything complicated to grow your disk file soon. I know from personal experience that writing and reading to this disk file is pretty much on par with that of a real drive.
As far as performance goes you won't really notice the two shared CPU cores. You will notice the 2GBs of always allocated RAM, or rather the lack thereof, as that's a big chunk of RAM for most computers. It will cause more swap usage on the host as less RAM is available for buffering files and such. The disk space is gone either way, whether the chain is stored inside the VM or on the host it does not matter: 28GB is 28GB. Ubuntu itself pales in comparison to the size of the blockchain so I just leave that out of the equation. The disk IO for the blockchain is small enough that you won't really notice it. Especially not if you're using an SSD. You probably would notice some delays in the host if you use a regular hard drive and if the host itself also does a lot of disk IO.
Now monerod itself uses (very) roughly around 20% of the Athlon X4 620 I'm using to power my miner. This will be much less on more modern CPUs. It also uses around a 100MB of RAM and the combined reads/writes are less than 2MB per second from/to the drive. That's nowhere near breaking point for any recent hardware.
So, running a monero node inside a VM is perfectly possible. The VM itself is absolute overkill though and you could save a lot of CPU power and RAM by using a container solution like LXC. If you do want to stick to VirtualBox use Ubuntu Server to ditch the heavy GUI and strip out any unneeded parts. You could probably get away with using a single core and 512MB of RAM then.
And lastly. Don't forget to turn on Intel-VTx/VTd or AMD-V (hardware virtualization) in the BIOS/UEFI. This is the single biggest performance booster for any kind of virtualization. Some computers (like the laptop I'm typing this answer on did) might need a BIOS update for the option to show up. Consult the manual of your motherboard for more information regarding this option.


Q:

Turn "foreach" into "for" with structures

I have this block that prints some description and some product details.
<?php foreach ($_additional as $_data): ?>

    <?php echo $this->htmlEscape($this->__($_data['label'])) ?>
    <?php echo $_helper->productAttribute($_product, $_data['value'], $_data['code']) ?>

<?php endforeach; ?>

I want to turn this into printing the description and only a number of product details so what I did is this
<?php
  for ($i = 0; $i <=4; $i++) {
    print_r($_additional[$i]);
  }
?>

This prints only the description though. How can I also print the product details?
Thank you

A:

You can access the details of the array with
<?php for ($i = 0; $i <=4; $i++) {
  echo $_additional[$i]['label'];
  echo $_helper->productAttribute($_product, $_additional[$i]['value'], $_additional[$i]['code']);
}


Q:

What Bible translations are accepted by the Southern Baptist Convention?

Is there is a list of which translations of the Bible are accepted by the Southern Baptist Convention?

A:

The Southern Baptist Convention, while the highest authority within the Southern Baptist church, is not technically an authority amongst Baptists.  It functions as a voluntary association with which member churches may choose to associate, but cannot dictate terms to anyone.  While it does approve changes to the "Baptist Faith and Message," these are to be taken as guidelines not at odds with the local autonomy of the church.
Within the Baptist Faith and Message (the closest thing Baptists have to a creed), it simply says:

The Holy Bible was written by men divinely inspired and is God's revelation of Himself to man. It is a perfect treasure of divine instruction. It has God for its author, salvation for its end, and truth, without any mixture of error, for its matter. Therefore, all Scripture is totally true and trustworthy. It reveals the principles by which God judges us, and therefore is, and will remain to the end of the world, the true center of Christian union, and the supreme standard by which all human conduct, creeds, and religious opinions should be tried. All Scripture is a testimony to Christ, who is Himself the focus of divine revelation.

The BFM itself is silent on which versions are "approved."
That said, I suspect the question wants to know what translations are preferred.  Here, any major translation would suffice,  I propose the following list to help you figure out which ones are most likely:

Conservative to Evangelical:  English Standard Version (ESV), NIV, HCSB (if you went to Dallas Theological Seminary)
Moderate to Scholarly: NRSV, RSV
Moderate to Gender-inclusively liberal: TNIV
Super-traditional: King James Version.  Maybe New King James, if they're feeling special.
Conservative but Scholarly: The Amplified Bible.
When the Preacher wants to make a point: NLT, "The Message"

Perhaps more useful would be the ones Baptists would be very unlikely to use:

New Jerusalem Bible, Duoay-Rheims:  perceived as too Catholic
New World Translation: restricted to the Jehovah's Witness
Makes most conservatives barf:  The Living Bible, Readers Digest Condensed, Good News Translation.


Q:

Extract specific css classes in a file

I'm trying to use a file all.css containing some classes and want to get a file green.css containing only green classes.
I'm using perl CSS module, any suggestions on how can i use it to search for lines that contain .green and end with { and then extract the css block ?
I'm new to perl, So far i tried to just print the selector lines matching "green" but i can't get it to work:
my $css = CSS->new( { 'parser' => 'CSS::Parse::Lite'} );

print $styleSheetPath;
$css->read_file($styleSheetPath);

 open my $fileHandle, ">>", "green.css" or die "Can't open 'green.css'\n";

 #search for lines that contain .green and end { and then extract css block
 #and write to green.css
 serialize($css);

 sub serialize{
       my ($obj) = @_;

    for my $style (@{$obj->{styles}}){
         print join "\n ", map {$_->{name}} @{$style->{selectors}};
         if ( grep( /green/, @{$style->{selectors}} )) {
           print "green matches ";
            print $_->{name};
         }

       }
}

A:

It helps to read the documentation of the software you are working with. Call the get_style_by_selector method with a .green argument to find the styles.
use CSS qw();
my $css = CSS->new;
$css->read_string('.red { clear: both; } .green { clear: both; }');
$css->get_style_by_selector('.green')->to_string;