text:
Q: mappedBy reference an unknown target entity property with abstraction I have the following classes and I'm trying to store all the derived classes in one table (aircraft).
But I get the above error, of course, I was searching for a solution for a while, and tried to play with the mappedBy name value as well...
What am I missing?
@Entity // for hibernate
@Table // for database
public class Airline {
    @Id
    @SequenceGenerator(
            name = "airline_sequence",
            sequenceName = "airline_sequence",
            allocationSize = 1
    )
    @GeneratedValue(
            strategy = GenerationType.SEQUENCE,
            generator = "airline_sequence"
    )
    private long airline_id;

    @ManyToOne
    @JoinColumn(name = "airport_id")
    private Airport homeAirport;

    @OneToMany(mappedBy = "aircraft", cascade = CascadeType.ALL)
    private List<Aircraft> airplaneList;

@Inheritance
@DiscriminatorColumn
@Entity
public abstract class Aircraft implements Serializable {

    @Id
    @SequenceGenerator(
            name = "aircraft_sequence",
            sequenceName = "aircraft_sequence",
            allocationSize = 1
    )
    @GeneratedValue(
            strategy = GenerationType.SEQUENCE,
            generator = "aircraft_sequence"
    )

    // Data members
    private long aircraft_id

    @ManyToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "airline_id")
    private Airline airline;

    @Version
    private Long version;

@Entity // for hibernate
@Table // for database
@DiscriminatorValue("Airplane")
public class Airplane extends Aircraft {

    //Constructors here


text:
Q: Can't "open with" certain programs in Windows 7 For example:

*

*Right-click .pdf file

*Click "Open with..."

*"Choose default program"  (Reader is currently highlighted)

*Click Browse button

*Navigate to C:\Program Files\Inkscape\inkscape.exe, press Open
Nothing happens.  Inkscape doesn't appear in the Recommended Programs or Other Programs lists, and the highlighted program is still Reader.  It's impossible to select Inkscape.  I've had this working in the past, but now I can't select it.
I've seen this in the past with other programs.  Sometimes I can set a program as the default (or as a non-default option that shows up in "Open with" sub-menu), other times I can't.  Why?

redpajama_set_name: RedPajamaStackExchange


text:
Q: gplus button errors If I put simple iframe on my webpage
<iframe allowtransparency="true" frameborder="0" hspace="0" id="100513874119798249855" marginheight="0" marginwidth="0" name="I2_1321861433794" scrolling="no" src="https://plusone.google.com/_/+1/fastbutton?url=http%3A%2F%2Fwww.dudeye.com%2Fsite%2Flike%2F543&size=tall&count=true&annotation=&hl=en-US&jsh=m%3B%2F_%2Fapps-static%2F_%2Fjs%2Fwidget%2F__features__%2Frt%3Dj%2Fver%3DajMrQx3-U8Y.pl.%2Fsv%3D1%2Fam%3D!W_gXXLnZrrYgVlks%2Fd%3D1%2F#id=I2_1321861433794&parent=http%3A%2F%2Fwww.dudeye.com&rpctoken=295361220&_methods=onPlusOne%2C_ready%2C_close%2C_open%2C_resizeMe" style="width: 50px; margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; border-top-style: none; border-right-style: none; border-bottom-style: none; border-left-style: none; height: 60px; position: static; left: 0px; top: 0px; visibility: visible; " tabindex="-1" vspace="0" width="100%" title="+1"></iframe>

Without using <g:plus> tags I have many errors like:

document.getElementById(a) is null

And some errors in google badge like Unsafe JavaScript attempt to access frame with URL... bla bla bla... Domains, protocols and ports must match.
How can I repair this errors and what is going on with it?

A: You need the google +1 javascript inclusion on your parent page for it to work well.


text:
Q: Merge Statement Performance I have one table with one column iscurrent, values are 0 and 1.
I am inserting rows to this table with a merge statement that is inserting or updating based on the value of iscurrent. For performance tuning I have created two partitions with 0 and 1 on that table. But the performance is not good enough.
How can I tune the merge statement? Every time it is merging thousands rows to million of rows. Will partitioning the table help?

A: If you're using a derived table as the source, start by tuning that select statement first, or put the results of the derived table into a physical table with the proper indexes.
MERGE myTargetTabe as TargetTable
USING (derived table statement goes here) SourceTable on .......

A merge statement will scan every row that meets the criteria you specify in the "ON" clause, if there are rows that you don't need to merge, then exclude the rows here. For example:
MERGE myTargetTabe as TargetTable
USING (derived table statement goes here) SourceTable on TargetTable.ID = SourceTable.ID and TargetTable.OtherColumn NOT IN (....)  and ...... or .... and so on.


text:
Q: Bootstrap MDB Angular - time picker, change input date format to American format all I have the following date picker on my site:
<mdb-form-control>
      <input
        mdbInput
        [mdbDatepicker]="datepicker"
        type="text"
        class="form-control"
        id="exampleDatepicker"
        [(ngModel)]="selectedDate"
        (change)="changeDate(); calcNight()"
        placeholder="dd/mm/yyyy"

      />
      <label mdbLabel for="exampleDatepicker" class="form-label">Select a date</label>
      <mdb-datepicker-toggle [mdbDatepicker]="datepicker"></mdb-datepicker-toggle>
      <mdb-datepicker   [inline]="true" #datepicker (dateChanged)="dateChange($event)"></mdb-datepicker>
</mdb-form-control>

I am based in the UK and when I change the date I get the output eg Fri Jan 06 2023 02:35:19 GMT+0000 (Greenwich Mean Time) and here we use the format dd/mm/yyyy
Now a user of my site from the US has reported a problem where he entered the date in the format of mm/dd/yyyy but the picker translated it as a UK format dd/mm/yyyy. I am wondering how I set the input format so the picker knows the format of the input and therefore gives the correct selectedDate?
Thanks for any help here.


text:
Q: do-release-upgrade - Could not determine the upgrade Edit: Answer at bottom, I'm leaving the question untouch to keep all elements that might match someone else's search.
So, I've read about the issue (here, here, here and here) but could not find the help I needed.
It's happening on a server I run for personal usage, so it's not really well maintained. It's running Ubuntu 12.10 (told you!) Server on which I've installed a KDE desktop that I can connect to remotely using  X2Go.
Through SSH, I tried do-release-upgrade which resulted in the error in the title.
At this point, I opened the /var/log/dist-upgrade/apt.log file which ends with
Can't guess meta-package

Your system does not contain a ubuntu-desktop, kubuntu-desktop,
xubuntu-desktop or edubuntu-desktop package and it was not possible
to detect which version of Ubuntu you are running.
Please install one of the packages above first using synaptic or
apt-get before proceeding.

Easy enough... But:
$ sudo apt-get install kubuntu-desktop
Reading package lists... Done
Building dependency tree
Reading state information... Done
kubuntu-desktop is already the newest version.
0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.

I also tried
$ sudo dpkg --configure -a
followed by
$ sudo apt-get install -f
as advised in one of the answers linked above, just in case, but nothing changed/happened.

Then I tried to look for Broken like advised in one of the cited thread and got this :
$ grep Broken /var/log/dist-upgrade/apt.log
Broken cups-filters:amd64 Conflicts on ghostscript-cups [ amd64 ] < 9.06~dfsg-0ubuntu4 > ( text )
Broken php5-common:amd64 Breaks on php-apc [ amd64 ] < 3.1.13-1 > ( php ) (< 4.0.0)
Broken php5-common:amd64 Breaks on php5-suhosin [ amd64 ] < 0.9.33-3build1 > ( php ) (< 0.9.34)
Broken php5-common:amd64 Breaks on php5-xdebug [ amd64 ] < 2.2.1-1 > ( php ) (< 2.2.2)
Broken python3-pykde4:amd64 Depends on python3 [ amd64 ] < 3.2.3-5ubuntu1.2 -> 3.3.2-14ubuntu1 > ( python ) (< 3.3)
Broken libsnmp30:amd64 Breaks on libsnmp15 [ amd64 ] < 5.4.3~dfsg-2.5ubuntu1.1 > ( libs )
Broken software-properties-kde:amd64 Depends on python3-pykde4 [ amd64 ] < 4:4.9.4-0ubuntu0.1 > ( python )
Broken python-kde4:amd64 Depends on sip-api-8.1 [ amd64 ] < none > ( none )
Broken libfftw3-double3:amd64 Breaks on libfftw3-3 [ amd64 ] < 3.3.2-3.1ubuntu1 > ( libs ) (< 3.3.3-1)
Broken apport-kde:amd64 Depends on python3-pykde4 [ amd64 ] < 4:4.9.4-0ubuntu0.1 > ( python )
Broken ubuntu-release-upgrader-qt:amd64 Depends on ubuntu-release-upgrader-core [ amd64 ] < 1:0.190.8 -> 1:0.205 > ( admin ) (= 1:0.190.8)
Broken libmuonprivate1:amd64 Depends on software-properties-kde [ amd64 ] < 0.92.9.3 > ( kde )
Broken muon-notifier:amd64 Depends on ubuntu-release-upgrader-qt [ amd64 ] < 1:0.190.8 > ( admin )
Broken gtk2-engines-pixbuf:i386 Depends on libgtk2.0-0 [ i386 ] < 2.24.13-0ubuntu2 -> 2.24.20-1ubuntu1 > ( libs ) (= 2.24.13-0ubuntu2)
Broken muon-updater:amd64 Depends on libmuonprivate1 [ amd64 ] < 1.4.1-0ubuntu1.1 > ( kde ) (= 1.4.1-0ubuntu1.1)
Broken userconfig:amd64 Depends on python-kde4 [ amd64 ] < 4:4.9.4-0ubuntu0.1 > ( python ) (>= 4:4.7.0-0ubuntu2~)
Broken muon:amd64 Depends on libmuonprivate1 [ amd64 ] < 1.4.1-0ubuntu1.1 > ( kde ) (= 1.4.1-0ubuntu1.1)
Broken krita:amd64 Depends on libfftw3-3 [ amd64 ] < 3.3.2-3.1ubuntu1 > ( libs )
Broken muon-installer:amd64 Depends on libmuonprivate1 [ amd64 ] < 1.4.1-0ubuntu1.1 > ( kde ) (= 1.4.1-0ubuntu1.1)
Broken usb-creator-kde:amd64 Depends on usb-creator-common [ amd64 ] < 0.2.40ubuntu2 -> 0.2.50 > ( admin ) (= 0.2.40ubuntu2)
Broken apturl-kde:amd64 Depends on python3-pykde4 [ amd64 ] < 4:4.9.4-0ubuntu0.1 > ( python )
Broken jockey-kde:amd64 Depends on python-kde4 [ amd64 ] < 4:4.9.4-0ubuntu0.1 > ( python )
Broken plasma-scriptengine-python:amd64 Depends on python-kde4 [ amd64 ] < 4:4.9.4-0ubuntu0.1 > ( python ) (>= 4:4.6.80)
Broken kde-config-touchpad:amd64 Depends on python-kde4 [ amd64 ] < 4:4.9.4-0ubuntu0.1 > ( python ) (>= 4:4.5)
Broken kubuntu-desktop:amd64 Depends on software-properties-kde [ amd64 ] < 0.92.9.3 > ( kde )
Broken php5-ps:amd64 Depends on phpapi-20100525 [ amd64 ] < none > ( none )
Broken php5-imagick:amd64 Depends on phpapi-20100525 [ amd64 ] < none > ( none )
Broken php5-mcrypt:amd64 Depends on phpapi-20100525 [ amd64 ] < none > ( none )
Broken php5-imap:amd64 Depends on phpapi-20100525 [ amd64 ] < none > ( none )
Broken php5-memcache:amd64 Depends on phpapi-20100525 [ amd64 ] < none > ( none )
Broken ia32-libs-multiarch:i386 Depends on gtk2-engines-pixbuf [ i386 ] < 2.24.13-0ubuntu2 > ( graphics )
Broken kubuntu-notification-helper:amd64 Depends on ubuntu-release-upgrader-qt [ amd64 ] < 1:0.190.8 > ( admin )
Broken libfftw3-double3:amd64 Breaks on libfftw3-3 [ amd64 ] < 3.3.2-3.1ubuntu1 > ( libs ) (< 3.3.3-1)
Broken ubuntu-release-upgrader-qt:amd64 Depends on ubuntu-release-upgrader-core [ amd64 ] < 1:0.190.8 -> 1:0.205 > ( admin ) (= 1:0.190.8)
Broken plasma-widget-facebook:amd64 Depends on plasma-scriptengine-python [ amd64 ] < 4:4.9.5-0ubuntu0.1 > ( kde )
Broken krita:amd64 Depends on libfftw3-3 [ amd64 ] < 3.3.2-3.1ubuntu1 > ( libs )
Broken plasma-scriptengine-python:amd64 Depends on python-kde4 [ amd64 ] < 4:4.9.4-0ubuntu0.1 > ( python ) (>= 4:4.6.80)
Broken ia32-libs:amd64 Depends on ia32-libs-multiarch [ amd64 ] < none > ( none )
Broken ia32-libs-multiarch:i386 Depends on gtk2-engines-pixbuf [ i386 ] < 2.24.13-0ubuntu2 > ( graphics )
Broken kubuntu-notification-helper:amd64 Depends on ubuntu-release-upgrader-qt [ amd64 ] < 1:0.190.8 > ( admin )
Broken libfftw3-double3:amd64 Breaks on libfftw3-3 [ amd64 ] < 3.3.2-3.1ubuntu1 > ( libs ) (< 3.3.3-1)
Broken ubuntu-release-upgrader-qt:amd64 Depends on ubuntu-release-upgrader-core [ amd64 ] < 1:0.190.8 -> 1:0.205 > ( admin ) (= 1:0.190.8)
Broken plasma-widget-facebook:amd64 Depends on plasma-scriptengine-python [ amd64 ] < 4:4.9.5-0ubuntu0.1 > ( kde )
Broken krita:amd64 Depends on libfftw3-3 [ amd64 ] < 3.3.2-3.1ubuntu1 > ( libs )
Broken plasma-scriptengine-python:amd64 Depends on python-kde4 [ amd64 ] < 4:4.9.4-0ubuntu0.1 > ( python ) (>= 4:4.6.80)
Broken ia32-libs:amd64 Depends on ia32-libs-multiarch [ amd64 ] < none > ( none )
Broken ia32-libs-multiarch:i386 Depends on gtk2-engines-pixbuf [ i386 ] < 2.24.13-0ubuntu2 > ( graphics )
Broken kubuntu-notification-helper:amd64 Depends on ubuntu-release-upgrader-qt [ amd64 ] < 1:0.190.8 > ( admin )
Broken plasma-widget-facebook:amd64 Depends on plasma-scriptengine-python [ amd64 ] < 4:4.9.5-0ubuntu0.1 > ( kde )
Broken ia32-libs:amd64 Depends on ia32-libs-multiarch [ amd64 ] < none > ( none )

Notice that kubuntu-desktop is in the list. Not sure what to do with that...
As a side note, here is the list of PPA or thrid-party repository I've on this server
chris-lea-node_js-quantal
dropbox
google-musicmanager
guilhem-fr-vsftpd-quantal
newrelic
nginx-stable-quantal
nilarimogard-webupd8-quantal
tuxpoldo-btsync-quantal
webupd8team-sublime-text-2-quantal
x2go-ppa-quantal
x2go-stable-quantal

Which leaves me with a couple of questions:

*

*Am I supposed to delete all these packages by hand ?

*Will the update go through correctly after that ?

*Should I plan a whole afternoon to fix issues after the upgrade in order to get back a working configuration ? (Like: X2Go, KDE workspace etc...)

Edit:
The actual problem was the unreachable ubuntu mirrors due to the EOL process.
As pointed in the comment, fixing the source.list helped. See this answer for ways to fix the source.list.
Thanks to saiarcot895 for pointing me in the right direction!


text:
Q: How do I create log files inside my spring boot project directory? How do I create log files inside my spring boot project directory? I want to create separate files for error and info messages. I'm using spring boot v. 2.5.

A: first, add log4j dependency:
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-log4j2</artifactId>
    </dependency>

then create a log4j.xml file in your project directory with the following cinfig:
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN" monitorInterval="30">
<Properties>
    <Property name="LOG_PATTERN">%highlight{%d -%r-%-5p %X{MdcHeader} %C{1.} - %m%n}{STYLE=Logback}</Property>

