text:
Q: How does C# choose with ambiguity and params Say I have the following methods:
public static void MyCoolMethod(params object[] allObjects)
{
}

public static void MyCoolMethod(object oneAlone, params object[] restOfTheObjects)
{
}

If I do this:
MyCoolMethod("Hi", "test");

which one gets called and why?

A: The second one, the compiler will first try to resolve against explicitly declared parameters before falling back on the params collection.

A: It's easy to test - the second method gets called.
As to why - the C# language specification has some pretty detailed rules about how ambiguous function declarations get resolved.  There are lots of questions on SO surrounding interfaces, inheritance and overloads with some specific examples of why different overloads get called, but to answer this specific instance:
C# Specification - Overload Resolution

7.5.3.2 Better function member
For the purposes of determining the
better function member, a
stripped-down argument list A is
constructed containing just the
argument expressions themselves in the
order they appear in the original
argument list.
Parameter lists for each of the
candidate function members are
constructed in the following way:

*

*The expanded form is used if
the function member was applicable
only in the expanded form.

*Optional parameters with no
corresponding arguments are removed
from the parameter list

*The parameters are reordered
so that they occur at the same
position as the corresponding argument
in the argument list.

And further on...

In case the parameter type sequences {P1, P2, …, PN} and {Q1, Q2, …, QN} are equivalent > (i.e. each Pi has an identity conversion to the corresponding Qi), the following
tie-breaking rules are applied, in order, to determine the better function member.

*

*If MP is a non-generic method and MQ is a generic method, then MP is better than MQ.

*Otherwise, if MP is applicable in its normal form and MQ has a params array and is
applicable only in its expanded form, then MP is better than MQ.

*Otherwise, if MP has more declared parameters than MQ, then MP is better than MQ.
This can occur if both methods have params arrays and are applicable only in their
expanded forms.

The bolded tie-breaking rule seems to be what is applying in this case. The specification goes into detail about how the params arrays are treated in normal and expanded forms, but ultimately the rule of thumb is that the most specific overload will be called in terms of number and type of parameters.

A: This overload is tricky...
MyCoolMethod("Hi", "test") obviously calls the 2nd overload, but
MyCoolMethod("Hi");  also calls the 2nd overload. I tested this.
Maybe since both of the inputs are objects, the compiler assume anything passed in will be an array of objects and completely ignores the 1st overload.
It probably has to do with the Better function member resolution mentioned by womp
http://msdn.microsoft.com/en-us/library/aa691338(v=VS.71).aspx


text:
Q: Microsoft Excel 2007 ignores / resets margins, are there any "known issue" fixes? I have an .xlsx file that I fill in automatically in C#. If I open the resulting file on a system with Office 2016, the custom margins and other print options are intact. Office 2007 though resets them to some default, making it not fit on the page when printing anymore.

A: I haven't found an exact official article to explain this phenomenon, but lower versions of word are not compatible with files generated by higher versions of word.
I recommend that these files be saved in the "word 97 - 2003" format.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Synchronization on App Engine I'm building an application using Google App Engine.  The application consists of several servlets, one of which has a static member object that holds a lot of internal state.  Multiple Android phones contact this servlet, causing the servlet to update the state of the static member object.  However, when multiple phones happen to talk to the server at the same time, I get synchronization issues in which the static object is being modified by multiple threads at once.  I've tried throwing in some synchronized blocks, but this does not seem to help.
I think the reason has something to do with how App Engine spawns threads for HTTP requests, but I'm not sure.  What's the standard way to synchronize access to shared objects in App Engine?  Thanks!

A: Your GAE app can be started on different servers, there can be, and will be few instances at one time. Any instance can be started or killed at any time, without any notice before. So, any in-memory state is useless.
You have to use or memcache service, or database instead.


text:
Q: What powershell command can change the TextInfo.ListSeparator? I am loading data into ERP software which requires the end user to change their default ListSeparator from , to |
Documentation for the software states that the user should open "Region and Language" settings and select the "Additional Settings..." button to change it, however I am trying to avoid users having to make this change.
I would like to automate the process to change the listSeparator for the duration of this process but also automatically change it back and not leave it as |

A: To give credit where credit is due, please see original source of this function located at:
https://gist.github.com/abombss/1129655
function toggle-list-sep
{
  $path = "hkcu:\Control Panel\International"
  $key = "sList"

  $cur_sep = (Get-ItemProperty -path $path -name $key).$key

  if ($args.Length -gt 0) { $value = $args[0] }
  elseif ($cur_sep -eq ",") { $value = "|" }
  else { $value = "," }

  Set-ItemProperty -path $path -name $key -Value $value -type string
  $new_sep = (Get-ItemProperty -path $path -name $key).$key

  Write-Output "Changed $path.$key from '$cur_sep' to '$new_sep'"
}

From that you should be able to either just run the function before and after the application or extrapolate what you need to make the exact script that you want.


text:
Q: Searching for a similar tex font I'm trying to find out what font this book is written with and which similar tex font I could use. Any idea?

A: I think it could be Monotype Garamond:

Look for example at the slope of the aperture in the lowercase "a", and the tail's angle in uppercase "Q". The weight is also a good match, I think.
EB Garamond is available on CTAN (\usepackage{ebgaramond}) and it's quite close. Another option would be URW Garamond (or, better, the package garamondx for small caps and old-style numerals), but in my opinion it's less similar to Monotype than EB (especially in the italics).
EB Garamond:
URW Garamond:


text:
Q: HSTS understanding I'm interested in HSTS mechanism and want to clarify following moment:
For example, there is site https://example.com exists. I use chrome://net-internals/#hsts to check if HSTS enabled there. And it shows the next information:
static_sts_domain:
static_upgrade_mode: UNKNOWN
static_sts_include_subdomains:
static_sts_observed:
static_pkp_domain:
static_pkp_include_subdomains:
static_pkp_observed:
static_spki_hashes:
dynamic_sts_domain: example.com
dynamic_upgrade_mode: FORCE_HTTPS
dynamic_sts_include_subdomains: true
dynamic_sts_observed: 1524145911.957196
dynamic_sts_expiry: 1555681911.957194
dynamic_pkp_domain:
dynamic_pkp_include_subdomains:
dynamic_pkp_observed:
dynamic_pkp_expiry:
dynamic_spki_hashes:

So I expect and think that HSTS is enabled there. But at the same moment there is no Strict-Transport-Security header in response. Why does chrome show such information and is HSTS enabled for that site?

A:
But at the same moment there is no Strict-Transport-Security header in response.

It must have been there at some point because the dynamic entry has been added to your instance of Chrome.
Also remember that HSTS can be sent on any resource, not just the main document. So if you have it being sent on a logo resource, then that will set it for the whole domain.
You could clear it using the same chrome://net-internals/#hsts page and see if it comes back after browsing around? If so then something is still sending it, if not then maybe the site used to advertise HSTS but no longer does.
It was set to be active for one year:
(1555681911.957194 - 1524145911.957196) / 365 / 24 / 60 = 1 year

And from my rough calculations trying to convert those date stamps, it looks like it was last set on 20th April 2018.
If the site has indeed stopped using HSTS, for whatever reason, it might be better to advertise a 0 header instead so at least those visitors that visit over HTTPS now will remove the policy:
Strict-Transport-Security: max-age=0; includeSubDomains

Anyone who doesn't visit over HTTPS will not get this cleared until it expires.

A: HSTS represents HTTP Strict Transport Security. At the point when you have HSTS support it doesn't permit the site to be initially stacked in HTTP before utilizing the 301 redirects. This implies there is no time for any programmers to slip in and use it with HTTP and keep the site from stacking HTTPS. HSTS permits the site to stack just in HTTPS giving an additional layer of security for your site. This security layer tells the program that the site has HTTPS assurance and there is no compelling reason to attempt to access the site in HTTP. This will close the little window that the programmers got during the 301 redirects.
See Steps below:

To know detailed understanding of hypertext protocols and HSTS support click here.


text:
Q: Intellij 12.1.6 (Community), Creating Grails project, Caught: groovy.lang.MissingPropertyException: No such property: grails for class: BuildConfig I was following this tutorial to create grails (version 2.3.1) application.
I am not using Maven and instead of MongoDb i'm using postgresql, but I believe these changes are not the things to be concerned for the issue I am facing.
After $ grails integrate-with --intellij, I ran the project on the intellij.
I am getting this error:

Caught: groovy.lang.MissingPropertyException: No such property: grails for class: BuildConfig
groovy.lang.MissingPropertyException: No such property: grails for class: BuildConfig
  at BuildConfig.run(BuildConfig.groovy:1)

I suspect that there may be some issue in Framework Support.
I googled for adding framework and according to this, Add Framework Support UI should show grails library, but for me it is not showing, please see the below screenshot.

First question, is the error i am getting because of wrong framework (I suspect this because the error is saying no such property as grails), if so how to add grails framework support.
Secondly, If this is not the cause for the error then what else I am doing wrong ?
You can assume I am a newbie-newbie, I just started Grails for the first time in my life just half-an-hour back. So, you can point out any stupid mistakes I might have done.

A: Grails is not supported in the Community Edition of IntelliJ.
You need to pay for the Ultimate Edition to use Grails
See the "Frameworks and Technologies" section here:
http://www.jetbrains.com/idea/features/editions_comparison_matrix.html


text:
Q: grep with pipe and variables NOT working on remote server through ssh (working locally) Below grep command is not giving expected result (matching line number) if I run it through ssh from a remote machine (passwordless authentication enabled). Variables have been defined correctly as well.
From Server 1 :
ssh user@server2 grep -n -i $J2C_ID1 $CUST_NODE_PATH1/resources.xml | awk '{print $1}' | tr -d ':'

above command returns blank output.
From Server 2 (running locally) returns expected output i.e., a line number:
grep -n -i $J2C_ID1 $CUST_NODE_PATH1/resources.xml | awk '{print $1}' | tr -d ':'

474

(expected out i.e., a line number of matching string specified in $J2C_ID, on the specified file resources.xml)
I tried modifying the command which is giving me full line as output, though I just need the line number and not the full line:
ssh user@server2 grep -n -i "'$J2C_ID1' '$CUST_NODE_PATH1/resources.xml' | awk '{print $1}' | tr -d ':'"

474        <resourceProperties xmiid="J2EEResourceProperty" name="Password" type="java.lang.String" value="null" description="password" required="false" ignore="false" confidential="false" supportsDynamicUpdates="false"/>

Need to get rid of redundant text and see just the line number as o/p.
Can you please help fix the command to run successfully and return the line number of matching string IF run as ssh from another server? Quick help is highly appreciated.
Thanks


