text:
Q: Debugging an API using AFNetworking 2.0 I'm using php to build a web API for an iOS app. I'm not very good at it. As I go, I like to echo stuff to help me debug.
If I attempt to access one such API using AFNetworking 2.0, how can I log the echo string? Is there some property of the AFHTTPSessionManager POST response I can access? None of the below is useful:
[self POST:@""
    parameters:params
       success:^(NSURLSessionDataTask *task, id responseObject) {
           NSLog(@"success");
       }
       failure:^(NSURLSessionDataTask *task, NSError *error) {
           NSLog(@"%@", [error userInfo]);
           NSLog(@"%@", task.response);
       }
];

Note that this is a json API so echo causes the failure callback to run, not the success.

A: Log the response from the server:
NSLog(@"%@",responseObject);

A: change your code to this
   [self POST:@""
parameters:params
   success:^(NSURLSessionDataTask *task, id responseObject) {
       NSLog(@"success");

      //log the response string here
      NSLog(@"%@",responseObject);

   }
   failure:^(NSURLSessionDataTask *task, NSError *error) {
       NSLog(@"%@", [error userInfo]);
       NSLog(@"%@", task.response);
   }
];


text:
Q: Seeking park land cover in UK? I would like to mapping like in this link
http://www.geocomputation.org/1998/78/gc78_07.jpg
However, I could not find the park data, so do anyone know where can I find these kind of data.

A: The park data seems to be from OpenStreetMap licensed under the Open Data Commons Open Database License (ODbL).
You can use Overpass Turbo with this query to extract all parks in Cardiff and use them in your GIS application.

redpajama_set_name: RedPajamaStackExchange


text:
Q: how backbone fetch construct the model or collection? In many backbone examples I saw code with mymodel.fetch() or mycollection.fetch() and most of the codes didn't use the success callback in order to construct the model / collection from  the response. I am filling like I am missing something about how fetch is creating model instance from the result. How does this happen?
EDIT

*

*Thare are cases where the model is not the same structure as the returned json and there is a need to map model attributes. For example, the model attributes are 'name' and 'age' but the returned json is: {n_name:'dan', props: {age: 12, address: 'this data is not relevant'}}. There is a need to map the returned json to the model. How can I do it? Is such cases force me to use the success callback?

*Sometimes the model contains relations to other models or collections. For example a HouseModel that has an attribute of type AddressModel and collection of people called People. I wish the fetch will create a model when constructing the AddressModel and create a people collection when constructing People. How can I do it? Should I use the success for this or there are other way/workarounds?

A: The instance of the model is already "constructed". That is what you are calling fetch() on.
Otherwise, what is occurring is that the response JSON is being used to assign each key value pair as an attribute on that instance of the model. For collections it is creating new models based on the response.
So essentially:
// This line instantiates a new model
var model = new MyApp.Models.ModelThing();
// This line loads the model's attributes from the database
model.fetch();

If you are interested in how exactly this all happens, look at the Backbone.sync method. That is what actually does the AJAX request and fires the majority of callbacks that handle the response.
The success and error callbacks that can be passed to fetch are purely optional for doing things like cleanup a failed load or signaling the user that the load occurred.

A: This is one example you might get this from.
I suggest you manipulate & use your updated model from the success callback
function, since this is async method and it may be the only way you can actually use your model afterwards.
var MyModel = new Todo({id: Number(item)});
MyModel.fetch({success:function(){
        var todo = new updateView({model: dModel });
        todo.render();
}});

Model is already constructed with fetched data, but use that, populated model, within success callback.
Edited:
For your first issue: you need to see the documentation for model.parse or collection.parse so that you can customize backbone fetch for your backend's response. It is fairly easy to do that:
var Collection = Backbone.Collection.extend({

    parse: function(data){return data.objects;}

});

For your other question, I didn't quite get what you're trying to do.
But I think it should be pretty straightforward. You can do it both ways.
Just don't try using the constructed & fetched collection on its own in the same function (outside of binding events and success callback), because due to async fetch you might get nothing.


text:
Q: problems with jquery load() I need a certain div refreshed on the page every 3 seconds. This div contains other divs inside it.
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
setInterval(function()
{
    $('#gamewrapper2').load('find.php #gamewrapper2');
}, 3000);
;

This code works but only if the page visited is domain/find.php and it doesn't work for domain/find.php?id=1000001
Maybe i don't understand something but shouldn't this function load take the block #gamewrapper2 from find.php and paste it into the block #gamewrapper2 of the current page?

A: You can try the following to pass variables into the php document:
setInterval(function()
{
    $('#gamewrapper2').load('find.php #gamewrapper2', {id: 1000001});
}, 3000);
}

Additionally, you can provide a function callback when it has completed loading to perform some task...
setInterval(function()
{
    $('#gamewrapper2').load('find.php #gamewrapper2', {id: 1000001}, function(){
        alert("find.php has been loaded.");
    });
}, 3000);
}

.load() method
You should probably use $_POST['id'] to get the value from find.php.

A: Do you just need to keep the query string on find.php? Something like:

    setInterval(function(){
        $('#gamewrapper2').load(window.location.pathname + window.location.search + ' #gamewrapper2');
    }, 3000);


text:
Q: Interactive Grid shows no results when filtered or sorted I am using Oracle Apex v21.1. I have an Interactive Grid on a Modal Dialog Page which gives me the logs of the modifications made on a certain item.
Here's the scenario :

*

*Select the item on the list Step 1

*The details page of the item opens

*Click on the "Logs" button Step 2 & 3

*The "Logs" button open another Modal Dialog Page which displays an interactive grid Step 4

*The "Logs" button set the value of the primary key to the interactive grid, so the list is filtered to show the information of this particular item. Step 5
Everything works fine, but when I try to apply a filter, sort or search, the interactive grid refresh, shows no data, and a blank column appears. If I close the list but reopen it again, the results are appearing, based on the filter, sort or search.
What could be the reason behind this problem ?
Here's the code of my Interactive Grid
SELECT * FROM inv_tb_item_logs
WHERE pk_article = :P24_PK_ARTICLE;   --pk_article is my primary key

You can see more details on the screenshots
Thank you in advance,
Thomas

A: Based on Koen Lostrie's answers, here's how to fix it :

*

*Create an Hidden Item to retrieve the ID of the Item later on the Logs List page Step 1

*In the Behaviour of the Logs button, set the value of the hidden item to the value of the ID of the Item Step 2

*Change the WHERE clause to WHERE id_item = :P25_PK_ARTICLE

*In the Page Item to Submit attribute, select P25_PK_ARTICLE
I had to create this specific hidden item because i couldn't select the P24_PK_ARTICLE item to submit since it was on another page.
I hope this could help other people, thanks again for your answer Koen !


text: Q: How to debug a webapp from the Edge browser in iPad? How to debug a webapp from the Edge browser in iPad? There are no developer tools attached to the browser in the iPad. What will be the best bay to enable debugging webapps in iPad?


text:
Q: Grey dirt sliding in behind navigation & tab bars When I push my UITableViewController subclass it nicely slides in from the right, immediately followed by some kind of grey dirt that shows up on/under the navigation & tab bar.  It's very fast but I've been able to capture it red handedly.
(I also saw it elsewhere in my app with another view controller that slides up, here the dirt comes from below and makes the navigation bar darker.)
Any idea what this is, and more importantly how to get rid of it.

A: I added:
self.window.backgroundColor = [UIColor whiteColor];

