text:
Q: Static function Javascript I want to have a prototype and call a static function. Here is my code:
function Client() {
    this.username = "username",
    this.password = "Password",
    this.printUsername = function() {
        this.username=$("#Username").val()
        console.log(this.username);
    };
};

Here is me calling it:
<button onclick="Client.printUsername()" type="button">Submit</button>

Here is the error in the console:
Uncaught TypeError: Object function Client() {
    this.username = "username",
    this.password = "Password",
    this.printUsername = function() {
        this.username=$("#Username").val()
        console.log(this.username);
    };
} has no method 'printUsername'

What is wrong with my code?
This still creates the error:
function Client() {
    this.username = "username",
    this.password = "Password",
    this.setUsername = function() {
        this.username=$("#Username").val()
        console.log(this.username);
    };
};

Client.prototype.printUsername = function() {
    this.username = $("#Username").val();
    console.log(this.username);
}

A: you must instantiate your Client like so:
var client = new Client();
// now you can do:
client.printUsername();

This enables the this inside your Client to reference the thing you actually want, because without the new.. thing above, the this will point to something else, the window object probably.
you could also use a prototype: (extending original Client)
Client.prototype.printUsername = function() {
    this.username = $("#Username").val();
    console.log(this.username);
};

Update - Showing all the code flow:
function Client(){
    this.username = "username";
    this.password = "Password";
};

Client.prototype.printUsername = function(){
    this.username = $("#Username").val();
    console.log(this.username);
};

var client = new Client();
// call it
client.printUsername();

A: Sorry I didn't feel like downloading jQuery just to test this. It works any way. The method is both static, and an instance method.
<html>
<body>
<input id="Username">
<button onclick="Client.printUsername()" type="button">Submit</button>
<script>
function Client() {
    this.username = "username",
    this.password = "Password",
    this.printUsername = function() {
        this.username=document.querySelector("#Username").value;
        console.log(this.username);
    };
};
var proto = Client.prototype;
Client.printUsername = function(){
    proto.username=document.querySelector("#Username").value;
    console.log(proto.username);
};
</script>
</body>
</html>

You can also do it like this.
<html>
<body>
<input id="Username">
<button onclick="Client.printUsername()" type="button">Submit</button>
<button onclick="new Client().printUsername2()" type="button">Submit</button>
<script>
function Client() {};

Client.prototype.username = "username";
Client.prototype.password = "Password";
Client.prototype.printUsername = function() {
    this.username=document.querySelector("#Username").value;
    console.log(this.username);
};
var proto = Client.prototype;
Client.printUsername = function(){
    proto.printUsername.call(proto);
};
Client.prototype.printUsername2 = function(){
    console.log(this.username);
};
</script>
</body>
</html>

The solution to instance properties being unique for the instance.
<html>
<body>
<input id="Username">
<button onclick="Client.printUsername()" type="button">Submit</button>
<button onclick="new Client().printUsername2()" type="button">Submit</button>
<script>
function Client() {
    //this.init can also be left outside the constructor if you want to choose
    //if properties change between instances, and call the init method directly.
    this.init.apply(this, arguments);
};
Client.prototype.init = function(){
    this.username = "username";
    this.password = "Password";
};
Client.prototype.username = "username";
Client.prototype.password = "Password";
Client.prototype.printUsername = function() {
    this.username=document.querySelector("#Username").value;
    console.log(this.username);
};
var proto = Client.prototype;
Client.printUsername = function(){
    proto.printUsername.call(proto);
};
Client.prototype.printUsername2 = function(){
    console.log(this.username);
};
</script>
</body>
</html>

A: Change the function to:
function Client() {
    this.username = "username",
    this.password = "Password",
};

Client.printUsername = function() {
    this.username=$("#Username").val()
    console.log(this.username);
};

That is the equivalent to a static function.
--EDIT--
Re-read the question and the code, this won't work as expected since this won't be available. Static functions don't have access to an instance which is why they are static.


text:
Q: Write access on Apache WebDAV server I have set up a WebDAV server running Arch Linux 3.19.3 and Apache 2.4, according to the Arch Wiki [1] [2] and the Apache Documentation [3].
The only changes I made to /etc/httpd/conf/httpd.conf:
LoadModule dav_module modules/mod_dav.so
LoadModule dav_fs_module modules/mod_dav_fs.so
LoadModule dav_lock_module modules/mod_dav_lock.so

DAVLockDB /home/httpd/dav/DAVLock

Alias /dav "/srv/http/dav"
<Directory "/srv/http/dav">
    DAV On
    AllowOverride None
    Options Indexes FollowSymLinks
    AuthType Basic
    AuthName name
    AuthUserFile /etc/httpd/conf/passwd
    Require user name
    Order allow,deny
    allow
</Directory>

Related folders and their owners and permissions
drwxr-xr-x root root /srv
drwxrwxr-x http http /srv/http
drwxrwxr-x http http /srv/http/dav

As I'm editing this I realize the following is where the problem is.
drw-rw-r-x http http /home/httpd

The permissions should in stead be
drwxrwxr-x http http /home/httpd

since you can't access the contents of a folder without being able to execute (open) it.
I'm leaving the thread for the afterlife. Hopefully someone will find it useful.

A: The following is where the problem is.
drw-rw-r-x http http /home/httpd

The permissions should in stead be (and the same for the subdirectory)
drwxrwxr-x http http /home/httpd

since you can't access the contents of a folder without being able to execute (open) it.

redpajama_set_name: RedPajamaStackExchange


text:
Q: SearchView не обрабатывает поиск по пустой строке Использую для поиска в приложении onQueryTextListener.
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                // Делаем что-то...
                return true;
            }

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


text:
Q: PHP PDO : Binding value in one foreach loop regarding insert into on duplicate key update I'm using two foreach loops to bind the values to the positional parameters, one for INSERT INTO, the other for DUPLICATE KEY UPDATE. I was trying to reduce it to just one loop. But array_merge didn't work. Can someone tell me how can I get it done by using just one loop?
Here's an example:
  $facts = array("age","race");

  $ifield = "";
  $ufield="";
  $comma = "";
  foreach($facts as $f)
  {
    $$f  = (isset($_POST["$f"])?$_POST["$f"]:"");
    if ($$f)
    {
      $ifield .= $comma.$f;
      $ufield .= "{$comma}{$f} = ?";
      $comma = ",";
    }
  }

  $i = explode(',',$ifield);

  $in  = str_repeat('?,', count($i) - 1) . '?';

  $sql .= "INSERT INTO `users` (user_id,model_no,{$ifield}) VALUES(?,?,$in)";

  $sql .= " ON DUPLICATE KEY UPDATE $ufield";

  $users = $dbh->prepare($sql);

  $user_id = $_SESSION['user_id'];
  $model_no = $_POST["model_no"];

  $users->bindValue(1,$user_id);
  $users->bindValue(2,$model_no);

  /****************************************************************/
  $i = 3;

  foreach($facts  as $f)
  {
    global $$f;

     if ($$f)
     {
       $users->bindValue($i++, $$f);

     }
  }

  foreach($facts  as $f)
  {
    global $$f;

     if ($$f)
     {
       $users->bindValue($i++, $$f);

     }
  }

  $users->execute();

A: You don't need to use bound parameters in the ON DUPLICATE KEY clause. Use:
$ufield = "$comma $f = VALUES($f)";

Using VALUES(columndname) in the ON DUPLICATE KEY clause makes it use the value that would have been inserted into that column. See the documentation


text:
Q: Isolating Admin from User login windows app form to Database C# )
I'm having a bit of a problem separating a normal user login from an admin login.
the admin should see * data in the DB, and freely change any data s/he wants while a user may only see the allowed data without editing them.
and is there a way to set the permission within the DB ITSELF?
Thank you in previous.

A: The simplest implementation would be Role-Based Login. You can save the role attribute in your user table and read it each time users login. Here is a sample implementation:
https://www.c-sharpcorner.com/forums/role-based-user-login-with-switch-case-in-windows-app-in-c-sharp
For more granular access and more complicated permission we can use Controls Based Security. This makes role permission editable through the database. Sample implementation:
https://www.red-gate.com/simple-talk/dotnet/windows-forms/controls-based-security-in-a-windows-forms-application/

A: You need to distinguish users (admin/user) by adding a field in Users table.
For example if IsAdmin field is true then the logged in user is admin and you can give him editing permissions in your windows app.
When user logs in you can save his status (IsAdmin) in a global variable.
This is the simplest way.


text:
Q: JSch: sudo  sometimes not working I have three machines and I need to ssh to them one by one, and then sudo a command.
I need the JSch to do the following things:
ssh <user>@<machine>
sudo <some command>

This is the code block how I use to run JSch:
String homeFolder = System.getProperty("user.home");
JSch jsch = new JSch();
jsch.addIdentity(homeFolder + "/.ssh/id_rsa.pub");
jsch.setKnowHosts(homeFolder + "/.ssh/known_hosts");

final Session session = jsch.getSession(user, machine);
session.connect();

StringBuilder response = new StringBuilder();
try {
    final Channel channel = session.openChannel("exec");
    ((ChannelExec) channel).setCommand("sudo /etc/init.d/eedir status")
    channel.connect();

    try {
        InputStream in = channel.getInputStream();
        OutputStream out = channel.getOutputStream();

        out.write((password + System.getProperty("line.separator")).getBytes());

        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        String line = null;
        while (null != (line = reader.readLine())) {
            System.out.println(line);
        }
    } finally {
        channel.disconnect();
    }
} finally {
    session.disconnect();
}

My problem is that I can use this program successfully to get the status of the eedir service on two of the three machines I have, but not the last one.
I can ssh to the remote machine with the given user name and then run this command directly:
sudo /etc/init.d/eedir status

The username used in ssh is already configured in my /etc/sudoers.
So, my questions are:

*

*Why JSch can run this program on two of the three machines while the
rest one cannot? The sudoers' configuration is exactlly the same on
these machines.

*And another question is: why sudo  on the real machine
can run without typing the password again if I configured the current
user in sudoers, while JSch sudo require the password in the program?
Any directions are really appreciated. If there are some potential errors that I might have under my current circumstances, welcome everybody to point them out.
Thanks.

A: *

*what output do you get from the jsch sudo attempt on the failed machine? to get the error output you may need:
(ChannelExec)commandChannel.getErrStream();

the ssh server probably has different settings. on my server you need pty:
(ChannelExec)commandChannel.setPty(true);
(ChannelExec)commandChannel.setPtyType("VT100");

*generally you only need to type your password once per session for sudo. Maybe on the real machine you had already done sudo once and had not logged out. The above code reconnects each time so it needs to send the password every time.

A: I had the same problem on CentOS. Solved it by
1) after you do the setCommand on the channel do this:
((ChannelExec) channel).setPty(true);

2) make sure you have finally block/s to close the input stream, channel and session
Note: if the user does not require a password you don't need to open the output stream (unlike what is shown in the above example)

A: The latest version to date has a sample java class using sudo commands on a remote host. Download both the project .zip file and the .jar for they are separated for a reason only GOD knows !!


