text:
Q: Repetitive wrapper functions for logging I am writing a script that needs to use a class from an external library, do some
operations on instances of that class, and then repeat with some more instances.
Something like this:
import some_library

work_queue = get_items()

for item in work_queue:
  some_object = some_library.SomeClass(item)
  operation_1(some_object)
  # ...
  operation_N(some_object)

However, each of the operations in the loop body can raise some different exceptions.
When these happen I need to log them and skip to the next item. If they raise
some unexpected exception I need to log that before crashing.
I could catch all the exceptions in the main loop, but that would obscure what it does.
So I find myself writing a bunch of wrapper functions that all look kind of similar:
def wrapper_op1(some_object):
  try:
    some_object.method_1()
  except (some_library.SomeOtherError, ValueError) as error_message:
    logger.error("Op1 error on {}".format(some_object.friendly_name))
    return False
  except Exception as error_message:
    logger.error("Unknown error during op1 on {} - crashing: {}".format(some_object.friendly_name, error_message))
    raise
  else:
    return True

# Notice there is a different tuple of anticipated exceptions
# and the message formatting is different
def wrapper_opN(some_object):
  try:
    some_function(some_object.some_attr)
  except (RuntimeError, AttributeError) as error_message:
    logger.error("OpN error on {} with {}".format(some_object.friendly_name, some_object.some_attr, error_message))
    return False
  except Exception as error_message:
    logger.error("Unknown error during opN on {} with {} - crashing: {}".(some_object.friendly_name, some_object.some_attr, error_message))
    raise
  else:
    return True

And modifying my main loop to be:
for item in work_queue:
  some_object = some_library.SomeClass(item)
  if not wrapper_op1(some_object):
    continue
  # ...
  if not wrapper_opN(some_object):
    continue

This does the job, but it feels like a lot of copy and paste programming with
the wrappers. What would be great is to write a decorator function that could
do all that try...except...else stuff so I could do:
@ logged_call(known_exception, known_error_message, unknown_error_message)
def wrapper_op1(some_object):
  some_object.method_1()

The wrapper would return True if the operation succeeds, catch the known exceptions
and log with a specified format, and catch any unknown exceptions for logging before re-raising.
However, I can't seem to fathom how to make the error messages work - I can do it with fixed strings:
def logged_call(known_exceptions, s_err, s_fatal):
  def decorate(f):
    @wraps(f)
    def wrapper(*args, **kwargs):
      try:
        f(*args, **kwargs)
      # How to get parameters from args in the message?
      except known_exceptions as error:
        print(s_err.format(error))
        return False
      except Exception as error:
        print(s_fatal.format(error))
        raise
      else:
        return True
    return wrapper
  return decorate

However, my error messages need to get attributes that belong to the decorated function.
Is there some Pythonic way to make this work? Or a different pattern to be using
when dealing with might-fail-in-known-ways functions?

A: The below tryblock function can be used for this purpose, to implement your logged_call concept and reduce the total amount of code, assuming you have enough checks to overcome the decorator implementation.  Folks not used to functional programming in Python may actually find this more difficult to understand than simply writing out the try blocks as you have done.  Simplicity, like so many things, is in the eye of the beholder.
Python 2.7 using no imports.  This uses the exec statement to create a customized try block that works in a functional pattern.
def tryblock(tryf, *catchclauses, **otherclauses):
  u'return a general try-catch-else-finally block as a function'
  elsef = otherclauses.get('elsef', None)
  finallyf = otherclauses.get('finallyf', None)
  namespace = {'tryf': tryf, 'elsef': elsef, 'finallyf': finallyf, 'func': []}
  for pair in enumerate(catchclauses):
    namespace['e%s' % (pair[0],)] = pair[1][0]
    namespace['f%s' % (pair[0],)] = pair[1][1]
  source = []
  add = lambda indent, line: source.append(' ' * indent + line)
  add(0, 'def block(*args, **kwargs):')
  add(1,   "u'generated function executing a try block'")
  add(1,   'try:')
  add(2,     '%stryf(*args, **kwargs)' % ('return ' if otherclauses.get('returnbody', elsef is None) else '',))
  for index in xrange(len(catchclauses)):
    add(1, 'except e%s as ex:' % (index,))
    add(2,   'return f%s(ex, *args, **kwargs)' % (index,))
  if elsef is not None:
    add(1,   'else:')
    add(2,     'return elsef(*args, **kwargs)')
  if finallyf is not None:
    add(1,   'finally:')
    add(2,     '%sfinallyf(*args, **kwargs)' % ('return ' if otherclauses.get('returnfinally', False) else '',))
  add(0, 'func.append(block)')
  exec '\n'.join(source) in namespace
  return namespace['func'][0]

This tryblock function is general enough to go into a common library, as it is not specific to the logic of your checks.  Add to it your logged_call decorator, implemented as (one import here):
import functools
resultof = lambda func: func()  # @ token must be followed by an identifier
@resultof
def logged_call():
  truism = lambda *args, **kwargs: True
  def raisef(ex, *args, **kwargs):
    raise ex
  def impl(exlist, err, fatal):
    return lambda func: \
      functools.wraps(func)(tryblock(func,
          (exlist, lambda ex, *args, **kwargs: err(ex, *args, **kwargs) and False),
          (Exception, lambda ex, *args, **kwargs: fatal(ex, *args, **kwargs) and raisef(ex))),
          elsef=truism)
  return impl  # impl therefore becomes logged_call

Using logged_call as implemented, your two sanity checks look like:
op1check = logged_call((some_library.SomeOtherError, ValueError),
    lambda _, obj: logger.error("Op1 error on {}".format(obj.friendly_name)),
    lambda ex, obj: logger.error("Unknown error during op1 on {} - crashing: {}".format(obj.friendly_name, ex.message)))

opNcheck = logged_call((RuntimeError, AttributeError),
    lambda ex, obj: logger.error("OpN error on {} with {}".format(obj.friendly_name, obj.some_attr, ex.message)),
    lambda ex, obj: logger.error("Unknown error during opN on {} with {} - crashing: {}".format(obj.friendly_name, obj.some_attr, ex.message)))

@op1check
def wrapper_op1(obj):
  return obj.method_1()

@opNcheck
def wrapper_opN(obj):
  return some_function(obj.some_attr)

Neglecting blank lines, this is more compact than your original code by 10 lines, though at the sunk cost of the tryblock and logged_call implementations; whether it is now more readable is a matter of opinion.
You also have the option to define logged_call itself and all distinct decorators derived from it in a separate module, if that's sensible for your code; and therefore to use each derived decorator multiple times.
You may also find more of the logic structure that you can factor into logged_call by tweaking the actual checks.
But in the worst case, where each check has logic that no other does, you may find that it's more readable to just write out each one like you have already.  It really depends.
For completeness, here's a unit test for the tryblock function:
import examplemodule as ex
from unittest import TestCase
class TestTryblock(TestCase):
  def test_tryblock(self):
    def tryf(a, b):
      if a % 2 == 0:
        raise ValueError
      return a + b
    def proc_ve(ex, a, b):
      self.assertIsInstance(ex, ValueError)
      if a % 3 == 0:
        raise ValueError
      return a + b + 10
    def elsef(a, b):
      return a + b + 20
    def finallyf(a, b):
      return a + b + 30
    block = ex.tryblock(tryf, (ValueError, proc_ve))
    self.assertRaises(ValueError, block, 0, 4)
    self.assertRaises(ValueError, block, 6, 4)
    self.assertEqual([5, 16, 7, 18, 9], map(lambda v: block(v, 4), xrange(1, 6)))
    block = ex.tryblock(tryf, (ValueError, proc_ve), elsef=elsef)
    self.assertEqual([25, 16, 27, 18, 29], map(lambda v: block(v, 4), xrange(1, 6)))
    block = ex.tryblock(tryf, (ValueError, proc_ve), elsef=elsef, returnbody=True)
    self.assertEqual([5, 16, 7, 18, 9], map(lambda v: block(v, 4), xrange(1, 6)))
    block = ex.tryblock(tryf, (ValueError, proc_ve), finallyf=finallyf)
    self.assertEqual([5, 16, 7, 18, 9], map(lambda v: block(v, 4), xrange(1, 6)))
    block = ex.tryblock(tryf, (ValueError, proc_ve), finallyf=finallyf, returnfinally=True)
    self.assertEqual([35, 36, 37, 38, 39], map(lambda v: block(v, 4), xrange(1, 6)))


text:
Q: if-else behaviour without braces: How is the answer 7 and not 6? public class inc {
    public static void main (String []args) {
       inc.sixOrSeven();
    }

    public static void sixOrSeven() {
        byte q=5;
        if (q==5)
            q+=1;
        else
            q--;
            q++;
        System.out.println(q);
    }
}

I'm new to computer science and my teacher taught me a few concepts about increments and decrements. When I ran the program, the console showed me the answer is 7. But I began doubting the answer itself. Since q=5 5+1=6 and if q isn't 5 then 5+1-1=5? How can the answer be 7.

A: It would be 6 if you wrote:
    public static void sixOrSeven() {
        byte q=5;
        if (q==5) {
            q+=1;
        }
        else {
            q--;
            q++;
        }
       System.out.println(q);
    }

According to the specification:

and statements, it can be written as:
Statement:
    StatementWithoutTrailingSubstatement
    (...)
StatementWithoutTrailingSubstatement:
    Block
    (...)
(...)

So we end up with:
if (Expression)
    single statement (can be a block)
else
    single statement (can be a block)

A: Check the comments
public static void sixOrSeven() {
    byte q=5; // q is 5
    if (q==5) // q == 5 true
        q+=1; // q = q + 1 which is q = 5 + 1 = 6. That means Now q = 6
    else  // As if was true so this else is ignored
        q--;
    q++; // q++ means q = q + 1 = 6 + 1 = 7; So Now q = 7
    System.out.println(q); // print q which is 7
}

If-else logic if [if or else] doesn't have any { } . Then next immediate single statement will be considered as under that if or else

redpajama_set_name: RedPajamaStackExchange


