text:
Q: Collectors groupingBy based on City I have a person object which has a name and a list of addresses as parameters. The address has a street, type, city, and personId
I want to get a grouping map by the city. I am stuck
This is my code so far :
Map<String,List<Person>> MAP = personRepository.findAll().stream()
         .collect(Collectors.groupingBy(person->person.getAddresses().stream()
         .map(address -> address.getCity())
         ."some kind of collector I assume"))

A: You can do it using flatMap possibly as :
Map<String, List<Person>> finalPersonMap = personRepository.findAll().stream()
            .flatMap(person -> person.getAddresses().stream()
                    .map(address -> new AbstractMap.SimpleEntry<>(address.getCity(), person)))
            .collect(Collectors.groupingBy(Map.Entry::getKey,
                    Collectors.mapping(Map.Entry::getValue, Collectors.toList())));

Assuming the basic models to be like:
static class Person {
    List<Address> addresses;

    List<Address> getAddresses() {
        return addresses;
    }
}

static class Address {
    String city;

    String getCity() {
        return city;
    }
}


text:
Q: Questions about Datomic Quick questions.
1) If I perform a Transaction, when that result of that transaction returns, are all peers updated? Or will the other peers eventually reflect the change of the transaction?
2) How do peers update their state? From what I understand, Peers have direct access to storage, and is their own cache. So when they don't have what you're asking for, I guess they just retrieve it from storage. How do peers know when their information is out of date?
3) How much does the choice of storage/backend matter? Since db's like MySQL and the like were optimized for a server/client relationship, wouldn't it be possible to create a Datomic-optimized storage solution? Or wouldn't it be worth it?

A: 1) The only peer guaranteed to have been updated is the peer requesting the transaction. The others will eventually see the change. If your application requires peer coordination, you need to use the blocking (sync connection t) function to achieve it. For more information, see datomic-docs.
2) The transactor broadcasts new changes to all connected peers. The peers state is composed of the novelty coming from the transactor and the data segments they retrieve directly from storage. Again, the sync function can communicate with the transactor to ensure that a peer blocks until all transactions written before the call to sync are available. Most other functions do not communicate with the transactor or block.
3) If your system doesn't require huge write scalability and your application data tends to fit in memory, then the choice of a particular storage service is generally irrelevant except, of course, for their operational capabilities (backups, admin tools, etc.) which have nothing to do with Datomic. See How does the storage backend influence Datomic? for more details.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Node.js cors request - Async example not working I am using the node-cors module in an app. I've followed some of their examples to make a cors request.
I have a route that I'd like to dynamically add cors options for:
var cors = require('cors'),
    user = require('../models/user');

router.get('/route', cors(corsOptions), function(req, res) {...}

This works (this comes straight from one of the examples):
var whitelist = ['http://example1.com', 'http://example2.com'];
var corsOptionsDelegate = function(req, callback){
  var corsOptions;
  if(whitelist.indexOf(req.header('Origin')) !== -1){
    corsOptions = { origin: true, credentials: true }; // reflect (enable) the requested origin in the CORS response
  }else{
    corsOptions = { origin: false }; // disable CORS for this request
  }
  callback(null, corsOptions); // callback expects two parameters: error and options
};

This, however, doesn't work and I'm not sure what is wrong:
var corsOptions = function(req, callback){
  user.findOne({
        url: req.header('Origin')
    },function(err,match){
        var options;
        if(!empty(match)){
            options = {
                origin:true,
                credentials: true
            };
        }else{
            options = {
                origin: false,
                credentials: false
            };
        }
        callback(null, options);
  });
};

Is this an issue with the module, or something I've implemented wrong?

A: You need to import this:
const cors = require('cors')({origin: true}); instead of const cors = require('cors');


text:
Q: Concentrating Sunlight to initiate fusion reaction The idea is to collect sunlight over a large area, and concentrate it down to the nano scale.
For the sake of discussion lets say you concentrate all the light you collect down to 1000 nanometers (1µm).
Questions is... how much surface area sunlight would you need to collect and focus to 1µm, in order to deliver enough energy density to initiate a fusion reaction.

A: Just to summarize the correct comments by dmckee and Alan.SE:
The second law prevents you from using the Sun (or anything) to heat an object to greater than the surface temperature of the Sun. Otherwise you could take a box of gas at equilibrium  split it into two halves, use lenses and mirrors to focus the radiation from the left half on the right half, and raise the temperature of the right half. Then you could use that temperature difference to run an engine, thereby extracting work from an equilibriated gas in blatant violation of the 2nd Law.
If you do not see how optics prevents you from doing this, you should ask that as a separate question. (Although dmckee and AlanSE have already said the main points in the comments.)
In any case delivering large quantities of energy to objects is not the constraint on fusion. (Militaries are quite good at that sort of thing). The issue is confining the resulting hot mess, and other subsidiary engineering challenges.
Finally, I do appreciate the elegance of using the Sun to power a fusion reaction. But wouldn't it be simpler to use regular solar power to power a fusion reaction? No giant lenses necessary! (Solar cells: cheap - Giant lenses: expensive.)

A: Visible part of spectrum does not get involved to nucleus. Maybe electrons. Which can only make plasma or increase pressure if it is constrained in a cube. If pressure can reach the critical level, then deuterium can be used for fusion(like pressurizing through lazer bombardment).
So, you need sudden increase of pressure right(to increase probability of tunneling and imploding of D-T pellet)? Which also needs high temperatures.
http://en.wikipedia.org/wiki/Radiation_pressure says on earth, 9.15 N per kilometer-square
Deuterium pellet initiating pressure is http://link.springer.com/article/10.1023%2FA%3A1020858108669#page-1
http://www.wolframalpha.com/input/?i=150+MPa 150MN per meter square so you need :
16,393,442,622,950 meter-square of lightened area. 16 Tera Meter Square
This number is for 1-meter-squared area target. Deuterium pellet is micro-meter sized so there are 1,000,000,000,000 pellets on 1m² area, which means only 16meter-square is enough to just to pressurize one of pellets.
Then, if you want to also increase the temperature by a great deal(maybe to heat 1micro-meter pellet to 100M Kelvin), you  would need %3 of earth surface.
For 100M Kelvin, you may need to multiply the result maybe by a million.
Focused and concentrated LASER array is just more applicable for now.
If what you think was applicable, scientists would have used that already.

A: There is another way to do what you are suggesting.  And that is to use an already concentrated form of energy -- lasers.
There are a variety of forms of high energy laser fusion projects underway.  Inertial Confinement Fusion is the fancy term for the leading method. See ICF details here  I would post some illustrations, but I'm not allowed to post images yet :(


text:
Q: PHP JSON array accessing I have a PHP variable, let's say named $products
when I try to print the first element in that variable by printing $products[0], the array print the word (array) on the screen.
how I can access each element in this array? thank you
Array(
[0] => Array
    (
        [id] => 2356
        [title] => REAR BRAKE
        [price] => $0
        [image] => 2356_BRS-10228-1.jpg
        [quantity] => 1
    )

[1] => Array
    (
        [id] => 2358
        [title] => REAR BRAKE MITSUBITSHI
        [price] => $0
        [image] => 2358_BRS-10230-1.jpg
        [quantity] => 1
    )

[2] => Array
    (
        [id] => 2360
        [title] => Axela CX-4
        [price] => $0
        [image] => 2360_BRP-10639-1.jpg
        [quantity] => 1
    )

)

A: you can use foreach loop :
foreach($data as $key =>$value){
echo $value['id'].'<br>';
}

result :
2356
2358
2360


text:
Q: What does the following code do if there is no GPS fix..? If there is no GPS FIX (because the person is in a metal building or something)....does it just stay in the Looper..?? OR does it keep trying for a fix via requestLocationUpdates..??
If I do have a good GPS FIX....my code works fine...and in onLocationChanged()...I update the current location to the database.
Also...when is onLocationChanged() called..?? Is it only called when there is a GPS FIX..??
Just wondering..
    public void run()
    {
        Looper.prepare();

        LocationManager lm = (LocationManager)            getSystemService(Context.LOCATION_SERVICE);
        LocationListener ll = new mylocationlistener();
        lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, ll);

        Looper.loop();
    }

A: Umm, is this in production code? Or are you just curious. This is absolutely not acceptable android code. Take a look at this for an idea on how to correctly implement a locationlistener
http://hejp.co.uk/android/android-gps-example/
when is onLocationChanged() called
Onlocationchanged is called when the parameters that you pass into the requestLocationUpdates(String provider, long minTime, float minDistance, PendingIntent intent) method are met. That is, whenever minTime passes or the device moves minDistance. (Note those are just hints, not exact values)

A: I found out (after alot of testing) that of the GPS fails....it will through an error and crash my service. Instead of killing the app...I just restart the service and try it again.


text:
Q: Is SpamAssassin sensitive against UTF-8 words? let me explain with a simple example:
An email with Order in its subject will trigger SPAM filters such as SpamAssassin.
I want to know if an email subject contains that words translation in Arabic: أطلب or in Persian: سفارش, Does it draw attentions too?


text:
Q: jQuery post can't get entity object as json I need to get my 'Comment' (stored in DAO) object from my controller and display it in my JSP but every time I see the error message from the error block.
Why is this happenning and what should I do?
Logic of my code is the next:

*

*After clicking on the 'Reply' button data from the form is sent to my controller.

*Controller saves data in DB and returns 'Comment' entity.

*I get this 'Comment' entity in my JSP page and use it for publishing on the page.

But I get the error msg from error block instead of msg from the success block.
Here is my form:
<form id="comment_${comment.getCommentId()}">
    <textarea class="textarea" rows="10" name="text"></textarea>
    <input type="hidden" name="bookId" value="${book.getBookId()}" />
    <input type="hidden" name="parentId" />
    <input type="hidden" name="commentId" value="${comment.getCommentId()}" /><br />
    <input type="button" class="button" value="Reply" id="submit_${comment.getCommentId()}" onclick="ajaxsubmit(this.id)"/>
</form>

Here is my script:
<script type="text/javascript">
    function ajaxsubmit(buttonId){
    var formId = document.getElementById(buttonId).parentNode.id;
    var dataString = $("#" + formId).serialize();

    $.ajax( {
        url: "ajaxcomment.htm",
        type: "post",
        data: dataString,
        dataType: "json",
        success: function(data) {
            alert(data.getCommentAdded());
        },
        error: function() {
            alert("error");
        }
    } );
}

Here is my controller
@RequestMapping(value = "ajaxcomment.htm", method = RequestMethod.POST)
public @ResponseBody Comment ajaxcomment(
        HttpServletRequest httpServletRequest,
        @RequestParam(value = "bookId", required = false) Long bookId,
        @RequestParam(value = "parentId", required = false) Long parentId,
        @RequestParam(value = "commentId", required = false) Long commentId,
        @RequestParam(value = "text", required = true) String text) {

    String username = httpServletRequest.getRemoteUser();
    User user = userDao.getUserByUsername(username);

    Comment comment = new Comment();

    // DAO logic

    commentDao.addComment(comment);
    return comment;
}

