text:
Q: Hibernate LEFTJOIN not generated for @ManyToOne reflexive relationship I have a table with reflexive association:
A container could be associated to a parent (Column container_id).
A container can have containers as child.
@Entity
public class Container implements Serializable {

  @ManyToOne
  @JoinColumn(name = "container_id", nullable = true, referencedColumnName = "original_id")
  private Container containedIn;

  @Column(name = "original_id")
  private long originalId;

  @OneToMany(mappedBy = "containedIn")
  private List<Container> contains = new ArrayList<>();

...

Problem:
The generated request is :
  Hibernate: select * from (
  select *
  from container con0_, container con1_
  where con0_.container_id=con1_.original_id
  order by con1_.code ) where rownum <= ?

where i'm expecting left outer join:
from container con0_ left outer join container con1_
      on con0_.container_id=con1_.original_id.

Container that doesn't have parent (Root Box CON0000007) are not retrieved as left join is not generated by Hibernate:
ID  | ORIGINAL_ID| CODE          | TYPE       |   CONTAINER_ID (Parent)
1     |  2         | CON000000002  | Package    |    12
2     |  4         | CON000000004  | Package    |    10
4     |  6         | CON000000006  | Package    |    11
5     |  8         | CON000000008  | Package    |    10
7     | 10         | CON0000002    | Box        |    15
8     | 11         | CON0000003    | Box        |    15
9     | 12         | CON0000004    | Box        |    15
12    | 15         | CON0000007    | Root Box   |    NULL

A: The model seems fine. It looks like you don't load children level in your query. And by default you have lazy load, so hibernate doesn't queries for children. If this is the case look here for examples Hibernate: best practice to pull all lazy collections


text:
Q: Return the cube of a number in Python stuck on this exercise.
INSTRUCTIONS

First, def a function called cube that takes an argument called
  number. Don't forget the parentheses and the colon!
Make that function return the cube of that number (i.e. that number
  multiplied by itself and multiplied by itself once again).
Define a second function called by_three that takes an argument called
  number. if that number is divisible by 3, by_three should call
  cube(number) and return its result. Otherwise, by_three should return
  False.

MY CODE
def cube(number):
    return number ** number ** number

def by_three(number)
    if number % 3 == 0:
        return cube(number)

    else:
        return False

A: number ** number ** number isn't the cube of number, rather it is the 3rd tetration of number.
In your cube function, you could use math.pow if you're going to need other math functions or simply number ** 3:
import math

def cube(number):
    return math.pow(number, 3) # number ** 3

A: Try this :
def cube(number):
    return number * number * number

x ** y means x ^y (x raised to the power y).

A: ** is not the multiplication operator, it's the power operator. Your cube function actually returns xxx, not xxx. You should use the * (multiplication) operator instead:
def cube(number):
    return number * number * number
    # Here -------^--------^

A: I wrote this code and it worked:
def cube(number):
    return number*number*number

def by_three(number):
    if number%3==0:
          return cube(number)
    else:
        return False

redpajama_set_name: RedPajamaStackExchange


text:
Q: how does " . ./filename " command work I was following a tutorial on openvpn and it needed to execute a command . ./vars.  It displays a message. On reading the file I found that it executes a echo command in file and disregards everything else in file. On adding other echo statement, it also gets executed. So i would like some basic explanation on this. Is this something related to bash only?

A: . and source are synonymous: it just runs the file line-by-line in the current shell. ./vars is just a path to some file named vars in the current directory. So all that command does is run the file vars line-by-line.
As for the rest of your question, I don't really understand what you're asking. Can you clarify?

A: The . at the start has an explanation here, and the ./filename is a relative reference to the file.

A: . sources or imports a bash script to the current script you are working on ( if you are creating a script ) or to the current tty ( terminal  or command line ) if you are working with the commandline interface. The script it is sourcing must be an executable ( it should have the -x flag set )
./filename means find filename in the present directory am in. if you execute only  ./filename in tty  ( terminal  or command line ) or inside a script, it finds filename and check if filename is executable, then it runs filename . You should take not that ./ means the present working directory. Using two dots ( ../filename ) instead of one with filename tells the bash parser go to the previous directory before the present one am in
using . ./filename you are telling the bash parser to import or source (.) filename (./filename ) in the directory you are currently on


text:
Q: Looking for information on a particular loss function I am looking for the name of a particular loss function or information about it. It is like a common loss function but slightly different.
The $\tau$ quantile of a distribution can be found by finding the value $q$ that minimizes the loss function
$$
L_1(q)=(\tau-1)\int_{-\infty}^{q}(y-q)dF_{Y}(y)+\tau\int_{q}^{\infty}(y-q)dF_{Y}(y)
$$
Is there a name for the value $q$ that minimizes the loss function
$$
L_2(q)=(1-\tau)\int_{-\infty}^{q}(y-q)^2dF_{Y}(y)+\tau\int_{q}^{\infty}(y-q)^2dF_{Y}(y)
$$
I can't seem to find this online.
Side Note: The $(\tau -1)$ changes to $(1-\tau)$ because the integrand is always negative in $L_1$ and always positive in $L_2$ so they actually are both $(1-\tau)$.


text:
Q: React Native: Custom font renders differently on Android and iOS In the picture below I have inspected the same Text-component as rendered on Android on the left and iOS on the right. It seems that iOS renders the font in top of the Text-container.
I'm using the same TTF font-file for both Android and iOS. (I found an online reference to the font I'm using here.)
Any ideas how to make the font render the same for both Android and iOS?

Just to be clear, the difference is not caused by any styling (margin, font size, etc.). It's exactly the same.

A: I found a fix but it doesn't feel right. I think you should find another font that renders the same on each device.
You can play around with the lineHeight, padding and margin to get the same vertical alignment for your text components :
Ios:
instructions: {
    fontFamily: 'Metric-Regular',
    fontSize: 50,
    lineHeight: 50,
    paddingTop: 25,
    marginBottom: -35,
    marginTop: 35
  }

A: Problem is with lineGap and ascender .ttf font file parameters. Fix them using ftxdumperfuser tool. Check https://medium.com/@martin_adamko/consistent-font-line-height-rendering-42068cc2957d


text:
Q: Converting file_get_contents to an array for IP details I have this simple code on my site:
$info = file_get_contents('http://freegeoip.net/json/'.$_SERVER['REMOTE_ADDR']);

which displays like this:
{"ip":"123.123.12.1","country_code":"GB","country_name":"United Kingdom","region_code":"ENG","region_name":"England","city":"London","zip_code":"LN1","time_zone":"Europe/London","latitude":30.302,"longitude":-1.123,"metro_code":0}

I am trying to turn this in to an array so that I can import this data to the database using something similar to:
$ip_address = $info['ip'];
$city = $info['city'];

And so on... I have attempted to use $info[1], $info[2] and it just displays { " each character of text. Is there a simple way to do this?

A: That is a JSON format and you can use the json_decode() function to convert it to either object or array.
So you have:

    $info = file_get_contents('http://freegeoip.net/json/'.$_SERVER['REMOTE_ADDR']);
    $info = json_decode($info, true);

Then you can use, as you said, the $info['ip'] and $info['city']

A: Use json_decode
$info_obj = json_decode($info);

Now $info_obj has the info you want, and you can access it this way:
$ip_address = $info_obj->ip;
$city = $info_obj->city;


text:
Q: Laravel Auth User via External System I am new to the Laravel framework and loving it so far! The part that is giving me the biggest headache to the point of giving up is trying to implement a login system that I have already coded and want to refactor into the Laravel framework. I have read ALOT of posts and I think the framework and how everything is connected is effing with me.
GOAL (Typical OAuth2 Client flow):

*

*User is directed to external login system (custom no third-party
available)

*User comes back with authorization code App calls API
with auth code to get access_token and id_token

*Using the id_token...store this information (in database or not and just keep reading from the id_token stored somewhere)

*User now has access to pages requiring an authenication

All the words are just getting confused in my head and I don't even know where to start (Guards, Middleware, UserProviders, Contracts....)
Thank you and let me know if you need more information (especially to prove that's I've given this a run and/or ALOT of thought).
Explaining to my like I'm 5, at this point, would be preferred :P


text:
Q: redirect with .htaccess rewrite rule to different folder on my server I have been trying to redirect to a different folder with .htaccess when I hit a domain.
Here's my .htaccess redirect rule, can you tell me where am I wrong?
Options +FollowSymLinks

RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d [OR]
RewriteCond %{HTTP_HOST} ^(www.)?racereadymotorsports.in$
RewriteRule ^(.*)$ /raceready/$1 [L,QSA]
RewriteCond %{HTTP_HOST} ^(www.)?annelies-slabbynck.com$
RewriteRule ^(.*)$ /annelies/$1 [L,R=301]

So, what I want is, if someone visits racereadymotorsports.in, they redirect to /raceready/ directory
and on the other hand if they visit to annelies-slabbynck.com, they should redirect to /annelies/ directory
At present, this redirects twice for annelies-slabbynck.com which means that, I end up with:
http://www.annelies-slabbynck.com/annelies/annelies/ as my final url
I am running a shared hosting and do not have access to add a new configuration.
Please help.

A: You need to remove the [OR] flag and reproduce the same conditions with the other rule. Maybe something like:
RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{HTTP_HOST} ^(www.)?racereadymotorsports.in$
RewriteRule ^(.*)$ /raceready/$1 [L,QSA]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{HTTP_HOST} ^(www.)?annelies-slabbynck.com$
RewriteRule ^(.*)$ /annelies/$1 [L,R=301]

Or better yet, you can use these conditions instead:    RewriteEngine on
RewriteCond %{HTTP_HOST} ^(www.)?racereadymotorsports.in$
RewriteCond %{DOCUMENT_ROOT}/raceready/$1 -f [OR]
RewriteCond %{DOCUMENT_ROOT}/raceready/$1 -d
RewriteRule ^(.*)$ /raceready/$1 [L,QSA]

RewriteCond %{HTTP_HOST} ^(www.)?annelies-slabbynck.com$
RewriteCond %{DOCUMENT_ROOT}/annelies/$1 -f [OR]
RewriteCond %{DOCUMENT_ROOT}/annelies/$1 -d
RewriteRule ^(.*)$ /annelies/$1 [L,R=301]

Note that the R=301 flag in your second rule redirects the browser, unlike the first rule which only internally rewrites the request.


text:
Q: Get event parameters via reflection I can't work out how to get the parameter types for an event.
For instance, I can only see using a MethodInfo to get parameters, but I have either an EventInfo or a FieldInfo.
What I want is to be able to get 'Boolean' from this:
Public Event EventName(ByVal sender As Object, ByVal value As Boolean)

I could theoretically try something like GetRaiseMethod() but that won't work (because that method returns null as per this link) and even if it did it would require a method binding first and this is meant to be for a test suite just confirming that the event has a certain typed parameter at initialisation.
Any ideas?

A: You can get the type of the second parameter as follows assuming the event EventName is declared in the class DeclaringClass and the event has at least to parameters. Else you will probably receive an exception.
Type secondEventHandlerParameterType =
   typeof(DeclaringClass).
   GetEvent("EventName").
   EventHandlerType.
   GetMethod("Invoke").
   GetParameters()[1].
   ParameterType;

A: I tried to use Daniel solution but got the TypeInitializationException exception in my PCL.
The following code works for me and looks more clear:
Type secondEventHandlerParameterType =
   typeof(DeclaringClass).
   GetEvent("EventName").
   EventHandlerType.
   GenericTypeArguments.
   First();


text:
Q: БЭМ как собирать merged-бандлы Добрый день! Столкнулся с проблемой при попытке собрать merged-бандл. Делал как описано здесь https://ru.bem.info/toolbox/enb/enb-bem-techs/build-merged-bundle/, пробовал по разному крутить, использовать другие модули вместо тех что в примере, но без толку. Скрипт нормально проходит по простым бандлам, находит decl-ы, ну и дальше вроде нормально отрабатывает но decl в папке merged не создается и, естественно вылетает ошибка при сборке, потому что собирать то и нечего. При этом сама папка создается.
С БЭМ только знакомлюсь, как и со сборщиком, возможно лучше для сбора ассетсов для всех бандлов в один использовать совсем другой инструмент или же подходить иначе?


text:
Q: jQuery Listen for list items being added to or removed from unordered list I'm trying to listen for items being added to an unordered list, and change the class of the unordered list if the list is not empty. For example:
$(document).on("CHANGE IN NUMBER OF ITEMS IN UL", "#listID", function() {
    if($('#listID') > li').size() >=1) {
        $('#listID').removeClass('invalid').addClass('valid');
    }
    else {
        $('#listID').removeClass('valid').addClass('invalid');
    }
});

Any help here would be greatly appreciated!


text:
Q: Android studio - How to save data selected on previous activity This is a snippet of my code. The Textview acts as buttons and have Onclicklistner on them. When cpu1000 Textview is clicked it leads to the cpu_g1000 class for which the code is shown below.
public class Game_1000 extends AppCompatActivity implements View.OnClickListener{

private TextView cpu1000, mobo1000;

TextView cpu, mobo;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_game_1000);

    cpu1000 = (TextView) findViewById(R.id.proName_G1);
    mobo1000 = (TextView) findViewById(R.id.moboName_G1);

    cpu1000.setOnClickListener(this);
    mobo1000.setOnClickListener(this);

    cpu = (TextView) findViewById(R.id.proNameG1000);
    cpu.setText(getIntent().getStringExtra("Processor"));

    mobo = (TextView) findViewById(R.id.moboNameG1000);
    mobo.setText(getIntent().getStringExtra("Motherboard"));
}

