text:
Q: White rectangles on Plasma desktop (Updated) I am having a problem with my desktop. I have ended up with three off-white rectangles on the desktop, each of which contain the name/title of a news item that I downloaded from a respectable linux news site. The "first" rectangle is approx. 56mm (hor.) x 33mm (ver.), the "second"" is approx. 56mm (hor.) x 58mm (ver.), and the "third" is approx. 56mm (hor.) x 58mm (ver.).
@DK Bose & @guiverc:
Thank you for your responses to my previous post which I have implemented. As you will see from the system info above, I have carried out a (Konsole-based) release-upgrade to a supported version and the original problem, as stated above, has persisted. I have also, as requested, supplied a screenshot.
My questions are :-
a) has anyone else ever experienced this type of desktop behaviour ?
b) does anyone know how I can clear these rectangles from the desktop ?
I should also state that I am using the Cube desktop and that these rectangles appear on every virtual desktop that comprises the Cube.
Any help would be greatly appreciated.
Stuart


text:
Q: Understanding and interpreting quantile regression I am trying to better understand what quantile regressions are and how we can interpret them. I know that quantile regressions are used to model a specific conditional quantile $\tau$ of a response variable $y$ given some covariates $X$ as opposed to modeling the conditional mean of $y$ in an OLS setting. Now I've been studying some of the standard definitions that are easily found online and in standard textbooks. However, I was specifically wondering why the approach I will outline below is not correct.
I understand estimating a quantile regression as estimating a changing relationship between $y$ and $X$ that varies over the distribution of $y$. In more formal terms, I have been thinking about a hypothetical quantile regression data generating process as
$y_{\tau} = X_{\tau}\beta_{\tau} + \epsilon_{\tau}$
where $y_{\tau}$ is an estimate of $y$ in quantile $\tau$ and $\epsilon$ is an error term. The main point is that the coefficient $\beta_{\tau}$ varies over the quantiles of $y$. In more simple terms, each quantile $\tau$ has its own coefficient $\beta_{\tau}.$
I implemented the DGP above and simulated 100 data points (representing 100 percentiles) increasing $\beta_\tau$ gradually. Then, I estimated a quantile regression for all percentiles of $y$. This exercise basically returns the OLS coefficient for all percentiles. I was expecting a lot of noise due to only 1 observation per percentile. However, I did also expect some evidence pointing into the direction of the true values of $\beta_\tau$. Now I am wondering where I went wrong and how the setup above differs from traditional quantile regression.
Edit:
To add some clarification after David's comment: Seemingly, the interpretation of quantile regressions is "a unit change in $X$ changes quantile $\tau$ of $y$ by $\beta_{\tau}$" where we estimate different $\beta_{\tau}$ for each quantile. If that is not the correct interpretation, this would already solve my question. If that is the correct interpretation, I do not understand why the DGP I outlined above, interpreted as "each quantile $\tau$ has its own coefficient $\beta_{\tau}$" does not give similar results.
My Code (in R):
X    = rnorm(100)
beta = seq(0,5,length.out = 100)
y = c()
for(tt in 1:100){

 y[tt] = X[tt] * beta[tt] + rnorm(1)

}

plot(y,X)

olsres = summary(lm(y~X-1))

qrres = quantreg::rq(y~X-1,tau = seq(0,1,length.out=100))

A: I suspect you mistake Quantile Regression for some sort of piece-wise linear regression, where a normal OLS line is fitted to subsets of the observation space (note that if you think about this, it can be quite complicated to determine how to subset this data in a multivariate case if you only have a single parameter $\tau$).
Quantile regression is something different, where the conditional median is estimated (for $\tau = 0.5$) or at any other percentile of interest. Which percentile depends on the value of $\tau$ you specify: you specifically are calculating the conditional median at every percentile.  It is usually applied in cases where certain assumptions do not hold (for example if there is a multimodal structure to your data and a conditional mean is not very informative). It is not re-estimating the OLS line based on bins of your independent variable (as you seem to suspect). Note also that if it was doing this, you would have a single observation in every bin and it would not even be possible to estimate a slope $\hat{\beta}$. In other words: Quantile Regression does not subset the number of observations used or anything like that.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can someone explain why Python isn't reading this file? So I have this code down below. Basically, it should read the lines in testcase.txt and print them out, however it's coming up blank when I run the program. Any solutions to this?
testFile = 'testcase.txt'
file = open(testFile, 'r')
index = 0
for line in file:
    test_list.insert(index,line)
    index += 1
file.close()

A: You probably want to read the documents a bit more regarding python file objects' methods, but here:
filecontents = open('testcase.txt').readlines()
#readlines automatically splits the file up by linebreaks

for index,line in enumerate(filecontents):
    print(index,line)


text:
Q: How to find convergence point for a given iterative scheme The equation $x^2+ax+b=0$ has two real roots $\alpha$ and $\beta$.
Show that the iterative method given by
$\displaystyle x_{k+1}=-\frac{(ax_k+b)}{x_k}$
is convergent near $x=\alpha$, if $|\alpha|>|\beta|$

A: You can see this as a fixed point iteration method for find a root of the polynomial function:
$$p(x) = x^2 + ax + b,$$
where the iteration function is defined by,
$$\phi(x) = - \frac{ax + b}{x}.$$
Since $\phi(x)$ and $\phi'(x)$ are continuous, the iterative method will converge if $|\phi'(x)|<1$, for all $x$ sufficiently near to $\alpha$. We have,
$$\phi'(x) = -\frac{b}{x^2} = \frac{\alpha\beta}{x^2}.$$
Then, for $x$ sufficiently near to $\alpha$, $|\phi'(x)|<1$, because $|\alpha|>|\beta|$. So the iterative method is convergent near $x = \alpha$.


text:
Q: Tips For an Intro Python Program Below is my first python program. I am trying idea not yet covered in class as i hate staying stagnant and want to solve issues that may arise if i were to just use the info we've learned in class. As for my question, the program works but what were be ways to condense the code, if any? Thanks!
#This is a program to provide an itemized receipt for a campsite
# CONSTANTS
ELECTRICITY=10.00 #one time electricity charge

class colors:
    ERROR = "\033[91m"
    END = "\033[0m"

#input validation
while True:
    while True:
        try:
            nightly_rate=float(input("Enter the Basic Nightly Rate:$"))
        except ValueError:
            print(colors.ERROR +"ERROR: Please Enter the Dollar Amount"+colors.END)
        else:
            break
    while True:
        try:
            number_of_nights=int(input("Enter the Number of Nights You Will Be Staying:"))
        except ValueError:
            print(colors.ERROR +"ERROR: Please Enter a Number"+colors.END)
        else:
            break
    while True:
        try:
            campers=int(input("Enter the Number of Campers:"))
        except ValueError:
            print(colors.ERROR +"ERROR: Please Enter a Number"+colors.END)
        else:
            break
    break
#processing
while True:
    try:
        campsite=nightly_rate*number_of_nights
        tax=(ELECTRICITY*0.07)+(campsite*0.07)
        ranger=(campsite+ELECTRICITY+tax)*0.15 #gratuity paid towards Ranger
        total=campsite+ELECTRICITY+tax+ranger  #total paid per camper
        total_per=total/campers
    except ZeroDivisionError:                  #attempt to work around ZeroDivisionError
        total_per=0                            #total per set to zero as the user inputed 0 for number-
    break                                          #-of campers

#Output     #Cant figure out how to get only the output colored
print("Nightly Rate-----------------------",nightly_rate)
print("Number of Nights-------------------",number_of_nights)
print("Number of Campers------------------",campers)
print()
print("Campsite--------------------------- $%4.2f"%campsite)
print("Electricity------------------------ $%4.2f"%ELECTRICITY)
print("Tax-------------------------------- $%4.2f"%tax)
print("Ranger----------------------------- $%4.2f"%ranger)
print("Total------------------------------ $%4.2f"%total)
print()
print("Cost Per Camper-------------------  $%4.2f"%total_per)

A: *

*You can remove both the outer while loops, as break is seen there at the top level, so the loops runs once only.

*You can convert colors to an Enum class if desired (this is more of a stylistic choice tbh)

*The line tax=(ELECTRICITY*0.07)+(campsite*0.07) can be represented as x*0.07 + y*0.07, which can be simplified to 0.07(x+y) or 0.07 * (ELECTRICITY + campsite) in this case.

*Instead of manually padding the - characters in the print statements, you can use f-strings with simple formatting trick.
For example, try this out:

width = 40
fill = '-'
tax = 1.2345

print(f'{"Tax":{fill}<{width}} ${tax:4.2f}')

A: *

*The else in try statement is unnecessary. You can just put the break in the the end of the try statement. REF

*In the end, in the print statements, I recommend you to use another types of formatting. You can use '...{}..'.format(..) or further pythonic is f'...{val}'. Your method is the oldest. More ref


text:
Q: iOS app binary submission: submitted from Xcode but it does not appear in iTunes Connect I've validated and submitted my app from Xcode. I received a warning saying "Archive submission completed with warnings", and saying that I must support 64-bits starting February 1. But as faras I understand, this is just a warning, and the warning's header says "Archive submission completed". However, the binary is not appearing in my iTunes Connect entry, has somebody experienced the same?
Thanks

A: Go to:

*

*iTunes Connect

*My Apps

*Your App Name

*Scroll down to "Build" and select the build you just uploaded.

A: The reason for the warning is to remind you that starting in February 1st, 2015, all iOS Apps need to provide 64-bit support. This is not an error nor is it a reason for rejection of your app.

As for the app on itunes connect, have you checked in: your_app/Prerelease ?
if you see this (in the page of your app) means that you have not uploaded any build

if you see this (in the page of your app) means you have successfully loaded one or more build

More info here


text:
Q: What in JavaScript can cause browser crashes? I have an application that a wrote in straight JavaScript (no jQuery or anything).  What it does is it uploads an image, and when you click on it, it gets the dominant colors of the image as well as picks the color you just clicked in the image, and generates a color scheme based on this.
I have part of it implemented here: http://cassidoo.co/assets/colordetect/index.html (this version only has the color detection part, not the color picker/color scheme part)
Now, I'm trying to figure out some issues.  The application usually works.  The only time it doesn't work is when the browser crashes.  I looked at the thread here:
How can I test potentially "browser-crashing" JavaScript?
And I've been using my debugger and everything, but I'm not actually getting any errors when the browser crashes.  It just suddenly isn't responsive and after a little while I get the "Oh, Snap" screen or something.
How can I debug this?  What in my code might be freaking out (like is it an infinite loop I'm not closing, something with the canvas that's not normal)?  Why does it only happen like 50-60% of the time?  Is it a cache issue?

A: Do you have particular test images which always make it crash? If so, can you upload them somewhere so we can test with them?
I'm finding that it always crashes when trying to process an animated GIF.  Using Chrome's debugger, I can see that it's getting into an infinite loop in the while (true) loop in k_mean(). The break condition diff < min_diff is never happening. Something's going wrong in the code, because diff is always NaN (not a number).
A good way to debug it is to set breakpoints at various places in the code, look at the state of the variables each time a breakpoint is triggered, etc. The profiler in Chrome can also be useful, by showing you where the execution time is being spent.

