text:
Q: Merge datatable (Row not found) i have sql1 insert into dt1, and sql2 insert into dt2.
Im trying to merge these 2 datatables. Ive try to run them separately and it work only if i try to merge error occur. Is there any way to merge? I dont want to use join
dt1
|column1|col2|col3|

dt2
|col4|col5|col6|

dt2 required infomation from sql1+sql3
ive tried dt1.Merge(dt2)
I was hoping to get end output like:
|col1|col2|col3||col4|col5|col6|

A: Why not use the database?
select sql1.col1, sql1.col2, sql1.col3, sql2.col4, sql2.col5, sql2.col6
from sql1 cross join
     sql2;


text:
Q: Rails account_params missing parameters from backbone `.save()` I am trying to create a user account using Backbone 1.1.2 and Rails 4.2.beta1.
In backbone I am calling:
public create(){
    var email:string = $('#create-account-email').val(), password:string = $('#create-account-password').val(), passconf:string = $('#create-account-password-confirm').val();
    this.model.set({email: email, password: password, password_confirmation: passconf});
    this.model.save(null, {success: this.success, error: this.error});
}

which correctly calls the rails create method in my webservice with the following request parameters:
{"email":"test@test.com","password":"123456","password_confirmation":"123456"}

It is going through the filter method
def account_params
  #breakpoint
  params.require(:account).permit(:password, :password_confirmation, :email)
end

but if I place a breakpoint in the above noted spot and inspect the params object I get:
{"email"=>"test@test.com",
 "password"=>"123456",
 "password_confirmation"=>"123456",
 "controller"=>"accounts",
 "action"=>"create",
 "account"=>{"email"=>"test@test.com"},
 "format"=>"json"}

Which to me looks correct at first glance. But the account creation fails because the password is nil
if inspecting the result of account_params I only get:
{"email" => "test@test.com")

Why is the password not being included in the account parameter object. I am using all default sacaffolded code with rails and default configuration for Backbone.

A: I found a GitHub repo for a ruby gem backbone-rails and used the sync override that they included here.
Backbone._sync = Backbone.sync;
Backbone.sync = function (method:string, model:Backbone.Model, options?: any){
    if(options.data == null && model && (method === 'create' || method === 'update' || method === 'patch')) {
        options.contentType = 'application/json';
        var data:any = JSON.stringify(options.attrs || model.toJSON(options));
        if(model.paramRoot) {
            data = {};
            data[model.paramRoot] = model.toJSON(options);
        } else {
            data = model.toJSON();
        }
        options.data = JSON.stringify(data);
    }
    return Backbone._sync(method, model, options);
}

I removed some items I didn't need, but this wraps the backbone attributes into an object and sends it to the rails app in the format it needs.
So the parameters:
{"email":"test@test.com",
 "password":"123456",
 "password_confirmation":"123456"}

Become:
{"account":
    {"email":"test@test.com",
     "password":"123456",
     "password_confirmation":"123456"}
}

This isn't without a little bit of reworking the backbone application code...
As I am using typescript I had to add the _sync() method to the backbone.d.ts file using the following signature.
declare module Backbone {

    function _sync(method: string, model: Model, options?: JQueryAjaxSettings):any;

    ...
}

I also needed to add the following to Backbone.Model
class Model extends ModelBase implements OptionalDefaults {

    paramRoot: string;

    ...
}

And then I added the paramRoot property to my model:
export class Account extends Backbone.Model {
    public urlRoot: string;
    public validation:any;
    public paramRoot:string;
    constructor(attributes?: any, options?: any){
        this.paramRoot = 'account';
        this.urlRoot = 'http://mydomain.fake/accounts';
        this.validation = {
            email: {
                required: true,
                pattern: 'email'
            },
            password: {
                required: true,
                minLength: 6
            }
        };
        super(attributes, options);
    }
}

There are other ways to allow the _sync() method and the paramRoot property to pass the compiler errors without modifying the backbone.d.ts file but instead extending the objects and adding it in another .d.ts file. But this was ok for me as I plan on using this in future projects and I don't mind having the .d.ts file being slightly modified.
Hope this helps someone in the future.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Rote copying the settings/preferences of a user to other users
Possible Duplicate:
how to copy old user account to new user account?

I have installed Ubuntu, with username andy, let's say I want to create accounts for  Ben, Chris, Dave and Ethan, all of whom I want to have non-admin rights and precisely the same (initial) settings... except their home folder.
Suppose I set up Ben's account, as I want it, for example: Libre Office writer saves as .doc, weather-indicator is set to computer's address, launcher icons are where I choose, desktop background etc.
Is there a way I can then set up Chris's, Dave's and Ethan's to (initially) behave in exactly the same way (with the exception of different home folders)?
At the moment, I am going through the motions four times!

A: When you create a new user, files are copied from /etc/skel onto their new home directory. If you want files to appear there by default, just add them to /etc/skel. That goes for default configurations as well, so you can make a prototype user and copy that users home directory onto /etc/skel. Automatic setup of email accounts, etc, will require some scripting, but doesn't necessarily need to be very complicated. If you wanted to provide default web feeds for Liferea, you'd add the feeds to the prototype user and then simply copy the ~/.liferea_1.6 folder to /etc/skel/.liferea_1.6 and it would just work.
Some applications doesn't work like this. You can't do that with Evolution, for instance, but most applications can be configured that way.


text:
Q: UITableView Autoresizing does not work in preview for iPhone 4s
In the above design the Autoresizing is configured correctly.
+0 from bottom , top ,left and right for the UITableView.
+8 from bottom , top ,left and right (The Green Color View)
But the preview looks like this.


text:
Q: "Failed to make complete framebuffer" error using Google maps SDK for iOS Searching for this problem only gave me posts that were regarding opengl stuff that I have no knowledge of whatsoever.
On my Storyboard, I've got 1 view in which I put another slightly smaller UIView object to act as a container for my map. This works fine, not much code at all. I set the class of the UIView to be GMSMapView. I CTRL-drag it to create a outlet to the corresponding viewController. After this I create a GMSCameraPosition to a specific location. I set self.mapView, which is the outlet, to [GMSMapView mapWithFrame:CGRectZero camera:camera]; camera being the camera position I specified.
This seems to work, the app starts without errors and the map is shown in the UIView that I created, but, the camera position is not where I specified. And I know that the position is valid because if I use self.viewinstead of self.mapViewthe map shows up on the whole screen at the correct position.
In the log I get the error Failed to make complete framebuffer object 8cd6 and as I said, posts regarding this made no sense whatsoever to me, and I am clueless to what problem this is.

A: For me, this gets the map working/loading the proper coordinates, but still throws the 8cd6 error.
Setup: Xcode 4.6.1 iOS 6.1 using storyboard
I have a view inside of a main view/viewcontroller.
Make sure the UIView (the sub view that is to be the map) under the attribute tab -->class = GMSMapView and is linked to the property *mapView below
YourViewController.h:
#import <UIKit/UIKit.h>
#import <GoogleMaps/GoogleMaps.h>
@interface YourViewController : UIViewController

//other @properties
@property (strong, nonatomic) IBOutlet GMSMapView *mapView;//linked to storyboard

@end

YourViewController.m:
#import "YourViewController.h"
#import <GoogleMaps/GoogleMaps.h>
@interface YourViewController()
@end

/*.. ..other setup code ..*/

-(void)viewDidLoad{
    [super viewDidLoad];
    GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:-33.8683 longitude:151.2086 zoom:10];
    self.mapView.camera = camera;
}

the 8cd6 error has to do with the frame/bounds (obviously).  Something isn't getting called (or set?) if you try to initWithFrame. Loading the view hangs and then defaults to the place near London.  I did not edit the setMapView for this solution, I merely skipped setting the bounds and let storyboard take care of that.
Still hope someone finds a fix that clears up the 8cd6 error though.

A: I wonder if it might be because you initialize the map view with a frame of CGRectZero. I think using CGRectZero is meant to be used when the view is the view controller's root view, meaning it will be resized to the full size of the screen. Maybe you need to set a size, eg:
[GMSMapView mapWithFrame:CGRectMake(0, 0, 300, 300) camera:camera];

A: I too have been experiencing this problem. My solution isn't very elegant, but it works.
First, @sythnesize your outlet in viewController.m (@synthesize mapView = _mapView;). Then write a custom setter:
- (void)setMapView:(GMSMapView *)mapView {
    if (!mapView) {
        mapView = [[GMSMapView alloc] initWithFrame:CGRectZero];
    }
    _mapView = mapView;
}

This will still give you the error that you saw, but then in the viewDidLoad (or somewhere else that will be called after the view loaded) method, set the camera:
self.mapView.camera = [GMSCameraPosition cameraWithLatitude:3 longitude:27 zoom:13];

For a split second, the map would be wrong, but I don't think it is visible to the user.

A: Had a friend over who helped me out, thank you for answering but those answers aren't the way i eventually solved it.
The code we used:
CLLocationDegrees lat = 59.34702;
CLLocationDegrees lon = 18.04053;
GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:lat longitude:lon zoom:10];
[self.mapView setCamera:camera];

We aren't fiddleing with that frame at all since, as it seems, the view automatically sets up a map at a position not specified by me, using the size it has in the storyboard. So all we had to do was to add the camera as in this example. This got rid of that error i talked about.
If someone has a better answer that can explain this more throughly it would be good. But this works, just ctrl drag a View with the class set to GMSMapView as an outlet and add the code i wrote.

A: This error appeared to me when I subclass GMSMapView. I basically declared all the "did*"/ "will*" methods and I found that the error was appearing between willMoveToWindow and didMoveToWindow. Debugging willMoveToWindow I found that the frame was (0,0,0,0). I basically added this and the error disappeared.
- (void)willMoveToWindow:(UIWindow *)newWindow
{
   self.bounds = self.superview.bounds ;
   [super willMoveToWindow:newWindow] ;
}


text:
Q: Formula to reflect changes made in "Sheet B, Sheet C, Sheet D on "SheetA" Excel 2013 I have a spreadsheet containing the sheets "Main Navigation", "Drop Down", "Drop Down Sub Menu" and as the main sheet "All Pages".
I want to be able to see any changes made in the first 3 sheets mentioned on the main sheet which is "All Pages". I have a system that i am using to asses where the pages of the website are at in terms of development.
This is a consistent feature on all of the sheets. So the question is.. How do i reflect a change in "Main Navigation" or the others on the "All Pages" sheet? The sheet "All pages" has as described all the pages of the site listed. The other sheets only have the specific pages that come under the description. So there is NO overlap of cells, they have just been split.
An example of what i am looking for is if Cell D2 in "Main Navigation" has an "X" inside, cell D2 on the sheet All Pages should have an "X" inside, or if cell D6 in "Drop Down" has an "X" inside the cell that is relevant in the sheet "All Pages" should also have an "X"!
Sorry if that has confused anyone!
Thank you in advance!!!