@Override
public void onClick(View v) {

    if (v == cpu1000) {
        opencpu_g1000();
    }
    else if (v == mobo1000) {
        openmobo_g1000();
    }
}

public void opencpu_g1000() {
    Intent intent = new Intent(this, cpu_g1000.class);
    startActivity(intent);
}

public void openmobo_g1000() {
    Intent intent = new Intent(this, mobo_g1000.class);
    startActivity(intent);
}

In this class, there are radio buttons. The users choose one of the choices and the choice is changed to strings. The strings are sent back to Game_1000 class. The string then gets substituted with "Choose a processor" to show the new choice. The issue I am having is when I choose a motherboard the processor choice is reverted back to "Choose a processor" and the motherboard choice shows. I need both to show at the same time.
public class cpu_g1000 extends AppCompatActivity {

Button button_save;
RadioGroup rG;
TextView tv;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_cpu_g1000);

    button_save = (Button) findViewById(R.id.Save_G1_cpu);
    rG = (RadioGroup) findViewById(R.id.cpu_RadioGrp);
    tv = (TextView) findViewById(R.id.proNameG1000);

    button_save.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {

            int selected_cpu = rG.getCheckedRadioButtonId();
            RadioButton selectedRadioButton = (RadioButton) findViewById(selected_cpu);

            String radioValue = selectedRadioButton.getText().toString();

            Intent intent = new Intent(cpu_g1000.this, Game_1000.class);
            intent.putExtra("Processor", radioValue);
            startActivity(intent);

        }

    });
}

Processor is chosen:

Motherboard is chosen:

Example of choices:

The previous choice are not recored and when a new choice is made the previous choice reverts back to "Please choose a processor" but I need both of the information to show. In my original code, I have more than just 2 choices but I shortened it to make it easier to read.

A: Start your second (Selection) activity for result by calling startActivityForResult(...) and then when user completes the interaction set your selected data in an Intent and pass that intent to method with desired result setResult(...) then call finish on second activity.
After finishing the second activity you will receive intent data in onActivityResult(...) method of first activity, extract that data from intent and then show it to user.
More Description
Example

A: Try using Shared Preference. Here's a good tutorial.

A: For your scenario what you have to do is save Processor and Motherboard selection result or send data form one Activity to another Activity. As after processor selection you are returning to Game_1000 Activity you can use startActivityForResult. This method send back the result to calling Activity via Intent. Thats means if you call cpu_g1000 Activity from Game_1000 Activity and after selecting Processor you can send back the result to Game_1000 Activity.  Game_1000 Activity will get the result in onActivityResult method.
Example:
Start cpu_g1000 Activity  with startActivityForResult from Game_1000 Activity.
public void opencpu_g1000() {
  Intent intent = new Intent(this, cpu_g1000.class);
  startActivityForResult(intent, PROCESSOR_SELECTION_CODE);
}

In cpu_g1000 Activity set the result to intent and send back to Game_1000 Activity
    button_save.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View view) {

        int selected_cpu = rG.getCheckedRadioButtonId();
        RadioButton selectedRadioButton = (RadioButton) findViewById(selected_cpu);

        String radioValue = selectedRadioButton.getText().toString();

        Intent resultIntent = new Intent();
         // TODO Add data to send back
        resultIntent.putExtra("ProcessorSelection", radioValue);
        setResult(Activity.RESULT_OK, resultIntent);
        // finishing this activity
        finish();

    }

});

In Game_1000 Activity get the value sent form cpu_g1000 Activity by overriding onActivityResult method.
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
  super.onActivityResult(requestCode, resultCode, data);

  switch(requestCode) {
    case (PROCESSOR_SELECTION_CODE) : {
      if (resultCode == Activity.RESULT_OK) {
        // TODO Extract the data returned from the child Activity.
        String radioValue = data.getStringExtra("ProcessorSelection");
        // save the result value and update UI
      }
      break;
    }
 }
}

For mobo_g1000 Activity use same procedure to get the result back in Game_1000 Activity. Start mobo_g1000 Activity with startActivityForResult and get the value in Game_1000 Activity's onActivityResult method. You have to add another case in onActivityResult method for mobo_g1000 Activity.
Check this and this link for better understanding how this work.


text:
Q: passing string to sub.re not working in Python This is so far what has been my progress with this regex function :
import os, re

dpath="/root/tree/def/"

fmatch = re.compile(r'\s+''[\[]+''[A-Z]+''[\]]+')
pmatch = fmatch.match('[FLAC]')

def replace(pmatch,df):
    m = re.sub(fmatch,df)
    print (m)

def regex(dpath):
    for df in os.listdir(dpath):
        replace(pmatch, df)

regex (dpath)

First do a for loop and look for files in (dpath), then pass the directory name string to replace(). But I am getting missing argument 'string' error :
root@debian:~# python regex3.py
Traceback (most recent call last):
  File "regex3.py", line 18, in <module>
    regex (dpath)
  File "regex3.py", line 16, in regex
    replace(pmatch, df)
  File "regex3.py", line 9, in replace
    m = re.sub(fmatch,df)
TypeError: sub() missing 1 required positional argument: 'string'

A: It seems that you want to replace alls all matches of the RegEx \s+[\[]+[A-Z]+[\]]+ to [FLAC]
Make sure you do the following:
def replace(pmatch,df):
    m = fmatch.sub('[FLAC]', df)
    print (m)

A: Using @martin-konecny 's Example,
I got this that worked.
Create Files for Example
# Run this in your Shell/Terminal
touch /tmp/abc.FLAC
touch /tmp/abcd.FLAC

Run Python
import re
import os

dpath = '/tmp/'

fmatch = re.compile(r'.+\.FLAC')
pmatch = fmatch.match('[FLAC]')

def replace(pmatch, df):
    m = fmatch.sub('[REDACTED]', df)
    print(m)

def regex(dpath):
    for df in os.listdir(dpath):
        replace(pmatch, df)

regex(dpath)

Result:
# ...
# [REDACTED]
# [REDACTED]
# ...

Great if you want to run a search and keep a selection of your results secret.


text:
Q: iOS routing viewDidAppear to child view controllers? I'm adding a child view controller to a parent view controller, and everything works as expected, except that child view controller isn't having its usual callbacks triggered. eg, things like viewWillAppear(animated) is never called. I looked into it and thought it may be because I wasn't calling willMoveToParentViewController and didMoveToParentViewController on the child view controller before and after adding it to the parent, respectively. Unfortunately, fixing that has made no difference. Does anyone know how I can wire this up so that when I do addChildViewController and removeChildViewController the regular callbacks are triggered? After adding the childViewController, I also add its view as a subview to the parent view controller's view. At neither point (addChildViewController & addSubview) does the child view controller's viewWillAppear(animated), etc methods get called...
Nick

A: Not sure if this can apply to your situation, but try experimenting with manually sending appearance callback methods to your children.
From apple's view controller containment documentation:

However, sometimes the default behavior may send those events in an
  order that doesn't make sense for your container. For example, if
  multiple children are simultaneously changing their view state, you
  may want to consolidate the changes so that the appearance callbacks
  all happen at the same time in a more logical order. To do this, you
  modify your container class to take over responsibility for appearance
  or rotation callbacks.

It recommends manually forwarding the appearance callbacks to your children if you want more fine grained control:
// From the container view controller
- (BOOL) shouldAutomaticallyForwardAppearanceMethods
{
    return NO;
}