A: It probably is an infinite loop. You can test that by putting a condition in your loop that throws an alert or console-log after 100 loops (or whatever) and halts execution.
Any tricky regular expressions? Catastrophic backtracking can bring you down too. http://www.regular-expressions.info/catastrophic.html
And as mentioned above, too many recursions will also. Any functions calling themselves repeatedly?

A: You could always do something like this:
var foo = "bar";
while (1) {
    foo = foo += "bar"; // adds until memory is full, then crashes (womp womp)
}

A: Here are some of the things that could cause browser crashes, although I am not sure if they are causing your problem.

*

*Anything while(1) (infinite loop) - Browsers cant seem to handle these

*Variable with too much data (out of memory - plausible if storing big images)

*Trying to reload too many times (like infinite loop of realoads)

*SetInterval to SetInterval To SetInterval etc... (this is more silly than a guess)

Probably an infinite loop or just a weird while. I hope you get it fixed!

A: Simplest way:
while(1)location.reload()

It works by creating an endless loop, then refreshes the page until the browser crashes.
Note: it instantly freezes and you can not see it refreshing.
Try it for yourself:
https://send-as-mail.000webhostapp.com/


text:
Q: Icon setting in Gridview in Android I have created a launcher screen following Android samples given in sdk. Now I want my icons to completely fill up the screen. Now if I drag one image view partially it remains as it is in the screen. I want my screen to adjust automatically upon dragging.
I can't post my screenshot here as it isn't allowed.
Hope my question is clear. Now please help me regarding this issue.Thanks in Advance.
Thanks,
Android developer

A: You must googling whatever you need to do. If you didn't get anything else means.  After, that ask here. There are lot of source code available for Drag and Drap imageView in Gridview.
public void onDragEnter(DragSource source, int x, int y, int xOffset, int yOffset,
    DragView dragView, Object dragInfo) {
int bg = mEmpty ? R.color.cell_empty_hover : R.color.cell_filled_hover;
setBackgroundResource (bg);
}

public void onDragExit(DragSource source, int x, int y, int xOffset, int yOffset,
    DragView dragView, Object dragInfo) {
int bg = mEmpty ? R.color.cell_empty : R.color.cell_filled;
setBackgroundResource (bg);
}

These are all the important methods for Drag&Drop the Images.
Take the Source Code.


text:
Q: Defaultdict / not enough values to unpack this is probably a stupid question but : I have this code which worked fine, until I tried to add ml. I tried several manners but
init_dict = []
with open("example.csv", "r") as new_data:
reader = csv.reader(new_data, delimiter=',', quotechar='"')
for row in reader:
    if row:
        columns = [row[0], row[1], row[3]]
        init_dict.append(columns)

result = defaultdict(list)
for ean, price, ml in init_dict:
    result[ean].append(price)
    result[ean].append(ml)

for ean, price, ml in result.items():
    print(ean, " // " . join(price), "::". join(ml))

I need to add the ml info to my current output which is like :
676543 : 6,7 // 6,7
786543 : 3
4543257 : 7,8 // 9,0

etc... Thank you for your help

A: Your result variable is a dict of lists of two items, so you should unpack its items like this instead:
for ean, (price, ml) in result.items():


text:
Q: How to get the id of a head I am trying to give the nearest player a SCP-049 head but i don't know how to put it on them, and how to even give them the head. is there a way to find the id of the head so its easier for me? this is all in Minecraft java 1.12.2
NOTE: SCP-049 looks like a plague doctor.

A: 1.12-
Command
/give @p minecraft:skull 1 3 {SkullOwner:"_plague_doctor__"}

Put On Head
/replaceitem entity @p slot.armor.head minecraft:skull 1 3 {SkullOwner:"_plague_doctor__"}

A: Try using this command:
/give @p minecraft:skull 1 3 {SkullOwner:"SCP-049 (The Doctor)"}


text:
Q: xcode not building arm64/apple silicon universal dylib I am on xcode 12.4 macOS catalina, Intel x64 machine. There is a project which is C/C++ project and outputs a dylib. In the xcode 12.4 the build setting "Architectures" is Apple Silicon & Intel.
Build active architecture Only is No.

The dylib builds fine but when I check if it is a Universal library or not using lipo then it shows on x64 and not arm.

A: I signed up just to post an answer, cause I spend couple of hours myself with the same problem.
There's a setting 'Allow Multi-Platform Builds' under 'Build Options', that should be turned on. It did the trick for me and now it compiles a 'fat' dylib.
Confusing thing is that for the bundles, it compiles the universal binary with this setting turned to off, but not for the dylib's.

A: I've just chased down my problem with a similar scenario, but with an application target. I had copied an FCPX project (created on Xcode v10.*) to a new project intended to support 'arm64' and
x86_64'. Since I was using *.xcconfig settings, I did not expect any problems - but, sure enough, arm64 was NOT built because of a "stray" setting for VALID_ARCHS that restricted the target to x86_64. But Xcode 12.2 no longer displays the "Valid Architectures" setting in the ui (this was the root of my confusion). At any rate, I fixed my issue first by adding a VALID_ARCHS setting (which included arm64) to the *.xcconfig file. The final solution was editing the project.pbxproj file, and discarding the VALID_ARCHS setting.


text:
Q: How do I get velocity for my character in as3 im trying to make a teleporter game and my character needs to have some velocity and gravity, does anyone know what sums i need to be able to acomplish this?
This is my code so far:
var char = this.addChild(new Char());
char.width = 20;
char.height = 20;
char.x = startPos.x;  //startPos is an invisible movieclip that I can move around to     make the starting position
char.y = startPos.y;        // accurate
var vx:Number = 0;
var vt:Number = 0;

stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler);

function keyDownHandler (e:KeyboardEvent):void {
    switch (e.keyCode)  {
        case Keyboard.UP:
        char.y = char.y - 5
    }
}

A: If your char only needs to go up then the following code will do the job.
But if it needs to move in all direction then much advanced code is required.
Follow Moving Character in all directions.
This is a quick solution to your need.
var gravity:Number = 2;

var velocity:Number = 1.1;

var move:Boolean = false;

function moveChar(e:Event):void
{
   if(move)
   {
       gravity *= velocity;
       char.y -= gravity; // move char
   }
}
char.addEventListener(Event.ENTER_FRAME, moveChar, false, 0, true);

//Keyboard events
function keyDownHandler (e:KeyboardEvent):void
{
    switch (e.keyCode)
    {
        case Keyboard.UP:
        move = true;
    }
}
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler);

function keyUpHandler (e:KeyboardEvent):void
{
    move = false;
    gravity = 2;
}
stage.addEventListener(KeyboardEvent.KEY_UP, keyUpHandler);


text:
Q: Building a pipeline for multiple-repository services I'm developing a service in Python which has a package as a dependency. I've developed that dependency myself.
I have a private PyPI server that contains artifacts(a wheel file) of every commit in the master branch(for both packages).
I'd like to create a CI which will use pip to install the dependency from the private PyPI server(because it's faster and easier than installing from the source code itself every time).
Example for the project's dependencies:

packages A requires package B
(which are all in the private repository and not public packages).

My problem is that if I'm trying to execute a CI on the A repository right after the B repository had a merge to master,
the private PyPI server won't have the latest version of B yet(Today there's a Jenkins job that is activated after every merge to master and uploads the B wheel to the private PyPI server,
but it takes a few minutes until the package is being built). The result is that package A might contain an old version of B instead of using the latest version of B.
Any suggestion on how to improve this process?
Installing from a private PyPI, in comparison to installing directly from Gitlab decreases the time it takes to install dramatically.
BTW, today I am using Gitlab's enterprise edition and Jenkins.
Thanks

A: You just need to check if package B is up-to-date before you start the installation of A. So (in your Jenkins job) just put a build step to download everything for B, and after that everything for A.


text:
Q: signrank test in a three-dimensional array in MATLAB I have a 60x60x35 array and would like to calculate the Wilcoxon signed rank test to calculate if the median for each element value across the third array dimension (i.e. with 35 values) is different from zero. Thus, I would like my results in two 60x60 arrays - with values of 0 and 1 depending on the test statistic, and in a separate array with corresponding p values.
The problem I am facing is specifying the command in a way that desired output would have appropriate dimensions and would be calculated across the appropriate dimension of the array.
Thanks for your help and all the best!

A: So one way to solve your problem is using a nested for-loop. Lets say your data is stored in data:
data=rand(60,60,35);
size_data=size(data);
p=zeros(size_data(1),size_data(2));
p(:,:)=NaN;
h=zeros(size_data(1),size_data(2));
h(:,:)=NaN;
for k=1:size_data(1)
    for l=1:size_data(2)
       tmp_data=data(k,l,:);
       tmp_data=reshape(tmp_data,1,numel(tmp_data));
       [p(k,l), h(k,l)]=signrank(tmp_data);
    end
end

What I am doing is I preallocate the memory of p,h as a 60x60 matrix. Then I set them to NaN, so if you can easily see if sth went wrong (0 would be an acceptable result). Now I loop over all elements and store the actual data array in a new variable. signrank needs the data to be an array so I reshape it to two dimensions.
I guess you could skip those loops by using bsxfun


text:
Q: Symfony createQueryBuilder JOIN I'm trying to get my products from repository
I have 3 tables:
- categories
- types which contains categorie_id
- produits which contains types_id
My twig view returns "variable produits does not exist"
What's going wrong in my querybuilder ?
Thanks
class ProduitsRepository extends \Doctrine\ORM\EntityRepository {

    public function byCategorie($categorie) {
        $qb = $this->createQueryBuilder('p')
                ->select('p') // Entity Produits
                ->join('p.type', 't')
                ->addSelect('t') // Entity Types
                ->where('p.type = t.id AND t.categorie = :categorie')
                ->orderBy('p.id')
                ->setParameter('categorie', $categorie);

        return $qb->getQuery()->getResult();
    }
}

ok i add a screenshot
enter image description here
This is my controller
public function categorieAction($categorie)
{
    $em = $this->getDoctrine()->getManager();
    $produits = $em->getRepository('GbaBundle:Produits')->byCategorie($categorie);

    return $this->render('GbaBundle:Default:produits/layout/produits.html.twig', array(
        'produits' => $produits
    ));
}

This is my twig view produits.html.twig

             {% for produit in produits %}

Thumbnail label

100,00 €

                        Plus d'infos

                        Ajouter au panier

              {% endfor %}

A: Sorry I can't post comments but you should give us your twig file, it might help us. Also, I don't think it will change anything but I would write the query like this:
$this->createQueryBuilder('p')
        ->select('p, t')
        ->join('p.type', 't')
        ->where('t.categorie = :categorie')
        ->orderBy('p.id')
        ->setParameter('categorie', $categorie);

Edit: Looking at your screenshot, it seems like you are rendering your view from the wrong controller action. You have one action called categorieAction and another one (which seems to be the wrong one) called produitsAction. You should make different routes for these two actions to avoid collisions.


