text:
Q: AngularJS loading page with unrelated data from controller (2 GETS or only 1?) I have a page, rendered by an angularjs controller, that shows the details of a user on page load.
This list is given by the controller of Spring:
@RequestMapping(value = "/contact/{id}", method = RequestMethod.GET, headers = "Accept=application/json")
public User getContact(@PathVariable String id) {
    User user = userService.findById(id);
    return user;
}

Which is requested by angularjs inside a details controller:
$http.get(urlBase+'/contact/'+$routeParams.userid).success(function(data) {
    $scope.user = data;
});

Now I also want to show, on the same page, other details such as whether the visitor on that page is friends with that user. This information should be loaded while the page loads (same as retrieving the details of the user)
Should I use a separate get method to do this kind of check and put it under the first get method for example? E.g.
@RequestMapping(value = "/isFriends/{userId}",  method = RequestMethod.GET, headers = "Accept=application/json")
@ResponseBody
public RETURNWHAT loadProfile(@PathVariable String userId, RequestParameter request) {
    /*
     * Do some checks whether a user is friends with the user on the page.
     */
     request.setParameter("isFriends", true); //Perhaps not a good idea to use set parameter to retrieve this inside the angularjs' controller?
}

Other get:
$http.get(urlBase+'/isFriends/' + $routeParams.userid).success(function(data) {

});

Or is there a better way to achieve this?
I thought of only calling 1 get method that retrieves this information from 1 method in the controller. But then I assume that the controller has to send back a map with all the details.
Edit:
I believe using 1 method in the controller of Spring which returns a Map<String, Object> and 1 get function in angularjs should be the best option, am I correct?

A: Actually is a trade off between no of http requests and amount data being sent back from server, so as specific to your user case, its just one field you want, piggybacking to existing response is better way than making two requests.

A: I agree with @vinayakj that it is more efficient to combine the data in one HTTP request (less server load, less bandwidth). Definitely makes sense if you expect alot of these requests. But instead of adding the "isFriends" information to User, I'd wrap both in an "aggregate" object:
class UserDetails {
    User user;
    boolean isFriends;
}

The resulting JSON might look like this:
{
    user: {
        id: 1,
        name: "abc"
    },
    isFriend: true
}

Why not just adding "isFriends" to User? Because what we are doing here is solely a webservice performance optimization. It should not make your model less maintainable.
Why not Map<String, Object>? Those maps are pretty generic - it would be harder to see which response contains which kind of data. A dedicated class adds type-safety and documentation. Also, you may want to annotate the components separately.
The obvious drawback is that you need to create extra classes with somewhat funny names.


text:
Q: How can I use json column type in Rails MySQL app? Because of server requirements, I'm using MySQL 5.5 in my Rails app.
I would like to use json column type, similar to PostgreSQL, but when I run migration I'm getting error, that json is not supported.
My migration:
def change
    add_column :profile_services, :price, :json
end

Can somebody suggest the best solution how to fix this issue?

A: Since MySQL 5.5 doesn't have JSON data type, in a Rails 4 app, you should use the more database agnostic TEXT type that will work in both MySQL and PostgreSQL.
def change
    add_column :profile_services, :price, :text
end

As of MySQL 5.7.8, the JSON column type has been added.
https://dev.mysql.com/doc/refman/5.7/en/json.html
As of Rails 5, MySQL JSON type has been added.
https://github.com/rails/rails/pull/21110

redpajama_set_name: RedPajamaStackExchange


text:
Q: Rails creating duplicate record I am trying to learn using rails. I was following http://guides.rubyonrails.org/getting_started.html
I added the associated model. but when I create the new event..it also duplicates it.
class EventsController < ApplicationController

def create
    @category = Category.find(params[:category_id])
    @event = @category.events.create(event_params)

    redirect_to category_path(@category)
end

def destroy
    @category = Category.find(params[:category_id])
    @event = @category.events.find(params[:id])
    @event.destroy
    redirect_to category_path(@category)
end
private
def event_params
    params.require(:event).permit(:event, :genus, :description)
end

end
Here is model :
class Event < ActiveRecord::Base
  belongs_to :category

end

Here is the form I am using to save event in the particular category:
<%= form_for ([@category, @category.events.build]) do |f| %>

    <%= f.label :name %>

    <%= f.text_field :event %>

    <%= f.label :genus %>

    <%= f.text_field :genus %>

    <%= f.label :description %>

    <%= f.text_area :description %>

    <%= f.submit %>

This is the show view code :

Title:
  <%= @category.name %>

  Text:
  <%= @category.key %>

Events

<%= render @category.events %>

    Add Event

<%= render 'events/form' %>

<%= link_to 'Back', categories_path %>

Thing is when i create record..it creates duplicate entry and
delete record it deletes both entries.
I cant figure out whats wrong with my code. I just followed the guide..

A: Ok, I found out what was wrong. It was    <% @category.events.each do |event| %> line in _event.html.erb It was creating duplicate views.
Thanks everyone for help
<% @category.events.each do |event| %>

    Event Name:
    <%= event.name %>

    Genus:
    <%= event.genus %>

    Description:
    <%= event.description %>

    <%= link_to 'Destroy Event', [event.category, event], method: :delete, data: {confirm: 'Are you sure?'} %>

<% end >

It should be like this :

    Event Name:
    <%= event.name %>

    Genus:
    <%= event.genus %>

    Description:
    <%= event.description %>

    <%= link_to 'Destroy Event', [event.category, event], method: :delete, data: {confirm: 'Are you sure?'} %>

What I understand is that  when    <%= render @category/events %> redirects to this page.
It was querying for data two times.
Correct me if i am not right?
but i dont understand why was this generating duplicate records?


text:
Q: Integration by parts - wondering what I did wrong Looking for help in solving a certain integral by parts:
$$ \int x^2 e^{-x} \, dx  $$
What I did was:
$$ u = x^2 \text{ and } dv = e^{-x} \, dx$$
along with
$du=2x \, dx$ and $v = -e^{-x}$
The integral then would be $ \int x^2 e^{-x} \, dx = -x^2e^{-x} - \int -2xe^{-x} \, dx$
I simplified it to $-x^2e^{-x} - x^2e^{-x} + C$
My final answer was $-2^2e^{-x} +C$
and the book's answer is $-(x^2 + 2x + 2)e^{-x} + C$
I'm not entirely sure what I did wrong, hopefully somebody can point it out to me!

A: You already have $$\int x^2e^{-x}dx = -x^2e^{-x} + 2\int xe^{-x}dx.$$
Now, you can continue $$\int xe^{-x}dx = -xe^{-x} + \int e^{-x}dx = -xe^{-x} - e^{-x}.$$
From this, you can get the final answer.


text:
Q: Why scalar in braces are not interpeted as initializer_list Consider the following code snippet:
#include <iostream>
#include <initializer_list>

struct C
{
    C(std::initializer_list<int>) { std::cout << "list\n"; }
    C(std::initializer_list<int>, std::initializer_list<int>) { std::cout << "twice-list\n"; }
};

int main()
{
    C c1 { {1,2}, {3} }; // twice-list ctor
    C c2 { {1}, {2} }; // why not twice-list ?
    return 0;
}

Live demo.
Why scalar values in braces for c2 variable are not interpreted as separate std::initializer_list?

A: First, something very important: You have two different kinds of constructors. The first in particular, C(std::initializer_list<int>), is called an initializer-list constructor. The second is just a normal user-defined constructor.
[dcl.init.list]/p2

A constructor is an initializer-list constructor if its first parameter is of type std::initializer_list<E> or reference to possibly cv-qualified std::initializer_list<E> for some type E, and either there are no other parameters or else all other parameters have default arguments (8.3.6).

In a list-initialization containing one or more initializer-clauses, initializer-list constructors are considered before any other constructors. That is, initializer-list constructors are initially the only candidates during overload resolution.
[over.match.list]/p1

When objects of non-aggregate class type T are list-initialized such that 8.5.4 specifies that overload resolution is performed according to the rules in this section, overload resolution selects the constructor in two phases:

*

*Initially, the candidate functions are the initializer-list constructors (8.5.4) of the class T and the argument list consists of the initializer list as a single argument.

*If no viable initializer-list constructor is found, overload resolution is performed again, where the candidate functions are all the constructors of the class T and the argument list consists of the elements
  of the initializer list.

So for both declarations of c1 and c2 the candidate set consists only of the C(std::initializer_list<int>) constructor.
After the constructor is selected the arguments are evaluated to see if there exists an implicit conversion sequence to convert them to the parameter types. This takes us to the rules for initializer-list conversions:
[over.ics.list]/p4 (emphasis mine):

Otherwise, if the parameter type is std::initializer_list<X> and all the elements of the initializer list can be implicitly converted to X, the implicit conversion sequence is the worst conversion necessary to convert an
  element of the list to X, or if the initializer list has no elements, the identity conversion.

This means a conversion exists if each element of the initializer list can be converted to int.
Let's focus on c1 for now: For the initializer-list {{1, 2}, {3}}, the initializer-clause {3} can be converted to int ([over.ics.list]/p9.1), but not {1, 2} (i.e int i = {1,2} is ill-formed). This means the condition for the above quote is violated. Since there is no conversion, overload resolution fails since there are no other viable constructors and we are taken back to the second phase of [over.match.list]/p1:

*

*If no viable initializer-list constructor is found, overload resolution is performed again, where the candidate functions are all the constructors of the class T and the argument list consists of the elements
  of the initializer list.

Notice the change in wording at the end. The argument list in the second phase is no longer a single initializer-list, but the arguments of the braced-init-list used in the declaration. This means we can evaluate the implicit conversions in terms of the initializer-lists individually instead of at the same time.
In the initializer-list {1, 2}, both initializer-clauses can be converted to int, so the entire initializer-clause can be converted to initializer_list<int>, the same for {3}. Overload resolution is then resolved with the second constructor being chosen.
Now let's focus on c2, which should be easy now. The initializer-list constructor is first evaluated, and, using { {1}, {2} } there surely exists a conversion to int from {1} and {2}, so the first constructor is chosen.

A: C c2 { {1}, {2} };
This line does not pass in two arguments of std::initializer_list<int>, but rather, it is passing in one std::initializer_list<std::initializer_list<int> >. A solution would be to instead instantiate c2 like so:
C c2({1}, {2});


text:
Q: NullPointerException when working with selenium-chrome-driver in Maven without ChromeDriver.exe Here is my LocalTestRunner class that contains method that getting WebDriver and also After and BeforeMethod which using it. But i am getting an error. This code i found on the github. I know that i this code can't find webdriver, should i write path to it?

java.lang.NullPointerException
        at dtapi.dtapiBase.LocalTestRunner.getDriver(LocalTestRunner.java:27)
        at dtapi.dtapiBase.LocalAdminTestRunner.loadSignInPage(LocalAdminTestRunner.java:18)
        at dtapiLoginTest.AdminPageTest.addRouter(AdminPageTest.java:47)