-(void) viewWillAppear:(BOOL)animated
{
    [self.child beginAppearanceTransition: YES animated: animated];
}

-(void) viewDidAppear:(BOOL)animated
{
    [self.child endAppearanceTransition];
}

-(void) viewWillDisappear:(BOOL)animated
{
    [self.child beginAppearanceTransition: NO animated: animated];
}

-(void) viewDidDisappear:(BOOL)animated
{
    [self.child endAppearanceTransition];
}

A: Try this one:
childController.willMoveToParentViewController(self)
childController.beginAppearanceTransition(true, animated: true)

after added to your view controller

A: Just tried do the following in viewDidLoad in the parent viewcontroller and it seems to work
ChildExperimentViewController *child = [[ChildExperimentViewController alloc]init];
[self addChildViewController:child];
[self.view addSubview:child.view];
[child didMoveToParentViewController:self];

A: viewWillAppear, viewDIdAppear called automatically when you adding your ViewControler view to a view hierarchy
viewWillDisappear, viewDidDisappear called automatically when you removing your ViewControler view from a view hierarchy
Maybe this methods not called because you are adding sub-controller view before displaying main view controller and, therefore your main view is not in view hiererchy itself?
When your main view controller appears or disappears you should call this methods for childs in corresponding methods.

A: let vc = ChildVC.init()
vc.frame = self.view.bounds
self.addChildViewController(vc)
self.view.addSubview(vc.view)
vc.willMove(toParentViewController: self)
vc.didMove(toParentViewController: self)

A: Chourobin answer in Swift:
override var shouldAutomaticallyForwardAppearanceMethods: Bool {
    return false
}

override func viewWillAppear(_ animated: Bool) {
    self.childViewControllers[self.segmentView.selectedSegmentIndex].beginAppearanceTransition(true, animated: animated)
}

override func viewDidAppear(_ animated: Bool) {
    self.childViewControllers[self.segmentView.selectedSegmentIndex].endAppearanceTransition()
}

override func viewWillDisappear(_ animated: Bool) {
    self.childViewControllers[self.segmentView.selectedSegmentIndex].beginAppearanceTransition(false, animated: animated)
}

override func viewDidDisappear(_ animated: Bool) {
    self.childViewControllers[self.segmentView.selectedSegmentIndex].endAppearanceTransition()
}

P.S. As I am not keeping the reference to a child VC as a property or a variable. I preferring to access it using the currently selected segment index. SegmentView is a third party UISegmentControl.

A: You can manual call the child view controller's viewWillAppear in parectViewController,code like this
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [selectedViewController viewWillAppear:animated];
}

if you have add a navigationController as childViewController you can add code like this in navigationController's delegate
-(void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated
{
    [viewController viewWillAppear:animated];
}

if you have add a tabBarController as childViewController you can add code like this in tabBarController's delegate and super view
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.tabBarController.selectedViewController viewWillAppear:animated];
}

- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
    [viewController viewWillAppear:NO];
}

I don't know if this can solve your problem,hope be able to help you.


text:
Q: Uncheck TableView all TableView Selections in Swift4 I have searched and haven't seen a solution to:

*

*I have a tableView that allows multiple selections

*I want to have a button to allow those selections to all be cleared at the same time, in Swift.  The button will be on a different viewController (a UIViewController) than the TableView.  Is it ok to use protocol & delegate, or is singleton required?  I want it to update when the button is clicked.

I saw an answer from Dejan Skledar a few years ago here: UITableViewCell checkmark to be toggled on and off when tapped   and the function called resetChecks() seems what I was looking for, but I am having trouble getting what I wrote for Swift to work. When I run it, it doesn't actually go into the method, and then when the method is called, it crashes with "unexpectedly finding nil". Please, can anyone offer some advice? Thanks. Here is what I wrote:
func removeChecks() {
    for i in 0...grainTableView.numberOfSections - 1 {
        for j in 0...grainTableView.numberOfRows(inSection: i) - 1 {
            if let cell = tableView(grainTableView, cellForRowAt: [i,j]) as? UITableViewCell {
                cell.accessoryType == .none
            }
        }
    }
}

A: Send object from the preVC when you present the currentVC
class currentVC:UIViewController {

    var delegate:PreVC?

