text:
Q: Set function signature in Python Suppose I have a generic function f. I want to programmatically create a function f2 that behaves the same as f, but has a customized signature.
More detail
Given a list l and and dictionary d I want to be able to:

*

*Set the non-keyword arguments of f2 to the strings in l

*Set the keyword arguments of f2 to the keys in d and the default values to the values of d
ie. Suppose we have
l = ["x", "y"]
d = {"opt": None}

def f(*args, **kwargs):
    # My code

Then I would want a function with signature:
def f2(x, y, opt=None):
    # My code

A specific use case
This is just a simplified version of my specific use case. I am giving this as an example only.
My actual use case (simplified) is as follows. We have a generic initiation function:
def generic_init(self, *args, **kwargs):
    """Function to initiate a generic object"""
    for name, arg in zip(self.__init_args__, args):
        setattr(self, name, arg)
    for name, default in self.__init_kw_args__.items():
        if name in kwargs:
            setattr(self, name, kwargs[name])
        else:
            setattr(self, name, default)

We want to use this function in a number of classes. In particular, we want to create a function __init__ that behaves like generic_init, but has the signature defined by some class variables at creation time:
class my_class:
    __init_args__ = ["x", "y"]
    __kw_init_args__ = {"my_opt": None}

__init__ = create_initiation_function(my_class, generic_init)
setattr(myclass, "__init__", __init__)

We want create_initiation_function to create a new function with the signature defined using __init_args__ and __kw_init_args__. Is it possible to write create_initiation_function?
Please note:

*

*If I just wanted to improve the help, I could set __doc__.

*We want to set the function signature on creation. After that, it doesn't need to be changed.

*Instead of creating a function like generic_init, but with a different signature we could create a new function with the desired signature that just calls generic_init

*We want to define create_initiation_function. We don't want to manually specify the new function!

Related

*

*Preserving signatures of decorated functions: This is how to preserve a signature when decorating a function. We need to be able to set the signature to an arbitrary value

A: I wrote a package named forge that solves this exact problem for Python 3.5+:
With your current code looking like this:
l=["x", "y"]
d={"opt":None}

def f(*args, **kwargs):
    #My code

And your desired code looking like this:
def f2(x, y, opt=None):
    #My code

Here is how you would solve that using forge:
f2 = forge.sign(
    forge.arg('x'),
    forge.arg('y'),
    forge.arg('opt', default=None),
)(f)

As forge.sign is a wrapper, you could also use it directly:
@forge.sign(
    forge.arg('x'),
    forge.arg('y'),
    forge.arg('opt', default=None),
)
def func(*args, **kwargs):
    # signature becomes: func(x, y, opt=None)
    return (args, kwargs)

assert func(1, 2) == ((), {'x': 1, 'y': 2, 'opt': None})

A: From PEP-0362, there actually does appear to be a way to set the signature in py3.3+, using the fn.__signature__ attribute:
from inspect import signature
from functools import wraps

def shared_vars(*shared_args):
    """Decorator factory that defines shared variables that are
       passed to every invocation of the function"""

    def decorator(f):
        @wraps(f)
        def wrapper(*args, **kwargs):
            full_args = shared_args + args
            return f(*full_args, **kwargs)

        # Override signature
        sig = signature(f)
        sig = sig.replace(parameters=tuple(sig.parameters.values())[1:])
        wrapper.__signature__ = sig

        return wrapper
    return decorator

Then:
>>> @shared_vars({"myvar": "myval"})
>>> def example(_state, a, b, c):
>>>     return _state, a, b, c
>>> example(1,2,3)
({'myvar': 'myval'}, 1, 2, 3)
>>> str(signature(example))
'(a, b, c)'

Note: the PEP is not exactly right; Signature.replace moved the params from a positional arg to a kw-only arg.

A: Have a look at makefun, it was made for that (exposing variants of functions with more or less parameters and accurate signature), and works in python 2 and 3.
Your example would be written like this:
try:  # python 3.3+
    from inspect import signature, Signature, Parameter
except ImportError:
    from funcsigs import signature, Signature, Parameter

from makefun import create_function

def create_initiation_function(cls, gen_init):
    # (1) check which signature we want to create
    params = [Parameter('self', kind=Parameter.POSITIONAL_OR_KEYWORD)]
    for mandatory_arg_name in cls.__init_args__:
        params.append(Parameter(mandatory_arg_name, kind=Parameter.POSITIONAL_OR_KEYWORD))
    for default_arg_name, default_arg_val in cls.__opt_init_args__.items():
        params.append(Parameter(default_arg_name, kind=Parameter.POSITIONAL_OR_KEYWORD, default=default_arg_val))
    sig = Signature(params)

    # (2) create the init function dynamically
    return create_function(sig, generic_init)

# ----- let's use it

def generic_init(self, *args, **kwargs):
    """Function to initiate a generic object"""
    assert len(args) == 0
    for name, val in kwargs.items():
        setattr(self, name, val)

class my_class:
    __init_args__ = ["x", "y"]
    __opt_init_args__ = {"my_opt": None}

my_class.__init__ = create_initiation_function(my_class, generic_init)

and works as expected:
# check
o1 = my_class(1, 2)
assert vars(o1) == {'y': 2, 'x': 1, 'my_opt': None}

o2 = my_class(1, 2, 3)
assert vars(o2) == {'y': 2, 'x': 1, 'my_opt': 3}

o3 = my_class(my_opt='hello', y=3, x=2)
assert vars(o3) == {'y': 3, 'x': 2, 'my_opt': 'hello'}

A: For your usecase, having a docstring in the class/function should work -- that will show up in help() okay, and can be set programmatically (func.__doc__ = "stuff").
I can't see any way of setting the actual signature. I would have thought the functools module would have done it if it was doable, but it doesn't, at least in py2.5 and py2.6.
You can also raise a TypeError exception if you get bad input.
Hmm, if you don't mind being truly vile, you can use compile()/eval() to do it. If your desired signature is specified by arglist=["foo","bar","baz"], and your actual function is f(*args, **kwargs), you can manage:
argstr = ", ".join(arglist)
fakefunc = "def func(%s):\n    return real_func(%s)\n" % (argstr, argstr)
fakefunc_code = compile(fakefunc, "fakesource", "exec")
fakeglobals = {}
eval(fakefunc_code, {"real_func": f}, fakeglobals)
f_with_good_sig = fakeglobals["func"]

help(f)               # f(*args, **kwargs)
help(f_with_good_sig) # func(foo, bar, baz)

Changing the docstring and func_name should get you a complete solution. But, uh, eww...

A: You can't do this with live code.
That is, you seem to be wanting to take an actual, live function that looks like this:
def f(*args, **kwargs):
    print args[0]

and change it to one like this:
def f(a):
    print a

The reason this can't be done--at least without modifying actual Python bytecode--is because these compile differently.
The former results in a function that receives two parameters: a list and a dict, and the code you're writing operates on that list and dict.  The second results in a function that receives one parameter, and which is accessed as a local variable directly.  If you changed the function "signature", so to speak, it'd result in a function like this:
def f(a):
    print a[0]

