text:
Q: Accessing Plague Wing of Naxxramas I tried to buy the Plague Wing of Naxxramas with gold.
But I'm stuck at an endless "Waiting for Authorization" screen.
I understand that a lot of people are seeing this (but I can't read posts cause I'm behind a work web filter.)
Was anyone able to get past this Authorization Screen without losing their gold?
UPDATE:
Well I just left it sitting there "Waiting for Authorization" and eventually it logged me out cause I had been inactive for too long.

A: The shop got overloaded when everybody tried to buy it at midnight. It's been going up and down throughout the day.
Real money purchases are fine- at least I haven't seen anyone complaining- because the real money purchasing system is so much more robust. This is understandable- charging someone real money twice would result in a lot of hassle and potentially legal action whereas Blizz can do whatever they want with Gold.
Gold purchases are still glitchy at the moment, judging by the forums. You're probably better off waiting.

A: So after restarting Hearthstone I had been charged exactly 700 Gold and the Plague Wing was unlocked.
I'm still unclear if I could have done that at any time. If anyone can answer with more precision I will accept that answer.
Hopefully we won't be back here next wing, but if we are, I'll try to post updates here.


text:
Q: How do I hide my discord bot token when I upload its code on github? I'm coding this discordbot and want it to be on github. How can I upload it without making its token public?
const Discord = require('discord.js');
const client = new Discord.Client();
// Following is the part that matter, the code before is just to get some context
const token = '[hidden for security reasons]';

I think I should put it on a separate file, but I don't know how to reference it on my index.js file.
How do I solve the problem?

A: There are many ways to get secret info out of your code.
The easiest is probably to use environment variables.
You could e.g. use this in your code:
const token = process.env.DISCORD_TOKEN;

And then set the env variable before calling your script (assuming bash shell):
DISCORD_TOKEN=1234foobar1234 node myscript.js

To simplify this you could use a package like dotenv:
require('dotenv').config();

const token = process.env.DISCORD_TOKEN;

Then you can create a .env file in your project root directory:
.env:
DISCORD_TOKEN=1234foobar1234

(remember to add this file to .gitignore to avoid accidental commits)

redpajama_set_name: RedPajamaStackExchange


text:
Q: java.io.StreamCorruptedException: invalid stream header Hola buenas estoy teniendo dificultades con una tarea de clases, en la cual debemos hacer una agenda escribiendo en un fichero binario y luego volcando los datos en una colección, pos al insertar un objeto de tipo persona en el fichero pos va va bien, yo estoy sobrescribiendo el método writeStreamHeader para que no tener problemas con las cabeceras, pero una vez ya insertado los primeros contacto en la primera arrancada, cuando voy a ejecutar por segunda vez entonces me salta dicha excepción, cosa que no comprendo debido a que ya estoy sobrescribiendo el método de ObjectOutputStream...
Os adjunto algo de código , si me podeis ayudar a ver la luz lo agradecería mucho. Un saludo. (Por cierto cabe decir, que tengo un objeto persona serializado...)
package ejercicio1;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.OutputStream;

/**
 *
 * @author xymind
 */
public class MiObjectOutputStream extends ObjectOutputStream {

    public MiObjectOutputStream(OutputStream out) throws IOException {
        super(out);
    }

    public MiObjectOutputStream() throws IOException, SecurityException {
        super();

    }

    /**
     * Redefinición del método de escribir la cabecera para que no haga nada.
     *
     * @throws java.io.IOException
     */
    @Override
    protected void writeStreamHeader() throws IOException {
    }

}

Constructor de la clase fichero (CRUD) con la colección y el fichero:
public Fichero(String path) {
        this.file = new File(path);

        this.personas = new HashSet<>();
        cargarDatos();
}