Here is my 'Comment' entity:
@Entity @Table(name = "COMMENT") public class Comment implements Serializable {

@Id
@GeneratedValue
@Column(name = "COMMENT_ID", nullable = false)
private Long commentId;

@Column(name = "COMMENT_TEXT", length = 512, nullable = true)
private String commentText;

@Column(name = "COMMENT_ADDED", length = 128, nullable = true)
@Temporal(TemporalType.TIMESTAMP)
private Date commentAdded;

@ManyToOne(cascade = CascadeType.REFRESH, fetch = FetchType.EAGER)
@JoinColumn(name = "BOOK_ID")
private Book book;

@ManyToOne(cascade = CascadeType.REFRESH, fetch = FetchType.EAGER)
@JoinColumn(name = "PARENT_ID")
private Comment parentComment;

@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "parentComment")
@OrderBy("commentAdded")
private Collection<Comment> subcomments;

public void setCommentText(String commentText) {
    this.commentText = commentText;
}
public String getCommentText() {
    return this.commentText;
}

// other getters and setters are public too

And here is my applicationContext.xml:
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-2.5.xsd
    http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

<mvc:annotation-driven />
<context:component-scan base-package="com.demo"/>
<context:component-scan base-package="com.demo.service"/>
<context:annotation-config />

<bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
    <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
    <property name="prefix" value="/WEB-INF/jsp/"/>
    <property name="suffix" value=".jsp"/>
</bean>

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/>

<bean id="jacksonMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"/>

<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
    <property name="messageConverters">
        <list>
            <ref bean="jacksonMessageConverter" />
        </list>
    </property>
</bean>

<bean id="exceptionMessageAdapter"
    class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerExceptionResolver">
    <property name="messageConverters">
        <list>
            <!-- Support JSON -->
            <ref bean="jacksonMessageConverter" />
        </list>
    </property>
</bean>

A: It might be that in your form you are setting values like value="${book.getBookId()}" instead of  value="${book.bookId}".
In other words you have to use the expression language by referring to the name of the field in the bean (entity or whatever) rather than trying to use the getter for that field directly.

A: It works.
I've updated my controller method (handler):
@Autowired private DAOComment commentDao;

@RequestMapping(value = "ajaxcomment.htm", method = RequestMethod.POST)
public @ResponseBody String ajaxcomment(
    HttpServletRequest httpServletRequest,
    @RequestParam(value = "bookId", required = false) Long bookId,
    @RequestParam(value = "parentId", required = false) Long parentId,
    @RequestParam(value = "commentId", required = false) Long commentId,
    @RequestParam(value = "text", required = true) String text) {

String username = httpServletRequest.getRemoteUser();
User user = userDao.getUserByUsername(username);

Comment comment = new Comment();

// DAO logic

commentDao.addComment(comment);
return  "{\"id\":\""    + comment.getCommentId() + "\"," +
     "\"username\":\""  + comment.getUser().getUsername() + "\"," +
     "\"text\":\""      + comment.getCommentText() + "\"," +
     "\"added\":\""     + comment.getFormattedDate() + "\"}";
}

I used \" instead of ' because JSON.parse() doesn't parse string like 'param':'value', "param":"value" only.
Updated script:
<script type="text/javascript">
    function ajaxsubmit(buttonId, className){
        var formId = document.getElementById(buttonId).parentNode.id;
        var dataString = $("#" + formId).serialize();
        $.ajax( {
            url: "ajaxcomment.htm",
            type: "post",
            data: dataString,
            dataType: "text",
            success: function(data) {
                var response = JSON.parse(data);

                //This's it.
                alert(response.id);

            },
            error: function() {
                alert("Error has occured.");
            }
        } );
    }
</script>


text:
Q: Problem related to adiabatic invariants
A simple pendulum is oscillating in the gravity field, while its length slowly decreases with time. Determine amplitude of the small oscillations $A$ of the bob, when length of the oscillating part of the string would be reduced by a half. Initial amplitude of the bob is $A_0$.

What approach should I use?

A: This question is a bit confusing since the amplitude does not depend on the oscillations, it's just the length of the pendulum. So either you calculate the rate of change $\frac{dA}{dt}$ or you're dealing with a damped system
But assuming you meant damping then I would suggest you find the damping factor
$$x(t) = A_{\circ}e^{-\gamma t}cos(\omega t) $$
Where $\gamma$ is the damping factor.
This will give you the change in amplitude with time


text:
Q: MvvmCross 6.0 UWP dependency I'm trying to make dependency on UWP by this tutorial https://www.mvvmcross.com/documentation/platform/uwp/universal-windows-platform-uwp?scroll=621
but on this step in Setup.cs:
 public Setup( Frame rootFrame ) : base( rootFrame ){}
I get an error
does anybody have an idea why??
Dependency on Android works well

A: Solution
App.xaml.cs
public partial class App
{
    public App()
    {
        InitializeComponent();
    }
}
public abstract class AWSService : MvxApplication<Setup, Core.App>
{ }

Setup.cs
public class Setup : MvxWindowsSetup<Core.App>
{
    public Setup()
    { }

    protected override IMvxApplication CreateApp()
    {
        Mvx.IoCProvider.RegisterType<IYourInterface, YourNativeClass>();
        return new Core.App();
    }
}


text:
Q: jQuery $("#elementID").click interfers with other elementIDs Htmlshot: http://fallenhero.mysteria.cz/Leetleaflet.htm
Scenario: When I check "Polozka 1", then select "Pulena" and uncheck "Polozka 1", everything works well. But when, after doing the above mentioned process, I check "Polozka 2", the "Polozka 1 box" suddenly appears. Revelation of the "Polozka 1 Box" is bounded to checking "Polozka 1", not "Polozka 2".
Can anyone explain this odd behavior?
Code of the event handlers:
  $('#frmletakForm-polozka1').on("click", function(){
     var pulena1Box = $("#pulena1Box");
     var radioPulena1 = $("#frmletakForm-typpolozky1-1");
     if(!$(this).is(":checked") && radioPulena1.is(":checked")) {
      pulena1Box.toggle();
     }
   });
  $('#frmletakForm-polozka2').on("click", function(){
     var pulena2Box = $("#pulena2Box");
     var radioPulena2 = $("#frmletakForm-typpolozky2-1");
     if(!$(this).is(":checked") && radioPulena2.is(":checked")) {
      pulena2Box.toggle();
     }
   });

Thank you in advance for your help.

A: You better do something like, then you don't have to repeat all the 1,2,3,4 number for each checkbox, and have less code.
$('[id^="frmletakForm-polozka"]').on("click", function(){
    var num = this.id.replace(/[^0-9]/g, "");
    var pulenaBox = $("#pulena" + num + "Box");
    var radioPulena = $("#frmletakForm-typpolozky" + num + "-1");
    if(!$(this).is(":checked") && radioPulena.is(":checked")) {
        pulenaBox.toggle();
    }
});

I also get these errors from your page:
Uncaught TypeError: Cannot read property 'id' of undefined Leetleaflet.htm:1446
Uncaught TypeError: Cannot read property 'id' of undefined saved_resource.htm:735
5Unable to post message to http://googleads.g.doubleclick.net. Recipient has origin http://fallenhero.mysteria.cz.

A: The error is caused with your use of nette.toggle
For example the code
    visible = true; val = nette.getValue(form["typpolozky1"]); res = (val=="p"); visible = visible && res;

    nette.toggle("pulena1Box", visible);

Is only checking the value of the select list and not if the enclosing container is visible.
Since this whole function is run for all of the aux items -- they will get shown each time there is a change in the form if the item they are checking is selected.


text:
Q: Unable to solve logarithm question Given
$$\dfrac{a(b+c-a)}{\log a}=\dfrac{b(c+a-b)}{\log b}=\dfrac{c(a+b-c)}{\log c}$$
To prove:
$$a^bb^a=b^cc^b=c^aa^c$$
What i tried is
$$\log (a^z)=a(b+c-a)$$ and similarly for other two. I am unable to break this down further! please help!

A: Just like in your other question,
$$\log a = \lambda\cdot a(b+c-a)$$
and so on give:
$$ b\log a +a\log b = \lambda\cdot\left(ab(b+c-a)+ab(a+c-b)\right)=2\lambda\cdot abc$$
that is symmetric in $a,b,c$, so by exponentiating the previous line
$$ a^b b^a = a^c c^a = b^c c^b $$
follows.


text:
Q: AngularJS ui-router inconsistently behaving on manual refresh On an application my team and I are working on, we're observing some inconsistent behavior.  When a user performs a browser refresh, the refresh button fully refreshes the page including UI state...but only does that up to a certain route.
Our App starts on the /Home route, which sets up the overall application, as well as the component hierarchy.  The user proceeds to A.A, A.B, A.C, which all function fine.  B.A works fine as well.
Then, trouble.  If you perform a browser refresh from B.B or B.C, you get returned to B.A.  We expect that the end-user would be returned to B.B or B.C if they refresh from those pages.
Routes.ts
    $stateProvider
        .state('Home',
        {
            url: '/Home',
            templateUrl: 'App/Home/home.html',
            controller: 'homeCtrl',
            controllerAs: '$ctrl'
        })
        .state('A',
        {
            url: '/A',
            templateUrl: 'app/A/A.html',
            controller: 'aCtrl',
            controllerAs: '$ctrl'
        })
            .state('A.A',
            {
                url: '/A.A',
                component: 'aPartA'
            })
            .state('A.B',
            {
                url: '/A.B',
                component: 'aPartB'
            })
            .state('A.C',
            {
                url: '/A.C',
                component: 'aPartC'
            })
        .state('B',
        {
            url: '/B',
            component: 'b'
        })
            .state('B.A',
            {
                url: '/B.A',
                component: 'bPartA'
            })
            // Beyond this part, oddness starts...
            .state('B.B',
            {
                url: '/B.B',
                component: 'bPartB'
            })
            .state('B.C',
            {
                url: '/B.C',
                component: 'bPartC'
            });

    $urlRouterProvider.otherwise('/Home');

    $locationProvider.html5Mode({ enabled: true});

The way we actually perform our routing, is using a component!
Relevant HTML:
<order-navigation validate-view="$ctrl.validate(someForm)"
     previous-route="A.C"
     previous-button-text="previous"
     next-route="B.A"
     next-button-text="continue">
</order-navigation>

Order Navigation Component Controller:
export class OrderNavigationCtrl implements angular.IController {
    //#region Variables / Properties

    public nextRoute: string;
    public previousRoute: string;
    public nextButtonText: string;
    public previousButtonText: string;
    public validateView : () => boolean;

    //#endregion Variables / Properties

    //#region Constructor