which obviously wouldn't work.
If you want more detail (though it doesn't really help you), a function that takes an *args or *kwargs has one or two bits set in f.func_code.co_flags; you can examine this yourself.  The function that takes a regular parameter has f.func_code.co_argcount set to 1; the *args version is 0.  This is what Python uses to figure out how to set up the function's stack frame when it's called, to check parameters, etc.
If you want to play around with modifying the function directly--if only to convince yourself that it won't work--see this answer for how to create a code object and live function from an existing one to modify bits of it.  (This stuff is documented somewhere, but I can't find it; it's nowhere in the types module docs...)
That said, you can dynamically change the docstring of a function.  Just assign to func.__doc__.  Be sure to only do this at load time (from the global context or--most likely--a decorator); if you do it later on, tools that load the module to examine docstrings will never see it.

A:
We want create_initiation_function to change the signature

Please don't do this.

We want to use this function in a number of classes

Please use ordinary inheritance.
There's no value in having the signature "changed" at run time.
You're creating a maintenance nightmare.  No one else will ever bother to figure out what you're doing.  They'll simply rip it out and replace it with inheritance.
Do this instead.  It's simple and obvious and makes your generic init available in all subclasses in an obvious, simple, Pythonic way.
class Super( object ):
    def __init__( self, *args, **kwargs ):
        # the generic __init__ that we want every subclass to use

class SomeSubClass( Super ):
    def __init__( self, this, that, **kwdefaults ):
        super( SomeSubClass, self ).__init__( this, that, **kwdefaults )

class AnotherSubClass( Super ):
    def __init__( self, x, y, **kwdefaults ):
        super( AnotherSubClass, self ).__init__( x, y, **kwdefaults )

A: Edit 1: Answering new question:
You ask how you can create a function with this signature:
def fun(a, b, opt=None):
    pass

The correct way to do that in Python is thus:
def fun(a, b, opt=None):
    pass

Edit 2: Answering explanation:
"Suppose I have a generic function f. I want to programmatically create a function f2 that behaves the same as f, but has a customised signature."
def f(*args, **kw):
    pass

OK, then f2 looks like so:
def f2(a, b, opt=None):
    f(a, b, opt=opt)

Again, the answer to your question is so trivial, that you obviously want to know something different that what you are asking. You really do need to stop asking abstract questions, and explain your concrete problem.

A: Maybe I didn't understand the problem well, but if it's about keeping the same behavior while changing the function signature, then you can do something like :
# define a function
def my_func(name, age) :
    print "I am %s and I am %s" % (name, age)

# label the function with a backup name
save_func = my_func

# rewrite the function with a different signature
def my_func(age, name) :
    # use the backup name to use the old function and keep the old behavior
    save_func(name, age)

# you can use the new signature
my_func(35, "Bob")

This outputs :
I am Bob and I am 35


text:
Q: Delphi GetLastError with execute packages When I execute this code without runtime packages, I have a 32 code error, that is correct.
But when I activite runtime packages (for exemple just with "FireDACASADriver;YmagControlDB") the error code is always "0"
procedure TForm1.Button1Click(Sender: TObject);
Var
   Stream: TStream;
   iError : integer;
begin
   Stream := nil;
   iError := -1;
   try
      try
         Stream := TFileStream.Create('d:\toto.docx', fmOpenRead);
      except
         begin
            iError := GetLastError;
         end;
      end;
   finally
      if Assigned(Stream) then
         Stream.Free;
   end;
   showmessage('Erreur : ' + inttostr(iError));
end;

How I can fix the GetLastError with runtime packages ?

A: It is simply not appropriate to call GetLastError there. You are mixing two different error handling models.
Call GetLastError immediately after an API call fails, if the documentation says to do so. When you call it, something other function could very well have called SetLastError and reset the value.
So it is wrong to call GetLastError since you aren't using Win32 functions, and should remove the call to GetLastError. Your code should be:
procedure TForm1.Button1Click(Sender: TObject);
var
  Stream: TStream;
begin
  Stream := TFileStream.Create('d:\toto.docx', fmOpenRead);
  try
    // ....
  finally
    Stream.Free;
  end;
end;

If there is an error, an exception will be raised which will be reported by the top level exception handler.
Runtime packages should have no bearing on how this code executes.
Possible causes of an error are that the file does not exist, or that it is locked.
You wrote:
if Assigned(Stream) then
  Stream.Free;

That is always pointless since the Free method also checks for the object reference being nil. In fact your code is equivalent to:
if Assigned(Stream) then
  if Assigned(Stream) then
    Stream.Destroy;

So it is cleaner to rely on test inside Free and simply write:
Stream.Free;

In the comments you state that you actually want to test whether or not the file is locked. Don't use a file stream for that. Instead do the following:

*

*Call CreateFile to open the file.

*Check the returned handle against INVALID_HANDLE_VALUE to detect error.

*In case of error use GetLastError to find out the cause of error.

*Otherwise close the handle with CloseHandle.

However, this is not to be recommended. You might use this approach to determine that the file is not locked, but by the time you try to read it, it has been locked. There is an inherent race condition.
As a general guideline it is better to ask forgiveness than permission.

A: The act of raising an exception can reset the calling thread's error code.  It is simply not appropriate to call GetLastError() inside an exception handler.
That being said, if TFileStream fails to open the file, an exception is raised that contains a system-provided error message (but not the actual error code), eg:
procedure TForm1.Button1Click(Sender: TObject);
var
  Stream: TStream;
begin
  try
    Stream := TFileStream.Create('d:\toto.docx', fmOpenRead);
    try
      // use Stream as needed
    finally
      Stream.Free;
    end;
  except
    on E: Exception do
      ShowMessage('Erreur : ' + E.Message);
  end;
end;

If you need access to the error code, you can't use TFileStream, you will have to use CreateFile() directly instead:
procedure TForm1.Button1Click(Sender: TObject);
var
  hFile: THandle;
  iError: DWORD;
begin
  hFile := CreateFile('d:\toto.docx', GENERIC_READ, 0, nil, OPEN_EXISTING, 0, 0);
  if hFile <> INVALID_HANDLE_VALUE then
  begin
    try
      // use hFile as needed...
      //
      // if you need to access the file as a TStream, you can
      // instantiate a THandleStream passing hFile to its constructor...
      //
    finally
      CloseHandle(hFile);
    end;
  end else
  begin
    iError := GetLastError;
    ShowMessage('Erreur : ' + IntToStr(iError));
    if iError = ERROR_SHARING_VIOLATION then
    begin
      // do something...
    end;
  end;
end;

Alternatively:
procedure TForm1.Button1Click(Sender: TObject);
var
  hFile: THandle;
begin
  hFile := CreateFile('d:\toto.docx', GENERIC_READ, 0, nil, OPEN_EXISTING, 0, 0);
  try
    Win32Check(hFile <> INVALID_HANDLE_VALUE);
    try
      // use hFile as needed...
    finally
      CloseHandle(hFile);
    end;
  except
    on E: EOSError do
    begin
      ShowMessage('Erreur : ' + IntToStr(E.ErrorCode));
      if E.ErrorCode = ERROR_SHARING_VIOLATION then
      begin
        // do something...
      end;
    end;
  end;
end;

redpajama_set_name: RedPajamaStackExchange


text:
Q: while replacing the fragment view pager the viewpager fragment shows blank I am calling the view pager fragments by replacing over frame layout but when when i call it again the last loaded fragments of view pager are shown blank.
//Here I am replacing the view pager fragment in main activity
All_Women_Categories fragment = new All_Women_Categories();

            fragmentManager = getSupportFragmentManager();
            fragmentManager.beginTransaction()
                    .replace(R.id.frame_container, fragment).commit();

//Here is my called view pager fragment
public class All_Ethnic_Fragment extends Fragment {
    private static SectionsPagerAdapter mSectionsPagerAdapter;
    private static ViewPager mViewPager;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        View rootView = inflater.inflate(R.layout.all_women_ethnic_view_pager,
                container, false);
        mViewPager = (ViewPager) rootView.findViewById(R.id.women_ethnic_pager);

            mSectionsPagerAdapter = new SectionsPagerAdapter(getActivity()
                    .getSupportFragmentManager());
            mViewPager.setAdapter(mSectionsPagerAdapter);

        return rootView;
    }

    public class SectionsPagerAdapter extends FragmentPagerAdapter {

        public SectionsPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {

            switch (position) {
            case 0:
                return Sarees.newInstance("Hello");
            case 1:
                return Lehengas.newInstance("Hello");
            case 2:
                return Salwars_n_Churidars.newInstance("Hello");
            case 3:
                return Kurtis.newInstance("Hello");
            case 4:
                return Dress_Materials.newInstance("Hello");
            case 5:
                return Stitched_Suits.newInstance("Hello");

            }
            return null;
        }

        @Override
        public int getCount() {
            // Show 3 total pages.
            return 6;
        }

        @Override
        public CharSequence getPageTitle(int position) {

            switch (position) {
            case 0:
                return getString(R.string.sarees).toUpperCase();
            case 1:
                return getString(R.string.lehngas).toUpperCase();
            case 2:
                return getString(R.string.salwars).toUpperCase();
            case 3:
                return getString(R.string.kurti).toUpperCase();
            case 4:
                return getString(R.string.dress_material).toUpperCase();
            case 5:
                return getString(R.string.stiched).toUpperCase();
            }
            return null;
        }
    }
}

If anyone get anything that what's happening then please tell me..
Thanks..

A: I'm not sure I got your question, but I think you should stack fragments instead of replacing them. Instead of
                .replace(R.id.frame_container, fragment).commit();

You should try using add(Fragment fragment), remove() and/or show(Fragment fragment). In this way, you may add all of your fragments first, and then decide to show/hide them as appropriate.


text:
Q: How to find the sum of two separate items of data in python, separately? How can I restart the program?
I am trying to find the sum of the first set of data in the first loop and then the sum of the data in the second loop alone, but the sum in the last loop calculates the sum of the data in that loop and the one before.  What mistake did I make?
import random, time

#Variables
die1 = 0
die2 = 0
goal = 0
tries1 = 0
tries2 = 0
sum = 0
#Asking for the player's names
player1 = input("What is your name, player1?")
player2 = input("What is your name, player2?")

#The "goal"
goal = random.randrange(5) + 1
print("The goal is:", goal)

while die1 != goal:
   die1 = random.randrange(5) + 1
   print(player1, "Your roll is:", die1)
   tries1 = tries1 + 1
   sum = sum + die1
print(sum)
while die2 != goal:
    die2 = random.randrange(5) + 1
    print(player2, "Your roll is:", die2)
    tries2 = tries2 + 1
    sum = sum + die2
print(sum)

A: You are missing re-initializing sum to 0 after the first loop.


text:
Q: Why is the S3 Url not able to be added to the object and submitted to MongoDB? I am working on this nextjs jobboard website app and I have a job object which has several key value pairs that gets filled up over several sibling components and is to be submitted by the current component. The current component's job is to upload the job file attachment to s3, retrieve the url, and store it in the job object and upload it to mongodb. The file was successfully added to s3 and able to grab the url. However after retrieving the file url from s3, it was not able to add the string url to the job object which has a specific string field for the url. When i click submit job from the UI, the joblisting was able to be submitted to mogodb with all the other fields filled with values from other sibling components but failed to add the string URL. I have tried to find a way to solve it but was unable to even though the logic seems so clear.
I need help. Thank you in advance
const submit = async (e) =>{

  setsubmitjob(true);
  let {url}  = await uploadToS3(file);
  setFileUrl(url);

  setjob({
    ...jobarray, joblistingattachment: url
  })

  createjoblist();
}

const createjoblist = async () =>{

  try {
    const res = await axios.post("http://localhost:3000/api/job", jobarray);
    setuploadstatus(true);
    sleep(3500).then(() => {
      router.push("/");
    })
  } catch (e) {
    console.log("Connection to server failed. Please try again in a minute")
  }
}


text:
Q: initializer element is not constant - avr gcc I have a simple code of seven segment deceleration :
#include<avr/io.h>
#include<util/delay.h>
int dp=1<<0;
int a=1<<1;
int b=1<<2;
int c=1<<3;
int d=1<<4;
int e=1<<5;
int f=1<<6;
int g=1<<7;
int ss[]={
    a|b|c|d|e|f,
    b|c,
    a|b|g|e|d,
    a|b|g|c|d,
    f|g|b|c,
    a|f|g|c|d,
    a|f|g|c|d|e,
    a|b|c,
    a|b|c|d|e|f|g,
    a|b|c|d|f|g,
    0x00
};
int main()
{
 while(1){}
}

But this gives me error when I am trying to generate .hex from this .c code:
Here is the error:
main.c:12: error: initializer element is not constant

main.c:12: error: (near initialization for 'ss[0]')
...

Same for all element..

A: One way to do this is to ensure they are constants (available at compile time), by changing it to:
#define dp 0x01
#define a  0x02
#define b  0x04
#define c  0x08
#define d  0x10
#define e  0x20
#define f  0x40
#define g  0x80

I wouldn't worry too much about making them 1<<n values since the number of times you'll have to change it will be vanishingly small.

Changing them to const int doesn't seem to help. I suspect constexpr would be an ideal solution for this, except for the fact it's C++ :-)

If you have binary constants available to you, you may also want to lokk into something like:
static const int sevenSegMap[] = {
    // .abcdefg
     0b01111110,  // or use 0xfe if no binary constants.
     0b00110000,
     : and so on
     0b01111011,
};

A: Variables with the static storage duration shall be initialized with compile-time constant expressions.
Instead of the set of the variables use an enumeration. For example
#include <stdio.h>

enum
{
 dp=1<<0,
 a=1<<1,
 b=1<<2,
 c=1<<3,
 d=1<<4,
 e=1<<5,
 f=1<<6,
 g=1<<7
};

int ss[]={
    a|b|c|d|e|f,
    b|c,
    a|b|g|e|d,
    a|b|g|c|d,
    f|g|b|c,
    a|f|g|c|d,
    a|f|g|c|d|e,
    a|b|c,
    a|b|c|d|e|f|g,
    a|b|c|d|f|g,
    0x00
};

int main(void)
{
    return 0;
}


text:
Q: PHP similiar_text() function issue I was coding a little PHP script that find how much two strings are similar, in percent.
I have this code. If you try to invert the position of the two variable, as seen in figure, the result is different.
<?php
$var_1 = 'PHP IS GREAT';
$var_2 = 'WITH MYSQL';

$var_1 = trim(strtolower ( $var_1 ));
$var_2 = trim(strtolower ( $var_2 ));

similar_text($var_1, $var_2, $percent);

echo $percent;
// 27.272727272727

similar_text($var_2, $var_1, $percent);

echo $percent;
// 18.181818181818
?>

Can someone tips me a better PHP function or explain why the two results are different?

A: Use levenshtein():
$var_1 = 'PHP IS GREAT';
$var_2 = 'WITH MYSQL';
var_dump(levenshtein($var_1, $var_2));
var_dump(levenshtein($var_2, $var_1));

