text:
Q: Is there a way to print value from internal code in Cucumber Report? Is there any way to print out some internal code values from Java code to appear in Cucumber Report?
There is one integer value inside step definition file of Cucumber that is being implemented on Java code (transaction ID) which I need to display on Cucumber Report. Usually the Cucumber report only displays the Gherkin language of feature files.
Is there any way that I can display transaction ID on Cucumber Report?
Thanks in advance!

A: You can use Cucumber Hooks to get the scenario and then use log on it.
Something like:
class Steps {
    Scenario scenario;

    @Before
    public void beforeScenario(Scenario scenario) {
        this.scenario = scenario;
    }

    @Then("Internal Data is logged")
    public void logging() {
        scenario.log("transactionId");
    }
}


text:
Q: Selenium - getBodyText() return empty string I'm trying to save the whole html page with getBodyText into a String and then write it to a file (.txt). However when I check the file, it's empty. Here's my code:
    String store_report = selenium.getBodyText();
    File f = new File("C:/folder/" + "report" + ".txt");
    FileWriter writer = new FileWriter(f);
    writer.append(store_report);
    System.out.println("Report Created is in Location : " + f.getAbsolutePath());

A: I think you just forgot to flush the FileWriter:
writer.flush()
This of course happens automatically if you properly close the FileWriter.

A: Well first, I'd strongly encourage you to consider a try/finally block which closes that FilreWriter :)
Can you confirm you see the getBodyText() command actually being sent to the Selenium server? Have you seen it run in the command log that is embedded inside the browser? Do you have a public URL that reproduces the problem?

A: Thanks everyone for your help. I think what happened was I didn't close the FileWriter correctly, now it's working.

redpajama_set_name: RedPajamaStackExchange


text:
Q: React native web send an email I'm trying to set a function where when a button is clicked the program will send an email. I'm using react native web. so far I have tried react-native-mail. this opens an email client but when I try to run build-web, the node module for react-native-mail can't be minified. I've also tried react-native-communications but I get an error as well. Are there any methods I'm missing?

A: react-native-mail is a native module. As in react-native-web, you are running javascript code in the browser environment. It's not possible to run native code in the browser.
In this case, I'd suggest you write a specific component for web browser, and create an <a> element with a mailto: href attribute to invoke the system email client.


text:
Q: sum of reciprocals is $1$ (diophantine) My exploration of this recent question

$\qquad$Proving $P$ for $N(n+N-1)$$\qquad$

provoked the following (speculative)
Conjecture:

If $a_1,...,a_m$ are positive rational numbers whose sum is an integer, and the sum of whose reciprocals is $1$, then $a_1,...,a_m$ must be integers.

Partial results:

*

*$\;$For $m=1$, the conjecture holds, and the proof is trivial.

*$\;$For $m=2$, the conjecture also holds, and the proof is easy.

*$\;$For $m=3$, while I don't have a proof, limited testing suggests that the conjecture holds.

Remarks:

*

*If the conjecture is true, a proof for the general case (arbitrary $m$) might be very hard.

*Or perhaps there's an easy counterexample.

To test the waters, can anyone resolve the conjecture for the case $m=3\,?$

A: $${10\over 3} + {5\over 3} + 10 = 15$$
$${3\over 10} + {3\over 5} + {1\over10} = 1$$


text:
Q: What is windows way to do `mount -o loop,rw,offset=X`? I want to mount with -o loopoffset=70254080 an  ./raspbian-jessie-lite.img  onto ./mntpt folder. The rw parameter is the key here - I need to edit .iso insides (set wifi login\password) and save it back. How to mount with rw on Windows 10?

Bash on Windows gives to me no loop back devices found error, while recomended
panda@host:~$ sudo /sbin/modprobe loop.o
modprobe: ERROR: ../libkmod/libkmod.c:556 kmod_search_moddep() could not open moddep file '/lib/modules/3.4.0+/modules.dep.bin'

so I wonder, what is free or opensource or shareware software that allows to do such loopback mount thing on Windows 10?

A: The below powershell script will take an .iso and mount it to a directory.  I assume it will work for .img, too, but am unsure if it will accept writing.
For example, $img_path of D:\my_stuff\mount_me.iso, will create a mount point at D:\my_stuff\mount_me\
Note that the command $drive.AddMountPoint requires admin privileges.
param([Parameter(Mandatory=$true, Position=1)] [string] $img_path)

##
# https://social.technet.microsoft.com/Forums/scriptcenter/en-US/d2faa6c3-35e8-4bad-8ac8-24902bbb6f1a/what-is-the-point-of-nodriveletter-in-mountdiskimage
##

$ErrorActionPreference = "Stop"

$mount_dir_path = Join-Path `
    ([System.IO.Path]::GetDirectoryName($img_path)) `
    ([System.IO.Path]::GetFileNameWithoutExtension($img_path))

if(-Not (Test-Path -Path $mount_dir_path -PathType "Container")) {
    $null = mkdir $mount_dir_path
}

$img = Mount-DiskImage -ImagePath $img_path -NoDriveLetter -PassThru
$vol = Get-Volume -DiskImage $img
$drive = Get-WmiObject "win32_volume" -Filter "Label = '$($vol.FileSystemLabel)'"
$mount_return = $drive.AddMountPoint($mount_dir_path)

if($mount_return.ReturnValue -ne 0) {
    # https://msdn.microsoft.com/en-us/library/aa384762(v=vs.85).aspx
    throw $mount_return
}

##

A: Not a windows-10 expert, but I presume that being able to use bash doesn't implies that you can use the whole GNU/linux toolchain.
No loop device on windows, as far as I know
Also, no modprobe ( this is a specific of linux kernel ), and no mount probably ( this time, a specific of some file systems )


text:
Q: Ionic Cordova inappbrowser not working in iOS I installed the inAppBrowser plugin for Ionic Cordova (at least I think I installed it correctly. I followed the directions here: https://cordova.apache.org/docs/en/latest/reference/cordova-plugin-inappbrowser/#installation).
I imported inAppBrowser into my app.module.ts file and added it to the list of providers:
import { InAppBrowser } from '@ionic-native/in-app-browser';

and
providers: [
StatusBar,
SplashScreen,
InAppBrowser,
{provide: ErrorHandler, useClass: IonicErrorHandler}
]

I also injected it into the relevant pages like this:
export class AboutPage {

options : InAppBrowserOptions = {
    location : 'yes',
    hidden : 'no',
    clearcache : 'yes',
    clearsessioncache : 'yes',
    zoom : 'yes',//Android only
    hardwareback : 'yes',
    mediaPlaybackRequiresUserAction : 'no',
    shouldPauseOnSuspend : 'no', //Android only
    closebuttoncaption : 'Close', //iOS only
    disallowoverscroll : 'no', //iOS only
    toolbar : 'yes', //iOS only
    enableViewportScale : 'no', //iOS only
    allowInlineMediaPlayback : 'no',//iOS only
    presentationstyle : 'pagesheet',//iOS only
    fullscreen : 'yes',//Windows only
};

  constructor(public navCtrl: NavController, public navParams: NavParams, private theInAppBrowser: InAppBrowser) {
  }

  public openWithSystemBrowser(url : string){
    let target = "_system";
    this.theInAppBrowser.create(url,target,this.options);
}
public openWithInAppBrowser(url : string){
    let target = "_blank";
    this.theInAppBrowser.create(url,target,this.options);
}
public openWithCordovaBrowser(url : string){
    let target = "_self";
    this.theInAppBrowser.create(url,target,this.options);
}

  ionViewDidLoad() {
    console.log('ionViewDidLoad AboutPage');
  }

}

Then I added a button into the html page using:
<button ion-button (click)="openWithSystemBrowser('https://www.preachingfriars.org')">Visit our site</button>

It seems to work great in Android, but no luck in iOS. When I click the button nothing at all happens. I have been scouring the forums for days and still can't manage to make it work. I'd appreciate any help you could provide!
Thanks!
Brent

A: The create method takes a string as options parameters and not an object.
And also you have to call the show method.
const browser = this.iab.create(targetUrl, '_self', 'location=no');
browser.show();

A: Try loading it within platform ready method.
@Component({
  templateUrl: 'app.html'
})
export class MyApp {

  browser: InAppBrowserObject;
options: InAppBrowserOptions = {
  location: 'no', //Or 'no'
  hidden: 'yes', //Or  'yes'
  zoom: 'no', //Android only ,shows browser zoom controls
  hardwareback: 'yes',
  mediaPlaybackRequiresUserAction: 'yes',
  shouldPauseOnSuspend: 'no', //Android only
  closebuttoncaption: 'Share', //iOS only
  disallowoverscroll: 'no', //iOS only
  toolbar: 'yes', //iOS only
  toolbarposition: 'bottom',
  enableViewportScale: 'no', //iOS only
  allowInlineMediaPlayback: 'no', //iOS only
  presentationstyle: 'formsheet', //iOS only
  fullscreen: 'yes', //Windows only
  suppressesIncrementalRendering: 'no',
  transitionstyle: 'crossdissolve',

};

constructor(public toastCtrl: ToastController, public actionSheetCtrl: ActionSheetController, public network: Network, public iab: InAppBrowser, public platform: Platform, statusBar: StatusBar, public splashScreen: SplashScreen) {

  platform.ready().then(() => {
    statusBar.styleDefault();
    this.openinInappbrowser();
  });

}

openinInappbrowser() {
  this.browser = this.iab.create('https://ionicframework.com', '_blank', this.options);
  this.browser.show();
  this.splashScreen.hide();
  this.browser.on('loaderror').subscribe(event => {

    this.browser.hide();
    this.presentToast('Something Wnt Wrong');
  });

}

let toast = this.toastCtrl.create({
  message: arg,
  duration: 1500,
  position: 'bottom'
});

toast.onDidDismiss(() => {
  console.log('Dismissed toast');
});

toast.present();
}
isNetavailable() {
  if (this.network.type == 'none' || this.network.type == 'unknown') {
    return false;
  } else {
    return true;
  }

}

}

A:
Options for the InAppBrowser. Optional, defaulting to: location=yes.
  The options string must not contain any blank space, and each
  feature's name/value pairs must be separated by a comma. Feature names
  are case insensitive. - https://ionicframework.com/docs/native/in-app-browser/

Here's how you could convert your options object to a string that can be used when using theInAppBrowser.create:
// ...

var optionsStr = '';