text:
Q: How to count inner XML elements with restriction to outer elements I have a question on how to count elements in other elements by filtering the outer element by attribute. I have the following XML document:
<?xml version="1.0" encoding="ISO-8859-1" standalone="no"?>
<DSCT2C>
    <TESTSTEPS APPLICATION="UGS">

        <TESTSTEP ORDER_NUMBER="0">
            <EN>Common Test</EN>
            <DE>Allgemeiner Test</DE>

            <TEST NEED_FUNCTION="true" FUNCTION_NAME="functionName">
                <DESCRIPTION>
                    <DE>Hallo</DE>
                    <EN>Hello</EN>
                </DESCRIPTION>
                <FILES>
                    <FILE>test.prt</FILE>
                    <FILE>test.drw</FILE>
                </FILES>
            </TEST>
            <TEST NEED_FUNCTION="false">
                <DESCRIPTION>
                    <DE>Hallo2</DE>
                    <EN>Hello2</EN>
                </DESCRIPTION>
                <FILES>
                </FILES>
            </TEST>
        </TESTSTEP>

        <TESTSTEP ORDER_NUMBER="1">
            <EN>Just a test</EN>
            <DE>Nur ein Test</DE>

            <TEST NEED_FUNCTION="true" FUNCTION_NAME="functionName123">
                <DESCRIPTION>
                    <DE>Hallo</DE>
                    <EN>Hello</EN>
                </DESCRIPTION>
                <FILES>
                    <FILE>test.prt</FILE>
                    <FILE>test.drw</FILE>
                </FILES>
            </TEST>
            <TEST NEED_FUNCTION="true" FUNCTION_NAME="functionName456">
                <DESCRIPTION>
                    <DE>Hallo2</DE>
                    <EN>Hello2</EN>
                </DESCRIPTION>
                <FILES>
                </FILES>
            </TEST>
        </TESTSTEP>

    </TESTSTEPS>
</DSCT2C>

I want to count all TEST elements from a TESTSTEP element with for example ORDER_NUMBER=0. How can I do that with DOM?

A: Use the xpath expression:
"//TESTSTEP[@ORDER_NUMBER = '0']/TEST"

Then get the length of the NodeList that's returned.
The code will look something like:
XPath xpath = XPathFactory.newInstance().newXPath()
NodeList tests = (NodeList)xpath.evaluate("//TESTSTEP[@ORDER_NUMBER = '0']/TEST", document, XPathConstants.NODESET);

int testCount = tests.getLength();

A: try this
    int n = 0;
    Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new File("1.xml"));
    NodeList list = doc.getElementsByTagName("TESTSTEP");
    for (int i = 0; i < list.getLength(); i++) {
        Element e = (Element) list.item(i);
        if (e.getAttribute("ORDER_NUMBER").equals("0")) {
            n += e.getElementsByTagName("TEST").getLength();
        }
    }


text:
Q: Failed to build pyarrow during installation of Snowflake-SQLAlchemy through pip installation I am trying to use Snowflake Python Connector through SQLAlchemy, While I am running pip install --upgrade snowflake-sqlalchemy I am getting error failed to build pyarrow during installation. I am using python version 3.7

A: I recommend reinstalling pyarrow, and then you might want to upgrade snowflake-sqlalchemy after that.  Probably couldn't hurt to redo the standard connector as well, steps as follows:
1.
pip install --upgrade pyarrow

*pip install --upgrade snowflake-connector-python

3.
pip install --upgrade snowflake-sqlalchemy


text:
Q: GDAL Not Linking I'm trying to get my program running on Windows. It depends on GDAL,  a library for loading GIS data. It compiles and links fine on both Linux and macOS. I'm using CMake with MinGW and I'm running into linking errors like this:
undefined reference to `GDALRasterBand::RasterIO(GDALRWFlag, int, int, int, int, void*, int, int, GDALDataType, long, long, GDALRasterIOExtraArg*)'
CMakeFiles\Routes.dir/objects.a(elevation.cpp.obj): In function `ZN13ElevationData9calcStatsEv':
C:/Users/Logan/Documents/Routes/src/elevation/elevation.cpp:138: undefined reference to `GDALDataset::GetRasterXSize()'
C:/Users/Logan/Documents/Routes/src/elevation/elevation.cpp:139: undefined reference to `GDALDataset::GetRasterYSize()'
CMakeFiles\Routes.dir/objects.a(elevation.cpp.obj): In function `ZN13ElevationData17createOpenCLImageEv':
C:/Users/Logan/Documents/Routes/src/elevation/elevation.cpp:206: undefined reference to `GDALRasterBand::RasterIO(GDALRWFlag, int, int, int, int, void*, int, int, GDALDataType, long, long, GDALRasterIOExtraArg*)'

I compiled GDAL with VS2017 and I've verified that it is installed where I am specifying in my CMake File. Here is the relevant portions of the CMakeLists.txt:
IF (WIN32)

  message(STATUS "Compiling for Windows")
  set(GDAL_LIBRARY "C:/warmerda/bld/lib/gdal_i.lib")
  set(GDAL_INCLUDE_DIR "C:/warmerda/bld/include/")

  find_package(OpenCL REQUIRED)
  include_directories(${OpenCL_INCLUDE_DIRS})

ELSE()

...

message(STATUS ${GDAL_LIBRARY})
target_link_libraries(Routes ${GDAL_LIBRARY} ${OpenCL_LIBRARIES})

I almost never do development on Windows so I'm kind of stuck. I've tried linking against the dll as well with no avail. Any ideas?

A: Apparently you're attempting to link a library you compiled with VC++ with object
files that you're compiling with GCC (MinGW). That doesn't work.
GCC and VC++ have different and incompatible ABIs,
and in particular different name mangling protocols.
Hence the mangled function names emitted by MinGW in your object code will
not match any exported by your VC++ compiled library. You will need to
build the GDAL library with MinGW.

A: Thanks @MikeKinghan! I had been pulling my hair out for couple of days! Your answer clicked right away. For those who want to have no headache with the libraries, just use MSYS2 (msys2.org). Then using pacman in the msys2 command prompt, get the MingW (pacman -S mingw-w64-x86_64-gcc) and GDAL (pacman -S mingw-w64-x86_64-gdal).


text:
Q: Convert a String to generic type My program has to recieve input from a file, the input can be chars, integers or characters. With this I have to create a tree out of the elements given in the file. The type of the input is given at the start of the file. My problem is that my insertNode function recieves the element as generic type T, but the file is read as Strings. How can I convert the String to type T?
Trying to compile with:
String element = br.readLine();
T elem = (T)element;

results in compile error:

"found   : java.lang.String required:
  T "

A: You'd need to have some way of creating an instance of T, based on a String (or equivalently, converting a String to a T).
Casting doesn't do what you perhaps think it does in this case.  All a cast does is tell the type system, "I know that you have a different, less specific idea of what class this object is, but I'm telling you that it's a Foo.  Go ahead, check its run-time class and see that I'm right!".  In this case, however, the String is not necessarily a T, which is why the cast fails.  Casting doesn't convert, it merely disambiguates.
In particular, if T happens to be Integer in this case, you'd need to convert the String to an Integer by calling Integer.parseInt(element).  However, the part of the code that you've copied doesn't know what T is going to be when it's invoked, and can't perform these conversions itself.  Hence you'd need to pass in some parameterised helper object to perform the conversion for you, something like the following:
interface Transformer<I, O> {
    O transform(I input);
}

...

public void yourMethod(BufferedReader br, Transformer<String, T> transformer) {

    String element = br.readLine();
    T elem = transformer.transform(element);

    // Do what you want with your new T
}


text:
Q: Java TCP SSL sockets - How does the server keep me waiting? I am composing my own client to communicate with an existing server, using some uncommon protocol.
The protocol is basically to send and receive XML chunks over a TLS 1.2 TCP socket.
It describes quite long sessions. Sometimes, client and server will send and receive XML's for weeks without disconnecting.
I don't understand how my client is patiently waiting for stuff to be sent, even when the server isn't sending.
When connecting to the server, I am getting something like:
<mainTag>
<greeting>
</greeting>
(notice: no </mainTag>)

Nothing in my client implements a logic of "if you see <tag>, wait for </tag>" (I've written it all myself, from scratch).
Here's some of my code regarding how I read stuff sent from the server:
try (
    SSLSocket socket = getSSLsocket(keystoreFile, keystorePass, keystorePass);
        // ... Write-stuff removed, irrelevant to the question ...
    BufferedReader in = new BufferedReader(
            new InputStreamReader(
                    socket.getInputStream()));
    ) {
        socket.startHandshake();
        // ... Write-stuff removed, irrelevant to the question ...
        String inputLine;
        while ((inputLine = in.readLine()) != null)
            System.out.println(inputLine);
    }
}

private static SSLSocket getSSLsocket (String ksPath, String ksPass, String pkPass) {
    SSLContext context = SSLContext.getInstance("TLS");
        // ... Some key management stuff removed ...
    SSLSocketFactory sslScktFactory = context.getSocketFactory();
    return (SSLSocket)sslScktFactory.createSocket(hostFQDN, port);
}

In particular, during debugging, I am stepping into: while ((inputLine = in.readLine()) != null) and I reach </greeting> but when I step-into again, I can see it's just hanging there.
Is .readLine() returning something? if so, why isn't it printed?
Or, it's not returning something? if so, why isn't .readLine() null?


text:
Q: Cannot perform 'Like' operation on System.Int32 and System.String. with MySQL VB.Net I don't know why this error still shows up. It says to convert the string but I think it is already in string format. What's the solution to this?
Private Sub txtSearch_TextChanged(sender As System.Object, e As System.EventArgs) Handles txtSearch.TextChanged
    Dim DV As New DataView(dbDataSet)
    DV.RowFilter = String.Format("emp_no Like '%{0}%'", txtSearch.Text)
    DataGridView1.DataSource = DV
End Sub

A: Try like this
Private Sub txtSearch_TextChanged(sender As System.Object, e As System.EventArgs) Handles txtSearch.TextChanged
    Dim DV As New DataView(dbDataSet)
    DV.RowFilter = String.Format("Convert(emp_no,'System.String') Like '%{0}%'", txtSearch.Text)
    DataGridView1.DataSource = DV
End Sub


text:
Q: Runtime error showing in running .wav audio import java.awt.event.*;
import javax.swing.*;
import javax.sound.sampled.*;
import java.net.URL;
import java.io.*;

class SoundTest
{
    public static void main(String[] args) throws Exception
    {
        URL file = new URL("file:C:/Users/a/Documents/My/baby.wav");

        AudioInputStream ais = AudioSystem.getAudioInputStream(file);
        Clip clip = AudioSystem.getClip();
        clip.open(ais);

        JButton button = new JButton("Play Clip");
        button.addActionListener( new ActionListener()
        {
            @Override
            public void actionPerformed(ActionEvent ae)
            {
                clip.setFramePosition(0);
                clip.start();
            }
        });

        JOptionPane.showMessageDialog(null, button);
    }
}

I'm trying this code but when I am trying to run it is showing error -
javax.sound.sampled.UnsupportedAudioFileException:
    could not get audio input stream from input URL (in javax.sound.sampled.AudioSystem)

Please anyone solve my problem