Output:
int(11)
int(11)

A: It would indeed seem the function uses different logic depending of the parameter order. I think there are two things at play.
First, see this example:
echo similar_text('test','wert'); // 1
echo similar_text('wert','test'); // 2

It seems to be that it is testing "how many times any distinct char on param1 is found in param2", and thus result would be different if you swap the params around. It has been reported as a bug, which hasn't been confirmed by anyone.
Now, the above is the same for both PHP and javascript implementations - paremeter order has an impact, so saying that JS code wouldn't do this is wrong. I think it is possible to argue that as intended behaviour. Not sure if it is.
Second - what doesn't seem correct is the MYSQL/PHP word example. With that, javascript version gives 3 irrelevant of the order of params, whereas PHP gives 2 and 3 (and due to that, percentage is equally different). Now, the phrases "PHP IS GREAT" and "WITH MYSQL" should have 5 characters in common, irrelevant of which way you compare: H, I, S and T, one each, plus one for empty space. In order they have 3 characters, 'H', ' ' and 'S', so if you look at the ordering, correct answer should be 3 both ways.
As result use levenshtein()

A: Calulation of similar_text() is:
similar_chars * 200 / (t1_length + t2_length)
Case 1: 3 * 200 / (10+12) = 27.27;
Case 2: 2 * 200 / (10+12) = 18.18;
Why Case 1?
Step 1: PHP_IS_GREAT <-> WITH MYSQL =>  when H is found all before this char will be deleted in both string
Step 2: P_IS_GREAT <-> _MYSQL       =>  Now Whitespace will be found and all before this   char will be deleted in both strings
Step 3: IS_GREAT <-> MYSQL          =>  S will be found and all before this char will be deleted in both strings
Step 4: _GREAT <-> QL               => Nothing else found: Result=3;
Why Case 2?
Step 1: WITH_MYSQL <-> PHP_IS_GREAT => I found and all before this char will be deleted in both strings
Step 2: TH_MYSQL <-> S_GREAT => T found all before  this char will be deleted in both strings
Step 3: H_MYSQL <-> nothing left to compare => Nothing else found: Result=2;
Found here: How does similar_text work?
and wrote it in a bit shorter way.


text:
Q: Booting Linux with different security configurations On an embedded system, we need to boot a Linux partition in several "flavors":

*

*an operational mode where sensitive services are disabled (e.g. sshd);

*an integration mode where such services are enabled.

The expected process is to detect specific GPIOs signals at startup.
The bootloader is U-Boot, and already reads those GPIOs.
I was thinking of letting U-Boot pass some specific argument to the Linux kernel, and then let startup scripts parse /proc/cmdline in order to alter their behaviour accordingly.
The other obvious solution would be to let the startup scripts reacquire the GPIOs once they are started, but this solution doesn't seem robust to signal jitters (some of them are dependant on an operator holding a button...)

*

*Are there any drawbacks to the "kernel argument" solution ?

*Did I miss any other simple solutions ?

Sincerely,
Vincent

A:
Are there any drawbacks to the "kernel argument" solution ?

I don't think so.

Did I miss any other simple solutions ?

I would go on the kernel solution and use a specific runlevel.
If i understood well your needs, the integration mode will implement the same things than production/operation mode but with stuff added (ssh, etc...).
So i would use runlevel 4 for operation mode and runlevel 5 for integration mode.
See manpage for runlevel and more globally for boot


text:
Q: How to access nested class B in an interface? interface C {
    class B {
        void run() {
            System.out.println("nested class run method");
        }
    }
}

public class MainClass {
    public static void main(String[] args) {
    }
}

How to access the run method in class B in interface C?

A: You must prefix the name of the class with the name of its enclosing interface:
C.B runner = new C.B();
runner.run();


text:
Q: Directory as a dependency in make rule Is it possible to specify a directory as a dependency in a Makefile rule? Actually I have a Makefile in a directory and another directory containing all the source files.
.
.
|_ Makefile
|_ src
    |_a.c
    |_a.h

Now I want that whenever I make any change in the src directory i.e. in either of a.c or a.h , a particular rule in my Makefile get called on issuing make command. Something like
Makefile
.
.
.
build: src
    <commands>

clean:
    <commands>

A: While it is possible to have a directory as a dependency, there are a few things to be aware of. Consider this:
directory:
        @mkdir -p directory

directory/file : directory
        commands-to-make-the-file

This will do what you think. However, it executes the commands-to-make-the-file whenever file is older than directory, which may not be what you want.
You need to consider the scenarios where the timestamp of directory gets updated. That happens whenever files are added into or removed from the directory but it doesn't happen when an existing file is modified.
So, some unrelated action that updates the directory will cause the file to become out of date, perhaps needlessly so, which will trigger the commands to re-make it.

A: It is possible to have a directory as a dependency, in the sense that if it does not exist it will be rebuilt. It's even possible to arrange a rule that will execute when anything in the directory changes, but it's tricky. And in this case it's almost certainly overkill.
If your intent is ordinary, the usual method will suffice:
OBJ_FILES = foo.o bar.o baz.o
# There are ways to be more succinct, but for now we'll keep it simple.

build: $(OBJ_FILES)
    <commands...>

%.o: src/%.c src/%.h
    <commands for building something.o>

clean: # This should not require prerequisites
    <commands...>


text:
Q: Start apps minimized on try for Windows 8.1 startup Is there any way to start a selected app minimized on try on a Windwos 8.1 startup?
I tried with no success with Task Schedule on Windows 8.1 and starting a cmd with the following optional arguments: /c start "ZimMini" /min "C:\Program Files (x86)\Zim Desktop Wiki\zim.exe"
Any ideas?

A: Make a shortcut of the Application you want to start minimized.
Put it in the start-up menu so it can start at windows load.
Click properties on it.
Click on the drop-down menu under Run. Select "Minimized," then click the OK button.
When start of the program occurs, it'll start up minimized. If the program has been written to minimize to the notification area in the system tray it'll show up there, which is even better.


text:
Q: Using MySQL & MSSQL for two different databases with Entity Framework I am trying to build a web api that serves data from either a MySQL database or a MSSQL database (completely different data and schema). It also provides some endpoints for moving data between the two. I have created two class libraries to hold the EF models for both databases and have been successful in connecting to both instances and running queries against both. Where it falls down is trying to access both of them. I have to tweak the web.config entityFramework section to get either to work, I can't get it so that both work at the same time effectively. I am using EF6 and the latest MySQL connector.
This is the working config for MSSQL entities:
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
  <parameters>
    <parameter value="v11.0" />
  </parameters>
</defaultConnectionFactory>
<providers>
  <provider invariantName="MySql.Data.MySqlClient" type="MySql.Data.MySqlClient.MySqlProviderServices, MySql.Data.Entity.EF6" />
  <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>

This is the error it produces when I try to use the MySQL entity context
The default DbConfiguration instance was used by the Entity Framework before the 'MySqlEFConfiguration' type was discovered. An instance of 'MySqlEFConfiguration' must be set at application start before using any Entity Framework features or must be registered in the application's config file. See http://go.microsoft.com/fwlink/?LinkId=260883 for more information.

This is the working config for MySQL entities:
<entityFramework codeConfigurationType="MySql.Data.Entity.MySqlEFConfiguration, MySql.Data.Entity.EF6">
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
<providers>
  <provider invariantName="MySql.Data.MySqlClient" type="MySql.Data.MySqlClient.MySqlProviderServices, MySql.Data.Entity.EF6" />
  <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />

This then complains about the connection string as its trying to use the MySQL libraries. I can't find much online about this, this question here is similar but there was no answer to it: Is it possible to have a EF Context for MySql and SqlServer?
Has anyone done this or know of a way round the issue?

A: To resolve this error i put this on my App.config: "codeConfigurationType"
<entityFramework codeConfigurationType="MySql.Data.Entity.MySqlEFConfiguration, MySql.Data.Entity.EF6">

Why? Possible the Configurations is not fiding the location of MySqlEFConfiguration.
Im using here only Mysql, i dont know if this work on SQLServer and Mysql togueter.
For your problem this link can be useful: Link
And you can have 2 separeted configuration.cs Files. One for MySql and other for MSSQL