 func removeChecks() {

   if let grainTableView = delegate?.tableView {
      for i in 0...grainTableView.numberOfSections - 1 {
          for j in 0...grainTableView.numberOfRows(inSection: i) - 1 {
              if let cell = tableView(grainTableView, cellForRowAt: [i,j]) as? UITableViewCell {
                cell.accessoryType == .none
             }
          }
      }
   }
}

//
func removeChecks() {

   if let grainTableView = delegate?.tableView {

      delegate?.shouldClear = true

      grainTableView.reloadData()

   }

}


text:
Q: Converting JPA specification to JPQL we have JPA Specifications defined on an entity. I want to convert that specification to JPQL So I can create join it with some other entity. (I tried using parent-child relationship but that's not efficient, and that doesn't allow us to put filtering(specifications) on chile entity). Earlier We were reading from a single table so we had specifications in place that was working fine. Now we need to join this with another entity, For that I want to use JPQL over specifications. I want to convert specification on one table to JPQL and than join it with other entity.

A: Use @query annotation on your repository method and write your JPQL query inside the @query annotation.
you can refer table names with your entity name inside the @query annotation.

A: Let say you have User and List  entities
In JPQL you will write something like this
public List<User> getUserByName(String username) {
    String queryString = "select u from User u where u.name= '"+username+"' ";
    Query query = getEntityManager().createQuery(queryString);
    return query.getResultList();
}

With JPA and Hibernate older than 5.1
even with JPA 2.1 and Hibernate 5.0 it's still not possible to join two unrelated entities.
If User and UserAddress are not related to each other
List<Object[]> results = em.createQuery("SELECT u FROM User u, UserAddress ua WHERE u.firstName = ua.firstName AND u.lastName = ua.lastName").getResultList();

Hibernate will transform this as cross join something like this
User user01_ cross join UserAddress useraddress1_

With Hibernate 5.1
Same quesry will be treated as inner Join
List<Object[]> results = em.createQuery("SELECT u FROM User u, UserAddress ua WHERE u.firstName = ua.firstName AND u.lastName = ua.lastName").getResultList();

User user01_ inner Join UserAddress useraddress1_

Other Imp Point:
Using subqueries in the join clause is not allowed. in JPQL, subqueries are only allowed in the WHERE and HAVING part.


text:
Q: twisted group ring: uniqueness of representation $G$ is a multiplicative group, $K$ is a field. Let $\gamma$ and$\tilde{\gamma}$ be two twistings of $K^t[G]$ related by the equation $\tilde{\gamma}(x,y)=\delta(x)\delta(y)\delta(xy)^{-1}\gamma(x,y)$. Is function $\delta:G\rightarrow:K^0$ unique?

A: No. You can multiply $\delta$ pointwise by a homomorphism $G \to K^{\times}$.


text:
Q: Inequality in non-decreasing sequence Let $a, b$ be two sequences of real numbers such that $a_1 \le a_2 \le \dots \le a_n$ and $b_1 \le b_2 \le \dots \le b_n$. Prove (or disprove) that
$$\left(\frac{1}{n}\sum_{i=1}^{n}{a_i}\right)\left(\frac{1}{n}\sum_{i=1}^{n}{b_i}\right) \le \left(\frac{1}{n}\sum_{i=1}^{n}{a_ib_i}\right)$$
Now obviously, I have no idea from where to even start attacking this monster. I tried Cauchy-Schwarz (square roots of $a_i$ and $b_i$), and by using AM-GM on the left side, but realized that they are not necessarily non-negative.

A: It is a standard Inequality and there are numerous proofs if I am not mistaken. I'll give you two options. One I'll give you a hint and you can pursue a solution on your own which will help you. But if you have a million exercises following this and using this inequality then you can choose to just refer this Wikipedia page which contains a simple proof.
Hint: Consider the sum $$ \sum_{i = 1}^n \sum_{j = 1}^n(a_i - a_j)(b_i - b_j) $$
Since we know that $\{a_k\}$ and $\{b_k\}$ are monotonically increasing and since either $i \le j$ or $ i \gt j$ the signs of the two facotrs $ (a_i - a_j) $ and $ (b_i - b_j)$ will always be the same and hence the iterated sum will be non-negative. Now you have an inequality. Expand and continue.


text:
Q: spring boot hot reload when jar file changed Spring boot project, build and package a jar file then upload it to the server, run it:
java -jar xxx.jar
How can I make it auto reload when I upload a new jar file?

A: add Spring Boot DevTools to your dependencies for developer friendly options like auto restart of the server:
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
    </dependency>
</dependencies>


text:
Q: How to determine if a package is a meta-package from the command line? How can I determine if a package is a meta-package from the command line, possibly via apt-get, aptitude or apt-cache?
I have tried:
apt-cache show texlive-full
apt-cache showpkg texlive-full

but the only way I can tell this package is meta is by reading the "en-description" field.
Is there a more automatic way of doing this, that will give me a yes/no response, or at least have a field such as then "en-description" dedicated to this?

A: There is no formal definition of a metapackage. The informal definition is that a metapackage is one that is only intended to be installed for its dependencies and contains no useful file of its own.
You can define a metapackage as a package that contains no file. There is no way to determine this from the package database. You can use the file database and check that the package contains only directories (many such packages contain a few directories). In fact, most metapackages contain a few files in /usr/share/doc/<package name>: a copyright file, a changelog, sometimes a few more. Here's an approximation that defines a metapackage as containing only files in /usr/share/doc/<some directory> (not in subdirectories of that) and the leading directories:
if ! apt-file -F list $package | grep -qvE '^/(usr(/share(/doc(/[^/]*(/[^/]*)?)?)?)?)?$'; then
  echo "$package looks like a metapackage"
fi

Another approach is to look for a package tag with debtags. There are several tags that are commonly used on metapackages.
debtags tag ls $package | grep -x -e 'role::metapackage' -e 'role::dummy' -e 'special::meta'

Another approach is to look for packages with a small size. Each directory counts as 4 kB, so plan accordingly when picking a threshold (again, this is an approximation).
aptitude -F '%I %p' search "~n^$package\$"

Upon reflection, I wonder if you mean virtual packages rather than metapackages. Virtual packages are actually not packages but package names used in Provides: fields. You can list them with aptitude search '~v'. Running apt-cache show on one displays "Can't select versions from package 'zcav' as it is purely virtual". Running aptitude show lists the packages that provide it. A convenient way to show virtual packages is with apt-cache: this prints one line for a non-virtual package and potentially multiple lines (one for each provider) for a virtual package — you can tell if the package is virtual even if there is a single provider because the name of the provider is different.
apt-cache -n search "^$package\$"

A: You could try entering
apt-cache search 'metapackage | meta-package'

which will give you a long list, and then use grep to, say show all science related metapackages with
apt-cache search 'metapackage | meta-package' | grep -i science

This will return a long list (I have shortened it here)
science-astronomy - Debian Science Astronomy packages
science-astronomy-dev - Debian Science Astronomy-dev packages
science-biology - Debian Science Biology packages
science-chemistry - Debian Science Chemistry packages
science-dataacquisition - Debian Science data acquisition packages
science-dataacquisition-dev - Debian Science data acquisition development packages
science-distributedcomputing - Debian Science Distributed Computing packages
science-electronics - Debian Science Electronics packages
science-electrophysiology - Debian Science packages for Electrophysiology
science-engineering - Debian Science Engineering packages
science-engineering-dev - Debian Science Engineering-dev packages
science-geography - Debian Science Geography packages
science-highenergy-physics - Debian Science High Energy Physics packages

You can use any number of alternatives for science, such as KDE to find all the KDE metapackages.
This is probably about the best you can do with apt-cache, but it should quickly locate most of the metapackages you want to find. If it doesn't find exactly everything you were looking for, the simplest thing is to look in the metapackage section in Synaptic.


text:
Q: Doing a certain action after pressing the Enter key -React Native I am using react-native-phone-input package for entering phone number. I want the password field below to open when the user presses the enter key on the keyboard after entering the phone number. There is no such method in the package. How can I do that? Can I just listen for the enter key when the keyboard is turned on and make it go to password input?

import { TextInput, View } from 'react-native';
import React, { useState } from 'react';
import PhoneInput from 'react-native-phone-input';

export default function SignUp({ navigation }) {

  const [password, setPassword] = useState('');
  const [phoneNumber, setPhoneNumber] = useState('');

  return (
    <View >
      <PhoneInput
        ref={ref => { phone = ref }}
        onChangePhoneNumber={setPhoneNumber}
        style={{ width: 150, height: 30, backgroundColor: 'grey' }}
      />
      <TextInput
        onChangeText={setPassword}
        value={password}
        style={{ width: 150, height: 30, backgroundColor: 'grey', marginTop: 20 }}
      />
    </View >
  );
}

A: There is a prop in react-native-phone-input that should allow you to handle this as you would with a normal TextInput.

onPressConfirm
func  none
handler to be called when taps the confirm button

Thus, you can define a state and use the onPressConfirm function prop to change this state. Then use conditional rendering to hide or show the password input.
import { TextInput, View } from 'react-native';
import React, { useState } from 'react';
import PhoneInput from 'react-native-phone-input';

export default function SignUp({ navigation }) {

  const [password, setPassword] = useState('');
  const [phoneNumber, setPhoneNumber] = useState('');
  const [confirm, setConfirm] = useState(false)

  return (
    <View >
      <PhoneInput
        ref={ref => { phone = ref }}
        onChangePhoneNumber={setPhoneNumber}
        style={{ width: 150, height: 30, backgroundColor: 'grey' }}
        onPressConfirm={() => setConfirm(true)}
      />
      { confirm &&
      <TextInput
        onChangeText={setPassword}
        value={password}
        style={{ width: 150, height: 30, backgroundColor: 'grey', marginTop: 20 }}
      />}
    </View >
  );
}


text:
Q: change animated image background using imagemagick I'm trying to fill the background of a gif using imagemagick,
this is the input file
I was able of cropping the background
still not perfect but it's an acceptable result
Now when I try to fill the background:
the output is static despite being a gif
This is the command I tried :
convert "$1" -resize 400x400  -gravity center -background "pink" -extent 400x400 "out.gif"

What am I doing wrong?

A: I don't know what you are trying to do, but this should show you how to replace the background using floodfill:
magick crybaby.gif -coalesce -fuzz 10% -fill yellow -floodfill 0x0 "rgb(251,102,90)" result.gif


text:
Q: Finding the equation of a line that is tangent to. I have the following question & its answer but I do not understand how some parts were obtained - Q&A, Previous Q
Where does the $1+dy/dx (x-1)$ come from?

A: Hint: Assuming $y=y(x)$ then we get by the chain and product rule
$4x+2y(x)y'(x)+2y(x)+2xy'(x)=0$
Can you finish?

A: ok so you don't have any problem with calculating $\frac{dy}{dx}$
you want to find the tangent at the curve at the point (1,1)
the equation of a line passing through the point (1,1) is given by
$$(y-1)=m(x-1)$$
where m is the slope of the line
now to calculate$$ m=slope=\frac{dy}{dx}\big|_{(1,1)}$$
$$ m=slope=-\frac{2x+y}{x+y}\big|_{(1,1)}$$
$$ m=slope=-\frac{2(1)+(1)}{(1)+(1)}=\frac{-3}{2}$$
thus equation of tangent $$(y-1)=-\frac{3}{2}(x-1)$$
                         $$y-1=-\frac{3}{2}x+\frac{3}{2}$$
$$y=-\frac{3}{2}x+\frac{5}{2}$$


text:
Q: How can i create Push notification? Problems in Code. not getting registration id I am new to android need some help with my code. I am doing push notifications where I pass the registration id to my server using a post request. I wrote the code to do this, but I keep getting a registration id of null while I'm debugging. Here is the code I've written:
Splashscreen.java
package com.driverapp.inis.zuber;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import android.widget.RelativeLayout;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.gcm.GoogleCloudMessaging;

import java.io.IOException;

import Connectivity_manager.Internet_CheckingActivity;
import UI_Alert.AlertDialogManager;

public class Splashscreen extends Activity {
    private static final String TAG = "SplashScreenActivity";
    private static final String TAG1 = "lifecycle";
    private Location newLocation = null;
    private AlertDialogManager alert;
    private Internet_CheckingActivity chckInternt;
    private GeoLocationFinder geoLocationFinder;
    private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
    public static final String EXTRA_MESSAGE = "message";
    public static final String PROPERTY_REG_ID = "registration_id";
    private static final String PROPERTY_APP_VERSION = "appVersion";
    protected String SENDER_ID = "525761298572";
    private GoogleCloudMessaging gcm = null;
    private String regid = null;
    private Context context = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splashscreen);
        alert = new AlertDialogManager();
        chckInternt = new Internet_CheckingActivity(this);
        Log.d(TAG1, "oncreate");
        context = getApplication();
        if (checkPlayServices()) {
            gcm = GoogleCloudMessaging.getInstance(this);
            regid = getRegistrationId(context);

            if (regid.isEmpty()) {
                registerInBackground();
            } else {
                Log.d(TAG, "No valid Google Play Services APK found.");
            }
        }

    }

    @Override
    public void onBackPressed() {
        restart();
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.d(TAG1, "onresume");
        //  setupLocation();
        if (chckInternt.isNetworkAvailable() == true) {
            setupLocation();
        } else {
            alert.showAlertDialog(Splashscreen.this, "Error", "Please Check Your Internet Connection", false);
        }

        checkPlayServices();
    }

    /**
     * Method for checking the current lat log values.
     */
    private void setupLocation() {
        GeoLocationFinder.LocationResult locationResult = new GeoLocationFinder.LocationResult() {

            @Override
            public void gotLocation(Location location) {
                if (location != null) {

                    newLocation = new Location(location);
                    newLocation.set(location);

                    Log.d(TAG,
                            "Got coordinates, congratulations. Longitude = "
                                    + newLocation.getLongitude() + " Latitude = "
                                    + newLocation.getLatitude());
                    Intent i = new Intent(Splashscreen.this, DefaultMAP.class);
                    startActivity(i);
                    finish();
                } else {
                    new Handler(Looper.getMainLooper()).post(new Runnable() {
                        @Override
                        public void run() {
                            alert.showAlertDialog(Splashscreen.this, "Check Your GPS", "Restart your Application", false);

                        }
                    });
                }
            }
        };
        geoLocationFinder = new GeoLocationFinder();
        geoLocationFinder.getLocation(this, locationResult);

        RelativeLayout root = (RelativeLayout) findViewById(R.id.splash);
        root.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                restart();
            }
        });

    }

    public void restart() {
        Intent rIntent = getBaseContext().getPackageManager()
                .getLaunchIntentForPackage(getBaseContext().getPackageName());
        rIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(rIntent);
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.d(TAG1, "onpause");
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.d(TAG1, "onstart");
    }

    private boolean checkPlayServices() {
        int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
        if (resultCode != ConnectionResult.SUCCESS) {
            if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
                GooglePlayServicesUtil.getErrorDialog(resultCode, this,
                        PLAY_SERVICES_RESOLUTION_REQUEST).show();
            } else {
                Log.d(TAG, "This device is not supported - Google Play Services.");
                finish();
            }
            return false;
        }
        return true;
    }

    private String getRegistrationId(Context context) {
        final SharedPreferences prefs = getGCMPreferences(context);
        String registrationId = prefs.getString(PROPERTY_REG_ID, "");
        if (registrationId.isEmpty()) {
            Log.d(TAG, "Registration ID not found.");
            return "";
        }
        int registeredVersion = prefs.getInt(PROPERTY_APP_VERSION, Integer.MIN_VALUE);
        int currentVersion = getAppVersion(context);
        if (registeredVersion != currentVersion) {
            Log.d(TAG, "App version changed.");
            return "";
        }
        return registrationId;
    }

    private SharedPreferences getGCMPreferences(Context context) {
        return getSharedPreferences(Splashscreen.class.getSimpleName(),
                Context.MODE_PRIVATE);
    }

    private static int getAppVersion(Context context) {
        try {
            PackageInfo packageInfo = context.getPackageManager()
                    .getPackageInfo(context.getPackageName(), 0);
            return packageInfo.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            throw new RuntimeException("Could not get package name: " + e);
        }
    }

    private void registerInBackground() {
        new AsyncTask() {
            @Override

            protected Object doInBackground(Object... params) {
                String msg = "";
                try {
                    if (gcm == null) {
                        gcm = GoogleCloudMessaging.getInstance(context);
                    }
                    regid = gcm.register(SENDER_ID);
                    Log.d(TAG, "########################################");
                    Log.d(TAG, "Current Device's Registration ID is: " + msg);
                } catch (IOException ex) {
                    msg = "Error :" + ex.getMessage();
                }
                return null;
            }

            protected void onPostExecute(Object result) { //to do here
            };

        } .execute(null,null,null);
    }
}