Class
public abstract class LocalTestRunner {
    public String url = "https://example.com";
    public String serverUrlLogout = "https://example.com";
    public String adminServerUrl = "https://example.com";

    public final Long ONE_SECOND_DELAY = 1000L;
    public Map<Long, WebDriver> drivers;
    protected WebDriver driver;
    public SoftAssert softAssert;

    public WebDriver getDriver() {
        WebDriver currentWebDriver = drivers.get(Thread.currentThread().getId());
        if (currentWebDriver == null) {
            currentWebDriver = new ChromeDriver();
            currentWebDriver.manage().window().maximize();
            currentWebDriver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
            drivers.put(Thread.currentThread().getId(), currentWebDriver);
        }
        return currentWebDriver;
    }

    @BeforeSuite
    public void beforeSuite() {
        WebDriverManager.chromedriver().setup();
    }

    @BeforeClass
    public void beforeClass(ITestContext context) {
        drivers = new HashMap<>();
        for (Map.Entry<String, String> entry : context.getCurrentXmlTest().getAllParameters().entrySet()) {
            if (entry.getKey().toLowerCase().equals("url")) {
                url = entry.getValue();
            }
            if (entry.getKey().toLowerCase().equals("serverUrlLogout")) {
                serverUrlLogout = entry.getValue();
            }
        }
    }

    @AfterClass(alwaysRun = true)
    public void afterClass() {
        for (Map.Entry<Long, WebDriver> currentWebDriver : drivers.entrySet()) {
            if (currentWebDriver.getValue() != null) {
                currentWebDriver.getValue().quit();
            }
        }
    }

    @BeforeMethod
    public void beforeMethod() {
        softAssert = new SoftAssert();
        getDriver().get(url);
    }

    @AfterMethod
    public void afterMethod(ITestResult result) {
        if (!result.isSuccess()) {
            System.out.println("***Test " + result.getName() + " ERROR");
            // Take Screenshot, save sourceCode, save to log, prepare report, Return to
            new ScreenShotHelper(getDriver()).keepPageSourceStatus();
            // previous state, logout, etc.
        }
        getDriver().get(serverUrlLogout);
        ApplicationStatus.get().setLogged(false);
    }

UPDATE
I have added some code in my pom.xml but it still isn't working
<configuration>
                    <installationDirectory>${project.build.directory}/test-classes</installationDirectory>
                    <!-- <installationDirectory>${project.basedir}/src/test/resources</installationDirectory>-->
                    <keepDownloadedWebdrivers>true</keepDownloadedWebdrivers>
                    <drivers>
                        <driver>
                            <name>chromedriver</name>
                            <!--suppress UnresolvedMavenProperty -->
                            <platform>${os.detected.name}</platform>
                            <!-- <platform>windows</platform> -->
                            <bit>32</bit>
                            <!-- <version>74.0.3729.6</version> -->
                            <!-- <url>https://chromedriver.storage.googleapis.com/74.0.3729.6/chromedriver_win32.zip</url> -->
                            <!-- <version>76.0.3809.126</version> -->
                            <!-- <url>https://chromedriver.storage.googleapis.com/76.0.3809.126/chromedriver_win32.zip</url> -->
                            <!--                            <url>https://chromedriver.storage.googleapis.com/79.0.3945.36/chromedriver_win32.zip</url> -->
                            <url>https://chromedriver.storage.googleapis.com/80.0.3987.106/chromedriver_win32.zip</url>