A: It seems most likely that one (or both!) of two things could be happening. One is that the addressing of the file is not working. The other is that the file is a format that Java does not support.
I'd put a request for info in the comments but things are getting quite cluttered there!
Can you tell us the format of the wav file? Try checking it's properties. For sure, Java will support 16-bit, 44100 fps, mono or stereo, little endian, which is the most common format. You can check properties using Audacity if the properties from your OS are incomplete. There are a lot more files these days that are 24-bit or 32-bit, or 48000fps or even 92000fps, and Java doesn't support them yet, afaik.
A "safe" test sound would be this thunder clap at Freesound.org. You can see on the specs on the right side of the page it's 16-bit, 44100 fps stereo. I would download it and add it to your program rather than trying to play it from its web location.
To help test if the addressing is a problem, I would put the sound in the same folder as your SoundTest.java file. Then, use the following line to get the file's URL.
URL url = this.getClass().getResource("soundfilename.wav");

This will search in the project folder for the resource. There are other addressing modes for different purposes, but this should help with getting the basic code working. Having your program read directly from a disc location, if truly needed, can be worked out after verifying that you have a working sound file.

A: The string for the URL you're inputting is incorrect, try this instead:
C:\\Users\\a\\Documents\\My\\baby.wav

I also recommend reading files form a resources folder instead of from anywhere on your system, this blog post does a decent job explaining resources.
If you would like an easier way to access different files, I see that you're using the Swing library so consider using the JFileChooser component.
Edit: Changed URL path


text:
Q: Cannot retrive NgForm.value inside ngAfterViewInit I have a template driven form and I have to save the initial values of controls. To do this, I supposed the ngAfterViewInit method was a good place, since it is called after the template is rendered and I'm sure I can "read" the value of form controls.
When I try to save the form controls value inside a variable this way:
  ngAfterViewInit() {
      this.initialFormValue = this.form.value;
  }

I get just an empty object. The weird thing happens when I try to print the NgForm Object and the initialFormValue variable. The NgForm object has data inside the value property, but the initialFormValue is an empty object;
  ngAfterViewInit() {
    if(this.form!=null){
      this.initialFormValue = this.form;
      console.dir(this.initialFormValue.value);
      console.dir(this.form);
    }
  }

I expected initialFormValue variable has the same value of NgForm.value.

A: You have to set value, for example:

ngAfterViewInit() {
  this.contact = {
    firstname: "Sachin"
  }
}
<form #contactForm="ngForm" (ngSubmit)="onSubmit(contactForm)">
  <p>
    <label for="firstname">First Name </label>
    <input type="text" id="firstname" name="firstname" [(ngModel)]="contact.firstname">
  </p>
</form>


text:
Q: Is there a way to get "java.sql.SQLIntegrityConstraintViolationException" from Microsoft SQL JDBC driver? I have noticed that MS SQL JDBC driver throws
"com.microsoft.sqlserver.jdbc.SQLServerException"

for constraint violation issues. Is there a way to get subtype of
"java.sql.SQLIntegrityConstraintViolationException"

from the driver for  a constraint violation? may be using a different driver?

A: We would need to see the JDBC API you're calling to see if the Microsoft JDBC implementation throws java.sql.SQLIntegrityConstraintViolationException. As Tim B. mentioned above, you can't force a method to throw an exception if it wasn't coded to do so. Check the API.

Please consult your driver vendor documentation for the vendor-specified conditions for which this Exception may be thrown.


text:
Q: Test Addition to a List or Set using Test class I have the following code which is fetching only First Name from Contact where Account Name is 'United Oil & Gas, UK'.
public class ContactUK {
    public List<string> viewcontactUK(string acctnm){
        List<string> contactFirstName = new List<string>();
        Set<string> contactset = new set<string>();
            for (Contact c : [SELECT FirstName,Name FROM Contact where Account.Name = :acctnm]){
                contactFirstName.add (c.FirstName);
                contactset.add(c.FirstName);
            }
        system.debug(contactFirstName);
        system.debug(contactset);
        Return contactFirstName;
    }
}