A: If you don't want to link every single cell, the most simple catch all solution is to use the change event. (http://msdn.microsoft.com/en-us/library/office/ff839775.aspx)
You can add a function which copies the changes to a cell onto your all pages. I guess you need some formula so the right change goes to the right cell which depends on how you want your page to look.


text:
Q: AWS Media Convert 1401 error: Authorization error when "Block Public Access settings for this account" is enabled on S3 bucket I have a media convert job that will take input video from s3 bucket then convert it and store it in another bucket within the same account.
However, when "Block Public Access settings for this account" is enabled for s3 bucket then I get 1401
Unable to write to output file: [Failed to write data: Access Denied].
The media convert and S3 are on the same AWS account.
When I disabled the blocking of public access it worked. However, i would like to have this security layer in place

A: The MediaConvert service assumes a specified IAM role within your AWS account when running jobs and accessing S3 buckets on your behalf.
Please double-check that the IAM Role you are using to run your MediaConvert jobs has the Policy called 'AmazonS3FullAccess' attached along with the Policy called 'AmazonAPIGatewayInvokeFullAccess'.
These policies are all that is required for MediaConvert to read & write to a typical S3 bucket owned by this account, unless the bucket has additional conditions and restrictions within its Bucket Policy.
You may optionally prevent the Role from accessing a certain bucket by explicitly denying that Role access within the Bucket Policy on that bucket.
If you are using custom s3 access policies on the IAM Role used for MediaConvert jobs, rather than the default 'AmazonS3FullAccess', then you will have to ensure that the Conditions and Resources within your Role Policy and Bucket Policy both permit access to the bucket in question.


text:
Q: QM homework: I need to find result of this gaussian distribution integral This is a part of problem 1.3 from Griffiths's Introduction to Quantum Mechanics, 3rd Edition:

Consider the gaussian distribution: $\rho (x) = Ae^{-\lambda
 (x-a)^{2}}$
Find $\left \langle x \right \rangle = \int_{-\infty}^{+\infty}x\rho
 (x) \ dx$
Where A, a, and $\lambda$ are positive real constants.
(Look up any integrals you need)

I have scoured the web to find the result of this integral but have come up with nothing that includes the x term. I have normalized the distribution so I know what A is already, but beyond that I'm stumped. Any help will be much appreciated!

A: This is a pretty easy integral, just make the change of variable $u = x - a$. As far as I can see, you should get a term where you can complete the differential, and another which is a Gaussian integral.


text:
Q: Touchstart doesn't work properly On my company website, there is a button like this one:

<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar" id="menu"  onclick="expandfullscreenmenu('open'); return false">

</button>

The problem is that a user cannot 'tap' the button with a native browser on a Galaxy Tab 3. However, using Chrome on an LG Phone, the button works fine. In addition, many types of 'touchstart' stuff has been tried, but none of it is working on this this website. What is missing?
(The website can be viewed here.)


text:
Q: Parsing ony few fields of JSON I'm new to JSON so I hope you can help me.
I did this:
var myfields = Newtonsoft.Json.JsonConvert.DeserializeObject<Rootobject>(s);

this is the link for the JSON: link
As you can see I have many fields, each field is shown few times.
Now I have access only to the first one.
for example:
 final = myfields.results.First().warnings[0];

This String contains the first warnings field.
I tried to put instead of 0 - 1 but I get an error.
How can I get the others?
Thanks

A: Create class with only fields you need and then deserialize json
public class YourTwoField
{
    [JsonProperty("field1")]
    public string FieldOne { get; set; }

    [JsonProperty("field2")]
    public string FieldTwo { get; set; }
}

var myfields = Newtonsoft.Json.JsonConvert.DeserializeObject<YourTwoField>(yourJsonString);
// use values
myfields.FieldOne

Update on comments:
Your problem was that You didn't provide enough information at the beginning.
Fields you required is in the bottom level of JSON hierarchy.

*

*Copy your json result to the clipboard

*In Visual Studio open empty file

*Then Edit -> Paste Special -> Paste JSON as Classes

Now get all JSON schema as classes where I think will be generated some RootObject, then
var root = Newtonsoft.Json.JsonConvert.DeserializeObject<RootObject>(yourJsonString);

//Then your can brows to the values you want
root.results.First().openfda.generic_name
root.results.First().openfda.brand_name

Or loop all results
foreach(var result in root.results)
{
    result.openfda.generic_name;
    result.openfda.brand_name;
}


text:
Q: Select field that is not in a table but from alphanumeric data So I have 2 tables test1 and test2, they both contain columns: id,type,number, I want to select all the number from table test1 that are NOT in table test2, I know this would work;
SELECT test1.number,test2.number
FROM test1 LEFT JOIN test2 ON test1.number=test2.number
WHERE test2.number is null;

It returns what I was looking for when number column is entirely numeric but happens to be new numbers in new tables are like:
test1.number
MFP773773
**MFP874747**
MFP099290
MFP763636

test2.number
HBM366363
**HBM874747**
HBM773383
HBM092827

Then, how can I do the very same thing but only with the numeric part of "number" like in the second row where number is the same but letters are not, they way that they return different numbers no matter the characters before the numbers,please help.
Thank you very much.

A: Here is a userdefined function which can extract the numbers. try it out and see.
 CREATE FUNCTION dbo.udf_GetNumeric
    (@strAlphaNumeric VARCHAR(256))
    RETURNS VARCHAR(256)
    AS
    BEGIN
    DECLARE @intAlpha INT
    SET @intAlpha = PATINDEX('%[^0-9]%', @strAlphaNumeric)
    BEGIN
    WHILE @intAlpha > 0
    BEGIN
    SET @strAlphaNumeric = STUFF(@strAlphaNumeric, @intAlpha, 1, '' )
    SET @intAlpha = PATINDEX('%[^0-9]%', @strAlphaNumeric )
    END
    END
    RETURN ISNULL(@strAlphaNumeric,0)
    END
    GO

/* Run the UDF with different test values */
SELECT dbo.udf_GetNumeric('') AS 'EmptyString';
SELECT dbo.udf_GetNumeric('asdf1234a1s2d3f4@@@') AS 'asdf1234a1s2d3f4@@@';
SELECT dbo.udf_GetNumeric('123456') AS '123456';
SELECT dbo.udf_GetNumeric('asdf') AS 'asdf';
SELECT dbo.udf_GetNumeric(NULL) AS 'NULL';
GO


text:
Q: PHP read Javascript array I am passing an array from Javascript to PHP page, as below.
var arrF1 = [{"Item":"item1no",
      "Desc":"item1desc",
      "Remarks":"item1note"},
             {"Item":"item2no",
      "Desc":"item2desc",
      "Remarks":"item2note"}
    ];
$.ajax({
   type: "POST",
   url: "http://www.mydomain.com/pdfs/flist.php",
   data: { favArray : arrF1 },
   success: function() {
        alert('ok, sent');
   }
});

In my PHP page, I read the array as below.
$fArray = json_decode($_POST['favArray'])

And I tried to access the arrays value like this.
$fArrav[0]->{'Item'}
$fArrav[0]->{'Desc'}
$fArrav[1]->{'Item'}

Is this correct?
I am generating a PDF on the server using FPDF.
But with the above, its not reading the array.
I must not be doing this right.
Please help.
Thank you.

A: With this PHP:
function handlePost() {
    $a = $_POST['favArray'];
    var_dump($a);
}

..and this Javascript:
function post() {
    var a1 = [
        {"Item":"109249383",
         "Desc":"item1desc",
         "Remarks":"item1note"},

        {"Item":"298298210",
         "Desc":"item2desc",
         "Remarks":"item2note"}
    ];

    $.ajax({
        type: "POST",
        url: "readArray.php",
        data: { favArray : a1 },
        success: function() {
            alert1('ok, sent');
        }
    });
}

...I get this output:
HTTP/1.1 200 OK
Content-Type: text/html
Server: Microsoft-IIS/7.5
X-Powered-By: PHP/5.3.10
Date: Wed, 11 Jul 2012 21:04:16 GMT
Content-Length: 315

array(2) {
  [0]=>
  array(3) {
    ["Item"]=>
    string(9) "109249383"
    ["Desc"]=>
    string(9) "item1desc"
    ["Remarks"]=>
    string(9) "item1note"
  }
  [1]=>
  array(3) {
    ["Item"]=>
    string(9) "298298210"
    ["Desc"]=>
    string(9) "item2desc"
    ["Remarks"]=>
    string(9) "item2note"
  }
}

In this case, the encoding of the data on the wire is not JSON.  It is 'application/x-www-form-urlencoded' as per the default used by jQuery's ajax function. Looks like this:
favArray=%5B%7B%22Item%22%3A%22109249383%22%2C%22Desc%22%3A%22item1desc%22%2C
    %22Remarks%22%3A%22item1note%22%7D%2C%7B%22Item%22%3A%22298298210%22%2C%22
    Desc%22%3A%22item2desc%22%2C%22Remarks%22%3A%22item2note%22%7D%5D

(all on one line)
Therefore it does not make sense to call json_decode within PHP - there was never any JSON involved. PHP decodes the url-encoded post body automatically.

If you want to encode with JSON, then you can use JSON.stringify() directly.  This may require json2.js on the browser side. (see this answer)
To use JSON, then you would need something like this in the browser:
function post_json_encoded() {
    $.ajax({
        type: "POST",
        url: "postArray.php",
        contentType: 'application/json', // outbound header
        dataType: 'text',                // expected response
        data: JSON.stringify(a1),        // explicitly encode
        success: function() {
            alert1('ok, json sent');
        }
    });
}

...and then something like this on the php side:
function handlePost() {
    header('Content-Type: text/plain; charset="UTF-8"');
    $post_body = file_get_contents('php://input');
    $a = json_decode($post_body);
    var_dump($a);
}

In this case the on-the-wire representation looks like this:
[{"Item":"109249383","Desc":"item1desc","Remarks":"item1note"},
 {"Item":"298298210","Desc":"item2desc","Remarks":"item2note"}]

