text:
Q: Felix: deployed bundle starts twice I'm deploying with Maven (but same issue with Felix web console) and the maven-sling-plugin and I see it starts twice:
*INFO* [qtp1462409406-40] logs/access.log 127.0.0.1 - admin 25/Feb/2016:11:18:31 +0100 "POST /dev/system/console/install HTTP/1.1" 200 - "-" "Jakarta Commons-HttpClient/3.1"
*INFO* [Background Install /var/folders/v0/gh9_k3ld5vx43sn057mg6h3c0000gn/T/install2994913564032148892.tmp] com.as.test.content BundleEvent INSTALLED
*INFO* [Background Install /var/folders/v0/gh9_k3ld5vx43sn057mg6h3c0000gn/T/install2994913564032148892.tmp] com.as.test.content BundleEvent RESOLVED
*INFO* [Background Install /var/folders/v0/gh9_k3ld5vx43sn057mg6h3c0000gn/T/install2994913564032148892.tmp] com.as.test.content BundleEvent STARTING
*INFO* [Background Install /var/folders/v0/gh9_k3ld5vx43sn057mg6h3c0000gn/T/install2994913564032148892.tmp] com.as.test.content BundleEvent STARTED
*INFO* [Background Install /var/folders/v0/gh9_k3ld5vx43sn057mg6h3c0000gn/T/install2994913564032148892.tmp] com.as.test.content Service [com.as.test.jcr.service.NodeFinderImpl,374] ServiceEvent REGISTERED
*INFO* [Background Install /var/folders/v0/gh9_k3ld5vx43sn057mg6h3c0000gn/T/install2994913564032148892.tmp] com.as.test.content Service [com.as.test.jcr.service.NodeSorterImpl,375] ServiceEvent REGISTERED
*INFO* [Background Install /var/folders/v0/gh9_k3ld5vx43sn057mg6h3c0000gn/T/install2994913564032148892.tmp] com.as.test.content Service [com.as.test.jcr.service.UserProcessorImpl,376] ServiceEvent REGISTERED

====> Starts executing code: creates users, sets permissions and sort nodes with the JCR API
[...]
*ERROR* [pool-7-thread-1] com.as.test.content [com.as.test.jcr.service.ContentInitializerImpl(173)] Failed creating the component instance; see log for reason
*INFO* [FelixFrameworkWiring] com.as.test.content BundleEvent STOPPING
*INFO* [FelixFrameworkWiring] com.as.test.content Service [com.as.test.jcr.service.ContentInitializerImpl,383] ServiceEvent UNREGISTERING
*INFO* [FelixFrameworkWiring] com.as.test.content Service [com.as.test.jcr.service.NodeSorterImpl,375] ServiceEvent UNREGISTERING
*INFO* [FelixFrameworkWiring] com.as.test.content Service [com.as.test.jcr.service.UserProcessorImpl,376] ServiceEvent UNREGISTERING
*INFO* [FelixFrameworkWiring] com.as.test.content Service [com.as.test.jcr.service.NodeFinderImpl,374] ServiceEvent UNREGISTERING
*INFO* [FelixFrameworkWiring] com.as.test.content BundleEvent STOPPED
*INFO* [FelixFrameworkWiring] com.as.test.content BundleEvent UNRESOLVED
*INFO* [FelixFrameworkWiring] com.as.test.content BundleEvent RESOLVED
*INFO* [FelixFrameworkWiring] com.as.test.content BundleEvent STARTING
*INFO* [FelixFrameworkWiring] org.apache.sling.jcr.contentloader.internal.Loader Content of bundle already loaded com.as.test.content.
*INFO* [FelixFrameworkWiring] com.as.test.content BundleEvent STARTED
*INFO* [FelixFrameworkWiring] com.as.test.content Service [com.as.test.jcr.service.NodeFinderImpl,384] ServiceEvent REGISTERED
*INFO* [FelixFrameworkWiring] com.as.test.content Service [com.as.test.jcr.service.NodeSorterImpl,385] ServiceEvent REGISTERED
*INFO* [FelixFrameworkWiring] com.as.test.content Service [com.as.test.jcr.service.ContentInitializerImpl,387] ServiceEvent REGISTERED
*INFO* [FelixFrameworkWiring] com.as.test.jcr.service.ContentInitializerImpl Initializing Sling content
====> Starts (again) executing code: creates users, sets permissions and sort nodes with the JCR API

I'm executing some code on bundle's startup and it gets stopped in the middle of it, and then restarted, and I can't find why.
I've tried with Sling launchpad 7 and 8, respectively using org.apache.felix.framework 4.4.1 and 5.2.0
EDIT: stacktraces
1. Starts from background install
*INFO* [Background Install /var/folders/v0/gh9_k3ld5vx43sn057mg6h3c0000gn/T/install3836459285044407564.tmp] com.as.test.Activator   java.lang.Thread.getAllStackTraces(Thread.java:1640)
*INFO* [Background Install /var/folders/v0/gh9_k3ld5vx43sn057mg6h3c0000gn/T/install3836459285044407564.tmp] com.as.test.Activator   com.as.test.Activator.printStrackTraces(Activator.java:33)
*INFO* [Background Install /var/folders/v0/gh9_k3ld5vx43sn057mg6h3c0000gn/T/install3836459285044407564.tmp] com.as.test.Activator   com.as.test.Activator.start(Activator.java:23)
*INFO* [Background Install /var/folders/v0/gh9_k3ld5vx43sn057mg6h3c0000gn/T/install3836459285044407564.tmp] com.as.test.Activator   org.apache.felix.framework.util.SecureAction.startActivator(SecureAction.java:645)
*INFO* [Background Install /var/folders/v0/gh9_k3ld5vx43sn057mg6h3c0000gn/T/install3836459285044407564.tmp] com.as.test.Activator   org.apache.felix.framework.Felix.activateBundle(Felix.java:2154)
*INFO* [Background Install /var/folders/v0/gh9_k3ld5vx43sn057mg6h3c0000gn/T/install3836459285044407564.tmp] com.as.test.Activator   org.apache.felix.framework.Felix.startBundle(Felix.java:2072)
*INFO* [Background Install /var/folders/v0/gh9_k3ld5vx43sn057mg6h3c0000gn/T/install3836459285044407564.tmp] com.as.test.Activator   org.apache.felix.framework.BundleImpl.start(BundleImpl.java:976)
*INFO* [Background Install /var/folders/v0/gh9_k3ld5vx43sn057mg6h3c0000gn/T/install3836459285044407564.tmp] com.as.test.Activator   org.apache.felix.framework.BundleImpl.start(BundleImpl.java:963)
*INFO* [Background Install /var/folders/v0/gh9_k3ld5vx43sn057mg6h3c0000gn/T/install3836459285044407564.tmp] com.as.test.Activator   org.apache.felix.webconsole.internal.core.InstallHelper.doRun(InstallHelper.java:67)
*INFO* [Background Install /var/folders/v0/gh9_k3ld5vx43sn057mg6h3c0000gn/T/install3836459285044407564.tmp] com.as.test.Activator   org.apache.felix.webconsole.internal.core.BaseUpdateInstallHelper.doRun(    BaseUpdateInstallHelper.java:89)
*INFO* [Background Install /var/folders/v0/gh9_k3ld5vx43sn057mg6h3c0000gn/T/install3836459285044407564.tmp] com.as.test.Activator   org.apache.felix.webconsole.internal.core.BaseUpdateInstallHelper.run(    BaseUpdateInstallHelper.java:121)

2. Stops from FelixFrameworkWiring
*INFO* [FelixFrameworkWiring] com.as.test.Activator THREAD: Thread[FelixFrameworkWiring,5,main]
*INFO* [FelixFrameworkWiring] com.as.test.Activator   java.lang.Thread.dumpThreads(Native Method)
*INFO* [FelixFrameworkWiring] com.as.test.Activator   java.lang.Thread.getAllStackTraces(Thread.java:1640)
*INFO* [FelixFrameworkWiring] com.as.test.Activator   com.as.test.Activator.printStrackTraces(Activator.java:33)
*INFO* [FelixFrameworkWiring] com.as.test.Activator   com.as.test.Activator.start(Activator.java:23)
*INFO* [FelixFrameworkWiring] com.as.test.Activator   org.apache.felix.framework.util.SecureAction.startActivator(SecureAction.java:645)
*INFO* [FelixFrameworkWiring] com.as.test.Activator   org.apache.felix.framework.Felix.activateBundle(Felix.java:2154)
*INFO* [FelixFrameworkWiring] com.as.test.Activator   org.apache.felix.framework.Felix.startBundle(Felix.java:2072)
*INFO* [FelixFrameworkWiring] com.as.test.Activator   org.apache.felix.framework.Felix$RefreshHelper.restart(Felix.java:4911)
*INFO* [FelixFrameworkWiring] com.as.test.Activator   org.apache.felix.framework.Felix.refreshPackages(Felix.java:4148)
*INFO* [FelixFrameworkWiring] com.as.test.Activator   org.apache.felix.framework.FrameworkWiringImpl.run(FrameworkWiringImpl.java:178)
*INFO* [FelixFrameworkWiring] com.as.test.Activator   java.lang.Thread.run(Thread.java:745)

3. Restarts from FelixFrameworkWiring
*INFO* [FelixFrameworkWiring] com.as.test.Activator THREAD: Thread[FelixFrameworkWiring,5,main]
*INFO* [FelixFrameworkWiring] com.as.test.Activator   java.lang.Thread.dumpThreads(Native Method)
*INFO* [FelixFrameworkWiring] com.as.test.Activator   java.lang.Thread.getAllStackTraces(Thread.java:1640)
*INFO* [FelixFrameworkWiring] com.as.test.Activator   com.as.test.Activator.printStrackTraces(Activator.java:33)
*INFO* [FelixFrameworkWiring] com.as.test.Activator   com.as.test.Activator.start(Activator.java:23)
*INFO* [FelixFrameworkWiring] com.as.test.Activator   org.apache.felix.framework.util.SecureAction.startActivator(SecureAction.java:645)
*INFO* [FelixFrameworkWiring] com.as.test.Activator   org.apache.felix.framework.Felix.activateBundle(Felix.java:2154)
*INFO* [FelixFrameworkWiring] com.as.test.Activator   org.apache.felix.framework.Felix.startBundle(Felix.java:2072)
*INFO* [FelixFrameworkWiring] com.as.test.Activator   org.apache.felix.framework.Felix$RefreshHelper.restart(Felix.java:4911)
*INFO* [FelixFrameworkWiring] com.as.test.Activator   org.apache.felix.framework.Felix.refreshPackages(Felix.java:4148)
*INFO* [FelixFrameworkWiring] com.as.test.Activator   org.apache.felix.framework.FrameworkWiringImpl.run(FrameworkWiringImpl.java:178)

A: The best is for your bundle to be prepared for such a situation. Many things can cause bundles to start multiple times, that shouldn't be an exceptional situation.


text:
Q: How can I run a Powershell script in PHP? I have this Powershell V2.0 script that pings every computer on the database server and if it pings succesfully it will return the usernames that are logged on. Now, with my PHP I am displaying the computer names but I need to execute the Powershell script in order to display the usernames. How Can I achieve this?
Working fiddle click on the box it displays the computer name
thanks in advance!
Powershell script:
#call procedure to execute the command
$command.CommandText = "SELECT w.ws FROM
                        sandbox_maesc4.coordinates c
                        INNER JOIN
                        softphone_materials_updater.workstations w
                        ON c.station_number = w.pod";

#Execute the Command by reading each row
$reader = $command.ExecuteReader();
#Read values from database
$workstation_list = $( while ($reader.Read() ){
                    $reader.GetValue(0)
                })
   #close reader
$reader.Close()

#ping each computer if online, obtain information about the local hard drives only
try{
    foreach($pc_db in $workstation_list){
        if(Test-Connection -ComputerName $pc_db -Count 1 -ErrorAction SilentlyContinue){
           $username = Get-WMIObject -ComputerName $pc_db -Class Win32_ComputerSystem | Select-Object Username #-ExpandProperty
            #Get-WMIObject -ComputerName $pc_db -Class Win32_ComputerSystem -Property Username
            Write-host "$username is logged into $pc_db";
         } #end if

        else{
            Write-Host "$pc_db is Offline" -ForegroundColor Red
        }#end else

     }#end for each loop
 }#end try
 catch{
            Write-Host "Caught the exception";
            Write-Host "$_";
            throw $error[0].Exception
     }#end catch
$connection.Close()
}#end ping_test function

ping_getUser #execute function

PHP:
<?
//query to show workstation/desks information from DB for the DESKS
$station_sql = "SELECT coordinate_id, section_name, x_coord, y_coord, w.ws, w.pod FROM
                                sandbox_maesc4.coordinates c
                                INNER JOIN
                                softphone_materials_updater.workstations w
                                ON c.station_number = w.pod";

$station_result = mysqli_query($conn,$station_sql);