                        </driver>
                    </drivers>
                </configuration>

Where should  test-classes directory be located? under src directory in my project?
installationDirectory>${project.build.directory}/test-classes</installationDirectory>


text:
Q: Compilation and Output issues in Visual Studio Code (C++) I am a beginner in C++ and I'm still a huge noob. My current problem with Visual Studio Code is that, unlike in Python or Linux bash, I do not see the output of my C++ program anywhere. I downloaded a compiler (I'm sure I downloaded several ones that I can't remember, but clang is definitely there) and I can see the output window that shows this when I press CTRL+Alt+N (Run Code) in a Hello, world! program:
    [Running] cd "c:\Users\<USER>\Desktop\" && g++ main.cpp -o main && "c:\Users\<USER>\Desktop\"main
    'g++' is not recognized as an internal or external command, operable program or batch file.
    [Done] exited with code=1 in 0.076 seconds.

I have so many questions...

*

*First of all, why g++? I tried downloading GNU before and it DID NOT WORK
for some reason. Why g++ now? I have clang. Why does it even mention
g++ when it's apparently compiling without problems in the Problems
tab? I don't get this...

*When I press F5 (Start Debugging), I get
a pop up menu with two options: C++ (GDB/LLDB) and C++ (Windows).
None of them work, when I press on them a new tab called
settings.json opens with the follpwing text:
{
    "workbench.colorTheme": "Solarized Dark",
    "C_Cpp.default.compilerPath": "D:\\Programs\\LLVM\\bin"
}

Why does this tab even open and why do I get no output?

*Back to the main problem, where can I see the output of my program? By output I mean seeing "Hello, World!" when I write and compile a Hello World program and not just [Done] executed in blah blah seconds. It is definitely not in the output tab and I am so confused I don't know where to find it or if it even exists in Visual Studio Code. I am sorry I'm still a big noob and have stupid questions, but could someone ELI5 to me what the problem is?


text:
Q: Link to another workbook using conditional formatting in Excel How can i use conditional formatting to extract data from other workbook?
I tried:
=IF(LEFT(B26,3)="SSS",VLOOKUP(B26,'XXX.xls!$A$4:$E$119,4,FALSE))

But I get this error message:

You may not link to other workbook via conditional formatting

What can I do with this situation? People out there mentioned "define name" but I'm not sure how can it be done.

A: Lets call the workbook where you want to enter the conditional format as MyWbk and the other one SrcWbk. This instructions are for excel 2007. Your mileage may vary.

*

*Open both Workbooks

*In MyWbk go to the Formulas Menu, and select  Define Name

*Enter in Name > testname

*In the "Refers to" field, select click on the range selector (at right) and when the selector opens, select SrcWkb and then the cell you want as source for the format condition.

*Accept the name creation

*Go to the cell where you want to enter the conditional format

*Select the Home Menu / Conditional Formatting / Manage Rules

*Enter New Rule

*Select "Use a formula to determine which cells to format"

*Enter the formula you want, using the defined name. For example
 =IF(testname=1,TRUE)

*Select the desired formatting

*Test the formula changing the value in SrcWbk

*SAVE SrcWbk
You are done!

A: I just ran into this. The limitation is still there in Excel 2013.
But there is a workaround.
The limitation only exists in the Conditional Formatting editor.
The conditional formatting itself works just fine.
So in the editor, you can't refer to a defined range that refers to another workbook. You have to create the named range referring to your current workbook, define the conditional formatting that uses it, then when you are finished debugging it, change the defined range to the other workbook.
This isn't as bad as it sounds because it is easier to debug your formatting within the same sheet anyway.
This is only really a pain when you want to go back and change your formatting later.


text:
Q: Whats the correct way of outputting html in a custom module in Drupal I have worked on a few project with drupal, and the main suggestion I got when learning was to use Views to output your data, although this was fine for some items I found it cumbersome to achieve my projects requirements in the set time and to style it the controls were too limiting.
I want to know whats wrong with doing it like this, or whats right about doing it like this?
You run a query to get the specific data you want.
function custom_block_get_item($nid){
  $result = db_query("SELECT `field_custom_item`  FROM {field_data_field_custom_item} WHERE entity_id = :entity_id",
  array(
    ':entity_id' => $nid,
  ));
return $result;
}

Then you loop through creating the html
function custom_block_display_blurb($nid){
$html='

';
  $result=custom_block_get_blurb($nid);
    while($row1 = $result->fetchAssoc()){
  $a=check_markup($row1['field_custom_item'],'full_html','','');
  $html.='
  '.
  $a.'';
 }
$html.='

';
return $html;
}

Finally display it at the end
function custom_block_block_view($delta=''){
  if (arg(0) == 'node' && is_numeric(arg(1))) $nodeid = arg(1);
    switch($delta) {
     case 'custom_block':
   $block['content'] = custom_block_display_blurb($nodeid);
  break;
  }
  return $block;
}

This seems like a kind of hacky way to do things, what is the correct drupal way?

A: Maybe you mean using the drupal theme layer? This allows for use of .tpl files and overriding. I have a simple block module that does it here Source here.
Here is some documentation on using the theme layer within a module.
Here is some official Drupal docs on themeing (mainly themes rather than using the theme layer in a module).


text:
Q: Sitemesh custom javascript per page I am using sitemesh for a spring based site. The problem is that I have some javascript that I want it to run on the onload event of only one specific page using jquery $(function() { ... }) and not on every page.
I have included the jquery.js in the bottom of my decorator, after the body. So, if I try to include a <script> tag in the body of my decorated page the script won't be executed because jquery will be loaded after that! I know that I could include the jquery.js in the header of my decorator so it will be before the custom script in the decorated page however I don't really like that solution since it will contain javascritp in the head of my page.
So I would like to have something like a placeholder in my sitemesh decorator in where the custom  from my decorated page will be placed (as you can understand I come from the django world :p). Is this possible ? Do you propose anything else or should I just put my jquery.js in the header and be done with it ?

A: To answer my question, after some search I found the following solution:
I Added the following to the end of my decorator page (after including jquery.js)

<decorator:getProperty property="page.local_script"></decorator:getProperty>

I also added the following

<content tag="local_script">
<script>
  $(function() {
    alert("Starting");
  });
</script>
</content>

The decorated result page contained the contents of the local_script tag exactly where I wanted them and everything worked fine :)
I don't know why this feature of sitemesh is not properly documented - using this you can have a great templating behaviour (like django).


text:
Q: get action to happen, only when submit button is pressed i have some code that will post to the users wall, however, at the minute it will post when the page is loaded, i need it to post only when the 'post to my wall button is submitted.
here is my code:

<form method="GET" action="translate.php">
<textarea name="status2" cols="50" rows="5"<input type="text"/>
<?php echo str_ireplace(array     ('old','awkward','all','again','behind','along','alright','hello','among','children','yes','child','kids','food','barnard castle','beer','book','blow','beautiful','bird','burst','brown','burn','boots'),
array ('auld', 'aakwad', 'aall','agyen','ahint','alang','alreet','alreet','amang','bairns','aye','bairn','bairns','bait','barney','beor','beuk','blaa','bonny','bord','borst','broon','bourn','byeuts'),$status); ?>

</textarea>

<input type="submit" value="post to wall"
// i did try my wall code here but it still posted on page load
 />
</form>

<?php

$args = array(
    'message'   => 'Hello World',
    'link'      => 'http://apps.facebook.com/geordie-status/',
    'caption'   => 'Translate from English to Geordie'
    );
$post_id = $facebook->api("/$uid/feed", "post", $args);

?>

A: Add name attribute to your input tag. and use isset for check if the user pressed the submit button.
        <input type="submit" value="post to wall" name="submit"
        // i did try my wall code here but it still posted on page load
         />
        </form>

    <?php
        if (isset($_POST['submit'])){
        $args = array(
            'message'   => 'Hello World',
            'link'      => 'http://apps.facebook.com/geordie-status/',
            'caption'   => 'Translate from English to Geordie'
            );
        $post_id = $facebook->api("/$uid/feed", "post", $args);
        }
        ?>

A: You should put the code for the posting to the wall inside translate.php since that is the page listed in the form action. When the form gets submitted, values will be passed as parameters to translate.php then you can use $_GET to fetch them and execute the code that writes to the wall.

A: I think your problem is that your browser re-sends data each time the page is reloaded.
There are 2 approaches:

*

*Redirect user to the same page, so sent data will be cleared (header("Location: asd"))

*Store some hash in session, make a hidden input and check whether the hash is right. Change the hash when the form is correctly submitted.


text:
Q: Getting a format exception parsing a string to a double So there are still some logic errors in this that I am working on. I'm not worried about those, and I want to figure them out myself.
I'm working on a slot machine app for some independent study and when I try to parse the value of the label that shows the players cash into a variable I am getting a format exception. How do fix this and more importantly why am I getting this exception?
I have also tried using TryParse and Convert.ToDouble.
protected void PullBTN_Click(object sender, EventArgs e)
{
    // Get players cash//////////////////////////////
    double playersCash = Convert.ToDouble(playerMoneyLBL.Text);

    // Other way I tried that didn't work ////////////
    //double playersCash = 0;
    //double.TryParse(playerMoneyLBL.Text.Trim(), out playersCash);

    // Get players bet /////////////////////////////
    double playerBet = 0;
    if (!double.TryParse(betTB.Text, out playerBet))
        return;

   // Spin the slots//////////////////////////////
   Image1.ImageUrl = spinReel();
   Image2.ImageUrl = spinReel();
   Image3.ImageUrl = spinReel();

    // Find multiplier //////////////////////////////
    double multiplier = findMultiplier();

    // Find winnings ///////////////////////////////
    double winnnings = multiplier * playerBet;
    playerMoneyLBL.Text = (playersCash + winnnings).ToString();

    // Add winnings to players money //////////////
    playerMoneyLBL.Text = (playersCash + winnnings).ToString();
}

A: Your problem is here.
playerMoneyLBL.Text = "$100";

As you have $ in-front of 100, you cannot convert that to float. Make it something like this.
double playersCash = Convert.ToDouble(playerMoneyLBL.Text.substring(1));

A: double.Parse uses your CurrentCulture settings on the current environment by default.
double d = double.Parse("Your Text Here", CultureInfo.InvariantCulture);

Or if you want it more secure way, try:
value = "Your String";
style = NumberStyles.Number | NumberStyles.AllowCurrencySymbol| NumberStyles.AllowThousands;
culture = CultureInfo.InvariantCulture
if (Double.TryParse(value, style, culture, out number))
{
   // Write your code for true condition
}
else
{
  // Write your code for false condition
}


text:
Q: PostgreSQL: Query for location of global tablespace? I have been trying to make our database clients pro-active about not filling up the partition on which the database they are using resides.
As all our clients are on the same host as the database manager, it should be easy enough for user-created tablespaces; the client can look up the filesystem path for the tablespace (in spclocation), and use OS calls to check how much available space is available:
adb=> select * from pg_tablespace;

  spcname   | spcowner |    spclocation    |       spcacl
------------+----------+-------------------+---------------------
 pg_default |       10 |                   |
 pg_global  |       10 |                   |
 adb        |  2033793 | /database/adb     | {adb=C/adb}

I can't see how, from the client, to get the path to where the global tablespace is stored; an empty string is returned for it in the above query.
Unfortunately, we have many legacy systems in the field using a particular database created in the global tablespace, and it would be a monumental effort to get it moved into a user-created tablespace.
Hopefully I'm just missing something really simple.

A: PostgreSQL creates pg_default and pg_global when you create a cluster, perhaps by using initdb directly. The initdb utility can take an argument that sets the data directory, but no arguments about where to put the pg_default and pg_global tablespaces.
I'd conclude they're always created in the data directory. I could easily be wrong about that. I don't think they can be moved. I could be wrong about that, too.
But if I'm right up to this point, you can derive their physical location by
show data_directory;

The pg_global tablespace is almost certainly is the "global" subdirectory; pg_default probably is, too.
If I had time, I'd read the source code. That would remove all doubt.

A: pg_default and pg_global locations are "hardcoded".
pg_default lives in:
select setting||'/base' from pg_settings where name='data_directory';

and pg_global lives in:
select setting||'/global' from pg_settings where name='data_directory';

src/backend/commands/tablespace.c says so:
 * There are two tablespaces created at initdb time: pg_global (for shared
 * tables) and pg_default (for everything else).  For backwards compatibility
 * and to remain functional on platforms without symlinks, these tablespaces
 * are accessed specially: they are respectively
 *          $PGDATA/global/relfilenode
 *          $PGDATA/base/dboid/relfilenode

Please also note, that exposing location of data directory is a - not so terrible but still - security hole.
app01@postgres=> show data_directory;
ERROR:  must be superuser to examine "data_directory"


text:
Q: Calling a function from a dropdown selection in html and javascript Okay,so I was coding a simple HTML program and I ran into some problems.
I wanted to make a function that is called when certain options in a dropdown list is selected. My setup looks a bit like this.
<input type="number" id="int_c" value="" style="display:none">

<select id="mode">
        <option id="prtr" selected="myFunction()"> Selection 1 </option>
</select>

<script>
    function myFunction(){
document.getElementById("int_c").style.display = "block";
}
</script>

That doesn't work,it doesn't even reach the function (I tested it with alert()). So I also tried putting an onchange that calls the function in select.It also didn't work. Any ideas?

A: The event needs to be called on <select>, not on the <option>.
<input type="number" id="int_c" value="" style="display:none">

<select id="mode" onchange="myFunction(this)">
        <option id="prtr"> Selection 1 </option>
</select>

<script>
    function myFunction(elem){
        var selectedValue = elem.value;
        document.getElementById("int_c").style.display = "block";
}
</script>

A: Try to add the function to the onchange event handler of the select.
Also for this you need at least two select options

function myFunction(elem) {
  console.log(elem.value)
  document.getElementById("int_c").style.display = "block";
}
<input type="number" id="int_c" value="" style="display:none">

<select id="mode" onchange="myFunction(this)">
  <option> select </option>
  <option id="prtr" value="test"> Selection 1 </option>
</select>

A: *

*Add an onchange event on select tag

*Check the selected value with event.target.value

*Call your function

document.getElementById("mode").addEventListener("change",function(event){
   if(event.target.value ==="3"){
     document.getElementById("int_c").style.display = "block";
   }
})
<input type="number" id="int_c" value="" style="display:none">
<select id="mode">
        <option value="1"> Selection 1 </option>
        <option value="2"> Selection 2 </option>
        <option value="3"> Selection 3 </option>
</select>

A: There is no selected event on options. You will need to use the change event of the select box itself:

var selectBox = document.getElementById('mode');
var numberInput = document.getElementById('int_c');

function handleModeChanged(e) {
  var value = e.target.value;

  console.log('Mode has changed.');

  if (value === 'selection1') {
    console.log('Show input.');
    numberInput.style.display = 'inline-block';
  } else {
    console.log('Hide input.');
    numberInput.style.display = 'none';
  }
}

selectBox.addEventListener('change', handleModeChanged);
<input type="number" id="int_c" value="" style="display:none">

<select id="mode">
    <option>Select</option>
    <option value="selection1">Selection 1</option>
    <option value="selection2">Selection 2</option>
</select>

A: You need to attach a change in event to a select box and once any option is selected then you will call that function depend on that call.

var selectBox = document.getElementById("mode");
selectBox.addEventListener("change", function(){
  myFunction();
});

function myFunction(){
    document.getElementById("int_c").style.display = "block";
  }
<input type="number" id="int_c" value="" style="display:none">

<select id="mode">
    <option id="none"> none </option>
    <option id="prtr"> Selection 1 </option>
</select>

A: Try something like this. You'll need to include jQuery in the head of your page.
<input type="number" id="int_c" value="" style="display:none">

<select id="mode">
        <option>Select a value.</option>
        <option id="prtr">Selection 1</option>
</select>

<script>
     $("#mode").on("change",
         function(){
              var option = $(this).find("option:selected").html();
              if(option == "Selection 1"){
                  document.getElementById("int_c").style.display = "block";
              }
     });
</script>

Once again, be sure to include jQuery in your head. This grabs the ID of the dropdown list, and when the list changes, it pulls the html value, in your case "Selection 1". I've removed any spacing you had in the option
Then there is a conditional if statement that checks if the html value is equal to "Selection 1". I'll try this in a fiddle and see what happens
edit: I've also added a default value for your selector, so it isn't initially set to Selection 1.
edit2: link to js fiddle: https://jsfiddle.net/nj3fsdnv/
It's working for me.


text:
Q: Array cell reference in where clause of query Google Sheets sample file:
https://docs.google.com/spreadsheets/d/1WqqiysWdYMAop5uQXZnisuX291wY2PFmAMEKZhya2IM/edit?usp=sharing
I am trying to calculate the average value of each person for each month. My two variables to match are the names and month of the date. Currently I am able to get the correct values if I am applying the formula to each cell using this formula:
=IFERROR(QUERY(Sheet2!A:C,"Select avg(C) where A = '"&A2&"' and month(B) = month(date '"&TEXT(DATE(2021,MONTH(DATEVALUE($A$1&"1")),1),"yyyy-mm-dd")&"') label avg(C) '' "),"-")
What I want to do is be able to do an arrayformula instead so I will only need to input the formula once and wont have to worry about the number of names entered. I tried using this formula:
=ARRAYFORMULA(IFERROR(QUERY(Sheet2!A:C,"Select avg(C) where A = '"&A2:A&"' and month(B) = month(date '"&TEXT(DATE(2021,MONTH(DATEVALUE($A$1&"1")),1),"yyyy-mm-dd")&"') label avg(C) '' "),"-"))
, but it only calculates the average for that row.
If possible, the solution should also be using query since in the data I will be using it on I am not able to use sumifs/averageifs for some reason.

A: try:
=QUERY('data source'!A2:C,
 "select A,avg(C)
  where month(B)+1 = "&MONTH(A1&1)&"
  group by A
  label avg(C)''")

=ARRAYFORMULA({SORT(UNIQUE(FILTER('data source'!A2:A, 'data source'!A2:A<>""))),
 IFNA(VLOOKUP(SORT(UNIQUE(FILTER('data source'!A2:A, 'data source'!A2:A<>""))),
 QUERY('data source'!A2:C, "select A,avg(C) where month(B)+1 = "&
 MONTH(A1&1)&" group by A label avg(C)''"), 2, 0), "-")})


text:
Q: return colum name when has a value sql mysql I'm creating a poll with three options A, B & C
table votes
 id_poll id_voter value_A value_B value_C
    23      12      0       1       0
    23      11      1       0       0

Anytime I vote on an specific letter I insert the number 1 to its column and 0 to the others
PROBLEM
I want to return the column name of the voted letter (where 1 exists).
I was tthinking something like this
SQL
SELECT (¿?) as entry_selected
FROM poll
WHERE (column_value=1?) AND id_voter='11'

I want to return value_A

A: I would recommend using case:
select (case when value_a = 1 then 'value_a'
             when value_b = 1 then 'value_b'
             when value_c = 1 then 'value_c'
        end)
from poll
where 1 in (value_a, value_b, value_c);

A: You will have to hardcode the column names (unless someone else has a better solution), but you could do:
SELECT IF(value_a = 1, 'value_a', IF(value_b, 'value_b', IF(value_c, 'value_c', ''))) as entry_selected
FROM poll
WHERE (value_a = 1 OR value_b = 1 OR value_c = 1) AND id_voter='11'

A better solution would be to change how your data is structured:
id_poll id_voter value
23      12       B
23      11       A


text:
Q: GLib: propagate warning errors through UI I'm making a framework in ANSI C using GLib. The GError struct provides a nice method to manage errors, but I would like to modify my print_error macro, to propagate the error, for example, to the UI.
'print_error' macro is the following one:
#define print_error( error ) \
g_assert(error != NULL); \
g_warning("%s", error->message); \
g_error_free(error);

How can I modify it for my purpose?

A: Keep the macro as-is, but register a handler which displays the error in your UI.  How you do that depends on your application, and how you want your error to be displayed.
void my_log_handler (const gchar *log_domain,
                     GLogLevelFlags log_level,
                     const gchar *message,
                     gpointer user_data) {
  // Message contains the error string... put it in your UI here
  popup_error_dialog_or_whatever (message);
}

How exactly to send the data to the UI depends on your code, what toolkit you're using, how you want it to be displayed, etc.
Actually, I wouldn't quite keep the macro as-is--I would put it inside of a do...while loop.


text:
Q: Creating key,value pair dynamically with angularjs and passing the same to java Map I have two empty text boxes in front end one for key and another for value one add button and a submit button.User can click on the add button to add one more pair of two text boxes each representing key and value respectively.
User is free to add any text as key and any text as value in the text boxes.
The submit button is to submit the final form.
I want to get these data in angularJS and further pass this to java Map through a post request.
To be specific a Map in java looks like this when converted to Json.
{"A":"something","B":"something","C":"something","D":"value"}

But I am not able to create such structure dynamically from front end using angularJS.

A: As you need to map the key and value, I wont recommend array.
I think this is what you need:
$scope.map={};
//  Add header data
$scope.addToMap=function()
{
    $scope.map[$scope.key]=$scope.value;
    $scope.key="";    //clear the textbox
    $scope.value="";  //clear the textbox
};

execute addToMap() when your button is clicked. You can also have an ng-repeat with non-editable text boxes, and run the ng-repeat on map

A: Try following code to create dynamic JSON object.

var myApp = angular.module('myApp',[]);

myApp.controller('MyCtrl', ['$scope', function MyCtrl($scope) {
 $scope.jsonObject = {};

  $scope.add = function(){
   $scope.jsonObject[$scope.key] = $scope.value;
  };

  $scope.submitForm = function(){
   console.log($scope.jsonObject);
  }
}]);

  <form>
     Key: <input ng-model="key">
     Value: <input ng-model="value">
     <button ng-click="add()">ADD</button>
     <button ng-click="submitForm()">submit form</button>
   </form>

  {{jsonObject}}

A: try this
here is the working fiddle

 <input type="text" ng-model="item">

  <button ng-click="addItem()">Add</button>

Controller
var myApp = angular.module('myApp',[]);
 myApp.controller('MyCtrl',function($scope){
  $scope.items=['item1','item2','item3','item4','item5'];

  $scope.addItem = function(){
    $scope.items.push('');
  }
})

A: Check this Plunker
http://plnkr.co/edit/sgKYtxFGL1JyrVFMkQM4?p=info
$scope.name = {"A":"something","B":"something","C":"something","D":"value"};

$scope.example = $scope.name["A"];


text:
Q: installing adhoc distribution but profile gives error  Profile does not match application bundel identifier.
com..BayerCropSciences this is my application identifier and
my certificate has
com.celeritas.Cerenia
how to fix this issue and make the certificate work

A: make the bundle identifier for the app com.celeritas.cerenia or download the right certificate from the provisioning portal


text:
Q: Grep and returning only column of match if i want to search from a file with various number of columns like this:
ppl:apple    age:5    F    add:blabla    love:dog
ppl:tom    M    add:blablaa    love:cat
ppl:jay    age:3    M    love:apple
ppl:jenny    acc:jen    age:8   F   add:blabla

...

the file is tab separated, and the output i want is:
age:5
age:3
age:8
...

using grep age: will return the entire row, while
using cut -f2 will return some unwanted column:
age:5
M
age:3
acc:jen

and neither cut -f2|grep age: nor grep age|cut -f2: work
My data may range from 11-23 columns,
will there be any simpler way to handle it using grep sed or awk,
many thanks

A: You can use script below:
cat file|grep age|awk '{for(i=1;i<22;i++){if($i ~ /^age:/)print $i}}'

A: grep itself can do this, with no additional tools, by using the -o/--only-matching switch. You should be able to just do:
grep -o '\<age:[0-9]\+'

To explain the less common parts of the regex:

*

*\< is a zero-width assertion that you're at the beginning of a word (that is, age is preceded by a non-word character or occurs at the beginning of the line, but it's not actually matching that non-word character); this prevents you from matching, say image:123. It doesn't technically require whitespace, so it would match :age: or the like; if that's a problem, match \t itself and use cut or tr to remove it later.

*\+ means "match 1 or more occurrences of the preceding character class" (which is [0-9], so it matches one or more digits). \+ is equivalent to repeating the class twice, with the second copy followed by *, e.g. [0-9][0-9]*, except it's shorter, and some regex engines can optimize \+ better.

A: ShadowRanger's simple grep-based answer is probably the best choice.
A solution that works with both GNU sed and BSD/OSX sed:
sed -nE 's/^.*[[:blank:]](age:[0-9]+).*$/\1/p' file

With GNU sed you can simplify to:
sed -nr 's/^.*\t(age:[0-9]+).*$/\1/p' file

Both commands match the entire input line, if it contains an age: field of interest, replace it with that captured field (\1), and print the result; other lines are ignored.

Original answer, before the requirements were clarified:
Assuming that on lines where age: is present, it is always the 2nd tab-separated field, awk is the best solution:
awk '$2 ~ /^age:/ { print $2 }' file

*

*$2 ~ /^age:/ only matches lines whose 2nd whitespace-separate field starts with literal age:

*{ print $2 } simply prints that field.

A: You can also use sed
    sed -nr 's/^.*(age:.).*$/\1/p'  input_pattern.txt

Where input_pattern.txt contains you data.

A: Limit search for regexp to columns 11 to 23:
awk '{ for(i = 11; i <= 23; i++) { if ($i ~ /^age:/) print $i } }' file


text:
Q: p5.js How would I prevent a small circle from crossing a diameter of a bigger circle Im working of a program that has a circle moving around inside another bigger circle.
var offX;

function setup() {
  createCanvas(400, 400);
  offX = 0.00;
}

function draw() {
  background(220);

  var bigBoy = {
    x: 200,
    y: 200,
    r: 150,
  };

  var smallBoy = {
    x: noise(offX) * 400,
    y: map(sin(offX),-1,1,10,380),
    r: 10,
  };

  offX += 0.005;

  ellipse(bigBoy.x,bigBoy.y,bigBoy.r * 2);
  ellipse(smallBoy.x,smallBoy.y,smallBoy.r * 2);

  var d = dist(bigBoy.x,bigBoy.y,smallBoy.x,smallBoy.y);

  text(round(d,0),30,20);

  //-------------------------------//

  if(d > bigBoy.r - smallBoy.r){

    //move away from / dont cross over bigBoy's diameter//

  } else{

    //crack on mate//
  }
}

could anyone advise me how I would keep the smaller circle within the bigger circles diameter. I would need it to look natural, like the small circle has a force preventing it from leaving the bigger one?
Thanks in advance!
P


text:
Q: Are JAD decompiled files 100% accurate Are JAD decompiled files 100% accurate. I am decompiling some jar files to get the source code and when i am trying to build the project with these java files it is not showing the accurate build. Does i am doing it wrong or the decompiled files are not accurately same as the original one.

A: Short answer: 99% of the time, decompiled code will not look like the original code, but it should behave the same way. So, assuming the decompiler doesn't make any mistakes, it should be accurate in function, but not in implementation.
Long answer: When the Java compiler translates your source to byte code, it performs certain operations that change how to code looks. I am not an expert on the details of the Java compiler, but A simple optimisation that many compilers perform is inserting small methods into the location in code where they are called.
For example, lets say we compile this code:
public class c
{
   public int add(int a, int b)
   {
      return a + b;
   }

   public static void main(String [] args)
   {
      int i = add(1, 2);
   }
}

Since b is only one line, and it can safely be substituted with it's contents, a smart compiler may change the main method into this:
public static void main(String [] args)
{
   int a = 1, b = 2
   int i = a + b;
}

or this:
public static void main(String [] args)
{
   int i = 1 + 2;
}

This would be done because the overhead for calling a method is worse than the overhead of putting the method's contents directly into the place it's called.
I have no idea what the Java compiler would do in this situation, but it does make changes to the code like this. It isn't necessarily inaccurate, because it does do the same thing as the original code. Since the compiler doesn't leave the details of these changes anywhere in the .class file, there is no way for a decompiler to know whether an optimisation was performed at any given point in the code, of if it was written that way.
There are also a number of other things that may not survive the transition to byte code (variable names and comments, for instance).
So yes, when you look at decompiled code, you are looking at what the .class file looks like, rather than what the .java file looks like. Even though it seems inaccurate, it should run the same.


text:
Q: Celluloid::Notifications Failing After App Daemonized I'm using Celluloid::Notifications publish/subscribe to communicate between two actors. Everything works fine when running the app normally but when I try and run it in the background the subscribing actor fails to receive the notification. I've tried a number of different gems for daemonizing all of which seem to break the notifications.
The app does work when run with nohup which leads me to believe the issue has to do with the forking that's part of the daemonization process.

A: You need to fork before you instantiate actors.
Demonizing is no problem using command & and having the Process.pid stored... but if you want to truly fork, you need to fork before the actor system goes online... which itself instantiates actors, including the ones handling notifications ( as you noticed ).


text:
Q: One hot encoding when a column has more than one label I'm looking to convert the below dataset
-----------------------
|   Name   | Subject  |
-----------------------
| Student1 | Subject1 |
| Student1 | Subject2 |
| Student2 | Subject1 |
| Student3 | Subject3 |
| Student3 | Subject4 |
| Student3 | Subject5 |
| Student4 | Subject6 |
-----------------------

to this
-------------------------------------------------------------------------------
|    Name   | Subject1 | Subject2 | Subject3 | Subject4 | Subject5 | Subject6 |
-------------------------------------------------------------------------------
|  Student1 |     1    |     1    |     0    |     0    |     0    |     0    |
|  Student2 |     1    |     0    |     0    |     0    |     0    |     0    |
|  Student3 |     0    |     0    |     1    |     1    |     1    |     0    |
|  Student4 |     0    |     0    |     0    |     0    |     0    |     1    |
-------------------------------------------------------------------------------

Is there a one liner code that can do this on a pandas dataframe?

A: You can try pd.crosstab
out = pd.crosstab(df['Name'], df['Subject'])

print(out)

Subject   Subject1  Subject2  Subject3  Subject4  Subject5  Subject6
Name
Student1         1         1         0         0         0         0
Student2         1         0         0         0         0         0
Student3         0         0         1         1         1         0
Student4         0         0         0         0         0         1

A: You can do crosstab
pd.crosstab(df.Name, df.Subject).reset_index()


text:
Q: How do I get the sequence of vocabulary from a sparse matrix I have a list of vocabularies ['Human', 'interface', 'machine', 'binary', 'minors', 'ESP', 'system', 'Graph'] and a list of sentences ["Human machine interface for lab abc computer applications", "A survey of user opinion of computer system response time", "The EPS user interface management system", "Relation of user perceived response time to error measurement", "The generation of random binary unordered trees", "The intersection graph of paths in trees", "Graph minors IV Widths of trees and well quasi ordering", "Graph minors A survey"].
I use 'CountVectorizer' from 'sklearn' to fit the sentences into a sparse matrix based on the eight words. And I get a output below.
[[0 0 0 0 0 1 0 1]
 [0 0 0 0 1 0 0 0]
 [0 0 0 0 1 0 0 1]
 [0 0 0 0 1 0 0 0]
 [0 0 0 0 0 0 0 0]
 [1 0 0 0 0 0 0 0]
 [0 0 0 0 0 0 0 0]
 [0 1 0 0 0 0 0 0]
 [0 1 0 0 0 0 0 0]]

Now I'm trying to find out the sequence of that eight words in the matrix. Any help will be appreciated.

A: CountVectorizer use lowercase by default, so 'Human', 'Graph', 'ESP' have no matches. And it seems vocabulary vector is sorted somehow in your result.
You can set lowercase = False.

lowercaseboolean, True by default Convert all characters to lowercase
  before tokenizing. sclearn doc

I did like this.
from sklearn.feature_extraction.text import CountVectorizer

corpus = ["Human machine interface for lab abc computer applications", "A survey of user opinion of computer system response time", "The EPS user interface management system", "Relation of user perceived response time to error measurement", "The generation of random binary unordered trees", "The intersection graph of paths in trees", "Graph minors IV Widths of trees and well quasi ordering", "Graph minors A survey"
]

voc = ['Human', 'interface', 'machine', 'binary', 'minors', 'ESP', 'system', 'Graph']

vectorizer = CountVectorizer(vocabulary=voc, lowercase=False)

X = vectorizer.fit_transform(corpus)

print(vectorizer.get_feature_names())
print(X.toarray())

#     ['Human', 'interface', 'machine', 'binary', 'minors', 'ESP', 'system', 'Graph']
#     [[1 1 1 0 0 0 0 0]
#      [0 0 0 0 0 0 1 0]
#      [0 1 0 0 0 0 1 0]
#      [0 0 0 0 0 0 0 0]
#      [0 0 0 1 0 0 0 0]
#      [0 0 0 0 0 0 0 0]
#      [0 0 0 0 1 0 0 1]
#      [0 0 0 0 1 0 0 1]]

In matrix, each row is voc matching for a sentence. So this case 'Human', 'interface', 'machine' matched for 1st row(sentence).


text:
Q: r - create function to calculate count of filtered rows in dataset I'm trying to create a helper function that will calculate how many rows are there in a data.frame according parameters.
getTotalParkeds <- function(place, weekday, entry_hour){
  data <- PARKEDS[
                  PARKEDS$place      == place,
                  PARKEDS$weekday    == weekday,
                  PARKEDS$entry_hour == entry_hour
                  ]
  return(nrow(data))
}

Then I'm running this like:
getTotalParkeds('MyPlace', 'mon', 1)

So it is returning this error:
Warning: Error in : Length of logical index vector must be 1 or 11 (the number of columns), not 10000

I'm totally new to R, so I have no idea on what is happening.

A: Here's the correction you need for your approach -
getTotalParkeds <- function(place, weekday, entry_hour){
  data <- PARKEDS[
                  PARKEDS$place      == place &
                  PARKEDS$weekday    == weekday &
                  PARKEDS$entry_hour == entry_hour,
                  ]
  return(nrow(data))
}

A: Allowing different PARKEDS data, say next month's data:
getTotalParkeds <- function(input, place, weekday, entry_hour){

  row.count <- nrow(subset(input, place == place &
                                  weekday == weekday &
                                  entry_hour == entry_hour))
  return(row.count)
}


text:
Q: Gerrit + Jenkins: how to trigger an action after the merge is complete OR the review is abandoned? I current trigger Jenkins builds on a git push to refs/for/ via the gerrit trigger in Jenkins (at the start of a review). This produces a build that is suitable for testing and verification prior to review completion. When the review is done (and any necessary rebasing is finished) the review is marked complete and this triggers the final merge of the code to Git (fast-forward only).
This works, but I'd prefer to park the build artifacts from Jenkins somewhere special until the review is finally merged, at which time that last build's artifacts go somewhere else (if the review is abandoned those artifacts would instead get purged).
I thought I might create a special post-merge job in Jenkins and have it trigger on a merge, but since I want to trigger such a job if a branch is abandoned I don't think the merge trigger will cut it. Is there a gerrit/Jenkins trigger that'll help me automate this more exactly? (Currently we have a main build job per major component... but I might only need one global job that triggers for any merged component to handle the final disposition of said artifacts.)

A: Jenkins has a trigger for "change abandoned" too.
There's no problem having more than one Jenkins job per branch/change/commit/push, both with fire (and will return a combined comment on Gerrit so there's no extra email spam).
You can create a new global jobs that will just trigger on merge or abandoned (just add both triggers). Your build or post-build action can be a shell script or utility program that will do what you want.

A: There are also hooks; e.g.
change-merged --change <change id> --change-url <change url> \
--project <project name> --branch <branch> --topic <topic> \
--submitter <submitter> --commit <sha1>

or
change-abandoned --change <change id> --change-url <change url> \
--project <project name> --branch <branch> --topic <topic> \
--abandoner <abandoner> --reason <reason>

or a event stream where you can subscribe to, and trigger custom actions.
$ ssh -p 29418 review.example.com gerrit stream-events
{"type":"comment-added",change:{"project":"tools/gerrit", ...}, ...}
{"type":"comment-added",change:{"project":"tools/gerrit", ...}, ...}


text:
Q: How change server map path and file name when file uploaded in asp.net mvc? I am trying to save picture in folder and store path in database using entity framework in asp.net mvc 5.
I did it but I have some problems .
image path in DB saved like this :
C:\Users\Shima\Documents\Visual Studio 2013\Projects\NP1\NP1\Images\SubGoods\2.jpg

How can I change it to:  ~/Images/SubGoods/2.jpg ??
and I want to change image name to it's primary key id and I used pic =Convert.ToString( subgood.SubGoodID); to do it, but it saves Zero :
C:\Users\Shima\Documents\Visual Studio 2013\Projects\NP1\NP1\Images\SubGoods\0

It saves always 0 .I know that's because Primary key in that line not generated yet .  where of my codes primary Key id generated ?
public ActionResult AddSubGood(SubGood subgood, HttpPostedFileBase UploadImage)
    {
        var MainGoodId = subgood.FKMainGoodID;
        SubGoodRepositories blSubGood = new SubGoodRepositories();
        string path="";
        if (UploadImage != null)
        {
            string pic = System.IO.Path.GetFileName(UploadImage.FileName);
            pic =Convert.ToString( subgood.SubGoodID);
             path = System.IO.Path.Combine(
                                   Server.MapPath("~/Images/SubGoods"), pic);

        }

        if (ModelState.IsValid)
        {
            subgood.FKMainGoodID = MainGoodId;
            UploadImage.SaveAs(path);
            subgood.SubGoodImage = path;

            if (blSubGood.Add(subgood))
            {
                return JavaScript("alert('saved');");
            }
            else
            {
                return JavaScript("alert('didn't saved');");
            }
        }
        else
        {
            return JavaScript("alert('error');");
        }

    }

A: Server.MapPath will return you Virtual path(which you don't needed) , you can create another variable and concatenate like this :
string DbPath = "~/Images/SubGoods/"; // better to store in web.config file
DbPath = DbPath  + ""//here you can query in table and find the last inserted primary key and increment it with '1'

A: You should save only the file name:
var fileName = Path.GetFileName(UploadImage.FileName);

Then when you want to fetch the file for user you can simply address the file name with specific path:
<img src="~/Content/Uploaded/@item.fileName" .../>

You can also generate a random file name using Guid:
var rondom = Guid.NewGuid() + fileName;


text:
Q: Navicat Premium Essentials Wont SSH Im trying to get Navicat Premium Essentials to ssh tunnel into my aws Ec2 server. to access Mysql DB hosted on there. The error is Access denied. Authentication that can continue: publickey,gssapi-keyex,gssapi-with-mic
I can ssh into the instance via terminal no problem. Key Permission is 400.
When I save the connection and reload it, the pem file is no longer loaded in the browser file box (not sure if this is how it is suppose to be for security reasons) I have copied the same login from ssh cmd to navicat.
User: centos
Ip: Ec IP (also tried public dns)
Pem file: same as the one used to SSH.
Both port 22 and 3306 are open to my IP address
Any ideas? I feel like Navicat isn't sending the Pem file with the ssh request.
Mac: Sierra 10.12.5
Navicat Essentials 12.0.9
AWS Centos ec2.

A: Navicat has emailed me back and informed me that it is a problem with their product I have asked for them to send me the most stable version.


text:
Q: How to set hidden attributes to an Controller method in Laravel5.0? I want to hide some data which selected from database but reinitialize from some method in Controller not defined in its Models.
function ddd(){
        return Client::select($this->_client)->with([
            'Contact'=>function($s){
                //$this->setHidden('use_id');
                //$s->setHidden('use_id');
                $s->select($this->_contact);
            },
            'Employer'=>function($s){$s->select($this->_employers);},
        ])->get();
    }

A: You requirement is not very clear. However. I am assuming that you have 3 models Client hasOne Contact and belongsTo Employer.
In order to hide the use_id property of the Client model you can define a hidden property in your model
class Client extends Model
{
    //will hide the `use_id` from the model's array and json representation.
    protected $hidden = ['use_id'];

    //Relations
    /**
     * Get the Contact which the given Client has.
     * @return \Illuminate\Database\Eloquent\Relations\HasOne
     * will return a App\Contact model
     */
    public function contact()
    {
        return $this->hasOne('App\Contact');
    }

    /**
     * Get the Employee to which the given Client belongs.
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     * will return a App\Employer model
     */
    public function employer()
    {
        return $this->belongsTo('App\Employer');
    }
}

Then in probably your ClientsController in some action ddd
public function ddd()
{
    return Client::with('contact')->with('employer')->get();
}


text:
Q: How to properly run googletest with global static initializer methods I wonder if anyone have practical experience of how to handle static initializer functions in googletest?
For example assume you have an external library which requires you to run ExtLib::Init() exactly once, and no more, for each process. The code you need to test then obviously have to use this ExtLib.
Then assume you have a couple of tests running with some EXPECT_DEATH. As I understand it some of these death tests run in a subprocess.
Do I have to call ExtLib::Init within the body that is passed to EXPECT_DEATH or how do I cope with it?
Thanks in advance...

A: You should use AddGlobalTestEnvironment() to register a class to perform global setup and tear-down, such as initializing external libraries.
According to the documentation, when using the "threadsafe" style of death tests, every death test spawns a new process that executes the test program but only runs the one test. I assume it will also run global setup and tear-down, but you will have to check this. For example, by writing a message to std::cerr or using a debugger.
This style is always used on Windows.
When using the "fast" style, it probably depends on the external library whether it needs to be initialized again or it's state is preserved over a fork()/clone() call.


text:
Q: With Swiftui how we can create user form I want to create a form in which all textfield need to start from the same alignment, like in below image it does not start from the same alignment. First name, last name and Phone number all textFields are not aligned properly in a single vertical line.
VStack(){
        HStack(){
            Text("First Name")
            TextField("First name", text: $name).textFieldStyle(RoundedBorderTextFieldStyle())
        }
        HStack(){
            Text("Last Name")
            TextField("Last Name", text: $name).textFieldStyle(RoundedBorderTextFieldStyle())
        }
        HStack(){
            Text("Phone number")
            TextField("Phone number", text: $name).textFieldStyle(RoundedBorderTextFieldStyle())
        }
        Spacer()
    }.padding(10)

A:         VStack{
            HStack(){
                Text("First Name").frame(width: 120, alignment: .leading)
                TextField("First name", text: $name).textFieldStyle(RoundedBorderTextFieldStyle())
            }
            HStack(){
                Text("Last Name").frame(width: 120, alignment: .leading)
                TextField("Last Name", text: $name).textFieldStyle(RoundedBorderTextFieldStyle())
            }
            HStack{
                Text("Phone number").frame(width: 120, alignment: .leading)
                TextField("Phone number", text: $name).textFieldStyle(RoundedBorderTextFieldStyle())
            }
            Spacer()
        }.padding(10)

or more flexible solution
struct TestView: View {
    @State var name = ""
    @State var width: CGFloat = 0

    struct Label: ViewModifier {
        @Binding var width: CGFloat

        func getWidth(content: Content, proxy: GeometryProxy) -> some View {
            if proxy.size.width > width {
                RunLoop.main.perform {
                    self.width = proxy.size.width
                }
            }
            return content
        }

        func body(content: Content) -> some View {
            content.overlay(GeometryReader { proxy in
                self.getWidth(content: content, proxy: proxy)
            }).frame(minWidth: self.width, alignment: .leading)
        }
    }

    var body: some View {
        VStack(alignment: .center){
            HStack(){
                Text("First Name").modifier(Label(width: $width))
                TextField("First name", text: $name).textFieldStyle(RoundedBorderTextFieldStyle())
            }
            HStack(){
                Text("Last Name").modifier(Label(width: $width))
                TextField("Last Name", text: $name).textFieldStyle(RoundedBorderTextFieldStyle())
            }
            HStack{
                Text("Phone numbe").modifier(Label(width: $width))
                TextField("Phone number", text: $name).textFieldStyle(RoundedBorderTextFieldStyle())
            }

            Spacer()
        }.padding(10)
    }
}

A: You can use GeometryReader to access device size and frame to set fixed width for Texts. For example:
GeometryReader { geometry in
    VStack(spacing: 10) {
        HStack {
            Text("First Name").frame(width: geometry.size.width / 3)
            TextField("First name", text: self.$name).textFieldStyle(RoundedBorderTextFieldStyle())
        }
        HStack {
            Text("Last Name").frame(width: geometry.size.width / 3)
            TextField("Last Name", text: self.$name).textFieldStyle(RoundedBorderTextFieldStyle())
        }
        HStack{
            Text("Phone number").frame(width: geometry.size.width / 3)
            TextField("Phone number", text: self.$name).textFieldStyle(RoundedBorderTextFieldStyle())
        }
        Spacer()
    }.padding(10)
}

A: This will align your TextFields:
VStack {
    HStack {
        HStack {
            Text("First Name")
            Spacer()
        }
        TextField("First name", text: $name)
            .textFieldStyle(RoundedBorderTextFieldStyle())
    }
    HStack {
        HStack {
            Text("Last Name")
            Spacer()
        }
        TextField("Last Name", text: $name)
            .textFieldStyle(RoundedBorderTextFieldStyle())
    }
    HStack {
        HStack {
            Text("Phone number")
            Spacer()
        }
        TextField("Phone number", text: $name)
            .textFieldStyle(RoundedBorderTextFieldStyle())
    }
    Spacer()
}   .padding(10)


text:
Q: Why does C# implicitly convert to nullable DateTime if there is no implicit operator for nullable DateTime? This is a question about the C# language or at least how that language is implemented in Visual Studio.
Assume one has a class Foo which defines an implicit operator to System.DateTime
public static implicit operator DateTime(Foo item)

Consider the following code:
Foo foo = SomeMethodWhichCanReturnNull();
DateTime?  dtFoo = foo;

What I would expect:
A failure-to-compile complaining that there is no conversion from Foo to DateTime?.
What I find: The compiler actually calls the defined implicit operator from Foo to DateTime and crashes when it is passed a null (which is the only way the converter can respond to a null).
Of course, work-around is to define
public static implicit operator DateTime?(Foo item)

but why do I have to do this?  Are not DateTime and DateTime? two different types?

A: DateTime? is actually a C# syntactic sugar to represent Nullable<DateTime>. When you write something like DateTime?  dtFoo = foo the compiler actually generate code like:
Nullable<DateTime> dtFoo = new Nullable<DateTime>(foo);

Which is perfectly fine from compiler point of view as the nullable constructor take a DateTime as param and foo has type conversion for it.

A: When you have this:
Foo foo = SomeMethodWhichCanReturnNull();
DateTime? dtFoo = foo;

The compiler sees that there is an implicit conversion from Foo to DateTime, and an implicit conversion from DateTime to DateTime?. It decides it can thus implicitly convert from Foo to DateTime? and quite happily compiles.
An implicit operator should not throw an exception. The fact that you are violating this is why you are seeing confusing behavior. You should probably change that to an explicit operator, and optionally add an implicit conversion to DateTime? that returns null in the case of a null Foo.

A: First off, the C# language specification says that a built-in implicit conversion can be inserted on either side of a user-defined implicit conversion. So if you had a user-defined implicit conversion from Shape to Giraffe then you are automatically allowed to convert from Square to Mammal, because it goes Square --> Shape --> Giraffe --> Mammal.  In your case the extra conversion is only inserted on one side, presuming that the operand is of type Foo. There is an implicit conversion from any type to its corresponding nullable type. A second user defined conversion is never inserted; only built in conversions can be inserted on either side.
(I note that this is true of user-defined explicit conversions as well; explicit conversions may be inserted on either side.)
Second, you are in violation of the specification, which strongly suggests that a user-defined implicit conversion should never throw an exception. If you cannot guarantee that the operation will succeed then either change the types or make it an explicit conversion.
Third, you might be interested to know that the C# compiler will automatically define a "lifted" conversion if both types in a user-defined implicit conversion are non-nullable value types. If you have a user-defined implicit conversion from struct type S to struct type T then you get a "lifted" conversion from S? to T? for free, with the semantics of s.HasValue ? new T?((T)s.Value) : new T?().
This subject is one of the more complex areas in the C# specification so I recommend that you read it carefully if you wish to know the exact details.

A: This is valid for the same reason you can do the following:
DateTime time1 = new DateTime();
DateTime? time2 = time1;

A normal DateTime can be transformed into a nullable DateTime. This means that your Foo class, which acts like a DateTime, can follow the path Foo -> DateTime -> DateTime?
I guess DateTime? (or any other null-ed class) has an implicit operator to its normal type.

A: First of all, remember that T? (when T's a struct) actually means Nullable<T>.
Now, let's make a short test program that replicates this:
using System;
class Program
{
    public static void Main(string[] args)
    {
        DateTime? x = new Program();
        Console.ReadKey(true);
    }
    public static implicit operator DateTime(Program x)
    {
        return new DateTime();
    }
}

And now see what it compiles to (decompiled using the great dotPeek):
using System;
internal class Program
{
  public Program()
  {
    base..ctor();
  }

  public static implicit operator DateTime(Program x)
  {
    return new DateTime();
  }

  public static void Main(string[] args)
  {
    DateTime? nullable = new DateTime?((DateTime) new Program());
    Console.ReadKey(true);
  }
}

In fact, dotPeek is being nice to me here: it should be the same, but with DateTime? nullable = new DateTime?((DateTime) new Program()); changed into Nullable<DateTime> nullable = new Nullable<DateTime>((DateTime) new Program());
As you can see, implicit conversions are just turned into explicit ones by the compiler.
What I'm guessing happens is that the compiler first thinks[1] that you can't make Foo a DateTime?, as a) it's not a reference type, and b) it's not a DateTime. So then it might go through some of its implicit operators[2] , and finds one that matches DateTime. And then it realizes[1] that you can convert a DateTime to a Nullable<DateTime>, so it then does it.
:)
[1]: Not really thinks, but don't be pedantic.
[2]: Eric Lippert has a comment about this, that explains it.


text:
Q: CakePHP returning 502 when passing large dataset to the view I am passing a large data set to a view (~3000 rows). The view then presents the data in a table.
This works locally, but returns a 502 in the server.
I am not using pagination for this particular query because the client wants the whole list in one go. Retrieving the results is actually working fine, I can stop the process and view the query results.
The issue comes from passing the large array to the view using set(): $this->set('data', $data);
If I comment this line, the process completes as expected (with no data to display obviously).
I tried saving the array in the session, and using this to render the table on the view. This works, but it crashes the Cake debugging plugin.
I also tried caching the data, and retrieving the data from the cache on the view. This also works.
What could cause the $this->set() to return a 502? Is there a setting I am missing to allow passing large dataset to the view?
Also, there is nothing relevant in the logs.
Thanks,


text:
Q: How can I prove that this polynomial is irreducible? I have a polynomial $y^4-10y^2+x^4-10x^2+20$ how can I prove that it is irreducible?
Wolfram says that it is. Also, I know that $p(x)+y$ is always irreducible, so $y':=y^4-10y^2$.


text:
Q: Can you access an element in CSS by referring to its child element? So I have a basic table, in which some of the <td> tags consist of a div defined by a class called "chapter-div".
Is there a way I could access only the <td>s which have the "chapter-div" divisions inside of them (USING ONLY THIS TRAIT OF THEM), excluding all of the others tds?
For perception purposes, if we can do this in CSS:
td > .chapter-div

What I'd like to do is something like this:
td < .chapter-div

Thank you in advance!

A: This can only be achieved with Javascript. If you're using jQuery, its pretty simple:
$('.chapter-div').parent().addClass('chapter-div-parent');

Then you can style your td with the .chapter-div-parent class.


text:
Q: Problema consumo WebService NFS-e Estou tenho vários problemas no consumo do webservice de Joinville, SC.
Homologação: https://nfemwshomologacao.joinville.sc.gov.br/NotaFiscal/Servicos.asmx?wsdl
Produção: https://nfemws.joinville.sc.gov.br/NotaFiscal/Servicos.asmx?wsdl
Para consumir o WebService eu fiz dessa forma:

E depois para consumir esse WebService, ficou mais ou menos assim:
private EnviarLoteRpsEnvio1 EmitirNFSe(X509Certificate2 certificado, EnviarLoteRpsEnvio envio)
{
#if DEBUG
   string enderecoBase = "https://nfemwshomologacao.joinville.sc.gov.br";
#else
   string enderecoBase = "https://nfemws.joinville.sc.gov.br";
#endif
   var client = new ServicosSoapClient(CriarBinding(), new EndpointAddress(enderecoBase + "/NotaFiscal/Servicos.asmx"));
   client.ClientCredentials.ClientCertificate.Certificate = certificado;
   return ((ServicosSoap)client).RecepcionarLoteRps(envio);
}

Problema 1
Um dos problemas é que a classe EnviarLoteRpsEnvio esperada no método cliente.RecepcionarLoteRps(envio) tem 2 propriedades: LoteRps e Signature, ambos do tipo XmlNode:
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
[System.ServiceModel.MessageContractAttribute(WrapperName="EnviarLoteRpsEnvio", WrapperNamespace="https://nfemwshomologacao.joinville.sc.gov.br", IsWrapped=true)]
public partial class EnviarLoteRpsEnvio {