in my AppDelegate code and the effect is still there (compared to what I see in iOS' Settings app for example), but it's very faint, and the final result after animation looks normal.


text:
Q: Why am I getting this error, eventhough I am getting result? Getting exception in  the code below:
import java.io.*;

public static void main(String[] args) throws IOException{
    FileReader objRead = new FileReader("/home/acer/Desktop/sulabh");
    BufferedReader objB = new BufferedReader(objRead);
    String input = null;
    while((input=objB.readLine())!= null){
        String temp = input.substring(0,2);
       if(temp.contains("77")) {
           System.out.println(input);
       }
    }
    objB.close();
}

And error with the answer is:
777
777
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: begin 0, end 2, length 0 at java.base/java.lang.String.checkBoundsBeginEnd(String.java:3319) at java.base/java.lang.String.substring(String.java:1874) at Main.main(Main.java:10)

A: From the java docs for substring:
Throws:
    IndexOutOfBoundsException - if the beginIndex is negative, or endIndex is larger than the length of this String object, or beginIndex is larger than endIndex.

Your String temp = input.substring(0,2); is getting a line shorter than length 2 after it gets the two good lines.
Protect against that as follows.
String temp = "";

if (input.length()>=2){
temp = input.substring(0,2);
}

A: I guess the first two lines have been processed fine and it throws error for the blank line at the end. Please check if you have a blank line at the end of the file. The blank line may contain less than 2 chractors.
Alternatively you can try input.startsWith("77") as well


text:
Q: How to publish two test result set with cake build system on azure devops ITNOA
I have one test project that run with NUnit3 Runner in cake that generate test result in test1.xml with NUnit format, and I have another test project that run with VSTest Runner in cake that generate test result in test2.xml with VSTest format.
My question is How to publish two test result into Azure DevOps with one command? or any other way exist to combine these files?
My command is like below
    if (testProjects.Any() && AzurePipelines.IsRunningOnAzurePipelines || AzurePipelines.IsRunningOnAzurePipelinesHosted)
    {
        Information("Publish test result.....................................");
        if (testResultsFiles.Any())
        {
            AzurePipelines.Commands.PublishTestResults(
                new AzurePipelinesPublishTestResultsData
                {
                    TestResultsFiles = testResultsFiles.ToArray(),
                    TestRunner = AzurePipelinesTestRunnerType.NUnit
                }
            );
        }
        if (vsTestResultsFiles.Any())
        {
            AzurePipelines.Commands.PublishTestResults(
                new AzurePipelinesPublishTestResultsData
                {
                    TestResultsFiles = vsTestResultsFiles.ToArray(),
                    TestRunner = AzurePipelinesTestRunnerType.VSTest
                }
            );
        }
    }

but As you can see above code, I write two publish method that is very bad, So I want to find a way that can send all test result in one command
GitHub disscussion
thanks


text:
Q: checking whether key value exist or not using C# I have a key as

"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Uninstall\{4CHJHSDJHSJHDJS-SDGSJAD}"

in my registry. using
Registry.GetValue("keyname", "valuename", "default value")

i can retrieve any value of it. But I need to check whether "{4CHJHSDJHSJHDJS-SDGSJAD}" exists in the registry or not. Can anybody suggest me what check I should use to do this?

A: With a registry key, you can try to get it with the OpenSubKey method. If the returned value is null, then the key does not exist. I'm talking about keys here, not values.
In your example, that would come down to:
var key = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Uninstall\{4CHJHSDJHSJHDJS-SDGSJAD}");
if (key == null)
{
    // Key does not exist
}
else
{
    // Key exists
}

A: Have you tried this
          using Microsoft.Win32;
          RegistryKey myregistry = Registry.CurrentUser.OpenSubKey("MyKey");
          if (myregistry != null)
          {
           string Value=myregistry.GetValue("ID").ToString();
          }

A: You can query for the Registry key with Registry.CurrentUser and then OpenSubKey.
RegistryKey key = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Uninstall\{4CHJHSDJHSJHDJS-SDGSJAD}");

if (key != null)
{
    // key exists
}
else
{
    // key does not exists
}


text:
Q: Couldn't install File::Path library with cpan
I am unable to install File::Path library using cpan. What is wrong?
# perl -v

This is perl 5, version 26, subversion 1 (v5.26.1) built for x86_64-linux

Copyright 1987-2017, Larry Wall

Perl may be copied only under the terms of either the Artistic License or the
GNU General Public License, which may be found in the Perl 5 source kit.

Complete documentation for Perl, including FAQ lists, should be found on
this system using "man perl" or "perldoc perl".  If you have access to the
Internet, point your browser at http://www.perl.org/, the Perl Home Page.

# cpan -v
/usr/bin/cpan script version 1.66, CPAN.pm version 2.18

Is there some other way how to make it installed or is there some workaround?
# cpan install File::Path
Reading '/root/.cpan/Metadata'
  Database was generated on Thu, 01 Mar 2018 13:17:03 GMT
Running install for module 'File::Path'
CPAN: Digest::SHA loaded ok (v6.01)
CPAN: Compress::Zlib loaded ok (v2.074)
Checksum for /root/.cpan/sources/authors/id/J/JK/JKEENAN/File-Path-2.15.tar.gz ok
CPAN: YAML loaded ok (v1.24)
CPAN: CPAN::Meta::Requirements loaded ok (v2.140)
CPAN: Parse::CPAN::Meta loaded ok (v2.150010)
CPAN: CPAN::Meta loaded ok (v2.150010)
CPAN: Module::CoreList loaded ok (v5.20180220)
Configuring J/JK/JKEENAN/File-Path-2.15.tar.gz with Makefile.PL
Checking if your kit is complete...
Looks good
Generating a Unix-style Makefile
Writing Makefile for File::Path
Writing MYMETA.yml and MYMETA.json
  JKEENAN/File-Path-2.15.tar.gz
  /root/localperl/bin/perl Makefile.PL -- OK
Running make for J/JK/JKEENAN/File-Path-2.15.tar.gz
cp lib/File/Path.pm blib/lib/File/Path.pm
Manifying 1 pod document
  JKEENAN/File-Path-2.15.tar.gz
  /usr/bin/make -- OK
Running make test
PERL_DL_NONLAZY=1 "/root/localperl/bin/perl" "-MExtUtils::Command::MM" "-MTest::Harness" "-e" "undef *Test::Harness::Switches; test_harness(0, 'blib/lib', 'blib/arch')" t/*.t
t/Path-Class.t .. ok
t/Path.t ........ ok
t/Path_root.t ... 1/11
#   Failed test 'created a directory not owned by 1:inpuu...'
#   at t/Path_root.t line 77.
#                   'unable to map inpuu to a gid, group ownership not changed:  at t/Path_root.t line 72.
# '
#     doesn't match '(?^s:unable to map 1 to a uid, ownership not changed:)'
# Looks like you failed 1 test of 11.
t/Path_root.t ... Dubious, test returned 1 (wstat 256, 0x100)
Failed 1/11 subtests
t/Path_win32.t .. skipped: not win32
t/taint.t ....... ok

Test Summary Report
-------------------
t/Path_root.t (Wstat: 256 Tests: 11 Failed: 1)
  Failed test:  8
  Non-zero exit status: 1
Files=5, Tests=214,  2 wallclock secs ( 0.05 usr  0.01 sys +  0.36 cusr  0.09 csys =  0.51 CPU)
Result: FAIL
Failed 1/5 test programs. 1/214 subtests failed.
make: *** [test_dynamic] Error 255
  JKEENAN/File-Path-2.15.tar.gz
  /usr/bin/make test -- NOT OK
//hint// to see the cpan-testers results for installing this module, try:
  reports JKEENAN/File-Path-2.15.tar.gz

A: This test failure is a known problem on centos 7, try the patch on RT.
https://rt.cpan.org/Public/Bug/Display.html?id=121967


text:
Q: $(1−x^n) = (1−x)(1 + x + x^2 +\cdots + x^{n−1})$ Is this expression generally true?
$$(1−x^n) = (1−x)(1 + x + \cdots + x^{n−1})$$
The closest Identity I could find in "Mathematical Handbook of Formulas and Tables", Schaum's Outline is:
$$x^{2n+1} - y^{2n+1} = (x-y)(x^{2n} +x^{2n-1}y + x^{2n+2}y^2 + \cdots +y^{2n})$$
Which I could almost believe is the same thing if I set x=1.
$$1 - y^{2n+1} = (1-y)(1 +y + y^2 + \cdots + y^{2n})$$
let $N=2n+1$
$$1 - y^N = (1-y)(1 +y + y^2 + \cdots + y^{N-1})$$
But doesn't this restrict N to be an odd number?  I was just asking because i saw this identity being used in a case where N could be an even or odd number, which made me think its generally true.  I'm just not sure how to prove it.

A: Of course it is always true just multiply
$$(1−x)(1 + x + \cdots + x^{n−1}) =$$
$$= 1 + x + \cdots + x^{n−1}-x(1 + x + \cdots + x^{n−1})=$$
$$=1\color{red}{ + x + \cdots + x^{n−1}- x-x^2 - \cdots - x^{n−1}}-x^n=1-x^n$$

A: Here are the formulæ I learnt in med-school:
$$x^n-y^n=(x-y)(x^{n-1}+x^{n-2}y+x^{n-3}y^2+\dots+xy^{n-2}+y^{n-1}),$$
in other words, it is $x-y$ times the sum of all homogeneous monomials in $x$ and $y$, with total degree $n-1$.
The sum of two powers requires an odd exponent:
$$x^{2n+1}+y^{2n+1}=(x+y)(x^{2n}-x^{2n-1}y+x^{2n-2}y^2-\dots+x^2y^{2n-2}-xy^{2n-1}+y^{2n}).$$

A: If you expand the sum of powers of $x$ times $1-x$, you get the sum of powers minus the sum of the same powers plus one. After cancellation, all intermediate powers vanish and $1-x^n$ remains.


text:
Q: Why does `... | sed 's/^/stdout: /'` print on empty stdin when `... > >(sed 's/^/stdout: /')` doesn't? I'm trying to understand what causes the difference in these 2 constructs that I thought were functionally equivalent:
$ ( echo foo >&2 ) 2> >(sed 's/^/stderr: /') | sed 's/^/stdout: /'
stdout: stderr: foo
$ ( echo foo >&2 ) 2> >(sed 's/^/stderr: /') > >(sed 's/^/stdout: /')
stderr: foo

EDIT: If I understood user1133275 right, he suggests that >(sed 's/^/stdout: /') is not run unless the subshell ( echo foo >&2 ) outputs to stdout. However, that would mean that the following:
$ ( echo foo >&2 ) 2> >(sed 's/^/stderr: /') > >(echo baz)
baz
stderr: foo

should not display baz.
EDIT 2: Perhaps also of interest, sed doesn't output stdout: on empty input, even when piped:
$ sed 's/^/stdout: /' < /dev/null
$ printf "" | sed 's/^/stdout: /'
$

A: Your first command,
( echo foo >&2 ) 2> >(sed 's/^/stderr: /') | sed 's/^/stdout: /'

in simplified form (using a temporary file to hold the data produced by echo):
{ echo foo 2>file >&2; sed 's/^/stderr: /' file; } | sed 's/^/stdout: /'

I.e., the first sed reads what is produced on standard error from the echo and writes to standard output and the second sed reads and modifies that.
Your second command,
( echo foo >&2 ) 2> >(sed 's/^/stderr: /') > >(sed 's/^/stdout: /')

in simplified form,
echo foo 2>file >&2; sed 's/^/stderr: /' file; sed 's/^/stdout: /' </dev/null

Here, the sed that gets the standard error output produces output while the other sed that gets the standard output output (which is nothing) does not produce any output (since it didn't get any input and since it did not insert or append any data).
Another way of formulating it:
First command:
( echo foo >&2 ) 2>file
sed 's/^/stderr: /' file | sed 's/^/stdout: /'

Second command:
( echo foo >&2 ) 2>file >otherfile
sed 's/^/stderr: /' file
sed 's/^/stdout: /' otherfile

In short, the second sed in the second command never reads anything. In particular, it does not read the output from the first sed as in the first command.

Using extremely simplified symbols, the first command is something like
utility-writing-to-stderr 2> >(something1) | something2

where something1 writes to standard output, which is read by something2.
The second command, using the same notation,
utility-writing-to-stderr 2> >(something1) >(something2)

i.e. something1 and something2 is not even connected to each other, and something2 can not in any way read what something1 is producing. Furthermore, since utility-writing-to-stderr does not produce anything on its standard output stream, something2 will have nothing to read from its standard input.

A: > is operating on ( echo foo >&2 ) and  | is operating on >(sed 's/^/stderr: /') because of the order of redirection in shells. E.G.
$ ( echo foo >&2 ) 2> >(sed 's/^/stderr: /' > >(sed 's/^/stdout: /') )
stdout: stderr: foo

or
$ ( echo foo >&2 ) 2> >(sed 's/^/stderr: /') | cat > >(sed 's/^/stdout: /')
stdout: stderr: foo

vs explicit examples the order in the question
$ ( ( echo foo >&2 ) > >(sed 's/^/stdout: /') ) 2> >(sed 's/^/stderr: /')
stderr: foo

or
$ ( ( echo foo >&2 )  | sed 's/^/stdout: /' ) 2> >(sed 's/^/stderr: /')
stderr: foo

A: The two commands are not equivalent.
The command (1):
( one ) 2> >(two) | three

Sends the (std) output of two to three (More about stderr below).
The command (2):
( one ) 2> >(two) > >(three)

Sends the (std) output of one to three (stderr goes to two).

The painful detail is:
Command 1: ( one ) 2> >(two) | three

*

*Command three is started (sed 's/^/stdout: /') waiting for input on stdin.

*Redirection of 2 (stderr) to the stdin of two takes place.

*Internal redirection of one takes place (echo foo >&2).

*The command gets executed sending foo to stderr (nothing to stdout).

*The word foo gets redirected from (stderr of one) to (stdin of two).

*The command in two gets executed (sed 's/^/stderr: /')

*The now modified output of two (stderr: foo) is sent to the stdout of two.

*The present stdout of two goes through the pipe to three.

*The command three which was waiting for input from the start gets the output.

*The output gets modified adding a leading stdout:.

*The final string stdout: stderr: foo goes to tty.

Command 2: ( one ) 2> >(two) > >(three)

*

*The last redirection (>) gets built first.

*The command three is started waiting for input on stdin only (>()).

*The command three gets only the stdout of one.

*The command two is started waiting for input.

*The command two gets (only) the stderr of one.

*The internal redirection of one connects the stdout of one to its stderr.

*The command one gets executed sending foo to the stderr (of one).

*foo goes to two

*two change the string received to stderr: foo and sends it to tty.

*three receives an empty input form the stdout of one.

*three prints nothing (as there is no line to process).

Understand that this command:
printf '' | sed 's/^/initial: /'

has no output (and there is no way to make it work).

Changing the order: Command 3: ( one ) > >(three) 2> >(two)
Makes the output of two go to three (not the tty) detail left as an exercise.

A: I upvoted @Kusalananda's very clear-cut answer, but I venture to (belatedly) add this to his answer, as a small illustration of process substitution at work:
Your second proposition would work with a small typographical change (and a comparatively large change in its faulty logic):
  $ ( echo foo >&2 ) 2> >(sed 's/^/stderr: /') > >(sed 's/^/stdout: /')
  stderr: foo    # for the well explained reason above

But:
    v                                          vv
  $ ( (echo foo >&2) 2> >(sed 's/^/stderr: /') )> >(sed 's/^/stdout: /')
  stdout: stderr: foo

Because adding ( )> as illustrated (or >( ), both work fine) actually allows you to create a file via process substitution, whose output can be redirected as input toward >(sed 's/^/stdout: /').
I thought about adding this to illustrate how process substitution can be embedded in another process substitution. For readability I would not push it to more levels of embedding. But if for any reason you need to avoid a pipe and the associated shell, this is a good solution.


text:
Q: Get marker added by google map drawing I'm using google map drawing library to draw shapes like polygon, rectangle and etc. I want to know how can I get shape object after drawing is done on map.
Any advice will be helpful.

A: You should be able to use event listeners for any shapes being added.  Either using a specific listener for certain types, or the generic overlay complete for all shape types.
google.maps.event.addListener(drawingManager, 'circlecomplete', function(circle) {
  var radius = circle.getRadius();
});

google.maps.event.addListener(drawingManager, 'overlaycomplete', function(event) {
  if (event.type == 'circle') {
    var radius = event.overlay.getRadius();
  }
});

https://developers.google.com/maps/documentation/javascript/drawinglayer#drawing_events
You could probably do something like:
var infowindow = new google.maps.InfoWindow({
    content: 'hello'
});

google.maps.event.addListener(drawingManager, 'markercomplete', function(marker) {
    marker.addListener('click', function() {
        infowindow.open(map, marker);
    });
});


text:
Q: I can't recreate the JSON object from unescaped Java string of JSON I am facing some issue in the following code.
  import org.json.JSONObject;

/**
 *
 * @author ajmalsha
 *
 */
public class test {

    /**
     *
     * @param args
     */
    public static void main(String[] args) {

        String value="[Mother's Day, Birthday \"Add to Cart\"]";

        JSONObject data= new JSONObject();
        data.put("title", value);
        System.out.println(data);
        String finalData=org.apache.commons.lang3.StringEscapeUtils.unescapeJava(data.toString());
        System.out.println(finalData);
    }

}

The output of the above code is
{"title":"[Mother\u2019s Day, Birthday \"Add to Cart\"]"}
{"title":"[Mother's Day, Birthday "Add to Cart"]"}

In the above first JSON were generated normally, In this the ' of Mother's were replaced with \u2019
I am able to retrieve the original value using org.apache.commons.lang3.StringEscapeUtils but not able to reconstruct the JSON from this finalData  String.
Can any one please help.

A: Why you need this process just serialize and deserialize as below.
If you try to read unescaped json from file and construct JSONObject it throws org.json.JSONTokener.syntaxError. You should use escaped json to reconstruct it.
    String value="[Mother's Day, Birthday \"Add to Cart\"]";

    JSONObject data= new JSONObject();
    data.put("title", value);
    System.out.println(data.toString());

    String deserialized = new JSONObject(data.toString()).getString("title");
    System.out.println(deserialized);

Output :
{"title":"[Mother\u2019s Day, Birthday \"Add to Cart\"]"}
[Mother's Day, Birthday "Add to Cart"]


text:
Q: Curl - Save cookie after login How to save the cookie so I can use it curl other URL?
Here is the request I'm passing to login.
curl -v -L -d "user_name=admin&user_password=password" -H "Content-Type: application/x-www-form-urlencoded" -X POST https://localhost/auth

I want to save the cookie so I can use it to curl other url. It seems like it doesn't write to ./somefile when using -d "user_name=admin&user_password=password"
--cookie-jar ./somefile


text:
Q: Text value doesn't change in React Native app using Class Component I have this react native app that shows the splash screen first and loads a home screen. The sample home screen shows text as "Demo Display" and I want to change it to "Text Changed!". I'm using a stateful class component. But everytime I try to restart/reinstall/debug the app the text remains same as "Demo Display". How can I fix this?
App.js

import React,{ Component } from 'react'
import { View, Text } from 'react-native'
import SplashScreen from 'react-native-splash-screen'

export default class App extends Component {

  componentDidMount() {
      SplashScreen.hide();
  }

  render() {
    return (
      <View>
        <Text>Text Changed!</Text>
      </View>
    );
  }
}

This is a screen shot of the app

A: Your text is there on the screen but it will not replace the default text.
Give some style to your main View and you will see your text there.
Try,
<View style={{justifyContent: 'center',alignItems: 'center'}}>
  <Text>Text Changed!</Text>
</View>


text:
Q: How do you use Google API getRequestHeaders() to get an OAuth2 access token? I'm using the googleapis npm library to authorize using OAuth2 to access my Gmail account to send emails. I am using the following code (TypeScript) to do that:
const oAuth2Client = new google.auth.OAuth2(
  googleConfig.clientId,
  googleConfig.clientSecret
);

oAuth2Client.setCredentials({
  refresh_token: googleConfig.refreshToken
});

const accessTokenRetVal = (await oAuth2Client.refreshAccessToken()).credentials.access_token;
const accessToken = accessTokenRetVal || '';

This code works, but I get the following message:
(node:8676) [google-auth-library:DEP007] DeprecationWarning: The `refreshAccessToken` method has been deprecated, and will be removed in the 3.0 release of google-auth-library. Please use the `getRequestHeaders` method instead.

I have searched on Google, on the GitHub for the googleapis module, on StackOverflow, and I haven't been able to find any documentation for what constitutes the getRequestHeaders method. I've tried calling getRequestHeaders, but it doesn't appear to return a credentials object with an access token.
Are there official docs for how getRequestHeaders should be used in this situation?

A: const accessToken=oAuth2Client.getAccessToken()
This worked for me

A: This new function directly gives you an 'Headers' object:
{ Authorization: 'Bearer xxxxxxxxx' }

So you can happend it directly use it as your header object:
const authHeaders = await this.auth.getRequestHeaders();
yourfetchlibrary.get('https://......', {
            headers: authHeaders,
        })

Or extract the Authorization part:
const authHeaders = await this.auth.getRequestHeaders();
yourfetchlibrary.get('https://......', {
            headers: {
                'Authorization': authHeaders.Authorization,
                'Content-Type': 'application/json',
            },
        })


text:
Q: Testing internal classes when using test class inheritance I cannot build the test project beacuse I get: Inconsistent accessibility: property type 'Lib.MyClass' is less accessible than property 'Lib.Tests.GivenMyClass.Cut'.
Assembly Lib
[assembly: InternalsVisibleTo(".Lib.Tests")]

internal class MyClass
{
    public string Foo(int x) { ... }
}

Assembly Lib.Test
public GivenMyClass
{
    protected internal SynchronizedDataLink Cut { get; private set; } // Inconsistent accessibility: property type 'Lib.MyClass' is less accessible than property 'Lib.Tests.GivenMyClass.Cut'

    public GivenMyClass()
    {
        Cut = new MyClass();
    }
}

[TestClass]
public WhenFooCalled
{
    private int x;

    public WhenFooCalled()
    {
        x = Create.Any<int>();
        Cut.Foo(x);
    }

    [TestMethod]
    public void ThenSomething()
    {
        // assert something using x
    }
}

What are the solutions - how can I make it working?

*

*I do not want to make the 'MyClass' as public because it is
dedicated just for one assembly. This is the use-case of using internal - am I correct?

*The real code is much more complex and thanks to the following
pattern of writing unit tests it removes as a lot of test code
redundancy and makes the refactoring easier. However I do not say
that I strictly must follow this pattern of writing...
I can for example write my tests like this:
[TestClass]
public MyClassTests
{
    private MyClass cut;

    public MyClassTests()
    {
        cut = new MyClass();
    }

    public int ExecuteFoo()
    {
        int x = Create.Any<int>();
        cut.Foo(x);
        return x;
    }

    [Fact]
    public void Foo_ThenSomething()
    {
        int x = ExecuteFoo();
        // assert something using x
    }
}

However then I had a lot of invoking like ExecuteFoo and everything is in one class. Int inhertiance pattern when we change a method int the ClassUnderTest then we change only tests in one class (high cohesion). In the one-class approach everything is in one place (a lot of unreadable code)...


text:
Q: Скрипт работает но завершается с ошибкой Fatal error: Uncaught Error: Call to a member function fetch_object() on boolean Как это исправить? При том что скрипт работает и отправляет данные в БД
Ошибка полностью
Fatal error: Uncaught Error: Call to a member function fetch_object() on boolean in W:\domains\localhost\DB.php:26 Stack trace: #0 W:\domains\localhost\handler.php(39): DB->query('INSERT INTO sho...') #1 {main} thrown in W:\domains\localhost\DB.php on line 26

Handler.php
<?php

require_once 'DB.php';

$grade_ch = check_input($_POST["grade"], "Введите класс!");
$sho_name_ch = check_input($_POST["sho_name"], "Введите имя!");
$radio_ch = check_input($_POST["y_n"], "Да или нет?");
$b_day_ch = check_input($_POST["b_day"], "Ввведите дату");

//Если при заполнении формы были допущены ошибки сработает следующий код:
function check_input($data, $problem = "")
{
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    if ($problem && strlen($data) == 0) {
        show_error($problem);
    }
    return $data;
}

function show_error($myError)
{
    ?>

Пожалуйста исправьте следующую ошибку:

    <?php echo $myError; ?>

    <?php
    exit();
}

$grade = $_POST["grade"];
$sho_name = $_POST["sho_name"];
$y_n = $_POST["y_n"];
$b_day = $_POST["b_day"];

$result = DB::getInstance()->query("INSERT INTO sholar (grade, sho_name, y_n, b_day) VALUES ('$grade', '$sho_name', '$y_n', '$b_day')");

if ($result == true) {
    echo "Информация занесена в базу данных";
} else {
    echo "Информация не занесена в базу данных";
}

// }

DB.php
<?php
class DB {
    private $_mysqli,
            $_query,
            $_results = array(),
            $_count = 0;

    public static $instance;

    public static function getInstance() {
        if(!isset(self::$instance)) {
            self::$instance = new DB();
        }
        return self::$instance;
    }

    public function __construct() {
        $this->_mysqli = new mysqli('127.0.0.1', 'root', '', 'test');
        if ($this->_musqli->connect_error) {
            die($this->_mysqli->connect_error);
        }
    }

    public function query($sql) {
        if ($this->_query = $this->_mysqli->query($sql)) {
              while ($row = $this->_query->fetch_object()) {
                $this->_results[] = $row;
              }
              $this->_count = $this->_query->num_rows;
        }
        return $this;
    }

    public function results() {
        return $this->_results;
    }

    public function count() {
        return $this->_count;
    }
}

строка 26 класса db
while ($row = $this->_query->fetch_object()) {

A: mysqli::query возвращает false, в случае неудачного запроса в БД. Отсюда и ошибка. Попробуйте сделать проверку в методе query
public function query($sql)
{
    $this->_query = $this->_mysqli->query($sql);
    if (!$this->_query) {
        throw new \Exception('something is wrong with a query' . $this->_mysqli->error);
    }

    while ($row = $this->_query->fetch_object()) {
        $this->_results[] = $row;
    }
    $this->_count = $this->_query->num_rows;

    return $this;
}


text:
Q: How to avoid including an unwanted `+` separator in a label for my dice game? I have a problem with a simple Windows Forms program. The program is a dice game:

*

*The user writes into a textbox how many dice they want to roll.

*The application rolls the number of dice entered.

*The application shows the value of each die as well as the total across all rolled dice in a label.

Example: If I roll 4 dice, the application should show their values together with the sum of their values, such as: 4 + 3 + 6 + 1 = 14.
I don't know how to make my application decide if it rolled the dice enough times before writing an extra + sign out.
Right now, the application shows the result of rolling 3 dice like:

3 + 3 + 3 += 9

But I don't want that last + in the label – I want it to only write = 9, not += 9.
This is how my code looks now:
private void throwDice_Click(object sender, EventArgs e)
{
    int numberOfDices = int.Parse(dicesTextBox.Text);
    int sum = 0;
    showLabel.Text = "";

    if (numberOfDices == 1)
    {
        Random rand = new Random();
        int dice1 = rand.Next(1, 7);
        sum = dice1;
        showLabel.Text = dice1 + " = " + sum;
    }
    else if (numberOfDices > 1)
    {
        Random rand1 = new Random();

        for (int i = 0; i <= numberOfDices; i++)
        {
            int dice = rand1.Next(1, 7);
            sum += dice;

            if (i != numberOfDices)
            {
                showLabel.Text += dice.ToString() + " + ";
            }
            else
            {
                showLabel.Text += "=" + sum.ToString();
            }
        }
    }
}

A: Simply change if (i != antal) to if (i < numberOfDices) and visaLabel.Text += "=" + summa.ToString(); to visaLabel.Text += dice.ToString() + " = " + sum.ToString();.

A: A more elegant approach could be:
private void throwDice_Click(object sender, EventArgs e)
{
    int numberOfDices = int.Parse(dicesTextBox.Text);
    int sum = 0;
    int i = 1;
    showLabel.Text = "";

    do
    {
        Random rand = new Random();
        int dice1 = rand.Next(1, 7);
        sum += dice1;
        showLabel.Text += string.Format("{0} {1}", dice1.ToString(), i ==  numberOfDices ? " = " + sum.ToString() : " + ");
        i++;
    } while (i <= numberOfDices);
}


text:
Q: Let $A = 2*p_1*...*p_n + 1$ where $p_i$'s are odd primes . Prove that $\gcd(A,p_i) = 1$ for all $i$. I'm trying to prove this but I can't figure it out. I'm pretty much stuck. Trying to start with $B = 2*p_1* \dots * p_n$ and clearly the $\gcd(B, p_i) = p_i$ for some $i$.
But adding $1$, I can't figure out how to prove that the $\gcd(A, p_i) = 1$, any hints to lead me in the right direction?

A: First approach: Since $$A+p_i\cdot(-2\cdot p_1\cdots p_{i-1}p_{i+1}\cdots p_n)=1$$ then Bezout's identity implies that $\gcd(A,p_i)=1.$
Second approach: Suppose, for the sake of contradiction, that $d=\gcd(A,p_i)>1$ for some $i.$ If $q$ is any prime factor of $d,$ then $q$ divides both $p_i$ and $A$ and thus $p_i=qb$ and $A=qc$ for some $b,c\in\mathbb Z.$ Hence $( 2p_1\cdots p_{i-1}bp_{i+1}\cdots p_n-c )q=1$ and so $q\mid1,$ which is clearly false since $q$ is prime.


text:
Q: How to use needsInputModeSwitchKey properly? When i try to use (anywhere and anytime in my code) needsInputModeSwitchKey property from UIInputViewController i'm facing with warning:

-[UIInputViewController needsInputModeSwitchKey] was called before a connection was established to the host application. This will produce an inaccurate result. Please make sure to call this after your primary view controller has been initialized.

Despite the warning, i get correct value and it looks weird. What should i do to remove this warning?


text:
Q: PageReference to Libaries page clearing my search I have a Visualforce page that renders part of library content in it, but I also give them the option to type in a search which will renavigate them to the default Libraries tab with the search option they filled in earlier.  For some reason when I redirect them via Page Reference, it clears out the information on the URL.  For now I have values hardcoded in, but I'm just trying to get the simpliest things working first.
public PageReference doSearch()
{
  PageReference pRef = new PageReference('/sfc/#search?searchTerm=testing&shepherdToken=3hhlYajWjfdqOLQNlORGloGav8BWt7ZKFeAwWdELQSKmmZaWOmcS8usuaXys9gtgqdAP0DGsg69Fb6FZFclETy7UVbW1V1HKh4uIhQMYPAQ_MgNvEpDHNC1UTzyoCY8xaFlZkcC3ZGTLmADq8V7mVDsV3B8%3D&searchPageNum=0&searchWorkspaceIds=%5B%22ALL_WORKSPACES%22%5D&masterWorkspaceId=ALL_WORKSPACES');

  pRef.setRedirect(true);
  return pRef;
}

I arrive at the Libraries page.... but it clears the URL to /sfc/#search.
EDIT:  I have also tried using pRef.setRedirect(false);

A: Your URI is invalid according to RFC 3986: the fragment part (the "#search") should come after the query part (the "?searchTerm..."). If you fix that, the PageReference will correctly parse the query terms rather than throwing them away. Its a pity PageReference silently discards the query terms rather than throwing an exception.
(You can confirm this by writing a unit test using your current URI and the corrected URI.)
PS
Here is a test case fail illustrating that having the anchor at the beginning results in the query string getting made part of the anchor. The test pass1 shows that removing the anchor fixes the query string. And pass2 shows that putting the anchor at the end results in both the query string and anchor being correctly parsed.
@isTest
private class Test {

    @isTest
    static void fail() {
        PageReference pr = new PageReference('/sfc/#search?searchTerm=testing&shepherdToken=3hhlYajWjfdqOLQNlORGloGav8BWt7ZKFeAwWdELQSKmmZaWOmcS8usuaXys9gtgqdAP0DGsg69Fb6FZFclETy7UVbW1V1HKh4uIhQMYPAQ_MgNvEpDHNC1UTzyoCY8xaFlZkcC3ZGTLmADq8V7mVDsV3B8%3D&searchPageNum=0&searchWorkspaceIds=%5B%22ALL_WORKSPACES%22%5D&masterWorkspaceId=ALL_WORKSPACES');
        // The problem: the query string gets included in the anchor
        System.assertEquals('search?searchTerm=testing&shepherdToken=3hhlYajWjfdqOLQNlORGloGav8BWt7ZKFeAwWdELQSKmmZaWOmcS8usuaXys9gtgqdAP0DGsg69Fb6FZFclETy7UVbW1V1HKh4uIhQMYPAQ_MgNvEpDHNC1UTzyoCY8xaFlZkcC3ZGTLmADq8V7mVDsV3B8%3D&searchPageNum=0&searchWorkspaceIds=%5B%22ALL_WORKSPACES%22%5D&masterWorkspaceId=ALL_WORKSPACES', pr.getAnchor());
        System.assertEquals(0, pr.getParameters().size());
    }

    @isTest
    static void pass1() {
        PageReference pr = new PageReference('/sfc/?searchTerm=testing&shepherdToken=3hhlYajWjfdqOLQNlORGloGav8BWt7ZKFeAwWdELQSKmmZaWOmcS8usuaXys9gtgqdAP0DGsg69Fb6FZFclETy7UVbW1V1HKh4uIhQMYPAQ_MgNvEpDHNC1UTzyoCY8xaFlZkcC3ZGTLmADq8V7mVDsV3B8%3D&searchPageNum=0&searchWorkspaceIds=%5B%22ALL_WORKSPACES%22%5D&masterWorkspaceId=ALL_WORKSPACES');
        System.assertEquals(null, pr.getAnchor());
        System.assertEquals(5, pr.getParameters().size());
    }

    @isTest
    static void pass2() {
        PageReference pr = new PageReference('/sfc/?searchTerm=testing&shepherdToken=3hhlYajWjfdqOLQNlORGloGav8BWt7ZKFeAwWdELQSKmmZaWOmcS8usuaXys9gtgqdAP0DGsg69Fb6FZFclETy7UVbW1V1HKh4uIhQMYPAQ_MgNvEpDHNC1UTzyoCY8xaFlZkcC3ZGTLmADq8V7mVDsV3B8%3D&searchPageNum=0&searchWorkspaceIds=%5B%22ALL_WORKSPACES%22%5D&masterWorkspaceId=ALL_WORKSPACES#search');
        System.assertEquals('search', pr.getAnchor());
        System.assertEquals(5, pr.getParameters().size());
    }
}

A: So far the only workaround I found is to use onclick javascript to navigate me away.  I prefer using my controller for this, but as of now this is my only solution:
function navigateAway()
{
  window.location.href = 'https://cs7.salesforce.com/sfc/#search?searchTerm=testing&searchPageNum=0&searchWorkspaceIds=%5B%22ALL_WORKSPACES%22%5D&masterWorkspaceId=ALL_WORKSPACES';
}


text:
Q: S3 folder keeps reappearing and disappearing I have an S3 bucket.  In it are folders Foo and foo (among others).  I deleted Foo.
When I refresh the page in the S3 browser console, about 50% of the time I still see Foo listed.  I refresh again, and it's gone.  Refresh a third time, and it's back.  This is also the case with the AWS CLI.
The only idea I can come up with is something related to upper/lowercase clashes, but I was under the impression that S3 is case-sensitive.  Any idea what might be going on?

A: The important thing to appreciate is that folders do not actually exist in Amazon S3. Amazon S3 is an object store, not a filesystem, and all objects are stored in a flat namespace with no directories.
That said, S3 emulates directories via:

*

*Filenames (the key of the object) include the full path, so bar.txt stored in the foo directory actually has a Key of foo/bar.txt

*The S3 management console simulates folders by showing objects with a common prefix

*You can actually copy files to a 'folder' even if the folder doesn't exist, eg: aws s3 cp bar.txt s3://bucket/docs/bar.txt

*Empty folders created in the management console actually create a hidden zero-length file to force the 'folder' to appear

So, firstly don't worry too much about empty folders appearing/disappearing. It doesn't really mean anything. It might be caused by S3 eventual consistency or due to versioning. If it is really upsetting for you, you could contact AWS Support (if you are subscribed). Otherwise, just keep trying to delete it and hopefully it will give you a consistent result.


text:
Q: Can't center my background in Firefox/IE - can't display menu over background HTML Please i need help , im having problems ok first is my bacground image is not showing centerd in firefox or IE but in chrome it works fine and SECOND i ahve amenu and i cant get it to display ontop of my background picture: Below i have pasted my Html code and my css please help me and have a look i would really appreciate it....

<title>Just something</title>

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<link rel="stylesheet" href="css/css.css" type="text/css" media="screen"/>

<link rel="stylesheet" href="bcg_files/css3menu1/style.css" type="text/css" />

                                    Home

                                        Product Information

MAXOFIX

Splicing

Sidewalls

Cleats

Basebelts

Accessories

                                        Downloads

Catalogues

Mobile App.

Enquiries

Contacts

Advantages:

                                        Space-saving Inclines of up to

                                        90(and then that small 0) possible.

                                        Belts are easy on material

                                        transported.

                                        Direction of feed and dis-

                                        charge can be different.

                                        More...

Products:

                                Space-saving Inclines of up to

                                        90(and then that small 0) possible.

                                        Belts are easy on material

                                        transported.

                                        Direction of feed and dis-

                                        charge can be different.

                                        More...

News:

  Space-saving Inclines of up to

                                        90(and then that small 0) possible.

                                        Belts are easy on material

                                        transported.

                                        Direction of feed and dis-

                                        charge can be different.

                                        More...

HERE IS MY CSS

/* this is for the main page */

/*this is for the menu*/
.menu
{
    align:center;
    left:567px;
}

/*This is for the boxes at the bottom of the pag*/
.cc_content
{

    width:233px;
    height:236px;
    /*border-bottom:1px solid #000;*/
    position:absolute;
    left:567px;
    overflow:hidden;
    /*-moz-box-shadow:4px 0 7px #000;
    -webkit-box-shadow:4px 0 7px #000;
    box-shadow:4px 0 7px #000;*/
    top:876px;
}

.cc_content1
{
    width:233px;
    height:236px;
    /*border-bottom:1px solid #000;*/
    position:absolute;
    left:328px;
    overflow:hidden;
    /*-moz-box-shadow:4px 0 7px #000;
    -webkit-box-shadow:4px 0 7px #000;
    box-shadow:4px 0 7px #000;*/
    top:  876px;
}

.cc_content2
{
    width:233px;
    height:236px;
    /*border-bottom:1px solid #000;*/
    position:absolute;
    left:806px;
    overflow:hidden;
    /*-moz-box-shadow:4px 0 7px #000;
    -webkit-box-shadow:4px 0 7px #000;
    box-shadow:4px 0 7px #000;*/
    top:  876px;
}

/*This is for the content of the boxes exept the Header*/
.cc_content p
{
    background:none;
    text-align:left;
    padding-left:15px;
}

.cc_content1 p
{
    background:none;
    text-align:left;
    padding-left:15px;
}
.cc_content2 p
{
    background:none;
    text-align:left;
    padding-left:15px;
}

/*This is for the Header of the boxes*/
.cc_content h1
{
    text-align:left;
    padding-left:15px;
}

.cc_content1 h1
{
    text-align:left;
    padding-left:15px;
}

.cc_content2 h1
{
    text-align:left;
    padding-left:15px;
}

I HAVE A CUSTOM CSS3 MENU BUT I DONT THINK THAT IS THE PROBLEM..

A: z-index is ignored unless the div is position: relative or absolute, make sure it is one of these otherwise the z-index is pointless


text:
Q: Read connection from appsettings.json in .net core 1.1 web api I am create a web api project in .net core 1.1 but problem is when its try to read connectionstring from appsettings.json an exception occurs .

System.IO.FileNotFoundException: 'The configuration file
  'appsettings.json' was not found and is not optional. The physical
  path is
  'C:\Test\netCoreWebApi\netCoreWebApi\bin\Debug\netcoreapp1.1\appsettings.json'.'

Startup.cs
public class Startup
    {
        public Startup(IHostingEnvironment env)
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(env.ContentRootPath)
                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
                .AddEnvironmentVariables();
            Configuration = builder.Build();
        }

        public IConfigurationRoot Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<NorthWindDBContext>();
            // Add framework services.
            services.AddMvc();

            services.AddScoped<ICategory_Product, Category_ProductRepository>();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            app.UseMvc();
        }
    }

also eclare connectionstring in DBContext class (may be I am doing wrong here)
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            var builder = new ConfigurationBuilder()
                       .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);

            var configuration = builder.Build();

            string connectionString = configuration.GetConnectionString("northwindConnection");
            optionsBuilder.UseMySql(connectionString);

        }