A: The issue appears to have been addressed in the beta MySQL connector at the time of writing this, version 6.9.1. I now have the two running side by side without any problems.
Update
For clarification the setup I have is EF5 (EF6 won't work) and the MySQL connector version 6.9.1 (beta). my web.config section looks like this:
<entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="v11.0" />
      </parameters>
    </defaultConnectionFactory>
  </entityFramework>

The model's are located in the same project, again I have had difficulty with class libraries.

A: I had the same issue. I'm using migrations in my code first project with two db contexts for mysql and mssql. The issue is because EF6 tries to find db configuration in config file or in the same assembly where db context is. For mysql migrations I use MySqlHistoryContext that inherits from DbContext. During db initialization stage EF6 creates instance of MySqlHistoryContext and find MySqlEFConfiguration type and tries to use it.
I found two ways to solve the issue. The first is disabling migrations checks by call Database.SetInitializer with null argument. The second is inherit from MySqlHistoryContext in my own assembly. The second seems to work for me.

A: I chased down all the solutions I could find on SO and elsewhere, and for me the issue turned out to be my MSSQL connection string.
before:
<add name="DefaultConnection" providerName="System.Data.SqlClient" connectionString="Server=serverName/instance;Database=PublicWebsite;Integrated Security=True;" />

after:
<add name="DefaultConnection" providerName="System.Data.SqlClient" connectionString="Data Source=serverName/instance;Initial Catalog=PublicWebsite;Integrated Security=True;" />

The "before" connection string worked fine for EF.  The problem presented after we introduced MySQL for EF (in a different class library).
To be clear, in MSSQL the connection string we just changed "server" to "data source" and we changed "database" to "initial catalog".


text:
Q: Dynamics 365: Are portal comments supposed to show up in Audit History? When a "portal comment" is added to a case, it is not logged to the cases Audit History. Is that an error or to be expected?

A: Portal comment is a child activity (another entity record) of the case entity, that's why it's not showing in case audit history. Only case record attribute changes will be in case audit history.
The activities including portal comments will be listed under Timeline and Activities list, not in audit history.
Troubleshooting related to Portal comments


text:
Q: Environment.SpecialFolders in Silverlight 4 on Mac Silverlight 4 running with elevated permissions provides access to certain special folders in the file system.
http://msdn.microsoft.com/en-us/library/system.environment.specialfolder(VS.95).aspx
These work great on Windows, but what do they map to on Mac OSX systems?
My application needs to access "My Documents". Will this map somewhere sensible on the mac?

A: Yes, but with a little trick.
You can create a file on windows even the containing folder does not exist, but on OS X your have to create the directory first. If not you will get an exception.
My code is as follow:
Directory.CreateDirectory(dirPath);  // Not necessary on windows
FileStream newFs = File.Create(dirFile);
newFs.Close();
newFs.Dispose();

On OS X the "My Documents" folder is here:
/Users/[UserName]/Documents


text:
Q: Most elegant way to prove a prime is a prime? Taking say 103, the best way I can think of is to square root it (giving 10.14889), then say that all factors must be below that root, then show that 103 is not divisible by 2,3,5,7 (prime factors below the square root), and is therefore prime?
Is there a better way to prove it is a prime, or is this the best way?

A: For small odd numbers, say below $10^6$, there is just no better way than trial division: try dividing $n$ by each prime less than $\sqrt n$ and see what happens. Heck, you can even try dividing by all odd numbers, including composite numbers like $9$ and $15$, with hardly any performance penalty (assuming you're using a computer).
When you go above $10^{10}$ (these are not hard limits, more like fuzzy gray lines) things start getting hairy and you need something more elegant in order to get results in your lifetime.
For example, is $2^{44501} - 1$ prime? This is a number with more than ten thousand digits in base $10$, and $44500$ bits in binary. Trial division just won't cut it.
Mathematicians have developed all kinds of tests for primes of special forms. I could be wrong, but $103$ doesn't seem all that special. Now consider a number like $127$. It's special because it's $2^7 - 1$. Because $11 < \sqrt{127}$, it's enough to test the primes $3, 5, 7, 11$.
The Lucas-Lehmer test applied to $127$ seems kind of overkill, except for pedagogic purposes. Set $LL_0 = 4$, and then $LL_n = (LL_{n - 1})^2 - 2$. If $2^p - 1$ is prime, then $LL_{p - 2} \equiv 0 \pmod{2^p - 1}$. The proof is too long to repeat here but can be found on the Web easily enough. So modulo $127$, we have: $4, 14, 194, 42,  111, 0$, bingo!
When you start to look at numbers like $2^{31} - 1$, then you can really appreciate things like the Lucas-Lehmer test. But to deal with large odd numbers that don't seem to be of any special form, there are algorithms like Pollard $p - 1$ and Pollard $\rho$, which have their best case and worst case scenarios (e.g., hardly any better than trial division).


text:
Q: Webpack/webpack-cleanup-plugin: webpack.config.js that only does the cleanup Is it possible to configure a webpack.config.js that only does a cleanup (using "webpack-cleanup-plugin"), without having to configure the entry or output parameters?

A: If you want to run the cleanup plugin but don't want webpack to bundle your files then that's not possible because primary goal of webpack is to bundle your dependencies and taks like cleanup are add-ons
There is probably a better way to do this thing but to answer your question

without having to configure the entry or output parameters?

yes this is possible with Webpack 4 if you don't specify entry or output parameter it will use the default values which is src/index.js for entry and dist for output.folder
Webpack will throw a error if entry file is not found
so if you dont specify entry then src/index.js must be present in your project
so lets say your folder structure is as following
| src
     |index.js
| libs
| build

now if you want to clean the build directory then you create a configuration like this
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const path = require('path');

module.exports = {
  plugins: [
    new CleanWebpackPlugin({
      // takes an array so you can specify multiple patterns
      // build/**/* will clean everything inside build but not build directory itself
      cleanOnceBeforeBuildPatterns: [path.resolve(process.cwd(), 'build/**/*')]
    }),
  ]
};

notice that now you need to specify the cleanOnceBeforeBuildPatterns because by default clean-webpack-plugin

will remove all files inside webpack's output.path directory

and we didn't specify the output.path so it's default value is dist more accurate would be path.resolve(process.cwd(), 'dist') but we want to cleanup everything inside build
you can specify other options like
cleanOnceBeforeBuildPatterns, cleanAfterEveryBuildPatterns or event if you want to clean up outside of your project then you cant set dangerouslyAllowCleanPatternsOutsideProject to true
more info here
because running webpack with this configuration will also create the dist/main.js bundle so we need to remove that as well so your script may look like this
  "scripts": {
    "clean": "webpack --config webpack.config.js && rm -rf ./dist"
  }

A more simple way to do this is by specifying a simple bash command in your package.json file something like
  "scripts": {
    "clean": "rm -rf ./build/**"
  }

and you can run it like yarn clean or npm run clean


text:
Q: MVC. Bind TextBoxFor to a Field of type object Suppose the following code:
public class Person
{
    public object Age { get; set;}
}

Inside view:
@Html.TextBoxFor(x => x.Age, new { @type = "number" })

Now when posting the Form, the typeOf person.Age property is string[1]. Why?
Shouldn't there be some input type based, Type pick-up logic, when binding things?

A: You can't use the *For helpers with a property of type object. These helpers need to do type inference in order to create the right type of input with the right name and attributes. An object could literally be anything.
I'm not sure why you're using object for a property like Age (isn't that fairly obviously a int?). However, if you truly need to do that, I would recommend using a view model where you can define a more concrete type for the purposes of your view. Then, you can simply map the posted value back onto your object property.


text:
Q: Workaround to Quantmod getDividends which apparently stopped working Jan 16, 2020 My R program started failing Jan 16
 quantmod::getDividends('BBY')
gives:

Error in vapply(parse(text = fr[, 2]), eval, numeric(1)) :
  values must be length 1,
 but FUN(X[[1]]) result is length 2

A: Yahoo Finance changed the split ratio delimiter from "/" to ":".  For example, a 2-for-1 split was 1/2 but is now "2:1". This broke getSplits() and getDividends() (which called getSplits()).
This has been fixed in quantmod 0.4-16, which is on CRAN now. Windows binaries should be available over the next few days.


text:
Q: Externally adding another layer to convolution output I have a network in which the data comes from a stack of images and a vector of numbers.
I begin with two "branches": The images go through several convolutions and produce an output of shape (50, 50, 64). In the other branch I import the number and go:
x = Input(shape = (13)) # data vector is of length 13
x = Dense(50*50)(x)
x = Reshape((50,50))(x)

I now have 2 outputs from the branches - one is of shape (50, 50, 64) and the other of shape (50, 50, 1). How can I "stick" them together to get a collective (50, 50, 65) which I'd then Deconv2D?

A: You could use the keras Concatenate() layer as in follows:
import numpy as np
from keras import backend as K
from keras import layers

# create some dummy tensors with numpy and the keras backend
arr1 = K.constant(np.zeros((50, 50, 1)))
arr2 = K.constant(np.zeros((50, 50, 64)))

# and this is how you call the concatenate layer
combined = layers.Concatenate()([arr1, arr2])

# it should print this:
# Tensor("concatenate_1/concat:0", shape=(50, 50, 65), dtype=float32)
print(combined)

A: you can use numpy function : np.c_
try:
>>> x.shape
(50, 50, 64)
>>> y.shape
(50, 50, 1)
>>> z = np.c_[x,y]
>>> z.shape
(50, 50, 65)


text:
Q: C++: calling main() twice leads to infinite loop recursion I have the following C++ code
#include <iostream>
using namespace std;

int main()
{
    static int v = 5;
    cout<<v;
    v--;
    if(v)
    {
        main();
        main();
    }
}

If I call the main just once the code behaves properly and gives the output 54321 but if I compile the above program it gives as infinite loop and then segmentation fault occurs. can anyone please explain?

A: In an if statement, any non-zero value is evaluated as true.
The 1st call will run a recursive loop, starting with v=5, decrementing v to 4 before the first if, and then continuing to decrement v on each iteration until v becomes 0, breaking the loop.
The 2nd call will run a new recursive loop, starting with v=0, decrementing v to -1 before the first if, and then continuing to decrement v on each iteration until v overflows and eventually becomes 0 again, breaking the loop.
If it even gets far, since each call to main() pushes data on the call stack, recursively, until there is no more stack space available.


text:
Q: Getting around Chrome's Malicious File Warning I created an application which comprises a number of *.exe files. I've packaged these up into an NSIS installer which I hosted on my website. When I try to download it Chrome reports it as potentially malicious. At first I thought it could be the URL/site I was hosting on not being recognized so I signed up for Amazon S3 storage and moved the file there. Same problem. I then thought that packing the executables might cause this, so I tried without.
Same issue.
After some more reading I decided to try signing the executables as well as the installer package EXE.
I created a dev cert as follows:
makecert
pvk2pfx
signtool"http://timestamp.verisign.com/scripts/timstamp.dll" *.exe

Still malicious... I check the exe's even after download and confirmed they have a digital signature tab, granted it's not a fully verified commercial certificate but I can't believe the only way around Chromes half-baked code analysis is to spend $200 a year to have a verisign etc. code signing cert issued?
Any ideas how I can change what I'm doing to avoid this nasty message?

A: Well, anonymous .exe are potential threats, Chrome is preventing users about this.
You are signing the exes, but I'm not quite sure your certificate is backed by a Certification Authority, like Verisign.  They sell this services.  But yet, I'm not sure signing will make any difference.  Chrome reads the files' names inside the zip, but I don't think it decompress the entire file to read the sign.
I can tell you one or two workarounds, I'm pretty sure you know them:

*

*Change the file extension, and ask the user to rename the files back to .exe

*Password protect your zip, rar, or whatever, so Chrome won't be able to look inside, and supply the password to users: it's not a secret password

A: I also had the same issue, and tried the options described above as well,but no luck. I guess I was just too impatient to wait for Google to crawl my site.
I ended up registering with Softonic and CNET's Upload.com, and submitted my application for review and inclusion on their sites. After their approval, I added the link to my site, the file downloaded fine.
The only bad thing is that you need to download the Softonic downloader to install your application on softonic, but CNET offers a "direct download link" that allows you to download your original installer.

A: I had exactly this problem with an exe file that is downloadable from my web site. Whenever I tried to download the file using Chrome it gave the warning.
The solution I found was to sign up to Google Webmaster Tools and add my site. It took several days for Google to crawl my site, and fill in any information, but I went back today and finally found loads of information there.
Now I can download my file, and there is no malicious warning any more.
It seems that once Google has checked out your site and determined that you are not a bad person, the problem goes away.

A: I ran into this issue. The simplest work around: use another [insert browser name here]. eg. firefox.

A: If you have a domain with a non-standard domain suffix such as .one, Chrome will complain. So will FireFox for that matter.
I don't think this was the OP's problem but if you land here because you're searching madly trying to figure out why a commom file like a .zip file is giving you a warning in Chrome or FF when downloading, it could very well be that you need to use a common domain suffix such as .com

A: I also had this issue. I am using a certificate generated from my own CA which is installed to the Trusted root certification authorities. At first signing wasn't enough, but then I added file version with my name on it and also an icon. Now Chrome is happy to download and run it.


text:
Q: Is the minimum number of relations in a free product, the sum of the minimum number of relations in the free factors? Say $\rho(G)$ is the minimum number of relations required to present the group $G$. Is $\rho(A*B)= \rho(A)+\rho(B)$? What can be said about $\rho(A*B)$?
A while ago I was thinking about $C_3*C_4$, thinking it was obvious that this group should not be a one-relator group. I am pretty sure at one point I came up with an argument but it seemed awfully complicated, and using specific information about one-relator groups for something that "feels" obvious.

Using the comments below as a guide, one can prove that if the abelianization of $A,B$ is finite and $\rho(A)=r(A),\rho(B)=r(B)$ where $r(G)$ is the rank of the group (minimum number of generators), then we can get that $\rho(A*B)=\rho(A)+\rho(B)$.

*

*It is known that $r(A*B) =r(A)+r(B)$, this can be found in Ch IV Cor 1.9 in Lyndon and Schupp.

*We also have that $\rho(A*B) \leq \rho(A)+\rho(B)=r(A)+r(B)$.

*If $\rho(A*B) < r(A*B)$, then a presentation witnessing that inequality can be shown to have an infinite abelianization, since the number of generators would be strictly greater than the number of relations (see this answer). This contradicts that the abelianization of $A*B$ is finite.

So finite free products of finite cyclic groups works and other groups too.

I could see a careful analysis the abelianization of f.g. groups giving more more information. And it does seem that a somewhat related concept, group deficiency, is related to some cohomology groups (I don't know any cohomology, but I would welcome an answer, even if it used cohomology).

A: $\DeclareMathOperator{\def}{def}$
It turns out that there are groups $A*B$ with $\rho(A*B) < \rho(A)+\rho(B)$!

*

*$(C_2 \times C_2) * (C_3 \times C_3)$ has a 5 relation presentation $$\langle x,y,z,t \mid x^2,z^3,xyx^{-1}y^{-3}, ztz^{-1}t^{-4}, y^2t^{-3} \rangle$$ by theorem 3 in Presentation classes, 3-manifolds and free products by Cynthia Hog, Martin Lustig and Wolfgang Metzler.

*The Schur multiplier  of a finite group $G$ gives information about the deficiency of the group, where the deficiency is the maximum value of generators minus relators over all presentation of the group which will be called $\def G$. In particular, the Schur multiplier can be generated by $-\def G$ generators. Both $C_2 \times C_2$ and $C_3 \times C_3$ have nontrivial Schur multiplier, so neither can have deficiency equal to $0$. That implies that they do not have two relator, two generator presentations.

*The groups $C_i \times C_i$ is not cyclic and can not have more generators than relations, since they are finite.  So the fewest number of relations comes from the standard presentation $$C_i \times C_i\cong\langle x,y \mid x^i, y^i, xyx^{-1}y^{-1} \rangle.$$

This means that $$\rho {\big{(}}(C_2 \times C_2) *(C_3 \times C_3) {\big )}\leq 5 <6=\rho(C_2 \times C_2) + \rho(C_3 \times C_3).$$


text:
Q: Using JUnit to perform an insert I need to insert data into a table using JUnit tests.  Is this possible? If so, how? Thanks!

A: Check out DBUnit.

DbUnit is a JUnit extension (also usable with Ant) targeted at database-driven projects that, among other things, puts your database into a known state between test runs. This is an excellent way to avoid the myriad of problems that can occur when one test case corrupts the database and causes subsequent tests to fail or exacerbate the damage.
DbUnit has the ability to export and import your database data to and from XML datasets. Since version 2.0, DbUnit can also work with very large datasets when used in streaming mode. DbUnit can also help you to verify that your database data match an expected set of values.

A: You can use JDBC and regular insert statements to do this.
See the Java JDBC tutorial to get started: http://download.oracle.com/javase/tutorial/jdbc/

A: I don't have time to write a sample for you.
You're new to this, so it's likely to be over your head, but I'd recommend that you study some Spring 3 examples even if you don't use Spring.  The ideas will help you to write better tests.
The key is to make your tests transactional: Do your INSERT, check the result, and roll the transaction back when you're done.  It should be as if your test was never there.
http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/testing.html


text:
Q: Non-problematic XML-to-Java binding I've looked all over the place for a good way to bind XML elements to Java classes. It sounds like a fairly easy thing to implement (for some value of easy), but wherever I look, there's the need for XSDs, explicit mapping and a bunch of other things that really get in the way for me.
This is my (possibly incomplete) idea of a Java object representing a sitemap.
public class Sitemap {

    private List<Url> urls;

    public List<Url> getUrls() {
        return urls;
    }

    public void setUrls(List<Url> urls) {
        this.urls = urls;
    }
}

I'm looking for something which lets me do:
Sitemap sitemap = (Sitemap) Foo.fromXml("sitemap.xml")

Something like that, or at least similar. Is there any such thing?

A: Below is how this could be done with a JAXB (JSR-222).  An implementation is included in Java SE 6.  There are also other implementations such as EclipseLink MOXy (I'm the tech lead).
SHORT ANSWER
You couls use the following API call with JAXB with any annotations or XML schemas.
Sitemap sitemap = JAXB.unmarshal(xml, Sitemap.class);

LONG ANSWER
Below is a more detailed example.
Sitemap
I've modified your class slightly.  I wasn't sure what the Url class was so I changed it to java.net.URL.  Note how no annotations are required on the domain model.
package forum10854001;

import java.net.URL;
import java.util.List;

public class Sitemap {

    private List<URL> urls;

    public List<URL> getUrls() {
        return urls;
    }

    public void setUrls(List<URL> urls) {
        this.urls = urls;
    }
}

Demo
Instead of the code used in the short answer, I have created a JAXBContext.  The JAXBContext is a thread safe object that represents all the initialized metadata.  The Marshaller and Unmarshaller objects provider additional flexibility over the JAXB class.
The code below demonstrates how to read in the XML and them write it back out:
package forum10854001;

import javax.xml.bind.*;
import javax.xml.transform.stream.StreamSource;

public class Demo {

    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContext.newInstance(Sitemap.class);

        Unmarshaller unmarshaller = jc.createUnmarshaller();
        StreamSource xml = new StreamSource("src/forum10854001/input.xml");
        JAXBElement<Sitemap> jaxbElement = unmarshaller.unmarshal(xml, Sitemap.class);

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(jaxbElement, System.out);

    }

}

input.xml/Output
<?xml version="1.0" encoding="UTF-8"?>
<sitemap>
    <urls>http://www.eclipse.org/eclipselink/moxy.php</urls>
    <urls>http://jaxb.java.net</urls>
</sitemap>

For More Information

*

*http://wiki.eclipse.org/EclipseLink/Examples/MOXy/GettingStarted

A: You can also consider XStream.  Here is roughly equivalent code to Blaise's, though working in the opposite direction (starting with an Object, not XML) for variety:
public class Sitemap{
      private List<URL> urls = new ArrayList();

      // I left out the setters and getters

      public static void main(String[] args) throws IOException {
         Sitemap sitemap = new Sitemap();
         sitemap.urls.add(new URL("http://www.eclipse.org/eclipselink/moxy.php"));
         sitemap.urls.add(new URL("http://jaxb.java.net"));

         XStream xs = new XStream(new DomDriver());
         String xmlString = xs.toXML(sitemap);
         System.out.println(xmlString);
         Sitemap readBack = (Sitemap) xs.fromXML(xmlString);
      }
   }

yields the following output:
<com.your.name.here.Sitemap>
  <urls>
    <url>http://www.eclipse.org/eclipselink/moxy.php</url>
    <url>http://jaxb.java.net</url>
  </urls>
</com.your.name.here.Sitemap>

And you can set a breakpoint and view readBack in the debugger and it has both URLS.


text:
Q: How to install PHP in IIS 7.5, Windows Server 2008 R2 (64bits) In http://windows.php.net/downloads I couldn't find any x64 built for download.
Further I have to choose among "Thread Safe" and "Non Thread Safe" with no explanation whether one is safer than the other or it performs better. The install.txt inside the available ZIPs for download seems out-dated an it doesn't mention anything about this.
In http://php.net/manual/pl/install.windows.iis7.php they don't say a word about it either...
Another doubt is once I know what to download (and why), should it be setup as a FastCGI module or as an ISAPI extension?

A: (My experiences running PHP under IIS)
I believe that you should set up PHP as a FastCGI module - I don't think you are able to set up PHP as an ISAPI extension. You can  set up PHP either using FastCGI or ISAPI - It may be that ISAPI is faster than FastCGI. There is a guide on setting up IIS using ISAPI here:

*

*http://www.lazynetworkadmin.com/knowledgebase-mainmenu-6/2-windows/141-install-php-on-server-2008-r2
Searching google reveals a lot of pages discussing the thread safe vs non thread safe argument if you want to know the detail, however the short version is that the non thread safe version is faster, but the thread safe version is safer.  You should choose the thread safe version for now unless you have a performance problem and know that your app is going to run correctly under the non thread safe binaries.
Finally, there isn't really any need for x64 binaries when running PHP as a FastCGI application - php runs as a separate process and so the x86 binaries will run fine on a x64 web server, and most normal php applications will have no need for an address space above 4GB as to scale IIS can simply start additional php processes.
When configuring your FastCGI extension you need to point it at the php-cgi.exe executable in the php installation directory.

A: I often use FastCGI when setting up PHP on IIS. It is moreso habit than anything else. While I did read over many of the other articles posted and it does appear that ISAPI has many advantages I thought I'd add a link to setting up FastCGI for those who want to go that route. I've used it and never had any issues with moderate request traffic.
Anyway here's a link to an article with screenshots on setting up PHP via FastCGI on IIS 7.5.
Click here to visit the article.


text:
Q: MsgBox with Scripting.FileSystemObject's File.Path does not display Cyrillic characters I am walking through all files in a folder. When I hit a file name that includes these special characters "Информационное письмо" the special characters are turned into "?" - question marks. Please how can I get the original file name this way?
Code:
Dim objFolder As Object
Dim objFile As Object
Dim objFSO as Object
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFSO.GetFolder("C:\test")
For Each objFile In objFolder.Files
    MsgBox objFile.Path
next objFile

A: Choose the correct codepage for Non Unicode Programs in Regional Settings.
All API calls are ANSI. MsgBoxA is an ANSI function.


text:
Q: appium , selenium.SessionNotCreatedException Error I tried to launch appium first test but I got an error however some fields are not blank.
My error log is that:
**

Exception in thread "main"
  org.openqa.selenium.SessionNotCreatedException: A new session could
  not be created. Details: The desiredCapabilities object was not valid
  for the following reason(s):  deviceName can't be blank, (WARNING: The
  server did not provide any stacktrace information) Command duration or
  timeout: 393 milliseconds Build info: version: '3.5.3', revision:
  'a88d25fe6b', time: '2017-08-29T12:42:44.417Z' System info: host:
  'ASUS-BILGISAYAR', ip: '192.168.1.103', os.name: 'Windows 7', os.arch:
  'amd64', os.version: '6.1', java.version: '1.8.0_151' Driver info:
  driver.version: AndroidDriver     at
  sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown
  Source)   at
  sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown
  Source)   at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at
  org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:215)
    at
  org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:167)
    at
  org.openqa.selenium.remote.JsonWireProtocolResponse.lambda$new$0(JsonWireProtocolResponse.java:53)
    at
  org.openqa.selenium.remote.JsonWireProtocolResponse.lambda$getResponseFunction$2(JsonWireProtocolResponse.java:91)
    at
  org.openqa.selenium.remote.ProtocolHandshake.lambda$createSession$24(ProtocolHandshake.java:359)
    at java.util.stream.ReferencePipeline$3$1.accept(Unknown Source)    at
  java.util.Spliterators$ArraySpliterator.tryAdvance(Unknown Source)    at
  java.util.stream.ReferencePipeline.forEachWithCancel(Unknown Source)
    at java.util.stream.AbstractPipeline.copyIntoWithCancel(Unknown
  Source)   at java.util.stream.AbstractPipeline.copyInto(Unknown Source)
    at java.util.stream.AbstractPipeline.wrapAndCopyInto(Unknown Source)
    at java.util.stream.FindOps$FindOp.evaluateSequential(Unknown Source)
    at java.util.stream.AbstractPipeline.evaluate(Unknown Source)   at
  java.util.stream.ReferencePipeline.findFirst(Unknown Source)  at
  org.openqa.selenium.remote.ProtocolHandshake.createSession(ProtocolHandshake.java:362)
    at
  org.openqa.selenium.remote.ProtocolHandshake.createSession(ProtocolHandshake.java:136)
    at
  org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:142)
    at
  io.appium.java_client.remote.AppiumCommandExecutor.execute(AppiumCommandExecutor.java:89)
    at
  org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:646)
    at
  io.appium.java_client.DefaultGenericMobileDriver.execute(DefaultGenericMobileDriver.java:42)
    at io.appium.java_client.AppiumDriver.execute(AppiumDriver.java:1)
    at
  io.appium.java_client.android.AndroidDriver.execute(AndroidDriver.java:1)
    at
  org.openqa.selenium.remote.RemoteWebDriver.startSession(RemoteWebDriver.java:255)
    at
  org.openqa.selenium.remote.RemoteWebDriver.startSession(RemoteWebDriver.java:237)
    at
  org.openqa.selenium.remote.RemoteWebDriver.(RemoteWebDriver.java:138)
    at
  io.appium.java_client.DefaultGenericMobileDriver.(DefaultGenericMobileDriver.java:38)
    at io.appium.java_client.AppiumDriver.(AppiumDriver.java:87)
    at io.appium.java_client.AppiumDriver.(AppiumDriver.java:111)
    at
  io.appium.java_client.android.AndroidDriver.(AndroidDriver.java:72)
    at com.enuygun.test.StartApplication.main(StartApplication.java:19)