    [System.ServiceModel.MessageBodyMemberAttribute(Namespace="https://nfemwshomologacao.joinville.sc.gov.br", Order=0)]
    public System.Xml.XmlNode LoteRps;

    [System.ServiceModel.MessageBodyMemberAttribute(Namespace="https://nfemwshomologacao.joinville.sc.gov.br", Order=1)]
    public System.Xml.XmlNode Signature;

    public EnviarLoteRpsEnvio() {
    }
}

Como faço para preencher esses campos? Eu criei uma classe LoteRps e preenchi com os dados pedidos pelo WebService, transformei em XmlDocument e coloquei nessa propriedade, mas o xml convertido (peguei pelo Fiddler) é gerado com a tag LoteRps duplicada:

Problema 2
A consulta eu consegui fazer funcionar, porém eu tiver um erro em release:
Server did not recognize the value of HTTP Header SOAPAction: https://nfemwshomologacao.joinville.sc.gov.br/ConsultarNfseRpsEnvio.

Isso acontece pois o endereço de produção é outro. Veja como foi gerada a classe proxy:
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
[System.ServiceModel.ServiceContractAttribute(Namespace = "https://nfemwshomologacao.joinville.sc.gov.br", ConfigurationName = "NFSe.Joinville.ServicosSoap")]
public interface ServicosSoap
{
    [System.ServiceModel.OperationContractAttribute(Action = "https://nfemwshomologacao.joinville.sc.gov.br/EnviarLoteRpsEnvio", ReplyAction = "*")]
    [System.ServiceModel.XmlSerializerFormatAttribute(SupportFaults = true)]
    Wiser.Servicos.NFSe.Joinville.EnviarLoteRpsEnvio1 RecepcionarLoteRps(Wiser.Servicos.NFSe.Joinville.EnviarLoteRpsEnvio request);