Método cargarDatos, aqui supuestamente casca, en la instanciación de ObjectInputStream:
public void cargarDatos() {
        ObjectInputStream obs = null;
        Persona persona;

        try {
            if (!this.file.exists()) {
                this.file.createNewFile();
            }
            if (this.file.length() > 0) {
                obs = new ObjectInputStream(new FileInputStream(this.file));

                while (obs.available() != 0) {
                    persona = (Persona) obs.readObject();
                    this.personas.add(persona);
                }
            }

        } catch (FileNotFoundException ex) {
            Logger.getLogger(Fichero.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Fichero.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(Fichero.class.getName()).log(Level.SEVERE, null, ex);
        } finally {

            if (obs != null) {

                try {
                    obs.close();
                } catch (Exception e) {
                    System.out.println(e.toString());
                }
            }

        }

    }

Método para escribir el objeto:
public void guardarCambios(Persona persona) {
        ObjectOutputStream obsStream = null;

        try {

            if (this.file.length() > 0) {
                obsStream = new MiObjectOutputStream(new FileOutputStream(this.file, true));

            } else {
                obsStream = new MiObjectOutputStream(new FileOutputStream(this.file));

            }

            obsStream.writeObject(persona);

        } catch (IOException e) {
            System.out.println("Error: " + e.toString());
        } finally {
            if (obsStream != null) {
                try {
                    obsStream.close();
                } catch (IOException e) {
                    System.out.println(e.toString());
                }
            }
        }
    }


text:
Q: How can someone corrupt an NTFS filesystem with a user space application So the question may look strange.
I've encountered many times a folder that cannot be deleted on a NTFS filesystem unless the PC was rebooted. When this happens, the issue is not a permission things, even the local administrator can't deal with it. But reboot the PC and the folder is gone.
Even this Microsoft post says that it is a possible behaviour
Now, I have an application that creates a temporary folder, write inside it and deletes it afterward. Sometime, this application crashes because it cannot delete the files inside that folder. When I look at it, the temporary folder is empty and show the behaviour described above.
So my question goes as follow : How can my software do that?
I would like to debug this but I have no clue where to start as I would expect the filesystem to be robust when accessed through the WinAPI. My application is a C# .Net 4.5 application.
Is there known vulnerabilities on the NTFS filesystems that could result in bad sectors? We're talking about Windows 7. This looks a lot like a race condition scenario.
Thanks!


text:
Q: Changing filename in ubuntu for 001,002 I'm currently have ~4500 file 2MB with .001, .002 .
I want to remove 2 parts first and 2 parts last (mean remove 001,002 and two last parts
Now I have file from .003, .004
How can I change 003 to 001, 004 to 002, 005 to 003?

A: It's no pretty solution, but what about something like this?
i=1; temp=$(mktemp temp); for file in .[0-9][0-9][0-9]
do
mv "$file" $temp;
mv $temp $(printf ".%0.3d" $i)
i=$((i + 1))
done

(Adapted version of Renaming files in a folder to sequential numbers)

A: Try the following script:
numerate.sh
This code snipped should do the job:
./numerate.sh -d <your image folder> -b 1 -L 3 -p "." -o numerically -r


text:
Q: Batch update returned unexpected row count from update - updating row count? When adding a new row in a table right after deleting one, I'm getting such an error:
"Batch update returned unexpected row count from update; actual row count: %x; expected: %(x+1)", where x - is a number of rows after deleting and before inserting.
Code for deleting:
using (var session = factory.OpenSession())
{
    using (var transaction = session.BeginTransaction())
    {
        foreach (var row in rows)
        {
            session.Delete((Word)row.DataBoundItem);
        }
        transaction.Commit();
        session.Flush();
    }
}

Code for adding:
using (var session = factory.OpenSession())
{
    using (var transaction = session.BeginTransaction())
    {
        language.AddWord(word);
        session.SaveOrUpdate(language);
        transaction.Commit();
        session.Flush();
    }
}

Mapping:
public WordMapping()
{
    Id(x => x.Id).GeneratedBy.Native();
    Map(x => x.Word1);
    Map(x => x.Word2);
        Map(x => x.Count);
        References(x => x.Language)
            .Not.LazyLoad();
}

SQL code, that is written to debug:
NHibernate: INSERT INTO [Word] (Word1, Word2, Count, Language_id)
    VALUES (@p0, @p1, @p2, @p3);
    select SCOPE_IDENTITY();
    @p0 = 't2' [Type: String (4000)],
    @p1 = 't2' [Type: String (4000)],
    @p2 = 10 [Type: Int32 (0)],
    @p3 = 1 [Type: Int32 (0)]

Can you give me a hint what to do? Maybe I should somehow update the number of rows?


text:
Q: What is the proper way to deploy a multi-region CloudFormation stack that includes global resources? I have a cloudformation stack template that includes regional resources (lambdas, api, topics, etc.) and global resources (user, policies, route53, cloudfront, dynamodb global tables, etc.) and want to deploy it to multiple region in the same AWS account.
I can't directly deploy this stack template in multiple region because global resources will already exist after the first creation.
I know I could split everything in two separate stack templates but I would prefer to avoid this and keep everything in the same single stack template.
I saw that I could probably use CF Conditions + Parameters to toggle global resource creation only on first creation but that doesn't look very good...
I was wondering if I could leverage some CloudFormation feature like StackSets or something else to achieve that.
Any idea on what would be the proper way to do this?

A: The solution is at your hands. I suggest that you do the following:

*

*Create a separate template for the global resources (yes, I know that you don't like it, but it works well in my experience)

*Store references to the shared global resources in SSM using AWS::SSM::Parameter

*Deploy regional stacks and de-reference the global resources (either using Parameters, such as the AWS::SSM::Parameter::Value<String> or dynamic reference, e.g. {{resolve:ssm:S3AccessControl:2}})

You can use either StackSets for your regional stack deployments or create a parameterized build script that deploys the regional stacks one at the time (to be executed either locally or preferably by your CI/CD server).


text:
Q: Why are JUnit5 Parametrized tests using argument providers not defined in @ArgumentSource? I have a problem with my parameterized tests.
  @ParameterizedTest
  @ArgumentsSource(CorrectMessagesArgumentProvider.class)
  void shouldSendMessageForCorrectConfiguration(SmtpConfiguration configuration) {
    var expectedMessageBody = fetchMessage();
    var alertSender = new AlertSender(configuration);
    var alertSubject = subjectFrom();
    alertSender.send(expectedMessageBody, alertSubject);
    var receivedMessages = greenMail.getReceivedMessages();

    assertEquals(1, receivedMessages.length);
  }

  @ParameterizedTest
  @ArgumentsSource(IncorrectMessagesArgumentProvider.class)
  void shouldNotSendMessageForIncorrectConfiguration(SmtpConfiguration smtpConfiguration) {
    var expectedMessageBody = fetchMessage();
    var alertSender = new AlertSender(smtpConfiguration);
    var alertSubject = subjectFrom();

    var expectedErrorMessage = "Error sending alert";
    var actualErrorMessage =
        assertThrows(
            SendAlertException.class, () -> alertSender.send(expectedMessageBody, alertSubject));
    assertTrue(actualErrorMessage.getMessage().contains(expectedErrorMessage));
  }

When I run those tests separetly, they work correctly. But when I run suite, the second test running fails, because it is using arguments from the other test.
They're somehow sharing that resource, but I have no idea how. Any ideas?

A: Okey, I got it - deep in the class responsible for sending emails, I was creating session object by getDefaultInstance(). It was creating singleton which was available for all JVM processes. When I used getInstance() - it work like a charm.


text:
Q: Jasmine/Karma branch not covered when using null assertion I am trying to improve my code coverage in Jasmine/Karma but have been hitting a branch coverage roadblock in cases where I'm using null assertion in my code.
For instance:
this.parentCarrierForm.controls.carrierName.setValue(
  this.carrier?.carrierName,
);

The testrunner coverage report shows:

Hovering over the highlighted portion raises the branch not covered tooltip and dings the branch coverage percentage.
In the example above, I am trying to use null assertion into a FormControl, the same result can be found when assigning the value to a variable such as const myVariable = String(this.carrier?.carrierName). The branch not covered coverage error is still present.
What is the best way to get Jasmine/Karma to stop complaining about null assertion?

A: That is trying to tell you that you have a test that has an undefined this.carrier and it tested fine.
However you have zero tests where you have assigned a value to this.carrier.
A test like the following would help your coverage.
it('carrier name gets set correctly', () => {
 // however you're setting up the component, hopefully in the beforeEach
 const fixture = TestBed.createComponent(AppComponent);
 const component = fixture.componentInstance;

 // set the carrier to something
 component.carrier = new Carrier();
 component.carrier.carrierName = 'meow';
 fixture.detectChanges(); // or whatever calls your code that you want covered

 // assert that the form value has been set appropriately
 const element = fixture.debugElement.query(By.css(selector));
 expect(element.nativeElement.value.trim()).toBe('meow');
});

Remember that if you don't put in that assert your test coverage only indicates that the code doesn't throw null exceptions, it won't guarantee that the code does what you want it to.


text:
Q: AutoLayout Constraints Across All Devices Mathematically I am new to IOS Development, please go easy.
I am attempting to create a universal identically positioned UIView in the main ViewController of any IOS Device (The view will change dynamically and match across all IOS devices (relative to the size of the screen), and not ruin the positioning of the view). Basically, is it possible to mathematically alter the "equalToConstants" in the anchor to create some kind of formula that will yield the same result across all screens using division/multiplication of the main screen size (IPad, IPhone, etc.) to determine an exact similar location visually?
Something like bottomButtonView.widthAnchor.constraint(equalToConstant: -/+ 20).isActive = true
As opposed to a "fixed" variable that yields a different "visual" position across all IOS devices:
bottomButtonView.widthAnchor.constraint(equalToConstant: 400).isActive = true

I do not want to use the storyboard, as I am knee-deep in programmatically building my app. I have also heard programmatically programming your app is the way to go for easier future changes etc.
The following snippet of code is showing what I have in the ViewController that displays a red rectangle which would be great to have the same size/shape relative to the screen size (IPad, IPhone 6,7,8,X,11, etc.):
let bottomButtonView = UIView()
bottomButtonView.translatesAutoresizingMaskIntoConstraints = false
bottomButtonView.backgroundColor = .red
view.addSubview(bottomButtonView)
bottomButtonView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor).isActive = false
bottomButtonView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor).isActive = true
bottomButtonView.widthAnchor.constraint(equalToConstant: 400).isActive = true
bottomButtonView.centerXAnchor.constraint(equalTo: view.safeAreaLayoutGuide.centerXAnchor).isActive = true
bottomButtonView.heightAnchor.constraint(equalToConstant: 300).isActive = true
bottomButtonView.centerYAnchor.constraint(equalTo: view.centerYAnchor, constant: 400).isActive = true

Thank you in advanced.


text:
Q: Editing html text with JEditorPane I wrote a text editor that saves the text as html.
I'm having no problem with the styles like bold, italic, etc etc, the only problem I'm having is the way it behaves when I press enter.
Instead of creating a new normal line, it creates a extra spaced line. I think it has something to do with the
 tag but I'm not sure...
Anyway here's an example of my problem:
import java.awt.BorderLayout;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.text.html.HTMLEditorKit;

public class test extends JFrame {

    public static void main(String[] args){
        new test().open();
    }

    private void open() {
        setSize(200, 200);
        JEditorPane jp = new JEditorPane();
        setLayout(new BorderLayout());
        add(jp, BorderLayout.CENTER);

        jp.setEditorKit(new HTMLEditorKit());
        jp.setText("
hey

Write in here
");
        setVisible(true);
    }
}

Is there anyway to fix this?

A: I think you are trying to edit directly onto the JEditorPane after it renders the HTML.  JEditorPane reads in the text you provide it and renders it in accordance with the HTML markup that accompanies the text. So, if you want to make it have a newline at some point in your text, then you need to input a break tag, like so:
public class test extends JFrame
{
  public static void main(String[] args){
    test t = new test();
    t.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    t.open();
  }

  private void open()
  {
    setSize(200, 200);
    JEditorPane jp = new JEditorPane();
    jp.setEditable(false);
    setLayout(new BorderLayout());
    add(jp, BorderLayout.CENTER);

    jp.setEditorKit(new HTMLEditorKit());
    jp.setText("
hey

Don't write here.
Let JEditor rendor your HTML text.
");
    setVisible(true);
  }
}

Hope this helps.


text:
Q: How can I use some new analog video formats or route to some new physical connectors when dealing with video capturing? I'm developing a multimedia player app with Directshow recently, and I can successfully build the filter graph to capture video stream from a webcam.
I read the Directshow document on MSDN and found that WDM video capture filter exposes IAMAnalogVideoDecoder interface and I can set the analog video format listed in AnalogVideoStandard enum, but this enum does not contain some new HD standard such as 720p, 1080i, 1080p:
typedef /* [v1_enum] */
enum tagAnalogVideoStandard
    {
        AnalogVideo_None    = 0,
        AnalogVideo_NTSC_M  = 0x1,
        AnalogVideo_NTSC_M_J    = 0x2,
        AnalogVideo_NTSC_433    = 0x4,
        AnalogVideo_PAL_B   = 0x10,
        AnalogVideo_PAL_D   = 0x20,
        AnalogVideo_PAL_G   = 0x40,
        AnalogVideo_PAL_H   = 0x80,
        AnalogVideo_PAL_I   = 0x100,
        AnalogVideo_PAL_M   = 0x200,
        AnalogVideo_PAL_N   = 0x400,
        AnalogVideo_PAL_60  = 0x800,
        AnalogVideo_SECAM_B = 0x1000,
        AnalogVideo_SECAM_D = 0x2000,
        AnalogVideo_SECAM_G = 0x4000,
        AnalogVideo_SECAM_H = 0x8000,
        AnalogVideo_SECAM_K = 0x10000,
        AnalogVideo_SECAM_K1    = 0x20000,
        AnalogVideo_SECAM_L = 0x40000,
        AnalogVideo_SECAM_L1    = 0x80000,
        AnalogVideo_PAL_N_COMBO = 0x100000,
        AnalogVideoMask_MCE_NTSC    = ( ( ( ( ( ( AnalogVideo_NTSC_M | AnalogVideo_NTSC_M_J )  | AnalogVideo_NTSC_433 )  | AnalogVideo_PAL_M )  | AnalogVideo_PAL_N )  | AnalogVideo_PAL_60 )  | AnalogVideo_PAL_N_COMBO ) ,
        AnalogVideoMask_MCE_PAL = ( ( ( ( AnalogVideo_PAL_B | AnalogVideo_PAL_D )  | AnalogVideo_PAL_G )  | AnalogVideo_PAL_H )  | AnalogVideo_PAL_I ) ,
        AnalogVideoMask_MCE_SECAM   = ( ( ( ( ( ( ( AnalogVideo_SECAM_B | AnalogVideo_SECAM_D )  | AnalogVideo_SECAM_G )  | AnalogVideo_SECAM_H )  | AnalogVideo_SECAM_K )  | AnalogVideo_SECAM_K1 )  | AnalogVideo_SECAM_L )  | AnalogVideo_SECAM_L1 )
    }   AnalogVideoStandard;

What's more, when a capture card has more than one physical input, a crossbar filter will be added automatically and I can route which input I want using the PhysicalConnectorType enum, but some new input such as HDMI is not included:
typedef
enum tagPhysicalConnectorType
    {
        PhysConn_Video_Tuner    = 1,
        PhysConn_Video_Composite    = ( PhysConn_Video_Tuner + 1 ) ,
        PhysConn_Video_SVideo   = ( PhysConn_Video_Composite + 1 ) ,
        PhysConn_Video_RGB  = ( PhysConn_Video_SVideo + 1 ) ,
        PhysConn_Video_YRYBY    = ( PhysConn_Video_RGB + 1 ) ,
        PhysConn_Video_SerialDigital    = ( PhysConn_Video_YRYBY + 1 ) ,
        PhysConn_Video_ParallelDigital  = ( PhysConn_Video_SerialDigital + 1 ) ,
        PhysConn_Video_SCSI = ( PhysConn_Video_ParallelDigital + 1 ) ,
        PhysConn_Video_AUX  = ( PhysConn_Video_SCSI + 1 ) ,
        PhysConn_Video_1394 = ( PhysConn_Video_AUX + 1 ) ,
        PhysConn_Video_USB  = ( PhysConn_Video_1394 + 1 ) ,
        PhysConn_Video_VideoDecoder = ( PhysConn_Video_USB + 1 ) ,
        PhysConn_Video_VideoEncoder = ( PhysConn_Video_VideoDecoder + 1 ) ,
        PhysConn_Video_SCART    = ( PhysConn_Video_VideoEncoder + 1 ) ,
        PhysConn_Video_Black    = ( PhysConn_Video_SCART + 1 ) ,
        PhysConn_Audio_Tuner    = 0x1000,
        PhysConn_Audio_Line = ( PhysConn_Audio_Tuner + 1 ) ,
        PhysConn_Audio_Mic  = ( PhysConn_Audio_Line + 1 ) ,
        PhysConn_Audio_AESDigital   = ( PhysConn_Audio_Mic + 1 ) ,
        PhysConn_Audio_SPDIFDigital = ( PhysConn_Audio_AESDigital + 1 ) ,
        PhysConn_Audio_SCSI = ( PhysConn_Audio_SPDIFDigital + 1 ) ,
        PhysConn_Audio_AUX  = ( PhysConn_Audio_SCSI + 1 ) ,
        PhysConn_Audio_1394 = ( PhysConn_Audio_AUX + 1 ) ,
        PhysConn_Audio_USB  = ( PhysConn_Audio_1394 + 1 ) ,
        PhysConn_Audio_AudioDecoder = ( PhysConn_Audio_USB + 1 )
    }   PhysicalConnectorType;

I know that Directshow is an old multimedia framework and the header may be out of time. So is there any way to apply some new standard to Directshow? Is there some other redistribution of Directshow? Or I should just give up using Directshow and use Media Foundation instead?

A: So, you correct wrote that Microsoft stopped supporting of DirectShow. DirectShow does not support HD standard such as 720p, 1080i, 1080p by default. For resolving of such problem vendor of the video capture device develops private direct show filter with supporting of the such new device and include it into the driver for devices - this filter is installed while installing of drives - it means that you must research OS system for finding of DirectShow Source Filters - one of them will your's needed filter, of course if you installed drivers. About Media Foundation - at the present moment it supports only USB Video Class driver Audio/Video Capture in Media Foundation for capture of video - such driver supports only USB web cameras.
Regards.
P.S. for getting of output pin you can use the next code:`
                CComPtrCustom<ICaptureGraphBuilder2> lCaptureGraph;

                LOG_INVOKE_FUNCTION(lCaptureGraph.CoCreateInstance, __uuidof(CLSID_CaptureGraphBuilder2Proxy));

                LOG_CHECK_PTR_MEMORY(lCaptureGraph);

                CComPtrCustom<IGraphBuilder> lGraphBuilder;

                LOG_INVOKE_FUNCTION(lGraphBuilder.CoCreateInstance, __uuidof(CLSID_FilterGraphProxy));

                LOG_CHECK_PTR_MEMORY(lGraphBuilder);

                LOG_INVOKE_POINTER_METHOD(lCaptureGraph, SetFiltergraph,
                    lGraphBuilder);

                CComPtrCustom<IBaseFilter> lVideoCaptureFilter;

                CComPtrCustom<IBindCtx> pbc;

                LOG_INVOKE_FUNCTION(CreateBindCtx, NULL, &pbc);

                LOG_INVOKE_POINTER_METHOD(mMoniker, BindToObject,
                    pbc,
                    nullptr,
                    IID_PPV_ARGS(&lVideoCaptureFilter));

                LOG_CHECK_PTR_MEMORY(lVideoCaptureFilter);

                LOG_INVOKE_POINTER_METHOD(lGraphBuilder, AddFilter,
                    lVideoCaptureFilter,
                    L"Video Capture");

                std::vector<CComPtrCustom<IMFMediaType>> lMediaTypes;

                do
                {
                    CComPtrCustom<IPin> lPin;

                    LOG_INVOKE_POINTER_METHOD(lCaptureGraph, FindPin,
                        lVideoCaptureFilter,
                        PINDIR_OUTPUT,
                        &PIN_CATEGORY_CAPTURE,
                        &__uuidof(MEDIATYPE_VideoProxy),
                        FALSE,
                        aStreamIndex,
                        &lPin);

                    if (lPin != nullptr)
                    {
                        PIN_INFO lPIN_INFO;

                        ZeroMemory(&lPIN_INFO, sizeof(lPIN_INFO));

                        HRESULT lr = lPin->QueryPinInfo(&lPIN_INFO);

                        if (SUCCEEDED(lr) && lPIN_INFO.achName[0] != L'\0')
                        {
                            if (aPtrStreamNameString != nullptr)
                            {
                                *aPtrStreamNameString = SysAllocString(lPIN_INFO.achName);
                            }
                        }

                        getMediaTypes(
                            lPin,
                            lMediaTypes);
                    }

                } while (false);

`
Some vendors define own interface for extension of DS filter - for example AJA DS Filters:
EXTERN_C const IID IID_IAJACaptureFilter;

MIDL_INTERFACE("D941E04F-3B38-4F27-82DD-943FBEA7E755")
IAJACaptureFilter : public IUnknown
{
public:
    virtual HRESULT STDMETHODCALLTYPE SetBoardNumber(
        /* [in] */ WORD value) = 0;

    virtual HRESULT STDMETHODCALLTYPE GetBoardNumber(
        /* [out] */ WORD *value) = 0;

    virtual HRESULT STDMETHODCALLTYPE GetNumBoards(
        /* [out] */ WORD *value) = 0;

    virtual HRESULT STDMETHODCALLTYPE ReserveBoard(
        /* [in] */ WORD value) = 0;

    virtual HRESULT STDMETHODCALLTYPE SetVideoFormat(
        /* [in] */ WORD value) = 0;

    virtual HRESULT STDMETHODCALLTYPE GetVideoFormat(
        /* [out] */ WORD *value) = 0;

    virtual HRESULT STDMETHODCALLTYPE SetReferenceSource(
        /* [in] */ WORD value) = 0;

    virtual HRESULT STDMETHODCALLTYPE GetReferenceSource(
        /* [out] */ WORD *value) = 0;

    virtual HRESULT STDMETHODCALLTYPE SetVideoSource(
        /* [in] */ WORD value) = 0;

    virtual HRESULT STDMETHODCALLTYPE GetVideoSource(
        /* [out] */ WORD *value) = 0;

    virtual HRESULT STDMETHODCALLTYPE SetAnalogVideoFormat(
        /* [in] */ WORD value) = 0;

    virtual HRESULT STDMETHODCALLTYPE GetAnalogVideoFormat(
        /* [out] */ WORD *value) = 0;

    virtual HRESULT STDMETHODCALLTYPE GetSourceVideoFormat(
        /* [out] */ WORD *value) = 0;

    virtual HRESULT STDMETHODCALLTYPE GetInput1VideoFormat(
        /* [out] */ WORD *value) = 0;

    virtual HRESULT STDMETHODCALLTYPE GetInput2VideoFormat(
        /* [out] */ WORD *value) = 0;

    virtual HRESULT STDMETHODCALLTYPE GetHDMIInVideoFormat(
        /* [out] */ WORD *value) = 0;

    virtual HRESULT STDMETHODCALLTYPE GetReferenceVideoFormat(
        /* [out] */ WORD *value) = 0;

    virtual HRESULT STDMETHODCALLTYPE SetFourCC(
        /* [in] */ DWORD value) = 0;

    virtual HRESULT STDMETHODCALLTYPE GetFourCC(
        /* [out] */ DWORD *value) = 0;

    virtual HRESULT STDMETHODCALLTYPE SetEnableEtoE(
        /* [in] */ BOOL value) = 0;

    virtual HRESULT STDMETHODCALLTYPE GetEnableEtoE(
        /* [out] */ BOOL *value) = 0;

    virtual HRESULT STDMETHODCALLTYPE SetEnableVANCMode(
        /* [in] */ BOOL value) = 0;

    virtual HRESULT STDMETHODCALLTYPE GetEnableVANCMode(
        /* [out] */ BOOL *value) = 0;

    virtual HRESULT STDMETHODCALLTYPE SetScaleMode(
        /* [in] */ WORD value) = 0;

    virtual HRESULT STDMETHODCALLTYPE GetScaleMode(
        /* [out] */ WORD *value) = 0;

    virtual HRESULT STDMETHODCALLTYPE SetAudioSource(
        /* [in] */ WORD value) = 0;

    virtual HRESULT STDMETHODCALLTYPE GetAudioSource(
        /* [out] */ WORD *value) = 0;

    virtual HRESULT STDMETHODCALLTYPE SetInputAlarm(
        /* [in] */ BOOL value) = 0;

    virtual HRESULT STDMETHODCALLTYPE GetInputAlarm(
        /* [out] */ BOOL *value) = 0;

    virtual HRESULT STDMETHODCALLTYPE GetCurrentFrame(
        /* [out] */ DWORD *value) = 0;

    virtual HRESULT STDMETHODCALLTYPE GetDroppedFrames(
        /* [out] */ DWORD *value) = 0;

    virtual HRESULT STDMETHODCALLTYPE GetBufferLevel(
        /* [out] */ DWORD *value) = 0;

    virtual HRESULT STDMETHODCALLTYPE GetBoardID(
        /* [out] */ DWORD *value) = 0;

    virtual HRESULT STDMETHODCALLTYPE GetSerialNumber(
        /* [retval][out] */ BSTR *value) = 0;

    virtual HRESULT STDMETHODCALLTYPE GetDebug(
        /* [out] */ int *pnDebug1,
        /* [out] */ int *pnDebug2,
        /* [out] */ int *pnDebug3) = 0;

};

Filter of AJA company can be used for setting format of output filter.


text:
Q: Issue with showing date when csv file opened in MS Excel 2010 I have a problem with exporting to CSV format. This issue is reproduced on Excel 2010 and isn't on Excel 2013,2016. Column which contains date format value is automatically converted from MM-DD-yyyy hh:mm a to MM-DD-YYYY HH:MM (24hours format). When I open *.csv file using notepad everything works fine.
Maybe it depends on custom user preferences in Excel? Could you provide solution to resolve this problem?

A: When opening text files such as CSV in Excel, Excel uses the most recently used settings for the Text To Columns feature (which are the same settings used for the import text file feature).
Furthermore, if you don't specify all of the Text To Columns settings, Excel will use the most recently used values, or the defaults.
Excel's re-use of the previous settings will explain why you are seeing different results on different versions of Excel - It's not because the versions differ, it's because each installation has a different set of most recently used preferences for Text To Columns.
You can step through the Text To Columns wizard (on the Data tab in the Data Tools group), chooisng all of the preferences you'd like, and then try opening the CSV file again.


text:
Q: Apply Polar Coordinates to UIImage I want to convert regular panoramic photos to polar coordinates to create a "tiny earth" effect but i cannot figure out how to solve this. I would assume there is some helpful Core Graphics filter or third party library but i cannot find any.
Example:

A: This is actually quite simple, you just have to apply polar coordinates. Here is a fully commented example (implemented in C++ and using OpenCV only for data structures and image loading and display):
#include <opencv2/highgui.hpp>

// Function returning the bilinear interpolation of the input image at input coordinates
cv::Vec3b interpolate(const cv::Mat &image, float x, float y)
{
    // Compute bilinear interpolation weights
    float floorx=std::floor(x), floory=std::floor(y);
    float fracx=x-floorx, fracy=y-floory;
    float w00=(1-fracy)*(1-fracx), w01=(1-fracy)*fracx, w10=fracy*(1-fracx), w11=fracy*fracx;

    // Read the input image values at the 4 pixels surrounding the floating point (x,y) coordinates
    cv::Vec3b val00 = image.at<cv::Vec3b>(floory, floorx);
    cv::Vec3b val01 = (floorx<image.cols-1 ? image.at<cv::Vec3b>(floory, floorx+1) : image.at<cv::Vec3b>(floory, 0));       // Enable interpolation between the last right-most and left-most columns
    cv::Vec3b val10 = image.at<cv::Vec3b>(floory+1, floorx);
    cv::Vec3b val11 = (floorx<image.cols-1 ? image.at<cv::Vec3b>(floory+1, floorx+1) : image.at<cv::Vec3b>(floory+1, 0));   // Enable interpolation between the last right-most and left-most columns

    // Compute the interpolated color
    cv::Vec3b val_interp;
    val_interp.val[0] = cv::saturate_cast<uchar>(val00.val[0]*w00+val01.val[0]*w01+val10.val[0]*w10+val11.val[0]*w11);
    val_interp.val[1] = cv::saturate_cast<uchar>(val00.val[1]*w00+val01.val[1]*w01+val10.val[1]*w10+val11.val[1]*w11);
    val_interp.val[2] = cv::saturate_cast<uchar>(val00.val[2]*w00+val01.val[2]*w01+val10.val[2]*w10+val11.val[2]*w11);
    return val_interp;
}

// Main function
void main()
{
    const float pi = 3.1415926535897932384626433832795;

    // Load and display color panorama image
    cv::Mat panorama = cv::imread("../panorama_sd.jpg", cv::IMREAD_COLOR);
    cv::namedWindow("Panorama");
    cv::imshow("Panorama", panorama);

    // Infer the size of the final image from the dimensions of the panorama
    cv::Size result_size(panorama.rows*2, panorama.rows*2);
    float ctrx=result_size.width/2, ctry=result_size.height/2;

    // Initialize an image with black background, with inferred dimensions and same color format as input panorama
    cv::Mat tiny_earth_img = cv::Mat::zeros(result_size, panorama.type());
    cv::Vec3b *pbuffer_img = tiny_earth_img.ptr<cv::Vec3b>();   // Get a pointer to the buffer of the image (sequence of 8-bit interleaved BGR values)

    // Generate the TinyEarth image by looping over all its pixels
    for(int y=0; y<result_size.height; ++y) {
        for(int x=0; x<result_size.width; ++x, ++pbuffer_img) {

            // Compute the polar coordinates associated with the current (x,y) point in the final image
            float dx=x-ctrx, dy=y-ctry;
            float radius = std::sqrt(dx*dx+dy*dy);
            float angle = std::atan2(dy,dx)/(2*pi); // Result in [-0.5, 0.5]
            angle = (angle<0 ? angle+1 : angle);    // Result in [0,1[

            // Map the polar coordinates to cartesian coordinates in the panorama image
            float panx = panorama.cols*angle;
            float pany = panorama.rows-1-radius;    // We want the bottom of the panorama to be at the center

            // Ignore pixels which cannot be linearly interpolated in the panorama image
            if(std::floor(panx)<0 || std::floor(panx)+1>panorama.cols || std::floor(pany)<0 || std::floor(pany)+1>panorama.rows-1)
                continue;

            // Interpolate the panorama image at coordinates (panx, pany), and store this value in the final image
            pbuffer_img[0] = interpolate(panorama, panx, pany);
        }
    }

    // Display the final image
    cv::imwrite("../tinyearth.jpg", tiny_earth_img);
    cv::namedWindow("TinyEarth");
    cv::imshow("TinyEarth", tiny_earth_img);
    cv::waitKey();
}

Sample input panorama (source):

Resulting image:

EDIT:
To answer your remark about the black borders, you can adjust the mapping function (which maps pixel coordinates in the final image to pixel coordinates in the panorama image) to achieve what you want to do. Here are some examples:
Source panorama:

1) Original mapping: pixels with radius>panorama.rows/2 are left un-touched (hence you can have whatever background image show up there)
float panx = panorama.cols*angle;
float pany = panorama.rows-1-radius;

Result:

2) Closest-point mapping: pixels with radius>panorama.rows/2 are mapped to the closest valid pixel in the panorama.
float panx = panorama.cols*angle;
float pany = std::max(0.f,panorama.rows-1-radius);

Result:

3) Zoomed-in mapping: the tiny-earth image is zoomed in so that pixels with radius>panorama.rows/2 are mapped to valid panorama pixels, however some parts of the panorama are now mapped outside the tiny-earth image (at the top/bottom/left/right)
float panx = panorama.cols*angle;
float pany = panorama.rows-1-0.70710678118654752440084436210485*radius;