    public static $inject: string[] = ['$state', '$window'];
    constructor(
        private $state: angular.ui.IStateService,
        private $window: angular.IWindowService) {
    }

    public $onInit(): void {

    }

    //#endregion Constructor

    //#region Methods

    public navigatePrevious(route: string): void {
        if (route.search('www') > 0)
            this.$window.open(route, '_self');
        else
            this.$state.go(route);
    }
    public navigateNext(route: string): void {
        if (this.validateView())
            this.$state.go(route);
    }

    //#endregion Methods
}

I've checked each page's HTML, and found no typos that would cause B.B or B.C to redirect to B.A.  As we're using a common component, I would expect that if the flaw were in the component controller, it would affect all pages equally, and cause any page refresh to fall back to a common point, which is not the case.
Questiosn:
A: What's causing B.B and B.C to redirect to B.A, instead of themselves?
B: In what way can I change this to ensure that B.B and B.C redirect to themselves?
Possible Workaround:
One thing my research has suggested that I can do is to use localStorage and .run() to cache the UI router state.  I would like to avoid this, because ideally this routing should 'just work'; we're not doing anything special.  If there is something we're doing incorrectly in this, I also need to know what it is, so that my team and I don't do that incorrect thing.

A: The problem was that the 'B' 'trunk' route was incorrect.  It should be:
.state('B', {
    url: '/B',
    templateUrl: 'app/A/A.html',
    controller: 'aCtrl',
    controllerAs: '$ctrl'
})
    .state('B.A', {
        // ...Other B substates here...
    })

It appears that, defining a 'trunk' view as a component has some awkward relationships with the UI router setup.  Instead, a trunk view should always be defined in a more classic manner, with the URL, controller/controller as setup defined.  When this happens, child component states can work in the manner that we expect.


text:
Q: Variable t is never used this belove is my load_data java class. I got only the variable s displayed on screen because "variable t is never used". Could someone please tell me where I can find it?
package etn.transport.transporteexpress;

import...

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class display_clicked_load extends AppCompatActivity {

    String id;
    String loginemail;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_display_clicked_load);
        mLockScreenRotation();
        Button send = (Button) findViewById(R.id.sendbutton);

        id = getIntent().getStringExtra("id");
        String shipping_date = getIntent().getStringExtra("shipping_date");
        String shipping_time = getIntent().getStringExtra("shipping_time");
        String shipping_address_address = getIntent().getStringExtra("shipping_address_address");
        String shipping_address_postal_code = getIntent().getStringExtra("shipping_address_postal_code");
        String shipping_address_city = getIntent().getStringExtra("shipping_address_city");
        String shipping_address_nation = getIntent().getStringExtra("shipping_address_nation");
        String description = getIntent().getStringExtra("description");
        String weight = getIntent().getStringExtra("weight");
        String destination_date = getIntent().getStringExtra("destination_date");
        String destination_time = getIntent().getStringExtra("destination_time");
        String destination_address_address = getIntent().getStringExtra("destination_address_address");
        String destination_address_postal_code = getIntent().getStringExtra("destination_address_postal_code");
        String destination_address_city = getIntent().getStringExtra("destination_address_city");
        String destination_address_nation = getIntent().getStringExtra("destination_address_nation");

        //loginemail = getIntent().getStringExtra("loginemail");

        loginemail=global.email1;

        TextView loaddate = (TextView) findViewById(R.id.txtloaddate);
        TextView loadtime = (TextView) findViewById(R.id.txtloadtime);
        TextView loadplace = (TextView) findViewById(R.id.txtloadplace);
        TextView txtdesc = (TextView) findViewById(R.id.txtdescription);
        TextView txtweight = (TextView) findViewById(R.id.txtweight);
        TextView txtdestdate = (TextView) findViewById(R.id.txtdestinationdate);
        TextView txtdesttime = (TextView) findViewById(R.id.txtdestinationtime);
        TextView txtdestplace = (TextView) findViewById(R.id.txtdestplace);

       /* String s = "Shipping Date:" + shipping_date.toString();
        loaddate.setText(Html.fromHtml(s));

        String t = "Time:" + shipping_time.toString();
        loadtime.setText(Html.fromHtml(t));

        String u = "shipping_address" + shipping_address_address.toString();
        loadplace.setText(Html.fromHtml(u));

        String v = "Description:" + description.toString();
        txtdesc.setText(Html.fromHtml(v));

        String w = "Weight:" + weight.toString() + " KG";
        txtweight.setText(Html.fromHtml(w));

        String x = "Destination Date:" + destination_date.toString();
        txtdestdate.setText(Html.fromHtml(x));

        String y = "Time:" + destination_time.toString();
        txtdesttime.setText(Html.fromHtml(y));

        String z = "Destination Address:" + destination_address_address.toString();
        txtdestplace.setText(Html.fromHtml(z));
*/

        String s = getResources().getString(R.string.shipping_date, shipping_date.toString());
        loaddate.setText(Html.fromHtml(s));
        String t= getResources().getString(R.string.shipping_time, shipping_time.toString());
       /* loaddate.setText(Html.fromHtml(t));
        String u= getResources().getString(R.string.shipping_address_c, shipping_address_address.toString());
        loaddate.setText(Html.fromHtml(u));
        String v= getResources().getString(R.string.transport_description_c, description.toString());
        loaddate.setText(Html.fromHtml(v));
        String w= getResources().getString(R.string.weight, weight.toString());
        loaddate.setText(Html.fromHtml(w));
        String x= getResources().getString(R.string.destination_date, shipping_date.toString());
        loaddate.setText(Html.fromHtml(x));
        String z= getResources().getString(R.string.destination_time, destination_time.toString());
        loaddate.setText(Html.fromHtml(y));
        String z= getResources().getString(R.string.destination_address, destination_address.toString());
        loaddate.setText(Html.fromHtml(z));
       /* loaddate.setText(Html.fromHtml(s));
       loadtime.setText("Time:" + shipping_time.toString());
        loadplace.setText("Shipping Address:" + shipping_address_address);
        txtdesc.setText("Description:" + description);
        txtweight.setText("Weight: " + weight + " KG");
        txtdestdate.setText("Destination Date:" + destination_date.toString());
        txtdesttime.setText("Time:" + destination_time.toString());
        txtdestplace.setText("Destination Address:" + destination_address_address);
*/

        send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                new myTask().execute();

            }
        });

    }

    class myTask extends AsyncTask<Void, Void, Void> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            Log.d("inside", "onPre");
        }

        @Override
        protected Void doInBackground(Void... voids) {
            Log.d("inside", "DoIn");
            sendData();
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            AlertDialog.Builder dlgAlert  = new AlertDialog.Builder(display_clicked_load.this);
            dlgAlert.setMessage("Quotation Send Successfully");
            dlgAlert.setTitle("Quotation Confirmation");
            dlgAlert.setPositiveButton("OK", null);
            dlgAlert.setCancelable(true);
            dlgAlert.create().show();
        }
    }

    public void sendData() {
        try {
            String ssendoffer;
            String email;
          //  email=getIntent().getStringExtra("loginemail");

            EditText sendoffer = (EditText) findViewById(R.id.sendoffer);
            ssendoffer=sendoffer.getText().toString();
            loginemail=global.email1;
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost("http://www.testsite.com/folder/myfile.php");
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(13);
            nameValuePairs.add(new BasicNameValuePair("amount", ssendoffer));
            nameValuePairs.add(new BasicNameValuePair("email",loginemail));
            nameValuePairs.add(new BasicNameValuePair("quotation_id",id));

            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            HttpResponse hresponse = httpclient.execute(httppost);
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            Log.d("error....", e + "");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            Log.d("error.......", e + "");
        }

    }
    private void mLockScreenRotation() {
        // Stop the screen orientation changing during an event
        switch (this.getResources().getConfiguration().orientation) {
            case Configuration.ORIENTATION_PORTRAIT:
                this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                break;
            case Configuration.ORIENTATION_LANDSCAPE:
                this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                break;
        }
    }
}

screenshot

A:  String t= getResources().getString(R.string.shipping_time, shipping_time.toString());
 /* loaddate.setText(Html.fromHtml(t)); */

Quite simply you defined variable t but commented out where you used it. This is not an error, this is a warning.
In the future, search for "t=" or if you use common coding standards "t =" through the Find feature (typically Ctrl+F).  I'm not sure how this was difficult, the variables are alphabetized and I'm sure your IDE put a squiggle under it.


text:
Q: How to use readField in apollo client polices for sub selecting a query that has arguments Using @apollo/client 3.4.7
I have been following this great blog by Dan Reynolds https://www.apollographql.com/blog/apollo-client/architecture/redux-to-apollo-data-access-patterns/ which explains moving from a Redux world to an Apollo GraphQL world. A nice part of Redux is the ability to use selectors to select portions of data from your state. In Apollo land you are able to run queries, but sometimes you already have your data and only need a subset of it. The blog goes into some nice detail explaining you can do something akin to:
const schema: TypePoliciesSchema = {
  typeDefs: gql`
    extend type Query {
      readManagers: [Employee!]!
    }
  `,
  typePolicies: {
    Query: {
      fields: {
        readManagers: {
          read(employees, context) {
            const employees = readField<Query, 'readEmployees'>(context, 'readEmployees');

            return employees.filter(employeeRef => {
              const employeeRole = readField<Employee, 'role'>(context, 'role', employeeRef);
              return employeeRole === EmployeeRole.Manager;
            });
          },
        }
      }
    }
  }
}

This is based on a simple GraphQL query:
query GetEmployees {
  employees {
    id
    name
    role
    team
  }
}

My question is how can you get the query results when your query has parameters:
query GetEmployees($companyId: ID!) {
  employees(companyId: $companyId) {
    id
    name
    role
    team
  }
}

Suddenly you can't get access to readEmployees because the cache key is now something like readEmployees({"companyId": "uuid"})?
I appreciate that you may have to setup the readManagers query to use params too, to get the same ID to be able to make a sub selection. I tried manually fudging the query key to match but it didn't work.
My work around at the moment is to use the cache from the context and run the same query and many convert them to references with toReference:
const schema: TypePoliciesSchema = {
  typeDefs: gql`
    extend type Query {
      readManagers: [Employee!]!
    }
  `,
  typePolicies: {
    Query: {
      fields: {
        readManagers: {
          read(employees, context) {
            const employees = context.cache.readQuery('readEmployees', { variables: { companyId: context.args.companyId || context.variables.companyId } } );
            return employees.filter(employeeRef => {
              const employeeRole = readField<Employee, 'role'>(context, 'role', employeeRef);
              return employeeRole === EmployeeRole.Manager;
            });
          },
        }
      }
    }
  }
}

This doesn't feel like the best solution, and feels like a lot of boilerplate for reading a sub selection of the cache.