...and the php var_dump output is this:
array(2) {
  [0]=>
  object(stdClass)#1 (3) {
    ["Item"]=>
    string(9) "109249383"
    ["Desc"]=>
    string(9) "item1desc"
    ["Remarks"]=>
    string(9) "item1note"
  }
  [1]=>
  object(stdClass)#2 (3) {
    ["Item"]=>
    string(9) "298298210"
    ["Desc"]=>
    string(9) "item2desc"
    ["Remarks"]=>
    string(9) "item2note"
  }
}

A: $fArray = $_POST['favArray'];
echo $fArray[0]['Item']; // item1no
echo $fArray[1]['Item']; // item2no

A: NO need for the extra brackets:
$fArrav[0]->Item


text:
Q: Java: get Map from Object Using this code
Map<String,Object> payloadMap = new HashMap<String,Object>();
payloadMap = (Map<String,Object>) new Gson().fromJson(result, payloadMap.getClass());

, I convert this json:
{
"name":"name1",
"job":"prosecutor",
"department": {
"department_name":"prosecutor's office"
}
}
to the map (map with unlimited number of child maps):

This done well, but now I want to get an access to values of child (nested) maps.
In parent map child maps "wrapped" to Object.
So, I tried to get "wrapped" child maps from the Object-values of parent map.
  public void mapRequestNode (Map<String,Object> payloadMap) {
    payloadMap.entrySet().forEach(node->this.getDataFromNode(node));
  }