text:
Q: How to choose pdf file from android storage I'm trying to get a pdf file from my android storage, but everytime it returns null.
It already works with image files, but when i try to get a pdf file it always returns null.
I'm already able to select the pdf file. On onActivityResult i'm able to get the uri from data, but the path is wrong ("content://com.android.providers.media.documents/document/document%3A140"), so i'm trying to get the full path using getPath method, but like i said before, it always returns null.
This code must work with android version >= Android 6.0 (Sdk 23).
private void selecionarArquivo() {
        boolean marshmallow = Build.VERSION.SDK_INT >= 22;
        boolean validate;
        if (marshmallow) {
            String permissions[] = new String[]{ Manifest.permission.READ_EXTERNAL_STORAGE };
            validate = PermissionUtils.validate(getActivity(), 0, permissions);
        } else {
            validate = true;
        }
        if (validate) {
            Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
            // tipo can be application/pdf or image/*
            intent.setType(tipo);
            startActivityForResult(intent, Constantes.REQUEST_CODE_SELECIONAR_ARQUIVO);
        } else {
            AlertUtils.alert(getActivity(), R.string.necessario_aceitar_permissoes, new Runnable() {
                @Override
                public void run() {
                    getActivity().finish();
                }
            });
        }
    }

@Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        try {
            LogUtil.log(TAG, "onActivityResult(): requestCode[" + requestCode + "], resultCode[" + resultCode + "]");

            if (requestCode == Constantes.REQUEST_CODE_SELECIONAR_ARQUIVO && resultCode == Activity.RESULT_OK && data != null) {
                LogUtil.log(TAG, "onActivityResult(): SELECIONOU");
                Uri selectedImageUri = data.getData();

                final String path = FileUtils.getPath(getContext(), selectedImageUri);
                // here path is always null if pdf file is selected
                File f = null;
                if (path != null) {
                    f = new File(path);
                }

                if (f != null) {
                    String fileExtension = FileUtils.getFileExtension(f.getName());
                    if (tipo.contains("pdf") && !fileExtension.equals("pdf")) {
                        alert(R.string.tipo_de_arquivo_invalido);
                        selecionarArquivo();
                    } else {
                        Bundle bundle = new Bundle();
                        foto.file = f;
                        bundle.putSerializable(Foto.KEY, foto);
                        showForResult(ExemploEFotoActivity.class, bundle, Constantes.REQUEST_CODE_CONFIRMAR_FOTO);
                    }
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            alert(R.string.msg_error_foto);
            getActivity().finish();
        }
    }

FileUtils.java
public class FileUtils {
 public static String getPath(final Context context, final Uri uri) {
        if (DocumentsContract.isDocumentUri(context, uri)) {
            // ExternalStorageProvider
            if (isExternalStorageDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                if ("primary".equalsIgnoreCase(type)) {
                    return Environment.getExternalStorageDirectory() + "/" + split[1];
                }
            }
            // DownloadsProvider
            else if (isDownloadsDocument(uri)) {

                final String id = DocumentsContract.getDocumentId(uri);
                final Uri contentUri = ContentUris.withAppendedId(
                        Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

                return getDataColumn(context, contentUri, null, null);
            }
            // MediaProvider
            else if (isMediaDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                } else if ("document".equals(type)) {
                    contentUri = uri;
                }

                final String selection = "_id=?";
                final String[] selectionArgs = new String[] {
                        split[1]
                };

                return getDataColumn(context, contentUri, selection, selectionArgs);
            }
        }
        // MediaStore (and general)
        else if ("content".equalsIgnoreCase(uri.getScheme())) {

            // Return the remote address
            if (isGooglePhotosUri(uri))
                return uri.getLastPathSegment();

            return getDataColumn(context, uri, null, null);
        }
        // File
        else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }

        return null;
    }

    public static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    public static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    public static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }

    public static boolean isGooglePhotosUri(Uri uri) {
        return "com.google.android.apps.photos.content".equals(uri.getAuthority());
    }

    public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
        Cursor cursor = null;
        final String column = "_data";
        final String[] projection = {
                column
        };

        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
                    null);
            if (cursor != null && cursor.moveToFirst()) {
                final int column_index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(column_index);
            }
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return null;
    }
}

A: I end up using this FileUtils, wich worked perfectly.
Thanks for the answers.


text:
Q: Jmeter-While controller is not exiting from loop I have JDBC request which has modified_date which will populate with value depends on payload size. For small payload it will populate the date and time value immediately, for large size it will take from 10 to 30 minutes.
I have added JSSR223 post processor for JDBC request and i am capturing the modified_date and saving in variable "modified". I have added while controller with ${__javaScript(vars.get("Modified"))=="null"} and added same JDBC request with constant timer.
So the while controller keeps looping and it is not stopping or exiting after the value is populated for modified_date. Can you please help.

A: As per documentation

Variables, functions (and properties) are all case-sensitive.

So Modified and modified are different beasts, you need to mind the case and change the While Controller's condition to ${__javaScript(vars.get("Modified"))=="null"}
Also you don't need any scripting in order to save JDBC Request sampler result into a variable, just define it under "Variable names" section:

and given your query returns a single result you will have it in ${modified_1} JMeter Variable.
More information: Debugging JDBC Sampler Results in JMeter


text:
Q: Grammar Rules regarding the pronoun 'it' "I want to be a doctor. I like helping people that's why I want to be it."
"Where's your new iphone? Can you show me it?"
What grammar rules govern the use of the pronoun 'it' in these sentences. They don't sound natural but I'm not sure if they are incorrect.

A: In the first example, the antecedent is "a doctor". The usual way to refer back to an indefinite antecedent (e.g., a noun preceded by the indefinite article) is one:

I want to be a doctor. I like helping people that's why I want to be
  one.

As Swan in Practical English Usage (p369) states in his entry on one:

We often use one instead of repeating a singular countable noun.

*

*Can you len me a pen? ~ Sorry, I don't have one.

In the second example, there is a definite, identifiable antecedent. The usual pronoun for definite, non-human antecedents is it. So there is nothing wrong with it itself in Can you show me it? Some native speakers, however, may object to the order of the pronouns, and prefer: Can you show it to me?
There's a lengthy discussion on this latter issue, here:
Is it incorrect to say, 'Give me it'?
and here:
Direct object "it" in final position... grammatical?

A: These are not typical sentences for an English speaker.

I want to be a doctor. I like helping people that's why I want to be
  it.

… would be:

I want to be a doctor. I like helping people, that's why.

… or more naturally:

I want to be a doctor because I like helping people.

And this sentence:

Where's your new iphone? Can you show me it?

… is fine except you drop the unnecessary "it:"

Where's your new iphone? Can you show me?


text:
Q: Юнит тестирование приложения при кросс-компиляции Я разрабатываю консольное C++ приложение для MIPS роутера. Сборка с помощью кросс-тулчейна. Соответственно, нет возможности запускать юнит-тесты на локальной машине. Для тестирования использовать собираюсь Boost Test.
Вопрос в том, как правильно организовать сборку и запуск юнит-тестов?
У меня два варианта:
- Создание отдельной цели в мейкфайле. будет собираться такой же бинарник, только у него будет другой main.cpp
- Включение всех тестов в сбоку с помощью условий препроцессора. Ну и потом запуск тестов через
./application tests
Как вы тестируете такого рода приложения?
Я, конечно, пользуюсь IDE, но сборка всё равно через Makefile. Так что всякие плагины к IDE точно не подойдут.
UPD: Я понял, что после хорошей декомпозиции, на локальной машине можно делать почти все юнит-тесты, а на целевое железо вынести тесты функциональные, которые будут запускаться при вызове программы с параметром, как описано выше.

A: В общем тактика простая здесь, код для тестирования писать кроссплатформенным, тестировать и на земле и на железке. Вся надежда на то, что Си будет вести себя одинаково.
Процесс примерно такой:

*

*Разработку и тестирование выполняет на рабочей платформе, как можно больше кода выносим в кросплатформенную часть.

*Периодически выполняем тестирование на целевом вычислителе, при этом результаты тестов на целевой и рабочей платформах должны точно совпадать. В идеале код тестов должен быть одним и тем же.

*Платформозависимые части должны быть максимально простыми, ошибки в них должны легко находится.

Организация сборки зависит от среды разработки. Вполне может быть что тестирование выполняется на "Виндоуз" и тесты собираются и выполняются студией, при этом целевая платформа может быть лысым чертом с рогами. В этом случае приходится вести два отдельных сборочных проекта, каждый под свой набор инструментов.
Если у вас один и тот же инструмент все собирает, то можно воспользоваться его возможностями для разделения на модули. Ваш вариант с отдельными целями вполне рабочий.


text:
Q: To retrieve contact list with number in android Hi i want to retrieve name and numbers from contact list in android ,am using following code, it will give me name but not number it gives null value  for number
NOTE: am using android emulator
  public void demo(){
    String phoneNumber;
    String [] item = new String[]{ People._ID,

            People.NAME,
            People.NUMBER};

    Cursor cur = getContentResolver().query(People.CONTENT_URI ,item , null, null, null);
    int phoneNumberIndex = cur.getColumnIndexOrThrow(People.NUMBER);
    if (cur != null) {
        Log.v("cur not null", "Cursor Not null");

        if (cur.moveToNext()) {
            Log.v("moveToNext", "Moved to first");
            Log.v("moveToNext", "Cursor Moved to first and checking");
            phoneNumber = cur.getString(phoneNumberIndex);
            System.out.println("****** from_number "+phoneNumber +" *****************");
        }
    }
}

A: It gives null because u r trying to retrieve only one number.. this should work..
if (cur.moveToNext()) {
            Log.v("moveToNext", "Moved to first");
            Log.v("moveToNext", "Cursor Moved to first and checking");
while(cur.moveToNext())
{
            phoneNumber = cur.getString(phoneNumberIndex);
            System.out.println("****** from_number "+phoneNumber +" *****************");
}
        }


text:
Q: Autoregression model I am using AR model in Python. The code is:
from statsmodels.tsa.ar_model import AR
import numpy as np
signal=np.loadtxt("secular.txt")
ar_mod = AR(signal)
ar_res = ar_mod.fit(4)
print AR(signal)
print ar_res

As I know, the ar_res shoule be an array which is detrended of the original one. But, the result of print is this one:
<statsmodels.tsa.ar_model.AR object at 0x7f9224f88d10>
<statsmodels.tsa.ar_model.ARResultsWrapper object at 0x7f9225542b10>

I do not know what is wrong.


text:
Q: MovieWriter (ffmpeg) not available PyCharm (Windows) I have followed instructions to download ffmpeg and add the path according to
Matplotlib-Animation "No MovieWriters Available"
Although I can type version in both in command prompt and Bash on Windows console, beloved PyCharm warns me:
Requested MovieWriter (ffmpeg) not available

when I try to save the animation:
ani = anim.FuncAnimation(fig, animate, frames = 14, init_func = init, interval = 500, repeat = False)
plt.show()
ani.save("Inno.mp4", writer=writer)

Do I have to add another path? Please, help me, I am really tired of this error.

A: You can specify the ffmpeg path directly as follows:
plt.rcParams['animation.ffmpeg_path'] = 'ffmpeg path on your machine' (e.g.: "C:\FFmpeg\bin\ffmpeg.exe")

or try on your cmd calling the ffmpeg to make sure the have properly defined its path in your env variables.
to get the path after making sure the path s properly defined, write in your cmd:
where ffmpeg

A: Windows 10:
1) open: Anaconda prompt
2) fire: conda install -c conda-forge ffmpeg
3) restart your environment
Worked for me.

