text:
Q: Which version of C# am I using I want to find out which version of C# I'm using.
If I would be using python I would do something like python -V from the command line, or type:
import sys
print sys.version

In PHP I would do something like this: phpinfo(); in java: java -version
But I was not able to find how to achieve this in C#.
This question does not answer it, although the name suggests that it should.
I got that it depends on the .NET framework, but is there a programmatic way of figuring out my framework? I mean without going to the directory and checking the name of my .NET folders.

A: To get version of framework - look at version of one of main Assemblies i.e.
 Console.Write(typeof(string).Assembly.ImageRuntimeVersion);

Getting version of C# compiler is somewhat harder, but you should be able to guess version by checking what framework  version is used.
If you are using command line compiler (csc.exe) you can check help to see version (also you'd need to know Framework version anyway:
C:\Windows\Microsoft.NET\Framework\v4.0.30319>csc /?
Microsoft (R) Visual C# 2010 Compiler version 4.0.30319.1

A: The C# version you are using totally depends upon the .Net version you are using.
if you are using visual studio for development, you get to choose the .net framework version
 the c# version associated with it comes accordingly
These are the versions of C# known:

*

*C# 1.0 released with .NET 1.0 and VS2002 (January 2002)

*C# 1.2 (bizarrely enough); released with .NET 1.1 and VS2003 (April 2003). First version to call Dispose on IEnumerators which implemented IDisposable. A few other small features.

*C# 2.0 released with .NET 2.0 and VS2005 (November 2005). Major new features: generics, anonymous methods, nullable types, iterator blocks

*C# 3.0 released with .NET 3.5 and VS2008 (November 2007). Major new features: lambda expressions, extension methods, expression trees, anonymous types, implicit typing (var), query expressions

*C# 4.0 released with .NET 4 and VS2010 (April 2010). Major new features: late binding (dynamic), delegate and interface generic variance, more COM support, named arguments and optional parameters

*C# 5.0 released with .NET 4.5 in August 2012.

Refrence  Jon Skeet's C# Versions Answer

A: .NET version through registry
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\NET Framework Setup\NDP\ explore the children and look into each version. The one with key 'Full' is the version on the system.
https://support.microsoft.com/en-us/kb/318785
https://msdn.microsoft.com/en-us/library/hh925568(v=vs.110).aspx
.NET version through Visual Studio
Help -> About Microsoft Visual Studio -> The .NET version is specified on the top right.
As I understand at this time the Visual studio uses .NET Framework from the OS.
The target .NET Framework version of a project in Visual Studio can be modified with Project Properties -> Application -> Target Framework
Through the dll
If you know the .NET Framework directory
e.g. C:\Windows\Microsoft.NET\Framework64\v4.0.30319
Open System.dll, right click -> properties -> Details tab
C# version
Help -> About Microsoft Visual Studio
In the installed products lists there is Visual C#. In my case Visual C# 2015
Visual Studio (Microsoft) ships C# by name Visual C#.
https://msdn.microsoft.com/en-us/library/hh156499.aspx
C# 6, Visual Studio .NET 2015
Current version, see below

A: By default following are corresponding version of C# compilers for Visual Studio:

*

*Visual Studio 2015: C# 6.0

*Visual Studio 2013: C# 5.0

*Visual Studio 2012: C# 5.0

*Visual Studio 2010: C# 4.0

*Visual Studio 2008: C# 3.0

*Visual Studio 2005: C# 2.0

*Visual Studio.NET 2003: C# 1.2

*Visual Studio.NET 2002: C# 1.0

You can also modify version please follow below steps.
Open the project properties window:
step 1. Right click on the Project Name
step 2. Select "Properties" (last option in menu)
step 3. Select "Build" from left hand side options and scroll till down
step 4. click on "Advance" button.
step 5. It will open a popup and there you will get "Language Version" dropdown
step 6. Select desired version of C# and Click "OK"

A: In visual studio 2022 we can check from project properties inside build in Advanced Tab

A: The language version is chosen based on the project's target framework by default.
Each project may use a different version of .Net framework, the best suitable C# compiler will be chosen by default by looking at the target framework. From visual studio, UI will not allow the users to changes the language version, however, we can change the language version by editing the project file with addition of new property group. But this may cause compile/run time issues in existing code.
<PropertyGroup>
<LangVersion>8.0</LangVersion>
</PropertyGroup>

I could see the following from Microsoft docs.
The compiler determines a default based on these rules:
Target framework  version     C# language version default
.NET Core           3.x         C# 8.0
.NET Core           2.x         C# 7.3
.NET Standard       2.1         C# 8.0
.NET Standard       2.0         C# 7.3
.NET Standard       1.x         C# 7.3
.NET Framework      all         C# 7.3

A: The current answers are outdated. You should be able to use #error version (at the top of any C# file in the project, or nearly anywhere in the code). The compiler treats this in a special way and reports a compiler error, CS8304, indicating the language version, and also the compiler version. The message of CS8304 is something that looks like the following:

error CS8304: Compiler version: '3.7.0-3.20312.3 (ec484126)'. Language version: 6.

A: From developer command prompt ( Visual Studio > View > Terminal ) type :
csc -langversion:?

That will display all C# versions supported including the default:
1
2
3
4
5
6
7.0 (default)
7.1
7.2
7.3 (latest)

A: In order to see the installed compiler version of VC#:
Open Visual Studio command prompt and just type csc then press Enter.
You will see something like following:

Microsoft (R) Visual C# Compiler version 4.0.30319.34209
for Microsoft (R) .NET Framework 4.5
Copyright (C) Microsoft Corporation. All rights reserved.

P.S.: "CSC" stand for "C Sharp Compiler". Actually using this command you run csc.exe which is an executable file which is located in "c:\Windows\Microsoft.NET\Framework\vX.X.XXX". For more information about CSC visit http://www.file.net/process/csc.exe.html

A: It depends upon the .NET Framework that you use.  Check Jon Skeet's answer about Versions.
Here is short version of his answer.

C# 1.0 released with .NET 1.0
C# 1.2 (bizarrely enough); released
with .NET 1.1
C# 2.0 released with .NET 2.0
C# 3.0 released with .NET 3.5
C# 4.0 released with .NET 4
C# 5.0 released with .NET 4.5
C# 6.0 released with .NET 4.6
C# 7.0 released with .NET 4.6.2
C# 7.3 released with .NET 4.7.2
C# 8.0 released with NET Core 3.0
C# 9.0 released with NET 5.0
C# 10.0 released with NET 6.0
C# 11.0 released with NET 7.0

A: Useful tip for finding the C# version:

To know what language version you're currently using, put #error version (case sensitive) in your code. This makes the compiler produce
a diagnostic, CS8304, with a message containing the compiler version
being used and the current selected language version.

From C# language versioning in MS docs.
You can drop #error version anywhere in your code.  It will generate an error so you'll need to remove it after you've used it.  The error gives details of the compiler and language versions, eg:
Error   CS8304  Compiler version: '3.7.0-6.20459.4 (7ee7c540)'. Language version: 8.0.

In VS 2019, at least, you don't need to compile your code for #error version to give you the version number.  Just mousing over it in your code will bring up the same error details you would see when you compile the code.

A: Most of the previous answers are correct. Just consolidating 3 which I found easy and super quick. Also, #1 is not possible now in VS2019.

*

*Visual Studio: Project > Properties > Build > Advanced
This option is disabled now, and the default language is decided by VS itself. The detailed reason is available here.

*Type "#error version" in the code(.cs) anywhere, mousehover it.

*Go to 'Developer Command Prompt for Visual Studio' and run following command.
csc -langversion:?
Read more tips: here.

A: For Windows, you run dev at the command/ search program line and select Developer Command Prompt for VS. Then you are going to just run
csc

Now you get information similar to
Microsoft (R) Visual C# Compiler version 2.6.0.62329 (5429b35d)
Copyright (C) Microsoft Corporation. All rights reserved.

For Windows and if you start with cmd terminal
cd C:\Windows\Microsoft.NET\Framework\
dir

Now you see all directories and files in .NET\Framework\ Please, select v... latest and go there, for example,
cd v4.0.30319

Run
csc

You will see information about version of C# compiler, that can be something similar to
Microsoft (R) Visual C# Compiler version 4.7.2556.0
for C# 5
Copyright (C) Microsoft Corporation. All rights reserved.

A: In Visual Studio, see the C# language version by looking at the build output when build verbosity is set "normal" or higher (default is "minimal").

*

*Adjust your build output verbosity to "Normal", "Detailed", or "Diagnostic". (The other two values, "Quiet" and "Minimal" do not show the language version.) To set build output verbosity, select menu Tools | Options... and then in the "Options" dialog, select "Project and Solutions" | "Build and Run". Look for the label "MSBuild project output verbosity". Set to one of the three values given, above.

*Build (If your build is up to date, force a build with the menu selection Build | Rebuild.)

*Open the Output window
Menu selection View | Output.

*In the output window, set "Build" for the item labeled "Show output from:"

*Search for "langversion". In the middle of a very, very long line (1578 characters on my machine just now) look for a switch like this: /langversion:9.0
(To search in the Output window, click in the Output window then use the keyboard shortcut Ctrl+F to summon the search pane.)

A: While this isn't answering your question directly, I'm putting this here as google brought this page up first in my searches when I was looking for this info.
If you're using Visual Studio, you can right click on your project -> Properties -> Build -> Advanced
This should list available versions as well as the one your proj is using.

A: If you are using VS2015 then follow below steps to find out the same:

*

*Right click on the project.

*Click on the Properties tab.

*From properties window select Build option.

*In that click on the Advance button.

*There you will find out the language version.

Below images show the steps for the same:
Step 1:

Step 2:

A: Thanks to @fortesl and this answer
I'm using VS 2019 and it doesn't easily tell you the C# version you are using.  I'm working with .Net Core 3.0, and VS 2019 using C# 8 in that environment.  But "csc -langversion:?" makes this clear:
D:\>csc -langversion:?
Supported language versions:
default
1
2
3
4
5
6
7.0
7.1
7.2
7.3
8.0 (default)
latestmajor
preview
latest

Not sure what csc -version is identifying:
D:\>csc --version
Microsoft (R) Visual C# Compiler version 3.4.0-beta1-19462-14 (2f21c63b)
Copyright (C) Microsoft Corporation. All rights reserved.

A: Here is an overview of how the .NET framework and compiler versions are related, set and modified. Each project has a target .NET framework version(s), for example version 3.x or 2.x .  The .NET framework contains the run time types and components.
The Visual Studio version installation and the .NET framework version determine the compatible c# language version and compiler options that can be used. The default c# version and options used in a Visual Studio project is the latest language version installed that is compatible with the .NET framework version being used.
To view or update the Framework or C# language within a project within Visual Studio 2011:

*

*right click the project within Solution Explorer and select
Properties

*select 'Application' in the left navigation pane.  Under Target framework: is the .NET framework version. Select the down arrow to see all available framework versions.

*select 'Build' in the left navigation pane. In the 'General' section of the pane next to 'Language Version:' is the c# compiler language version being used, for example 'default' or c# 5.0

*select the down arrow in the 'Language Version:" dropdown to see all available language versions. If 'default' is the c# version being used, the latest compatible c# language version will be used.

To see the exact compiler language version for 'default', enter the following in the developer command prompt for your installed Visual Studio version. For example, from the Windows Start icon select icon: "Developer Command Prompt for VS2011' and enter:

csc -langversion:Default

Microsoft (R) Visual C# Compiler version 4.7.3062.0 for c# 5

A: Here is one weird trick to quickly find what version of C# you are using. Edit any .cs file in your project and add a semicolon at the end on the namespace statement:
namespace Whatever -> namespace Whatever;
The namespace work will become underlined in red; hover you mouse over it and it  will say something like the following:
"CS8370: File-scoped namespace is not available in c#7.3. Please use language version 10.0 or greater."
Tested on VS2022 using a .NET Framework project. If using a .NET or .NET Core project then this feature will work fine.

A: To get the C# version from code, use this code from the Microsoft documentation to get the .NET Framework version and then match it up using the table that everyone else mentions. You can code up the Framework to C# version map in a dictionary or something to actually have your function return the C# version. Works if you have .NET Framework >= 4.5.
using System;
using Microsoft.Win32;

public class GetDotNetVersion
{
   public static void Main()
   {
      Get45PlusFromRegistry();
   }

   private static void Get45PlusFromRegistry()
   {
      const string subkey = @"SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full\";

      using (var ndpKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32).OpenSubKey(subkey))
      {
        if (ndpKey != null && ndpKey.GetValue("Release") != null) {
            Console.WriteLine($".NET Framework Version: {CheckFor45PlusVersion((int) ndpKey.GetValue("Release"))}");
        }
         else {
            Console.WriteLine(".NET Framework Version 4.5 or later is not detected.");
         }
      }

      // Checking the version using >= enables forward compatibility.
      string CheckFor45PlusVersion(int releaseKey)
      {
         if (releaseKey >= 528040)
            return "4.8 or later";
         if (releaseKey >= 461808)
            return "4.7.2";
         if (releaseKey >= 461308)
            return "4.7.1";
         if (releaseKey >= 460798)
            return "4.7";
         if (releaseKey >= 394802)
            return "4.6.2";
         if (releaseKey >= 394254)
            return "4.6.1";
         if (releaseKey >= 393295)
            return "4.6";
         if (releaseKey >= 379893)
            return "4.5.2";
         if (releaseKey >= 378675)
            return "4.5.1";
         if (releaseKey >= 378389)
            return "4.5";
         // This code should never execute. A non-null release key should mean
         // that 4.5 or later is installed.
         return "No 4.5 or later version detected";
      }
   }
}
// This example displays output like the following:
//       .NET Framework Version: 4.6.1