A: According to the answer from github issue you can use another form of readField function which takes object.
Then you can use it in your type policy definition to read data with arguments
 users: {
        read(users, { args, readField }) {
             const { where: { id } } = args;

             const users = readField({
                fieldName: 'Users',
                args: { where: { id } },
              });

             return users;
        },
   }


text:
Q: Alternative to Ctrl-R reverse search in bash I am happy and really like the Ctrl-R backward search feature of the bash shell. Some of my colleagues don't like it, since it is sometimes confusing. I understand them. If you enter the wrong characters, the current position in the history is somewhere in the past, and you won't find the recent matches.
Is there a more user friendly alternative for seaching backward in the shell history?
I want to stick with bash. Suggesting an alternative shell is not an answer to this question.
The issue with the "lost position" is explained here: Reset bash history search position. These solutions work. That's right. But the solution there are not easy and user friendly according to my point of view. These solutions are not simple and straight forward. These are solutions of the past. In the past the human needed to learn the way the computer wanted the input. But today the tools should accept the input in a way which is easy for the user.
Maybe someone knows a IDE of jetbrains like PyCharm. If you search for "foobar" you even get the lines which contain "foo_bar". That's great, that's unix :-)

A: I'm using the fuzzy finder program FZF. I've written my own key bindings and shell scripts to utilize FZF as my tool of choice to reverse-search an interactive Bash shell's history. Feel free to copy and paste the code from my Config GitHub repository.
~/.bashrc configuration file
# Test if fuzzy finder program _Fzf_ is installed.
#
if type -p fzf &> /dev/null; then

  # Test if _Fzf_ specific _Readline_ file is readable.
  #
  if [[ -f ~/.inputrc.fzf && -r ~/.inputrc.fzf ]]; then

    # Make _Fzf_ available through _Readline_ key bindings.
    #
    bind -f ~/.inputrc.fzf
  fi
fi

~/.inputrc.fzf configuration file ##
$if mode=vi

  # Key bindings for _Vi_ _Insert_ mode
  # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  set keymap vi-insert

  "\C-x\C-a": vi-movement-mode
  "\C-x\C-e": shell-expand-line
  "\C-x\C-r": redraw-current-line
  "\C-x^": history-expand-line
  "\C-r": "\C-x\C-addi$(HISTTIMEFORMAT= history | fzf-history)\C-x\C-e\C-x\C-r\C-x^\C-x\C-a$a"

  # Key bindings for _Vi_ _Command_ mode
  # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  set keymap vi-command

  "\C-r": "i\C-r"
  "\ec": "i\ec"

$endif

fzf-history executable Bash script
#!/usr/bin/env bash
#
# Retrieve command from history with fuzzy finder
# ===============================================
# Tim Friske <me@tifr.de>
#
# See also:
#   * man:bash[1]
#   * man:fzf[1]
#   * man:cat[1]

shopt -os nounset pipefail errexit errtrace
shopt -s extglob globstar

function print_help {
  1>&2 cat \
<<'HELP'
usage:
  HISTTIMEFORMAT= history | fzf-history
HELP
}

function fzf_history {
  if [[ -t 0 ]]; then
    print_help
    exit
  fi

  local fzf_options=()
  fzf_options+=(${FZF_DEFAULT_OPTS:-})
  fzf_options+=('--tac' '-n2..,..' '--tiebreak=index')
  fzf_options+=(${FZF_HISTORY_FZF_OPTS:-})
  fzf_options+=('--print0')

  local cmd='' cmds=()
  while read -r -d '' cmd; do
    cmds+=("${cmd/#+([[:digit:]])+([[:space:]])/}")
  done < <(fzf "${fzf_options[@]}")
  if [[ "${#cmds[*]}" -gt 0 ]]; then
    (IFS=';'; printf '%s\n' "${cmds[*]}")
  fi
}

fzf_history "$@"

key-bindings.bash sourceable Bash script
Taken and slightly adapted from FZF's Bash key bindings file here are the Emacs mode compatible key bindings for Bash's history reverse-search with Ctrl-R (untested):
if [[ ! -o vi ]]; then
  # Required to refresh the prompt after fzf
  bind '"\er": redraw-current-line'
  bind '"\e^": history-expand-line'

  # CTRL-R - Paste the selected command from history into the command line
  bind '"\C-r": " \C-e\C-u\C-y\ey\C-u$(HISTTIMEFORMAT= history | fzf-history)\e\C-e\er\e^"'
fi

A: *

*Up arrow: only practical for very recent stuff.

*grep blablabla ~/.bash_history: you will have to set bash to save history to file after each command.

From my ~/.bashrc You may want to find out what the commands do and tweak.
# don't put duplicate lines in the history. See bash(1) for more options
HISTCONTROL=ignorespace:ignoredups:erasedups
HISTFILESIZE=99999
HISTSIZE=99999
export PROMPT_COMMAND="history -a; $PROMPT_COMMAND"
# append to the history file, don't overwrite it
shopt -s histappend
#history
shopt -s cmdhist
shopt -s histreedit
shopt -s histverify
shopt -s lithist

A: For what it's worth, if you disable the stop/start feature of your tty (that you probably don't use that much), you can change the search direction by pressing Control-S.
% stty stop undef

% true str1
% true str2
% true str3
% true str4
Control-R => (reverse-i-search)`str': true str4
Control-R => (reverse-i-search)`str': true str3
Control-S => (i-search)`str': true str3
Control-S => (i-search)`str': true str4

As to those keybindings not being "user-friendly" or intuitive, they're emacs keybindings. emacs is not for everybody, there's no surprise there (though I know secretaries and other not-so-pretentious individuals which were able to master them in no time and without much fuss). It's more of a culture thing.

A: McFly is another option. It's very easy to install - you can do it through brew or just download the latest binary. It's written in Rust so they're statically linked. No dependency nonsense.
Then just add this to your .bashrc/.zshrc:
eval "$(mcfly init bash)" # or zsh

It gives you a full-screen UI sorted in some intelligent way.

A: FZF comes with support for bash (also zsh & fish).
@Tim Freske's answer describes their modifications for vi style keybinding.
Default key bindings are emacs style. Which even overrides the Ctrl-r behavior to fuzzy find without losing position.
They may not be enabled by default. To enable them add this to .bashrc:
source /usr/share/doc/fzf/examples/key-bindings.bash