here is the test class I have written to get 100% test coverage
@isTest
private class testContactUK {
    static testmethod void myTest(){

        Account acc = new Account(Name = 'Test Account');
        Contact c = new Contact(FirstName = 'Ashley',
                                LastName = 'Jones',
                                AccountId = acc.Id);
        insert c;

        ContactUK cont = new ContactUK();
        cont.viewcontactUK('United Oil & Gas, UK');
    }

But the below code is not covered under my test coverage:-
contactFirstName.add (c.FirstName);
contactset.add(c.FirstName);

Could anybody please help me to understand which test coverage is excluding those two lines of code?

A: *

*In the test code you are missing to insert the account

*You should search by the account name you created, so if you creates 'Test Account' you should pass to the method 'Test Account' as name of the account to search.

Hope this solves your question


text:
Q: Give an example of a structure of cardinality $\omega_2$ that has a substructure of $\omega$ but no substructure of $\omega_1$
Give an example of a structure of cardinality $\omega_2$ that has a substructure of $\omega$ but no substructure of $\omega_1$

This is from Hodges' A Shorter Model Theory.
My idea is to take some set of cardinality $\omega_2$ as the domain, $\mathrm{dom}(A)$. Choose and fix a subset of $\mathrm{dom}(A)$ with cardinality $\omega$, call this $X$. I need to then choose an $n$-ary relation, $R^A$ carefully. The point is that I need to find something that breaks:
$R^A=R^B\cap A^n$
for every subset of cardinality $\omega_1$ but such that that holds for A subset of cardinality $\omega$. The ones I've tried (like everything in the set $X$ being related to each other, etc.) didn't work.
Any hints?

A: HINT: Using only relations won't work, since given a language with only relation symbols, and a structure to the language, every subset of the domain defines a substructure. So using functions is necessary here.
Let $\{f_\alpha\mid\alpha<\omega_2\}$ be a list of $\omega_2$ unary function symbols. For sake of concreteness we can take $A=\omega_2$. Find a way to interpret $f_\alpha$ so for every $n<\omega$, $f_\alpha(n)<\omega$; and if $\beta\geq\omega$, then $\{f_\alpha(\beta)\mid\alpha<\omega_2\}=\omega_2$ (you actually don't need equality there, requiring that $|\{f_\alpha(\beta)\mid\alpha<\omega_2\}|=\aleph_2$ is enough).

A: (Inspired by Asaf Karagila)
Let $A$ be a structure with $\mathrm{dom}(A)=\omega_2$. $C^A=\emptyset$, $R^A=\emptyset$ and $F^A=\{f_{\alpha}\colon \alpha<\omega_2\}$ where:
$$f_{\alpha}(\beta)=\begin{cases}\beta \text{ for } \beta<\omega\\
\alpha \text{ for } \beta\geq \omega\end{cases}$$
Then define $S$ to be a substructure of $A$ with $\mathrm{dom}(S)=\omega$, $C^A=\emptyset$, $R^A=\emptyset$ and $F^A=\{f_{\alpha}\colon \alpha<\omega\}$. Then trivially $F^S=F^A\mid \mathrm{dom}(A)$ and $S$ is a substructure of $A$.
However if $T$ is a substructure with $|T|=\omega_1$, then there is some $t\in T\setminus\omega$. Pick $\alpha\in  A\setminus T$, then $f_{\alpha}(t)=\alpha\not\in T$.


text:
Q: Finding Word Length I am looking for a script that can open myfile.txt, read it and count the number of words that have 10 or more letters in the file. I made several attempts and consistently receive syntax errors. Need help.

A: Try like this:
f = open("myfile.txt")
data = f.read()
wc = 0
for x in data.split():
  if len(x) >= 10:
    wc += 1

print(wc)

A: This is a possible solution:
with open('myfile.txt', 'r') as input_file:
    word_list = input_file.read().split()
    print(len(list(filter(lambda x: len(x)>10, word_list))))

There are a lot of different solutions though. What did you try?


text:
Q: Basis for the intersection of two subspaces Consider two subspaces $U=\{(a,b,c,d)|b-5c+d=0\}$ and $W=\{(a,b,c,d)|a=d\;,\; b=5c\}$ of $\mathbb{R}^4$.
Find  a basis and the dimension of $U \cap W$.
So what I have so far is that the intersection must contain vectors which exist in both subspaces so these vectors must meet both $b-5c+d=0$ and $a=d$, $b=5c$ which led me to the conclusion that the vectors in the intersection follow $b(5c)-5c+d(a)=0 \Rightarrow d(a) = 0$ : so vectors in the intersection are of the form $(0,5,1,0)$.
Is this a basis for the intersection, and if so is the dimension just $1$?
Thank you.

A: Choose basis $\;\{\,(1,1,0,-1)\,,\,\,(1,0,0,0)\,,\,\,(0,5,1,0)\,\;,\;\;\{\,(0,5,1,0)\,,\,\,(1,0,0,1)\,\}\;$ of$\;U,\,W\,$ resp., and now form a matrix with the above vectors as rows and reduce it. Whatever "vanishes" belongs to the intersection:
$$\begin{pmatrix}1&1&0&\!-1\\1&0&0&0\\0&5&1&0\\0&5&1&0\\1&0&0&1\end{pmatrix}\longrightarrow\begin{pmatrix}1&1&0&\!-1\\0&\!-1&0&1\\0&5&1&0\\0&5&1&0\\0&\!-1&0&2\end{pmatrix}\longrightarrow\begin{pmatrix}1&1&0&\!-1\\0&\!-1&0&1\\0&0&1&5\\0&0&1&5\\0&0&0&1\end{pmatrix}$$
we can already see that only the fourth row is going to become all zedros in the next step, thus
$$U\cap W=\text{Span}\,\{\,(0,5,1,0)\,\}$$
which is your answer. Observe the above shows you a general way to attack these problems, as "seeing" the solution straighforward from the definition is, usually, much harder and not always will be possible to do it as you did it.


text:
Q: Is it proper to call a getter for the value of a variable for a class instanace within methods for that class in Java? I am writing a non-static method for a Java class that uses the value of a class variable for the class instance that is calling the method as one of the factors in determining the output. Is it standard practice to call the getter method for that variable from within the class method, or simply type the name of the variable?
For example, consider a class with the following constructor:
public BoardSpaceSymmetry(int boardSize, int xIndex, int yIndex) {
    this.boardSize = boardSize;
    this.xIndex = xIndex;
    this.yIndex = yIndex;
    this.xMax = xIndex + boardSize - 1;
    this.yMax = yIndex + boardSize - 1;
}

If I am writing a method for an instance of the BoardSpaceSymmetry class that uses the values of xIndex and yIndex, which of these would be a more standard way to write the method?
Option A:
public boolean isSpaceOnDiagonal (int xCoord, int yCoord) {
    if ((xCoord - getxIndex()) == (yCoord - getyIndex())) {
        return true;
    }
    if(getyMax() - yCoord == xCoord - getxIndex()) {
        return true;
    }
    return false;
}

Option B:
public boolean isSpaceOnDiagonal (int xCoord, int yCoord) {
    if ((xCoord - xIndex) == (yCoord - yIndex)) {
        return true;
    }
    if(yMax - yCoord == xCoord - xIndex) {
        return true;
    }
    return false;
}

Option C:
public boolean isSpaceOnDiagonal (int xCoord, int yCoord) {
    if ((xCoord - this.xIndex) == (yCoord - this.yIndex)) {
        return true;
    }
    if(this.yMax - yCoord == xCoord - this.xIndex) {
        return true;
    }
    return false;
}

Thanks.


text:
Q: NEVPNManager's onDemandEnabled flag When NEVPNProtocol property is updated by the server such that the username & password isn't valid anymore, is there a way we can handle this?
Lets say if we turn on onDemandEnabled flag for NEVPNManager, and when the server invalidates the credential (since the user has been blacklisted), is there a way we can toggle this programmatically? From the end user's experience perspective, the user would wait for a long time to fail webpage loading. Background fetch using a timer might not work if the app is killed.
Other than using push notifications, is there a better way to solve this issue?

A: I didn't try it myself, but what you should do is when you configure your VPN and set the onDemandEnabled, you need to define the onDemandRules.
There you have NEOnDemandRuleDisconnect, which will prevent your VPN from starting, and will disconnect it if it's already active.
https://developer.apple.com/library/ios/documentation/NetworkExtension/Reference/NEOnDemandRuleDisconnectClassRef/index.html#//apple_ref/occ/cl/NEOnDemandRuleDisconnect
This way even if your VPN is active, you will use it only when the rules still applies.
Edit: you can also use onDemandRule - probeURL . With this, before any activation of your VPN, it will send a request to a server of your choice. The server will return an answer if you should use your VPN or not.


text:
Q: how to draw graphically a bfs tree by preorder and inorder traversal this is not a duplicated question i searched in SO but i can't find any approach i have preorder and inorder traversal and i want to draw a bfs tree graphically in console
first we get inorder and preorder traversal and we calculate the size of them. and we build the tree by a function that exists in my posted code.
then i show the bfs traversal. my problem is draw it graphically in console.
i want this similar solution :
   1
   / \
  2   3
 /   / \
4   5   6

here is my code :
#include<iostream>
using namespace std ;

struct node
{
    char data;
    struct node* left;
    struct node* right;
};

int searching(char arr[], int strt, int ending, char value)
{
    int i;
    for(i = strt; i <= ending; i++)
    {
        if(arr[i] == value)
        return i;
    }
}

struct node* newNode(char data)
{
    node* node1 = new node();
    node1->data = data;
    node1->left = NULL;
    node1->right = NULL;
    return(node1);
}

struct node* buildTree(char in[], char pre[], int inStrt, int inEnd)
{
    static int preIndex = 0;
    if(inStrt > inEnd)
    return NULL;
    struct node *tNode = newNode(pre[preIndex++]);
    if(inStrt == inEnd)
    return tNode;
    int inIndex = searching(in, inStrt, inEnd, tNode->data);
    tNode->left = buildTree(in, pre, inStrt, inIndex-1);
    tNode->right = buildTree(in, pre, inIndex+1, inEnd);
    return tNode;
}

void printInorder(struct node* node)
{
    if(node == NULL)
    return;
    printInorder(node->left);
    cout <<  node->data;
    printInorder(node->right);
}
void printPostorder(struct node* node)
{
    if(node == NULL)
    return;
    printPostorder(node->left);
    printPostorder(node->right);
    cout << node->data;
}
int x=-1 , y=-1 ;
node* Queue[100];
void Add(struct node* node)
{
   Queue[++x] = node ;
}
node* del()
{
    node* item ;
    item= Queue[++y] ;
    return item ;
}
int counter=0 ;
void printBFS(struct node* node)
{
    if(node!=NULL)
    {
       Add(node) ;
       while(x!=y)
       {
           node = del() ;
           cout << node->data ;
           if(node->left!=NULL) Add(node->left) ;
           if(node->right!=NULL) Add(node->right) ;
       }
   }

}
int main()
{
    char in[] = {'B' , 'c' , 'A' , 'E' , 'D' , 'G' , 'H' , 'F'} ;
    char pre[] ={'A' , 'B' , 'C' , 'D' , 'E' , 'F' , 'G' , 'H'} ;
    int len = sizeof(in);
    struct node *root = buildTree(in, pre, 0, len - 1);
    cout << "BFS traversal of the constructed tree is \n" ;
    printBFS(root); /// show bfs traversal
    return 0 ;
}

I searched in web but i could not find any answer
any idea?


text:
Q: Capybara visit page, assigns always nil In my spec, I'm visiting a page and checking that an instance variable is being set correctly. The spec is always saying that the assigns is nil. Looking at the saved page, it's blank—not a 404 or any sort of error page.
describe ArtistsController do
    before :each do
        @artist = Artist.first
    end
    describe "GET #about" do
        it "finds artist by artistname" do
            visit artist_about_path(@artist.artistname); save_page
            puts "2 ===================== #{ artist_about_path(@artist.artistname) }"
            # assigns(:artist).should eq(@artist)
            assigns[:artist].should_not be_nil
        end
        it "renders the :about view" do
            visit artist_about_path(@artist.artistname)
            # response.should render_template :about
            response.should be_success
        end
    end
# Similar specs for other pages to be rendered

Artist.first comes from a rake task that's being run in spec_helper to populate the database; that part works correctly in other tests.
I'm checking the path by printing it, and it looks fine. Controller methods:
class ArtistsController < ApplicationController
before_filter :get_artist_from_params
def about
    @artist = Artist.find_by_artistname(params[:artistname].downcase)
    @contact_info = @artist.contact_info
    puts "1 ==============================="
    puts @artist.inspect
  end

In the server logs, @artist is the object we expect.
def get_artist_from_params
    if !params[:artistname].blank?
      @artist = Artist.find_by_artistname(params[:artistname].downcase)
      if @artist.blank?
        not_found
      end
    end
end

I'm not sure where the test is going wrong…The puts are outputting the right values.
Using Ruby 2.0, Rails 3.2, Capybara 2.1, Rspec 2.12.

A: I'm a little confused by this testing, but maybe I can help shore some up.
I think you can leave your about action blank:
def about
end

Then you can clean up your before_filter as such:
private

def get_artist_from_params
  if params[:artistname]
    @artist = Artist.find_by_artistname(params[:artistname].downcase)
    if @artist
      @contact_info = @artist.contact_info
    else
      not_found
    end
  end
end

First, I honestly don't think you need to do integration testing, if all you want to do is assure yourself that your instance variables are being set properly in your controllers. I believe you want to do functional testing as shown here http://guides.rubyonrails.org/testing.html#what-to-include-in-your-functional-tests. Alright, so lets see if we can do this with what you have so far:
describe ArtistsController do
  let(:artist) { Artist.first } #May want to look into FactoryGirl
  describe "GET #about" do
    before :each do
      @parameters = { artistname: artist.name }
      Artist.should_receive(:find_by_artistname).with(artist.name.downcase).and_return(artist)
    end
    it "assigns artist and contact_info instance variables" do
      get :about, @parameters
      assigns(:artist).should eq(artist)
      assigns(:contact_info).should eq(artist.contact_info)
    end
    it "responds successfully" do
      get :about, @parameters
      expect(response).to be_success
    end
    it "renders about template" do
      get :about, @parameters
      expect(response).to render_template("about")
    end
  end
end

Let me know if that makes sense I can provide additional details.


text:
Q: Find the values of $\alpha$ and $\beta$ for which the function $f$ is of bounded variation on $[0,1]$? The question is :

Let $f : [0,1] \longrightarrow \mathbb {R}$ be defined by

$f(x) = x^{\alpha} \sin {\frac {1} {x^{\beta}}}$ , whenever $x \in (0,1]$ and $=0$ , whenever $x = 0$.
Then find the values of $\alpha$ and $\beta$ for which $f$ becomes a function of bounded variation on $[0,1]$.
Please give me a right way to proceed.Thank you in advance.
I have just obtained the result which is
$\alpha > 2$ and $\beta < \alpha - 2$.Is it correct at all?Please verify it.

A: Hint: If $f$ is continuously differentiable on $[a,b],$ then the total variation of $f$ on $[a,b]$ is $\int_a^b|f'(x)|\, dx.$

A: Claim. Let $\alpha>0$, $\beta > 0$ and let $f$ be as given. Then $f \in \operatorname{BV}(\left[0,1\right])$ if and only if $\alpha > \beta$.
Proof. Suppose that $\alpha>\beta$. Let $h:\left[0,1\right]\to\mathbf{R}$ be defined by
$$
h(x)=
\begin{cases}
\displaystyle{x^{\alpha/(\alpha-\beta)}\sin\left(\frac{1}{x^{\beta/(\alpha-\beta)}}\right)}&,\text{ if } 0<x\le 1\\
0&,\text{ if } x = 0.
\end{cases}
$$
Then $h$ is differentiable at every $x\in \left[0,1\right]$. In fact, we have
$$
h^{\prime}(x)=
\begin{cases}
\displaystyle{\frac{\alpha}{\alpha-\beta}x^{\beta/(\alpha-\beta)}\sin\left(\frac{1}{x^{\beta/(\alpha-\beta)}}\right)-\frac{\beta}{\alpha-\beta}\cos\left(\frac{1}{x^{\beta/(\alpha-\beta)}}\right)}&,\text{ if }0<x\le1\\
0&,\text{ if }x=0.
\end{cases}
$$
In particular, $h^{\prime}$ is bounded, hence $h$ is Lipschitzian of order $1$, i.e., there is some $C>0$ such that for all $x\in\left[0,1\right]$ and all $y\in\left[0,1\right]$, we have
$$ \left|h(x)-h(y)\right|\le C\left|x-y\right|. $$
Substituting $x\mapsto x^{\alpha-\beta}$, $y\mapsto y^{\alpha-\beta}$, we finally get
$$ \left|f(x)-f(y)\right|\le C\left|x^{\alpha-\beta}-y^{\alpha-\beta}\right|, $$
therefore the sums appearing in the definition of total variation are bounded above by $C(t_{n}^{\alpha-\beta} - t_{0}^{\alpha-\beta})=C(1-0)=C$, which implies $f\in\operatorname{BV}(\left[0,1\right])$.
Suppose that $\alpha\le\beta$ and consider the following partition
$$ \left\lbrace 0, \left(\frac{2}{\pi(2n+1)}\right)^{1/\beta}, \left(\frac{2}{\pi(2n)}\right)^{1/\beta},\left(\frac{2}{\pi(2n-1)}\right)^{1/\beta},\cdots,\left(\frac{2}{\pi}\right)^{1/\beta},1 \right\rbrace. $$
The following holds:
$$ \begin{aligned}
\sum_{k=1}^{2n+2}\left|f(t_{k})-f(t_{k-1})\right|&\ge\sum_{k=2}^{2n+1}\left|f(t_{k})-f(t_{k-1})\right|\\
&=\left(\frac{2}{\pi}\right)^{\alpha/\beta}\sum_{k=2}^{2n+1}\left|\frac{1}{(2n+2-k)^{\alpha/\beta}}\sin\left(\frac{k\pi}{2}\right)-\frac{1}{(2n+2-(k-1))^{\alpha/\beta}}\sin\left(\frac{(k-1)\pi}{2}\right)\right|
\\
&\ge\left(\frac{2}{\pi}\right)^{\alpha/\beta}\sum_{k=1}^{n}\frac{1}{\left(2(n-k)+1\right)^{\alpha/\beta}}\\
&=\left(\frac{2}{\pi}\right)^{\alpha/\beta}\sum_{k=0}^{n-1}\frac{1}{\left(2k+1\right)^{\alpha/\beta}}.
\end{aligned} $$
Because $0<\alpha\le\beta$, the last sum can be made arbitrarily large. Consequently, $f\notin \operatorname{BV}(\left[0,1\right])$ and the claim is proved.


text:
Q: upload with ftp to web api I created a web api in asp.net core 3,
I made it possible to send files to the web api,
I'm looking for a way to upload a file to the web api by Ftp,
I don't know if it's possible,
If there is a way to do this, please help me


text:
Q: Mapping virtual memory to virtual memory I am supplied with a struct that lies somewhere in the memory. Is it possible in WinAPI/POSIX to create a memory mapping that would alias the struct to a different part of the memory range so that identical bytes could be accessed from both locations? I cannot control the location of the original struct, but the new one can be stored anywhere.
I think, at least in WinAPI, I could create a temporary file and store the pages that contain the struct there, and then I could (hopefully) replace the original pages with new ones that point to the file, then map the file to a new section in the memory. However, I am worried about the performance of accessing the memory. Is there something better?

A: In Linux you can use memfd_create(2) to allocate memory which you can access through a file descriptor. You'd then write(2) the original data to that in-memory file and map it over the original location with mmap(2) using MAP_FIXED flag, and then to another location with a non-fixed mmap(2). Be aware that mapping must be a multiple of the underlying page size (4k in regular address space, or hugepage size if the memfd was allocated from hugepages).


text:
Q: System.UnauthorizedAccessException appears while accessing Temporary Internet Files I have created a utility for cleaning Temporary internet files but when the application tried to access Temporary Internet Files, exception appear that
"System.UnauthorizedAccessException: Access to the path 'c:\users\test\AppData\Local\Temporary Internet Files' is denied."
The application runs from an Administrator account and UAC is off.
I am running the code on Windows 7 enterprise N 64 bit
I have also tried to remove the security but nothing happend.
public static void RemoveDirectorySecurity(string FileName, string Account,
FileSystemRights Rights, AccessControlType ControlType)
    {
        // Create a new DirectoryInfo object.
        DirectoryInfo dInfo = new DirectoryInfo(FileName);

        // Get a DirectorySecurity object that represents the
        // current security settings.
        DirectorySecurity dSecurity = dInfo.GetAccessControl();

        // Add the FileSystemAccessRule to the security settings.
        dSecurity.RemoveAccessRule(new FileSystemAccessRule(Account,
                                                        Rights,
                                                        ControlType));

        // Set the new access settings.
        dInfo.SetAccessControl(dSecurity);

    }

Any suggestion to resolve this issue?
Thankx and Regards


text:
Q: Android Splash screen for "Application" class I have an Android app where I've extended the base Application class in order to set up some global variables.
public class MyApplication extends Application {

 private ArrayList<ModelClass> master_list; // global variable 1
 private DataBaseHelper db_helper; // global variable 2

 @Override
 public void onCreate() {
  super.onCreate();
  //do database work that will take about 5 seconds
 }
}

I'd like to show a splash screen to the user while the Application class is working (i.e. before my Main Activity is created).  Is there a way to do this?

A: You could make the SplashActivity your start activity.
When MyApplication has completed it's work you could start your main activity and dispose the splash screen.
But don't do the heavy database work in onCreate, create another function and do it there, otherwise your splash activity won't be shown.
public class SplashActivity extends Activity
    @override
    protected void onResume() {
    //Create a thread
    new Thread(new Runnable() {
            public void run() {
                //Do heavy work in background
                ((MyApplication)getApplication()).loadFromDb();
                startActivity(new Intent(SplashActivity.this, MainActivity.class));
                finish(); //End this activity
            }
        }).start();
    }
}

A: The way I do this in my apps is by having your main activity extend ActivityGroup.
public class App extends ActivityGroup {
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.splashscreen);
        new Thread(new Runnable() {
            public void run() {
                // do your loading here
                final LocalActivityManager lam = getLocalActivityManager();
                runOnUiThread(new Runnable() {
                    public void run() {
                        Intent mainIntent = new Intent(MainActivity.class, App.this);
                        Window w = lam.startActivity("main", mainIntent);
                        setContentView(w.getDecorView());
                    }
                }
            }
        }, "App loading thread").start();
    }
}

This way, when the app resumes you immediately get the app, not the splash screen, and you only load your data once (when the app starts).
I actually use this to make sure the user is logged in when the app starts, and if the username/password combination is not right I don't start the main app, but a login screen :)

A: First off, I think there are many approaches to having a splash screen. Intuitively, I would not have a special class/activity just to load specific information, because to keep that information, you will have to keep that activity alive and well somewhere- taking up resources.
I would have a splash screen just be a layout, that is initially loaded on with the main activity's onCreate(), and then once the DB information is loaded, change your layout to the main activities layout.
something like:
public void onCreate() {
    super.onCreate();
    setContentView(R.layout.splashscreen);
    //do database work that will take about 5 seconds
    setContentView(R.layout.mainscreen)
}

A: I realize this is rather far after this was asked but I hope someone finds this useful and I will provide code if needed. My approach was to create a public boolean in the application class called "finishedLoading". I launch the application into my splash screen activity and I have that check every 250 milliseconds as to whether or not finishedLoading = true and when it does, I launch the new activity. another nice part about that is I have a little spinner progress bar so the user sees somethings happening and animation all around.


text:
Q: Keras TimeDistributed Dense drops vector dimension by 1 I am not able to figure out how the tensor dimension got reduced by 1 in the TimeDistributed Dense step in the following
model = Sequential()
model.add(Embedding(vocab_size +1, 128, input_length=unravel_len))  # embedding shape: (99, 15, 128)
model.add(Bidirectional(LSTM(64, return_sequences=True)))   # (99, 15, 128)
model.add(Dropout(0.5))
model.add(TimeDistributed(Dense(categories, activation='softmax')))    # (99, 15, 127)

I labeled the tensor shape along each step. You can see the last dimension dropped from 128 to 127. Can someone explain why that is. Thanks


text:
Q: Transforming data with NAs in ggaluvial format and visualizing as a alluvial plot in R I tried multiple options with Python, but did not resolve it. Found ggaluvial package and need some help.
This is my fake data in such format. I calculated the frequency of each unique combination, which goes across five different roles.
My problem I have NAs in some combinations and they also can increase in numbers.
For instance, in Role 1 I can have 20 roles A, but when ppl move to Role 2, the total number of roles A is 30. Maybe it is a problem.
Role 1  Role 2  Role 3  Role 4  Role 5  freq
Role A   Role A  Role A  Role B  Role A 8
Role A   Role A  Role A  Role B NA  5
Role A   Role A  Role A  Role C NA  4
Role A   Role A  Role B  Role A  Role B 4
Role A   Role A  Role B  Role B  Role A 4
Role A   Role A NA  NA  NA  3
Role A   Role A  Role C  Role A NA  3

My ideal output is like this for 5 roles (like here 5 semesters) with color by Role A, B, C, D.

I also was thinking to restructure data like this Majors dataset example from package.
    Frequency   Role    Type
1   1           Role1   Role A
2   2           Role1   Role B
3   6           Role1   Role C
4   8           Role1   Role D
5   9           Role2   Role A
6   10          Role2   Role B
7   11          Role2   Role C
8   12          Role2   Role D
9   14          Role3   Role A
10  15          Role3   Role B
11  1           Role3   Role C
12  2           Role3   Role D

But it gives me
ggplot(df,
   aes(x = Role, stratum = Type, alluvium = Frequency, y = 1)) +
  geom_alluvium(fill = "darkgrey") +
  geom_stratum(aes(fill = Type)) +
  theme_bw()

The help here is super appreciated.
Restructuring data like this

I achieved a desired result with a non-programming tool. But still looking for the same ideal output in R.


text:
Q: Python requests trust certificate in cer-file I got such certificate :
certificate.base64.cer
-----BEGIN CERTIFICATE-----
MIIGGDCCBQCgAwIBAgITcwAHCoPQ7YzgDXiRHQACAAcKgzANBgkqhkiG9w0BAQsF
...(some symbols)
oWt63wOSxGxa3ASu1UFGCd9o+PxnaUA12EGU9A==
-----END CERTIFICATE-----

And I want to send request using it
api.py
session = requests.Session()
session.auth = HTTPBasicAuth('user', 'pass')
session.cert = 'path to .cer file'
host = 'https://api.com/webservices/MediaPool/?wsdl'
session.headers = {'Content-Type': 'application/json'}
client = Client(transport=Transport(session=session), wsdl=host)
response = client.service.uploadMedia(uploadMediaData={'fileName': image.name, 'fileData': image.read()})

but I get
HTTPSConnectionPool(host='some.host', port=443): Max retries exceeded with url: /webservices/MediaPool/?wsdl (Caused by SSLError(SSLError(9, '[SSL] PEM lib (_ssl.c:4050)'))

How to fix that? What is wrong?

A:
Python requests trust certificate in cer-file

session.cert is used for authentication using client certificates. For specifying the trusted CA session.verify must be used instead. For more see the documentation.


text:
Q: styling issue how can I bring down the div id="space" off the ul tag? http://jsfiddle.net/ZrNaa/5/
in that link above I have added a map in the profile for member location but I would like to style a boder, or something that match the whole profile around the map so it doesn't look so plain plus I would like to know where it would be the best position in the profile to put this map. There will be some user description about where his live, biography, age, and all that common staff. how it would be better to place all this information so it all make sense? the picture, map, description and some comment form?
Map
Profiles content
1.picture
 2.unordered list map
 3.description of the member"age, bio, location, hobbies etc"
 4. Comment form

A: Is this what you meant? You need to tell the div to clear, not the ul.

A: You're better off using a different pattern. If you want the image to appear below the menu item, make it part of the menu item and position it relative to the LI parent:

Pumpkin

  ...

ul li {
   position:relative;
   ... your styles ...
}

ul li img {
    position:absolute;
    top: ...px;
    left:0px;
}

You'll need to adjust the CSS to suit your layout, but this should get you started.

A: The
 is the element that needs clearing, and take the float off it.


text:
Q: How to add an item in a collection in amazon s3? I have  this code  for create a data collection:
import boto3

def createCollection():
        cliente = boto3.client('rekognition')
        respuesta = cliente.create_collection (CollectionId = 'Fotos')
        print (respuesta)

createCollection()

But my question is how to add an item in this collection.
Could you please help me.
thanks.

A: Assuming you're trying to add an image to the collection from your local filesystem, you can do so with the index_faces() method:
with open('image.png', 'rb') as image:
    respuesta = cliente.index_faces(Image={'Bytes': image.read()}, CollectionId='Fotos')
    print respuesta


text:
Q: Risks of Opening iWork '09 files in iWork 2013? Ever since last year's iWork update I've been hesitant to use it, on the basis that it made it clear that simply opening iWork '09 files would result in destructive changes that would become permanent if saved, and which still wouldn't be restored if exported.
I'm aware that since that time Apple has also done an update to restore some of what was lost.
The question for now is, is there a comprehensive list anywhere that tracks what's going to be lost when opening iWork '09 files in the current version of iWork?

A: Here is the list published by Apple.
Changes that occur when exporting to iWork '09
All Apps
Curved shadows and contact shadows are converted to drop shadows.
Comments on objects are removed.
Anchored objects are converted to floating or inline objects.
The following formulas are removed: INTERSECT.RANGES, POLYNOMIAL, SERIESSUM, UNION.RANGES, WEIBULL. Note: The last calculated values are exported.
Interactive charts are converted to regular charts.
Bubble charts are converted to scatter charts.
Vertical text—such as Chinese, Japanese, and Korean—isn't fully supported in iWork '09.

Pages
Tables of contents are converted to plain text. They won't update automatically in Pages '09.
Right-to-left text—such as Arabic and Hebrew—isn't fully supported in Pages '09.

Numbers
If a document contains "OR" filters within a column and "AND" filters across columns, all filter rules are exported; "AND" filters are converted to "OR".
Duration-based filters and conditional highlights are removed.

Keynote
The following transitions are converted to Dissolve: Clothesline, Object Cube, Object Pop, Object Revolve, and Switch.
The Object Flip transition is renamed Revolve.
The following build-in effects are converted to Dissolve: Blur, Drift and Scale, Fade and Scale, Twist and Scale, Fireworks, Skid.
The following build-out effects are converted to Dissolve: Blur, Crumble, Fade and Scale, Skid, Twist and Scale, Vanish.
Emphasis builds are removed. Emphasis builds are Blink, Bounce, Flip, Jiggle, Pop, and Pulse.
Comments on table cells are removed.

*

*I think I got the previous version so here is the newer one-moving from iWorks 09 to iWorks 2013 as of April 1. 2014
Changes that occur when importing from iWork '09
All Apps
Rotation is removed from tables and charts.
Table fills are removed.
Grouped wedges in pie charts are ungrouped.
OS X search (Spotlight) metadata is removed.

Pages
Change tracking is only supported for body text. Other tracked changes are accepted as final.
Linked text boxes are unlinked.
Links to other Pages files are removed.
Bookmarks are hidden in Pages for Mac, but if you export your document back to Pages '09, they'll reappear.

Numbers
Table categories are removed.

Keynote
The "Require password to exit show" setting is removed. To set a new password, choose Keynote > Preferences > Slideshow, and then select "Require password to exit slideshows." Enter a password when prompted, and then click Set Password. This password will apply to all presentations played on this computer.
Slides indented more than six levels are promoted to level six.
Links to other Keynote files are removed.
Rotation is removed from object placeholders.
The following transitions are converted to Dissolve: Blur, Burn, Falling Tiles, Flash, Motion Dissolve, Radial, Shutter.
The Revolve transition is renamed Object Flip.
Convergence builds are converted to Dissolve.
The following types of builds are removed: Builds on master slides, smart builds, builds on chart legends.


text:
Q: am I using Dictionary wrong, it seems it too slow I've used VS profilier and noticed that ~40% of the time program spends in the lines below.
I'm using title1 and color1 because either Visual Studio or Resharper suggested to do so. Are there any perfomance issues in the code below?
Dictionary<Item, int> price_cache = new Dictionary<Item, int>();
....

string title1 = title;
string color1 = color;
if (price_cache.Keys.Any(item => item.Title == title && item.Color == color))
{
    price = price_cache[price_cache.Keys.First(item => item.Title == title11  && item.Color == color1)];

A: The problem is that your Keys.Any method iterates through all keys in your dictionary to find if there is a match. After that, you use the First method to do the same thing again.
Dictionary is suited for operations when you already have the key and want to get the value fast. In that case, it will calculate the hash code of your key (Item, in your case) and use it to "jump" to the bucket where your item is stored.
First, you need to make your custom comparer to let the Dictionary know how to compare items.
class TitleColorEqualityComparer : IEqualityComparer<Item>
{
     public bool Equals(Item a, Item b)
     {
          // you might also check for nulls here
          return a.Title == b.Title &&
              a.Color == b.Color;
     }

     public int GetHashCode(Item obj)
     {
          // this should be as much unique as possible,
          // but not too complicated to calculate
          int hash = 17;
          hash = hash * 31 + obj.Title.GetHashCode();
          hash = hash * 31 + obj.Color.GetHashCode();
          return hash;
     }
}

Then, instantiate your dictionary using your custom comparer:
Dictionary<Item, int> price_cache =
    new Dictionary<Item, int>(new TitleColorEqualityComparer());

From this point on, you can simply write:
Item some_item = GetSomeItem();
price_cache[some_item] = 5; // to quickly set or change a value

or, to search the dictionary:
Item item = GetSomeItem();
int price = 0;
if (price_cache.TryGetValue(item, out price))
{
    // we got the price
}
else
{
    // there is no such key in the dictionary
}

[Edit]
And to emphasize again: never iterate the Keys property to look for a key. If you do that, you don't need a Dictionary at all, you can simply use a list and get same (even slightly better performance).

A: Try using an IEqualityComparer as shown in the sample code on this page: http://msdn.microsoft.com/en-us/library/ms132151.aspx and make it calculate the hash code based on the title and color.

A: As Jesus Ramos suggested (when he said use a different data structure), you could make the key a string that is a concatenation of the title and color, then concatenate the search string and look for that.  It should be faster.
So a key could look like name1:FFFFFF (the name, a colon, then the hex of the color), then you would just format the search string the same way.

A: Replace your price_cache.Keys.Any() with price_cache.Keys.SingleOrDefault() and this way you can store the result in a variable, check for nullity and if not you already have the searched item instead of searching for it twice like you do here.

A: If you want fast access to your hashtable, you need to implement the GetHashCode and Equals functioning:
public class Item
{
.....
    public override int GetHashCode()
    {
        return (this.color.GetHashCode() + this.title.GetHashCode())/2;
    }

    public override bool Equals(object o)
    {
        if (this == o) return true;
        var item = o as Item;
        return (item != null) && (item.color == color) &&  (item.title== title) ;
    }

Access you dictionary like:
Item item = ...// create sample item
int price = 0;

price_cache.ContainsKey(item);
price_cache[item];
price_cache.TryGetValue(item, out price);


text:
Q: Converting dv to mpeg I'm trying to transfer videos from an old tape recorder onto DVDs. I think that I need to use ffmpeg to convert the dv files to mpeg but can't find the right commands to use. Does anybody know what the right commands are or if there is an alternative method?

A: This can be accomplished with FFmpeg and DVDauthor. A very basic form of the required command lines would be:
1. Convert to mpg:
ffmpeg -i test.mp4 -target pal-dvd -aspect 16:9 -ac 2 output.mpg

This command line can be embellished to your taste and also altered to fit any form of input file. Tip: Perhaps add in a bitrate setting for the video: -b:v 6000k or even a quality setting: -qscale:v 2 if the output video is at all disappointing.
Note: For those in non-'PAL' countries the option would be -target ntsc-dvd rather than -target pal-dvd.
2. Create the DVD structure:
Create the file $HOME/.config/video_format and place either PAL or NTSC in the file (depending which is relevant in your country), using your favourite text editor. I use PAL in the following example for the command line to create the DVD structure:
dvdauthor -t -o dvd --video=pal -f output.mpg
dvdauthor -T -o dvd

Note: For those in non-'PAL' countries the option would be --video=ntsc rather than --video=pal.
3. Create the iso:
Use mkisofs to then create an iso suitable for burning to DVD:
mkisofs -dvd-video -o testing.iso dvd/

4. Burn to DVD:
Finally you can use K3B or whichever tool you prefer to burn the iso to DVD; perhaps even use the following command line:
growisofs -dvd-compat -Z /dev/sr0=testing.iso

And then sit back and enjoy your movie :)
References:

*

*How to make an MPEG2 video file with the highest quality possible using FFMPEG?: Some thoughts on creating a high quality encode with FFmpeg


text:
Q: The mandatory text (CDATA) inside tag 'head > style[amp-boilerplate]' is missing or incorrect Why am I receiving this error? i use wordpress and using Automattic AMP plugin.
The mandatory text (CDATA) inside tag 'head > style[amp-boilerplate]' is missing or incorrect. MANDATORY_AMP_TAG_MISSING_OR_INCORRECT
line 1, column 473
The mandatory text (CDATA) inside tag 'noscript > style[amp-boilerplate]' is missing or incorrect. MANDATORY_AMP_TAG_MISSING_OR_INCORRECT
line 10, column 19
<!doctype html><html amp lang="tr-TR"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no"><title>Example</title><link rel="canonical" href="http://www.example.com/okul-kombinleri/" /> <script src="https://cdn.ampproject.org/v0.js" async></script> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Merriweather:400,400italic,700,700italic"><style amp-boilerplate>body {
-webkit-animation:0 8s steps(1,end) 0 1 normal both;
-moz-animation:0 8s steps(1,end) 0 1 normal both;
-ms-animation:0 8s steps(1,end) 0 1 normal both;
animation:0 8s steps(1,end) 0 1 normal both;
}

to {
visibility:visible;
}</style><noscript><style amp-boilerplate>body {
-webkit-animation:none;
-moz-animation:none;
-ms-animation:none;
animation:none;
}</style></noscript>

A: According to the AMP HTML specs, I believe you need to remove all new lines from the AMP boilerplate code because it's validated with regex (regular expressions) so all new lines are being read as "\n" causing errors.
Direct from the docs

AMP Boilerplate Code ('head > style[amp-boilerplate]' and 'noscript > style[amp-boilerplate]')
AMP HTML documents must contain the following boilerplate in their head tag. Validation is currently done with regular expressions, so it's important to keep mutations as minimal as possible. Currently, allowed mutations are: (1) inserting arbitrary whitespace immediately after the style tag opens, and immediately before it closes; (2) replacing any space in the snippet below with arbitrary whitespace.

amphtml/spec/amp-boilerplate.md


text:
Q: Show Dialog "Save To.." I m searching why my show *.showDialog for a "save to" doesn't work.
It works correctly when i m launching it with my IDE Intellij-idea.

But when i want to start my app with the .jar file, the showDialog doesn't work.

It would be run when i click on "Valider".
This is my code:
JFileChooser chooser = new JFileChooser();

chooser.setCurrentDirectory(new File("."+File.separator));

int reponse = chooser.showDialog(chooser, "Enregistrer sous");

if(reponse == JFileChooser.APPROVE_OPTION)  {
    String fichier = chooser.getSelectedFile().toString();

    document.save(fichier+".pdf");
}

Edit:
This is the new code:
JFileChooser chooser = new JFileChooser();

chooser.setCurrentDirectory(new File(System.getProperty("user.home")));

int reponse = chooser.showDialog(chooser, "Enregistrer sous");

if(reponse == JFileChooser.APPROVE_OPTION)  {
    String fichier = chooser.getSelectedFile().toString();
    document.save(fichier+".pdf");
}

Edit 14/03:
I have found my error:
"javax.imageio.IIOException: Can't read input file!"
I'm trying to resolve this one, it probably because the file path is uncorrectly defined.
This is my code to draw my image:
PDImageXObject pdImage = PDImageXObject.createFromFile("myImage.png", document);
contentStream.drawImage(pdImage, 480, 720);

Thanks


text:
Q: Unsupported kotlin version My gradle build completes successfully, but I get:
WARNING: Unsupported Kotlin plugin version.
The `embedded-kotlin` and `kotlin-dsl` plugins rely on features of Kotlin `1.5.31` that
might work differently than in the requested version `1.6.10`.

All of my build.gradle.kts scripts refer to using version 1.5.31.  The only association my project has with version 1.6.10 is that Android Studio has the Kotlin version 1.6.10 plugin added.  If I try to disable that plugin, I get a message that several other plugins will be disabled.  If I accept that, android studio crashes and will not start up again.  It won't start up again even if you reinstall android studio again.  The solution is to find the file named "disabled-plugins.txt" and delete that file.  It's in your AppData folder and in a JetBrains subdirectory. It turns out that it's one or more of those other disabled plugins that prevents Android Studio from starting up again.
The question I have is how do I fix this version mismatch issue.  I can't delete the plugin from Android Studio for the reasons I mentioned above.  If I try to update my project to using version 1.6.10 I get literally 100's of unresolved dependencies. And it seems from opinionated investigation that 1.6.10 still have too many issues for general use.
By the way, when I look at the gradle window for the project I can see where the dependencies come from.  Usually when I look at the gradle window I just see sub project folders that I can drill into for more information, but for this project, it has an additional folder name dependencies. I don't know how they get into my project.  But when I look at their version numbers that's where the 1.6.10 mismatch happens.
So, I think I understand why the warning message is valid, I'm at a lost on what I need to do to correct this situation. For the moment, I'm just ignoring the warning, and so far I'm not finding any issues in proceeding that way. But that's means I'm proceeding, without an understanding of what's going on here! Sometimes that's okay and at other times that's a bad  judgment The error message itself seems inverted. I would think that 1.6.10 is the embedded kotlin and kotlin-dsl since it an android studio plugin, but the error message seems to say it in the opposite way. So anyway, if someone can bring some clarity as to what's going on, and how I'm thinking wrongly about this problem would be greatly appreciated.

A: I'll accept the following as the answer to what's going on about the unsupported kotlin version:
https://github.com/gradle/gradle/issues/13020
So, for the moment, I'll go on like this is just a nuisance warning and ignore that.

A: What I just did was to re-create my Android Studio from a blank brand new project.  I copied and pasted stuff from the previous project into the new project.  I copied the source and build.script.kts files, so essentially everything is a copy of the disabandoned project.  This new project didn't give me the WARNING message anymore.  And in additional, I'm now able to upgrade my project to using kotlin 1.6.10, which I previously couldn't do because of the literally 100's of dependencies resolution issues.  Whatever, that issue went away, and a lot of others things started working as expected once I recreated the project.  I can't say what got my project into that weird state. Deleting the .gradle and .idea folders, wouldn't fix the problem.  I didn't try deleting the JetBrains cache, I wish I would have tried that.


text:
Q: asp.net MVC 3 Razor layout error In my asp.net MVC 3 application, I have nested layouts. I have followed following link:
http://blogs.msdn.com/b/marcinon/archive/2010/12/15/razor-nested-layouts-and-redefined-sections.aspx
My main layout page is_MasterLayout.cshtml and then a nested layout page _fullLayout.cshtml. In  _fullLayout.cshtml, I have:
@this.RedefineSection("BodyTitle")
@this.RedefineSection("Showcase")

but I am getting on these lines. Error is:
Compilation Error
Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.
Compiler Error Message: CS1928: 'ASP._Page_Views_Shared__fullLayout_cshtml' does not contain a definition for 'RedefineSection' and the best extension method overload 'SectionExtensions.RedefineSection(System.Web.WebPages.WebPageBase, string)' has some invalid arguments
Source Error:
Line 9:
Line 10: }
Line 11: @this.RedefineSection("BodyTitle")
Line 12: @this.RedefineSection("Showcase")
Line 13: @RenderBody()
my helper methods are defined like this:
public static class SectionExtensions
{

