text:
Q: GraphQL / Apollo - Can't get NetworkError I'm unable to get any network error with my Apollo Client, only GraphQL errors.
I have the client set up like so:
    const errorLink = onError(({ graphQLErrors, networkError }) => {
  if (graphQLErrors)
    graphQLErrors.map(({ message, locations, path }) =>
      console.log(`[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`)
    );
  if (networkError) console.log(`[Network error]: ${networkError}`);
});

  const client = new ApolloClient({
    link: ApolloLink.from([
      errorLink,
      new HttpLink({
        uri: 'http://localhost:4000/graphql'
      }),
    ]),
  });

On the server i'm making a request which i parse like this:
 .then(res => {
  if (res.ok) {
    return { blah: res.json(), count };
  }
  throw new Error();
})
.catch(error => {
  throw new AuthenticationError('Must Authenticate');
});

The AuthenicationError just bubbles up to the Client as a GraphQL Error ([GraphQL error]: Message: Must Authenticate,, i basically just want to be able to get the HTTP Status Code from the server request, on the client.
Thanks

A: Your client side implementation looks correct.
I guess you are using express with some graphl middleware to handle the requests. The main thing is that you would need to handle the authentication process before the graphql middleware comes in to play.
So the authentication is a graphql mutation which you handle directly. In my case it looked kind of like this:

...

const app = express();

app.use(
  "/graphql",
  bodyParser.json(),
  (request, response, next) => authenticationMiddleware(request) // authentication is handled before graphql
  .then(() => next())
  .catch(error => next(error)),
  graphqlExpress(request => {
    return {
      schema: executable.schema,
      context: {
        viewer: request.headers.viewer
      },
    };
  }),
);

...

app.listen(...)

Another possibility would be to add the status code to the error response in the graphql errors.
But that depends on the npm package you are using.
e.g. formatError in apollo-server-graphql
https://www.apollographql.com/docs/apollo-server/api/apollo-server.html#constructor-options-lt-ApolloServer-gt


text:
Q: Console only recognizes second input Java I need to type a command twice into the Console, only then it recongnizes it as a input. I tried as the reader from the command file also a scanner instead of a bufferedReader. I hope you can help me!
private File commandFile = new File("commands.txt");

public void run() {
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    while(true) {
        try {
            if(in.readLine() != null) {
                String input = in.readLine();
                if(commandExists(input) == true) {
                    System.out.println("Command exists");
                }else LogManager.writeLog("Cannot find Command " + input);
            }
        } catch (IOException e) {
            LogManager.writeLog("[InputScanner] Cannot read Console Input!");
            System.err.println(e.getCause());
        }
    }
}

private boolean commandExists(String command) {
    Boolean result = false;
    if(!commandFile.exists()) {
        LogManager.writeLog("[InputScanner] Cannot Find Commands File!");
    }
    try {
        BufferedReader reader = new BufferedReader(new FileReader(commandFile));
          String line;
          while (null != (line = reader.readLine())) {
              if(line.equalsIgnoreCase(command)) {
                  result = true;
              }
          }
    } catch (IOException e) {
        e.printStackTrace();
    }

    return result;
}

This is the code from the commands.txt file:
Code command.txt file

A:
if(in.readLine() != null) {
    String input = in.readLine();

Those are two reads. The first consumes the first part, but you don't use it other than for the nullcheck.
Fix:
String input = in.readLine();
if (input != null) {
    ...

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to leave a war in which you are not the main attacker/defender? I was invited into a war via a defensive pact and we're losing terribly. The problem is, even if the warscore is below -50%, the main defender has not yet sent their peace terms and I'm stuck fighting the enemy myself. Is there a way to stop my involvement abruptly?

A: You can't.
You can minimise losses by keeping your fleet out of the way, but there's not much you can do if the enemy decides to attack your territory or, worse, cede your planets.
In future, you can avoid this by not making defensive pacts that you don't want to have to honour.


text:
Q: Showing edit button to current_user only (Rails 4) I'm trying to allow users to show the edit button only if the profile belongs to them. Currently, they're only allowed to edit the profile if it belongs to them but I can't seem to hide the button. I have this so far
<% if request.original_url == request.base_url + "current_user.id" %>
  <%= link_to "Edit Profile", edit_user_path(current_user), class: "btn btn-primary btn-xs" %>
<% end %>

This is what I'm trying to compare:
request.original_url => localhost:3000/users/random_user
request.base_url + "users/" + current_user.id => localhost:3000/users/current_user
Thanks in advance.

A: Authorization
To give you some perspective, you'll be looking for something called authorization.
This is different from authentication because it deals with permissions, rather than identifying your identity. I'll get into how this works in a minute.

To solve your problem, here's what you need to do:
<%= link_to "Edit Profile", edit_user_path(current_user), class: "btn btn-primary btn-xs", if user_signed_in? && current_user == @user %>

I'm guessing you're showing this on a user#show action, which can be invoked using the following code:
#app/controllers/users_controller.rb
class UsersController < ApplicationController
   def show
      @user = User.find params[:id]
   end
end

This means that if you have the following routes:
#config/routes.rb
resources :users

you'll have access to @user and current_user. It's important to note that current_user != @user. Although weezing's answer is succinct, it does not validate whether the user is the one which owns the page authorized; just that the user is authenticated

Thus, you have several specifications:

*

*You need to know if the user is actually logged in

*You need to make sure your logged-in user has the authorization to edit the profile (IE is it theirs)

I would highly recommend looking into the use of gems such as CanCanCan or Pundit. I'll show you CanCanCan:
#app/models/ability.rb
class Ability
   include CanCan::Ability

   def initialize(user)
      user ||= User.new # guest user (not logged in)
      can :edit, Article, id: user.id
   end
end

#app/views/users/show.html.erb
<%= link_to "Edit", edit_user_path(@user) if can? :edit, @user %>

There is a great resource here.

A: This should work (little bit simpler):
<% if current_user %>
  <%= link_to "Edit Profile", edit_user_path(current_user), class: "btn btn-primary btn-xs" %>
<% end %>


text:
Q: Forward declaring class with templated code I'm trying to implement the double dispatch pattern for a message interface in C++. However, I find that I have to be too verbose in my handler class due to having to forward declare each message.
I'm looking for a way to structure the file(s) to be able to omit the forward declarations.
I'm aware that I can template the MessageHandler class with a tuple of all available messages. However, I found this not straightforward enough and looking for more simple - explainable - methods.
struct MessageA;
struct MessageB;
// etc...

class MessageHandler {
public:
    virtual void handle(MessageA& m);
    virtual void handle(MessageB& m);
    // etc...

    virtual void handle(Message&) {}

};

struct Message {
    virtual void dispatch(MessageHandler&) = 0;
};

template<typename ActualMessage>
struct MessageHelper : Message {
    void dispatch(MessageHandler& handler)
    {
        handler.handle(static_cast<ActualMessage&>(*this));
    }
};

struct MessageA : MessageHelper<MessageA> {};
struct MessageB : MessageHelper<MessageB> {};
// etc...

In the real code I'm dealing with more than 20 messages. I'm okay with the verbosity of the handler class, the forward declarations are a bit "much".
Is there some way I can restructure this? Of course I'm limited due to the fact that the MessageHelper class is templated. This restricts me in forward declaring the MessageHandler class instead.
Thanks!

A: You can't get rid of forward declarations entirely, but you can change the order so that you only need to forward declare MessageHandler and none of the messages:
struct MessageHandler;

struct Message {
    virtual void dispatch(MessageHandler&) = 0;
};

template<typename ActualMessage>
struct MessageHelper : Message {
    void dispatch(MessageHandler& handler);
};

struct MessageA : MessageHelper<GetDeviceConfig> {};
struct MessageB : MessageHelper<GetDeviceConfig> {};
// etc...

class MessageHandler {
public:
    virtual void handle(MessageA& m);
    virtual void handle(MessageB& m);
    // etc...

    virtual void handle(Message&) {}
};

template<typename ActualMessage>
void MessageHelper<ActualMessage>::dispatch(MessageHandler& handler)
{
    handler.handle(static_cast<ActualMessage&>(*this));
}

I'm limited due to the fact that the MessageHelper class is templated. This restricts me in forward declaring the MessageHandler class instead.

It's unclear why you think MessageHelper being templated would restrict you from forward declaring MessageHandler.


text:
Q: Angular 12 *ngFor Displays Parent Menus but don't display subsequent child menus from Nested Array Here is my Nested Array result from typescript.ts
[
    {
        "0": {
            "menuName": "Home",
            "childs": [
                {
                    "subMenuName": "",
                    "subMenuValue": ""
                }
            ]
        },
        "2": {
            "menuName": "User",
            "childs": [
                {
                    "subMenuName": "User List",
                    "subMenuValue": "/users"
                }
            ]
        },
        "5": {
            "menuName": "ABC",
            "childs": [
                {
                    "subMenuName": "ABC Admin menu 1",
                    "subMenuValue": "/DEF/DEFreport"
                },
                {
                    "subMenuName": "Fund ",
                    "subMenuValue": "/admin/manage-sub-fund"
                },
                {
                    "subMenuName": "ABC Screen",
                    "subMenuValue": "/admin/ABC"
                }
            ]
        },
        "6": {
            "menuName": "AI",
            "childs": [
                {`enter code here`
                    "subMenuName": "AI Screen",
                    "subMenuValue": "/AI"
                }
            ]
        },
        "8": {
            "menuName": "DEF",
            "childs": [
                {
                    "subMenuName": "DEF Int List",
                    "subMenuValue": "/admin/DEFreport-Intdist"
                },
                {
                    "subMenuName": "DEF Ext List",
                    "subMenuValue": "/admin/DEFreport-Extdist"
                },
                {
                    "subMenuName": "DEF ISIN",
                    "subMenuValue": "/admin/DEFassign"
                },
                {
                    "subMenuName": "DEF Report",
                    "subMenuValue": "/DEF/DEFreport"
                }
            ]
        }
    }
]

This is how I am trying to access in component.html page

            <button type="button" class="btn dropdown-toggle" data-toggle="dropdown"
            style="color: antiquewhite;">{{parent.key}}</button>

                {{child.subMenuName}}

I am trying to display dynamic menus from database.
Please Correct me as, I am new to angular.
It might be possible, I am writing wrong parent and child menus properties names.
any help regarding solution is appreciated.
Thanks

A: The *ngFor directive allows iterating over a collection, and what you posted is NOT an array (as you seem to describe it), and hence is not a collection. It's an object, which is something different in javascript.
You can use the angular's built-in KeyValuePipe, which transforms an object into an array of key-value pairs, to iterate the properties of the object though.

A: You can do with the help of keyvalue like this

  <button type="button" class="btn dropdown-toggle" data-toggle="dropdown"
            style="color: antiquewhite;"> {{parent.value["menuName"]}}</button>

    {{child.subMenuName}}

A: I have found few problems with KeyValuePipe, for the child sub menus parents are being displayed i did changes on my object to become flat array and basis on this i have implemented changes on the HTML to loop through menus and sub-menus. which resolved the issue.


text:
Q: Render or convert proprietary-encoded characters that use custom fonts for HTML I have extracted characters from PDFs that require custom fonts to render.
I can render the characters OK in SVG, but I need to render them in HTML (as SVG made old mobile browsers laggy and battery hungry).
However if I render the same characters as HTML with the custom font face, they render as, for example M¿'ƒ" T¡u``  ̈ÃU uìÒ SkuM"  M¿. I think this is because the fonts use proprietary encodings?
To see this, click the "Text only" checkbox on this page, and it will replace the correct server-side render with the incorrectly rendered characters.
(For now, I have included the ineffective CSS referencing the font files (extracted from the PDF using pdf.js), but I'll disable this after a week or two.)
However if you go to the first page of that book, you can see that standard fonts in the same alphabet (Fidel, from Ethiopia) render OK, presumably as it is not using proprietary encodings.
Is there any way I can get those proprietary encodings rendering in HTML? Either by preprocessing/decoding the source characters (ideally Python or Node, as I'm already using them, but anything - I am pretty desperate), or doing something to help the browser render them?
Thanks


text:
Q: Why is the Facebook login dialog opening in Safari when building their framework for ARC? When I'm building the Facebook framework for ARC on iOS, the login dialog is opening in Safari instead of a separate dialog.
What can I do to get this to open in a separate dialog, and not in Safari when building for ARC?

A: Before compiling facebook api file open facebook.m file then go to the method [facebook authorize:nil]; and set [self authorizeWithFBAppAuth:NO safariAuth:NO]; and then compile it.

A: After making changes as described by Khoool i.e. [self authorizeWithFBAppAuth:NO safariAuth:NO] in Facebook.m located in the src folder which is in facebook-ios-sdk a great reference for including the modified facebook-ios-sdk into your Xcode project and performing the compilation is: http://nabtech.wordpress.com/2012/02/02/facebook-ios-sdk-and-arc/
Note: Notepad++ can be used to make the change on line 336 of the Facebook.m file before adding to the Xcode project and compiling.
Before finding this stackoverflow solution I was using techniques that involved compiling build_facebook_ios_sdk_static_lib.sh. Using this technique for ARC does not make the Facebook.m file visible so that the change [self authorizeWithFBAppAuth:NO safariAuth:NO] can be made.


text:
Q: Efficient Way to Tokenize String With Complex Delimiter / Separator and Preserving the Delimiter / Separator as Token in C# I am trying to find the most efficient way to create a generic tokenizer that will retain the complex delimiters / separators as extra token.
And yes... I looked at some SO questions like How can i use string#split to split a string with the delimiters + - * / ( ) and space and retain them as an extra token? but so far, it's too specific.  I need the solution to work against generic string.
In my case, I am looking to tokenize strings such as
"   A brown bear     A red firetruck  A white horse   "

and as result, I am expecting the following tokens:
"   ",              //3 spaces
"A brown bear",
"     ",            //5 spaces
"A red firetruck",
"  ",               //2 spaces
"A white horse",
"   "               //3 spaces

and so, here is the code that I come up with, it's working as expected but I am wondering if there is anyway to improve on this...
public static class StringExtension
{
    public static List<string> TokenizeUsingRegex(this string input, string separatorRegexPattern, bool includeSeparatorsAsToken = true)
    {
        var tokens = Regex.Split(input, separatorRegexPattern).Where(t => !string.IsNullOrWhiteSpace(t)).ToList();

        if (!includeSeparatorsAsToken)
            return tokens;

        //Reinstate the removed separators
        var newTokens = new List<string>();
        var startIndex  = 0;
        for(int i = 0, l = tokens.Count(); i < l; i++)
        {
            var token = tokens[i];
            var endIndex = input.IndexOf(token);

            if (startIndex < endIndex) {
                //Add back the separator as a new token
                newTokens.Add(input.Substring(startIndex, endIndex - startIndex));
            }
            //Then add the token afterward
            newTokens.Add(token);

            startIndex = endIndex + token.Length;
        }

        //Add last separator if any
        if (startIndex < input.Length) {
            newTokens.Add(input.Substring(startIndex));
        }

        return newTokens;
    }
}

Live example at: https://dotnetfiddle.net/l3mesr

A: What about this?
using System;
using System.Linq;
using System.Text.RegularExpressions;

class Program
{
    static void Main()
    {
        var str = "    Invisible Pty. Ltd.     1 Nowhere St.  Sydney  2000  AUSTRALIA   ";
        //str = " A teddy bear   A red firetruck ";

        //tokenize the input delimited by 2 or more whitespaces
        var tokens = Regex.Matches(str, @"\s{2,}|(\s?[^\s]+(\s[^\s]+)*(\s$)?)").Cast<Match>().ToArray();

        foreach(var token in tokens)
        {
            Console.WriteLine("'{0}' - {1}", token, token.Length);
        }
    }
}

I used visual studio's Perf and Diagnositics in visual studio and this takes 40ms vs the existing one took 80ms.  dotnetfiddle.net reported the performance as slower(?)  I would probably trust VS more but I just wanted to throw that out there.
Basically how it works is it looks for either multi-spaces OR anything else with no more then one space between.


text:
Q: FileNotFoundError: Entity folder does not exist! in Google Colab Can anyone help me in sorting out this issue?
When I run these lines in Colab
:param files_name: containing training and validation samples list file.
:param boxes_and_transcripts_folder: gt or ocr result containing transcripts, boxes and box entity type (optional).
:param images_folder: whole images file folder
:param entities_folder: exactly entity type and entity value of documents, containing json format file
:param iob_tagging_type: 'box_level', 'document_level', 'box_and_within_box_level'
:param resized_image_size: resize whole image size, (w, h)
:param keep_ratio: TODO implement this parames
:param ignore_error:
:param training: True for train and validation mode, False for test mode. True will also load labels, and files_name and entities_file must be set.
'''
class PICKDataset(Dataset):
    def __init__(self, files_name: str = None,
                 boxes_and_transcripts_folder: str = 'boxes_and_transcripts',
                 images_folder: str = 'images',
                 entities_folder: str = 'entities',
                 iob_tagging_type: str = 'box_and_within_box_level',
                 resized_image_size: Tuple[int, int] = (480, 960),
                 keep_ratio: bool = True,
                 ignore_error: bool = False,
                 training: bool = True
                 ):

        super().__init__()
        self._image_ext = None
        self._ann_ext = None
        self.iob_tagging_type = iob_tagging_type
        self.keep_ratio = keep_ratio
        self.ignore_error = ignore_error
        self.training = training
        assert resized_image_size and len(resized_image_size) == 2, 'resized image size not be set.'
        self.resized_image_size = tuple(resized_image_size)  # (w, h)

        if self.training:  # used for train and validation mode
            self.files_name = Path(files_name)
            self.data_root = self.files_name.parent
            self.boxes_and_transcripts_folder: Path = self.data_root.joinpath(boxes_and_transcripts_folder)
            self.images_folder: Path = self.data_root.joinpath(images_folder)
            self.entities_folder: Path = self.data_root.joinpath(entities_folder)
            if self.iob_tagging_type != 'box_level':
                if not self.entities_folder.exists():
                    raise FileNotFoundError('Entity folder is not exist!')

I get this error
RuntimeError: module compiled against API version 0xe but this version of numpy is 0xd
[2022-02-26 13:17:11,933 - train - INFO] - Distributed GPU training model start...
[2022-02-26 13:17:11,933 - train - INFO] - [Process 306] Initializing process group with: {'MASTER_ADDR': '127.0.0.1', 'MASTER_PORT': '29500', 'RANK': '0', 'WORLD_SIZE': '1'}
[2022-02-26 13:17:11,934 - train - INFO] - [Process 306] world_size = 1, rank = 0, backend=nccl
Traceback (most recent call last):
  File "train.py", line 162, in <module>
    entry_point(config)
  File "train.py", line 126, in entry_point
    main(config, local_master, logger if local_master else None)
  File "train.py", line 34, in main
    train_dataset = config.init_obj('train_dataset', pick_dataset_module)
  File "/content/PICK-pytorch/parse_config.py", line 105, in init_obj
    return getattr(module, module_name)(*args, **module_args)
  File "/content/PICK-pytorch/data_utils/pick_dataset.py", line 66, in __init__
    raise FileNotFoundError('Entity folder is not exist!')
FileNotFoundError: Entity folder is not exist!
Traceback (most recent call last):
  File "/usr/lib/python3.7/runpy.py", line 193, in _run_module_as_main
    "__main__", mod_spec)
  File "/usr/lib/python3.7/runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "/usr/local/lib/python3.7/dist-packages/torch/distributed/launch.py", line 263, in <module>
    main()
  File "/usr/local/lib/python3.7/dist-packages/torch/distributed/launch.py", line 259, in main
    cmd=cmd)
subprocess.CalledProcessError: Command '['/usr/bin/python3', '-u', 'train.py', '--local_rank=0', '-c', 'config.json', '-d', '0', '--local_world_size', '1']' returned non-zero exit status 1.

What I have tried
Changing inputfilepath in PICKDataset, remving lines which rise error.
Complete Notebook

A: There is error in https://github.com/wenwenyu/PICK-pytorch/blob/master/config.json file. you have to change the path of data as per your working directory. Check line number 61 to 64 and 73 to 76.


text:
Q: IndexError: list index out of range for nested list I have a list that contains lists of 5 values and i'm getting an index out of range error when trying to run a while loop if a value in the list is == 5.
Here is pretty much all my code
from solverFuncs import *
puzzle = [[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0]]

pos = 0
backtrack = 0
checks = 0

while pos <25:
    puzzle[pos/5][pos%5] += 1
    checks+=1
    if check_valid(puzzle,cages):
        pos+=1
    elif puzzle[pos/5][pos%5]==5:
        while puzzle[pos/5][pos%5]==5:
            puzzle[pos/5][pos%5]=0
            pos=pos-1
            backtrack+=1

The error im getting shows up as such:
File "solver.py", line 16, in <module>
while puzzle[pos/5][pos%5]==5:
IndexError: list index out of range

A: In python, list's indexes starts with [0]. So you have 5 elements in your list with min index = 0 and max index = 4. Hope it will help

A: Whatever check_valid does, I think you should add a check in the while block at line 16
while pos>=0 and puzzle[pos/5][pos%5]==5:

and also adding pos=0 before going back to while pos<25


text:
Q: Why i cannot apply an !Important CSS rule? Somewhere within my application i have
.table-striped tbody>tr:nth-child(odd)>td, .table-striped tbody>tr:nth-child(odd)>th {
   background-color: #f9f9f9;
}

By using Server-Side code (at the ItemDataBound event of a repeater control) i apply the following CSS classes to specific rows like so
<tr id="MyRow" class="fc pwon">

Which are...
.fc {
   background-color: #fcfcfc;
}
.pwon {
   background-color: rgba(77, 144, 254, 0.47) !important;
   color: black;
   text-align: center;
}

Unfortunately the color that is applied at the row is #f9f9f9;
Why is this happening? How can i fix that?

A: Your .fc and .pwon classes are on a tr element, but in your first rule you're applying that background to either td or th. The background of a table cell is always painted over the background of a table row so you won't see your row background.
You need to replace your selectors with the following:
.fc>td, .fc>th {
   background-color: #fcfcfc;
}
.pwon>td, .pwon>th {
   background-color: rgba(77, 144, 254, 0.47) !important;
   color: black;
   text-align: center;
}

It's not clear to me why you have only one !important there, but either both of them need to be there, or it doesn't need to be there at all. Remove the !important first (because !important is usually bad practice if you don't know what you're doing), and if you're not seeing the background, try matching the specificity of your first rule by copying the selector and then adding .fc or .pw to the tr part. This may or may not work depending on the HTML that's being generated; you'll have to tinker with it a little.

A: In your code you are applying pwon to tr while the .table-striped tbody>tr:nth-child(odd)>td is applying style to the td.
try this:
.pwon td, .pwon td {
   background-color: rgba(77, 144, 254, 0.47) !important;
}

A: The code that is setting the background is scoring higher on specificity.
Basically, although you're referred directly to the class applied to the item, the first piece of code is referring to the table, table body, row, and index of the row specifically, so it scores higher.
It's not ideal, but if you added the other code to the beginning of your selectors like this:
.table-striped tbody>tr.fc:nth-child(odd)>td, .table-striped tbody>trfc:nth-child(odd)>th
{
    background-color: #fcfcfc;
}
.table-striped tbody>tr.fc:nth-child(odd)>td, .table-striped tbody>trfc:nth-child(odd)>th
{
    background-color: rgba(77, 144, 254, 0.47) !important;
    color: black;
    text-align: center;
}

That would fix it for you.  But it's quite messy, and you could look at reducing specificity of the other selector instead, or using an important! declartaion (urgh) ;)


text:
Q: Calling method within Class im new in ruby so this code is not working, please provide me the proper way of calling a method within class
Class TestClass

  def testMethod
    puts "hello"
  end

  testMethod
end

UPDATE
hi everyone thanks for all the help and comments just like @Stefan and @Matt said, my example is very uncommon to use this way and thanks for giving the right path anyway i just want to add this from my question and i found a way to work
class TestClass
    def self.testMethod
       puts "hello"
    end

    TestClass.testMethod
end

A: class TestClass
    # a class method
    def self.test_method
       puts "Hello from TestClass"
    end

    # an instance method
    def test_method
       puts "Hello from an instance of TestClass"
    end
 end

 # call the class method
 TestClass.test_method

 # create and instance object of TestClass
 instance_of_TestClass = TestClass.new

 # call the instance method of the new object
 instance_of_TestClass.test_method

A: Your example defines a class with an instance method. You then try to call the instance method from the class - this won't work.
Instead, you need to call the method as in instance, or convert it to a class method.
class TestClass

  def self.testMethod
     puts "hello"
  end

  testMethod
end

Instance and class level distinction is a fundamental concept, you would benefit from taking some tutorials, start with a read of http://www.railstips.org/blog/archives/2009/05/11/class-and-instance-methods-in-ruby/

A: You have to call method in with in class like:
class TestClass

  def testMethod
     puts "hello"
  end
  def test_2
    testMethod
  end
end

object = TestClass.new()
puts object.test_2


text:
Q: C# to move files older than N days from one folder to another folder I'm new to world of C#. What I'm trying to do is move files older than N days from one folder to another folder. This to archive files continuously. When used within SSIS package, I get error saying, "Exception has been thrown by the target of an invocation.".
Details of error:
at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at System.RuntimeType.InvokeMember(String name, BindingFlags bindingFlags, Binder binder, Object target, Object[] providedArgs, ParameterModifier[] modifiers, CultureInfo culture, String[] namedParams)
at Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTATaskScriptingEngine.ExecuteScript() "
Any thoughts ?
Code:
      public partial class Script Main :
      Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase
{
    string rootFolderPath = @"\\A\B";
    string destinationPath = @"\\A\C";

    public void Main()
    {
        string[] files = System.IO.Directory.GetFiles(rootFolderPath); ;

        foreach (string file in files)
        {
            if (File.Exists(file))
            {
                if (File.GetCreationTime(file)
                    < DateTime.Now.AddDays(-1))
                {
                    File.Move(rootFolderPath, destinationPath);
                }
            }
        }

        Dts.TaskResult = (int)ScriptResults.Success;
    }

    #region ScriptResults declaration
    /// <summary>
    /// This enum provides a convenient shorthand within the scope of this class for setting the
    /// result of the script.
    ///
    /// This code was generated automatically.
    /// </summary>
    enum ScriptResults
    {
        Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success,
        Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure
    };
    #endregion

}

}


text:
Q: Why am I not getting a forward compatible OpenGL context with GLFW? To my knowledge, when I set these context constraints on GLFW:
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

I should get the maximum available OpenGL context on the running machine, provided that it's above OpenGL 3.3. However, by using glGetString to get the OpenGL context version, I am finding that this is not the case. Everytime I query glGetString for the context version, I only get the major and minor versions I set with glfwWindowHint, nothing above. Keep in mind, my GPU supports OpenGL 4.5.
Another thing to note, when I set no constraints whatsoever, I do in fact get an OpenGL 4.5 context.
Here is the full source code, which seems to replicate the problem:
#define GLEW_STATIC

#include <iostream>

#include <GL\glew.h>
#include <GLFW\glfw3.h>
#include <glm\glm.hpp>

int main(int argc, char argv[])
{

    if (!glfwInit())
    {
        std::cerr  << "Failed to initialize GLFW 3.0.4" << std::endl;
        getchar();

        glfwTerminate();
        return -1;
    }

    std::cout << "Initialized GLFW 3.0.4" << std::endl;

    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

    GLFWwindow* m_window = glfwCreateWindow(640, 480, "Koala", NULL, NULL);

    if (!m_window)
    {
        std::cerr  << "Failed to create OpenGL 3.3+ context" << std::endl;
        getchar();
        glfwTerminate();
        return -1;
    }

    glfwMakeContextCurrent(m_window);

    std::cout << "Created OpenGL 3.3+ context" << std::endl;

    glewExperimental = GL_TRUE;

    if (glewInit() != GLEW_OK)
    {
        std::cerr << "Failed to initialize GLEW 1.11.0" << std::endl;
        getchar();
        glfwTerminate();
        return -1;
    }

    std::cout << "Initialized GLEW 1.11.0" << std::endl;

    const GLubyte* renderer = glGetString(GL_RENDERER);
    const GLubyte* version = glGetString(GL_VERSION);

    std::cout << "GPU: " << renderer << std::endl;
    std::cout << "OpenGL Version: " << version << std::endl;

    while (!glfwWindowShouldClose(m_window))
    {
        glfwSwapBuffers(m_window);
        glfwPollEvents();
    }

    glfwTerminate();
    return 0;

}

A:
I should get the maximum available OpenGL context on the running machine, provided that it's above OpenGL 3.3.

That's not the way it is defined. From the GLFW documentation:

The GLFW_CONTEXT_VERSION_MAJOR and GLFW_CONTEXT_VERSION_MINOR hints specify the client API version that the created context must be compatible with.
For OpenGL, these hints are not hard constraints, as they don't have to match exactly, but glfwCreateWindow will still fail if the resulting OpenGL version is less than the one requested.
While there is no way to ask the driver for a context of the highest supported version, most drivers provide this when you ask GLFW for a version 1.0 context.

So "most drivers" would give you what you expected, but this is not guaranteed.
The typical usage is that you specify the minimum version that supports all the features that your code uses. Then you don't care if you get exactly that version, or possibly a higher one. But you know that you will get a failure if the minimum version is not supported.
If you want to dynamically test which version is supported, your best bet is probably to first specify the highest version you can take advantage of, and test the return value of glfwCreateWindow(). If it fails, reduce the version as long as it fails, and call glfwCreateWindow() again, until you reach the minimum version you can run with. Then you can keep track of which version succeeded, or the version reported by glGetString(GL_VERSION), and use that to decide at runtime which features you can use.

A: The version you receive from the glGetString does not mean that functionality is capped at that version. In our experience, we receive a 3.3 context that can do everything that any context from that driver can (I mean 4.2+ version features). You only need to worry about the minimum version you require from the driver.


text:
Q: Many to many с одной и той же моделью Есть таблица warehouses и сущность warehouse, у сущности warehouse может быть несколько партнеров таких же как он сам, вот так:
public class Warehouse
{
    public int Id { get; set; }
    public string Code { get; set; }
    public string Name { get; set; }
    public int CountGate { get; set; }
    public decimal Standart { get; set; }
    public decimal Normal { get; set; }
    public List<Warehouse> FrendlyWarehouses { get; set; }

    public Warehouse()
    {
        FrendlyWarehouses = new List<Warehouse>();
    }
}

Но в таком случае, я получаю ошибки ссылки на самого себя, если я в складе 1 укажу на склад 2, а во 2 укажу на 1. Выход я вижу многие ко многим, если бы вручную в SQL я бы создал таблицу с двумя столбцами WarehouseId, FrendlyWarehouseId. Как мне это сделать с EF Core?
Пытаюсь вот так:
public class Warehouse
{
    public int Id { get; set; }
    public string Code { get; set; }
    public string Name { get; set; }
    public int CountGate { get; set; }
    public decimal Standart { get; set; }
    public decimal Normal { get; set; }
    public List<WarehouseFrendlyWarehouse> FrendlyWarehouses { get; set; }

    public Warehouse()
    {
        FrendlyWarehouses = new List<WarehouseFrendlyWarehouse>();
    }
}
public class WarehouseFrendlyWarehouse
{
    public int WarehouseId { get; set; }
    public int FrendlyWarehouseId { get; set; }

    public Warehouse Warehouse { get; set; }
    public Warehouse FrendlyWarehouse { get; set; }
}

Во время миграции получаю ошибку:

Unable to determine the relationship represented by navigation
  property 'Warehouse.FrendlyWarehouses' of type
  'List'. Either manually configure the
  relationship, or ignore this property using the '[NotMapped]'
  attribute or by using 'EntityTypeBuilder.Ignore' in 'OnModelCreating'

Как правильно поступить, дайте пожалуйста совет.
Дополнил
modelBuilder.Entity<WarehouseFrendly>()
    .HasKey(pr => new { pr.WarehouseId, pr.FrendlyWarehouseId });

modelBuilder.Entity<WarehouseFrendly>()
    .HasOne(pr => pr.FrendlyWarehouse)
    .WithMany(p => p.FrendlyWarehouses)
    .HasForeignKey(pr => pr.FrendlyWarehouseId);

modelBuilder.Entity<WarehouseFrendly>()
    .HasOne(pr => pr.Warehouse)
    .WithMany(r => r.FrendlyWarehouses)
    .HasForeignKey(pr => pr.WarehouseId);


text:
Q: PowerShell command in batch file where double quotes are required inside the command I try to invoke a PowerShell command within a batch file:
powershell -Command "(gc test.txt ) -replace ("~\[","`r`n[") | sc test.txt"

But it always fails with this error:
At line:1 char:29
+ (gc test.txt ) -replace (~\[,`r`n[) | sc test.txt
+                             ~
Missing argument in parameter list.
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordEx
   ception
    + FullyQualifiedErrorId : MissingArgument

I try with single quotes for the replace strings:
powershell -Command "(gc test.txt ) -replace ('~\[','`r`n[') | sc test.txt"

But the backtick escape character is treated like any other text character when it appears within a string enclosed in single quotes.

A: Just escape the double quotes using a backslash:
powershell -Command "(gc test.txt ) -replace (\"~\[\",\"`r`n[\") | sc test.txt"


text:
Q: How do i get a guild by its invite link? discord.js I've been looking all over the internet and I can't find a answer to my question,
I am trying to get a guild by it's invite link, so like I have a discord invite link such as https://discord.com/invite/ainvitecodegoeshere, Now I want my discord.js bot to get it's guild ID with using only the invite code, Is that possible? If so how can I do it?

A: I know its a pretty old post, but you can get the guild ID trough the discord api. You can find a link to the documentation here
If you have the invite link, you can use the api by fetching https://discord.com/api/invites/[code] where [code] is the invite code.
It will return some guild information including the guild ID, even if your bot is not in it. To get the guild object, you can use:
const guild = client.guilds.cache.get('guildID')

A: const Invite = "InviteCode"; // Example: bM2Ae2

client.guilds.cache.forEach(guild => { // Looping through all the guilds your bot is in.
    guild.fetchInvites().then(invites => { // Fetching the invites of the guild.
        invites.forEach(invite => { // Looping through all the invites of the guild.
            if (invite.code == Invite) { // Checking if the invite code matches.
                message.channel.send(`Found guild : ${guild.name} | ${guild.id}`);
            }
        })
    })
});

I'd personally use a plain loop instead since you cannot stop the .forEach() loop, and it'll continue to loop through guilds even after it finds the guild you're looking for.
Note: Your bot must be in  the guild you want to find.


text:
Q: Derived class should call static methods of base class but with overriden property How do I do that?
The scenario:
abstract class DataAccess
{
    public abstract string ConnectionString { get; set; }

    public static DataTable ExecuteSql(string sql)
    {
        // ...
    }

    public static object ExecuteStoredProc(string storedProcName, ...)
    {
        // ...
    }
}

abstract class DataAccessDb1 : DataAccess
{
    public override string ConnectionString = "SetDbSpecificConnectionStringHere";

    public static DataTable GetStuff()
    {
        // Call the method with the ConnectionString set HERE.
        return ExecuteSql("select * from stuff");
    }
}

I know it's know possible to set the connection string like in the derived class, but I want to keep it static, therefore I won't set the property in every method in the derived class... Any ideas?

A: Yes: pass the connection string in as a parameter into the method.

*

*Fields don't behave polymorphically, so the declaration in DataAccessDb1 is invalid

*static and polymorphism don't mix

So basically, if you want polymorphic behaviour, you should be using instance members. If you don't really need polymorphic behaviour, pass any variations (such as the connection string) as a parameter for the method.

A: There is no static inheritance in C# so your goal of having the ConnectionString has a static member and override it won't work. Rethink your design - having ConnectionString as static really says this field should be the same on all your DataAccess instances since it is defined on the type itself.
Is there a particular reason you use static methods - using instance methods and setting the connection string in the constructor would work:
public class DataAccessDb1
{
    public string ConnectionString {get;set;}

    public DataAccessDb1()
    {
        ConnectionString = "SetDbSpecificConnectionStringHere";
    }

    public void DataTable GetStuff()
    {
        return DataAccess.ExecuteSql(ConnectionString, "select * from stuff");
    }
}

A: What I think that you should only have a ExecuteSql method in the abstract class and all derived classes would implement ExecuteSql with their respective connection string,
    public abstarct string ConnectionString{get;set;}

can be removed from the base class.


text:
Q: Make sure this class is defined as a service and tagged with "doctrine.fixture.orm" I'm trying to debug my fixtures on Symfony and I have this error:
 The "App\Entity\Mappool" fixture class is trying to be loaded, but is not available. Make sure t
his class is defined as a service and tagged with "doctrine.fixture.orm".
My entity
namespace App\Entity;

use App\Repository\MappoolRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity(repositoryClass=MappoolRepository::class)
 */
class Mappool
{
    /**
     * @ORM\Id
     * @ORM\GeneratedValue
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $name;

    /**
     * @ORM\Column(type="string", length=255, nullable=true)
     */
    private $thumbnail;

    /**
     * @ORM\Column(type="integer")
     */
    private $follow;

    /**
     * @ORM\Column(type="datetime")
     */
    private $updated_at;

    /**
     * @ORM\Column(type="datetime")
     */
    private $created_at;

    /**
     * @ORM\OneToMany(targetEntity=MappoolMap::class, mappedBy="mappool")
     */
    private $mappoolMaps;

    /**
     * @ORM\OneToMany(targetEntity=Step::class, mappedBy="mappool")
     */
    private $steps;

    /**
     * @ORM\ManyToOne(targetEntity=PoolSet::class, inversedBy="mappools")
     * @ORM\JoinColumn(nullable=false)
     */
    private $poolSet;

    /**
     * @ORM\OneToMany(targetEntity=MappoolFollowed::class, mappedBy="mappool", orphanRemoval=true)
     */
    private $mappoolFolloweds;

    /**
     * @ORM\ManyToOne(targetEntity=Contributor::class, inversedBy="mappools")
     */
    private $Contributor;

    public function __construct()
    {
        $this->mappoolMaps = new ArrayCollection();
        $this->steps = new ArrayCollection();
        $this->mappoolFolloweds = new ArrayCollection();
    }

    public function getId(): ?int
    {
        return $this->id;
    }

    public function getName(): ?string
    {
        return $this->name;
    }

    public function setName(string $name): self
    {
        $this->name = $name;

        return $this;
    }

    public function getThumbnail(): ?string
    {
        return $this->thumbnail;
    }

    public function setThumbnail(?string $thumbnail): self
    {
        $this->thumbnail = $thumbnail;

        return $this;
    }

    public function getFollow(): ?int
    {
        return $this->follow;
    }

    public function setFollow(int $follow): self
    {
        $this->follow = $follow;

        return $this;
    }

    public function getUpdatedAt(): ?\DateTimeInterface
    {
        return $this->updated_at;
    }

    public function setUpdatedAt(\DateTimeInterface $updated_at): self
    {
        $this->updated_at = $updated_at;

        return $this;
    }

    public function getCreatedAt(): ?\DateTimeInterface
    {
        return $this->created_at;
    }

    public function setCreatedAt(\DateTimeInterface $created_at): self
    {
        $this->created_at = $created_at;

        return $this;
    }

    /**
     * @return Collection|MappoolMap[]
     */
    public function getMappoolMaps(): Collection
    {
        return $this->mappoolMap;
    }

    public function addMappoolMap(MappoolMap $mappoolMap): self
    {
        if (!$this->mappoolMaps->contains($mappoolMap)) {
            $this->mappoolMaps[] = $mappoolMap;
            $mappoolMap->setMappool($this);
        }

        return $this;
    }

    public function removeMappoolMap(MappoolMap $mappoolMap): self
    {
        if ($this->mappoolMaps->removeElement($mappoolMap)) {
            // set the owning side to null (unless already changed)
            if ($mappoolMap->getMappool() === $this) {
                $mappoolMap->setMappool(null);
            }
        }

        return $this;
    }

    /**
     * @return Collection|Step[]
     */
    public function getSteps(): Collection
    {
        return $this->steps;
    }

    public function addStep(Step $step): self
    {
        if (!$this->steps->contains($step)) {
            $this->steps[] = $step;
            $step->setMappool($this);
        }

        return $this;
    }

    public function getPoolSet(): ?PoolSet
    {
        return $this->poolSet;
    }

    public function setPoolSet(?PoolSet $poolSet): self
    {
        $this->poolSet = $poolSet;

        return $this;
    }

    /**
     * @return Collection|MappoolFollowed[]
     */
    public function getMappoolFolloweds(): Collection
    {
        return $this->mappoolFolloweds;
    }

    public function addMappoolFollowed(MappoolFollowed $mappoolFollowed): self
    {
        if (!$this->mappoolFolloweds->contains($mappoolFollowed)) {
            $this->mappoolFolloweds[] = $mappoolFollowed;
            $mappoolFollowed->setMappool($this);
        }

        return $this;
    }

    public function removeStep(Step $step): self
    {
        if ($this->steps->removeElement($step)) {
            // set the owning side to null (unless already changed)
            if ($step->getMappool() === $this) {
                $step->setMappool(null);
            }
        }

        return $this;
    }

    public function removeMappoolFollowed(MappoolFollowed $mappoolFollowed): self
    {
        if ($this->mappoolFolloweds->removeElement($mappoolFollowed)) {
            // set the owning side to null (unless already changed)
            if ($mappoolFollowed->getMappool() === $this) {
                $mappoolFollowed->setMappool(null);
            }
        }

        return $this;
    }

    public function getContributor(): ?Contributor
    {
        return $this->Contributor;
    }

    public function setContributor(?Contributor $Contributor): self
    {
        $this->Contributor = $Contributor;

        return $this;
    }
}

My Fixture
<?php

namespace App\DataFixtures;

use App\Entity\Mappool;
use Doctrine\Bundle\FixturesBundle\Fixture;
use Doctrine\Common\DataFixtures\DependentFixtureInterface;
use Doctrine\Persistence\ObjectManager;

class MappoolFixtures extends Fixture implements DependentFixtureInterface
{
    public function load(ObjectManager $manager)
    {
        for($i = 0; $i < 10; $i++){
            $mappool = new Mappool();
            $date = new \DateTime();
            $date->setDate(2021, 12 , 1 + $i);
            $mappool->setName('name_' . $i);
            $mappool->setThumbnail('thumbnail_' . $i);
            $mappool->setFollow($i);
            $mappool->setUpdatedAt($date);
            $mappool->setCreatedAt($date);
            $mappool->setPoolSet($this->getReference('poolSet_' . $i));
            $mappool->setContributor($this->getReference('contributor_' . $i));
            $manager->persist($mappool);
            $this->addReference('mappool_' . $i, $mappool);
        }
        $manager->flush();
    }

    public function getDependencies()
    {
        return [
            ContributorFixtures::class,
        ];
    }
}

For dependencies, I just follow error message to generate them (I don't understand how doctrine read fixtures).

A: After some research, it was my fault  :
i use
Mappool::class
instead of
MappoolFixtures::class
on
 getDependencies()


text:
Q: How to retrieve the Description property from SettingsProperty? For each item in my application's settings, I've added text to its Description Property which I want to retrieve at runtime. I'm sure I'm missing some basic logical nuance here, but everything I've tried has failed. Clearly, my understanding of what value needs to be passed to the Attributes property of the SettingsProperty class is wrong. I'm further confused by the fact that when I iterate through all they keys returned by SettingsProperty.Attributes.Keys, I can see "System.Configuration.SettingsDescriptionAttribute", but when I pass that string in as the key to the Attributes property, null is returned.
Any insight into how to properly retrieve the value Description Property would be very much appreciated. Thanks. :)
public void MyMethod()
    {
        SettingsPropertyCollection MyAppProperties =
            Properties.Settings.Default.Properties;

        IEnumerator enumerator = MyAppProperties.GetEnumerator();

        // Iterate through all the keys to see what we have....
        while (enumerator.MoveNext())
        {
            SettingsProperty property = (SettingsProperty)enumerator.Current;
            ICollection myKeys = property.Attributes.Keys;

            foreach (object theKey in myKeys)
                System.Diagnostics.Debug.Print(theKey.ToString());
                // One of the keys returned is:
                   System.Configuration.SettingsDescriptionAttribute
        }

        enumerator.Reset();

        while (enumerator.MoveNext())
        {
            SettingsProperty property = (SettingsProperty)enumerator.Current;

            string propertyValue = property.DefaultValue.ToString();

            // This fails: Null Reference
            string propertyDescription =
                property.Attributes["System.Configuration.SettingsDescriptionAttribute"].ToString();

            // Do stuff with strings...
        }
    }

A: This code showed all settings that have a description:
using System;
using System.Configuration;
using System.Reflection;

namespace ConsoleApplication1 {
  class Program {
    static void Main(string[] args) {
      var all = typeof(Properties.Settings).GetProperties();
      foreach (var prop in all) {
        var attr = (SettingsDescriptionAttribute[])prop.GetCustomAttributes(typeof(SettingsDescriptionAttribute), false);
        if (attr.Length > 0)
          Console.WriteLine("{0}: {1}", prop.Name, attr[0].Description);
      }
      Console.ReadLine();
    }
  }
}

A: You're trying to get a value from a HashTable by its key, but you're using the wrong key. (I guess the hashtable uses the hashvalue of the attribute itself as the key)
This change to your code demonstrates:
    public void MyMethod()
    {
        SettingsPropertyCollection MyAppProperties =
            Properties.Settings.Default.Properties;

        IEnumerator enumerator = MyAppProperties.GetEnumerator();

        // Iterate through all the keys to see what we have....
        while (enumerator.MoveNext())
        {
            SettingsProperty property = (SettingsProperty)enumerator.Current;
            ICollection myKeys = property.Attributes.Keys;

            foreach (object theKey in myKeys)
            {
                if (property.Attributes[theKey].GetType().Name == "SettingsDescriptionAttribute")
                {
                    SettingsDescriptionAttribute sda = property.Attributes[theKey] as SettingsDescriptionAttribute;
                    System.Diagnostics.Debug.Print(sda.Description); // prints the description
                }
            }
        }

    }

A: The problem is that the key into the Attributes[] indexer does not take a string.
Try this:
    public void MyMethod()
    {
        SettingsPropertyCollection MyAppProperties =
            Properties.Settings.Default.Properties;

        IEnumerator enumerator = MyAppProperties.GetEnumerator();
        object settingsDescriptionAttribute = null;

        // Iterate through all the keys to see what we have....
        while (enumerator.MoveNext())
        {
            SettingsProperty property = (SettingsProperty)enumerator.Current;
            ICollection myKeys = property.Attributes.Keys;

            foreach (object theKey in myKeys)
            {
                System.Diagnostics.Debug.Print(theKey.ToString());
                if (theKey.ToString() == "System.Configuration.SettingsDescriptionAttribute")
                    settingsDescriptionAttribute = theKey;
            }
        }

        enumerator.Reset();

        while (enumerator.MoveNext())
        {
            SettingsProperty property = (SettingsProperty)enumerator.Current;

            string propertyValue = property.DefaultValue.ToString();

            // This fails: Null Reference
            string propertyDescription =
                property.Attributes[settingsDescriptionAttribute].ToString();

            // Do stuff with strings...
        }
    }


text:
Q: Calculating the area of classified pixels in google earth engine The code of my problem is as follows:
var image = ee.Image(sent2
 .filterBounds(geometry2)
 .filterDate('2016-01-01', '2016-03-31')
 .sort("CLOUD_COVERAGE_ASSESSMENT")
 .first());

// print the image to the console.

    print("A Sentinel-2 scene:", image);

Clip a geometry of study area
var image1=image.clip(geometry2)

//merging the feature collection collected

var newfc = forest.merge(gram2).merge(baresoil).merge(wheat2).merge(mustard2);

var bands = [ 'B8', 'B4', 'B3'];

var training = image1.select(bands).sampleRegions({collection: newfc, properties: ['landcover'], scale: 10});

Train the classifier using CART
var classifier = ee.Classifier.cart().train({features: training, classProperty: 'landcover', inputProperties: bands});

Run the classification
var classified = image1.select(bands).classify(classifier);

Map.addLayer(classified, {min: 0, max: 4, palette: '0D5D07','B47610','F7C537','7CE72E','EFF60E']},'classification');

//0 forest 1 baresoil 2 gram 3 wheat 4 mustard
var PIXEL_SCALE = 10; // Meters. Resolution of most sentinel bands

var PIXEL_AREA = PIXEL_SCALE * PIXEL_SCALE; // Square meters.

Calculate the number of pixels of each classification in our polygon
var regionCoverHistogram = image1.select('classifier') .reduceRegion(ee.Reducer.frequencyHistogram(), geometry2, PIXEL_SCALE);

print('classified class pixel count within region', regionCoverHistogram);

var wheatPixelCount =ee.Dictionary(regionCoverHistogram.get('wheat2')).get(wheat2.toString());

var wheatArea = ee.Number(wheatPixelCount).multiply(PIXEL_AREA);

print('Wheat Area (sq meters) in region', wheatArea);

showing error as follows:

classified class pixel count within region
  Dictionary (Error)
  Image.select: Pattern 'classifier' did not match any bands.
  Wheat Area (sq meters) in region
  Number (Error)
  Image.select: Pattern 'classifier' did not match any bands.

A: Without the script it will be difficult to tell but my guess would be that the band('classifier) you are trying to select for your histogram is not inside image1 but inside your result image: 'classified'.
Change image1 to classified would be a first suggestion.


text:
Q: Does the Landau-Lifshitz pseudotensor contain all non-linear terms in $h_{\mu\nu}$? I was recently reading up some literature on gravitational waves in curved spaces and came across the following confusion. Basically starting from the Einstein Field Equation (EFE),
$$G_{\mu\nu} = 8\pi T_{\mu\nu}$$
we can expand it in powers of $h_{\mu\nu}$ (where $g_{\mu\nu} = \eta_{\mu\nu} + h_{\mu\nu}$) as,
$$G^{(1)}_{\mu\nu} = 8\pi (T_{\mu\nu} + t_{\mu\nu})$$
where $t_{\mu\nu}$ is the LL pseudotensor and $G^{(1)}_{\mu\nu}$ contains only linear terms in $h$.
My question is starting from the definition of the Landau-Lifschitz pseudotensor, i.e.
$$t_{\mu\nu} = -\frac{1}{8\pi}G_{\mu\nu} + \frac{1}{16\pi}\{(-g)(g_{\mu\nu}g_{\alpha\beta} - g_{\mu\alpha}g_{\nu\beta})\},^{\alpha\beta}.$$
How is it evident that $t_{\mu \nu}$ contains all the higher powers of $h_{\mu\nu}$? Any hint whatsoever will be appreciated.
Note: Had the last expression looked like $G_{\mu\nu}$ minus the linear terms in $g_{\mu\nu}$ (or $h_{\mu\nu}$), it would have been easier to conclude possibly.
Edit 1: In case it is not clear, I want to understand mathematically how all terms in the LL pseudotensor are quadratic or higher in the metric and connections.

A: The physics of the pseudo- tensor is quite independent of the weak field decomposition of the metric ($g_{\mu \nu}= \eta_{\mu \nu} +h_{\mu \nu}$). So, for the time being, lets forget about the decomposition and focus of the pseudo-tensor itself.
The key facts about the quantity
$$\tilde{t}^{\mu \nu}=\frac{1}{16\pi}  \partial_\alpha \partial_{\beta} \left[(-g) (g^{{\mu \nu}}g^{{\alpha \beta}}-g^{{\mu \alpha}}g^{{\nu \beta}} )\right]  $$
are:

*

*Its automatically (ordinarily, not covariantly) conserved as an identity owing to $\mu, \alpha$ antisymmetry.

*It reduces to $\frac{G^{\mu \nu}}{8\pi}$ in Riemann Normal Coordinates(RNC).

Remember, that in RNC, there are no gravitational waves, and no energy, momentum associated with gravity. Therefore in RNC, since $\frac{G^{\mu \nu}}{8\pi}$ is exactly equal to $T^{\mu \nu}_\text{matter}$ (by Einstein's equations) and there is there is no energy, momentum associated with gravity, this is also the full energy momentum tensor in RNC.
Now, LL define $\tilde{t}^{\mu \nu}$ to be the full energy momentum pseudo tensor (accounting for matter+gravity), in arbitrary frames. The motivation for this is:

*

*It is ordinarily conserved and therefore obeys ordinary conservation laws.

*Since it is a two derivative quantity, its integral over all space lives at spatial infinity (by successive application of integration theorems relating volume integration to surface integrals)

*Assuming asymptotically flat space, it is a tensor at spatial infinity, under Lorentz transformations.

Now, turning to your question. You have defined the quantity
$$t^{\mu \nu}= \tilde{t}^{\mu \nu} - \frac{G^{\mu \nu}}{8 \pi}$$
This equation, intuitively reads:
$$t^{\mu \nu} =T^{\mu \nu}_\text{full}- T^{\mu \nu}_\text{matter}$$.
$t^{\mu \nu}$ is therefore the energy momentum tensor associated with gravity. It needs to be fully non linear as you have pointed out.
With indices up, its clear how this quantity is non linear in $h_{\mu \nu}$:

*

*$G^{\mu \nu}$ is the full Einstein tensor and has an infinite expansion in $h$

*$(-g)$ has an infinite expansion in $h$.

*$g^{\mu \nu}$ is the inverse of $g_{\mu \nu}$ and therefore has an infinite expansion in $h$.

A: If you're making the assumption $$g_{\mu\nu}=\eta_{\mu\nu}+h_{\mu\nu}$$ then its very easy Landau, Lifshitz already gave us the ready to substitute formulae ($101.6$ in Vol2)  here
Because of the above assumption $$\Gamma^{\alpha}_{\mu\nu}=\frac{1}{2}\eta^{\alpha\rho}(\partial_{\mu}h_{\nu\rho}+\partial_{\nu}h_{\mu\rho}-\partial_{\rho}h_{\mu\nu})$$
where higher order terms are dropped.
Now $\Gamma=O(1)$ just looking at $101.6$ gives $$t^{\mu\nu}=(O(1)\times O(1))(O(0)+O(1))+l.c.$$
clearly $$t^{\mu\nu}=O(2)\times (O(0)+O(1))$$
so in no way it can have $O(1)$ terms in $h_{\mu\nu}$. That's it!
Just a heads up the original formulae given Landau book is for curved background $g_{\mu\nu}=g_{\mu\nu}^{B}+h_{\mu\nu}$ so if we have to show the above result we have to do a bit longer calculation, $\Gamma$ will have two contributing terms of zeroth and first order, the computation will require $30$ terms in total to be calculated $((6+2+2)\times3)$ which will be of order $1$ and they have to add up to zero which is really a non-trivial result. Let's hope someone by the time this bounty ends come up with a clever way to calculate those 30 terms or with some other solution.

A: You can check my blog post for all the mathematical details of the derivation of the LL pseudotensor. Basically, it's not a decomposition of the metric in higher or lower order terms. It is a separation of first from second derivatives. The local stress-energy tensor is so constructed from the Einstein tensor that it becomes a second derivative of an antisymmetric tensor which in the locality should turn to zero (see the LL book, chapter 96). In the process of its construction all first derivatives are ignored (see the detailed derivation in my post). However, in the general non-local case, this construct does not turn to zero and the difference contains all first derivatives but does not contain the second derivatives. This difference is namely the LL pseudotensor. It can be expressed in several different ways: as metric derivatives (16 terms), as Christiffels (16 terms), or as metric density derivatives (10 terms).


text:
Q: Summation of binomial coefficients multiplied by their index
$\sum_{r=0}^{300}a_rx^r = (1+x+x^2+x^3)^{100}.$ If $a= \sum^{300}_{r=0}a_r$ then $\sum_{r=0}^{300}ra_r =?  $
a) $300a$
b) $100a$
c) $150a$
d) $75 a$

Attempt:
First of all if we substitute $x=1$, we get $a= 4^{100}$
Then, using formula of summation of geometric progression:
$\sum_{r=0}^{300}a_rx^r= (1-x^4)^{100}(1-x)^{-100}$
Using generalised binomial theorem, coefficient of $x^r$ in $(1-x)^{-100}$ is $\dbinom{99+r}{r}$ and that of $x^{4r}$ in $(1-x^4)^{100}$ is $(-1)^{100-r}\dbinom{n}{r}$
What do I do after this?

A: You have been given
$$\sum_{r=0}^{300}a_rx^r = (1+x+x^2+x^3)^{100}$$
substitute $x = 1 $ to get $a = \sum a_r = 4^{100}$
Differentiate once w.r.t $x$ to get
$$\sum_{r=0}^{300}ra_rx^{r-1} = 100(1+x+x^2+x^3)^{99} (1+2x+3x^2)$$
again substitute $x = 1$ to get $\sum ra_r = 4^{99} \cdot 100  \cdot 6 = 150a$

A: Hint
$$f(x)=\sum_{r=0}^{300} a_rx^r=(1+x+x^2+x^3)^{100}$$
$$f'(x)=\sum_{r=0}^{300} ra_rx^{r-1}=100(1+x+x^2+x^3)^{99}(1+2x+3x^2)$$
$$f'(1)=\sum_{r=0}^{300} ra_r=600\cdot 4^{99}=150\cdot 4^{100}$$
We also have $$a=f(1)=\sum_{r=0}^{300} a_r=4^{100}$$


text:
Q: How to count the number of terms in a taxonomy I have a custom post type "Services".  It has a hierarchal taxonomy of "service-category".  Service-category has both parent and child terms.
I need to count the number of parent terms in the taxonomy.  NOT posts.  The # of terms in the taxonomy is being used in my code to layout the page in a recursive loop.
Everything I have researched is about the number of posts per term, not the number of terms in the taxonomy..  I am sure I am missing an obvious way of doing this, but I haven't run across it.
Thanks in advance for your help!

A: As @shanebp suggests, you could use wp_count_terms() like this:
$numTerms = wp_count_terms( 'service-category', array(
    'hide_empty'=> false,
    'parent'    => 0
) );

The above will list All top parent terms, empty or not. This function uses get_terms() functions arguments which can be found in the link or the arguments below:
$args = array(
    'orderby'           => 'name',
    'order'             => 'ASC',
    'hide_empty'        => true,
    'exclude'           => array(),
    'exclude_tree'      => array(),
    'include'           => array(),
    'number'            => '',
    'fields'            => 'all',
    'slug'              => '',
    'parent'            => '',
    'hierarchical'      => true,
    'child_of'          => 0,
    'get'               => '',
    'name__like'        => '',
    'description__like' => '',
    'pad_counts'        => false,
    'offset'            => '',
    'search'            => '',
    'cache_domain'      => 'core'
);

A: Try this. Untested but should work -- get_the_terms returns an array with each term, and then sizeof() counts it, returning an integer. The variable $number will return an integer corresponding to the number of terms.
$terms = get_the_terms ( $post->ID, 'service-category' );
$number = sizeof ($terms);
echo $number;

if ( $number == XX ) {
// do something
}


text:
Q: What does it mean by saying "It is impossible to recover from errors" in java? Here says that it is impossible to recover from errors.
I am not sure what does it mean because I can catch Error just like Exception.
Eg:
public static void main(String args[]) {
    while (true) {
        try {
            throw new StackOverflowError("stackoverflow");
        } catch (Throwable throwable) {
            //do something
        }
        //program recover and continue to execute
    }
}

The above program execute normally and It seems that It's possible to recover from errors. Can anyone help?
UPDATE:
example of stackoverflow is a little puzzling, only idiot want to recover from stackoverflow. Here is another example about OutOfMemory:
public class Main {
    public static Map<Long, Object> cache = null;
    public static void main(String args[]){
        while(true){
            try {
                if(cache == null) {
                    cache = new HashMap<>();
                }
                for (long i = 0; i < Long.MAX_VALUE; ++i) {
                    cache.put(i, i);
                }
            }catch(OutOfMemoryError error) {
                cache.clear();//delete some unused entry or clear all.
                cache = null;
                System.gc();
                System.out.println("release memory");
            }
        }
    }
}

It's a simple HashMap cache, execute the code using java -Xmx1m Main , and we will see an OutOfMemoryError soon, then release memory manually, and the program will continue to execute. insert-> OutOfMemoryError -> release -> insert...
See? the program have recovered from an OutOfMemoryError. Isn't it? And I think it's meaningful. So, Why someone still said program can't recover from OutOfMemoryError.

A: Obviously, the mere ability to "catch" an exception does not mean that you will (always ...) be able to "recover from" it ...
... i.e.:   "to sally forth, entirely unscathed, as though 'such an inconvenient event' never had occurred in the first place."
I think that the essential point of the original author is more-or-less that:   Even though the poor souls on the Titanic might have "caught" the fact that their ship was sinking, there was nothing that they could do to "recover" the ship and to sail it on unscathed to New York.
--- Edit:
"Now, let me add one more thought!" (As other Answerers have also done here.) Sometimes, an Error Exception is intentionally "thrown" in some block of code that has intentionally been surrounded by a catch-block.
Maybe the error (which is itself "an object") is of a particular user-defined type that the catcher will recognize. (He can "re-throw" any that he does not recognize, or simply decline to catch it.) This can be a very elegant and efficient way to handle, well, "the exceptions to the rule." (Hence the name...)
Whenever a block of code encounters a situation that "only happens once in a blue moon, but it just did," it can throw an exception high into the air, knowing that the nearest catcher will catch it. This catcher, in turn, can recognize the thing that just landed into his baseball-mitt, and respond accordingly. There can be any number of "catchers" out there, looking for different things.
This strategy is not "an Error," but rather an intentional alternative flow-of-control within the program.

A: Consider the following code which actually throws a StackOverflowError
public class Code
{
    public static void main(String[] args)
    {
        try
        {
            f();
        }
        catch (Throwable t)
        {
            System.out.println("OK I'm recovered, let me try that again");

            try
            {
                f();
            }
            catch (Throwable t2)
            {
                System.out.println("What's going on here??");

                // let me try one more time..
                try
                {
                   f();
                }
                catch (Throwable t3)
                {
                     System.out.println("Why can't I really recover");
                }
            }
        }

    }

    // Bad recursion...
    private static void f()
    {
        f();
    }
}

Do you really want to continue with execution knowing that your code has such an issue? What if you need to call f() again somewhere down the line? You would want to have such code in production that tries to continue if a method keeps giving a StackOverflowError?

A: You're just catching the Throwable here, before it ever gets to the point where it's an error. Throwable is the superclass of both errors and exceptions. Therefore, a Throwable is not comparable to an error itself, much less a StackOverflowError, and your program is not recovering from an error.
An exception is sort of like a misdemeanor charge. It's not a fantastic thing to happen to you, or rather, your program, but it definitely won't land you in jail for extended periods of time. However, an error is dangerous - it is on the level of a felony, to continue this analogy. Java is considered safer than, say, C, because it will tell you when you are doing something that is unsafe. C, on the other hand, will allow you to access data that is beyond the scope of an array, for example, and you'll get awful bugs that are very difficult to debug that way.
The analogy to crime ends after that point. If you had scrolled down a little further on the page that you linked to, it continues to delineate the reasons why exceptions and errors are different, namely, that "errors are caused by the environment in which the application is running," and therefore, because your application is only in charge of itself, and not the actual environment, it cannot of its own volition recover from an error.
The page also gives the example of an OutOfMemoryError. While you, as the programmer, can plan ahead to try to prevent an OutOfMemoryError by making your code as efficient as you can, you won't be able to prevent such an error if the code is run on a machine that has, say, 1 byte of RAM. Errors cannot be caught because they are (mostly) out of the hands of the application itself. It's up to the programmer, such as in Michael Markidis' example, to not cause an error and avoid any error-causing programming techniques (such as using "Bad recursion") that will crash your program.


text:
Q: Why AbstractList class implement set() method Why does AbstractList class implements set(int index, E element) method? All it does is, it throws UnsupportedOperationException.
However, All childs of it(ArrayList,LinkedList,Vector) implements(overrides) this method and provides its logic for the operation. Why is this method implemented by AbstactList at all, if all classes extending AbstractList provides its own logic.

A: It's done for descendants classes that implement List interface.
For example utility Arrays.ArrayList class which is created by asList method
List<Integer> readOnly = Arrays.asList(1, 2, 3);

does not allow to modify the list, so it's set(int index, E element) method throws UnsupportedOperationException. This default behaviour is implemented in AbstractList class.


text:
Q: Stripe checkout with custom form symfony I have a checkout form that I am using to send shopping cart details to different payment gateways like paypal using Symfony and Payum.
Now I am trying to send payment details to stripe in case user selects stripe checkout option. At the moment the integration with stripe is working fine, i can send the payment and get the response from stripe however in order to send credit card details to stripe i get redirected to capture

where i see the "pay with card" button and if i click on it the popup appears to enter credit card details

What I would like to do is allow user to add credit card details on checkout form that I have rather than the form you see on popup. Is it possible to achieve this? How can i use my own form to send data to stripe rather than using stripe popup?
I found a close example of the process in this and this example. Is there any example for stripe? Any help will be greatly appreciated.

A: This is an example for stripe In Javascript:
Including Stripe.js
<script type="text/javascript" src="https://js.stripe.com/v2/"></script>

Setting your publishable key :
Stripe.setPublishableKey('YOUR_PUBLISHABLE_KEY');

send data :
    Stripe.card.createToken({
      number: $('.card-number').val(),
      cvc: $('.card-cvc').val(),
      exp_month: $('.card-expiry-month').val(),
      exp_year: $('.card-expiry-year').val()
    }, stripeResponseHandler);

response :
function stripeResponseHandler(status, response) {
  var $form = $('#payment-form');

  if (response.error) {
    // Show the errors on the form
    $form.find('.payment-errors').text(response.error.message);
    $form.find('button').prop('disabled', false);
  } else {
    // response contains id and card, which contains additional card details
    var token = response.id;
    // Insert the token into the form so it gets submitted to the server
    $form.append($('<input type="hidden" name="stripeToken" />').val(token));
    // and submit
    $form.get(0).submit();
  }
}

for more detail check this link
https://stripe.com/docs/stripe.js

A: Stripe Checkout is designed this way. You see the button click it, fill all the required info and that's it.
If you want to fill credit card details earlier you can do that, but in that case you have to use

*

*Stripe "direct". Implemented in Omnipay and used via Omnipay Bridge

*You have to pass omnipay credit cards like this (better way is not implemented yet):
$order->setDetails(array(
  'card' => new CreditCard($data),
));

*

*and use $this->forward instead of redirect. Because credit card is not saved to database you have to process them immediately. (example)


text:
Q: Finding the cycle in a directed graph I was solving a problem to determine whether a graph contains a cycle. I solved it using the coloring method (in the visited array I will mark, 0 if it has never visited, 1 if it is visited, and 2 if the tour of vertex is done)
for this I wrote the code:
#include <bits/stdc++.h>
using namespace std;

vector<int> adj[20005];
int vis[20005];
int chk = 0;
void dfs(int u){
    if(vis[u]==1) {
        chk = 1;
        return;
    }
    if(vis[u]==2) return;
    vis[u] = 1;
    for(auto v:adj[u]) dfs(v);
    vis[u] = 2;
}

int main(){
    int N, M; cin>>N>>M;
    for(int i = 0; i<M; i++){
        int p, q; cin>>p>>q;
        adj[p].push_back(q);
    }
    for(int i = 1; i<=N; i++){
        if(vis[i]==1) break;
        if(!vis[i]) dfs(i);
    }
    cout<<(chk?"Yes\n":"No\n");
}

Now, I'm thinking, if there's a way to write the cycle which has been detected. I know most people will say DFS and backtracking and it's very intuitive. But want to know how do I implement it.

A: par[v] - parent node of v, pr - previously visited node:
void dfs(int u, int pr = -1){
    if(vis[u]==1) {
        vector<int> cycle();
        int cur = pr;
        while(cur != u) {
            cycle.push_back(cur);
            cur = par[cur]
        }
        cycle.push_back(u);
        chk = 1;
        return;
    }
    if(vis[u]==2) return;
    vis[u] = 1;
    par[u] = pr;
    for(auto v:adj[u]) dfs(v, u);
    vis[u] = 2;
}


text:
Q: Run Windows command After File Copy I want to copy files (inputs given by user) into installed folder at the end. I believed this command would work -
Filename: "cmd.exe"; Parameters: "cp {code:GetClientPrivatePEM} {code:GetServerPublicPEM} ."; WorkingDir: "{app}\trust"; Flags:

But it does't copy and is stuck. However, I can see the output in the logs.
Is there any problem with syntax? How do I fix this?
One possible problem that can arise is if the {code:GetClientPrivatePEM} or {code:GetServerPublicPEM} has space. How do I handle that? (Current input doesn't have space)
The other way of copying that I thought of was  -
[Files]
 Source: "C:\Users\pnarendr\Desktop\API_DAST\*"; DestDir: "{app}"; Flags: ignoreversion recursesubdirs createallsubdirs
; NOTE: Don't use "Flags: ignoreversion" on any shared system files
;Source: "C:\Users\pnarendr\Desktop\output.log"; DestDir: "{code:GetPythonHome}";
Source: "{code:GetServerPublicPEM}"; DestDir: "{app}\trust"; Flags: external ignoreversion recursesubdirs createallsubdirs
Source: "{code:GetClientPrivatePEM}"; DestDir: "{app}\trust"; Flags: external ignoreversion recursesubdirs createallsubdirs

But this says that {code:GetServerPublicPEM} is in accessible. Not Sure how

A: The problem in the function - GetServerPublicPEM. In case the Page isnt assigned, send a default value.  Example
function GetUserID(Param: String) : string;
begin
  if Assigned(InputValuesPage) then
    Result := InputValuesPage.Values[3]
  else
    Result := '';
end;


text:
Q: Change a color of a certain line in d3.js I have implemented a network with d3.js in javascript and I would like to change a color of a link from grey to red according to a json received. The JSON shows the source and the target node that will be connected. The schema of the nodes architecture is the one below:

Now, when the JSON is received, I parse the data and I append a new line connecting the source and the target node to red with the code below:
       svg.selectAll()
          .data(data.links)
          .enter()
          .append("line")
          .attr("x1", function(d) { return nodes[source].x; })
          .attr("y1", function(d) { return nodes[source].y; })
          .attr("x2", function(d) { return nodes[target].x; })
          .attr("y2", function(d) { return nodes[target].y; })
          .attr("stroke","#b72b34")
          .attr("stroke-width", 2)

Then, after 2secs I use the same code to change again the color of the line to grey.
Is there another more easier way to do it?
The result that I have now is:

As you can see the user is able to see the lines added in the past, though this is not the wanted image. I want only to change the color of the existing links (as shown in schema 1).
Thank you in advance.
My code:
var nodes = [
 { x:   width/2, y: height/4, id: 0, url: "http://icons.iconarchive.com/icons/icons-land/vista-hardware-devices/128/Computer-icon.png"},
 { x:   60, y: height-150, id: 1, url: "http://icons.iconarchive.com/icons/icons-land/vista-hardware-devices/128/Computer-icon.png"},
 { x:   width-100, y: height-150, id: 2, url: "http://icons.iconarchive.com/icons/icons-land/vista-hardware-devices/128/Computer-icon.png"},
 { x:   60, y: height-50, id: 3, url: "http://icons.iconarchive.com/icons/icons-land/vista-hardware-devices/128/Computer-icon.png"},
 { x:   width-100, y: height-50, id: 4, url: "http://icons.iconarchive.com/icons/icons-land/vista-hardware-devices/128/Inkjet-Printer-icon.png"}
  ];

  var links = [
  { source: 1, target: 2 },
  { source: 1, target: 3 },
  { source: 1, target: 4 },
  { source: 1, target: 0 },
  { source: 2, target: 3 },
  { source: 2, target: 1 },
  { source: 2, target: 4 },
  { source: 2, target: 0 },
  { source: 3, target: 4 },
  { source: 3, target: 1 },
  { source: 3, target: 2 },
  { source: 3, target: 0 },
  { source: 4, target: 1 },
  { source: 4, target: 2 },
  { source: 4, target: 3 },
  { source: 4, target: 0 },
  { source: 0, target: 1 },
  { source: 0, target: 2 },
  { source: 0, target: 3 },
  { source: 0, target: 4 },
  ];

  svg.selectAll()
     .data(links)
  .enter()
  .append("line")
   .attr("x1", function(d) { return nodes[d.source].x; })
   .attr("y1", function(d) { return nodes[d.source].y; })
   .attr("x2", function(d) { return nodes[d.target].x; })
   .attr("y2", function(d) { return nodes[d.target].y; })
   .attr("stroke-width", function (d) { return Math.sqrt(d.value); })
   .attr("stroke","#f6f6f6")
   svg.selectAll()
    .data(nodes)
    .enter()
    .append("image")
    .attr("x", function(d) { return d.x - 30/2; })
    .attr("y", function(d) { return d.y - 30/2; })
    .attr("width", 45)
    .attr("height", 45)
    .attr("xlink:href",function(d) { return d.url; })

    setInterval(function(test){
       var url = "http://..."
       d3.json(url, function(error, data) {
       for (var i = 0; i < data.links.length; i++) {
         source = findNode(data.links[i].source);
         target = findNode(data.links[i].target);
            svg.selectAll()
              .data(data.links)
              .enter()
              .append("line")
              .attr("x1", function(d) { return nodes[source].x; })
              .attr("y1", function(d) { return nodes[source].y; })
              .attr("x2", function(d) { return nodes[target].x; })
              .attr("y2", function(d) { return nodes[target].y; })
              .attr("stroke","#b72b34")
              .attr("stroke-width", function (d) { return Math.sqrt(d.value);
               })
          ;

  }
   });
   }, 5000);

A: You are currently appending new lines each time you update the graph:
svg.selectAll()
   .data(data.links)
   .enter()
   .append("line")

svg.selectAll() is an empty selection, the same as svg.selectAll(null). So an item is created in the DOM for every item in the data array ever update. This will slow things down after a while.
We could select circles with svg.selectAll("circle") in order to update (or exit/enter old/new lines) but the new data array will be assigned to existing lines in  order of their index, not whether the data pairs. We can do a key for each element with .selectAll().data() (the second argument for .data()), but this must be a string.
Rather than use a key, I'll propose using we could give each line an id (when initially appending the lines) representing its source and target:
 .attr("id", function(d) { return "link-"+d.source+"-"+d.target; })

Then when we process the json data for updating the graph we select the proper lines. Once selected we apply the style. Using the delay on a transition we can ensure the transition back to normal is completed after two seconds:
newData.links.forEach(function(d) {
    d3.select("#link-"+d.source+"-"+d.target)
       .attr("stroke","red")
       .transition()
       .delay(1500)
       .duration(500)
       .attr("stroke","#f6f6f6")
})

This portion of code fits in your timeout function:

var width = 600;
var height = 400;

var svg = d3.select("body").append("svg")
  .attr("width",width)
  .attr("height",height);

var nodes = [
 { x:   width/2, y: height/4, id: 0, url: "http://icons.iconarchive.com/icons/icons-land/vista-hardware-devices/128/Computer-icon.png"},
 { x:   60, y: height-150, id: 1, url: "http://icons.iconarchive.com/icons/icons-land/vista-hardware-devices/128/Computer-icon.png"},
 { x:   width-100, y: height-150, id: 2, url: "http://icons.iconarchive.com/icons/icons-land/vista-hardware-devices/128/Computer-icon.png"},
 { x:   60, y: height-50, id: 3, url: "http://icons.iconarchive.com/icons/icons-land/vista-hardware-devices/128/Computer-icon.png"},
 { x:   width-100, y: height-50, id: 4, url: "http://icons.iconarchive.com/icons/icons-land/vista-hardware-devices/128/Inkjet-Printer-icon.png"}
  ];

  var links = [
  { source: 1, target: 2 },
  { source: 1, target: 3 },
  { source: 1, target: 4 },
  { source: 1, target: 0 },
  { source: 2, target: 3 },
  { source: 2, target: 1 },
  { source: 2, target: 4 },
  { source: 2, target: 0 },
  { source: 3, target: 4 },
  { source: 3, target: 1 },
  { source: 3, target: 2 },
  { source: 3, target: 0 },
  { source: 4, target: 1 },
  { source: 4, target: 2 },
  { source: 4, target: 3 },
  { source: 4, target: 0 },
  { source: 0, target: 1 },
  { source: 0, target: 2 },
  { source: 0, target: 3 },
  { source: 0, target: 4 },
  ];

svg.selectAll()
     .data(links)
  .enter()
  .append("line")
   .attr("x1", function(d) { return nodes[d.source].x; })
   .attr("y1", function(d) { return nodes[d.source].y; })
   .attr("x2", function(d) { return nodes[d.target].x; })
   .attr("y2", function(d) { return nodes[d.target].y; })
   .attr("stroke-width", function (d) { return Math.sqrt(d.value); })
   .attr("id", function(d) { return "link-"+d.source+"-"+d.target; })
   .attr("stroke","#f6f6f6")

   svg.selectAll()
    .data(nodes)
    .enter()
    .append("image")
    .attr("x", function(d) { return d.x - 45/2; })
    .attr("y", function(d) { return d.y - 45/2; })
    .attr("width", 45)
    .attr("height", 45)
    .attr("xlink:href",function(d) { return d.url; })

    setInterval(function(){
         // randomly links instead of calling external file:
         var data = links.filter(function(d) { if (Math.random() < 0.5) return d; })

        data.forEach(function(d) {
          d3.select("#link-"+d.source+"-"+d.target)
              .attr("stroke","red")
              .transition()
              .delay(1500)
              .duration(500)
              .attr("stroke","#f6f6f6")
          })

   }, 3000);  // sped up for demonstration
<script src="https://d3js.org/d3.v3.min.js"></script>

For the sake of comparison, here's a key provided to .data() as an alternative method. For it we convert the target and source into a string much like we did for the id, but apply it as the key in .data(). This allows us to skip the for each loop. It's a more canonical d3 approach:

var width = 600;
var height = 400;

var svg = d3.select("body").append("svg")
  .attr("width",width)
  .attr("height",height);

var nodes = [
 { x:   width/2, y: height/4, id: 0, url: "http://icons.iconarchive.com/icons/icons-land/vista-hardware-devices/128/Computer-icon.png"},
 { x:   60, y: height-150, id: 1, url: "http://icons.iconarchive.com/icons/icons-land/vista-hardware-devices/128/Computer-icon.png"},
 { x:   width-100, y: height-150, id: 2, url: "http://icons.iconarchive.com/icons/icons-land/vista-hardware-devices/128/Computer-icon.png"},
 { x:   60, y: height-50, id: 3, url: "http://icons.iconarchive.com/icons/icons-land/vista-hardware-devices/128/Computer-icon.png"},
 { x:   width-100, y: height-50, id: 4, url: "http://icons.iconarchive.com/icons/icons-land/vista-hardware-devices/128/Inkjet-Printer-icon.png"}
  ];

  var links = [
  { source: 1, target: 2 },
  { source: 1, target: 3 },
  { source: 1, target: 4 },
  { source: 1, target: 0 },
  { source: 2, target: 3 },
  { source: 2, target: 1 },
  { source: 2, target: 4 },
  { source: 2, target: 0 },
  { source: 3, target: 4 },
  { source: 3, target: 1 },
  { source: 3, target: 2 },
  { source: 3, target: 0 },
  { source: 4, target: 1 },
  { source: 4, target: 2 },
  { source: 4, target: 3 },
  { source: 4, target: 0 },
  { source: 0, target: 1 },
  { source: 0, target: 2 },
  { source: 0, target: 3 },
  { source: 0, target: 4 },
  ];

svg.selectAll()
  .data(links, function(d) { return d.source+"-"+d.target })
  .enter()
  .append("line")
   .attr("x1", function(d) { return nodes[d.source].x; })
   .attr("y1", function(d) { return nodes[d.source].y; })
   .attr("x2", function(d) { return nodes[d.target].x; })
   .attr("y2", function(d) { return nodes[d.target].y; })
   .attr("stroke-width", function (d) { return Math.sqrt(d.value); })
   .attr("stroke","#f6f6f6")

   svg.selectAll()
    .data(nodes)
    .enter()
    .append("image")
    .attr("x", function(d) { return d.x - 45/2; })
    .attr("y", function(d) { return d.y - 45/2; })
    .attr("width", 45)
    .attr("height", 45)
    .attr("xlink:href",function(d) { return d.url; })

    setInterval(function(){
  // randomly links instead of calling external file:
     var data = links.filter(function(d) { if (Math.random() < 0.5) return d; })

     d3.selectAll("line")
       .data(data, function(d) { return d.source+"-"+d.target; })
       .attr("stroke","red")
       .transition()
       .delay(1500)
       .duration(500)
       .attr("stroke","#f6f6f6")

   }, 3000);  // sped up for demonstration
<script src="https://d3js.org/d3.v3.min.js"></script>

A: You can cache the line selection in a variable to reuse it in your timeout. Have a look at the code below. I also added an optional 300ms transition.
const redLine = svg.selectAll()
  .data(data.links)
  .enter()
  .append("line")
  .attr("x1", function(d) { return nodes[source].x; })
  .attr("y1", function(d) { return nodes[source].y; })
  .attr("x2", function(d) { return nodes[target].x; })
  .attr("y2", function(d) { return nodes[target].y; })
  .attr("stroke","#b72b34")
  .attr("stroke-width", 2)

// drop this code inside setTimeout() instead of the whole block of code from
// above that you repeat
redLine
  .transition(300)
  .attr("stroke","grey")
  .attr("stroke-width", 1)


text:
Q: After logging in through a display manager, xfce presents me with only a cursor and wallpaper (no icons, menus, etc.) I had a hard drive stop working last week. Not a big problem, I just purchased a new one and restored the latest backup (I back it up using rsync on it while it is running). I get the computer working again, boot it, attempt to log in, and as the title says, I'm greeting with only wallpaper and a cursor.
I've spent most of the day scouring the Internet for a solution but haven't found one. Here's what I've tried and found out.

*

*It affects all users so solutions like deleting ~/.config haven't
worked.

*I installed another display manager (gdm, I usually use lightdm), and
tried to login using it; it also displayed the wallpaper and cursor.

*I installed other desktop environments (lxde and gnome, I usually use
xfce). lxde returns me to the login screen, gnome occasionally has a
system error, but I'm not sure if it is related.

*I'm guessing that the backup possibly picked up something in /var
that is now confusing the system (I don't back up /proc, /run, /sys, or /tmp).

*The applications that normally start upon login appear to start and run.

*Checking the log files hasn't yielded much of anything.

I'm running Ubuntu 14.04.1. I suspect tracking this down is a long shot, but reinstalling and reconfiguring a new system is not something I'm looking forward to doing.
Thanks!


text:
Q: I don't understand how to return all values in string with return string[i:i+max_width]? I have a code and I wanna return all values in string with newline.
def wrap(string, max_width):
for i in range(0, len(string), max_width):
    return string[i:i+max_width]

# You can't change anything here.
if __name__ == '__main__':
    string, max_width = input(), int(input())
    result = wrap(string, max_width)
    print(result)

My input
ABCDEFGHIJKLIMNOQRSTUVWXYZ
4

Required output
ABCD
EFGH
IJKL
IMNO
QRST
UVWX
YZ

My output
ABCD

A: The problem with the code is that you need to run the wrap function n times not just return the value. Also, return breaks the function so it executes only once. One of the correct codes would be:
def wrap(string, max_width):
    temp = ''
    for i in range(0, len(string), max_width):
        temp += f'{string[i:i+max_width]}\n'
    return temp

if __name__ == '__main__':
    string, max_width = input(), int(input())
    result = wrap(string, max_width)
    print(result)


text:
Q: How do I assign values to variables which comprise a matrix? I have a m x n matrix (5 x 5) and I wish to assign values for m1,m2, m3, etc and n1, n2, and n3 etc, without changing the a[m x n] values.  I'm not looking so much for a direct solution but maybe a place to start because I'd like to try it myself first, I'm just a little lost as to where to start.

A: Use ReplacePart. For example, for the $5\times5$ matrix defined as
matrix = Array[m, {5, 5}];

we can replace $m_{23}$ as
newMatrix = ReplacePart[matrix, {2, 3} -> 0];

Explicitly:

$matrix\;=\left(
\begin{array}{ccccc}
 m(1,1) & m(1,2) & m(1,3) & m(1,4) & m(1,5) \\
 m(2,1) & m(2,2) & m(2,3) & m(2,4) & m(2,5) \\
 m(3,1) & m(3,2) & m(3,3) & m(3,4) & m(3,5) \\
 m(4,1) & m(4,2) & m(4,3) & m(4,4) & m(4,5) \\
 m(5,1) & m(5,2) & m(5,3) & m(5,4) & m(5,5) \\
\end{array}
\right)$

and

$newMatrix\;= \left(
\begin{array}{ccccc}
 m(1,1) & m(1,2) & m(1,3) & m(1,4) & m(1,5) \\
 m(2,1) & m(2,2) & 0 & m(2,4) & m(2,5) \\
 m(3,1) & m(3,2) & m(3,3) & m(3,4) & m(3,5) \\
 m(4,1) & m(4,2) & m(4,3) & m(4,4) & m(4,5) \\
 m(5,1) & m(5,2) & m(5,3) & m(5,4) & m(5,5) \\
\end{array}
\right)$


text:
Q: Creating swatches in Shopify for a drop downlist I try to create Swatches in Shopify for a drop down list. What I want, is the colour I'm selecting in the drop down, to appear underneath the drop down, on the right of it or somewhere in the page. I've read what some other answers but I can't figure how to change the background colour of the swatch based on the selection from the drop down list and if I need to create a new .css stylesheet just for the swatch.
Thanks for the help.

A: See my answer to a similar question here.
This tutorial is a good starting point: Adding color swatches to your products
To change the background colour of the swatch based on the dropdown selection, add something like this to the selectCallback function:
if (variant) {
  jQuery('.swatch li span').css("background-color", variant.option2); // or whichever option 'colour' is in your case...
}

Edit: gist available here


text:
Q: ingress does not work with GRPC gateway. HTTP requests are not being forwarded to GRPC gateway as expected by the ingress I have set up a GRPC gateway with all the methods corresponding to HTTP URLs. e.g. v1/my-service. These paths do not seem to work for the ingress I have set up. I can send a request indirectly by using another pod to route the requests to this URL using the internal cluster IP however when I try to go directly my-ip/v1/myservice I get a server error with little description:
Error: Server Error

The server encountered a temporary error and could not complete your request.
Please try again in 30 seconds.

Is there a reason why this occurs? I can't see why I get server errors this way when I know that the incoming URL format corresponds to the method defined in the gateway. I would like to point out that my ingress definitely works as I am simply using this intermediary pod to route the successful requests but I am still sending them through the ingress.

A: Possibly, you need the annotation on your Ingress resource(?):
nginx.ingress.kubernetes.io/backend-protocol: "GRPC"

and the HTTP/2 ingress controller ConfigMap option(?):
use-http2="true"

Also, check the nginx.conf in the Nginx ingress controller pod:
kubectl exec -it <nginx-ingress-pod> sh
# cat nginx.conf

You want to check that something like this is configured at the server level:
    server {
        listen 80 http2;

        access_log logs/access.log main;

        location / {
            # Replace localhost:50051 with the address and port of your gRPC server
            # The 'grpc://' prefix is optional; unencrypted gRPC is the default
            grpc_pass grpc://localhost:50051;
        }
    }


text:
Q: Unable to concatenate html "I'm trying to make an Ajax call, which is successful. But when I try to print the response it does not concatenate the "success" or "failure: string with "initial value"
it prints the middle vale and Also, if i put console.log inside success or failure it prints the value. It does not work outside the Ajax call
loadData : function(groupRID, serviceName) {
    var html = 'initial value';
    var params = {
        codeGroupRid : groupRID,
        outputFormat : 'json'
    };
    html +=' middle'
    Util.Functions.eAjax(serviceName, params, {
        success : function(response) {
            html += ' Success';
            return html;
        },
        failure : function(errMsg) {
            html += ' Failure';
            return html;
        }
    });
},

Expected is - initial value middle Success
Actual is - initial value middle

A: Remove the return html; part from success and failure callbacks cause ajax is asynchronous. If you use return inside the callback it return before response is obtained.

A: As @Gokul Raj K.N. said - Ajax is asynchronous method by default. So:
Recommended solution:
You should add function parameter to loadData method which can be done like:
loadData(groupRID, serviceName, function (result) {
    let loaded_data = result;
    // do something with loaded data
});

And loadData method with callback:
loadData : function(groupRID, serviceName, callback) {
    var html = 'initial value';
    var params = {
        codeGroupRid : groupRID,
        outputFormat : 'json'
    };
    html +=' middle'
    Util.Functions.eAjax(serviceName, params, {
        async: false,
        success : function(response) {
            html += ' Success';
            callback(html);
        },
        failure : function(errMsg) {
            html += ' Failure';
            callback(html);
        }
    });
},

Not recommended solution:
You can easy change async parameter to make it synchronous.

true if this request should run asynchronously. Setting this to false should generally be avoided, since it will cause the UI to be blocked, the user won't be able to interact with the browser until the request completes.
  Defaults to: true

loadData : function(groupRID, serviceName) {
    var html = 'initial value';
    var params = {
        codeGroupRid : groupRID,
        outputFormat : 'json'
    };
    html +=' middle'
    Util.Functions.eAjax(serviceName, params, {
        async: false,
        success : function(response) {
            html += ' Success';
            return html;
        },
        failure : function(errMsg) {
            html += ' Failure';
            return html;
        }
    });
},