Result:

4) Logarithmic mapping: a non-linear mapping involving the log function is used to minimize the areas of the panorama which are mapped outside the tiny-earth image (you may adjust the 100 constant to scale more or less).
const float scale_cst = 100;
float panx = panorama.cols*angle;
float pany = (panorama.rows-1)*(1-std::log(1+scale_cst*0.70710678118654752440084436210485*radius/panorama.rows)/std::log(1+scale_cst));

Result:


text:
Q: Vaadin v.23 how to create a popup window that will return a value on closing I am still learning Vaadin while trying to make my application.
I have a button with click listener. Upon click it shall open a popup window, passing in an object.
In this popup window I have several text fields and buttons to edit this object.
I created a class extending VerticalLayout which contains these components.
When popup windows closed, it should return updated object to the main layout.
I can't find neither in Javadocs, nor in tutorials a way to do it. In older versions of Vaadin there was a component Window which does not longer exist.
If someone can point me to the right direction, I will appreciate.

A: The component you are looking for is called Dialog. Dialogs don't have a "return value" (just like Windows in older versions) - you just maintain the state of the application to get the value the user has entered in the Dialog. If you want to do something when the Dialog is closed, you can use a listener for that.
Example:
    private String name;

    @Override
    public void openNameDialog() {

        Dialog dialog = new Dialog();
        TextField nameTextField = new TextField("Enter name");
        nameTextField.addValueChangeListener(e -> {
           name = e.getValue();
        });
        Button closeButton = new Button("close", e -> { dialog.close(); });
        dialog.add(nameTextField, closeButton);
        dialog.addOpenedChangeListener(e -> {
            // if dialog was closed
            if (!e.isOpened()) {
                // do something with the `name`
                System.out.println("Value entered in Dialog: " + name);
            }
        });
        dialog.open();
    }