(If this doesn't work, do apt-cache show fzf and find ...fzf/README... file, it lists commands for bash, zsh, fish and vim)


text:
Q: Trying to run this sql but I'm not sure if I'm doing it right Hi I'm trying to run this sql but as I'm new to sql I'm getting errors and not sure if I'm doing it right.
SELECT DISTINCT
 V1.TREE_NAME AS "MSTR_ACCOUNT_ALL",
 V1.TREE_NODE AS "REAL_ESTATE_EXP",
 V1.REPORT_TYPE AS "C",
 V1.ACCOUNT FROM PS_ACCT V1
INNER JOIN PS_TRAN F1 ON F1.ACCOUNT = V1.ACCOUNT
INNER JOIN PS_ACCT V2 ON V2.REPORT_TYPE = F1.REPORT_TYPE
 where F1.ACCOUNT = V1.ACCOUNT

and I'm getting this error
DB2 Database Error: ERROR [42703] [IBM][DB2/AIX64 SQL0206N  "V1.PS_ACCT.ACCOUNT" is not valid in the context where it is used. SQLSTATE=42703

A: There are a few problems with your query.
Firstly, you only need to refer to the table alias, not the full table name, e.g.:
SELECT DISTINCT V1.TREE_NAME = 'MSTR_ACCOUNT_ALL',
     V1.TREE_NODE = 'REAL_ESTATE_EXP',
     V1.REPORT_TYPE = 'C'
     V1.ACCOUNT
  FROM PS_ACCT V1
  INNER JOIN PS_TRAN F1 ON F1.ACCOUNT = V1.ACCOUNT
  INNER JOIN PS_ACCT V2 ON V2.REPORT_TYPE = F1.REPORT_TYPE
  where F1.ACCOUNT = V1.ACCOUNT

Secondly, your "where" clause merely restates the join condition between F1 and V1, so you can safely omit it (this wouldn't cause any error, though):
SELECT DISTINCT V1.TREE_NAME = 'MSTR_ACCOUNT_ALL',
     V1.TREE_NODE = 'REAL_ESTATE_EXP',
     V1.REPORT_TYPE = 'C'
     V1.ACCOUNT
  FROM PS_ACCT V1
  INNER JOIN PS_TRAN F1 ON F1.ACCOUNT = V1.ACCOUNT
  INNER JOIN PS_ACCT V2 ON V2.REPORT_TYPE = F1.REPORT_TYPE

Finally, your SELECT clause merely needs to list the columns you wish to report - the = is not valid syntax here:
SELECT DISTINCT
     V1.TREE_NAME,
     V1.TREE_NODE,
     V1.REPORT_TYPE,
     V1.ACCOUNT
FROM PS_ACCT V1
INNER JOIN PS_TRAN F1 ON F1.ACCOUNT = V1.ACCOUNT
INNER JOIN PS_ACCT V2 ON V2.REPORT_TYPE = F1.REPORT_TYPE

Now, it's not clear from the very limited info you have supplied whether the PS_ACCT table/view has a column called REPORT_TYPE. If it doesn't, the query will fail as you have referred to the V1 alias here.


text:
Q: Conditional move loop - VBA excel I just learned to use VBA in excel, I have a spreadsheet as shown,

I have columns from B1:B12 containing content to search and move, I want to build code to search Move the characters in the range C13:AD31 to the same row in the range from C1:AD12.
For example, in the area C13:AD31, there is a subregion E14:J14 containing the content "Vn" which is the same as B2, then move (cut + paste) E14:J14 to E2:J2, and continue the loop until moved all the characters in the area C13:AD31 (in other words A13:AD31 only left all empty cells). The loop I want will return the result as shown below.

-----a-----++++
(Update 3/31/2022)
Thank you VBasic2008 your code is amazing,
sorry to bother you again, indeed I can't understand every single content in your code, so I still can't customize the code to fit my generated data. Currently my excel sheet has generated 169 lines.
This time I have columns from B40:B51 and B127:B138 containing content to search and move.

Screenshot of column B40: B51

The loop I want will return the result as shown below.

A: Update Missing Data
Option Explicit

Sub UpdateData()

    Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code
    Dim ws As Worksheet: Set ws = wb.Worksheets("Sheet1")
    Dim rg As Range
    With ThisWorkbook.Worksheets("Sheet1").UsedRange
        Set rg = .Resize(, .Columns.Count - 1).Offset(, 1)
    End With

    Dim cell As Range
    Set cell = rg.Columns(1).Find("*", , xlValues, , , xlPrevious)
    Dim drCount As Long: drCount = cell.Row - rg.Row + 1
    Dim cCount As Long:  cCount = rg.Columns.Count - 1

    Dim lrg As Range: Set lrg = rg.Cells(1).Resize(drCount) ' Lookup
    Dim drg As Range: Set drg = lrg.Resize(, cCount).Offset(, 1) ' Destination

    ' Source
    Dim srCount As Long: srCount = rg.Row + rg.Rows.Count - cell.Row - 1
    Dim srg As Range: Set srg = rg.Resize(srCount, cCount).Offset(drCount, 1)

    Debug.Print lrg.Address, drg.Address, srg.Address, cCount

    Application.ScreenUpdating = False

    Dim srrg As Range
    Dim sValue As Variant
    Dim drIndex As Variant
    Dim c As Long

    For Each srrg In srg.Rows
        If Application.CountBlank(srrg) < cCount Then
            For c = 1 To cCount
                sValue = srrg.Cells(c).Value
                If Not IsError(sValue) Then
                    If Len(sValue) > 0 Then
                        drIndex = Application.Match(sValue, lrg, 0)
                        If IsNumeric(drIndex) Then
                            srrg.Cells(c).Copy drg.Cells(drIndex, c)
                        End If
                    End If
                End If
            Next c
        End If
    Next srrg

    Application.ScreenUpdating = True

    MsgBox "Data updated.", vbInformation

End Sub


text:
Q: python 3 форматирование текста Есть код:
print("Сумма вашего кредита {0:.2f} за  период {1:d} месяцев. Ежемесячный взнос, составит {2:.2f} "+\
      "в месяц процент банка ежемесячно составит {3:.2f} !".format(creditSum, period, result, bankProcent))

Выводит только последние значение адекватно, все остальные как строку. Поясните в чем ошибка?

A: Внимательно посмотрите на свой код:
print("Сумма вашего кредита {0:.2f} за период {1:d} месяцев. Ежемесячный взнос, составит {2:.2f} "+\
      "в месяц процент банка ежемесячно составит {3:.2f} !".format(creditSum, period, result, bankProcent))

Вы склеиваете две строки, при этом метод format применяется только ко второй.


text:
Q: Is this a secure way of connecting to an SQL server? Suppose I have a .php script on my server which interacts with a MySQL server. Part of it is:
function sqlQuery($queryString) {
    ...
    $mysqli = new mysqli("theHost:some-port",
                         "DB_allowed_username",
                         "password123", "dbName");
    ...
}

This script is solely server-side, and something like DevTools or view-source://web.address will not show the source code.
However, it is really important that nobody is able to see this source code because it bears my username and password for one of the privileged users of the database. Is there some other way someone could discover these details, and if so, how do I hide them more securely?
Note:- currently I have an SSL certificate but it is not guaranteed that I will have it indefinitely.

A: Browsers can see the PHP code only if your http server becomes misconfigured. I have seen this happen for example on Apache if the PHP handler directives are removed from the httpd.conf file. Then the code in .php files is delivered to browsers as-is.
A good way to protect your password against that (rare) possibility is to store the password in a config file that is read by your PHP code, and put the config file outside the Apache document root directory.


text:
Q: Customizing  borders using CSS I am trying to create a web page that looks like like in this site:

I tried creating an image with that design(the one in the middle with a white background and pointy edges on the top and bottom) but the result is that the image is static and does not dynamically change when the content of the page changes.
I do not know if I can implement the design by customizing the
 borders or upload the design as a background image then dynamically create it.
Thanks for all the help.

A: If you don't want to use CSS3 (for more browser support) use the following structure:

         your dynamic content here

where pointyHeader and pointyFooter have a fixed height and background image.
Working jsFiddle

A: I thought of a .box { position: relative; }
and a .top { position: absolute; top: 0; } and same with bottom .bottom { position: absolute; bottom: 0;}
check it here: http://jsfiddle.net/DyG8F/


text:
Q: Vagrant/homestead: too many arguments I´m installing vagrant+homestead for a new laravel project.
When I write the command 'vagrant up' to the terminal, there is an error msg: 'Check your Homestead.yaml (or Homestead.json) file, the path to your private key does not exist.'
At first, according to the video tutorial, I tried to solve it with: 'ssh-keygen -t rsa -f ~/.ssh/id_rsa'.
The error msg changed to: 'Saving key "/home/serverkeys/.ssh/id_rsa" failed: No such file or directory'
Then I found out, it could work when creating a folder (c:/users/havon/.ssh) for adding the path: 'c:/users/havon/.ssh/id_rsa' at the end of the command.
It is not. The error msg: 'too many arguments'.
Now it looks like this: ssh-keygen -t rsa -f ~/.ssh/id_rsa "c:/users/havon/.ssh/id_rsa"
And it doesnt work. Please, help.

A: I resolve it with: ssh-keygen -t rsa -C "you@homestead".
Then it ask you for path with a msg:
Enter file in which to save the key (c:/users/havon/.ssh/id_rsa):
This works for me.


text:
Q: Catching an exception when creating a new SoapClient properly I'm having a difficult time catching a SoapClient authentication issue.  When my code executes, Laravel declares it's throwing an ErrorException but I can't seem to catch it no matter what code I use.  I'm tagging Laravel in case there's some magic going on somewhere I don't know about because App::error() will trigger on this error still.
try {
    $client = new SoapClient(
        $this->serviceUrl . $this->clients[$clientName],
        array(
            'login'      => $this->username,
            'password'   => $this->password,
            'exceptions' => true,
        )
    );
} catch (SoapFault $e) {
    die('soapfault never fires!');
} catch (Exception $e) {
    die('exception won\t t');
} catch (ErrorException $e) {
    die('error exception also doesn\'t error');
}

According to Laravel an ErrorException is being thrown but the above code doesn't catch it.
ErrorException

SoapClient::SoapClient(https://control.akamai.com/nmrws/services/RealtimeReports?wsdl) [soapclient.soapclient]: failed to open stream: HTTP request failed! HTTP/1.1 401 Unauthorized

A: Add backslash before exception types (e.g. Exception becomes \Exception).
They belong to global namespace. Your code tries to catch exceptions in currently used namespace which doesn't have to be the same as global.


text:
Q: cmake and make build reproductibility I'm evaluating the use of cmake to generate makefile for embedded FW. The cmakelists.txt will be shared in the team.

*

*Can you confirm the makefile cannot be shared between different computers ?

*Is this still true if project path is identical on both computers ?

*Using cmake makefile generation and same version of compiler, will the generated binary be the same on all computers ?

*Is this the same behavior as a makefile shared in the project ?

A: Why would you share a generated makefile anyway!? You usually share the cmake files.

*

*Can you confirm the makefile cannot be shared between different computers ?

You should not share the makefile. It's generated only for you and includes local information as well as the cmake (cached) options and state. There's no serious reason to actually do this!

*Is this still true if project path is identical on both computers ?

Yes, because cmake maintains a cache of settings, options etc. So the makefile may differ depending on paths, options and states. You also have to guarantee the paths for any dependency.

*Using cmake makefile generation and same version of compiler, will the generated binary be the same on all computers ?

If environment (Compiler, libraries, …) and options (build type, project options, …) are same, Cmake will reliable produce exact the same binaries on all systems.

*Is this the same behavior as a makefile shared in the project ?

No, CMake is much better: it's cross-platform. It doesn't depend on make, you can use any other system (like ninja or an IDE project) too – without touching your source or cmake code.
CMake does much more than just creating a makefile. You can even compile a CMake based project with several different compiler / cross-compiler without a single change.
TL;DR
Don't share generated Makfiles, share the Cmake sourcefiles instead – that's what CMake is used for.

A: In theory, if your project path, toolchain path, toolchain version, and the path to every external library used by the project is the same on different computers, then you can move the generated Makefile between them without regenerating.  When you run make it might detect that things have changed and try to rerun CMake, though.  I'm not sure why you'd want to do this, however, it seems like kind of bad practice.
If the compilers, libraries, and code are the same, the same code will get generated (unless your compiler has some sort of bug).


text:
Q: weatheR data package using weatheR package i need data from a specific station, so i tried to use getStationByID funciont.
The station is GROTTAGLIE and in my station.list df its USAF id is 163240:
require(devtools)
install_github("mpiccirilli/weatheR")
require(weatheR)
station.list <- allStations()

station.list %>% filter(USAF==163240)

USAF     WBAN       NAME   CTRY   STATE    ICAO    LAT    LON      ELEV    BEGIN      END
 163240   99999  GROTTAGLIE  IT           LIBG    40.518    17.403    65.5    19430927 20170710

if i launch the funcion
grottaglie<- getStationByID(stationID = '163240',station.list = station.list, begin = 2013, 2016)

i get

Error in names(combined.list)[i] <- keys[i] :
      'names' attribute [1] must be the same length as the vector [0]

any suggestions?

A: You can use rnoaa
install.packages("rnoaa")
library(rnoaa)
(res <- isd(usaf=163240, wban=99999, year=1986))
#> # A tibble: 7,364 x 78
#>    total_chars usaf_station wban_station     date  time date_flag latitude longitude type_code elevation
#>          <chr>        <chr>        <chr>    <chr> <chr>     <chr>    <chr>     <chr>     <chr>     <chr>
#>  1        0058       163240        99999 19860101  0032         4   +40517   +017400     FM-15     +0069
#>  2        0058       163240        99999 19860101  0100         4   +40517   +017400     FM-15     +0069
#>  3        0058       163240        99999 19860101  0208         4   +40517   +017400     FM-15     +0069
#>  4        0058       163240        99999 19860101  0308         4   +40517   +017400     FM-15     +0069
#>  5        0058       163240        99999 19860101  0408         4   +40517   +017400     FM-15     +0069
#>  6        0074       163240        99999 19860101  0508         4   +40517   +017400     FM-15     +0069
#>  7        0074       163240        99999 19860101  0610         4   +40517   +017400     FM-15     +0069
#>  8        0074       163240        99999 19860101  0710         4   +40517   +017400     FM-15     +0069
#>  9        0074       163240        99999 19860101  0810         4   +40517   +017400     FM-15     +0069
#> 10        0074       163240        99999 19860101  0910         4   +40517   +017400     FM-15     +0069
#> # ... with 7,354 more rows, and 68 more variables: call_letter <chr>, quality <chr>,
#> #   wind_direction <chr>, wind_direction_quality <chr>, wind_code <chr>, wind_speed <chr>,
#> ...

A: The weatheR package seems to be an abandoned project.
Looking inside the code of the getStationByID function, one can realize that it cannot work.
A modified getStationByID is available here.
Download this file and save it in the working directory with the name mygetStationByID.r.
Then, use the following code:
require(weatheR)
station.list <- allStations()

# Load the modified version of getStationByID
source("mygetStationByID.r")
# The structure of the fixed-width files
# downloaded from ftp://ftp.ncdc.noaa.gov/pub/data/noaa/
col.width <- c(4,6,5,8,4,1,6,7,5,5,5,4)
# Column names
col.names <- c("TOT", "USAF", "WBAN", "DATE", "TIME", "DATASOURCE",
 "LAT","LON","CODE","ELEV.DIM","CALL.LETTER","QLT.CTRL")

grottaglie <- mygetStationByID(stationID = 163240,
             station.list = station.list, begin = 2013, end=2016)

str(grottaglie)
# List of 2
#  $ dl_status   :'data.frame':   4 obs. of  4 variables:
#   ..$ File  : chr [1:4] "163240-99999-2013.gz" "163240-99999-2014.gz" "163240-99999-2015.gz" "163240-99999-2016.gz"
#   ..$ Status: chr [1:4] "Failed" "Failed" "Failed" "Failed"
#   ..$ City  : chr [1:4] "Grottaglie, Italy" "Grottaglie, Italy" "Grottaglie, Italy" "Grottaglie, Italy"
#   ..$ rank  : num [1:4] 1 1 1 1
#  $ station_data:List of 1
#   ..$ Grottaglie_163240:'data.frame':   19264 obs. of  12 variables:
#   .. ..$ TOT        : int [1:19264] 126 126 138 137 145 145 145 137 89 89 ...
#   .. ..$ USAF       : int [1:19264] 163240 163240 163240 163240 163240 163240 163240 163240 163240 163240 ...
#   .. ..$ WBAN       : int [1:19264] 99999 99999 99999 99999 99999 99999 99999 99999 99999 99999 ...
#   .. ..$ DATE       : int [1:19264] 20130101 20130101 20130101 20130101 20130101 20130101 20130101 20130101 20130101 20130101 ...
#   .. ..$ TIME       : int [1:19264] 650 750 850 950 1050 1250 1350 1450 1550 1650 ...
#   .. ..$ DATASOURCE : int [1:19264] 4 4 4 4 4 4 4 4 4 4 ...
#   .. ..$ LAT        : num [1:19264] 40.5 40.5 40.5 40.5 40.5 ...
#   .. ..$ LON        : int [1:19264] 17400 17400 17400 17400 17400 17400 17400 17400 17400 17400 ...
#   .. ..$ CODE       : Factor w/ 2 levels "FM-15","FM-16": 1 1 1 1 1 1 1 1 1 1 ...
#   .. ..$ ELEV.DIM   : int [1:19264] 69 69 69 69 69 69 69 69 69 69 ...
#   .. ..$ CALL.LETTER: Factor w/ 2 levels "99999","LIBG ": 2 2 2 2 2 2 2 2 2 2 ...
#   .. ..$ QLT.CTRL   : Factor w/ 1 level "V020": 1 1 1 1 1 1 1 1 1 1 ...

# Table by years
table(as.numeric(substr(grottaglie$station_data[[1]]$DATE, 1, 4)))
# 2013 2014 2015 2016
# 4866 4816 4794 4788

I hope it can help you.
N.B. If at the first run the code generates an error message, try to rerun it.


text:
Q: How to Pass Data from One frame to Another and to all other frames in the project? I wanna want to pass or share data(values) from login frame to all frames in my project, H have made class of this variables like this
public class SharedData {

    public  String LoginName;

    public SharedData() {
    }

    /**
     * @return the LoginName
     */
    public String getLoginName() {
        return LoginName;
    }

    /**
     * @param LoginName the LoginName to set
     */
    public void setLoginName(String LoginName) {
        this.LoginName = LoginName;
    }
}

and from the first frame (login frame) I make object of this class and sets its username like this
 public  SharedData  data1=new SharedData();
    data1.setLoginName(Username_Login.getText().toString());

and from the second frame i get the value :
public  SharedData  data=new SharedData();
ogin_labelName.setText(data1.getLoginName().toString());

But finally it doesn't work ... what is the problem or any solution ?
thanks in advance

A: You can create a bean class like :
public class SharedData {
        public  static String LoginName;

        public static void setLoginName(String LoginName) {
            SharedData.LoginName = LoginName;
        }

        public static String getLoginName() {
            return LoginName;
        }
    }

And use this class for setting and getting a values from another form  just calling this class for setting a value:
SharedData.setLoginName(Username_Login.getText().toString());

and for getting a value :
ogin_labelName.setText(SharedData.getLoginName(Username_Login.getText().toString()));

A: You're creating a new object in the second frame. So obviously, this second object doesn't contain the same data as the first one.
If you put a message in a box, and open another box, you won't find the message in it. Same with Java objects.
When the login frame constructs the main frame, it should pass the SharedData object it has created to the main frame constructor (or to a setter method):
SharedData data1 = new SharedData();
data1.setLoginName(Username_Login.getText().toString());

MainFrame frame = new MainFrame(data1);

You should also learn Java naming conventions and stick to them. Fields should start with a lower-case letter, and shouldn't contain underscores: userNameLogin instead of Username_Login. And there is no point in calling toString() on a String.


text:
Q: create array instead of repeating a function function givemebann($pos) {
    global $db;
    $st = $db->prepare("select * from banners where home = '" . $pos . "' limit 1");
    $st->execute();
    return $st->fetch();
}

<?php
$row = givemebann('big-top');
$x = $row['src'];
?>
<img class='bigbann' src='../banners/<?php echo $x; ?>' alt='img'>

This all works but I have 50 such places on a single page.
givemebann('left-a');
givemebann('right-b');
... etc
So, I need to reduce this communication between php and mysql server and I suppose the solution is to create an array of values and then get them inside html from that array.
I need any help to create such array?

A: It would be wise if you select only the column(s) that you really need in your SQL query rather than all the existing columns:
// declare all the banners that you will need on this page
$banner_list = Array('"left-a"', '"right-b"', '"big-top"', '"small-bottom"');

// get all the required banners
$st = $db->prepare("select home, src from banners where home IN (" . implode(",",$banner_list) . ") GROUP BY home");
$st->execute();
$result = $st->fetchAll();
foreach($result as &$row) $banners[$row['home']] = $row;

<?php
$row = $banners['big-top'];
$x = $row['src'];
?>
<img class='bigbann' src='../banners/<?php echo $x; ?>' alt='img'>


text:
Q: How does an "account" work with AWS Identity Token Vending Machine? I've followed the instructions in this post http://mobile.awsblog.com/post/Tx371Y7CA0QJ95X/Simplifying-Token-Vending-Machine-Deployment-with-AWS-CloudFormation
And I can see that it's working somewhat, and i understand the overall concept of what TVM is and why it's needed, however I still have hard time understanding how this works in practicality. I read a post somewhere that anonymous token vending machine is designed for read-only and if I wanted to actually provide write access I need to use identity TVM.
In the demo app it makes me register my account on the cloudformation server i set up, but I don't understand how this works with say my own web app. I have a mobile app that connects to rails app where I need users to upload their profile images as well as post photo content. I already have the app running except for the integration part with the TVM (basically my aws credentials are embedded in the app which Amazon doesn't recommend)
So my question is how do i integrate an existing REST based iOS app with identity token vending machine to upload photos to S3? How can i integrate it without making users separately create an "account" for the identity token vending machine on top of registering for my app?

A: We recently launched Amazon Cognito, which obviates the need for the TVM in many cases, particularly in the "anonymous TVM" case. Through Cognito's unauthenticated access you can grant users of your application limited access privileges to various AWS resources. Cognito leverages existing functionality of IAM Roles and STS to deliver these credentials.
If you want to maintain the integration with your existing backend authentication solution, you will need to generate and maintain the list of identity ids for your application. You can read more about the APIs involved in our API documentation.

A: Your app can act as the TVM, mapping your user identities to the IAM Roles with the permissions they need. Then can use the AssumeRole calls on STS to create temporary credentials for these users. Your app then creates a S3Client object with these credentials and use it to upload the photo.
See the "Identity federation" and "Web identity federation" sections of the of IAM Roles documentation
The AWS Web Identity Federation Playground is a nice example app to see it at work.
CoudFormation will automate the creation, updates and deletion of AWS Resources, including EC2 Instances and IAM Roles, but will not be directly related to the user authentication.


text:
Q: .serialize() for upload file, i.e filefield I'm submitting a form through jQuery and all my form data working fine except File Field. When I use without jQuery then file field is also working fine. Below is my code,
jQuery
jQuery.noConflict();
jQuery(document).ready(function(){
jQuery('#submit_data').click(function(e){
    e.preventDefault();
    var error = false;
    var name = jQuery('#name').val();
    if(name.length == 0){
        var error = true;
        jQuery('#name_error').fadeIn(500);
    }else{
        jQuery('#name_error').fadeOut(500);
    }
    if(error == false){
        $('#submit_data').attr({'disabled' : 'true', 'value' : 'Submitting...' });
        $.post("submit.php?action=add_user", $("#add_user").serialize(),function(result){
            if(result == 'sent'){
                 $('#submit_data').remove();
                $('#submit_success').fadeIn(500);
            }else{
                $('#submit_fail').fadeIn(500);
                $('#submit_data').removeAttr('disabled').attr('value', 'Submit');
            }
        });
    }
});
});

HTML
<form action="" method="post" enctype="multipart/form-data" id="add_user">
<input type="test" id="name" name="name" />
<input type="file" id="file" name="file" />
<input type='submit' value='Submit' class="button" id='submit_data'>
</form>

In my PHP code I just want to echo $image =$_FILES["file"]["name"]; but it doesn't pass value and other fields of that form is working perfect.

A: serialize() can't send files.
I suggest using " FormData " for uploading files with Ajax function:
if( window.FormData !== undefined )
    //make sure that we can use FormData ie>9, chrome > 7, opera > 12 safari >5, android > 3 gecko mobile > 2, opera mobile >12 <- wil support XHR too
        {

            var formData = new FormData($('#yourForm')[0]);
            $.ajax({
                url: 'fileUpload.php',  //Server script to process data
                type: 'POST',
                xhr: function() {  // Custom XMLHttpRequest
                    var myXhr = $.ajaxSettings.xhr();
                    if(myXhr.upload){ // Check if upload property exists
                        myXhr.upload.addEventListener('progress',progressHandlingFunction, false); // For handling the progress of the upload
                    }
                    return myXhr;
                },

                beforeSend: function(){

                },
                success: function(response){

                },
                error: function(xhr, ajaxOptions, thrownError){
                    console.log(thrownError);
                },
                // Form data
                data: formData,
                //Options to tell jQuery not to process data or worry about content-type.
                cache: false,
                contentType: false,
                processData: false
            });
        }

FormData wil support multi file upload too and you can easily add your own fields by using:
formData.append("fieldname",value1);

Add to your Form tag the attribute:
enctype="multipart/form-data"

Should work great!
NOTE:
   You may find that the FILES array is empty on server side page - In this case you need to make
   sure your server configuration allows file uploads, size limit of file upload is enough, post time
   is enough etc....
The best way to begin is to make sure that file uploads is allowed and then testing with very
   small files to be sure everything in your code is OK.

A: You can't send a file with .serialize(). Instead you can use FormData api to do it.
if(error == false){
    var file =  $("#file")[0].files[0];

    var formData = new FormData($("#add_user"));
    formData.append("name", name);
    formData.append("file", file);
    $('#submit_data').attr({'disabled' : 'true', 'value' : 'Submitting...' });

    $.ajax({
      url: 'submit.php?action=add_user',
      type: 'POST',
      // Form data
      data: formData,
      success: function(data){
        $('#submit_data').remove();
        $('#submit_success').fadeIn(500);
      },
      error: function(){
        $('#submit_fail').fadeIn(500);
        $('#submit_data').removeAttr('disabled').attr('value', 'Submit');
      },

      //must keep false
      cache: false,
      contentType: false,
      processData: false
    });
 }

A: You can't submit a file through ajax.
I would suggest this plugin to quickly do what you're trying to do
http://malsup.com/jquery/form/


text:
Q: Querying a relational table in Django database I have an database with a relational table created by my Models.  This table has all the information I'm trying to query, but I'm having a difficult time getting the values from it that aren't objects of the Model.
Models.py
class Ingredient(models.Model):
    '''All ingredients for any recipe or individual selection'''
    ingredient = models.CharField(max_length=50)
    department = models.ForeignKey(Department, null=True, on_delete=models.SET_NULL)

    def __str__(self):
        return self.ingredient

class IngredientDetail(models.Model):
    '''A class to identify variable quantities of ingredients'''
    recipe = models.ForeignKey('Recipe', null=True, on_delete=models.SET_NULL)
    ingredient = models.ForeignKey(Ingredient, null=True, on_delete=models.SET_NULL)
    quantity = models.CharField(max_length=1)

    class Meta:
        verbose_name_plural = 'Ingredient Details'

    def __str__(self):
        return self.quantity

class Recipe(models.Model):
    '''A Recipe class to input new recipes'''
    recipe = models.CharField(max_length=50)
    ingredients = models.ManyToManyField(Ingredient, through=IngredientDetail)
    instructions = models.TextField(null=True)
    cuisine = models.ForeignKey(Cuisine, null=True, on_delete=models.SET_NULL)
    picture = models.ImageField(upload_to= 'media/', null=True, blank=True)

    def __str__(self):
        return self.recipe

It creates the following table, which has the info I need:

ID
quantity
ingredient_id
recipe_id

1
1
5
5

2
1
6
5

3
2
7
5

When I try to query Ingredient details with IngredientDetails.objects.filter(recipe_id='5'), it only gives me the values for quantity, and I also need the ingredient_id. Did I structure my models incorrectly, or have I overlooked an obvious solution to this?  Ideally, I'd like to be able to write a query for recipe_id, and receive the ingredient_id and quantity associated with it.  Thank you in advance


text:
Q: React native: How to individually control each onpress() from map() generated components I'm new to react native.
I'm rendering 3 dropdowns in a row, multiple times according to the no of elements in an array.
So if the array has 3 elements, there will be 3 rows of 3 dropdowns.
But when invoke an onpress from a single dropdown it affects corresponding elements all 3 rows.
How can i individually control each row.?
Lot of solutions say use bind but the way i tried did not affect anything.
click to see the rendered layout looks for 3 elements in the arrray
render_center_selection(){

      return(
        this.props.selecteddays_array.map((a, i) => {
          return(
           <View key={i} style={{ height:40, borderBottomWidth:2, borderBottomColor: '#ededed' }}>{
                      <View  style={{flexDirection:'row'}}>
                        <ModalDropdown
                            style={styles.selection}
                            defaultValue='Venue'
                            textStyle={{width:200,fontSize:20,textAlign:'center',color: '#7070D8'}}
                            dropdownStyle={styles.dropdownstyle}
                            dropdownTextStyle={{width:350,fontSize:20,textAlign:'center',backgroundColor: '#FDD60B',}}
                            options={this.state.venue_name_array}
                            onSelect={(index,value)=>{this.onVenueSelect(index,value)}}/>
                        <ModalDropdown
                            ref="modal_dayselect"
                            style={styles.dayselection}
                            defaultValue='Day'
                            textStyle={{width:50,fontSize:15,textAlign:'center',color: '#7070D8'}}
                            dropdownStyle={styles.daydropdownstyle}
                            dropdownTextStyle={{width:50,fontSize:15,textAlign:'center',backgroundColor: '#FDD60B',color: '#7070D8'}}
                            options={this.state.day_array}
                            onSelect={(index,value)=>{this.onDaySelect(index,value)}}/>
                        <ModalDropdown
                            ref="modal_hrsselect"
                            style={styles.dayselection}
                            defaultValue='HRS'
                            textStyle={{width:50,fontSize:15,textAlign:'center',color: '#7070D8'}}
                            dropdownStyle={styles.daydropdownstyle}
                            dropdownTextStyle={{width:50,fontSize:15,textAlign:'center',backgroundColor: '#FDD60B',color: '#7070D8'}}
                            options={this.state.hrs_array}
                            onSelect={(index,value)=>{this.setState({selected_hr:value})}}/>
                        {(this.state.editstatus)
                          ?<Text>Edit</Text>
                          :<Text></Text>
                        }
                      </View>
                  }</View>)
        })
      );
  }

A: You will have to pass a unique key to the onSelect method then you will be able to individually control each row. In the below example, you can see there are two arrays and to get the data of inner array, I have to pass the index of outer array as well as the index of inner array. This will also make it unique.
var arr1 = [1,2,3]
var arr2 = ['a','b','c']

function looper(data1,data2){
  data1.map((item1,index1) => {
   data2.map((item2,index2) =>console.log("item1: " + item1 + " " + index1 + " item2: " + item2 + " " + index2));
  })
}
looper(arr2,arr1);


text:
Q: Java Convention for file/media upload location I have searched around and haven't found anything very specific.  I know that it should sit outside the war.  My application is built on Spring and works under Tomcat.  Should the directory location stay within Tomcat /opt/tomcat or can I put it in /var/www/projectname (I prefer the latter)?
Might be over analyzing but I would much rather learn the convention then to create something new. I think by default it puts me in tomcats bin folder.

A: There's no convention. Choose a location that is accessible. If you control the installation, give that location group/user access permissions and start your process with that user.


text:
Q: how to press up, down, left, right keys in games. using python I created a script that plays the piano and the up and down arrows change the transpose. But when it's used within a game, the up, down, left, right keys don't work.
my script:
def play_midi(notes, tempo):
    import keyboard
    import shocurasy
    for variables in notes:
        exec(f'note{variables} = 0')

    transpose = 0
    keys = ['1', 'shift + 1', '2', 'shift + 2', '3', '4', 'shift + 4', '5', 'shift + 5', '6', 'shift + 6',
            '7', '8', 'shift + 8', '9', 'shift + 9', '0', 'q', 'shift + q', 'w', 'shift + w', 'e', 'shift + e',
            'r', 't', 'shift + t', 'y', 'shift + y', 'u', 'i', 'shift + i', 'o', 'shift + o', 'p', 'shift + p',
            'a', 's', 'shift + s', 'd', 'shift + d', 'f', 'g', 'shift + g', 'h', 'shift + h', 'j', 'shift + j',
            'k', 'l', 'shift + l', 'z', 'shift + z', 'x', 'c', 'shift + c', 'v', 'shift + v', 'b', 'shift + b',
            'n', 'm']

    for id_note in range(len(notes)):
        shocurasy.tempo(tempo[id_note])
        if eval(f'note{notes[id_note]}') == 0:
            exec(f'note{notes[id_note]} = 1')
            if notes[id_note] < 24:
                set = notes[id_note] - 24
            elif notes[id_note] > 84:
                set = notes[id_note] - 85
            else:
                set = 0

            while True:
                if transpose < set:
                    transpose += 1
                    keyboard.press_and_release('up')
                elif transpose > set:
                    transpose -= 1
                    keyboard.press_and_release('down')
                else:
                    break

            print(f'note value = {notes[id_note]}')
            if notes[id_note] < 24:
                keyboard.press(keys[0])
            elif notes[id_note] > 84:
                keyboard.press(keys[-1])
            else:
                keyboard.press(keys[notes[id_note]-24])

        else:
            exec(f'note{notes[id_note]} = 0')
            if notes[id_note] < 24:
                keyboard.release(keys[0])
            elif notes[id_note] > 84:
                keyboard.release(keys[-1])
            else:
                keyboard.release(keys[notes[id_note] - 24])

I've already tested it with pydirectinput, but it's too much slow to run the function. I need something I can do quickly.


text:
Q: XPath Search in Chrome JS Console ("$x(...)") outputs arrays (jQuery Objects?) rather than sections of HTML text (DOM elements?) I'm relatively new to using Chrome developer tools/doing XPath searches/this kind of programming in general, so please excuse any incorrect terminology or vague-sounding descriptions. I think the screenshots below will demonstrate what I'm talking about more easily than I can describe with my limited vocabulary.

What I'm Looking For
When I started using developer tools to search XPaths, using the "$x(...)" function would return a section of the html, that I could then navigate within the console or with more specific searches to get a sense of the structure before I extracted text. My console is no longer returning the markup text in this form, but I found an example in another StackOverflow post that will suffice to show what kind of return I'm looking for:
What I would be looking for
I was able to navigate this HTML text within the console (highlighted section) to find the section I needed, before using a more specific XPath, extracting, etc.

What I'm Seeing Now
What I'm now getting instead is an array or nested set of arrays. I think that these are jQuery objects being returned (could be way off here). See below:
What I'm seeing now
I'm sure that in many cases, navigating the elements in this array could actually be easier than working through the HTML and, as someone with very little exposure to web development, I'm sure that there's something I'm missing here. As someone working on a scraping project just looking to find specific elements or text on the page. This is much more difficult to work with.

As a made up example, in the past, if I were trying to pull the names of different kinds of fruit off of a page and I typed into the console...
$x('//*[@class="fruit"]/h1')

...the console would have spit out something like:
[
Peach
,
Strawberry
,
Watermelon
,
Apple
,
Orange
]

And then, had I followed that up with...
$x('//*[@class="fruit"]/h1.text()')

...the console would have spit out:
["Peach", "Strawberry", "Watermelon", "Apple", "Orange"]

Now, if I run a search like this, I'll get a result that will (not literally, but in this form) look something like this:
Array[2]0: form#aspnetForm0: input#__LASTFOCUS1: input#__EVENTTARGET2: input#__EVENTARGUMENT3: input#EktronClientManager4: input#__VIEWSTATE5: input#__VIEWSTATEGENERATOR6: input#__EVENTVALIDATION7: input#ctl00_Header_searchTextBox.searchterm8: input#ctl00_Header_searchButton.searchbtn9: fieldset10: input#ctl00_contentPlaceHolder_login_emailTextBox.max-width11: input#ctl00_contentPlaceHolder_login_passwordTextBox.max-width12: input#ctl00_contentPlaceHolder_login_rememberMeCheckBox13: input#ctl00_contentPlaceHolder_login_signInButton.button.green_events: etc, etc...

For my purposes, that array of strings is much easier to work with, because I can confirm exactly what I'm getting from that XPath search and what I'm going to have to work with once I get the element off the site.

I'm sorry that this post is probably really frustrating to an experienced web programmer, because I'm missing both the larger picture and a lot of the vocabulary. Could someone please explain to me 1. what I going on? Why am I getting these arrays full of data when I was getting the HTML text before and 2. how to revert to getting the HTML text returned when I do this kind of search in the JavaScript console?
Thank you!

A: There is no difference between the "what I would be looking for" and "what I'm seeing now" screenshots. When you click on the little triangle to the left of "what I would be looking for", you can see that it becomes equivalent to the "what I'm seeing now" format.
For example, opening up DevTools on this very Stack Overflow page, and searching for
 elements:

When you click on the little triangle to the left of the result you get:

The $x() function returns a JavaScript array (not jQuery) of DOM nodes that match your XPath query. If there's multiple nodes that match your query, then the result will be an array of multiple nodes.
You can iterate through the results by assigning the results to an array, and then looping through them, like in the screenshot below. I think this is the kind of functionality that you're looking for.


text:
Q: JSON string validation in Python I need to write a test in Python to validate that the payload I am returning is a valid JSON.
import json
s = '{"position": NaN, "score": 0.3}'
json.loads(s)

the code above doesn't throw an exception, while the string is obviously not a valid JSON according to my backend friend and jsonlint.com/.
What should I do?

A: By default json.loads accepts '-Infinity', 'Infinity', 'NaN' as values. But you can control this by using parse_constant parameter.
Quoting from the documentation,

if it specified, will be called with one of the following strings:
'-Infinity', 'Infinity', 'NaN'. This can be used to raise an exception
if invalid JSON numbers are encountered

A: According to json.JSONDecoder documentation - "It also understands NaN, Infinity, and -Infinity as their corresponding float values, which is outside the JSON spec. [...] parse_constant, if specified, will be called with one of the following strings: '-Infinity', 'Infinity', 'NaN'. This can be used to raise an exception if invalid JSON numbers are encountered."
import json

def exc(x):
    raise ValueError(f"{x} is not a valid JSON object")

s = '{"position": Infinity, "score": 0.3}'

d = json.loads(s, parse_constant=exc)
print(d)

A: You can use parse_constant, documentation says:

if specified, will be called with one of the
following strings: -Infinity, Infinity, NaN.
This can be used to raise an exception if invalid JSON numbers
are encountered.

For example:
import json

s = '{"position": NaN, "score": 0.3}'

def validate(val):
    if val == 'NaN':
        raise ValueError('Nan is not allowed')
    return val

print(json.loads(s, parse_constant=validate))


text:
Q: mysql update insert join avoid duplicates I have a table that I wish to update (or insert if no previous condition exists)
servers table              clusters table              datacenters table

server_id | server_name     cluster_id | cluster_name   datacenter_id | datacenter_name
-----------------------     -------------------------   -------------------------------
1           server1          1           cluster1        1               datacentereast
2           server7          3           Cluster22       5               datacenterwest

server_status table

status_id   |    status_server   | status_cluster | status_datacenter
---------------------------------------------------------------------

I wish to populate server_status with the ids of the other tables and avoid duplicates.
So far I have :
sql_string = """
INSERT into server_status (status_datacenter,status_cluster, status_server)
    SELECT
        d.datacenter_id,c.cluster_id,s.server_id
    FROM
        datacenters as d, clusters as c, servers as s
    WHERE
        d.datacenter_name = \'%s\'
        AND c.cluster_name = \'%s\'
        AND s.server_name = \'%s\'
        AND d.datacenter_id != status_datacenter
        AND c.cluster_id != status_cluster
        AND s.server_id != status_server;
    """ % (datacenter,cluster,server)

The above fails with:
_mysql_exceptions.OperationalError: (1054, "Unknown column 'status_datacenter' in 'where clause'")

Print out of an actual sql command:
INSERT into server_status (status_datacenter,status_cluster, status_server)
 SELECT d.datacenter_id,c.cluster_id,s.server_id
  FROM datacenters as d, clusters as c, servers as s
   WHERE d.datacenter_name = 'SDDC'
   AND c.cluster_name = 'qboc37'
   AND s.server_name = 'ap30'
   AND d.datacenter_id != status_datacenter
   AND c.cluster_id != status_cluster
   AND s.server_id != status_server;

A: First create a unique index on server_status (status_datacenter,status_cluster, status_server), then
INSERT IGNORE into server_status (status_datacenter,status_cluster, status_server)
 SELECT d.datacenter_id,c.cluster_id,s.server_id
  FROM datacenters as d, clusters as c, servers as s
   WHERE d.datacenter_name = 'SDDC'
   AND c.cluster_name = 'qboc37'
   AND s.server_name = 'ap30'


text:
Q: Sharing a (single point?) wireless internet connection Could you help, please? I have tried (seemingly) everywhere and I get no answers. Like many people, I live in an apartment building, which provides wireless access for which each computer (not apartment or user) has to pay (monthly) to access the Internet. I use a (wireless) Belkin USB Adapter, to access the service. There is no set-up procedure or any special actions required - you just login to the network using the login details provided every month. I use Windows 7, but in my time here, I have used XP Pro, Vista and even Linux (Ubuntu).
Is it possible for me to use modern equipment (say, an all-in-one) to accept the signal and then re-broadcast it in my apartment- thereby creating another (wireless) Lan just for my family? Also, I can now add some security to the network, which is non-existent, now.
I would LOVE to know just what is inside the Belkin (and similar) adapter (I can't find out from the internet) as that would help me to understand requirements, etc, a little more, i.e does it contain a router, modem, switch ... etc) in this very small package.
At the end of the day, what I need is to have more than one computer on the internet at the same time from the one (single) source that I have.
Thanks very much, in anticipation. Mike

A: There are many devices, called wireless repeaters or wireless range extenders, that can do this.  Not all devices marketed as such can do what you need, though.  Essentially, the device must act as a router for your home network, and act as a client on the apartment network.  Some range extenders are only capable of repeating the original wireless signal, which doesn't help you.  Look for a range extender that indicates it supports being a DHCP server to make sure it will fulfill your purpose.
There are several other methods by which you can accomplish this.  Many garden variety wireless routers have two antennae, and third-party firmware like DD-WRT can be used to configure the router to act in this manner.  (This is usually cheaper, and standard routers are generally easier to find in local stores.  If you decide to buy one for this purpose, make sure it supports DD-WRT.)  You can also have a computer with a wireless adapter that is connected to the apartment wireless network that subsequently shares that connection via Ethernet cable with your own wireless router, or via a second wireless adapter in the computer.
While you will be able to encrypt your wireless connection, this will only be effective in preventing unwanted access to your personal wireless network and securing connections between computers connected to it.  Connections to the Internet via the apartment network will still have to be sent in the clear.


text:
Q: GIS with Bing Silverlight and SQL 2008? I have data that I want to create a GIS type application that will have the typical features of adding and removing layers of different types. What is the best architectural approach?
The data consists of property locations in Eastings and Northings.
I also have ordnance survey data in GML and Shapefiles.
I know this is a very broad question but the subject area also seems very broad to me and I am unsure which direction to go.
I was thinking of using SQL 2008 spatial and Bing Silverlight control to visualise that maps.To do this would I have to convert the eastings and northings to GWS84 geography datatype? But then if I converted the shapefiles to GML and imported all the GML files to sql  using GeomFromGML they would be in geometry datatypes. Wouldn't the two types be incompatible?
Also, should ESRI ArcGIS API for Silverlight
feature in the equation? Is this a good environment to create maps that I can point as SQL sqerver 2008 as the datasource (using a WCF service if necessary)?
Any advice greatly appreciated!

A: This is something I've done several times, using OS data from SQL Server in both Bing Maps AJAX and Silverlight controls. Some general comments below (in no particular order!):

*

*Don't expect to implement full-blown
GIS functionality using Bing Maps.
Simple querying, retrieval and
display of the data is all fine (+
some simple editing), but after that
you'll be struggling with what can be
achieved in the browser.

*All vector shapes supplied to Bing Maps need to be in (geography)
WGS85 coordinates, EPSG:4326.

*However, all data will be projected
and displayed using (projected)
Spherical Mercator system, EPSG:3857.

*In terms of vector shapes, you can expect to achieve a similar level of performance as you get in the SSMS spatial results tab - that is, (with careful architecture) you can plot up to about 5,000 features on the map at once, zoom / pan around them, click on them to bring up various properties and attributes etc. However, after that you'll find the UI becomes fairly unresponsive (which
I imagine is the reason why the spatial results tabs itself limits you to displaying 5,000 records at once).

*If you want to display more features than this, one approach is to rasterize them by projecting them into the EPSG:3857 projection, creating a .PNG/.JPG image file of the features and then cutting that image into tiles according to the Bing Maps quadkey tile numbering system as explained here:
http://msdn.microsoft.com/en-us/library/bb259689.aspx and displaying them as a tilelayer. Tile layers are significantly faster than displaying the equivalent vector shapes, although it means the data is static.

*If you do create raster tiles, you can either render them    dynamically
or pre-render them to    improve performance - i.e. you could    set
up a job to render and update the tileset for slowly-changing data
every night/every month etc.

*If you're talking about OS Mastermap data, the sheer level of    detail
involved means that you need to think more carefully about what
features you want to display, and how you want to display them. Take
greater London, for example, which covers an area about 50km x 40km. To
create raster tiles (each of which are 256px x 256px) at zoom level 19
covering this area you'd need to render and store 1.3 million separate
tiles. If each of those is generated from a database query that takes, say
200ms to run, it's gonna take a looooonggggg time to prepare all your
data. Also, once the files have been generated, you might want to think
about storing them in a DB rather than saving them on a file system.

*As for loading the OS data into SQL Server in the first place - there
are several tools that will import either from GML or shapefile into SQL
Server, and handle the projection from EPSG:27700 (Ordnance Survey
National Grid) to WGS84 along the way. Try GDAL/OGR or Safe FME for
starters.

I have a blog at http://alastaira.wordpress.com that has several blog posts that you may find useful describing various aspects of integrating Bing Maps and SQL Server. Particularly, you might want to look at:
http://alastaira.wordpress.com/2011/02/16/loading-ordnance-survey-open-data-into-sql-server-2008/
http://alastaira.wordpress.com/2011/01/23/the-google-maps-bing-maps-spherical-mercator-projection/
http://alastaira.wordpress.com/2011/02/21/using-ogr2ogr-to-convert-reproject-and-load-spatial-data-to-sql-server/