text:
Q: Java FXML TableColumn not supporting GregorianCalendar The GregorianCalendar is not displayed correctly inside the cells of the tablecolumn. When i use Strings, ints and doubles it works fine.
When i run the application the cells containing dates show this
java.util.GregorianCalendar[time=?,areFieldsSet=false,areAllFieldsSet=false,lenient=true,zone=sun.util.calendar.ZoneInfo[id="Europe/Berlin",offset=3600000,dstSavings=3600000,..
But i want it to be displayed in year-month-day
public class ProjectenController implements Initializable {

  @
  FXML
  private TableView < Project > TVProject;@
  FXML
  private TableColumn < Project, Integer > TCID;@
  FXML
  private TableColumn < Project, String > TCNaam;@
  FXML
  private TableColumn < Project, GregorianCalendar > TCBeginDatum;@
  FXML
  private TableColumn < Project, GregorianCalendar > TCEindDatum;@
  FXML
  private TableColumn < Project, Double > TCAanneemsom;@
  FXML
  private TableColumn < Project, String > TCGefactureerd;@
  FXML
  private TableColumn < Project, String > TCBeschrijving;

  final ObservableList < Project > data = FXCollections.observableArrayList(
    new Project(1, "500", new GregorianCalendar(2015, 1, 23), null, 1000, false, null)
  );

  @
  Override
  public void initialize(URL url, ResourceBundle rb) {
    TCID.setCellValueFactory(new PropertyValueFactory < > ("ProjectNr"));
    TCNaam.setCellValueFactory(new PropertyValueFactory < > ("Naam"));
    TCBeginDatum.setCellValueFactory(new PropertyValueFactory < > ("BDatum"));
    TCEindDatum.setCellValueFactory(new PropertyValueFactory < > ("EDatum"));
    TCAanneemsom.setCellValueFactory(new PropertyValueFactory < > ("Aanneemsom"));
    TCGefactureerd.setCellValueFactory(new PropertyValueFactory < > ("Gefactureerd"));
    TCBeschrijving.setCellValueFactory(new PropertyValueFactory < > ("Beschrijving"));
    TVProject.setItems(data);

  }
}

public class Project {

  private int ProjectNr;
  private String Naam;
  private GregorianCalendar BDatum;
  private GregorianCalendar EDatum;
  double Aanneemsom;
  boolean Gefactureerd;
  String Beschrijving;
  List < Artikel > Artikelen;
  List < Activiteit > Activiteiten;

  public Project(int projectnr, String naam, GregorianCalendar bdatum,
    GregorianCalendar edatum, double aansom, boolean fact, String besc) {
    this.ProjectNr = projectnr;
    this.Naam = naam;
    this.BDatum = bdatum;
    this.EDatum = edatum;
    this.Aanneemsom = aansom;
    this.Gefactureerd = fact;
    this.Beschrijving = besc;
  }

  public int getProjectNr() {
    return this.ProjectNr;
  }

  public String getNaam() {
    return this.Naam;
  }

  public GregorianCalendar getBDatum() {
    return this.BDatum;
  }

  public GregorianCalendar getEDatum() {
    return this.EDatum;
  }

  public double getAanneemsom() {
    return this.Aanneemsom;
  }

  public String getFactureerd() {
    if (this.Gefactureerd == true) {
      return "Ja";
    } else {
      return "Nee";
    }
  }

  public String getBeschrijving() {
    return this.Beschrijving;
  }
}

A: Create a method returning a String with the formatted date.
In your controller:
@FXML
private TableColumn < Project, String> TCBeginDatum;
...
TCBeginDatum.setCellValueFactory(new PropertyValueFactory < > ("formattedBDatum"));

In your bean:
public String getFormattedBDatum() {
  return this.BDatum!=null ? new SimpleDateFormat("yyyy/MM/dd").format(this.BDatum.getTime()) : "";
}


text:
Q: Java POI HSSF Memory Handling Question I have a design question on how to design parsing a large excel file say 1000 x 100 Rows, and about 10 tabs.
Each Tab having a set of records with primary key as the first col. but these could be repeted in different tabs and each does not have the same set of primary keys.

*

*Read a single primary key and form a java object with all the attributes spread across multiple tabs.

*Read tab by tab, and process the record
In terms of how Memory is handled in HSSF Java API.
Thanks in Advance

A: I have an app that does almost exactly your option 1.
You'll need about 500M of ram for the VM for it to run at all well.
And its not super fast, but it works.
I'd therefore go for option 2. ( refactoring to cache tabs parse results has improved performance.
I'd recommend to stop using HSSF objects as soon as you can so they can be garbage collected.


text:
Q: Deleted users persists in database in liferay 6.1.0 CE From Liferay GUI first i deactivate user and then delete deactivate user but  looking in the database i see that the deleted user still there,and i will not able to add again some deleted user from GUI.
I am usig liferay version 6.1.0 CE and mysql 5.1.71.
Please help me how can i delete user permanently from GUI as well as from database.


text:
Q: Append paths to HttpUrlConnection in Java Can we create a connection with base URI using java HttpUrlConnection, and append resource paths to connection later?
Eg:
URL baseUri = new URL("http://localhost:9090");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();

conn.appendUrl("/file-repo/list") // NEED THIS

If yes, Pls provide an example.


text:
Q: How to run the same pandas manipulations on a batch of CSV files I am running the following code on individual CSV files:
import pandas as pd

header_names = ['column1', 'column2', 'column3', 'column4', 'column5', 'column6']

df = pd.read_csv('some.csv', delimiter= "|", skiprows=1, names=header_names)

df['column2'].replace(['bad', 'worse'],['good', 'better'],inplace =True)

df.to_csv('new.csv', index=False)

How can I run this code on a batch of files instead of changing the code for each file name?
Edit: If all of the CSV files I want to modify are in a single folder would that make this easier?

A: Running this logic for multiple files:
import os
import pandas as pd

def my_function(source_file, target_suffix):
    header_names = ['column1', 'column2', 'column3', 'column4', 'column5', 'column6']
    df = pd.read_csv(source_file, delimiter= "|", skiprows=1, names=header_names)
    df['column2'].replace(['bad', 'worse'],['good', 'better'],inplace =True)
    # Generating output file name based on the input file name, and the provided suffix
    target_file = source_file.replace('.csv', '') + '_output_' + str(target_suffix) + '.csv'
    df.to_csv(target_file, index=False)

# Define list of input_file
file_names = []

# Set the directory of your files
directory = os.path.join("c:\\","path")
# Locate the input csv file
for root,dirs,files in os.walk(directory):
    for file in files:
       if file.endswith(".csv"):
           file_names.append(file)

# Looping on the input file names and their indexes using enumerate
for i, source_file in enumerate(file_names):
    # Call the function on the file name, and passing file index as the suffix
    my_function(source_file, i)

A: As answered by gtomer and Aviv Yaniv, I'd like to extend this answer as how are you gonna get the name of the files which are in your target directory.
You can use the following code to get the names of csv files in the directory.
csv_files=[]
import os
directory=os.path.join("Path to the directory")
for root,dirs,files in os.walk(directory):
    for file in files:
        if file.endswith(".csv"):
            print(file)
            csv_files.append(pd.read_csv(file,error_bad_lines=False))

and the you can run your logic inside a for loop iterating over each file.

A: You can loop between you files:
files = ['file1.csv','file2.csv','file3.csv']
agg_df = pd.DataFrame()
for file in files:
    df = pd.read_csv(file, delimiter= "|", skiprows=1, names=header_names)
    df['column2'].replace(['bad', 'worse'],['good', 'better'],inplace =True)
    agg_df = agg_df.append(df)
agg_df.to_csv('new.csv', index=False)

A: import pandas as pd
import dask.dataframe as dd

header_names = ['column1', 'column2', 'column3', 'column4', 'column5', 'column6']

df = dd.read_csv("./directory/*.csv", delimiter= "|", skiprows=1, names=header_names)
df['column2'] = df['column2'].replace(['bad', 'worse'],['good', 'better'])
df.to_csv("./directory/export-*.csv")

There's a lot of ways to change the export name. The * in the read_csv will read all files with a .csv ending. The * on the to_csv will number all the different files when they get exported. No need to use for loops using this method.


text:
Q: Problem evaluation conditional Lambdaexpressions I have a problem evaluation conditional lambdaexpressions, using System.Linq.Expressions.
Here the full example Code:
using System;
using System.Linq.Expressions;
using System.Reflection;

namespace ExpressionTree
{
    class Program<TType>
    {
        public TType Data { get; set; }

        public void RegisterLambda<TProp>(Expression<Func<TType, TProp>> expression)
        {
            if (expression.Body.NodeType == ExpressionType.Conditional)
            {
                ConditionalExpression condExp = (ConditionalExpression)expression.Body;
                var condTest = condExp.Test;
                var paramExpression = Expression.Parameter(typeof(TType), "x");
                var lambda = Expression.Lambda(condTest, paramExpression);
                var deleg = lambda.Compile();   // this will raise an InvalidOperationException: variable 'x' of type 'ExpressionTree.DataObject'
                                                // referenced from scope '', but it is not defined
                var testResult = deleg.DynamicInvoke(Data);
            }
            if (expression.Body.NodeType == ExpressionType.MemberAccess)
            {
                var pi = expression.GetPropertyInfo();
                Console.WriteLine(pi.GetValue(Data));
            }
            if (expression.Body.NodeType == ExpressionType.Constant)
            {
                ConstantExpression ce = (ConstantExpression)expression.Body;
                Console.WriteLine(ce.Value);
            }
        }
    }

    class Start
    {
        static void Main(string[] args)
        {
            Program<DataObject> P = new Program<DataObject>();
            P.Data = new DataObject();
            P.Data.DisplayName = "1234567890";
            P.RegisterLambda(x => x.DisplayName);
            P.RegisterLambda(x => x.DisplayName.Length <= 3 ? "Foobar" : x.DisplayName);
            P.RegisterLambda<string>(something => "abc");
        }
    }
    class DataObject
    {
        public string DisplayName { get; set; }
    }

    static class Extensions
    {
        public static PropertyInfo GetPropertyInfo(this LambdaExpression expression)
        {
            if (expression.Body is UnaryExpression unaryExp)
            {
                if (unaryExp.Operand is MemberExpression memberExp)
                {
                    return (PropertyInfo)memberExp.Member;
                }
            }
            else if (expression.Body is MemberExpression memberExp)
            {
                return (PropertyInfo)memberExp.Member;
            }
            throw new Exception();
        }
    }
}

While calling the 2nd RegisterLambda, which is a ternery conditional lambda. The execution fails on the Compile()-line. Does anyone have a clue to solve that problem? I have tried many combinations using ParameterExpression
Thanks in advance!


text:
Q: Changing the Name of an Excel ActiveX ListBox I have a set of ActiveX controls and subs that fit together like this:

*

*User types into an ActiveX TextBox,

*TextBox_Click triggers execution of 3 subs.

*The first sub updates the value of a named range on a sheet; based on that updated value a table is created in excel using an offset function

*The second sub copies the table range updated in 3 and paste.values into a range on the sheet (to eliminate formulas)

Here's where it is breaking down.

*When I set the sheet up I create one ListBox (ListBox1).  The third of the three subs mentioned in #2 above tests to see if ActiveX 'ListBox1' exists in the sheet.  If not, the intention is the code will determine what the ListBox is called (LB1 or LB2 or LB2 etc), changes the name to 'ListBox1', and pastes the table from #4 above into ListBox1.  Then a ListBox1_Click command could trigger a unique set of code to execute.

Right now I'm just testing switching between the names ListBox1 and ListBox2.
The idea is that as a user types into TextBox1 for example, ListBox1 updates at every keystroke. So type "g" and the list shows 20 names starting with the first "g" in the database sheet. Then type "ge" and the list shows 20 names starting with the first "ge" in the database sheet etc etc.  The user clicks on a name and ListBox1_click does something unique.  If the user was typing in TextBox2 they would see different data in the ListBox (which I would like to rename as ListBox2) and if they click a unique set of code is executed by ListBox2_Click.
The problem in #5 is the I get error 'Object doesn't support this property or method' the FIRST time I try to execute. The second time it is ok. If I do something else on the sheet and come back to it i get the error again.
Here is the code for #5 which is in a Module:
Sub PutListInListBox()

    Dim OBJ As Object

    On Error Resume Next
        Set OBJ = ActiveSheet.OLEObjects("ListBox1")
    On Error GoTo 0

    If OBJ Is Nothing Then
        ActiveSheet.ListBox2.Name = "ListBox1"
    End If

    ActiveSheet.ListBox1.Clear
    ActiveSheet.ListBox1.List = Sheets("Search Criteria Control").Range("G1:G21").Value

End Sub

I have no idea what I'm doing wrong and any help is appreciated.
I hope I'm making this clear.
UPATED CODE
I have a bunch of ActiveX Lables and Text boxes so I used the first form you suggested to search for specific name Cases.  I've been reading about it and can't see what I have wrong here.  After typing in TB5, the LB doesn't update.  I click back to Design Mode and can see that the name is still ListBox2.
Any ideas?
Private Sub TextBox5_Change()

    Call UpdateValues(TextBox5.Value)
    Call CopyTable

    Dim OLEOBJ As OLEObject

    For Each OLEOBJ In ActiveSheet.OLEObjects
        Select Case OLEOBJ.Name
            Case "ListBox1", "ListBox2", "ListBox3"
                OLEOBJ.Name = "ListBox1"
                OLEOBJ.ListFillRange = Sheets("Search Criteria Control").Range("G1:G21").Address(external:=True)
        End Select
        Exit For
    Next

End Sub

A: I'll concentrate on your Code#5.
First, if you are changing the name of the ListBox Object, it is better to iterate the Object Collection it belongs to since you are not sure of it's name. Something like this:
Dim oleobj As OLEObject
Dim sh As Worksheet: Set sh = ActiveSheet

For Each oleobj In sh.OLEObjects
    Select Case oleobj.Name
    Case "LB1", "LB2", "ListBox1", "ListBox2" 'put the possible names here
        oleobj.Name = "ListBox1" 'change it to the name you want
    End Select
    Exit For 'if you have more than 1 ListBox
Next

If you just want to change the name of an existing ListBox, then skip the checking.
For Each oleobj In sh.OLEObjects
    oleobj.Name = "ListBox1"
    Exit For 'if you have more than 1 ListBox
Next

Now, to assign values or list to it, you can directly assign the source Range, using ListFillRange Property after you've change its name.
oleobj.ListFillRange = Sheets("Search Criteria Control") _
    .Range("G1:G21").Address(, , , True) 'add this line within the loop

Take note that you need not clear the previous list. It will automatically update. Since I'm not sure what you want to achieve entirely, I'll stop here. HTH though.


text:
Q: Check if element of object exists in request if a $request object and I need check if some values are on $request
Request {#43 ▼
  #json: null
  #convertedFiles: null
  #userResolver: Closure {#170 ▶}
  #routeResolver: Closure {#172 ▶}
  +attributes: ParameterBag {#45 ▶}
  +request: ParameterBag {#44 ▼
    #parameters: array:18 [▼
      "_token" => "sT4yCby4ieh3rHAK0MBcMIcYkGMDzjs0Jf1co4WS"
      "is_demand" => "1"
      "title" => null
      "main_category" => "C01"
      "secondary_category" => "C0201"
      "main_category_2" => "C01"
      "secondary_category_2" => "C0201"
      "status" => "granted"
      "interest" => "code1"
      "keywords" => null
      "keywords_secondary" => null
      "challenge" => null
      "requirement" => null
      "summary" => null
      "dateStart" => "1970-01-01"
      "dateEnd" => "2017-11-07"
      "trlMin" => null
      "trlMax" => null
    ]
  }

Try
if ( ! property_exists($this->request, 'is_demand')) {
   throw new \Exception('"is_demand" is undefined');
}

But get exception, although is_demand is defined and has value
What is my error or my lack of understanding?

A: $this->request is a ParameterBag. Not only that it doesn't have the is_demand property but you don't even care about its properties but about the values of the parameters it contains.
Use the has() method provided by the ParameterBag class to find out what you need:
if ($this->request->has('is_demand')) {
    $is_demand = $this->request->get('is_demand');
}


text:
Q: Python3 Keylogger for MacOs : Script not working I am trying to run a simple Keylogger using Python3 on MacOs. Below is the script.
import pynput
from pynput.keyboard import Key, Listener

count = 0
keys = []

def on_press(Key):
    global keys, count
    print("hello")
    keys.append(Key)
    count += 1
    print(f"{Key} pressed")

    if count >= 10:
        count = 0
        write_file(keys)
        keys = []

# hello this is a test for the keylogger.

def write_file(keys):
    with open("logger.txt", "a") as f:
        for key in keys:
            f.write(str(key))

def on_release(Key):
    if Key == Key.esc:
        return False

with Listener(on_press= on_press, on_release = on_release) as listener:
    listener.join()

The code displays which key is pressed on the console and also after every some period, it stores the keys pressed in a file. When I run the script using sudo, nothing is happening when I press some keys. I am not being shown which keys are pressed on the console and the file is also empty.
I am not able to understand what is the problem. I am guessing it's something related to MacOs restrictions for giving full access to the keyboard. But I am not sure.
Please someone help me on this.

A: I found the solution in a related question. For security reasons MacOS does not allow keylogging by default.
So you need to enable it manually:

*

*Settings -> Security & Privacy

*Click on the Privacy tab

*Click the + and hold down CMD + SHIFT + . (so that you can see hidden files/folders)

*Navigate to /usr/local/bin or wherever you have Python installed

*Click okay.

cited from this answer


text:
Q: Running `ls` in git repository results in `git status --porcelain --ignore` When connected to our production server over ssh, sometimes when running ls inside a git repository and simultaneously looking at the output of htop I can see a process git status --porcelain --ignore appearing as a child of ls. I can spot this when the server's disk IO is saturated and the execution of ls takes long enough for one to see the short lived git command. Why is the aforementioned git command being run as a child of ls?

A: Your ls command may in fact be an alias to someting more complicated; you can try by running instead /bin/ls or \ls, you should not see the same behavior. The alias command could show you if you have an aliased ls and to what.
Also your shell prompt could be configured to run such a command: it is "common" to put various git information (state of the directory, lastest commit ID, branch name, etc.) inside one's prompt and to do that git status must be run automatically after each command invocation.


text:
Q: floats (figures...) does not respect width of adjustwidth When I use floats in the middle of an environment that uses adjustwidth, the caption takes the whole space instead of simply taking the space allowed by adjust width. The problem is that I want to draw lines in the margin obtained with adjustwidth, and lines overlap with the content:

Is there a way to make sure that my captions will behave correctly (I'm fine with getting rid of adjustwidth if you have a better solution that works with floats)?
MWE
\documentclass[options]{memoir}

\RequirePackage{tikz}
\usetikzlibrary{calc,tikzmark}
\usepackage{amsmath}
\usepackage{amsthm}
\usepackage{changepage}
\usepackage{lipsum}
\usepackage{thmtools} %% Improves existing theorem packages (like amsthm) and provides declaretheorem
\theoremstyle{plain} % Style, see http://www.ams.org/arc/tex/amscls/amsthdoc.pdf p. 8 for recommanded styles
\declaretheorem[name=Theorem,numberwithin=section]{theorem}

\begin{document}
\lipsum[1][1-3]

\begin{adjustwidth}{2cm}{0cm}
  \advance\textwidth-2cm% Hum... Is it safe to do that?
  \advance\linewidth-2cm
  \lipsum[2][1-3]

  \noindent\rule{\textwidth}{1mm}
  \begin{figure}[h]
    \centering
    \noindent\rule{\textwidth}{2mm}\\
    See I don't care about adjustwidth
    \caption{\lipsum[3][1-3]}
    \label{fig:fds}
  \end{figure}
  \lipsum[2][1-3]
\end{adjustwidth}

\end{document}

For the captions, I found a funny trick: \captionsetup. I'm not sure if it's the best solution... but does the job. But unfortunately, it does not apply to all floats. For instance, it does not apply to floats defined with the float environment.
If you have a better solution (that may work for more kinds of floats), please let me know. Also, if you know how to center the image, I'd be interested.

\documentclass[options]{memoir}

\RequirePackage{tikz}
\usetikzlibrary{calc,tikzmark}
\usepackage{amsmath}
\usepackage{amsthm}
\usepackage{changepage}
\usepackage{lipsum}
\usepackage{thmtools} %% Improves existing theorem packages (like amsthm) and provides declaretheorem
\theoremstyle{plain} % Style, see http://www.ams.org/arc/tex/amscls/amsthdoc.pdf p. 8 for recommanded styles
\declaretheorem[name=Theorem,numberwithin=section]{theorem}
\usepackage{caption}
%% Hyperref should be loaded before cryptocode! Otherwise, errors with labels of lines for example.
%%% Cryptocode
\usepackage [
  lambda,
  advantage,
  operators,
  sets,
  adversary,
  landau,
  probability,
  notions,
  logic,
  ff,
  mm,
  primitives,
  events,
  complexity,
  asymptotics,
  keys
  ] {cryptocode}
\usepackage{float}
\floatstyle{ruled} % Defines the "rule" style for next environments defined using newfloat.
\newfloat{protocol}{htb!}{protocol}
\floatname{protocol}{Protocol}

\begin{document}
\lipsum[1][1-3]

\begin{adjustwidth}{2cm}{0cm}
  \advance\textwidth-2cm% Hum... Is it safe to do that?
  \advance\linewidth-2cm%
  \captionsetup{width=\linewidth} % The width seems actually smaller than linewidth, but it does the trick.
  \lipsum[2][1-3]

  \noindent\rule{\textwidth}{1mm}
  \begin{figure}[h]
    \centering
    \noindent\rule{\textwidth}{2mm}\\
    See I don't care about adjustwidth
    \caption{\lipsum[3][1-3]}
    \label{fig:fds}
  \end{figure}
  \lipsum[2][1-3]
  \begin{protocol}
    \caption{My caption}
    \lipsum[1][1]
  \end{protocol}

  \lipsum[1][1-2]
\end{adjustwidth}

\end{document}

EDIT
by adding \advance\columnwidth-2cm I managed also to change the size of floats inserted using the float library... Unfortunately it is still not perfect because the floats are flushed left, so the overlap is the same, and pictures are even less centered now ^^

EDIT
I tried to apply the advice of John to insert adjustwidth inside the floats. I semi-works for picture (the caption is still not behaving properly, either it is too big, or if I use \captionsetup{width=1\linewidth} it is too small), but fails with other floats:

\documentclass[options]{memoir}

\RequirePackage{tikz}
\usetikzlibrary{calc,tikzmark}
\usepackage{amsmath}
\usepackage{amsthm}
\usepackage{changepage}
\usepackage{lipsum}
\usepackage{thmtools} %% Improves existing theorem packages (like amsthm) and provides declaretheorem
\theoremstyle{plain} % Style, see http://www.ams.org/arc/tex/amscls/amsthdoc.pdf p. 8 for recommanded styles
\declaretheorem[name=Theorem,numberwithin=section]{theorem}
\usepackage{caption}
%% Hyperref should be loaded before cryptocode! Otherwise, errors with labels of lines for example.
%%% Cryptocode
\usepackage [
  lambda,
  advantage,
  operators,
  sets,
  adversary,
  landau,
  probability,
  notions,
  logic,
  ff,
  mm,
  primitives,
  events,
  complexity,
  asymptotics,
  keys
  ] {cryptocode}
\usepackage{float}
\floatstyle{ruled} % Defines the "rule" style for next environments defined using newfloat.
\newfloat{protocol}{htb!}{protocol}
\floatname{protocol}{Protocol}

\begin{document}
\lipsum[1][1-3]

\begin{adjustwidth}{2cm}{0cm}
  \advance\textwidth-2cm% Hum... Is it safe to do that?
  \advance\linewidth-2cm%
  \captionsetup{width=1\linewidth} % The width seems actually smaller than linewidth, but it does the trick.
  \lipsum[2][1-3]

  \noindent\rule{\textwidth}{1mm}
  \begin{figure}[h]
    \begin{adjustwidth}{2cm}{0cm}
      %\advance\textwidth-2cm% Hum... Is it safe to do that?
      %\advance\linewidth-2cm%
      %\captionsetup{width=\linewidth} % The width seems actually smaller than linewidth, but it does the trick.
      \centering
      \noindent\rule{\textwidth}{2mm}\\
      See I don't care about adjustwidth
      \caption{\lipsum[3][1-3]}
      \label{fig:fds}
    \end{adjustwidth}
  \end{figure}
  \lipsum[2][1-3]
  \begin{protocol}
    \begin{adjustwidth}{2cm}{0cm}
      \caption{My caption}
      \lipsum[1][1]
    \end{adjustwidth}
  \end{protocol}

  \lipsum[1][1-2]
\end{adjustwidth}

\end{document}

UPDATE
Thanks to comments of David on minipages I tried to create one inside figures... and indeed it basically solves the problem for pictures (now I need to automatically applies that), and it can actually float on new pages if required. I still need to find a way to patch all figure environments into my adjustwidth, but it's getting there. However, I'm not sure how to apply it to other kinds of floats, if I do that into a ruled environment the patch is not applied to the caption.

\documentclass[options]{memoir}

\RequirePackage{tikz}
\usetikzlibrary{calc,tikzmark}
\usepackage{amsmath}
\usepackage{amsthm}
\usepackage{graphicx}
\usepackage{changepage}
\usepackage{lipsum}
\usepackage{thmtools} %% Improves existing theorem packages (like amsthm) and provides declaretheorem
\theoremstyle{plain} % Style, see http://www.ams.org/arc/tex/amscls/amsthdoc.pdf p. 8 for recommanded styles
\declaretheorem[name=Theorem,numberwithin=section]{theorem}
\usepackage{caption}
\usepackage{float}
\floatstyle{ruled} % Defines the "rule" style for next environments defined using newfloat.
\newfloat{protocol}{htb!}{protocol}
\floatname{protocol}{Protocol}

\begin{document}
\lipsum[1][1-3]

\begin{adjustwidth}{2cm}{0cm}
  \advance\textwidth-2cm% Hum... Is it safe to do that?
  %\advance\columnwidth-2cm% Hum... it's breaking images
  %\captionsetup{width=1\linewidth} % The width seems actually smaller than linewidth, but it does the trick.
  \lipsum[2][1-3]. Checking that linewidth and textwidth are appropriately configured

  \noindent\rule{\linewidth}{1mm}

  \noindent\rule{\textwidth}{1mm}

  \lipsum[2][1-3]

  \begin{figure}[htbp]
    \begin{adjustwidth}{2cm}{0cm}
      \noindent\begin{minipage}{1.0\linewidth}
        \includegraphics[width=\textwidth]{example-image-a}
        \caption{I am a true float, with the appropriate margin!! Now I need to patch all figure environments automatically.}
      \end{minipage}
    \end{adjustwidth}
  \end{figure}

  Unfortunately, floats created with the float package are still not patched.
  \begin{protocol}
    \begin{adjustwidth}{2cm}{0cm}
      \noindent\begin{minipage}{1.0\linewidth}
      \caption{Non patched float}
      The adjustwidth is applied to the content of the float but not the the surounding. I need to find a way to apply this patch directly around the float.
      \end{minipage}
    \end{adjustwidth}
  \end{protocol}

  \lipsum[1][1-2]
\end{adjustwidth}

\end{document}


text:
Q: How can I find out which object has a file open in Java? I need to find out which object in my Java app has a file open. This is for debugging, so tools or utilities are welcome.
If finding which object is too specific, which class would also be very helpful.

A: That could be tricky. You could start by using a profiler, like VisualVM (free) or YourKit (not free) to inspect java.io.File objects in memory. If you can find one with the path you're interested in, that might point you in the right direction. The problem is that a File object doesn't necessarily have to exist for an app to still have the file open.
Your next step might be to set breakpoints in both FileInputStream and FileOutputStream (unless you know whether the file is being read or written to), attach a debugger, and watch for your file to be opened by one of those. But of course, there are other ways of opening files as well. You might also need to stake out things like Class.getResourceAsStream() and URL.openConnection(), for example.
Your last resort might be to try out an omniscient debugger, like ODB or TOD. I only have limited experience with them, but they claim to "know everything". You'll just have to figure out how to ask the right question.

A: The following is Windows and IntelliJ specific, though it is likely similar for other operating systems and IDEs.
Additionally it relies on JDK internals, the following has been written for JDK 11.

*

*Find out the handle of the file. For this you can use the Windows Sysinternals Handle tool (see also this Server Fault question):
.\handle64.exe -p java

*In the output search for the relevant file, e.g.:
D7C: File          C:\Users\Someone\myfile.txt

(Note: Most terminals provide a search function, for cmd.exe it is Ctrl + F; for Windows Terminal it is Ctrl + ⇧ + F.)
The value before the colon is important (in this example D7C), note it down.

*In IntelliJ pause execution with the debugger.

*Open the Memory tab

*Search for java.io.FileDescriptor

*Right-click the result and select "Show Instances"

*As condition enter handle == 0xhandle, with handle being the value you noted down in step 2 (in this example handle == 0xD7C).
(Note: Under Unix you might have to compare fd == instead.)
➔ You should see a single result

*Right-click the result and select "Show Referring Objects..."

*On the results you can then continue selecting "Show Referring Objects..." until you found the relevant result (the reference in FileCleanable can most likely be ignored)

This won't always answer which caller forgot to close the file, but it might give a hint. You can then for example set further breakpoints in the relevant classes to find out who opened the file.

A: Use AspectJ and intercept calls to various flavors of opening file streams.  Use an around aspect.  Note this can only tell you which object opens the stream, but obviously the object can pass around references to the stream, so ...


text:
Q: WiFi No Longer Works after Installing Xubuntu 16.04 on a Microsoft Surface Pro 1st Gen This is quite exciting, my first post on ask Ubuntu.
Initially, the Wifi was working and then an update was pushed(I apologize, I don't remember the update that affected it) and for some reason, the Wifi only worked every now and then or seemed like the signal was very weak. I did my best to try and solve the issue by searching several hundred resources for the right answer and I got as far as trying to setup wpa_gui and the proper source to run it.
So, unfortunately I now do not receive any indication that networks are being picked up by the wireless adapter or anything. I also attempted to do a fresh install of Xubuntu to try and fix the issue but I also cannot get to my BIOS to set up booting from the MicroSd like I had installed it with.
I apologize if this is a noobish question but I really do need some help. If there are any pros out there that could walk through this lend me a hand I'd greatly appreciate it.
In case it is needed the PC is the Microsoft Surface Pro Gen 1 128GB.
Thanks in advance and I'll be watching out for a reply.

A: Connect device to an ethernet
     sudo apt-get install git
git clone https://github.com/kvalo/ath10k-firmware.git
sudo cp -r ath10k-firmware/QCA9377 /lib/firmware/ath10k/
sudo cp /lib/firmware/ath10k/QCA9377/hw1.0/firmware-5.bin_WLAN.TF.1.0-00267-1 /lib/firmware/ath10k/QCA9377/hw1.0/firmware-5.bin

Reboot
You do not need Windows drivers and ndiswrapper
This has been recently fixed upstream, follow the instructions to install the backported modules and needed firmware
sudo apt-get install build-essential linux-headers-$(uname -r) git
echo "options ath10k_core skip_otp=y" | sudo tee /etc/modprobe.d/ath10k_core.conf
wget https://www.kernel.org/pub/linux/kernel/projects/backports/stable/v4.4.2/backports-4.4.2-1.tar.gz
tar -zxvf backports-4.4.2-1.tar.gz
cd backport-4.4.2-1
make defconfig-wifi
make
sudo make install
git clone https://github.com/kvalo/ath10k-firmware.git
sudo cp -r ath10k-firmware/QCA9377 /lib/firmware/ath10k/
sudo cp /lib/firmware/ath10k/QCA9377/hw1.0/firmware-5.bin_WLAN.TF.1.0-00267-1 /lib/firmware/ath10k/QCA9377/hw1.0/firmware-5.bin

And it should work after a reboot
It will fail when a new kernel is installed through updates until the kernel is patched to support the wifi. When that happens you will need to
cd backports-4.4.2-1
make clean
make defconfig-wifi
make
sudo make install

And reboot
Source: Qualcomm Atheros Device [168c:0042] (rev 30) Wi-Fi driver installation


text:
Q: how to call function inside reactjs render method properly? I want to fetch data from server & show it inside tables. When I directly put code inside the render it works. But, When I encapsulate inside the addElementsToDisplay function & call that function inside render method it doesn't work. Actually, the function gets called, but response is not rendered in table format. Below is my code:
import React, { Component } from "react";
import ReactDOM from "react-dom";
import { Button } from 'semantic-ui-react';
import ResponseRenderer from './responseRenderer';
import "./App.css";

const responseDataContext = React.createContext({});

class App extends Component {
    constructor(props) {
    super(props);
    this.getPastJobs = this.getPastJobs.bind(this);
    this.addElementsToDisplay = this.addElementsToDisplay.bind(this);
    this.state = { pastJobs: [] }
  }

  render() {
    return (
      <div className="App">
        <Button onClick={this.getPastJobs}>Get Past Jobs</Button>
        <h1> Hello, World! </h1>
        {this.addElementsToDisplay()}
      </div>
    );
  }

  addElementsToDisplay() {
    console.log("state: ", JSON.stringify(this.state));
    this.state.pastJobs.map((value, index) => {
      return <ResponseRenderer key={Math.random()} data={value} />
    });
  }

  getPastJobs() {
    fetch('http://localhost:9090/getPastJobs', {
     method: 'POST',
      body: JSON.stringify({})
    })
      .then((response) => {
        if (response.status !== 200) {
          return;
        }
        response.json().then((jobs) => {
          console.log(jobs);
          this.setState({ pastJobs: jobs.data })
        });
      })
      .catch((err) => {
        console.log(err.message, err.stack);
      });
  }
}

export default App;

A: You are not returning the response and hence it is not rendered, just return the mapped response and it will work fine
addElementsToDisplay() {
    console.log("state: ", JSON.stringify(this.state));
    return this.state.pastJobs.map((value, index) => {
      return <ResponseRenderer key={Math.random()} data={value} />
    });
  }


text:
Q: Block a registry key to prevent rewriting or deleting accidentally or intentionally using the command line I see the post in superuser and I have a similar case, but with a small difference.
I created a reg key.
"HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\wscript.exe"

And the content target: /windows/system32/wscript.exe
And I need to block this key permanently (or any other key that I want to create), to prevent accidental or intentional deletion or modification of any malware
Question:
What command line can help me to do this? (cmd or powershell or both)

A: I need to block this key to prevent deletion or modification by malware.
HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\wscript.exe

What command line can help me to do this?

As per the answers in the link in your question, the easiest way to do this is to remove the Edit permissions from SYSTEM and the Administrators groups and the key should then effectively be read only.
You can do this from the command line with regini by following the procedure below.

Warning:

*

*I would be very tempted to back up your whole system before making such changes (you may feel comfortable just backing up the registry - see below).

*The instructions below contain steps that tell you how to modify the registry. However, serious problems might occur if you modify the registry incorrectly.

*For added protection, back up the registry before you modify it. Then, you can restore the registry if a problem occurs.

*For more information see How to back up and restore the registry in Windows

*

*Create a file (for example block.txt) with the following contents:
 HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\wscript.exe [2 19]

*Execute the block.txt script using the following command, run from an elevated (Administrator) cmd shell:
 regini block.txt

Notes:

*

*The regini command must be run from an elevated (Administrator) cmd shell, otherwise it will fail (an no error will be displayed).

*The permission entry is set to [2 19] which is Administrators Read Access and SYSTEM Read Access.

*You need to think carefully whether other user groups also require read access.
Using a permission entry of [2 8 19] will in addition also allow standard users (and administrator accounts with filtered user token) read access for the key.

*You may need to change the permissions of the parent key to prevent sub-keys being deleted (I haven't verified this).

Further Reading

*

*An A-Z Index of the Windows CMD command line - An excellent reference for all things Windows cmd line related.

*regini - Change Registry Permissions.

*How to: Use a Script to Change Registry Permissions from the Command Line


text:
Q: asp.net page not displaying correctly I started learning asp.net (I think the webpages not webforms, razor thingy? :) )
Ok I'm a complete noob, but anyway, I've been looking online and I've seen this question asked multiple times but none of the answers are helping me. I'm following a tutorial and I'm trying to do what its saying but when I run the code.cshtml it just displays the code in a webpage... I know there's gotta be some setting I have to fix or something but I don't know where that is.
my question is, how do I get a web browser to display an x.cshtml file? (I'm using microsoft visual web developer, but I also tried it using notepad and uploading the file to my website, still no good)
I forgot to add, using visual web developer gives me the following errors and wont run:
Error   1   Keyword, identifier, or string expected after verbatim specifier: @
Error   2   A namespace cannot directly contain members such as fields or methods
Error   3   Identifier expected line 8
heres the code
@
{
    var total = 0;
    var totalMessage = "";
    if(IsPost) {

        // Retrieve the numbers that the user entered.
        var num1 = Request["text1"];
        var num2 = Request["text2"];

        // Convert the entered strings into integers numbers and add.
        total = num1.AsInt() + num2.AsInt();
        totalMessage = "Total = " + total;
    }
}

<!DOCTYPE html>

    <title>Add Numbers</title>
    <meta charset="utf-8" />

Enter two whole numbers and then click Add.

  <form action="" method="post">

First Number:
      <input type="text" name="text1" />

Second Number:
      <input type="text" name="text2" />

<input type="submit" value="Add" />

  </form>

@totalMessage

A: I think you are dealing with WebPages, Not MVC. The simplest way to develope webpages is to have WebMatrix.
Check out this tutorial to get started with WebMatrix
When it comes to your code, I only see one mistake i.e, @{ they should some side by side. Other than that everything is working good.
To run your cshtml in browser, please refer to the link I shared at top, that is clearly showing how to run the page in browser.

A: I think your immediate problem is that you cannot have a linebreak after the '@' character in razor.  Try @{ then linebreak...


text:
Q: Access query - does one field contain the value of another field I'm trying to use a query to narrow the table down to only the rows in which the field [full name] contains the value in the field [first name].
For instance, if a row has "Blake Johnson" in [full name] and "John" in [first name] - this row will be included.
But if [full name] has "Garry Sways" and [first name] has "Swan" - this row will NOT be included.
I tried to use:
Like "*[first name]*"

In the criteria for [full name].
But it didn't work quite well.
Is there a "Contains" funciton for this case?
Thanks in advance.

A: Just do this
SELECT * From yourTable WHERE instr(fullname, firstname) > 0

A: I am not sure what kind of query language you are using but you can use regular expressions to make a more granular version of "like"
For example, in MySql you can do:
SELECT * FROM 'foo' WHERE 'bar' REGEXP "^\$"

or in your case:
SELECT * FROM table WHERE fullname REGEXP (".*" + firstname + ".*");


text:
Q: Como ejecuto dos archivos de C# en un mismo proyecto estoy aprendiendo a usar C# y quiero hacer un juego de una trivia, me gustaria tener distintos archivos como por ejemplo un archivo con los datos del jugador, otro archivo con las preguntas y otro archivo donde guarde las respuestas, y luego ejecutar todos juntos, pero no se como hacerlo.
Por el momento solo tengo 2 archivos, en los cuales solo hago una impresion de caracteres por consola utilizando
Console.WriteLine("Hello World in Question file!");

pero me gustaria que se ejecutaran distintos archivos en un orden estilo cascada.
Este es es el archivo Program.cs

Este es el archivo Question.cs

A: El problema no es que tengas muchos archivos sino que en una aplicacion de consola solamente puedes tener un punto de entrada, es decir, un método static void Main. En ése caso tienes dos por lo cuál no compila.
Para lograr lo que deseas, podrías crear varias clases, una en cada archivo (aunque no es necesario pero sí una excelente práctica) y utilizarlas dentro del método Main.
Ejemplo:
// Archivo PlayerData.cs

using System;
namespace proyectoa
{
   public class PlayerData
   {
      public string Name { get; set; }
      public void Run()
      {
         Console.WriteLine("Cual es tu nombre?");
         Name = Console.Readline();
      }
   }
}

// Archivo Questions.cs

using System;
namespace proyectoa
{
   public class Questions
   {
      public string Answer { get; set; }
      public void Run()
      {
         Console.WriteLine("Cuanto es 2+2?");
         Answer = Console.Readline();
      }
   }
}

Así, dentro de tu método Main puedes hacer uso de ellas:
// Archivo Program.cs

namespace proyectoa
{
   class Program
   {
      static void Main(string[] args)
      {
         PlayerData data = new PlayerData();
         data.Run();

         Questions ques = new Questions();
         ques.Run();
      }
   }
}

Si requires utilizar las propiedades de un objeto en otro hay varias maneras de hacerlo. Una de ellas es guardar una referencia de un objeto como un atributo. Por ejemplo, si quisieramos usar el nombre del jugador dentro de Questions:
// Archivo Questions.cs

using System;
namespace proyectoa
{
   public class Questions
   {
      private PlayerData _playerData;
      public string Answer { get; set; }

      public Questions(PlayerData playerData)
      {
         _playerData = playerData;
      }

      public void Run()
      {
         // Puedes utilizar el nombre del jugador
         Console.WriteLine($"Cuanto es 2+2 {_playerData.Name}?");
         Answer = Console.Readline();
      }
   }
}

Y dentro de Program.cs:
// Archivo Program.cs

namespace proyectoa
{
   class Program
   {
      static void Main(string[] args)
      {
         PlayerData data = new PlayerData();
         data.Run();

         Questions ques = new Questions(data);
         ques.Run();
      }
   }
}

Te recomiendo estudies los conceptos de clases, objetos, encapsulación para que puedas comprenderlo mejor y llegar a mejores soluciones.


text:
Q: Systematic integer approximations of $\ \frac n{\log(n)} $ MO-post
            Why Is $\frac{163}{\operatorname{ln}(163)}$ a Near-Integer?
presents the topic in a somewhat chaotic manner. However, this topic should admit a regular diophantine analysis of the integer approximations of $\ \frac n{log(n)},\ $
where $\ 1<n\in\mathbb N.$ Let's start:
Theorem 0
$$ \forall_{\epsilon>0}\,\forall_{M\in\mathbb N}\,
     \exists_{n>M;\, n\in\mathbb N}\,\exists {s\in\mathbb N}
       \quad \left|\frac n{\log(n)} - s\right|\ <\ \epsilon $$
Actually, it's already a bit better:
Theorem 1
$$ \forall_{M\in\mathbb N}\,\exists_{n>M;\, n\in\mathbb N}\,
     \exists {s\in\mathbb N}\quad
        \left|\frac n{\log(n)} - s\right|\ <\ \frac 1{\log(n+1)} $$
Now, the problem is adding Thm.2, Thm.3, ... One would like to get (significantly) smaller error values in place of the above
$\ \frac1{log(n+1)}\ $.
Another direction -- given $\ M\ $ one could
try to minimize $\ n-M\ $ in the above two theorems or their sharper versions   (this second type of results have their value independent of how sharp are the results of the first type).
Thus, the second type of a question would be:
Problem Compute (or estimate) the minimal jump $\ J_k(M)\ $ from $\ M\ $ to $\ n\ $ (i.e. $\ M-n)\ $ as
described above, where parameter $\ k\ $ refers to the theorems above, i.e. to Theorem k, where $\ k=0\ $ or $\ 1\ $ or whatever the future theorem would be.


text:
Q: Meteor JS Shared Methods and Objects My Problem
While using Meteor JS I ran into something that I wasn't quite sure how to fix because everything seems to be loading in the corrector order. It still isn't acting in the correct way it is saying that the functions are not defined.
I have viewed other questions, most of which refer to the meteor methods section.  I'm a little confused as to why I would need to wrap that in a Method object in order for all of them to be used.
My question is how would I get multiple functions and "faux" classes to be used as shared javascript files without using the meteor methods call and putting them in as sub objects.
Sample Class I'm trying use as shared js.
function CustomerProjects(){
  // declare variables
  this.name = null;
  this.scope = null;
  this.time = null;
  this.completed = false; // set every project to default false
  this.description = null;

  // Get the time array
  this.billableHours  = function(){
    if(this.completed){
      var totalTime = 0; // int
      var time = this.time;
      // calculate time
      for(var i = 0; i < time.length; i++){
          totalTime = totalTime + time[i];
      }
      return totalTime;
    } else {
      return "Not Completed";
    }
  };
}

My File Structure

A: Your definition is file-scoped, change it to global scope:
function CustomerProjects(){  // file scoped
..

CustomerProjects = function (){  // global scoped
..


text:
Q: Chartist.js: How to make chart axis not start at 0 but 10 off min value and 10 above max value? Is there a way to make the x axis on a chartist line graph to not start at 0 but 10 under the min and 10 above max value, currently no matter what the minimum number it always starts at 0?

A: Normally Chartist.js already does what you want. However, with options high and low you should be able to setup the borders of the diagram yourself, though this requires you to calculate those values for yourself:
var chart = new Chartist.Line('#chart',
  {
    "labels": ["11/July", "12/July", "12/July", "13/July", "13/July"],
    "series": [[ 2150, 2152, 2147, 2148, 2149 ]],
  }, {
    high: 2160,
    low: 2140
  }
);

See also JSFiddle


text:
Q: Filesystem provider disappearing in Spark? Mysteriously, when I use Spark my custom filesystem provider vanishes.
The full source for my example is available on github so you can follow.
I'm using maven to depend on gcloud-java-nio, which provides a Java FileSystem for Google Cloud Storage, via "gs://" URLs. My Spark project uses maven-shade-plugin to create one big jar with all the source in it.
The big jar correctly includes a META-INF/services/java.nio.file.spi.FileSystemProvider file, containing the correct name for the class (com.google.cloud.storage.contrib.nio.CloudStorageFileSystemProvider). I checked and that class is also correctly included in the jar file.
The program uses FileSystemProvider.installedProviders() to list the filesystem providers it finds. "gs" should be listed (and it is if I run the same function in a non-Spark context), but when running with Spark on Dataproc, that provider's gone.
I'd like to know: How can I use a custom filesystem in my Spark program?
edit: Dennis Huo helpfully contributed that he sees the same problem when running on a Spark cluster, so the problem isn't specific to Dataproc. In fact, it also occurs when just using Scala. Also there are workarounds for the example I'm showing here, but I'd still like to know how to use a custom filesystem with Spark.

A: This doesn't appear to be a Dataproc-specific issue, more of a Scala issue and Spark fundamentally depends on Scala; if I build your jarfile and then load it up with scala independently of Dataproc or Spark, I get:
scala -cp spark-repro-1.0-SNAPSHOT.jar

scala> import java.nio.file.spi.FileSystemProvider
import java.nio.file.spi.FileSystemProvider

scala> import scala.collection.JavaConversions._
import scala.collection.JavaConversions._

scala> FileSystemProvider.installedProviders().toList.foreach(l => println(l.getScheme()))
file
jar

scala> SparkRepro.listFS(1)
res3: String = Worker 1 installed filesystem providers: file jar

So it seems any bundling that's being done isn't properly registering the FileSystem provider, at least for scala. I tested the theory using the ListFilesystems example code  (just removed the package at the top for convenience) on both a Dataproc node as well as a manually created VM with scala and Java 7 installed independently of Dataproc just to double-check.
$ cat ListFilesystems.java
import java.io.IOException;
import java.net.URI;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.spi.FileSystemProvider;

/**
 * ListFilesystems is a super-simple program that lists the available NIO filesystems.
 */
public class ListFilesystems {

  /**
   * See the class documentation.
   */
  public static void main(String[] args) throws IOException {
    listFilesystems();
  }

  private static void listFilesystems() {
    System.out.println("Installed filesystem providers:");
    for (FileSystemProvider p : FileSystemProvider.installedProviders()) {
      System.out.println("  " + p.getScheme());
    }
  }

}

$ javac ListFilesystems.java

Running using java and then scala:
$ java -cp spark-repro-1.0-SNAPSHOT.jar:. ListFilesystems
Installed filesystem providers:
  file
  jar
  gs
$ scala -cp spark-repro-1.0-SNAPSHOT.jar:. ListFilesystems
Installed filesystem providers:
  file
  jar
$

This was the same on both Dataproc and my non-Dataproc VM. It looks like there's still unresolved difficulties getting the FileSystemProviders to load properly in Scala, and there doesn't seem to be an easy way to dynamically register them system-wide at runtime either; the most I could find was this old thread that didn't seem to come to any useful conclusion.
Fortunately though, it looks like at least the CloudStorageFileSystemProvider has no problem making it onto the classpath, so you can at least fall back to explicitly creating an instance of the cloud storage provider to use:
new com.google.cloud.storage.contrib.nio.CloudStorageFileSystemProvider()
    .getFileSystem(new java.net.URI("gs://my-bucket"))

Alternatively, if you're using Spark anyways, you might want to consider just using the Hadoop FileSystem interfaces. It's very similar to Java NIO FileSystems (rather, predated the Java NIO FileSystem stuff), and it's more portable for now. You can easily do things like:
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.conf.Configuration;

...
Path foo = new Path("gs://my-bucket/my-data.txt");
InputStream is = foo.getFileSystem(new Configuration()).open(foo);
...

The benefit of working with the Hadoop FileSystem interfaces is that you're guaranteed the configuration/settings will be clean both in your driver program and in the distributed worker nodes. For example, sometimes you'll need to modify filesystem settings just for a single job running in a Dataproc cluster; then you can plumb through Hadoop properties which are properly scoped for a single job without interfering with other jobs running at the same time.

A: My comment on the linked ticket (https://github.com/scala/bug/issues/10247):
Using scala -toolcp path makes your app jar available to the system class loader.
Or, use the API where you can provide the class loader to find providers which are not "installed."
The scala runner script has a few interacting parts, like -Dscala.usejavacp and -nobootcp, which possibly behave differently on Windows. It's not always obvious which incantation to use.
The misunderstanding here is the assumption that java and scala do the same thing with respect to -cp.
This example shows loading a test provider from a build dir. The "default" provider comes first, hence the strange ordering.
$ skala -toolcp ~/bin
Welcome to Scala 2.12.2 (OpenJDK 64-Bit Server VM 1.8.0_112)

scala> import java.nio.file.spi.FileSystemProvider
import java.nio.file.spi.FileSystemProvider

scala> FileSystemProvider.installedProviders
res0: java.util.List[java.nio.file.spi.FileSystemProvider] = [sun.nio.fs.LinuxFileSystemProvider@12abdfb, com.acme.FlakeyFileSystemProvider@b0e5507, com.acme.FlakeyTPDFileSystemProvider@6bbe50c9, com.sun.nio.zipfs.ZipFileSystemProvider@3c46dcbe]

scala> :quit

Or specifying loader:
$ skala -cp ~/bin
Welcome to Scala 2.12.2 (OpenJDK 64-Bit Server VM 1.8.0_112)

scala> import java.net.URI
import java.net.URI

scala> val uri = URI.create("tpd:///?count=10000")
uri: java.net.URI = tpd:///?count=10000

scala> import collection.JavaConverters._
import collection.JavaConverters._

scala> val em = Map.empty[String, AnyRef].asJava
em: java.util.Map[String,AnyRef] = {}

scala> import java.nio.file.FileSystems
import java.nio.file.FileSystems

scala> FileSystems.
getDefault   getFileSystem   newFileSystem

scala> FileSystems.newFileSystem(uri, em, $intp.classLoader)
res1: java.nio.file.FileSystem = com.acme.FlakeyFileSystemProvider$FlakeyFileSystem@2553dcc0


text:
Q: Where I can find some good UI templates to style my application? I'm developing a GWT application and I'd like to make it look good.
Since I'm not a graphic designer I think I'm going to look for a user interface template and replicate it in GWT using CSS.
For example I like the theme of ExtJS/ExtGWT a lot, but I don't think I can replicate the graphics due to licence restrictions.
Anyone has any idea where to look for some themes I can use without getting in trouble?
P.S.: I don't like built-in GWT themes.

A: You can look at Twitter Bootstrap. There are 2 existing port in GWT :

*

*http://gwtbootstrap.github.io/

*http://nyao.github.io/bootstrap4gwt/


text:
Q: Hiding title rows of empty data charts I have a series of worksheets that show values from Vlookups. I have created a sub to hide all the empty rows within the tables but I am unsure how to hide the title rows if all the rows beneath it are hidden. For the hidden row function I use color and the value in four of the columns to determine whether or not to hide the row using a for loops with the number of rows. The row hide code is as shown.
Public Sub RowHide()
    Application.ScreenUpdating = False

    'variable declarations
    Dim ws As Worksheet
    'column number ref.
    Dim r As Integer
    r = 6
    Dim num As Integer
    'To go through Each WS
    For Each ws In ActiveWorkbook.Worksheets
        Dim i As Integer
        Dim plusVar As Integer
        Let plusVar = 2
        'To go through the rows
        With ws
           For i = 1 To 200
               .Rows(i).AutoFit

            If (.Cells(i, r).Value = 0 Or .Cells(i, r).Text = "") And .Cells(i, r).Interior.ColorIndex < 0 Then
                If (.Cells(i, r - 1).Value = 0 Or .Cells(i, r).Text = "") And .Cells(i, r).Interior.ColorIndex < 0 Then
                    If (.Cells(i, r + 1).Value = 0 Or .Cells(i, r).Text = "") And .Cells(i, r).Interior.ColorIndex < 0 Then
                        If (.Cells(i, r + plusVar).Value = 0 Or .Cells(i, r).Text = "") And .Cells(i, r).Interior.ColorIndex < 0 Then
                            .Rows(i).Hidden = True
                        End If
                    End If
                End If
            End If

            On Error Resume Next
            Next i

        End With

        On Error Resume Next
    'adjusting the target column for each Ws
        r = r - 1
        If r = 4 Then
            r = 3
            plusVar = 3
        End If

    Next ws
    Application.ScreenUpdating = True

End Sub

This code works perfectly. The next step is to have a sub that would check if the rows under each "title" are all hidden (If there is any data present in the table I don't want to hide the title) and if so then hide the row with the title on it.
This is the formatting of the table:
 A          B         [Status]
**TITLE**  BlankCell Not Hidden (what I want to hide)
Category1  BlankCell Row Hidden
Category2  BlankCell Row Hidden
Category3  BlankCell Row Hidden
Category4  BlankCell Row Hidden
Blank Cell BlankCell Row Not hidden

Example of other possibility:
A          B         [Status]
**TITLE**  BlankCell Not Hidden (Don't want to hide it in this scenario)
Category1  BlankCell Row Hidden
Category2  BlankCell Row Hidden
Category3  BlankCell Row Hidden
Category4  Value     Row not hidden
BlankCell  BlankCell Not hidden (was trying to use this to determine range of what to hide)

This is the code I have so far for the title row hide sub:
Public Sub UnusedTitleHide()

    Dim ws As Worksheet
    Dim rw As Range
    Dim LastRow As Long
    Dim i As Integer
    Dim b As Integer

    For Each ws In ActiveWorkbook.Worksheets
        With ws
            LastRow = .Cells.SpecialCells(xlCellTypeLastCell).Row
            Dim firstRow As Long
            Dim endRng As Range
            Dim endRow As Long
            Dim hide As Boolean
            Dim hiC As Integer
            Dim hiT As Integer
            hiC = 0
                For i = 1 To LastRow
                    If (.Cells(i, 1).Value <> 0 And .Cells(i, 1).Text <> "") Then
                        Set endRng = .Cells(i, 1).End(xlUp).Offset(1)
                        Let endRow = endRng.Row
                    End If
                b = i
                hiC = 0
                    Do While b <= endRow
                        hiT = endRow - b
                            If .Rows(b).Hidden = True Then
                                hiC = hiC + 1
                            End If
                        b = b + 1
                    Loop
                    If hiC = hiT Then
                        If i - 1 <> 0 Then
                            If (.Cells(i - 1, 1).Text = "") And hiC = hiT Then
                                .Rows(i).Hidden = True
                            End If
                        End If
                    End If

                    On Error Resume Next

                    Next i
        End With
    Next ws

End Sub

Edit: Clarifying formatting of the worksheet.
    A          B         [Status]
    **TITLE**  BlankCell Not Hidden (what I want to hide as no categories have values.)
    Category1  BlankCell Row Hidden
    Category2  BlankCell Row Hidden
    Category3  BlankCell Row Hidden
    Category4  BlankCell Row Hidden
    Blank Cell BlankCell Row Not hidden
    **TITLE**  BlankCell Row Not hidden (Don't want to hide this row as a category has values)
    Category1  Text/Num  Row Not Hidden
    Category2  BlankCell Row Hidden
    Category3  Text/Num  Row Not Hidden
    Category4  BlankCell Row Hidden

A: Since the rows are hidden only if you get to the last if statement, as true, in your nested ifs, then any else would not hide the row and leave the headers, so:
  If (.Cells(i, r).Value = 0 Or .Cells(i, r).Text = "") And .Cells(i, r).Interior.ColorIndex < 0 Then
            If (.Cells(i, r - 1).Value = 0 Or .Cells(i, r).Text = "") And .Cells(i, r).Interior.ColorIndex < 0 Then
                If (.Cells(i, r + 1).Value = 0 Or .Cells(i, r).Text = "") And .Cells(i, r).Interior.ColorIndex < 0 Then
                    If (.Cells(i, r + plusVar).Value = 0 Or .Cells(i, r).Text = "") And .Cells(i, r).Interior.ColorIndex < 0 Then
                            .Rows(i).Hidden = True
                    Else
                    Titlesvisable = 1
                    End If
                Else
                Titlesvisable = 1
                End If
            Else
            Titlesvisable = 1
            End If
        Else
        Titlesvisable = 1
        End If

A: One method to do this is to check each row in your data table. If any rows are not hidden (i.e., have data), then don't hide the title row. Otherwise, if all the rows are hidden, then hide the title row. Assuming that your title row is the first row:
For Each ws In ActiveWorkbook.Worksheets

    With ws
    LastRow = .Cells.SpecialCells(xlCellTypeLastCell).Row

    For i = LastRow To 2 Step (-1) 'from the end to one below the title row

        If .Rows(i).Hidden = True Then
            'Hidden Row. Keep checking for data
        ElseIf .Rows(i).Hidden = False Then
            'Data is present, no need to hide title
            GoTo NextSht
        End If

    Next i

    'No Data was found, so hide the title row
    .Rows(1).Hidden = True

NextSht:
    End With

Next ws

BETTER EDIT: The below code looks for the title rows. It loops to the next unhidden row, and if it is blank, hides the title row. Let me know if this one works for you:
For Each Cell In rng
    If Cell.Font.Bold = True Then
    Set TitleCell = Cell
        i = 1
        Do While Cell.Offset(i, 0).Rows.EntireRow.Hidden = True
            i = i + 1
        Loop

        If IsEmpty(Cell.Offset(i, 0)) = True Then
            TitleCell.Rows.EntireRow.Hidden = True
        End If

    End If
    'Next Cell
Next Cell

EDIT: The revised code will look through a set of cells, if they are separated by one empty line, and provided that there are no blanks in between. It further assumes that the lines are hidden based on whether or not there is a value in the right adjacent cell of the "categories."
Public Sub UnusedTitleHide()

Dim ws As Worksheet
Dim LastRow As Long

Dim LocalLastRow As Long
Dim LocalFirstCell, LocalLastCell, LocalCells As Range

On Error GoTo ErrHandle

WSCount = ActiveWorkbook.Worksheets.Count

'I was getting errors when using the "For Each ws" loop.
'It failed to move onto the next worksheet, for some reason
For W = 1 To WSCount
    Set ws = ActiveWorkbook.Sheets(W)

    With ws
        'A more reliable way of finding the last row
        LastRow = .Cells.Find(What:="*", LookIn:=xlFormulas, SearchOrder:=xlByRows, searchdirection:=xlPrevious).Row

        'Unhide everything so the End function doesn't skip cells.
        For i = 1 To LastRow
            Rows(i).Hidden = False
        Next i

        'Start with the first cell
        Set LocalFirstCell = .Cells(1, 1).Offset(1, 0)

        Do While LocalLastRow < LastRow
            'Last cell is at the end of the section
            Set LocalLastCell = LocalFirstCell.End(xlDown)
            'Set is made up of cells between first and last
            Set LocalCells = Range(LocalFirstCell, LocalLastCell)

            For Each Cell In LocalCells
                If IsEmpty(Cell.Offset(0, 1)) = True Then
                    Cell.Rows.EntireRow.Hidden = True
                End If
            Next Cell

            For Each Cell In LocalCells
                If Cell.Rows.EntireRow.Hidden = True Then
                    'HiddenRow. Keep Checking for data
                ElseIf Cell.Rows.EntireRow.Hidden = False Then
                    'Data is present, no need to hide title
                    GoTo NextSet
                End If
            Next Cell

            'No Data Was found, so hide the title row
            LocalFirstCell.Offset(-1, 0).Rows.EntireRow.Hidden = True

NextSet:
            LocalLastRow = LocalLastCell.Row
            Set LocalFirstCell = LocalLastCell.End(xlDown)
            'Catch if the End function goes to the end of the sheet
            If LocalFirstCell.Row = 1048576 Then
                GoTo NextWorksheet
            Else
                'Otherwise keep on looping
                Set LocalFirstCell = LocalFirstCell.Offset(1, 0)
            End If

        Loop

NextWorksheet:
        End With

    Next W

ErrHandle:
        'Triggered by the Find function not finding anything
        If Err.Number = 91 Then
            MsgBox ("No Data in " & ws.Name)
            Resume NextWorksheet
        End If

End Sub

While this may work for your current situation, as @Mooseman suggested, it may be best to hide the title row while you are hiding all the other rows.

A: This is the final rendition of the code based on E. Merckx's "Better Edit"
Public Sub UnusedTitleFinal()
Dim ws As Worksheet
Dim Cell As Range
Dim Rng As Range
Dim lastRow As Long
Dim rngString As String
Dim TitleCell As Range
Dim i As Integer

'Iterating through each worksheet
For Each ws In ActiveWorkbook.Worksheets

    With ws
        'Finding and setting the range to check the cells
        lastRow = .Cells.Find(What:="*", LookIn:=xlFormulas, SearchOrder:=xlByRows, searchdirection:=xlPrevious).Row
        rngString = "A" & "6" & ":" & "A" & lastRow + 1
        Set Rng = .Range(rngString)
        For Each Cell In Rng.Cells

            If Cell.Font.Bold = True Then
            Set TitleCell = Cell
                i = 1
                Do While Cell.Offset(i, 0).Rows.EntireRow.Hidden = True
                    i = i + 1
                Loop

                If IsEmpty(Cell.Offset(i, 0)) = True Then
                    TitleCell.Rows.EntireRow.Hidden = True
                End If

            End If
            'Next Cell
        Next Cell
   End With
Next ws

End Sub


text:
Q: Making changes to default IPv6 route persistent in CentOS 7 I have several IPv6 addresses on a CentOS 7 server and need to make a specific v6 address the default address used in routing. I have been able to do this by modifying the route table.
ip -6 route del default
ip -6 route add default via 2001:470:xxxx:xx::1 src 2001:470:xxxx:xx::6

Problem is each time the network interface is restarted or the server itself is rebooted, the change to the default IPv6 route is lost. How can I make this change persistent so its permanently kept?

A: When Red Hat's networking scripts set multiple IPv6 addresses configured in /etc/sysconfig/network-scripts/ifcfg-*, for whatever reason, they are applied in reverse order, so that the last address listed in IPV6ADDR_SECONDARIES becomes the address used by default for outgoing connections. Reversing the order in which IPv6 addresses are listed is generally sufficient to fix the problem.
To answer the only vaguely related bounty question: IPv6 static routes can be set by adding them to a corresponding /etc/sysconfig/network-scripts/route6-*. The format of this file is the same as the ip route add command with that bit omitted, e.g.:
default via 2001:db8:dead:beef:: dev eno1
2001:db8:deca:fbad::/64 via 2001:db8:dead:beef::8bad:f00d dev eno1

A: One place you can put it is in the /sbin/ifup-local file which is run when an interface comes up.
#!/bin/sh
if [[ "$1" == "eth0" ]]
then
  ip -6 route del default
  ip -6 route add default via 2001:470:xxxx:xx::1 src 2001:470:xxxx:xx::6
else
  #DO_NOTHING
fi

It doesn't exist by default so you will need to create it and set permissions to make it executable.


text:
Q: Java make a list of classes with multiple objects I want to create a list of classes with different attributes but i'm facing a problem: when I add a new one, all the others are modify.(the code is really big so i'm posting just a small sample)
public abstract class A{
public static Point Position;
public static int LifePoints;
public static int range;
public static int atackValue;
public static double movementSpeed;

public double getMovementSpeed() {
return movementSpeed;
}
public static void setMovementSpeed(double movement) {//this n funciona
movementSpeed = movement;
}
(...)to make the topic shorter i only show the movement part but class A contains all getters and setters for all movement,position,range,life points and attack value
}

public class B extends A{

public static Point Position;
public static int LifePoints=10000;
public static int range=50;
public static int atackValue=100;
public static double movementSpeed=2;

public A(Point startPoint){
setMovementSpeed(movementSpeed);
setAtackValue(atackValue);
setRange(range);
setLifePoints(LifePoints);
setPosition(startPoint);
}

public class createB(){

(...)

public void create(){

private List<B> list = new ArrayList<B>();

B b = new B(startpoint);

list.add(b);

}

(...)

for(int x=0;x!=list.length();x++){

move(list.get(x));

system.out.println(list.get(x).getMovementSpeed());

}

The println returns the correct value (2.0) for all b's created but everytime I create a new b all the other b's stop moving and the new b moves faster than the previous one. The move function it's made by my teacher and it's confirmed to be working correctly. I suspect the position isn't working correctly and instead of moving the pictures 2 pixels it moves only one X times.

A: That's because you have static fields instead of instance variables.

A: The first point is that static fields are class-allocated: there is only one field for all instances.
There are other basic mistakes in your sample, though.

*

*If you create a subclass, it inherits all fields from its superclass.  You do not need to repeat those.  That is the whole point of inheritance.  Your initial values should be set in the constructor.

*The constructor of a class should be defined in that class and be named the same as that class.  It does not make sense to declare a constructor A inside of class B (I guess that your adjustments for posting this were not quite clean).  Your code also seems to have some issues with unbalanced parentheses.

*You seem to have execution statements outside of a method (or static initialization block, but let's leave that alone), which also does not make sense.

*As shown, the abstract class A is completely superfluous.

*Your method create never seems to return the list it created.  How do you want to use it?

*Use indentation.  Standard in Java is 4 spaces of indentation for each nested block.

*Name your variables properly.  A variable should always start with a lowercase letter.  Names starting with uppercase letters denote classes.
All in all, I feel a lot of confusion there.  You should try to read more code of real projects, to get a feeling for the language(s).


text:
Q: Why am I getting fatal: Authentication failed for  I just got started on Github again, and created a new repo.  It's a private repo, so I use  git clone <URL_clone_link>, and it prompts for username and password (both of which I've verified are correct), but ends with the fatal error in the Title.
I'm using a terminal on a relatively new iMac, and it doesn't seem to be a local machine issue.  I just don't understand why it won't authenticate me using the same username/pwd I use to log in.

A: First, check that, as commented, you have 2FA activated.
If yes, the password to enter would be a PAT (Personal Access Token) that you would need to generate and add to your tokens.
Second, check your git config credential.helper output: if osxkeychaiy, you might need to do:
 git credential-osxkeychain erase https://github.com

In order to remove the password cached by the osxkeychain credential caching setup.


text:
Q: How to stitch schemas using apollo graphQL? I am a java programmer learning graphQL. I have dataset as below sample where comment has postId, but post doestn't have comment information.
     comments
     {
        "postId": 1,
        "id": 1,
        "name": "id labore ex et quam laborum",
        "email": "Eliseo@gardner.biz",
        "body": "laudantium enim quasi"
      }

    post
      {
        "userid": 3,
        "id": 1,
        "title": "Post 1"
      }

Using Apollo Federation

*

*Can I have comment details in Post response?
{
  "data": {
  "posts": [
          {
         "userid": 3,
         "id": 1,
         "title": "Post 1"
         "comments":
            {
             "id": 1,
             "name": "id labore ex et quam laborum",
             "email": "Eliseo@gardner.biz",
             "body": "laudantium enim quasi"
             }
           }
          ]
        }

*I need to basically use following algorithm

*

*get all comments

*Filter comments with given postId

*collect all matching comments and return from resolver function

Below is the post.js code
 type Post @key(fields: "id"){
     id: ID!
     userid: Int!
     title: String!
     comments: [Comment]
   }

   extend type Comment @key(fields: "id" ){
       id: ID! @external
   }

  const resolvers = {
    Post: {
        comments(post){
          return ( { __typename: "Post",  postId:post.id });
       }

   Query: {
        post: (root, { id }, { dataSources }) => dataSources.mvrpAPI.getAPost(id),
       posts: (root, args, { dataSources }) => dataSources.mvrpAPI.getAllPosts()}

With above resolver's comment method I am getting below error
  "message": "Expected Iterable, but did not find one for field
 \"Post.comments\".",

then I tried below resolver method and this cannot recognize mvrpAPI, even though it works in query section of resolvers
     async comments(post, {dataSources}){
      const allComments =  dataSources.mvrpAPI.getAllComments();;

      return allComments.postId.findAll(
        { __typename: "Post",  postId:post.id }
      );
    }
    }

Can someone help on how to write above mentioned logic (in point 2) in graphql.

A: here is how I solved above issue

*

*response.filter retuns an array and since I was looking for an array of comments with specific post id, just putting condition inside map function helped.

*dataSources.mvrpAPI.getAllComments() gives Promise . To get real Object I  used "await" and since await can only be used from async function, I made comments function async.
async comments(post, {postid}, {dataSources}){
     const response =  await dataSources.mvrpAPI.getAllComments();
       return response.filter(comment => comment.postId === post.id);
     }
  },

A: You are declaring comments as a list on the Post schema, and on the resolver you are returning a single object

return ( { __typename: "Post",  postId:post.id });

that's the reason for the "Expected Iterable" error.
I'm not familiar with that database api, but this shouldn't be hard with most api's.
In mongoose it would be something like
async (post,_, {model}) => model.Comment.find({postId: post.id})


text:
Q: Adding elements to array struct in c++ im doing an assignment on c++ and im stuck on how i would add a new transaction to my work, with a user defined numShares, and pricePerShare.
i have a transaction struct which looks like this:
struct Transaction
{
string stockSymbol;     // String containing the stock symbol, e.g. "AAPL"
string buyerName;       // String containing the buyer's name e.g. "Mr Brown"
int buyerAccount;       // Integer containing an eight digit account code
int numShares;          // Integer containing the number of sold shares
int pricePerShare;      // Integer containing the buy price per share
};

this is the buildTransaction class:
static Transaction* buildTransactions(int numTransactions)
{
    int maxShareVolume = 100000;
    int maxSharePrice = 1000;

    Transaction *transactions = new Transaction[numTransactions];

        for(int idx = 0; idx < numTransactions; idx++)
        {
            transactions[idx].stockSymbol = pickRandomStockSymbol();

            std::string buyerName = pickRandomBuyer();
            transactions[idx].buyerName = buyerName;
            transactions[idx].buyerAccount = lookupBuyerAccount(buyerName);

            transactions[idx].numShares = 1 + rand() % maxShareVolume;
            transactions[idx].pricePerShare = 1 + rand() % maxSharePrice;
        }

        return transactions;
    }

how would i use that to add data to the transactions array using this:
void Analyser::addTransactions(Transaction* transactions, int numTransactions)

i would assume from this that all i would really need to have as user input would be the amount of shares, and the price per share, but that the other information fills itself in automatically, from choosing from the arrays.

A: instead of using arrays, you should use vectors.. the buildTransactions would be written this way:
std::vector<Transaction> buildTransactions(int numTransactions)
{
    int maxShareVolume = 100000;
    int maxSharePrice = 1000;
    std::vector<Transaction> transactions;

    for(int idx = 0; idx < numTransactions; idx++)
    {
        Transaction t;
        t.stockSymbol = pickRandomStockSymbol();
        std::string buyerName = pickRandomBuyer();
        t.buyerName = buyerName;
        t.buyerAccount = lookupBuyerAccount(buyerName);
        t.numShares = 1 + rand() % maxShareVolume;
        t.pricePerShare = 1 + rand() % maxSharePrice;

        transactions.push_back(t);
    }

    return transactions;
}

by editting the buildTransactions function, you can easily add more data by doing this to your addTransactions function:
void Analyser::addTransactions(std::vector<Transaction> &transactions, int numTransactions)
{
    for(int idx = 0; idx < numTransactions; idx++)
    {
        Transaction t;
        t.stockSymbol = pickRandomStockSymbol();
        std::string buyerName = pickRandomBuyer();
        t.buyerName = buyerName;
        t.buyerAccount = lookupBuyerAccount(buyerName);

        std::cout << "Enter number of shares for transaction: ";
        std::cin >> t.numShares;
        std::cout << "Enter price per share for transaction: ";
        std::cin >> t.pricePerShare;

        transactions.push_back(t);
    }
}

hope it helps :)

A: you can get amount of shares, and the price per share as inputs in a loop in addTransactions() method like  the following:
for(int idx = 0; idx < numTransactions; idx++)
    {
        transactions[idx].stockSymbol = pickRandomStockSymbol();

        std::string buyerName = pickRandomBuyer();
        transactions[idx].buyerName = buyerName;
        transactions[idx].buyerAccount = lookupBuyerAccount(buyerName);

        ctd::cout<<"Enter number of shares for transaction "<<idx+1<<std::endl;
        std::cin>>transactions[idx].numShares;
        ctd::cout<<"Enter price per share for transaction "<<idx+1<<std::endl;
        std::cin>>transactions[idx].pricePerShare;
    }


text:
Q: Click to create tag / label random but start from label-default When I click on my button I am trying to create a bootstrap label. But each time I click it should start off at label-default and work through the switch until it gets to the last one the go back to the beginning
As shown on image below it not starting off at label-default

Question each time I click on the button to create label how can I
  make sure it does not double up and starts from label-default

DEMO

CODEPEN DEMO

SCRIPT
$(document).on('click', '#category_button', function(e){

    e.preventDefault();

    //if ($("#label-" + category_name).length  == 0) {

        var rand = Math.floor((Math.random() * 5) + 1);

        switch(rand){
          case 1:
            element = 'label-default';
            break;
          case 2:
            element = 'label-primary';
            break;
          case 3:
            element = 'label-success';
            break;
          case 4:
            element = 'label-info';
            break;
          case 5:
            element = 'label-warning';
            break;
        }

        html = '';
        html += '
';
        html += '';
        html += 'Hello';
        html += '';
        html += '
';

        $('.categories ul').append(html);
    //}
});

A: You can use an array, Array.prototype.slice(), Array.prototype.splice() to create a copy of original array. If copied array has .length equal to 0 remove first element from array, set the element as element value, else get, set random element from copied array as element value, repeat procedure.

var arr = ["default", "primary", "success", "info", "warning"];
var label = "label-";
var copy = [];

$(document).on("click", "#category_button", function(e) {

  e.preventDefault();

  var element, rand;

  if (!copy.length) {
    copy = arr.slice(0);
    element = copy.splice(0, 1);
  } else {
    rand = Math.floor(Math.random() * copy.length);
    element = copy.splice(rand, 1);
  }

  var html = $("
", {
    "id":"",
    "html":$("", {
             "class": label.slice(0, -1).concat(" ", label, element),
             "html": label + element
           })
  });

  $(".categories ul").append(html);

});

<button id="category_button">click</button>

codepen http://codepen.io/anon/pen/PpXryW

A: Not sure if I misunderstood your question, but you are using a random to decide which label to add. If you want an ordered sequence, you should not be using random. Code shown below:
var counter = 0;
$(document).on('click', '#category_button', function(e){
  e.preventDefault();
    switch(counter) {
      case 0:
        element = 'label-default';
        break;
      case 1:
        element = 'label-primary';
        break;
      case 2:
        element = 'label-success';
        break;
      case 3:
        element = 'label-info';
        break;
      case 4:
        element = 'label-warning';
        break;
    }

    counter = (counter + 1) % 5;

    var html = '';
    html += '
';
    html += '';
    html += 'Hello';
    html += '';
    html += '
';

    $('.categories ul').append(html);
  //}
});