**
My codes are as in the below:
package com.enuygun.test;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;

import io.appium.java_client.android.AndroidDriver;

public class StartApplication {

        public static void main(String[] args) throws MalformedURLException, InterruptedException {
            DesiredCapabilities capabilities = DesiredCapabilities.android();
            WebDriver driver = new AndroidDriver(new URL("http://127.0.0.1:4723/wd/hub"), capabilities);
            File classpathRoot = new File(System.getProperty("user.dir"));
            File appDir = new File(classpathRoot, "/Apps/Amazon/");
            File app = new File(appDir, "in.amazon.mShop.android.shopping.apk");

            capabilities.setCapability(CapabilityType.BROWSER_NAME, "");
            capabilities.setCapability("deviceName", "Micromax A311");
            capabilities.setCapability("platformVersion", "4.4.2");
            capabilities.setCapability("platformName", "Android");
            capabilities.setCapability("app", app.getAbsolutePath());
            capabilities.setCapability("appPackage", "in.amazon.mShop.android.shopping");
            capabilities.setCapability("appActivity", "com.amazon.mShop.home.HomeActivity");

            driver.manage().timeouts().implicitlyWait(80, TimeUnit.SECONDS);
            Thread.sleep(10000);
            driver.quit();

    }

}

A: You are instantiating your driver before you are setting your desired capabilities, so your capabilities object is blank.  Move your line to create a new driver after your desired capabilities properties are being set.