text:
Q: How can I create this string? My goal is to create a new variable that matches the output from fun(5) for each row but right now fun(1:5) does not give the desired output. Please advise me on how to create a new function that allows me to perform this operation in a vectorized manner since looping it would take a very long time.
I would like f(1:5) to produce a vector of 5 elements, each one matching the output given from f(5) corresponding to each row.
Thanks
names1 = c("x","y","z")
names2 <- c("hi","hello","bye")
fun <- function(x){paste(names2[which(df[x,names1] == 1)],collapse = " ")}
df <- data.frame(a = c(0,1,2,3,4),x = c(0,0,1,0,1),y = c(0,1,0,0,1),z = c(0,1,0,1,0))
fun(5) = "hi hello"
fun(1:5) = "bye NA NA NA NA NA"

A: You could use Vectorize in the following way below (if I understand correctly what the desired result is):
names1 = c("x","y","z")
names2 <- c("hi","hello","bye")
fun <- function(x){
           paste(names2[which(df[x,names1] == 1)],collapse = " ")
}
df <- data.frame(a = c(0,1,2,3,4),
                 x = c(0,0,1,0,1),
                 y = c(0,1,0,0,1),
                 z = c(0,1,0,1,0))
vfun <- Vectorize(fun)
vfun(5)
## [1] "hi hello"
vfun(1:5)
## [1] ""          "hello bye" "hi"        "bye"       "hi hello"

This essentially puts a wrapper around your function to deal with a vector of values of length > 1.


text:
Q: How to install Glc in Ubuntu 13.10? I am trying to install Glc on Ubuntu Saucy 13.10 so far without luck.
How can I install it?

A: There was no official glc package for "raring" and "saucy" in PPA repositories.So we need to edit the repository file for installing glc in Ubuntu 13.10,
sudo add-apt-repository ppa:arand/ppa
sudo gedit /etc/apt/sources.list.d/arand-ppa-saucy.list

change "saucy" to "precise" then save the file.Now run,
sudo apt-get update
sudo apt-get install glc