    private static readonly object _o = new object();

    public static HelperResult RenderSection(this WebPageBase page, string sectionName, Func<object, HelperResult> defaultContent)
    {
        if (page.IsSectionDefined(sectionName))
            return page.RenderSection(sectionName);
        else
            return defaultContent(_o);
    }

    public static HelperResult RedefineSection(this WebPageBase page, string sectionName)
    {
        return RedefineSection(page, sectionName, defaultContent: null);
    }

    public static HelperResult RedefineSection(this WebPageBase page, string sectionName, Func<object, HelperResult> defaultContent)
    {
        if (page.IsSectionDefined(sectionName))
            page.DefineSection(sectionName, () => page.Write(page.RenderSection(sectionName)));
        else if (defaultContent != null)
            page.DefineSection(sectionName, () => page.Write(defaultContent(_o)));
        return new HelperResult(_ => { });
    }

}

Please suggest solution.
Regards,
Asif Hameed

A: Following step to resolve your issue
1. Get the namespace of your class "SectionExtensions".
2. In your layout page where you use RedefineSection import that name space at top of page using
@using yournamespace;
Thanks.

A: RedefineSection helper contains two or more argument
RedefineSection(this WebPageBase page, string sectionName)

but you are passing only one in your view
@this.RedefineSection("BodyTitle")
@this.RedefineSection("Showcase")

According to
http://blogs.msdn.com/b/marcinon/archive/2010/12/15/razor-nested-layouts-and-redefined-sections.aspx
you have to put something
@this.RedefineSection("TitleSection",
                  @
Default SubLayout title
)


text:
Q: How to retrieve binarydata source of an image in asp.net I want to get image preview before uploading any image in my asp.net webform. I am doing this by the following code. But after clicking Save button I want to upload the image to the server. In my codebehind I am getting src="" for . What can I do to get the binarydata back to save my file.

<title></title>

<form id="form1" runat="server">
    <asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server"></asp:ToolkitScriptManager>
    <asp:UpdatePanel runat="server">
        <ContentTemplate>
            <input type="file" accept="image/*" onchange="showMyImage(this)" />