text:
Q: ValidateAntiForgeryToken 400 error Using angular 13 and ASP.NET core 5 I am using Angular 13 and ASP.Net Core5. I am trying to use ValidateAntiFOrgeryToken attribute and always get 400 error. Before I post this question, I tried almost all the solutions found on the internet. But, I want to clarify my case, I am creating a multi-tenant app. Every business owner will have a subdomain and separate database. I don't know if the Antiforgery token is not working due to this condition or not, but I tried many solutions for 3 days.
Startup.cs
services.AddAntiforgery(options =>
            {
                options.Cookie.Name = "XSRF-TOKEN";
                options.HeaderName = "X-XSRF-TOKEN";
                options.Cookie.HttpOnly = false;
            });

I used this configuration and ASP.NET sent antiforgery cookie with the name XSRF-TOKEN. According the Angular documentation, Angular will sent a header with name X-XSERF-TOKEN if there is a cookie with the name X-XSRF-TOKEN. Actually, Angular sent it successfully with every request, but I still getting error with code 400.
I tried to add the X-XSRF-TOKEN manually. I tried to use following a middlewhere
app.Use(next => context =>
            {
                if (
                    string.Equals(context.Request.Path.Value, "/", StringComparison.OrdinalIgnoreCase) ||
                    string.Equals(context.Request.Path.Value, "/index.html", StringComparison.OrdinalIgnoreCase) ||
                    string.Equals(context.Request.Path.Value, "/api", StringComparison.OrdinalIgnoreCase))
                {
                    // We can send the request token as a JavaScript-readable cookie, and Angular will use it by default.
                    var tokens = antiForgery.GetAndStoreTokens(context);
                    context.Response.Cookies.Append("XSRF-TOKEN", tokens.RequestToken,
                        new CookieOptions() { HttpOnly = false, Secure = false });
                }

                return next(context);
            });

I tried to use CORS in startup.cs
services.AddCors(c =>
{
c.AddPolicy("AllowOrigin", options => options.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod());
});
app.UseCors(policy =>
           {
              policy.AllowAnyOrigin();
              policy.AllowAnyHeader();
              policy.AllowAnyMethod();
           });

then added [EnableCors(PolicyName = "AllowOrigin")] for the controller.
I tried combinations of these solutions but I am still getting the same error.

A: Finally, I figured out the problem. My case is that I create a subdomain and different database for each business owner. The [ValidateAntiForgeryToken] works well with the following configuration:
in ConfigureServices:
services.AddAuthentication(x =>
            {
                x.DefaultAuthenticateScheme = IdentityConstants.ApplicationScheme;
                x.DefaultChallengeScheme = IdentityConstants.ApplicationScheme;
            })
            .AddCookie(IdentityConstants.ApplicationScheme)
            .AddJwtBearer(x =>
            {
                x.RequireHttpsMetadata = false;
                x.TokenValidationParameters = new TokenValidationParameters()
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["TokenKey"])),
                    ValidateIssuer = false,
                    ValidateAudience = false
                };
            });

In Configure:
app.Use(next => context =>
            {
                if (context.Request.Path.Value.IndexOf("/api", StringComparison.OrdinalIgnoreCase) != -1)
                {
                    var tokens = antiForgery.GetAndStoreTokens(context);
                    context.Response.Cookies.Append("XSRF-TOKEN", tokens.RequestToken,
                        new CookieOptions() { HttpOnly = false, Secure = false });
                }

                return next(context);
            });

However, this works will without the Authorize attribute [Authorize].
So, my solution to use [Authorize] and [ValidateAntiForgeryToken] is to create a custom Antiforgery token attribute.
I created the custom AntiForgeryToken using the solution in this question
https://stackoverflow.com/a/28526906/14474303.
But be carefull, If your controller class inherits from ControllerBase, this means you using Microsoft.AspNetCore.Mvc;, but if it inherits from ApiController, then, you are using System.Web.Http. The solution in this link is using System.Web.Http and it will not work if you are using `Microsoft.AspNetCore.Mvc.
Simply, if you will create a custom Antiforgery token, your custom class will inherits from ActionFilterAttribute. So, if you are using System.Web.Http, then ActionFilterAttribute will be imported from System.Web.Http, but, it you are using Microsoft.AspNetCore.Mvc, then ActionFilterAttribute will be imported from `Microsoft.AspNetCore.Mvc.