text:
Q: Windows 10 cannot connect to Linux Samba shares, except from SMB1/CIFS I have an issue under Windows 10 to access some Linux Samba shares with following error:
Check the spelling of the name. Otherwise, there might be a problem with your network. To try to identify and resolve network problems click Diagnose.
Error code: 0x80070035
The network path was not found

I can successfully browse from an old openSUSE 12.1 that uses only SMB1/CIFS but not from a more recent openSUSE Leap 15, except if I force NT1 protocol (that is for SMB1/CIFS) on its side, in /etc/samba/smb.conf global section:
[global]
...
min protocol = NT1
max protocol = NT1

For information, by default min protocol is LANMAN1 and max protocol is SMB3, that range then includes NT1 protocol (see SMB protocol min max values available?):
$ testparm --parameter-name="min protocol"
[...]
LANMAN1
$ testparm --parameter-name="max protocol"
[...]
SMB3

And I can access these shared folders from another Linux computer without forcing protocol with following command for example I can list folders:
smbclient -L MyLeap15Computer -N

Or connect to tmp shared folder with:
smbclient //MyLeap15Computer /tmp -N

I also confirmed that SMB2 and 3 are actually active with How to detect, enable and disable SMBv1, SMBv2, and SMBv3 in Windows, and also been able to access them from another Windows 10. And from the computer on which I cannot access them I successfully ping MyLeap15Computer.
Anyway, technically I can access my shared folders by forcing NT1 protocol, but since it should be possible I want to be able to access them from SMB2 or SMB3 since there are security issues in SMB1/CIFS (and then deactivate it in Windows 10 too), also, since I can access them from another Windows 10 without forcing this protocol it then should be something in Windows configuration but I cannot manage to see which since everything appears active on both.
And finally, even if issue seems to be more on client side, here is the server condifuration, /etc/samba/smb.conf without forcing to NT1 protocol (this configuration accepts guest users, then no credentials have to be given for connection):
[global]
workgroup = WORKGROUP
passdb backend = tdbsam
printing = cups
printcap name = cups
printcap cache time = 750
cups options = raw
map to guest = bad user
logon path = \\%L\profiles\.msprofile
logon home = \\%L\%U\.9xprofile
logon drive = P:
usershare allow guests = yes
usershare max shares = 100
winbind offline logon = yes
winbind refresh tickets = yes
create mask = 777
directory mask = 777
delete readonly = yes

[tmp]
comment = Temp folder
path = /tmp
browseable = yes
writable = yes
read only = no
guest ok = yes
mangled names = no

Edit: here are more information after what suggested @JW0914, what was suggested did not work but I found something interesting in server logs (added log level = 3 to /etc/samba/smb.conf global section then looked on /var/log/samba/log.smbd after having tried connection):
  check_ntlm_password:  Checking password for unmapped user [DOMAIN]\[USER]@[Windows10Computer] with the new password interface
[2020/02/05 14:21:23.845849,  3] ../source3/auth/auth.c:192(auth_check_ntlm_password)
  check_ntlm_password:  mapped user is: [DOMAIN]\[USER]@[Windows10Computer]
[2020/02/05 14:21:23.845879,  3] ../source3/auth/check_samsec.c:399(check_sam_security)
  check_sam_security: Couldn't find user 'USER' in passdb.
[2020/02/05 14:21:23.845890,  2] ../source3/auth/auth.c:332(auth_check_ntlm_password)
  check_ntlm_password:  Authentication for user [USER] -> [USER] FAILED with error NT_STATUS_NO_SUCH_USER, authoritative=1
[2020/02/05 14:21:23.845910,  2] ../auth/auth_log.c:760(log_authentication_event_human_readable)
  Auth: [SMB2,(null)] user [DOMAIN]\[USER] at [Wed, 05 Feb 2020 14:21:23.845900 CET] with [NTLMv2] status [NT_STATUS_NO_SUCH_USER] workstation [Windows10Computer] remote host [ipv4:172.168.0.69:56937] mapped to [DOMAIN]\[USER]. local host [ipv4:172.168.0.99:445]
[...]
  No such user USER [DOMAIN] - using guest account
[2020/02/05 14:21:23.847182,  3] ../source3/smbd/server_exit.c:244(exit_server_common)
  Server exit (NT_STATUS_CONNECTION_RESET)

I see server is trying to authenticate with user logged in Windows 10, but since not existing it falls back to guest user but connection is reset just after. In the other side, with a computer for which it is working, when logged with same domain/user and accessing successfully I have quite the same logs (different computer name and IP) but at the end:
  No such user USER [DOMAIN] - using guest account
[2020/02/05 14:43:21.147396,  3] ../lib/util/access.c:365(allow_access)
  Allowed connection from 192.168.0.77 (192.168.0.77)

I'm looking into it but I would be glad if anybody has a clue on what is happening.
Edit2: after a quick look I found a workaround on Windows 10 fall update and samba guest account but when trying net use command I have following issue, then this is my company that may have change security on newer computer (both used are on the same domain but the one not working comes from a newer installation):
You can't access this shared folder because your organization's security policies block unauthenticated guest access. These policies help protect your PC from unsafe or malicious devices on the network.

Thanks

A: In my case (Windows 10, ancient Samba 4.2.10 on CentOS 6) what helped was setting the min protocol to SMB2, max protocol to SMB3:
[global]

min protocol = SMB2
max protocol = SMB3

client min protocol = SMB2
client max protocol = SMB3

client ipc min protocol = SMB2
client ipc max protocol = SMB3

server min protocol = SMB2
server max protocol = SMB3

And then connecting the share as a network drive (Explorer -> Home -> Easy access -> Map as drive), putting in the share name (\\1.2.3.4\ShareName), ticking "Connect using different credentials", then Other, and put in username in the format DOMAIN\username.
When trying to get to the share in Explorer, it would never ask for credentials, nor was I able to specify the username with net use \\shareserver\data /user:testuser (got System Error 58).

A: Running smbpasswd -a user is crucial here!
My running smb.conf:
[global]
    client max protocol = SMB3
    name resolve order = wins lmhosts host bcast
    security = USER
    username map = /etc/samba/smbusers
    idmap config * : backend = tdb

[rootfs]
    create mask = 0644
    force group = root
    force user = root
    path = /
    read only = No

A: Finally, thanks to Can't access shared folder because of organization's security policies, I found a way to override this:

*

*From regedit go to HKLM\SOFTWARE\Policies\Microsoft\Windows

*Create a new Key LanmanWorkstation and within it a new DWORD named AllowInsecureGuestAuth with value 1

*Reboot

Of course not to do without your company approval, I just did it to test but I'm working with our IT to see how we can manage this.

A: In my case, disabling connections on port 139/TCP helped a lot for error 0x80070035 at first connection of Windows 10 client to samba Ubuntu 20.04
[global]
...
smb ports = 445
...

Now connections to the samba server from my home Windows 10 PCs are quicker than ever.
But I really don't know which side effects this will introduce.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How multi match and type phrase is used on _all Let 's say I have the following code:
 "multi_match": {
                                        "query": x,
                                         "type": "phrase",
                                         "fields":"_all",
                                     }

x is a keyword in an array of keywords and I want to search for exact keyword. I know that using _all will concatenate the values for each filed into one big string separated by tabs. Now, my question is that in the above example x is searched in each indexed value?
Thanks,


text:
Q: How to pass data from editText.text to another activity in Xamarin Android when button is clicked From MainActivity.cs to AnotherActivity.cs
  public static string hisname;
    public static string hername;
    private Handler mHandler = new Handler();
    protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);
        SetContentView(Resource.Layout.Register1);
        // Create your application here
        EditText her = FindViewById<EditText>(Resource.Id.editTextHername);
        EditText his = FindViewById<EditText>(Resource.Id.editTextUrname);
        //RotateAnimation anim = new RotateAnimation(0f, 350f, 15f, 15f);
        //anim.setInterpolator
        //anim.setRepeatCount(Animation.INFINITE);
        //anim.Duration(700);
        //splash.StartAnimation(anim);

        WindowRotationAnimation q = new WindowRotationAnimation();
        Button getStarted = FindViewById<Button>(Resource.Id.myButton);
        getStarted.Click += delegate
        {
            var intent = new Intent(this, typeof(CalculateActivity));
            intent.PutExtra("yourname", ""+hisname);
            intent.PutExtra("GFname", "" + hername);
            StartActivity(intent);

        };
    }
}

A: Try with following
var herName = her.text;

vad hisName = his.text;

and add into intent.putextra method.

A:   public static string hisname;
public static string hername;
private Handler mHandler = new Handler();
protected override void OnCreate(Bundle savedInstanceState)
{
    base.OnCreate(savedInstanceState);
    SetContentView(Resource.Layout.Register1);
    // Create your application here
    EditText her = FindViewById<EditText>(Resource.Id.editTextHername);
    EditText his = FindViewById<EditText>(Resource.Id.editTextUrname);
    //RotateAnimation anim = new RotateAnimation(0f, 350f, 15f, 15f);
    //anim.setInterpolator
    //anim.setRepeatCount(Animation.INFINITE);
    //anim.Duration(700);
    //splash.StartAnimation(anim);

    WindowRotationAnimation q = new WindowRotationAnimation();
    Button getStarted = FindViewById<Button>(Resource.Id.myButton);
    getStarted.Click += delegate
    {
        hisname=his.Text;
        hername=her.Text;
        var intent = new Intent(this, typeof(CalculateActivity));
        intent.PutExtra("yourname", hisname);
        intent.PutExtra("GFname",  hername);
        StartActivity(intent);

    };
}