for (var key of Object.keys(this.options || {})) {
    if (optionsStr) {// Add a comma if there are any previous options to keep each key value pair seperated
        optionsStr += ",";
    }
    // Add <key>=<value> to optionsStr
    optionsStr += key + '=' + options[key];
}

// Be sure to pass a string instead of an object for options https://ionicframework.com/docs/native/in-app-browser/
// create(url: string, target: string, options: string)
this.browser = this.theInAppBrowser.create('https://ionicframework.com', '_blank', optionsStr);

// ...

A: you can try adding this in your config.xml file
plugin name="cordova-plugin-inappbrowser" spec="3.1.0" value="CDVInAppBrowser"
Add CDVInAppBrowser as the value if it is not here

A: We have to encode url, which is we are going to pass on inappbrowser methods
let encodedUrl = encodeURI(your_url);
let iab = this.iab.create(encodedUrl, '_blank');

Ionic Android app this plugins working fine. This is required for ionic iOS application,

A: you can try adding this in your config.xml file
<allow-intent href="*" />
<feature name="InAppBrowser">
        <param name="android-package" value="org.apache.cordova.inappbrowser.InAppBrowser" />
</feature>


text:
Q: Git / Gitolite Some folders empty, permissions issue? I am using git, but in a centralized manor. I have a server hosting a repo that we pull/push to. I noticed a couple of the folders in the repo when pulled/cloned on another machine are empty (noticed this when I got a new computer and cloned the repo to is). I looked on the gitolite web interface and the permissions of these folders are "m---------", where as the others are drwxr-xr-x. I am not sure how it even got this way... I have tried a few things but am not able to fix it.

A: That could be explained, in the gitweb source by:
# convert file mode in octal to symbolic file mode string
sub mode_str {
  my $mode = oct shift;

  if (S_ISGITLINK($mode)) {
    return 'm---------';
  } elsif (S_ISDIR($mode & S_IFMT)) {
    return 'drwxr-xr-x';
  } elsif (S_ISLNK($mode)) {
    return 'lrwxrwxrwx';
  } elsif (S_ISREG($mode)) {
    # git cares only about the executable bit
    if ($mode & S_IXUSR) {
      return '-rwxr-xr-x';
    } else {
      return '-rw-r--r--';
    };
  } else {
    return '----------';
  }
}

With S_IFGITLINK => 0160000, which is a special mode for submodules
Since 2007 and this patch, submodule entries are shown in gitweb:

There is only link to the history of submodule entry in the supermodule (current repository) for now, because gitweb doesn't know where to search for submodule repository objects.

So they aren't empty directories, only submodules root directories.
See "Git - easy way pull latest of all submodules" for more.


text:
Q: изменение css в зависимости от значения переменной php Цель - добиться изменения цвета каждого блока floor, в зависимости от параметра base[6], так чтобы каждый блок был разного, если и переменная возвращает другой результат, цвета
Пробовал сделать так:
    <?php
    if($base[6]=='оплачено'){ ?>

    <?php echo $base[6]; } ?>

Но результатом было выделение всех блоков.
<?php
  include_once 'connect.php';
  $query = "SELECT * FROM `work`";
  $base = mysqli_query($connect, $query);
  $base = mysqli_fetch_all($base);
?>

  <meta charset="utf-8">
  <title>main</title>

      Москва

      Этаж 1

      <?php foreach ($base as $base){ ?>

        <?php if($base[8] == "Москва"){?>

              <a href="main/update.php?id=<?= $base[0] ?>">

                  <?= $base[1] ?>  <?= $base[7] ?>кв.м

        <?php }else{pass;} ?>

      <?php } ?>