LoginActivity
public class LoginActivity extends AppCompatActivity {

    private Button btnlogin;
    private EditText txtusername;
    private EditText txtpassword;
    private String userName;
    private String message;
    private String userid;
    private JSONArray login_data = null;
    private Internet_CheckingActivity chckInternt;
    private TransparentProgressDialog pDialog;
    private static final String URL_Login = "http:myapi";
    private static final String TAG_MESSAGE = "message";
    private static final String TAG_username = "username";
    private static final String TAG_password = "password";
    SessionManager msessionManager;
    private AlertDialogManager alert;
    private Location newLocation = null;
    private static final String TAG = "SplashScreenActivity";
    private  GeoLocationFinder geoLocationFinder;
    private static final String TAG_regid = "gcm_regid";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        alert = new AlertDialogManager();
        chckInternt = new Internet_CheckingActivity(this);
        txtusername = (EditText) findViewById(R.id.lusername);
        txtpassword = (EditText) findViewById(R.id.lpassword);
        btnlogin = (Button) findViewById(R.id.loginbtn);
        msessionManager = new SessionManager(getApplicationContext());
        btnlogin.setOnClickListener(mbtnLogin);

        if (SERVER_URL == null || SENDER_ID == null || SERVER_URL.length() == 0
                || SENDER_ID.length() == 0) {
            // GCM sernder id / server url is missing
            alert.showAlertDialog(LoginActivity.this, "Configuration Error!",
                    "Please set your Server URL and GCM Sender ID", false);
            // stop executing code by return
            return;
        }
    }
    @Override
    public void onBackPressed() {
        startActivity(new Intent(this, Splashscreen.class));
    }
      private View.OnClickListener mbtnLogin = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (chckInternt.isNetworkAvailable() == true) {
                    if (txtusername.getText().toString().isEmpty() || txtpassword.getText().toString().isEmpty()) {
                        alert.showAlertDialog(LoginActivity.this, "Login failed", "Both Username and Password required", false);
                        txtusername.setText("");
                        txtpassword.setText("");

                    } else {

                        setupLocation();
                    }
                } else {
                    alert.showAlertDialog(LoginActivity.this, "Login failed", "Please check your internet Connection and Retry Again", false);
                    txtusername.setText("");
                    txtpassword.setText("");
                }
            }
        };
    private void setupLocation() {
        GeoLocationFinder.LocationResult locationResult = new GeoLocationFinder.LocationResult() {

            @Override
            public void gotLocation(Location location) {
                if (location != null) {

                    newLocation = new Location(location);
                    newLocation.set(location);

                    Log.d(TAG,
                            "Got coordinates, congratulations. Longitude = "
                                    + newLocation.getLongitude() + " Latitude = "
                                    + newLocation.getLatitude());
                    new Handler(Looper.getMainLooper()).post(new Runnable() {
                        @Override
                        public void run() {
                            new AttemptLogin().execute();
                        }
                    });

                } else {
                    new Handler(Looper.getMainLooper()).post(new Runnable() {
                        @Override
                        public void run() {
                            alert.showAlertDialog(LoginActivity.this, "Check Your GPS", "Restart your Application", false);

                        }
                    });
                }
            }
        };
        geoLocationFinder = new GeoLocationFinder();
        geoLocationFinder.getLocation(this, locationResult);
    }

        @Override
    protected void onPause() {
        super.onPause();
        txtusername.setText("");
        txtpassword.setText("");
    }
    class AttemptLogin extends AsyncTask<Void, Void, Void> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new TransparentProgressDialog(LoginActivity.this,R.drawable.spinner);
            pDialog.setCancelable(Boolean.FALSE);
            pDialog.show();

        }
        @Override
        protected Void doInBackground(Void... params) {
            HashMap<String, String> regId = msessionManager.getUserregidDetails();
            String registrationId = regId.get(SessionManager.KEY_Regid);
            Httpmanager hm = new Httpmanager();
            final String username = txtusername.getText().toString();
            String password = txtpassword.getText().toString();
            List params1 = new ArrayList();
            params1.add(new BasicNameValuePair(TAG_username, username));
            params1.add(new BasicNameValuePair(TAG_password, password));
            params1.add(new BasicNameValuePair(TAG_regid, registrationId));
            String jsonstr = hm.makeServiceCall(URL_Login, Httpmanager.post, params1);
            Log.d("Response: ", "> " + jsonstr);
            if (jsonstr != null) {
                try {
                    JSONObject jsonObject = new JSONObject(jsonstr);
                   if (jsonObject.getString("hasError").equals("1")) {
                        message = jsonObject.getString(TAG_MESSAGE);
                        runOnUiThread(new Runnable() {
                            public void run() {
                                alert.showAlertDialog(LoginActivity.this, "Alert", message, false);
                            }
                        });
                    }
                    else {
                        message = jsonObject.getString(TAG_MESSAGE);
                        login_data = jsonObject.getJSONArray("data");
                        for (int i = 0; i < login_data.length(); i++) {
                            JSONObject l = login_data.getJSONObject(i);
                            userName = l.getString("username");
                            userid = l.getString("userid");
                            msessionManager.createLoginSession(userName, userid);
                            Intent intent = new Intent(LoginActivity.this, DefaultMAP.class);
                            runOnUiThread(new Runnable() {

                                public void run() {
                                    Toast.makeText(getApplicationContext(), message + userName, Toast.LENGTH_LONG).show();
                                }
                            });
                            startActivity(intent);
                            finish();
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            else
            {
                Log.e("HttpManager", "Couldn't get any data from the url");
                runOnUiThread(new Runnable() {
                    public void run() {
                        Toast.makeText(getApplicationContext(),"Please check your internet Connection and Retry Again", Toast.LENGTH_LONG).show();
                    }
                });
            }
            return null;
        }
        @Override
        protected void onPostExecute(Void file_url) {
            pDialog.dismiss();
            txtusername.setText("");
            txtpassword.setText("");
        }
    }
    }

Commonutilities.java
public class CommonUtilities {
    // give your server registration url here
    static final String SERVER_URL = "http:myapp";

    // Google project id
    static final String SENDER_ID = "525761298572";

    /**
     * Tag used on log messages.
     */
    static final String TAG = "GCM";

    static final String DISPLAY_MESSAGE_ACTION =
            "com.driverapp.inis.zuber.DISPLAY_MESSAGE";

    static final String EXTRA_MESSAGE = "message";

    /**
     * Notifies UI to display a message.
     * <p>
     * This method is defined in the common helper because it's used both by
     * the UI and the background service.
     *
     * @param context application's context.
     * @param message message to be displayed.
     */
    static void displayMessage(Context context, String message) {
        Intent intent = new Intent(DISPLAY_MESSAGE_ACTION);
        intent.putExtra(EXTRA_MESSAGE, message);
        context.sendBroadcast(intent);
    }
}

Serverutility.java
public final class ServerUtilities {
    private static final int MAX_ATTEMPTS = 5;
    private static final int BACKOFF_MILLI_SECONDS = 2000;
    private static final Random random = new Random();
    /**
     * Register this account/device pair within the server.
     *
     */
    static void register(final Context context, String email, final String regId) {
        Log.i(TAG, "registering device (regId = " + regId + ")");
        String serverUrl = CommonUtilities.SERVER_URL;
        Map<String, String> params = new HashMap<String, String>();
        params.put("regId", regId);
        params.put("email", email);

        long backoff = BACKOFF_MILLI_SECONDS + random.nextInt(1000);
        // Once GCM returns a registration id, we need to register on our server
        // As the server might be down, we will retry it a couple
        // times.
        for (int i = 1; i <= MAX_ATTEMPTS; i++) {
            Log.d(TAG, "Attempt #" + i + " to register");
            try {
                CommonUtilities.displayMessage(context, context.getString(
                        R.string.server_registering, i, MAX_ATTEMPTS));
                post(serverUrl, params);
                GCMRegistrar.setRegisteredOnServer(context, true);
                String message = context.getString(R.string.server_registered);
                CommonUtilities.displayMessage(context, message);
                return;
            } catch (IOException e) {
                // Here we are simplifying and retrying on any error; in a real
                // application, it should retry only on unrecoverable errors
                // (like HTTP error code 503).
                Log.e(TAG, "Failed to register on attempt " + i + ":" + e);
                if (i == MAX_ATTEMPTS) {
                    break;
                }
                try {
                    Log.d(TAG, "Sleeping for " + backoff + " ms before retry");
                    Thread.sleep(backoff);
                } catch (InterruptedException e1) {
                    // Activity finished before we complete - exit.
                    Log.d(TAG, "Thread interrupted: abort remaining retries!");
                    Thread.currentThread().interrupt();
                    return;
                }
                // increase backoff exponentially
                backoff *= 2;
            }
        }
        String message = context.getString(R.string.server_register_error,
                MAX_ATTEMPTS);
        CommonUtilities.displayMessage(context, message);
    }

    /**
     * Unregister this account/device pair within the server.
     */
    static void unregister(final Context context, final String regId) {
        Log.i(TAG, "unregistering device (regId = " + regId + ")");
        String serverUrl = SERVER_URL + "/unregister";
        Map<String, String> params = new HashMap<String, String>();
        params.put("regId", regId);
        try {
            post(serverUrl, params);
            GCMRegistrar.setRegisteredOnServer(context, false);
            String message = context.getString(R.string.server_unregistered);
            CommonUtilities.displayMessage(context, message);
        } catch (IOException e) {
            // At this point the device is unregistered from GCM, but still
            // registered in the server.
            // We could try to unregister again, but it is not necessary:
            // if the server tries to send a message to the device, it will get
            // a "NotRegistered" error message and should unregister the device.
            String message = context.getString(R.string.server_unregister_error,
                    e.getMessage());
            CommonUtilities.displayMessage(context, message);
        }
    }

    /**
     * Issue a POST request to the server.
     *
     * @param endpoint POST address.
     * @param params request parameters.
     *
     * @throws IOException propagated from POST.
     */
    private static void post(String endpoint, Map<String, String> params)
            throws IOException {

        URL url;
        try {
            url = new URL(endpoint);
        } catch (MalformedURLException e) {
            throw new IllegalArgumentException("invalid url: " + endpoint);
        }
        StringBuilder bodyBuilder = new StringBuilder();
        Iterator<Entry<String, String>> iterator = params.entrySet().iterator();
        // constructs the POST body using the parameters
        while (iterator.hasNext()) {
            Entry<String, String> param = iterator.next();
            bodyBuilder.append(param.getKey()).append('=')
                    .append(param.getValue());
            if (iterator.hasNext()) {
                bodyBuilder.append('&');
            }
        }
        String body = bodyBuilder.toString();
        Log.v(TAG, "Posting '" + body + "' to " + url);
        byte[] bytes = body.getBytes();
        HttpURLConnection conn = null;
        try {
            Log.e("URL", "> " + url);
            conn = (HttpURLConnection) url.openConnection();
            conn.setDoOutput(true);
            conn.setUseCaches(false);
            conn.setFixedLengthStreamingMode(bytes.length);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type",
                    "application/x-www-form-urlencoded;charset=UTF-8");
            // post the request
            OutputStream out = conn.getOutputStream();
            out.write(bytes);
            out.close();
            // handle the response
            int status = conn.getResponseCode();
            if (status != 200) {
              throw new IOException("Post failed with error code " + status);
            }
        } finally {
            if (conn != null) {
                conn.disconnect();
            }
        }
      }
}

A: Larry tried your got but not able to find the error. Add google play services  to your project and try getDeviceToken() method.
  private void getDeviceToken() {
    GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(context
            .getApplicationContext());

    String deviceToken = null;
    try {
        deviceToken = gcm.register(Constants.Project_ID);
    } catch (IOException e) {
        e.printStackTrace();
    }
    Log.i("GCM", "Device token : " + deviceToken);
    if (deviceToken == null) {
        System.out.println("null");
        getDeviceToken();
    } else {
        System.out.println("device"+deviceToken);
        // save registeration ID here

    }
}

For more information, try these links Android hive
push-notifications-in-android-platform


text:
Q: Why does bool and not bool both return true in this case? This is my code:
#include <cstring>
#include <iostream>
int main() {
    bool a;
    memset(&a, 0x03, sizeof(bool));
    if (a) {
        std::cout << "a is true!" << std::endl;
    }
    if (!a) {
        std::cout << "!a is true!" << std::endl;
    }
}

It outputs:
a is true!
!a is true!

It seems that the ! operator on bool only inverts the last bit, but every value that does not equal 0 is treated as true. This leads to the shown behavior, which is logically wrong. Is that a fault in the implementation, or does the specification allow this? Note that the memset can be omitted, and the behavior would probably be the same because a contains memory garbage.
I'm on gcc 4.4.5, other compilers might do it differently.

A: The standard (3.9.1/6 Fundamental types) says:

Values of type bool are either true or false.
....
Using a bool value in ways described by this International Standard as "undefined," such as by examining the value of an
  uninitialized automatic object, might cause it to behave as if it is neither true nor false.

Your program's use of memset leads to undefined behaviour. The consequence of which might be that the value is neither true nor false.

A: It's not "logically wrong", it's undefined behaviour. bool is only supposed to contain one of two values, true or false. Assigning a value to it will cause a conversion to one of these values. Breaking type-safety by writing an arbitrary byte value on top of its memory (or, as you mention, leaving it unintialised) will not, so you might well end up with a value that's neither true nor false.

A: Internally it is likely using a bitwise not (~ operator) to invert it, which would work when the bool was either zero or all ones:
 a = 00000000 (false)
!a = 11111111 (true)

However if you set it to three:
 a = 00000011 (true)
!a = 11111100 (also true)


text:
Q: Why are serializing instructions inherently pipeline-unfriendly? Why are serializing instructions inherently pipeline-unfriendly?
On this other answer [ Deoptimizing a program for the pipeline in Intel Sandybridge-family CPUs ] was stated this:

Time each iteration independently, with something even heavier than RDTSC. e.g. CPUID / RDTSC or a time function that makes a system call. Serializing instructions are inherently pipeline-unfriendly.

I think it should be the opposite. Serialized instructions are very good for pipe line. For example,
sum = 5 * sum;
sum = 5 * sum;
sum = 5 * sum;
sum = 5 * sum;
sum = 5 * sum;
sum = 5 * sum;
sum = 5 * sum;

Assembly by g++ main.cpp -S
addl    %edx, %eax
movl    %eax, -4(%rbp)
movl    -4(%rbp), %edx
movl    %edx, %eax
sall    $2, %eax
addl    %edx, %eax
movl    %eax, -4(%rbp)
movl    -4(%rbp), %edx
movl    %edx, %eax
sall    $2, %eax
addl    %edx, %eax
movl    %eax, -4(%rbp)
movl    -4(%rbp), %edx
movl    %edx, %eax
sall    $2, %eax
addl    %edx, %eax
movl    %eax, -4(%rbp)
movl    -4(%rbp), %edx
movl    %edx, %eax
sall    $2, %eax
addl    %edx, %eax
movl    %eax, -4(%rbp)
movl    -4(%rbp), %edx
movl    %edx, %eax
sall    $2, %eax
addl    %edx, %eax
movl    %eax, -4(%rbp)
movl    -4(%rbp), %edx
movl    %edx, %eax
sall    $2, %eax
addl    %edx, %eax

Is much better for pipe line, instead of:
for( int i = 0; i < 7; i++ )
{
    sum = 5 * sum;
}

sum = sum + 5;

Assembly by g++ main.cpp -S
    movl    $0, -4(%rbp)
    movl    $0, -8(%rbp)
.L3:
    cmpl    $6, -8(%rbp)
    jg  .L2
    movl    -4(%rbp), %edx
    movl    %edx, %eax
    sall    $2, %eax
    addl    %edx, %eax
    movl    %eax, -4(%rbp)
    addl    $1, -8(%rbp)
    jmp .L3
.L2:
    addl    $5, -4(%rbp)
    movl    $0, %eax
    addq    $48, %rsp
    popq    %rbp

Because each time the loop goes:

*

*Is need to perform a if( i < 7 )

*Adding branch prediction, for the above loop we could assume the first time the prediction will fail

*The instruction sum = sum + 5 will be discarded.

*And the next time the pipe line will do sum = 5 * sum,

*Until the condition if( i < 7 ) fail,

*Then the sum = 5 * sum will be discarded

*And sum = sum + 5 will be finally processed.

A: You confused "serialized" with "serializing." A serializing instruction is one that guarantees a data ordering, i.e. everything before this instruction happens before everything after this instruction.
This is bad news for super-scalar and pipelined processors which usually don't make this guarantee and have to make special accomendations for it, e.g. by flushing the pipeline or by waiting for all execution units to be finished.
Incidentally, this is some times exactly what you want in a benchmark as it forces the pipeline into a predictable state with all execution units being ready to execute your code; no stale writes from before the benchmark can cause any performance deviations.

A: I think he meant serialization as dependency.
sum = 5 * sum;
sum = 5 * sum;
sum = 5 * sum;
sum = 5 * sum;
sum = 5 * sum;
sum = 5 * sum;
sum = 5 * sum;

would be slower than parallel version:
sum1 = 5 * sum1;
sum2 = 5 * sum2;
sum1 = 5 * sum1;
sum2 = 5 * sum2;
sum1 = 5 * sum1;
sum2 = 5 * sum2;
sum1 = 5 * sum1;
sum = sum2*sum1;

because there are multiple pipelines and each pipeline can work on multiple instructions in flight so there could be sum1 sum2 ... sum8 many accumulators issued at the same time.
If serializer instructions are long enough, it makes pipeline ready for measurement after N cycles since new instructions cannot start without completing the last one(for serializer instructions).


text:
Q: How to call events method after new event source in FullCalendar.js? I am trying to create a client side filter for events, I have gone with the same approach of addEventSource. I use the events method to conditionally render the events. I just wanna know how to call the events method or even redefine it?
This is the initial code I am using to render the the calendar
        $('#calendar').fullCalendar({
            header: {
                left: 'prev,next today',
                center: 'title',
                right: 'month,basicWeek,basicDay'
            },
            displayEventTime: false,
            navLinks: true, // can click day/week names to navigate views
            editable: true,
            eventLimit: true, // allow "more" link when too many events
            events: (start, end, timezone, callback) => {
                $.ajax({
                    url: 'get-events',
                    dataType: 'json',
                    data: {
                        // our hypothetical feed requires UNIX timestamps
                        start: start.unix(),
                        end: end.unix()
                    },
                    success: function (res) {
                        console.log(res)
                        var events = [];
                        res.map((value, index) => {
                            if (value.cadence != null) {
                                $("#allDropdown").append(`<a id="file-${value.dq_datafile_id}" onclick="selectThis(this)" href="#about">${value.data_file_name}</a>`)
                            }

                            if (value.cadence == "WEEKLY") {
                                if (value.dqfeed__file_status == "RECEIVED") {
                                    const data_file_name = value.data_file_name;
                                    let repeatDay = dow_handler.hasOwnProperty(data_file_name) ? dow_handler[data_file_name] : undefined

                                    events.push({
                                        title: `${value.data_file_name}`,
                                        start: '2020-04-13',
                                        dow: [repeatDay, 1],
                                        color: '#00ff00'
                                    });
                                }
                           });
                       });
                    });

This is the code I am using to fetch new events or filtered events
    const applyCalendarFilter = () => {
        var filter = {
            type: 'get',
            url: 'filter-events',
        }
        $("#calendar").fullCalendar('addEventSource', filter);
    }

The error I get is Uncaught TypeError: Cannot read property 'hasTime' of undefined because the JSON returned doesn't have a start_date or end_date

A: So I found removeEvents that will clear all the events from the calendar and renderEvents that takes an option argument events and this will render the rest of the events.
So here's the code that did this.
const applyCalendarFilter = () => {
    var filter = {
        type: 'get',
        url: 'filter-events',
    }
    $("#calendar").fullCalendar('removeEvents');
    $.ajax({
            url: 'filter-events',
            type: 'get',
            success: (res) => {
                let events = [];
                res.map((value, index) => {
                    if (value.cadence == "WEEKLY"){
                        events.push({
                            'title': value.title,
                            'start_date': value.start_date,
                            'end_date': value.end_date
                    }
                })
                $("#calendar").fullCalendar('renderEvents', events);
            }, error: (res) => {
                alert('cant get the data');
            }
    )};


text:
Q: How to upload 3 attachments to current post? I have a form which updates a post but when updating I need to be able to also upload 3 posts:

    <input class="form-control" type="file" tabindex="3" name="custom-upload1" id="custom-upload2" />
    <input class="form-control" type="file" tabindex="3" name="custom-upload2" id="custom-upload2" />
    <input class="form-control" type="file" tabindex="3" name="custom-upload3" id="custom-upload3" />

The post I am updtaing is a draft which I then make it publish and within the same form I need to be able to also change the title, so within the same template I also have:

    <input id="theTitle" class="form-control" type="hidden" name="inputTitle" value="<?php echo $myTitle; ?>" autocomplete="nope">

<?php if ($post->post_author == $current_user->ID) {
    toPubblish($post->ID); ?>
    <input type="hidden" value="ok" name="pubblish">
    <?php
        if ( get_post_status ($post->ID) == 'publish' ) {
        } else { ?>
            <input id="upTitle" type="submit" name="newTitle" value="BUONA SERATA" class="btn secondary-btn primary-bg">
    <?php }
} ?>

And then I do
if($_SERVER['REQUEST_METHOD']=="POST") {
    if ('BUONA SERATA' === ($_POST['newTitle'])) {

        $post = array(
            'ID' => $id,
            'post_title' => $_POST['inputTitle']
        );
        wp_update_post($post, true);

        if ($_FILES['postImage']) {
            foreach ($_FILES as $file => $array) {
                if ($_FILES[$file]['error'] !== UPLOAD_ERR_OK) {
               //Add your error action
                } else {
                    $attach_id = media_handle_upload( $file, $post->ID );
                }
            }
        }
        if ($attach_id > 0){
          update_post_meta($post,'bgc_event_pimg',$attach_id);
        }

        ob_start(); //this should be first line of your page
        $myurl = get_site_url();
        header('Location: '.$myurl."/profile/");
        ob_end_flush(); //this should be last line of your page
    }
}

And in function I have:
function insert_attachment($file_handler,$post_id,$setthumb='false') {

  // check to make sure its a successful upload
  if ($_FILES[$file_handler]['error'] !== UPLOAD_ERR_OK) __return_false();

  require_once(ABSPATH . "wp-admin" . '/includes/image.php');
  require_once(ABSPATH . "wp-admin" . '/includes/file.php');
  require_once(ABSPATH . "wp-admin" . '/includes/media.php');

  $attach_id = media_handle_upload( $file_handler, $post_id );

  if ($setthumb) update_post_meta($post_id,'_thumbnail_id',$attach_id);
  return $attach_id;
}

But the images are uploading but are not attaching to current posts and I cannot see them if I see the posts


text:
Q: Can I use a coaxial cable as a DC power cable (without using it as a signal cable)? On my balcony I have a satellite dish and two coaxial cables attached to it. I don't use that dish, and I want to remove it and reuse those coaxial cables to power some other device on the balcony (a kind of IoT stuff).
Can I send DC power over that coaxial cable? If yes, then can I use a single cable and its centre wire as positive and outer wire mesh and foil as ground?
EDIT: my dish has LNB sign on it if it matters:

A: Yes, you can. In fact, using coaxial cables to deliver power to small-scale electronics is a common engineering practice, with all corresponding approvals (EA, UL, etc). You can combine DC on coax even with AC signal transmission if you need. All TV cable amplifiers (usually located on attic) use this method of delivering DC over a single coax cable.
Using outer shield of coax cable as negative end of supply makes a lot of practical sense since it is frequently exposed at connectors and junction boxes, and it is advisable to maintain it as common ground.

A: Yes, this should work fine.  Even in its original application, the coax was probably carrying a DC bias to power the LNB on the satellite dish.
Assuming it's RG-6 cable, it should be good for at least 3 amps.
It's considered conventional to use the shield as ground and the core as +V, though it doesn't particularly matter from a functional point of view.

A: RG-6 coax has a 18-gauge center conductor, and exhibits a resistance of 6.385mOhm per foot. Its insulation is suitable for a max of around 10A, but it may get too hot before that. Typical satellite TV operates at voltages between 13v and 18v. At 18v, a 200ft long RG6 will allow up to ~14A. However at 10A, the voltage drop is about 7.8v, so your mileage will vary.
So, yes, it is entirely suitable to carry power. That is after all what it does in a satellite TV setup. The set-top box powers the LNB through the coax.


text:
Q: OutOfMemoryException when large number of Unit Tests in a Resharper Unit Test session I am working on a large C# project with 1000+ unit tests. When I run all the test of the project in a session, after 10-12 mins many tests start throwing OutOfMemoryException. When I run them separately they run fine. When I run the whole session on my colleague's machine - they all run fine (and ends in 30-40 mins). Specs:
Nunit 2.6, Resharper 2017.1,  VS 2013, Win8, 16GB RAM, 8 logical processors


text:
Q: Sample from smoothed data I have a very  noisy function that I can smooth (following the answer given here How to smooth a curve in the right way?) using scipy.signal.savgol_filter. The original and smoothed data look like this (blue and red, respectively):

The issue is that I need to sample from the smoothed data, that is: I need to evaluate the red curve at arbitrary x values. The savgol_filter function only gives me back an array of values, not a function that I can evaluate.
What is the fastest way (it will be sampled millions of times) to do this?

MVCE
import numpy as np
from scipy.signal import savgol_filter
import matplotlib.pyplot as plt

# Noisy data
y = np.array([-5715.75, -5592.3 , -5548.33, -5638.97, -5586.43, -5703.21,
       -5660.6 , -5714.96, -5637.59, -5599.72, -5631.14, -5684.31,
       -5586.08, -5617.43, -5629.58, -5530.08, -5540.53, -5475.53,
       -5505.21, -5500.96, -5500.58, -5474.65, -5462.45, -5443.82,
       -5441.77, -5463.53, -5512.18, -5395.85, -5389.87, -5432.94,
       -5366.31, -5284.45, -5176.52, -5221.89, -5182.52, -5084.92,
       -5084.3 , -4972.78, -4968.32, -4818.19, -4789.56, -4872.02,
       -4809.45, -4855.06, -4806.77, -4717.93, -4741.29, -4822.45,
       -4760.51, -4698.31, -4744.1 , -4797.08, -4777.43, -4785.02,
       -4687.61, -4820.73, -4753.5 , -4777.99, -4812.5 , -4856.53,
       -4859.69, -4905.37, -4838.71, -5058.49, -5053.58, -5057.  ,
       -5159.58, -5155.03, -5079.21, -5228.57, -5257.26, -5409.64,
       -5505.87, -5511.82, -5471.4 , -5478.47, -5530.9 , -5578.88,
       -5705.87, -5633.66, -5740.72, -5760.05, -5801.39, -5808.52,
       -5803.22, -5832.76, -5867.51, -5837.56, -5923.97, -5933.75,
       -5945.04, -5932.16, -5909.68, -5951.29, -5958.6 , -5958.07,
       -5970.75, -5931.93, -5947.53, -5956.36])
x = np.linspace(0., 6, 100)

# Smoothed data
yhat = savgol_filter(y, 51, 3)

plt.plot(x, y)
plt.plot(x, yhat, color='r')
plt.show()

A: Use scipy's interp1d function:

x and y are arrays of values used to approximate some function f: y = f(x). This class returns a function whose call method uses interpolation to find the value of new points.

from scipy.interpolate import interp1d

y_ = interp1d(x, yhat)

new_x_vals = np.array([0.0001, 1.011, 2.022, 3.033, 4.044])
>>> y_(new_x_vals)
array([-5590.20368685, -5576.9338028 , -5140.41553793, -4749.82520031,
       -5153.81189525])


text:
Q: How to correctly store array of strings into array (In C)? *Edited*
Essentially, in a program I am writing I have initialised the following:
char **cmd[16];
cmd[15] = '\0';

I then loop through an piped in text file which contains lines of text. For example, when executing the program I will run ./a.out < file.txt
Within this loop, I break each line of the file into strings and store them in char *arguments[].
For example, the line of text "ls -n 5" creates arguments = {"ls", "-n", "5", NULL}
I then assign the pointer to arguments to an index of cmd based on the line number. I.e, cmd[line_number] = arguments;
My problem arises when I exit the while loop. Every index of cmd now points to the exact same thing, since what arguments points to has been changed. So even if I have a text file with:
ls -s1
sort -n
ls -n 5

cmd will contain 3 arguments, which all have the last line {"ls", "-n", "5", NULL}
My question is whether there's a way I can assign the current value of arguments to cmd[line_number], without the value inside being overridden in the next iteration.
The following is the relevant code:
int main(int argc, char **argv) {

    char ** cmd[16];
    cmd[15] = '\0';

    char buffer[256];

    int number_of_lines = 0;

    // Initialise arguments
    char * arguments[256];

    // Read until EOF
    while (fgets(buffer, sizeof(buffer), stdin) != NULL) {

        // tokenise buffer into arguments
        // E.g. "Hello World" => arguments = {"Hello", "World", NULL}
        parsecmd(buffer, arguments);

        // Points to arguments
        cmd[number_of_lines] = arguments;

        number_of_lines++;
    }
    return 0;
}

Here is the parsecmd function as well:
void parsecmd(char *buffer, char **arguments) {

    // Get Pointer to \n in string
    char *newline = strchr(buffer, '\n');
    // Remove if found
    if (newline) {
        *newline = 0;
    }

    int i = 0;
    int token_count = 1;
    // token equal to first to first string before whitespace in buffer
    char * token = strtok(buffer, " ");

    // While tokens remain
    while (token != NULL) {
        // Store token in arguments
        arguments[i] = token;

        // Get next token
        token = strtok(NULL, " ");

        // Increment counters
        i++;
        token_count++;
    }

    // Assign all unnasigned variables to NULL
    for (i = token_count - 1; i < 256; i++) {
        arguments[i] = NULL;
    }
}

Any help or suggestions would be much appreciated :)

A: suggest replacing:
printf("%s\n", cmd[0][0]);

with:
printf("%s\n", args[0]);

because the output format specifier: %s is expecting a pointer to the string, not the first char of the string


text:
Q: Problems starting Excel from .Net application I have a .Net 4 web application which opens excel and inserts some data from SQL Server. All works fine on local dev machine.
When I transferred it on to a laptop to show the user however, when I click the command button to open excel and export the data, excel does not open but the workbook is locked making it look like something is trying to happen.
The only difference I can see is the code is looking to open a .xls but the laptop has office 2010 (the dev machine had 2010 and 2003) so opens the .xls in compatibility mode when I open it manually.
Other than reworking the code is there anything I can configure on the laptop to get excel to open as is?
Don't have access to the source at the moment so can't post any code.


text:
Q: CDF deployment issues For a class I am teaching I would like to deploy CDFs on a website (BlackBoard-driven, if it matters), and I am running into two issues at this point:
A) I would like to have the CDFs styled according to a custom stylesheet of mine, but this only seems to work if that stylesheet is present on the target computer. I did follow the workflow suggested here, but I still get a message saying

The stylesheet "" depends upon a stylesheet named "name.nb" which
  cannot be found by the Wolfram System.

and no styles are applied to the content of the CDF.
B) When someone clicks on the link to a CDF, the results look disastrous: Not only are there no styles applied at all, but the CDF Player toolbar itself is messed up, like so:

I note that this does not happen if I provide a link to a notebook; it's only CDFs that result in the broken CDF Player toolbar.
If I choose "Web embeddable..." during the CDF creation process, things go a little better, in that in this case I get a CDF that seems to have style information embedded. However, the browser plugin opens the CDF such that it fits the entire document in the browser window so no scrolling is required, which makes the CDF (and its toolbar) unreadable. In addition, if I open the CDF file that's created directly, while I do get a properly styled layout, but with all input cells revealed and open.
Ideally, what I would like is for people to see a nice rendering, with styles applied, of the CDF in the same way I see it if I click on the "Open in Player" icon. I guess my question is, what is the secret to producing a usable CDF? Is this possible? The methods provided by the frontend interface certainly do not result in such CDFs.
Update:
I spent more time troubleshooting this, and here's my latest findings:
I realized that I don't really understand the mechanics of embedding stylesheets into notebooks at all. It appears that somehow, and I really don't know how that happened, I was able to create a notebook that has the stylesheet information embedded. If I open this on a machine with the stylesheet in question, I get a "ding" when opening it, but no error messages, and the styling is applied as it should. However, I have another notebook, that I had thought I had treated the same, and this one insists on the stylesheet being present, or else it will not format correctly.
By now I'm pretty sure that one of the fundamental questions here is: Why the hell is there no straightforward way to embed entire custom stylesheets in a notebook? You know, something as amazingly nifty as a menu item saying "Embed style definitions in this notebook". What this function would do is simply copy all of the style definitions in the notebook's custom Stylesheet into its private style definitions, and then switch the stylesheet in use to the Standard Stylesheet. This way we will have created a portable notebook that will render its styles the same on any machine with a standard Mathematica installation.
I also found that the CDFs produced as "Standalone" or "Web embedded" versions are quite different, and that I get yet a third version if I use the Save button in the CDF player from within the browser. I can find no rhyme or reason behind any of these.

A: Alright, I am going to answer my own question:
On issue A, a possible workflow is the following:

*

*Create the CDF source notebook using the intended custom Stylesheet

*In the new notebook, switch to Mathematica's Default Stylesheet

*Open the notebook file for the custom Stylesheet, and copy all of its cells

*In the new CDF source notebook, go to "Edit Stylesheet..." and then paste all of the cells copied in Step 3 into the Private Style definitions

It's a bloody hassle, and Wolfram should have provided a menu item to do this in the frontend, but it is what it is...
On issue B, it turns out that the function CDFDeploy does what I want, and by default creates a CDF that does not show the input cells. In addition, it allows me to modify the WindowSize of the CDF it creates, which solves the browser issue I saw.
As an aside, the way the CDF display in the browser is handled is very strange. The plugin always scales the document so the window height (as given by WindowSize)fills the available height of the browser window. To do so, it will scale the document just like a Magnification would. There is a magnification button on the toolbar of the CDF plugin, but this has no effect whatsoever. Also, the browser-provided zoom setting has no effect. Thus one really has to play with the WindowSize setting to try and find one that works alright on most computers. My guess is that someone with a high-resolution screen will be in trouble when trying to view a CDF produced in this way on a machine with a standard screen, and vice versa. Well, we already know that Wolfram never bothered to get Mathematica to display correctly on PCs.

A: I can answer on that:

Why the hell is there no straightforward way to embed entire custom stylesheets in a notebook?

Don't hack this on any important document!
Open the notebook where you want to embed style with a text editor, look for a line like
StyleDefinitions->"myJournalArticle.nb"

Find this file in your system.  It could be anywhere in $Path but if you have installed the style it will be in $UserBaseDirectory/Mathematica/SystemFiles/FrontEnd/StyleSheets.
Copy the part NoteBook[___] and paste it in the first notebook instead of "myJournalArticle.nb".
If you like the method, it can probably be automated it in Mathematica with NotebookOpen etc.
This question should be updated because with v12 CDF is supposed to be useless (so writes the CDF save dialog).


text:
Q: How to use "allow-return-values="true"" in TestNG test methods? I am beginner to TestNG. I about test method in official TestNG documentation. I am not clear with the use of allow-return-values="true" can any one explain it briefly with example. I did one example I didn't get way the way of using,
This is my .xml
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >

<suite name="newSuite" parallel="methods" thread-count="5" allow-return-values="true">
<parameter name="browser" value="Firefox"></parameter>
<test name="dataprovider" allow-return-values="true">
   <classes>
      <class name="com.tets.SampleTest"></class>
   </classes>
</test>
</suite>

and my test class is as follows,
public class SampleTest {

@AfterMethod
public void teardown(Object returnValueFromTest){
    //inspect returnValueFromTest and perform necessary clean up.
}

@Test
public String testEventGeneration(){
    //generate event

    //returning generated e vent id.
    return "E1234";

}

@Test
public String testMarketGeneration(){
    //generate market

    //returning generated market.
    return "hai";
}}

How and where can I get the return value from testMarketGeneration test method ?

A: The option 'allow-return-values' is not meant to test the return value "hai". It is meant to allow @Test annotation on methods that have return values.
By default TestNG follows best practices for unit testing, which means a unit test method should not have a return value. However sometimes you want to add the @Test annotation to a method with a return value. If you do not specify 'allow-return-values' in your Suite configuration TestNG will print out a warning and will not run the method as tests.
The warning TestNG gives is something like:

Method public java.util.List a.B.getC(java.util.List) has a @Test annotation but also a return value: ignoring it. Use 'suite allow-return-values="true"' to fix this

The only useful example of allowing return values I have found so far is when your test class implements a certain interface and you want to test all interface methods by adding @Test annotations.
See http://testng.org/doc/documentation-main.html for the real documentation.


text:
Q: Accessing a server as localhost? I use ssh keys to access a server at lets say 200.200.200.200. It works fine. How can i access that server in my host as 127.0.0.1?
I have tried my best but couldn't make it work.

A: You normally do this via port forwarding so you forward the remote port (the one from the server) that you are interested in to your local machine. Then you can access it via 127.0.0.1:
Example tutorial:
https://help.ubuntu.com/community/SSH/OpenSSH/PortForwarding
In putty it is also straight forward:
http://www.cs.uu.nl/technical/services/ssh/putty/puttyfw.html
You could also modify your local hosts file to point to this server but that often causes hick ups with local services.


text:
Q: Use current theme backgroundcolor in layout file I have 2 Themes, a dark and a bright one. I want to get the current themes background color and use it in a layout file like this:
<View
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:background="(backgroundColor)" />

Let's say (backgroundColor) is the current themes background color. What do I have to put in there instead of (backgroundColor)?

A: The correct answer to your question would probably be?android:colorBackground. But you might still want to use ?android:windowBackground on some occasions.
While windowBackground will be the background of your activity, colorBackground seems like the default background color for your content.
In your case you would end up like the following:
<View
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:background="?android:colorBackground" />

For a full list of those "default" theme attributes you can check out the source code of the basic Android themes.xml

A: use  android:theme
<View
    android:theme="@style/yourTheme"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

and in your values\styles.xml
 <style name="yourTheme" parent="AppTheme">
        <item name="android:background">@color/green</item>
 </style>

Edit: Please try to post your full question at the first time and if you make a change try to add it under edit section.  People who love to help you gets in trouble otherwise.
For your edited question already has an answer here

You can get the background color (or Drawable) from the current theme
  by:
TypedValue a = new TypedValue();
getTheme().resolveAttribute(android.R.attr.windowBackground, a, true);
if (a.type >= TypedValue.TYPE_FIRST_COLOR_INT && a.type <= TypedValue.TYPE_LAST_COLOR_INT) {
    // windowBackground is a color
    int color = a.data;
} else {
    // windowBackground is not a color, probably a drawable
    Drawable d = activity.getResources().getDrawable(a.resourceId);
}

and set it to your view!


text:
Q: How to enable auto-screen update on monitor plug-in/out on Lubuntu (Also, how can this be achieved in Ubuntu)? I have a laptop which I want to have connected to an external monitor 99% of the time. The other 1% I would use its screen. I want the laptop to be closed (usually) to save space, and to use external KB/mouse. The external monitor supports a higher resolution than the laptop screen, so I won't use screen duplication, and extended desktop is annoying when one of the monitors can't be viewed, so also out of the question.
Is there a simple way to enable the external only configuration, but that would switch to the internal monitor when the external monitor is disconnected, like regular Ubuntu/Windows/etc provide?
In addition/alternatively, What software does regular Ubuntu or other linux distros use to enable this?

A: It is probably a Gnome or Unity feature which is absent from LXDE. You could probably write a udev rule to do this on monitor disconnect.
I have written a little script that will detect the monitors and extend accordingly:
#!/usr/bin/env bash

xrandr | grep VGA | grep -w connected >/dev/null
echo $?
if [[ "$?" -lt 1 ]]
then
    notify-send "Extending desktop to VGA screen"
    xrandr --output DP-3 --auto --output VGA-0 --auto --right-of DP-3 --primary
else
    xrandr | grep DP-2 | grep connected >/dev/null
    if [[ "$?" -gt 0 ]]
    then
    notify-send "Extending desktop to DisplayPort screen"
    xrandr --output DP-3 --auto --output DP-2 --auto --right-of DP-3 --primary
    else
    notify-send "No known screens found"
    fi

fi

You need to have xrandr installed but you almost certainly do. You will also need to change the monitor names accordingly (in my case I switch between an external VGA and and external Display Port display). Run xrandr with your external screen connected to getthe right name or update your question with the output of xrandr and I can help you with it.
I have mapped this script to be run with a keyboard shortcut and simply run it whenever I connect or disconnect a screen.

A: You can use autorandr to save both settings and let autorandr change the settings when you plug/unplug your screen. If it does not work automatically, use autorandr -c to force detection of the current setting.