   /*Outros métodos*/
}

Está fixo o endereço de homologação
Resumo
Na verdade eu tive vários problemas com esse WebService, então minha duvida é se estou consumindo da forma correta. Eu já consumi outros WebServices sem problema, esse foi o único que parece diferente.
Para a emissão da nota eu consegui fazer uma requisição http montando o request manualmente, sem usar as classes de proxy geradas para consumir o webservice. Mas isso deu muito trabalho. Alguma sugestão?


text:
Q: Custom area graph in Excel (or google spreadsheet) I am trying to visualize my loans with area graph and have some additional needs/wishes.
For example - this is my data (made up):
           house    car     mower   vacation
           diners   diners  visa    visa
jan.12     60       30      0       0
feb.12     60       30      0       0
mar.12     60       30      0       20
apr.12     60       30      10      20
maj.12     60       30      10      20
jun.12     60       0       10      20
jul.12     60       0       10      20
avg.12     60       0       10      20
sep.12     60       0       10      20
okt.12     60       0       10      0
nov.12     60       0       10      0
dec.12     60       0       10      0

And the corresponding graph:

I have 2 additional wishes:

*

*Loans from the same account should have similar color (for example I pay for house and car with diners, and for mower and vacation with visa), so the graph would look something like this:

*I would like to have legend somewhere inside the graph, like this:

Is this even possible with Excel (or google spreadsheets)? Any other ideas/tools?

A: For the second part of your question, you can replace the legend with data labels:

*

*Right mouse button on legend -> Delete

*Right mouse button on each series in the chart -> Add data labels

*Right mouse button on each set of data labels -> Format data labels -> Under "Label contains" check only "Series name"

For stacked area charts, the default label location is centered horizontally, and vertically aligned with the corresponding data. You can override the default locations by dragging the labels around with the mouse, but then you'll have to manually update them whenever the data changes.


text:
Q: Can a USB C PD connection kill USB A port? I wanted to debug an Android-based device (not a cell phone), and connected its USB C port to my computer's USB A port using a cable with USB C connector on one end and a USB A connector on another end.
The computer (an iMac) turned off immediately after I connected the devices. And it seems to be lethal - the iMac seems to be dead since then.
As I later figured out, it was a wrong port to use on an android device - it wasn't a USB C slave data port for debugging/data transfer, it was a USB C PD port for powering other devices.
The Android device is a point of sale system / kiosk, based on Snapdragon 8xx CPU, if that helps. The USB C port I connected to was at the bottom of the device, right where it had a power adapter. It wasn't the device's port at all, but rather the power adapter's port.
According to the USB C spec, it seems that the power delivery is enabled only after some negotiations, but that negotiation happens only between two USB C ports. What happens if I connect USB C to USB A?
And is it possible to resurrect my computer now, or is it dead forever?

A: Can a USB-C port kill a USB A port?  Maybe, but not if everything is functioning correctly.
If you force a USB C cable into a USB A port, it won't be good for either of them, and you'll probably bend and break stuff and maybe short out the port.  This shouldn't hurt the computer (other than damaging the port), but if the port is not well designed, it is possible it could damage the computer.  But I'm sure this isn't what you meant.
You probably meant you have a cable with a USB C on one end and a USB A on the other end.  Can this damage a computer?  If the cable is not a valid USB cable, it could.  If the cable and USB C port follow USB specs, this is perfectly legitimate and it should not damage anything at all.
As hinted i the comments, your computer turning off could be totally coincidental.  Maybe it ran out of power in the battery just at the moment you plugged the cable in, or maybe you bumped the power button while inserting the cable or something else ...


text:
Q: How to get ATT HANDLE of UUID on BLE Advertiser I have created a simple BLE advertiser using Python's dbus Library (Bluez 5.48).
This sample application adds one service, and and this service has 2 characteristics.
On starting advertiser, all services and Characterictic UUID will be assigned a 16 bit long ATT Handle so that Client can directly read or write on those UUIDs using HANDLEs.
Advertiser works perfectly fine, and Client can subscribe to UUIDs. However Client expects a fixed ATT Handle for both UUIDs. But Advertiser swaps the ATT Handles when reconnected.
So is there any way by which I can either
1- Keep my ATT Handles static.
2- Or Advertiser should know ATT handles assigned to UUIDs.
I have spent good amount of time in finding this out, but got no success so far.
Using this code to create advertiser.
https://github.com/ukBaz/python-bluezero/blob/master/bluezero/peripheral.py

A: I think that BlueZ tries to do the right thing looking at this:
https://git.kernel.org/pub/scm/bluetooth/bluez.git/tree/doc/settings-storage.txt
The issue is likely to be that it only does it with paired devices and that example has security turned off. I can't remember how to turn it on off the top of my head. I'll try to find some time later to take a look.


text:
Q: how to create a GUI java for password and ID using array application will ask the user for an ID and password and whether they are an existing or new user. If you are a new user you will prompted to re-enter your details to confirm id and password and they will then be stored in the array.
Once the user clicks the login button the application will search through an array of IDs and password for verification. (Set your array up to contain a maximum of 10 users – given it is a small array can use linear search)
The application then will display an appropriate message.
my code so far
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;

public class Log extends JFrame
{
    public static void main(String[] args)
    {
        Log frameTabel = new Log();
    }