As you can see from the above picture, there are no way to use child map "department", which had been "wrapped" to Object. I have an access to Object-methods, but not to the Map-methods (for example, I cant use "value.get("department_name")". I tried cast "(Map<String, Object>)value", but without success...
The "department" name in case above is only for example!  I dont know concrete name of json child-objects. There may be unlimited number of names! So I cant use something like this "payloadMap.get("department")"

A: Following
((Map<String, Object>)payloadMap.get("department")).get("department_name")

should work, dont?

A: Your variable value is of type Object, which means that the compiler will not know anything else about the variable. Even if the object you retrieve from your json file is a map, as you store it in a Object variable, the compiler will handle it as an Object and not as a Map. That is why you cannot do value.get("department"); : the method get does not exist for the type Object.
You need to cast whatever is stored in value.get("department") as a Map<String, Object> to be able to handle it as a Map.

A: I have found a special solution.
I convert json to Map<String,Map<String,Object>>.
Not in Map<String,Object>. In this case I can successfully use child-maps of parent dto-map.
But this solution is special (not general) in the meaning that, I can handle in this way json, which consist only of objects.
For example, if I try to get the value of "job" in following example:
{
   "job": "prosecutor",
  "department": {
                 "department_name":"prosecutor's office"
                 }
}

by using Map.Entry<String, Map<String, Object>> payloadNodeEntry.getValue,
I will receive ClassCastException (cant cast String to Map<String, Object> ).


text:
Q: PHP Show more decimal numbers i want to show numbers like this 200,00 when i write them in input.
Like i write 200 and automatically the number changes to 200,00
How can i do this?
<?
Value 1 <input type="text" name="value1">
Value 2 <input type="text" name="value2">
?>
<?
$total = $value1 + $value2;
?>

$total must have ,00 numbers at the end

A: Try number_format function
$total = "1279";
echo number_format($total, 2, ',', '.'); // 1.279,00

Syntax
number_format(number, decimal, decimal seperator, thousand seperator)

A: Use number_format to echo the variable on your site.
See here: http://php.net/manual/en/function.number-format.php
number_format($total, 2, ',', '');

A: Try using a function called number_format
echo number_format($total,2);

A: number_format( $total, 2, ',', '' );


text:
Q: Messy vector cross product supposed to equal zero vector If $\vec{u},\vec{v},\vec{w}$, and $\vec{a}$ all lie in the same plane in $\mathbb{R_3}$, then $(\vec{u} \times \vec{v}) \times (\vec{w}\times\vec{a})=\vec{0}$.
I tried to multiply the whole thing out manually and ended up with a VERY messy expression that didn't simplify to the zero vector.
Any better ways of doing it?

A: A somewhat nicer formula to prove is for any vectors $a,b,c\in \mathbb R^3$ is $a\times (b\times c) = \langle a,c\rangle b -\langle a, b\rangle c$
Then we have
$(u\times v)\times(w\times a)= \langle (u\times v),a\rangle w - \langle (u\times v),w\rangle a$
Notice that $(u\times v)$ will be perpendicular to the plane where $a$ is lying, hence their dot product is 0. Same goes for  $\langle(u\times v),w\rangle$
Thus, $(u\times v)\times(w\times a)=0-0=0$


text:
Q: Python type annotations breaking syntax highlighting in vscode When I try to add type annotations (for return types) to my functions then the syntax highlighting in vscode is not working after that point. Do you have a hint on what setting to change to fix the issues?
VSCode Version 1.67.1
Python Version 3.10.8
Code with type annotations
def median_absolute_deviaton(data: list) -> float:
    """Returns the median absolute deivation (MAD) [float]."""
    med = median(data)
    deviations = [abs(i-med) for i in data]
    return statistics.median(deviations)

Image with working syntax highlighting

Image with broken syntax highlighting

A: You may need to install and/or select the right Python interpreter:

There's a python version shown at the lower right corner of the VSCode window. Click it, then select a version of python at least as high as python 3.5 (the version of python where type annotations were added).
If you don't have a version of python that high listed, then you'll need to install one.
If you have one installed and it isn't listed, then you can manually enter the path to the version you installed.

A: SOLVED: It was caused by the "Python for VSCode" extension. Uninstalling helped. Found it here: https://github.com/MagicStack/MagicPython/issues/138#issuecomment-403538358


text:
Q: What's the difference between HEAD and HEAD~1? It was suggested to me that I could restore my code to the way it is in the origin repository using this command:
git reset --soft HEAD~1

I looked for information on this but didn't find anything that explained
HEAD~1

What does the ~1 part of the command do?

A: The official documentation for this syntax is in the gitrevisions manpage.
HEAD~1 means: go back 1 commit from HEAD, using the first parent (most commits have only one parent, so this syntax covers most cases where you want to go further back).
HEAD~1 is so common that it can also be shortened to HEAD~.
It's important to understand, though, that HEAD has little to do with the state of the origin repository! HEAD~1 will happen to match the current state of the origin in these cases:

*

*You just pulled (merged) from the origin, and it created a merge commit (prompted for a merge commit message).

*You were up-to-date with the origin and then made a single new commit on top.

In other cases you would probably use @{upstream} which references the upstream of your current branch (also documented in the gitrevisions manpage).
Finally, --soft often isn't the right choice, either. It means that all your changes will be preserved in the working tree and index. Your files won't change at all, and git status will show all the changes as "to be committed".
If you want to basically hit the reset button and irrevocably destroy all committed and uncommitted changes you have locally compared to the upstream, I recommend this:
git reset --hard @{upstream}


text:
Q: Consuming webservices with arrays c# asp.net

This is the Struct class I create
public struct Biller
{

    public string BillerTag { get; set; }
    public string Description { get; set; }
    public string FirstField { get; set; }
    public string FirstFieldFormat { get; set; }
    public string FirstFieldWidth { get; set; }
    public string SecondField { get; set; }
    public string SecondFieldFormat { get; set; }
    public string SecondFieldWidth { get; set; }
    public string ServiceCharge { get; set; }

}

I am trying to use this code but it only shows 1 and only the last output
[WebMethod(Description = "Retrieves list of available BILLERS for collection as well as other information necessary for the transaction")]
    public Biller GetBillerList(string AccountID, string UserName, string Password)
    {

    ECPNBills.ECPNBillsPaymentService Client = new ECPNBills.ECPNBillsPaymentService();
    ECPNBills.BStruct Str = new ECPNBills.BStruct();

        Biller Bil = new Biller();

        Str = Client.GetBillerList(AccountID, UserName, Password);

        foreach (ECPNBills.BStruct cd in Client.GetBillerList(AccountID, UserName, Password))
        {
            Bil.BillerTag = cd.BillerTag;
            Bil.Description = cd.Description;
            Bil.FirstField = cd.FirstField;
            Bil.FirstFieldFormat = cd.FirstFieldFormat;
            Bil.FirstFieldWidth = cd.FirstFieldWidth;
            Bil.SecondField = cd.SecondField;
            Bil.SecondFieldFormat = cd.SecondFieldFormat;
            Bil.SecondFieldWidth = cd.SecondFieldWidth;
            Bil.ServiceCharge = cd.ServiceCharge;

        }

        return Bil;

    }

I am not sure what code to use in order to get all the items from BStruct.
I am also trying to consume webservice to webservice. Thank you in advance~

A: Change return type of your method to List<Biller>.
[WebMethod(Description = "Retrieves list of available BILLERS for collection as well as other information necessary for the transaction")]
public List<Biller> GetBillerList(string AccountID, string UserName, string Password)
{

    ECPNBills.ECPNBillsPaymentService Client = new ECPNBills.ECPNBillsPaymentService();
    ECPNBills.BStruct Str = new ECPNBills.BStruct();

    List<Biller> BilList = new List<Biller>();

    Str = Client.GetBillerList(AccountID, UserName, Password);

    foreach (ECPNBills.BStruct cd in Client.GetBillerList(AccountID, UserName, Password))
    {
        Biller Bil = new Biller();

        Bil.BillerTag = cd.BillerTag;
        Bil.Description = cd.Description;
        Bil.FirstField = cd.FirstField;
        Bil.FirstFieldFormat = cd.FirstFieldFormat;
        Bil.FirstFieldWidth = cd.FirstFieldWidth;
        Bil.SecondField = cd.SecondField;
        Bil.SecondFieldFormat = cd.SecondFieldFormat;
        Bil.SecondFieldWidth = cd.SecondFieldWidth;
        Bil.ServiceCharge = cd.ServiceCharge;

        BilList.Add(Bil);
    }

    return BilList;

}


text:
Q: Slowing Down JavaScript Loop I have a piece of JavaScript that generates every possible combination of a charset for the length provided. Since I'm using it for a length of 12, it's a very long loop that freezes and crashes the browser.
I've tried replacing the for loop with a setInterval() but it only seemed to break it.
How can I slow down my loop?
Here's the script:
var charset = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890',
    charset_length = charset.length;

function recurse(width, pos, base) {
    for (var i = 0; i < charset_length; i++) {
        if (pos < width - 1) {
            recurse(width, pos+1, base + charset[i]);
        }
        console.log(base + charset[i]); // replaced later
    }
}

recurse(12, 0, '');

EDIT: Because each output will open a new tab (that will close itself once done), I want to slow it down so a maximum of 5 tabs approx. are open at the same time.


text:
Q: Obtaining timing score of a implementation run with a PlanAhead TCL script In a PlanAhead TCL script, I need to know the timing score of a completed implementation run.
I have found an old way to do this from 2012. The solution is read directly the PAR report file.
In Vivado exist the TNS property that can be read directly with the report_property command. It exist a similar (and cleaner) way to obtain the timing score in PlanAhead?
Other options to obtain the timing score?
Best regards

A: Seems that the only way to obtain the Timing Score is reading directly the PAR report.
Next the code posted by Avrum in that old conversation at Xilinx forum
set d [get_property DIRECTORY [get_runs impl_1]]
set f [glob $d/*routed.par]
set chan [open $f]
while {[gets $chan line] >= 0} {
  # puts $line
  if {[string match "Timing Score*" $line]} {set score [lindex $line 2] }
}
close $chan
puts "Timing Score is $score"

I have test it, and works fine.
Best regards


text:
Q: How do I embed an open-source project in a django project for GAE? I am a python newbie. Can anybody tell me how I will be embed an open-source project in my django project for GAE? Let's say I would like to embed Python markdown. Can anybody show me a direction? Can I just copy and paste my source into my django folder and modify something in the settings.py to get it done?
The reason for embedding the source is that GAE does not allow egg files running in it.

A: Simply unzip the contents of the folder inside the .egg archive which is not named EGG-INFO to your application folder.

A: Obviously you are inteding to use the python version of appengine, for every external library that you want to deploy with your application, except from importing in my own experience when I recently had to use external libraries they weren't working in the online version unless I had them to the root folder of my app.

A: Surely you can place the module in the python-path and import it wherever you need in your django code? Or is this not what you want?

A: Take a look at Tipfy and see how they handle dependencies. You can probably use the same techniques in Django.
http://www.tipfy.org/


text:
Q: With EclipseLink how do you disable automatic uppercase conversion on creation When using EclipseLink for ddl generation, it always default column and table names to uppercase.
Is there a way to disable this globally rather than setting each columns name attribute? , or to make it use the Class name, or your own column name serializer?
Thanks a lot!
EclipseLink output
[EL Config]: metadata: The column name for element [warehouseCreatedTimestamp] is being defaulted to: WAREHOUSECREATEDTIMESTAMP.
The table name for entity [class entities.ActivityFlags] is being defaulted to: ACTIVITYFLAGS.

A: This can be disabled by configuration:
https://www.eclipse.org/eclipselink/documentation/2.5/jpa/extensions/p_jpa_uppercase_column_names.htm
in persistence.xml or code (as usual)
 <property name="eclipselink.jpa.uppercase-column-names" value="false"/>

If You want implement selective rule, implement in code
org.eclipse.persistence.dynamic.DynamicHelper.SessionCustomizer

My fragment add underscores to tables by specific rule.  Columns are possible too.
public class MySessionCustomizer extends SessionCustomizer {

@Override
public void customize(Session session) throws SQLException {

    for (ClassDescriptor descriptor : session.getDescriptors().values()) {
        // Only change the table name for non-embedable entities with no
        // @Table already
        if (!descriptor.getTables().isEmpty() && descriptor.getAlias().equalsIgnoreCase(descriptor.getTableName())) {
            String tableName = addUnderscores(descriptor.getTableName());
            descriptor.setTableName(tableName);
    }
 }
 }

and fire it from persistence.xml
<property name="eclipselink.session.customizer"  value="pl.....MySessionCustomizer" />

EDIT: people say UPPERCASE columns are orthodox. I use CamelCase in one JPA project, UPPER in other, historical dependency.
Some databases are strict (MS SQL Server), some not (Derby for column given without apostrophes?)


text:
Q: scroll view does not display the received data correspondingly in my App i have a scroll view that should display data received from network broker using mqtt protocol at very high rate. the published DATA to the network broker are sent in millisecond percision. the time stamp spans from .001xx seconds to 4500 seconds, and for each time-scheduled some data will be published according to the time stamp, and the app should receive these data and display it on the scroll view.
the problem is, when the data is published at very high rate, the scroll view freez for some seconds then display the data, in other words, the scroll view does not display the data interactively.
to clarify my problem mre, i have a large file with thousands of lines, and each line has a time-stamp, and according to the time stamp i am publishing data from a java GUI, the published data is received on an Android App, that should display these data in the scrolView, but what happens is, for an example, after approx. 1000 published line, the scroll view display them at once, and for the subsequent 1000 lines the scroll view freez for a while and then display them at once, and it does not correspondingly display each published data, it should wait for a while then display bunch of published data.
is there any way to solve such problem.
i wish my explanation is clear.
Code:
sv_arrivedMessaes = (ScrollView) v.findViewById(R.id.sv_arrivedMessaes);
sv_arrivedMessaes.post(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                tv_msg_arrived.setText(mStrBuf);
                sv_arrivedMessaes.fullScroll(View.FOCUS_DOWN);
            }
        });
    }


text:
Q: Adding dynamic block to magento checkout Hello I was wondering if it possible to add 'dynamic' block to magento checkout onepage. Under 'dynamic' block I mean that when I proceed through checkout onepage steps and for example, I choose specific payment type then the block is shown, otherwise it's not seen at all.
I've reached as far as when I choose my custom payment method the block is generated and text is shown, but only if I add the block's name('excellence2') to my Onepage.php $stepCodes list:
   $stepCodes = array('billing', 'shipping',  'shipping_method', 'payment', 'excellence2', 'review');

Is there any way to generate 'excellence2' block without adding it to stepCodes?


text:
Q: Error transporting binary data over ssh/telnet (even shell) in expect script It seems like no one is maintaining this repo and this repo any more.
Assuming I'd like to fetch data from remote with user/password auth automating in expect script, like the following:
ps: I use sh to refer ssh/telnet connection
$ expect -v
expect vesion 5.45.4
$ cat expect.sh
#!/usr/bin/expect -f

spawn -noecho sh -c ./download.sh
interact
$ cat download.sh
#!/bin/sh

sh -c 'cat /bin/ls' # cat a binary file
$ ./expect.sh > a.out
$ file a.out
a.out: ELF 64-bit LSB shared object, x86-64, version1 (SYSV), too many program (2304)

As the last command said, captured command ls (i.e. a.out) has broken locally. And you can find if you actually run the script, the two files are different in bytesize (let alone checksum).
I though it might be related to traslation and encoding issue, so I change the expect.sh script to this and it still not working
$ cat expect.sh
#!/usr/bin/expect -f

spawn -noecho sh -c ./download.sh
fconfigure $spawn_id -translation binary -encoding binary
fconfigure stdin -translation binary -encoding binary
fconfigure stdout -translation binary -encoding binary
interact

Anybody has any idea?

A: Usually dumping a binary file to tty would cause unexpected results. You can just try cat /bin/ls in an interactive shell and see what would happen. A tty is not a pass-through pipe. It does not output exactly what is sent to it.
See this simple example:
[STEP 101] # printf '\n'

[STEP 102] # printf '\n' | hexdump -C
00000000  0a                                                |.|
00000001
[STEP 103] #
[STEP 104] # expect -c 'spawn -noecho printf \n; expect eof'

[STEP 105] # expect -c 'spawn -noecho printf \n; expect eof' | hexdump -C
00000000  0d 0a                                             |..|
00000002
[STEP 106] #
[STEP 107] # expect -d -c 'spawn -noecho printf \n; expect eof'
expect version 5.45.4
parent: waiting for sync byte
parent: telling child to go ahead
parent: now unsynchronized from child
spawn: returns {57875}

expect: read eof
expect: set expect_out(spawn_id) "exp4"
expect: set expect_out(buffer) "\r\n"
argv[0] = expect  argv[1] = -d  argv[2] = -c  argv[3] = spawn -noecho printf \n; expect eof
set argc 0
set argv0 "expect"
set argv ""
[STEP 108] #

As you can see, \n is converted to \r\n when outputted to the tty.

A: You should have more success if you set the tty to raw mode first. In expect this is done by setting global variable stty_init to the sort of string values you would give the stty command. For example,
set stty_init raw
log_user 0
spawn ssh user@host "cat /bin/ls; sleep 1"
expect assword: {send mypassword\r}
expect \n
log_user 1
expect eof

Direct the stdout of the above into a file and it should get just the contents of the ls file. Note how log_user 0 is used to suppress output until we have read past the \n newline. Also, I had to add a sleep after the cat otherwise the tty was closed before all the data was read and the file ended up a little shorter than the original. There should probably be a better way of doing that.


text:
Q: lxml get text of elements with no tag I am using lxml library with python to parse a simple XML that prints the text of the next elements in this case HD as shown in the XML below
<BOOK>
   <HD>The Best Book Ever</HD>
   <HD>Table of Contents</HD>
   <EXTRACT>
      <TC>I. Introduction</TC>
      <TC>II. Summary</TC>
      <TC>III. Topic 1</TC>
      <TC>IV. Topic 2</TC>
   </EXTRACT>
   <HD>I. Introduction</HD>

      Lorem Ipsum is simply dummy text of the printing and typesetting industry.
      <FTN>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam purus elit, suscipit eget</FTN>

has been the industry standard dummy text ever since the 1500s

   <HD>II. Summary</HD>

       <FT>data 1</FT>
       data 2
      <FT>data 3</FT>

       <FT>data 4</FT>
       data 5
      <FT>data 6</FT>

has been the industry standard dummy text ever since the 1500s

   <HD>III. Topic 1</HD>

      something

something else

   <HD>IV. Topic 2</HD>

      something1

something else 1

      something 2

something else 2

   <HD>V. Topic 3</HD>

      something not to show up

because not in EXTRACT as TC

</BOOK>

my python code looks as shown below where it's supposed to print all the contents next to HD tag
import os
from lxml import etree

file_name = 'demofile2.xml'
full_file_name = os.path.abspath(os.path.join('', file_name))

def load_local_file(filename):
    dom = etree.parse(filename)

    #get all content of elements after HD tag
    TOCsHD = dom.getroot().findall('HD')
    for hd in TOCsHD:
        text = hd.text
        print(text)
        for x in hd.getnext().iter():
            print(x.text)
            print(x.tail)
        print("------------------------------")

load_local_file(full_file_name)

My output is shown below. As you can see, II. Summary for example is not printing data 4, data 5, data 6. Can someone please help me with this? Thank you so much!
The Best Book Ever
Table of Contents

------------------------------
Table of Contents

I. Introduction

II. Summary

III. Topic 1

IV. Topic 2

------------------------------
I. Introduction

      Lorem Ipsum is simply dummy text of the printing and typesetting industry.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam purus elit, suscipit eget

------------------------------
II. Summary

data 1

       data 2

data 3

------------------------------
III. Topic 1

      something

something else

------------------------------
IV. Topic 2

      something1

something else 1

------------------------------
V. Topic 3

      something not to show up

because not in EXTRACT as TC

------------------------------

A: I am not sure, but guess what you need probably is itersiblings:
import os
from lxml import etree

file_name = 'demofile2.xml'
full_file_name = os.path.abspath(os.path.join('', file_name))

def load_local_file(filename):
    dom = etree.parse(filename)

    #get all content of elements after HD tag
    TOCsHD = dom.getroot().findall('HD')
    for hd in TOCsHD:
      print("Siblings of: " + hd.text)
      theIter = hd.itersiblings()
      for x in theIter:
          print(x.tag, "".join(x.itertext()).strip().replace("\n", ""), sep=": ")
      print("------------------------------")

load_local_file(full_file_name)

I am not sure this would be the result you are seeking, but if you are interested in the sibling of the tags, this function would work.
Output
Siblings of: The Best Book Ever
HD: Table of Contents
EXTRACT: I. Introduction      II. Summary      III. Topic 1      IV. Topic 2
HD: I. Introduction
p: Lorem Ipsum is simply dummy text of the printing and typesetting industry.      Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam purus elit, suscipit eget
p: has been the industry standard dummy text ever since the 1500s
HD: II. Summary
p: data 1       data 2      data 3
p: data 4       data 5      data 6
p: has been the industry standard dummy text ever since the 1500s
HD: III. Topic 1
p: something      something else
HD: IV. Topic 2
p: something1      something else 1
p: something 2      something else 2
HD: V. Topic 3
p: something not to show up      because not in EXTRACT as TC
------------------------------
Siblings of: Table of Contents
EXTRACT: I. Introduction      II. Summary      III. Topic 1      IV. Topic 2
HD: I. Introduction
p: Lorem Ipsum is simply dummy text of the printing and typesetting industry.      Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam purus elit, suscipit eget
p: has been the industry standard dummy text ever since the 1500s
HD: II. Summary
p: data 1       data 2      data 3
p: data 4       data 5      data 6
p: has been the industry standard dummy text ever since the 1500s
HD: III. Topic 1
p: something      something else
HD: IV. Topic 2
p: something1      something else 1
p: something 2      something else 2
HD: V. Topic 3
p: something not to show up      because not in EXTRACT as TC
------------------------------
Siblings of: I. Introduction
p: Lorem Ipsum is simply dummy text of the printing and typesetting industry.      Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam purus elit, suscipit eget
p: has been the industry standard dummy text ever since the 1500s
HD: II. Summary
p: data 1       data 2      data 3
p: data 4       data 5      data 6
p: has been the industry standard dummy text ever since the 1500s
HD: III. Topic 1
p: something      something else
HD: IV. Topic 2
p: something1      something else 1
p: something 2      something else 2
HD: V. Topic 3
p: something not to show up      because not in EXTRACT as TC
------------------------------
Siblings of: II. Summary
p: data 1       data 2      data 3
p: data 4       data 5      data 6
p: has been the industry standard dummy text ever since the 1500s
HD: III. Topic 1
p: something      something else
HD: IV. Topic 2
p: something1      something else 1
p: something 2      something else 2
HD: V. Topic 3
p: something not to show up      because not in EXTRACT as TC
------------------------------
Siblings of: III. Topic 1
p: something      something else
HD: IV. Topic 2
p: something1      something else 1
p: something 2      something else 2
HD: V. Topic 3
p: something not to show up      because not in EXTRACT as TC
------------------------------
Siblings of: IV. Topic 2
p: something1      something else 1
p: something 2      something else 2
HD: V. Topic 3
p: something not to show up      because not in EXTRACT as TC
------------------------------
Siblings of: V. Topic 3
p: something not to show up      because not in EXTRACT as TC
------------------------------

Note that you need to use itertext as well in order to get all the text inside of all tags. For example, there are a few p tags that have inner tags inside them. If you want to have the text value of these p tags, you will need to apply itertext in order to get the inner text. You can gain insight into the process by looking at the line with "".join(x.itertext()).strip().replace("\n", "").


text:
Q: Application to Display Morning,Evening IOS application to display Morning/Afternoon/Evening with logged in Name.
eg: Good Morning Mr.X like this.
Need to calculate those event from current date and time zone

A: // For calculating the current date
NSDate *date = [NSDate date];

// Make Date Formatter
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"hh a"];

// hh for hour mm for minutes and a will show you AM or PM
NSString *str = [dateFormatter stringFromDate:date];
NSLog(@"%@", str);

// Sperate str by space i.e. you will get time and AM/PM at index 0 and 1 respectively
NSArray *array = [str componentsSeparatedByString:@" "];

// Now you can check it by 12. If < 12 means Its morning > 12 means its evening or night

NSString *message;
NSString *personName = @"Mr.X";
NSString *timeInHour = array[0];
NSString *am_pm      = array[1];

if([timeInHour integerValue] < 12 && [am_pm isEqualToString:@"AM"])
{
    message = [NSString stringWithFormat:@"Good Morning %@", personName];
}
else if ([timeInHour integerValue] <= 4 && [am_pm isEqualToString:@"PM"])
{
    message = [NSString stringWithFormat:@"Good Afternoon %@", personName];
}
else if ([timeInHour integerValue] == 12 && [am_pm isEqualToString:@"PM"])
{
    message = [NSString stringWithFormat:@"Good Afternoon %@", personName];
}
else if ([timeInHour integerValue] > 4 && [am_pm isEqualToString:@"PM"])
{
    message = [NSString stringWithFormat:@"Good Night %@", personName];
}

NSLog(@"%@", message);

Using NSCalendar You can get hour as well:
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *dateComponents = [gregorian components:NSHourCalendarUnit fromDate:date];

NSInteger hour = [dateComponents hour];
if (hour < 12)
{
    // Morning
}
else if (hour > 12 && hour <= 16)
{
    // Afternoon
}
else
{
    // Night
}

A: You could use NSDateComponents
NSDateComponents *components = [[NSCalendar currentCalendar] components:NSCalendarUnitHour fromDate:[NSDate date]];
NSInteger currentHour = [components hour];
if (currentHour >= 0 && currentHour < 12) {
    //@"Good Morning
} else if (currentHour >= 12 && currentHour < 17) {
    //Good Afternoon
} else if (currentHour >= 17 && currentHour < 21) {
    //Good Evening
} else {
    //"Good Night
}


text:
Q: Spring MVC Web Request and Android Request to Same Method I have an spring mvc web application in which users login to session "session.setAttribute" classically. Whenever I need loggedin user data I use this data.
Now I want to add android app and what I want to learn do I have to add additional methods for each android request and send user data within it?
Or Is there away to make a request to same methods.
What is the consept for this kind of cloud apps? Do I have to write different methods for android requests? Because it is not possible session.getAttribute when wemake an android request, it returns null.
User user = userService.getByUserNameAndPassword(userName, password);
    if (user != null) {

        if (user.isActive()) {
                Account account = new Account(user, request.getRemoteAddr());
                HttpSession httpSession = request.getSession(true);
                AccountRegistry.add(httpSession);
                httpSession.setAttribute(Constant.ACCOUNT, account);
                result.put(Constant.REF, Constant.SUCCESS);

        }

public class Account {
private UserRightsHandler userRightsService = null;
private User user;
private String ipAddress;
private boolean admin;

public Account(User user, String ipAddress) {
    this.user = user;
    this.ipAddress = ipAddress;
    userRightsService = new UserRightsHandler(user);
    setAdmin(userRightsService.isAdmin());
}

public UserRightsHandler getUserRightsService() {
    return userRightsService;
}

public User getUser() {
    return this.user;
}

public String getIpAddress() {
    return ipAddress;
}

public boolean isAdmin() {
    return admin;
}

private void setAdmin(boolean admin) {
    this.admin = admin;
}

}
public class AccountRegistry {
private static final Map<String, HttpSession> sessions = new HashMap<String, HttpSession>();

public static void add(HttpSession session) {
    sessions.put(session.getId(), session);
}

public static void remove(HttpSession session) {
    if (session != null) {
        sessions.remove(session.getId());
        session.setAttribute(Constant.ACCOUNT, null);
        session.invalidate();
    }
}

public static HttpSession getByHttpSessionID(String httpSessionID) {
    Set<String> keys = sessions.keySet();
    Iterator it = keys.iterator();
    while (it.hasNext()) {
        String sID = (String) it.next();
        HttpSession session = sessions.get(sID);
        if (sID.equals(httpSessionID)) {
            return session;
        }
    }
    return null;
}

public static void removeByHttpSessionID(String httpSessionID) {
    HttpSession session = getByHttpSessionID(httpSessionID);
    remove(session);
}

public static Account getCurrentAccount() {
    HttpServletRequest request = ContextFilter.getCurrentInstance().getRequest();
    HttpSession session = request.getSession();
    return (Account) session.getAttribute(Constant.ACCOUNT);
}

}
@RequestMapping(value = "/changeStatus", method = RequestMethod.POST)
    public @ResponseBody
    String changeStatus(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
        User editor = AccountRegistry.getCurrentAccount().getUser();

    }

A: You can ask user send their user and password at the start of Android app via custom authenticate request like /appLogin then if it is correct creditentals you can return a key to user (to app) and store it to some variable during app run. Then when user want to do something send a request to server you can send it to a function with mapping like /appExampleService then you can check at that function this key and device valid depending on how you handle custom login process then this function call existing function that is used for web browsers that have mapping /exampleService. For example;
@JsonSerialize
@RequestMapping("/appExampleService")
public int someServiceForAppClient(
        @RequestParam(value = "key", required = true) String apikey,
        @RequestParam(value = "param", required = true) String someParam{
    String name=userDAO.getUsernameFromApiKey(apikey);
    return someService(someParam, name);
}

@JsonSerialize
@RequestMapping("/exampleService")
public int someServiceForWebClient(
        @RequestParam(value = "param", required = true) String someParam) {
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    String name = auth.getName();
    return someService(someParam, name);
}

public int someService(String someParam,String name){

    return doBusiness(someParam, name);
}

userDAO is just something I created for to get info of user with given key. And there is a service for App login as well which return that key to user when he started the app send his username and pass


text:
Q: Receive ,display and incorporate? Is someone tried already the receive, display and incorporate CCDA document?
Can someone give me a not technical explanation for this one?

A: Well, in short, yes - C-CDA documents are XML files that can be transmitted to other organizations or vendors. The XML needs to be parsed - meaning you need to know what you are looking for in terms of patient information - then normalized (JSON) with objects created (javascript) that can be called from the HTML or whatever you're building. It's very possible and there are several resources out there, such as BlueButton+, but I wouldn't suggest moving forward with any project until you have someone who has a clinical or health admin background.


text:
Q: How to adapt mobile site for different mobiles? I am developing a mobile site for iphone, and i want it to be used in other mobiles, for example, gphone, blackberry, sumsong, motorola etc.
what should i do for adapting the mobile site for so many different mobile devices?
Thanks for any advice.

A: Unfortunately I do not think there is an easy answer to this, other than to say that the simpler you make your mobile site the more likely it is to appear correctly/consistently across multiple devices/networks. You also need to consider the 'app' mindset with iPhone, where something that previously might have been presented simply as a web site, is now frequently presented in an app instead. Finally, bear in mind that many phones do not support flash (iPhone famously..), silverlight, javascript etc. If your site loses too much of its look and feel without these than you may have to redirect to targeted sub-sites per phone type.
See this similar question which may help you get a feel first for how your web site looks on different devices and in different networks:
Testing Mobile Sites
If you do need to change the look and feel for different phones, then you will need some way to detect the phone types - there are many articles etc about this which you should be able to find with Google - for example:
http://www.hand-interactive.com/resources/detect-mobile-php.htm
Again, it would be good to test whatever one you use in your target network to check it works as expected (operators may use devices, for example proxies and optimisers, which may affect how things arrive at your webserver or phone...).


text:
Q: Is there a way to put an image into the legend of a bar chart (chart.js)? A simple stacked bar graph

    <title>Stacked Bar Chart</title>

        <canvas id="canvas"></canvas>

    <button id="randomizeData">Randomize Data</button>

in the x-axis labels, I am trying to get a small icon (image) to be displayed instead of a number. I have tried to put just the image tag in all possible combinations of " and ' as well as with the number. But to no avail. The chart does not render. It seems that the label needs to recognized as a value to render and the html tag knocks this out of place. I don't see why an image tag cannot be put in there, is there a way to do this?


text:
Q: c# WebBrowser GetElementById don't work I have this html code:
    <div style="font-size: 0.8em; font-weight: bold">
    <label
    for="formFile" style="margin-right: 10px">Select a file:
    </label>
    <input
    class="text" type="file" tabindex="1" value="" id="formFile"
    name="formFile"
    />
</div>

This is my code for find HtmlElement formFile:
HtmlElement oElement = webBrowser1.Document.GetElementById("formFile");

But oElement is Always null. What am I doing wrong?


text:
Q: Visualizar dados de banco Oracle via MySQL Preciso saber como faço para ter os dados de um banco de dados Oracle em meu banco MySQL, uma espécie de view.
Não desejo fazer insert, update nem delete no banco Oracle, preciso apenas um select desses dados, para ter eles em minha base MySQL.
Encontrei dois caminhos, os quais não tenho certeza se funcionam:
1) Tenho o ODBC do Oracle instalado em meu servidor que tem MySQL, porém não sei fazer o MySQL "ver" esse meu ODBC para criar um link entre as bases de dados.
2) Encontrei o que parece ser um bom caminho para solucionar o problema: http://ftp.nchu.edu.tw/MySQL/tech-resources/articles/dbixmyserver.html
O tutorial referencia a utilização de um servidor de Proxy, o qual torna-se o intermediário entre banco MySQL e outros bancos. Este intermediário é quem permite que uma base de dados possa dar um SELECT na outra base.
Acredito que a solução disposta no item 2 realmente funciona, porém, não tenho conhecimentos em desenvolvimento Perl e não sei como fazer a configuração de proxy requerida para dar certo.

A: Eu só utilizei ao contrário, fazendo o oracle acessar as tabelas no mysql através de um DBLINK [https://hs2n.wordpress.com/2012/04/03/oracle-create-database-link-to-mysql-database/]
Não seria melhor você fazer isto? De acordo com o que muda no oracle, você por dentro do oracle atualiza no mysql.
Nunca configurei, mais para acessar um dblink vc vai acessar assim: tabela@nomeDbLink, no caso se tiver um dblink configurado no oracle para o mysql, você já consegue acessar as tabelas.
Acessando: [https://community.oracle.com/thread/2273134]

A: É possível utlizando Federated Tables via Perl DBIx::MyServer proxy

*

*referência

*download
O link que você mandou (que citei como referência) coincidentemente é a melhor referência que existe para se fazer isso, então a melhor opção e estudar mesmo

A: $ora_user = "usuario";
$ora_senha = "senha";
$ora_bd = "(DESCRIPTION=
      (ADDRESS_LIST=
        (ADDRESS=(PROTOCOL=TCP)
          (HOST=192.168.xxx.xxx)(PORT=1521)
        )
      )
      (CONNECT_DATA=(SERVICE_NAME=yyyyy))
 )";

if ($ora_conexao = oci_connect($ora_user,$ora_senha, $ora_bd)){
    echo 'Conexão bem sucedida';
}else{
    echo 'Conexão falhada';
}

select
$stid = oci_parse($ora_conexao, 'SELECT A.MATRICULA,
A.NOME_FUNCIONARIO, A.APELIDO FROM VIEW_X A');
oci_execute($stid);

while ($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS)) {
    //echo ....
}


text:
Q: Error executing DDL "insert into ..." via JDBC Statement in Spring Boot I'm working on a simple Spring Boot project, and I try to load some data from an import.sql file.
The table is created from the entity, but the data isn't loaded and I receive this error below. The problem is only for MySQL, for H2 there is no error.
2022-06-18 15:37:05.457 DEBUG 16272 --- [           main] o.h.type.spi.TypeConfiguration$Scope     : Scoping TypeConfiguration [org.hibernate.type.spi.TypeConfigur
ation@7b3085a3] to SessionFactoryImpl [org.hibernate.internal.SessionFactoryImpl@c1a74d]
Hibernate:

    drop table if exists currency_exchange
Hibernate:

    create table currency_exchange (
       id bigint not null auto_increment,
        conversion_multiple decimal(19,2),
        environment varchar(255),
        currency_from varchar(255),
        currency_to varchar(255),
        primary key (id)
    ) engine=InnoDB
2022-06-18 15:37:05.874  INFO 16272 --- [           main] o.h.t.schema.internal.SchemaCreatorImpl  : HHH000476: Executing import script 'file:/D:/cloud-project/cur
rency-exchange-service/target/classes/import.sql'
Hibernate:
    insert into currency_exchange
2022-06-18 15:37:05.896  WARN 16272 --- [           main] o.h.t.s.i.ExceptionHandlerLoggedImpl     : GenerationTarget encountered exception accepting command : Err
or executing DDL "insert into currency_exchange" via JDBC Statement

org.hibernate.tool.schema.spi.CommandAcceptanceException: Error executing DDL "insert into currency_exchange" via JDBC Statement
        at org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:67) ~[hibernate-core-5.6.9.Final.jar:5.6.9.Fin
al]
        at org.hibernate.tool.schema.internal.SchemaCreatorImpl.applySqlString(SchemaCreatorImpl.java:458) ~[hibernate-core-5.6.9.Final.jar:5.6.9.Final]
        at org.hibernate.tool.schema.internal.SchemaCreatorImpl.applyImportSources(SchemaCreatorImpl.java:514) ~[hibernate-core-5.6.9.Final.jar:5.6.9.Final]
        at org.hibernate.tool.schema.internal.SchemaCreatorImpl.performCreation(SchemaCreatorImpl.java:183) ~[hibernate-core-5.6.9.Final.jar:5.6.9.Final]
        at org.hibernate.tool.schema.internal.SchemaCreatorImpl.doCreation(SchemaCreatorImpl.java:138) ~[hibernate-core-5.6.9.Final.jar:5.6.9.Final]
        at org.hibernate.tool.schema.internal.SchemaCreatorImpl.doCreation(SchemaCreatorImpl.java:124) ~[hibernate-core-5.6.9.Final.jar:5.6.9.Final]
        at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.performDatabaseAction(SchemaManagementToolCoordinator.java:168) ~[hibernate-core-5.6.9.Fin
al.jar:5.6.9.Final]
        at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.process(SchemaManagementToolCoordinator.java:85) ~[hibernate-core-5.6.9.Final.jar:5.6.9.Fi
nal]
        at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:335) ~[hibernate-core-5.6.9.Final.jar:5.6.9.Final]
        at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:471) ~[hibernate-core-5.6.9.Final.jar:5.6.9.Final]
        at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:1498) ~[hibernate-core-5.6.9.Final.jar:5.6.9.
Final]
        at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:
58) ~[spring-orm-5.3.20.jar:5.3.20]
        at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:365) ~[s
pring-orm-5.3.20.jar:5.3.20]
        at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:409) ~[spring-orm-5.3
.20.jar:5.3.20]
        at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:396) ~[spring-orm-5.3.20.jar:5.3.2
0]
        at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.afterPropertiesSet(LocalContainerEntityManagerFactoryBean.java:341) ~[spring-orm-5.3.
20.jar:5.3.20]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1863) ~[spring-be
ans-5.3.20.jar:5.3.20]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1800) ~[spring-beans
-5.3.20.jar:5.3.20]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:620) ~[spring-beans-5.
3.20.jar:5.3.20]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:542) ~[spring-beans-5.3.
20.jar:5.3.20]
        at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335) ~[spring-beans-5.3.20.jar:5.3.20]
        at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-5.3.20.jar:5.3
.20]
        at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333) ~[spring-beans-5.3.20.jar:5.3.20]
        at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208) ~[spring-beans-5.3.20.jar:5.3.20]
        at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1154) ~[spring-context-5.3.20.jar:5.3.20]
        at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:908) ~[spring-context-5.3
.20.jar:5.3.20]
        at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:583) ~[spring-context-5.3.20.jar:5.3.20]
        at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:147) ~[spring-boot-2.7.0
.jar:2.7.0]
        at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:734) ~[spring-boot-2.7.0.jar:2.7.0]
        at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:408) ~[spring-boot-2.7.0.jar:2.7.0]
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:308) ~[spring-boot-2.7.0.jar:2.7.0]
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1306) ~[spring-boot-2.7.0.jar:2.7.0]
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1295) ~[spring-boot-2.7.0.jar:2.7.0]
        at com.gab.microservices.currencyexchangeservice.CurrencyExchangeServiceApplication.main(CurrencyExchangeServiceApplication.java:10) ~[classes/:na]
Caused by: java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syn
tax to use near '' at line 1
        at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:120) ~[mysql-connector-java-8.0.29.jar:8.0.29]
        at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122) ~[mysql-connector-java-8.0.29.jar:8.0.29]
        at com.mysql.cj.jdbc.StatementImpl.executeInternal(StatementImpl.java:763) ~[mysql-connector-java-8.0.29.jar:8.0.29]
        at com.mysql.cj.jdbc.StatementImpl.execute(StatementImpl.java:648) ~[mysql-connector-java-8.0.29.jar:8.0.29]
        at com.zaxxer.hikari.pool.ProxyStatement.execute(ProxyStatement.java:94) ~[HikariCP-4.0.3.jar:na]
        at com.zaxxer.hikari.pool.HikariProxyStatement.execute(HikariProxyStatement.java) ~[HikariCP-4.0.3.jar:na]
        at org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:54) ~[hibernate-core-5.6.9.Final.jar:5.6.9.Fin
al]
        ... 33 common frames omitted

Hibernate:
    (id, currency_from, currency_to)
2022-06-18 15:37:05.909  WARN 16272 --- [           main] o.h.t.s.i.ExceptionHandlerLoggedImpl     : GenerationTarget encountered exception accepting command : Err
or executing DDL "(id, currency_from, currency_to)" via JDBC Statement

org.hibernate.tool.schema.spi.CommandAcceptanceException: Error executing DDL "(id, currency_from, currency_to)" via JDBC Statement
        at org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:67) ~[hibernate-core-5.6.9.Final.jar:5.6.9.Fin
al]
        at org.hibernate.tool.schema.internal.SchemaCreatorImpl.applySqlString(SchemaCreatorImpl.java:458) ~[hibernate-core-5.6.9.Final.jar:5.6.9.Final]
        at org.hibernate.tool.schema.internal.SchemaCreatorImpl.applyImportSources(SchemaCreatorImpl.java:514) ~[hibernate-core-5.6.9.Final.jar:5.6.9.Final]
        at org.hibernate.tool.schema.internal.SchemaCreatorImpl.performCreation(SchemaCreatorImpl.java:183) ~[hibernate-core-5.6.9.Final.jar:5.6.9.Final]
        at org.hibernate.tool.schema.internal.SchemaCreatorImpl.doCreation(SchemaCreatorImpl.java:138) ~[hibernate-core-5.6.9.Final.jar:5.6.9.Final]
        at org.hibernate.tool.schema.internal.SchemaCreatorImpl.doCreation(SchemaCreatorImpl.java:124) ~[hibernate-core-5.6.9.Final.jar:5.6.9.Final]
        at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.performDatabaseAction(SchemaManagementToolCoordinator.java:168) ~[hibernate-core-5.6.9.Fin
al.jar:5.6.9.Final]
        at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.process(SchemaManagementToolCoordinator.java:85) ~[hibernate-core-5.6.9.Final.jar:5.6.9.Fi
nal]
        at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:335) ~[hibernate-core-5.6.9.Final.jar:5.6.9.Final]
        at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:471) ~[hibernate-core-5.6.9.Final.jar:5.6.9.Final]
        at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:1498) ~[hibernate-core-5.6.9.Final.jar:5.6.9.
Final]
        at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:
58) ~[spring-orm-5.3.20.jar:5.3.20]
        at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:365) ~[s
pring-orm-5.3.20.jar:5.3.20]
        at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:409) ~[spring-orm-5.3
.20.jar:5.3.20]
        at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:396) ~[spring-orm-5.3.20.jar:5.3.2
0]
        at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.afterPropertiesSet(LocalContainerEntityManagerFactoryBean.java:341) ~[spring-orm-5.3.
20.jar:5.3.20]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1863) ~[spring-be
ans-5.3.20.jar:5.3.20]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1800) ~[spring-beans
-5.3.20.jar:5.3.20]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:620) ~[spring-beans-5.
3.20.jar:5.3.20]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:542) ~[spring-beans-5.3.
20.jar:5.3.20]
        at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335) ~[spring-beans-5.3.20.jar:5.3.20]
        at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-5.3.20.jar:5.3
.20]
        at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333) ~[spring-beans-5.3.20.jar:5.3.20]
        at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208) ~[spring-beans-5.3.20.jar:5.3.20]
        at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1154) ~[spring-context-5.3.20.jar:5.3.20]
        at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:908) ~[spring-context-5.3
.20.jar:5.3.20]
        at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:583) ~[spring-context-5.3.20.jar:5.3.20]
        at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:147) ~[spring-boot-2.7.0
.jar:2.7.0]
        at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:734) ~[spring-boot-2.7.0.jar:2.7.0]
        at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:408) ~[spring-boot-2.7.0.jar:2.7.0]
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:308) ~[spring-boot-2.7.0.jar:2.7.0]
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1306) ~[spring-boot-2.7.0.jar:2.7.0]
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1295) ~[spring-boot-2.7.0.jar:2.7.0]
        at com.gab.microservices.currencyexchangeservice.CurrencyExchangeServiceApplication.main(CurrencyExchangeServiceApplication.java:10) ~[classes/:na]
Caused by: java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syn
tax to use near 'id, currency_from, currency_to)' at line 1
        at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:120) ~[mysql-connector-java-8.0.29.jar:8.0.29]
        at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122) ~[mysql-connector-java-8.0.29.jar:8.0.29]
        at com.mysql.cj.jdbc.StatementImpl.executeInternal(StatementImpl.java:763) ~[mysql-connector-java-8.0.29.jar:8.0.29]
        at com.mysql.cj.jdbc.StatementImpl.execute(StatementImpl.java:648) ~[mysql-connector-java-8.0.29.jar:8.0.29]
        at com.zaxxer.hikari.pool.ProxyStatement.execute(ProxyStatement.java:94) ~[HikariCP-4.0.3.jar:na]
        at com.zaxxer.hikari.pool.HikariProxyStatement.execute(HikariProxyStatement.java) ~[HikariCP-4.0.3.jar:na]
        at org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:54) ~[hibernate-core-5.6.9.Final.jar:5.6.9.Fin
al]
        ... 33 common frames omitted

Hibernate:
    values (10001, 'USD', 'INR')
2022-06-18 15:37:05.959  WARN 16272 --- [           main] o.h.t.s.i.ExceptionHandlerLoggedImpl     : GenerationTarget encountered exception accepting command : Err
or executing DDL "values (10001, 'USD', 'INR')" via JDBC Statement

org.hibernate.tool.schema.spi.CommandAcceptanceException: Error executing DDL "values (10001, 'USD', 'INR')" via JDBC Statement
        at org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:67) ~[hibernate-core-5.6.9.Final.jar:5.6.9.Fin
al]
        at org.hibernate.tool.schema.internal.SchemaCreatorImpl.applySqlString(SchemaCreatorImpl.java:458) ~[hibernate-core-5.6.9.Final.jar:5.6.9.Final]
        at org.hibernate.tool.schema.internal.SchemaCreatorImpl.applyImportSources(SchemaCreatorImpl.java:514) ~[hibernate-core-5.6.9.Final.jar:5.6.9.Final]
        at org.hibernate.tool.schema.internal.SchemaCreatorImpl.performCreation(SchemaCreatorImpl.java:183) ~[hibernate-core-5.6.9.Final.jar:5.6.9.Final]
        at org.hibernate.tool.schema.internal.SchemaCreatorImpl.doCreation(SchemaCreatorImpl.java:138) ~[hibernate-core-5.6.9.Final.jar:5.6.9.Final]
        at org.hibernate.tool.schema.internal.SchemaCreatorImpl.doCreation(SchemaCreatorImpl.java:124) ~[hibernate-core-5.6.9.Final.jar:5.6.9.Final]
        at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.performDatabaseAction(SchemaManagementToolCoordinator.java:168) ~[hibernate-core-5.6.9.Fin
al.jar:5.6.9.Final]
        at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.process(SchemaManagementToolCoordinator.java:85) ~[hibernate-core-5.6.9.Final.jar:5.6.9.Fi
nal]
        at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:335) ~[hibernate-core-5.6.9.Final.jar:5.6.9.Final]
        at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:471) ~[hibernate-core-5.6.9.Final.jar:5.6.9.Final]
        at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:1498) ~[hibernate-core-5.6.9.Final.jar:5.6.9.
Final]
        at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:
58) ~[spring-orm-5.3.20.jar:5.3.20]
        at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:365) ~[s
pring-orm-5.3.20.jar:5.3.20]
        at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:409) ~[spring-orm-5.3
.20.jar:5.3.20]
        at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:396) ~[spring-orm-5.3.20.jar:5.3.2
0]
        at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.afterPropertiesSet(LocalContainerEntityManagerFactoryBean.java:341) ~[spring-orm-5.3.
20.jar:5.3.20]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1863) ~[spring-be
ans-5.3.20.jar:5.3.20]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1800) ~[spring-beans
-5.3.20.jar:5.3.20]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:620) ~[spring-beans-5.
3.20.jar:5.3.20]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:542) ~[spring-beans-5.3.
20.jar:5.3.20]
        at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335) ~[spring-beans-5.3.20.jar:5.3.20]
        at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-5.3.20.jar:5.3
.20]
        at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333) ~[spring-beans-5.3.20.jar:5.3.20]
        at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208) ~[spring-beans-5.3.20.jar:5.3.20]
        at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1154) ~[spring-context-5.3.20.jar:5.3.20]
        at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:908) ~[spring-context-5.3
.20.jar:5.3.20]
        at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:583) ~[spring-context-5.3.20.jar:5.3.20]
        at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:147) ~[spring-boot-2.7.0
.jar:2.7.0]
        at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:734) ~[spring-boot-2.7.0.jar:2.7.0]
        at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:408) ~[spring-boot-2.7.0.jar:2.7.0]
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:308) ~[spring-boot-2.7.0.jar:2.7.0]
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1306) ~[spring-boot-2.7.0.jar:2.7.0]
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1295) ~[spring-boot-2.7.0.jar:2.7.0]
        at com.gab.microservices.currencyexchangeservice.CurrencyExchangeServiceApplication.main(CurrencyExchangeServiceApplication.java:10) ~[classes/:na]
Caused by: java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syn
tax to use near '(10001, 'USD', 'INR')' at line 1
        at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:120) ~[mysql-connector-java-8.0.29.jar:8.0.29]
        at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122) ~[mysql-connector-java-8.0.29.jar:8.0.29]
        at com.mysql.cj.jdbc.StatementImpl.executeInternal(StatementImpl.java:763) ~[mysql-connector-java-8.0.29.jar:8.0.29]
        at com.mysql.cj.jdbc.StatementImpl.execute(StatementImpl.java:648) ~[mysql-connector-java-8.0.29.jar:8.0.29]
        at com.zaxxer.hikari.pool.ProxyStatement.execute(ProxyStatement.java:94) ~[HikariCP-4.0.3.jar:na]
        at com.zaxxer.hikari.pool.HikariProxyStatement.execute(HikariProxyStatement.java) ~[HikariCP-4.0.3.jar:na]

This is the entity:
package com.gab.microservices.currencyexchangeservice.bean;

import lombok.*;

import javax.persistence.*;
import java.math.BigDecimal;
@Data
@RequiredArgsConstructor
@NoArgsConstructor
@Entity
public class CurrencyExchange {
    @NonNull
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @NonNull
    @Column(name = "currency_from")
    private String from;

    @NonNull
    @Column(name = "currency_to")
    private String to;

    @NonNull
    private BigDecimal conversionMultiple;

    private String environment;
}

application.yml
spring:
  application:
    name: currency-exchange
  config:
    import: optional:configserver:http://localhost:8888
  cloud:
    config:
      uri: http://localhost:8888
      username: gigi
      password: test1234
  jpa:
    show-sql: true
  datasource:
    url: jdbc:mysql://127.0.0.1:6666/testdb?allowPublicKeyRetrieval=true&useSSL=false
    username: root
    password: test1234

server:
  port: 8000

spring.jpa.defer-datasource-initialization: true
spring.jpa.properties.hibernate.format_sql: true
logging.level.org.hibernate.type: trace
spring.jpa.hibernate.ddl-auto: create
spring.datasource.initialization-mode: always
spring.jpa.properties.hibernate.dialect: org.hibernate.dialect.MySQL8Dialect

import.sql
insert into currency_exchange
(id, currency_from, currency_to)
values (10001, 'USD', 'INR');

pom
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.0</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.gab.microservices</groupId>
    <artifactId>currency-exchange-service</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>currency-exchange-service</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>11</java.version>
        <spring-cloud.version>2021.0.3</spring-cloud.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-config</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.24</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

I don't think the problem is the dialect, because it creates the table, only the data isn't loaded in the table. I'm using org.hibernate.dialect.MySQL8Dialect, if I change the value for dialect it doesn't create the table. Any feedback will be apreciated! Thank you!

A: It seems like the insert query has been read like 3 separate queries. Try to change the import.sql to:
insert into currency_exchange(id, currency_from, currency_to) values (10001, 'USD', 'INR');

Not sure why you have the error though, I've tested it with the latest Hibernate ORM 5.6.9.Final and it worked fine.
Maybe it's a bug in the version you are using (should be 5.4.32).
Or maybe there's something else in the import.sql?


text:
Q: Wanna use 1 field for data positioning in table and that must be auto incremented I want to use 1 field for data positioning in table and that must be auto incremented
public function DBInsert($table_name, $form_data){
    // retrieve the keys of the array (column titles)
    $fields = array_keys($form_data);// build the query
    $sql = "INSERT INTO ".$table_name.".(`".implode('`,`', $fields)."`)VALUES('".implode("','", $form_data)."')";
    //echo $sql;// run and return the query result resource return
    mysql_query($sql) or die(mysql_error());
}


text:
Q: Visual Studio "New Project" Dialog - Set available tests Does anyone know how to include NUnit (for example) as one of the available test types in the Visual Studio 2010 "New Project" dialog for MVC projects and / or as an installed template in the New Project window?
From memory, it requires a number of steps including playing with the registry, copying files to specific folders, secret incantations and ritual sacrifice.
Suggestions appreciated.

A: See Creating Project and Item Templates on MSDN.


text:
Q: Date based script not working I have added a query in my site so that it will show div based on date. I have added 30 div in my site and added display none to them. Used the date based query to make one div active each day. Previously it is working when I have added that for 2 days. But when I am adding that for 30 day basis, it is not working for me. My url is here.
You can check the code is executed here.

Can anyone point me what I am doing wrong?

A: There's issue in your javascript logic. In your case, current date is always greater than the date in any of the expiry named variable, so always first if statement is executed, rest of the statement provided in else if block will never be executed. This is how the if  elseif statement work i.e., when condition in if block evaluates to true then do not execute elseif statement.
You will need to check current date with all expiry date variable i.e. with expiry , expiry2 , expiry3, expiry4 and so on.
Correction required:
Replace else if with if.
here's the correct logic:

Hope this helps!

A: In your question I found it odd that you were hard coding all of the days. If you are planning to use var current = new Date(); then this gets today's / current date, therefore you will literally have to update those hard coded values every single day for forever.
I took the liberty of converting your code into something more minimalistic. Clicking the Click Me button simulates the passing of days over the next 30 consecutive days relative to today's current date.

// Create an ease of use function to add days to a given date
Date.prototype.addDays = function(days) {
  var dat = new Date(this.valueOf());
  dat.setDate(dat.getDate() + days);
  return dat;
}

// Start with all divs hidden
$('.panchang').hide();

// This will be called when our button is clicked
function start() {
  var today = new Date(); // get today's date
  var expiryDates = new Array();
  for (var i = 0; i < 30; ++i) // store the dates of the next 30 days
    expiryDates.push(new Date().addDays(i));

  // Every 100 milli seconds, simulate the passing of 1 day
  var interval = setInterval(() => {
    var keyDateIndex = null;
    // iterate expiry dates and see which dates we have surpassed
    for (let [index, value] of expiryDates.entries()) {
      if (today.getTime() > value.getTime())
        keyDateIndex = index;
      else
        break;

    }

    if (keyDateIndex == expiryDates.length - 1)
      clearInterval(interval);
    else
      today = today.addDays(1);

    // Show the correct divs
    $('.panchang').hide();
    $('.panchang:eq(' + keyDateIndex + ')').show();

  }, 100);

}

<button onclick="start()">Click Me</button>

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30


text:
Q: Tsql function to return parent id of the direct parent, not the grandparent This is the structure of my database: I have a table tblMenu and table tblProduct. One menu can have multiple products. That relationship is stored in the tblMenu_products table. However, one product can be consisted of multiple products and multiple ingredients. That relationship is saved in the tblProduct_Ingredients table, in which I have a column called table so that I know if the ingredient is from tblProduct or tblIngredient.
What I need to do is this: for one menu, list all of its direct and indirect items. That means all of the products in the menu, and all of their products and ingredients, and all of their products anmd ingredients, and so on.
This is my function in tsql:
CREATE function [dbo].[fnListInfo](@menu_id int) returns @res table(
 [id] [int] NOT NULL IDENTITY,
 [itemId] INT,
 [name] NVARCHAR(255),
 [type] NVARCHAR(20),
 [parent] int
)

BEGIN
    INSERT INTO @res

    SELECT product.product_id, product.name, product.type, menuProducts.parent
    FROM tblMenu menu
    JOIN dbo.tblMenu_products menuProducts on menu.menu_id = menuProducts.menu_products_menu
    JOIN dbo.tblProduct product ON menuProducts.menu_products_product = product.product_id
    WHERE menu.menu_id = @menu_id

    insert into @res
        SELECT t.*
        FROM @res r
        CROSS APPLY dbo.fnTest(r.itemId, r.id) AS t
        WHERE r.type = 'product'

 RETURN
END
GO

In fnTest I send an input parameter of the product id and get all of the items for that product (sons, grandsons, etc.).
That function shows me the correct items I need to get.
Now what I need to do is this: fnListInfo has an id column which is autoincremented. I also have parentId which needs to show me the autoincremented id of the item's direct parent.
The problem happens when setting the parentid in fnTest. here's fnTest:
create function dbo.fnTest(@product_id INT, @autoincrement_id INT) returns @res table(
    [itemId] INT,
    [name] NVARCHAR(255),
    [type] NVARCHAR(20),
    [parent] INT)
begin
    ;WITH ret AS(
        SELECT *
        FROM dbo.tblProduct_Ingredients
        WHERE product_ingredient_product = @product_id
        UNION ALL
        SELECT prodIng.*
        FROM dbo.tblProduct_Ingredients AS prodIng
        INNER JOIN ret AS r ON r.product_ingredient_ingredient = prodIng.product_ingredient_product AND r.product_ingredient_table = 'tblProduct'
    )
    insert into @res
        select  ing.ing_id, ing.name, 'ingredient', @autoincrement_id /*parent*/
        FROM ret
        join dbo.tblIng as ing ON ret.product_ingredient_ingredient = ing.ing_id
        WHERE ret.product_ingredient_table = 'tblIng'

        UNION

        SELECT  product.product_id, product.name, 'product', @autoincrement_id /*parent*/
        FROM ret
        join dbo.tblProduct as product ON ret.product_ingredient_ingredient = product.product_id
        WHERE ret.product_ingredient_table = 'tblProduct'
    return
end
GO

The problem is that I set the parent to the items to the product in the menu, not to their direct product parent.
So, let's say we have a menu 'Breakfast' and in it I have a product 'Omelette Extra' which has a product of 'Omelette' and ingredient tomatoes. And let's say 'Omelette' has ingredient Egg. With my method above, I get that the parentId of Egg is 'Omelette extra', but I need to get 'Omelette'. How do i do this?


text:
Q: Update multiple sqlite rows with ids from same table I need some help with improving my SQLite database.
Right now table looks something like this:
ID |FORM     |MAINFORM
----------------------
1  |form     |form
2  |formAB   |form
3  |formBC   |form
4  |sample   |sample
5  |sampleAB |sample
6  |sampleBC |sample

What is the best and fastest way to update data in MAINFORM column from string format to int format, as in, to ID of an FORM which I can get from same table?
In the end I should have something like:
ID |FORM     |MAINFORM
----------------------
1  |form     |1
2  |formAB   |1
3  |formBC   |1
4  |sample   |4
5  |sampleAB |4
6  |sampleBC |4

So in this example "form" has an ID = 1, so all rows with MAINFORM = "form" will be updated to MAINFORM = 1.
MAINFORM can be empty, but if it's not, it will definitely have corresponding value in the table somewhere as a FORM (it will have ID).
Currently, there is around 600.000 rows in this table.

A: You can use a correlated subquery to look up the new value:
UPDATE MyTable
SET MainForm = (SELECT ID
                FROM MyTable AS T2
                WHERE T2.Form = MyTable.MainForm);

(The subquery will result in a value of NULL if the lookup fails.)