//see if query is good
if($station_result === false) {
    die(mysqli_error());
}

    //display hidden DIV when toggle with information inside
        while($row = mysqli_fetch_assoc($station_result)){
                //naming values

                //coordinates table
                $id       = $row['coordinate_id'];
                $x_pos    = $row['x_coord'];
                $y_pos    = $row['y_coord'];
                $sec_name = $row['section_name'];

                //workstations table
                $workstations = $row['ws'];
                $pod                  = $row['pod'];

                //display DIV with the content inside
echo '

Section:' . $sec_name     .     '
Station:' . $workstations .     '
Pod:'     . $pod          .     '

' . "\n";
            }//end while loop for station_result

?>

A: You can use exec() or shell_exec() to run Windows commands.
If you need to use powershell, simply start powershell before running your command:
$output = shell_exec('powershell Test-Path C:\\');
echo $output // True

Or if you want to run a specfici powershell script:
$output = shell_exec('powershell -File C:\Path\To\Script.ps1');
echo $output // True

If you need to bypass the execution policy that denies you running powershell scripts:
$output = shell_exec('powershell -ExecutionPolicy ByPass -File C:\Path\To\Script.ps1');
echo $output // True

A: You can use either exec, system or passthru function

redpajama_set_name: RedPajamaStackExchange


text:
Q: Force jenkins to return stable build? We have 11 @tests which we call a test pack and each test pack gets populated with about 15 -20 individual tests.
We then split the @tests into 2 batches.
Batch one is test pack 1 -6 and batch two is from 7 - 11. We build these tests on jenkins each night concurrently. Batch 1 99% of the time returns stable.
Batch 2 99% of the time returns unstable even if the build was successful. We have a @test after test pack 11 that creates a report with failed tests.
Now when jenkins returns a build as unstable the @test generateReport doesnt "close" the report has been created however the bytes indicate 0kb thus tells me it never closed.
Is there a way to force jenkins to return stable state? Using java and Selenium

A: If you are using Pipeline Jobs and Jenkinsfiles for your build process, you can manually set the build result.
The currentBuild variable is made available in any Jenkinsfile. The following is untested, but should give you a general idea
node {
    stages{
        stage('Test') {
            script {
                try {
                    # Run tests here
                } catch (e) {
                    # Determine if e indicates the expected test failures or something else
                    currentBuild.result = 'SUCCESS'
                }
            }
        }
    }
}

Note that the above should mark the Test stage succesful; the rest of the build would continue as normal


text:
Q: How to obtain $\int_0^{\infty} \frac{1}{\sqrt{\frac{\sigma^2}{N-1} y + \sigma_t^2}} y^{\frac{N-1}{2}-1}e^{-\frac{y}{2}} dy$? Let $X_1, X_2 \cdots X_N$ be random variables, which follow a Gaussian distribution.
\begin{equation}
X \sim N(\mu, \sigma^2)
\end{equation}
Let the parameters $\mu$ and $\sigma^2$ be unknown.
The unbiased estimator of $\sigma^2$ is
\begin{equation}
U = \frac{1}{N-1}\left((X_1 -\bar{X})^2 \cdots (X_N -\bar{X})^2\right)
\end{equation}
I'd like to calculate the mean value of $\tilde{F}=\frac{1}{\sqrt{U + \sigma_t^2}}$ where $\sigma_t^2$ is a known parameter.
\begin{equation}
\begin{split}
E\left[\tilde{F} \right]&= E\left[\frac{1}{\sqrt{U + \sigma_t^2}}\right] \\
&=  E\left[\frac{1}{\sqrt{\frac{\sigma^2}{N-1} Y +  \sigma_t^2}}\right] \quad (Y \sim \chi_{N-1}^2) \\
&=  \int_0^{\infty}
\frac{1}{\sqrt{\frac{\sigma^2}{N-1} y +  \sigma_t^2}}
\frac{y^{\frac{N-1}{2}-1}e^{-\frac{y}{2}}}
{2^{\frac{N-1}{2}} \Gamma(\frac{N-1}{2})} dy
\end{split}
\end{equation}
How can I calculate this value?


text:
Q: No more volume OSD after 14.10 -> 15.04 upgrade In 14.10 when I pressed a volume key on my keyboard, the volume value would show in a popup in the top right corner of the screen.
The volume keys still work (I can hear the "pop" sound) but the notification popup does not show anymore since 15.04. Is it something normal for 15.04? How can I enable it back?
I still have notifications but one strange thing I noticed is that when the notification popup appears, for example when a new mail is received in Thunderbird, or by manually sending a notification with "notify-send" from a terminal, the look&feel of the popup is not the same at all than with 14.10. The background is now light gray instead of being dark brown/gray.

A: For some reason I had another notification daemon running, so I uninstalled it before reinstalling notify-osd:
sudo apt-get remove xfce4-notifyd
sudo apt-get install --reinstall notify-osd

then reboot.

A: After upgrading from Ubuntu 12.04 to 16.04, I had to uninstall this notification daemon to get the volume OSD to work:
sudo apt purge notification-daemon

Then log out and in again.


text:
Q: How to set Development environment in V.S.Code? I am using V.S Code to develop an Asp.net Core project. I tried to set the environment to "Development" by setting it in cmd line with
setx ASPNETCORE_ENVIRONMENT "Development"
or/and changing settings in Launch.json with
"env": {
                "ASPNETCORE_ENVIRONMENT": "Development"
        },

as showed in the attached picture below, but seems the environment is still "Production". Did I miss anything? Thanks!
Setting "Development" in V.S Code

A: The environment variables will not take effect if we run directly from the terminal.
Instead, click the "Run and Debug" menu on the left and chose the name of the configuration profile where the environmental variables are added, then click the "Run" icon.


text:
Q: Keeping this combo box enabled I have 3 rad drop down lists. On page load ComBox_MDCList is disabled until one of other drop downs selected index = "Pizza". The problem is that after it is enabled by the first dropdown, if the 2nd dropdown is selected and does not = Pizza it will then disable again. How can I keep ComBox_MDCList enabled as long as 1 dropdown = Pizza?
Page Load
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
    ComBox_MDCList.Enabled = False
End Sub

sub called
 Protected Sub MDCList()
        If (ComBox_Growth1.Text Or ComBox_Growth2.Text = "Pizza") Then
            ComBox_MDCList.Enabled = True
        Else
            ComBox_MDCList.Enabled = False
        End If
    End Sub

1st drop box vb
  Protected Sub ComBox_Growth1_SelectedIndexChanged(sender As Object, e As RadComboBoxSelectedIndexChangedEventArgs) Handles ComBox_Growth1.SelectedIndexChanged

    If ComBox_Growth1.Text = "Pizza" Then
        MDCList()
    End If

End Sub

2nd drop box vb
Protected Sub ComBox_Growth2_SelectedIndexChanged(sender As Object, e As RadComboBoxSelectedIndexChangedEventArgs) Handles ComBox_Growth2.SelectedIndexChanged

    If ComBox_Growth2.Text = "Pizza" Then
        MDCList()
    End If

End Sub

A: Try
Protected Sub MDCList()
     If (ComBox_Growth1.Text = "Pizza" Or ComBox_Growth2.Text = "Pizza") Then
         ComBox_MDCList.Enabled = True
     Else
         ComBox_MDCList.Enabled = False
     End If
End Sub

Protected Sub ComBox_Growth1_SelectedIndexChanged(sender As Object, e As RadComboBoxSelectedIndexChangedEventArgs) Handles ComBox_Growth1.SelectedIndexChanged
     MDCList()
End Sub

Protected Sub ComBox_Growth2_SelectedIndexChanged(sender As Object, e As RadComboBoxSelectedIndexChangedEventArgs) Handles ComBox_Growth2.SelectedIndexChanged
     MDCList()
End Sub