        JLabel title = new JLabel("Please type your ID and Password");
        JLabel id = new JLabel("ID:");
        JLabel psword = new JLabel("Password:");
        JButton blogin = new JButton("Login");
        JPanel panel = new JPanel();
        JTextField txuser = new JTextField(15);
        JPasswordField pass = new JPasswordField(15);

        JRadioButton radNew = new JRadioButton("New", true);
        JRadioButton radExisting = new JRadioButton("Existing", false);

        ButtonGroup radioGroup1 = new ButtonGroup();

        Log()
        {
            super("Week 9 Question 3");
            setSize(300,250);
            setLocation(600,250);
            panel.setLayout (null);

            title.setBounds(40,5,300,20);
            id.setBounds(52,40,150,20);
            txuser.setBounds(70,40,150,20);
            psword.setBounds(7,80,150,20);
            pass.setBounds(70,80,150,20);
            blogin.setBounds(180,130,80,20);

            radNew.setBounds(30, 130, 50, 20);
            radExisting.setBounds(90, 130, 90, 20);

            panel.add(title);
            panel.add(id);
            panel.add(psword);
            panel.add(blogin);
            panel.add(txuser);
            panel.add(pass);
            add(radNew);
            add(radExisting);
            radioGroup1.add(radNew);
            radioGroup1.add(radExisting);

            map.put("test", "12345");

            getContentPane().add(panel);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            setVisible(true);
            actionlogin();
        }