text:
Q: How to run Mongoose/MongoDB updates/queries in node.js backend without starting the server? (Heroku Scheduler) I have an app hosted on Heroku (https://trendedge.app) (front-end and back-end are separate apps), and am working on implementing the Heroku Scheduler for basic tasks such as sending emails, and running updates on my MongoDB Atlas database (hit an API, update MongoDB w/ Mongoose).
For the MongoDB updates, I currently hit an admin route on the front-end, and the updates start running on the backend. Easy PZ.
To setup the Heroku scheduler, though, it requests a node.js command (seen here) ...
... and this makes sense, but if my connection to MongoDB atlas is made upon the starting up the server ('npm start', i.e. 'node index.js'), then how do I run a node command to update MongoDB, when the server hasn't been started yet?
For example, if I run "node updateDB.js", it will error out because there is no server running, and connection to Mongo has yet to be established.
Any insight to how I can setup/test these scheduled node functions (without starting up the server?) would be greatly appreciated.

A: Can require just the necessary startups from index.js in schedule.js. In this instance just the validation and mongodb startups

A: for a run single file and connect with database to perform some task. you can try this way.
mongodb = require('mongodb');
config = module.exports = require("/home/node/myclass/crons/config.json");

var MongoClient = mongodb.MongoClient;
ObjectId = module.exports = mongodb.ObjectID;
var dbConnUrl = 'mongodb://' + config.DB_USERNAME + ':' + config.DB_PASSWORD + '@' + config.DB_HOST + ':' + config.DB_PORT + '/' + config.DB_NAME;
console.log("dbConnUrl >> ", dbConnUrl);
MongoClient.connect(dbConnUrl, { useNewUrlParser: true, useUnifiedTopology: true }, function (err, dclient) {
    if (err) {
        console.log("mongodb connection error >> ", err);
        process.exit();
    } else {
        db = module.exports = dclient.db();
        console.log("---------------------------mongodb connected-----------------------");
        run();
    }
});

async function run() {
    await db.collection("notification_token").find({}).toArray();
    process.exit();
}


text:
Q: Exporting C++ function with std::function argument to Python using Boost.Python I have the following function signature that I am trying to wrap with Boost. Python.
void myfunc(std::string str1, std::string str2,
            std::function<void(std::string)> callback1,
            std::function<void(int, std::string)> callback2);

I tried exporting it in Boost.Python as:
BOOST_PYTHON_MODULE(my_module)
{
    using namespace boost::python;

    class_<MyClass>("MyClass")
        .def("myfunc", &MyClass::myfunc)
    ;
}

And calling it in Python with:
def update(message):
    print(message)

def error(status, message):
    print("Error {}: {}".format(status, message))

strarg1c= r"""path..."""
strarg2 = "test"

import my_module
obj = my_module.MyClass()
obj.myfunc(strarg1, strarg2, update, error)

But I get the following errors:
Boost.Python.ArgumentError: Python argument types in
    MyClass.myfunc(MyClass, str, str, function, function)
did not match C++ signature:
    myfunc(class Myclass {lvalue}, class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >, class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >, class std::function<void __cdecl(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >)>, class std::function<void __cdecl(int,class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >)>)

I've found some similar questions but they generally deal with handling arbitrary functions as return types and not one in a list of arguments to a function. I'm hoping there is something simple I am missing when it comes to Boost.Python and std::function.
It seems Pybind11 has this functionality. Is this functionality missing in Boost.Python or am I missing something?


text:
Q: Problem on adding a counter to a code with 3 foreach loops I am having trouble on adding a counter starting from 1 to the following piece of code, near echo $images;
I would like to count how many times it echoes $images. My purpose i to add the number next to images.
Any help would be great! Please have in mind if there is a way of making the following code better. Thank you!
foreach($items as $item) {
    $descr = $xPath->query('./description', $item);

    foreach ($descr as $d) {

        $temp_dom = new DOMDocument();
        $temp_dom->loadHTML( $d->nodeValue );
        $temp_xpath = new DOMXPath($temp_dom);
        $img = $temp_xpath->query('//div[@class="separator"]//img');

 foreach ($img as $imgs) {
$images=$imgs->getAttribute('src');
echo $images; }

   }

}

A: Initialize a variable, e.g. $count = 0;, and then add 1 on each loop:
 foreach ($img as $imgs) {
$images=$imgs->getAttribute('src');
++$count; // <= here you go
echo $images; }

A: foreach don't maintain its own counter, if you want a counter you can use the for loop instead
for ($i = 0; $i <= count($img).; $i++) {
    $images = $img[i]->getAttribute('src');
    echo $images;
}

Or you can just initialize your own counter in the foreach
foreach($img as $imgs) {
$i = 1;
$images = $imgs->getAttribute('src');
echo $images;
$i++;
}

A: Can't you just add something like
$counter = 0;

before the firsrt foreach, and then somethin like
$counter++;
echo $images;
echo $counter;

just increase counter at same time, you echo $images. Or am I missing something?


text:
Q: Рисование на Canvas фигуры с градиентом Как нарисовать круг с заливкой градиентом и контуром который тоже с градиентом.
У меня есть обычный  Paint с заливкой:
mProgressPaint.setStyle(Style.FILL);
mProgressPaint.setColor(Color.parseColor("#09A513"));

В cети нашел что  можно градиент сделать тако, но он все равно получаеться одного цвета. И это не делает контур.
mProgresGoldPain.setStyle(Style.FILL);
mProgresGoldPain.setShader(new LinearGradient(0, 0, getWidth(), 0, color, color2, Shader.TileMode.MIRROR));

Потом рисую так:
canvas.drawCircle(dX, dY, mRadius, mProgressPaint);

Вобщем вот пример того что я пытаюсь сделать:

A: Можно сделать контур отдельно:
mProgressPaint.setStyle(Style.STROKE);

А затем можно задать им отдельно градиент как описано здесь.
Для класса RadialGradient указываем центр и радиус, и тогда градиент пойдет от центра к краям. А SweepGradient – градиент, который идет по кругу вокруг центра. У этих двух классов, аналогично LinearGradient, есть простой конструктор, где можно указать два цвета, а есть посложнее - с возможностью указания массива цветов и их соотношений.
Подробнее по ссылке.
И документация RadialGradient, SweepGradient.


text:
Q: Google API authentification Server-Side I'm trying to use the Gmail API reading the emails, but I'm running into the problem that I want to do a server-side authentification but with all the examples from google Doc., he always shows me window asking me to add my credentials (Gmail & password).
public static async void CreateService()
    {
        GoogleCredential credential;
        using (var stream = new FileStream(@"key.json", FileMode.Open,
FileAccess.Read))
        {
            credential = GoogleCredential.FromStream(stream)
                .CreateScoped(GmailService.Scope.GmailLabels,
GmailService.Scope.GmailModify, GmailService.Scope.GmailMetadata,
GmailService.Scope.GmailReadonly);
        }
        var service = new GmailService(new BaseClientService.Initializer()
        {
            HttpClientInitializer = credential,
            ApplicationName = "Gmail",
        });
        Console.WriteLine(ListMessages(service, "me", ""));
    }

Then I got this code from the documentation of the google api of how to read the messages from a user.
public static List<Message> ListMessages(GmailService service, String userId, String query)
            {
                List<Message> result = new List<Message>();
                UsersResource.MessagesResource.ListRequest request = service.Users.Messages.List(userId);
                request.Q = query;
                do
                {
                    try
                    {
                        ListMessagesResponse response = request.Execute();
                        result.AddRange(response.Messages);
                        request.PageToken = response.NextPageToken;
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("An error occurred: " + e.Message);
                    }
                } while (!String.IsNullOrEmpty(request.PageToken));

                return result;
            }

But when I run it I get this error: An error occurred:
Google.Apis.Requests.RequestError
Bad Request [400]
Errors [
        Message[Bad Request] Location[ - ] Reason[failedPrecondition] Domain[global]
]

A: Answer:
If you want to use a user as the authentication account, then no. This is not possible and you will always get a login window pop-up.
Other Methods:
You can however create and use a service account to impersonate your user and bypass the need for authenticating on run. They require a little extra set up but you can create them in the Google Developer Admin Console.
Code Example:
After creating your service account and giving it the roles and permissions it needs (see links below), you only need to make small edits to your code to use it instead of your regular account. This is an example in Python, but you can find other examples on the managing keys page:
import os

from google.oauth2 import service_account
import googleapiclient.discovery

def create_key(service_account_email):
    """Creates a key for a service account."""

    credentials = service_account.Credentials.from_service_account_file(
        filename=os.environ['GOOGLE_APPLICATION_CREDENTIALS'],
        scopes=['YOUR SCOPES HERE'])

    # Rememer here that your credentials will need to be downloaded
    # for the service account, YOU CAN NOT USE YOUR ACCOUNT'S CREDENTIALS!
    service = googleapiclient.discovery.build(
        'service', 'version', credentials=credentials)

    key = service.projects().serviceAccounts().keys().create(
        name='projects/-/serviceAccounts/' + service_account_email, body={}
        ).execute()

    print('Created key: ' + key['name'])

References:

*

*Google Developer Admin Console

*Google Cloud - Service Accounts

*Understanding Service Accounts

*Creating and Managing Service Accounts

*Creating and Managing Service Account Keys

*Granting Roles to Service Accounts


text:
Q: Explicit map for Scholz reflection principle The question is about the specific case of reflection theorems (copied straight from Franz Lemmermeyer's "Class Groups of Dihedral Extensions"):

Let $k^+ = \mathbb{Q}(\sqrt{m})$ with $m\in \mathbb{N}$, and put $k^- = \mathbb{Q}(\sqrt{-3m})$; then the 3-ranks $r_3^+$ and $r_3^-$ of $Cl(k^+)$ and $Cl(k^-)$ satisfy the inequalities $r_3^+ \le r_3^- \le r_3^+ + 1$.

The proofs I have seen either use p-adic arguments or galois actions.
Question
Is there an explicit surjective map from $Cl(k^-)[3]$ to $Cl(k^+)[3]$ that might, as the theorem suggests, have kernel of size 3?
At the least, an algorithm for such a map?

A: One way to think the reflection principle, which is similar to what you are proposing in your question, is a relation between the index 3 subgroups of $Cl(k^{+})$, which I'll call $I_{3}(m)$, and the subgroups of $Cl(k^{-})$ order 3 which I'll call $S_{3}(-3m)$. It is not difficult to see that $$|S_{3}(-3m)|=\frac{3^{r_{3}^{-}}-1}{2}$$ and that $$|I_{3}(m)|=\frac{3^{r_{3}^{+}}-1}{2},$$ hence any injective map $$ \Phi_{m}: I_{3}(m) \rightarrow S_{3}(-3m)$$ would yield to $r_{3}^{+}\leq r_{3}^{-}$. It is a result of Hasse that the set $I_{3}(m)$ is in bijection with the isomorphism classes of cubic fields of discriminant $m$ (notice that here I'm assuming that $m$ is fundamental, i.e., $m=disc(k^{+})$) hence what we are looking is for a map $\Phi$ that takes a cubic field $K$ and produces a subgroup of $Cl(k^{-})$ of order $3$. In other words given a cubic field $K$ of discriminant $m$ we need to associate a primitive, binary quadratic form of discriminant $-3m$ with the extra condition that the form has order 3 under Gauss composition. To shorten the exposition I'll assume $(3,m)=1$ however all that I'm saying can be worked out in full generality. One natural way to define $\Phi_{m}$ is as follows: Let $O_{K}^{0}$ be the set of integral elements in $K$ with zero trace. Let $q_{K}(x):=Tr(x^{2})/2$. Then, one can show that $q_{K}(x)$ is a primitive, binary quadratic form of discriminant $-3d$. Moreover, as an element of the class group $q_{K}^{2}$ has order $3$. It is possible to show that the map $\Phi_{m}$ sending $K$ to the group generated by $q_{K}^{2}$ is injective, so the result follows.
All the above results should be appearing at some point soon in ANT, but I can email you a copy of the article if you are curious of the details.
Added: In response to Alex comment I should say that the other inequality can be also derived with the same ideas I explained above. Now, you start with $I_{3}(-3m)$ and you notice that $$|I_{3}(-3m)|=\frac{3^{r_{3}^{-}}-1}{2}$$ Moreover, $S_{3}(-3(-3m))=S_{3}(m)$ hence by using the trace you get a map  $$ \Phi_{-3m}: I_{3}(-3m) \rightarrow S_{3}(m).$$ The diference here is that this map is not injective, but it can be shown that roughly the map is 3-to-1 hence the other inequality. So summarizing Scholz reflection principle is a relation between index 3 subgroups in one class group and subgroups of order 3 in the other, and one way to make this relation explicit is via the trace form.
One place to see where the difference in the behavior $\Phi_{m}$ and $\Phi_{-3m}$ is, as professor Lemmermeyer  already pointed out, Bhargava's first paper on Higher composition laws, more specifically Corollary 15. Another place to look at this is J. W. Hoffman and J. Morales, Arithmetic of binary cubic
forms,  Enseign. Math. (2) 46, 2000, 61-94.

A: Leopoldt's reflection theorem, of which Scholz's result (discovered independently by Reichardt) is a special case, bounds the sizes of certain eigenspaces of the class group
of abelian extensions. I see the main reason for their existence in the fact that abelian
extensions over fields containing the appropriate roots of unity are Kummer extensions.
Anyway what you are looking for is not so much a map between class groups of different fields as a map between eigenspaces of the class group of one single field, which can be pulled down to subfields in some cases.
If you're interested in an explicit map in Scholz's case, you should have a look at Bhargava's
excellent Higher composition laws. I: A new view on Gauss composition, and quadratic generalizations. There he mentions a map defined in terms of binary quadratic forms studied already by Eisenstein, which I think might have something to do with the question
you're asking. I always wanted to study this part in detail, but haven't yet found time to do so.  If you come to understand Eisenstein's result before I do let me know -)


text:
Q: What's the equivalent of jQuery.when() in nodejs? I asked whats the equivalent of jquery when in angular and now I want to do similar thing in node. I need to something like this:
when(fs.readFile('file1'), fs.readFile('file2'))
    .done(function( a1, a2 ) {
       ... // do stuff
    });

How can I achieve this? Thanks.

A: You need node 0.11.13 or higher for this to work or to use a library but that would be Promise.all:
var Promise = require("bluebird"); // Imports the Bluebird promise library in
                                   // new versions of node this is optional

Promise.promisifyAll(fs); // this is required if using Bluebird, you'll have to
                          // do this manually with native promises.
Promise.all([fs.readFileAsync('file1'), fs.readFileAsync('file2')])
.spread(function( a1, a2 ) {
   ... // do stuff
});

As for how to convert a callback API to promises - see this question and answer.


text:
Q: Mixing cleveref, vref and ref: Argument of \@firstoftwo has an extra } I am using varioref and cleveref together. This works pretty well. I had to add a hack though, which modifies the strings used by varioref (in german it should read "ab Seite X" ("starting on page X") instead of "auf Seite X" ("on page X") for chapters, sections, etc.).
The hack for this modification can be found here:
http://texwelt.de/wissen/fragen/7013/vref-in-den-appendix
This also works pretty well. But I noticed that I cannot use the plain old \ref alongside of this shiny new cleveref+varioref+hack-setup. When I use
\vref{} after \ref{}, I trigger the following error:
LaTeX Warning: Reference `Foo' on page 1 undefined on input line 38.

! Argument of \@firstoftwo has an extra }.
<inserted text>
\par
l.39 Second Ref: \vref{Foo}
                         .
?
! Emergency stop.

Here is a minimal example:
\documentclass[a4paper,11pt]{scrreprt}
\usepackage{fontspec}
\usepackage{etoolbox}

\usepackage[ngerman]{varioref}
\usepackage{cleveref}

% This changes the string "auf Seite..." to "ab Seite..." for
% chapter/section/etc.-labels, which are 'far away'.
%
% Thanks for this hack to http://texwelt.de/wissen/fragen/7013/vref-in-den-appendix
% and http://www.schlosser.info/latex-cleveref-varioref-ab-seite/

\makeatletter
\newcommand*\curtlabtype{}
\let\@old@cref@vref\cref@vref
\renewcommand*\cref@vref[2]{%
  \ifcsdef{r@#2}% teste, ob Label `#2' definiert ist
    {\cref@gettype{#2}{\curtlabtype}}% %% FIXME, this line seems to break it! %
    {}%
  \@old@cref@vref{#1}{#2}%
}
\vref@addto\extrasngerman{%
  \renewcommand*\reftextfaraway[1]{%
    (%
    \ifboolexpr
      {
        test {\ifdefstring{\curtlabtype}{chapter}}
      }
      {ab Seite}
      {auf Seite}%
    ~\pageref{#1})}%
}
\makeatother

\begin{document}

First Ref: \ref{Foo}. Without this, it works.
Second Ref: \vref{Foo}.

\chapter{Foo}
\label{Foo}

\end{document}

In the cleveref-Hack, I highlighted the line which seems to have something to do with error with a FIXME. I don't understand this error... I need the plain \ref{} also, because in some context I really only need the number of the chapter/section, not anything fancy, like "Chapter X" (\cref{}) or "Chapter X (on page ...)" (\vref{}). I am using LuaLaTeX beta-0.76.0-2014042815 (from TeX Live 2013/Arch Linux).
Thanks in advance for any hints/pointers.

A: The problem is that there are two kinds of »check if macro is undefined« tests in LaTeX.
As you've noticed the error appears with an undefined label and if \ref is used before \vref. This gives us some clues: the internal code should test if a label is defined or not, right?
\renewcommand*\cref@vref[2]{%
  \ifcsdef{r@#2}% <<<<<<<< test if label is defined
    {\cref@gettype{#2}{\curtlabtype}}%
    {}%
  \@old@cref@vref{#1}{#2}%
}

But obviously it fails after a \ref has been used. How can that be? Well, \ref also tests if a label exists. More precisely the command \@setref (which is called by \ref at some point) does it, also by testing if the macro \r@<label> is defined (or rather if it is not \relax). LaTeX's definition of \ref is
\def\ref#1{\expandafter\@setref\csname r@#1\endcsname\@firstoftwo{#1}}

The problem now is that \csname r@#1\endcsname defines a macro equal to \relax if it does not exist yet. But in the eyes of \ifcsdef a definition \relax is a valid one so it (mistakenly in this case) uses the true branch if \cref@vref is used after \ref has been used regardless if the label exists or not.
So we need a test that checks if a macro is undefined or equal to \relax. Since you're using a KOMA-Script class this is easy: it comes with
\scr@ifundefinedorrelax{<csname>}{<true>}{<false>}
\ifundefinedorrelax{<csname>}{<true>}{<false>}

With this the definition of above becomes
\renewcommand*\cref@vref[2]{%
  \scr@ifundefinedorrelax{r@#2}% <<<<<<<< test if label is defined
    {}%
    {\cref@gettype{#2}{\curtlabtype}}%
  \@old@cref@vref{#1}{#2}%
}

and the error is gone.
Also possible: doing the same kind of test that \@setref does – this does not require a KOMA-Script class or the package scrbase:
\renewcommand*\cref@vref[2]{%
  \expandafter\ifx\csname r@#2\endcsname\relax % <<<<<<<< test if label is defined
  \else
    \cref@gettype{#2}{\curtlabtype}%
  \fi
  \@old@cref@vref{#1}{#2}%
}


text:
Q: Copy Constructor and/or pop method in framework for a stack class C++ So I have a stack that is made up of randomly generated strings and then a pointer to the next item in my .cpp code. I then go through and pop each item off the stack and print them out. I get a seg fault at the end though so I'm guessing I'm trying to pop an item one past the stack where I do not own the memory.
I believe my copy constructor is incorrect - maybe it doesn't set the last value to null in my stack but I can't figure out why it's not setting the value to NULL when I put the line
newPrev->next = NULL;
here's my code (class only)
    #include <string>
    using namespace std;
    class Stack
    {
    protected:
        struct Node
        {
            string item;
            Node* next;
        }; // struct Node

    public:
        // constructor of an empty stack
        Stack ()
        {
            head = NULL;
        }

        // copy constructor
        Stack( const Stack & rhs )
        {
            if (rhs.head == NULL) {// check whether original is empty
                head = NULL;
            }else{
                head = new Node;
                head->item = rhs.head->item;
                Node* newPrev = head;
                // Now, loop through the rest of the stack
                for(Node* cur = rhs.head->next; cur != NULL; cur = cur->next)
                {
                    newPrev->next = new Node;
                    newPrev = newPrev->next;
                    newPrev->item = cur->item;
                } // end for

                newPrev->next = NULL;

            } // end else
        }

        // destructor
        ~Stack ()
        {
            delete head;
        }

        // assignment
        const Stack & operator=( const Stack & rhs )
        {
            return *this;
        }

        // query whether the stack is empty
        bool empty () const
        {
            return false;
        }

        // add an item to the top of the stack
        // this method is complete and correct
        void push (const string & new_item)
        {
            Node* new_node = new Node;
            new_node->item = new_item;
            new_node->next = head;
            head = new_node;
        }

        // remove the item on the top of the stack
        void pop ()
        {
            if (head!=NULL){
                Node *n = head;
                head = head->next;
                delete n;
            }
        }

        // return the item on the top of the stack, without modifying the stack
        string & top () const
        {
            return head->item;
        }

    private:
        Node* head;
    };

A: Your copy constructor is fine. You didn't implement your bool Stack::empty() function. I changed it to this:
// query whether the stack is empty
bool empty () const
{
    return head == NULL;
}

And this ran just fine:
int main()
{
    Stack s;
    s.push("a");
    s.push("b");
    Stack b(s);
    while(!s.empty())
    {
        cout << s.top() << endl;
        s.pop();
    }
    while(!b.empty())
    {
        cout << b.top() << endl;
        b.pop();
    }
    return 0;
}


text:
Q: Issue with Querying Large Table Started having the following errors as the size of my database grow. It's at about 4GB now for this table with millions of rows.
Laravel cant handle large tables?
$count = DB::table('table1')->distinct('data')->count(["data"]);
$count2 = DB::table('table2')->distinct('data')->count(["data"]);

SQLSTATE[HY000]: General error: 2014 Cannot execute queries while other unbuffered queries are active. Consider using PDOStatement::fetchAll(). Alternatively, if your code is only ever going to run against mysql, you may enable query buffering by setting the PDO::MYSQL_ATTR_USE_BUFFERED_QUERY attribute. (SQL: select count(distinct data) as aggregate from data)

A: I think the table is very large and will take some time to finish. You are running another huge query directly after which also needs a long time to fully execute. I think you need to rerun a second query when first finishes.
Please try this:
$count = DB::table('table1')->distinct('data')->count(["data"]);
if($count){
$count2 = DB::table('table2')->distinct('data')->count(["data"]);
}

But this will need a result from first the query.
Try using:
if($count>-1)
or
 if(DB::table('table1')->distinct('data')->count(["data"]) >-1){
    $count2 = DB::table('table2')->distinct('data')->count(["data"]);
}

For the MySQL statement this might be faster:
DB::table('table1')->select(DB::raw("SELECT COUNT (DISTINCT data)"))->count();

And best solution will be using execute as Laravel allow to use it too
Please tell me if you encounter any problems.


text:
Q: Restoring SQL Server 2008 R2 I am running SQL Server 2008 R2 Standard Edition on a Windows Server 2008 R2 Enterprise. I'm using the standard backup and restore for the server portion and the native SQL Backups for the databases.
I want to exempt the Transaction Log and Data File Directories from the Server backup because I am taking SQL Backups and I don't want to waste space backing up the same objects twice.
However, SQL Server cannot start without the Master database (and perhaps others as well). What's the best process/solution for this?

A: Just back up the master and msdb databases too, same way you do the user databases.  You can restore them as well:
http://msdn.microsoft.com/en-us/library/ms190190.aspx


text:
Q: Can we automatically detect discouraged patterns in question titles? Given
Should questions include "tags" in their titles?
I was wondering whether it would be viable to detect patterns like
Foo: Does the quick brown fox jump over the lazy dog?

in a question's title and show a sort of warning

It looks like you are including a tag in your title. The format
[TAG]: Question
and similar are strongly discouraged and you should include tags in the appropriate section below.

I believe this could educate new users, especially those coming from a forum background.
Seriously my eyes hurt every time I see
iOS - How to blablabla
NSString: cannot blablabla
...

I'm aware of Can we prevent titles with an unnecessary tag in them? but it's two years old and it has been dismissed with - in my opinion - questionable reasons. Specifically Jeff stated

[It's] not really a problem so long as they are not happening "too often". It is the ritual and systemic use of tags in this manner that I object to, not the mere presence of it at all.

This was two years ago. Right now I feel like this format is being abused and we are doing nothing for discouraging it.
Also I strongly believe that moving the tags box before the question title (as proposed in Tags: Adding tags before title of the question) would help a lot. Clearly people think about narrowing the topic down before making the question, and I think it's also why we get so many tags in the titles.