            <asp:Button runat="server" Text="Save" OnClick="Unnamed_Click"/>
        </ContentTemplate>
    </asp:UpdatePanel>

</form>

Thanks in advance..

A: ### Undated whole Answer ###
Option 1:
dont read the img-tag src-attribute, the client cant update it on server side and it wont be "post-back". use an input field like this
<form...>
    ...
    <input class="image-data" type="hidden" id="imageString" runat="server" />
    ...
</form>

and in the Js-Code add this dataurl as value of this field.
 ...
 reader.onload = (function (aImg) {
     return function (e) {
     aImg.src = e.target.result;
     //... add this, it's searches for the input-field, to be able to post the String to the Server
     $(".image-data").val(e.target.result);
 };
 ...

Update:
On the Server you can read the Data like this.
 string imageData = imageString.Value;

Option 2:
you could also do this:
alter your asp.net-file

<form id="form1" runat="server" enctype="multipart/form-data">
    ...

    <input type="file" accept="image/*" onchange="showMyImage(this)" name="uploadImage" />
    ...

in the Codebehind:
HttpPostedFile imageFile= Request.Files["uploadImage"];

if (imageFile && imageFile.ContentLength > 0)
{
   // ... Use the imageFile variable as you please
}

Which Option depends, what you want to do with the data.


text:
Q: Private Java class properties mysteriously reset between method calls I have a very odd problem.
A class property is mysteriously reset between method calls.
The following code is executed so the constructor is called, then the parseConfiguration method is called. Finally, processData is called.
The parseConfiguration method sets the "recursive" property to "true". However, as soon as it enters "processData", "recursive" becomes "false".
This problem isn't isolated to a single class -- I have several examples of this in my code.
How can this possibly be happening? I've tried initialising properties when they're declared outside any methods, I've tried initialising them in constructors... nothing works.
The only complication I can think of here is that this class is invoked by an object that runs in a thread -- but here is one instance per thread, so surely no chance that threads are interfering. I've tried setting both methods to "synchronized", but this still happens.
I'm on JDK 1.6.0_19 on linux.
Please help!
/**
 * This class or its superclasses are NOT threaded and don't extend Thread
 */
public class DirectoryAcquirer extends Manipulator
{
/**
 * @var Whether to recursively scan directories
 */
private boolean recursive = false;

/**
 * Constructor
 */
public DirectoryAcquirer()
{
}

/**
 * Constructor that initialises the configuration
 *
 * @param config
 * @throws InvalidConfigurationException
 */
public DirectoryAcquirer(HierarchicalConfiguration config) throws InvalidConfigurationException
{
    super(config);
}

@Override
protected void parseConfiguration() throws InvalidConfigurationException
{
    // set whether to recurse into directories or not
    if (this.config.containsKey("recursive"))
    {
    // this.recursive gets set to "true" here
        this.recursive = this.config.getBoolean("recursive");

    }
}

@Override
public EntityCollection processData(EntityCollection data)
{
// here this.recursive is "false"
    this.logger.debug("processData: Entered method");
}
}

A: Synchronized methods just means that two threads cannot be within the synchronized methods at the same time.  It is useful for race conditions, but it is not the only way that unexpected things might happen.
The line
// this.recursive gets set to "true" here
    this.recursive = this.config.getBoolean("recursive");

confuses me.  How do you know that this.config.getBoolean("recursive") returns true?  It's only getting a boolean value stored with the key recursive.  That value might be true, but it might also be false.
Assuming you verify that this.config.getBoolean("recursive") really does return true, then you have to look outside your code.  Did something actually call protected void parseConfiguration()?  If not, then this.recursive will have never been set beyond it's initial declaration.
Let's say that protected void parseConfiguration() was called, and it properly set this.recursive to true.  Then you need to hunt through the rest of the class (an only this class because this.recursive is private, and see if any other code might reset the value.
Other possibilities are that you're not dealing with the same object between the two calls to protected void parseConfiguration().  Sometimes this happens when you use object maps or other forms of object caching which present the opportunity to switch out objects if they are used or written wrong.  You might want to put in some logging which will print out the Object's id (toString()) along with the value of this.recursive.

A: There is not sufficient context to explain what is going on, but I can guarantee that private attributes do not reset "spontaneously" in Java.  If I were to guess at possible causes, I'd vote for one or more of the following:

*

*the methods are not being called in the order you think they are,

*one or of the methods is overloaded or overridden, or

*you are looking at different objects.

For example, if a parseConfiguration method is called by the superclass, then it may be that the actual parseConfiguration method used is one in a subclass of DirectoryAcquirer.
Declaring the methods as synchronized is unlikely to help.  At best, that will prevent two threads calling those methods simultaneously on the same object.  It won't stop calls from another thread entirely.

A: I'd take an old-school approach.
Add this to parseConfiguration:
System.err.println("parseConfiguration: this = " + this + ", config = " + config
    + ", recursive = " + recursive + " on " + Thread.currentThread());

Add this to processData:
System.err.println("processData: this = " + this + ", config = " + config
    + ", recursive = " + recursive + " on " + Thread.currentThread());

It will tell you in what order they are being called and verify that they are referencing the same objects and doing so on the same threads.
The only causes I can think of are either threading (parseConfiguration and processData are being called on different threads) or, they are being called on different objects.

A: It really smells to me like the different method calls on the one object are being called from two different threads. This totally explains the 'mysterious reset'-like behavior.
In a nutshell, changes to member variables are not guaranteed to be seen between threads.  Read up on the Java Memory Model for details.
To over come this, there are a couple of options.  The two easiest (for your example) would be either a) use the volatile modifier:
private volatile boolean recursive = false;

or b) use java.util.concurrent.AtomicBoolean
private AtomicBoolean recursive = new AtomicBoolean(false);

The synchronized keyword, while an important tool for multithreaded programming, is not something one can use properly without understanding how it works (and does not work) in greater detail.  Try the above suggestions first.

A: I would try running this piece of code with a debugger and see what exactly is happening.
Because there are a few simple scenarios for a mistake:

*

*the methods are not doing what you expect

*your this.recursive = true code is not reached at all

*you are not setting the value to true at all

*you are not checking the right property

*you are not checking the property correctly

Debugger will help you with that. Please update information when you see it and you could even have an idea to help yourself.

A: Thanks for your replies.
It seems that the problem was related to casting:
/**
 *
 */
public class Manipulator
{
    // both constructors call parseConfiguration()