so wats the correct way .
please help .


text:
Q: How to make RadMenu root items justified? Specifically, how would I do this without any JavaScript?
I have a RadMenu that I made 1080px wide, I have about 7 items in it so they only take up about 2/3 of that width.
I want force the items to split the width of the whole RadMenu between them so there's no awkward blank area on either side.
(Similar to using Justify on a RadTab)
Can this be achieved with CSS, or existing functionality of the RadMenu?

A: You'll have to play with the padding element of the RadMenu and adjust the right and left side to get the desired with you want.
.RadMenu .rmRootGroup .rmRootLink {
    padding: .25em .54em .35em .50em;
}

Remember the order is top, right, bottom, left.


text:
Q: Error message when using openpyxl.load_workbook() function I have just started to learn programming and I am currently trying to read an excel file from IDLE. I'm following instruction from the book "Automate the Boring Stuff". I have successfully imported openpyxl, and thereafter, as instructed tried wb = openpyxl.load_workbook('example.xlsx') where I exchanged "example" to the actual name of the workbook. However, I get this error message:
Traceback (most recent call last):   File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/openpyxl/reader/excel.py", line 117, in load_workbook
    archive = ZipFile(filename, 'r', ZIP_DEFLATED)   File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/zipfile.py", line 1216, in __init__
    self.fp = io.open(file, filemode) FileNotFoundError: [Errno 2] No such file or directory: 'jan.xlsx'