        public void actionlogin() {
            blogin.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent ae) {
                    String puname = txuser.getText();
                    String ppaswd = new String(pass.getPassword());

                        JOptionPane.showMessageDialog(null, "Correct Information", "Correct",
                                JOptionPane.INFORMATION_MESSAGE);
                    } else {
                        JOptionPane.showMessageDialog(null, "No Password/ID Found on System",
                                "Incorrect", JOptionPane.INFORMATION_MESSAGE);
                        txuser.setText("");
                        pass.setText("");
                        txuser.requestFocus();

                        if (radNew.isSelected()) {

                            }

                            JOptionPane.showMessageDialog(null,
                                    "Re-enter your password and ID to confirm", "Information Saved",
                                    JOptionPane.INFORMATION_MESSAGE);
                        }
                    }
}

            });
        }
}

A: Use
 char[] ppaswd = pass.getPassword();

instead of
String ppaswd = pass.getText();

because

The method getText() from the type JPasswordField is deprecated.

As @MadProgrammer says:

The password is stored in a char array and you never convert it back to a String.
Strings live in the JVM for the life of JVM, making easier for nasty people examine the String pool and find the passwords.

Use a Map to store username/password.
 Map<String, char[]> map = new HashMap<String, char[]>();

put some initial values
    map.put("test", "12345".toCharArray());
    map.put("admin", "admin".toCharArray());