    <!--WINDOWS LOG DIRECTORY-->
    <Property name="logDirWindows">D:\\myLogs\\logger\\</Property>
    <Property name="logDir">${logDirLinux}</Property>
</Properties>
<Appenders>
    <Console name="ConsoleAppender" target="SYSTEM_OUT" follow="true">
        <PatternLayout pattern="${LOG_PATTERN}"/>
    </Console>

    <RollingRandomAccessFile name="MainLogger" fileName="${logDir}main.log" filePattern="${logDir}main.log.%d{yyyy-MM-dd}" bufferedIO="true" >
        <Policies>
            <TimeBasedTriggeringPolicy interval="1" modulate="true"/>
        </Policies>
        <PatternLayout pattern="${LOG_PATTERN}"/>
    </RollingRandomAccessFile>

</Appenders>

<Loggers>
    <Logger name="MainLogger" level="info" additivity="false">
        <AppenderRef ref="ConsoleAppender"/>
        <AppenderRef ref="MainLogger"/>
    </Logger>
    <Root level="info">
        <AppenderRef ref="ConsoleAppender"/>
    </Root>
</Loggers>

as you can see in the config file, I define a directory address to store the log:

<Property name="logDirWindows">D:\\myLogs\\logger\\</Property>


text:
Q: Using React i18next do I have to use withTranslation? I am wondering something.
Say I have a component and I want to access the t value. Do I have to hook it to redux. Since to use react-i18next I am also using i18next can't I just do:
import i18next from 'i18next'

class Comp extends Component {
    render() {
      return <Text>{i18next.t('space')}</Text>
    }
}

Or what's the downside of doing this? It seems it still does my translation but there must be a downside? I'm guessing only if the locale changes it won't see the update? Anything else?
Thanks.

A: You can't use hooks on React Component classes (at least without HOC).
Best thing you can do is to import withTranslation and export the class via this component.
What I mean:
// Other imports
import { withTranslation } from "react-i18next";

class ClassComponent extends React.Component {
    //Code of your class
}

export default withTranslation()(ClassComponent);

Notice you should call t with this.props.t while rendering.


text:
Q: Integrate function (and their types) from Python to C# My goal is to convert a Python function to a function in C# with the same functionality. The important aspect here is that I have information in Python on the input types and output types of the function. This information should be transferred to the function in C#.
Using IronPython I can integrate the Python function to C# with object as input and output types. Currently I have the following code:
    class Program
    {
        public static void Main(string[] args) {
        var engine = Python.CreateEngine();
        var scope = engine.CreateScope();
        var source = engine.CreateScriptSourceFromString(
                "def Add(arg1, arg2):\n" +
                "   return arg1 +1\n"  +
                "\n" +
                "functionTypes = int" +
                "\n" +
                "class MyClass(object):\n" +
                "   def __init__(self, value):\n" +
                "       self.value = value\n");
        source.Execute(scope);

        var Add= scope.GetVariable<Func<object, object , object>>("Add");
        Console.WriteLine(Add(2,3 ));

But what I would like to have is var Add= scope.GetVariable<Func<functionTypes, functionTypes , functionTypes>>("Add"); where functionTypes represents int.
EDIT: Is there a solution which works for functions with arbitrary inputs. For instance, we want to translate an arbirtary function in python to the same function in c# (including all the types)

A: The easiest way to deal with it is using a manual casting. You can get C# clr type from IronPython using clr() method, then you can create if statement to create specific Func type (like in this post). You can also try to find a C# reflection solution (read this post) but in case of making Func<yourType, yourType, yourType> it could be extremly hard.
static void Main(string[] args)
{
    var engine = Python.CreateEngine();
    var scope = engine.CreateScope();
    var source = engine.CreateScriptSourceFromString(
            "def Add(arg1, arg2):\n" +
            "   return arg1 +1\n" +
            "\n" +
            "functionTypes = int" +
            "\n" +
            "class MyClass(object):\n" +
            "   def __init__(self, value):\n" +
            "       self.value = value\n");
    source.Execute(scope);
    var type = scope.GetVariable("functionTypes") as IronPython.Runtime.Types.PythonType;
    Type clrType = type.__clrtype__();
    if (clrType == typeof(int))
    {
        var Add = scope.GetVariable<Func<int, int, int>>("Add");
        Console.WriteLine(Add(2, 3));
    }
    else if (clrType == typeof(double))
    {
        var Add = scope.GetVariable<Func<double, double, double>>("Add");
        Console.WriteLine(Add(2, 3));
    }
    //make your own else statements here
}


text:
Q: Android video captured in portrait mode is not playing in portrait mode In my app there I am capturing video in portrait mode but the video is by default changing to landscape when I play it.
I tried mCamera.setDisplayOrientation(90) worked in Android 4.0 devices but not in 2.3 devices. My App target is 2.3
I have also noticed one thing that when I go to Gallery and play it through the default media player it plays in Portait mode. :-(
Try various options and I goggled around but couldn't find any solution. Please someone guide me if you have ever faced the same issue.
here's my Code
mMediaRecorder = new MediaRecorder();

    mCamera.unlock();
    mCamera.setDisplayOrientation(90);
    mMediaRecorder.setCamera(mCamera);

    mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
    mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
    mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
    mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
    mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
    mMediaRecorder.setVideoFrameRate(30);

A: It seems it cannot record video in other way than landscape. Your mCamera.setDisplayOrientation(90) is affecting preview according to the docs.


text:
Q: CakePHP - Recuperar valor do option Olá! Estou consertando um website que peguei pronto e nele tem uma parte que o usuário seleciona um bairro em um <option>, porém, este <option> não está enviando a informação para o banco de dados.
Selecionando a cidade, aparece os bairros desta determinada cidade. Aqui está o arquivo view:
echo $this->Form->input('cidade', array('label' => 'Cidade', 'empty' => 'Selecione uma cidade', 'options' => $Cidades));
echo $this->Form->input('bairro', array('label' => 'Bairro', 'empty' => 'Selecione o Bairro', 'options' => array()));

No controller, a função para add:
public function add () {
    if (empty($this->request->data)); else {
        $data = $this->request->data;
        if ($data['Imovel']['opcoes']) $data['Imovel']['opcoes'] = implode(';', $data['Imovel']['opcoes']);
        $data['Imovel']['ativo'] = $data['Imovel']['ativoPeloAdm'] = 1;
        $data['Imovel']['creator'] = $data['Imovel']['modifier'] = $this->Session->read('Auth.User.Imobiliaria.id');
        if ($data['Imovel']['bairro']) {
            $bairro = $this->Cep->find('first', array('conditions' => array('id' => $data['Imovel']['bairro'])));
            $data['Imovel']['bairroNome'] = $bairro['Cep']['bairro'];
        }

        if ($data['Imovel']['cidade']) {
            $cidade = $this->Cidade->find('first', array('conditions' => array('id' => $data['Imovel']['cidade'])));
            $data['Imovel']['cidadeNome'] = $cidade['Cidade']['nome'];
        }

        $data['Imovel']['especificacao'] = $data['Imovel']['imovel'];
        if ($this->Imovel->save($data)) $this->redirect(array('action' => 'index'));
    }
}

Alguém pode me ajudar?
Ajax :
    $('#ImovelCidade').change(function(e) {
    $('#ImovelBairro').html($('<option />').val('').text('Carregando...'));
    $.getJSON(
        "<?php echo Router::url(array('controller' => 'pages', 'action' => 'pegarBairros')) ?>",
        { "cidade" : $(this).val() },
        function (data) {
            $('#ImovelBairro').html($('<option />').val('').text('Selecione'));
            $.each(data, function (chave, valor) {
                $('#ImovelBairro').append($('<option />').val(chave).text(valor));
            } );
        }
    );
});

Função pegarbairros no controller:
public function pegarBairros ($cidade = null) {
    $this->layout = 'json';
    $result = array();

    if (in_array($_REQUEST['cidade'], array_keys($this->cidade))) {
        $bairros = $this->Cep->find('list', array('fields' => array('id','bairro'), 'conditions' => array('cidade' => $this->cidade[$_REQUEST['cidade']]),'group' => 'bairro'));
        sort($bairros);

        foreach ($bairros as $id => $bairro) {
            if (!empty($bairro))
                $result[$id] = $bairro;
            else
                $result[] = 'error';
            $this->set('data', $result);
        }
    }
}

estou tentando inserir um bairro, mas está retornando um Array

A: Lendo seu código me parece que é um erro na formatação dos dados. Você precisa que seu ajax retorne um json assim você vai ter mais facilidade para manipular o retorno por javascript e gerar um html válido.
O que eu sugiro:
public function pegarBairros ($cidade = null) {
    $this->layout = 'json';
    $result = array();

    if (in_array($_REQUEST['cidade'], array_keys($this->cidade))) {
        $bairros = $this->Cep->find('list', array('fields' => array('id','bairro'), 'conditions' => array('cidade' => $this->cidade[$_REQUEST['cidade']]),'group' => 'bairro'));
        sort($bairros);

        foreach ($bairros as $id => $bairro) {
            if (!empty($bairro)) {
                $result[$id] = $bairro;
            } else {
                $result[] = 'error';
            }
            $result = json_encode($result);
            $this->set('data', $result);
        }
    }
}


text:
Q: Creating Table in dataset in BigQuery I want to create a Table for my dataset in BigQuery. I want to upload CSV file. When I upload it and clicked on "create table" it is saying:

unexpected error. Tracking number c986854671035387

What is this error and How can I solve this? (I also upgraded my BigQuery to 90 days free trial).

A: You need to check the data inside CSV. If it has column names and no faulty records.
you can download any sample CSV file from here and try
http://www.mytrapture.com/sampledata/


text:
Q: Simple code only works in certain editor but not anywhere else Why does the below code only work in the Codecademy.com editor and not in a real browser or jsfiddle? There seem to be no mistakes...
HTML

Zebras eat bananas

That's nonsense

With this javascript, #p2 should change automatically when the page has loaded. In the Codecademy editor that's what happens, but see it not work in Jsfiddle and also not when I make HTML/js files and run it in my browser.
How can I fix this? Or did they teach me wrong?
Javascript
$(document).ready(function(){
$('#p2').html("Now it makes sense!");
})

A: As @dfsq has mentionend, you need to include jQuery to your file, as to your fiddle. You can do this by adding this line before your script:

After that, you can put your code in

and you will see that it works.
Your jQuery script should allways be directly before the closing  tag, so that the DOM is loaded before you try to access it with javascript/jQuery


text:
Q: Is this a portable strdup I have a c program I'm writing that I want to be portable and future compliant. The POSIX function strdup() is not in the current C standard, but it has been added to the C2x standard. Will this code work properly with C standard compliant compilers in the future.
Will it work on both POSIX and non POSIX systems?
my_strdup.h
#ifndef MY_STRDUP_H
#define MY_STRDUP_H

#include <string.h>

#ifndef strdup
#ifdef _MSC_VER
#if _MSC_VER > 1920
#define strdup _strdup
#endif
#else
#define strdup mystrdup
#endif
#endif

char* mystrdup(const char* string_to_copy);
unsigned char* ucstrdup(const unsigned char* string_to_copy);

#endif  // MY_STRDUP_H

my_strdup.c
#include "my_strdup.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char* mystrdup(const char* string_to_copy)
{
    char* return_string = NULL;
    size_t length = strlen(string_to_copy);
    ++length;

    return_string = calloc(length, sizeof(*return_string));
    if (return_string)
    {
        memcpy(return_string, string_to_copy, length - 1);
    }

    return return_string;
}

unsigned char* ucstrdup(const unsigned char* string_to_copy)
{
    unsigned char* return_string = NULL;
    size_t length = strlen((const char*)string_to_copy);
    ++length;

    return_string = calloc(length, sizeof(*return_string));
    if (return_string)
    {
        memcpy(return_string, string_to_copy, length - 1);
    }

    return return_string;
}

Post Answer Update:
This code is part of a project I am working on, the code that uses this code can be found in 4 questions on Code Review. Those questions are all related to unit tests I am writing for this project.
Here are the questions on code review in the order asked:

*

*Hand Coded State Driven Lexical Analyzer in C With Unit Test Part A

*Hand Coded State Driven Lexical Analyzer in C With Unit Test Part B

*Part C

*Follow up to Part C
Feel free to write answers for the questions as long as they follow the Code Review Guidelines

A: Read carefully the C11 standard n1570. For things like Arduino, you might not even have any malloc, and you could have some free-standing implemention of C11.
As a concrete example, the Linux kernel is coded in C, and your code could not be part of it.
Also see this answer providing some funny implementation of malloc (you could extend it to calloc...)

Will this code work properly with C standard compliant compilers in the future.

Of course not in general.
Look on many examples of toy operating systems on OSDEV.
You could have some operating system without  malloc or calloc but with a C compiler.

I have a c program I'm writing that I want to be portable and future compliant.

The motto I read somewhere is: there is no such thing as portable programs, just programs which have been ported (to some given systems)
Did you consider some approach inspired by GNU autoconf ? Your build automation could use preprocessing tricks and/or generate C code with e.g. GPP, SWIG or other tools.


text:
Q: How to load Imagick convert and all dependencies into /dev/shm for performance? I am trying to compare at least 40000 screenshots from videos with Imagick command "/dev/shm/convert s1 s2  -metric RMSE -format %[distortion] -compare info:".
I have succeded to get an average speed of ~ 0.04 seconds.
If I am using in 3 threads the convert command CPU rises to 80-90% an all cores(witch it should be), but also the load on server increase exponentially and affects the average speed to ~0.09 seconds
I am using s1 and s2 image paths from /dev/shm to lower the impact on loading server and SSD. Also I am using the convert command from /dev/shm, is not enough , because it uses other libraries from the SSD.
I dont know what are the dependencies library to copy them to /dev/shm ,or any other approach would be good to achieve the same result.


text:
Q: SpaCy can't find table(s) lexeme_norm for language 'en' in spacy-lookups-data I am trying to train a text categorization pipe in SpaCy:
import spacy

nlp = spacy.load("en_core_web_sm")
nlp.add_pipe("textcat", last=True)
other_pipes = [pipe for pipe in nlp.pipe_names if pipe != 'textcat']
with nlp.disable_pipes(*other_pipes):
    optimizer = nlp.begin_training()
    # training logic

However, every time I call nlp.begin_training(), I get the error
ValueError: [E955] Can't find table(s) lexeme_norm for language 'en' in spacy-lookups-data. Make sure you have the package installed or provide your own lookup tables if no default lookups are available for your language.

Running python3 -m spacy validate returns
✔ Loaded compatibility table

================= Installed pipeline packages (spaCy v3.0.3) =================
ℹ spaCy installation:
/xxx/xxx/xxx/env/lib/python3.8/site-packages/spacy

NAME             SPACY            VERSION
en_core_web_lg   >=3.0.0,<3.1.0   3.0.0   ✔
en_core_web_sm   >=3.0.0,<3.1.0   3.0.0   ✔

Furthermore, I have tried installing spacy-lookups-data without success.
How can I resolve this error?

A: It isn't allowed to call nlp.begin_training() on pretrained models. If you want to train a new model, just use:
nlp = spacy.blank('en')
instead of nlp = spacy.load("en_core_web_sm")
However, if you want to continue training on an existing model call optimizer = nlp.create_optimizer() instead of begin_training()


text:
Q: How do I access a variable in a button action in Swift I cannot access the variable incomeValue in the savingsGoal function. Xcode gives me the error "Use of unresolved identifier 'incomeValue'.
@IBAction func incomeSliderChanged(sender: UISlider) {
    var incomeValue = Double(sender.value)
    currentIncomeLabel.text = ("$\(incomeValue) /yr")
}
@IBAction func savingsSliderChanged(sender: UISlider) {
    var savingsValue = Int(sender.value)
    savingsLabel.text = ("\(savingsValue)% of income")

    println("savings value \(savingsValue)%")
}
@IBAction func indexChanged(sender: UISegmentedControl) {
    switch sender.selectedSegmentIndex {
    case 0:
        println("first segement clicked")
    case 1:
        println("second segment clicked")
    default:
        break;
    }
}
@IBAction func calculateButtonPressed(sender: AnyObject) {
}

func savingsGoal () {
    var futureIncome = incomeValue + (incomeValue * 3.8)
}

}

A: Your problem is that you declared incomeValue inside your incomeSliderChanged(_:) function. This limits the scope of incomeValue to that function, meaning you can only reference it from withing the opening { and closing } of incomeSliderChange(_:). To fix this declare your incomeValue variable outside of the function.
var incomeValue: Double = 0.0 // You can replace 0.0 with the default value of your slider

@IBAction func incomeSliderChanged(sender: UISlider) {
    // Make sure you get rid of the var keyword.
    // The use of var inside this function would create a
    // second incomeValue variable with its scope limited to this function
    // (if you were to do this you could reference the other incomeValue
    // variable with self.incomeValue).
    incomeValue = Double(sender.value)
    currentIncomeLabel.text = ("$\(incomeValue) /yr")
}

func savingsGoal() {
    // You can now access incomeValue within your savingsGoal() function
    var futureIncome = incomeValue + (incomeValue * 3.8)
}

If you are new to programming, I recommend reading about the concept of Scope: http://en.wikipedia.org/wiki/Scope_(computer_science)


text:
Q: Find polar equation from 4 polar points Given $4$ polar coordinates $(3, -\pi/6)$, $(1, \pi/3)$, $(3, 5\pi/6)$, $(-3, 4\pi/3)$, graph and find the polar equation.
I know that the general polar equation is $r = ep / 1+- e \cos (\theta)$. After plotting the points, I am not sure how the graph looks like, but I assume it looks like this :
Since it's hyperbola, the eccentricity will be $> 1$. Then I am kind of stuck. Not sure how can I determine the sign and cos/sin for the polar equation though I think I can find $e$ and $p$ by plugging-in 2 points for $\theta$ and $r$ into the general polar equation and then solving it as a system of equations. Am I on the right way? Thanks!

A: The polar form of the conic section you quote,
$$r = \frac{p}{1+\epsilon \cos{\theta}}$$
is very restrictive and does not cover a hyperbola that has an offset and rotation such as that in your graph.  If you convert back to cartesian form, the polar equation is equivalent to
$$\frac{\left ( x + \frac{\epsilon p}{1-\epsilon^2}\right)^2}{p^2/(1-\epsilon^2)^2} + \frac{y^2}{p^2/(1-\epsilon^2)} = 1$$
Thus, the conic, whether an ellipse or hyperbola, is centered on the $x$-axis and has axes of symmetry parallel to the $x$ and $y$ axes.  Thus, the conic having the given polar form is completely determined using only two points.
Obviously, you need a more general parameteric form; I do not what it is off the top of my head.  That said, you can start with the cartesian form:
$$a x^2+ 2 b x y+c y^2 + d x + e y + f=0$$
Thus, you need six points for the general conic.  Perhaps you can eliminate two parameters, say $e$ and $f$, but remember you are imposing a symmetry that may or may not be valid for your plot.


text:
Q: Symfony custom form weird property access errors I've got this strange problem, here is example usage of my custom ThingType class.
->add('photos', 'namespace\Form\Type\ThingType', [
    'required' => false,
])

if the field name is photos everything works as expected, but if I change my entity field to let's say photosi, run generate entities, and change the form field name, this error is thrown:

Neither the property "photosi" nor one of the methods
  "addPhotosus()"/"removePhotosus()", "setPhotosi()", "photosi()",
  "__set()" or "__call()" exist and have public access in class
  "AppBundle\Entity\Product".

I guess the problem comes from Symfony trying to generate getter method name for my entity. Why is this addPhotosus method name generated? How can I solve this?
EDIT:
I'm using model transformer when showing the data to the user.
    $builder->addModelTransformer(new CallbackTransformer(
        function ($imagesAsText) {
            if (!$imagesAsText) {
                return null;
            }

            $newImages = [];
            foreach($imagesAsText as $img) {
                $newImages[] = $img->getID();
            }

            return implode(',', $newImages);
        },
        function ($textAsImages) use ($repo) {
            $images = [];
            foreach(explode(',', $textAsImages) as $imgID) {
                $img = $repo->findOneById($imgID);

                if ($img) {
                    $images[] = $img;
                }
            }

            return $images;
        }
    ));

The actual field is TextType::class with entity ids in it for example 1,10,32,51. The model transformer transforms this data to entities. Setting 'data_class' to my form type seems irrelevant, because the actual form type is a part of entity. I mean I have Product entity and Photo entity, photos is array of photo entity. So in my ThingType, what data_class should I use, photo or product?
Thanks

A: The fist parameter of the add method for a form, should be one of the mapped attributes of the data_class of the form, usually selected inside the form as
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
        $resolver->setDefaults(array(
            'data_class' => 'AppBundle\Entity\Product'
        ));
}

That isn't related to the form name. So , you are trying to access to a "photosi" attribute inside your Product class.
Hope this help you.

A: Ok so for the first point you need to remember that Symfony is looking for setXX() and getXX()method in your entity for each entry of your form.
If you change your variable name you need to update the form :
->add('newName', XXType::class, [
    'required' => false,
])

and you're entity by changing the variable
class Entity
{

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $newName;