text:
Q: For ruby/webrick, I need windows to recognize shebang (#!) notation (Bear with me, I promise this gets to shebang and windows.)
I have about the simplest of WEBRick servers put together:
require 'webrick'
include WEBrick

s = HTTPServer.new(:Port=>2000, :DocumentRoot=>Dir::pwd)
s.start

Couldn't be simpler.  This basic server does accept http connections (firefox, internet exploder, wget, TELENT) and deals with them appropriately, as long as I'm just fetching static documents.  If, however, I set one of the files in the directory to have a .cgi extension, I get a 500 back and the following on the server's terminal:
ERROR CGIHandler: c:/rubyCGI/test.cgi:
C:/...[snip]...webrick/httpservlet/cgi_runner.rb:45: in 'exec': Exec format error - ...[snip]...

I've done a few things on the command line to mimic what is going on in line 45 of cgi_runner.rb
c:\>ruby
exec "c:/rubyCGI/test.cgi"
^Z
(same error erupts)

c:\>ruby
exec "ruby c:/rubyCGI/test.cgi"
^Z
Content-type: text/html

Mares eat oats and does eat oats and I'll be home for Christmas.

Clearly, WEBrick hasn't been cleared for landing on windows.  Your usual headaches of corporate paranoia prevent me from modifying webrick, so can I get the shebang notation in c:/rubyCGI/test.cgi recognized by the OS (windows) so I don't have to explicitly tell it each time which interpreter to use?  I could assign all .cgi files to be associated with ruby, but that would be limiting in the long run.
UPDATE:
Since posting this, it has occurred to me that it may not be possible at all to run a cgi web server from ruby; ruby has no forking support.  With no ability to fork a process, a cgi server would have to execute each cgi script one-at-a-time, neglecting all concurrent requests while the first one completed.  While this may be acceptable for some, it would not work for my application.  Nevertheless, I would still be very interested in an answer to my original question—that of getting shebang working under windows.

A: I think what you want is to associate the file extension with Ruby.  I don't think it's possible to get the !# notation to work on Windows but it is possible to get Windows to automatically launch a script with a particular interpreter (as in your second example).  A good step by step discussion of what you'd want to do is here.  You specifically want the section headed: "To create file associations for unassociated file types".  I think that will accomplish what you're trying to do.

A: A generic solution that works for both Ruby 1.8.6.pxxx and 1.9.1.p0 on
Windows is the following:
Edit the file: c:\ruby\lib\ruby\1.9.1\webrick\httpservlet\cgi_runner.rb
Add the following lines at the top of the file:

if "1.9.1" == RUBY_VERSION
  require 'rbconfig'  #constants telling where Ruby runs from
end

Now, locate the last line where is says:  exec ENV["SCRIPT_FILENAME"]
Comment that line out and add the following code:

# --- from here ---
if "1.9.1" == RUBY_VERSION  #use RbConfig
  Ruby = File::join(RbConfig::CONFIG['bindir'],
                        RbConfig::CONFIG['ruby_install_name'])
  Ruby << RbConfig::CONFIG['EXEEXT']
else                        # use ::Config
  Ruby = File::join(::Config::CONFIG['bindir'],
                        ::Config::CONFIG['ruby_install_name'])
  Ruby << ::Config::CONFIG['EXEEXT']
end

if /mswin|bccwin|mingw/ =~ RUBY_PLATFORM
  exec "#{Ruby}", ENV["SCRIPT_FILENAME"]
else
  exec ENV["SCRIPT_FILENAME"]
end
# --- to here ---

Save the file and restart the webrick server.
Explanation:
This code just builds a variable 'Ruby' with the full path to
"ruby.exe", and
(if you're running on Windows) it passes the additional parameter
"c:\ruby\bin\ruby.exe" , to the Kernel.exec() method, so that your
script can be executed.

A: Not really to argue... but why bother webrick when mongrel is much faster and with native compiled with windows? And of coz, that means no shebang is needed.

A: Actually, it is possible to get Windows to recognize shebang notation in script files. It can be done in a relatively short script in say, Ruby or AutoIt. Only a rather simple parser for the first line of a script file is required, along with some file manipulation. I have done this a couple times when either cross-compatibilty of script files was required or when Windows file extensions did not suffice.


text:
Q: Corsair K70: Adjusting keyboard brightness triggers chrome reload I am using a Corsair K70 (single colour backlit) on Ubuntu 14.04. If I cycle through the brightness setting (off, dim, normal, bright), transitioning from off -> dim caused calculator to open, and bright -> off causes a reload page (e.g., in Chrome).
I am mostly interested in why this is? Is it a fault with the design? How can I monitor exactly what key signals are being sent to the computer? But also, how can this behaviour be disabled?

A: I have the same issue with my new K70 I got today.
The solution was to install the unofficial (because Linux isn't supported officially) driver, ckb, It's working great!
I also noticed that the lights for numlock and capslock started responding correctly after installing the driver.


text:
Q: how to add current active user as foreign key to the task model in django 3? I am creating a task to do web app using django 3,
I have two models one is UserCustom and other is UserTask in which each corresponding active user can add task.
I am getting the entry details through a "model form".
For adding the task user need to be login.
But mentioning UserCustom as foriegn key in UserTask model, creates a combo (dropdown) box on the "AddTask.html" page with all the registered users.
How can i autimatically add current active user as foreign key in UserTask model ?
Below are the codes
models.py
from django.db import models
from django.contrib.auth.models import User
from django.conf import settings
# Create your models here.

class UserCustom(models.Model):
    user=models.OneToOneField(User,on_delete=models.CASCADE)

    profile_pic=models.ImageField(upload_to='profile_pics',blank=True)

    def __str__(self):
        return self.user.username   #user os object defined above

class UserTask(models.Model):
    author = models.ForeignKey(UserCustom,on_delete=models.CASCADE)
    label=models.CharField(max_length=264)
    date=models.DateField()
    status=models.BooleanField(default=False)

    def __str__(self):
        return str(self.label)

forms.py
from django import forms
from django.forms.fields import DateField
from django.contrib.auth.models import User
from taskApp.models import UserCustom,UserTask
from django.contrib.admin.widgets import AdminDateWidget

class UserForm(forms.ModelForm):
    password=forms.CharField(widget=forms.PasswordInput())

    class Meta():
        model=User
        fields=('username','email','password')

class UserCustomForm(forms.ModelForm):
    class Meta():
        model=UserCustom
        fields=('profile_pic',)

class UserTaskForm(forms.ModelForm):
    date=DateField(widget=forms.DateInput(attrs={'placeholder': 'YYYY-MM-DD', 'required': 'required'}))
    class Meta():
        model=UserTask
        fields=('author','label','status','date')

views.py
from django.shortcuts import render
from taskApp.forms import UserForm,UserCustomForm,UserTaskForm

#below libraries required for login
from django.contrib.auth import authenticate,login,logout

from django.http import HttpResponseRedirect,HttpResponse
from django.urls import reverse
from django.contrib.auth.decorators import login_required

# Create your views here.
def index(request):
    return render(request,'taskApp/index.html')

@login_required
def add_task(request):
    #return HttpResponse("You are logged in, Nice!")
    added=False
    if request.method == "POST":
        task_form=UserTaskForm(data=request.POST)
        if task_form.is_valid():

            task=task_form.save()
            #task.user=user
            task.save()

            added=True

        else:
            print(task_form.errors)

    else: #no request=POST yet
        task_form=UserTaskForm()

    return render(request,'taskApp/task.html',{'added':added,'task_form':task_form})

@login_required
def user_logout(request):  #only login users can logout
    logout(request)
    return HttpResponseRedirect(reverse('index'))

def register(request):

    registered=False

    if request.method == "POST":

        user_form=UserCustomForm(data=request.POST)
        profile_form=UserProfileInfoForm(data=request.POST)

        if user_form.is_valid() and profile_form.is_valid():

            #grabbing user form ,saving to DB and hashing the password and then saving the changes
            user=user_form.save()
            user.set_password(user.password)
            user.save()

            profile=profile_form.save(commit=False)
            profile.user=user

            if 'profile_pic' in request.FILES:
                profile.profile_pic=request.FILES['profile_pic']

            profile.save()

            registered=True

        else:
            print(user_form.errors,profile_form.errors)

    else: #no request=POST yet
        user_form=UserCustomForm()
        profile_form=UserProfileInfoForm()

    return render(request,'taskApp/registration.html',
                            {'user_form':user_form,
                            'profile_form':profile_form,
                            'registered':registered })

def user_login(request):

    if request.method=='POST':
        username=request.POST.get('username')  #name of element
        password=request.POST.get('password')

        user=authenticate(username=username,password=password)

        if user:
            if user.is_active:
                login(request,user)
                return HttpResponseRedirect(reverse('index')) #redirect to home page
            else:
                return HttpResponse("ACCOUNT NOT ACTIVE")

        else:
            print("Someone tried to login and failed!")
            print("Username: {} and password {}".format(username,password))
            return HttpResponse("invalid login details supllied!")

    else:
        return render(request,'taskApp/login.html',{})

A: You can access the current user with request.user.
...
 if request.method == "POST":
    task_form=UserTaskForm(data=request.POST)
    if task_form.is_valid():

        task=task_form.save(commit=False)
        task.author= request.user
        task.save()

        added=True
...


text:
Q: Insert data-bound HTML into standalone auto-binding template It is documented that you can override Polymer's data binding default behavior of escaping HTML by using the injectBoundHTML method.
That's fine for some use cases, but is there a way to prevent HTML escaping for just standalone templates?
For example, I have a template in the  of my HTML page that looks like this; how can I prevent the HTML of the myHTMLsnippet value from being escaped?
<template is="auto-binding">

{{myHTMLsnippet}}

</template>

A: I was able to find a workaround by nesting the juicy-html element inside the auto-binding template.
<template is="auto-binding">

    <template is="juicy-html" content="{{myHTMLsnippet}}"></template>

</template>


text:
Q: Angularjs issue with directive unchecking all checkboxes Hello and thank you for looking at my issue.
I am creating a directive that simply list parents and their children. Each parent have a checkbox available to allow user to print the parents indeed checked (examples: if user check parent #1 and #5, only #1 and #5 will be printed ). I also have a filter the allow users to "filter" parents (over 100 of them).
The issue is with the checkboxes: I would like that the filter ( a drop down ) when selected would clear all checkboxes. Right now if user checks parent #1 and #5 and filter out 5, #1 stays checked. I am adding my code below.
Thanks so much for helping me...
app.directive('isolateScopeWithController', function () {

var controller = ['$scope', 'treeFactory', '$q', function ($scope, treeFactory, $q) {

    var vm = this;

    $scope.ocw = "";

    $scope.types = [
                   {description : "All Parent", type : 2},
                   {description : "True Parent", type : 1},
                   {description : "Parent", type : 0}
               ];

     $scope.$watch('selectedType', function(){
        // I wish I would have this function working
        uncheckAll();

    })

   function uncheckAll() {
        // uncheck all the  check box currently checked
        // cannot do it!
    }

    init();

    function init(){

        $scope.selectedType = "2";

        $scope.ocw = {
         "parents":[
         {name: "parent1", "type": 0, children: ["name": "child1", "name": "child2"]},
         {name: "parent2", "type": 0, children: ["name": "child3", "name": "child4"]},
         ...
         {name: "parent5", "type": 1, children: ["name": "child10", "name": "child11"]}
         ]
        }
    }
    ],

  template = '
'+
                 '
'+
                    '<select ng-model="selectedType" ng-change="update(selectedType)">'+
                        '<option ng-repeat="x in types" value="{{x.type}}">{{x.description}}</option>'+
                    '</select>'+
                 '
'+
                 '
'+
                    '<button type="button" class="btn btn-default btn-primary" ng-click="printParentschecked(ocw)">  Print Selected </button>'+
                 '
'+
             '
'+
                 '
'+
                    '
'+
                         '
'+
                            '
'+
                                '{{parent.name}}'+
                            '
'+
                            '
'+
                                '<input type="checkbox" ng-model="parent.isOpenValue" ng-click="checked(parent.name)" >'+
                            '
'+
                         '
'+
                        '
'+
                            '{{children.name}}'+
                        '
'
                    '
'+
                 '
'+

             '
';
  return {
      restrict: 'E',
      replace: true,
      scope: {},
      controller: controller,
      template: template,
      transclude: true,
      link: function(scope, element, attrs, transclude) {
                scope.printParentschecked = function(ocw){
                    // print the checked parents... I can do it!
                }
                scope.filterType = function(type) {
                    //it works, it checks the value selected in the drop down and the type of the parent
                    // if they match they are shown
                if (types === 1 && type === 1) {
                    return true;
                }
                ....

          }
      }
  };
});

P.S. probably the real issue is that I do not really understand angular directives :(

A: Try this:
  function uncheckAll() {
              angular.forEach(ocw.parents,function(parent,key){
                       parent.isOpenValue=false;
                      }
            }


text:
Q: How to send an entity in JavaScript? How to send a StringEntity like java HttpRequest in JavaScript.i know in java but how to send in java script.

A: Neither JavaScript not HTTP have any concept of a StringEntity.
Googling for it suggests that StringEntity is a Java object which is a string with some extra methods on it.
Have your JavaScript send text to the server with XMLHttpRequest (or JSONP) as you would for any other Ajax request. Turn that text into a StringEntity object in your server side code.


text:
Q: Trying to run code in IOKE shell results in error? When I try to execute code in the IOKE shell it crashes.
 >ioke
 iik> "Hello World" println
Exception in thread "main" java.lang.NullPointerException
            at ioke.lang.IokeIO$2.activate(IokeIO.java:129)
            at ioke.lang.TypeCheckingNativeMethod.activate(TypeCheckingNativeMethod.java:50)
            at ioke.lang.IokeObject.activate(IokeObject.java:1053)
            at ioke.lang.IokeObject.getOrActivate(IokeObject.java:1038)
            at ioke.lang.IokeObject.getOrActivate(IokeObject.java:514)
            at ioke.lang.IokeObject.perform(IokeObject.java:659)
            at ioke.lang.IokeObject.perform(IokeObject.java:592)
            at ioke.lang.IokeObject.perform(IokeObject.java:522)
            at ioke.lang.Message.sendTo(Message.java:999)
            at ioke.lang.Message.evaluateCompleteWithoutExplicitReceiver(Message.java:1145)
            at ioke.lang.Message.getEvaluatedArgument(Message.java:979)
            at ioke.lang.Message.getEvaluatedArgument(Message.java:983)
            at ioke.lang.FlowControlBehavior$9.activate(FlowControlBehavior.java:379)
            at ioke.lang.IokeObject.activate(IokeObject.java:1053)
            at ioke.lang.IokeObject.getOrActivate(IokeObject.java:1038)
            at ioke.lang.IokeObject.getOrActivate(IokeObject.java:514)
            at ioke.lang.IokeObject.perform(IokeObject.java:659)
            at ioke.lang.IokeObject.perform(IokeObject.java:592)
            at ioke.lang.IokeObject.perform(IokeObject.java:522)
            at ioke.lang.Locals$1.activate(Locals.java:63)
            at ioke.lang.IokeObject.activate(IokeObject.java:1053)
            at ioke.lang.IokeObject.getOrActivate(IokeObject.java:1038)
            at ioke.lang.IokeObject.getOrActivate(IokeObject.java:514)
            at ioke.lang.IokeObject.perform(IokeObject.java:659)
            at ioke.lang.IokeObject.perform(IokeObject.java:592)
            at ioke.lang.IokeObject.perform(IokeObject.java:522)
            at ioke.lang.Message.sendTo(Message.java:999)
            at ioke.lang.Message.evaluateCompleteWith(Message.java:1093)
            at ioke.lang.LexicalBlock.activate(LexicalBlock.java:198)
            at ioke.lang.IokeObject.activate(IokeObject.java:1053)
            at ioke.lang.LexicalBlock$2.activate(LexicalBlock.java:86)
            at ioke.lang.IokeObject.activate(IokeObject.java:1053)
            at ioke.lang.IokeObject.getOrActivate(IokeObject.java:1038)
            at ioke.lang.IokeObject.getOrActivate(IokeObject.java:514)
            at ioke.lang.IokeObject.perform(IokeObject.java:659)
            at ioke.lang.IokeObject.perform(IokeObject.java:592)
            at ioke.lang.IokeObject.perform(IokeObject.java:522)
            at ioke.lang.Message.sendTo(Message.java:1011)
            at ioke.lang.FileSystem$7.activate(FileSystem.java:308)
            at ioke.lang.IokeObject.activate(IokeObject.java:1053)
            at ioke.lang.IokeObject.getOrActivate(IokeObject.java:1038)
            at ioke.lang.IokeObject.getOrActivate(IokeObject.java:514)
            at ioke.lang.IokeObject.perform(IokeObject.java:659)
            at ioke.lang.IokeObject.perform(IokeObject.java:592)
            at ioke.lang.IokeObject.perform(IokeObject.java:522)
            at ioke.lang.Message.sendTo(Message.java:999)
            at ioke.lang.Message.evaluateCompleteWithoutExplicitReceiver(Message.java:1145)
            at ioke.lang.ConditionsBehavior$4.activate(ConditionsBehavior.java:342)
            at ioke.lang.IokeObject.activate(IokeObject.java:1053)
            at ioke.lang.IokeObject.getOrActivate(IokeObject.java:1038)
            at ioke.lang.IokeObject.getOrActivate(IokeObject.java:514)
            at ioke.lang.IokeObject.perform(IokeObject.java:659)
            at ioke.lang.IokeObject.perform(IokeObject.java:592)
            at ioke.lang.IokeObject.perform(IokeObject.java:522)
            at ioke.lang.Locals$1.activate(Locals.java:63)
            at ioke.lang.IokeObject.activate(IokeObject.java:1053)
            at ioke.lang.IokeObject.getOrActivate(IokeObject.java:1038)
            at ioke.lang.IokeObject.getOrActivate(IokeObject.java:514)
            at ioke.lang.IokeObject.perform(IokeObject.java:659)
            at ioke.lang.IokeObject.perform(IokeObject.java:592)
            at ioke.lang.IokeObject.perform(IokeObject.java:522)
            at ioke.lang.Message.sendTo(Message.java:999)
            at ioke.lang.Message.evaluateCompleteWithoutExplicitReceiver(Message.java:1145)
            at ioke.lang.Message.getEvaluatedArgument(Message.java:979)
            at ioke.lang.Message.getEvaluatedArgument(Message.java:983)
            at ioke.lang.FlowControlBehavior$7.activate(FlowControlBehavior.java:298)
            at ioke.lang.IokeObject.activate(IokeObject.java:1053)
            at ioke.lang.IokeObject.getOrActivate(IokeObject.java:1038)
            at ioke.lang.IokeObject.getOrActivate(IokeObject.java:514)
            at ioke.lang.IokeObject.perform(IokeObject.java:659)
            at ioke.lang.IokeObject.perform(IokeObject.java:592)
            at ioke.lang.IokeObject.perform(IokeObject.java:522)
            at ioke.lang.Locals$1.activate(Locals.java:63)
            at ioke.lang.IokeObject.activate(IokeObject.java:1053)
            at ioke.lang.IokeObject.getOrActivate(IokeObject.java:1038)
            at ioke.lang.IokeObject.getOrActivate(IokeObject.java:514)
            at ioke.lang.IokeObject.perform(IokeObject.java:659)
            at ioke.lang.IokeObject.perform(IokeObject.java:592)
            at ioke.lang.IokeObject.perform(IokeObject.java:522)
            at ioke.lang.Message.sendTo(Message.java:999)
            at ioke.lang.Message.evaluateCompleteWithoutExplicitReceiver(Message.java:1145)
            at ioke.lang.ConditionsBehavior$4.activate(ConditionsBehavior.java:342)
            at ioke.lang.IokeObject.activate(IokeObject.java:1053)
            at ioke.lang.IokeObject.getOrActivate(IokeObject.java:1038)
            at ioke.lang.IokeObject.getOrActivate(IokeObject.java:514)
            at ioke.lang.IokeObject.perform(IokeObject.java:659)
            at ioke.lang.IokeObject.perform(IokeObject.java:592)
            at ioke.lang.IokeObject.perform(IokeObject.java:522)
            at ioke.lang.Locals$1.activate(Locals.java:63)
            at ioke.lang.IokeObject.activate(IokeObject.java:1053)
            at ioke.lang.IokeObject.getOrActivate(IokeObject.java:1038)
            at ioke.lang.IokeObject.getOrActivate(IokeObject.java:514)
            at ioke.lang.IokeObject.perform(IokeObject.java:659)
            at ioke.lang.IokeObject.perform(IokeObject.java:592)
            at ioke.lang.IokeObject.perform(IokeObject.java:522)
            at ioke.lang.Message.sendTo(Message.java:999)
            at ioke.lang.Message.evaluateCompleteWith(Message.java:1093)
            at ioke.lang.DefaultMethod.activate(DefaultMethod.java:283)
            at ioke.lang.IokeObject.activate(IokeObject.java:1053)
            at ioke.lang.IokeObject.getOrActivate(IokeObject.java:1038)
            at ioke.lang.IokeObject.getOrActivate(IokeObject.java:514)
            at ioke.lang.IokeObject.perform(IokeObject.java:659)
            at ioke.lang.IokeObject.perform(IokeObject.java:592)
            at ioke.lang.IokeObject.perform(IokeObject.java:522)
            at ioke.lang.Message.sendTo(Message.java:999)
            at ioke.lang.Message.evaluateComplete(Message.java:1066)
            at ioke.lang.Runtime.evaluateString(Runtime.java:525)
            at ioke.lang.Main.main(M

ain.java:149)

What is causing this to error? I'm using Windows 10, my IOKE_HOME and JAVA_HOME env variables are set (Otherwise the REPL wouldn't be invoked in the first place). Any help will be appreciated.

A: I suspect that this has to do with Ioke attempting to use some Java API to retrieve the user's home directory. I found that the problem reproduced on Linux when running Ioke as any user who did not have a home directory, despite the HOME environment variable being set. I was able to work around the problem by setting the JAVA_OPTS environment variable:
$ JAVA_OPTS="-Duser.home=$PWD" ioke

Note that similar problems occur with other Java-based programming languages such Kotlin, and the same workaround can sometimes be applied. Clearly, somebody made a very poor design decision deep down in the Java APIs.
Note that Ioke has been completely abandoned since 2011, and is unlikely to receive any updates or support in the future.


text:
Q: Prevent Flash Player fault in WebView, as is done by the Android Browser I'm loading .swf files into a WebView directly using webView.loadUrl("http://whatever.com/file.swf");. It works perfectly in the vast majority of cases.
When loading a few specific swf files on certain devices, though, shortly after the Flash media begins to be displayed, my app closes with a Signal 11 fault caused by the Flash Player plugin. Example LogCat dump here. No Exception is thrown. The same thing happens if I load those files into the xScope browser.
When loading them into Dolphin Browser or the default Android Browser, however, shortly after the media begins to be displayed, the following is printed to LogCat:
05-31 18:13:15.498: DEBUG/FONT(9183): WARNING: **************************** Detect FLEngine error 1 ****************************
05-31 18:13:15.558: DEBUG/(9183): ---------------------------------------------------------------> call AudioTrack stop()

and an error icon is displayed on-screen:

No SIGSEGV fault occurs, and the browser is not terminated.

Does anyone know how I could do the exact same thing? Prevent the Flash Player plugin from causing the SIGSEGV fault, and simply handle the error myself, without the app being terminated? Any help would be greatly appreciated.

A: I see in your logcat output that the crash occurs in libflashlite.so. You should be using real Flash 10.3 or higher, not Flash Lite. The Flash player is available on the Android Market now.


text:
Q: Portable USB harddisk regardless in Windows and Ubuntu / Linux environment I am doing web development mostly in Ubuntu. Sometimes I need to go into Windows to do other administrative work. Now, I am ignorant about file systems. I cannot tell the difference between NTFS and FAT32. My eyes just glaze over the Wikipedia articles.
All I know is I have been using this 320 GB portable USB harddisk to save files when I am in Ubuntu and when I am in Windows.
Now I got a situation where sometimes the Windows 7 system cannot detect the harddisk. In Ubuntu, I cannot mount the harddisk. I suspect the NTFS data inside is no longer consistent. I believe it has to do with the file system issue. Or my harddisk is coming apart.
How do I make it easy to backup my files in a portable USB harddisk regardless in Ubuntu or Windows?
That would mean I can go from

*

*from Linux/Ubuntu to a portable harddisk read/write files

*from Windows 7 to a portable harddisk read/write files

the same files.
Update
I realise that the issue is due to bad sectors in the hard disk drive. Now I am trying to recover the files. I want to prevent this from happening again since I still need to use Ubuntu and Windows. And yes, the files can be larger than 4 GB, so FAT32 is out.
By the way, I bought a new hard disk drive.

A: Unless you plan on having files larger than 4GB in your web development files... I would recommend FAT32.
While Linux supports NTFS, I understand the implementation is reverse-engineered... even if they people find it to be "quite reliable" there is still a huge margin for issues for the filesystem to fail.

A: Everyone else is choosing between FAT32 and NTFS, but there is one more alternative: exFAT.
exFAT works any Windows version newer than XP and works on Ubuntu Linux with the "exfat-fuse" package (run "sudo apt-get install exfat-fuse" in a terminal). I am not sure when support first came for OS X, but I believe it works on Macs
I am also not 100% sure of how reliable exFAT is on Linux but I am reasonably sure that your files will not disappear or fail to mount one day. This is the next topic I would research if I was in your position.
exFAT does not have the same limitations of FAT32 for max file size (4GB). It is also another proprietary filesystem from Microsoft, however, so it may not be implemented perfectly on Linux. My advice is to also set up a way to back up your files (maybe to Dropbox, for example)
For any further reading on exFAT, see here: https://en.wikipedia.org/wiki/ExFAT

A: If the file size limitation of FAT32 is an issue, you could switch it around and install Ext2/3 support in Windows (http://www.fs-driver.org/). Then you could format the USB drive in Ubuntu to use either the Ext2 or Ext3 filesystem native to Linux while still being able to access it in Windows (assuming the driver linked or a similar one is installed). The drawback with this method is that the drive would be inaccessible on any non-Linux operating system without those drivers.


text:
Q: How to I set document ID or ID to PDF file via terminal? Hello I am writing a bash script, this script must give ID to pdf file. How do I solve the this, is there a way?
Example as using bash shell.
Document ID is:
$ exiftool example.pdf | grep 'Document ID'
Document ID        : uuid:d037451d-240e-4d82-ba6d-92390b1d2962

For example:
$ pdftool --setDocID "newID" example.pdf

A: exiftool -DocumentID="uuid:$newID" example.pdf

see examples on man exiftool


text:
Q: java.lang.NoSuchMethodError: org.springframework.beans.factory.support.CglibSubclassingInstantiationStrategy I have upgraded my Spring framework from 3.1.0 to 3.2.18.
Then I am getting below exception.

org.springframework.beans.factory.BeanCreationException: Error creating bean
  with name 'myService' defined in class path resource
  [spring-biproxy-context.xml]: Instantiation of bean failed; nested
  exception is java.lang.NoSuchMethodError: org.springframework.beans.factory.support.CglibSubclassingInstantiationStrategy$CglibSubclassCreator$LookupOverrideMethodInterceptor: method (Lorg/springframework/beans/factory/support/CglibSubclassingInstantiationStrategy$CglibSubclassCreator;Lorg/springframework/beans/factory/support/CglibSubclassingInstantiationStrategy$1;)V not found

I did not make any code changes. Only altered the spring version.
Looks like spring framework removed class called LookupOverrideMethodInterceptor in 3.2.18 But in runtime, spring is looking for this class.
Spring_bean_jar_diff
pom.xml
<dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</artifactId>
        <version>3.2.18</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-beans</artifactId>
        <version>3.2.18</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
        <version>3.2.18</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aop</artifactId>
        <version>3.2.18</version>
      <scope>compile</scope>
    </dependency>


text:
Q: Maintenance Plan fails but the query it generates Runs I have an SQL Server 2005 Enterprise Edition whose Maintenance plan fails constantly with the error:
backup MYSERVER (MYSERVER)
Backup Database on MYSERVER
Databases that have a compatibility level of 70 (SQL Server version 7.0) will be skipped.
Databases: All databases
Type: Differential
Append existing
Task start: 2011-10-18T00:10:09.
Task end: 2011-10-18T00:10:09.
Failed:(-1073548784) Executing the query "BACKUP DATABASE [model] TO  DISK = N'\\myNetworkDrive\\opovo\\BackupSQL\\MYSERVER\\model\\model_backup_201110180010.bkp' WITH  DIFFERENTIAL ,  RETAINDAYS = 13, NOFORMAT, NOINIT,  NAME = N'model_backup_20111018001008', SKIP, REWIND, NOUNLOAD,  STATS = 10
" failed with the following error: "Cannot open backup device 'C:\\Program Files\\Microsoft SQL Server\\MSSQL.1\\MSSQL\\Backup\\Arca\\opovo\\BackupSQL\\MYSERVER\\model\\model_backup_201110180010.bkp'. Operating system error 3(The system cannot find the path specified.).
BACKUP DATABASE is terminating abnormally.". Possible failure reasons: Problems with the query, "ResultSet" property not set correctly, parameters not set correctly, or connection not established correctly.

But the query that this maintenance plan generates:
BACKUP DATABASE [model] TO  DISK = N'\\myNetworkDrive\\opovo\\BackupSQL\\MYSERVER\\model\\model_backup_201110180010.bkp' WITH  DIFFERENTIAL ,  RETAINDAYS = 13, NOFORMAT, NOINIT,  NAME = N'model_backup_20111018001008', SKIP, REWIND, NOUNLOAD,  STATS = 10

runs normally.
even stranger is the error message: "Cannot open backup device 'C:\Program Files(...)" maybe there's a difference between how SSIS and SSMS/SS Agent handles the backslash?
The user for SQL Agent and the user with which I ran this query successfully in all these cases was a domain user "ABC.MyDomainUser" that has permissions to access the network mapping \myNetworkDrive. I even used MSTSC to log in the server that runs SQL Server and ran the query locally, it runs fine, only fails when in the maintenance plan.
Is this a bug? What am I missing here? What is the elegant way to backup to a network location?
Thanks in advance,
Lynx Kepler

A: The SQL Server Agent account has both share and local security permissions right?
I would also ensure that you have given the SQL Server Agent appropriate network permissions -- it really sounds like a permission issue.


text:
Q: Simple rectangle pattern with graphics in java So basically when I try to increase the number of the variable which increases the number of rectangles, it starts to overlap. At the moment when i increase the variable to 2, the first column duplicates on top of the second and the second columns duplicates to the third spot where the first column duplicate should be. I'm sure it has an easy fix. I have a feeling that i need to add something to the coordinates but i'm not sure what exactly. Heres the code
public class Pattern extends JComponent implements ActionListener{

JPanel panel = new JPanel(new GridLayout(4, 4));
int width = 100;
int height = 100;
int number = 1;
JTextField tf = new JTextField(String.valueOf(width));
JTextField kl = new JTextField(String.valueOf(height));
JColorChooser color = new JColorChooser();
JCheckBox selection = new JCheckBox();
JTextField howMany =new JTextField(String.valueOf(number));

public Pattern(){

    setLayout(new BorderLayout());

    paneel.add(new Label("Width:"));
    paneel.add(tf);
    paneel.add(new Label("Height:"));
    paneel.add(kl);
    paneel.add(new Label("Filled in:"));
    paneel.add(selection);
    paneel.add(new Label("Number:"));
    paneel.add(howMany);

    tf.addActionListener(this);
    kl.addActionListener(this);
    selection.addActionListener(this);
    howMany.addActionListener(this);

    add(panel, BorderLayout.SOUTH);
    add(color, BorderLayout.EAST);
    color.setPreviewPanel(new JPanel());

}

public void paintComponent(Graphics g){
    g.setColor(color.getColor());
    for(int i=0; i<number; i++){
        if(selection.isSelected()){

            g.fillRect((width)*i, 10, width, height);
            g.drawRect((width)*i, 110, width, height);
            g.drawRect((width)*i+width, 10, width, height);
            g.fillRect((width)*i+width, 110, width, height);
        } else {
            g.drawRect((width)*i, 10, width, height);
            g.fillRect((width)*i, 110, width, height);
            g.fillRect((width)*i+width, 10, width, height);
            g.drawRect((width)*i+width, 110, width, height);
        }
    }

}

public static void main(String[] args){
    JFrame window = new JFrame("Window");
    window.setSize(1000, 1000);
    window.getContentPane().add(new Pattern());
    window.setVisible(true);
    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

}

@Override
public void actionPerformed(ActionEvent e) {
    System.out.println(tf.getText());
    System.out.println(kl.getText());
    width = Integer.parseInt(tf.getText());
    height = Integer.parseInt(kl.getText());
    number =Integer.parseInt(howMany.getText());

    repaint();
}

}


text:
Q: Paypal Sandbox Business Account not credited and Buyer is not debited I made a DoExpressCheckoutPayment call with following detail and success.[Of course the call is made after the successful SetExpressCheckout call]
METHOD=DoExpressCheckoutPayment&
VERSION=93&
PWD=MyPassword&
USER=User&
SIGNATURE=Signature&
PAYMENTREQUEST_0_PAYMENTACTION=Order&
PAYMENTREQUEST_0_AMT=85.0&
PAYMENTREQUEST_0_CURRENCYCODE=USD&
IPADDRESS=localhost&
BUTTONSOURCE=PP-ECWizard

The Response details from above call
PAYMENTINFO_0_REASONCODE=None, PAYMENTINFO_0_TAXAMT=0.00, PAYMENTINFO_0_ERRORCODE=0, PAYMENTINFO_0_SECUREMERCHANTACCOUNTID=AHYPGLSVNYNYC, BUILD=6118442, PAYMENTINFO_0_TRANSACTIONTYPE=expresscheckout, PAYMENTINFO_0_ORDERTIME=2013-05-30T11:26:49Z, PAYMENTINFO_0_PROTECTIONELIGIBILITY=None, CORRELATIONID=c7061e7e201b4, SUCCESSPAGEREDIRECTREQUESTED=false, INSURANCEOPTIONSELECTED=false, PAYMENTINFO_0_CURRENCYCODE=USD, PAYMENTINFO_0_PAYMENTSTATUS=Pending, PAYMENTINFO_0_AMT=85.00, PAYMENTINFO_0_TRANSACTIONID=O-3M746191252284215, PAYMENTINFO_0_ACK=Success, VERSION=93, PAYMENTINFO_0_PAYMENTTYPE=None, PAYMENTINFO_0_PENDINGREASON=order, ACK=Success, SHIPPINGOPTIONISDEFAULT=false, TIMESTAMP=2013-05-30T11:26:49Z, TOKEN=EC-9J328055AB342102B

(I have modified response and convert response into HashMap)
I have created two test accounts in Paypal Sandbox
One is Business Account and one is Personal Account.All has opening Balance of 5000 USD.
Everything works fine except one thing.
The buyer account shows the Order Detail as shown in following figure as Pending only and does not debit itself. the balance as same as it was the last.

The Merchant's account shows the order detail but same as the account is not credited and balance is not updated as shown in following figure.

Now if i look at the Sandbox notifications i can see some text for Buyer account only and not for Merchant's account as shown in following figure.

What i am missing here ?
Why the amount is not debited from buyer and credited to Merchant's ?
why the transaction status is Pending ?
I found 3 similar questions on SO match my problem and some of the questions on the internet , i tried all the solutions but could not success .
Payment Review is tuned off in My Sandbox Business Account.
If you need me any more detail from me please ask feel free to ask me.
Thanks

A: The reason that your transaction is showing pending is because you processed this as an order.  You can also see the pending reason in the response that you provided.
PAYMENTINFO_0_PENDINGREASON=order

You need to go back now and perform a transaction against the order to actually charge the buyer and this will move the funds from the buyer account to the seller account.  For example you can go back and perform an Authorization against the order using the DoAuthorization API and then once that is completed you can run the DoCapture API to complete the purchase.
If you are not wanting to process the transaction as an order initially, you can process it as a "Sale" rather than an "Order", and this will take the money up front when you complete the DoExpressCheckoutPayment API call.


text:
Q: BERT - Extract values from all layers i'm trying to get the "Word Embedding" from BERT.
I have already fine tuned the model for "Sentiment classification" and the model predict if a sentence is positive or negative.
But i need to extract values from all layers to get the featurized representation.
i have tried something like this
all_layers = model.get_all_encoder_layers()
but doesn't works
# Compute # train and warmup steps from batch size
num_train_steps = int(len(train_features) / BATCH_SIZE * NUM_TRAIN_EPOCHS)
num_warmup_steps = int(num_train_steps * WARMUP_PROPORTION)

# Specify outpit directory and number of checkpoint steps to save
run_config = tf.estimator.RunConfig(
    model_dir=OUTPUT_DIR,
    save_summary_steps=SAVE_SUMMARY_STEPS,
    save_checkpoints_steps=SAVE_CHECKPOINTS_STEPS)

model_fn = model_fn_builder(
    num_labels=len(label_list),
    learning_rate=LEARNING_RATE,
    num_train_steps=num_train_steps,
    num_warmup_steps=num_warmup_steps)

estimator = tf.estimator.Estimator(
    model_fn=model_fn,
    config=run_config,
    params={"batch_size": BATCH_SIZE})

# Create an input function for training. drop_remainder = True for TPUs.
train_input_fn = bert.run_classifier.input_fn_builder(
    features=train_features,
    seq_length=MAX_SEQ_LENGTH,
    is_training=True,
    drop_remainder=False)

i have to change the model_fn to get values from all layers of BERT?


text:
Q: Is there a way to get a React component's internal values when I click a button on the parent? Suppose I have a component like this -
const MyForm = ({ formId }) => (

      <input type="text" placeholder="Full name"></input>
      <input type="text" placeholder="Email"></input>

)

export default MyForm;

And then I have my App.js like so -
import React from "react";
import MyForm from "./MyForm";

const App = () => (

      <MyForm formId="formOne"></MyForm>
      <MyForm formId="formTwo"></MyForm>
      <button onClick={
         () => {
            // Here, when the user clicks the button,
            // I want to get values of both the textboxes,
            // from both the component instances
         }
      }>Submit</button>

)

export default App;

So basically, what I want is - when the button is clicked, I want to be able to retrieve the values of the textboxes. One way to do this is to raise an event from inside MyForm.js so that every text change is bubbled up to the parent via a callback function prop, but that feels too cumbersome, especially if the form has a lot of fields. Is there any simple or direct way to do this? Do I need to involve global state management tools like Redux?

A: State inside a component is specific only to that component, the parent , children or sibling of a component have no idea of the state. The only way to communicate the value from one component to another component is via props . In your case, what we need is a state to reside at the App which can then be passed as a prop to both the MyForm Components.
App.js
const [ formState, setFormState ] = useState({ formOne: {fullName: '', Email: ''}, formTwo: '' })

const updateFormValues = (formId, key, value) => {
   const stateCopy = JSON.parse(JSON.stringify(formState));
   const formToUpdate = stateCopy[formId];
   formToUpdate[key] = value;
   setFormState(stateCopy)
}

<MyForm formId="formOne" values={formState.formOne} updateFormValues={updateFormValues}></MyForm>
<MyForm formId="formTwo" values={formState.formTwo} updateFormValues={updateFormValues}></MyForm>

MyForm.js
const MyForm = ({ formId, values, updateFormValues }) => {
     const onInputChange = (e, key) => {
        updateFormValues(formId, key, e.target.value)
     }

return(

          <input type="text" onChange={(e) => onInputChange(e, 'fullName'} value={values.fullName} placeholder="Full name"></input>
          <input type="text" onChange={(e) => onInputChange(e, 'email'} value={values.email} placeholder="Email"></input>

    )}

    export default MyForm;

A: To have access to data inside children components you need to lift the state to the parent component.
One-way data flow

Identify every component that renders something based on that state.
Find a common owner component (a single component above all the components that need the state in the hierarchy).
Either the common owner or another component higher up in the hierarchy should own the state.
If you can't find a component where it makes sense to own the state, create a new component solely for holding the state and add it somewhere in the hierarchy above the common owner component.

One way to do this:
import React, { useState } from "react";

function MyForm(props) {
const { handleChange, values } = props;
return (

        Your name
        <input
            type="text"
            placeholder="Full name"
            onChange={handleChange}
            value={values.name}
            id="name"
            name="name"
        />
        Your email
        <input
            type="email"
            placeholder="Email"
            onChange={handleChange}
            value={values.email}
            id="email"
            name="email"
        />

        );
   }

function App() {
const [values, setValues] = useState({ name: "", email: "" });

const handleChange = (event) => {
    const updatedForm = { ...values, [event.target.name]: event.target.value };
    setValues(updatedForm);
};

return (

        <MyForm
            formId="formOne"
            values={values}
            handleChange={handleChange}
        ></MyForm>

        <button
            onClick={() => {
                console.log(values);
            }}
        >
            Submit
        </button>

);
}

export default App;


text:
Q: url parameters in Command Line i am trying to make a pdf file with wkhtmltopdf when i pass url www.example.com pdf is generating or www.example.com?id=1
but when i try to put another parameter command execution is not working
www.example.com?id=1&type=u

shell_exec("c:\pdf\wkhtmltopdf.exe
  http://localhost/test/index.php?id=1&typee=abc
  test.pdf ");

i try to use it via command line to but its not working there also
thanks for help

A: The & is causing your command to fail as it has special meaning in shell. Use escapeshellarg() to escape those characters first.

A: Use escapeshellarg() to escape parameters before passing them to the command line.
This is also mandatory when passing external data (e.g. user input) as parameters.


text:
Q: Multi-photo upload to album and wall story I'm confident about posting multiple photos to a fan page album through a common batch request with PHP, and I also know how to use che "no_story" command to hide the wall posts showing each image just uploaded. What I need to know is if it's possible to show an unique wall post on the fan page showing the whole upload, like the standard Facebook behavior when you upload more pictures using the web interface, and not one post for each photos.

A: This is the closest I have got:
$attachment = array
(
'access_token'=>$fanPageAccessToken,
'object_id' => $AlbumId,
'message' => $AlbumDesc,
'link' =>$AlbumLink
);
$result = $facebook->api($fanPageId.'/links/','post',$attachment);
}

I get the variables by querying the albums associated with the fanpage:
$fanPageAlbums = $facebook->api($fanPageId . '/albums/');
foreach ($this->fanPageAlbums['data'] as $fanPageAlbum) {

if ($albumId == $fanPageAlbum['id']) {
   $albumLink = $fanPageAlbum['link'];
   $albumDesc = $fanPageAlbum['description'];
   break;
  }
 }

The key thing is your are posting to the links part of the graph, not the feed.
This works in that it will produce one big picture and three thumbs below it, as you would expect. However, it doesn't appear on the feeds of friends properly.
I've been struggling with this for ages, and the above is the closest I have got to mimicing exactly the facebook behavior. If you get any further please let me know!


text:
Q: Antialiasing of Curves by Discrete Pre-filtering I'm looking to implement the bezier curve algorithm described in the paper "Antialiasing of Curves by Discrete Pre-filtering" by A.E. Fabris and A.R. Forrest. However I'm missing a core piece of the puzzle: the point containment algorithm for curves by Corthout and Pol. It's outlined in the book Raster Imaging and Digital Typography.
I could simply iterate over every pixel, calculate the shortest distance to the bezier, and use that to calculate the effect of the brush. However as mentioned in the paper it's an inefficient approach.
Is there an outline or pseudo code for the point containment algorithm (or equivalent) that would do the same thing?

A: I'm going to answer my own question seeing that I've figured it out. Turns out point containment isn't needed, and was already outlined in the paper.
Here's the implementation in python and wxwidgets, rendering a few curves using the box brush.
Sadly it's too slow for practical use, even after rewriting it in C and making several optimisations. The best I could get it was about 30ms per bezier, and rendering a picture of 100 curves took 3 seconds. Most other vector applications tend to use path based bezier rendering algorithms which is what I'll be exploring now.
#!/usr/bin/python
# test15.py

import wx
import math
import cProfile

class Brush(object):
    def __init__(self, size):
        self._brushsize = size
        self.__halfbrush = self._brushsize / 2
    # returns true if inside or touching box
    def insidebox(self, box):
        minp = box[0]
        maxp = box[1]
        if maxp.x < -self.__halfbrush:
            return False
        if minp.x > self.__halfbrush:
            return False
        if maxp.y < -self.__halfbrush:
            return False
        if minp.y > self.__halfbrush:
            return False
        return True

    def at(self, p):
        px = p.x * p.x # 0.027
        py = p.y * p.y
        d = math.sqrt(px + py)
        return  d < self.__halfbrush

    def getSize(self):
        return self._brushsize

class BezierPoint(object):
    SCALEFACTOR = 4 # we divide each pixel into 4x4 matrix

    @classmethod
    def newRealPoint(nbs, x,y):
        x=int(x*BezierPoint.SCALEFACTOR)
        y=int(y*BezierPoint.SCALEFACTOR)
        return BezierPoint(x,y)

    def __init__(self,x,y):
        self.x=int(x)
        self.y=int(y)

    def __str__(self):
        return  self.x+ 'x' + self.y

#recalls = 0

class QuadBezier(object): # cubic bezier
    COVERED = 0x01
    NOT_COVERED = 0x02

    @classmethod
    def newRealPoint(nbs, x1,y1,x2,y2,x3,y3,x4,y4):
        b = QuadBezier(x1,y1,x2,y2,x3,y3,x4,y4)
        b.p1 = BezierPoint.newRealPoint( x1, y1)
        b.p2 = BezierPoint.newRealPoint( x2, y2)
        b.p3 = BezierPoint.newRealPoint( x3, y3)
        b.p4 = BezierPoint.newRealPoint( x4, y4)
        b._minx = min(b.p1.x,b.p2.x,b.p3.x,b.p4.x)
        b._maxx = max(b.p1.x,b.p2.x,b.p3.x,b.p4.x)
        b._miny = min(b.p1.y,b.p2.y,b.p3.y,b.p4.y)
        b._maxy = max(b.p1.y,b.p2.y,b.p3.y,b.p4.y)
        return b

    def __init__(self,x1,y1,x2,y2,x3,y3,x4,y4):
        self.p1 = BezierPoint(x1,y1)
        self.p2 = BezierPoint(x2,y2)
        self.p3 = BezierPoint(x3,y3)
        self.p4 = BezierPoint(x4,y4)
        self._minx = min(x1,x2,x3,x4)
        self._maxx = max(x1,x2,x3,x4)
        self._miny = min(y1,y2,y3,y4)
        self._maxy = max(y1,y2,y3,y4)

    def __str__(self):
        s = 'p1 = ' + str(self.p1.x) +'x'+ str(self.p1.y) +' p2 = '+str(self.p2.x) +'x'+str(self.p2.y)
        s = s + ' p3 = ' + str(self.p3.x) +'x'+ str(self.p3.y) +' p4 = '+str(self.p4.x) +'x'+str(self.p4.y)
        return  s

    def subdivide(self, left=True):
        # http://antigrain.com/research/adaptive_bezier/
        # according to the paper, we control vertices need to be performed at
        # higher precision than the discrete space will allow to for any accuracy loss
        x1 = self.p1.x << 2
        x2 = self.p2.x << 2
        x3 = self.p3.x << 2
        x4 = self.p4.x << 2
        y1 = self.p1.y << 2
        y2 = self.p2.y << 2
        y3 = self.p3.y << 2
        y4 = self.p4.y << 2
        x12   = (x1 + x2) >> 1
        y12   = (y1 + y2) >> 1
        x23   = (x2 + x3) >> 1
        y23   = (y2 + y3) >> 1
        x34   = (x3 + x4) >> 1
        y34   = (y3 + y4) >> 1
        x123  = (x12 + x23) >> 1
        y123  = (y12 + y23) >> 1
        x234  = (x23 + x34) >> 1
        y234  = (y23 + y34) >> 1
        x1234 = (x123 + x234) >> 1
        y1234 = (y123 + y234) >> 1

        if left:
            return QuadBezier(x1 >> 2, y1 >> 2, x12 >> 2, y12 >> 2, x123 >> 2, y123 >> 2, x1234 >> 2, y1234 >> 2)
        return QuadBezier(x1234 >> 2, y1234 >> 2, x234 >> 2, y234 >> 2, x34 >> 2, y34 >> 2, x4 >> 2, y4 >> 2)

    def getboundingbox(self):
        return BezierPoint(self._minx,self._miny), BezierPoint(self._maxx,self._maxy)

    def area (self):
        m1,m2 = self.getboundingbox()
        return m2.x-m1.x, m2.y-m1.y

    def minus (self, p):
        px = p.x
        py = p.y
        return QuadBezier(self.p1.x - px, self.p1.y - py,
                          self.p2.x - px, self.p2.y - py,
                          self.p3.x - px, self.p3.y - py,
                          self.p4.x - px, self.p4.y - py)

    def draw(self, img,pd, stackofbrushes):
        mmin,mmax = self.getboundingbox()
        numberofbrushes = len(stackofbrushes)
        largestbrushsize = stackofbrushes[numberofbrushes-1].getSize()
        print 'largestbrushsize = ', largestbrushsize
        xstart,xend = int(math.floor(mmin.x/BezierPoint.SCALEFACTOR-largestbrushsize)), int(math.ceil(mmax.x/BezierPoint.SCALEFACTOR+largestbrushsize))
        ystart,yend = int(math.floor(mmin.y/BezierPoint.SCALEFACTOR-largestbrushsize)), int(math.ceil(mmax.y/BezierPoint.SCALEFACTOR+largestbrushsize))
        print (xend - xstart) * 4, (yend - ystart) * 4, ' total area = ', ((xend - xstart) * 4) * ((yend - ystart) * 4)
        # for each pixel in the image
        for x in xrange(xstart, xend):
            for y in xrange(ystart, yend):
                pixel = BezierPoint(x*BezierPoint.SCALEFACTOR+2,y*BezierPoint.SCALEFACTOR+2) # todo: fix me
                covered, height = self.antialisedDilate(stackofbrushes, pixel, numberofbrushes)
                if covered == QuadBezier.COVERED:
                    img.MoveTo(pd,x,y)
                    #print height
                    img.Set(41*height,41*height,41*height)

    def antialisedDilate(self, stackofbrushes, p, numberofbrushes):
        mstroke = self.minus(p)  # centre the stroke
        h = 0
        n = numberofbrushes - 1
        for i in range(n,-1,-1):
            if mstroke.stroke(stackofbrushes[i]) == QuadBezier.COVERED:
                h = i
            else:
                if h == 0:
                    return QuadBezier.NOT_COVERED, 0
                return QuadBezier.COVERED, h
        return QuadBezier.COVERED, h

    def baseCase(self):
        """ returns true if the curve is primitive, that is that the length of the curve is <= 1 of the discrete space selected
        """
        p1,p2 = self.getboundingbox()
        mx,my = p2.x-p1.x, p2.y-p1.y
        #print mx,my
        distance = 2
        if mx >= -distance and mx <= distance:
            if my > -distance and my <= distance:
                return True
        return False

    def stroke(self, b):
        """ http://pdf.aminer.org/000/593/297/antialiasing_of_curves_by_discrete_pre_filtering.pdf
        """
        # NotInDilatedBBox
        if not b.insidebox(self.getboundingbox()):
            return QuadBezier.NOT_COVERED
        if self.baseCase():
            return QuadBezier.NOT_COVERED
        if b.at(self.p1):
            return QuadBezier.COVERED
        if b.at(self.p4):
            return QuadBezier.COVERED

        left = self.subdivide(True)
        if (left.stroke(b)==QuadBezier.COVERED):
            return QuadBezier.COVERED
        right = self.subdivide(False)
        if (right.stroke(b)==QuadBezier.COVERED):
            return QuadBezier.COVERED

        return QuadBezier.NOT_COVERED

pd = None
pixels = None
def timer ():
    stackofbrushes = [Brush(6.0), Brush(7.0), Brush(9.0), Brush(11.0), Brush(13.0), Brush(15.0)] # largest last

    for i in xrange(6):
        yplus = i * 20
        bezier = QuadBezier.newRealPoint(40.0,50.0+yplus, 80.0,46.0+yplus, 120.0,46.0+yplus, 160.0,50.0+yplus)
        bezier.draw(pixels, pd, stackofbrushes)

class MyToolBar(wx.Frame):
    def __init__(self, parent, id, title):
        wx.Frame.__init__(self, parent, id, title, wx.DefaultPosition, wx.Size(700, 700))
        self.Centre()

        self.Bind(wx.EVT_TOOL, self.OnExit, id=4)
        bmp = wx.EmptyBitmap(700,700)
        # we're using the undocumented native pixel data because the memorydx object introduces artifacts on MacOS
        global pd
        global pixels

        pd = wx.NativePixelData(bmp, wx.Point(0,0), wx.Size(700,700))
        width,height = pd.GetWidth(), pd.GetHeight()
        pixels = pd.GetPixels()
        for x in xrange(width):
            for y in xrange(height):
                pixels.MoveTo(pd,x,y)
                pixels.Set(255,255,255)

        cProfile.run('timer()')

        wx.StaticBitmap(self, wx.ID_ANY, bmp)

    def OnExit(self, event):
        self.Close()

class MyApp(wx.App):
    def OnInit(self):
        frame = MyToolBar(None, -1, 'Antialiasing of Curves by Discrete Pre-filtering')
        frame.Show(True)
        return True

app = MyApp(0)
app.MainLoop()


text:
Q: With Entity Framework 4.1 Codefirst, how do you create unmapped fields in the poco classes? I have a set of classes as my domain objects.
I have a set of configuration files to map these objects (EntityTypeConfiguration<>).
When I add a property to any of the domain objects without mapping to a column, the dbcontext attempts to query for the column, ignoring the fact that it is not mapped.
I must be missing a setting either in the configuration code or the dbcontext code.  I do not want to add an attribute to the poco class (decorating the pocos tie them to a specific persistence implementation, which I wish to avoid).
On the call against the IQueryable to populate a ticket object, the call fails with the message:
Invalid column name 'NotInDatabase'.
public class Ticket
{
    public Ticket()
    {
    }

    public virtual int Id
    {
        get;
        set;
    }

    public virtual string Title
    {
        get;
        set;
    }

    public virtual string Description
    {
        get;
        set;
    }

    public string NotInDatabase
    {
        get;
        set;
    }
}

internal class TicketConfiguration : EntityTypeConfiguration<Ticket>
{
    public TicketConfiguration()
    {
        ToTable("ticket_table_name");

        HasKey(o => o.Id)
            .Property(o => o.Id)
            .HasColumnName("ticketId")
            .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity)
            .IsRequired();

        Property(o => o.Title).HasColumnName("TicketTitle");
        Property(o => o.Description).HasColumnName("TicketDescription");
    }
}

Note:
Please do not suggest using "Database First" or "Model First" for my situation.  I want to map poco objects to the database using the features of code first, even though I have an existing db structure.  I am comparing this to nhibernate and really want to stick to a similar structure (since Microsoft "adopted" fluent nhibernate's approach, it's pretty easy to compare apples to apples).
Thanks!

A: .Ignore should do the trick or by attribute it's called [NotMapped]


text:
Q: jquery chekbox selected Hi I'm having some problems with jquery checkbox selected. I want to do a task when the checkbox is selected. my code for this is
$(document).ready(function() {
        if ($('#chxGetText').is(':checked')) {
            alert("OK");
        }
    });

<input id="chxGetText" type="checkbox" />

But nothing happen when I check the checkbox. Any ideas?

A: You need to bind an event listener to the change event of the checkbox. Right now, you're only checking if the checkbox is checked when the page loads, i.e. once.
$(function() {
 $('#chxGetText').change(function() {
  if ($(this).is(':checked')) {
   alert('OK');
  } else {
   alert('Not OK');
  };
 }).trigger('change'); // trigger it on page load as well
});

Note that you should probably trigger the event on page load as well, in case the user refreshes the page after checking the checkbox (hence the .trigger('change') in my code).

A: You were not assigning an event to the element, try this:
$(document).ready(function() {
  $('#chxGetText').click(function(){
    if ($(this).is(':checked')) {
     alert("OK");
    }
  });
});

A: :checked is just a selector, it doesn't bind any event listeners. Do something like this:
$(document).ready(function() {
    $('#chxGetText').change( function (e) {
       if($(this).is(':checked')) {
          alert('Checked');
       }
       else {
          alert('Unchecked');
       }
    });
});

<input id="chxGetText" type="checkbox" />

A: You can use code like
jQuery("#chxGetText").click(function() {
    if ($(this).is(':checked')) {
        alert("#chxGetText is checked");
    }
    else {
        alert("#chxGetText is unchecked");
    }
});

A: You need to assign an event handler to the onclick event of the checkbox. Your current code only runs once, when the document is loaded and doesn't react to any state changes after that.
<input id="chxGetText" type="checkbox" />

function checkState(node) {
    if (node.checked) {
        alert("OK");
    }
}

$(document).ready(function() {
    $('#chxGetText').click(function() {
        // Bind checkState to click event
        checkState(this);
    }).each(function() {
        // Initial check on load
        checkState(this);
    });
});


text:
Q: Calling Code Activity Within Code Activity How do I execute a code activity from within a code activity?
public sealed class ApprovalRequired : CodeActivity
{
    EmailActivity ea = new EmailActivity() // this is a code activity
    ea.Sender = ...
    ea.Rec = ...
    ea.Subject = "Approved"
   // ea.Execute() -- there is no way to call the execute method..
}

A: The easiest approach would be to prepare a XAML-based activity that has a sequence activity with your ApprovalRequired activity somewhere in it. Something like this:

Edit: To actually have an 'inner' activity be executed from another activity, your ApprovalRequired class should inherit from the NativeActivity class first, and override the CacheMetadata method to let the workflow application know to expect a child activity will be executed. The ApprovalRequired activity would look like this:
namespace WCA.Scratch
{
    using System.Activities;

    public sealed class ApprovalRequired : NativeActivity
    {
        public ApprovalRequired()
        {
            this.Email = new Email();
        }

        public Email Email
        {
            get;
            set;
        }

        protected override void CacheMetadata(NativeActivityMetadata metadata)
        {
            metadata.AddImplementationChild(this.Email);
        }

        protected override void Execute(NativeActivityContext context)
        {
            // Some logic here...
            this.Email.Body = "My email body.";
            this.Email.From = "me@someplace.com";
            this.Email.To = "someone@someplace.com";
            this.Email.Subject = "Approval Request";
            context.ScheduleActivity(this.Email);
            // Some other logic here...
        }
    }
}

Keep in mind that you'll need to manually register any activity arguments or activity variables in the ApprovalRequired's CacheMetadata method as well.


text:
Q: Best strategy to correctly index complex join query This is the query running on MySQL 5.7 with INNODB:
SELECT SQL_CALC_FOUND_ROWS
    calendar.id_calendar AS calendar_id,
    calendar.event_datetime AS calendar_event_datetime
FROM
    users
    INNER JOIN calendar ON (users.login_enabled = 1 AND calendar.id_agente = users.id)
    LEFT  JOIN customers ON customers.id_customer = calendar.id_customer
    LEFT  JOIN ads ON ads.id = calendar.id_ads
WHERE
    calendar.hidden = 0
     AND calendar.id_agenzia = 5134 AND users.id IN (5134,6816,5155,6181,5154,8783,5172,5143,11360)
     AND eventi_custom_id IN (1,2,3,15,4,5,7,8,9,10,11,12,13,14,6)
    AND (calendar.commento LIKE '%figline%' OR customers.surname LIKE '%figline%' OR customers.name LIKE '%figline%' OR customers.company_name LIKE '%figline%' OR ads.agency_code LIKE '%figline%')
ORDER BY
    calendar.event_datetime DESC LIMIT 0,50

An explain shows me a very basic index usage even if I tried to create better ones according with MySQL index optimization tips found on Mysql official docs.
Biggest problem is indexing table Calendar which seems to use partially some index but gives me "using where" on explain's extra column.
I tried to create many index for table Calendar but they are always partially used.
id  select_type   table     type     possible_keys                                                                 key                          key_len  ref                                rows  filtered   Extra
1   SIMPLE        calendar  ref      id_agente-event_datetime,id_agenzia-event_datetime,id_                        id_agenzia-evento_datetime   5        const                              1     5.00       Using where
                                     id_agente-id_agenzia-hidden-event_datetime,id_agente-hidden-event_datetime,
                                     eventi_custom_id,id_agenzia,prova
1   SIMPLE        users     eq_ref   PRIMARY,login_enabled,id-logo_img,id                                          PRIMARY                      4        prossima-casa.calendar.id_agente   1     50.00      Using where
1   SIMPLE        customers eq_ref   PRIMARY                                                                       PRIMARY                      4        prossima-casa.calendar.id_customer 1     100.00
1   SIMPLE        ads       eq_ref   PRIMARY                                                                       PRIMARY                      4        prossima-casa.calendar.id_ads      1     100.00     Using where

Here's table defs:
CREATE TABLE `calendar` (
 `id_calendar` int(11) NOT NULL AUTO_INCREMENT,
 `parent_id_calendar` int(11) DEFAULT NULL,
 `id_ripetizione` varchar(32) DEFAULT NULL,
 `childs_count` enum('0','1','2','3') NOT NULL DEFAULT '0',
 `id_ads` int(11) DEFAULT NULL,
 `id_customer` int(11) DEFAULT NULL,
 `id_agente` int(11) NOT NULL,
 `id_agenzia` int(11) NOT NULL,
 `event_datetime` datetime NOT NULL,
 `event_length` time NOT NULL DEFAULT '00:15:00',
 `commento` text,
 `hidden` tinyint(3) unsigned NOT NULL DEFAULT '0',
 `eventi_custom_id` tinyint(2) NOT NULL DEFAULT '1',
 `event_in_out` tinyint(1) unsigned NOT NULL DEFAULT '0',
 `flag_in_evidenza` tinyint(1) unsigned NOT NULL DEFAULT '0',
 `flag_confirmed` tinyint(1) unsigned NOT NULL DEFAULT '0',
 `flag_confirmed_prop` tinyint(1) unsigned NOT NULL DEFAULT '0',
 `flag_eseguito` tinyint(1) unsigned NOT NULL DEFAULT '0',
 `flag_only_for_me` tinyint(1) unsigned NOT NULL DEFAULT '0',
 `google_id` varchar(255) DEFAULT NULL,
 `commento_pubblico` text',
 `flag_preview_pubblica` tinyint(1) unsigned NOT NULL DEFAULT '0',
 `creator_users_id` int(11) NOT NULL,
 `creator_time` datetime NOT NULL,
 `last_editor_time` datetime NOT NULL,
 `last_editor_user_id` int(11) DEFAULT '0',
 `last_editor_user_ip` varchar(30) DEFAULT NULL,
 `external_id_calendar` varchar(255) DEFAULT NULL,
 PRIMARY KEY (`id_calendar`),
 KEY `id_customer-event_datetime` (`id_customer`,`event_datetime`),
 KEY `id_agente-event_datetime` (`id_agente`,`event_datetime`),
 KEY `id_agenzia-event_datetime` (`id_agenzia`,`event_datetime`),
 KEY `id_agente-id_agenzia-hidden-event_datetime` (`id_agente`,`id_agenzia`,`hidden`,`event_datetime`),
 KEY `parent_id_calendar-hidden` (`parent_id_calendar`,`hidden`),
 KEY `id_agente-hidden-event_datetime` (`id_agente`,`hidden`,`event_datetime`,`flag_in_evidenza`,`creator_users_id`),
 KEY `eventi_custom_id` (`eventi_custom_id`),
 KEY `id_ads` (`id_ads`),
 KEY `event_datetime` (`event_datetime`),
 KEY `id_ripetizione` (`id_ripetizione`),
 KEY `external_id_calendar` (`external_id_calendar`),
 KEY `id_customer-hidden` (`id_customer`,`hidden`) USING BTREE,
 KEY `id_agenzia` (`id_agenzia`,`hidden`,`event_datetime`) USING BTREE,
 KEY `prova` (`id_agente`,`id_customer`,`id_ads`) USING BTREE,
 CONSTRAINT `calendar_ibfk_18` FOREIGN KEY (`id_customer`) REFERENCES `customers` (`id_customer`) ON DELETE CASCADE ON UPDATE CASCADE,
 CONSTRAINT `calendar_ibfk_19` FOREIGN KEY (`id_agente`) REFERENCES `users` (`id`) ON UPDATE CASCADE,
 CONSTRAINT `calendar_ibfk_20` FOREIGN KEY (`id_agenzia`) REFERENCES `users` (`id`) ON UPDATE CASCADE,
 CONSTRAINT `calendar_ibfk_5` FOREIGN KEY (`id_ads`) REFERENCES `ads` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=3977444 DEFAULT CHARSET=utf8

CREATE TABLE `customers` (
 `id_customer` int(11) NOT NULL AUTO_INCREMENT,
 `name` varchar(50) DEFAULT NULL,
 `surname` varchar(50) DEFAULT NULL,
 `email` varchar(100) DEFAULT NULL,
 `email2` varchar(100) DEFAULT NULL,
 `email_pec` varchar(100) DEFAULT NULL,
 `skype` varchar(100) DEFAULT NULL,
 `facebook` varchar(100) DEFAULT NULL,
 `linkedin` varchar(100) DEFAULT NULL,
 `tel` varchar(15) DEFAULT NULL,
 `tel2` varchar(20) DEFAULT NULL,
 `cell` varchar(20) DEFAULT NULL,
 `fax` varchar(20) DEFAULT NULL,
 `indirizzo` varchar(100) DEFAULT NULL,
 `civico` varchar(50) DEFAULT NULL,
 `cap` varchar(5) DEFAULT NULL,
 `latitude` double NOT NULL DEFAULT '0',
 `longitude` double NOT NULL DEFAULT '0',
 `ind_stati_id` smallint(3) unsigned DEFAULT '110',
 `ind_province_id` int(11) DEFAULT NULL,
 `ind_comuni_id` int(11) DEFAULT NULL,
 `ind_zone_id` int(11) DEFAULT NULL,
 `id_agente` int(11) NOT NULL,
 `id_agenzia` int(11) NOT NULL,
 `flag_storico` tinyint(1) unsigned NOT NULL DEFAULT '0',
 `deleted` tinyint(1) NOT NULL DEFAULT '0',
 `tipo_customer` enum('compra','vende','entrambi','costruttore','contatto','altro') NOT NULL DEFAULT 'altro',
 `rating` tinyint(1) unsigned NOT NULL DEFAULT '0',
 `privacy_flag` tinyint(1) unsigned NOT NULL DEFAULT '0',
 `note` text,
 `azienda_flag` tinyint(1) unsigned NOT NULL DEFAULT '0',
 `data_nascita` date DEFAULT NULL,
 `luogo_nascita` varchar(255) DEFAULT NULL,
 `company_name` varchar(255) DEFAULT NULL,
 `iva_cf` varchar(50) DEFAULT NULL,
 `codice_fiscale` varchar(50) DEFAULT NULL,
 `creator_time` datetime NOT NULL DEFAULT '1970-01-01 01:00:00',
 `last_editor_time` datetime NOT NULL DEFAULT '1970-01-01 01:00:00',
 `external_id_customer` varchar(255) DEFAULT NULL,
 `external_id_richiesta_tipo` enum('R','P','D') DEFAULT NULL,
 `external_id_richiesta` int(11) DEFAULT NULL,
 PRIMARY KEY (`id_customer`),
 UNIQUE KEY `id_agenzia-id_agente-external_id_customer` (`id_agenzia`,`id_agente`,`external_id_customer`),
 KEY `ind_comuni_id` (`ind_comuni_id`),
 KEY `ind_province_id` (`ind_province_id`),
 KEY `id_agente-id_agenzia-id_customer` (`id_agente`,`id_agenzia`,`id_customer`),
 KEY `surname-name` (`surname`,`name`),
 KEY `id_agenzia-id_agente-flag_storico-deleted` (`id_agenzia`,`id_agente`,`flag_storico`,`deleted`),
 KEY `email_email2` (`email`,`email2`),
 KEY `ind_stati_id` (`ind_stati_id`),
 KEY `ind_zone_id` (`ind_zone_id`),
 KEY `id_agenzia-external_id_customer` (`id_agenzia`,`external_id_customer`),
 KEY `rating` (`rating`),
 CONSTRAINT `customers_ibfk_23` FOREIGN KEY (`ind_stati_id`) REFERENCES `ind_stati` (`id`) ON UPDATE CASCADE,
 CONSTRAINT `customers_ibfk_24` FOREIGN KEY (`ind_province_id`) REFERENCES `ind_province` (`id`) ON UPDATE CASCADE,
 CONSTRAINT `customers_ibfk_25` FOREIGN KEY (`id_agente`) REFERENCES `users` (`id`) ON UPDATE CASCADE,
 CONSTRAINT `customers_ibfk_26` FOREIGN KEY (`id_agenzia`) REFERENCES `users` (`id`) ON UPDATE CASCADE,
 CONSTRAINT `customers_ibfk_28` FOREIGN KEY (`ind_comuni_id`) REFERENCES `ind_comuni` (`id`) ON UPDATE CASCADE,
 CONSTRAINT `customers_ibfk_29` FOREIGN KEY (`ind_zone_id`) REFERENCES `ind_zone` (`id`) ON UPDATE CASCADE,
) ENGINE=InnoDB AUTO_INCREMENT=10020244 DEFAULT CHARSET=utf8

CREATE TABLE `users` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `parent_users_id` int(11) DEFAULT NULL,
 `franchising_id` int(11) DEFAULT NULL,
 `affiliates_id` smallint(5) unsigned DEFAULT NULL,
 `website_type` enum('dinamico','professionale','sito_terzi','non_definito') NOT NULL DEFAULT 'non_definito',
 `flag_website_modulistica` tinyint(4) NOT NULL DEFAULT '0',
 `email` varchar(255) NOT NULL,
 `email_pec` varchar(255) NOT NULL,
 `password` varchar(255) NOT NULL,
 `password_sent` tinyint(1) unsigned NOT NULL DEFAULT '0',
 `show_email` tinyint(1) unsigned NOT NULL DEFAULT '0',
 `newsletter_wanted` tinyint(1) unsigned NOT NULL DEFAULT '1',
 `referrer` varchar(255) DEFAULT NULL,
 `logo_img` varchar(255) DEFAULT NULL,
 `agenzia_img` varchar(255) DEFAULT NULL,
 `watermark_img` varchar(255) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL,
 `login_enabled` tinyint(1) unsigned NOT NULL DEFAULT '1',
 `login_expires` datetime DEFAULT NULL,
 `max_ads` int(11) NOT NULL DEFAULT '0',
 `flag_import` tinyint(1) unsigned NOT NULL DEFAULT '0',
 `creation_time` datetime NOT NULL DEFAULT '1970-01-01 01:00:00',
 `contract_price` int(11) DEFAULT NULL,
 `modification_time` datetime DEFAULT NULL,
 `lastlogin_time` datetime DEFAULT NULL,
 `lastlogin_ip` varchar(30) DEFAULT NULL,
 `lastnotification_time` datetime DEFAULT NULL,
 `note` text,
 PRIMARY KEY (`id`),
 UNIQUE KEY `email` (`email`),
 KEY `password_sent` (`password_sent`),
 KEY `creation_time` (`creation_time`),
 KEY `lastlogin_time` (`lastlogin_time`),
 KEY `login_expires` (`login_expires`),
 KEY `login_enabled` (`login_enabled`),
 KEY `password` (`password`),
 KEY `newsletter_wanted` (`newsletter_wanted`),
 KEY `referrer` (`referrer`),
 KEY `parent_users_id` (`parent_users_id`),
 KEY `franchising_id` (`franchising_id`),
 KEY `affiliates_id` (`affiliates_id`),
 KEY `email-login_enabled` (`email`,`login_enabled`),
 KEY `email-password` (`email`,`password`),
 KEY `id-logo_img` (`id`,`logo_img`),
 KEY `rinnovo_automatico` (`rinnovo_automatico`),
 KEY `id` (`id`,`login_enabled`),
 CONSTRAINT `users_ibfk_10` FOREIGN KEY (`parent_users_id`) REFERENCES `users` (`id`) ON UPDATE CASCADE,
 CONSTRAINT `users_ibfk_11` FOREIGN KEY (`franchising_id`) REFERENCES `franchising` (`id`) ON UPDATE CASCADE,
 CONSTRAINT `users_ibfk_12` FOREIGN KEY (`affiliates_id`) REFERENCES `affiliates` (`id`) ON UPDATE CASCADE,
) ENGINE=InnoDB AUTO_INCREMENT=2760 DEFAULT CHARSET=utf8

CREATE TABLE `ads` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `unique_code` varchar(50) NOT NULL DEFAULT '',
 `agency_code` varchar(255) DEFAULT NULL,
 `deleted` tinyint(1) unsigned NOT NULL DEFAULT '0',
 `flag_storico` tinyint(1) unsigned NOT NULL DEFAULT '0',
 `rating` tinyint(1) unsigned NOT NULL DEFAULT '0',
 `logo_img_filename` varchar(255) DEFAULT NULL,
 `allegati_xml` varchar(3500) DEFAULT NULL,
 `planimetrie_xml` varchar(3500) DEFAULT NULL,
 `virtual_tour_panora` varchar(255) DEFAULT NULL,
 `video_tour` varchar(255) DEFAULT NULL,
 `vt360` varchar(255) DEFAULT NULL,
 `mq` int(11) unsigned DEFAULT '0',
 `mq_hidden` int(6) unsigned DEFAULT '0',
 `price` int(11) unsigned DEFAULT '0',
 `price_xml` int(11) unsigned DEFAULT '0',
 `age` varchar(255) DEFAULT NULL,
 `ipe` decimal(6,2) DEFAULT '0.00',
 `abstract` text,
 `seo_title` varchar(100) NOT NULL DEFAULT '',
 `description` text,
 `latitude` double NOT NULL DEFAULT '0',
 `longitude` double NOT NULL DEFAULT '0',
 `latitude_real` double NOT NULL DEFAULT '0',
 `longitude_real` double NOT NULL DEFAULT '0',
 `ind_stati_id` smallint(3) unsigned NOT NULL DEFAULT '110',
 `ind_province_id` int(11) DEFAULT NULL,
 `ind_comuni_id` int(11) DEFAULT NULL,
 `ind_zone_id` int(11) DEFAULT NULL,
 `ind_zone_casa_it_id` int(11) DEFAULT NULL,
 `ind_zone_immobiliare_it_id` int(11) DEFAULT NULL,
 `zona` varchar(255) DEFAULT NULL,
 `indirizzo` varchar(255) DEFAULT NULL,
 `civico` varchar(255) DEFAULT NULL,
 `civico_interno` varchar(50) DEFAULT NULL,
 `indirizzo_xml` varchar(255) DEFAULT NULL,
 `consegna` varchar(255) DEFAULT NULL,
 `spese_condominiali` varchar(255) DEFAULT NULL,
 `unita_abitative` varchar(255) DEFAULT NULL,
 `finiture` text,
 `nord` tinyint(1) unsigned DEFAULT '0',
 `sud` tinyint(1) unsigned DEFAULT '0',
 `ovest` tinyint(1) unsigned DEFAULT '0',
 `est` tinyint(1) unsigned DEFAULT '0',
 `no_nord` tinyint(1) unsigned DEFAULT '0',
 `incarico` enum('condiviso','esclusivo','normale','notizia','censimento') NOT NULL DEFAULT 'normale',
 `incarico_inizio` datetime DEFAULT NULL,
 `incarico_fine` datetime DEFAULT NULL,
 `stato_rogito` enum('non_definito','occupato','libero','affittato') NOT NULL DEFAULT 'non_definito',
 `tipo_affitto` enum('non_definito','3+2','4+4','6+6','9+9','transitorio','concordato','libero','studenti') NOT NULL DEFAULT 'non_definito',
 `tipo_proprieta` enum('non_definito','intera_proprieta','nuda_proprieta','parziale_proprieta','usufrutto','multiproprieta','diritto_di_superficie') NOT NULL DEFAULT 'non_definito',
 `ads_category_id` tinyint(3) unsigned NOT NULL DEFAULT '0',
 `ads_category_micro_id` tinyint(3) unsigned DEFAULT NULL',
 `flag_vacanza` tinyint(1) unsigned NOT NULL DEFAULT '0',
 `flag_mls` tinyint(1) unsigned NOT NULL DEFAULT '0',
 `flag_share_franchising` tinyint(1) unsigned NOT NULL DEFAULT '0',
 `flag_vetrina` tinyint(1) unsigned NOT NULL DEFAULT '0',
 `flag_website_export` tinyint(1) unsigned NOT NULL DEFAULT '0',
 `flag_website_carosello` tinyint(1) unsigned NOT NULL DEFAULT '0',
 `flag_garantito` tinyint(1) unsigned NOT NULL DEFAULT '0',
 `external_id_immobile` varchar(255) DEFAULT NULL,
 `agent_users_id` int(11) NOT NULL,
 `creator_users_id` int(11) NOT NULL DEFAULT '0',
 `creator_time` datetime NOT NULL DEFAULT '1970-01-01 01:00:00',
 `last_editor_users_id` int(11) NOT NULL DEFAULT '0',
 `last_editor_time` datetime NOT NULL DEFAULT '1970-01-01 01:00:00',
 `note` text,
 `note_franchising` text,
 `edit` tinyint(1) NOT NULL DEFAULT '0',
 `imposte` enum('non_definito','regime_di_iva','imposta_di_registro','esente_iva','mista_iva_registro') NOT NULL DEFAULT 'non_definito',
 `destinazione_uso` enum('non_definito','residenziale','commerciale','artigianale','produttivo','direzionale','agricola') NOT NULL DEFAULT 'non_definito',
 `immobile_reddito` tinyint(1) unsigned NOT NULL DEFAULT '0',
 PRIMARY KEY (`id`),
 UNIQUE KEY `unique_code` (`unique_code`),
 KEY `last_editor_users_id` (`last_editor_users_id`),
 KEY `ads_category_id` (`ads_category_id`),
 KEY `zona` (`zona`),
 KEY `logo_img_filename` (`logo_img_filename`),
 KEY `price` (`price`),
 KEY `agency_code` (`agency_code`),
 KEY `flag_storico` (`flag_storico`),
 KEY `ind_zone_immobiliare_it_id` (`ind_zone_immobiliare_it_id`),
 KEY `creator_users_id-deleted-incarico-last_editor_time` (`creator_users_id`,`deleted`,`incarico`,`last_editor_time`),
 KEY `creator_users_id-deleted-flag_storico` (`creator_users_id`,`deleted`,`flag_storico`),
 KEY `flag_website_export` (`flag_website_export`,`flag_website_carosello`),
 KEY `ind_stati_id` (`ind_stati_id`,`creator_users_id`),
 KEY `mq` (`mq`),
 KEY `external_id_immobile` (`external_id_immobile`),
 KEY `price_xml` (`price_xml`),
 KEY `stato_rogito` (`stato_rogito`),
 KEY `ind_comuni_id_2` (`ind_comuni_id`),
 KEY `ind_zone_casa_it_id` (`ind_zone_casa_it_id`),
 KEY `incarico-deleted-flag_storico` (`agent_users_id`,`incarico`,`deleted`,`flag_storico`),
 KEY `agent_users_id-id` (`agent_users_id`,`id`),
 KEY `ind_comuni_id-creator_users-id` (`ind_comuni_id`,`creator_users_id`,`flag_mls`),
 KEY `ind_zone_id` (`ind_zone_id`,`creator_users_id`),
 KEY `flag_share_franchising` (`flag_share_franchising`),
 KEY `ind_province_id` (`ind_province_id`),
 KEY `ads_category_micro_id` (`ads_category_micro_id`),
 KEY `civico` (`civico`),
 KEY `rating` (`rating`),
 KEY `creator_users_id-deleted-flag_mls` (`creator_users_id`,`deleted`,`flag_mls`) USING BTREE,
 CONSTRAINT `ads_ibfk_116` FOREIGN KEY (`ind_stati_id`) REFERENCES `ind_stati` (`id`) ON UPDATE CASCADE,
 CONSTRAINT `ads_ibfk_117` FOREIGN KEY (`ind_province_id`) REFERENCES `ind_province` (`id`) ON UPDATE CASCADE,
 CONSTRAINT `ads_ibfk_118` FOREIGN KEY (`ind_comuni_id`) REFERENCES `ind_comuni` (`id`) ON UPDATE CASCADE,
 CONSTRAINT `ads_ibfk_119` FOREIGN KEY (`ind_zone_id`) REFERENCES `ind_zone` (`id`) ON UPDATE CASCADE,
 CONSTRAINT `ads_ibfk_120` FOREIGN KEY (`ads_category_id`) REFERENCES `ads_category` (`id`) ON UPDATE CASCADE,
 CONSTRAINT `ads_ibfk_121` FOREIGN KEY (`ads_category_micro_id`) REFERENCES `ads_category_micro` (`id`) ON UPDATE CASCADE,
 CONSTRAINT `ads_ibfk_123` FOREIGN KEY (`creator_users_id`) REFERENCES `users` (`id`) ON UPDATE CASCADE,
 CONSTRAINT `ads_ibfk_124` FOREIGN KEY (`last_editor_users_id`) REFERENCES `users` (`id`) ON UPDATE CASCADE,
 CONSTRAINT `ads_ibfk_125` FOREIGN KEY (`agent_users_id`) REFERENCES `users` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4095242 DEFAULT CHARSET=utf8

Anyone could give me some advices please?

A: (Too long for a Comment)
Does that even work???  I see LEFT JOIN ads twice, but with no alias to distinguish them??
OR is a performance killer, especially across multiple tables.  UNION may help.
LIKE with a leading wildcard is a performance killer.  Consider FULLTEXT.
JOIN..ON should say how things are related.  users.login_enabled = 1 smells like filtering not relationship.
The EXPLAIN says that the index agenzia was used -- but there is no such index??