During handling of the above exception, another exception occurred:
Traceback (most recent call last):
  File "<pyshell#4>", line 1, in <module>
    wb = openpyxl.load_workbook('jan.xlsx')
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/openpyxl/reader/excel.py", line 145, in load_workbook
    raise InvalidFileException(unicode(e))
openpyxl.exceptions.InvalidFileException: [Errno 2] No such file or directory: 'jan.xlsx'

I don't understand how to solve this.

A: This error message simply says that python can't locate the file. When you try to open a file 'jan.xlsx', it's trying to locate it in the base directory of your code in your IDE. So say your code is in a directory called /Users/username/PycharmProjects/myCode
(I'm assuming here you are on a Mac OS as the path to your python suggests...
but jan.xlsx is in /Users/username
Since that is 2 directories up from your code directory, you can do one of two things:

*

*Write in the absolute path to the file:

wb = openpyxl.load_workbook('/Users/username/jan.xlsx')

*Use a relative path that is relative to the base project directory. Two dots in a relative path means one level up from the current directory. So if the excel file is 2 levels up, you can do:

wb = openpyxl.load_workbook('../../jan.xlsx')


text:
Q: Adding specific Dictionary key to a list (Python 2.6) Hi there I've been struggling with this problem for a while now.
I have a dictionary like:
dict1  =  {
    'Name': 'ID Numbers',
    'children': []
    }

I have an other list of dictionaries with a number of IDs in it such as:
list1 = [
  {
    "id": 1004,
    "othervalue": "blah blah"

  },
  {
    "id": 1008,
    "othervalue": "blah blah"

  }

I need to add those dictionaries to the 'children' list.
If it was 2.7 i could probably do:
for x in dict1:
  x['children'].append(IDs from list1)

Possibly? But alas it's 2.6 and I have absolutely no idea how to go about this. Any ideas would be so very much appreciated.
Expected output:
dict1  =  {
    'Name': 'ID Numbers',
    'children': [

    {
    "id": 1004,
    },

    {
    "id": 1008,
    }

]
}

A: Although dict comprehensions are not available in Python 2.6, you still may use dict constructor. Since it looks like you want to add multiple items to list, extend may be better suitable than append.
dict1['children'].extend(dict([('id', d['id'])]) for d in list1)


text:
Q: sudoers: default secure path изменил Я изменил sudoers файл в процессе инсталяции судо пакета, изменил случайно, и не знаю его стандартное значение, подскажите, пожалуйста.
Суть проблемы в том, что перестали работать некоторые стандартные пакеты типа
uptime # и некоторые другие

Как исправить проблему?

A: содержимое файла можно взять из файла с пакетом. в вашем случае имя пакета — sudo. все действия отлично выполняются от имени непривилегированного пользователя:

*

*скачайте файл с пакетом в текущий каталог:
$ apt download имя-пакета

*распакуйте его:
$ dpkg-deb -R *.deb каталог

каталог/etc/sudoers — это и есть искомый вами файл.
редактировать файл /etc/sudoers лучше программой-обёрткой visudo.

связанный вопрос: Где взять файл нужной версии?


text:
Q: Center a TextView inside another View in Android Relative Layout In my relative layout, I have a circle View and a TextView. I would like to center the TextView exactly within the circle View. How do I do that? The code I have so far is below:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <View
        android:id="@+id/firstCircle"
        android:layout_width="24dp"
        android:layout_height="24dp"
        android:layout_marginLeft="24dp"
        android:layout_marginTop="24dp"
        android:background="@drawable/circle" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="1"
        android:id="@+id/number1" />

</RelativeLayout>

I want the final result to look like:
Screenshot

A: try this
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <View
        android:id="@+id/firstCircle"
        android:layout_width="24dp"
        android:layout_height="24dp"
        android:layout_marginLeft="24dp"
        android:layout_marginTop="24dp"
        android:background="@drawable/circle" >
    </View>

    <TextView
        android:id="@+id/number1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="30dp"
        android:layout_marginTop="28dp"
        android:text="1" />

</RelativeLayout>

A: To paste a view on other framelyout is used.
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <View
            android:id="@+id/firstCircle"
            android:layout_width="24dp"
            android:layout_height="24dp"
            android:layout_marginLeft="24dp"
            android:layout_marginTop="24dp"
            android:background="@drawable/circle" />

        <TextView
            android:id="@+id/number1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="1"
            android:layout_alignBottom="@+id/firstCircle"
            android:layout_alignRight="@+id/firstCircle"
            android:layout_alignEnd="@+id/firstCircle"
            android:layout_alignLeft="@+id/firstCircle"
            android:layout_alignStart="@+id/firstCircle"
            android:layout_alignTop="@+id/firstCircle"
            android:gravity="center" />
    </RelativeLayout>

</FrameLayout>

A: <?xml version="1.0" encoding="utf-8"?>

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:android="http://schemas.android.com/apk/res/android">

        <View
            android:id="@+id/firstCircle"
            android:layout_width="24dp"
            android:layout_height="24dp"
            android:layout_marginLeft="24dp"
            android:layout_marginTop="24dp"
            android:background="@drawable/circle" />

        <TextView
            android:id="@+id/number1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="1"
            android:layout_alignBottom="@+id/firstCircle"
            android:layout_alignRight="@+id/firstCircle"
            android:layout_alignEnd="@+id/firstCircle"
            android:layout_alignLeft="@+id/firstCircle"
            android:layout_alignStart="@+id/firstCircle"
            android:layout_alignTop="@+id/firstCircle"
            android:gravity="center" />
    </RelativeLayout>

A: Change your view by any one layout as below it will work better,
 <LinearLayout
    android:id="@+id/firstCircle"
    android:layout_width="24dp"
    android:layout_height="24dp"
    android:layout_marginLeft="24dp"
    android:layout_marginTop="24dp"
    android:gravity="center"
    android:layout_gravity="center"
    android:background="@drawable/circle">

   <TextView
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:text="1"
       android:gravity="center"
       android:id="@+id/number1" />
</LinearLayout>

A: I think you want circleview as background of TextView. then why not that view as background as TextView.
Try this.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/circle"
        android:text="1"
        android:gravity="center"
        android:padding="10dp"
        android:id="@+id/number1" />

</RelativeLayout>

Note : you can adjust padding according to your need

A: You don't need to use some extra View, simply set circle image as background of TextView and set gravity to center as below:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        xmlns:app="http://schemas.android.com/apk/res-auto">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="1"
            android:gravity="center"
            android:background="@drawable/circle"
            android:id="@+id/number1" />

    </RelativeLayout>


text:
Q: PHP PDO mysql prepared statment and join I have a question.
I have the following query:
$query = "select * from module,bloc where module.id_bloc = ?";

I tried to bind the value so I did:
$stmt = $this->db->prepare($query);
$stmt->bindValue(1, "bloc.id_bloc");

But, when I test I don't get any result on my browser.
It's weird because when I replace directly inside like the following code:
$query = "select * from module,bloc where module.id_bloc = bloc.id_bloc";

I get the the right result on my browser.
Could someone explain to me why it doesn't work when I am doing a bindValue?

A: It will not work because, when bound, a string will be quoted. (Or, for all intents and purposes, work as if it were quoted, however PDO may handle it behind the scenes.) Then, your query is interpreted as:
select * from module,bloc where module.id_bloc = 'bloc.id_bloc'

That is: It will be interpreted as a literal string, rather than a reference to a table column, and will obviously not give you the expected result. There is no need for binding it to begin with.
If, for some reason, you need to run a query with a variable table/column name from an unsafe source, you will have to manually format/sanitize it; see here for an example of how to do it.


text:
Q: System.js and Babel not working in IE 8 I am developing a web project using ES 6 in combination with the Babel transpiler and System.js as module loader. In all browsers from IE 9 up, that works well, unfortunately I have to support IE 8 though.
In the unbundled file, IE 8 can't even load my main.js file. It fails with the following console message without indicating any line of code.
Potentially unhandled rejection [4] SyntaxError: Error loading "main" at http://localhost:8080/assets/js/main.js
Error loading "npm:babel-core@5.8.22" at http://localhost:8080/assets/libs/npm/babel-core@5.8.22.js
expected identifier

I am using jspm as a dependency manager. The bundled sfx file built with jspm bundle-sfx yields a different error:
cannot read property "call" of undefined

Here, at least a line is given, it points to the following function of the system.js core:
function forEachGlobal(callback) {
 iterateGlobals(function(globalName) {
   if (indexOf.call(ignoredGlobalProps, globalName) != -1)
     return;
   try {
     var value = loader.global[globalName];
   }
   catch(e) {
     ignoredGlobalProps.push(globalName);
   }
   callback(globalName, value);
 });
}

indexOf is indeed undefined here when logging it to the console, although it shouldn't, because it is defined earlier in the file.
The only relevant additional info I can give you is my package.json:
{
  // some metadata
  "devDependencies": {
    "jspm": "^0.15.7",
    "jspm-bower-endpoint": "^0.3.2",
    // some more grunt tasks
  },
  "jspm": {
    "directories": {
      "baseURL": "source",
      "packages": "source/assets/libs"
    },
    "dependencies": {
        // frontend libraries
    },
    "devDependencies": {
      "babel": "npm:babel-core@^5.1.13",
      "babel-runtime": "npm:babel-runtime@^5.1.13",
      "core-js": "npm:core-js@^0.9.4"
    },
  }
}

Officially, both system.js and babel support IE 8. I couldn't find everyone else with this issue, so I hope someone can help me solving that issue.
Thanks in advance!


text:
Q: How to implement dynamic pages in React.js?

import React, { Component } from "react";
import { FormattedMessage } from "react-intl";
import { connect } from "react-redux";

class Project extends Component {
  render() {
    return (

        <FormattedMessage id="route.project">
          {route => {
            return (

{this.props.header}

{this.props.description}

            );
          }}
        </FormattedMessage>

    );
  }
}

const mapStateToProps = state => {
  return {
    projects: state.project.projects
  };
};

export default connect(
  mapStateToProps,
  {}
)(Project);

How to implement projects' pages and custom URL for every one. I suppose custom URLs have to be done with MongoDB, but how to implement it in reactjs. That is third day of my research, but mostly I found complicated code
Thanks for every answer

A: You would most likely use a client-side navigation package such as React-Router to accomplish this.
In order to set up a basic router, you need to define routes and views for those routes in the following fashion, where the "path" prop refers to your desired endpoint and "component" being the desired view:
import React from "react";
import { BrowserRouter as Router, Route, Link } from "react-router-dom";

const BasicExample = () => (
  <Router>

     {/* Navigation menu */}

          <Link to="/">Home</Link>

          <Link to="/about">About</Link>

          <Link to="/topics">Topics</Link>

      {/* Routes */}
      <Route exact path="/" component={Home} />
      <Route path="/about" component={About} />
      <Route path="/topics" component={Topics} />

  </Router>
);

These routes can also be dynamically-generated using an array of routes, such as the following (defined in your component state):
routes = [
  {
    path: "/",
    exact: true,
    component: Home
  },
  {
    path: "/bubblegum",
    component: () =>
bubblegum!
,

  },
  {
    path: "/shoelaces",
   component: Shoelaces
  }

and then rendered in React using .map():
{this.state.routes.map(route => (
  <Route exact={route.exact||false} path={route.path} component={route.component} />
))}

A: I think you need to install react-router-dom.
Second, please use template strings.


text:
Q: Using a SIM900a with Arduino uno to send GPS location to a server using GPRS I have been trying to do this for 2 days now. I am able to send the GPS lat,lang as a text message to a receiving number. However what i want now is to send this using GPRS. I am using a SIM900A GSM/GPRS module. I am a Software Engineering student and I'm quite new to Arduino. This is my code to use GSM.
#include <SoftwareSerial.h>
#include <TinyGPS.h>

TinyGPS gps;
SoftwareSerial ss(5, 6);

static void smartdelay(unsigned long ms);

void setup()
{
  Serial.begin(115200);
  ss.begin(9600);
}

void loop()
{
  float flat, flon;
  unsigned long age, date, time, chars = 0;
  unsigned short sentences = 0, failed = 0;

  gps.f_get_position(&flat, &flon, &age);
  sendLatLang(flat, flon);

  gps.stats(&chars, &sentences, &failed);
  Serial.println();

  smartdelay(1000);
}

static void smartdelay(unsigned long ms)
{
  unsigned long start = millis();
  do
  {
    while (ss.available())
      gps.encode(ss.read());
  } while (millis() - start < ms);
}

static void sendLatLang(float lat, float lang)
{
  if (lat == TinyGPS::GPS_INVALID_F_ANGLE || lang == TinyGPS::GPS_INVALID_F_ANGLE) {
Serial.println("Searching for GPS fix...");
  } else {
    Serial.println("AT+CMGF=1");
    delay(1000);
    Serial.println("AT+CMGS=\"+94123445678\"");
    delay(1000);
    Serial.print("Latittude : ");
    Serial.println(lat);
    Serial.print("Longitude : ");
    Serial.println(lang);
    Serial.write(26);
    delay(1000);
  }
}

A: First, SoftwareSerial is very, very inefficient.  It disables interrupts for long periods of time, which interferes with other parts of your sketch.
To summarize this answer:

*

*AltSoftSerial is best, but it only works on pins 8 & 9 (on an UNO).

*NeoSWSerial is next best.  It works on any two pins, but it only supports baud rates 9600, 19200 and 38400

Second, your because your program talks to two devices, you have to be careful about using delay or "blocking" at any part of your program.  While the program is "stuck" at a delay, nothing else is being processed.  GPS characters continue to come in, and they will eventually overflow the input buffer (64 char limit).  The smartDelay function tries to work around that.
You should use a Finite-state Machine to handle the sending, without calling delay.  Every time through loop, the FSM will check to see if it's time to do the next step.  This is very easy to implement with a switch statement and a case for each "step" of the sending process (i.e., the current "state").
This allows loop to constantly handle all the GPS characters, even though the FSM is "waiting" for some time to elapse.  The FSM isn't using delay, it is constantly checking millis() to see if the time has elapsed.  It checks once per loop.
I would also recommend using my NeoGPS library.  It is smaller, faster and more accurate than all other libraries, and it can be configured to parse only the fields and NMEA messages that you really use.  If you'd like to try it, it is available from the Arduino IDE menu Sketch -> Include Library -> Manage Libraries.
Here is a NeoGPS version of your sketch:
#include <NeoSWSerial.h>
#include <NMEAGPS.h>

NMEAGPS gps;
NeoSWSerial gps_port(5, 6);

enum state_t { WAITING_TO_SEND, SENDING_CMD1, SENDING_CMD2 }; // valid FSM states
state_t  state;     // current FSM state
uint32_t stateTime; // FSM timer for delays between states

bool     newData = false; // true when a fix with a location is ready
gps_fix  fixToSend;
const uint32_t SEND_INTERVAL = 60 * 1000UL; // once a minute

void setup()
{
  Serial.begin(115200);
  gps_port.begin(9600);
}

void loop()
{
  // Always process GPS characters so the latest fix is ready to go
  while (gps.available( gps_port )) {
    gps_fix newFix = gps.read();

    if (newFix.valid.location) {
      newData   = true;
      fixToSend = newFix;
    }
  }

  // FSM for sending fixes
  switch (state) {

    case WAITING_TO_SEND:
      //  Don't send new data too often.
      if (newData && (millis() - stateTime >= SEND_INTERVAL)) {
        Serial.println( F("AT+CMGF=1") );
        stateTime = millis();
        state     = SENDING_CMD1;
      }
      break;

    case SENDING_CMD1:
      //  Delay 1 second after the CMGF command
      if (millis() - stateTime >= 1000) {
        Serial.println( F("AT+CMGS=\"+94123445678\"") );
        stateTime = millis();
        state     = SENDING_CMD2;
      }
      break;

    case SENDING_CMD2:
      //  Delay 1 second after the CMGS command...
      if (millis() - stateTime >= 1000) {
        // ... then send the message
        sendFix( fixToSend );
        Serial.write(26); // no more data to send

        newData   = false;
        stateTime = millis();
        state     = WAITING_TO_SEND;
      }
      break;
  }
}

static void sendFix( const gps_fix &fix )
{
  //  Send only the fix pieces of interest
  //    (other pieces described on Data Model page)

  Serial.print( F("Latitude : ") );
  Serial.println( fix.latitude(), 6 );
  Serial.print( F("Longitude : ") );
  Serial.println( fix.longitude(), 6 );
}

Your original program used 8896 bytes of program space and 564 bytes of RAM.
The NeoGPS version uses 8562 bytes of program space and 364 bytes of RAM.
Even if you don't use NeoGPS, be sure to read the Troubleshooting page.  It describes many common problems, which are usually related to program structure and timing.
P.S.  Notice that the F macro is used on "double-quoted" string constants... this saves RAM by forcing them to be used from FLASH memory.  The sketch also has a SENDING_INTERVAL to avoid sending lat/long messages every second.  :P


text:
Q: Extracting classes that extend "Randomizer" from all jarfiles in the classpath The subject really says my goal, but I'm stumped as to the implementation. I have a program that takes in different objects that extend my Randomizer class. I want to make it so that one can place a JAR file in the classpath and the program will search for it upon running it, and add it to the main program. This is what I tried, so far, but I stopped when I realized that a java.util.jar.JarFile can't give you Classes or Methods.
since it relies on it, I might as well mention that my class ArrayPP<T> is like ArrayList, but with alot more methods. Its addAll method, shown here, functions like its add method, but with multiple arguments or an array of objects of generic type T.
  private static Randomizer[] loadExternalRandomizers() throws IOException
  {
    java.io.File classPath = new java.io.File(System.getProperty("user.dir"));
    ArrayPP<Randomizer> r = new ArrayPP<>();
    if (classPath.isDirectory())
    {
      r.addAll(getRandomizersIn(classPath));
    }
    return r.toArray();
  }

  private static Randomizer[] getRandomizersIn(File dir) throws IOException
  {
    ArrayPP<Randomizer> r = new ArrayPP<>();
    java.io.File fs[] = dir.listFiles(new java.io.FileFilter() {

      @Override
      public boolean accept(File pathname)
      {
        return pathname.isDirectory() || pathname.toString().endsWith(".jar");
      }
    });
    java.util.jar.JarFile jr;
    java.util.Enumeration<java.util.jar.JarEntry> entries;
    java.util.jar.JarEntry thisEntry;
    for (java.io.File f : fs)
    {
      if (f.isDirectory())
      {
        r.addAll(getRandomizersIn(f));
        continue;
      }
      jr = new java.util.jar.JarFile(f);
      entries = jr.entries();
      while (entries.hasMoreElements())
      {
        thisEntry = entries.nextElement();
        //if (the jar file contains a class that extends Randomizer
        //  add that class to r
      }
    }
    return r.toArray();
  }

I'm building it on Java 7, if that helps. I'm also looking to do this without using any libraries.
Implementing a solution

I've tried implementing the solution described by Ryan Stewart, and it is shown below. I'm working it with a test JAR called BHR2 - Ranger.jar, which contains one class that extends Randomizer, called Ranger, in the package bhr2.plugins. The JAR contains, within its META-INF\services folder, one file called bhr2.plugins.Ranger with one line in it which reads bhr2.Randomizer    # Abstract Randomizer.
  private static ArrayPP<Randomizer> loadExternalRandomizers() throws IOException, ClassNotFoundException, InstantiationException, IllegalAccessException
  {
    java.io.File classPath = new java.io.File(System.getProperty("user.dir"));
    ArrayPP<Randomizer> r = new ArrayPP<>();
    if (classPath.isDirectory())
    {
      r.addAll(getRandomizersIn(classPath));
    }
    return r;
  }

  private static int depth = 0;
  private static ArrayPP<Randomizer> getRandomizersIn(File dir) throws IOException, ClassNotFoundException, InstantiationException, IllegalAccessException
  {
    ArrayPP<Randomizer> r = new ArrayPP<>();
    java.io.File fs[] = dir.listFiles(new java.io.FileFilter() {

      @Override
      public boolean accept(File pathname)
      {
        return pathname.isDirectory() || pathname.toString().endsWith(".jar");
      }
    });
    for (java.io.File f : fs)
    {
      for (int i=0; i < depth; i++)
        System.out.print("  ");
      System.out.println(f);
      if (f.isDirectory())
      {
        if (depth < 4)
        {
          depth++;
          r.addAll(getRandomizersIn(f));
          depth--;
        }
        else
          System.out.println("Skipping directory due to depth");
        continue;
      }
        java.util.ServiceLoader<Randomizer> sl = ServiceLoader.loadInstalled(Randomizer.class);

        for (Randomizer rand : sl)
        {
          r.add(rand);
          System.out.println("adding " + rand);
        }
    }
    return r == null || r.isEmpty() ? new ArrayPP<Randomizer>() : r;
  }

But when I run it, this is all I get as an output before it starts doing other things:
I:\Java\NetBeansProjects\BHRandomizer2\nbproject
  I:\Java\NetBeansProjects\BHRandomizer2\nbproject\private
I:\Java\NetBeansProjects\BHRandomizer2\src
  I:\Java\NetBeansProjects\BHRandomizer2\src\bhr2
    I:\Java\NetBeansProjects\BHRandomizer2\src\bhr2\resources
    I:\Java\NetBeansProjects\BHRandomizer2\src\bhr2\randomizers
  I:\Java\NetBeansProjects\BHRandomizer2\src\bht
    I:\Java\NetBeansProjects\BHRandomizer2\src\bht\test
    I:\Java\NetBeansProjects\BHRandomizer2\src\bht\tools
      I:\Java\NetBeansProjects\BHRandomizer2\src\bht\tools\comps
        I:\Java\NetBeansProjects\BHRandomizer2\src\bht\tools\comps\gameboard
Skipping directory due to depth
      I:\Java\NetBeansProjects\BHRandomizer2\src\bht\tools\effects
      I:\Java\NetBeansProjects\BHRandomizer2\src\bht\tools\misc
      I:\Java\NetBeansProjects\BHRandomizer2\src\bht\tools\utilities
    I:\Java\NetBeansProjects\BHRandomizer2\src\bht\resources
I:\Java\NetBeansProjects\BHRandomizer2\lib
  I:\Java\NetBeansProjects\BHRandomizer2\lib\CopyLibs
    I:\Java\NetBeansProjects\BHRandomizer2\lib\CopyLibs\org-netbeans-modules-java-j2seproject-copylibstask.jar
  I:\Java\NetBeansProjects\BHRandomizer2\lib\swing-layout
    I:\Java\NetBeansProjects\BHRandomizer2\lib\swing-layout\swing-layout-1.0.4.jar
I:\Java\NetBeansProjects\BHRandomizer2\BHR2 - Ranger
  I:\Java\NetBeansProjects\BHRandomizer2\BHR2 - Ranger\META-INF
  I:\Java\NetBeansProjects\BHRandomizer2\BHR2 - Ranger\bhr2
    I:\Java\NetBeansProjects\BHRandomizer2\BHR2 - Ranger\bhr2\plugins
I:\Java\NetBeansProjects\BHRandomizer2\build
  I:\Java\NetBeansProjects\BHRandomizer2\build\classes
    I:\Java\NetBeansProjects\BHRandomizer2\build\classes\bhr2
      I:\Java\NetBeansProjects\BHRandomizer2\build\classes\bhr2\randomizers
      I:\Java\NetBeansProjects\BHRandomizer2\build\classes\bhr2\resources
    I:\Java\NetBeansProjects\BHRandomizer2\build\classes\bht
      I:\Java\NetBeansProjects\BHRandomizer2\build\classes\bht\tools
        I:\Java\NetBeansProjects\BHRandomizer2\build\classes\bht\tools\comps
Skipping directory due to depth
        I:\Java\NetBeansProjects\BHRandomizer2\build\classes\bht\tools\utilities
Skipping directory due to depth
        I:\Java\NetBeansProjects\BHRandomizer2\build\classes\bht\tools\effects
Skipping directory due to depth
        I:\Java\NetBeansProjects\BHRandomizer2\build\classes\bht\tools\misc
Skipping directory due to depth
      I:\Java\NetBeansProjects\BHRandomizer2\build\classes\bht\resources
      I:\Java\NetBeansProjects\BHRandomizer2\build\classes\bht\test
    I:\Java\NetBeansProjects\BHRandomizer2\build\classes\META-INF
  I:\Java\NetBeansProjects\BHRandomizer2\build\empty
  I:\Java\NetBeansProjects\BHRandomizer2\build\generated-sources
    I:\Java\NetBeansProjects\BHRandomizer2\build\generated-sources\ap-source-output
I:\Java\NetBeansProjects\BHRandomizer2\dist
  I:\Java\NetBeansProjects\BHRandomizer2\dist\BHRandomizer2.jar
I:\Java\NetBeansProjects\BHRandomizer2\BHR2 - Ranger.jar

A: A typical solution to this problem is to build jar files that have a file in META-INF that tells your program what class(es) to load from that jar. Spring custom namespace handlers and JDBC drivers, for example, are loaded in this way.
Instead of figuring out how to actually scan all the classes in a jar, which nobody does, so I expect isn't possible/feasible, make your code look for a specific file in each jar on the classpath which lists the Randomizer implementations it contains. For instance, expect a file named META-INF/randomizers.list to have a list of class names, one per line, which are classes in that jar that implement your Randomizer. Read the file, and for each line, use Class.forName() to load the class by name, then newInstance() to instantiate it.
Edit: For loading your "list" file from everywhere in the classpath:
Enumeration<URL> resources = getClassLoader().getResources(
    "/META-INF/randomizers.list");
while (resources.hasMoreElements()) {
    URL url = resources.nextElement();
    // Load the Randomizer(s) specified in this file
}

Edit: So it turns out the JDK exposes the mechanism it uses for this kind of thing, which I didn't know about before. Just use a ServiceLoader. The docs explain how to use it, and I've coded up an example of how to use it, too. You can find the code on github or simply clone and run it yourself:
git clone git://github.com/zzantozz/testbed.git tmp
cd tmp
mvn install -pl serviceloader-example/service-usage -am
mvn -q exec:java -D exec.mainClass=rds.serviceloader.ServiceLoaderExample -pl serviceloader-example/service-usage

The example consists of five modules: one that defines a service interface, three that define separate service implementations, and one that loads the implementations using ServiceLoader. That last is called "service-usage" and demonstrates how to use the ServiceLoader class to load the three services defined in the other three modules/jars that implement the interface defined in the first module/jar.
Edit: Since you seem to be having trouble with the sample project, here are the basics.

*

*Each jar file that contains one or more Randomizer implementations should contain a file named META-INF/services/com.foo.Randomizer (where com.foo is your package name).

*This file should contain a list of class names, one per line, each of which is an implementation of Randomizer.

*With those files in place, all you have to do to get all the Randomizer instances is
ServiceLoader<Randomizer> loader = ServiceLoader.load(Randomizer.class);
for (Randomizer randomizer : loader) {
    randomizer.doWhatever();
}

A: Fetching the class list from the Manifest is of course the preferable solution. But if you don't expect the jars to contain such information, you can fall back to this:
  private static void scanClasses(File file) throws MalformedURLException, IOException {
    ClassLoader classLoader = new URLClassLoader(new URL[]{ file.toURI().toURL() });
    JarFile jar = new JarFile(file.getAbsoluteFile());
    Enumeration<JarEntry> jarEntries = jar.entries();
    while (jarEntries.hasMoreElements()) {
      JarEntry je = jarEntries.nextElement();
      if (je.getName().endsWith(".class")) {
        String clazzName = je.getName();
        clazzName = clazzName.substring(0, clazzName.length() - ".class".length()).replaceAll("/", ".");
        clazzName = clazzName.replaceAll("/", ".");
        try {
          Class clazz = Class.forName(clazzName, false, classLoader);
          if (Randomizer.class.isAssignableFrom(clazz)) {
            System.out.println("Found Randomizer: " + clazz);
          }
        } catch (ClassNotFoundException ex) {
          // this really should not happen,
          // since we *know* the class exists
          throw new AssertionError(ex.getMessage());
        }
      }
    }
  }

A: Here here is the code I am using to retrieve all the classes belonging to a package and any sub-packages. You just need to search the list of returned classes for those implementing Randomizer using reflection.
/**
 * Scans all classes accessible from the context class loader which belong
 * to the given package and subpackages.
 * <p>
 * Inspired from post on: {@code http://snippets.dzone.com/posts/show/4831}
 */
public static List<Class<?>> getClasses(String packageName)
        throws ClassNotFoundException, IOException {

    // Retrieving current class loader
    final ClassLoader classLoader
            = Thread.currentThread().getContextClassLoader();

    // Computing path from the package name
    final String path = packageName.replace('.', '/');

    // Retrieving all accessible resources
    final Enumeration<URL> resources = classLoader.getResources(path);
    final List<File> dirs = new ArrayList<File>();

    while (resources.hasMoreElements()) {
        final URL resource = resources.nextElement();
        final String fileName = resource.getFile();
        final String fileNameDecoded = URLDecoder.decode(fileName, "UTF-8");
        dirs.add(new File(fileNameDecoded));
    }

    // Preparing result
    final ArrayList<Class<?>> classes = new ArrayList<Class<?>>();

    // Processing each resource recursively
    for (File directory : dirs) {
        classes.addAll(findClasses(directory, packageName));
    }

    // Returning result
    return classes;

}

/**
 * Recursive method used to find all classes in a given directory and
 * subdirs.
 */
public static List<Class<?>> findClasses(File directory, String packageName)
        throws ClassNotFoundException {

    // Preparing result
    final List<Class<?>> classes = new ArrayList<Class<?>>();

    if ( directory == null )
        return classes;

    if (!directory.exists())
        return classes;

    // Retrieving the files in the directory
    final File[] files = directory.listFiles();

    for (File file : files) {

        final String fileName = file.getName();

        // Do we need to go recursive?
        if (file.isDirectory()) {

            classes.addAll(findClasses(file, packageName + "." + fileName));

        } else if (fileName.endsWith(".class") && !fileName.contains("$")) {

            Class<?> _class;

                _class = Class.forName(packageName + '.'
                        + fileName.substring(0, fileName.length() - 6));

            classes.add(_class);

        }

    }

    return classes;

}

A: I think you should stick with the java ServiceLoader. Then you don't need to fiddle with jars yourself.
Here's a good tutorial:
http://java.sun.com/developer/technicalArticles/javase/extensible/index.html
If your developing an extensible desktop application the netbeans platform might be the right solution for you. It has a higher learning curve but it is quite worth it.
http://netbeans.org/features/platform/index.html


text:
Q: Container running on ACI on a VNET is unable to reach internet addresses (Outbound connections) We have a container running via ACI on a VNET that recently has stopped being able to reach internet addresses (google.com, Azure SQL Databases, etc). I have brought up several other containers in the VNET as well as in brand new VNETS that are created by the "az container create" command and they all display the same behavior. I have tested with stock ubuntu, and alpine images (in addition to our original custom image), and have even tried Microsoft's Hello World image. In every instance (every vnet and region I have tried them in) ping to any external address fails (but internal addresses don't), but DNS does resolve. We get the following network interfaces (with the eth0 getting a VNET/Subnet local address)
eth0      Link encap:Ethernet  HWaddr 36:57:E0:61:78:DF
          inet addr:10.202.94.4  Bcast:0.0.0.0  Mask:255.255.255.0
          inet6 addr: fe80::3457:e0ff:fe61:78df/64 Scope:Link
          UP BROADCAST RUNNING  MTU:1500  Metric:1
          RX packets:12 errors:0 dropped:0 overruns:0 frame:0
          TX packets:12 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:936 (936.0 B)  TX bytes:936 (936.0 B)
eth1      Link encap:Ethernet  HWaddr C2:DB:44:D5:48:5D
          inet addr:169.254.0.4  Bcast:0.0.0.0  Mask:255.255.0.0
          inet6 addr: fe80::c0db:44ff:fed5:485d/64 Scope:Link
          UP BROADCAST RUNNING  MTU:1500  Metric:1
          RX packets:50 errors:0 dropped:0 overruns:0 frame:0
          TX packets:30 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:3835 (3.7 KiB)  TX bytes:2392 (2.3 KiB)
lo        Link encap:Local Loopback
          inet addr:127.0.0.1  Mask:255.0.0.0
          inet6 addr: ::1/128 Scope:Host
          UP LOOPBACK RUNNING  MTU:65536  Metric:1
          RX packets:0 errors:0 dropped:0 overruns:0 frame:0
          TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:0 (0.0 B)  TX bytes:0 (0.0 B)

We get the following route table (again vnet specific on eth0)
default via 169.254.0.1 dev eth1
10.0.0.0/8 via 10.202.94.1 dev eth0
10.202.94.0/24 dev eth0  src 10.202.94.4
169.254.0.0/16 dev eth1  src 169.254.0.4
172.16.0.0/12 via 10.202.94.1 dev eth0
192.168.0.0/16 via 10.202.94.1 dev eth0

and the result of traceroute is as follows for google and one of our databases
/ # traceroute google.com
traceroute to google.com (216.58.193.78), 30 hops max, 46 byte packets
 1  169.254.0.1 (169.254.0.1)  0.007 ms  0.008 ms  0.005 ms
 2  *

# traceroute [ourdb].database.windows.net
traceroute to [ourdb].database.windows.net (xxx.xx.xxx.xxx), 30 hops max, 46 byte packets
 1  169.254.0.1 (169.254.0.1)  0.008 ms  0.008 ms  0.005 ms
 2  *  *  *
 3  *  *  *
 4  *

An example of what I used to auto create a vnet with an instance on it.
az container create --resource-group rg-dev-aci --image alpine:latest --vnet vnet-dev-aci-east2  --subnet subnet-aci --subscription [my subscription id] --name test-alpine-networking-autovnet --command-line "tail -f /dev/null" --location "East US 2" --vnet-address-prefix 10.201.0.0/16 --subnet-address-prefix 10.201.94.0/24

It seems like something has changed with ACI (on VNET?) network configuration or something else with ACI. I know it is a preview feature of ACI, but I would not think that containers running in a VNET would be prevented from connecting to internet addresses.
Anyone have any ideas on what we could be doing wrong or what we could do to change things (like the default route's gateway). Is anyone else seeing the same issues?


text:
Q: vue-router navigate to the same route and re-run mounted hook How can I naviagte to the current route using router-link and re-run mounted hook?
HTML

    <router-link :to="{ name: 'home' }" exact>Home</router-link>
       <router-link :to="{ name: 'about' }" @click.native.prevent="router.push({ name: 'about' })">About</router-link>

  <router-view :key="$route.fullPath"></router-view>

JS
console.clear()
console.log('Yes! We are using Vue version', Vue.version)

Vue.use(VueRouter)

const Home = {
    template: `<h1>Home</h1>`,
}

const About = {
    template: `<h1>{{new Date()}}</h1>`,
  mounted(){
    console.log('mounted')
  }
}
const routes = [
    { path: '/', name: 'home', component: Home },
  { path: '/about', name: 'about', component: About },
]
const router = new VueRouter({
    routes,
})
// New VueJS instance
var app = new Vue({
    // CSS selector of the root DOM element
  el: '#app',
  // Inject the router into the app
  router,
})

In the above example, if I navigate to 'About' it shows the timestamp from new Date and logs 'mounted'. However, if I'm already on /about, clicking the about link does nothing. I want to re-run the whole component lifecycle when clicking 'About', even if I'm already hit it.

A: You'll need to change the key in the <router-view> element whenever the user clicks your about page, that will force the mounted hook:
<template>

    <router-link @click.native="updateViewKey" :to="{ name: 'about' }">About</router-link>

    <router-view :key="viewKey"></router-view>

</template>

A: Try this :
router.push({
    name: 'routeName',
    params: {
        id: 'new value'
    }
})


text:
Q: BNE - I type instruction - Where does 'i' come into play? I am trying to understand assembly a little better, and I am not really sure how the i (immediate) comes into play for BNE. Please forgive the noobness.
If BNE writes like this:
BNE $1, $2, loop

which means "goto loop if $1 does not equal $2" then I am assuming that the loop is the immediate part. Correct?
Is this just a program counter or a location of the loop? So, if the loop was set at some instruction count (let's just call it 0x0001), would this loop address (or instruction count) be set in this i?
Maybe it would be better if I wrote it out like this...
opcode  = 5 | reg1 = whatever addr | reg2  = whatever addr | immediate = 0x0001

Does that look right, or am I just really confused?

A: the assembler takes the address loop (that is really what it is a name for some address somewhere) it does the work for you to compute the offset, and encodes that offset into the instruction for you.  Otherwise you would have to say bne $1, $2, +28, hand computed number and then every time you modify your code between these two points you would have to re-adjust every one of these offsets.
Some assemblers or linkers actually, may go so far as to add a trampoline for you.  Say for example you have some instruction set that the relative jump is only 128 instructions, and you use a label that is not defined in that object.  The assembler might be so kind as to place an unconditional branch within 128 instructions to the place you really wanted to go.  some might not and you end up with an error that it cannot encode the offset in the instruction you asked for.
where I am headed is that you program with labels (addresses) and let the assembler do some of the work for you.  As in this case it converts the label you have to a distance from the current instruction and encodes that.


text:
Q: Typescript Alert showing multiple times when not needed I am trying to get the button to do a single alert when the button is clicked, but the button odes something strange:

The first time I click the Login Button, the alert shows once, when I click it again the alert shows 2 times, then I click the button a 3rd time, the alert shows 3 times.
After that, If I were to click the Forgot Password Button, the alert assigned to Forgot password would show 4 times.

I am very confused as to why this happens and how to fix it?

.ts

class LoginTs{
    username: string;
    password: string;

    constructor(username: string, password: string ) {
        this.username = username;
        this.password = password;

        let submitBtn = document.getElementById("enter")
        submitBtn.addEventListener("click", (e: Event) => {
            return LoginTs.validateInput(this.username,this.password)
        });

        let forgotBtn= document.getElementById("forgotPass")
        forgotBtn.addEventListener("click",(e:Event) =>LoginTs.forgotPassword());
    }

    private static validateInput(username: string, password: string) {
        if(username =="billy" && password =="bronco1"){
            return alert("success")
        }
        else{
            return alert("wrong username or password")
        }
    }

    private static forgotPassword() {
        return alert("tough luck lmao")
    }
}

document.getElementById("enter").addEventListener("click", function() {
    let iUser =(document.getElementById("se") as HTMLInputElement).value;
    let iPass =(document.getElementById("sp") as HTMLInputElement).value;
    let loginTs = new LoginTs(iUser,iPass);
})

.html

    <TITLE>Capstone Typescript Login</TITLE>

Billy Bronco's Grading Calculator

Log in

        <link rel="stylesheet" href="Login.css">

Sign in

            <input id="se" type="email" placeholder="Email" required/>
            <input id="sp" type="password" placeholder="Password" required/>

            <input type="button" class="button" id="enter" value="Login">
            <input type="button" class="button" id="forgotPass" value="Forgot Password?">
             Don't have an account? CLICK HERE

Thank You!

A: You are setting up new event listeners in your constructor every time the enter button is clicked. They're compounding on top of each other. Additionally, you're setting the username and password values at the wrong time. They should be set when the user tries to validate their input (clicks the submit button). The constructor should be instantiated after the html and script have loaded, eg. in a window.onload event
window.onload = function() {
    let loginTs = new LoginTs();
}

Here is your class with a couple changes. The username and password variables aren't set until the user clicks the button, since that is the point at which you want to capture them for validation.
class LoginTs{
    username: string;
    password: string;

    constructor( ) {
        // this.username = username;
        // this.password = password;

        let submitBtn = document.getElementById("enter")
        submitBtn.addEventListener("click", (e: Event) => {
            this.username =(document.getElementById("se") as HTMLInputElement).value;
            this.password =(document.getElementById("sp") as HTMLInputElement).value;

            return LoginTs.validateInput(this.username,this.password)
        });

        let forgotBtn= document.getElementById("forgotPass")
        forgotBtn.addEventListener("click",(e:Event) =>LoginTs.forgotPassword());
    }

    private static validateInput(username: string, password: string) {
        if(username =="billy" && password =="bronco1"){
            return alert("success")
        }
        else{
            return alert("wrong username or password")
        }
    }

    private static forgotPassword() {
        return alert("tough luck lmao")
    }
}

window.onload = function() {
        let loginTs = new LoginTs();
    }