text:
Q: Search for a value in a two dimensional array I want to compare a number to a dimensional array. I think that my problem is here, but I dont know why it cannot compile because of this.
if(a[j].equals(numb)){

A: That's because a[j][i] is int and no Integer, it means that you can't compare it with .equals() since it is a primitive type, you have to use ==
Furthermore, you are comparing a[j] with an int but a[j] is an array, you have to access its int with double [][] : a[i][j]

A: Why dont you just write a[j] == numb ? Since a[j] and numb are both integers, that should work just fine. equals() is a method for objects, which you could call for Integers for instance, but not for ints.


text:
Q: Limit step-by-step explanation required I have a step by step solution of a limit, but I do not understand it. The part that I have problems with is the last line, the second term of the sum, the denominator of the fraction. How come n(n+1) can be approximated by n?
By the way wolfram gave the same answer, but step by step solution was unavailable.

A: This is $\left(1+\frac{1+x_n}n\right)^{-(1+y_n)n}$ where $x_n=\frac2{n+1}\to0$ and $y_n=\frac{4}{n-3}\to0$, and no further detail of the setting matters. Actually, the book merely uses, without mentioning it, the result  that, for every sequences $(x_n)$ and $(y_n)$ such that $x_n\to0$ and $y_n\to0$, $\lim\limits_{n\to\infty}\left(1+\frac{1+x_n}n\right)^{(1+y_n)n}=\mathrm e$. This is a generalization of the fact that $\lim\limits_{n\to\infty}\left(1+\frac1n\right)^n=\mathrm e$, with basically the same proof.

A: Use that $lim_{n \rightarrow \infty} (1+1/n)^n = e$. More precisely:
$$lim_{n \rightarrow \infty} \left(\frac{n+1}{n} + \frac{2}{n(n+1)} \right)^{\frac{n(n+1)}{3-n}}
= lim_{n \rightarrow \infty} \left( \underbrace{ \left( 1+\frac{3+n}{n(n+1)} \right)^{\frac{n(n+1)}{3+n}}}_{\rightarrow e} \right)^{ \overbrace{\frac{3+n}{3-n}}^{\rightarrow -1}} = e^{-1}$$
Note that we can "pull the limit inside the bracket" because the exponential is continuous.


text:
Q: algorithm to pick set of winners using different weights I'm attempting to design an algorithm that does the following.
Input:
I've a set of keys (total n) that are mapped to set of properties. The properties contain the weight for each property and the value for the property.
Output:
Identify a set of keys that are qualified (total k) based on the set of properties and their respective weights and values.
Additionally, the data should be modified as such in every cycle of choosing winners such that the chances of someone who was not chosen goes up in the next cycle (whereas the chances of someone who has won would be as if they are completely new in the system).
Hopefully the issue at hand is clear. Basically, the value of the property and the respective weight would determine which keys are more likely to win (a higher value with a higher weight would increase the probability of that key winning) and we will eventually end up choosing everyone.
Any input on how this can be done would be greatly appreciated.
Thanks! - Azeem

A: Consider your weights as segments of a line, with the overall line length equal to the sum of the weights. Pick a uniform random number between 0 and that length. The winner is the candidate whose segment the number falls into.
Remove that winner, and reduce the overall line length accordingly. Then repeat the process with the remaining candidates until you've chosen your k.
After the cycle, rescale the losers to occupy most of the original length and add back the winners with the remaining small chunk divided evenly between them.

A: an unoptimized but effective method would to make a list of all contestants, but append additional indexes for contestest proportional to weight.
psuedo is totally out of context of any real implementation, but you should get the idea.
const int DEFAULT_WEIGHT = 1;
public List<Contestant> items = new List<Contestant>();
public List<Guid> LotteryPool = new List<int>();

public Contestant Roll()
{
     Random rnd = new Random();
     rnd.Seed = DateTime.Now.Ticks;

     // Generate LotteryPool
     foreach(Contestant item in items)
     {
              for(int i = 0; i < item.Weight; i++)
              {
                       LotteryPool.Add(item.Id);
              }

              item.Weight++;
     }

     // Find the contestant matching a random id from the pool.
     Contestant result = FindContestant(LotteryPool[rnd.Next(0, LotterPool.Count]);

     // apply the default weight the winner
     result.Weight = DEFAULT_WEIGHT;

     return result;
}


text:
Q: Method to static method Create class A has not method full
class A{

}

Create class B has method full
class B{
   public function full(){
      echo "success";
   }
}

How do?
A::full();
// success

A: First class A should extend class B so the method full will available in class A.
class A extends B
{

}

Second you have to use static keyword in method full.
public static function full()
{
    ...
}

References :
Inheritance
Static


text:
Q: WheelView change setCurrentItem doesn´t work I have a problem with WheelView using these library.  I've created a Dialog in which I want to put a WheelView, but i can't change current item and I can't figure about what the problem is, code:
public class SpeedDialog extends AlertDialog implements android.view.View.OnClickListener{
    private Activity activity;
    TextView textView;
    int current = 50;

    public SpeedDialog(Activity activity, int theme) {
        super(activity, theme);
        this.activity = activity;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.speed_dialog);
        WheelView wheelView = (WheelView)findViewById(R.id.wheel_speed);
        textView = (TextView) findViewById(R.id.current_value);
        Button button = (Button) findViewById(R.id.apply);
        button.setOnClickListener(this);
        wheelView.setViewAdapter(new NumericWheelAdapter(activity, 50, 200, "%1.2f", 100));
        wheelView.addChangingListener(new OnWheelChangedListener() {
            @Override
            public void onChanged(WheelView wheel, int oldValue, int newValue) {
                setCurrent(newValue);
                textView.setText(String.valueOf(newValue));
            }
        });
        wheelView.setCurrentItem(getcurrent());
    }

    public Integer getcurrent() {
        return current;
    }

    public void setCurrent(int current) {
        this.current = current;
    }
   @Override
    public void onClick(View v) {
        switch (v.getid()) {
            case R.id.apply:
                dismiss();
                break;
        }
    }
}

A: Solved using sharedpreferences to save and load value


text:
Q: Change start-up options for mysqld in whm on CentOS I have a WHM/Cpanel server set up on CentOS 7.6.
I need to set up my mysqld process with a start-up option --init-file, to be ran every time the service is restarted.
I assume there is a file somewhere on the server that tells WHM what options to use when starting the service mysqld. But I can't find it.
Thanks
Matt

A: Figured out that CentOS uses the systemd service initializer.
Answer:
Edit the mysqld.service file in
/usr/lib/systemd/system
Then you have to reload the systemctl daemon. Run command:
systemctl daemon-reload
Then restart mysql from WHM and it will execute the option


text:
Q: Using dlopen, how can I cope with changes to the library file I have loaded? I have a program written in C++ which uses dlopen to load a dynamic library (Linux, i386, .so).  When the library file is subsequently modified, my program tends to crash.  This is understandable, since presumably the file is simply mapped into memory.
My question is: other than simply creating myself a copy of the file and dlopening that, is there way for me to load a shared object which is safe against subsequent modifications, or any way to recover from modifications to a shared object that I have loaded?
Clarification: The question is not "how can I install a new library without crashing the program", it is "if someone who I don't control is copying libraries around, is it possible for me to defend against that?"

A: If you install a new version of the library, the correct procedure is to create a new file in the same directory, then rename it over the old one. The old file will remain while it's open, and continue to be used.
Package managers like RPM do this automatically - so you can update shared libraries and executables while they're running - but the old versions keep running.
In the case where you need to take a new version, restart the process or reload the library - restarting the process sounds better - your program can exec itself. Even init can do this.

A: It is not possible to defend against someone overwriting your library if they have file write permission.
Because dlopen memory maps the library file, all changes to the file are visible in every process that has it open.
The dlopen function uses memory mapping because it is the most memory efficient way to use shared libraries. A private copy would waste memory.
As others have said, the proper way to replace a shared library in a Unix is to use unlink or rename, not to overwrite the library with a new copy. The install command will do this properly.

A: This is an intriguing question.  I hate finding holes like this in Linux, and love finding ways to fix them.
My suggestion is inspired by the @Paul Tomblin answer to this question about temporary files on Linux.  Some of the other answers here have suggested the existence of this mechanism, but have not described a method of exploiting it from the client application as you requested.
I have not tested this, so I have no idea how well it will work.  Also, there may be minor security concerns associated with a race condition related to the brief period of time between when the temporary file is created and when it is unlinked.  Also, you already noted the possibility of creating a copy of the library, which is what I am proposing.  My twist on this is that your temporary copy exists as an entry in the file system for only an instant, regardless of how long you actually hold the library open.
When you want to load a library follow these steps:

*

*copy the file to a temporary location, probably starting with mkstemp()

*load the temporary copy of the library using dlopen()

*unlink() the temporary file

*proceed as normal, the file's resources will be automatically removed when you dlclose()

It would be nice if there were a really easy way to achieve the "copy the file" step without requiring you to actually copy the file.  Hard-linking comes to mind, but I don't think that it would work for these purposes.  It would be ideal if Linux had a copy-on-write mechanism which was as easy to use as link(), but I am not aware of such a facility.
Edit: The @Zan Lynx answer points out that creating custom copies of dynamic libraries can be wasteful if they are replicated into multiple processes.  So my suggestion probably only makes sense if it is applied judiciously -- to only those libraries which are at risk of being stomped (presumably a small subset of all libraries which does not include files in /lib or /usr/lib).

A: If you rm the library prior to installing the new one, I think your system will keep the inode allocated, the file open, and your program running. (And when your program finally exits, then the mostly-hidden-but-still-there file resources are released.)
Update: Ok, post-clarification. The dynamic linker actually completely "solves" this problem by passing the MAP_COPY flag, if available, to mmap(2). However, MAP_COPY does not exist on Linux and is not a planned future feature. Second best is MAP_DENYWRITE, which I believe the loader does use, and which is in the Linux API, and which Linux used to do. It errors-out writes while a region is mapped. It should still allow an rm and replace.  The problem here is that anyone with read-access to a file can map it and block writes, which opens a local DoS hole. (Consider /etc/utmp. There is a proposal to use the execute permission bit to fix this.)
You aren't going to like this, but there is a trivial kernel patch that will restore MAP_DENYWRITE functionality. Linux still has the feature, it just clears the bit in the case of mmap(2). You have to patch it in code that is duplicated per-architecture, for ia32 I believe the file is arch/x86/ia32/sys_ia32.c.
asmlinkage long sys32_mmap2(unsigned long addr, unsigned long len,
                            unsigned long prot, unsigned long flags,
                            unsigned long fd, unsigned long pgoff)
{
        struct mm_struct *mm = current->mm;
        unsigned long error;
        struct file *file = NULL;

        flags &= ~(MAP_EXECUTABLE | MAP_DENYWRITE); // fix this line to not clear MAP_DENYWRITE

This should be OK as long as you don't have any malicious local users with credentials. It's not a remote DoS, just a local one.

A: If you can figure out where your library is mapped into memory, then you might be able to mprotect it writeable and do a trivial write to each page (e.g. read and write back the first byte of each page).  That should get you a private copy of every page.
If 'mprotect' doesn't work (it may not, the original file was probably opened read-only), then you can copy the region out to another location, remap the region (using mmap) to a private, writeable region, then copy the region back.
I wish the OS had a "transform this read-only region to a copy-on-write region".  I don't think something like that exists, though.
In any of these scenarios, there is still a window of vulnerability - someone can modify the library while dlopen is calling initializers or before your remap call happens.  You're not really safe unless you can fix the dynamic linker like @DigitalRoss describes.
Who is editing your libraries out from under you, anyway?  Find that person and hit him over the head with a frying pan.


text:
Q: What parts of math do I need in order to understand 3d programming? ( OpenGL ) I feel like Open GL ( on Android, and generally I assume ) is not so friendly to me. It may be the API but also I miss some math skills.
For example Vectors 3D, I know some theory ( pretty low ) about them, but fail to understand clearly the practical situations in which I need to use them.
I am thrilled about 3D programming, but having some pretty low math skills ( highschool ) and some concepts from faculty, I don't even know what kind of math I need for it.
Clueless, If someone would be to ask me what kind of math would it suffice for 3D, I would say matrix, vectors, geometry and trigonometry.
But I don't where do these belong ( Basic Algebra, Calculus, etc ).
So, can someone, tell me what are all the concepts needed to understand 3D programming and also enumerate some books ( beginner ones ) on each topic?

A: What you need to learn depends on what you need to do.
For vector and matrix operations and coordinate systems you need Linear algebra. This is probably the most essential field of maths.
The rendering equation and Phong shading you need Trigonometry and integrals.
To understand rasterization you need interpolation.
If you want to define 3d shapes or textures mathematically some useful feilds of maths are trigonometry, bezier curves, splines, fractal math (depending on what kind of shape you want to define.
For some rendering effects such as bump mapping you need Partial derivatives.
Also numerical analysis is useful in many cases to understand about precision in your calculations and also how to implement some kinds of operations effectively.
I'm sure that there's a lot more that can be relevant depending on what you want to do, but these are some things that come to mind.

A: You need to have a grasp of Linear Algebra; and for the book, this one is pretty good
http://www.amazon.com/Mathematics-Programming-Computer-Graphics-Edition/dp/1435458869/


text:
Q: Referring to source code of Java project in xText I am creating a DSL in xText for modeling the functional behaviour of an application. My goal for this is to couple resource demands (e.g. number of CPU cycles, write actions on hard drive) with the functional behaviour I want to model with the DSL. The DSL is written in xText with the Eclipse IDE. The DSL syntax including comments can be found below.
For now it's a really simple DSL to model functional behaviour; combining if/else and for statements and adding libraryFunctions to them. I came up with this latter term myself; it is used to refer to actions which are the basic steps of my functional behaviour (e.g. login, encrypt, display; you can think of them as methods in a programming language). Now I would like to extent my DSL with the option to be able to refer to the source code of a Java Project. I created a small Java Program which resembles a basic program with a login screen and create account screen (see class diagram below). In order to model the functional behaviour of this program with the DSL, I want to be able to refer to certain details of the Java Program source code so that I can pull these details right from the source code and use it in the DSL. For example; suppose that I want to refer to certain methods used in the Java Program. Right now I have simple enumeration 'libraryFunctionsEnum' in my DSL, but it would be nice if I could somehow directly refer to the methods used in the source code of the Java Program (so that when I compile the DSL and use it, the xText editor automically provides a list of available methods I can refer to).
I tried to use ecore models to convert class diagrams of my Java Project and integrate them in xText, but I have the feeling that I am a bit lost on what to do. I have also looked at xBase and xTend (two languages directed towards making xText more interoperable with Java), but so far I have found that these are more focussed on automatically generating Java source code from xText models. I want to do it the other way around (refer to Java source code from an external project so that I can use these references in my DSL). I don't know if the methods I mentioned above (ecore, xBase, xTend) are even the right methods to achieve what I want. If you have some better idea or explation, then I am glad to hear it!
By the way, I am still new to xText and DSL modelling/DSL development. I might have forgotten some important details/explanations. Please let me know if you miss something.
grammar org.xtext.example.mydsl.FinalDsl with org.eclipse.xtext.common.Terminals

generate finalDsl "http://www.xtext.org/example/mydsl/FinalDsl"

Model:
    'functionName' name = STRING
    functions += FunctionElements*
;

// Function elements of which the model exists. The model can contain
// library functions, for loops, and if/else statements.
  FunctionElements:
        (
            functions += libraryFunctionsEnum |
            forLoops += ForLoops |
            ifElseStatements += IfElseStatements
        )
;

// IfElse Statements requiring if statements and optionally followed by
// one else statement.
IfElseStatements:
    ifStatements += IfStatements
    (elseStatement = ElseStatement)?
;

// If statements requiring conditions and optionally followed by
// library functions or for loops.
IfStatements:
    'if'
    conditions = Conditions
    (ifFunctions += libraryFunctionsEnum | forLoops += ForLoops)
;

// Else statement requiring one or multiple library functions.
ElseStatement:
        'else' elseFunctions += libraryFunctionsEnum
;

// For loops requiring one condition and followed by zero or more
// library functions
ForLoops:
    'for'
    conditions = Conditions
    libraryFunctions += libraryFunctionsEnum*

;

//*Eventually filled with details from class diagram, but for now we manually fill it for the sake of testing.
enum libraryFunctionsEnum:
createAccount='createInstance'|
login='login'|
hasCode= 'encrypt'|
display='display'
;

Conditions:
    STRING
    operator=logicalOperators
    STRING
;

enum logicalOperators:
greaterThan='>'|
smallerThan='<'|
greaterOrEqualThan='=>'|
smallerOrEqualThan='<='|
equalTo='=='
;

Java Class Diagram:

A: I think what you want to achieve is not easy. Still, a few thoughts:

*

*Your "libraryFunctions" could link to Java elements gotten through the Java Reflection API. I imagine you would somehow import some ".java" or ".class" file, and through reflection, reference its Method or Class objects.

*Instead, maybe it is possible, but I am really not sure, to reference elements provided by the Eclipse JDT tooling, such that you could reference elements from a Java source file and easily link to it (e.g. to open the editor on it with a ctrl + left click). Or you might have to find out how, from an element retrieved via the Reflection API, you will be able to link to the source Java code (if it is even possible).


text:
Q: ansible nmcli for Raspbian 10 Using Ansible, I am trying to provision a Raspberry Pi just freshly imaged with Raspbian 10.
One of the tasks is to set up the network. I'm trying to use community.general.nmcli, but so far without success:
- hosts: all

  tasks:

    - name: update and upgrade apt packages
      become: true
      apt:
        upgrade: dist
        update_cache: true

    - name: Install network manager
      become: true
      apt:
        name: network-manager
        state: present

    # see https://gist.github.com/truh/de723a3bc0f837f75d3673ddf101e108 and
    # https://raspberrypi.stackexchange.com/a/73816/137489
    - name: Uninstall openresolv and dhcpcd5
      become: true
      apt:
        pkg:
        - openresolve
        - dhcpcd5
        state: absent
        purge: yes

    - name: configure network
      become: true
      community.general.nmcli:
        state: present
        conn_name: my-eth0
        ifname: eth0
        type: ethernet
        ip4: 192.168.1.2/24
        gw4: 192.168.1.1

The first three tasks correspond to:
sudo apt update
sudo apt install network-manager
sudo apt purge openresolv dhcpcd5

as recommended by this gist and this discussion.
These first 3 tasks allow me to use nmcli on the command line (of the RPi).
However, the fourth task (using community.general.nmcli) fails:
fatal: [192.168.1.2]: FAILED! => {"changed": false, "msg": "Error: invalid property 'routing-rules': 'routing-rules' not among [method, dns, dns-search, dns-options, dns-priority, addresses, gateway, routes, route-metric, route-table, ignore-auto-routes, ignore-auto-dns, dhcp-client-id, dhcp-timeout, dhcp-send-hostname, dhcp-hostname, dhcp-fqdn, never-default, may-fail, dad-timeout].\n", "name": "my-eth0", "rc": 2}

Is there a way to get Ansible's community.general.nmcli to work on Raspbian 10?

A: That is due to Raspbian using NetworkManager prior to version 1.18, which is when the functionality routing-rules was released. It wouldn't otherwise be a problem, however, Ansible nmcli module expects that this parameter is there when it attempts to create the interface, but then nmcli fails with this weird message.
There's already an open issue for that: https://github.com/ansible-collections/community.general/issues/3948


text:
Q: button disappears in a horizontal orientation Hello I have LinearLayout in ScrollView
In this LinearLayout I have some checkbox and
button at the bottom.
In vertical view it's ok but in horizontal view
the button disappear.
You can see this situation on screen shots:
vertical view

horizontal view

Of course srclolling down doesnt help
This is my xml
<ScrollView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"

    >

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="80dp"
    android:layout_marginLeft="10dp"
    >

    <CheckBox android:id="@+id/hotele"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hotele"
        android:textSize="18sp"
        android:layout_margin="5dp"
        android:checked="true"
        />

     <!-- more checkboxs... -->

    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        xmlns:android="http://schemas.android.com/apk/res/android">

        <Button
            android:id="@+id/gotowe"
            android:layout_width="160dp"
            android:layout_height="wrap_content"
            android:layout_marginTop="30dp"
            android:background="@color/colorPrimary"
            android:padding="5dp"
            android:text="Gotowe"
            android:textColor="#fff"
            android:textSize="16sp"
            android:layout_centerInParent="true"
            android:textAllCaps="false"/>

    </RelativeLayout>

</LinearLayout>

</ScrollView>

A: Try to set the
<ScrollView
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

to be with layout_height="wrap_content" . This will let you scroll to the end of the content.

A: I'm not sure what your looking for but may this help you
<LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:layout_marginTop="80dp"
        android:weightSum="10">

        <ScrollView
            android:id="@+id/scrollView"
            android:layout_width="fill_parent"
            android:layout_height="0dp"
            android:layout_marginBottom="10dp"
            android:layout_weight="9.5">

            <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10dp"
                android:orientation="vertical">

                <CheckBox
                    android:id="@+id/hotele"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_margin="5dp"
                    android:checked="true"
                    android:text="Hotele"
                    android:textSize="18sp" />
            </LinearLayout>

        </ScrollView>

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="50dp"
            android:layout_weight=".5">

            <Button
                android:id="@+id/gotowe"
                android:layout_width="160dp"
                android:layout_height="wrap_content"
                android:layout_centerHorizontal="true"
                android:layout_centerVertical="true"
                android:layout_gravity="center"
                android:background="@color/colorPrimary"
                android:padding="5dp"
                android:text="Gotowe"
                android:textAllCaps="false"
                android:textColor="#fff"
                android:textSize="16sp" />
        </RelativeLayout>
    </LinearLayout>

A: <RelativeLayout
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"

    xmlns:android="http://schemas.android.com/apk/res/android">
<ScrollView android:layout_width="fill_parent"
    android:layout_height="fill_parent>

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_marginTop="80dp"
        android:layout_marginLeft="10dp"
        >

        <CheckBox android:id="@+id/hotele"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Hotele"
            android:textSize="18sp"
            android:layout_margin="5dp"
            android:checked="true"
            />

        <!-- more checkboxs... -->

        <RelativeLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            xmlns:android="http://schemas.android.com/apk/res/android">

        </RelativeLayout>

    </LinearLayout>

</ScrollView>
    <Button
        android:id="@+id/gotowe"
        android:layout_width="160dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="30dp"
        android:background="@color/colorPrimary"
        android:padding="5dp"
        android:text="Gotowe"

        android:textColor="#fff"
        android:textSize="16sp"
        android:layout_centerInParent="true"
        android:textAllCaps="false"/>
</RelativeLayout>

A: Try this
<ScrollView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"

    >
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">
<LinearLayout
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_marginTop="80dp"
    android:layout_marginLeft="10dp"
    >

    <CheckBox android:id="@+id/hotele"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hotele"
        android:textSize="18sp"
        android:layout_margin="5dp"
        android:checked="true"
        />

     <!-- more checkboxs... -->

    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        xmlns:android="http://schemas.android.com/apk/res/android">

        <Button
            android:id="@+id/gotowe"
            android:layout_width="160dp"
            android:layout_height="wrap_content"
            android:layout_marginTop="30dp"
            android:background="@color/colorPrimary"
            android:padding="5dp"
            android:text="Gotowe"
            android:textColor="#fff"
            android:textSize="16sp"
            android:layout_centerInParent="true"
            android:textAllCaps="false"/>

    </RelativeLayout>

</LinearLayout>
</RelativeLayout>
</ScrollView>

A: Try this code : The list of checkbox will be scrollable and the button will be shown in two cases :
 (As for the margin is up to you to choose the values of your margins)

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ScrollView
        android:id="@+id/scrollable_holder"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_above="@+id/gotowe"
        android:layout_marginLeft="10dp"
        android:layout_marginTop="80dp"
        android:isScrollContainer="true">

        <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
                      android:layout_width="match_parent"
                      android:layout_height="wrap_content"
                      android:orientation="vertical">

            <CheckBox
                android:id="@+id/hotele"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="5dp"
                android:checked="true"
                android:text="Hotele"
                android:textSize="18sp"
                />

            <CheckBox
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="5dp"
                android:checked="true"
                android:text="Hotele"
                android:textSize="18sp"
                />

            <CheckBox
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="5dp"
                android:checked="true"
                android:text="Hotele"
                android:textSize="18sp"
                />

            <CheckBox
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="5dp"
                android:checked="true"
                android:text="Hotele"
                android:textSize="18sp"
                />

            <CheckBox
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="5dp"
                android:checked="true"
                android:text="Hotele"
                android:textSize="18sp"
                />

            <CheckBox
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="5dp"
                android:checked="true"
                android:text="Hotele"
                android:textSize="18sp"
                />

            <CheckBox
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="5dp"
                android:checked="true"
                android:text="Hotele"
                android:textSize="18sp"
                />

            <CheckBox
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="5dp"
                android:checked="true"
                android:text="Hotele"
                android:textSize="18sp"
                />

            <CheckBox
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="5dp"
                android:checked="true"
                android:text="Hotele"
                android:textSize="18sp"
                />

            <CheckBox
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="5dp"
                android:checked="true"
                android:text="Hotele"
                android:textSize="18sp"
                />

            <CheckBox
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="5dp"
                android:checked="true"
                android:text="Hotele"
                android:textSize="18sp"
                />

            <CheckBox
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="5dp"
                android:checked="true"
                android:text="Hotele"
                android:textSize="18sp"
                />

            <CheckBox
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="5dp"
                android:checked="true"
                android:text="Hotele"
                android:textSize="18sp"
                />

            <CheckBox
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="5dp"
                android:checked="true"
                android:text="Hotele"
                android:textSize="18sp"
                />

            <CheckBox
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="5dp"
                android:checked="true"
                android:text="Hotele"
                android:textSize="18sp"
                />

            <CheckBox
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="5dp"
                android:checked="true"
                android:text="Hotele"
                android:textSize="18sp"
                />

            <CheckBox
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="5dp"
                android:checked="true"
                android:text="Hotele"
                android:textSize="18sp"
                />

            <CheckBox
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="5dp"
                android:checked="true"
                android:text="Hotele"
                android:textSize="18sp"
                />

            <CheckBox
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="5dp"
                android:checked="true"
                android:text="Hotele"
                android:textSize="18sp"
                />
            <!-- more checkboxs... -->
        </LinearLayout>
    </ScrollView>

    <Button
        android:id="@+id/gotowe"
        android:layout_width="160dp"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="10dp"
        android:layout_marginTop="30dp"
        android:background="@color/colorPrimary"
        android:padding="5dp"
        android:text="Gotowe"
        android:textAllCaps="false"
        android:textColor="#fff"
        android:textSize="16sp"/>

</RelativeLayout>

A: Just a minor change from your current xml file.
Try changing the margins of your inner Linearlayout to padding.
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:paddingTop="80dp"
        android:paddingLeft="10dp"
        >

I was able to make it work this way.


text:
Q: Google Sheet Query: Return default value to 0 in group by query if a particular group by condition doesn't exist Not sure if it is possible, however, I am looking if we can do a query in google sheet, which can give the result for the below table as

Month
Value

1
20

4
30

1
10

4
30

1
30

Expected Result:

Month
Value

1
60

2
0

3
0

4
60

As I am trying to create a dynamic dashboard in Google sheets, where a lot of data is being generated for Query to create plot and I would need the above to maintain consistency
Thanks a lot for any help in this regard

A: This was posted as an answer but was deleted. I'm not sure why, but try this:
=arrayformula(
     query({A:B;split(sequence(max(A:A)-min(A:A)+1,1,min(A:A))&"_0", "_")},
     "select Col1, sum(Col2) group by Col1
                             order by Col1 label sum(Col2) ''", 0)
)

A: If you want a script (a custom function, to be precise) it's here:
function make_table(arr) {
  // [[1,...],[4,...],[1,...],[4,...],[1,...]] --> 4
  const latest_month = Math.max(...arr.map(x => x[0]));

  // 4 --> [1,2,3,4]
  const months = new Array(latest_month).fill().map((_,i) => i+1);

  // [1,2,3,4] --> { 1:0, 2:0, 3:0, 4:0 }
  const obj = months.reduce((ar,m) => ({ ...ar, [m]:0 }), {});

  // [[1,20], [4,30], [1,10], [4,30], [1,10]] + obj --> { 1:40, 2:0, 3:0, 4:60 }
  arr.forEach(row => obj[row[0]] += row[1]);

  // { 1:40, 2:0, 3:0, 4:60 } --> [ [1,40], [2,0], [3,0], [4,60] ]
  return Object.keys(obj).sort().map(month => [+month, obj[month]]);
}


text:
Q: WebForms GET Json requests (JsonRequestBehavior.AllowGet) I have an old WebForms project that needs revisiting and I want to add some new features.
I want to load the data using $.getJSON(), this is very simple in ASP.NET MVC because you can return the data like this,
return Json(data, JsonRequestBehavior.AllowGet);

The Get doesn't work in WebForms,
// Http GET request
$.getJSON('Attributes.aspx/GetAttributes', { 'ProductId': '3' }, function (d) { alert(d); });

The Post works.
// Http POST
$.post('Attributes.aspx/GetAttributes', { 'ProductId': '3' }, function (d) { alert(d); });

Here is the WebForms WebMethod,
[WebMethod]
public static string GetAttributes(string ProductId)
{
    List<QuoteAttribute> list = DAL.GetAttributes(ProductId);
    var json = JsonConvert.SerializeObject(list);
    return json;
}

I want to return json using the GET method.
Is there an JsonRequestBehavior.AllowGet for WebForms?
Any help is appreciated.
Thanks

A: Need to add "[ScriptMethod(UseHttpGet = true)]" before the method.This will allow GET method.
eg.
[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public static string GetAttributes(string ProductId)
{
    List<QuoteAttribute> list = DAL.GetAttributes(ProductId);
    var json = JsonConvert.SerializeObject(list);
    return json;
}


text:
Q: Copy core file to app/code/local/Mage can't overload! I have 2 files need to be overload
core/Mage/Admin/Model/Session.php
and
core/Mage/Adminhtml/controllers/IndexController.php
I already copy it to local with same structure, but the bad news is it wasn't overloaded. I can overload Block in local folder before. Now, I want to know why and how to do it.

A: Copying files to local code pool will only work for blocks, helpers and models. You cannot override controllers using this method since they are not autoloaded like other classes.
So the only way to do it is via custom module. You will need following definition in your config.xml
<admin>
    <routers>
        <adminhtml>
            <args>
                <modules>
                    <Foo_Bar before="Mage_Adminhtml">Foo_Bar_Adminhtml</Foo_Bar>
                </modules>
            </args>
        </adminhtml>
    </routers>
</admin>

And in your controller class you need to add this:
require_once Mage::getModuleDir('controllers', 'Mage_Adminhtml') . DS . 'IndexController.php';
class Foo_Bar_Adminhtml_IndexController extends Mage_Adminhtml_IndexController
{

Your controller class should be in local/Foo/Bar/controllers/Adminhtml/IndexController.php

A: I would like to add that though it is possible to copy a model or block to local to get this working that you should not do this as it will be an issue when you decide to update Magento.
You have a few options here:

*

*Rewrite the model using the rewrite node in your extension's xml,

*Leave the model and find an event that works for your needs,

I would always try to choose the second option but since I do not know your needs I will go with number 1 for this answer.
To rewrite the model simply add the follow to your module's config.xml
<global>
    <models>
        <your_module>
            <class>Your_Module_Model</class>
        </your_module>
        <admin>
            <rewrite>
                <session>Your_Module_Model_Admin_Session</session>
            </rewrite>
        </admin>
    <models>
</global>

Now what you can simply do is create the model Your_Module_Model_Admin_Session that extends the model Mage_Admin_Model_Session and you can make your changes in there.
Final note I would consider investigating if there are any events that will fit your needs.


text:
Q: Session support in Now.js Now.js quotes:

Simply pass a connect or express http server in nowjs.initialize and this.user.session should be available.

So:
express = require 'express'
app = module.exports = express.createServer()
connect = require 'connect'
nowjs = require 'now'
everyone = nowjs.initialize(app)

The output of this.user is:
{
  clientId: '353725111301231610',
  cookie: { 'connect.sid': 's0meC00k1e1nF0rm4ti0n' },
  session: undefined
}

Any idea why session is undefined?

A: I ran into this problem and turns out it was happening because I was initializing NowJS before configuring express.
app.configure(function(){
    ...

    app.use(express.cookieParser());
    app.use(express.session({ secret: "my_key", store: redisStore }));
    app.use(app.router);
});

var everyone = nowjs.initialize(app); //must be defined after app.configure

One thing to note is that session is not set until a request is made to the server so if the server is reset, the client socket will reconnect but session will be undefined until the browser does a page refresh.

A: I managed to find a solution (CoffeeScript), for every "everyone"-request:
self = this
sid = decodeURIComponent(this.user.cookie['connect.sid'])
sessionStore.get sid, (err, session) ->
    self.user.session = session
    <<more code here>>

Any way to get to this.user.session directly?


text:
Q: Do we really need std::error_category and std::error_condition? So, on my journey to understand how std::error_code works I'm starting to wonder if we really need std::error_condition and std::error_category. I'm trying to implement what's in this and this tutorial and the amount of work is non-trivial along with it being fairly fragile (I'm currently stuck trying to figure out why this code causes linking errors with duplicate symbols.
Isn't it easier to subclass std::error_code, add a message property & method and then let std::error_code be comparable to an enum where error codes are defined? I'm struggling to understand why I need std::error_category and std::error_condition at all.

A: The main advantage is that error_code is a copyable type that can be handed around from library to library without having to involve any dynamic memory allocation or templating, making it very light-weight, and easy to work with.
If you are writing a fully self-contained project, then yes, error codes and categories seem overly complicated when you could just have your own type.
However, things change when writing a library meant to be used by other people (like ASIO, since you linked think-async.com). You can have a library receive an error_code instance, and it will be able to pass it around cleanly and efficiently without having to know anything about the code that is using the library, or having to make every error-handling function be templated on the error type.
In that context, error categories are important when dealing with multiple error sources, as a given error-code could mean two different things based on the source of the error.
Edit: Notice, in your first link, how categories are actually singletons. This is done in the service of maintaining lightweightness, since copying a pointer to an object that is guaranteed to never be deleted or modified is cheap, memory-safe and thread-safe.


text:
Q: Can I get the steps for crawling in the below link available to execute in ubuntu 16.04.1? Search Engine with Apache Nutch, MongoDB and Elasticsearch.
A brief description about each component:

*

*Apache Nutch
An open source web crawler forked from Apache Lucene

*MongoDB
An open source document database and one of the leading NoSQL databases

*Elasticsearch
A highly scalable, distributed search engine stemming from Apache Lucene

*Kibana
An open source browser based analytics and search dashboard for Elasticsearch
Data Flow

I'm in need of the whole set of tasks in the blog mentioned above to be executed in ubuntu 16.04.1. Can I get the steps for the same?
Edit 1:
I followed the instructions from the 1st comment for this post. But i executed the third command(commented) in the blog above and ended up with the result shown below.
root@gizmeon-Aspire-ES1-571:/apps# useradd -d /apps/se -c "Search Engine" se
useradd: user 'se' already exists
root@gizmeon-Aspire-ES1-571:/apps# su - se
No directory, logging in with HOME=/
$ su
Password:
root@gizmeon-Aspire-ES1-571:/# su -se
Cannot execute e: No such file or directory
root@gizmeon-Aspire-ES1-571:/#


text:
Q: Show the next data while looping over an array in typescript react So, I am trying to add some data to two different array in react typescript
const [deviceNames, setDeviceNames] = useState<Array<string>>([])
  const [serialNumbers, setSerialNumbers] = useState<Array<string>>([])

I am now looping over both the array here and displaying the content
{deviceNames.length > 0 &&
      serialNumbers.length > 0 &&
      deviceNames.map(deviceName => {
        return serialNumbers.map(serialNumber => {
          return (
            <CardDevice
              deviceName={deviceName}
              serialNumber={serialNumber}
            />
          )
        })
      })}

I am adding data to these array by clicking on a button and then showing modal and then like this
 onSubmit = (values: any) => {
    clearError()
    setAddDevice(false)
    setDeviceNames(deviceName => [...deviceName, values.deviceName])
    setSerialNumbers(serialNumber => [...serialNumber, values.serialNumber])
  }

I am using react hook form.
So what i want is whenever i loop over both the arrays, each time it should display the content which was just added in the array the new one not the last one again which was already added and displayed. I hope i am able to make some point here. It does the job but whenever user enters new device after adding one, it add the old one again and then the new one and then again and then again same thing.
i just want to display just one new item which was just last added to an array by the user.
Thanks

A: Basically i answered my own question:
import React, { useState } from "react";

function App() {
  const [addCardData, setAddCardData] = useState("");
  const [addCards, setAddCards] = useState<Array<string>>([]);

  const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    setAddCardData(event.target.value);
  };

  const handleSubmit = (event: React.FormEvent<HTMLFormElement>): void => {
    event.preventDefault();
    setAddCards(prevState => [...prevState, addCardData]);
  };
  return (

      <form onSubmit={handleSubmit}>
        <input type="text" onChange={handleChange} placeholder="Add any text" />
        <button type="submit">Add</button>
      </form>
      {addCards.map(addCard => (

{addCard}

      ))}

  );
}

export default App;

A: Here is some more Dynamic Approach:
import React, { useState } from "react";
import { TextInput } from "./components/TextInput";

interface Device {
  deviceName: string;
  serialNumber: string | number;
}

const App: React.FC = () => {
  const [deviceName, setDeviceName] = useState("");
  const [serialNumber, setSerialNumber] = useState("");
  const [deviceInfos, setDeviceInfos] = useState<Device[]>([]);

  const handleDeviceChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    setDeviceName(event.target.value);
  };
  const handleSerialChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    setSerialNumber(event.target.value);
  };

  const handleSubmit = (event: React.FormEvent<HTMLFormElement>): void => {
    event.preventDefault();
    addDevice();
    setDeviceName("");
    setSerialNumber("");
  };

  const addDevice = () => {
    const newDevice: Device[] = [
      ...deviceInfos,
      { deviceName: deviceName, serialNumber: serialNumber }
    ];
    setDeviceInfos(newDevice);
  };
  return (

      <form onSubmit={handleSubmit}>
        <TextInput
          type="text"
          placeholder="Add Device Name"
          handleChange={handleDeviceChange}
          value={deviceName}
        />
        <TextInput
          type="text"
          placeholder="Add fuck"
          handleChange={handleSerialChange}
          value={serialNumber}
        />
        <button type="submit">Add</button>
      </form>
      {deviceInfos.map((device, i) => (

{device.deviceName}

{device.serialNumber}

      ))}

  );
};

export default App;

A: Much Better Approach i used in the production
  const ProfileDevices: React.FC<Props> = ({ onSubmit }) => {
      const [addDevice, setAddDevice] = useState(false)
      const [deviceInfos, setDeviceInfos] = useState<Device[]>([])

      const { register, handleSubmit, errors, clearError } = useForm({
        mode: 'onSubmit',
      })
      const addDevices: any = () => {
        setAddDevice(true)
      }

      onSubmit = (values: any) => {
        clearError()
        setAddDevice(false)
        const newDevice: Device[] = [
          ...deviceInfos,
          { deviceName: values.deviceName, serialNumber: values.serialNumber },
        ]
        setDeviceInfos(newDevice)
      }

      return (
        <ProfileContentContainer>
          <ProfileHeader>
            <ProfileTitle>Devices</ProfileTitle>

            <ProfileActions>
              <Button
                type="button"
                bgType="fill"
                size="default"
                label="Add Device"
                onClick={addDevices}
              />
            </ProfileActions>
          </ProfileHeader>
          {console.log(deviceInfos)}
          <DeviceList>
            <CardDevice deviceName="Device Name" serialNumber="QR10001123456788" />
            <CardDevice deviceName="Device Name" serialNumber="QR10001123456789" />
            {deviceInfos.map((device, i) => (
              <CardDevice
                key={i}
                deviceName={device.deviceName}
                serialNumber={device.serialNumber}
              />
            ))}
          </DeviceList>
          <Modal isActive={addDevice} toggleModal={() => setAddDevice(false)}>
            <ModalContent>
              <ModalHeader title="Add Device" />
              <AuthForm
                onSubmit={handleSubmit(onSubmit)}
                className="modalAddDeviceForm"
              >
                <InputText
                  placeholder="DeviceName"
                  name="deviceName"
                  type="text"
                  register={register({ required: true, maxLength: 10 })}
                  hasError={errors.deviceName}
                  errorMessage={
                    errors.serialNumber ? errors.serialNumber.message : undefined
                  }
                />
                <InputText
                  placeholder="Serial Number"
                  name="serialNumber"
                  type="text"
                  register={register({ required: true, maxLength: 10 })}
                  hasError={errors.serialNumber}
                  errorMessage={
                    errors.serialNumber ? errors.serialNumber.message : undefined
                  }
                />
                <Button type="submit" bgType="fill" size="default" label="Add" />
              </AuthForm>
              <ModalActions></ModalActions>
            </ModalContent>
          </Modal>
        </ProfileContentContainer>
      )
    }

    export default ProfileDevices


text:
Q: bashscript for changing wput uploaddirectory on every 5000 passage how i can change the uploaddirectory of wput on every 5000 passage?
whats wrong in my code?
only for the record; i need infnite loop i want run this script 24h 365 days!
every 5000 passage one number higher in directory like incoming1-infinite
best regards
haug
#!/bin/bash
for (( ; ; ))
do
  no=1
  while [ $no -le 5000 ]
  do
    perl job.pl false false 1
    cd comp

    for fname in *.jpg;
    do
      mv -i "$fname" ${RANDOM}${RANDOM}.jpg
    done

    for fname in *.jpg;
    do
      mv "$fname" $(echo "$fname" | sha1sum | cut -f1 -d' ').jpg
    done

    if [ $no = '5000' ]
    then
      echo $no
      echo $n
      n=$(( n+1 )) # <-- this one not do what i need :-(

    else
      wput *.jpg ftp://user:pass@ip:port/incoming$n/  # <-- here is the important part 2, i need it to change one directory higher every 5000 passage for example; incoming1 until   infinite
      rm  -rf *.jpg
      cd ..
    fi

    no=`expr $no + 1`
  done
done

A: cd comp
for ((no=1; ; no++))
do
  n=`expr $no / 5000`

  perl job.pl false false 1

  for fname in *.jpg;

  # ... rest of the script
done

A: Just calculate the remainder of division by 5000 and if it is equal 0 (or 1 or anything < 5000) do what you need.
if [ $((no%5000)) = 0 ]
then
...
fi

A: Just put a for-loop that executes 5,000 times inside your infinite loop (which can keep track of the directory sequence number for you):
#!/bin/bash
for (( n=0; ; n++ )); do
  for (( no=1; no < 5000; no++ )); do
    perl job.pl false false 1
    ( # Subshell so we don't have to worry about returning
      # to the previous directory.
      cd comp

      # No need to rename each file twice.
      for fname in *.jpg; do
        mv "$fname" $(echo "${RANDOM}${RANDOM}.jpg" | sha1sum | cut -f1 -d' ').jpg
      done

      wput *.jpg ftp://user:pass@ip:port/incoming$n
    )
  done
done


text:
Q: Running command on task startup Im trying to run a command in conemu when I open up a console from a task.
For example, I want to open a bash terminal and run node -v to see my current node version. My Current task commands look like this:
set "PATH=%ConEmuBaseDirShort%\wsl;%PATH%" & %ConEmuBaseDirShort%\conemu-cyg-64.exe --wsl -cur_console:pm:/mnt node -v

This opens a bash terminal and executes node -v, but then closes the process, giving me the error
Root process was alive less than 10 sec, ExitCode=0

My expected result is that the output of node -v would be visable, and under that would be a working bash console.
v12.6.0
root@COMPUTER:/mnt/c# _

I had it like this in my previous environment so I know it's possible, but I don't remember how I did it.

A: You can suppress this error by adding the flag -new_console:n.
This is more a feature than an error; if your process runs and ends in less than ten seconds, ConEmu will keep the tab open until you press a key, just so you can see the message it produces.
More info here!
Edit: You're also able to change the amount of time before this message shows in the settings, or set it to never/always show
Edit 2: To force a 'Press Enter or Escape to close the console' message, append -new_console:c


text:
Q: Adjunctions between derived functors Given an adjunction $F\dashv G$ between functors between Abelian categories, we know that $F$ is right exact and $G$ is left exact so there are derived functors $LF$ and $RG$ between (bounded above, respectively below) derived categories. What can one say about the existence of an adjunction $LF\dashv RG$?

A: It seems this question was considered in:
William W Adams, Marc A Rieffel.
Adjoint functors and derived functors with an application to the cohomology of semigroups
Journal of Algebra, V. 7, N 1, 1967,  25-34


text:
Q: Python Virtual Environment - Dodgy Files? I'm new to Python and a little paranoid since malware scares a few weeks ago.
I created a project and configured a python interpreter by making a new virtual environment, which worked fine. The virtual environment shows in the file directory on the left of a Pycharm window in red, which I assume is because I haven't activated it. I now want to know, are the files in the venv Directory normal (there are many .exe files I can't find a reference to online)?
Many thanks for the help in advance!

I tried googling what files I should find in a venv but didn't find anything too useful. I would be grateful for reassurance/help.

A: if you install all python futures in these ways are safe :

*

*PIP3 install Python from the command prompt

*Install Vscode and after that from extensions

*Install a complete anaconda package from that site to be free from all libraries in the future.
and as I saw your Sc,

all those files are necessary to run python and virtual environments.

But there is a point: Don't try to make several virtual environments, because in the future you will be confused between them, and also your python version will be set on each environment differently!
notice: if you are a beginner, try to work on VS CODE. because it is very helpful and easy.


text:
Q: Creating a Team ReSharper Settings File based on Defaults I read how ReSharper uses the different layers of settings files as per https://www.jetbrains.com/resharper/help/Sharing_Configuration_Options.html
So I want to set up a new file for my team, I add a new Blah.sln.DotSettings file at the root of by solution alongside Blah.sln.
When I do this, the file is empty.  How to I create this file with the ReSharper defaults in place?
For example, if a developer changes 'Setting A' from 'Value 1' to 'Value 2' at their machine level, because there is no entry for 'Setting A' in the team file, their machine level setting wins.  I need the original 'Setting A' line in the team level file to overrule their machine level settings
How do I get those default values in the team file in the first place?
I'm having such difficulty doing something that seems so simple that I think there's something I'm missing.
Update 1
If at my machine level I change all the settings I'm interested in so they are no longer at the default value, then I go to the team level and set each one back to the default value at that level, that gives me the explicit lines for each of those settings in the team level file.  Then if I clear out the machine level line, I still have those lines at team level which I can check in and share with the team.  I think this will work, it just doesn't seem the right way to go about it.

A: ReSharper will only save settings that are different to the defaults, to prevent bloating settings files. And due to the hierarchical nature of the settings files, this manifests as not saving if a value in a lower layer is already set to that value.
So, if I change a value in the global settings to a default value, it doesn't get written to the global settings file. If I change a value in the shared team layer, but it's already set in the global settings file (or in the defaults), it doesn't get written to the shared team layer.
What you can do is to use the "Copy Settings To" command in the "Manage Options" dialog. This will give you a list of layers you can copy to, and will copy the settings from the currently selected layer. It will also allow you to choose which settings to copy. This will allow you to copy settings from the default layer, or the global settings layer to a team shared layer.
I've added a feature request to make it easier to set up team shared settings. Please track and vote: RSRP-444671.


text:
Q: Bootstrap 3 daterange select in form I'm trying to add daterange (https://github.com/eternicode/bootstrap-datepicker) select to my bootstrap 3 form.
I've added form element to my form:

    Dates range

            <input type="text" class="input-small" name="start"/>
            to
            <input type="text" class="input-small" name="end"/>

But I get weird looking inputs:

I would like it to look as here.
How should I build my form to get this daterange to look nice? I would like to have those 2 inputs and "to" to be same width as other inputs and have same focus color.
Here is my form to play with: http://jsfiddle.net/Misiu/a3NV4/

A: See here example.
To work on Bootstrap 3
http://jsfiddle.net/a3NV4/4/

        <input type="text" class="input-small form-control" name="start" />
        to
        <input type="text" class="input-small form-control" name="end" />

JS
$('.input-daterange').datepicker({});

A: You are working with Bootstrap 3 and the datepicker plugin is for bootstrap 2.3, that is the problem. So you have to use the according bootstrap 3 classes:
JSFIddle

    <input type="text" class="input-small form-control" name="start" />
    to
    <input type="text" class="input-small form-control" name="end" />


text:
Q: Mysql update function I have created a form that submits to the mysql database. Now what I am trying to do is get it to update. The bit I'm having trouble with is the update query below, I just can not figure out where I am going wrong.
 <?php
/*
Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password)
*/
include 'db.php';

// Check connection
if($link === false){
    die("ERROR: Could not connect. " . mysqli_connect_error());
}

// Escape user inputs for security
$title = mysqli_real_escape_string($link, $_POST['title']);
$price = mysqli_real_escape_string($link, $_POST['price']);
$sqm = mysqli_real_escape_string($link, $_POST['sqm']);
$sqm_land = mysqli_real_escape_string($link, $_POST['sqm_land']);
$type = mysqli_real_escape_string($link, $_POST['type']);
$area = mysqli_real_escape_string($link, $_POST['area']);
$location = mysqli_real_escape_string($link, $_POST['location']);
$bedroom = mysqli_real_escape_string($link, $_POST['bedroom']);
$terrace = mysqli_real_escape_string($link, $_POST['terrace']);
$orientation = mysqli_real_escape_string($link, $_POST['orientation']);
$water = mysqli_real_escape_string($link, $_POST['water']);
$seaview = mysqli_real_escape_string($link, $_POST['seaview']);
$pool = mysqli_real_escape_string($link, $_POST['pool']);
$ownerinfo = mysqli_real_escape_string($link, $_POST['ownerinfo']);
$gaddress = mysqli_real_escape_string($link, $_POST['gaddress']);
$description = mysqli_real_escape_string($link, $_POST['description']);

// attempt insert query execution
$sql = "update INTO property (title, price, sqm, sqm_land, type, area, location, bedroom, terrace, orientation, water, seaview, pool, ownerinfo, gaddress, description) VALUES
('$title', '$price', '$sqm', '$sqm_land', '$type', '$area', '$location', '$bedroom', '$terrace', '$orientation', '$water', '$seaview', '$pool', '$ownerinfo', '$gaddress', '$description' )";
if(mysqli_query($link, $sql)){
    echo "Records updated successfully.";
} else{
    echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}

// close connection
mysqli_close($link);

?>

A: You're using the wrong syntax for UPDATE.
Read the manual:

*

*http://dev.mysql.com/doc/en/update.html
What you're using is INSERT syntax. http://dev.mysql.com/doc/en/insert.html
Example from the manual:
UPDATE t1 SET col1 = col1 + 1, col2 = col1;

and use a WHERE clause, otherwise you will be updating your entire db.
Example from the manual:
UPDATE items,month SET items.price=month.price
WHERE items.id=month.id;

So in your case and for example (fill in the rest):
UPDATE property SET title = '$title', price = '$price' ... WHERE column = ?

*

*column being the column name you want to target and the ? being the row.

Your mysqli_error($link) would have thrown you something about it.
Sidenote: "Teach a person how to fish, rather than throwing them a fish".
However, if the goal here is to INSERT, then you need to use INSERT INTO table and not UPDATE INTO table.
Also make sure your form uses a POST method and that all POST arrays contain values.
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Then the rest of your code

Sidenote: Displaying errors should only be done in staging, and never production.

Footnotes:
The MySQL API used to connect with in db.php is unknown. Make sure you are using the same API you are using to query with, being mysqli_. Different APIs do not intermix.

A: Your syntax is incorrect, it should be formatted like this:
$sql = "UPDATE property SET title='$title'";

You'll have to add all the name/value pairs separated by commas since I only included 'title.'


text:
Q: linux ubuntu : can't make modules I am trying to learn Kernel Module programming. I have configured options by the make menuconfig command (seems that if I undo my operations the error still exists).
But under "/usr/src/linux-headers-3.13.0-36-generic" , while entering "make modules",I got :
    make[1]: *** No rule to make target `/usr/src/linux-headers-3.13.0-36-generic/arch/x86/syscalls/syscall_32.tbl', needed by `arch/x86/syscalls/../include/generated/uapi/asm/unistd_32.h'.  Stop.

I tried to add a file named syscall_32.tbl but another required file pops out. Is there any library or package that needs to be installed?


text:
Q: Get JSON value from BASH CURL Response with Python I am having a problem parsing a JSON response to 2 variables in BASH. I dont have access to install jq or jsawk or anything cool that makes life easier. I have python, thats all.
This is what I'm working with: I have a curl call that gets a JSON response. The response is stored in a variable called api_response.
API_RESPONSE=$(curl --silent -v -H "Content-Type: application/json" -H "MY-Token: $Token" -XPOST -d "$INPUTS" ${MY_BASE}$MY_PROCESS${PROCESS})

this variable essentially is the value of the response from the api
[{"name":"test-name1", "value" : "test-value1"},{"name" : "test-name2","value" : "test-value2"}]

In the past, I had only need to get a single value from the response and was able to do that using the following
API_RESPONSE=$(curl --silent -v -H "Content-Type: application/json" -H "MY-Token: $Token" -XPOST -d "$INPUTS" ${MY_BASE}$MY_PROCESS${PROCESS} | python -c "import sys, json; print json.load(sys.stdin)[1]['value'])

[outputs]
test-value2

I was trying to extract to two JSON values from the single variable API_RESPONSE but I get an error doing it this way.
API_RESPONSE=$(curl --silent -v -H "Content-Type: application/json" -H "MY-Token: $Token" -XPOST -d "$INPUTS" ${MY_BASE}$MY_PROCESS${PROCESS})

myvar1=$($API_RESPONSE | python -c "import sys, json; print json.load(sys.stdin)[0]['value']")
myvar2=$($API_RESPONSE | python -c "import sys, json; print json.load(sys.stdin)[1]['value']")

I get the following error:
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/usr/lib64/python2.6/json/__init__.py", line 267, in load
parse_constant=parse_constant, **kw)
File "/usr/lib64/python2.6/json/__init__.py", line 307, in loads return _default_decoder.decode(s)
File "/usr/lib64/python2.6/json/decoder.py", line 319, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/lib64/python2.6/json/decoder.py", line 338, in raw_decode
raise ValueError("No JSON object could be decoded")
ValueError: No JSON object could be decoded

The variable api_response is the same data that was working before. Why would it work with a curl call and not from variable?

A: I figured it out with help from a friend.
When going from bash variable to python sys.stdin, a bash variable needs to be redirected by SOME action to the python sys.stdin.
With the curl execution piping output to the python sys.stdin it would work because the output was being redirected to python.  But once I had the entire response stored in the variable within bash, the next step was to echo the output and redirect to python.
[json response]
[{"name":"test-name1", "value" : "test-value1"},{"name" : "test-name2","value" : "test-value2"}]

[code block]
API_RESPONSE=$(curl --silent -v -H "Content-Type: application/json" -H "MY-Token: $Token" -XPOST -d "$INPUTS" ${MY_BASE}$MY_PROCESS${PROCESS})

myvar1=$( echo $API_RESPONSE | python -c "import sys, json; print json.load(sys.stdin)[0]['value']")
myvar2=$( echo $API_RESPONSE | python -c "import sys, json; print json.load(sys.stdin)[1]['value']")
echo $myvar1
echo $myvar2

[outputs]
test-value1
test-value2


text:
Q: How can I get permisson to delete files from a memory card? In Ubuntu I'm trying to delete some files from a memory card, but whenever I try to do so, I get a Permission denied error and can't delete them.
The files happen to be viruses so I need to get rid of them. How can I do that?

A: Try deleting them as super user, if you haven't yet:
sudo rm theFile


text:
Q: Tried accessing nonexisting field (context) on node type (User) I am accessing connection.fetchUserProfile() from Connection<?> connection but it gives org.springframework.social.UncategorizedApiException: (#100) Tried accessing nonexisting field (context) on node type (User). This particular error never happen before until now.
maven :
<dependency>
    <groupId>org.springframework.social</groupId>
    <artifactId>spring-social-facebook</artifactId>
     <version>3.0.0.M3</version>
</dependency>

Any idea why is this happening?

A: I had the same issue and looked for a solution everywhere. Without any luck, I ended up writing a custom service that calls the Facebook Graph API and populates the UserProfile object.
Add a new FBService.java class to your project:
package net.attacomsian.services;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.http.*;
import org.springframework.social.connect.UserProfile;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.Collections;

@Service
public class FBService {

    private final RestTemplate restTemplate;

    public FBService(RestTemplateBuilder restTemplateBuilder) {
        this.restTemplate = restTemplateBuilder.build();
    }

    public UserProfile getProfile(String id, String accessToken) {
        try {
            //params
            String params = "fields=id,name,email,first_name,last_name&access_token=" + accessToken;

            //build url
            String url = "https://graph.facebook.com/v3.2/" + id + "?" + params;

            //create headers
            HttpHeaders headers = new HttpHeaders();
            headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));

            // create request
            HttpEntity request = new HttpEntity(headers);

            //use rest template
            ResponseEntity<String> response = this.restTemplate.exchange(url, HttpMethod.GET, request, String.class);

            //check for status code
            if (response.getStatusCode().is2xxSuccessful()) {
                JsonNode root =  new ObjectMapper().readTree(response.getBody());

                // return a user profile object
                return new UserProfile(root.path("id").asText(), root.path("name").asText(), root.path("first_name").asText(),
                        root.path("last_name").asText(), root.path("email").asText(), null);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        return null;
    }
}

v3.2 is the Graph API version. Replace it with your own. Now inject this service to your controller and instead of calling:
UserProfile profile = connection.fetchUserProfile();

Call the new service getProfile() method like below:
Profile profile = fbService.getProfile("me", connection.createData().getAccessToken());

It works like a magic for me.
Update: Here is the complete web controller code that shows how you can use the custom service for Facebook while keep using the default one for Google's user profile:
@Controller
public class AuthController {

    private FBService fbService;
    private final ProviderSignInUtils providerSignInUtils;

    public AuthController(FBService fbService,
                          ConnectionFactoryLocator connectionFactoryLocator,
                          UsersConnectionRepository connectionRepository) {
        this.fbService = fbService;
        this.providerSignInUtils = new ProviderSignInUtils(connectionFactoryLocator, connectionRepository);
    }

    @GetMapping("/social-signup")
    public String socialSignup(WebRequest request, HttpSession session) {

        Connection<?> connection = providerSignInUtils.getConnectionFromSession(request);
        if (connection == null) {
            return "redirect:/login";
        }

        //fetch user information
        UserProfile profile = null;
        if (connection.getKey().getProviderId().equalsIgnoreCase("google")) {
            profile = connection.fetchUserProfile();
        } else if (connection.getKey().getProviderId().equalsIgnoreCase("facebook")) {
            profile = fbService.getProfile("me", connection.createData().getAccessToken());
        }

        // TODO: continue doing everything else
    }
}

A: It looks like facebook social will be not updated anymore.
Anyway, I don't want to spend time for switching to another lib.
I've just fetched the fields I need:
FacebookTemplate facebook = new FacebookTemplate(socialToken);

User facebookUser = facebook.fetchObject(FacebookUtils.LOGGED_USER_ID, User.class, FacebookUtils.USER_FIELD_ID, FacebookUtils.USER_FIELD_EMAIL,
            FacebookUtils.USER_FIELD_FIRST_NAME, FacebookUtils.USER_FIELD_LAST_NAME);

Fields I've added into my FacebookUtils:
/** The Constant LOGGED_USER_ID. */
public static final String LOGGED_USER_ID = "me";

/** The Constant USER_FIELD_ID. */
public static final String USER_FIELD_ID = "id";

/** The Constant USER_FIELD_EMAIL. */
public static final String USER_FIELD_EMAIL = "email";

/** The Constant USER_FIELD_FIRST_NAME. */
public static final String USER_FIELD_FIRST_NAME = "first_name";

/** The Constant USER_FIELD_LAST_NAME. */
public static final String USER_FIELD_LAST_NAME = "last_name";

A: EDIT#2: This issue came up again for me.  If you want to figure out how to modify some package and add it to maven, fine go ahead and read on, but if you're just here to figure out how to get rid of that error (and other similar errors like this involving different properties) then you should just follow the advice in this answer: https://stackoverflow.com/a/34133450/754988. It is much better than mine.

While attacomsian's solution may work for some, I depend on an abstract UserProfile for other services like Google sign in and their solution would break that for me.
A less invasive maneuver that I've found works is to head over to ss-facebook's github and follow the first two lines of their instructions to build from source:
git clone git://github.com/SpringSource/spring-social-facebook.git
cd spring-social-facebook

But before you run the ./gradlew build command, open up this file for editing:
./spring-social-facebook/src/main/java/org/springframework/social/facebook/api/UserOperations.java

Scroll down to the bottom and remove "context" from the array, changing
static final String[] PROFILE_FIELDS = {
        "id", "about", "age_range", "birthday", "context", "cover", "currency", "devices", "education", "email",

        ....

        "website", "work"
    };

to
static final String[] PROFILE_FIELDS = {
        "id", "about", "age_range", "birthday", "cover", "currency", "devices", "education", "email",

        ....

        "website", "work"
    };

Now go back to the source folder and run the final command:
./gradlew build

You'll get a ./build folder there with a zip file in it, unzip it to find your working jars!  I use maven, and replaced the two remote dependencies that I had with some local dependencies, like so:
        <dependency>
            <groupId>org.springframework.social</groupId>
            <artifactId>spring-social-facebook</artifactId>
            <version>3.0.0.M1</version>
            <scope>system</scope>
            <systemPath>${project.basedir}/src/main/resources/lib/spring-social-facebook-3.0.0.BUILD-SNAPSHOT.jar</systemPath>
        </dependency>
        <dependency>
            <groupId>org.springframework.social</groupId>
            <artifactId>spring-social-facebook-web</artifactId>
            <version>3.0.0.M1</version>
            <scope>system</scope>
            <systemPath>${project.basedir}/src/main/resources/lib/spring-social-facebook-web-3.0.0.BUILD-SNAPSHOT.jar</systemPath>
        </dependency>

EDIT: I have since learned this is not the optimal way to include a custom jar like this with Maven.  It's a bit of a rabbit hole to actually get it in there where it works like other jars in your pom.  I got it to work better eventually by running these commands to manually install the two jars I made (3.0.1337 is the version I made up to avoid name collision - not sure if it's necessary) ...
mvn org.apache.maven.plugins:maven-install-plugin:2.3.1:install-file -Dfile=web/src/main/resources/lib/spring-social-facebook-3.0.1337.BUILD-SNAPSHOT.jar -DgroupId=org.springframework.social -DartifactId=spring-social-facebook -Dversion=3.0.1337 -Dpackaging=jar -DlocalRepositoryPath=web/src/main/resources/local-repo -DgeneratePom=true

mvn org.apache.maven.plugins:maven-install-plugin:2.3.1:install-file -Dfile=web/src/main/resources/lib/spring-social-facebook-web-3.0.1337.BUILD-SNAPSHOT.jar -DgroupId=org.springframework.social -DartifactId=spring-social-facebook-web -Dversion=3.0.1337 -Dpackaging=jar -DlocalRepositoryPath=web/src/main/resources/local-repo -DgeneratePom=true

...Into a local repository that I declared in my pom like so:
<repositories>
  <repository>
    <id>local-repo</id>
    <url>file://${project.basedir}/src/main/resources/local-repo</url>
  </repository>
</repositories>

and then I added the jars to source control and added a line in my gitignore to ignore the /src/main/resources/local-repo folder.
If anyone has a better way of doing this that retains all of the original code, only removing that "context" string from the array at the end of that file, and hopefully avoids ALL of this junk in favor of a simple singular class replacement or extension, please chime in.  I'm just including all of it because it definitely would have saved me a day of having to figure each of these things out one by one.
DISCLAIMER: I do not know what side effects this may have and I am otherwise unfamiliar with this library.  Although I doubt that this will hurt much and is clearly an improvement in this one area, the change may have ramifications of which I could have no reasonable foresight without putting more time in working on this library.  As such I am not supplying a modified JAR, only writing down some easy instructions for everyone else.  Proceed with these instructions at your own risk.
Also, I just checked the license and if you do make this change make sure you follow the instructions that say:
      (b) You must cause any modified files to carry prominent notices
          stating that You changed the files; and

If I'm missing any other legal stuff, please comment to let me know.

A: In answer to @JohnTD, if you are using multiple social connections then you can just do the following to incorporate @attacomsian answer
   public void getProfile(Connection connection) {
    UserProfile socialMediaProfile = getSocialUserProfile(connection);
      .
      .
}

/**
 * Checks for facebook connection requests so that we can call a custom service
 *
 * @param connection
 * @return
 */
private UserProfile getSocialUserProfile(Connection<?> connection) {
    if (isFacebookConnection(connection)) {
        return facebookService.getProfile("me", connection.createData().getAccessToken());
    } else {
        return connection.fetchUserProfile();
    }
}

private boolean isFacebookConnection(Connection<?> connection) {
    return connection.getApi().toString().indexOf("FacebookTemplate") != -1;
}

A: I solved it by overriding the missing field with any other one. Add this somewhere in your code:
    // Patch: spring social facebook tries to get a removed "context" field
    for (int i=0; i<UserOperations.PROFILE_FIELDS.length; i++) {

        // To avoid error override with existing "ratings" field
        if (UserOperations.PROFILE_FIELDS[i].equals("context")) {
            UserOperations.PROFILE_FIELDS[i] = "ratings";
        }
    }


text:
Q: Getting value of anchor tag from repeater? I have a regular html anchor link that is bound to an Id column.  I want to loop through the repeater and get the value of the Id column, but can't figure out how.  I have some code below my repeater markup.  I can't figure out how to do it with just a client side anchor tag.
<asp:Repeater ID="repSearchResults" runat="server">
    <ItemTemplate>

           <a href='<%#Eval("Id")%>'><%#Eval("Id")

</asp:Repeater>

Protected Sub btnGetIds_Click(ByVal sender As Object, ByVal e As System.EventArgs)
    For Each item As RepeaterItem In repSearchResults.Items
        If (item.ItemType = ListItemType.Item) Then

           'Get Id here

        End If

    Next
End Sub

A: You would need to make the anchor runat=server, name it, and then access it with the FindControl method.

A: You could add a hidden field inside each template:
<ItemTemplate>
    <asp:HiddenField ID="hid" runat="server" Value='<%#Eval("Id")%>' />
    ...
</ItemTemplate>

and then inside the loop:
If item.ItemType = ListItemType.Item Then
    Dim ctrl As HiddenField = TryCast(item.FindControl("hid"), HiddenField)
        If ctrl IsNot Nothing Then
            Dim id As String = ctrl.Value
            ' do something with the id
    End If
End If


text:
Q: Django: Calling another modules function passed through a parameter I have a list of functions as:
FUNCS=[{'someattr':'somedetail', 'func':baseapp.module.function_name}, {...}, ...]

Unfortunately it doesnt work if i try calling the func with
FUNCS[0]['func']
I get the error
Tried function_name in module baseapp.module Error was: 'module' object has no attribute 'function_name'
I presume there must be something i'm missing with how python finds functions because the following does work:
   In [11]: def localfunc():
   ....:     print 'hi there'
   ....:     return

   In [13]: f=[{'func':localfunc}]

   In [16]: f[0]['func']()

   hi there

What am i missing?

A: I managed to find the solution.
i = __import__('baseapp.module')
m = getattr(i,'module')
return m.function_name

thanks for the help