text:
Q: jquery 1.6.2 and 1.4.2 issue.. how to fix this? I have a few jquery thinngs added to my site like gallery, callendar, autocomplete
the problem is that all works except that when I click on a image the main image is not changing. I used to click on a thumbnail and in a larger div I get the larger picture displayed, but this thing isn't working since I replaced jquery 1.4.2 with 1.6.2. What is the difference between them and how can I fix this?
here is the js code for my gallery on main page, gallery on car_show page and a little thumbnail gallery to show related products
 <script type="text/javascript">
    $(function() {
      $('#newsflash-text').cycle({
        timeout: 5000,  // milliseconds between slide transitions (0 to disable auto advance)
        fx:      'fade', // choose your transition type, ex: fade, scrollUp, shuffle, etc...
        pause:   1,   // true to enable "pause on hover"
        cleartypeNoBg:   true, // set to true to disable extra cleartype fixing (leave false to force background color setting on slides)
        pauseOnPagerHover: 0 // true to pause when hovering over pager link
      });
      $('#slideshow').cycle({
        timeout: 5000,  // milliseconds between slide transitions (0 to disable auto advance)
        fx:      'fade', // choose your transition type, ex: fade, scrollUp, shuffle, etc...
        pause:   1,   // true to enable "pause on hover"
        pager:'#pagerslide',
        cleartypeNoBg:   true, // set to true to disable extra cleartype fixing (leave false to force background color setting on slides)
        pauseOnPagerHover: 0 // true to pause when hovering over pager link
      });

//for scroll box
$('#scroll-box').cycle({
  timeout: 0,  // milliseconds between slide transitions (0 to disable auto advance)
  fx:     'scrollHorz', // choose your transition type, ex: fade, scrollUp, shuffle, etc...
  prev:   '#arrowprev', // selector for element to use as click trigger for next slide
  next:   '#arrownext', // selector for element to use as click trigger for previous slide
  cleartypeNoBg:   true, // set to true to disable extra cleartype fixing (leave false to force background color setting on slides)
  height:         150, // container height
  pauseOnPagerHover: 0 // true to pause when hovering over pager link
});

// for slideshow with thumb image
$('#img-slide-large').cycle({
  fx:     'fade',
  speed:  'slow',
  timeout: 6000,
  pager:  '#nav-thumb',
  pagerAnchorBuilder: function(idx, slide) {
    // return sel string for existing anchor
    return '#nav-thumb li:eq(' + (idx) + ') a';
  }
});
});
</script>

is there any way to fix this? if I remove the jquery 1.6.2 and install 1.4.2 then this little part is working but then fails the autocomplete feature. Is there any way to merge those 2 jquery files to have all elements working? Thanks.

A: You probably need to get the latest version of cycle plugin? http://jquery.malsup.com/cycle/download.html

A: Done!  I just tried another release of jquery and jquery 1.4.4 works fine. everything is running now. So if any of you have this issues when effect X requires 1.4.2 version and effect Y requires 1.5.2 version, just try replace your jquery release with one that's between this releases.


text:
Q: Using OpenPyxl to dynamically create dictionaries? I'm using Openpyxl to read an excel file, specifically one column, that looks like:
this excel snapshot
The number of main and sub classes in the source document can change, and my goal is to be able to iterate through and create perhaps a nested dictionary for each main class of the form:
main_Class1 = { 'subClass1': {'data': 'data_1'},
                'subClass2': {'data': 'data_2'}}

I'm open to any data type, so long as the info is connected like such.
I've though to have the Classes in column B, merge Main Classes into column A and Subclasses into column C, then hide A and C so I can separate main and subs to more easily iterate like
this
and tried:
mainClassList = []
mainClassDict = defaultdict(list)
activeClassList=[]

for row in ws.iter_rows(min_row=2):
    activeClass ="" #supposed to update this at every
                    #appropriate row
    if row[0].value is not None:
        activeClass=row[0].value
        mainClassList.append(activeClass)
        mainClassDict[activeClass]=[]
        activeClassList.append(activeClass)
    # add 2nd column entries to 1st column keys
    # would be better if these were nested dicts
    if row[0].value is None and row[1].value is not None:
        mainClassDict[activeClass].append(row[1].value)

#check to see things are being added and updated as needed
print("main Class List:", mainClassList)
print("active classes;", activeClassList)
for key, value in mainClassDict.items():
    print(key, ' : ', value)

A: I eventually solved with the following:
mainClassDict = {} #create an empty dictionary for each level
subClassDict = {}
for row in class_sheet.iter_rows(min_row=2):
        #catch only row 1 values
        if row[0].value is not None:
            main = row[0].value
            mainClassDict[main]={}
            subClassDict[main]={}
        # if none in row 1, select row 2 value instead
        if row[0].value is None and row[1].value is not None:
            subclasslist = []
            subclasslist.append(row[1].value)
            #create empty list for data
            attributelist = []
            # populate data list from row of choice
            attributelist.append(row[...].value)
            # populate dict from elements in list using nested for
            for key in subclasslist:
                for value in attributelist:
                    subClassDict[main][key] = value


text:
Q: Using empty PUT on a REST service I'm wondering if it is correct to use a PUT request with an empty body.
The service just clones an existing object and persists it with a new identifier, like
PUT /object/clone/{objectId}
Is this correct?

A: According to this (part about REST-methods):
https://docs.oracle.com/cd/E38689_01/pt853pbr0/eng/pt/tibr/concept_UnderstandingRESTServiceOperations.html
it is better to use the POST-request for this, as long as you are creating a new resource using the existing URL.

A: Since you are creating new element that is legitimate solution. Even better would be to use POST.

A: If you are following a true RESTful approach using PUT/PATCH makes a little sense though PUT/PATCH in some schools of thought is used predominantly to update/edit an existing resource rather than create. If following this thinking a POST request would make more sense.
If I was posed with this dilemma I'd say a POST request would be more viable for creation (how it is created is down to implementation not the language used to request it's construction).


text:
Q: Recursive function called in setTimeout is executing even after navigated to other Angular components It became challenging for me to stop executing a recursive function that is used to display a progress bar even after navigating to different component.
animateProgress() {
    var counter = this.incrementCounter;    //initial value = 0
    if (counter <= 100) {
      this.updateProgressBar(counter);
      setTimeout(()=>{
        this.animateProgress();
      }, 3000);
      this.incrementCounter++;
    }
    else {
      return false;
    }
  }

updateProgressBar(percentage) {
    $('.progressBarDiv').css("width", percentage + "%");
}

A: I think you should use setInterval since you want that part of code to be repeated multiple times.
animateProgress() {
    // removed the local variable counter cause it wasn't really necessary

    // setInterval returns an id that you can later use to cancel the interval
    const interval = setInterval(() => {
        if (this.incrementCounter <= 100) {
          this.updateProgressBar();
          this.incrementCounter++;
        }
        else {
            // when you reach the condition you clear the inverval
          clearInterval(interval);
        }
    }, 3000);
}

updateProgressBar() {
    $('.progressBarDiv').css("width", this.incrementCounter + "%");
}

Otherwise if you wish to stick with setTimeout and recursion this whould work:
animateProgress() {
    if (this.incrementCounter <= 100) {
      this.updateProgressBar();
      this.incrementCounter++;
      setTimeout(()=>{
        this.animateProgress();
      }, 3000);
    }
  }


text:
Q: Can someone give me an example of a layered architecture? I have to do a java application for bank employees hat can add/delete/update accounts and I don't know how to implement a layered architecture. I have the Gui, the database, I know something about the layered architecture but I don't know how to code it.

A: question is too generic, but layered architecture is something that can be applied anywhere. So Android is a good example of layered architecture.
see here http://developer.android.com/about/versions/index.html