A: I suggest the following to show the simulation for a time t (for example 3000 ms here) then saving the animation before closing the animation because the problem in your code is to close the animation before creating saving so the tk backend fails to find the figure to draw inside of it. I suggest the following:
def close():
    animation.save("Inno.mp4", writer='ffmpeg')
    plt.close()

timer = fig.canvas.new_timer(interval = 1000)
timer.add_callback(close)

plt.show(block=False)
timer.start()
plt.show()


text:
Q: How To Start A Session Using Another Field Name From DatabasE? I have a session registered from previous webpages in my website called 'name'. this is one of my fields in my database and was registered as a session after a person has logged into one section out of the many login screens. How do i go about changing this session variable? my code is as follows:
    <?php

$secret_anwser=$_POST['secret_anwser'];
$secret_anwser = stripslashes($secret_anwser);
$secret_anwser = mysql_real_escape_string($secret_anwser);

$sql="SELECT * FROM public WHERE secret_anwser ='$secret_anwser' AND active = 'activated' AND name = '". $_SESSION['name']."'";

$result=mysql_query($sql);

// Mysql_num_row is counting table row
$count=mysql_num_rows($result);

if($count==1){

header("location:votenow.php");
}
?>

i have a table in my database with a field called 'ni'. how would i register this session instead of the current 'name' session before redirecting on the votenow.php page?
thanks in advance

A: Not sure what you mean by register, if your still using session_register() you shouldn't be. You can simply read and write the $_SESSION array directly as long as you have stated the sessions (session_start) on the page.
in responce to comment - the same why you change any variable.
$_SESSION['xxxx']='yyyyy';

A: php.net has substantial information on php and how to work with sessions


text:
Q: Can't execute shell script from python subprocess: permission denied Tried googling but couldn't find something that relates to my particular problem. I'm trying to run a shell script from python but the shell script wouldn't run because of a permission denied error. The python code I'm running is:
process = subprocess.Popen('run.sh', shell=True, stdout=subprocess.PIPE)
process.wait()
....
os.killpg(pro.pid, signal.SIGTERM)

The error I'm getting:
python RunScript.py "input"
/bin/sh: 1: run.sh: Permission denied

The contents of my shell script is:
#!/bin/sh
abspath=$(cd "$(dirname "$0")"; pwd)
CLASSPATH=$CLASSPATH:$abspath/"lib/*":$abspath/"bin"
export CLASSPATH
java -classpath $CLASSPATH my.folder.path.Class $abspath/../data/data.txt $abspath/../data/data2.txt

Thanks in advance.

A: Check your run.sh mode, if no executable flag, set it with command
chmod +x run.sh

A: its because you don't have permission to run that script. You will need to give executable permission for that script to run.

chmod a+x run.sh


text:
Q: AMPScript: Search for numbers in a string I want to loop through a comma separated list of numbers to see which is present in a string, here is a very simplified version of what I want to do:

@string: %%=v(@string)=%%

@numbers: %%=v(@numbers)=%%

@numberfound: %%=v(@numberfound)=%%

So, in this example I find the number 13 present in the string.
First of all, I'm not a programmer, so I am aware that my AMPScript is not very good, especially my IF ELSE approach as it isn't easily scalable.
Second of all, the above is just an example.
When I need to finish this project I'd have to handle much more complex strings and search for many more numbers, I would have a string and a comma separated list of numbers like this:
**SET @string = "586136#outlet;586476#outlet-dametøj;623741#forår/sommer;586802#bluser, toppe & t-shirts;"**

**SET @numbers = "601292,601443,601441,601440,601444,619575,601442,632938,629574,614516,620205,587712,587649,586476,586477,586478"**

Can anyone help me with AMPScript for a proper approach on how to loop through a list of numbers in a string like the one above?
Thank you

A: I'm not sure what you intend to use the returned numbers for, but the following code will:

*

*Build a rowset from a delimited array of numbers

*Loop through the rowset and for each number in the rowset, search for that number in the string

*Output a list of matching numbers from the string

Code
%%[

var @string, @numbers, @counter, @rows, @rowCount, @row, @numberToFind, @findNumber, @numberFound, @delimiter, @result

set @string = '586136#outlet;586476#outlet-dametøj;623741#forår/sommer;586802#bluser, toppe & t-shirts;620205#test;586477#testagain'
set @numbers = '601292,601443,601441,601440,601444,619575,601442,632938,629574,614516,620205,587712,587649,586476,586477,586478'

set @rows = BuildRowsetFromString(@numbers,',')

set @rowCount = RowCount(@rows)

for @counter = 1 to @rowCount do

    set @row = Row(@rows, @counter)

    set @numberToFind = Field(@row,1)

    set @findNumber = IndexOf(@string, @numberToFind)

    if @findNumber > 0 then
       set @numberFound = @numberToFind
       set @delimiter = '
'
    else
       set @numberFound = ''
       set @delimiter = ''
    endif

    set @result = Concat(@numberFound, @delimiter)

]%%

%%=v(@result)=%%

%%[ next ]%%

Result
620205
586476
586477