    public function getOldName(){
        return $this->$oldName;
    }

   public function setOldName(oldName){
       $this->oldName = $oldName;
       return $this
   }

}

then run the command
php bin/console make:entity --regenerate

and symfony will upload your entity by itself
class Entity
{

    /**
     * @ORM\Column(type="string", length=255)
     * @SerializedName("title")
     * @Groups({"calendar"})
     */
    private $newName;

    public function getOldName(){
        return $this->$oldName;
    }

   public function setOldName($oldName){
       $this->oldName = $oldName;
       return $this
   }

   public function getNewName(){
       return $this->newName;
   }

   public function setNewName($newName){
       $this->newName = $newName;
       return $this
   }

note that the old get and set method are not deleted by the script
note as well that in your specific case of photosi, symfonyguess that the "i" is a plural mark and look for addPhotosus() methods

For the edit it looks very unclear and has nothing to do with the first question. Consider reading : doc on collectionType


text:
Q: Show different content based on option class, not value in a web page i have various forms like this:

<form action="" method="post">

 <input type="text">

 <select name="a">
  <option class="hide-all">Choose</option>
  <option class="show-link">Show link</option>
  <option class="show-submit">1</option>
  <option class="show-submit">2</option>
 </select>

 <input class="hidden show-if-class-show-submit-selected" type="submit">Submit form</form>
 Link

</form>

How can i show the submit button or the link based only on option class not on value optoin, i must use only class not ids....:). Thank you!

A: Check the change event of the select element. (also add a class to identify the elements involved so you can hide them again once you change the option)

$(function() {

  $('select').on('change', function() {
    var option = $(this).find(':selected'),
      relatedClass = option.attr('class');

    $(this).closest('form')
      .find('.select-target')
      .addClass('hidden')
      .filter('.' + relatedClass)
      .removeClass('hidden');
  });

});
.hidden {
  display: none;
}

<form action="" method="post">