    protected void parseConfiguration() throws InvalidConfigurationException
    {
      // don't do anything. this is a default method that can optionally be
      // overridden by subclasses
    }
}

I was referring in some places to the object as a DirectoryAcquirer, an at other times it was upcast to a Manipulator. I think that this was interfering so the empty parseConfiguration method was called after the child one was called -- or something like that.
Anyway, I made the parseConfiguration method in the superclass abstract, and now it's fine.


text:
Q: a['map'](b) how does this Javascript syntax work and what is it called? var a = [1, 2, 3];
var b = n => n + 5;
var wtf = 'map'

a[wtf](b);     // Array(3) [ 6, 7, 8 ]
a['map'](b);   // Array(3) [ 6, 7, 8 ]

I don't understand the general principle behind it and can't figure out what is it called so I can look it up.


text:
Q: How to loop through table cells in the same row with JQuery I have this table, which is always going to have one row:

            @foreach (var coverableItem in Model.ContractCoverablesList)
            {

                        @Html.Hidden("coverableID", coverableItem.CoverID)
                        @Html.Label(coverableItem.Name)
                        @Html.CheckBox("coverableItemCheckBox", coverableItem.IsApplied)

            }

I would like to be able to loop through every cell, find out if the checkbox is checked, then capture the ID in that cell, which is as you see a hidden field.
I have tried to do this, but the problem is that when it reaches the if clause; it doesn't detected the checked box:
//Coverable Items
var count = 0;
var allCoverableItems = [];
$("#contractCoverablesGrid tbody tr td").each(function () {
    var cell = $(this);

    var coverableItem = {};

    if (cell.find('td input[type="checkbox"]').is(':checked')) { // Here, it doesn't detect checked boxes!!
        var coverableId = cell.find("input[name='coverableID']")[count].value;

        coverableItem["CoverID"] = coverableId;
        allCoverableItems.push(coverableItem);
    }
    count++;
});

I wonder what is wrong here - I am a bit new to JQuery/Javascript.
Many thanks.
Edit
This is the working code:
//Coverable Items
var allCoverableItems = [];
$("#contractCoverablesGrid tbody tr td").each(function () {
    var cell = $(this);

    var coverableItem = {};

    if (cell.find('input[type="checkbox"]').is(':checked')) {
        var coverableId = cell.find("input[name='coverableID']").val();

        coverableItem["CoverID"] = coverableId;
        allCoverableItems.push(coverableItem);
    }
});

I removed the count and followed the answer below, plus; I used val() instead of value;

A: The trouble is with your selector.  You are searching for a td within cell, but cell already is a td.  Change it to this:
cell.find('input[type="checkbox"]')

You'll also have trouble with the next line, when you try to access the hidden field via [count].  It looks like when you started writing this code, you intended to act on the row, but at some point chose to iterate the cells instead.  The next line should be:
var coverableId = cell.find("input[name='coverableID']").val();


text:
Q: Google Chart Tools - How to create stacked bar chart
Possible Duplicate:
Can someone help me create a simple vertical bar chart using google charts?

Im using new Google Chart Tools, and I want to create stacked bar chart format.

A: The Google Developers site gives some details on the bar chart format: https://developers.google.com/chart/interactive/docs/gallery/barchart
To make a normal bar chart stacked, you need to user the isStacked: true option. You can copy and paste the following code into the Chart Tools playground to see a working example:
http://code.google.com/apis/ajax/playground/?type=visualization
function drawVisualization() {
  // Create and populate the data table.
  var data = google.visualization.arrayToDataTable([
    ['Year', 'Austria', 'Bulgaria', 'Denmark', 'Greece'],
    ['2003',  1336060,    400361,    1001582,   997974],
    ['2004',  1538156,    366849,    1119450,   941795],
    ['2005',  1576579,    440514,    993360,    930593],
    ['2006',  1600652,    434552,    1004163,   897127],
    ['2007',  1968113,    393032,    979198,    1080887],
    ['2008',  1901067,    517206,    916965,    1056036]
  ]);

  // Create and draw the visualization.
  new google.visualization.BarChart(document.getElementById('visualization')).
      draw(data,
           {title:"Yearly Coffee Consumption by Country",
            width:600, height:400,
            vAxis: {title: "Year"},
            hAxis: {title: "Cups"},
            isStacked: true}
      );
}

You might also be interested in a Stacked Area Chart, depending on what data you are trying to display.
There is also a question which gives an example of a stacked bar chart using the Chart Tools Image API: Bar chart in Javascript: stacked bars + grouped bars
Note that the Image Charts portion of Google Chart Tools was officially deprecated on the 20th April, 2012. Image charts will still work for a while as per Google's deprecation policy, but I recommend you concentrate on the interactive HTML5+SVG implementation described above.


text:
Q: Keyboard shortcut for R assignment operator (<-) in VSCode in editor and terminal How would I add a keyboard shortcut for the basic assignment operator (<-) that works both in the editor AND the terminal?
Getting it to work in the editor is straightforward (content goes into keybindings.json):
{
  "key": "alt+-",
  "command": "type",
  "when": "editorLangId == r && editorTextFocus || editorLangId == rmd && editorTextFocus",
  // if you want using quarto, try this
  // "when": "editorLangId =~ /r|rmd|qmd/ && editorTextFocus",
  "args": {"text": " <- "}
}

But I'm struggling with understanding what the when clause would need to look like for the terminal.
Things I tried based on the official doc on when clauses:

*

*using terminalFocus
{
    "key": "alt+-",
    "command": "type",
    // "when": "editorLangId == r && editorTextFocus || editorLangId == rmd && editorTextFocus || terminalFocus",
    "args": {"text": " <- "}
}

*

*additional explicit language ID based on official doc
{
    "key": "alt+-",
    "command": "type",
    // "when": "editorLangId == r && editorTextFocus || editorLangId == rmd && editorTextFocus || editorLangId == shellscript && terminalFocus",
    "args": {"text": " <- "}
}

A: You can't use the type command to write to the terminal.  Try this instead:
{
  "key": "alt+-",  // or whatever keybinding you want
  "command": "workbench.action.terminal.sendSequence",
  "args": {
      "text": " <- "
  },
  "when": "terminalFocus && !terminalTextSelected"
}

See send text to terminal docs


text:
Q: smart double quotes cause compilation error I am facing a error in Java using the method Loops. I  am a basic user learning Java and I am following a book with teaches you the basics of Java.
I have this problem when I use this code in my Java Program. It gives me an red line under my code. Here's my code:
public class Game{