text:
Q: How to add background Image to each item in React-Native? So I'm using React Native Super Grid to display a Section grid that looks like this:
 const [items] = React.useState([
    //Plants
    {
      name: 'Orchid',
      price: '0$',
      uri:
        'https://cdn.pixabay.com/photo/2015/04/28/11/19/flower-743373_1280.jpg'
    },

and my problem is that I need the uri of each item in the items list to display as a <ImageBackground> but I'm not sure why <ImageBackground style={styles.container} source={item.uri} /> doesn't work.
For now I created a const to test the image and it looks like this:
  const images = {
    uri: 'https://cdn.pixabay.com/photo/2015/04/28/11/19/flower-743373_1280.jpg'
  }

and how it's rendered:
              <View style={[styles.itemContainer]}>
            <ImageBackground style={styles.container} source={images} />
            <Text style={styles.itemName}>{item.name}</Text>
            <Text style={styles.itemPrice}>{item.price}</Text>

But I need for each uri in const[items] to be redered just like item.name and item.price

A: put your both text in imageBackground and check See Details about ImageBackground here.
      <ImageBackground style={styles.container} source={images} >
            <Text style={styles.itemName}>{item.name}</Text>
            <Text style={styles.itemPrice}>{item.price}</Text>
     </ImageBackGroung>


text:
Q: This mail server requires authentication before sending mail from a locally hosted domain I got a Error while sending mail in asp.net c#
The error says

User not local; please try a different path. The server response was:
  This mail server requires authentication before sending mail from a
  locally hosted domain. Please reconfigure your mail client to
  authenticate before sending mail.

    string result = "";
    try
    {
        string SmtpHost = "mail.catertainment.com";
        int port = 25;

        string path = string.Format("{0}{1}", Common.ApplicationVirtualRootUrl, "admin.xml");
        XmlDocument doc = new XmlDocument();
        doc.Load(path);
        XmlNode root = doc.DocumentElement;
        XmlNodeList nodeList = root.SelectNodes("//COMMONSETTING/EMAILSETTING");
        foreach (XmlNode node in nodeList)
        {
            SmtpHost = node.SelectSingleNode("SMTP_HOST").InnerText;
            port = Convert.ToInt32(node.SelectSingleNode("SMTP_PORT").InnerText);
        }

        int i = 0;
        MailMessage mailMessage = new MailMessage();
        mailMessage.From = new MailAddress("dhasarathan@***.com", "Dhasarathan");
        for (i = 0; i < toAddresses.Length; i++)
        {
            mailMessage.To.Add(toAddresses[i]);
        }
        mailMessage.Subject = subject;
        mailMessage.Body = body;
        mailMessage.Priority = MailPriority.High;
        mailMessage.IsBodyHtml = true;
        if (ccAddresses != null)
        {
            for (i = 0; i < ccAddresses.Length; i++)
            {
                mailMessage.CC.Add(ccAddresses[i]);
            }
        }
        if (bccAddresses != null)
        {
            for (i = 0; i < bccAddresses.Length; i++)
            {
                mailMessage.Bcc.Add(bccAddresses[i]);
            }
        }
        SmtpClient smtpClient = null;
        if (!string.IsNullOrEmpty(SmtpHost) && port != 0)
            smtpClient = new SmtpClient(SmtpHost, port);
        else
            smtpClient = new SmtpClient();
        smtpClient.EnableSsl = false;
        smtpClient.Credentials = new System.Net.NetworkCredential("erp@******.com", "*****");
        smtpClient.Send(mailMessage);
        result = "Success";
    }
    catch (Exception ex)
    {
        result = "Failure due to " + ex.Message;
    }
    return result;


text:
Q: Illuminate\Foundation\Application::__construct() must be an instance of Illuminate\Http\Request, string given I am a fresh starter in laravel. On my fresh installation of laravel 5 I am getting this....any help??
Catchable fatal error: Argument 1 passed to Illuminate\Foundation\Application::__construct() must be an instance of Illuminate\Http\Request, string given, called in D:\xampp\htdocs\laravel\bootstrap\app.php on line 16 and defined in D:\xampp\htdocs\laravel\vendor\laravel\framework\src\Illuminate\Foundation\Application.php on line 108


text:
Q: Undefined Variable model in kartik mpdf - yii2 I'm trying to use kartik mpdf to print data to a pdf file. I'm facing kind of same problem as - yii2 basic printing a page in pdf.
I've tried the solution given there but still getting the error.
View file(the code for the button) -
<?= Html::a(' Print Salary Statement', ['/salary/salary/printsalarystatement'], [
            'class'=>'btn btn-primary',
            'target'=>'_blank',
            'data-toggle'=>'tooltip',
            'title'=>'Will open the generated PDF file in a new window'
        ]);?>

Controller
public function actionPrintsalarystatement() {

        $pdf = new Pdf([
        'content'=>$this->renderPartial('_printSalarystatement'), [
            'model'=> $model,
            'mode'=> Pdf::MODE_CORE,
            'format'=> Pdf::FORMAT_A4,
            'orientation'=>Pdf::ORIENT_POTRAIT,
            'destination'=> Pdf::DEST_BROWSER,
            'cssFile' => '@vendor/kartik-v/yii2-mpdf/assets/kv-mpdf-bootstrap.min.css',
            'cssInline'=> '.kv-heading-1{font-size:18px}',
            'options'=> ['title'=> 'Salary Statement'],
            'methods'=> [
                   'setHeader'=>['Generated on: '.date("r")],
                   'setFooter'=>['|page {PAGENO}|'],
                    ]
            ],

        ]);
        return $pdf->render();
    }

Present View.php -
<?= Html::a(' Print Salary Statement', ['/salary/salary/printsalarystatement?id=s_id'], [
            'class'=>'btn btn-primary',
            'target'=>'_blank',
            'data-toggle'=>'tooltip',
            'title'=>'Will open the generated PDF file in a new window'
        ]);?>

Present Controller
public function actionPrintsalarystatement($id) {

        //$model =  Salary::find()->where(['s_id' => $id]);
        $model = $this->findModel($id);
        $searchModel  = new SalarySearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
        $data         = Salary::findOne($id);
        $content = $this->renderPartial('_printSalarystatement', ['model' => $model,'dataProvider' => $dataProvider,'searchModel'  => $searchModel,'data'=> $data]);
        $pdf = new Pdf([
            'mode'=> Pdf::MODE_CORE,
            'format'=> Pdf::FORMAT_A4,
            'destination'=> Pdf::DEST_BROWSER,
            'content'     => $content,

        ]);
        return $pdf->render();
    }

A: Where are you generating the $model? You need to pass or call that into the function somehow.

A: public function actionPrintsalarystatement() {

     // you don't have the model for passing to the pdf object
     // eg:
      $model =  YourModel::find()->where(['your_column' => 'your_value']);

     $pdf = new Pdf([
      'content'=>$this->renderPartial('_printSalarystatement'), [
        'model'=> $model, // this $model is missing if you don assign a proper result to the this var like suggested above
        'mode'=> Pdf::MODE_CORE,

Based on your comment :

*

*you don'have a proper $id so you can't retrieve nothings

*you have  $model = Salary::find()->where(['s_id' => '$id']);   this is wrong you must remove  the quotes around $id this way    $model = Salary::find()->where(['s_id' => $id]);
If you have $id in the page where you call the actionPrintsalarystatement tye you could pass to the action
eg:
  /salary/salary/printsalarystatement?id=your_id

and
   public function actionPrintsalarystatement($id) {


text:
Q: OpenCV on iOS - VideoCapture properties always return 1 I have been trying to build a simple OpenCV (iOS) app that loads a video from the bundle and queries it for its frame count, duration, etc. then it will try to grab individual frames from it. Unfortunately, when I use VideoCapture class, all the properties return values of 1. Then I try to navigate to frame #100 but that also doesn't work. Am I doing this the wrong way?
cv::VideoCapture capture([[movieURL path] UTF8String]);
if (!capture.isOpened()) {
    Log(@"Could not open the video:%@", [movieURL path]);
}

double rate = capture.get(CV_CAP_PROP_FPS);

cv::Mat frame; //current video frame

//Delay between each frame in ms
//corresponds to video frame rate
int delay = 1000/rate;

long numOfFrames = static_cast<long>(capture.get(CV_CAP_PROP_FRAME_COUNT));

Log(@"Video Frame rate:%f, delay:%d, numOfFrames:%ld", rate, delay, numOfFrames);

double position = 100.0;
capture.set(CV_CAP_PROP_POS_FRAMES, position);

long frameNum = static_cast<long>(capture.get(CV_CAP_PROP_POS_MSEC));

Log(@"Moved to Frame 100. Getting frame number:%ld", frameNum);


text:
Q: jQuery on click doesn't work on iOS Devices I tried multiple solutions from here:
jQuery click not working in iOS?
or this
How to bind 'touchstart' and 'click' events but not respond to both?
but none of them are working.

This doesn't work at all. I also tried touch start event but even with this event, it doesn't work.
Any other solutions?
$("#more").on("click", function(e) {
  console.log(e.type);
  if (biography) {
    $("#biography").attr("src", "/images/arrow_down.svg");
    $("#user-biography").slideUp(500);
    $("#biography-arrow").slideUp(499);
    biography = false;
  }
  if (!more) {
    $("#user-info").fadeOut(500);
    $("#profile-info").fadeOut(500);
    $("#more-options").delay(500).slideDown(500);
    $("#more-arrow").delay(499).slideDown(500);
    more = true;
  } else {
    $("#user-info").delay(500).fadeIn(500);
    $("#profile-info").delay(500).fadeIn(500);
    $("#more-options").slideUp(500);
    $("#more-arrow").slideUp(499);
    more = false;
  }
});

EDIT:
Solution found:
window.onload = function () {
            document.getElementById("more").onclick = function () {

}
}

Inside also jQuery functions are working.


text:
Q: How to get the names of a subfolder in c# I have a folder path with me something like "c:/videos". it contains subfolders like car, bike, bus ... etc. need to get only the sub folder name and store in a string array.
And please note i don't need a full sub folder path
out needed like:- car, bike, bus
not like c:/videos/car
c:/videos/bike
c:/videos/bus

A: You can use GetDirectories method
var directories = Directory.GetDirectories(@"c:/videos");

this will give you a string array of all the subdirectories and then you can call Path.GetDirectoryName() to get the folder name
 List<string> subfolders = List<string>();
 var directories = Directory.GetDirectories(@"c:/videos");
 foreach(var directory in directories)
 {
    subfolders.Add(Path.GetDirectoryName(directory));
 }

 var result = subfolders.ToArray();

A: You have to iterate over the SubDirectories.
And replace the startpath c:\videoswith an empty string:
var rootDir = @"c:\videos";
DirectoryInfo directoryInfo = new DirectoryInfo(rootDir);

var dirs = new System.Collections.Generic.List<string>();
foreach (var dir in directoryInfo.GetDirectories())
{
    dirs.Add(dir.Name.Replace($"{rootDir}\\", ""));
}
var result = dirs.ToArray();

A: string yourPath= @"C:\videos";

// Get all subdirectories

string[] subDirs = Directory.GetDirectories(root);

foreach (string subdirectory in subdirectoryEntries)

    LoadSubDirs(subdirectory);

List<string> subfolders = List<string>();
private void LoadSubDirs(string dir)
{
  subfolders.Add(Path.GetDirectoryName(dir));

  string[] subdirectoryEntries = Directory.GetDirectories(dir);

  foreach (string subdirectory in subdirectoryEntries)

  {

    LoadSubDirs(subdirectory);

  }

}


text:
Q: Pascal's law question I apologise for the very basic question, I'm just trying to grasp the concept of Pascal's law.
I'm familiar with the fact that if pressure is applied to a confined liquid, the latter will be applied equally throughout the fluid, but what would happen if pressure is applied by two pistons at the same time rather than just one causing the second to move. If two pistons with a surface area of $10\ m^2$ applied force of $10\ N$, what would be the increase in pressure throughout the liquid? Would each piston deliver $1\ Pa$ of pressure each, with the overall increase throughout the fluid being $2\ Pa$. If this is not the case, why not?
Would one piston of $3\ m^2$ with $3\ N$ pushing on it apply less pressure than two of 2 square meters with two newtons and 1 of 1 square meter with one newton.
3 / 3 = 1 pascal change
2/2 + 1/1 = 2 pascal pressure change.
IM CONFUSED.

A: Consider any piston in your system. If the system is in equilibrium the net force on the piston must be zero, so if we apply a force $F$ to the piston and the pressure is $P$ and the piston area $A$ we must have:
$$ F = PA $$
If the system is in equilibrium this has to be obeyed by all the pistons in your system regardless of their area.


text:
Q: How do I loop back if there is an exception in java? I'm a beginner in java, and I've been wondering about this. Is there any way to make the code loop back if it caught an exception? For example, in this code, can I make it so that it loops back and makes the user put in input again if there was an error?
double divide = 0;
try {
    divide = sc.nextDouble();
    }
    catch (Exception e) {
    System.out.println("Please enter an actual number.");
    }


text:
Q: Why do I get this Fedena installation error? I wanted to install Fedena on CPanel, but when I used the command rake gems:unpack I got this error:
Fedena requires i18n gem version 0.4.0 to be installed.
Run gem install i18n -v 0.4.0
rake aborted!
ERROR: 'rake/rdoctask' is obsolete and no longer supported. Use 'rdoc/task' (available in RDoc 2.4.2+) instead.
/home/iiumprin/public_html/projectfedena-fedena-84b5ad9/Rakefile:8
(See full trace by running task with --trace)

I have the i18n gem inside my Ruby but it's still giving me this error, what should I do?
'rake gems:unpack --trace'
iiumprin@iiumprinting.com [~/public_html/projectfedena-fedena-84b5ad9]# rake gems:unpack --trace
Fedena requires i18n gem version 0.4.0 to be installed.Run gem install i18n -v 0.4.0
rake aborted!
ERROR: 'rake/rdoctask' is obsolete and no longer supported. Use 'rdoc/task' (available in RDoc 2.4.2+) instead.
/usr/lib/ruby/gems/1.8/gems/rake-10.1.0/lib/rake/rdoctask.rb:2
/usr/lib/ruby/site_ruby/1.8/rubygems/core_ext/kernel_require.rb:45:in `gem_original_require'
/usr/lib/ruby/site_ruby/1.8/rubygems/core_ext/kernel_require.rb:45:in `require'
/home/iiumprin/public_html/projectfedena-fedena-84b5ad9/Rakefile:8
/usr/lib/ruby/gems/1.8/gems/rake-10.1.0/lib/rake/rake_module.rb:25:in `load'
/usr/lib/ruby/gems/1.8/gems/rake-10.1.0/lib/rake/rake_module.rb:25:in `load_rakefile'
/usr/lib/ruby/gems/1.8/gems/rake-10.1.0/lib/rake/application.rb:637:in `raw_load_rakefile'
/usr/lib/ruby/gems/1.8/gems/rake-10.1.0/lib/rake/application.rb:94:in `load_rakefile'
/usr/lib/ruby/gems/1.8/gems/rake-10.1.0/lib/rake/application.rb:165:in `standard_exception_handling'
/usr/lib/ruby/gems/1.8/gems/rake-10.1.0/lib/rake/application.rb:93:in `load_rakefile'
/usr/lib/ruby/gems/1.8/gems/rake-10.1.0/lib/rake/application.rb:77:in `run'
/usr/lib/ruby/gems/1.8/gems/rake-10.1.0/lib/rake/application.rb:165:in `standard_exception_handling'
/usr/lib/ruby/gems/1.8/gems/rake-10.1.0/lib/rake/application.rb:75:in `run'
/usr/lib/ruby/gems/1.8/gems/rake-10.1.0/bin/rake:33
/usr/bin/rake:23:in `load'
/usr/bin/rake:23


text:
Q: How can I monitor the length of the accept queue? I have a hypothesis: sometimes TCP connections arrive faster than my server can accept() them. They queue up until the queue overflows and then there are problems.
How can I confirm this is happening?
Can I monitor the length of the accept queue or the number of overflows? Is there a counter exposed somewhere?

A: Sysdig will provide some of this information at the end of each accept syscall, as the queuelen argument. It also shows the length of the queue as queuemax.
7598971 21:05:30.322229280 1 gunicorn (6451) < accept fd=13(<4t>127.0.0.1:45882->127.0.0.1:8003) tuple=127.0.0.1:45882->127.0.0.1:8003 queuepct=0 queuelen=0 queuemax=10

As far as I'm aware, it provides no mechanism to know exactly when or how many times the queue has overflowed. And it would be cumbersome to integrate this with periodic monitoring by collectd or similar.

A: What you are looking for is the entry in output of sysctl -a command as such:
net.ipv4.tcp_max_syn_backlog = 4096

In the above example case, the backlog of SYN state connections is at most 4096. You can increase that based on how much RAM is in your server. I consider 32K worth of backlog to be a good start for tuning of heavily loaded web servers.
Also make sure the following is NOT set to 1:
net.ipv4.tcp_abort_on_overflow = 0

Otherwise it will definitely drop packets if there is a backlog overflow.
You can easily check values with sysctl -a | grep backlog or sysctl -a | grep overflow.
Additionally, you can find "dropped" label under the
ifconfig -a

command's output. That shows how many packets were dropped for each interface along with other data and errors etc.
For logging dropped packets there is a [paywalled] article for RHEL 7: https://access.redhat.com/solutions/1191593
For further research you may read http://veithen.io/2014/01/01/how-tcp-backlog-works-in-linux.html
It states here, as per Steven's Book Illustrated TCP/IP:

The queue limit applies to the sum of […] the number of entries on the incomplete connection queue […] and […] the number of entries on the completed connection queue […]."

It also states that:

The completed connection queue is almost always empty because when an entry is placed on this queue, the server's call to accept returns, and the server takes the completed connection off the queue.

The accept queue may hence seem completely empty and you will have to tune your Web server to accept the connections placed on the "total aggregate" queue, faster.

A: To check if your queue is overflowing use either netstat or nstat
[centos ~]$ nstat -az | grep -i listen
TcpExtListenOverflows           3518352            0.0
TcpExtListenDrops               3518388            0.0
TcpExtTCPFastOpenListenOverflow 0  0.0

[centos ~]$ netstat -s | grep -i LISTEN
    3518352 times the listen queue of a socket overflowed
    3518388 SYNs to LISTEN sockets dropped

Reference:
https://perfchron.com/2015/12/26/investigating-linux-network-issues-with-netstat-and-nstat/
To monitor your queue sizes, use the ss command and look for SYN-RECV sockets.
$ ss -n state syn-recv sport = :80 | wc -l
119

Reference:
https://blog.cloudflare.com/syn-packet-handling-in-the-wild/


text:
Q: Invoke a class dynamically let's assume that I have two identical services from two providers and I want to write a code that calls either one of them depending on the client request.
To be more clear, I have provider A and provider B. A client will submit a request for either A or B, so I have to invoke their classes to handle the request.
I created the provider interface
interface IProviderInterface
{
    string GetRedirectUrl();
    string GetStatus();
}

then each provider class has implemented the interface
public class ProviderA: IProviderInterface
{
    public ProviderA()
    {
    }

    public string GetRedirectUrl()
    {
        return "URL for provider A";
    }

    public string GetStatus()
    {
        return "Check status with provider A API";
    }
}

Now in the provider manager class I used the switch statement to invoke the desired provider class.
public class ProvidersManager
{
    IProviderInterface ProviderObj;

    public ProvidersManager(string ProviderName)
    {
        switch (ProviderName)
        {
            case "A":
                ProviderObj = new ProviderA();
                break;
            case "B":
                ProviderObj = new ProviderB();
                break;
        }
    }

    public string GetRedirectUrl()
    {
        return  ProviderObj.GetRedirectUrl();
    }

    public string GetStatus()
    {
        return ProviderObj.GetStatus();
    }
}

But this method requires me to edit the provider manager class each time I add a new provider.
I was wondering if there was a way to invoke the desired class with a more dynamic way without altering the code.

A: Use the DI to avoid the changes in ProvidersManager.
Or you can just refactor this code and create a factory which can take the responsibility to provide the object of provide type for supplied provider name.

A: There are some alternatives you could use to accomplish this:
Generic type
public class ProvidersManager<TProvider> where TProvider : IProviderInterface
{
    public ProvidersManager() =>
       ProviderObj = Activator.CreateInstance<TProvider>();
}

// eg: new ProvidersManager<ProviderA>();

Using type (loaded before somewhere else)
public ProvidersManager(Type providerImplementationType) =>
    ProviderObj = (IProviderInterface)Activator.CreateInstance(myType);

// eg: new ProvidersManager(typeof(ProviderA));

Using type full name
public ProvidersManager(string providerFullName) =>
    ProviderObj = (IProviderInterface)Activator.CreateInstance(Type.Load(providerFullName));

// eg: new ProvidersManager("MyApplication.Common.ProviderA");

A: ProviderManager.cs
internal static class ProviderManager
{
    private static readonly Dictionary<string, BaseProvider> _providers = new Dictionary<string, BaseProvider>();

    public static void Register(string name, BaseProvider provider) => _providers.Add(name, provider);
    public static string GetRedirectUrl(string name) => _providers[name].GetRedirectUrl();
    public static string GetStatus(string name) => _providers[name].GetStatus();
}

BaseProvider.cs
internal abstract class BaseProvider
{
    private BaseProvider(string name) => ProviderManager.Register(name, this);
    public abstract string GetRedirectUrl();
    public abstract string GetStatus();
}

ProviderA.cs
internal class ProviderA : BaseProvider
{
    private readonly string _redirectUrl;
    private readonly string _status;

    public ProviderA(string redirectUrl, string status) : base("A")
    {
        _redirectUrl = redirectUrl
        _status = status;
    }

    public string GetRedirectUrl() => _redirectUrl;
    public string GetStatus() => _status;
}

Usage
internal class Program
{
    public static void Main(string[] args)
    {
        ProviderA providerA = new ProviderA("http://stackoverflow.com", "active");
        string url = ProviderManager.GetRedirectUrl("A");
    }
}

Hope this helps.

A: Change the manager constructor which takes IProviderInterface as a parameter.
public class ProvidersManager
{
    IProviderInterface ProviderObj;

    public ProvidersManager(IProviderInterface providerObj)
    {
        ProviderObj = providerObj;
    }

    public string GetRedirectUrl()
    {
        return  ProviderObj.GetRedirectUrl();
    }

    public string GetStatus()
    {
        return ProviderObj.GetStatus();
    }
}

Now, in the calling client pass the instance.
var providerManager = new ProvidersManager(new ProviderA());
var anotherProviderManager = new ProvidersManager(new ProviderB());

or go for DI. Also, when using DI check Service lifetimes
public void ConfigureServices(IServiceCollection services)
{
    services.AddScoped<IProviderInterface, ProviderA>();
}

A: If you really don't want to change code as you add new providers then you an use reflation
Type providerType = Type.GetType("Provider" + ProviderName);
ProviderObj = (IProviderInterface)Activator.CreateInstance(providerType);


text:
Q: Unable to resize a button using java.awt this is my code:
import java.applet.Applet;
import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.Panel;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class Maapp extends Applet implements ActionListener
{
    private int flag=0;
    Panel p1=new Panel();
    Panel p2=new Panel();
    Button[] arr=new Button[12];

    TextField textf=new TextField("",25);
    public void init()
    {
        this.setLayout(new BorderLayout());
        this.p2.setBackground(Color.DARK_GRAY);
        this.p2.setLayout(new GridLayout(2,30));
        textf.setBackground(Color.BLACK);
        textf.setForeground(Color.YELLOW);
        this.p1.setLayout(new GridLayout(4,10));
        p2.add(textf);
        for(int i=0; i<10 ;i++)
        {

            arr[i]=new Button(""+i);
            arr[i].setForeground(Color.WHITE);
            arr[i].setBackground(Color.DARK_GRAY);
            p1.add(arr[i]);
            this.arr[i].addActionListener(this);
        }
            arr[10]=new Button("=");
            p1.add(arr[10]);
            arr[10].setPreferredSize(new Dimension(20,40));
            this.arr[10].addActionListener(this);

        this.add(p2,BorderLayout.NORTH);
        this.add(p1,BorderLayout.CENTER);
    }

    public void actionPerformed(ActionEvent arg0)
    {

        for(int i=0;i<10;i++)
        {
            if(arg0.getSource()==arr[i])
            {
                this.textf.setText(this.textf.getText()+i);
            }

        }
    }
}

I want to resize one of the buttons.
I tried to write:
arr[10].setPreferredSize(new Dimension(20,40));

it did not work.
i tried to write:
arr[10].resize(10,20);

it did not work.
so how can i resize button arr[10]?

A: Try setting the min and max size of the button.  The layout manager you are using might not be able to honor the preferred size.

A: For your button panel, you specified GridLayout, which ignores the preferred size. As an alternative, you can use GridBagLayout or MigLayout, which can span columns.
Addendum: Note that you can indicate an arbitrary number of rows or columns in GridLayout. In your example, this would signify three columns with as many rows as required:
this.p1.setLayout(new GridLayout(0, 3));


text:
Q: how to implement a user space multi-thread vm e.g. Erlang runtime How does the Erlang runtime implement a user-space multi-threaded mechanism on UNIX-like systems?
Is it implemented using something like getcontext(2) or longjump(3)?
Any related documentation would be much appreciated.

A: Each Erlang process is just a struct with a heap and a stack in it. So switching process is just a matter of using another struct in an queue. I think this paper describes it nicely.


text:
Q: Classic ASP: General access denied error I have a system, written in Classic ASP, which reads data from a form and updates AD. I am, however, getting the following error when I try and update my own information:
Active Directory error '80070005'
General access denied error
/activedirectory/index.asp, line 99
Line 99 is
objUser.SetInfo

and the entire code block is as follows:
 <%
 uname = request.querystring("account_name")
 ADUser = "LDAP://OU=Staff,OU=Users,DC=example,DC=internal"
 Set objCon = Server.CreateObject("ADODB.Connection")
 objCon.provider ="ADsDSOObject"
 objCon.Properties("User ID") = "NETWORK\example"
 objCon.Properties("Password") = "PaSsWoRd"
 objCon.Properties("Encrypt Password") = TRUE
 objCon.open "Active Directory Provider"
 Set objCom = CreateObject("ADODB.Command")
 Set objCom.ActiveConnection = objCon
 objCom.CommandText ="select distinguishedName FROM '"+ ADUser +"' where sAMAccountname='"& uname &"'"
 Set objRS = objCom.Execute
  distinguishedName = objRS.Fields("distinguishedName")
 'Const ADS_PROPERTY_UPDATE = 2
 Set objUser = GetObject _
 ("LDAP://" & distinguishedName)
 objUser.Put "givenName", firstname
 objUser.Put "mail", email
 objUser.Put "sn", lastname
 objUser.Put "mobile", mobile
 objUser.Put "description", description
 objUser.Put "telephoneNumber", telephonenumber
 objUser.Put "department", department
 objUser.Put "title", title
 objUser.Put "company", company
 objUser.SetInfo
 Response.Write("User data for "& uname &" has been modified. Click here to go home")
%>

I have gone through the troubleshooting steps that I can think of, ensuring the password I am using is correct, making sure the account has delegated write permissions, etc. Some pointers would be much appreciated


text:
Q: Computer starts operating slow after crashing due to power outage. I need help debugging Summary:
After an unscheduled restart my computer becomes an order of magnitude slower. If manually restarted afterwards, the computer reverts back to its expected performance.
Detailed description:
While the computer is running normally, this is the score it gets while running a standard geekbench score: https://browser.geekbench.com/v5/cpu/13619045
If the computer crashes, or loses power due to an electricity outage, and has to be booted normally back again it becomes super slow. If I run geeksbench again this happens: https://browser.geekbench.com/v5/cpu/13618924 (an order of magnitude slower)
I have no ideia how to debug this problem. Can somebody suggest a plan of action to debug the situation?
Things I have tried:

*

*updating bios,

*switching processor

*trying a different graphics card

*using only on RAM stick

Specs:

*

*X399 GAMING PRO CARBON AC (MS-7B09)

*AMD Ryzen Threadripper 2970WX 24-Core Processor

*32Gb Kingston DDR4 2400mhz (2x16Gb)

*NIVIDA 1080 gtx

EDIT:
Thanks to someone's answer I was able to extract logs regarding a good boot and a bad boot. Unfortunately I'm not able to find anything weird myself. Here they are:
Bad boot: https://privatebin.net/?b17e26b3c0f22e17#2BAJAZPkriuv1w2qZ1YXq1QkwkhCjpTafjjdHs8TcEko
Good boot: https://privatebin.net/?26f18a19ce07b211#37gdQV998RX8tvtUyqHp9RmcpuC92gypZvc5mPQ3gzmY
I removed timestamps to be able to compare them using: colordiff -y -W 256 broken.txt working.txt

A: Compare the startup logs of the two types of reboots. Use sudo journalctl --list-boots | tee boots.txt (very slow the first time you run it - journalctl has to index all the logs) to get the index number and sudo journalctl -b # will let you pick a boot from the list (# values are 0:current boot, -1:previous boot, -2:the one before that,...).
There will be a difference!


text:
Q: how to call a matlab function with arguments and capture output in java? I would like to know how to call and execute a matlab function with parameters  using java and capture the output in java.

A: I see different options.

*

*Create a JAR from your code, using the Builder JA.

*Use matlabcontrol, which is a 3rd party automation server:

*Use the MatlabControl.java, which allows to run matlab code from java running within the matlab JRE. enter link description here

*While the Builder JA is expensive and the options 2 and 3 might get you in truble with future matlab versions, using the matlab CLI is another possibility which probably does not cause any maintenance. For parameters and return, I would use a file. The main disadvantage is a new matlab session starting for each call, which needs some time.


text:
Q: Is it Possible to Integrate Third Party Sellers in WooCommerce Well the Title says all, I am making a woo-commerce website for selling products as in India it is banned to stock someone else products and sell them on own website, So I want to make it like when a user orders a product an notification to me and the real seller of the product is sent.

A: Go to your WordPress admin panel > WooCommerce > Settings > Emails > New Order
Make sure "Enable this email notification" is checked.
In Recipient(s), type in the email address that you want to receive order notifications.


text:
Q: Handling Kernel start. What is a full initialization stack and what place the Autoload has there? According to: tutorial/WolframSystemSessions

Initialization
On startup, the Wolfram Language kernel does the following:

*

*Performs license management operations.

*Runs Wolfram Language commands specified in any -run options passed to the kernel executable.

*Runs the Wolfram Language commands in the systemwide initialization file $BaseDirectory/Kernel/init.m.

*Runs the Wolfram Language commands in the user-specific initialization file $UserBaseDirectory/Kernel/init.m.

*Loads init.m and Kernel/init.m files in Autoload directories.

*Begins running the main loop.

So I'd say that packages in Autoload have a freedom to do everything since everything should be already loaded. Yet this example fails:
dir = FileNameJoin[{$UserBaseDirectory, "Autoload", "Fetch", "Kernel"}];

CreateDirectory[dir, CreateIntermediateDirectories -> True]

SetDirectory @ dir;

Export[
 "init.m",
 "Print @ StringTake[URLFetch[\"www.wolfram.com\"], 300]; ",
 "Text"]

Now quit the Kernel and evaluate something. I only get messages:

URLFetch::invhttp: Couldn't resolve proxy name.
StringTake[$Failed, 300]
Throw::nocatch: Uncaught Throw[False] returned to top level.
Throw::nocatch: Uncaught Throw[False] returned to top level.
Throw::nocatch: Uncaught Throw[False] returned to top level.
General::stop: Further output of Throw::nocatch
       will be suppressed during this calculation.
Break::nofwd: No enclosing For, While, or Do found for Break[].

While normally this procedure works StringTake[URLFetch["www.wolfram.com"], 300].
Question What's the problem? What more do we need to know about the Initialization stack? Are there any workarounds?
Currently I'm just setting procedure via ScheduledTask to fire 2 seconds later. But that's just silly.
This is not a question about URLFetch (yet good to know this specific problem) but about things I have to know to not be surprised next time.

A: Update
Leaving my original answer below for historical purposes, however it only applies up until version 11.1.1.
As of version 11.2.0, the kernel startup initialization has been overhauled and this example (as well as others) now works correctly: placing the URLFetch call in init.m does result in an output like
<!doctype html>
<html lang="en" class="homepage">
<head>

<!-- begin framework head en -->

    <meta http-equiv="x-ua-compatible" content="ie=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta charset="utf-8">
    <meta name="msapplication-config" content="/b

This improvement was motivated in part by the new Persistence & Initialization framework, and I recommend Roman Maeder's presentation from the 2017 Wolfram Technology Conference.

To make my comment into an answer,

The basic problem, which is not so easy to fix, is that the kernel
  initialization code has protection against aborts. Since Throw/Catch
  are implemented internally using this (C code level) abort machinery,
  they are not functional during initialization, so running any code
  using them is problematic.

The URLFetch implementation does depend on Catch working correctly, as can be seen from
TracePrint[URLFetch["www.wolfram.com"], _Catch]

Some related questions are the following: (1), (2), (3), (4).


text:
Q: Get C++ runtime type during debugging? Curious if anyone has any ideas on this one; working on a game engine that implements a tree of GameObject's. Various specific game objects inherit from that type ( BouncingBall, StatScreen, or whatever).
class GameObject {
    public:
    vector<Component *> Components;
    vector<GameObject *> Children;
    GameObject *Parent;
};

So at runtime, the game will have a huge tree of these, all of different types. Unfortunately the objects in the Children vectors are all reported as "GameObject *" in the debugger making it really hard to tell what's what.
Best solution I've come up with is to store the type as a member variable on construction:
class GameObject {
    public:
    // ...
    const char *Type;

    // Saves current class name as Type.
    template<class T>
    void StoreTypeName( T *thisPointer ) {
        this->Type = typeid( *thisPointer ).name();
    }
};

But then in every object constructor I have to remember to call StoreTypeName:
class FancyBlinkingObject : public GameObject {
    public:
    FancyBlinkingObject() {
        StoreTypeName( this );
    }
};

Any other possible tricks to just do this automatically? Either on the debugger end (Visual Studio 2012) or in the code?
I thought of maybe some kind of central dynamic cast testing function:
if ( dynamic_cast<FancyBlinkingObject *>( basePointer ) ) {
    return "FancyBlinkingObject";
}
if ( dynamic_cast<UglyBlueObject *>( basePointer ) ) {
    return "UglyBlueObject";
}

But I can't think of a way to do it without me having to manually maintain the list of if's. Want something totally automatic if possible. :)

A: Per David Rodriguez's comment - making GameObject polymorphic (in my case by making the destructor virtual) changed its classification in the debugger and showed a vptr to the runtime type info, which did the trick.


text:
Q: php handler not responding when using mutliple form with same handler I use the following code to output a table with FAQ.
// get faq
global $wpdb;
$faq = $wpdb->get_results("SELECT ID, q, a, cat, quality, active FROM ce_faq");

foreach ($faq as $i) {
    echo
    '

        ID.'" class="question" href="#">'.$i->q.'

ID.'" class="answer">

'.$i->a.'

        <form method="POST"  id="form'.$i->ID.'">
        <input type="hidden" value="'.$i->ID.'" name="faq_id"></input>
        <input type="hidden" name="action" value="ce_faq_quality"/>'
        .wp_nonce_field( 'name_of_my_action','name_of_nonce_field' ).
        '
 Was this answer usefull? <input type="radio" name="quality" value="1" class="quality_radio"> yes </input><input type="radio" name="quality" value="-1" class="quality_radio"> No </input>

        </form>

';

}

echo '
feedback
';

I use jQuery().slidetoggle to toggle the answers when somebody clicks on the question. I want  to enable end-users to give feedback on the questions with a simple yes or no question. The form should be submitted when one of the radio buttons is selected. the trigger jQuery('.quality_radio').click is working and also the formid is correctly fetched.
problem: The function ce_faq_quality(); is unfortunately not responding, when i use console.log(qu) i get for example 'faq_id=1&action=ce_faq_quality&name_of_nonce_field=7dd1d930af&_wp_http_referer=%2Ffaq%2F&quality=1', which seems to be correct to me. I also get the alert 'this is working'. The php handler doesn't seem to work however. the div feedback turns 0 (instead of 'success php function') and also the query isn't performed (while I know it works for 120%).  I am at a loss here...
solved: the handler wasn't accessible from the page i was working on...
jQuery('.question').click(
    function(){
       var id = this.id;

        jQuery('#a'+id).slideToggle(350);
    });

jQuery('.quality_radio').click(

    function(){

       var formid = jQuery(this).closest('form').attr('id');
       var formid = '#'+formid;

      jQuery(formid).submit(ajaxSubmit(formid));
      });

        function ajaxSubmit(formid){

            var qu = jQuery(formid).serialize();
            console.log(qu);
        jQuery.ajax({
        type:"POST",
        url: "/wp-admin/admin-ajax.php",
        data: qu,
        success:function(data){
        jQuery("#feedback").html(data);
        alert('this is working');
        }
        });

        return false;
            }

This is the php function i use to process the form.
add_action('wp_ajax_ce_faq_quality', 'ce_faq_quality');
add_action('wp_ajax_nopriv_ce_faq_quality', 'ce_faq_quality');

function ce_faq_quality(){

    $quality = 1; //$_POST['quality'];
    $faq_id =  1; //$_POST['faq_id'];

    global $wpdb;
    $wpdb->query($wpdb->prepare("UPDATE `ce_faq` SET `quality`= `quality` + $quality WHERE id = $faq_id"));

    echo 'succes php function ';
    die();
}

A: Your formid variable falls out of scope in the ajaxSubmit function.  You should instead try:
jQuery('.quality_radio').click(

    function() {

        var formid = jQuery(this).closest('form').attr('id')
        var formid = '#' + formid;

        jQuery(formid).submit(ajaxSubmit(formid));
});

function ajaxSubmit(formId) {

    var qu = jQuery(formid).serialize();

    jQuery.ajax({
        type: "POST",
        url: "/wp-admin/admin-ajax.php",
        data: qu,
        success: function(data) {
            jQuery("#feedback").html(data);
        }
    });

    return false;
}

So that you pass the formid to the ajaxSubmit function.


text:
Q: LESSCSS: Assign a value to a property taken from another one's In some cases is common to use same values in different properties, for example (is just an example to show purpose) the following nested rule:
.button-link
{
   height:40px;

   a
   {
     line-height:40px;
   }
}

The idea is that to vertically center button text line-height and height should be equal.
Is there a way in LESS to "assign a value taken from a diffent property"?
I know that I should use a LESS @variable but in this case is not the same thing and need extra code. Instead should very interesting and useful if I should edit only button's height and then LESS will replaced the same value to line-height
UPDATE:
Another example could be the following:
.button-link
{
   color:white;
   background:black;

   &:hover
   {
     color:black;
     background:white;
   }
}

In which "hover" status should invert color and background-color comparing to default state.

A: This is possible starting with v3 of LESS! Here is the documentation on it.
The example use case they provide ends up with the background-color getting the same value as the color property when compiled:
.widget {
  color: #efefef;
  background-color: $color;
}

A: You can´t :(. What i usually do is:
@buttom-height = 100px;
@a-link-height: @buttom-height;

and use that variables in your less declarations. Its a dummy example, i know, but imagine calculated data values from other variables or complex dependencies, proportional paddings/margins... that´s the way i learnt from Bootstrap LESS code.


text:
Q: error while using python 3.6 and opencv-python cv2 Error in using python open cv to initialize the camera in a face recognition task
import cv2
camera = cv2.VideoCapture(1)
camera.grab()
ret, frame = camera.retrieve()
cv2.namedWindow('frame')

.
OpenCV: out device of bound (0-0): 1
OpenCV: camera failed to properly initialize!

A: The problem is that I'm not using an extra webcam and my pc has just one camera, so this line should be:
    camera = cv2.VideoCapture(0)


text:
Q: Do joins using search:search API How one should do join queries when using search:search API?
I see in Inside MarkLogic Server that one can use a 'Shotgun OR' (scatter query), but it doesn't use 'search:search'. In a message at 'MarkLogic Dev General' mail list I found that in theory this could be done by  a search constraint, but I couldn't understand how exactly it should work.
My use case is the following:

*

*I use MarkLogic Java client API to construct my queries. I want to avoid using xqy extensions if possible.

*I have two kind of entities (e.g. Books and Authors) and I may want to do queries like: give me the Books published in 1980 that were written by Brazilian Authors. I.e. I want to filter on both entities and join the results, without denormalizing the data.

A: It is correct that the Search API does not provide a declarative interface for shotgun OR.
If you're using MarkLogic 9 (especially with the performance enhancements in the latest release), you may find that the Optic API meets your requirements:
http://docs.marklogic.com/guide/java/OpticJava
Instead of requiring a shotgun OR, the Java API provides a fluent builder for Optic queries with direct joins between entities.
If you're on an earlier release of MarkLogic or if Optic doesn't fit your requirements for some reason, you can do a shotgun OR query entirely in Java by using a values query to retrieve the names of all Brazilian authors matched by a query in the first request:
http://docs.marklogic.com/guide/java/searches#id_83836
Then, use the retrieved values to construct into a query to retrieve the books written by those authors in a second request:
http://docs.marklogic.com/guide/java/searches#id_70572
That could be as simple as constructing an array of name values and passing the array into a single range query:
http://docs.marklogic.com/javadoc/client/com/marklogic/client/query/StructuredQueryBuilder.html#range-com.marklogic.client.query.StructuredQueryBuilder.RangeIndex-java.lang.String-java.lang.String:A-com.marklogic.client.query.StructuredQueryBuilder.Operator-java.lang.Object...-
The cost of this Java-based approach to a shotgun OR query consists of two network roundtrips:  one to get the list of names from the server to the Java client and one to get the documents.
For better performance with a shotgun OR, create an XQuery or Server Side JavaScript (SJS) module on the MarkLogic enode that takes the query criteria and executes the shotgun OR query followed by the document query.  You can then execute the enode module with an invoke:
http://docs.marklogic.com/guide/java/resourceservices#id_84134
or with a resource service extension:
http://docs.marklogic.com/guide/java/resourceservices#id_27702
Hoping that helps,


text:
Q: React firebase getting data from react route v params How to get data from firebase. im using react router v4. In the details page . "this.props.match.params.movie" this is diplaying only the movie name. I wanna show other details also from the databse. need help
componentDidMount() {
    this.firebaseRef = firebase.database().ref("movies");
    this.firebaseRef.on('value', function (snapshot) {
        var movies = [];
        snapshot.forEach(function (data) {
            var movie = data.val();
            movie['.id'] = data.id;
            movies.push(movie);
        });
        this.setState({ movies });
    }.bind(this));
}

Index.js page
<Switch>
   <Route exact path="/" component={App} />
    <Route path="/create-movie" component={CreateMovie}/>
    <Route path="/details/:movie" component={Details} />
  </Switch>

Movie list page

  <Link to={"/details/" + movie.name}>

  </Link>

A: In details page, query Firebase again:
componentDidMount() {
  this.firebaseRef = firebase.database().ref("movies");
  this.firebaseRef.on('value', (snapshot) => {
    snapshot.forEach((data) => {
      var movie = data.val();
      if (movie.name === this.props.match.params.movie) {
        this.setState({ movie });
      }
    });
  });
}


text:
Q: How to introduce custom variable(s) inside driver.execute_script()? For a web driver we can execute JavaScript code which includes custom variable like this:
driver.execute_script("alert('%s')" % variable) # an example introducing variable in alert()

But what to do if I need to modify the content of the variable where I have to write the variable inside the script?
More specifically, I am facing the following problem:
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")

Here in this code, I have to write the document.body.scrollHeight inside the script. But I want to add a random factor [0-1] to be multiplied with document.body.scrollHeight such that the scrolling doesn't seem to be automated. For this reason, I tried the following:
import numpy as np
factor = float(np.random.uniform(0, 1))
driver.execute_script("window.scrollTo(0, %s);" % str(np.int(float(document.body.scrollHeight) * factor)))

But this doesn't work. As document.body.scrollHeight is outside, hence, the program doesn't find document. So I want to introduce a custom variable factor inside the script. How to do that?

A: See the selenium docs here.
To pass variables into the execute script you use comma.
This bit:

execute_script(script, *args)¶
Synchronously Executes JavaScript in
the current window/frame.
Args:  script: The JavaScript to execute.
*args: Any applicable arguments for your JavaScript. Usage:    driver.execute_script('return document.title;')

When you accessing variables you then use arguments[x] to access (indexed at 0).
A good example and a common one you'll find is: execute_script("arguments[0].click()" , element).  You can see script then comma then the element you want to click. But you can pass in as many as you like.
Onto your problem.
There are a couple of ways to get the scroll height.
You can get the body scroll height from selenium or from js.
Doing it in js (so it matches your current approach) you can do it in 2 calls.
BodyScrollHeight = driver.execute_script("return document.body.scrollHeight;")

factor = float(np.random.uniform(0, 1))
driver.execute_script("window.scrollTo(0, %s);" % str(np.int(float(BodyScrollHeight) * factor)))

or - using the comma approach.
BodyScrollHeight = 100 #calculate your factor here
driver.execute_script("window.scrollTo(0, arguments[0]);", BodyScrollHeight)

I've not had chance to run this but if it doesn't work let me know and I'll look again.


text:
Q: How to import recursive-readdir in typescript I am a little bit struggling with import and usage of npm module recursive-readdir in a typescript program.
After npm install recursive-readdir @types/recursive-readdir (@types/recursive-readdir@2.2.0, recursive-readdir@2.2.2) the following snippet works:
import * as RecursiveReaddir from 'recursive-readdir';

async function test () {
    const files = await RecursiveReaddir.default('/tmp');
    ...
}

The file node_modules/@types/recursive-readdir/index.d.ts contains:
...
import * as fs from "fs";
declare namespace RecursiveReaddir {
    type IgnoreFunction = (file: string, stats: fs.Stats) => boolean;
    type Ignores = ReadonlyArray<string|IgnoreFunction>;
    type Callback = (error: Error, files: string[]) => void;
    interface readDir {
        (path: string, ignores?: Ignores): Promise<string[]>;
        (path: string, callback: Callback): void;
        (path: string, ignores: Ignores, callback: Callback): void;
    }
}

declare var recursiveReadDir: RecursiveReaddir.readDir;
export = recursiveReadDir;

My questions:

*

*Where is the function RecursiveReaddir.default(...) coming from?

*Is there a more readable and intuitive import and usage possible?
In example ìmport { readDir } from 'recursive-readdir'; or something like that?

Testprogram is available under:
https://github.com/ManfredSteiner/stackovf_65391266

A: I got the error in your code.
(node:7541) UnhandledPromiseRejectionWarning: TypeError: RecursiveReaddir.default is not a function
So, I implemented it to work by referring to the existing test codes. See below

*

*npm/recursive-readdir

*github/recursive-readdir
test.ts
// ./test.ts
import recursive from 'recursive-readdir';

async function test () {
    const files = await recursive(__dirname);
    console.log(files);
}

test()

commands
# node v12.13.1
# npm v6.11.3
npm install @types/recursive-readdir && \
npm install recursive-readdir

+ @types/recursive-readdir@2.2.0
+ recursive-readdir@2.2.2

tsc && node ./build/test.js

results
# Success
[ '/Users/kmk/Project/src/github.com/myeongkil/tmp/stackoverflow/recursive-readdir/build/test.js' ]


text:
Q: How do I create a dropdown list for a column of constantly-changing values in Excel 2010? I have an excel spreadsheet with a column for years, with a header:
Years
1993
1993
1994
1994
1994
...
2011
2011

There are duplicate values for the years, and additional rows will be added over time.
I have another cell that needs to show a dropdown list for the years, but only the unique years. I've tried using the data validation feature in Excel 2011, but it has 2 issues:

*

*It displays the duplicate years.

*I tell it to use the entire column, and it includes the empty cells in the dropdown list.

How do I get a dropdown list of years that will display only unique values, while automatically updating as additional rows are added?
Edit: a little more information. The dropdown list is used in a separate sheet to display calculated data, like an Access form. The user can pick a year range and the data will update accordingly. The original sheet is just a list of all the data.

A: For this kind of validations, I use VBA + one dirty trick:
First, enter VBA editor with Alt+F11
Then, I put my "Dynamic List Validation Code" (tm) :) in the respective worksheet.
Private Sub Worksheet_SelectionChange(ByVal rTarget As Excel.Range)

On Error GoTo noVal

With rTarget.Validation
    .Modify xlValidateList, xlValidAlertStop, xlBetween, Excel.Evaluate(.ErrorTitle)
End With

noVal:

End Sub

This code updates the cell validation list with the list generated by the formula entered in Data->Validation->Error Message->Title. This way, each cell with list validation
can have its own formula.
Then, I add a module (Insert->Module) and then put this code in the new module:
Function GenDynList(rRng As Range)

sRet = ""

For Each rCell In rRng
    If Not IsEmpty(rCell.Value) And InStr(sRet, rCell.Value) = 0 Then
        sRet = sRet & "," & rCell.Value
    End If
Next

GenDynList = Mid(sRet, 2)

End Function

This function returns all the cells in the range without blanks or repetitions.
Then, in each cell with list validation, I add GenDynList(range) in the
Error Message title of data validation.

A: Messy. There's no built-in way to do that that automatically updates. It would be simpler to just create a separate list with all the possible years that you could be interested in rather than trying to limit it to those in your data set.

A: Add a Pivot Table from the data on another sheet. Use Years as rows, the rest of the table is irrelevant. Sort and filter the rows as required (eg explicitly filter OUT "[blank]"). Make the cells where the row labels are into the target of your data validation.
Use an expanding named range to always use all the new labels:
http://www.ozgrid.com/Excel/DynamicRanges.htm
Repeat for other columns such as country, state etc. If you base all the pivots off the same data range they will all refresh together when you refresh any one of them. Your process will now be: add new data, refresh pivots, use updated data validation.
Further thoughts: Using a table for the source data will make it easy to update the Pivot Tables since they will always use the whole table. Alternatively use an expanding named range as the data source to avoid issues when you add more rows.
Note that you can use a range from a different worksheet as a source for data validation if you do this by defining a named range. You can't use a normal range explicitly referring to another sheet.