Here is the modified code
public void actionlogin() {
    blogin.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent ae) {
            String puname = txuser.getText();
            char[] ppaswd = pass.getPassword();
            if (map.keySet().contains(puname) && Arrays.equals(map.get(puname), ppaswd)) {
                JOptionPane.showMessageDialog(null, "Correct Information", "Correct",
                        JOptionPane.INFORMATION_MESSAGE);
            } else {
                JOptionPane.showMessageDialog(null, "No Password/ID Found on System",
                        "Incorrect", JOptionPane.INFORMATION_MESSAGE);
                txuser.setText("");
                pass.setText("");
                txuser.requestFocus();

                if (radNew.isSelected()) {
                    if (!puname.equals("") && ppaswd.length > 0) {
                        map.put(puname, ppaswd);
                    }

                    JOptionPane.showMessageDialog(null,
                            "Re-enter your password and ID to confirm", "Information Saved",
                            JOptionPane.INFORMATION_MESSAGE);
                }
            }
        }
    });
}


text:
Q: How to reload angular single page subpages and don't lose content I'm using Spring Boot 1.4.0.M2, Angular 1.5.8, Angular UI Router 0.3.1, and Thymeleaf templating.
What I want to do is to remove hash # from my url I want to something like this:
http://localhost:8080/#/contact
look like this
http://localhost:8080/contact
What I did:

*

*added to my angular configuration.js file something like this:
$locationProvider.html5Mode(true);
$locationProvider.hashPrefix('!');

*added to my userIndex.html head
base href="/userIndex.html"/>
This userIndex.html contains all js libraries, this is my single page index page it contains imports like this:


text:
Q: Cannot reinstall iMessage Extension after explicitly uninstalling I have an iMessage extension included in my main app. Added to the project like so:

And then chose my app Xcode Project from the "Embed in Application" dropdown (I already did this step, the screenshot was taken afterwards to help explain my question):

I pushed a new build to the iTunes Connect and TestFlight. Another tester and myself than explicitly deleted the iMessage extension (NOT the main app) like so:

Now the tester and myself cannot get the embedded iMessage Extension to reinstall. We have explicitly deleted the main app and reinstalled and that did not reinstall the embedded iMessage extension.
I even incremented the build number (not the version number) and pushed another build to TestFlight to try and trigger and fresh reinstall.
I am going to increment the version number of my app now (even though there are no changes) to see if that will get the iMessage Extension to reinstall.
Any other suggestions?

A: It looks the an iPhone will remember an explicit decision to uninstall an iMessage Extension and though a new install of the main app with an embedded iMessage Extension will install the extension again it is now off by default and has to be explicitly reenabled:


text:
Q: Why System.IO.File.Exists doesn't take if else statement I have if condition issues when running the following code for an image file:
    Dim mainFolder As String = "\\Users\No_Image_Available.png"
    Dim saveDirectory As String = "\\IMAGE\"
    Dim Filename As String = System.IO.Path.GetFileName(mainFolder)
    Dim mainSavePath As String = System.IO.Path.Combine(saveDirectory, Filename)

    If System.IO.File.Exists(mainSavePath) Then
        'do nothing
    Else
        'file doesn't exist
        My.Computer.FileSystem.CopyFile("\\Users\No_Image_Available.png", "\\IMAGES\No_Image_Available.png")

    End If

If the file doesn't exist then it will accept the if statements by either IF Not exist or IF exist... however, if the file already exist it will take the copy argument whether it is in the right if condition or not.
Why is that? It is as if it still reads and accepts the first 'do nothing' condition regardless.
FYI- the paths you see are fake

A: Issue was that they were server directories. I made the corrections that worked.
Dim Filename = "No_Image_Available.png"
    Dim savePathcopy As String = Server.MapPath("~/IMAGES/")
    Dim pathToCheckCopy As String = savePathcopy + Filename

    'Dim mainSavePath As String = System.IO.Path.Combine(saveDirectory, Filename)
    If (System.IO.File.Exists(pathToCheckCopy)) Then
        ' If System.IO.File.Exists(noImg) = True Then
    Else
        'file doesn't exist
        My.Computer.FileSystem.CopyFile("\\..\Dev\web\WebUsers\...\..\Classified_Ads_V2\No_Image_Available.png", "\\...\Dev\web\WebUsers\...\..\...\IMAGES\No_Image_Available.png")
    End If


text:
Q: PostgreSQL query returning all "reference" columns in a table Wondering how to use information_schema to query a single table for all the references it has defined on it.
create table article(
  id varchar(255),
  photo int references photos
)

select references from information_schema where table_name = 'article'

Hoping for something like that to list out photo since it's the only reference column in that table.

A: You can try something like below.
information_schema.table_constraints will contain all the constraints with the constraint type and information_schema.key_column_usage will contain the column names and constraint names etc.
KEY COLUMN USAGE
TABLE CONSTRAINTS
So, in order to get the column name, you would have to join both and get your desired output.
SELECT col.column_name
FROM

INFORMATION_SCHEMA.key_column_usage AS col
INNER JOIN
INFORMATION_SCHEMA.table_constraints AS constr

ON col.constraint_name = constr.constraint_name
AND col.table_name = <YOUR TABLE NAME>
AND constr.constraint_type = 'FOREIGN KEY'
AND constr.table_catalog = <YOUR DATABASE NAME>
AND constr.table_schema = 'public';


text:
Q: How to identify different data types within a single column? Let us say that we have a column with the following values:
Apple,
Mango,
Orange,
123,
987,
Guava,
01/01/2020
python recognizes this column as an "object" data type automatically.
I have been given a task to count the number of data types in a single column.
For a human eye, it is evident that there are 3 data types in the above column values: string, int, date.
However, I am unable to come up with a code which could do this segregation.
Looking forward to the guidance!
Thank you!

A: Could you provide some code on what you have attempted? How are you setting up the data structure? Is it an m * n matrix where each column would have a common j in data[i][j]? In that case, it seems like you could just iterate over the matrix rows for the column and use the type() method.
Not knowing a bit more about your setup makes it difficult to provide a solution. Generally data in columns is of a common type.

A: If your data is in the form of a list, you could always do list(map(type, list_name)) to return a list of types.


text:
Q: Check if user is older then 18 in Checkout We have the problem that a customer needs to enter his Date of Birth.
The DOB field is selected as required, however, theres no check for the age itself.
How can I modify templates in order to check if the entered age is >= 18? Checkout process should throw an error if the customer is not at least 18.


text:
Q: How do I force Maven to use external repos to retrieve artifacts? I got following error while trying to build the project. The project is spring project and use IntelliJ with java 8.
Could not find artifact org.springframework.data:spring-data-bom:pom:2021.0.0-M2 in nexus (http://maven:8081/nexus/content/groups/public)

Is there a way to fix it through setting.xml?
I have not access to any configuration on http://maven:8081/nexus/content/groups/public
This is my setting.
<settings
xmlns="http://maven.apache.org/SETTINGS/1.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0
                    http://maven.apache.org/xsd/settings-1.0.0.xsd">

<servers>
    <server>
        <id>releases</id>
        <username>me</username>
        <password>mee</password> <!-- impossible password here :-) -->
    </server>
    <server>
        <id>snapshots</id>
        <username>me</username>
        <password>mee</password> <!-- impossible password here :-) -->
    </server>
    <server>
        <id>nexus</id>
        <username>me</username>
        <password>mee</password> <!-- impossible password here :-) -->
    </server>
</servers>

<mirrors>
    <mirror>
        <!--This sends everything else to /public -->
        <id>nexus</id>
        <mirrorOf>*</mirrorOf>
        <url>http://maven:8081/nexus/content/groups/public</url>
    </mirror>
</mirrors>

<profiles>
    <profile>
        <id>nexus</id>
        <!--Enable snapshots for the built in central repo to direct -->
        <!--all requests to nexus via the mirror -->

        <repositories>
            <repository>
                <id>central</id>
                <url>https://mvnrepository.com/repos/central</url>
                <releases><enabled>true</enabled><updatePolicy>always</updatePolicy></releases>
                <snapshots><enabled>true</enabled><updatePolicy>always</updatePolicy></snapshots>
            </repository>
        </repositories>

        <pluginRepositories>
            <pluginRepository>
                <id>central</id>
                <url>https://mvnrepository.com/repos/central</url>
                <releases><enabled>true</enabled><updatePolicy>always</updatePolicy></releases>
                <snapshots><enabled>true</enabled><updatePolicy>always</updatePolicy></snapshots>
            </pluginRepository>
        </pluginRepositories>
    </profile>

    <profile>
        <id>defaultprofile</id>
        <!-- if you want to be able to switch to the defaultprofile profile put this in the active profile -->

        <repositories>
            <repository>
                <id>maven.default</id>
                <name>default maven repository</name>
                <url>http://repo1.maven.org/maven2</url>
                <releases><enabled>true</enabled><updatePolicy>always</updatePolicy></releases>
                <snapshots><enabled>true</enabled><updatePolicy>always</updatePolicy></snapshots>
            </repository>
            <repository>
                <id>maven.snapshot</id>
                <name>Maven snapshot repository</name>
                <releases><enabled>true</enabled><updatePolicy>always</updatePolicy></releases>
                <url>http://people.apache.org/repo/m2-snapshot-repository</url>
                <snapshots><enabled>true</enabled><updatePolicy>always</updatePolicy></snapshots>
            </repository>
            <repository>
                <id>vaadin-addons</id>
                <url>https://maven.vaadin.com/vaadin-addons</url>
            </repository>
        </repositories>
    </profile>
</profiles>

<activeProfiles>
    <!--make the profile active all the time -->
    <activeProfile>nexus</activeProfile>
</activeProfiles>

A: If you set
    <mirrorOf>*</mirrorOf>
    <url>http://maven:8081/nexus/content/groups/public</url>

then you send every request to this repository, regardless of the rest of the settings.xml. You need to do something like
    <mirrorOf>*,!central</mirrorOf>
    <url>http://maven:8081/nexus/content/groups/public</url>

but please also correct/remove the URLs as khmarbaise said.