text:
Q: create bitpay client in node If I try to create a bitpay client in node after npm install bitpay and feeding it my on bitpay.com generated api key.
var client = BitPay.createClient('apikey');
I get:
assert.js:92  throw new assert.AssertionError({
AssertionError: Not enough entropy. Minimum is: 192 bits
at new HmacDRBG (/home/enigma/WebstormProjects/expensereports/node_modules/bitpay/node_modules/bitauth/node_modules/elliptic/lib/elliptic/hmac-drbg.js:24:3)
at EC.sign (/home/enigma/WebstormProjects/expensereports/node_modules/bitpay/node_modules/bitauth/node_modules/elliptic/lib/elliptic/ec/index.js:94:14)
at Object.BitAuth.sign (/home/enigma/WebstormProjects/expensereports/node_modules/bitpay/node_modules/bitauth/lib/bitauth.js:101:25)
at RESTClient._sendRequest (/home/enigma/WebstormProjects/expensereports/node_modules/bitpay/lib/rest-client.js:156:46)
at RESTClient.get (/home/enigma/WebstormProjects/expensereports/node_modules/bitpay/lib/rest-client.js:282:28)
at RESTClient._getAccessTokens (/home/enigma/WebstormProjects/expensereports/node_modules/bitpay/lib/rest-client.js:81:19)
at new RESTClient (/home/enigma/WebstormProjects/expensereports/node_modules/bitpay/lib/rest-client.js:51:17)
at Object.module.exports.createClient (/home/enigma/WebstormProjects/expensereports/node_modules/bitpay/index.js:10:12)
at Object.<anonymous> (/home/enigma/WebstormProjects/expensereports/server/api/btc/btc.controller.js:6:21)
at Module._compile (module.js:456:26)

if I try the website provided way:
$ npm install bitpay
var BitPay = require('bitpay');
var client = new BitPay('apikey');
client.on('ready', function() {
   client.post('invoices', { price: 10.00, currency: 'USD' });
});

it complains
var client = new BitPay('apikey'
TypeError: object is not a function
at Object.<anonymous> (/home/enigma/WebstormProjects/expensereports/server/api/btc/btc.controller.js:6:14)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Module.require (module.js:364:17)
at require (module.js:380:17)
at Object.<anonymous> (/home/enigma/WebstormProjects/expensereports/server/api/btc/index.js:4:18)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)

I also tried a couple of other ways non of them worked so my question how am I supposed to connect to this service?
If I use bitpay keygen to create a api.key file locally. How could I set this in my settings on bitpay.com to avoid {"error": "Invalid token"}?

A: There's a realistic possibility this API token is invalid. The 1st error message displayed means the API token's length is way too short and therefore invalid. Please verify you entered the correct API keys and enter it as a string. Are you sure you didn't remove the first character of the token when copying and pasting? Are you sure you didn't pick the wrong token? Example:
var client = new BitPay('MY_192_BIT_HUGE_API_TOKEN'); //192 bit string

Best regards,


text: Q: Adding a function on the paste event of Cleditor I am using cleditor as an text editor in my app. Whenever I paste something in the editor, I need to add a functionality on that event. But not able to find it. Please help me.


text:
Q: Highlight active link in SWRevealViewController I'm using SWRevealViewController in my project to create a slide out menu for my app.
Is it possible to highlight the currently active link in the menu which the slide out holds?
I've tried sending a page reference identifier to the sidebarviewcontroller but it seems like this has no effect as the view is only loaded once when the app launches and is then simply shown and hidden.
Any help would be much appreciated.
Cheers

A: I'm not sure that this is actually a question related to SWRevealViewController. Most likely your rear/bottom/menu view is really a UITableViewController. If that is that case then the solution is simple. Request that the UITableViewController remember its selected state.
- (void)viewDidLoad
{
    [super viewDidLoad];

    // Uncomment the following line to preserve selection between presentations.
    self.clearsSelectionOnViewWillAppear = NO;
}

This solution comes from: UITableView doesn't keep row selected upon return

A: I ended up doing this using NSNotification center. In each view controller's viewWillAppear I added...
// Send notification containing page reference to be picked up by sidebar view controller
NSDictionary *userInfo = [NSDictionary dictionaryWithObject:@"homePage" forKey:@"page"];
[[NSNotificationCenter defaultCenter] postNotificationName: @"activePage" object:nil userInfo:userInfo];

Which was picked up in the SidebarViewController viewDidLoad...
// Pick up the page reference notification and trigger receivePageReference function
[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(receivePageReference:)
                                             name:@"activePage"
                                           object:nil];

Then in the receivePageReference action...
-(void)receivePageReference:(NSNotification *)notification{
I reset all labels to a non-bold font
// Reset all labels to non-bold font
UILabel *homeLabel = (UILabel *)[self.view viewWithTag:12];
homeLabel.font = [UIFont fontWithName:@"Colaborate-Thin" size:19];

UILabel *liveLabel = (UILabel *)[self.view viewWithTag:13];
liveLabel.font = [UIFont fontWithName:@"Colaborate-Thin" size:19];

UILabel *racesLabel = (UILabel *)[self.view viewWithTag:14];
racesLabel.font = [UIFont fontWithName:@"Colaborate-Thin" size:19];

etc..
and set the label with the corresponding page reference to bold...
NSDictionary *notificationInfo = notification.userInfo;
if ([[notificationInfo objectForKey:@"page"] isEqualToString:@"homePage"]){
    UILabel *homeLabel = (UILabel *)[self.view viewWithTag:12];
     homeLabel.font = [UIFont fontWithName:@"Colaborate-Medium" size:19];
}


text:
Q: Finding the general solution of a differential equation using two methods. Can somebody please help me in finding the general solution of $2x^3dy=y(y^2+3x^2)dx$ using another method?
My attempt for the first method:
$2x^3y^{-3}dy-3x^2y^{-2}dx=dx$
Let $v=y^{-2}$; $dv=-2y^{-3}dy$
The equation now becomes:
$-x^3dv-3x^2vdx=dx$
$\frac{dv}{dx}+\frac{3v}{x}=-\frac{1}{x^3}$
$P(x)=\frac{3}{x}$, I.F.$=e^{3\int x^{-1}dx}=x^3$
$vx^3=-\int \frac{x^3}{x^3}dx$
$vx^3=-x+C$
$x^3=y^2(C-x)$

A: \begin{gather*}
\frac{dy}{dx} =\frac{y^{3}}{2x^{3}} +\frac{3y}{2x}\\
\\
Let\ y=tx\\
\frac{dy}{dx} =t+x\frac{dt}{dx}\\
t+x\frac{dt}{dx} =\frac{t^{3}}{2} +\frac{3t}{2}\\
x\frac{dt}{dx} =\frac{t^{3} +t}{2}\\
\\
\int \frac{2dt}{t^{3} +t} =\int \frac{dx}{x}\\
\\
Now,\ \int \frac{2dt}{t^{3} +t} =\int \frac{2dt}{t\left( t^{2} +1\right)} =\int \frac{2tdt}{t^{2}\left( t^{2} +1\right)}\\
\\
Let\ t^{2} =u\\
2tdt=du\\
\\
\int \frac{2dt}{t^{3} +t} =\int \frac{du}{u( u+1)} =\ln\frac{u}{u+1} =\ln\frac{t^{2}}{t^{2} +1} +C\\
\\
So,\ form\ the\ original\ differential\ equation,\\
\ln\frac{t^{2}}{t^{2} +1} +C_{1} =\ln x+C_{2}\\
\ln\frac{y^{2}}{y^{2} +x^{2}} -\ln x=C\\
\\
So,\ the\ general\ solution\ is\ \\
y^{2} =e^{c} x\left( x^{2} +y^{2}\right)
\end{gather*}
Hope this answers your question!


text:
Q: How to find what is inside of a selected parenthesis with regular expressions python? Hi I have this query and I would like to extract exactly the t0_0.pp,0 that is in COALESCENSE() parenthesis. I can have more parethesis before or after the COALESCENSE for this I am trying to use regular expressions like this (([^()]+))' but is givving me all inside all the parenthesis and I only wnat the COALESCENSE. Any idea?
select DISTINCT SUM(case when t0_0.pp is not null  then COALESCE(t0_0.pp,0)
else 0 end) from inventory_coverage_view t0_0 where  LOWER(t0_0.h) ='vg' AND t0_0.id = '9'

thank you in advance :)

A: To parse arbitrary SQL queries, you really need a specific parser.
If you know for sure there can be no other ) inside the COALESCE parentheses, you may update your regex in the following way:
import re
pat = r"COALESCE\((.*?)\)"
s = "select DISTINCT SUM(case when t0_0.pp is not null  then COALESCE(t0_0.pp,0)\nelse 0 end) from inventory_coverage_view t0_0 where  LOWER(t0_0.h) ='vg' AND t0_0.id = '9'"
m = re.search(pat, s)
if m:
    print(m.group(1)) # => t0_0.pp,0

See the regex demo and a Python demo.

*

*COALESCE\(  - matches the COALESCE( literal substring

*(.*?) - captures any 0+ chars other than line break chars, as few as possible, into Group 1

*\) - matches a literal ).


text:
Q: How to assert an imported Class in typescript? I need to import a nonexistent class (which would be exist when actually being used) in a typescript ES6 module. I hope it can be extended in this way:
/typings/events.d.ts:
export interface IEvents {
  $on(event: string, listener: () => {}): void;
  $once(event: string, listener: () => {}): void;
  $off(event: string, listener: () => {}): void;
  $emit(event: string): void;
}

main.ts
import { IEvents } from './typings/events.d.ts';
// @ts-ignore:ignore temporarily nonexistent module
import Events from '../../common/base/Events';

Events as IEvents; //Something like it...just to assert this class

class Monitor extends Events implements IEvents {
  constructor() {
    super();
    //So I can invoke this.$on, this.$off..etc directly.
  }
}

However, I always get the error message "Type 'Monitor' is missing the following properties from type 'IEvents': $on, $once, $off, $emit".
Is there any proper way to implement it? Thanks in advance! :D
EDIT:
I tried redeclaring Events variable after I import it (see code), but it doesnt work. The import line would be discarded after redeclaration..

A: When you have code written somewhere else but you want TypeScript to know about, you need to declare its type definitions somewhere.  Often you put these in their own dedicated library files, but you can use do inline declarations as well.
For example, you could declare it as a class, but you need to declare its property/methods also:
declare class Events implements IEvents {
    $on(event: string, listener: () => {}): void;
    $once(event: string, listener: () => {}): void;
    $off(event: string, listener: () => {}): void;
    $emit(event: string): void;
}

Or you can declare it is a type and a value, where the type corresponds to the instance side of the class, and the value represents the static side including the constructor.  This is often done in standard libraries, where you will see something like a Foo type and FooConstructor type, and a variable called Foo of the type FooConstructor.  (e.g., for Array you have interface Array<T> {...} for the instance side, interface ArrayConstructor for the static side, and declare var Array: ArrayConstructor; to show that there's an object named Array that acts as a constructor).  Here's how you might do it for Events:
interface Events extends IEvents { }
declare const Events: new () => IEvents;

Either of those would work for you.  Hope that helps; good luck!
Link to code


text:
Q: Drawing simple graphics over video, Play video frame-by-frame in Surface by lockCanvas() using MediaCodec? Surface without attching to window? I'm making a Live Wallpaper for Android API level 19+.
My wallpaper consists of two layers.

*

*I want to play video on a background. It should to be
transformable. I want to be able to change the scale and position of
the video.

*In the foreground I need to draw a simple graphics like
сanvas.drawCircle().
My attempts:
I started with MediaPlayer. The code below can play a video on wallpaper, but it can't to draw graphics over the video. OR it can draw graphics, but can't the video. As I understood it's because MediaPlayer completely locks the Canvas. I tried this by running MediaPlayer into the single Surface, in which I drawn animation of circle in the draw() method. And I received BaseSurfaceHolder: Exception locking surface.
There is a global problem that limits me:
Wallpaper is a Service, not an Activity. This is limited by the fact that we have only one Surface, which is created by the class WallpaperService.Engine (I may be wrong). Also we can't use any View objects.
Desired wallpaper result:

*

*Play background video (WebM preferred)

*To have a possibility to transform video (scale, translate)

*Draw simple foreground graphics

Questions
Now I have some ideas to implement this, but I don't know if it is possible:

*

*Is there a possible way to transform Surface's content? (exactly Surface, not a SurfaceView)

*Is it possible to create an additional Surface and then draw both Surfaces one above the other like a second layer? (maybe SurfaceFlinger does that?)

*Is it possible to use MediaCodec (which I'll have to study) to decode video and draw it frame-by-frame in draw() method using lock/unlock canvas and draw simple graphics there?

*Is it possible to have a SurfaceView but don't attach it to window? I tried it and got "surface has been released" Exception. How can I attach it in my case? As I understand it must to be attached to a window. But I don't have a window.

Now my code can only draw video OR draw graphics, and I'm almost sure that I need to replace the MediaPlayer for something else:
package com.android.grafika;

import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Handler;
import android.service.wallpaper.WallpaperService;
import android.util.Log;
import android.view.SurfaceHolder;

import java.io.IOException;

import static java.lang.Math.PI;
import static java.lang.Math.cos;

public class MyWallpaperService extends WallpaperService{

    @Override
    public Engine onCreateEngine() {
        return new MyEngine();
    }

    class MyEngine extends WallpaperService.Engine implements MediaPlayer.OnPreparedListener{

        private MediaPlayer player = null;
        private SurfaceHolder holder;
        private Handler handler = new Handler();
        private boolean visible = false;
        private Paint paint = new Paint();
        private int counter = 0;
        private int frameDelay = 30;
        private int rawVideoId = R.raw.mage_1sec;
        private Runnable drawFrame = new Runnable()
        {
            @Override
            public void run() {
                draw();
                counter++;
                if (visible) {
                    handler.postDelayed(this, frameDelay);
                }
            }
        };

        @Override
        public void onCreate(SurfaceHolder surfaceHolder) {
            super.onCreate(surfaceHolder);
            this.holder = surfaceHolder;
        }

        @Override
        public void onVisibilityChanged(boolean visible) {
            super.onVisibilityChanged(visible);
            this.visible = visible;
            if (visible) {
                handler.post(drawFrame);
                //playerStart();    // uncomment it and comment the statement above to draw the video
            } else {
                handler.removeCallbacks(drawFrame);
                //playerRelease();  // uncomment it and comment the statement above to draw the video
            }
        }

        private void draw() {
            Canvas canvas = holder.lockCanvas();
            canvas.drawColor(Color.CYAN);
            //mediaDecoder.drawVideoFrame(canvas); // this is my imaginary statement
            canvas.drawCircle(600f, (float) cos( (double) counter /30f * PI) * 200f + 400f, 30f, paint); // simple animation
            holder.unlockCanvasAndPost(canvas);
        }

        /**
         * MediaPlayer implementation
         */
        private void playerRelease() {
            player.release();
            player = null;
        }

        private void playerStart() {
            try {
                player = new MediaPlayer();
                player.setLooping(true);
                player.setSurface(holder.getSurface());
                player.setDataSource(getApplicationContext(), Uri.parse("android.resource://" + getPackageName() + "/" + rawVideoId));
                player.setOnPreparedListener(this);
                player.prepare();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onPrepared(MediaPlayer mediaPlayer) {
            player.start();
        }
    }
}

I'll be glad to any help: references, samples, advices or libs. Maybe I'm not doing everything right and you can say it to me.
Thank you for any help!


text:
Q: Java AsyncHttpClient: broken file while writing from LazyResponseBodyPart to AsynchronousFileChannel I use AsyncHttpClient library for async non blocking requests.
My case: write data to a file as it is received over the network.
For download file from remote host and save to file I used default ResponseBodyPartFactory.EAGER and AsynchronousFileChannel so as not to block the netty thread as data arrives. But as my measurements showed, in comparison with LAZY the memory consumption in the Java heap increases many times over.
So I decided to go straight to LAZY, but did not consider the consequences for the files.
This code will help to reproduce the problem.:
public static class AsyncChannelWriter {
     private final CompletableFuture<Integer> startPosition;
     private final AsynchronousFileChannel channel;

     public AsyncChannelWriter(AsynchronousFileChannel channel) throws IOException {
         this.channel = channel;
         this.startPosition = CompletableFuture.completedFuture((int) channel.size());
     }

     public CompletableFuture<Integer> getStartPosition() {
         return startPosition;
     }

     public CompletableFuture<Integer> write(ByteBuffer byteBuffer, CompletableFuture<Integer> currentPosition) {

         return currentPosition.thenCompose(position -> {
             CompletableFuture<Integer> writenBytes = new CompletableFuture<>();
             channel.write(byteBuffer, position, null, new CompletionHandler<Integer, ByteBuffer>() {
                 @Override
                 public void completed(Integer result, ByteBuffer attachment) {
                     writenBytes.complete(result);
                 }

                 @Override
                 public void failed(Throwable exc, ByteBuffer attachment) {
                     writenBytes.completeExceptionally(exc);
                 }
             });
             return writenBytes.thenApply(writenBytesLength -> writenBytesLength + position);
         });
     }

     public void close(CompletableFuture<Integer> currentPosition) {
         currentPosition.whenComplete((position, throwable) -> IOUtils.closeQuietly(channel));
     }
 }

 public static void main(String[] args) throws IOException {
     final String filepath = "/media/veracrypt4/files/1.jpg";
     final String downloadUrl = "https://m0.cl/t/butterfly-3000.jpg";

     final AsyncHttpClient client = Dsl.asyncHttpClient(Dsl.config().setFollowRedirect(true)
             .setResponseBodyPartFactory(AsyncHttpClientConfig.ResponseBodyPartFactory.LAZY));
     final AsynchronousFileChannel channel = AsynchronousFileChannel.open(Paths.get(filepath), StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.CREATE);
     final AsyncChannelWriter asyncChannelWriter = new AsyncChannelWriter(channel);
     final AtomicReference<CompletableFuture<Integer>> atomicReferencePosition = new AtomicReference<>(asyncChannelWriter.getStartPosition());
     client.prepareGet(downloadUrl)
             .execute(new AsyncCompletionHandler<Response>() {

                 @Override
                 public State onBodyPartReceived(HttpResponseBodyPart content) throws Exception {
//if EAGER, content.getBodyByteBuffer() return HeapByteBuffer, if LAZY, return DirectByteBuffer
                     final ByteBuffer bodyByteBuffer = content.getBodyByteBuffer();
                     final CompletableFuture<Integer> currentPosition = atomicReferencePosition.get();
                     final CompletableFuture<Integer> newPosition = asyncChannelWriter.write(bodyByteBuffer, currentPosition);
                     atomicReferencePosition.set(newPosition);
                     return State.CONTINUE;
                 }

                 @Override
                 public Response onCompleted(Response response) {
                     asyncChannelWriter.close(atomicReferencePosition.get());
                     return response;
                 }
             });
}

in this case, the picture is broken. But if i use FileChannel instead of AsynchronousFileChannel, in both cases, the files come out normal. Can there be any nuances when working with DirectByteBuffer (in case withLazyResponseBodyPart.getBodyByteBuffer()) and AsynchronousFileChannel?
What could be wrong with my code, if everything works fine with EAGER?

UPDATE
As I noticed, if I use LAZY, and for example,i add the line
 Thread.sleep (10) in the method onBodyPartReceived, like this:
 @Override
public State onBodyPartReceived(HttpResponseBodyPart content) throws Exception {
    final ByteBuffer bodyByteBuffer = content.getBodyByteBuffer();
    final CompletableFuture<Integer> currentPosition = atomicReferencePosition.get();
    final CompletableFuture<Integer> newPosition = finalAsyncChannelWriter.write(bodyByteBuffer, currentPosition);
    atomicReferencePosition.set(newPosition);
    Thread.sleep(10);
    return State.CONTINUE;
}

The file is saved to disk in non broken state.
As I understand it, the reason is that during these 10 milliseconds, the asynchronous thread in AsynchronousFileChannel manages to write data to the disk from this DirectByteBuffer.
It turns out that the file is broken due to the fact that this asynchronous thread uses this buffer for writing along with the netty thread.
If we take a look at source code with EagerResponseBodyPart, then we will see the following
private final byte[] bytes;
  public EagerResponseBodyPart(ByteBuf buf, boolean last) {
    super(last);
    bytes = byteBuf2Bytes(buf);
  }

  @Override
  public ByteBuffer getBodyByteBuffer() {
    return ByteBuffer.wrap(bytes);
  }

Thus, when a piece of data arrives, it is immediately stored in the byte array. Then we can safely wrap them in HeapByteBuffer and transfer to the asynchronous thread in file channel.
But if you look at the code LazyResponseBodyPart
  private final ByteBuf buf;

  public LazyResponseBodyPart(ByteBuf buf, boolean last) {
    super(last);
    this.buf = buf;
  }
  @Override
  public ByteBuffer getBodyByteBuffer() {
    return buf.nioBuffer();
  }

As you can see, we actually use in asynchronous file channel thread netty ByteBuff(in this case always PooledSlicedByteBuf) via method call nioBuffer
What can i do in this situation, how to safely pass DirectByteBuffer in an async thread without copying buffer to java heap?

A: I talked to the maintainer of AsyncHttpClient.
Can see here
The main problem was that i dont's use netty ByteBuf methods retain and release.
In the end, I came to two solutions.
First: Write the bytes in sequence to the file with tracking position with CompletableFuture.
Define wrapper class for AsynchronousFileChannel
@Log4j2
public class AsyncChannelNettyByteBufWriter implements Closeable {
    private final AtomicReference<CompletableFuture<Long>> positionReference;
    private final AsynchronousFileChannel channel;

    public AsyncChannelNettyByteBufWriter(AsynchronousFileChannel channel) {
        this.channel = channel;
        try {
            this.positionReference = new AtomicReference<>(CompletableFuture.completedFuture(channel.size()));
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        }
    }

    public CompletableFuture<Long> write(ByteBuf byteBuffer) {
        final ByteBuf byteBuf = byteBuffer.retain();
        return positionReference.updateAndGet(x -> x.thenCompose(position -> {
            final CompletableFuture<Integer> writenBytes = new CompletableFuture<>();
            channel.write(byteBuf.nioBuffer(), position, byteBuf, new CompletionHandler<Integer, ByteBuf>() {
                @Override
                public void completed(Integer result, ByteBuf attachment) {
                    attachment.release();
                    writenBytes.complete(result);
                }

                @Override
                public void failed(Throwable exc, ByteBuf attachment) {
                    attachment.release();
                    log.error(exc);
                    writenBytes.completeExceptionally(exc);
                }
            });
            return writenBytes.thenApply(writenBytesLength -> writenBytesLength + position);
        }));
    }

    public void close() {
        positionReference.updateAndGet(x -> x.whenComplete((position, throwable) -> {
            try {
                channel.close();
            } catch (IOException e) {
                throw new UncheckedIOException(e);
            }
        }));
    }
}

In fact, there probably won't be an AtomicReference here, if the recording happens in one thread, and if from several, then we need to seriously approach synchronization.
And main usage.
public static void main(String[] args) throws IOException {
    final String filepath = "1.jpg";
    final String downloadUrl = "https://m0.cl/t/butterfly-3000.jpg";
    final AsyncHttpClient client = Dsl.asyncHttpClient(Dsl.config().setFollowRedirect(true)
            .setResponseBodyPartFactory(AsyncHttpClientConfig.ResponseBodyPartFactory.LAZY));
    final AsynchronousFileChannel channel = AsynchronousFileChannel.open(Paths.get(filepath), StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.CREATE);
    final AsyncChannelNettyByteBufWriter asyncChannelNettyByteBufWriter = new AsyncChannelNettyByteBufWriter(channel);

    client.prepareGet(downloadUrl)
            .execute(new AsyncCompletionHandler<Response>() {
                @Override
                public State onBodyPartReceived(HttpResponseBodyPart content) {
                    final ByteBuf byteBuf = ((LazyResponseBodyPart) content).getBuf();
                    asyncChannelNettyByteBufWriter.write(byteBuf);
                    return State.CONTINUE;
                }

                @Override
                public Response onCompleted(Response response) {
                    asyncChannelNettyByteBufWriter.close();
                    return response;
                }
            });
}

The second solution: track the position based on the received size of bytes.
public static void main(String[] args) throws IOException {
    final String filepath = "1.jpg";
    final String downloadUrl = "https://m0.cl/t/butterfly-3000.jpg";
    final AsyncHttpClient client = Dsl.asyncHttpClient(Dsl.config().setFollowRedirect(true)
            .setResponseBodyPartFactory(AsyncHttpClientConfig.ResponseBodyPartFactory.LAZY));
    final ExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() * 2);
    final AsynchronousFileChannel channel = AsynchronousFileChannel.open(Paths.get(filepath), new HashSet<>(Arrays.asList(StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.CREATE)), executorService);

    client.prepareGet(downloadUrl)
            .execute(new AsyncCompletionHandler<Response>() {

                private long position = 0;
                @Override
                public State onBodyPartReceived(HttpResponseBodyPart content) {
                    final ByteBuf byteBuf = ((LazyResponseBodyPart) content).getBuf().retain();
                    long currentPosition = position;
                    position+=byteBuf.readableBytes();
                    channel.write(byteBuf.nioBuffer(), currentPosition, byteBuf, new CompletionHandler<Integer, ByteBuf>() {
                        @Override
                        public void completed(Integer result, ByteBuf attachment) {
                            attachment.release();
                            if(content.isLast()){
                                try {
                                    channel.close();
                                } catch (IOException e) {
                                    throw new UncheckedIOException(e);
                                }
                            }
                        }

                        @Override
                        public void failed(Throwable exc, ByteBuf attachment) {
                            attachment.release();
                            try {
                                channel.close();
                            } catch (IOException e) {
                                throw new UncheckedIOException(e);
                            }
                        }
                    });
                    return State.CONTINUE;
                }
                @Override
                public Response onCompleted(Response response) {
                    return response;
                }
            });
}

In the second solution, because we don't wait until some bytes are written to the file, AsynchronousFileChannel can create a lot of threads (If you use Linux, because Linux does not implement non-blocking asynchronous file IO. In Windows, the situation is much better).
As my measurements showed, in the case of writing to a slow USB flash, the number of threads can reach tens of thousands, so for this you need to limit the number of threads by creating your ExecutorService and transferring it to AsynchronousFileChannel.
Are there obvious advantages and disadvantages of the first and second solutions? It's hard for me to say. Maybe someone can tell what is more effective.


text:
Q: Split array in groups of n, m, o groups or more Is there any method to split an array like this?
[1, 2, 3, 4, 5, 6, 7, 8, 9].split(3, 4, 2)
#=> [[1, 2, 3],[4, 5, 6, 7],[8, 9]]

A: Immutable version with λ:
▶ splitter = ->(array, *parts) do
    parts.reduce([[], 0]) do |acc, i|
      right = acc.last + i
      [acc.first << (acc.last...right), right]
    end.first.map { |r| array[r] }
  end
#⇒ #<Proc:0x0055ae3d9ae7c8@(pry):18 (lambda)>
▶ splitter.((1..9).to_a, 3, 4, 2)
#⇒ [[1, 2, 3], [4, 5, 6, 7], [8, 9]]

A: No, there is none, but you can easily write one yourself.
class Array
  def in_groups_of_n(*sizes)
   sizes.map(&method(:shift))
  end
end

Example:
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
arr.in_groups_of_n(3, 4, 2)
# => [[1, 2, 3], [4, 5, 6, 7], [8, 9]]

Demonstration
In case you want a none-destructive version, you can use a dup method:
class Array
  def in_groups_of_n(*sizes)
   duplicate = dup
   sizes.map { |size| duplicate.shift(size) }
  end
end

arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
arr.in_groups_of_n(3,4,2)
# => [[1, 2, 3], [4, 5, 6, 7], [8, 9]
arr
# => [1, 2, 3, 4, 5, 6, 7, 8, 9]

Demonstration

A: Here's a naive Array implementation:
class Array
  def multi_split(*sizes)
    r = []
    e = self.each
    sizes.each do |size|
      t = []
      size.times do
        t << e.next
      end
      r << t
    end
    r
  end
end

p [1, 2, 3, 4, 5, 6, 7, 8, 9].multi_split(3, 4, 2)
# [[1, 2, 3], [4, 5, 6, 7], [8, 9]]

@Stefan mentioned it might make sense to implement it on Enumerable:
module Enumerable
  def multi_split(*sizes)
    Enumerator.new do |yielder|
      e = self.each
      sizes.each do |size|
        yielder << Array.new(size){ e.next }
      end
    end
  end
end

p [1, 2, 3, 4, 5, 6, 7, 8, 9].multi_split(3, 4, 2).to_a
# [[1, 2, 3], [4, 5, 6, 7], [8, 9]]

A: Another option (lossless in event the splits are not equal to the array size
def split_at(arr,splits)
  rest = arr.last(arr.size - splits.reduce(:+))
  enum = arr.to_enum
  splits.map do |n|
    n.times.map { enum.next }
  end.concat(rest.empty? ? [] : [rest])
end

Then called as
split_at (1..9), [3,4,2]
#=> [[1, 2, 3], [4, 5, 6, 7], [8, 9]]
split_at (1..22), [3,4,2]
#=> [[1, 2, 3], [4, 5, 6, 7], [8, 9], [10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22]]

Example

A: class Array
  def split_by_number(*sizes)
    sizes.each_with_object([]) { |n,a| a << [a.empty? ? 0 : a.last.sum, n] }.
          map { |start, nbr| self[start, nbr] }
  end
end

[1, 2, 3, 4, 5, 6, 7, 8, 9].split_by_number 3, 4, 2
  #=> [[1, 2, 3], [4, 5, 6, 7], [8, 9]]

Note that
[3, 4, 2].each_with_object([]) { |n,a| a << [a.empty? ? 0 : a.last.sum, n] }
  #=> [[0, 3], [3, 4], [7, 2]]


text:
Q: Error "Root element is missing" y "Unavaiable project" en Windows Forms C# El día de hoy me ocurrió un error, entré al visual studio, entre a mi aplicación y me mostró un error, no quería cargar el proyecto, me muestra una ventana la cual dice

The project file could not be loaded. Root element is missing

y a continuación una dirección del archivo,

C:\Users\M\source\repos\WindowsFormsApp2\WinfowsFormsApp2\ProjectReminders.csproj

Supongo que como dice, el archivo podría no estar en el lugar correcto, ya lo coloqué en la anterior dirección y sigue, también intenté borrar el proyecto de la solución e intentar de nuevo, pero sigue, nada.
ACTUALIZACIÓN:
Me di cuenta de que al ejecutarlo y salir error, se guardaron unos archivos y se duplicaban con cada error.
Esto Decían:

Migration Report
Overview
Project Path Errors Warnings Messages
ProjectR C:... 1    0        0
ProjectR
Message
Projectr.csproj : Error on line 1.Expected "<" but found null character


text:
Q: Flash click event If I plan to implement 100 objects on stage to be listen to mouse and keyboard input, is using "function" call responsive enough? How good does eventlistner work?

A: Yes, it's responsive enough but it also depends on what your function will be doing. As an extreme example if each function triggers some heavy computation then you may find it's not responsive anymore.
Furthermore , just don't take my word for it. If speed is a concern, you can easily setup a few tests.

A: I'm not sure I understand the question completely - like wtf is a "Function" call (is it a callback?) - but I do think you could potentially lower some overhead by setting up one listener for all your 100 stage objects, as opposed to an anonymous (inline in the listener) version for each one. That kind of thing happens more often than one might think in Actionscript.
Also, PatrickS hit the nail on the head about setting up simple tests. Here's the easiest way
http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/utils/package.html?filter_flex=4.1&filter_flashplayer=10.1&filter_air=2#getTimer()
That method gives you the number of milliseconds that've elapsed since the swf's started running. Grab it's value before your test, run your test, the grab the value after and figure out the difference. That's how long it took your function to run. If you are weighing the benefits vs. costs of one approach against another's, then set up two tests and see which is faster.


text:
Q: Pointer to 2D array in C I am trying to make a sudoku solver in C.
I have tried to make a function to solve the sudoku and then return the grid.
void solve(int *grid){
    //solve sudoku
}

int main(){
    int[][] grid = {
        {5,3,0,0,7,0,0,0,0},
        {6,0,0,1,9,5,0,0,0},
        {0,9,8,0,0,0,0,6,0},
        {8,0,0,0,6,0,0,0,3},
        {4,0,0,8,0,3,0,0,1},
        {7,0,0,0,2,0,0,0,6},
        {0,6,0,0,0,0,2,8,0},
        {0,0,0,4,1,9,0,0,5},
        {0,0,0,0,8,0,0,7,9}
    };
solve(&grid);
}

This does not seem to work.
It needs to take a pointer because it should edit the array not a copy
Why is this?

A: First of all this declaration of an array
int[][] grid = {
    {5,3,0,0,7,0,0,0,0},
    {6,0,0,1,9,5,0,0,0},
    {0,9,8,0,0,0,0,6,0},
    {8,0,0,0,6,0,0,0,3},
    {4,0,0,8,0,3,0,0,1},
    {7,0,0,0,2,0,0,0,6},
    {0,6,0,0,0,0,2,8,0},
    {0,0,0,4,1,9,0,0,5},
    {0,0,0,0,8,0,0,7,9}
};

is wrong. You have to use square brakets after the identifier and specify at least the number of elements in the inner dimension.
#define N 9

//...
int grid[][N]  = {
    {5,3,0,0,7,0,0,0,0},
    {6,0,0,1,9,5,0,0,0},
    {0,9,8,0,0,0,0,6,0},
    {8,0,0,0,6,0,0,0,3},
    {4,0,0,8,0,3,0,0,1},
    {7,0,0,0,2,0,0,0,6},
    {0,6,0,0,0,0,2,8,0},
    {0,0,0,4,1,9,0,0,5},
    {0,0,0,0,8,0,0,7,9}
};

If you want to pass the array to a function then the function can be declared like
void solve( int ( *grid )[N], size_t n );

and called like
solve( grid, N );

Take into account that arrays do not have the copy assignment operator and you may not assign an array identifier with a pointer.


text:
Q: Firebase Update If Exists I am trying to create an update function within firestore using the .update() method.
Here is the example of the function i'm running:
db.collection('Users').doc(offeruserid).update({
  overrideTag: process.env.A_ULTRA_SECRET_KEY,
  userExperience: firebase.firestore.FieldValue.increment(Number(offerrate))
})

Now what I actually want to happen, is it look in the document and see if the field "overrideTag" is there. If it IS NOT there, it WILL NOT update it and just forget about it.
Also, I wish to do this without first getting the data, seeing if it exists, then creating a update function separately - I know it can be done that way.
Is this something that we can do within firebase?

A: There is no way of doing this without first reading the document.  Usually people do check-and-set operations like this in a transaction, but you should be aware that transactions do read the document first before writing it.

A: You can do this in security rules, by checking for the presence of your super-secret value in the overrideTag field.
service cloud.firestore {
  match /databases/{database}/documents {
    match /Users/{user} {
      allow update: if request.resource.data.overrideTag == "YOUR_SUPER_SECRET_VALUE";
    }
  }
}

You could also store all super-secret values somewhere in the database, and then check for their existence with an exists call.
if exists(/databases/$(database)/documents/secrets/$(request.resource.data.overrideTag))

The latter will be a charged (so possibly paid) read operation, but you won't need to read the data in your application code.


text:
Q: Export ms-office file with markups to pdf via pdftron MS Office has functionality to add markups and comments into document. This functionality is shown on the following picture

The MS Office has option to generate PDF file from office file with markup, as a result pdf file will contain markups, comments etc.

I need to generate PDF file from office file on server machine but in my case I can not install MS Office on server machine to use Office API. I tried to use PDFTron to generate PDF file from office file but PDFTron does not export markups from office file to PDF file. How can I solve it?
What can I use to generated PDF file with markups if PDFTron does not support exporting markups in PDF file?


text:
Q: Can I load my existing village in clash of clans to a new Gmail account on the same device? I'm playing Clash of Clans on my device. I had linked it to my Gmail account in the beginning. Because of storage issues, I disabled my Google Play. But I proceeded with the game.
Now when I try signing in using my Gmail account, it asks whether to replace the existing present village with the one that had been saved before disabling Google Play. Is there a way to load my existing village into it? Or is there a way to load my existing village to a new Gmail account on the same device?

A: In my experience, if you connected your village to your Gmail account, it "sticks" to it. Meaning the village is no longer attached to the phone, but to your Gmail account.
This is what allows people to cross device villages. For example, I currently have my main village on both my phone and my tablet. However, I have found that you can have more than one village on a device. Just go to your settings, and change your primary email address. Word of caution, if you have yet to connect it to your Gmail account, and you decide you want to use your other village for a minute, the first village will go bye-bye.


text:
Q: VBA Conditional Format if both conditions met Conditional Format Code is working for each condition individually, but not if both are conditions are met. If both Conditions are met the only issue is column L doesn't highlight yellow:
Dim Cond1 As FormatCondition, cond2 As FormatCondition
Set Cond1 = Range("L" & bot_row).FormatConditions.Add(xlExpression, xlEqual,EmployeeInformation.ChiResident.Value = True)
Set cond2 = Range("L" & bot_row & ":AB" & bot_row).FormatConditions.Add(xlExpression, x1equal, EmployeeInformation.Apprentice.Value = True)
With Cond1
.Font.Color = vbRed
.Font.Bold = True
End With
With cond2
.Interior.Color = vbYellow
End With

I have tried a few ways to get this to work if both conditions are met.  Basically do the same thing but highlight whole range in yellow and have bold red text in column L.
Attempt 1:
  With Cond1 And Cond2
Range("L" & bot_row).Font.Color = vbRed And .Font.Bold = True And .Interior.Color = vbYellow
Range("M" & bot_row & ":AB" & bot_row).Interior.Color = vbYellow
End With

Attempt 2:
If Cond1 And Cond2 = True Then
Range("L" & bot_row).Font.Color = vbRed
Range("L" & bot_row).Font.Bold = True
Range("L" & bot_row).Interior.Color = vbYellow
Range("M" & bot_row & ":AB" & bot_row).Interior.Color = vbYellow
End If

Attempt 3:
Dim Cond1 As FormatCondition, Cond2 As FormatCondition, Cond3 As FormatCondition
Set Cond1 = Range("L" & bot_row).FormatConditions.Add(xlExpression, xlEqual, EmployeeInformation.ChiResident.Value = True)
Set Cond2 = Range("L" & bot_row & ":AB" & bot_row).FormatConditions.Add(xlExpression, x1equal, EmployeeInformation.Apprentice.Value = True)
Set Cond3 = Range("L" & bot_row).FormatConditions.Add(xlExpression, xlEqual, EmployeeInformation.ChiResident.Value = True) And Range("M" & bot_row & ":AB" & bot_row).FormatConditions.Add(xlExpression, x1equal, EmployeeInformation.Apprentice.Value = True)
With Cond1
.Font.Color = vbRed
.Font.Bold = True
End With
With Cond2
.Interior.Color = vbYellow
End With
With Cond3
Range("L" & bot_row).Font.Color = vbRed
Range("L" & bot_row).Font.Bold = True
Range("L" & bot_row).Interior.Color = vbYellow
Range("M" & bot_row & ":AB" & bot_row).Interior.Color = vbYellow
End With

A: This does not answer the question of the author entirely, as some information is missing, but it shows a way of working in order to solve the issue.
I would advise you to check the conditional formatting rules, as your VBA macro has created them. And even then, you might be faced with a bug, like in my case:
In order to check how conditional formatting works with different rules, I have created conditional formatting with two rules, who are both correct (the value of "B2" equals 5, and I use the formulas =B2>1 and =B2<8. Nevertheless the second rule never gets applied, which look like a bug, as you can see here:

(Although the checkbox "Stop if True" is not clicked, it looks like the conditional formatting stops after the first rule.)
So: check your rules, using the Conditional Formatting Rules Manager, and only if this is not clear, you can suspect a bug in the conditional formatting feature.


text:
Q: How to convert my enumeration code into a switch In my CustomerTypeApp class, I need to change the getDiscountPercent method to use a switch instead of a chain of if statements. Here is the if statement version:
public static double getDiscountPercent(CustomerType ct) {
        double discountPercent = 0;
        if (ct == CustomerType.RETAIL) {
            discountPercent = 0.156;
        } else if (ct == CustomerType.TRADE) {
            discountPercent = 0.30;
        } else if (ct == CustomerType.COLLEGE) {
            discountPercent = 0.20;
        }
        return discountPercent;
    }
}

Below is the switch statement I have tried, but which receives the error:

An enum switch case label must be the unqualified name of an enumeration constant

  double discountPercent = 0;

  switch(ct) {
      case CustomerType.RETAIL :
        discountPercent = 0.156;
        break;
     case CustomerType.TRADE :
        discountPercent = 0.30;
        break;
     case CustomerType.COLLEGE :
        discountPercent = 0.20;
        break;
     default :
        discountPercent = 0;
  }
  return discountPercent;

A: You want to switch for the variable ct
switch(ct) {
        case CustomeType.retail:
            /*Command*/
            break;
        case CustomerType.TRADE:
            /*Command*/
            break;
        default:
            /*else*/
}

If you need further help read these Java Docs

A: Try this:
(It's Very Simple)
public static double getDiscountPercent(CustomerType ct) {

      double discountPercent = 0;

      switch(ct) {
         case CustomerType.RETAIL :
            discountPercent = 0.156;
            break;
         case CustomerType.TRADE :
            discountPercent = 0.30;
            break;
         case CustomerType.COLLEGE :
            discountPercent = 0.20;
            break;
         default :
            discountPercent = 0;
      }
      return discountPercent;

   }


text:
Q: Laravel - Method App\Http\Controllers\MsisdnController::export does not exist I am trying to export to Excel in Laravel 5.8 using

"maatwebsite/excel": "^3.1"

but I got this error:

Method App\Http\Controllers\MsisdnController::export does not exist.

Exports
namespace App\Exports;

use App\User;
use Maatwebsite\Excel\Concerns\FromCollection;

class MsisdnExport implements FromCollection
{
    /**
    * @return \Illuminate\Support\Collection
    */
    public function collection()
    {
        return User::all();
    }
}

MsisdnController
use App\Exports\MsisdnExport;
use Maatwebsite\Excel\Facades\Excel;

class MsisdnController extends Controller
{

    public function msisdnexport()
    {
        return Excel::download(new MsisdnExport, 'msisdn.xlsx');
    }
}

Sidebar Nav

List of MSISDNs

route
Route::get('msisdnexport', 'MsisdnController@export')->name('msisdnexport');

View

            {{ Form::submit('Search',['class'=>'btn btn-warning']) }}
             Excel

        @foreach($msisdns as $key => $msisdn)

                {{ ++$key }}
                {{ $msisdn->phone }}

        @endforeach

When I click on Excel Button, I expect it to export to Excel. But I got the error above.

A: Your route definition:
Route::get('msisdnexport', 'MsisdnController@export');

references a function export that doesn't exist. Your function is named msisdnexport in your controller.


text:
Q: Can I customize geddy scaffold templates? Are geddy scaffold templates customizable? i.e Can I override standard view templates to add things on my own or change the way cruds are displayed?

A: We have an issue going for this feature request here: https://github.com/mde/geddy/issues/526


text:
Q: Bootstrap navbar button not working on mobile or any devices My navbar is not functioning properly on mobile devices the button is doing nothing at all.
Originally there was no button or navigation however I've placed the button within the navbar.
This doesnt seem to be doing anything and I have probably just not spotted the simplest mistake.
Any help? Thank you in advance.

      <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="defaultNavbar1" aria-controls="defaultNavbar1" aria-expanded="false" aria-label="Toggle navigation">

  </button>

Home

Info

Staff Team

Quests

Latest News

        <?php if ($session->logged_in) { ?>
            <?php if ($session->isAdmin()) { ?>

AdminCP

            <?php } ?>

                <?php echo $session->username ?>

                  <a class="dropdown-item" href="/profile?user=<?php echo $session->username; ?>">Profile
                  Account settings
                  Log out »

    <?php } else { ?>

Log in

Register

        <?php } ?>

A: You need to add the hash to your data-target like so:
data-target="#defaultNavbar1"


text:
Q: Deleting non matching records from a table prior to linking I have two tables in a new database containing data migrated from an old database.  These two tables need to be linked, but prior to that I need to remove those records that don't have matching id's.
The two tables in question are illustrated below;

I need to eradicate those rows in the landingDetails table that do not have corresponding landing headers in the landingHeaders table.  Can anyone suggest the correct form that a sql statement to carry this out should take.
By way of additional info.  When this is achieved it is my intention to link landing details to landing headers.  Currently there are approximately 107,000 rows in landing details and approxametly 8,500 rows in landing headers.
Thanks for any suggestions that you have.

A: The first major step is to backup your database :)
And give a try this query,
DELETE FROM LandingDetails WHERE LandingId NOT IN (SELECT LandingId FROM LandingHeaders)


text:
Q: Substituir uso de dataframe com pandas .apply Eu possuo uma função que itera uma planilha, que faz alguns controles. Procurei sobre e vi sobre o .apply, mas não consegui implentar. Gostaria de saber se conseguiria nesse caso, substituir o uso que faço e por questão de performance, alterar para o .apply.
No caso, possuo um dicionário que ele consulta para minhas condições tratadas. E a função que itera fazendo um laço pra que isso ocorra. A função depende do cargo que eu passo no dicionário e que vem da planilha para saber se exibe um campo de foto ou não.
    for i, row in df.iterrows():
        if row['cargo'] in cargos_to_display_photo:
            df.loc[i, 'display_foto'] = True
        else:
            df.loc[i, 'display_foto'] = False
    return df

a função que "prepara" o data frame é:
def prepare_dataframe(df_google):
    df_google = set_display_photo(df_google)
    return df_google

o dicionário:
cargos_to_display_photo = [
    'Trainee | Assessoria de Investimentos',
    'Sócio Fundador',
    'Superintendente',
    'Assessor de Investimentos',
    'Sócia | Assessor de Investimentos',
    'Líder Corporate',
    'Trainee | Corporate',
]

a coluna que consulto:
columns_dict = {
    'SEXO' : 'sexo',
    'CÓDIGO' : 'codigo',
    'Nome Completo' : 'nome',
    'Cidade' : 'unidade',
    'Cargo' : 'cargo',
}

As colunas que não efetuo consulta ou que não foram citadas no trecho eu descarto pelo próprio código, dando um drop nelas com as tratativas necessárias pra que não precise iterar.
das formas que pesquisei, não consegui implentar nenhuma. Não consegui fazer com que o apply populasse a planilha. Seria possível fazer isso com essas funções?

A:
Procurei sobre e vi sobre o .apply, mas não consegui implementar. Gostaria de saber se conseguiria nesse caso, substituir o uso que faço e por questão de performance, alterar para o .apply.

Importando o arquivo:
import pandas as pd

df = pd.read_excel('./Cadastro Colaboradores BT.xlsx')

Lista com os cargos:
cargos_to_display_photo = [ 'Trainee | Assessoria de Investimentos',
                           'Sócio Fundador', 'Superintendente',
                           'Assessor de Investimentos',
                           'Sócia | Assessor de Investimentos',
                           'Líder Corporate', 'Trainee | Corporate', ]

Código com o apply:
df['display_foto'] = df['Cargo'].apply(lambda x: x in cargos_to_display_photo)

Crio uma coluna chamada display_foto, aplico o apply na coluna Cargo do dataframe e faço uma função anonima que verifica se o conteúdo da coluna linha a linha.

*

*Tempo de execução com o laço for:
69.4 ms ± 1.52 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

*Tempo de execução com apply:
305 µs ± 30.8 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

A: Uma forma de fazer isso seria usando a função .isin() do pandas. Ela retorna uma lista booleana quando encontra algum valor dentro do array cargos_to_display_photo
df['display_foto'] = df['Cargo'].isin(cargos_to_display_photo)
df.head()
    SEXO    CÓDIGO  Nome completo   Cidade      Cargo       display_foto
0   m       NaN     Samuel...       Ribeir...   Sócio ...   False
1   m       NaN     Leonar...       Uberlâ...   Assess...   True
2   m       NaN     Andre ...       Franca      Sócio ...   False
3   f       NaN     Rejane...       Uberlâ...   Assess...   False
4   m       NaN     Wevers...       Rio de...   Traine...   True

Uma boa prática para se obter desempenho(velocidade) nas execuções em pandas é evitar usar loops de repetição, assim como a função apply (que também é um tipo de iteração).
Segue o tempo de execução da minha proposta:

220 µs ± 5.93 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)


text:
Q: Is it still possible to use sun.misc.Unsafe in Java 9? Until Java 8 it was possible to obtain the singleton sun.misc.Unsafe instance via a method like the following:
public static Unsafe getUnsafe() {
    try {
        Field f = Unsafe.class.getDeclaredField("theUnsafe");
        f.setAccessible(true);
        return (Unsafe) f.get(null);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

Even though it was highly suggested not to use Unsafe, many vendors and libraries use it internally.
Now, with Java 9 and Jigsaw, I think that also the way Unsafe is handled has changed. I read some posts with contrary information. Some say it has been completely hidden and it is not even retrievable, others say one has to enable a VM flag, while others write that it should be officially support now.
So: Is it possible to still use sun.misc.Unsafe in Java 9, and if so, how?

A: Not only has it remained the same obtaining it, but they also added more methods to it. The thing is this is now a promise that it will be removed some time in the future; this time for sure.
Also there are two of them now, one : sun.misc.Unsafe and jdk.internal.misc.Unsafe. The first one is the one to be removed btw.
The second one can be obtained also in java-9, but only with the special key addExports:java.base/jdk.internal.misc=ALL-UNAMED (but this is highly discouraged).
What has changed is the fact that lots of public methods that were either patched or added so that you do not need to use it anymore, like AtomicInteger#weakCompareAndSet for example that was not doing what you would expect.


text:
Q: Collapse text by group in data frame How do I aggregate data frame by group in column group and collapse text in column text?
Sample data:
df <- read.table(header=T, text="
group text
a a1
a a2
a a3
b b1
b b2
c c1
c c2
c c3
")

Required output (data frame):
group text
a     a1a2a3
b     b1b2
c     c1c2c3

Now I have:
sapply(unique(df$group), function(x) {
  paste0(df[df$group==x,"text"], collapse='')
})

This works to some extent as it returns text properly collapsed by group, but as a vector:
[1] "a1a2a3" "b1b2"   "c1c2c3"

I need a data frame with group column as a result.

A: Simply use aggregate :
aggregate(df$text, list(df$group), paste, collapse="")
##   Group.1      x
## 1       a a1a2a3
## 2       b   b1b2
## 3       c c1c2c3

Or with plyr
library(plyr)
ddply(df, .(group), summarize, text=paste(text, collapse=""))
##   group   text
## 1     a a1a2a3
## 2     b   b1b2
## 3     c c1c2c3

ddply is faster than aggregate if you have a large dataset.
EDIT :
With the suggestion from @SeDur :
aggregate(text ~ group, data = df, FUN = paste, collapse = "")
##   group   text
## 1     a a1a2a3
## 2     b   b1b2
## 3     c c1c2c3

For the same result with earlier method you have to do :
aggregate(x=list(text=df$text), by=list(group=df$group), paste, collapse="")

EDIT2 : With data.table :
library("data.table")
dt <- as.data.table(df)
dt[, list(text = paste(text, collapse="")), by = group]
##    group   text
## 1:     a a1a2a3
## 2:     b   b1b2
## 3:     c c1c2c3

A: You can use dplyr package for this
library(dplyr)

df %>%
  group_by(group) %>%
  summarise(text=paste(text,collapse=''))


text:
Q: Reactive Form valueChanges observable resets form value I have a dynamic reactive form. One part is build by binding the FormGroup and FormControl directives in the Html.In addition -there is a click event for adding other values to the form value programmatically.
The problem is that when subscribing to the this.form.valueChanges observable, the callback value (the lambda expression) includes the form value that is being added in the AddToList function, but it is empty, although it had a value before.
The valueChanges is being subscribed whenever I change the value in the select control.
Can't understand why this is happening.
<form *ngIf="form" >

          {{val}}

      <select [id]="col.field" [formControlName]="col.field" >
        <option [value]=''></option>
        <option *ngFor="let sys of col.data" [value]="sys.Code">{{sys.Value}}</option>
      </select>

       <input class="input" [id]="col.field" type="text"  #texttosearch>
       <button class="btnAddList" (click)="AddToList(texttosearch.value,
        col.field, $event)">
       </button>

This is the component needed code:
export class dynamicReactiveFrom
{
    form: FormGroup;
    advanceCols: AdvanceColumnBase<any>[];
    constructor(private fb: FormBuilder) { }

    initAdvancedSearch(arr:AdvanceColumnBase<any>[])
    {
         this.advanceCols = arr;
         let group: any = {};
         arr.forEach(col =>
         if (<some condition for the selected Items>)
         {
            group[col.field] = new FormControl(col.value || '');
         }
         else/*This is for the items which were added using the AddToList function*/
         {
            group[col.field] = this.fb.array([this.fb.control('')]);
         }
         );
         this.form = new FormGroup(group);

         this.form.valueChanges.subscribe(values => {
         /*the value that was set in the AddToList function is now reset, in
         the values callback*/
         doSeomthing(values);
     });
   }

   AddToList(value: string, field: string, event)
   {
       event.preventDefault();
       let selectedField = this.advanceCols.find( x => x.field === field);
       if(selectedField)
       {
         this.form.value[field] = item.dataList;
       }
   }
 }

The initAdvancedSearch function triggered from outside of the component and has the needed values to populate the form.

A: Found where the problem was - I was missing the FormArrayName directive in the ul where the items were added:

    <ul [formArrayName] = "col.<property with unique value - name or ID>">

         {{val}}

and instead of doing:
this.form.value[field] = item.dataList;

I'm doing:
this.form.value[field].push(value);

The problem was that the form.value[field] was referenced by the item.dataList, instead of being managed separately.

A: Remove the value changes subscription from initAdvancedSearch method and subscribe to it on the OnInit of the component. First implement the OnInit interface:
export class dynamicReactiveFrom implement OnInit

and then provide an implement of ngOnInint:
public ngOnInit() {
   this.form.valueChanges.subscribe(values => {
         /*the value that was set in the AddToList function is now reset, in
         the values callback*/
         doSeomthing(values);
     });

}


text:
Q: Scheme: 3 numbers in a row, implementation Currently I have a list of elements (1 2 1 2 2 0 0 1 0).
The point of the function I'm trying to write is that it should display a possibility that would show 3 of the same number in a row (which would be a 'winning' case).
The output I would want is (1 2 1 2 2 2 0 1 0).
The function, when called, would be in the format of
(display (next 2 (list)))
I'd assume I'd take the car of the list and if there's a way to store/remember the car I got (in case I call for it again and want to check if it matches).

A: The closest thing to a basic loop is the named let construct. Here's a simple implementation that works for your problem:
(define (next e lst)
  ; l1 : part of the list already processed (reversed)
  ; l2 : part of the list still to be processed
  ; c-2: element before previous
  ; c-1: previous element
  ; res: result (list of winning cases
  (let loop ((l1 null) (l2 lst) (c-2 null) (c-1 null) (res null))
    (if (null? l2)
        (reverse res)
        (let ((ca (car l2)) (cd (cdr l2)))
          (loop (cons ca l1) cd c-1 ca
                (if (and (= ca 0) (= c-2 e) (= c-1 e))
                    (cons (append (reverse l1) (cons c-1 cd)) res) ; build winning case
                    res))))))

then
> (next 2 '(1 2 1 2 2 0 0 1 0))
'((1 2 1 2 2 2 0 1 0))

> (next 2 '(1 2 1 2 2 0 2 2 0))
'((1 2 1 2 2 2 2 2 0) (1 2 1 2 2 0 2 2 2))

> (next 1 '(1 2 1 2 2 0 1 1 0))
'((1 2 1 2 2 0 1 1 1))


text:
Q: Wish to terminate main.exe after execute DLL (C++) I run my main.exe on a mobile device which executes my test.dll. Now after the dll has startet I need to wm_destroy the main.exe for exchange while the dll is still running. I'm pretty new to this field and I see it's against all logic. But maybe there is a way to change the main.exe while dll is running.
Thx in advance!

A: When a DLL is loaded it's linked into the address space of the main executable. It doesn't and isn't supposed to exist independently. DLLs don't "run"/"execute" independently.
What you want to do is not what DLLs for. You probably want to spawn a new, independent process, and from there send the WM_DESTROY to the parent process.

A: What purpose this can even serve? If dll is running by itself, it's an .exe and should have own WinMain, not just DllMain. Actually they have same format, both .dll and .exe are PEXE files and can have exports. It's a bit tricky to get address of exported function from running module that isn't child process, but it's how certain profiler tools work, including VS analyzer.
In Windows there is utility which sole purpose is to run a dll, rundll32, which you can spawn as child process, but it requires elevated rights.


text:
Q: Null list returned from hibernate query with embedded id I have an entity with an embedded key.  The entity has only the key as a field and the key has 7 fields, some of which can be null.
When I run the following query:
Criteria criteria = session.createCriteria(getPersistentClass());
criteria.add(Restrictions.eq("id.profPropertyId", profileExtensionName));
Object obj = criteria.list();
log.info(obj);
return (List<ProfileExtensions>) obj;

I get the correct number of results, but each result is null (i.e. I get a list of 4000 null objects).  I have tried using both a HQL query and criteria but they both give the same result.
The mapping classes were generated from an existing database.
The SQL generated for the query is as follows
select this_.PROF_DATA_TYPE as PROF1_14_0_, this_.PROF_EXT_KEY as PROF2_14_0_,
       this_.PROF_KEY as PROF3_14_0_, this_.PROF_NAME as PROF4_14_0_,
       this_.PROF_PROPERTY_ID as PROF5_14_0_, this_.PROF_VALUE as PROF6_14_0_,
       this_.PROF_VALUE_EXTENDED as PROF7_14_0_
from EMPINST.PROFILE_EXTENSIONS this_
where this_.PROF_PROPERTY_ID=?

Looks like it should return the correct data.
The mapping file is pretty simple (and generated from the schema:
// Generated Oct 18, 2010 11:08:08 PM by Hibernate Tools 3.2.2.GA
import javax.persistence.AttributeOverride;
import javax.persistence.AttributeOverrides;
import javax.persistence.Column;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;

@Entity
@Table(name="PROFILE_EXTENSIONS"
    ,schema="EMPINST"
    , uniqueConstraints = @UniqueConstraint(columnNames={"PROF_KEY", "PROF_PROPERTY_ID"}) )
public class ProfileExtensions  implements java.io.Serializable {

 private ProfileExtensionsId id;

public ProfileExtensions() {
}

public ProfileExtensions(ProfileExtensionsId id) {
   this.id = id;
}

 @EmbeddedId

@AttributeOverrides( {
    @AttributeOverride(name="profKey", column=@Column(name="PROF_KEY", nullable=false, length=36) ),
    @AttributeOverride(name="profPropertyId", column=@Column(name="PROF_PROPERTY_ID", nullable=false, length=64) ),
    @AttributeOverride(name="profExtKey", column=@Column(name="PROF_EXT_KEY", length=256) ),
    @AttributeOverride(name="profName", column=@Column(name="PROF_NAME", length=256) ),
    @AttributeOverride(name="profDataType", column=@Column(name="PROF_DATA_TYPE", length=64) ),
    @AttributeOverride(name="profValue", column=@Column(name="PROF_VALUE", length=1024) ),
    @AttributeOverride(name="profValueExtended", column=@Column(name="PROF_VALUE_EXTENDED") ) } )
  public ProfileExtensionsId getId() {
    return this.id;
  }

  public void setId(ProfileExtensionsId id) {
      this.id = id;
  }
}

A: In general it's probably not a good idea to have nullable columns as a part of composite id. In my case it was required because I had a view created using outer join and I faced exactly the same problem as you described. I was able to solve it using information provided on https://hibernate.atlassian.net/browse/HHH-1109. I used NullableStringType provided in the attachment to this Hibernate Jira. In my composite id class I used:
@Type(type = "nl.pinkroccade.quarant.common.model.hibernate.type.NullableStringType")
private String nullableField;

A: I had the same issue no exception and a list of nulls the same size as the query result. I started commenting out stuff and comparing to another EmbeddedId JPA. Here is what I found out, all columns in the EmbeddedId must be non null add nullable = false to Columns on the @AttributeOverride and in the @Embedded id class. Remove null columns from the PK class.
I don't know why this works but it did.

A: As user405935 said, it is not a good idea to have nullable columns as a part of your composite key.
I was in the same situation as yours and the problem was that the entries from the table had NULL values on the columns that took part from my composite key, so it couldn't create my embedded key at runtime.
Solutions:

*

*make those columns non-nullable, or

*add a new column used as primary key, or

*find another embedded key using only non-nullable columns

A: You are facing issue because you have included columns which may have null value.
Do no include nullable columns in composite key. By RDBMS definition a key must be not null. Rethink the columns which can uniquely identify each row and make them part of your composite key.


text:
Q: How to compile a .o file to a Linux kernel module (.ko) file?
*

*I write some code. Such as a test.c. I plan to compile it to a test.o file, and supply a head file.

*Then, I supply this .o file to another programmer, he is writing a Linux kernel module, e.g a driver.ko.

My question is: can he include my .o file in his .ko? How to write the make file? Is there any special requirement when I compile my .o file?
Thank you very much.


text:
Q: How to query for results recursively on the same table in SQL server I have a table with two columns - ID and AlternateID. The AlternateID may itself have an AlternateID, also captured in the same table.
My objective is to construct a table where AlternateIDs with AlternateIDs resolve until they no longer have an AlternateID. How do I do this?
Here is some sample data
Source table looks like this
ID | AlternateID
-----------------
10 | 1
11 | 2
12 | 3
13 | 11
14 | 12
15 | 14

My final table should look like this
ID | FinalAlternateID
-----------------
10 | 1
11 | 2
12 | 3
13 | 2
14 | 3
15 | 3

Things tried so far

*

*Wrote a recursive function that takes the id and calls itself. This
kind of works but for the data set I am working on this approach is
very very slow.

*Attempted to write a recursive CTE, but I couldn't
succeed, I was getting compile errors where the as soon as I add the recursive call, it wouldnt be recognized, not sure what the issue is.

Here is the code for the CTE (sorry, for some reason unable to format as code in Stack)
with FinalAlternateIDs (ID, AlternateID, Level) as
(
-- start with ones that dont have an AlternateID
select T1.ID, T1.AlternateID, 0 as Level
from InitialAlternateIDs T1
        left join InitialAlternateIDs T2 on (T1.AlternateID = T2.ID)
where T2.ID is NULL
union all
-- combine it with rows that have AlternateIDs in current result set
-- (exclude ones that are already in the result set)
select T1.ID, T3.AlternateID, (Level + 1) as Level
from InitialAlternateIDs T1
        left join FinalAlternateIDs T2 on (T1.ID = T2.ID)
        join FinalAlternateIDs T3 on (T1.AlternateID = T3.ID)
where T2.ID is NULL
)
select *
from FinalAlternateIDs

A: You can do this with a recursive CTE:
with cte as (
      select id, alternateid, 1 as lev
      from t
      union all
      select cte.id, t.alternateid, lev + 1
      from cte join
           t
           on cte.alternateid = t.id
     )
select cte.id, cte.alternateid
from (select cte.*, max(lev) over (partition by id) as maxlev
      from cte
     ) cte
where lev = maxlev;


text:
Q: is it possible to change the default behaviour of the feed based page layout I have set up a new page layouot which uses the feed based layout. Is it possible to configure the page to default to the "Details" tab of the page layout as opposed to the feed?

A: I cannot find any official documentation on this but, AFAIK, this is not possible.  I did find an idea for this functionality though.  Also found a blog post on feed based layouts where the poster suggests (in a comment at the bottom) that they also do not believe its possible to change details to the default.
IDEA
https://success.salesforce.com/ideaView?id=08730000000l6E9AAI
Blog Post
http://rakeshistom.wordpress.com/2014/02/11/feed-based-page-layouts/
Love to see if someone found some actual documentation that clearly states it is not possible.

A: I noticed that the last tab you switched to is set as default. So everytime you change tabs the default keeps changing. This was tested on a custom object.

A: An update on this - its possible and has been delivered. However, the catch is its only possible lightning. Obviously an effort for SFDC to try an migrate more customers over to lightning.

A: The default tab when first logging into Salesforce will always be the Feed tab for Feed Based layouts. If you then select Details on a record then it will remember via a cookie in your web browser. But cookies will expire as soon as the session ends and the browsers are closed.


text:
Q: Communication not possible with HyperV Virtual Maschine I started to work with hyper-v today. I setup an linux System in it. I now tried to also create a new internal network, because from monday on i don't have an network available but have to do some stuff on it. In the ubuntu server I also added all the hyper-v moduls into the kernel. As soon as I login in via ssh (I have a local connection via cable and an dhcp server in the network
System load:  0.13              Processes:           97
Usage of /:   21.6% of 7.47GB   Users logged in:     1
Memory usage: 28%               IP address for eth0: 192.168.0.14
Swap usage:   0%                IP address for eth1: 192.168.50.100

lsmod display's this:
Module                  Size  Used by
vesafb                 13516  1
joydev                 17393  0
hid_hyperv             12996  0
hid                    77367  1 hid_hyperv
psmouse                72846  0
serio_raw              13027  0
mac_hid                13077  0
i2c_piix4              13093  0
lp                     17455  0
parport                40930  1 lp
hv_netvsc              22462  0
hv_storvsc             17595  2
hv_utils               13284  0
floppy                 60310  0
hv_vmbus               29339  4 hid_hyperv,hv_netvsc,hv_storvsc,hv_utils

As you can see all moduls are loaded. On windows I gave the internal adapater the ip address 192.168.50.1 with the subnet mask 255.255.0.0
The network devices in the virtual maschine where identified as eth0 (external network) and eth1(as internal network)
eth0 works, because I can download packages from repository, so the interfaces work.
On the Linux System it is configurated to user the ip address 192.168.50.100 with the same subnet mask as above.
I can't connect the host with virtual maschine.
What am I doing wrong?


text:
Q: How to close Subprocess that runs other Subprocess on Windows? I am facing the following problem and can't solve it.

*

*A runs B as multiprocessing.Process()

*B runs C as subprocess.run()

*A terminates B by multiprocessing.Process.terminate()

*Expected: B and C are terminated
Result: B is terminated and C runs in background

Important additional information

*

*A, B, C are programs

*A is my program that I develop

*B, C are external programs not developed by me and I have no control
of

*Solution must work on  Windows
 Question  Does anyone have any solution or know if it isn't possible?
Following code describes my problem on example:
# main.py - Process A
# Runs Process B
import multiprocessing
from Manager import manager
from time import sleep

def main():
    proc = multiprocessing.Process(target=manager)

    proc.start()
    print("[MAIN] Process going sleep")
    sleep(3)
    print("[MAIN] Process is awake now. Beginning to terminate")
    proc.terminate()
    proc.join()
    print("[MAIN] Process Manager terminated.")

if __name__ == "__main__":
    main()

# Manager.py - Process B
# Cannot change any code
# Runs process C
import subprocess

def manager():
    print("[MANAGER] START")
    subprocess.run(["python", "sleepery.py"])
    print("[MANAGER] Terminated")

# sleepery.py - Process C
# Cannot change any code
from time import sleep

def sleeper():
    """This process prints info every two seconds for 8"""
    for _ in range(4):
        sleep(2)
        print(f"[SLEEPER] prints!")
    print("[SLEEPER] ends")

if __name__ == "__main__":
    sleeper()

 OUTPUT
[MAIN] Process going sleep
[MANAGER] START
[SLEEPER] prints!
[MAIN] Process is awake now. Beginning to terminate
[MAIN] Process Manager terminated.
[SLEEPER] prints!
[SLEEPER] prints!
[SLEEPER] prints!
[SLEEPER] ends

 WANTED OUTPUT
[MAIN] Process going sleep
[MANAGER] START
[SLEEPER] prints!
[MAIN] Process is awake now. Beginning to terminate
[MAIN] Process Manager terminated.

 My research
The only thing that works is to kill all python processes by taskkill
But it isn't exactly graceful

A: Use a Job object, this allows you to group all child processes in this job and kill them all in a single step.

A: Anders's answer goes right into the point.
Here is refactored main.py to use Job Objects
# main.py - Process A
# Runs Process B
import multiprocessing

import win32api
from Manager import manager
from time import sleep
import time
import win32job
import win32con

def main():
    jobHandle = win32job.CreateJobObject(None, "")
    proc = multiprocessing.Process(target=manager)
    proc.start()
    # Get handle to process and assign process to job object
    handle = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, True, proc.pid)
    win32job.AssignProcessToJobObject(jobHandle, handle)
    print("[MAIN] Process going sleep")
    sleep(3)
    print("[MAIN] Process is awake now. Beginning to terminate")
    win32job.TerminateJobObject(jobHandle, 0)
    print("[MAIN] Process Manager and his kids terminated.")

if __name__ == "__main__":
    main()

Then output:
> python .\main.py
[MAIN] Process going sleep
[MANAGER] START
[SLEEPER] prints!
[MAIN] Process is awake now. Beginning to terminate
[MAIN] Process Manager and his kids terminated.


text:
Q: Changing IP on CentOS machine I have a virtual machine (from Hetzner) under CentOS 7.2. If I type
hostname -I

I'll receive:
172.31.1.100

But really, the machine has another static IP address. Further, we denote its as <IP>. So, I modify my /etc/hosts file as following:
# IPv4
127.0.0.1 virtual-client.domain.org  virtual-client
<IP>  virtual-client.domain.org
#
# IPv6
::1     ip6-localhost ip6-loopback
...

Than I modified /etc/sysconfig/network-scripts/ifcfg-eth0 by adding the following lines:
BOOTPROTO=static
ONBOOT=yes
IPADDR=5.9.102.237

Then I restart network service but IP wasn't changed.
In addition, I worked out this and this instruction but it didn't help me to change IP (in some cases the even network service is hung).
So, how to change IP adress on CentOS machine?
UPD. Output of ip addr:
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
    inet6 ::1/128 scope host
       valid_lft forever preferred_lft forever
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP qlen 1000
    link/ether 52:54:a2:01:ab:1b brd ff:ff:ff:ff:ff:ff
    inet 172.31.1.100/24 brd 172.31.1.255 scope global dynamic eth0
       valid_lft 77783sec preferred_lft 77783sec
    inet6 2a01:4f8:c17:3b87::2/64 scope global
       valid_lft forever preferred_lft forever
    inet6 fe80::5054:a2ff:fe01:ab1b/64 scope link
       valid_lft forever preferred_lft forever

As you can see, the IPv4 address of eth0 still incorrect.


text:
Q: File not found exception even after bufferedwriter close New edit:
Now i found the cause, it is because there are two servers and it write into temp folder in 1st server and try to read from the 2nd one. But I still didn't find a solution for this unless write to Amazon S3 and read from there.
I tried to export csv with struts2 action. However if I tried to export 10 times i can only succeed once, all the others failed with File not found exception (if I refresh the link again, the file can be downloaded). Here is my code:
public String exportFile(String fileName) {
    File exportFile = null;
    try {
        if (CollectionUtils.isEmpty(receipts)) {
            return "";
        }

        exportFile = File.createTempFile(fileName, ".csv");
        exportFile.deleteOnExit();
        try (BufferedWriter fw = new BufferedWriter(new FileWriter(exportFile))) {
            try {
                fw.write("test");
            } finally {
                fw.close();
            }
        }
        return exportFile.getPath();
    } catch (Exception ex) {
        logger.error("Error exporting report. ", ex.getMessage());
    }
    return "";
}

String getStreamFromPath(String filePath) {
    try {
        File downloadFile = new File(filePath);
        fileInputStream = new FileInputStream(downloadFile);
        return SUCCESS;
    } catch (IOException e) {
        log.error(e.getMessage(), e);
        return ERROR;
    }
}

This is really weird, when i test in another server it works totally fine. Any ideas?


text:
Q: Showing Only Specified Property Based on Configuration Here's a question the popped in my mind: Is it possible to show only property(ies) based on what the user has passed parameter in the contructor? To make this question more clear, I'll illustrate a simple class with some properties.
Public Class SampleClass

    Dim _ForA as string
    Dim _ForB as string

    Public ReadOnly Property PropertyA as String
        Get
            return _ForA
        End Get
    End Property

    Public ReadOnly Property PropertyB as String
        Get
            return _ForB
        End Get
    End Property

    Public Sub New(SelectProp as string)

    End Sub

End Class

If the user will pass A (string) in the constructor only PropertyA is shown and if B is passed then PropertyB will only be shown. Is it possible in .Net?
Here's another thing. I found this declaration in some code in the internet. Can you explain what is happening in the declaration?
Imports System.Data

#If DBType = "OLEDB" THEN
Imports System.Data.OleDB
#End IF

#If DBType = "SQLClient" THEN
Imports System.Data.SqlClient
#End IF

Thanks.

A: The name is Conditional Compilation
You can use conditional compilation to select particular sections of code to compile while excluding other sections. For example, you may want to write debugging statements that compare the speed of different approaches to the same programming task, or you may want to localize an application for multiple languages. Conditional compilation statements are designed to run during compile time, not at run time.
You declare a conditional compiler constant in code with the #Const directive, and you denote blocks of code to be conditionally compiled with the #If...Then...#Else directive. For example, to create French and German language versions of the same application from the same source code, you embed platform-specific code segments in #If...Then statements using the predefined constants FrenchVersion and GermanVersion. The following example demonstrates how
#If FrenchVersion Then
   ' <code specific to the French language version>.
#ElseIf GermanVersion Then
   ' <code specific to the German language version>.
#Else
   ' <code specific to other versions>.
#End If

Read this
Conditional Compilation


text:
Q: bash: ./shelllab2.sh: No such file or directory I am running shell scripting program using git bash on windows 10.
I am sure I had created my file here then also getting this error.
bash: ./shelllab2.sh: No such file or directory

A: Check first where you are when you try to access that script:
pwd
ls -alrth

You will see if ./shelllab2.sh is indeed here.


text:
Q: c#,Textbox not working while taking web respose I am using the following function to get response of a url from web. when i place the response in message box it displays properly.when i put it in text box the programme gets stuck on that statement and doesn't move.why is it happening,as i am feeding the string(response_message) to textbox.
void message_send(int j)
{
    int y = 0;

        if (CONTACT_NO[j] != "")
        {

        string Message = "hello";

        string url = "some url not mentioned here ";

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
              request.Timeout = 30000;
              using (WebResponse response = (HttpWebResponse)request.GetResponse())
              {
                  byte[] bytes = ReadFully(response.GetResponseStream());
            response_message = System.Text.Encoding.UTF8.GetString(bytes);
            // error_logs(str);
            MessageBox.Show(response_message);
           textBox2.Text = response_message;
              }
        //textBox3.Text = response_message;

    }
        else
        {
           messagebox.show("some message");

        }

A: Since you're multithreading your update to your textbox, you need to be aware that your worker thread can't update the textbox because the textbox wasn't created on the worker thread.
To update the textbox in a thread safe way, I'd recommend the easiest way of invoking:
TextBox2.Invoke((MethodInvoker)(() => { TextBox2.Text = response_message });

A: I was using my this function in backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) function.which i guess is separate thread.due to which i wasn't able to access textbox1.hence i used the following method to access it.
 private void SetText1(string text)
        {
            // InvokeRequired required compares the thread ID of the
            // calling thread to the thread ID of the creating thread.
            // If these threads are different, it returns true.
            if (this.textBox1.InvokeRequired)
            {
                SetTextCallback d = new SetTextCallback(SetText1);
                this.Invoke(d, new object[] { text });
            }
            else
            {
                this.textBox2.Text = text;
            }

        }

Mistake that i was doing i wasn't using the try catch method to check for the exception.which helps me in understanding my issue.