inside your OnCreate of the AnotherActivity.cs you can get these strings like this:
string hisname=Intent.GetStringExtra ("yourname");
string hername=Intent.GetStringExtra ("GFname"); // Seriously :P

This is actually an easy solution if you wanted this one. I would suggest you should research first before you post questions
Happy Coding

A: pass data from your_first_activity to your_next_activity
Intent i = new Intent (Application.Context, typeof(your_next_activity));
i.PutExtra ("item", "item_to_pass");
StartActivity (i);

retrieve data bundle passed from your_first_activity on your_next_activity
string item = Intent.GetStringExtra("item");


text:
Q: Git Pull changes into a mono-repo from another repository I have a single git repository containing multiple projects. I have pulled these projects from different git repos using the method described here:
https://medium.com/@ayushya/move-directory-from-one-repository-to-another-preserving-git-history-d210fa049d4b
Example Repo Structure:
ProjectOne

*

*ProjectA

*ProjectB

*ProjectC

Now, the original git repo of ProjectA is constantly under development and I need to periodically pull in latest changes to my ProjectOne repo. I want to keep the commit history of ProjectA when pulling in changes. Does anyone here has any idea how to do it ?

A: Another approach would be to add ProjectA as a submodule of ProjectOne
cd ProjecTOne
git submodule add ProjectA /url/of/ProjectA

That way, a simple git submodule update --remote would be enough to update its content with the latest of ProjectA, and preserving its history.


text:
Q: How to inject more complex service in slim3 such as Paytrail Below is an example code for "Paytrail_Module_Rest.php", a set of classes for interacting with a rest api for a payment gateway. Some of the classes can be instantiated ahead of time such as (Paytrail_Module_rest which holds credentials), but some need to be instantiated with information only available in the controller, (such as Paytrail_Module_Rest_Payment_S1 which sets payment details such as price)
Can anyone suggest a clean way of injecting it into slim3? I can't see any good way of doing it with the standard container injection methods.
$urlset = new\App\Service\Paytrail\Paytrail_Module_Rest_Urlset(
    "https://www.demoshop.com/sv/success", // return address for successful payment
    "https://www.demoshop.com/sv/failure", // return address for failed payment
    "https://www.demoshop.com/sv/notify",  // address for payment confirmation from Paytrail server
    ""  // pending url not in use
);

$orderNumber = '1';
$price = 99.00;
$payment = new \App\Service\Paytrail\Paytrail_Module_Rest_Payment_S1($orderNumber, $urlset, $price);

$payment->setLocale('en_US');

$module = new \App\Service\Paytrail\Paytrail_Module_Rest(13466, '6pKF4jkv97zmqBJ3ZL8gUw5DfT2NMQ');

try {
    $result = $module->processPayment($payment);
}
catch (\App\Service\Paytrail\Paytrail_Exception $e) {
    die('Error in creating payment to Paytrail service:'. $e->getMessage());
}

echo $result->getUrl();

( credentials listed here are public test credentials )

A: Add the stuff that doesn't change to the container like the module and the urlset thingy
$container[\App\Service\Paytrail\Paytrail_Module_Rest_Urlset::class] = function($c) {
    return new \App\Service\Paytrail\Paytrail_Module_Rest_Urlset(
        "https://www.demoshop.com/sv/success", // return address for successful payment
        "https://www.demoshop.com/sv/failure", // return address for failed payment
        "https://www.demoshop.com/sv/notify",  // address for payment confirmation from Paytrail server
        ""  // pending url not in use
    );
};

$container[\App\Service\Paytrail\Paytrail_Module_Rest::class] = function($c) {
    return new \App\Service\Paytrail\Paytrail_Module_Rest(13466, '6pKF4jkv97zmqBJ3ZL8gUw5DfT2NMQ');
};

And then you either can instantiate the payment every time you need or add a helper class like an adapter:
class PaymentAdapter {

    public function __construct(
            \App\Service\Paytrail\Paytrail_Module_Rest $module,
            \App\Service\Paytrail\Paytrail_Module_Rest_Urlset $urlset)
    {
        $this->module = $module;
        $this->urlset = $urlset;
    }

    function createAndProcessPayment($orderNumber, $price)
    {
        $payment = new \App\Service\Paytrail\Paytrail_Module_Rest_Payment_S1($orderNumber, $this->urlset, $price);

        $payment->setLocale('en_US');
        try {
            $result = $module->processPayment($payment);
        }
        catch (\App\Service\Paytrail\Paytrail_Exception $e) {
            die('Error in creating payment to Paytrail service:'. $e->getMessage());
        }
        return $result;
    }

}

Then add the adapter also to the container:
$container[\yournamespace\PaymentAdapter::class] = function($c) {
    return new \yournamespace\PaymentAdapter(
        $c[\App\Service\Paytrail\Paytrail_Module_Rest::class],
        $c[\App\Service\Paytrail\Paytrail_Module_Rest_Urlset::class]
    );
};


text:
Q: Add new line of text to multiple files I am looking for a tool/shell command to edit multiple files. My exact use case is search recursively for a config files with a particular name and add a new line of config to it.
Rewording:
I have a bunch of configs in several dirs:
For ex:
/Users/myth/app1/config/a.cfg
/Users/myth/app1/config/b.cfg

/Users/myth/app2/config/a.cfg
/Users/myth/app2/config/b.cfg

/Users/myth/app3/config/a.cfg
/Users/myth/app3/config/b.cfg

/Users/myth/app4/config/a.cfg
/Users/myth/app4/config/b.cfg

I have to insert a line of configuration only in the a.cfg of all apps. I can find all the configs with find . -name "a.cfg". Now how would I pipe that to something like an echo or tee to just append a line of config on the last line of all a.cfg? I cannot use a shared a.cfg for these apps because content of a.cfg is not the same for all apps. But this line I intend to add is the same.
Update:
This is what I ended up using:
for configFile in $(find /Users/myth -type f -name "a.cfg" | xargs grep -iL "new config")
do
    echo "new config" >> $configFile
done

A: echo >> `find /start/directory -name "a.cfg"`

Echo should add append a new line to a list of paths listed by find command. Backtick enrures the "right" part of the command happens first.


text:
Q: Does the Implicit Function Theorem in Banach spaces holds if the differential is only one-to-one (not onto!)? Is the Implicit Function Theorem in the following form correct:
Let $V_1,V_2,W$ be Banach spaces, and $Ω⊂V_1×V_2$ an open subset containing $(x_0,y_0)$. Let consider a continuously differentiable map $f:Ω→W$ with $f(x_0,y_0)=0$ and s.t. the derivative on the second component
$D_2f(x_0,y_0):V_2\ni y↦Df(x_0,y_0)(0,y)∈W$
is one-to-one (but not necessarly onto).
Then there exists an open set $Ω_1×Ω_2⊂Ω$ around $(x_0,y_0)$ and a unique map
$g:Ω_1→Ω_2$ s.t $f(x,g(x))=0$ for all $x∈Ω_1$.
Indeed, the standard strategy would be to consider
$L \equiv D_2f_{(x_0,y_0)}$ and     $
\Phi(x,y)\equiv y - (L^{-1}\circ f)(x,y).
$
However, the map $\Phi$ is not defined everywhere. Indeed, it is defined only on
$$f^{-1}\bigg(L\big(V_2\big)\cap f(\Omega)\bigg).$$
I look forward to reading your comment, possibly references where I can find a proof if that statement is correct. Thanks in advance

A: No, it is not correct. Simple counterexamples can be obtained as follows. Let $V_1=W$ and $V_2$ be any Banach spaces such that the identity is continuous but not surjective $V_2\to W$. Then $f$ defined by $(x,y)\mapsto x+y$ is even smooth with $\partial_2 f(x_0,y_0)$ injective $V_2\to W$ and there cannot be any $g,\Omega_1,\Omega_2$ as required since we would have $g(x)=-x$ for all $x\in\Omega_1$ and further $W\subseteq V_2$.


text:
Q: Dynamic UITableView height in embedded view I have a table view as part of a larger controller. This table view can have various number of rows and rows are expandable (e.g. unselected state is 50pt, selected -> 120pt).
To animate sell expanding/collapsing I use those methods:
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    tableView.beginUpdates()
    tableView.endUpdates()
    view.setNeedsLayout()
    view.layoutIfNeeded()
}

func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {
    tableView.beginUpdates()
    tableView.endUpdates()
    view.setNeedsLayout()
    view.layoutIfNeeded()
}

But I need to update container view height in parent view controller together with the table view.
I've tried to achieve that by adding observer to the contentSize of the tableView and assigning its height to the containerView height constraint. Its kinda work but animation of the containerView height happens after cell increase/decrease animation already happened.
Is there a way to achieve dynamic height table view in embedded view controller?
PS. I don't want to use table view footer/header to put surrounding views there as surrounding view structure is more complex and table view is just part of it.


text:
Q: PrintStream is buffered, but flush does not degrade performance and BufferedOutputStream speeds up performance I expected that since PrintStream is buffered, by adding a flush operation after every print(), the speed performance should degrade significantly, but it did not at all, as shown in the below code snippet.
Furthermore, wrapping a PrintStream around a BufferedOutputStream improves performance by more than 10x -- implying that PrintStream is not buffered.
Is PrintStream really not buffered, or does it have a very small buffer, or is there some other explanation for why it does not afford the speed improvement expected from a buffered stream?
       // PrintStream is buffered but takes 4228ms to complete
    long start = System.currentTimeMillis();
    try (PrintStream ps = new PrintStream(new FileOutputStream("1.txt") ))
    {
        for (int i = 0; i < 1_000_000; i++) {
            ps.print(i + " ");
        }
    }
    long stop = System.currentTimeMillis();
    System.out.println(stop - start);

     // PrintStream is buffered, but with auto-flush takes 4140ms to complete, no degraded speed implying flush did nothing
    start = System.currentTimeMillis();
    try (PrintStream os = new PrintStream(new FileOutputStream("1.txt") ))
    {
        for (int i = 0; i < 1_000_000; i++) {
            os.print(i + " ");
            os.flush();
        }
    }
    stop = System.currentTimeMillis();
    System.out.println(stop - start);
    // PrintStream is buffered explicitly as a BufferedOutputStream and runs quickly: 202ms
    start = System.currentTimeMillis();
    try (PrintStream os = new PrintStream(new BufferedOutputStream(new FileOutputStream("1.txt")) ))
    {
        for (int i = 0; i < 1_000_000; i++) {
            os.print(i + " ");
        }
    }
    stop = System.currentTimeMillis();
    System.out.println(stop - start);

A: While the internals are "buffered", the write method flushes the internal buffers to the underlying stream on every write().  So in your first two examples, every write() is ultimately hitting FileOutputStream.  In your third scenario, you are getting actual buffering, where writes are only periodically hitting the FileOutputStream.
If you used your own underlying stream instead of FileOutputStream, you would see that the first two scenarios will result in ~1,000,000 write calls to your stream, whereas the last case will result in much fewer calls (based on the buffer size).


text:
Q: What are the benefits of code blocks inside a method? I've seen a method, which contains several blocks:
public class SomeClass {
    public void someMethod() {
        {
            ...
        }
        {
            ...
        }
        {
            ...
        }
    }
}

What are the benefits of such structure compared to the usual approach (put the code of each of the blocks into its own method and call them from someMethod) ?
What could be the reason the author of that source wrote it that way?

A: They can be useful for organising local variables:
{
    List<String> someTemporaryThing = getTemporaryThing();
    processTemporaryThing1(someTemporaryThing);
    processTemporaryThing2(someTemporaryThing);
}