  <input type="text" />

  <select name="a">
    <option class="hide-all">Choose</option>
    <option class="show-link">Show link</option>
    <option class="show-submit">1</option>
    <option class="show-submit">2</option>
  </select>

  <input class="hidden show-submit select-target" type="submit" value="Submit form">
  Link

</form>

A:

document.querySelector('select').addEventListener('change',function(){
    var selected = this.options[this.selectedIndex];
    document.querySelector('.show-if-class-show-link-selected').style.display = selected.className === 'show-link' ? '' : 'none';
    document.querySelector('.show-if-class-show-submit-selected').style.display = selected.className === 'show-submit' ? '' : 'none';
});
<form action="" method="post">

 <input type="text">

 <select name="a">
  <option class="hide-all">Choose</option>
  <option class="show-link">Show link</option>
  <option class="show-submit">1</option>
  <option class="show-submit">2</option>
 </select>

 <input class="hidden show-if-class-show-submit-selected" type="submit">Submit form</form>
 Link

</form>


text:
Q: Displaying what `history` line is current in bash prompt What formatting character needs to be added to a bash prompt to indicate the most recent history item run (or the current command number if 1 could be added to the last history entry)?
My prompt string is this:
\[\033[33m\][\u@\[\033[1;31m\]\h]\]\033[0m {\W}\n\033[1;34m\]\w\]\033[0m >

Gives me the following display:
[user@host] {~}
~ >

User is in yellow, and the host is in red. The entry in brackets is the current directory, and the entry before the greater-than sign is the full pwd.
Can I append to the first line the current command number so I would have something like the following:
[user@host] {~} (nnn)
~ >

where (nnn) is the current (or just processed) command number, as shown when running history?

A: From the PROMPTING section of the bash man page:
\!     the history number of this command
\#     the command number of this command

and further down:

The command number and the history
  number are usually different: the
  history number of a command is its
  position in the history list, which
  may include commands restored from the
  history file ..., while the command
  number is the position in the sequence
  of commands executed during the
  current shell session.

If you want the last command number, you could wrap the number in an arithmetic evaluation like this:
export PS1='last cmd num: $((\# -1)), this num: \# '


text:
Q: Exclude file when upload directories I have written a simple shell script which uses ncftpput to recursively upload all directories in a local directory to a remote directory. My shell script, upload.sh is placed in this local directory and I would like to exclude it from the upload. Is there any way to do this?
ncftpput -R -v -u myUsername -p myPassword myAddress /remoteDir /localDir/*

I have tried doing it like this:
for i in `ls /localDir | grep -v upload.sh`; do
  ncftpput -R -v -u myUsername -p myPassword myAddress /remoteDir /localDir/$i
done

But directories with spaces will be considered two directories. E.g. "My Directory" will be considered:

*

*/localDir/My

*/localDir/Directory

A: You could use find to upload all other elements separately:

find /localDir -mindepth 1 -maxdepth 1 ! -name "upload.sh" -exec ncftpput -R -v -u myUsername -p myPassword myAddress /remoteDir {} \;

Skip the -exec and everything after it to just print the matching files and folders, for testing..

You could also look into redefining IFS in bash, or the equivalent in your shell, but that still will fail with file names containing e.g. newlines.
Of course, the simplest solution would be to not mix the uploader script with the data to be uploaded...

A: Which is why you should never parse the output of ls. Especially if you can do the same thing with a simple wildcard.

#!/usr/bin/env bash

for i in /localDir/*; do
    [[ "$i" = */upload.sh ]] && continue
    ncftpput -R -v -u myUsername -p myPassword myAddress /remoteDir "$i"
done


text:
Q: How can I group categorical variable that also meets another criteria in R? DPLYR? I have a task that I can't solve. My goal is to be able to figure out how many "families" have children (under 18). I only need the sum of unique familyids and I've tried doing it in R and Excel and can't figure it out.
In my data I have four families and my data is saved on a client level.
data <- data.frame(

  "FamilyID" = c(10,10,10,11,11,11,12,12,13,13),
  "ClientID" = c(101,102,103,111,112,113,121,122,131,132),
  "Age" = c(26,1,5,35,34,1,54,60,17,21)
)

My goal is to have something like this
Metric                             Count
Families w/ Children                3
Families w/out Children             1

In my actual dataset I have thousands of families so I really appreciate ant help.
How can I do this with dplyr?

A: library(tidyverse)
counts <- data %>%
  group_by(FamilyID) %>%
  summarise(number_of_children = sum(Age<= 18), number_of_adults = sum(Age > 18)) %>%
  ungroup()

final <- counts %>%
  summarise("Families w/ children" = sum(number_of_children > 0), "Families w/o children" = sum(number_of_children < 1)) %>%
  gather() %>%
  rename("Metric" = key, "Count" = value)

A: You can try something like this:
data2 <- data %>% group_by(FamilyID) %>%
   mutate(children=sum(Age<18)) %>% mutate(children=ifelse(children>=1,1,0))
data2 %>% group_by(children) %>% summarize(n_distinct(FamilyID))

which shows how many distinct Family IDs correspond to 0 children, and how many correspond to at least 1 child.

A: One option is to use any to distinguish which families have children TRUE/FALSE, followed by dplyr::count
library(dplyr)

data %>%
  group_by(FamilyID) %>%
  summarize(have_children = any(Age < 18)) %>%
  count(have_children)

#------
  have_children     n
  <lgl>         <int>
1 FALSE             1
2 TRUE              3


text:
Q: Specifying % in href causing issue in IE As a business requirement i want anchor tag with % in the href.For eg
href="abc/a% bc.txt target="_blank"
This works in Chrome but it doesn't work in IE.
Can anybody help me in resolving this IE issue?
Any help will be highly appreciated.
Cheers,
Sajesh Nambiar

A: Use escaped version of "abc/a% bc.txt" string:
href="abc/a%25%20bc.txt"


text:
Q: Does anybody have experience with highfrequency R package? For the life of it I can't get this package to work with my own data. Is it essential to use the convert and TAQload to use your own data with this package? I would like to get in touch with someone that got experience with this and got it working. I have sent e-mails to both authors but no reply so far..

A: You do not need to use the convert code in case you have a premeditated setup that provides data into .xts files. Kris Boudt et al (n.d) quote "highfrequency provides functionality to convert raw data from several data providers into xts objects".
Check also this topic for further reference.
Bibliography:
Boudt, K., Cornelissen, J. and Payseur, S. (no date) Highfrequency: Toolkit for the analysis of highfrequency financial data in R. Available at: https://r-forge.r-project.org/scm/viewvc.php/checkout/pkg/highfrequency/inst/doc/highfrequency.pdf?revision=37&root=highfrequency&pathrev=38 (Accessed: 14 July 2016).


text:
Q: variatons on the standard Basis of $\Bbb R^n$
let n $\ge$ 2. For all $i=1,...n$ we denote $v_i$ as the vector in $\Bbb R^n$ where $v_i := (1,...,0,...,1)$. Show that $(v_1,...,v_n)$ is a basis of $\Bbb R^n$.

So this is a standard Basis, but with 0's in the places of the 1's and the other way around too.
My attempt at solving this:
I must show that
$$\lambda_1 \begin{pmatrix}
            0 \\
            \vdots \\
            1 \\
            \vdots \\
            1\\
            \end{pmatrix}
+...+ \lambda_i \begin{pmatrix}
            1 \\
            \vdots \\
            0 \\
            \vdots \\
            1\\
            \end{pmatrix}
+...+ \lambda_n \begin{pmatrix}
            1 \\
            \vdots \\
            1 \\
            \vdots \\
            0\\
            \end{pmatrix}
=           \begin{pmatrix}
            \ell_1 \\
            \vdots \\
            \ell_i \\
            \vdots \\
            \ell_n\\
            \end{pmatrix} $$
for all permutations of $\ell_1,...,\ell_n \in \Bbb R$. (in other words, the span of such vectors is $\Bbb R^n$)
I can create a new vector $w:= v_1+...+v_n=\begin{pmatrix}
            n-1 \\
            \vdots \\
            n-1 \\
            \vdots \\
            n-1\\
            \end{pmatrix}$
And so, with Steinitz's theorem we have
$$span(v_1,...v_n)=span(v_1,...,v_n,w) $$
Which, according to my intuition, should make things easier, but I don't know how to proceed from here. Am I on the right track? And then how do I go on to show that these family of vectors is linearly independent?

A: It suffices to show that $v_1, ..., v_n$ are linearly independent. You can use that method to get easier  to work with-vectors, for example,  you can try to prove $\{v_1, v_2 - v_1, ..., v_n - v_1\}$ is linearly independent.


text:
Q: DataBase connectivity in wordpress In WordPress how to store the data submitted from a form to a database through php file? I used many plugins but still can't find the solution

A: for inserting any data from wordpress form to wordpress database you need to do this by manually code.
create a new file in wordpress theme template and use wp insert query on this page.
currently we are developing a plugin for custom db insert in to database from admin, very soon we will upload it in wordpress free plugin list.


text:
Q: Affecting Child CSS Through Code Ok so I'm trying to set an unordered list from display none to block on a button click. I've set the css like so;
#ErrorDiv li{ color:#9a005a; font-weight:bold; display:none;}

So all my ListItems within my ErrorDiv don't display. Problem is, how do I display them then on a button click? I've tried in my code;
ErrorDiv.Style.Add("Display", "block")

But obviously this only the ErrorDiv and not the children ListItems. I've also tried calling javascript functions but that was just a bit of a headache. I imagine there must be a simple way I can affect this one style property for the child elements?
Just to be clear, it's not just button click -> Display. There's some work that goes on server side before the Display.

A: you should try something like this.
     Protected Sub Button1_Click(sender As Object, e As EventArgs)
     Me.ErrorDiv.Attributes.Add("style", "display:block;")
     End Sub

I hope this works for you.

A: Include the jquery framework in your page and then use the click event
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>

<script>
$(function(){
    $('#ID').click(function(){
        $('#ErrorDiv li').css({'display':'block'});
    });
});
</script>


text:
Q: Finger Draw on image is not working I want to scribble on image with finger(on image not on white background) and I am using this code to draw on image.
it draw on image but when when i release the touch the draw disappear.
i think the problem is in crating canvas.
And also
The image that i load in large so only a portion of image is displayed. So how can i stretch and fit the full image in screen for drawing on it.
public class MyView extends View {
private ImageView image;
private Bitmap mBitmap;
private Canvas mCanvas;
private Path mPath;
private Paint mBitmapPaint;
private Paint mPaint;
private float mX, mY;
private final float TOUCH_TOLERANCE = 4;

public MyView(Context c,View v) {
    super(c);
    mPath = new Path();
    mBitmapPaint = new Paint(Paint.DITHER_FLAG);
    mPaint = new Paint();
    mPaint.setAntiAlias(true);
    mPaint.setDither(true);
    mPaint.setStyle(Paint.Style.STROKE);
    mPaint.setColor(0XFF000000);
    mPaint.setStrokeJoin(Paint.Join.ROUND);
    mPaint.setStrokeCap(Paint.Cap.ROUND);
    mPaint.setStrokeWidth(3);

    image=(ImageView) v.findViewById(R.id.my_image);
}

@Override
public void onSizeChanged(int w, int h, int oldw, int oldh) {
    super.onSizeChanged(w, h, oldw, oldh);

    // Scribbling on white background
//  mBitmap=Bitmap.createBitmap(w,h,Bitmap.Config.ARGB_8888);
//  mCanvas =new Canvas(mBitmap);

    // Scribbling on image
    mBitmap =  BitmapFactory.decodeResource(getResources(), R.drawable.batman);
    mBitmap= Bitmap.createBitmap( mBitmap.getWidth() ,mBitmap.getHeight(), mBitmap.getConfig());
    mCanvas =new Canvas(mBitmap.copy(Bitmap.Config.ARGB_8888, true));
}

@Override
public void onDraw(Canvas c) {
    //  c.drawBitmap(DrawingActivity.mBitmap, 0, 0, null);

    c.drawBitmap(mBitmap, 0, 0,mBitmapPaint);
    c.drawPath(mPath, mPaint);
}

@Override
public boolean onTouchEvent(MotionEvent e) {
    float x=e.getX();
    float y=e.getY();

    switch(e.getAction()){
    case MotionEvent.ACTION_DOWN:
        touchStart(x,y);
        invalidate();
        break;
    case MotionEvent.ACTION_MOVE:
        touchMove(x,y);
        this.invalidate();
        break;
    case MotionEvent.ACTION_UP:
        touchUp(x,y);
        invalidate();
    }

    return true;
}

private void touchUp(float x, float y) {
    mPath.lineTo(mX, mY);
    mCanvas.drawPath(mPath, mPaint);
    mPath.reset();
}

private void touchMove(float x, float y) {
    float dx= Math.abs(x-mX);
    float dy= Math.abs(y-mY);
    if(dx>=TOUCH_TOLERANCE && dy>=TOUCH_TOLERANCE){
        mPath.quadTo(mX, mY, (x+mX)/2, (y+mY)/2);
        mX=x;
        mY=y;
    }
}

private void touchStart(float x, float y) {
    mPath.reset();
    mPath.moveTo(x, y);
    mX=x;
    mY=y;
}

}
please help


text:
Q: Azure DevOps Build Pipeline Resource Authorization Issue I am trying to build a pipeline that build, deploy and configure an Azure Function. So far so now I have the following yaml:
trigger:
- none

pr:
- none

pool:
  vmImage: "windows-latest"

variables:
  group: my_variable_group //here I have the target Azure Function Information (Subscription, Resource Group, Function Name, etc.)
  buildPath: $(System.DefaultWorkingDirectory)/pipelines/maintenance
  buildConfiguration: 'Release'
  dotNetVersion: '6.0.x'
  output: 'output'
  project: '**/project.csproj'

steps:

- task: UseDotNet@2
  displayName: 'Use .NET Core SDK'
  inputs:
    packageType: 'sdk'
    version: $(dotNetVersion)

- task: DotNetCoreCLI@2
  displayName: 'Restore Packages'
  inputs:
    command: restore
    projects: $(project)

- script: |
    dotnet build --configuration $(buildConfiguration)
  workingDirectory: $(buildPath)
  displayName: 'Build'

- task: DotNetCoreCLI@2
  displayName: 'Publish'
  inputs:
    command: publish
    arguments: '--configuration $(buildConfiguration) --output $(output)'
    projects: $(buildPath)
    publishWebProjects: false
    modifyOutputPath: false
    zipAfterPublish: false

- task: ArchiveFiles@2
  displayName: 'Archive files'
  inputs:
    rootFolderOrFile: $(System.DefaultWorkingDirectory)/$(output)
    includeRootFolder: false
    archiveFile: $(System.DefaultWorkingDirectory)/build.zip

- task: PublishBuildArtifacts@1
  displayName: 'Publish Build Artifacts'
  inputs:
    PathtoPublish: $(System.DefaultWorkingDirectory)/build.zip
    artifactName: 'content-maintenance'
//Issues starts here. For this steps on I use the variables inside my_variable_group
- task: AzureFunctionApp@1
  displayName: 'Azure Function App Deploy'
  inputs:
    azureSubscription: $(Subscription)
    appType: functionApp
    appName: $(AppName)
    deployToSlotOrASE: true
    resourceGroupName: $(ResourceGroup)
    slotName: $(Slot)
    deploymentMethod: zipDeploy

- task: AzureAppServiceSettings@1
  displayName: 'Azure App Service Settings'
  inputs:
    azureSubscription: $(Subscription)
    appName: $(AppName)
    resourceGroupName: $(ResourceGroup)
    slotName: $(Slot)
    appSettings: |
     [
       {
         "name": "AzureWebJobsStorage",
         "value": $(AzureWebJobsStorage),
         "slotSetting": false
       },
       {
         "name": "VaultUri",
         "value": $(VaultUri),
         "slotSetting": false
       },
       {
         "name": "WEBSITE_CONTENTAZUREFILECONNECTIONSTRING",
         "value": $(WEBSITE_CONTENTAZUREFILECONNECTIONSTRING),
         "slotSetting": false
       },
       {
         "name": "WEBSITE_CONTENTSHARE",
         "value": $(WEBSITE_CONTENTSHARE),
         "slotSetting": false
       }
     ]

When I try to run my pipeline, the following error is displayed

There was a resource authorization issue: "The pipeline is not valid.
Job Job: Step AzureFunctionApp input azureSubscription references
service connection $(Subscription) which could not be found. The
service connection does not exist or has not been authorized for use.
For authorization details, refer to https://aka.ms/yamlauthz. Job Job:
Step AzureAppServiceSettings input ConnectedServiceName references
service connection $(Subscription) which could not be found. The
service connection does not exist or has not been authorized for use.
For authorization details, refer to https://aka.ms/yamlauthz."

I already check and both, my_variable_group and the service connection where the variable $(Subscription) have my pipeline added on Pipeline permissions section.
Do you know how should I address this? I know that the part that is failing is:
- task: AzureFunctionApp@1
  displayName: 'Azure Function App Deploy'
  inputs:
    azureSubscription: $(Subscription) <-- here

I am assuming that I can use a variable to set subscription instead of hardcoding it into the yaml.

A: It happens due to how the Azure DevOps expand the pipelines during execution:
https://learn.microsoft.com/en-us/azure/devops/pipelines/process/runs?view=azure-devops#process-the-pipeline

It also answers another common issue: why can't I use variables to resolve service connection / environment names? Resources are authorized before a stage can start running, so stage- and job-level variables aren't available. Pipeline-level variables can be used, but only those explicitly included in the pipeline. Variable groups are themselves a resource subject to authorization, so their data is likewise not available when checking resource authorization.

To workaround it, I create a local variable in the pipeline with the same name, $(Subscription) in your case, and hard code the service connection of the lowest environment (usually dev), so the validation will pass. Be sure to add the local variable before the variable groups, so in a later stage, when the pipeline expands the variable groups will be replaced by the correct value.


text:
Q: Open DevExpress MVC Grid in Edit Mode with Custom Edit Button I'm using the Devexpress MVC Grid and I've added two custom buttons (Edit & Copy) and I'm performing the operations. With copy button, I'm creating a new record with existing data and opening the grid in Add New Row Mode.
Following is the code:
@Html.DevExpress().GridView(grid =>
{
    grid.Name = "gvInformation";
    grid.SettingsDetail.AllowOnlyOneMasterRowExpanded = true;
   grid.SettingsEditing.Mode = GridViewEditingMode.EditForm;

    //Callback Events
    grid.CallbackRouteValues = new { Controller = "Case", Action = "InformationGridContent"};
    grid.SettingsEditing.AddNewRowRouteValues = new { Controller = "Case", Action = "AddInformationRecord" };
    grid.SettingsEditing.UpdateRowRouteValues = new { Controller = "Case", Action = "UpdateInformationRecord" };
    grid.SettingsEditing.DeleteRowRouteValues = new { Controller = "Case", Action = "DeleteInformationRecord" };
    grid.ClientSideEvents.BeginCallback = "BeginGridCallback";
    grid.BeforeGetCallbackResult = (sender, e) =>
    {
        MVCxGridView gridView = sender as MVCxGridView;
        if (isCopyRequired)
            gridView.AddNewRow();

        if (gridView.IsNewRowEditing)
        {
            gridView.SettingsText.CommandUpdate = Html.Raw("Add").ToHtmlString();
            gridView.SettingsText.CommandCancel = Html.Raw("Cancel").ToHtmlString();
        }

        if (!gridView.IsNewRowEditing)
        {
            gridView.SettingsText.CommandUpdate = Html.Raw("Update").ToHtmlString();
            gridView.SettingsText.CommandCancel = Html.Raw("Cancel").ToHtmlString();
        }
    };

        //Custom Copy Record Button
    var btnCopy = new GridViewCommandColumnCustomButton { ID = "btnCopy" };
    btnCopy.Text = "";
    grid.CommandColumn.CustomButtons.Add(btnCopy);

    //Custom Edit Button
    var btnEdit = new GridViewCommandColumnCustomButton { ID = "btnEdit" };
    btnEdit.Text = "";
    grid.CommandColumn.CustomButtons.Add(btnEdit);

    //Custom Button Events
    grid.ClientSideEvents.CustomButtonClick = "OnCustomButtonClick";
    grid.CustomActionRouteValues = new { Controller = "Case", Action = "CustomInformationRecord" };
    }

Client Side Events:
var buttonCommand;
function OnCustomButtonClick(s, e) {
    buttonCommand = e.buttonID;
    s.PerformCallback();
}

function BeginGridCallback(s, e) {
    //Grid Edit Button Click Event
    if (buttonCommand === "btnEdit") {
        e.customArgs["buttonCommand"] = "btnEdit";
    }

    //Grid Copy Button Click Event
    if (buttonCommand === "btnCopy") {
        e.customArgs["buttonCommand"] = "btnCopy";
    }
}

It is working fine for Copy button and opening the Grid in Edit Form Mode but when Edit Button is clicked it is not opening the Grid in Edit Mode. Is there something I'm missing?


text:
Q: VueJs FrontEnd instance with Laravel BackEnd Api wire with Nginx in Centos so I have the following server blocks for nginx and I am trying to add a domain to it so I can install it live with google authentication.  These servers blocks work with the IP but I am trying to get it to work with the domain.   Any thoughts of what I am doing wrong?
VueJs FrontEnd Server block
server {
        listen 3001;
        server_name domain.com;//an example
        keepalive_timeout 60;
        index index.html;

        location / {
                root /var/www/html/app/front/dist;

        }
}

Laravel 8 BackEnd Server Block
server {
    listen       8001;
    server_name  domain.com;//example

    index index.php;
    autoindex on;

    root /var/www/html/app/api/public;

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    location ~ \.php$ {
        try_files $uri /index.php =404;
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_pass unix:/run/php-fpm/php-fpm.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME  $document_root$fastcgi_script_name;
        include fastcgi_params;
    }
}

If I make a call at domain.com/api, I get a 404 Not Found


text:
Q: Getting WrappedAttributeError when logged into website with djangorestframework freshly installed I have a website that has a user login function and works fine. I had to install django rest framework and followed the very basic instructions on the first page. Everything seems fine and rest framework works fine, but as soon as I log into my django and go back to rest framework it breaks with this error:
WrappedAttributeError at /rest-api/
'CSRFCheck' object has no attribute 'process_request'

I have no idea why this happens or what it means. Searching didn't help.
Edit: Exception location:
python3.6/site-packages/rest_framework/authentication.py in enforce_csrf, line 140

A: I have created an issue to report this : https://github.com/encode/django-rest-framework/issues/6305
You can see a fix here if you need a patch rapidly : https://github.com/encode/django-rest-framework/pull/6306/files
More details
In the release of Django Rest Framework 3.9 a new function call was introduced in the authentication process:
check = CSRFCheck()
check.process_request(request)

CSRFCheck is a class imported directly from Django. The process_request method of the CSRFCheck class was only added in the Django 1.11.6 version (and keeped after that). Therefore the release 3.9.0 of Django Rest Framework is not fully compatible with Django 1.11.x but only with 1.11.6 and upwards. Many solutions exists to this issue:

*

*Upgrade to Django 1.11.6 or upward if possible

*Fork Django Rest Framework and include the following patch in the enforce_csrf method of the SessionAuthentication class (rest_framework/authentication.py):
from django import VERSION as django_version

if tuple(django_version[:3]) < (1, 11, 6):
    csrf_token = check._get_token(request)
    if csrf_token is not None:
        request.META['CSRF_COOKIE'] = csrf_token
else:
    check.process_request(request)

This patch will work for any version of Django from 1.11.x and upward (at least Django 2.0 and 2.1).
Hopefully my patch will be merged and release in version 3.9.1 of Django Rest Framework. Also keep in mind that version 3.9.0 is probably one of the last release to support Django 1.11.

A: This seems really similar to this issue that was fixed and in the 3.8.2 release of DRF.
These are the things I would try:

*

*Make sure your Django is updated to at least 1.11 and DRF is updated to at least 3.8.2.

*Make sure you added 'rest_framework' to the bottom of your INSTALLED_APPS. This is easy to miss in the installation tutorial.

*Make sure your MIDDLEWARE in settings.py is relatively untouched, if this is a new project. At least make sure django.middleware.csrf.CsrfViewMiddleware is there and if there is any non-Django middleware above it, try moving it as far down as possible.

If none of this works, you can try truncating your django_session table, assuming you are using session authentication. I don't think this will help, but it's worth trying.


text:
Q: What is support for an end-to-end and peer-to-peer transparent clock? In the datasheet of LAN9353, the description states that it supports "supports end-to-end and peer-to-peer transparent clocks"
Can someone tell me what is the meaning of this?

A: Your quote omits information what it refers to. Here is better quote from the marketing material:

IEEE 1588v2 is supported via the integrated IEEE 1588v2 hardware time stamp unit, which supports end-to-end and peer-to-peer transparent clocks.

It just means that the chip has built in hardware features to support the IEEE 1588v2 protocol over Ethernet.


text:
Q: Difference between Dialogflow V1 API (Api.ai) and Dialogflow V2 API (Api.ai)? Difference between  Dialogflow V1 API (Api.ai) and Dialogflow V2 API (Api.ai) ?

A: https://dialogflow.com/docs/reference/v1-v2-migration-guide
If you were using V1 for fulfillment or the API, the concepts are nearly all the same. But many names (and fields in the JSON) have changed.
V2 adds new ways to use the API, including directly by voice, and an Enterprise level version of the product.


text:
Q: Why does it say 'TypeError: Cannot read property 'appendChild' of undefined' when it is defined? I defined a variable, and I want to append a child to it, but for some reason, I get an error that says the value is undefined, so I can't use appendChild().
Since I found some sources say that it's because the assets have not loaded yet, I tried using window.onload, but I really want my function to run when the button is clicked.
  document.getElementById("calc").onclick = function calculate(){
        var rate = +document.getElementById("rate").value/100;
        var years = +document.getElementById("years").value;
        var principal = +document.getElementById("principal").value;

        var i = 0;

        while(i < years){
          var afterRate = principal * rate;
          var totalAmount = principal += afterRate;
          var interestValue = document.createElement("div");
          var division = document.getElementById('divis');

          interestValue.style.color = "white";
          interestValue.style.fontFamily = "futura";
          interestValue.innerHTML = totalAmount;
          document.division.appendChild(interestValue);

          var lastButton = document.getElementById("last");
          var clearButton = document.getElementById("clear");
          var roundButton = document.getElementById("round");

          i++
        }
    }

I thought that the interestValue in my function would be added to the div I defined, but instead, I got the message, 'TypeError: Cannot read property 'appendChild' of undefined.'

A: Posting answer for this, same as what @Jaromanda X explained in comment.
  document.getElementById("calc").onclick = function calculate(){
    var rate = +document.getElementById("rate").value/100;
    var years = +document.getElementById("years").value;
    var principal = +document.getElementById("principal").value;

    var i = 0;

    while(i < years){
      var afterRate = principal * rate;
      var totalAmount = principal += afterRate;
      var interestValue = document.createElement("div");
      var division = document.getElementById('divis');

      interestValue.style.color = "white";
      interestValue.style.fontFamily = "futura";
      interestValue.innerHTML = totalAmount;
      division.appendChild(interestValue); // Removed document

      var lastButton = document.getElementById("last");
      var clearButton = document.getElementById("clear");
      var roundButton = document.getElementById("round");

      i++
    }
}

document.division is not defined anywhere in your code - perhaps you
  meant division.appendChild(interestValue); not
  document.division.appendChild(interestValue);


text:
Q: Django not using updated urls.py - returning 404 on www.site.com/page with outdated list I am very new to django and beginning to understand some of the framework however view-route binding is confusing me
There is a persistent issue that when I try to visit any url except for the homepage and /admin I receive a 404, including routes I have declared in my project's urls.py file
also i am following this mdn tutorial
project urls.py
"""trends URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/2.2/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include
from django.views.generic import RedirectView
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    path('admin/', admin.site.urls),
    path('articles/', include('articles.urls')),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

app named 'articles' urls.py
from django.urls import path
from . import views

urlpatterns = [
    path('', views.index, name='index'),
]

app named 'articles' views.py
from django.shortcuts import render
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the articles index.")

and here is the 404 page I receive

I know this is becoming very long but there is one more odd thing, when I refresh the 404 page, it will toggle between showing me the above screenshot and sometimes show me an old route which is no longer in the urls.py like this

this is on an nginx server with gunicorn, and restarting the nginx service does not solve the issue

A: In your projects urls.py you have defined
path('articles/', include('articles.urls')),

So by going to YOUR_URL/articles will not give a valid response. Instead try going to YOUR_URL/articles/ or change your path to
path('articles', include('articles.urls')),

A: Stumbled upon this SO post which lead me to the idea to restart gunicorn and that solved my problem so try running
sudo service gunicorn restart

should fix your problems


text:
Q: Как убрать ложные срабатывания с input Есть input для поиска товаров по названию
Есть обработка нажатий onChangeSearch в нем мы убираем все лишнее, оставляя только нужные нам символы
Есть функция load она отправлять запрос на сервер с текстом из поля(Для тестов, сейчас там просто вывод в консоль)
Проблема заключается в том, что при вводе любого запрещенного символа у нас вызывается функция load и идет запрос на сервер, возможно ли сделать вызов функции load только при условии, что введен нужный нам символ?

class TodoApp extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
     filter_search: ''
    }
    this.onChangeSearch = this.onChangeSearch.bind(this);
  }
  onChangeSearch(e) {
    let regexp = /[^a-zа-яё,._\-\/=\!\?0-9\s]/gi;
    let value = e.target.value;
    value = value.replace(/^\s/, '');
    value = value.replace(/  /, ' ');
    value = value.replace(regexp, '');
    value = value.substr(0, 25);
    this.setState({
      filter_search: value
    });
    this.load();
  }
  load() {
   console.log('1');
  }

  render() {
    return (

        <input
          value = {this.state.filter_search}
          onChange = {this.onChangeSearch}
        />

    )
  }
}

ReactDOM.render(<TodoApp />, document.querySelector("#app"))

A: Нашел решение, не знаю на сколько это правильное решение, но свою функцию выполняет
В чем суть: добавил новую переменную filter_search_old, добавил в onChangeSearch проверку на совпадение значения в переменной filter_search_old и полученного значения из input если они не совпадают, мы вызываем функцию load и записываем новое значение в filter_search_old, если они совпали, значит текст в поле не изменился.

class TodoApp extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
     filter_search: '',
      filter_search_old: ''
    }
    this.onChangeSearch = this.onChangeSearch.bind(this);
  }
  onChangeSearch(e) {
    let regexp = /[^a-zа-яё,._\-\/=\!\?0-9\s]/gi;
    let value = e.target.value;
    value = value.replace(/^\s/, '');
    value = value.replace(/  /, ' ');
    value = value.replace(regexp, '');
    value = value.substr(0, 25);
    this.setState({
      filter_search: value
    });
    if(this.state.filter_search_old != value) {
      this.load();
      this.setState({
        filter_search_old: value
      });
    }
  }
  load() {
   console.log('1');
  }

  render() {
    return (

        <input
          value = {this.state.filter_search}
          onChange = {this.onChangeSearch}
        />

    )
  }
}

ReactDOM.render(<TodoApp />, document.querySelector("#app"))
body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

#app {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  transition: all 0.2s;
}

input {
  margin-right: 5px;
}


text:
Q: How do I get a user's profile picture path on c++ (winapi) I'm trying to make a ui like in https://www.reddit.com/r/unixporn/comments/p7oloc/13gaps_my_first_complete_rice_on_i3
I know how to get the active wallpaper with registry.
(HKEY_CURRENT_USER\Control Panel\Desktop\WallPaper)
I'd like to get the active profile picture directory.
Thank you for your time.


text:
Q: Despite using isset() still geting Notice: Undefined variable: ScdTime in C:\wamp\...\AppointRequest2.php on line 25 I'm also getting this error:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ' , , '',128745)' at line 1

I've already used isset() and !empty() functions. All my variables are being declared before being used. I've also searched a lot and still couldn't solve this problem. PLease please help me. I'm stuck here. Any help will be of great use to me. Thanks.
Here's the code:
<?php

$authorized = false;
session_start();
include('config.php');

if(isset($_SESSION['crnumbers']) && isset($_SESSION['passwords']))
{
    $authorized = true;

    if(isset($_POST["submit"]) && !empty($_POST["submit"]))
    {
        $ScdDate = mysql_real_escape_string($_POST['ScdDate']);
        $ScdMonth = mysql_real_escape_string($_POST['ScdMonth']);
        $ScdYear = mysql_real_escape_string($_POST['ScdYear']);
        $DName = mysql_real_escape_string($_POST['DName']) ;
        $ScdTime = mysql_real_escape_string($_POST['ScdTime']);
    }

    $crnumber = mysql_real_escape_string($_SESSION['crnumbers']);

    $sql = mysql_query("INSERT INTO schedule(ScdDate,ScdMonth,ScdYear,ScdTime,crnumber,DName)VALUES($ScdDate, $ScdMonth, $ScdYear, '$ScdTime', $crnumber, '$DName')");

    if(!$sql)
    {
        die('There is some error. Damn it! ' .mysql_error());
    }

    header("location: http://localhost/Alok/Health%20Care%20Project\GUI\patientGUI2.php");

}

else if(!$authorized)
{
    header("location:");
    exit();
}
?>

A: The problem, as it seems, is that the variables used in the INSERT query aren't containing valid data and might be set to empty and therefore breaking the INSERT query.
There are 2 options that you can use here:
A] Try to use the below assignment syntax; it sets the given value if it is not-empty otherwise sets it to 0
$ScdDate = (!empty($_POST['ScdDate'])) ? mysql_real_escape_string($_POST['ScdDate']) : 0;
$ScdMonth = (!empty($_POST['ScdMonth'])) ? mysql_real_escape_string($_POST['ScdMonth']): 0;
$ScdYear = (!empty($_POST['ScdYear'])) ? mysql_real_escape_string($_POST['ScdYear']) : 0;
$DName = (!empty($_POST['DName'])) ? mysql_real_escape_string($_POST['DName']) : '';
$ScdTime = (!empty($_POST['ScdTime'])) ? mysql_real_escape_string($_POST['ScdTime']) : '';

B] Enclose all your values in single-quotes in the query
$sql = mysql_query("INSERT INTO schedule(ScdDate,ScdMonth,ScdYear,ScdTime,crnumber,DName)VALUES('$ScdDate', '$ScdMonth', '$ScdYear', '$ScdTime', '$crnumber', '$DName')");

Hope the above helps!
By the way, the error given in the question isn't perhaps in sync with the query; the last value in the query is $DName enclosed in single quotes but the last value in the error isn't enclosed in single-quotes. I might be incorrect though ;-)

A: You're checking $_POST["submit"] existence, but not $_POST["ScdTime"]'s. That's why the notice remains. Concerning your MySQL error, the comments let on your question quite answer it.
You need to use isset() on every variable that might be used later in the code :)
<?php
if(isset($_POST["submit"])) &&
   isset($_POST['ScdDate']) &&
   isset($_POST['ScdMonth']) &&
   isset($_POST['ScdYear']) &&
   isset($_POST['DName']) &&
   isset($_POST['ScdTime']))
      // We're good!

A: The correct way would be:
if(array_key_exists('crnumbers', $_POST)) {}
Also make sure you check ALL array keys. That's causing the second error.


text:
Q: Hamilton Graph and Complete Tripartite 1) Consider the complete tripartite graph $K_2,_3,_n$ for $n \ge 3$. Determine for what values of n the graph $K_2,_3,_n$ has a Hamilton path, and for what values of n the graph has a Hamilton cycle.
2) Consider the complete tripartite graph $K_2,_m,_n$ for $m \ge 2$ and $n \ge m$. Determine when $K_2,_m,_n$ has a Hamilton and when it has a Hamilton cycle.
I need help on how to go about it. I tried countless number to times on how to set the problem right but to no avail. I would be glad someone offers me assistance on how to answer this problem.

A: Consider the general tripartite case $G = K_{l,m,n}$ for $1 \leq l \leq m \leq n$. I will show that $K_{l,m,n}$ has a Hamiltonian cycle if and only if $l + m \geq n$.
Suppose $G$ has a Hamiltonian cycle $C$. Then $2n$ edges of $C$ are incident with vertices in the partite set of size $n$, and all $l+m+n$ edges of $C$ are incident with vertices in either the partite set of size $l$ or the partite set of size $m$, or both. Thus $2n \leq l+m+n$, and $l+m \geq n$. We now need only show that there is a Hamiltonian cycle when $l+m \geq n$.
Ore's Theorem states that if $d(u) + d(v) \geq |G|$ for all $u,v \in V(G)$ with $uv \not \in E(G)$, then $G$ has a Hamiltonian cycle. For $K_{l,m,n}$, the only non-adjacent vertices are within the partite sets, so Ore's criterion will be satisfied if each of the following is true:
$2(l + m) \geq l + m + n$
$2(l + n) \geq l + m + n$
$2(m + n) \geq l + m + n$
But since $l + m \leq l + n$ and $l + m \leq m + n$, these will be satisfied if $2(l+m) \geq l + m + n$ and thus $l + m \geq n$. So by Ore's Theorem, if $l + m \geq n$, then $G$ has a Hamiltonian cycle.
For the Hamiltonian path, you can show that $G$ has a Hamiltonian path if and only if the graph $H$ created by adding an extra vertex to $G$ adjacent to all vertices of $G$ has a Hamiltonian cycle. Then by essentially the same argument used above, you can show $H$ has a Hamiltonian cycle if and only $l + m \geq n-1$, and thus $G$ has a Hamiltonian path if and only if $l + m \geq n-1$.

A: For (1), let's use Ore's Theorem. It states if for every $u, v \in V(G)$ are not adjacent and $d(u) + d(v) \geq n$, then $G$ has a Hamiltonian Circuit. So since $K_{2, 3, m}$ is complete, the only non-adjacent vertices are in each partition. This gives us:
$2(3 + m) \geq 5 + m$, for the elements in the partition of two vertices.
$2(2 + m) \geq 5 + m$, for the elements in the partition of three vertices.
$2(5) \geq 5 + m$ for the elements in the new partition of $m$ vertices.
And so we get $m \geq -1$, $m \geq 1$, and $m \leq 5$ when solving. So $m \in \{1, 2, 3, 4\}$ will answer your question.
Now for a Hamiltonian Path, you want to determine if adding an extra vertex incident to all other vertices will create a Hamiltonian cycle. So $G$ has a Hamiltonian path if and only if $G + K_{1}$ has a Hamiltonian Circuit.
This should get you going in a good direction.


text:
Q: How does openCVs ORB achieve scale invariance? After scrolling through the openCVs ORB implementation
 https://github.com/opencv/opencv/blob/master/modules/features2d/src/orb.cpp
and reading the original paper: ORB achieves scale invariance by a scale pyramid, to quote the paper: " We employ a scale pyramid of the image, and produce FAST features (filtered by Harris) at each level in the pyramid"
What I do not understand is how all the features described at each level in the image pyramid combine to give back only  the features in the original image (not subsampled image i.e. 0th level pyramid) that it finds to be the invariant features? So far as I understand the code finds at each level in the pyramid features and give them a description but I do not see/understand if any collapse of the pyramid to the original image even happens, which to me looks as if it needs to be there for comparison of invariant features between images.


text:
Q: Spring Kafka: @KafkaListener - Message , Generic type "T" not getting resolved in abstract impl Trying to create abstract class AbstractTestKafka for @KafkaListener with generic type in Message<T>.
In concrete class that extends AbstractTestKafka, if we provide type T, MessagingMessageConverter not able to resolve the type T.
Getting -
Caused by: java.lang.ClassCastException: class java.util.LinkedHashMap cannot be cast to class com.demo.Cat (java.util.LinkedHashMap is in module java.base of loader 'bootstrap'; com.demo.Cat is in unnamed module of loader 'app')
    at com.spring.kafka.poc.test.TestKafkaImpl.processNew(TestKafkaImpl.java:13) ~[classes/:na]

Code:
public ConcurrentKafkaListenerContainerFactory<K, V> kafkaListenerContainerFactory() {
   ConcurrentKafkaListenerContainerFactory<K, V> factory =
       new ConcurrentKafkaListenerContainerFactory<>();
   initialiseFactory(factory);
   return factory;
 }

 private void initialiseFactory(ConcurrentKafkaListenerContainerFactory<K, V> factory) {
   factory.setConsumerFactory(consumerFactory());
   factory.setAutoStartup(false);
   factory.getContainerProperties().setAckMode(ContainerProperties.AckMode.MANUAL);
   factory.setBatchListener(true);
   factory.setConcurrency(1);

 //Converter
  factory.setMessageConverter(new BatchMessagingMessageConverter(new JsonMessageConverter()));

 }

  public ConsumerFactory<K, V> consumerFactory() {
     consumerCofigMap = getConsumerConfigs();
     return new DefaultKafkaConsumerFactory<>(consumerCofigMap);
   }

AbstractTestKafka
public abstract class AbstractTestKafka<T> {

     @KafkaListener(id = "newConsumer",topics = "topic1", containerFactory = "kafkaListenerContainerFactory",autoStartup = "true")
    public void listen(List<Message<T>> messages, Acknowledgment ack){
        Flux.fromIterable(messages)
                .log()
                .flatMap(
                        message -> {
                            return processNew(message);
                        })
                .subscribeOn(Schedulers.boundedElastic())
                .blockLast(Duration.ofMillis(6000));
        ;
        ack.acknowledge();
    }

    public abstract Mono<Object> processNew(Message<T> msg) ;

}

Concrete class
public class TestKafkaImpl extends AbstractTestKafka<Cat> {
    @Override
    public Mono<Object> processNew(Message<Cat> msg) {
        Cat cat=msg.getPayload();
        return Mono.empty();
    }
}

A: This will not work; the framework can't infer the generic type T.
You would need to use a Kafka deserializer to create the Cat object instead of relying on the framework's inferred type.
EDIT
Since there is no type information, the converter is converting to a Map.
There are several solutions, including:

*

*use a JsonDeserializer with a type function: https://docs.spring.io/spring-kafka/docs/current/reference/html/#serdes-type-methods

*use a custom message converter that overrides the inferred type:
@SpringBootApplication
public class So75030774Application {

    public static void main(String[] args) {
        SpringApplication.run(So75030774Application.class, args);
    }

    @Bean
    NewTopic topic() {
        return TopicBuilder.name("so75030774").partitions(1).replicas(1).build();
    }

    @Bean
    ApplicationRunner runner(KafkaTemplate<String, String> template) {
        return args -> {
            template.send("so75030774", "{\"bar\":\"baz\"}");
        };
    }

    @Bean
    MessagingMessageConverter converter() {
        return new JsonMessageConverter() {

            @Override
            protected Object extractAndConvertValue(ConsumerRecord<?, ?> record, Type type) {
                return super.extractAndConvertValue(record, Foo.class);
            }

        };
    }

}

abstract class AbsListener<T> {

    @KafkaListener(id = "so75030774", topics = "so75030774")
    void listen(Message<T> in) {
        process(in);
    }

    public abstract void process(Message<T> msg);
}

@Component
class ConcreteListener extends AbsListener<Foo> {

    @Override
    public void process(Message<Foo> msg) {
        System.out.println(msg.getPayload().getClass());
        System.out.println(msg);
    }

}


text:
Q: Text highlighting cuts off on top I am new to web design. I'm currently working on my school's website, but I encountered a problem. When I highlight a text in .wrap, the highlighting is cut off on the top. Why does this occur and how can I fix it? Thank you for your support.
Test Site: http://whileloop.x10.mx/test/

A: The highlight is cutting off at the top because your line-height is set to 70% on the .wrap class. If you keep it at the default and adjust the layout properly (setting the margin-top of the h3 for example if that is what you're after), it will highlight normally.

A: try change .wrap with this
    .wrap {
    color: #313131;
    float: left;
    line-height: 70%;
    margin-left: 1em;
    margin-right: 1em;
    margin-top: 3em;
    width: 100%;}


text:
Q: jquery ajax to php script not saving data I have the following jQuery ajax call to a php script:
actualHtml = $('div').html(); // could this line be causing an issue?
$.ajax({
        type: 'POST',
        url: 'save-html-css-action.php',
        data: {
           'htmlTextToSave': htmlTextToSave,
           'actualHtml': actualHtml,
           'userId':userId
        },
        success: function(msg){
            alert(msg);
        }
});

php:
$htmlCssToSave = $_POST['htmlTextToSave'];
$userId = $_POST['userId'];
$actualHtml = $_POST['actualHtml'];

$mysqli = new mysqli($servername, $sqlusername, $sqlpassword, $dbname);

/* check connection */
if (mysqli_connect_errno()) {
    //printf("Connect failed: %s\n", mysqli_connect_error());
     echo "Connection failed: ".mysqli_connect_error();
    exit();
}

    $mysqli->query("INSERT INTO user_saved_data (user_html_css_code, dd_id, actual_html) values ('".$htmlCssToSave."',".$userId.",'".$actualHtml."')");
    echo "success";

    /* close connection */
    $mysqli->close();

but when I check the database, the data isn't there. Am I doing something wrong in the jquery/php combo (meaning the ajax call)? I'm getting a javascript "success" alert, so it's hitting the script, but I'm not sure why the info isn't being inserted.
The table datatypes are medium text for both the htmlcsstosave and the actualhtml columns, and int for userid (not the primary key, this is a foreign key to another table)
so I added a an error alert and this is the output

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'margin-0'>
                            <head>
                            </head>
                            <body cl' at line 1

A: As we discussed, the issue is with escaping and sanitizing data. If you used prepared statements, it will handle it for you. let's have a look at how that would work:
Prepare the statement:
$stmt = $mysqli->prepare("INSERT INTO user_saved_data (user_html_css_code, dd_id, actual_html) values (?,?,?)");

Bind your parameters:
$stmt->bind_param('sis', $htmlCssToSave, $userId, $actualHtml);

Then execute your statement:
$stmt->execute();

Then you should be good to go. The prepared statement should handle the data sanitization for you now.
Resouces:

*

*mysqli prepare

*mysqli bind_param

*mysqli execute

A: Can you post the CREATE TABLE statement for the user_saved_data table?
In general, I'd recommend just tracing it through and see where the data gets lost.
For example, can you echo the query you are generating and run in manually in MySQL? You may have a syntax error in the SQL being generated...


text:
Q: Suppose $X$ is compact and $Y$ is Hausdorff show that $f$ is a closed map I have seen a few other proofs about this. I have written my own, and I just want to verify the error in my own logic.
The question states: Show that if $f:X\rightarrow Y$ is continuous, where $X$ is compact and $Y$ is Hausdorff, then $f$ is closed map (that is, $f$ caries closed sets to closed set).
Let $U$ be a closed set in $X.$ This implies that $U$ is compact since a closed subspace of a compact space is compact (Theorem 26.2 in Munkres). Since the image of a compact space is compact under a continuous map (by Theorem 26.5) we have that $f(U)$ is compact. Since every compact subspace of a Hausdorff space is closed (Theorem 26.3) this implies that $f(U)$ is closed. Therefore $f$ is a closed map.
I believe that the error comes from the idea that we don't know about other closed sets in $Y$. That my proof does not account for ALL closed sets in $Y$. Is this true?

A: There is no error in your proof. You do not need to know all closed subsets of $Y$, it suffices to know that compact subsets are closed.
By the way, your proof is the standard proof. I guess you found this proof as a solution to Munkres' exercise 6 in §26.


text:
Q: How can I keep the original :focus element with CSS? So, I have an <input> element that has the :focus attribute from CSS on it.
CSS
#my_input {
border: 1px solid black;
}

#my_input:focus {
border: 1px solid green;
}

This input is for a login form. If a user gets something wrong for a form, like entering less then the min characters, then the input form has a border of red. Once the error is fixed, I want the border to go back to normal. The border is turned back to normal, but now the :focus element from CSS doesn't work.
Once the user fixes the errors
JS
$("#my_input").css("border", "1px solid black");

How do you fix this problem?

A: By using $("#my_input").css("border", "1px solid black");, you're overwriting the CSS as you're adding that style directly to the element. Instead, use $("#my_input").css("border", ""); which will then force #my_input to use your original CSS styling.
As a quick tip, it would instead be better to do the following:
CSS
#my_input {
  border: 1px solid black;
}

#my_input:focus {
  border-color: green;
}

#my_input.error {
  border-color: red;
}

Then in your JS, to highlight the error:
$("#my_input").addClass('error');

And then to remove the error highlight:
$("#my_input").removeClass('error');


text:
Q: Oracle SQL: write manually a text I am currently trying to just get a certain format of a bill, but I don't know how to select a custom test.
For Example, I Select something like this
Name   Age   Birthday     Gender

Jonas  26    01.01.2000   Boy

The Boy in this one is no Information that is in a table but manually made and I don't know how to do that. Every other Information is from a Table (that was easy).
Summary: How do I manually write a text into a Select?

A: select name, age, birthday, 'Boy' as gender
from your_table             ---------------
                            like this!


text:
Q: problem of while loop and array $result=array();
$table_first = 'recipe';
$query = "SELECT * FROM $table_first";
$resouter = mysql_query($query, $conn);

while ($recipe = mysql_fetch_assoc($resouter, MYSQL_ASSOC)){
   $result['recipe']=$recipe;

$query2="SELECT ingredients.ingredient_id,ingredients.ingredient_name,ingredients.ammount FROM ingredients where rec_id = ".$recipe['rec_id'];
$result2 = mysql_query($query2, $conn);

 while($ingredient = mysql_fetch_assoc($result2)){

        $result['ingredient'] = $ingredient;

 }

 echo json_encode($result);
}
this code show me all the recipes but only the last ingredients i.e
{"recipe":{"rec_id":"14","name":"Spaghetti with Crab and Arugula","overview":"http:\/\/www","category":"","time":"2010-11-11 14:35:11","image":"localhost\/pics\/SpaghettiWithCrabAndArugula.jpg"},"ingredient":{"ingredient_id":"55","ingredient_name":"test","ammount":"2 kg"}}{"recipe":{"rec_id":"15","name":"stew recipe ","overview":"http:\/\/www","category":"","time":"2010-11-11 14:42:09","image":"localhost\/pics\/stew2.jpg"},"ingredient":{"ingredient_id":"25","ingredient_name":"3 parsnips cut into cubes","ammount":"11"}}
i want to output all the ingredient records relevant to recipe id 14 and this just print the last ingredient.

A: $result['ingredient'] = $ingredient;

Is replacing the variable $result['ingredient'] with the most recent $ingredient value each time, culminating with the last value returned, you should use:
$result['ingredient'][] = $ingredient;

To incrememnt/create a new value within the $result['ingredient'] array for each $ingredient. You can then output this array according to your needs. Using print_r($result['ingredient']) will show you its content...to see for yourself try:
while($ingredient = mysql_fetch_assoc($result2)){
        $result['ingredient'][] = $ingredient;

}

print_r($result['ingredient']);

A: If I understand correctly what you want to do, there is a way to optimize the code a lot, by fetching recipes and ingredients in one single query using a JOIN :
$recipes = array();
$recipe_ingredients = array();

$query = "SELECT * FROM recipe LEFT JOIN ingredients ON ingredients.rec_id=recipe.rec_id ORDER BY recipe.rec_id DESC";

$resouter = mysql_query($query, $conn);

$buffer_rec_id = 0;
$buffer_rec_name = "";
$buffer_rec_cat = "";

while( $recipe = mysql_fetch_array($resouter) )
{

  if( $buffer_rec_id != $result['recipe.rec_id'] )
  {
      $recipes[] = array( $buffer_rec_id, $buffer_rec_name, $buffer_rec_cat, $recipe_ingredients);

      $recipe_ingredients = array(  );

      $buffer_rec_id = $result['recipe.rec_id'];
      $buffer_rec_name = $result['recipe.rec_name'];
      $buffer_rec_cat = $result['recipe.rec_category'];
  }
  else
  {
      $recipe_ingredients[] = array( $result['ingredient_id'], $result['ingredient_name'], $result['ammount'] );

  }

}

$print_r($recipes);

This code should give you a multi-dimensional array that you can use later to get the data you want.
I let you adapt the code to have exactly the information you need.