A: Since this is so broad, I'll answer very broadly.
Generally it is perceived as a distinctive separation in application behaviour and state, each of which is designed to be applied only to its given concern and should not leak into another's.
This usually ends up as:
A presentation layer (web, desktop gui's, consoles, etc), a Service (business rules go here) layer and a data access layer (DAOs, repositories, etc).


text:
Q: .Net 4.5 and Task.Yield vs Task.Delay as an alternative to DoEvents? Which to use? I have been reading up on the async/await syntax introduced in .Net 4.5 and getting a feel of it.
I have found simple samples where Task.Yield is the way to go rather than Application.DoEvents. I tried one of the samples (filling in the blanks)
Code on Form1 with 1 button:
public async void button1_Click(object sender, EventArgs e) {
    var list = new List<int>();
    for (int i = 0; i < 10000; i++) {
        list.Add(i);
    }
    for (int i = 0; i < list.Count; i++) {
        Process(list[i]);
        await Task.Yield();
        //await Task.Delay(1);
    }
}

public static void Process(int i) {
    Debug.WriteLine(i);
}

However, running this code, the UI thread is blocked or I believe it is blocked as I can not move the window while the code runs. If I comment out the Task.Yield() and use the Task.Delay(1) line instead, the GUI is responsive.
So have I misunderstood something here? I know using DoEvents and the like is bad practice, but I have some legacy code I am responsible for that uses this, and I aim to replace it with Yield as it is the best choice. But first I need to get warm with async/await.

A: async doesn't magically make your code good. Yield is not a direct replacement for DoEvents (which is evil). It will take some work to change the alignment of your code.
As long as you don't need the UI context, you can just push your work off to the threadpool:
public async void button1_Click(object sender, EventArgs e) {
  await Task.Run(() => {
    var list = new List<int>();
    for (int i = 0; i < 10000; i++) {
      list.Add(i);
    }
    for (int i = 0; i < list.Count; i++) {
      Process(list[i]);
    }
  });
}

Alternatively, you can consider breaking up the UI-specific parts either using IProgress<T> or using Task.Run for the non-UI work:
public async void button1_Click(object sender, EventArgs e) {
  var list = new List<int>();
  await Task.Run(() => {
    for (int i = 0; i < 10000; i++) {
      list.Add(i);
    }
  });

  for (int i = 0; i < list.Count; i++) {
    await ProcessAsync(list[i]);
  }
}

public static async Task ProcessAsync(int i) {
  await Task.Run(() => { ... }); // background
  myUi.Text = i.ToString() + " working"; // ui
  await Task.Run(() => { ... }); // more background
  myUi.Text = i.ToString() + " complete"; // ui
}


text:
Q: Error Date format Picture Ends Before Converting Entire Input String In Oracle I'm getting the error:

Error Date format Picture Ends Before Converting Entire Input String

when I'm running the following query:
SELECT *
FROM TABLE
WHERE (trunc(sysdate) - to_date (completion_date,'YYYY-MM-DD'))>0

The completion_date field is in varchar and its value is 2018-11-30 00:00:00.723000

A: The value stored as varchar is a TIMESTAMP, not a DATE.
SQL> alter session set nls_date_format = 'yyyy-mm-dd hh24:mi:ss' ;
Session altered

SQL>  select to_timestamp('2018-11-30 00:00:00.723000','YYYY-MM-DD HH24:MI:SS.FF') from dual;

TO_TIMESTAMP('2018-11-3000:00:00.723000','YYYY-MM-DDHH24:MI:SS.FF')
---------------------------------------------------------------------------
30-NOV-18 12.00.00.723000000 AM

If you want a date
SQL> select to_date(to_char(to_timestamp('2018-11-30 00:00:00.723000','YYYY-MM-DD HH24:MI:SS.FF'),'YYYY-MM-DD HH24:MI:SS')) from dual;

TO_DATE(TO_CHAR(TO_
-------------------
2018-11-30 00:00:00

SQL>

A: You need to take the first 10 characters of the string and proceed as follows:
to_Date(SUBSTR(completion_date,1,10),'YYYY-MM-DD')

A: please use below statement
select * from TABLE where (trunc(sysdate) - to_date(substr(completion_date,1,10),'YYYY-MM-DD'))>0


text:
Q: Jackson databind error with scalatest Flatspec I was trying to execute the scala test cases in IntelliJ using gradle with spark 3.1.1 & scala 2.12.13. But the scala tests were failing with the below jackson-databind error.
val conf = new SparkConf().setMaster("local[2]")

val spark = SparkSession
  .builder()
  .config(conf)
  .appName("Scala Test Cases")
  .getOrCreate()

spark.sparkContext.setLogLevel("ERROR")
import spark.implicits._

Error initializing SparkContext.
com.fasterxml.jackson.databind.JsonMappingException: Scala module 2.12.4 requires Jackson Databind version >= 2.12.0 and < 2.13.0
    at com.fasterxml.jackson.module.scala.JacksonModule.setupModule(JacksonModule.scala:61) ~[jackson-module-scala_2.12-2.12.4.jar:2.12.4]
    at com.fasterxml.jackson.module.scala.JacksonModule.setupModule$(JacksonModule.scala:46) ~[jackson-module-scala_2.12-2.12.4.jar:2.12.4]
    at com.fasterxml.jackson.module.scala.DefaultScalaModule.setupModule(DefaultScalaModule.scala:17) ~[jackson-module-scala_2.12-2.12.4.jar:2.12.4]
    at com.fasterxml.jackson.databind.ObjectMapper.registerModule(ObjectMapper.java:808) ~[spark-cassandra-connector_2.12-3.0.0-jdk11-pie1.0.0.jar:3.0.0-jdk11-pie1.0.0]
    at org.apache.spark.ui.exec.ExecutorsPage.<init>(ExecutorsTab.scala:82) ~[spark-core_2.12-3.1.1.15-apple.jar:3.1.1.15-apple]
    at org.apache.spark.ui.exec.ExecutorsTab.init(ExecutorsTab.scala:41) ~[spark-core_2.12-3.1.1.15-apple.jar:3.1.1.15-apple]
    at org.apache.spark.ui.exec.ExecutorsTab.<init>(ExecutorsTab.scala:34) ~[spark-core_2.12-3.1.1.15-apple.jar:3.1.1.15-apple]
    at org.apache.spark.ui.SparkUI.initialize(SparkUI.scala:65) ~[spark-core_2.12-3.1.1.15-apple.jar:3.1.1.15-apple]
    at org.apache.spark.ui.SparkUI.<init>(SparkUI.scala:81) ~[spark-core_2.12-3.1.1.15-apple.jar:3.1.1.15-apple]
    at org.apache.spark.ui.SparkUI$.create(SparkUI.scala:184) ~[spark-core_2.12-3.1.1.15-apple.jar:3.1.1.15-apple]
    at org.apache.spark.SparkContext.<init>(SparkContext.scala:480) ~[spark-core_2.12-3.1.1.15-apple.jar:3.1.1.15-apple]
    at org.apache.spark.SparkContext$.getOrCreate(SparkContext.scala:2695) ~[spark-core_2.12-3.1.1.15-apple.jar:3.1.1.15-apple]
    at org.apache.spark.sql.SparkSession$Builder.$anonfun$getOrCreate$2(SparkSession.scala:956) ~[spark-sql_2.12-3.1.1.15-apple.jar:3.1.1.15-apple]
    at scala.Option.getOrElse(Option.scala:189) ~[scala-library-2.12.13.jar:?]
    at org.apache.spark.sql.SparkSession$Builder.getOrCreate(SparkSession.scala:950) ~[spark-sql_2.12-3.1.1.15-apple.jar:3.1.1.15-apple]
    at TestClass.getInputDF(TestClass.scala:597) ~[test/:?]
    at TestClass.$anonfun$new$35(TestClass.scala:638) ~[test/:?]
    at org.scalatest.OutcomeOf.outcomeOf(OutcomeOf.scala:85) ~[scalatest_2.12-3.0.4.jar:?]
    at org.scalatest.OutcomeOf.outcomeOf$(OutcomeOf.scala:83) ~[scalatest_2.12-3.0.4.jar:?]
    at org.scalatest.OutcomeOf$.outcomeOf(OutcomeOf.scala:104) ~[scalatest_2.12-3.0.4.jar:?]
    at org.scalatest.Transformer.apply(Transformer.scala:22) ~[scalatest_2.12-3.0.4.jar:?]
    at org.scalatest.Transformer.apply(Transformer.scala:20) ~[scalatest_2.12-3.0.4.jar:?]
    at org.scalatest.FlatSpecLike$$anon$1.apply(FlatSpecLike.scala:1682) ~[scalatest_2.12-3.0.4.jar:?]
    at org.scalatest.TestSuite.withFixture(TestSuite.scala:196) ~[scalatest_2.12-3.0.4.jar:?]
    at org.scalatest.TestSuite.withFixture$(TestSuite.scala:195) ~[scalatest_2.12-3.0.4.jar:?]
    at org.scalatest.FlatSpec.withFixture(FlatSpec.scala:1685) ~[scalatest_2.12-3.0.4.jar:?]
    at org.scalatest.FlatSpecLike.invokeWithFixture$1(FlatSpecLike.scala:1680) ~[scalatest_2.12-3.0.4.jar:?]
    at org.scalatest.FlatSpecLike.$anonfun$runTest$1(FlatSpecLike.scala:1692) ~[scalatest_2.12-3.0.4.jar:?]
    at org.scalatest.SuperEngine.runTestImpl(Engine.scala:289) ~[scalatest_2.12-3.0.4.jar:?]
    at org.scalatest.FlatSpecLike.runTest(FlatSpecLike.scala:1692) ~[scalatest_2.12-3.0.4.jar:?]
    at org.scalatest.FlatSpecLike.runTest$(FlatSpecLike.scala:1674) ~[scalatest_2.12-3.0.4.jar:?]
    at org.scalatest.FlatSpec.runTest(FlatSpec.scala:1685) ~[scalatest_2.12-3.0.4.jar:?]
    at org.scalatest.FlatSpecLike.$anonfun$runTests$1(FlatSpecLike.scala:1750) ~[scalatest_2.12-3.0.4.jar:?]
    at org.scalatest.SuperEngine.$anonfun$runTestsInBranch$1(Engine.scala:396) ~[scalatest_2.12-3.0.4.jar:?]
    at scala.collection.immutable.List.foreach(List.scala:431) ~[scala-library-2.12.13.jar:?]
    at org.scalatest.SuperEngine.traverseSubNodes$1(Engine.scala:384) ~[scalatest_2.12-3.0.4.jar:?]
    at org.scalatest.SuperEngine.runTestsInBranch(Engine.scala:379) ~[scalatest_2.12-3.0.4.jar:?]
    at org.scalatest.SuperEngine.runTestsImpl(Engine.scala:461) ~[scalatest_2.12-3.0.4.jar:?]
    at org.scalatest.FlatSpecLike.runTests(FlatSpecLike.scala:1750) ~[scalatest_2.12-3.0.4.jar:?]
    at org.scalatest.FlatSpecLike.runTests$(FlatSpecLike.scala:1749) ~[scalatest_2.12-3.0.4.jar:?]
    at org.scalatest.FlatSpec.runTests(FlatSpec.scala:1685) ~[scalatest_2.12-3.0.4.jar:?]
    at org.scalatest.Suite.run(Suite.scala:1147) ~[scalatest_2.12-3.0.4.jar:?]
    at org.scalatest.Suite.run$(Suite.scala:1129) ~[scalatest_2.12-3.0.4.jar:?]
    at org.scalatest.FlatSpec.org$scalatest$FlatSpecLike$$super$run(FlatSpec.scala:1685) ~[scalatest_2.12-3.0.4.jar:?]
    at org.scalatest.FlatSpecLike.$anonfun$run$1(FlatSpecLike.scala:1795) ~[scalatest_2.12-3.0.4.jar:?]
    at org.scalatest.SuperEngine.runImpl(Engine.scala:521) ~[scalatest_2.12-3.0.4.jar:?]
    at org.scalatest.FlatSpecLike.run(FlatSpecLike.scala:1795) ~[scalatest_2.12-3.0.4.jar:?]
    at org.scalatest.FlatSpecLike.run$(FlatSpecLike.scala:1793) ~[scalatest_2.12-3.0.4.jar:?]
    at org.scalatest.FlatSpec.run(FlatSpec.scala:1685) ~[scalatest_2.12-3.0.4.jar:?]
    at org.scalatest.tools.SuiteRunner.run(SuiteRunner.scala:45) ~[scalatest_2.12-3.0.4.jar:?]
    at org.scalatest.tools.Runner$.$anonfun$doRunRunRunDaDoRunRun$13(Runner.scala:1340) ~[scalatest_2.12-3.0.4.jar:?]
    at org.scalatest.tools.Runner$.$anonfun$doRunRunRunDaDoRunRun$13$adapted(Runner.scala:1334) ~[scalatest_2.12-3.0.4.jar:?]
    at scala.collection.immutable.List.foreach(List.scala:431) ~[scala-library-2.12.13.jar:?]
    at org.scalatest.tools.Runner$.doRunRunRunDaDoRunRun(Runner.scala:1334) ~[scalatest_2.12-3.0.4.jar:?]
    at org.scalatest.tools.Runner$.$anonfun$runOptionallyWithPassFailReporter$24(Runner.scala:1031) ~[scalatest_2.12-3.0.4.jar:?]
    at org.scalatest.tools.Runner$.$anonfun$runOptionallyWithPassFailReporter$24$adapted(Runner.scala:1010) ~[scalatest_2.12-3.0.4.jar:?]
    at org.scalatest.tools.Runner$.withClassLoaderAndDispatchReporter(Runner.scala:1500) ~[scalatest_2.12-3.0.4.jar:?]
    at org.scalatest.tools.Runner$.runOptionallyWithPassFailReporter(Runner.scala:1010) ~[scalatest_2.12-3.0.4.jar:?]
    at org.scalatest.tools.Runner$.run(Runner.scala:850) ~[scalatest_2.12-3.0.4.jar:?]
    at org.scalatest.tools.Runner.run(Runner.scala) ~[scalatest_2.12-3.0.4.jar:?]
    at org.jetbrains.plugins.scala.testingSupport.scalaTest.ScalaTestRunner.runScalaTest2or3(ScalaTestRunner.java:38) ~[runners.jar:?]
    at org.jetbrains.plugins.scala.testingSupport.scalaTest.ScalaTestRunner.main(ScalaTestRunner.java:25) ~[runners.jar:?]
2021-08-12 15:24:54,556 INFO o.a.s.i.Logging [dispatcher-event-loop-0] MapOutputTrackerMasterEndpoint stopped!

I'm importing scalatest & holdenkarau in build.gradle:
testImplementation("org.scalatest:scalatest_2.12:3.0.4") {
    exclude group: 'com.fasterxml.jackson.core', module: 'jackson-databind'
}
testImplementation("com.holdenkarau:spark-testing-base_2.12:3.0.1_1.1.0"){
    exclude group: 'org.apache.xbean', module: 'xbean-asm6'
}

These tests used to run fine when using spark 2.4.7 & scala 2.11.12 with below dependency versions.
testCompile("org.scalatest:scalatest_2.11:3.0.4")
testCompile("com.holdenkarau:spark-testing-base_2.11:2.4.5_0.14.0"){
    exclude group: 'org.apache.xbean', module: 'xbean-asm6'
}

Not sure what am I missing here. I tried force updating the jackson libraries, but still it is not resolving the issue.
configurations.configureEach {
    resolutionStrategy {
        force "com.fasterxml.jackson.module:jackson-module-scala_2.12:2.12.4"

        force "com.fasterxml.jackson.core:jackson-databind:2.12.4"

        force "com.fasterxml.jackson.core:jackson-core:2.12.4"

        force "com.fasterxml.jackson.core:jackson-annotations:2.12.4"

        force "com.fasterxml.jackson.module:jackson-module-jaxb-annotations:2.12.4"

        force "com.fasterxml.jackson.jaxrs:jackson-jaxrs-json-provider:2.12.4"

        force "com.fasterxml.jackson.jaxrs:jackson-jaxrs-base:2.12.4"

        force "org.scalatest:scalatest_2.12:3.0.4"
    }
}

A: I added the below properties in dependency section that took care of jackson libraries.
implementation ('com.fasterxml.jackson.core:jackson-databind') {
    version {
        strictly "2.12.4"
    }
}

implementation ('com.fasterxml.jackson.core:jackson-core') {
    version {
        strictly "2.12.4"
    }
}

implementation ('com.fasterxml.jackson.core:jackson-annotations') {
    version {
        strictly "2.12.4"
    }
}

Ref: Scala module requiring specific version of data bind for Spark


text:
Q: How to Update Php Variable Every Second? Variable from mySql First of all  Thank You for read my post.
I Have Code Like This.
<?php
   $con=mysqli_connect("localhost","u855423165_ardui","31039731","u855423165_ardui");
   $sql="SELECT * FROM tempLog ORDER BY timeStamp ASC";
   $result=mysqli_query($con,$sql);

   while ($data = mysqli_fetch_array($result,MYSQLI_ASSOC))
   {
     $data_1[] = $data;
   }
   mysqli_close($con);
?>

I and want to make $data_1[] = $data; Update Every Second and The from Updated database or we can say $sql="SELECT * FROM tempLog ORDER BY timeStamp ASC"; re-run to get newest data.
and my second code (chart code)
 <script type="text/javascript">
                AmCharts.makeChart("chartdiv",
                    {
                        "type": "serial",
                        "categoryField": "timeStamp",
                        "dataDateFormat": "YYYY-MM-DD HH:NN:SS",
                        "maxSelectedSeries": -1,
                        "zoomOutButtonTabIndex": 0,
                        "sequencedAnimation": false,
                                            "backgroundColor": "#FFFFFF",
                        "fontFamily": "Cabin",
                        "theme": "dark",
                        "export": {
                            "enabled": true
                        },
                        "categoryAxis": {
                            "minPeriod": "ss",
                            "parseDates": true
                        },
                        "chartCursor": {
                            "enabled": true,
                            "categoryBalloonDateFormat": "JJ:NN:SS"
                        },
                        "chartScrollbar": {
                            "enabled": true,
                            "dragIconWidth": 37,
                            "graphType": "line",
                            "gridColor": "#000000",
                            "hideResizeGrips": true,
                            "minimum": 1,
                            "offset": 2,
                            "tabIndex": 3
                        },
                        "trendLines": [],
                        "graphs": [
                            {
                                "bullet": "round",
                                "id": "AmGraph-1",
                                "title": "graph 1",
                                "valueField": "timeStamp"
                            },
                            {
                                "bullet": "round",
                                "id": "AmGraph-2",
                                "lineThickness": 3,
                                "title": "graph 2",
                                "valueField": "sensor1"
                            },
                            {
                                "bullet": "round",
                                "id": "AmGraph-3",
                                "lineThickness": 3,
                                "title": "graph 3",
                                "valueField": "sensor2"
                            },
                            {
                                "bullet": "round",
                                "id": "AmGraph-4",
                                "lineThickness": 3,
                                "title": "graph 4",
                                "valueField": "sensor3"
                            },
                            {
                                "bullet": "round",
                                "id": "AmGraph-5",
                                "lineThickness": 3,
                                "title": "graph 5",
                                "valueField": "sensor4"
                            },
                            {
                                "bullet": "round",
                                "id": "AmGraph-6",
                                "lineThickness": 3,
                                "title": "graph 6",
                                "valueField": "sensor5"
                            },
                            {
                                "bullet": "round",
                                "id": "AmGraph-7",
                                "lineThickness": 3,
                                "title": "graph 7",
                                "valueField": "sensor6"
                            }
                        ],
                        "guides": [],
                        "valueAxes": [
                            {
                                "id": "ValueAxis-1",
                                "title": ""
                            }
                        ],
                        "allLabels": [],
                        "balloon": {},
                        "titles": [
                            {
                                "id": "Title-1",
                                "size": 15,
                                "text": "Grafik 6 Sensor"
                            }
                        ],
                        "dataProvider": <?php echo json_encode($data_1); ?>
                    }
                );
  </script>

i wanna insert the new variable to my second code and update the chart.
this my how i insert the variable "dataProvider": <?php echo json_encode($data_1);

A: The simplest way forward is to move the once per second loop to JavaScript and have it call PHP once per second since that's more typical for a PHP/JS application.
PHP can do real-time applications with libraries like ReactPHP or Swoole + web sockets, but you should be aware that asynchronous programming is an advanced concept that brings a whole series of complications
As a beginner, you may find NodeJS + socket.io handles this more idiomatically than PHP does, but you may also need to change the database to a reactive one or set up an eventing/pub sub system.
What I'm trying to say is this is a deep rabbit hole to get right, I'd advise running the checking loop in JavaScript to keep things simple


text:
Q: How can I read Persian line in csv file c# I want to read a simple CSV file with comma separated with this code:
 var reader = new StreamReader(File.OpenRead(@"d:\34.csv"));

List<string> listA = new List<string>();
        List<string> listB = new List<string>();
        while (!reader.EndOfStream)
        {
            var line = reader.ReadLine();
            var values = line.Split(',');

            listA.Add(values[0]);
            listB.Add(values[1]);
        }
        MessageBox.Show("READ IT!!!");

But when I read the file an debug that code,attention can not read Persian or Arabic character! How can I solve that? I think my file is not valid encoding?

A: if your CSV file contains just one line the ReadToEnd could be acceptable, but if you have a log file composed by more than one line then it is better to read line by line using ReadLine of the StreamReader object
link for true answer and more information
 using (StreamReader sr = new StreamReader("c:/temp/34.csv"))
    {
        string currentLine;
        // currentLine will be null when the StreamReader reaches the end of file
        while((currentLine = sr.ReadLine()) != null)
        {
            // Search, case insensitive, if the currentLine contains the searched keyword
            if(currentLine.IndexOf("I/RPTGEN", StringComparison.CurrentCultureIgnoreCase) >= 0)
            {
                 Console.WriteLine(currentLine);
            }

        }
    }

More information

A: You can create a class composed of get and set for each line of the CSV . You can then instantiate an object list to retrieve the CSV lines.
Try this way :
class Program
{

static void Main(string[] args)
{

var reader = new StreamReader(File.OpenRead(@"YourCSV"),Encoding.Unicode);

 List<Customer> customer = new List<Customer>();

 while (!reader.EndOfStream)
 {
    Customer c = new Customer
    {
        m_line1 = null,
        m_line2 = null,
    };

     var line = reader.ReadLine();
     var tokens = line.Split(',');

     c.m_line1 = tokens[0];
     c.m_line2 = tokens[1];
     customer.Add(c);

 }

   foreach(var s in customer)
   {
      Console.Writline(s);
      Console.Readline();
   }
}
}

class Customer
{
   private string line1;
   public string m_line1
   {
   get
   {
     return line1;
   }

  set
  {
    line1= value;
  }
}

private string line2;
public string m_line2
{
  get
  {
    return line2;
  }

  set
  {
    line2= value;
  }
}

A: You will have to pass the character encoding to the StreamReader constructor. There is no such thing as plain text. Reading text requires knowing its encoding.
The line
using (StreamReader sr = new StreamReader("c:/temp/34.csv"))

should be
using (StreamReader sr = new StreamReader("c:/temp/34.csv"), myencoding)

what myencoding is is something only you can know. With what encoding was the file saved? That's the encoding you need there. If the file was generated on Windows, and educated guess of the most likely encoding would be it is UTF-16LE. That encoding is available as Encoding.Unicode - which is a bad name, it should have been Encoding.UTF16LE, but that's the name the .NET framework uses.
Other possible encodings that are supported by StreamReader are listed on https://msdn.microsoft.com/en-us/library/System.Text.Encoding_properties(v=vs.110).aspx
If you don't know with what encoding the file was saved, some encodings leave hints in the form of a Byte order mark sometimes abbreviated to BOM. A byte order mark are the first few bytes of a text document that tell you its encoding. You can find more information on the byte order mark, and some of its values on http://en.wikipedia.org/wiki/Byte_order_mark
Relying on the BOM is generally a bad idea, because

*

*it's not a full-proof solution: some encodings don't use a BOM, or make the BOM optional

*Even if you successfully determine the encoding, that doesn't mean that StreamReader knows how to handle that encoding (though this is unlikely, but possible)

*the BOM might not be a BOM at all, but be part of the actual text (also unlikely but possible)

In some cases it is impossible to know the encoding of a file, notably if the file comes from a file upload on the web, or if someone just mailed you the file, and they don't know how they encoded it. This can be a good reason not to allow "plain text" uploads (which is reasonable because, it can do with a little repetition, there is no such thing as plain text).
tl;dr: The most likely thing to work is one of
using (StreamReader sr = new StreamReader(File.OpenRead(@"c:/temp/34.csv"),Encoding.Unicode) {
  ...
}

or
using (StreamReader sr = new StreamReader(File.OpenRead(@"c:/temp/34.csv"),Encoding.UTF8)

or
using (StreamReader sr = new StreamReader(File.OpenRead(@"c:/temp/34.csv"),Encoding.UTF32)


text:
Q: Query Notification doesn't work for multiple tables I have the following setup:

*

*A WCF service which uses the query notification to monitor
changes on "Table1" say WCFService1

*Another WCF service which uses the query
notification to monitor changes on "Table2" say WCFService2

*Both service use the
"Start" and "Stop" method called by separate client to start the
notification

*A Windows Service client hosted on server which sends request to both WCF service a request to start the notification.

The problem is if the windows service client says WCFService1.Start and then WCFService2.Start, I get a notification from the table that was registered by WCFService2 i.e. "Table2". If I switch them around, then I get a notification only from WCFService1 i.e. "Table1".
This means that I get notification from only one table (which was registered last) where as I am expecting to receive a notification from  the other table. It seems that this whole "Query Notification" doesn't work with multiple notifications on different tables.
Any ideas?


text:
Q: Métodos estáticos em Factory Method Estou criando uma classe utilizando Factory Method e me surgiu a seguinte dúvida.
É recomendável a utilização de métodos estáticos em Factories?
Em muitos exemplos que encontrei temos que criar uma instância da classe Factory, mas no meu caso não pensei em nenhuma razão para que a mesma precise ser instanciada.
<?php
/* Factory and car interfaces */
interface CarFactory {
    public function makeCar();
}

interface Car {
    public function getType();
}

/* Implementações da Factory e Car */
class SedanFactory implements CarFactory {
    public function makeCar() {
        return new Sedan();
    }
}

class Sedan implements Car {
    public function getType() {
        return 'Sedan';
    }
}

/* Client */
$factory = new SedanFactory();
$car = $factory->makeCar();
print $car->getType();

Fonte
Notem a diferença na implementação com métodos estáticos:
<?php
/* Factory and car interfaces */
interface CarFactory {
    public static function makeCar();
}

interface Car {
    public function getType();
}

/* Implementações da Factory e Carro */
class SedanFactory implements CarFactory {
    public static function makeCar() {
        return new Sedan();
    }
}

class Sedan implements Car {
    public function getType() {
        return 'Sedan';
    }
}

/* Client */
$car = SedanFactory::makeCar();
print $car->getType();

A: Notem que existem 2 design patterns relacionados ao Factory Method:

*

*Factory Method - http://sourcemaking.com/design_patterns/factory_method

*Static Factory Method - http://www.informit.com/articles/article.aspx?p=1216151
Portanto, a resposta à sua pergunta é, depende do design pattern desejado.
O Factory Pattern é implementado como discutido até agora, sem métodos estáticos. Contudo, o Static Factory Method, é um pouco diferente (o exemplo é em Java mas acredito que a ideia seja a mesma):
public class Boolean {
  ...
  public static Boolean valueOf(boolean b) {
     return b ? Boolean.TRUE : Boolean.FALSE;
  }
  ...
}

O Static Factory Method é mais simples e já retorna o tipo da prórpria classe, como no exemplo do Boolean.
Já o Factory Method, não é definido utilizando métodos estáticos. Inclusive, sua implementação na wikipedia (http://pt.wikipedia.org/wiki/Factory_Method) não utiliza métodos estáticos.
Acredito que, há um PORÉM em tudo isso. Design Patterns são guias de boas práticas mas podem ser adaptados para nossas necessidades. Caso se instanciar objetos a toda hora que se chama o método da factory seja custoso, não vejo problemas em utilizar métodos estáticos. Contudo, isso é uma modificação do design pattern.

A: Não sendo estática você ganha na "configuração" e na "troca" da sua fábrica.
Com configuração, quero dizer que você pode alterar o valor ou chamar um método qualquer da classe SedanFactory antes de chamar makeCar(), alterando como o carro será construído (como o Renan falou).
Com a troca da fábrica, quero dizer que você pode ter um método que recebe como parâmetro um objeto de uma classe qualquer que implementa CarFactory, sabendo que poderá chamar makeCar() para construir um carro sem precisar de saber se é SedanFactory ou SUVFactory.


text:
Q: Error is showing when importing the Slides in Ionic 4 I am working in my Ionic 4 app and I have imported the Slides in my app but it is showing the error.
This is my intro.page.ts:
import { Slides } from '@ionic/angular';
@Component({
  selector: 'app-intro',
  templateUrl: './intro.page.html',
  styleUrls: ['./intro.page.scss'],
})
export class IntroPage implements OnInit {
  @ViewChild('slides') slides: Slides;
  constructor(private storage: Storage, private router: Router) { }

  ngOnInit() {
  }

  next() {
    this.slides.slideNext();
  }
}

Error:

Module
  '"../../../../../Users/challengesnew/node_modules/@ionic/angular/dist/core"'
  has no exported member 'Slides'.

Any help is much appreciated.

A: According to the GitHub issue and the mentioned changelog,
all ionic components are prefixed with Ion if you want to import.
Change your import to:
import { IonSlides } from '@ionic/angular';

and
 @ViewChild('slides') slides: IonSlides;

A: Now, With Angular 8, while the import stays the same:
import { IonSlides } from '@ionic/angular';

in the @ViewChild decorator, the static property is required inside the options parameter, as following:
@ViewChild('slides', {static: true}) slides: IonSlides;


text:
Q: Class file somehow not allowing multi-page deluxetable to fill each page Working with a thesis class file, I find that my multi-page deluxetables are not permitted to fill the margins all the way, but instead fill only about half the height of the page, and maybe ~2/3 of the area allowed by the margins.  Because of the complexity in my table formatting (more complex than the MWE I show here), I really need to stick with deluxetable rather than converting to a more normal LaTeX table format.
When I switch to the normal article class my tables work just fine.
One possibly relevant piece is that when I compile my document, I get a warning

! Undefined control sequence.
  l.12 \startlongtable

I find this frustrating because I'm using almost the same deluxetable environment available from NASA (only one line commented out in mine, line 299) but am adding the \startlongtable command based on the AASTeX v6.3 instructions for multi-page tables but it seems the NASA-provided file is now out of date and does not have \startlongtable implemented.
So basically, I don't know whether the fundamental issue is my not having \startlongtable defined (but still telling LaTeX to go ahead with compilation anyway, which it does) or whether it's something in the class file I am using.
Edit: I noticed that even tables I haven't explicitly set to be multi-page tables via \startlongtable are also breaking up over pages, about the same size as the other tables.
MWE:
First the class file, thesismod.cls, which I cut a bunch of stuff out of from the original.  I find that removing either \doublespacing or \makelot makes the table fill up the page within the margins.
\NeedsTeXFormat{LaTeX2e}
\ProvidesClass{thesismod}
\RequirePackage{setspace}
\newcommand*{\mainmatter}{\pagenumbering{arabic}}
\newcommand*{\makelot}{}
\newcommand*{\begincmd}{
\doublespacing
\makelot
\clearpage\mainmatter}

\DeclareOption*{\PassOptionsToClass{\CurrentOption}{report}}
\ProcessOptions
%% Not necessary to specify the point size - we inherit it from above
% \LoadClass[12pt]{report}
\LoadClass{report}
\setlength{\oddsidemargin}{.5in}   %{.4375in}
\setlength{\evensidemargin}{.5in} %{.4375in}
\setlength{\topmargin}{-.5in}  %{-.5625in}
\setlength{\textheight}{9in}
\setlength{\textwidth}{6in}
\AtBeginDocument{\begincmd}
\endinput

As mentioned, the deluxetable.sty is the same file as available from NASA with line 299 commented out.
And my main file:
\documentclass[12pt]{thesismod}

\usepackage{deluxetable}
\usepackage{longtable}

\begin{document}

\startlongtable
\begin{deluxetable}{c}
\tablewidth{0pc}
\tabletypesize{\scriptsize}
\tablecolumns{10}
\tablecaption{Title}
\tablehead{\colhead{ID }}
\startdata
W491 \\W508 \\W521 \\W566\\W689\\W799 \\W837 \\W869 \\W1091 \\W1154\\W1165 \\W1349\\W1582\\W1601 \\W1608 \\W1735 \\W1763 \\W1848 \\W1912 \\W1978 \\W2005 \\W2015 \\W2162 \\W2386 \\W2631 \\W2665 \\W2678 \\W2740 \\W2772 \\W2887 \\W2951 \\W3014 \\W3033 \\W3070 \\W3073 \\W3114 \\W3259 \\W3407 \\W3430 \\W3480 \\W3485 \\W3742 \\W3957 \\W3996 \\W4081 \\W4237 \\W4333 \\W4361 \\W4490 \\W58 \\W267 \\W371 \\W435 \\W461 \\W829 \\W901 \\W920 \\W1056 \\W1068 \\W1208 \\W1222 \\W1263 \\W1539 \\W1717 \\W1725 \\W1809 \\W1834 \\
\enddata
\end{deluxetable}

\end{document}

A: I found that encasing the table in a single space environment worked.  Also I dropped the \startlongtable since it wasn't doing anything as an undefined command.
\documentclass[12pt]{thesismod}

\usepackage{deluxetable}
\usepackage{longtable}

\begin{document}

\begin{singlespace}
\begin{deluxetable}{c}
\tablewidth{0pc}
\tabletypesize{\scriptsize}
\tablecolumns{10}
\tablecaption{Title}
\tablehead{\colhead{ID }}
\startdata
W491 \\W508 \\W521 \\W566\\W689\\W799 \\W837 \\W869 \\W1091 \\W1154\\W1165 \\W1349\\W1582\\W1601 \\W1608 \\W1735 \\W1763 \\W1848 \\W1912 \\W1978 \\W2005 \\W2015 \\W2162 \\W2386 \\W2631 \\W2665 \\W2678 \\W2740 \\W2772 \\W2887 \\W2951 \\W3014 \\W3033 \\W3070 \\W3073 \\W3114 \\W3259 \\W3407 \\W3430 \\W3480 \\W3485 \\W3742 \\W3957 \\W3996 \\W4081 \\W4237 \\W4333 \\W4361 \\W4490 \\W58 \\W267 \\W371 \\W435 \\W461 \\W829 \\W901 \\W920 \\W1056 \\W1068 \\W1208 \\W1222 \\W1263 \\W1539 \\W1717 \\W1725 \\W1809 \\W1834 \\
\enddata
\end{deluxetable}
\end{singlespace}

\end{document}


text:
Q: QGIS 2.18 ImportError: DLL load failed: The specified module could not be found I try to run the QSwat script and it begins with that:
from PyQt4.QtCore import * # @UnusedWildImport
from PyQt4.QtGui import * # @UnusedWildImport
from qgis.core import * # @UnusedWildImport
from qgis.gui import * # @UnusedWildImport

However I get this error:
Traceback (most recent call last):
  File "C:/Program Files/QGIS 2.18/apps/qgis/python/plugins/HidroTurk/HT_HJK/delineation.py", line 25, in <module>
    from qgis.core import * # @UnusedWildImport
  File "C:\Program Files\QGIS 2.18\apps\qgis\python\qgis\__init__.py", line 26, in <module>
    from qgis.PyQt import QtCore
  File "C:\Program Files\QGIS 2.18\apps\qgis\python\qgis\PyQt\QtCore.py", line 28, in <module>
    sip.setapi(api, 2)
ValueError: API 'QDate' has already been set to version 1

I read that if I import qgis.core and qgis.gui later, it fixes the problem so I wrote like that:
from qgis.core import * # @UnusedWildImport
from qgis.gui import * # @UnusedWildImport
from PyQt4.QtCore import * # @UnusedWildImport
from PyQt4.QtGui import * # @UnusedWildImport

I got this error:
Traceback (most recent call last):
  File "C:/Program Files/QGIS 2.18/apps/qgis/python/plugins/HidroTurk/HT_HJK/delineation.py", line 23, in <module>
    from qgis.core import * # @UnusedWildImport
  File "C:\Program Files\QGIS 2.18\apps\qgis\python\qgis\__init__.py", line 27, in <module>
    from qgis.core import QgsFeature, QgsGeometry
  File "C:\Program Files\QGIS 2.18\apps\qgis\python\qgis\core\__init__.py", line 30, in <module>
    from qgis._core import *
ImportError: DLL load failed: The specified module could not be found

I am sure that the problem source is PATH, PYTHONPATH and PYTHONHOME. Because I got this error in QGIS 3 and I solved it by adding paths that can be reached by writing python console print (sys.path) to the system variables of PATH and PYTHONPATH.
However I can not fix it with the same way. I have been handling with it for 5 days and I will go crazy!
Note: I can import them in QGIS 2.18 python console.

A: I'm using a batchfile to set the environment for python and qgis, like this:
SET QGIS_PREFIX_PATH=%OSGEO4W_ROOT:\=/%/apps/qgis
SET PYTHONPATH=%OSGEO4W_ROOT%\apps\qgis\python
SET PYTHONHOME=%OSGEO4W_ROOT%\apps\Python27
SET PATH=%PATH%;%OSGEO4W_ROOT%\apps\Python27\Scripts;%OSGEO4W_ROOT%\apps\qgis\bin

I put this batch file into the directory %OSGEO4W_ROOT%\etc\ini which is autmatically called by the OSGeo4W-Shell, or you can start mostly any Python-IDE by batch file and call that ini-batch file (here for pyscripter):
set PYSC_DIR=%~dp0

for %%F in ("%OSGEO4W_ROOT%\etc\ini\*.bat") do call "%%F"

SET PYTHONPATH=%PYTHONPATH%;%PYSC_DIR%;%PYSC_DIR%\lib;
SET PATH=%PYSC_DIR%;%PATH%

start "PyScripter" %PYSC_DIR%\PyScripter.exe --python27 --pythondllpath=%OSGEO4W_ROOT%\bin


text:
Q: Section Navigation I have achieved the section navigation.In that i am facing one probelm we have a header of height 120px with position:fixed .Since section navigation always move the section to the top of the window .Some of the content become hidden inside the 120px header.For that i made padding as 120px.but it looks odd since each and every section has the gap of 120px makes the section ugly.how can i make the content visible without adding the padding :120px.

-----------------------------------------------> on click of navigation content header came here and become hidden
Header - 120px

Content

just like this it is happening - http://www.w3.org/TR/REC-html40/struct/links.html#h-12.2.4
Since i am using fixed header.Content is hihding inside the Header
Updated - Added Fiddler
Whats happening : http://jsfiddle.net/rg46D/
How i fix that : http://jsfiddle.net/rg46D/1/
What i want to remove : Adding the padding top 80px;creating more space between the content.how to make the content visible without adding the padding top 80px

A: You need to wrap a div before your section with padding:

HOme

Links

about

and provide padding to this class:
.wrapper {
    padding-top:80px;
}

Add Js:
 $('.menu a').click(function (e) {
    var link = $(this).attr('href');
    $('.wrapper div').css({
        paddingTop: '0',
        marginTop: '0'
    });
    $(link).css({
        paddingTop: '80px',
        marginTop: '-80px'
    });
});

Demo
Add this .wrapper div in all your inner pages to get the desired result.

A: Finally i did that by dynamically adding the padding-top on click event and removing it when scroll event fires.
calling this onclick :
$('#id').css('padding-top','100px')

and setting a flag to true;
on scroll event checking for the flag and changing it back to the
$('#id').css('padding-top','0px')

A: Well I guess in this case jQuery might be useful. using which you can calculate how much space you want from top
$('.menu a').click(function(e){
    e.preventDefault();
    var getEle = $(this).attr('href');
    var navHeight = 72 // if you want you may calculate it dynamically using jQuery it would be better

    $("body, html").animate({
        scrollTop: ($(getEle).position().top)-navHeight
    });
});

Hope this helps!


text:
Q: Parse JSON array value as std::string using Boost I'm trying to parse a std::string JSON string with this code:
        std::string ss = "{ \"id\" : \"abc123\", \"number\" : \"0123456789\", \"somelist\" : [{ \"timestamp\" : \"May 1, 2015\" , \"data\" : { \"description\" : \"some description\", \"value\" : \"100.000000\" } }] }";

        ptree pt2;
        std::istringstream is(ss);
        read_json(is, pt2);
        std::string _id = pt2.get<std::string>("id");
        std::string _number = pt2.get<std::string>("number");
        std::string _list = pt2.get<std::string>("somelist");

        for (auto& e : pt2.get_child("somelist")) {
            std::cout << "timestamp: " << e.second.get<std::string>("timestamp") << "\n";
            for (auto& e1 : pt2.get_child("data")){ // not working
                std::cout << "description: " << e1.second.get<std::string>("description") << "\n";
                std::cout << "value: " << e1.second.get<std::string>("amount") << "\n";
            }
        }

Although my target is not to print the child items (nor convert the JSON string into C++ array). The code above does not work.
I want to know how to get the value of data not as array or something, just as string like this [{ "timestamp" : "May 1, 2015" , "data" : { "description" : "some description", "value" : "100.000000" } }]
Just need the JSON Array as-is as std::string

A: boost/property_tree/json_parser.hpp implements write_json, which is, as you would expect, the inverse of read_json. Since ptree stores arrays as objects with an empty key, to achieve the representation you want, you would loop over the top-level ptrees in pt2.get_child("somelist"), call write_json on each of them and format these representations as you wish.
for(auto const& node : pt2.get_child("somelist"))
 write_json(std::cout, node.second);

Coliru Demo.


text:
Q: Strange $.post() AJAX error when parsing JSON I am facing this strange error in using $.post.
works
$("#add-video").click(function(){
    var url = $("#new-video-url").val();
    $('#loader').show();
    $.post( base_url + "forms/coach/get_url.php", { url:url, base_url:base_url }, function(data){
        alert(data);
                    $('#loader').hide();
    });
});

The above piece of code, shows me the json array I am receiving using a php file, and also shows the title field here, and hides the loader image.
But when I alert(data.title), it shows me undefined. More over, when I add datatype 'json' to $.post,
doesn't work
$("#add-video").click(function(){
    var url = $("#new-video-url").val();
    $('#loader').show();
    $.post( base_url + "forms/coach/get_url.php", { url:url, base_url:base_url }, function(data){
        alert(data);
                    $('#loader').hide();
    }, "json"); //Added datatype here.
});

This neither alerts anything nor does it hide the loader image. I also tried,
$("#add-video").click(function(){
    var url = $("#new-video-url").val();
    $('#loader').show();
    $.post( base_url + "forms/coach/get_url.php", { url:url, base_url:base_url }, function(data){
        jQuery.parseJSON(data);
                    alert(data.title);
                    $('#loader').hide();
    });
});

The above one too neither alerts anything nor does it hide the loader. And then I tried this one too that did nothing.
$("#add-video").click(function(){
    var url = $("#new-video-url").val();
    $('#loader').show();
    $.post( base_url + "forms/coach/get_url.php", { url:url, base_url:base_url }, function(data){
        jQuery.parseJSON(data);  //tried without this too.
                    alert(data['title']);
                    $('#loader').hide();
    });
});

The strangest thing is that I have previously used json as I have shown in the 2nd script(out of 4), and that works normally. My JS console too doesn't show any errors or warning. What am I doing wrong here? How do I access the title field of data?
If this helps, here is how I send the json array,
$json = array("title" => $title, "embed" => $embed, "desc" => $desc, "duration" => $duration, "date" => $date);
print_r(json_encode($json));

I would really appreciate if someone can point out the error and tell me why my scripts are failing, similar functions worked in other js file.
here is my data, that is returned by server,

{"title":"Sunn Raha Hai Na Tu Aashiqui 2 Full Song With Lyrics |
  Aditya Roy Kapur, Shraddha Kapoor","embed":"\r\t\t\t\t\t\r\t\t\t\t\t</param></param>\r\t\t\t\t\t</param>\r\t\t\t\t\t\r\t\t\t\t\t</embed></object>","desc":"Presenting
  full song \"Sun Raha Hai Na Tu\" with lyrics from movie \"Aashiqui 2\"
  produced by T-Series Films & Vishesh Films, starring Aditya Roy Kapur,
  Shraddha Kapoor in voice of Ankit Tiwari. \n\nSong: SUNN RAHA
  HAI\nSinger: ANKIT TIWARI\nMusic Director: ANKIT TIWARI\nAssistant Mix
  Engineer - MICHAEL EDWIN PILLAI\nMixed and Mastered by ERIC PILLAI
  (FUTURE SOUND OF BOMBAY)\nLyrics:SANDEEP NATH\nMovie: AASHIQUI
  2\nProducer: BHUSHAN KUMAR KRISHAN KUAMR  Producer: MUKESH BHATT
  \nDirector: MOHIT SURI\nMusic Label: T-SERIES\n\nBuy from iTunes -
  https://itunes.apple.com/in/album/aashiqui-2-original-motion/id630590910?ls=1\n\nEnjoy
  & stay connected with us!! \n\nSUBSCRIBE T-Series channel for
  unlimited entertainment\nhttp://www.youtube.com/tseries\n\nCircle
  us on G+ \nhttp://www.google.com/+tseriesmusic\n\nLike us on
  Facebook\nhttp://www.facebook.com/tseriesmusic\n\nFollow
  us\nhttp://www.twitter.com/_Tseries","duration":"391","date":"2013-04-03"}

Edit
This worked suddenly.. :o
  $("#add-video").click(function(){
    var url = $("#new-video-url").val();
    $('#loader').show();
    $.post( base_url + "forms/coach/get_url.php", { url:url, base_url:base_url }, function(data){
            alert(data.desc);
            console.log(data.desc);
            $("#loader").hide();

    }, "json");
});

A: In comments, you mention that this AJAX corresponds to a YouTube API.
YouTube's blog announced in 2012 that they would support CORS, which uses server-side header flags that compatible browsers interpret as permitting requests that would otherwise be prohibited by browser security Same-Origin-Policy.
Assuming, as you say, the first example worked, the first issue was "Why did (a subsequent) alert(data.title) fail? (my edit) ".  If you type alert(data.title) in the console, it will fail because the scope of data is the callback function where it is defined as a parameter, and in the global scope data is undefined.  If you try to pass data back to the global scope somehow, it can still be undefined because $.post returns immediately, before the data has been fetched, and merely queues a request and sets the callback function you supply to handle the reply.
The second example, which explicitly sets the $.post dataType parameter to 'json',  may fail with CORS based API because the mime types for json are not allowed to be sent up to the server as Content-Type: for a simple CORS request, and $.post will as far as I know only do simple requests without preflight. $.ajax can possibly do the more complex requests if correctly applied.
The work around to keep using $.post is not to use json as the expected data type, send requests up as form data, the server may send you back json anyway if that is what the API says will happen, which can be verified while testing the code.
From https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS

Simple requests
A simple cross-site request is one that:
Only uses GET, HEAD or POST.
If POST is used to send data to the
  server, the Content-Type of the data sent to the server with the HTTP
  POST request is one of application/x-www-form-urlencoded,
  multipart/form-data, or text/plain.

Notice that application/json did not make the list of what Content-Type is permissible in a simple CORS request.
See also A CORS POST request works from plain javascript, but why not with jQuery?

A: Use ajax as
$.ajax({
url:url,
type:'post',
dataType:'json',
success:callback
})

With this type you can set lots of parameter in low level.
With datatype attribute jQuery parses JSON and send data as callback function.

A: I think you have to replace all single \ with double '\' to feed it to JSON.parse.


text:
Q: underscore module in webpack 5 module federation I am trying to add module federation plugin in webpack 5 react project. But in my react project there is a module of underscore and when I start webpack-dev-server I get following warning
WARNING in shared module underscore -> /c/Users/abc/projectname/node_modules/underscore/modules/index-all.js
No version specified and unable to automatically determine one. No version in description file (usually package.json). Add version to description file, or manually specify version in shared config.


text:
Q: How to extend built-in types with a set of attributes? I need to extend several xml elements of different XML Schema built-in types (e.g. xs:anyURI, xs:string...) with the same two attributes att1 and att2 over and over again.
Example xml to validate:
<extendedURI att1="abc" att2="def">my.uri</extendedURI>

I have tried defining a complex type parent:
<!-- The parent type defines the two attributes I'm interested in -->
<xs:complexType name="parentType">
    <xs:attribute name="att1" type="xs:string" />
    <xs:attribute name="att2" type="xs:string" />
</xs:complexType>

and then declaring the type of my elements as xs:anyURI and extending them, but this is not valid:
<!-- XXX: The following is not permitted: I cannot redefine the xs:anyURI type -->
<xs:element name="extendedURI" type="xs:anyURI">
    <xs:complexType>
        <xs:complexContent>
            <xs:extension base="parentType" />
        </xs:complexContent>
    </xs:complexType>
</xs:element>

I have also tried to restrict the simpleContent to xs:anyURI and extended it with parentType, but I couldn't find how. Something like:
<xs:element name="extendedURI">
    <xs:complexType>
        <xs:simpleContent>
            <!-- XXX: This is not permited: -->
            <xs:restriction base="xs:anyURI">
            </xs:restriction>
            <xs:extension base="parentType">
            </xs:extension>
            <!-- 'xs:restriction' and 'xs:extension' are alternatives and
            cannot be defined at the same time!
            -->
        <xs:simpleContent>
    </xs:complexType>
</xs:element>

So how could I accomplish this? Is it possible to extend a built-in type with a complexType (or to restrict a complexType with the definition of a built-in type)?

A: It is possible to reuse the same set of attributes by using the xsd:attributeGroup:
<!-- several types will declare this set of attributes -->
<xs:attributeGroup name="extensible">
    <xs:attribute name="att1" type="xs:string" />
    <xs:attribute name="att2" type="xs:string" />
</xs:attributeGroup>

<!-- extending a simple content element with the two 'inherited' attributes -->
<xs:element name="extendedURI">
    <xs:complexType>
        <xs:simpleContent>
            <xs:extension base="xs:anyURI">
                <xs:attributeGroup ref="extensible"/>
            </xs:extension>
        </xs:simpleContent>
    </xs:complexType>
</xs:element>