// other code that doesn't need to see someTemporaryThing

Of course, if you have more than a few lines in one of these it might be a good idea to make it a separate method.
I haven't found any other use for them.

A: This is legacy from C, where, originally, variables could be declared only at the start of a code block (i.e. right after a {).
In Java, it is only useful if, as you said already, you don't want to move the code in these blocks to separate methods, but want to keep their variables out of your method's scope. This could theoretically get some increase in performance compared to taking the stuff out to methods.


text:
Q: Parallelization of image processing on very large image set in MATLAB without Parallel Processing Toolkit I have apprxoimately 2,500,000 images to process on a single computer. I currently run sequentially an input image for a single output to my function (it takes ~5 seconds to compute). This obviously takes too much time. What other methods can I employ to speed up the process? I thought of starting multiple instances of MATLAB and running each on a subset of the data, but I'm not sure if I truly achieve parallelism with this method. What are better methods of increasing the overall speed?

A: As no-one seems to be helping out, I thought I would have a little attempt and see if I can get you started with some parallelisation. I do not use Windows or Matlab, so it may need some correcting... so, if anyone knows better... feel free to contribute.
You can install GNU Parallel under Cygwin in Windows - there are plenty of tutorials and blogs describing the process if you Google them.
First, I'm guessing/hoping that the following command will process one such image from the command line, so have a little experiment and see if that will work before you move to the next step
matlab.exe -nodisplay -nosplash -nodesktop -r "run('mfile.m image.jpg');exit;"

Then, to run in parallel, you will need to generate a list of all 2,500,000 JPEGs, so that will look something like this
DIR /B /S | FINDSTR /I "*JPG$"

and you will need to feed that into GNU Parallel, something like this
DIR /B /S | FINDSTR /I "*JPG$" | parallel matlab.exe -nodisplay -nosplash -nodesktop -r "run('mfile.m {}');exit;"

Obviously test this out on a dummy directory with a copy of a few of your files so that nothing gets broken or overwritten.
As @Daniel suggests, there is overhead to starting Matlab, so it would probably be better to change your code to process all images supplied as arguments, then maybe you could pass 2-8 images to each invocation of Matlab, something like this for 4 images per Matlab job:
DIR /B /S | FINDSTR /I "*JPG$" | parallel -N 4 matlab.exe -nodisplay -nosplash -nodesktop -r "run('mfile.m {1} {2} {3} {4}');exit;"


text:
Q: maximum connected component in matrix Somebody please help me find the maximum (longest) connected component (not diagonally, only bottom, top, left and right) in a matrix. My code does not work, I have been tying to solve this problem for 24 hours.
For first version:
What's idea? For example, take one element with value '1' and change its value to '2' and look for the other '1' around. Change their ('1' around) value to 3. Take one elem with value '3', look for '1' around, change '1' to '4', etc. All elements > 1 are calculated (l) and compared with the intermediate value of the largest component (comps[u], comps[1] for initial '1').
import random

n = int(input())
m = int(input())

#create and output matrix with elems 1-4

a = [[0]*(m+2) for i in range(n+2)]
b = [[0]*(m+2) for i in range(n+2)]

for i in range(n+2):
    for j in range(m+2):
        if i == 0 or i == n+1 or j == 0 or j == m+1:
            a[i][j] = -100
for i in range(1, n+1):
    for j in range(1, m+1):
        s = random.randint(1, 4)
        a[i][j] = s

for i in range(1, n+1):
    for j in range(1, m+1):
        print(a[i][j], end = " ")
    print()

comps = [0]*5 #counter of longest components
u = 1  #it is value of the elem, adjacent elems whith which we well check

def main(u):
    if u == 5: return()
    global a
    global b
    k = 0
    l = 0
    global m
    global n
    global comps
    for i in range(1, n+1):
        for j in range(1, m+1):
            if a[i][j] == u and k == 0:
                b[i][j] = 2
                k+=1

            elif a[i][j] == u:
                b[i][j] = 1
                k+=1

    w = m//2
    v = n//2
    #a[v][w] = u
    #b[v][w] = 2
    p = True
    c = 2
    while p:
        for h in range(1, n+1):
            for hh in range(1, m+1):
                    if b[h][hh] == c and b[h-1][hh] == 1:
                        b[h-1][hh] = c+1
                        c += 1
                    if b[h][hh] == c and b[h+1][hh] == 1:
                        b[h+1][hh] = c+1
                        c += 1
                    if b[h][hh] == c and b[h][hh-1] == 1:
                        b[h][hh-1] = c+1
                        c += 1
                    if b[h][hh] == c and b[h][hh+1] == 1:
                        b[h][hh+1] = c+1
                        c += 1
                    else:
                        b[h][hh] = 2
                    if c not in b:
                        p = False
                        break
    for x in range(1, n+1):
        for y in range(1, m+1):
            if b[x][y] > 1:
                l += 1
                b[x][y] = 0
                a[x][y] = 0
    if l > comps[u]:comps[u] = l
    if k == l:
        u+=1
    main(u)

main(u)

maxk = max(comps)
for i in range(1,5):
    if comps[i] == maxk:
        print('The length of the longest con. comp. for digit ', i, ' is ', comps[i])

And second version with recursion, it's does not work either.
import random

n = int(input())
m = int(input())

a = [[0]*(m+2) for i in range(n+2)]
b = [[0]*(m+2) for i in range(n+2)]

def deep_find(q, o):
    global b
    global ww
    ww += 1
    t = q
    d = o
    b[t][d] = 0
    if t <= n and b[t+1][d] == 1:
        deep_find(t+1, d)
    if t >= 1 and b[t-1][d] == 1:
        deep_find(t-1, d)
    if d<= m and b[t][d+1] == 1:
        deep_find(t, d+1)
    if d>= 1 and b[t][d-1] == 1:
        deep_find(t, d-1)
    print(ww)
    return()

for i in range(n+2):
    for j in range(m+2):
        if i == 0 or i == n+1 or j == 0 or j == m+1:
            a[i][j] = -100
for i in range(1, n+1):
    for j in range(1, m+1):
        s = random.randint(1, 4)
        a[i][j] = s

for i in range(1, n+1):
    for j in range(1, m+1):
        print(a[i][j], end = " ")
    print()

comps = [0]*5
u = 1
while u!=5:
    k = 0
    for i in range(1, n+1):
        for j in range(1, m+1):
            if a[i][j] == u:
                b[i][j] = 1
                k+=1
    p = True
    while p:
        for i in range(1, n+1):
            for j in range(1, m+1):
                if b[i][j] == 1:
                    t = i
                    d = j
                    ww = 0
                    deep_find(t, d)
                    p = False
                    break

    if ww>comps[u]: comps[u] = ww
    if ww == k: u += 1

maxk = max(comps)
for i in range(1,5):
    if comps[i] == maxk:
        print( i, comps[i])


text:
Q: Assigning data to a socket I'm working with Socket.io, node.js, and express to make a simple two player game that can be played online. Everything I've found on the subject so far either doesn't address my question or is far more complex than what I'm after.
Essentially, I want players to be able to join a room (which I have solved already), and when in a room, need to assign "player 1" and "player 2" attributes to each player. I imagine assigning player 1 to the first connected user and player 2 to the second, but I haven't figured out exactly how to do the assignment of values/variables to an individual socket connection.

A: You can add attributes to individual sockets like this:
io.sockets.on('connection', function(socket){
    socket.name = 'John';
    console.log(socket.name); // prints out 'John'
});

A: It seems like what you're looking for should be pretty straightforward.  I like @iheartramen's answer, except it makes it difficult to determine what sockets belong to what room.  What I would do is keep a list of rooms, and what sockets belong to them:
var _rooms = [
  {
    id: 'Some Unique Room ID',
    playerSockets: []
  }
  //...
}

Then when a player connects to a given room, you just add their connection to the list:
io.sockets.on('connection',function(socket){
    var room = getRoom();   // however it is you're mapping rooms...
                            // this returns a reference to a room object
                            // in the _rooms array
    // you can cap the number of players here
    socket.playerNumber = room.sockets.length+1;
    room.sockets.push( socket );
}

And now you have backwards and forward mapping.  You don't have to worry about thread safety with the push() method because there's only a single event thread.


text:
Q: Disable / Enable Chrome Extension Via Browser Action / Icon The chrome extension I am developing inserts content scripts and css onto every page of a website.  However, the user may have a certain page or pages he or she does not want the extension to run on, so it would be great if I could set up the browser action as basically a toggle on / off.
What I'd like to do is something like this:
chrome.browserAction.onClicked.addListener(function(tab) {

    //IF ENABLED THEN DISABLE

    //IF DISABLED THEN ENABLE

}

Any help would be greatly appreciated!

A: Such API is not provided. But two possible workarounds exist:
I. You can use the "disabled" flag variable and update it from your background page.
Background page:
function disableExtension(disabled)
{
    chrome.windows.getAll({populate : true}, function (window_list)
    {
        for (var i = 0; i < window_list.length; ++i)
        {
            var window = window_list[i];
            for (var j = 0; j < window.tabs.length; ++j)
            {
                var tab = window.tabs[j];
                if (checkContentScriptExists(tab))
                {
                    chrome.tabs.executeScript(tab.id, {code : "disabled = " + disabled + ";"}, allTabs: true)
                }
            }
        }
        // No matching url found. Open it in the new tab
        chrome.tabs.create({ url : url, selected: true });
    });
}

And content script should check the condition before the run
if (!disabled) doSomething();

II. A controversial approach to save disable variable within background page content
Background page:
function disableExtension(disabled)
{
    global.disabled = disabled;
}
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    if (request.msg == "getDisabled") {
        sendResponse({disabled: global.disabled});
        return true;
    }
});

and the content script should query currently disabled status before execution
chrome.runtime.sendMessage({msg: "getDisabled"}, function(response) {
   if (!response.disabled) doSomething();
});

A: Chrome extensions have APIs of their own. You can invoke them via content scripts. Not sure if you can invoke them via any third party JS. Refer this ink
Hope it helps.


text:
Q: XSLT to work on a particular group of nodes I want a XPath which will consider a particular group and ignore all other groups. Below is my XML code:
    <GetBillList>
    <Case>
    <CaseID>...</CaseID>
    <BillGroup>
    <BillGroupID>...</BillGroupID>
    </BillGroup>
    </Case>
    <StartDate>2014-01-01</StartDate>
    <GetBillListResponse>
    <Bill>
    <BillStatusCode>
    <BillStatusCode>type description</BillStatusCode>
    <typecode>1</typecode>
    </BillStatusCode>
    <EBillProcessStatusCode>
    <EBillProcessStatusCode>type description</EBillProcessStatusCode>
    <typecode>2</typecode>
    </EBillProcessStatusCode>
    <ToDate>...</ToDate>
    </Bill>
    </GetBillListResponse>
    </GetBillList>

XSLT Code:
     <xsl:stylesheet version="1.0"
     xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
    <xsl:strip-space elements="*"/>

    <xsl:template match="*">
    <xsl:copy>
    <xsl:for-each select="id | typecode">
    <xsl:attribute name="{name()}">
    <xsl:value-of select="."/>
    </xsl:attribute>
    </xsl:for-each>
    <xsl:apply-templates select="node()[not(self::id or self::typecode)]"/>
    </xsl:copy>
    </xsl:template>

    <xsl:template match="*[name(.) = name(..)]">
    <xsl:apply-templates/>
    </xsl:template>
    </xsl:stylesheet>

I want it to work on "GetBillListResponse" only ignoring "Case" group & "StartDate" element.
Desired output:
    <GetBillList>
    <GetBillListResponse>
    <Bill>
    <BillStatusCode typecode="1">type description</BillStatusCode>
    <EBillProcessStatusCode typecode="2">type description</EBillProcessStatusCode>
    <ToDate>...</ToDate>
    </Bill>
    </GetBillListResponse>
    </GetBillList>

Would Appreciate any help on this!

A: If I will just base my answer on your current input and XSLT, just add:
<xsl:template match="Case|StartDate"/>

in your stylesheet.
EDIT
if you want to work on the nodes you like to, get this instead:
<xsl:template match="/">
    <GetBillList>
        <xsl:apply-templates select="GetBillList/GetBillListResponse"/>
    </GetBillList>
</xsl:template>


text:
Q: Mongoose async/await find then edit and save? Is it possible to do a find then save using async/await promise?
I have the following code:
try {
    var accounts = await Account.find()
    .where("username").in(["email@gmail.com"])
    .exec();
    accounts.password = 'asdf';
    accounts.save();
} catch (error) {
    handleError(res, error.message);
}

and I am getting the following error:
ERROR: accounts.save is not a function

A: This is what I was looking for:
try {
    var accounts = await Account.findOneAndUpdate(
        {"username" : "helllo@hello.com"},
        {$set: {"password" : "aaaa"}},
        {new : true}
    );
    res.status(200).json(accounts);
} catch (error) {
    handleError(res, error.message);
}

or (thanks @JohnnyHK for the find vs findOne tip!):
try {
    var accounts = await Account.findOne()
    .where("username").in(["hello@hello.com"])
    .exec();
    accounts.password = 'asdf';
    accounts.save();
    res.status(200).json(accounts);
} catch (error) {
    handleError(res, error.message);
}


text:
Q: Multi-row x-axis labels in ggplot line chart Edit: This question has been marked as duplicated, but the responses here have been tried and did not work because the case in question is a line chart, not a bar chart. Applying those methods produces a chart with 5 lines, 1 for each year - not useful. Did anyone who voted to mark as duplicate actually try those approaches on the sample dataset supplied with this question? If so please post as an answer.
Original Question:
There's a feature in Excel pivot charts which allows multilevel categorical axes.I'm trying to find a way to do the same thing with ggplot (or any other plotting package in R).
Consider the following dataset:
set.seed(1)
df=data.frame(year=rep(2009:2013,each=4),
              quarter=rep(c("Q1","Q2","Q3","Q4"),5),
              sales=40:59+rnorm(20,sd=5))

If this is imported to an Excel pivot table, it is straightforward to create the following chart:

Note how the x-axis has two levels, one for quarter and one for the grouping variable, year. Are multilevel axes possible with ggplot?
NB: There is a hack with facets that produces something similar, but this is not what I'm looking for.
library(ggplot2)
ggplot(df) +
  geom_line(aes(x=quarter,y=sales,group=year))+
  facet_grid(.~year,scales="free")

A: New labels are added using annotate(geom = "text",. Turn off clipping of x axis labels with clip = "off" in coord_cartesian.
Use theme to add extra margins (plot.margin) and remove (element_blank()) x axis text (axis.title.x, axis.text.x) and vertical grid lines (panel.grid.x).
library(ggplot2)

ggplot(data = df, aes(x = interaction(year, quarter, lex.order = TRUE),
                      y = sales, group = 1)) +
  geom_line(colour = "blue") +
  annotate(geom = "text", x = seq_len(nrow(df)), y = 34, label = df$quarter, size = 4) +
  annotate(geom = "text", x = 2.5 + 4 * (0:4), y = 32, label = unique(df$year), size = 6) +
  coord_cartesian(ylim = c(35, 65), expand = FALSE, clip = "off") +
  theme_bw() +
  theme(plot.margin = unit(c(1, 1, 4, 1), "lines"),
        axis.title.x = element_blank(),
        axis.text.x = element_blank(),
        panel.grid.major.x = element_blank(),
        panel.grid.minor.x = element_blank())

See also the nice answer by @eipi10 here: Axis labels on two lines with nested x variables (year below months)

A: The suggested code by Henrik does work and helped me a lot! I think the solution has a high value. But please be aware, that there is a small misstake in the first line of the code, which results in a wrong order of the data.
Instead of
... aes(x = interaction(year,quarter), ...

it should be
... aes(x = interaction(quarter,year), ...

The resulting graphic has the data in the right order.

P.S. I suggested an edit (which was rejected until now) and, due to a small lack of reputation, I am not allowed to comment, what I rather would have done.

A: User Tung had a great answer on this thread
library(tidyverse)
library(lubridate)
library(scales)

set.seed(123)
df <- tibble(
  date = as.Date(41000:42000, origin = "1899-12-30"),
  value = c(rnorm(500, 5), rnorm(501, 10))
)

# create year column for facet
df <- df %>%
  mutate(year = as.factor(year(date)))

p <- ggplot(df, aes(date, value)) +
  geom_line() +
  geom_vline(xintercept = as.numeric(df$date[yday(df$date) == 1]), color = "grey60") +
  scale_x_date(date_labels = "%b",
               breaks = pretty_breaks(),
               expand = c(0, 0)) +
  # switch the facet strip label to the bottom
  facet_grid(.~ year, space = 'free_x', scales = 'free_x', switch = 'x') +
  labs(x = "") +
  theme_classic(base_size = 14, base_family = 'mono') +
  theme(panel.grid.minor.x = element_blank()) +
  # remove facet spacing on x-direction
  theme(panel.spacing.x = unit(0,"line")) +
  # switch the facet strip label to outside
  # remove background color
  theme(strip.placement = 'outside',
        strip.background.x = element_blank())
p


text:
Q: Best way to create an user authentication in Objective-C iOS App I'm currently developing my own service with its own app. The service has a backend JSON API that the app uses to communicate.
Now, since an iOS app does not have sessions or cookies, I was wondering how I would go about creating a user authentication/login for my app. Should I simply locally encrypt the password/username and then, for every action (such as posting a new entry), send the user/password with the request (which seems unsafe), use a token-based system (app receives a token from the service when authenticating, saves it locally - encrypted - and then sends it with the request), or something else? Should I try to implement OAuth for my service?
I'm using the CodeIgniter Rest API for the backend.
Thanks!

A: My preference includes both. I normally use oauth2 with a bearer token setup (if I remember correctly). I ask for a username/email + password, encrypt the password client-side and send it to the server via Basic Auth in return for an access token which I can send on all consecutive calls. That way I can always revoke access to the backend by invalidating the access token. Oauth2 is much easier to implement than Oauth 1.0a and by following the specification, it is easy to open up your api for 3rd party apps later.
The Oauth2 access token can be send as a GET parameter, but lately I start to think sending it as a header might be preferable, to distinguish better the meta parameters like an access token and data parameters like it's or a model's actual data.


text:
Q: Opcion MODIFICAR en programacion BATCH estoy haciendo un menu basico con las tipicas opciones, Registrar, Eliminar,Modificar y Mostrar Todos, conciste en que el usuario ingresa datos y esos datos que ingresa se guardan en un archivo.txt con el nombre que ingreso.
El caso, ya hice la opcion de registrar y eliminar funcionan correctamente, el tema es en modificar (ya paso codigo) donde si me modifica la letra, pero no me aparece el nombre de la variable, simplemente sale espacio en blanco, código:
@echo off
:inicio
echo.
echo MENU PRINCIPAL
echo 1. Alta
echo 2. Baja
echo 3. Modificar
echo 4. Mostrar Todos
echo 0.Salir

set /P op= Ingrese una opcion:

echo.

if %op% == 1 (GOTO :alta)
if %op% == 2 (GOTO :baja)
if %op% == 3 (GOTO :modificar)
if %op% == 4 (GOTO :mostrarTodos) else (echo Opcion incorrecta
     GOTO :inicio)

:alta
echo.
set /P nombre= Ingrese un nombre:
set /P ci= Ingrese la cedula de identidad:
mkdir Personal
echo Nombre: %nombre% > Personal/%nombre%.txt
echo Cedula: %ci% >> Personal/%nombre%.txt
GOTO :inicio

:modificar
set /P nombre= Ingrese un nombre:
if exist Personal\%nombre%.txt (
set /p nuevoNombre= Ingrese el nuevo nombre:
set /P nuevaci= Ingrese la cedula de identidad:
echo Nombre: %nuevoNombre% > Personal/%nombre%.txt   :: Me sale 'Nombre: ' espacio en blanco
echo Cedula: %nuevaci% >> Personal/%nombre%.txt)
GOTO :inicio

En cambio si el código de modificar lo pongo en la etiqueta :alta si me lo modifica correctamente.

A: @echo off
:inicio
cls <-------
echo.
echo MENU PRINCIPAL
echo 1. Alta
echo 2. Baja
echo 3. Modificar
echo 4. Mostrar Todos
echo 0.Salir

set /P op= Ingrese una opcion:

echo.

if %op% == 1 (GOTO :alta)
if %op% == 2 (GOTO :baja)
if %op% == 3 (GOTO :modificar)
if %op% == 4 (GOTO :mostrarTodos) else (echo Opcion incorrecta
     GOTO :inicio)

:alta
echo.
set /P nombre= Ingrese un nombre:
set /P ci= Ingrese la cedula de identidad:
mkdir Personal
echo Nombre: %nombre% > Personal/%nombre%.txt
echo Cedula: %ci% >> Personal/%nombre%.txt
GOTO :inicio

:modificar
cd Personal <-------
set /P nombre= Ingrese un nombre:
if exist %nombre%.txt (call:modificar_code) <-------
GOTO :inicio

:modificar_code <-------
set /p nuevoNombre= Ingrese el nuevo nombre:
set /P nuevaci= Ingrese la cedula de identidad:
ren "%nombre%.txt" "%nuevoNombre%.txt" <-------
echo Nombre: %nuevoNombre% > %nuevoNombre%.txt <-------
echo Cedula: %nuevaci% >> %nuevoNombre%.txt <-------
goto:EOF <-------

Con esto ya funcionaría, no puedes meter tantas cosas dentro de un if, tienes que llamar a una función desde el if o redireccionar el código a una etiqueta, además he añadido algunos detalles como limpiar la pantalla cada vez que llegas al menu para que no se repita constantemente y he solucionado un fallo que había al crear el archivo modificado.
Veo que estas empezando con este lenguaje, si tienes cualquier duda no dudes en preguntarme ya que me considero un usuario experto en este lenguaje. (las líneas cambiadas estan marcadas con flechas, quítalas antes de ejecutar el código).


text:
Q: remove a row from data table I want to exclude the last number in the table so that my data only has the following numbers
accuracy <- c(18,25,23,22,20,14,31,20,24,6,24,12,16,24,23,15,14,24,42,19,27,13,23,6,28,30,22,33,12,21,38,16,17,11,29,18,22,21,29,19,17,28,20,35,14,14,35,30,18,37,23,8,19,38,24,28,12,25,12,32,19,20,27,25,24,32,16,16,13,21,30,23,5,18,20,33,18,37,20,11,32,13,30,18,7,27,18,24,26,14,13,21,35,25,18,25,34,34,24,23)

A: Try adding
data3=data3[-(101:102),]

after creating data3.


text:
Q: Is there any class architecture diagram for react native published somewhere? I am trying to wrap my around the complex architecture of react native and was wondering if there is any class diagram architecture published somewhere?
Can someone please help me with this?
Thanks!


text:
Q: Finding Sum Of The Differences OF MAX and MIN of All Possible Subsets Given a set of elements, how can I find difference between MAX and MIN in all subsets of this list.
Eg:
set =  1 2 3
Subset = {1}, max(s)-min(s) = 0.
Subset = {2}, max(s)-min(s) = 0.
Subset = {3}, max(s)-min(s) = 0.
Subset = {1,2}, max(s)-min(s) = 1.
Subset = {2,3}, max(s)-min(s) = 1.
Subset = {1,3}, max(s)-min(s) = 2.
Subset = {1,2,3}, max(s)-min(s) = 2.

So the output will be 1+1+2+2 = 6

A: Sort the list.
After sorting, the i'th element will be minimum in all (and only) subsets that do not include the i-1 first elements, and does include this element. There are 2^(n-i) of those (when i is 1 based).
Similarly, i will be the highest element in each subset that does not include any number after i, and do include i, and there are 2^(i-1) such subsets (again, 1 based).
So, after sorting, just iterate, and for each i add:
arr[i] * (2^(i-1) - 2^(n-i))

Effectively adding the sum by arr[i] * #times_i_is_max, and reducing it by arr[i] * #times_i_is_min
In your example:
sorted=1,2,3
1* (2^0 - 2^2) + 2*(2^1 - 2^1) + 3*(2^2 - 2^0) =
1*(-3) + 2*0 + 3*(3) = -3 + 0 + 9 = 6

The bottleneck of this algorithm is the sorting, which is O(nlogn) - after that, everything is done in linear scan of the array.

A: @mukul
you can calculate all powers of 2 and store them in an array taking mod simultaneously
like
a[0]=1; for(i=1;i<any_no;i++)a[i]=(a[i-1]*2)%MOD;


text:
Q: Loses styling after horizontal scroll I'm combining react-window-scroller, react-window, and react-table - I'm experiencing issues when scrolling horizontally. It seems like it loses the styling on each row. Try scrolling a bit down, and then scroll horizontally - All content disappears, now try scrolling vertically and it shows again?
URL to issue:
https://codesandbox.io/s/react-window-full-height-page-scroll-7zg47?file=/src/App.js
I'm not sure what's causing this problem. If I remove the styling property on the list, in works, but then I lose the scrolling to window functionality...

A: A potential, but REALLY ugly solution is to trigger a scroll event onScroll:
const triggerScroll = () => {
  window.dispatchEvent(new CustomEvent('scroll'));
};

<VariableSizeList
                ref={ref}
                outerRef={outerRef}
                height={window.innerHeight}
                style={{...style, overflow: 'hidden'}}
                itemCount={data.length + 1}
                itemSize={() => 29}
                onScroll={triggerScroll}
                itemData={rows}
              >
                {renderRow}
              </VariableSizeList>

I dont think this is a good solution, but for now, I cant see any other way of solving this. Im hoping someone out there has a better solution for this problem? :)


text:
Q: IllegalStateException in android while using listview I have an activity_A which contains listView, this listView dynamically increases in size adding 10 items everytime I scroll to the bottom of the list, in the same activity_A I have an editTextView and a go_button which searches for the string in the editTextView.
Search is my activity_B which has a listView, even this listView dynamically increases in size adding 10 items every time.
My problem is when I want to go back to the activity_A from activity_B using a button click (not the back button of my device) it gives me this exception.
java.lang.IllegalStateException: The content of the adapter has changed but ListView did not receive a notification. Make sure the content of your adapter is not modified from a background thread, but only from the UI thread.

My way of going back to activity_A from activity_B is:
public void onClick(View v)
{
        Intent intent = new Intent(activity_B.this, activity_A.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
        startActivity(intent);
}

I even tried by removing intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT); line

A: try to use requestLayout() for your ListView.


text:
Q: Very simple application fails with "multiple target patterns" from Eclipse Since I'm more comfortable using Eclipse, I thought I'd try converting my project from Visual Studio. Yesterday I tried a very simple little test. No matter what I try, make fails with "multiple target patterns". (This is similar to this unanswered question.)
I have three files:
Application.cpp:
using namespace std;

#include "Window.h"

int main() {
    Window *win = new Window();
    delete &win;
    return 0;
}

Window.h:
#ifndef WINDOW_H_
#define WINDOW_H_

class Window {
public:
    Window();
    ~Window();
};

#endif

Window.cpp:
#include <cv.h>
#include <highgui.h>

#include "Window.h"

const char* WINDOW_NAME = "MyApp";

Window::Window() {
    cvNamedWindow(WINDOW_NAME, CV_WINDOW_AUTOSIZE);
    cvResizeWindow(WINDOW_NAME, 200, 200);
    cvMoveWindow(WINDOW_NAME, 0, 0);
    int key = 0;
    while (true) {
        key = cvWaitKey(0);
        if (key==27 || cvGetWindowHandle(WINDOW_NAME)==0) {
            break;
        }
    }
}
Window::~Window() {
    cvDestroyWindow(WINDOW_NAME);
}

I have added the following paths to the compiler include path (-I):
"$(OPENCV)/cv/include"
"$(OPENCV)/cxcore/include"
"$(OPENCV)/otherlibs/highgui"

I have added the following libraries to the linker (-l):
cv
cxcore
highgui

And the following library search path (-L):
"$(OPENCV)/lib/"

Eclipse, the compiler and the linker all succeed in including the headers and libraries. I am using the GNU C/C++ compiler & linker from Cygwin.
When compiling, I get the following make error:
src/Window.d:1: *** multiple target patterns.  Stop.
Window.d contains:
src/Window.d src/Window.o: ../src/Window.cpp \
  C:/Program\ Files/OpenCV/cv/include/cv.h \
  C:/Program\ Files/OpenCV/cxcore/include/cxcore.h \
  C:/Program\ Files/OpenCV/cxcore/include/cxtypes.h \
  C:/Program\ Files/OpenCV/cxcore/include/cxerror.h \
  C:/Program\ Files/OpenCV/cxcore/include/cvver.h \
  C:/Program\ Files/OpenCV/cxcore/include/cxcore.hpp \
  C:/Program\ Files/OpenCV/cv/include/cvtypes.h \
  C:/Program\ Files/OpenCV/cv/include/cv.hpp \
  C:/Program\ Files/OpenCV/cv/include/cvcompat.h \
  C:/Program\ Files/OpenCV/otherlibs/highgui/highgui.h \
  C:/Program\ Files/OpenCV/cxcore/include/cxcore.h ../src/Constants.h \
  ../src/Window.h
C:/Program\ Files/OpenCV/cv/include/cv.h:
C:/Program\ Files/OpenCV/cxcore/include/cxcore.h:
C:/Program\ Files/OpenCV/cxcore/include/cxtypes.h:
C:/Program\ Files/OpenCV/cxcore/include/cxerror.h:
C:/Program\ Files/OpenCV/cxcore/include/cvver.h:
C:/Program\ Files/OpenCV/cxcore/include/cxcore.hpp:
C:/Program\ Files/OpenCV/cv/include/cvtypes.h:
C:/Program\ Files/OpenCV/cv/include/cv.hpp:
C:/Program\ Files/OpenCV/cv/include/cvcompat.h:
C:/Program\ Files/OpenCV/otherlibs/highgui/highgui.h:
C:/Program\ Files/OpenCV/cxcore/include/cxcore.h:
../src/Window.h:

I tried removing all OpenCV headers from Window.d (from line 2 onwards), but the error remains. Also, I've updated Eclipse and OpenCV, all to no avail.
Do you have any ideas worth trying? I'm willing to try anything!

A: according to other internet sources this is related to a problem that cygwin make has with windows path names, specially the c:.
For me it workes fine with setting relative paths instead.
e.g. if you have something like
proj/mymodule/headers/afile.h
proj/mymodule/source/abc/afile.c

just add ../mymodule/headers/
as include path in the project configuration for the compiler this will find the header afile.h and will generate make files with relative path.
(compiler command will have the statement -I../mymodule/headers/ )
looks like execution directory is always the project base directory.

A: On Cygwin, GNU make version 3.81-1 delivered by the default setup program doesn't work with the automatic header file dependencies, generated by the compilers. The error message you will see because of this bug will look something like this:
Here are two suggested fixes:
- Try to obtain the previous version (3.80)
- Obtain a fixed 3.81 version, for example from  http://www.cmake.org/files/cygwin/make.exe
src: https://projects.coin-or.org/BuildTools/wiki/current-issues
Simply replace the make file in your "C:\cygwin\bin\" folder (or wherever cygwin is installed) with the "fixed" make file mentioned above.

A: Are you working from a Cygwin installation?
I've seen this problem before using Cygwin--basically, make sees the : in the path and thinks it is another target definition, hence the error.
If you are working from a Cygwin installation, you might try replacing the c:/ with /cygdrive/c/.  If not, you might try using relative paths or using a network mount and see if that fixes it.

A: Looks like there is a simple way to solve this.
Just change the "Current Builder" from "GNU Make Builder" to "CDT Internal Builder" in Project properties->C/C++ Builder->Tool Chain Editor->Current Builder will do.
To me, this problem is caused by the automatically generated  "XXX.d" dependency files in Debug directory (or release :), which were generated by gcc -MF as a side-effect to gcc -c. But GNU make obviously forgot to add quotations around file names when -MF.
"CDT Internal Builder" does not use makefile nor GNU make at all. Eclipse manage the build process itself.
If you insist to use GNU make, this doesn't work

A: I also had the problem of multiple target patterns reported by make when using eclipse on windows/cygwin.  I solved the problem as suggested above by using only relative paths.  I didn't realize that I had absolute paths, but when I specified an include directory using the project directory, eclipse expanded it into the full path.
For instance, if you add a path relative to the workspace, eclipse generates ""${workspace_loc:/include}"" which will expand to something starting with "c:\".  This is why it was happening in my case.
I simply replaced the complex string above with "../../include" and it solved my problem.

A: You can also delete *.d files under output folders and then build
Debug/src/

A: I'm working in the Cygwin environment, on Windows 7 (64bit), using Eclipse Kepler CDT for C++.
In Eclipse, goto

Project --> Properties --> C++ Builder --> Settings --> Tool Settings
  Tab
Cygwin C++ Compiler --> Includes

In the Include paths (-I) add 2 paths: "C:\cygwin64\usr\include\libxml2"
and "/cygdrive/c\cygwin64\usr\include\libxml2"

A: One change that worked for me (I use Cygwin and SSH terminal into an SVN server in parallel) was to delete the .d files. When I called the make -f makefile from Cygwin, it broke something. I usually compile from the Putty terminal, and after deleting the .d files from my project it stopped complaining about the multiple targets.

A: The error "multiple target patterns.  Stop."  will occur because src/Window.d have the paths generated by compiler in windows platform as:
C:/Program\ Files/OpenCV/cv/include/cv.h \
C:/Program\ Files/OpenCV/cxcore/include/cxcore.h \
C:/Program\ Files/OpenCV/cxcore/include/cxtypes.h \
C:/Program\ Files/OpenCV/cxcore/include/cxerror.h \
If you import this project into Eclipse in Linux platform, I would recommend you to give a clean build so that next build generates the path in Linux format as:
/home/user/OpenCV/cv/include/cv.h \
/home/user/OpenCV/cxcore/include/cxcore.h \
/home/user/OpenCV/cxcore/include/cxtypes.h \
/home/user/OpenCV/cxcore/include/cxerror.h \
The same is applicable, if you are using cygwin. The path format in cygwin is linux like format /cygdrive/c/ instead of C:/


text:
Q: Create linked list from elements of a Binary tree at a certain depth I am trying to build a linked list, with the elements at a certain depth
I came up with this:
void nivel(ABin a, int k, SList *l, int level){
    if (!a) return;
    if(k == level){
     SList n = (SList)malloc(sizeof(struct slist));
     n->value = a->value;
     n->next=(*l);
     (*l) = n;
     return;
    }else{
        nivel(a->left, k, l, level+1);
        nivel(a->right, k, l, level+1);
    }
}

It does work
But the exercise asks to use this header:
SList nivel (ABin a, int n)
I have tried with a void to practice. But can't figure out how to make the one that returns the linked lists.
Data from structure and binary tree:
typedef struct slist
{
    int value;
    struct slist* next;
} *SList;

typedef struct arvbin* ABin;
typedef struct arvbin
{
    int value;
    ABin right;
    ABin left;
} arvb;

EDIT:
<---------------working with header in the exercise----------->
// A thank you to Politank-Z
SList nivel_(ABin a, int k){
    SList *l;

    nivel(a, k, l, 1);

    return l;
}

void nivel(ABin a, int k, SList *l, int level){
    if (!a) return;
    if(k == level){
     SList n = (SList)malloc(sizeof(struct slist));
     n->value = a->value;
     n->next=(*l);
     (*l) = n;
     return;
    }else{
        nivel(a->left, k, l, level+1);
        nivel(a->right, k, l, level+1);
    }
}

A: Do you mean that you want to build a linked list using binary tree? However, you may add a new item into your list when (k == level), then you call nivel(a->left, k, l, level+1). It won't add any node here, because k != level+1 now, so your list will contain just one node actually...
BTW, you should ensure nivel add one node into your list everytime.

A: Regarding your difficulty with the prototype: it is fairly common to be restricted to a function prototype which doesn't meet the needs of your implementation. In such cases, it is often easier to call your function from the prototyped function then to shoehorn your functionality into the prototype.

A: } *SList;

will create a pointer type called SList. This causes confusion within your code, because you use SList *l which is a pointer to a pointer! Change your struct typedef to just } SList. This way you don't have to dereference a pointer of a pointer to reach the pointer value.


text:
Q: Run ElasticSearch using Python I am trying to turn on ElasticSearch node using python. I am doing this by running a shell script via python. I have tried the below commands in python to run the shell script :
import os
cmd = 'cd C:\Users\anoop\desktop\kibi\elasticsearch 2.3.3\bin && .\elasticsearch'
os.system(cmd)

from subprocess import call
call('cd C:\Users\anoop\desktop\kibi\elasticsearch 2.3.3\bin && .\elasticsearch')

import subprocess
p = subprocess.Popen('C:\Users\anoop\Desktop\RunES.bat', shell = True)
p.communicate()

None of the above three methods is working. Let me know if anyone can help on this!!


text:
Q: How to animate ExtJs window from top right of browser? this.changePasswordWin = Ext.create('Ext.window.Window', {
                title: "Change Password",
                modal: true,
                closeAction: 'hide',
                animateTarget: Ext.getDoc(),
                items: [ this.textfieldPanel ],
                dockedItems: [{
                    xtype: 'toolbar',
                    dock: 'bottom',
                    border: false,

                }]
            });

The above code is working fine with animate from top left. But i want this to animate from top right. Help me! Thanks in advance.

A: set x: screen.width. It will set the position of the window to the right corner. if it is not exactly minus the position based on the browser screen.


text:
Q: Strange NullPointerException I have strange problem...
My file strings.xml contains:
<?xml version="1.0" encoding="utf-8?>
<resources>
    <string name="building_name">My House</string>
</resources>

Well, my R contains:
[...]
public static final class String {
    public static final int building_name=0x7f02383;
}
[...]

So, when I try to call this String in my code like this:
private final String BUILDING_NAME = getString(R.string.building_name);

I have this error:
java.lang.RuntimeException: Unable to instanciate activity ComponentInfo{...}:          java.lang.NullPointerException
{...}
  caused by: java.lang.NullPointerException

at {the line where I instanciate the building_name}
What's wrong with my code?Please help

A: Using this might help you
getResources().getString(R.string.building_name);

This works for me

A: There are some cases where this happens, for the same you should try some steps mentioned below:

*

*Try to clean your project.

*Check whether the android.R class file is imported or not, if it is imported then remove it and import your R class file.

*Try using getResources().getString(R.string.myString) method.

A: You can't call getString before your Activity has been initialized. That's because getString is the same as context.getResources().getString(). And context is not initialized.
So basically, you can not assign value to static variables in this way.
But there is a way to use resource strings in your static variables. For this create your application (see this and this) and then retrieve context from there. Here is a short example:
<manifest ...>
    ...
    <application  android:name="com.mypackage.MyApplication" ... >
       ...
    </application>
    ...
</manifest>

Then create MyApplication.java file:
public class MyApplication extends Application
{
    private static MyApplication s_instance;

    public MyApplication ()
    {
        s_instance = this;
    }

    public static Context getContext()
    {
        return s_instance;
    }

    public static String getString(int resId)
    {
        return getContext().getString(resId);
    }
}

And then use it to get string resource:
private final String BUILDING_NAME = MyApplication.getString(R.string.building_name);

You can even do this fir static fields.

A: if you have error in getting some text from one activity to another activity
Like for example
StudentID = getIntent().getExtras().getString("Value");

getString giving null pointer exception then
that StudentID is of String type so just declare StudentID as
private String StudentID;


text:
Q: Spawn balls randomly Im making a game where balls spawn randomly from each side of the smartphone screen, and I got it working although the balls spawn mostly on the top side of the screen and 2/10 times on the bottom and sides of the screen. Heres the code:
//creates the balls and sets their position as well as the random timer for each
private void spawnBalls1() {

    Rectangle ball1 = new Rectangle();
    ball1.x = MathUtils.random(639, 641);
    ball1.y = 720;
    ball1.width = 32;
    ball1.height = 32;
    balls1.add(ball1);
    lastDropTime = TimeUtils.nanoTime();

}

private void spawnBalls2() {

    Rectangle ball2 = new Rectangle();
    ball2.x = 0;
    ball2.y = MathUtils.random(359, 361);
    ball2.width = 32;
    ball2.height = 32;
    balls2.add(ball2);
    lastDropTime = TimeUtils.nanoTime();
}

private void spawnBalls3() {

    Rectangle ball3 = new Rectangle();
    ball3.x = MathUtils.random(639, 641);
    ball3.y = 0;
    ball3.width = 32;
    ball3.height = 32;
    balls3.add(ball3);
    lastDropTime = TimeUtils.nanoTime();
}

private void spawnBalls4() {

    Rectangle ball4 = new Rectangle();
    ball4.x = 1280;
    ball4.y = MathUtils.random(359, 361);
    ball4.width = 32;
    ball4.height = 32;
    balls4.add(ball4);
    lastDropTime = TimeUtils.nanoTime();
}

//draws the balls
    for (Rectangle ball1 : balls1) {

        batch.draw(Ball, ball1.x, ball1.y);
    }

    for (Rectangle ball2 : balls2) {

        batch.draw(Ball, ball2.x, ball2.y);
    }

    for (Rectangle ball3 : balls3) {

        batch.draw(Ball, ball3.x, ball3.y);
    }

    for (Rectangle ball4 : balls4) {

        batch.draw(Ball, ball4.x, ball4.y);
    }

// if the time minus the time of the last ball spawn is less than x then spawn another ball in a random place
    if (TimeUtils.nanoTime() - lastDropTime > 1000000000) spawnBalls1();

    Iterator<Rectangle> iter1 = balls1.iterator();
    while(iter1.hasNext()) {

        Rectangle balls1 = iter1.next();
        balls1.y -= 500 * Gdx.graphics.getDeltaTime();
        if (balls1.overlaps(square)) {

            score++;
            showScore = "Score: " + score;
            iter1.remove();
        }
    }

    // if the time minus the time of the last ball spawn is less than x then spawn another ball in a random place
    if (TimeUtils.nanoTime() - lastDropTime > 1000000000) spawnBalls2();

    Iterator<Rectangle> iter2 = balls2.iterator();
    while (iter2.hasNext()) {

        Rectangle balls2 = iter2.next();
        balls2.x += 500 * Gdx.graphics.getDeltaTime();
        if (balls2.overlaps(square)) {

            score++;
            showScore = "Score: " + score;
            iter2.remove();
        }
    }

    // if the time minus the time of the last ball spawn is less than x then spawn another ball in a random place
    if (TimeUtils.nanoTime() - lastDropTime > 1000000000) spawnBalls3();

    Iterator<Rectangle> iter3 = balls3.iterator();
    while(iter3.hasNext()) {

        Rectangle balls3 = iter3.next();
        balls3.y += 500 * Gdx.graphics.getDeltaTime();
        if (balls3.overlaps(square)) {

            score++;
            showScore = "Score: " + score;
            iter3.remove();
        }
    }

    // if the time minus the time of the last ball spawn is less than x then spawn another ball in a random place
    if (TimeUtils.nanoTime() - lastDropTime > 1000000000) spawnBalls4();

    Iterator<Rectangle> iter4 = balls4.iterator();
    while(iter4.hasNext()) {

        Rectangle balls4 = iter4.next();
        balls4.x -= 500 * Gdx.graphics.getDeltaTime();
        if (balls4.overlaps(square)) {

            score++;
            showScore = "Score: " + score;
            iter4.remove();
        }
    }

What should I do/change to make them spawn randomly on each side?
Thanks in advance!

A: All four of your ball spawning methods share the same lastDropTime variable. The execution time between
if (TimeUtils.nanoTime() - lastDropTime > 1000000000) spawnBalls1();

and
if (TimeUtils.nanoTime() - lastDropTime > 1000000000) spawnBalls4();

is going to be a tiny percentage of 1000000000 ns, so it's going to be very unlikely for spawnBalls2-4 ever to get called.
You should only have one test instead of four, and randomly pick one of the methods. Something like this:
if (TimeUtils.nanoTime() - lastDropTime > 1000000000){
    switch (MathUtils.randomInt(4)){
        case 0: spawnBalls1(); break;
        case 1: spawnBalls2(); break;
        case 2: spawnBalls3(); break;
        case 3: spawnBalls4(); break;
    }
}

Also, this is a lot of copy-paste code, which is ballooning your time investment. You ought to write one spawnBalls method that takes some parameter that affects where it places the balls.

A: Is this what you are looking for?
private void spawnBalls1() {

    Rectangle ball1 = new Rectangle();
    ball1.x = MathUtils.random(0, 641);
    ball1.y = MathUtils.random(0, 720);
    ball1.width = 32;
    ball1.height = 32;
    balls1.add(ball1);
    lastDropTime = TimeUtils.nanoTime();

}


text:
Q: How to convert to a matrix and plot a variable in a MATLAB file in R? I have a MATLAB file that I want to work with, but I need to convert it to amtrix, so I can plot or do any calculations.
  data <- readMat('C:\\Usersfile.mat')
  str(data)
  List of 1
  $ LAND: num [1:500, 1:1300] 0 0 0 0 0 0 0 0 0 0 ...
  - attr(*, "header")=List of 3
  ..$ description: chr "MATLAB 5.0 MAT-file, Platform: GLNXA64, Created on:     Thu Oct 11 12:09:52 2012                                                "
  ..$ version    : chr "5"
  ..$ endian     : chr "little"

How do I plot "LAND"? Or convert it to a matrix?

A: What you have a list that contains element LAND, which is a numeric matrix of dimensions 500x1300. This matrix has some attributes like description, version and endian. You can access the matrix with data[[1]] or data[["LAND"]].


text:
Q: Subtract vector from 3d array Say if I have a 3d array:
lat = 45:49;
lon = -116:-110;
b = rand(5,7,12);

where the first dimension represents the latitude, the second dimension represents the longitude and the third row represents the data. I aim to plot this 3d data on a map using the mapping toolbox. But, before doing this, I would like to find the difference between the data in 'b' and the following vector:
vals = [2.3,5,6.8,5.4,3.3,12,1.5,4.6,9.8,82,3.3,1];

Specifically, for each spatial data point that I have in my mapped data I owuld like to calculate the mean absolute error between that vector and the data at each point in b. If these were two normal vectors I would use:
mae = mean(abs(bv - vals))

but I'm not sure how this can be done with the 3d array. Eventually, I aim to map this mean absolute error to see how it varies spatially. Can anyone suggest how this can be done in matlab?

A: Use bsxfun for this (it's more efficient than repmat):
V = permute(vals, [1,3,2])  %// Make sure that the dimesions 'align' correctly. i.e. 12 elements must go in the thrid dimension to match b
mae = mean(abs(bsxfun(@minus, b, V)),3)

A: As MATLAB does not support broadcasting, you need to create a matrix the same size as b with the repeated values of vals. To be able to do that, first you need to change vals to a shape of 1x1x12 and then repeat it 5x7 times. You can do that with
values=repmat(permute(vals,[1 3 2]),[5 7 1]);

now you can
mae = mean(abs(bv - values))


text:
Q: taskdef Could not load definitions from resource tasks.properties when i try to ant for eclipse, it shows below info:
ubuntu@sdnhubvm:~[04:06]$ cd floodlight/
ubuntu@sdnhubvm:~/floodlight[04:07] (master)$ ant
Buildfile: /home/ubuntu/floodlight/build.xml
  [taskdef] Could not load definitions from resource tasks.properties. It could not be found.

init:

compile:

compile-test:

dist:
     [echo] Setting Floodlight version: 1.2-SNAPSHOT
     [echo] Setting Floodlight name: floodlight
      [jar] Building jar: /home/ubuntu/floodlight/target/floodlight.jar
      [jar] Building jar: /home/ubuntu/floodlight/target/floodlight-test.jar

BUILD SUCCESSFUL
Total time: 29 seconds

Even building success, but how could i get rid of this info please?


text:
Q: Redirecting stdout/stderr of a child process to a file I have a Python script (popen.py) which runs another Python script (counter.py) as a child process with the output redirected to /tmp/counter.log. The code I am using is:
/tmp/counter.py
#!/usr/bin/env python2
import time

i = 0
while True:
    print i
    i +=1
    time.sleep(1)

/tmp/popen.py
#!/usr/bin/env python2
import subprocess

f = open("/tmp/counter.log", "a+")
p = subprocess.Popen("/tmp/counter.py", stdout=f, stderr=f, bufsize=1)

However when I run popen.py the child process is created and stays running, however nothing get written to /tmp/counter.log until the output reaches 4096 bytes, then it appears to be flushed to the file.
Is there any way I can get my child process to write to the logfile line-by-line without modifying the counter.py script itself?
The reason I don't want to modify counter.py is that the child process may not always be running a Python script. I've tried the same thing running a small executable (written in C) and the same problem occurs.
I have tried writing a self-flushing wrapper for the file and using that for stdout as described here but that doesn't work either.
I've done some debugging with lsof and strace and this is what I've managed to find out:
lsof (file descriptors)
Running /tmp/counter.py manually
COMMAND PID   USER   FD   TYPE DEVICE SIZE/OFF   NODE NAME
python2 629 daniel    0u   CHR  136,0      0t0      3 /dev/pts/0
python2 629 daniel    1u   CHR  136,0      0t0      3 /dev/pts/0
python2 629 daniel    2u   CHR  136,0      0t0      3 /dev/pts/0

Running /tmp/counter.py via /tmp/popen.py
COMMAND PID   USER   FD   TYPE DEVICE SIZE/OFF   NODE NAME
python2 638 daniel    0u   CHR  136,0      0t0      3 /dev/pts/0
python2 638 daniel    1u   REG  202,0        0    768 /tmp/counter.log
python2 638 daniel    2u   REG  202,0        0    768 /tmp/counter.log

strace (system calls during the while loop)
Running /tmp/counter.py manually
select(0, NULL, NULL, NULL, {1, 0})     = 0 (Timeout)
write(1, "11\n", 3)                     = 3
select(0, NULL, NULL, NULL, {1, 0})     = 0 (Timeout)
write(1, "12\n", 3)                     = 3
select(0, NULL, NULL, NULL, {1, 0})     = 0 (Timeout)
write(1, "13\n", 3)                     = 3
select(0, NULL, NULL, NULL, {1, 0})     = 0 (Timeout)
write(1, "14\n", 3)                     = 3
select(0, NULL, NULL, NULL, {1, 0})     = 0 (Timeout)
write(1, "15\n", 3)                     = 3

Running /tmp/counter.py via /tmp/popen.py
select(0, NULL, NULL, NULL, {1, 0})     = 0 (Timeout)
select(0, NULL, NULL, NULL, {1, 0})     = 0 (Timeout)
select(0, NULL, NULL, NULL, {1, 0})     = 0 (Timeout)
select(0, NULL, NULL, NULL, {1, 0})     = 0 (Timeout)
select(0, NULL, NULL, NULL, {1, 0})     = 0 (Timeout)
...
write(1, "11\n12\n13\n14\n15\n16\n17\n18\n"..., 4096) = 4096

A: The solution I ended up using, which does not fully solve the problem, but is the most acceptable compromise at this point, is to set the PYTHONUNBUFFERED environment variable while spawning a child process:
#!/usr/bin/env python2
import subprocess

f = open("/tmp/counter.log", "a+")
p = subprocess.Popen("/tmp/counter.py", stdout=f, stderr=f, env={
    "PYTHONUNBUFFERED": "Yes please"
})

This has the lowest overhead in terms of extra code and additional processes, but only works if the child process is a Python script.

A: In general, you can't get processes to write line-by-line into a file unless the process flushes at regular intervals. But you can make the calling process look like a terminal. Processes that follow CLIB rules will switch to line mode and give you what you want. In this example, I setup as a pseudo terminal and write + flush the log file.
#!/usr/bin/env python2

import os
import subprocess
import pty

master,slave = pty.openpty()
f = open("/tmp/counter.log", "a+")
p = subprocess.Popen(["python", "counter.py"], stdout=slave, stderr=slave, close_fds=True)
os.close(slave)
reader = os.fdopen(master)
while True:
    data = reader.readline()
    if not data:
        break
    f.write(data)
    f.flush()
    print data.strip()
print 'done'
reader.close()
p.wait()

A: Actually, subprocess.Popen can be used for executables other than Python scripts. Here's a snippet that creates a copy of the user's cron schedule:
import subprocess
import shlex

def getTempCrontabFile(argTmpFile='/tmp/tmpFile'):
    # Create a file in r/w mode that will be the target for
    # the crontab utility redirection.
    try:
        tmpFile = open(argTmpFile, 'a+')
    except IOError as customErr:
        print 'Failed to open or create temporary crontab file.'
        print customErr
        return customErr
    # Define the command line to list the cron schedule.
    cmdLine = 'crontab -l'
    # Format the command line into an array of arguments. This is
    # useful for proper formatting of spaces and quoted arguments
    # especially when commands get complicated.
    args = shlex.split(cmdLine)
    # Make the call to Popen using the file we created for stdout.
    result = subprocess.Popen(args, stdout=tmpFile)
    return result


text:
Q: Python sorting 2D list by multiple colums not provided expected results I have a set of data with 9 columns, that i want to sort by column 9, then 1, then 2
list.sort(key=itemgetter(8,0,1), reverse=False)

I dont know how to add an attachment here, but my sorted list ends up looking like this, and as you can see, it is sorted by column 9 (which is all zeros at first), then column 1, and then for column 2, particular at lines 9-17, it makes no sense:
   -5.8000    -4.0000     0.1005    -3.4900    -2.5000          0          1          2          0

   -5.8000     4.9500     0.1005    -3.4900    -2.5000          0          1          2          0

   -5.5000    -3.6250     0.2500    -5.5700    -5.4700          1          1          2          0

   -5.5000     4.5750     0.2500    -5.5700    -5.4700          1          1          2          0

   -5.1600    -0.3750     0.1105    -2.2850    -2.0000          1          1          1          0

   -5.1600    -0.3750     0.1105    -6.0700    -5.7850          1          1          3          0

   -5.1600    -0.3750     0.1725    -5.7850    -5.5700          1          1          3          0

   -5.1600    -0.3750     0.1002    -6.6102    -6.0702          0          1          4          0

   -5.1000    -0.9500     0.2425    -2.5000    -2.0000          1          1          1          0

   -5.1000    -0.9500     0.2425    -6.0700    -5.5700          1          1          3          0

   -5.1000     1.1000     0.2425    -2.5000    -2.0000          1          1          1          0

   -5.1000     1.1000     0.2425    -6.0700    -5.5700          1          1          3          0

   -5.1000    -0.9500     0.2590    -1.3750    -0.2500          1          1          0          0

   -5.1000    -0.9500     0.2160    -2.0000    -1.3750          1          1          0          0

   -5.1000     1.1000     0.2590    -1.3750    -0.2500          1          1          0          0

   -5.1000     1.1000     0.2160    -2.0000    -1.3750          1          1          0          0

   -5.1000    -0.9500     0.2425    -5.5700    -2.5000          1          1          2          0

any idea whats going on here?

A: turns out, i just needed to round the input data before sorting it. There must have been differences on the order of 1E-6


text:
Q: Checkbox is not checked, even though I do it with code I'm writing a Java Game similar to Tetris for a school project. In the game I have a checkbox to turn music on/off.
My problem is that the checkbox, even though I set it to be checked, is NOT checked when I click it (don't understand me wrong, not AFTER, but before/at the same moment when I clicked it).
Okay so, in my code where I first initialize the checkbox I set it to be checked based on a variable provided in another class.
I tried debugging everything that is going on with the checkbox but I didn't get anything I didn't already knew.
Here's the code where I initialize the box:
music_cbox = TexturesHandler.getCheckboxTemplate();
music_cbox.setName("Music");
music_cbox.addMouseListener(Retris.getButtonHandler());
music_cbox.setLocation(Retris.WIDTH / 2 - 25, 250);

 // Setting it to checked based on the variable

if(!Retris.getAudioHandler().canPlay()) {
    music_cbox.setIcon(TexturesHandler.getUncheckedCheckBoxStyle());
    music_cbox.setSelected(false);
    System.out.println("box not selected");
} else {
    music_cbox.setIcon(TexturesHandler.getCheckedCheckBoxStyle());
    music_cbox.setSelected(true);
    System.out.println("box selected");
    }

The canPlay variable only gets changed when you CLICK the box:
if(box.isSelected()) {
    Retris.getAudioHandler().canPlay(false);
    Retris.getAudioHandler().stopMusic();
    System.out.println("Music disabled");
    box.setIcon(TexturesHandler.getUncheckedCheckBoxStyle());
    break;
    // (in a switch statement)
} else {
    Retris.getAudioHandler().canPlay(true);
    Retris.getAudioHandler().startMusic("Main_Menu.wav", "Main Menu", 0.1F);
    System.out.println("Music enabled");
    box.setIcon(TexturesHandler.getCheckedCheckBoxStyle());
    break;
}

I also tried box.setSelected() after setting the new icon and all, but somehow when i first click the box, it does the else part instead of the if part.

A: Not sure if this helps but I noted that in the initialization you call music_cbox.setSelected() but then in your if statement you call box.isSelected()
Are these the same box? Could explain why you set the variable but then check another one.