    public static void main(String[] args){

    for (int dex = 0; dex < 1000; dex++) {
    if (dex % 12 == 0) {
          System.out.println("#: " + dex);
        }
       }
     }
    }

I have been following the tutorials correctly. I am a bit lost where I have gone or done wrong. I have my public static codes and such as you'd require in any Java programming.
Here's are the error given):
Cannot resolve method: 'Println(? , ?)'
Expression expected
',' or ')' expected
Unexpected Token
';' expected

A: Your code compiles and runs without problems on my computer. I only had to replace your " by "
 public class Game{

    public static void main(String[] args){

      for (int dex = 0; dex < 1000; dex++) {
        if (dex % 12 == 0) {
          System.out.println("#: " + dex);
        }
      }
    }
  }

A: nothing is wrong here with the code but use valid double quotes as java reads. Your code is not using them. As
System.out.println("#: " + dex);


text:
Q: why am not able to view to complete text in my app <?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#F3E889"
    android:paddingLeft="100dp"
    android:paddingTop="100dp"
    android:paddingEnd="100dp"
    android:paddingRight="100dp"
    android:paddingBottom="100dp"
    android:textAlignment="center"
    android:visibility="visible"
    tools:context=".MainActivity">
    <EditText
        android:id="@+id/editTextTextPersonName4"
        android:layout_width="300dp"
        android:layout_height="300dp"
        android:ems="100"
        android:inputType="textPersonName"
        android:text="I want to be a Android developer"

        tools:layout_editor_absoluteX="-64dp"
        tools:layout_editor_absoluteY="-46dp" />
</androidx.constraintlayout.widget.ConstraintLayout>

This is simple code which is trying to print I want to be a Android developed but when viewed on
mobile its not showing the complete sentence.

A: May be you don't give a proper constraints to your editText also you don't give a proper padding to your parent layout, please try this code :
<androidx.constraintlayout.widget.ConstraintLayout
      xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:app="http://schemas.android.com/apk/res-auto"
      xmlns:tools="http://schemas.android.com/tools"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:background="#F3E889"
      android:padding="10dp"
      android:textAlignment="center"
      android:visibility="visible"
      tools:context=".MainActivity">

    <EditText
         android:id="@+id/editTextTextPersonName4"
         android:layout_width="0dp"
         android:layout_height="wrap_content"
         app:layout_constraintEnd_toEndOf="parent"
         app:layout_constraintStart_toStartOf="parent"
         app:layout_constraintTop_toTopOf="parent"
         android:inputType="textPersonName"
         android:text="I want to be a Android developer"/>

A: There's 100 dp of padding on all 4 sides. That pushes all the content to the middle of the screen. It cuts off like half of the usable space.