text:
Q: PowerShell: finding which groups are attached to which folders (This is my first post, so sorry if I'm hard to understand or asked a bad question)
Here is my problem:
I have a few AD Groups with a similar naming convention. "*somename" and I used Get-ADGroup command to get an array filled with those objects.
Similarly, I have folders with NTFS permissions on them which I have in another array. These permissions are a mix of the groups I mentioned earlier, as well as other groups and individual users as needed.
End Goal (What I would like to find):

*

*Which folders do not have any of those AD Groups assigned.

*And which of those AD Groups aren't attached to any folders.

*Which folders have which AD Group from that list assigned to it.

Here is what I have tried
$CS_Dirs=get-childitem '\\my.server\share$\Dept' -recurse -depth 1 -filter copierscans
$CS_Roles=Get-ADGroup -filter {Name -like "* CopierScans"}

####For each directory in $CS_Dirs array, get acl###
foreach($dir in $CS_Dirs){

    ###Get the ACL for the Dir###
    get-acl $dir.PSPath | %{

        ####Variable to tell this loop if next loops find a match###
        $contains=$false

        ####For every access object in that ACL###
        foreach ($access in $_.access){

            ###loop through each group to check if any of the dir's ACL's principals are in my list of AD Groups.
            foreach($group in $CS_ADGrups){

                #If they are then set contains to true to tell the outer loop to select that path
                if($access.identityreference.ToString() -match {"DOMAIN\"+$group.name.ToString()}){
                    $contains=$true
                }
            }
        }

        #Should be a list of all the paths
        #Which are not assigned a group contained in my $CS_ADGroups list.
        if($contains){
            $_ | select @{n="path";e={$_.path}}
        }
    }
}

The Issues:
The matching in the end of the foreach I can't get to match eachother

*

*The matching in the end of the foreach, i can't get it to evaluate true properly when they match. partly because one of them has the domain attached to the front and the other doesn't (hence the "domain\" portion)

*I can't get it to select the directory path when it's inside a foreach loop,

A: It is difficult to see the errors you're getting without a similar environment to run it against. I can make the following two suggestions.
1) Get-Childitem does not return any items with a "path" property. Try using the "Fullname" property instead.
2) When you attempt to match a string that contains characters that perform special regex functions (like \$^?.) you need to escape those so they can be matched. Backslash is the primary escape character in regular expressions.
$group = "DOMAIN\Some Group"
$group -match $group
False
$group -match [regex]::Escape($group)
True

[Regex]::Escape("DOMAIN\Some Group")
DOMAIN\\Some\ Group
help about_regular_expressions

Try the following on the right side of your -match
-match ( [regex]::Escape("Domain\" + $group.name))


text:
Q: Using different size images for phones and tablets I want to use higher size images for tablets and to decrease the size for phones.
I am doing this for all images in ImageButton.
I have tried placing different size images like hdpi, ldpi, mdpi etc in different folders inside drawable but this is also not working.
I have read that different layouts should be used, but in newer API Levels it is now deprecated.
Is there any easy way of doing this?

A: Based on you Phone/Tablet pixel density , Android system will automatically choose the apt image for your Phone/Tablet. But still, you can explicitly make Android choose different size images. Like this..
// for Phones
drawable-ldpi
drawable-mdpi
drawable-hdpi
//for 7 inch tablets
drawable-large-mdpi
drawable-large-hdpi(for Nexus 7)
// for 10 inch tablets
drawable-xlarge-mdpi
res/drawable-xlarge-mdpi/

A: Android will choose which one it will need. So you just have to place images with good sizes on good folders.
You can check the documentation here, you also can check this post.

A: This is one of the code I found online to reduce the size of the image. Try using this.
    import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.widget.ImageView;

public class AndroidLoadImageViewActivity extends Activity {

 String imagefile ="/sdcard/IMG_9331.JPG";

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        ImageView image = (ImageView)findViewById(R.id.image);
        //Bitmap bm = BitmapFactory.decodeFile(imagefile);
        Bitmap bm = ShrinkBitmap(imagefile, 300, 300);
        image.setImageBitmap(bm);
    }

 Bitmap ShrinkBitmap(String file, int width, int height){

     BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options();
        bmpFactoryOptions.inJustDecodeBounds = true;
        Bitmap bitmap = BitmapFactory.decodeFile(file, bmpFactoryOptions);

        int heightRatio = (int)Math.ceil(bmpFactoryOptions.outHeight/(float)height);
        int widthRatio = (int)Math.ceil(bmpFactoryOptions.outWidth/(float)width);

        if (heightRatio > 1 || widthRatio > 1)
        {
         if (heightRatio > widthRatio)
         {
          bmpFactoryOptions.inSampleSize = heightRatio;
         } else {
          bmpFactoryOptions.inSampleSize = widthRatio;
         }
        }

        bmpFactoryOptions.inJustDecodeBounds = false;
        bitmap = BitmapFactory.decodeFile(file, bmpFactoryOptions);
     return bitmap;
    }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Access the protected variable from a nested class to the enclosing class class A
{
public:
   class B
   {
      public:
          int changevar (int b)
          {
            a = b; // 5 should go in "a"
          }
          int get()
          {
            return a;
          }
      protected:
          int a = 0; // value initialized here
   };

   private:
        int usechangedvar(B& hello);
};

int A::usechangedvar(B& hello)
{
    int final = hello.get(); // 5 should go in "final"
    return final;
}

int main()
{
    A::B hi;
    hi.changevar(5);

    A obj;
    obj.usechangedvar(hi);
}

This code will not compile because it will say that I am trying to access the private method.
Regardless, I am not sure what is the correct way of doing this but finally what I want is:
Under class B there is a protected variable whose value is changed by the public method called "changevar". Once the value is changed, I need to store that value in the variable "final" inside the private method called "usechangedvar".
Note: I do not want to change the variable "a" from protected to something else.
Edit: I am open to suggestions where class B is not a nested class. I can keep it outside meaning A and B are not within one another
EDITED:
#include <stdio.h>
#include <iostream>
#include <stdint.h>

class A
{
   public:
   class B
   {
      public:
          int changevar (int b) ------------- This method is called by application code(user) and whatever value user gives here should be the changed value
          {
            a = b; // 5 should go in "a"

          }
        //   int get()
        //   {
        //     return a;
        //   }
        protected:
            int a = 0; // value initialized here. This could be anything private/protected
   };

   class C : public class B
   {

   };

   private:
        int usechangedvar();
};

int A::usechangedvar()
{
    // 5 should come here which was inputted by user.
}

int main()
{
    //1) I instantiate class C by doing
    A::C objC;
    objC.changevar(5);
    // Whole purpose is to take 5 from user and then use it eventually in "usechangedvar" method.
}

A: Here is your problem reproduced with unrelated details eliminated:
class A
{
   private:
        int usechangedvar(int hello) { return hello; }
};

int main()
{
    A obj;
    obj.usechangedvar(5); //compile error, usechangedvar is private
}

Problem in your code is completely unrelated to class B as you can see here - you cannot call A::usechangedvar() from main() as it is private method of class A.
If you just need to check if your method usechangedvar() works you may add public method to A for example test(), call usechangedvar() from it and probably print the result. Then you can call obj.test() from main() and see if it works. You may want to remove that method test() if necessary after test is done.


text:
Q: Can we treat $\sim$ like =? Saw this particular statement from my lectures
$\frac{(n-p)s^2}{\sigma^2} \sim  \chi^2$ then  $(n-p)s^2 \sim  \sigma^2 \chi^2$
My first question was what does $\sigma \chi^2$ even mean?
Secondly, why are we able to just multiplying both sides by $\sigma^2?$ Are we just treating $\sim $ like an $=$ sign? If so, why?

A: I think your confusion arises from what can be considered an abuse of notation in the equation you quote. If you treat $ \chi^2 $ as a random variable, then the relation makes sense because for any two random variables $X,Y$ on the same probability space $\left(\Omega,\mathcal{F},P\right)$ if $X\sim Y$ then $f(X)\sim f(Y)$ for any Borel-measurable function $f$.  To see this, let $S \in \mathcal{B}\left(\mathbb{R}\right)$, that is, let $S$ be a Borel set in $\mathbb{R}$ and observe that $$P(f(X)\in S) = P(X \in f^{-1}(S)) = P(Y \in f^{-1}(S)) = P(f(Y)\in S)$$ where the second equality follows from the fact that $X,Y$ are identically distributed. While I am being precise and using the language of measure theory, the basic idea is very simple and the measurability condition is usually satisfied by most functions. In particular, it is satisfied by $f(x) = \sigma x$


text:
Q: Stop the android activity spinner manually My ListFragment fetches data from a REST service using an AsyncTask.
The onPostExecute() block returns a success/fail status back to my fragment rather than the result.
In my fragment use this status to show my ListView (in case of success) or pop up a toast(in case of failure).
As soon as the AsyncTask is executed, an activity circle is shown in the middle of the screen which gets replaced by the ListView once the data is available.
In case the data is not available, the toast message does pop up, but the activity circle does not get removed.
I am not declaring anywhere in the code when to start the activity spinner.
How can I stop the activity circle in case of failure?
Here is the code block of the AsyncTask:
    class invokeServiceTask extends AsyncTask<String, Void, ServiceResult> {
          @Override
          // method to be run in BG thread
          // pass the mashup parameters to the BG thread
          protected ServiceResult doInBackground(String... id) {
                 return invokeMashupService(id);
          }

          @Override
          // called on UI thread when the worker is done
          protected void onPostExecute(ServiceResult result) {
                 _delegate.mashupReturned(result);
          }
   }

If result is returned as SERVICE_FAILURE, I am displaying a toast as seen in the code block below which is executed in the UI after AsyncTask is completed.
    public void mashupReturned(ServiceResult result) {

          // check for getActivity to counter the case when user presses the back
          // button quickly and the app context is no longer valid.
          if (getActivity() != null) {
                 if (result == ServiceResult.SERVICE_SUCCESS) {
                       // Fetch the array of GroupListItems and create a
                       // GroupListAdapter using it
                       GroupListItem[] list_data = _dataModel.getData();
                       GroupListAdapter adapter = new GroupListAdapter(getActivity(),
                                     R.layout.list_row, list_data);
                       setListAdapter(adapter);
                 } else {
                       // TODO: stop the activity spinner
                       Toast.makeText(getActivity(),
                                     "Problem invoking service: " + result,
                                     Toast.LENGTH_SHORT).show();
                 }
          } else {
                 Log.i("test", "Activity is null");
          }
   }

A: I'm not sure if I can help you with that abstract a piece of code.
The only possible reason I can think of here is that the method invokeMashupService(id) is invoking a ProgressBar or spinner to start animating, and when your ListView's constructor or some other method in it is invoking the call to either stop the animation of the spinner, or to set its visibility to View.INVISIBLE or View.GONE.
Try looking for any ProgressBar or spinner in the xml file of the layout used by this file, and in the failure block of your method mashupReturned, set its visibility to View.GONE if the spinner is no longer reqd, or View.INVISIBLE if the spinner might be required later.
Hope this helps
Anuj

A: SOLVED..
I was not setting any UI element in the Failure state because of which the activity spinner was persisting.
I removed the Toast statement and added a Header row along with an empty ListView. This stops the spinner and shows me the message I want in the header.


text:
Q: How do make make subroutine parameter as readwrite Suppose I have a subroutine that swaps two given parameters. It logically needs to have read write parameters.
sub swap($l, $r)
{
   my $tmp = $l;
   $l=$r;
   $r=$tmp;
}

I get the error:

Cannot assign to a read only variable ($l) or a value

I don't think I can try \$param like in perl5.
I think I should try something with := but the documentation doesn't mention anything about the function parameters.
How do I pass parameter as a reference to this subroutine so that I can change its value?

A: sub swap ( $l is rw, $r is rw ) {
   ($r,$l) = ($l,$r)
}

my $a = 1;
my $b = 2;

swap $a, $b;

say $a; # 2;

my @a[2] = 1,2;

swap |@a;

say @a; # [2 1]

You can use reverse as well for what you are trying to accomplish.
my $a = 1;
my $b = 2;

($a,$b) .= reverse;

say $a; # 2
say $b; # 1


text:
Q: How to add matplotlib plot below and image in opencv I want to add two plots to the bottom of an image. It should look like this:
dog

plot (both plots look very similar)

I want to combine these two images together, specifically attaching the plot to the bottom of the dog image. I want the result to look like:

This link was helpful in getting plots to the right image format, but I do not know how to attach them to the main image
Combining cv2.imshow() with matplotlib plt.show() in real time
edit
High level pseudocode:
import cv2
import pandas
import matplotlib.pyplot as plt

vid = cv2.VideoCapture('video.mp4')
global data
data = pd.read_csv('data.csv')

assert len(data) == cv2.CAP_PROP_FRAMES_COUNT()

def pipeline(frame):

    frame_index = next(dfi[0])
    current_plot1 = plt.plot(df.time[:frame_index], df.data1[:frame_index]
    current_plot2 = plt.plot(df.time[:frame_index], df.data2[:frame_index]

    # add plots to frame somehow here
    frame = frame+current_plot1+current_plot2
    return frame

# write video
dfi = df.iterrows()
video = VideoFileClip(vid)
out_video = video.fl_image(pipeline)
out_video.write_videofile("vidout.mp4", temp_audiofile='temp-audio.m4a', remove_temp=True, codec="libx264", audio_codec="aac")

A: First use plot1 = plt.figure() similarly for plot2 = plt.figure() while initalizing the plots
then horizontally concat the plots
combined_plot=plt.hconcat([plot1,plot2])

then vertically concat these using
final_img=plt.vconcat([dog_img,combined_plot])

return final_img


text:
Q: Presenting a View Controller with an xib from an SKScene I have tried many things, none of which are working. I have an SKScene, and when the game is over, I want it to go back to the original view controller. Thank you in advance.
I have tried this in my SKScene
homeScreenViewController *viewCont = [[homeScreenViewController alloc] init];
            [viewCont viewDidLoad];

This in my other view controller
constructinoViewController *view = [[constructinoViewController alloc ] init];
        [self presentViewController:view animated:YES completion:nil];

It mostly says The view is not in the view hierarchy.

A: You need a way to send the parent viewController a message.
In your viewController which presents the SKScene, add the following line in viewDidLoad:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(closeScene) name:@"closeScene" object:Nil];

Also, add this method
-(void)closeScene
{
    //Remove the SKView, or present another viewController here.

    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"closeScene" object:nil];
}

Then in your SKScene, at the point where your game ends,
[[NSNotificationCenter defaultCenter] postNotificationName:@"closeScene" object:nil];

You can do this by using delegates as well.

A: If you have presented the ViewController, then you need to dismiss it to return to previous ViewController.
You should use
[self dismissViewControllerAnimated:YES completion:NULL];


text:
Q: How can I make VSCode recognize structural pattern matching (match case) with Python3.10? So I am using Python3.10rc2 (Py3.10 is not officially released yet), and I want the match case statement to be highlighted, or at least not have error squiggly lines show up. Somehow I did not have a problem with this before in VScode when using Py3.10 (maybe I was using a slightly earlier 3.10 beta version?). But now I seem to be getting error squiggly lines when I write this statement. Does anybody have an idea how I can fix this?

Cheers.

A: update Pylance to Pre-release and restart VS Code


text:
Q: How to save objects in Python without using pickle? I want to save a object in a file so i can use it later (after the program closes).
I tried to use pickle, but looks like it doesn't like my object :D
Traceback (most recent call last):
  File "(path)", line 4, in <module>
    pickle.dump(object, f)
AttributeError: Can't pickle local object '_createenviron.<locals>.encodekey'

here is the code:
import pickle
object = MyWeirdClass()
with open("data.pickle", "wb") as f:
    pickle.dump(object, f)

There is any other way to save objects (like an external library)?
I did something wrong and i got this error?
My MyWeirdClass() class is working perfectly fine, i tested it multiple times and i got exactly the results i expected.
EDIT:
i found out that the problem is that one of the object's variables is a selenium.webdriver.chrome.webdriver.WebDriver
object. after deleting this object (after doing what i wanted with it) it worked fine.
SECOND EDIT:
i also got this error:
RecursionError: maximum recursion depth exceeded while pickling an object

On the line of code i tried to write the object to file.
I found out that i have to set the sys.setrecursionlimit() to a higher value, so instead of setting it to random values until i got no errors, i make this:
import pickle
import sys
default_cursion_limit = sys.getrecursionlimit()# defalut is 1000
object = MyWeirdClass()
while True:
    try:
        with open("data.pickle", "wb") as f:
            pickle.dump(object, f)
        break
    except RecursionError:
        default_cursion_limit += 50
        sys.setrecursionlimit(default_cursion_limit)# looks like its working with 2600

A: The easiest solution is going to be to define your class in such a way that it's pickle-able.  The error message suggests that some of your class's attributes can't be pickled because they don't have globally-scoped names.
If you want to save an object that's not pickleable, you'll need to write your own logic to serialize and deserialize it.  It's impossible to give specific advice on this without seeing the object, but the general idea is that you need to figure out how to represent your object's state as something that you CAN pickle (like a series of simple string/int attributes) and then write a function that will reconstitute your object from that data.


text:
Q: Skip file lines until a match is found, then output the rest I can write a trivial script to do this but in my ongoing quest to get more familliar with unix I'd like to learn efficient methods using built in commands instead.
I need to deal with very large files that have a variable number of header lines. the last header line consists of the text 'LastHeaderLine'. I wish to output everything after this line. (I'm not worried about false positive matches.)

A: Similar to the answer of Avi, but without including the line with "LastHeaderLine".
sed -e '1,/LastHeaderLine/d'

A: Why not try awk for this? It would look like this:
awk 'NR == 1, /LastHeaderLine/ { next } { print }' myinputfile > myoutputfile

where NR == 1 is true for the first line, /LastHeaderLine/ matches your last header line. The comma operator lets the following function { next } fire for all sentences in the range of the two regular expression. In this case it will skip to the next line of input without further operation. For all other input lines it will print the lines to the standard output, which you can redirect using >.

A: Using sed:
sed -ne '/LastHeaderLine/,$p' <inputfile

will match everything from the regex match to the end of the file. 'p' prints the lines that match.
Edit:
On second thought, you don't want to print the line matching LastHeaderLine. This is difficult to do with sed. In perl, you could do the following:
perl -ne 'if ($flag) {print;} if (/LastHeaderFile/) {$flag=1;}' <inputfile

This would print only lines strictly following the regex match.


text:
Q: Google Calendar API V3 insert_calendar returns 503, but calendar was inserted successfully I'm running into an issue where I send an insert_calendar request to Google Calendar API V3, and I get back the following response:
Sending HTTP post https://www.googleapis.com/calendar/v3/calendars?

503

#<HTTP::Message:0x000000124eb008
  @http_header=#<HTTP::Message::Headers:0x000000124eafe0
  @http_version="1.1",
  @body_size=0,
  @chunked=false,
  @request_method="POST",
  @request_uri=#<Addressable::URI:0x9275f20 URI:https://www.googleapis.com/calendar/v3/calendars?>,
  @request_query=nil,
  @request_absolute_uri=nil,
  @status_code=503,
  @reason_phrase="Service Unavailable",
  @body_type=nil,
  @body_charset=nil,
  @body_date=nil,
  @body_encoding=#<Encoding:UTF-8>,
  @is_request=false,
  @header_item=[
    ["Vary", "Origin"],
    ["Vary", "X-Origin"],
    ["Content-Type", "application/json; charset=UTF-8"],
    ["Content-Encoding", "gzip"],
    ["Date", "Fri, 25 Aug 2017 20:16:34 GMT"],
    ["Expires", "Fri, 25 Aug 2017 20:16:34 GMT"],
    ["Cache-Control", "private, max-age=0"],
    ["X-Content-Type-Options", "nosniff"],
    ["X-Frame-Options", "SAMEORIGIN"],
    ["X-XSS-Protection", "1; mode=block"],
    ["Server", "GSE"], ["Alt-Svc", "quic=\":443\"; ma=2592000; v=\"39,38,37,35\""],
    ["Transfer-Encoding", "chunked"]
  ],
  @dumped=false>,
  @peer_cert=#<OpenSSL::X509::Certificate:
    subject=#<OpenSSL::X509::Name:0x00000012600998>,
    issuer=#<OpenSSL::X509::Name:0x000000126009c0>,
    serial=#<OpenSSL::BN:0x000000126009e8>,
    not_before=2017-08-15 16:06:52 UTC,
    not_after=2017-11-07 16:04:00 UTC
  >,
  @http_body=#<HTTP::Message::Body:0x000000124eaf68
    @body="{\n \"error\": {\n \"errors\": [\n{\n \"domain\": \"global\",\n \"reason\": \"backendError\",\n \"message\": \"Backend Error\"\n }\n ],\n \"code\": 503,\n \"message\": \"Backend Error\"\n }\n}\n",
    @size=0,
    @positions=nil,
    @chunk_size=nil
  >,
  @previous=nil>

Caught error Server error

Error - #<Google::Apis::ServerError: Server error>

I'm using the Google API Ruby Client, details here:
google-api-client (0.13.1)
  addressable (~> 2.5, >= 2.5.1)
  googleauth (~> 0.5)
  httpclient (>= 2.8.1, < 3.0)
  mime-types (~> 3.0)
  representable (~> 3.0)
  retriable (>= 2.0, < 4.0)

The issue I'm having is not encountering the error, but that the calendar is successfully inserted.
As you can see from the response I get nothing back that tells me it was successful in spite of the 503, such as a Google Calendar ID.
The impact this has on my application is that I do not know I have successfully synced, and in fact, by following the docs, I implement and exponential backoff, and so I continue to create duplicate calendars on my users' Google Calendars.
In the end, I have a bunch of orphan calendars showing up that I must remove with a string match.
Is this expected? Is there anything I can do to mitigate this?
This happens with regularity, and is not an isolated case.

The code in question:
def handle_calendar_response(response, error)
  self.update_column('last_synced_at', Time.now.utc)
  if error.present?
    Airbrake.notify('Sync Calendar Sync Error', {
      error: error,
      message: error.message,
      calendar: self
    })

    # String match :(
    if error.message =~ /not.?found/i || error.message =~ /forbidden/i
      Airbrake.notify('Removing user deleted calendar', {
        calendar: self,
        google_calendar_id: self.google_calendar_id,
        error: error,
        message: error.message
      })
      self.publish_to_google = false
      self.google_calendar_id = nil
      self.save!
    end
  end
end

...

def insert_calendar
  @client.insert_calendar(google_calendar_object) do |response, error|
    handle_calendar_response(response, error)
    if response.present?
      self.google_calendar_id = response.id
      self.save!
    end
  end
end

These are methods from a representation of a synced calendar in our data model. You can call insert_calendar to insert it. We always take the same action on a response from Google, if we are inserting, updating, or deleting, we always call handle_calendar_response.

A: Since the errors is in the google backend system there is not really much you can do about fixing it on their side aside of filing a bug report. However you can handle this on your side with adding your own identifier and putting it in the private extended properties of the calendar you want to create. The identifier can be something like combination of the date/time and subject of the event or even a random UIID just as long as you guarantee it is unique. Then before issuing another request when you get the error first go through the users calendars and check if there is an event with the identifier on the same date. This assumes that you have read rights for the users calendars. Hope this helps.


text:
Q: use ckeditor in bootbox is there a way that I can use ckeditor as the textarea within a bootbox dialog? I am using bootbox for other areas with inputs but the only bit I cannot get to work is the textarea. The textarea does show in the dialog, but it is not replaced with ckeditor. Any help with this would be appreciated.
Thanks

A: you can try to use this:
CKEDITOR.ui.dialog.textarea(dialog, elementDefinition, htmlList)

or visit here:http://docs.cksource.com/ckeditor_api/symbols/CKEDITOR.ui.dialog.textarea.html
hope it helps.

A: I managed to do this by loading the form with the textarea into the bootbox dialog using AJAX.
I just needed to include the following in my ajax response.
<script>CKEDITOR.replaceAll(function( textarea, config )</script>


text:
Q: React.js : Updating State of Nested Object Front End - Front End
Upon clicking the star, I want to update the state of nested object, with the new rating value of star.
I tried many things but it didnt work as states are immutable.
Nested State
Can some upon please suggest how can I update the value in nested object
onStarClicked = (kTypName, subItemId1, newRating) => {
//console.log(subItemId.split("_"));
let evaluation = subItemId1.split("_")[0];
let subItemId = subItemId1.split("_")[1];
console.log(subItemId);
const r = { ...this.state.ratings };
let kT = r.knowledgeTypes;
let sub = '', kTN = '', kIN = '';
kT.map(knowledgeType => {
  //console.log(knowledgeType.knowledgeTypeId);
  knowledgeType.knowledgeItems.map(knowledgeItem => {
    //console.log(knowledgeItem.knowledgeItemId);
    knowledgeItem.subItems.map(knowledgeSubItem => {
      //console.log(knowledgeSubItem.subItemId);
      if (subItemId === knowledgeSubItem.subItemId) {
        kTN = knowledgeType.knowledgeTypeName;
        kIN = knowledgeItem.knowledgeItemName;
        sub = knowledgeSubItem;
        if (evaluation === "self") {
          sub.evaluation.self.rating = newRating;
        }
        else if (evaluation === "evaluator") {
          sub.evaluation.evaluator.rating = newRating;
        }

        //alert(evaluation + subItemId + ' ' + newRating);
        //return;
      }
    })
  })

});

this.setState({
  ...this.state,
  ratings: {
    ...this.state.ratings,
    knowledgeTypes: [
      ...this.state.ratings.knowledgeTypes,
      this.state.ratings.knowledgeTypes.filter(kt => kt.knowledgeTypeName !== kTN),
      {
        ...this.state.ratings.knowledgeTypes.knowledgeItems.
          filter(ki => ki.knowledgeItemName !== kIN),
        knowledgeItems: {
          ...this.state.ratings.knowledgeTypes.knowledgeItems.subItems.
            filter(si => si.subItemId !== subItemId),
          sub
        }
      }]
  }
});

}

A: You basically have to create a new empty array of knowledgeTypes and use the current state to find which item of the state you need to change using Object.keys/map/filter functions.
You'd use the current state in a variable and modify that variable only. You'd likely not mess with the actual state object in any way.
After you have done that, simply append it to the empty array. Then you can setState() the new array to the actual state property.
class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      financialYear: "2019-20",
      quarter: "Q1",
      isCurrentQuarter: true,
      knowledgeTypes: [
        {
          knowledgeTypeName: "Technology",
          knowledgeItems: [
            {
              knowledgeItemName: "Java",
              subItems: [
                {
                  subItemId: "2",
                  subItemName: "Collections",
                  evaluation: {
                    self: {
                      ntnet: "Joe",
                      rating: 1,
                      isEditable: true
                    }
                  }
                }
              ]
            }
          ]
        }
      ]
    };
  }

  handleClick = e => {
    const { knowledgeTypes } = this.state;

    // transformation
    const itemToChange = knowledgeTypes.map(item => {
      if (item.knowledgeTypeName === "Technology") {
        return item;
      }
    });
    const currItems = itemToChange[0].knowledgeItems[0].subItems;
    const subItem = currItems.map(item => {
      if (item.subItemId === "2") {
        return item;
      }
    });
    const person = subItem[0].evaluation;
    person.self.rating = 55; //change

    const newKnowledgeTypes = [];
    knowledgeTypes.map(item => {
      if (item.knowledgeTypeName === "Technology") {
        newKnowledgeTypes.push(itemToChange);
      }
      newKnowledgeTypes.push(item);
    });

    this.setState({
      knowledgeTypes: newKnowledgeTypes
    });

    console.log(this.state);
  };

  render() {
    return (

        MyComponent
        <button onClick={this.handleClick}>Hello</button>

    );
  }
}

The sandbox can be found on https://codesandbox.io/s/musing-dew-8r2vk.
Note: It is advisable you do not use nested state objects because state objects are something more lightweight so that they do not have performance considerations.

A: import React, { Component } from 'react';
import Auxilary from '../../../hoc/Auxilary/auxilary';
import KnowledgeItems from '../KnowledgeItems/KnowledgeItems';
import Tabs from 'react-bootstrap/Tabs';
import Tab from 'react-bootstrap/Tab';
import knowledge from '../../../assests/staticdata.json';

import './QuarterLog.css';

class QuarterLog extends Component {

  constructor() {
    super();
    this.state = {
      "financialYear": "",
      "quarter": "",
      "isCurrentQuarter": "",
      "knowledgeTypes": []
    }
  }

  onStarClicked = (kTypName, kItemName, subItemIdName, newRating) => {
    let evaluation = subItemIdName.split("_")[0];
    let subItemId = subItemIdName.split("_")[1];

    const { knowledgeTypes } = this.state;

    // transformation
    let knowledgeTypeToChange = knowledgeTypes.map(kType => {
      if (kType.knowledgeTypeName === kTypName) {
        return kType;
      }
    });

    knowledgeTypeToChange = knowledgeTypeToChange.filter(function (element) {
      return element !== undefined;
    });

    console.log(knowledgeTypeToChange[0]);
    let knowledgeItemToChange = knowledgeTypeToChange[0].knowledgeItems.map(item => {
      if (item.knowledgeItemName === kItemName) {
        return item;
      }
    });

    knowledgeItemToChange = knowledgeItemToChange.filter(function (element) {
      return element !== undefined;
    });

    let knowledgeSubItem = knowledgeItemToChange[0].subItems.map(subItem => {
      if (subItem.subItemId === subItemId) {
        return subItem;
      }
    });

    knowledgeSubItem = knowledgeSubItem.filter(function (element) {
      return element !== undefined;
    });

    console.log(knowledgeSubItem);

    let personEvaluations = knowledgeSubItem[0].evaluation;

    if (evaluation === "self") {
      personEvaluations.self.rating = newRating.toString(); //change
    }
    else if (evaluation === "evaluator") {
      personEvaluations.evaluator.rating = newRating.toString(); //change
    }

    const newKnowledgeTypes = [];
    knowledgeTypes.map(item => {
      if (item.knowledgeTypeName === kTypName) {
        newKnowledgeTypes.push(knowledgeTypeToChange[0]);
      }
      else
        newKnowledgeTypes.push(item);
    });

    this.setState({
      knowledgeTypes: newKnowledgeTypes
    });

    console.log(this.state);

  }

  componentDidMount() {
    // TODO: remove staticdata.js and call REST API and set the response in state
    this.setState({
      ...this.state,
      "financialYear": knowledge.financialYear,
      "quarter": knowledge.quarter,
      "isCurrentQuarter": knowledge.isCurrentQuarter,
      "knowledgeTypes": knowledge.knowledgeTypes
    })

  }

  onSubmitRatings = () => {
    console.log(this.state);
  }

  render() {
    let data = knowledge; //remove this code, once REST API is implemented

    const posts = this.state.knowledgeTypes.map(knowledgeType => {
      return (
        <Tab key={knowledgeType.knowledgeTypeName} eventKey={knowledgeType.knowledgeTypeName}
          title={knowledgeType.knowledgeTypeName}>
          <KnowledgeItems
            kTypeName={knowledgeType.knowledgeTypeName}
            kItems={knowledgeType.knowledgeItems}
            ratings={this.state.ratings}
            onstarclicked={this.onStarClicked}
          />
        </Tab>)
    });

    return (
      <Auxilary>

Financial Year : {data.financialYear}

Quarter : {data.quarter}

          <Tabs defaultActiveKey="Domain" id="uncontrolled-tab-example">
            {posts}
          </Tabs>

        <button onClick={this.onSubmitRatings}> Submit </button>
      </Auxilary>
    );
  }
}

export default QuarterLog;


text:
Q: LinqPad timeout connecting to remote SQL Server I'm trying to connect my hosting providers SQL Server with LinqPad. It works fine using SSMS, but times out when trying to fetch the database list. I am successfully authenticated (via the test)... [ and if i change the credentials, it fails]...
Is there a way to extend the timeout??
Thanks - Kevin

A: The timeout for fetching schema information in LINQPad is 4 minutes, so something is going badly wrong if it times out! On the dialog, did you click 'Display all databases in TreeView' or did you connect to specific database?

A: One solution that our DBA mentioned is to set the database property "Auto Close" to false.
http://msdn.microsoft.com/en-us/library/ms188124.aspx
We did this on our development database server and it worked fine for linqpad with a few hundred databases.


text:
Q: Concise Way to Structure Multi-Variable Data in Excel? I have data with 3 independent variables that I need to perform calculations with and display in a presentable way. Here's an example of what the data looks like:

Obviously this structure isn't usable for calculations between X and Y, W and Z, etc. So I laid out a table like this:

This is super easy to work with; performing calculations between X and Y as well as filtering data by variables works well. I need to find a more presentable way to display the data however. I've been told to make something that looks like this:

It looks nice, but I think it's going to be difficult to look up values with the merged cells. I'm just looking for advice on how to structure this sort of data in a usable way.


text:
Q: NullReferenceException when using NetworkTransform with a RigidBody When I attempt to use NetworkServer.Spawn to create an object with a Rigidbody and a NetworkTransform set to Sync Rigidbody 3D, I get this:

NullReferenceException: Object reference not set to an instance of an object
  UnityEngine.Networking.NetworkTransform.SerializeMode3D (UnityEngine.Networking.NetworkWriter writer) (at C:/buildslave/unity/build/Extensions/Networking/Runtime/NetworkTransform.cs:251)

A: If this suddenly occurs when you think you haven't changed anything, it might be because you've disabled your prefab game object. Happened to me, so I thought I'd put it on here, in case it happens to anyone else :)

A: I was calling NetworkServer.Spawn in the Awake of another component before the NetworkTransform component had awoken. Since OnSerialize happens as soon as you call spawn, it was trying to pull data from an uninitialized reference to the Rigidbody.
UNET is now open source, and the code for NetworkTransform can be found here. Was useful for debugging this!


text:
Q: Jackson + Gson + Retrofit Expected BEGIN_OBJECT but was BEGIN_ARRAY I know this has been asked a lot but, none of the question I've found solve my especific problem.
Here is my JSON
[JSON URL][1]
[
  {
    "unit":"IMECA",
    "value":29,
  },
  {
    "unit":"IMECA",
    "value":43,
  }
]

this is my DTO
Zona.java
  public class Zona {
  private String unit;
  private int value;

  public String getUnit() {
    return unit;
  }

  public void setUnit(String unit) {
    this.unit = unit;
  }

  public int getValue() {
    return value;
  }

  public void setValue(int value) {
    this.value = value;
  }

  @Override
  public String toString() {
    return String.valueOf(unit) + ": " + String.valueOf(value);
  }
}

and this is my Interface
Api.java
public interface Api {
  @GET("/data/heatmap_stations.json")
  Call<Zona> getZona();
}

I kind of understand why it happens , because is a JSON Array the response but Jackson + Gson are expecting a single JSON Object.
I tried creating a POJO like this:
Zonas.java
Public class Zonas extends ArrayList<Zona> {}

and changing the Call signature in the Interface and the Retrofit call, replacing the single DTO to the plural, (from Call< Zona > to Call< Zonas >, replacing the single class to the one who inherits ArrayList<>), but it simply does nothing, I mean, it didn't threw an Exception, but it didn't threw a response either.

A: Change
public interface Api {
  @GET("/data/heatmap_stations.json")
  Call<Zona> getZona();
}

to
public interface Api {
  @GET("/data/heatmap_stations.json")
  Call<List<Zona>> getZona();
}

You are telling it to expect a single Zona object but it is returning an Array of Zona objects


text:
Q: How can I know exact font colors for Default/Classic Theme in Eclipse I would like to find the exact font colors for Default/Classic Theme in Eclipse IDE for Java Developers, Mars.1
Is there any documentation for that?
Can I find the color values in any config/settings files?
I tried to look for the same theme on http://www.eclipsecolorthemes.org/ but I was not able to find the same theme.

A: Color values are in the CSS files for the theme. These are in the css folder in the org.eclipse.ui.themes plugin's directory in the plugins directory of the Eclipse installation.


text:
Q: How to design an execution engine for a sequence of tasks I am trying to code a problem in Java where I have to execute a bunch of tasks.
Problem
Execute a job which consists of multiple tasks and those tasks have dependencies among them.
A job will have a list of tasks and each such task will further have a list of successor tasks (Each successor task will have its own successor tasks - you can see the recursive nature here). Each successor task can start its execution if -

*

*It is configured to be executed on partial execution of its predecessor task. In this case, predecessor task will notify that it has completed partially and my successor tasks can start

*Successful completion of its predecessor task.
Example
Job having 2 initial tasks A and B. A has 2 successor tasks M and N. B has 1 successor task P. P has 2 successor tasks Y and Z.
M can start on partial completion of its predecessor task A.
Z can start on partial completion of its predecessor task P.
N, P and Y can start only on completion of their predecessor tasks A, B and P respectively.

I have to design the execution of such a workflow/job. In the design we have to acknowledge the partial completion event sent by a predecessor task so that its successor task can be started. How should I go about it? Is there any design pattern which suits this problem in concurrency?

A: Take a look at akka - http://akka.io
using akka you create actors (event driven, concurrent entities that process messages asynchronously)
each task can be represented as an actor (you choose when to fire it up)
you can trigger other actors (tasks) on partial complete or full complete (actually you can trigger them whenever you want)

A: Your problem looks like a good use case for Java's ForkJoin Framework. You could implement your tasks as RecursiveActions or RecursiveTasks (depending on whether you need a return value or not) which will start their sub tasks on whatever condition you need. You'll also be able to control if your sub tasks run sequentially or in parallel.
Example:
public class TaskA extends RecursiveAction {
  // ...

  protected void compute() {
    if (conditionForTaskM) {
      TaskM m = new TaskM();
      // Run task M asynchronously or use m.invoke() to run it synchronously.
      invokeAll(m);
    }

    // Run task N at the end of A
    invokeAll(new TaskN());
  }

}

You need an instance of the ForkJoinPool to run your tasks:
public static void main(String[] args) {
  ForkJoinPool pool = new ForkJoinPool();
  pool.submit(new TaskA());

  // Properly shutdown your pool...
}

This example is quite simplistic in implementing a part of your example problem. But generally speaking, the ForkJoin Framework allows you to create tree-like structures of tasks where every parent task (such as A, B and P) allows you to control the execution of its immediate child tasks.

A: 2 options in terms of pattern usage, but in essence they are pretty similar.  In either cases, cyclic dependencies situation need to be handled as a error in task dependency configuration.  e.g. A -> B -> A

*

*Mediator pattern

After each task[i] finishes, it will notify the Mediator, the the Mediator will notify all successor tasks of task[i]. The graph of task dependencies will be read when the execution engine starts as the data structure for Mediator to use.

*Publish/Subscribe pattern via message bus.

The graph of task dependencies will be read as the engine starts, and each task will subscribe to MessageBus of its predecessor task's (task[i]) message of completion on topic[i]
When each task[i] finishes, it will send completion message to the MessageBus in topic[i]. Each task who subscribes to topic[i] will get notified and starts to work.

A: Your question is interesting because someone can simulate a simple neural network using this design. As far as the answer goes, I would like to view the problem as tasks ordering rather than a multithreading/concurrency problem because concurrency can be achieved simply by executing ordered tasks. Now lets try to use event driven programming to achieve that because it allows nice loosely coupled components. So, now our design in reactive in nature, so we will worry about signaling the dependent tasks once we are done, lets use observer pattern here .
Your tasks are both observable and observer as well because they wait on notification from predecessor and notify successor, which gives us the following construct.
// Task.java
public abstract class Task extends Observable implements Runnable, Observer {
    private final Mutex lock = new Mutex();
    private final String taskId;

    public String getTaskId() {
        return this.taskId;
    }

    private final Set<String> completedTasks;
    private final Set<String> shouldCompletedTasksBeforeStart;

    public Task(final String taskId) {
        this.taskId = taskId;
        this.completedTasks = new HashSet<>();
        this.shouldCompletedTasksBeforeStart = new HashSet<>();
    }

    @Override
    public void run() {
        while (true) {
            this.lock.getLock();
            if (this.completedTasks.equals(this.shouldCompletedTasksBeforeStart)) {
                doWork();
                setChanged();
                notifyObservers(this.taskId);
                // reset
                this.completedTasks.clear();
            }
            this.lock.freeLock();
            try {
                // just some sleep, you change to how it fits you
                Thread.sleep(1000);
            } catch (final InterruptedException e) {
                // TODO Auto-generated catch block
            }
        }
    }

    @Override
    public void update(final Observable observable, final Object arg) {
        this.lock.getLock();
        this.completedTasks.add((String) arg);
        this.lock.freeLock();
    }

    public void addPredecessorTask(final Task task) {
        if (this.taskId.equals(task.taskId)) {
            return;
        }
        this.lock.getLock();
        // Notice here, it is a little logic make your predecessor/successor work
        task.addObserver(this);
        this.shouldCompletedTasksBeforeStart.add(task.taskId);
        this.lock.freeLock();
    }

    protected abstract void doWork();

}

//HelloTask.java
public static class HelloTask extends Task {
    public HelloTask(final String taskId) {
        super(taskId);
    }

    @Override
    protected void doWork() {
        System.out.println("Hello from " + getTaskId() + "!");
    }
}

//Main.java
public class Main {
    public static void main(final String[] args) {
        final HelloTask helloTaskA = new HelloTask("A");
        final HelloTask helloTaskB = new HelloTask("B");
        final HelloTask helloTaskC = new HelloTask("C");

        helloTaskA.addPredecessorTask(helloTaskB);
        helloTaskC.addPredecessorTask(helloTaskB);

        final ExecutorService pool = Executors.newFixedThreadPool(10);
        pool.execute(helloTaskC);
        pool.execute(helloTaskA);
        pool.execute(helloTaskB);

    }
}

The implementation is very basic one and you improve upon it but it provides you the foundation structure. It would be interesting to know where you are applying this ?

A: If I understood well your need you may use a workflow engine like Activity to solve it.
I think it would be easier than re-inventing a workflow engine for your specific need.

A: If you want to reinvent the wheel and develop the solution yourself, fine - it's your choice. However doing this properly is rather hard, especially the threading part. However, if you can consider some outside help with at least the building blocks, those can be:

*

*guava's ListenableFuture - using this library you can create Callables and feed them to special thread pool executor, which then allows custom callbacks on ListenableFuture completion.

*you could take a look at RX Java Observable which allows mixing and matching different tasks. This uses non-imperative coding style so beware!

A: Your problem seems to be a modified version of the Observer Pattern.
The solution below is more general than as it allows dependency on a list of tasks to proceed.
Create  a class Task as follows:
class Task{
List<Task> partialCompletionSuccessors;//List of tasks dependent on the partial completeion of this Task
List<Task> fullCompletetionSuccessors;//List of tasks dependent on the full completeion of this Task

List<Task> partialCompletionPredeccessor;//List of tasks that this task depends on their partial completion to start
List<Task> fullCompletetionPredeccessor;//List of tasks that this task depends on their full completion to start

private void notifySuccessorsOfPartialCompletion(){
    for(Task task: partialCompletionSuccessors){
           task.notifyOfPartialCompletion(this);
    }

}

private void notifySuccessorsOfFullCompletion(){
    for(Task task: fullCompletetionSuccessors){
           task.notifyOfPartialCompletion(this);
    }

}

private tryToProcceed(){
 if(partialCompletionPredeccessor.size() == 0 && fullCompletetionPredeccessor.size()==0 ){
     //Start the following task...
      ....
     //When this task partially completes
    notifySuccessorsOfPartialCompletion();

      //When this task fully completes
      notifySuccessorsOfFullCompletion();

  }

}

public void notifyOfPartialCompletion(Task task){// A method to notify the following task that a predeccessor task has partially completed
      partialCompletionPredeccessor.remove(task);
      tryToProcceed();

}

public void notifyOfFullCompletion(Task task){// A method to notify the following task that a predeccessor task has partially completed
      fullCompletetionPredeccessor.remove(task);
      tryToProcceed();

}

}

A: This question is very loaded. I can see at least three different subsystems in your design:

*

*task DAG (partial completion to me just means you actually have 2 nodes instead of 1), which can be persisted in a database for example;

*work queue, where the next task to execute must be enqueued (this could be some kind of message queue, again for persistence/transactionality);

*the actual execution framework, which might involve accessing external resources like services/databases and can potentially be distributed.

Your description is very high level so you could start designing the abstractions you need for these three pieces and how they interact with each other (in terms of interfaces).
Once you have all of that, you can start providing some simple implementations. I would start from a "local mode", using a simple in memory DAG, a blocking queue and some type of java executor.
Your question does not provide details on SLA, length of jobs, failure/retry policies, transactions, etc., so it's hard to say how your modules should be implemented. But I suggest to think in terms of high level abstractions and iterate on the implementations. Great code will never fix bad design.
You could stop there, or start replacing each implementation with third party products if you need to.

A: There is a framework specifically dedicated for this purpose, called Dexecutor, with Dexecutor, you model your requirements in terms of graph, when in comes to execution, dexecutor would take care of it executing it in reliable way.
For example :
@Test
public void testDependentTaskExecution() {

    ExecutorService executorService = newExecutor();
    ExecutionEngine<Integer, Integer> executionEngine = new DefaultExecutionEngine<>(executorService);

    try {
        DefaultDependentTasksExecutor<Integer, Integer> executor = new DefaultDependentTasksExecutor<Integer, Integer>(
                executionEngine, new SleepyTaskProvider());

        executor.addDependency(1, 2);
        executor.addDependency(1, 2);
        executor.addDependency(1, 3);
        executor.addDependency(3, 4);
        executor.addDependency(3, 5);
        executor.addDependency(3, 6);
        executor.addDependency(2, 7);
        executor.addDependency(2, 9);
        executor.addDependency(2, 8);
        executor.addDependency(9, 10);
        executor.addDependency(12, 13);
        executor.addDependency(13, 4);
        executor.addDependency(13, 14);
        executor.addIndependent(11);

        executor.execute(ExecutionConfig.NON_TERMINATING);

        Collection<Node<Integer, Integer>> processedNodesOrder = Deencapsulation.getField(executor, "processedNodes");
        assertThat(processedNodesOrder).containsAll(executionOrderExpectedResult());
        assertThat(processedNodesOrder).size().isEqualTo(14);

    } finally {
        try {
            executorService.shutdownNow();
            executorService.awaitTermination(1, TimeUnit.SECONDS);
        } catch (InterruptedException e) {

        }
    }
}

private Collection<Node<Integer, Integer>> executionOrderExpectedResult() {
    List<Node<Integer, Integer>> result = new ArrayList<Node<Integer, Integer>>();
    result.add(new Node<Integer, Integer>(1));
    result.add(new Node<Integer, Integer>(2));
    result.add(new Node<Integer, Integer>(7));
    result.add(new Node<Integer, Integer>(9));
    result.add(new Node<Integer, Integer>(10));
    result.add(new Node<Integer, Integer>(8));
    result.add(new Node<Integer, Integer>(11));
    result.add(new Node<Integer, Integer>(12));
    result.add(new Node<Integer, Integer>(3));
    result.add(new Node<Integer, Integer>(13));
    result.add(new Node<Integer, Integer>(5));
    result.add(new Node<Integer, Integer>(6));
    result.add(new Node<Integer, Integer>(4));
    result.add(new Node<Integer, Integer>(14));
    return result;
}

private ExecutorService newExecutor() {
    return Executors.newFixedThreadPool(ThreadPoolUtil.ioIntesivePoolSize());
}

private static class SleepyTaskProvider implements TaskProvider<Integer, Integer> {

    public Task<Integer, Integer> provideTask(final Integer id) {

        return new Task<Integer, Integer>() {

            private static final long serialVersionUID = 1L;

            public Integer execute() {
                if (id == 2) {
                    throw new IllegalArgumentException("Invalid task");
                }
                return id;
            }
        };
    }
}

Here is the modeled graph

This means tasks # 1 , 12 and 11 would run in parallel, once one of them finishes its dependent tasks would kick off, for example once task#1 finishes, its dependent tasks #2 and #3 would kick off

A: Abstracting from the multithreading
class TaskA{
    SimpleTask Y;
    SimpleTask Z;

    SimpleTask PJ;
    SimpleTask RJ;

    Run(){
        // do the partial job
        PJ.Run();
        Y.Run();
        // do the remaining job
        RJ.Run();
        Z.Run();
        // return;
    }
}

class TaskB{
    TaskA P;
    SimpleTask J;

    Run(){
        // do the job
        J.Run();
        P.Run();
        // return;
    }
}


text:
Q: Evitar desbordamiento de numeros Estoy haciendo un programa basico que hace cálculos con números muy grandes, lo que hago es leerlo como String y la idea es que a cada dígito del numero lo multiplico por un numero grande (por ejemplo 100000).
#include <stdio.h>
#include <string.h>
#include <math.h>

int main( ) {
  char cadena[1000];
  char cadena2[1000];

  scanf( "%s", cadena2 );

  for( unsigned i = 0; i < strlen( cadena2 ); ++i ) {
    cadena[i] = cadena2[i] - '0';
    cadena[i] *= 100000;
    cadena[i] = cadena[i] + '0';
  }

  printf( "%s", cadena);

  return 0;
}

pero lógicamente se desborda y a la hora de imprimir, es decir no sale lo esperado.
Mi duda es como puedo guardar un numero tan grande que únicamente se deba leer como String ?
Gracias!

PD: Ya habia hecho un pregunta asociado a este tema Operación con valor numérico de un dígito no arroja resultado esperado

A: Si quieres multiplicar cada dígito por 100000, de entrada, tu cadena destino ha de tener un tamaño acorde: 1000 * 100000. El resultado de eso es ... algo mas de 95M.
Usaremos formaciones ... pero, en previsión de problemas de tamaño, las crearemos de forma dinámica (podemos tener problemas con el límite de tamaño para la pila del Sistema Operativo).
Tenemos que tener en cuenta el tamaño de los tipos ... una multiplicación por 100000 no cabe en un char, puesto que el propio char solo admite en el rango 0 - 255. Así que mejor usamos int para estas cosas.
Y, por último, para facilitarnos la vida, usaremos la función sprintf( ). Esta función es similar a printf( ), pero, en lugar de en un archivo, escribe en un buffer de memoria (que tenemos que gestionar nosotros). Es justamente lo que estamos buscando:
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>

int main( ) {
  char *resultado = malloc( 1000 * 100000 );
  char *iterator = resultado;
  char entrada[1000];

  scanf( "%s", entrada );

  for( unsigned i = 0; i < strlen( entrada ); ++i ) {
    entrada[i] -= '0';
    iterator += sprintf( iterator, "%d", entrada[i] * 100000 );
  }

  printf( "%s", resultado );

  return 0;
}

A: Si tu escaneas un número como cadena, no obtienes el número como tal sino su representación en forma de caracteres. Es decir:
        00   01   02   03  <- offset memoria
123 ->  '1'  '2'  '3' '\0' <- caracteres
       0x30 0x31 0x32 0x00 <- representación hexadecimal

Así pues, el número 123, almacenado como cadena, resulta en la siguiente secuencia numérica (en hexadecimal): 30313200.
Es facil ver que, en este caso, coger cualquiera de esos caracteres y multiplicarlo por 100000 no va a darte el resultado esperado.
Si optas por almacenar un número como secuencia de caracteres, tendrás que implementar todas las operaciones matemáticas involucradas, ya que la librería estándar no tiene ninguna utilidad al respecto. También podrías usar una librería de terceros.
Es decir, para sumar números podrías hacer algo tal que:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char* ReverseArray(char const* arr, size_t size)
{
  char* result = (char*)malloc(size * sizeof(char));
  for (size_t i = 0, j=size-1; i < size; ++i, --j)
  {
      result[j] = arr[i];
  }

  return result;
}

char* SumarNumerosGrandes(char const* numero1, char const* numero2)
{
  size_t length1 = strlen(numero1);
  size_t length2 = strlen(numero2);
  if( length2 > length1 )
    return SumarNumerosGrandes(numero2, numero1);

  // Invertimos los números para simplificar las operaciones
  char* sec1 = ReverseArray(numero1, length1);
  char* sec2 = ReverseArray(numero2, length2);
  char* resultado = (char*)malloc((length1 + 3) * sizeof(char));

  size_t i;
  int acarreo = 0;
  for( i=0; i<length1; i++ )
  {
    int suma = (sec1[i] - 0x30) + acarreo;
    if( i < length2 )
      suma += (sec2[i] - 0x30);

    acarreo = 0;
    if( suma >= 10 )
    {
      acarreo = 1;
      suma -= 10;
    }

    resultado[i] = suma + 0x30;
  }

  if( acarreo != 0 )
  {
    resultado[i++] = acarreo + 0x30;
  }

  resultado[i] = '\0'; // Finalizamos el array

  char* toReturn = ReverseArray(resultado, i);

  // Liberamos la memoria dinámica
  free(sec1);
  free(sec2);
  free(resultado);

  return toReturn;
}


text:
Q: "Sys is undefined" error because WebResource.axd is returning the wrong content I'm getting the dreaded "Microsoft JScript runtime error: 'Sys' is undefined" error while trying to develop a site in ASP.NET on .NET framework 4.0.  This was working fine until I tried programmatically adding items to a menu, and this started happening.  While debugging, I pointed Fiddler at my app and found that the request for the WebResource.axd is returning successfully (code == 200), but the response text is  the whole html page and NOT the javascript that it is supposed to be returning, and this is why Sys is undefined.
What's going on here?  Any help much appreciated.  Thanks.

A: Solved, thanks to this.  I'm using ASP.NET Routing, and I was routing root level requests like http://www.mysite.com/{PageId}, and this matching pattern is so general that it was also matching the request for /WebResource.axd, and that's why the page request for the axd file was being routed to an aspx page instead of the usual handler.  Not what I would have expected, but I can see the logic.
The fix is to tell the routing system to ignore this particular kind of request:
RouteTable.Routes.Ignore("{resource}.axd/{*pathInfo}")


text:
Q: Replace null varchar fields with empty string for whole db I'm rebuilding a legacy program for a client ... the database is relatively well designed the only thing I don't care for is all the null varchar values ... (personally don't care for handing this in my client code ... )
I'm trying to replace all null varchar columns with empty strings ... normally I would do this in my import script but I don't need to modify the schema so I'm not going to do an import script ...
wondering if any of you slick SQL guys /girls know a way to foreach (varchar column in db) replace null with '' kinda thing?
I know there must be a way ... P.S. MSSQL 2008r2 DB

A: Personally I think it's a bad idea to replace null with empty string.
But you asked for it, so here it is
UPDATE table1 SET field1 = '' WHERE field1 IS NULL

The other option is to solve it in your select statements:
SELECT coalesce(field1, '') as field1_excl_nulls FROM table1

This will replace null in the output with empty strings, whilst still leaving the null inside the database.

A: To do this, you can build dynamic SQL statement:
  declare @sSQl nvarchar(max)=''
SELECT
@sSQl=@sSQl+'UPDATE ['+TABLE_NAME+ '] SET ['+COLUMN_NAME+']='''''+' WHERE ['+COLUMN_NAME+ '] IS NULL'+CHAR(13)
 FROM  INFORMATION_SCHEMA.COLUMNS
WHERE DATA_TYPE LIKE '%CHAR%'

exec sp_executesql @ssql


text:
Q: sql isn't in GROUP BY using query builder laravel
I want to take how much amount of data based on the product_id taken from the table vote. on laravel this query does not work well but when i try it in mysql i run it fine is there any other solution?
this is a successfully executed query through mysql :
select count(product_id) as total, `v`.*, `p`.`name` from `votes` as `v` left join `products` as `p` on `p`.`id` = (select p1.id from products as p1 where v.product_id = p1.id ) group by v.product_id

result :

and it's a query on laravel that I use using query builder :
$count = DB::table('votes as v')->leftJoin('products as p',function($join){
  $join->on('p.id','=',DB::raw('(select p1.id from products as p1 where v.product_id = p1.id )'));
})->select(DB::raw('count(*) as total'),'v.*','p.name')->groupBy('v.product_id')->get();
dd($count);

and i got this error :

"SQLSTATE[42000]: Syntax error or access violation: 1055
  'lookbubbledrink.v.id' isn't in GROUP BY (SQL: select count() as
  total, v., p.name from votes as v left join products as
  p on p.id = (select p1.id from products as p1 where v.product_id
  = p1.id ) group by v.product_id

I have to use group by product_id only to calculate how much amount of data based on the number of product_id in the vote.

A: You are using strict mode in laravel. By the you can tweak it to your needs.
got to config/database.php  in set strict=>false and you are good to go.
  'mysql' => [
            'driver' => 'mysql',
            'host' => env('DB_HOST', '127.0.0.1'),
            'port' => env('DB_PORT', '3306'),
            'database' => env('DB_DATABASE', 'forge'),
            'username' => env('DB_USERNAME', 'forge'),
            'password' => env('DB_PASSWORD', ''),
            'unix_socket' => env('DB_SOCKET', ''),
            'charset' => 'utf8mb4',
            'collation' => 'utf8mb4_unicode_ci',
            'prefix' => '',
            'strict' => false,
            'engine' => null,
        ],


text:
Q: Line integrals and vector fields We had this example in class the other day, and the professor didn't not walk through how he obtained it.
Compute $\int_C \vec f \cdot d\vec r = \langle 4x^3y^2 - 2xy^3, 2x^4y - 3x^2y^2 + 4y^3\rangle$
The answer was written as $F(x,y) = x^4y^2 - x^2y^3 + y^4$
Maybe someone can confirm I did it the right way,
here's my work:
$$P_y = 8x^3y - 6xy^2$$
$$Q_x = 8x^3y - 6xy^2$$
So it might be the gradient field, since they agree.
$$F_x = 4x^3y^2 - 2xy^3$$
$$\int F_x \ dx = x^4y^2 - x^2y^3 + g'(y)$$
$$F_y = 2x^4y - 3x^2y^2 + 4y^3$$
$$\int F_y \ dy = x^4y^2 - x^2y^3 + y^4$$
So $g'(y)$ is supposed to be $y^4$ since I guess $\int F_x \,dx$ and $\int F_y \,dy$ are supposed to be equal?
Then $F(x,y) = x^4y^2 - x^2y^3 + y^4$

A: A couple of things. First, the answer is not $F(x,y)$; this is the gradient field. Presumably the answer is really $F(a_2,b_2)-f(a_1,b_1)$ where these are the endpoints of $C$. Now, as to your method, it's almost OK. It's more usual to do what you did by integrating $F_x$, then differentiate with respect to $y$ and compare that with $F_y$. The way you did things, the integral of $F_y$ should also have a term $+h(x)$, and you must do more work to convince yourself of the correct answer. (And, why did you call the function you got $g'(y)$ instead of $g(y)$?).
So: $\int F_x\,dx = x^4y^2 - x^2y^3 + g(y)$; then the derivative with respect to $y$ of this function is $2x^4y - 3x^2y^2 + g'(y)$, which must equal $2x^4y - 3x^2y^2 + 4y^3$, so that $g'(y) = 4y^3$ and therefore $g(y) = y^4+C$. Thus $F(x,y) = x^4y^2 - x^2y^3 + y^4 + C$.


text:
Q: Way to simplify functions? Is there a way to create a class or something that can contain all these different textboxes. I just want to know if this is the most efficient way I can code this.
private void textBox1_Click(object sender, EventArgs e)
        {
            textBox1.Text = "";
        }

        private void textBox2_Click(object sender, EventArgs e)
        {
            textBox2.Text = "";
        }

        private void textBox3_Click(object sender, EventArgs e)
        {
            textBox3.Text = "";
        }
        private void textBox4_Click(object sender, EventArgs e)
        {
            textBox4.Text = "";
        }
        private void textBox5_Click(object sender, EventArgs e)
        {
            textBox5.Text = "";
        }

A: Don't create separated event handlers for each TextBoxes. Instead, create a combined event for all the TextBoxes: textBox1..textBox5.
Then
private void textBoxs_Click(object sender, EventArgs e)
{
    if (sender is TextBox box) box.Text = "";
}

A: You can add the event handler to all the TextBoxes on load, eg
protected override void OnLoad(EventArgs e)
{
    base.OnLoad(e);

    foreach(var tb in this.Controls.OfType<TextBox>())
    {
        tb.Click += (sender, eventArgs) => ((TextBox)sender).Text = "";
    }
}


text:
Q: Dois botões para executar a mesma função? Gostaria que ao clicar em dois botões distintos os mesmos executassem a mesma função alterando apenas um valor.
No codigo abaixo consigo executar a função clicando no primeiro botão, porém quando clico no segundo não executa. Como posso proceder para realizar esta operação?

1) Botao:

Pagar com Cartão

2) Botao:
Gerar Boleto

A: O id dos botões não podem ser repetidos apenas as classes. O id é um identificador único.
O que você pode fazer é alterar o id do botão 2 para btn_pag2 e no seu seletor jquery fazer isso
$('#btn_pag,#btn_pag2')..on("click",function(){

A: Você está tentando usar o ID como se fosse uma classe, para selecionar vários elementos.
Quando o jQuery encontra o seletor de ID (i.e. #id), ele usa um método especializado do browser (getElementById), que retorna apenas o primeiro elemento com o ID especificado... por isso funciona para o primeiro botão e não para o segundo.
Você poderia, ao invés de definir o ID de ambos os elementos, definir uma classe chamada btn_pag para ambos, e então selecioná-los usando o seletor de classe (i.e. .classe):
HTML:
Pagar com Cartão
Gerar Boleto

Javascript:
$(document).ready(function(){
    $('.btn_pag').on("click", function() {

        var value = $(this).attr('value'); // Ao clicar no botao alterar apenas esse valor!

        alert(value);

        // .... restante do código
    });

});

jsfiddle de exemplo


text:
Q: Why this disable attribute in option tag not working? Where is the problem? I have designed a HTML webpage, and in my option tag I have set disabled="true", but it is not disabling the option.
Things I have tried -

*

*disabled="true"

*disabled="disabled"

*$(".dis").prop("disabled", true);
My code -

$(document).ready(function() {
  var $selects = $('select');
  $selects.on('change', function() {
    $("option", $selects).prop("disabled", false);
    $selects.each(function() {
      var $select = $(this),
        $options = $selects.not($select).find('option'),
        selectedText = $select.children('option:selected').text();
      $options.each(function() {
        if ($(this).text() == selectedText) $(this).prop("disabled", true);
      });
    });
  });

  $selects.eq(0).trigger('change');
});

var countries = {
  "India": ".ind",
  "Australia": ".aus",
  "England": ".eng",
  "NewZealand": ".nz",
  "SouthAfrika": ".sa",
  "WestIndies": ".wi",
  "Pakistan": ".pak",
  "SriLanka": ".sl",
  "Bangladesh": ".ban",
  "Afganistan": ".afg"

}

function getValue1(obj) {
  var sel1 = (obj.value);
  console.log(sel1);
  var counval = countries[sel1];

  for (var key in countries) {
    var dictvalue = countries[key];
    var hidden1 = 'select[name="player1"] '.concat(dictvalue);
    var hidden2 = 'select[name="player2"] '.concat(dictvalue);
    console.log("Hiding ".concat(dictvalue));
    $(hidden1).hide();
    $(hidden2).hide();

  }
  $(counval).show();
  console.log("Showing ".concat(counval));
}

function getValue2(obj) {
  var sel2 = (obj.value);
  console.log(sel2)
}

<form action="" method="get">

      <select name="selectcountry1" id="c1" onchange="getValue1(this)" class="btn btn-secondary btn-lg dropdown-toggle" style="background-color: #5959a6;">
        <option value="select" class="dis" disabled="true" style="color: grey" selected>Select Country 1</option>
        <option value="India">India</option>
        <option value="Australia">Australia</option>
        <option value="England">England</option>
        <option value="NewZealand">New Zealand</option>
        <option value="SouthAfrika">South Afrika</option>
        <option value="WestIndies">West Indies</option>
        <option value="Pakistan">Pakistan</option>
        <option value="SriLanka">Sri Lanka</option>
        <option value="Bangladesh">Bangladesh</option>
        <option value="Afganistan">Afganistan</option>
      </select>

      <select name="selectcountry2" id="c2" onchange="getValue2(this)" class="btn btn-secondary btn-lg dropdown-toggle" style="background-color: #5959a6;">
        <option value="select" class="dis" disabled="true" style="color: grey" selected>Select Country 2</option>
        <option value="India">India</option>
        <option value="Australia">Australia</option>
        <option value="England">England</option>
        <option value="NewZealand">New Zealand</option>
        <option value="SouthAfrika">South Afrika</option>
        <option value="WestIndies">West Indies</option>
        <option value="Pakistan">Pakistan</option>
        <option value="SriLanka">Sri Lanka</option>
        <option value="Bangladesh">Bangladesh</option>
        <option value="Afganistan">Afganistan</option>
      </select>

</form>

Is there any other way to disable those options?
I don't want those options to be enabled throughout the project.

A: Attribute disabled sets without ='true'. You need just add this attribute into the options you want disabled
<option value="select" class="dis" disabled>

for setting this attribute on JavaScript, you need to write something like this
$('option.dis').attr('disabled');

for check option to disabled:
($('option.dis').prop('disabled') === true)

A: The  disabled attribute does not take a value. It's an attribute in and of itself.
Change:
<option value="select" class="dis" disabled="true" style="color: grey"selected>Select Country 1</option>
To:
<option value="select" class="dis" disabled style="color: grey"selected>Select Country 1</option>


text:
Q: Simplifying If-conditions Is there a way to simplify:
if(a == b || a == o || a == j || a ==....)
{
    ...
}

I thought I could do something like
if( a == (b || o || j || ...))
{
     ...
}

But that turned out to be incorrect syntax

A: create a method to take the value of a and a varargs of the other elements, then you can stream over the elements and check if any is equal to the value of a.
an example:
public boolean anyMatch(int a, int... values){
      return Arrays.stream(values).anyMatch(e -> e == a);
}

then you can call it like so:
if(anyMatch(a, o, j, b)){ ... };

A: I suppose your variables are integers.
List<Integer> values = Arrays.asList(b, o, j);
if (values.contains(a)){
...
}


text:
Q: How do I copy info from a specific cell from one workbook in excel and paste it to a specific cell to another workbook using Powershell? So basically I wanted to pull information from one cell, using a specific location, copy that info and paste it into a whole other workbook with a specific cell location all while using Powershell.
An example of this would be: copy from cell B2 in wb1 (sheet4) --> paste in A2 in wb2 (sheet3)
Also, I want to be able to do this multiple different times (for different cells of course)
I tried the below code and this just had me extracting the entire workbook to another work. I know there could be a way to pull a specific cell but I'm not sure how to do that just yet. Can someone please help?
$file1 = 'C:\Book1.xlsx' # <-- source file full path
$file2 = 'C:\Book2.xlsx' # <-- destination file full path
$xl = new-object -c excel.application
$xl.displayAlerts = $false # don't prompt the user
$wb2 = $xl.workbooks.open($file1, $null, $true) # open source, readonly
$wb1 = $xl.workbooks.open($file2) # open target
$sh1_wb1 = $wb1.sheets.item(1) # second sheet in destination workbook
$sheetToCopy = $wb2.sheets.item('Sheet3') # source sheet to copy
$sheetToCopy.copy($sh1_wb1) # copy source sheet to destination workbook
$wb2.close($false) # close source workbook w/o saving
$wb1.close($true) # close and save destination workbook
$xl.quit()
spps -n excel

P.S. There is an answered question about this but the code uses C#. Can it be translated to Powershell?
Thanks!

A: You can get/set a specific cell value with:
# source/target cell
$sourceRange = $wb1.Worksheets.Item('Sheet4').Range('B2','B2')
$targetRange = $wb2.Worksheets.Item('Sheet3').Range('A2','A2')

# copy source value to target
$targetRange.Value = $sourceRange.Value


text:
Q: How to append the first and last with " double quotes for dw variable in Dataweave mule %output application/json
%var EmpIds=flowVars.empIDMap.EmpIds
---
    payload map using(eNumber=$.EMPLOYEE) {
                content: EmpIds.eNumber,
}

If i add value within double quotes i am getting value for example EmpIds."6" for
Need to append the first and last with " double quotes to get the value from EmpIds based on eNumber.
empIDMap data is :: {EmpIds={6=2, 19=3, 21=4, 36=5, 168421=6, 167727=7, 167729=8, 161759=9, 162052=10, 157633=11}}
can you please help on this.

A: To get value as string try eNumber= $.EMPLOYEE ++ "". This works fine.


text:
Q: Show average value only if combination is present x number of times I have a table (airfare_data) containing the columns city1 (Origin), city2 (Destination), quarter, fare. There are many rows of flights recorded in the data, often between the same cities. I am trying to find the average fare per quarter, excluding routes that didn't take place in all 4 quarters.
I have the following command:
select distinct city1, city2, quarter, round(avg(fare),0)AvgF
FROM airfare_data
GROUP BY 1,2,3
ORDER BY 1,2,3;

It gives the following results
city1 city2   quarter AvgF
Albany, NY  Denver, CO  1   224
Albany, NY  Denver, CO  2   256
Albany, NY  Denver, CO  3   256
Albany, NY  Denver, CO  4   255
Albany, NY  Fort Myers, FL  1   200
As the combination of Albany, NY, and Fort Myers, FL only occurs in Q1 I would like to exclude it from my table, but I am not sure how. The original table includes multiple rows of the combination Albany, NY and Fort Myers, FL, so just want to show where any combination is present in all 4 Qs.
Can anybody help?

A: Use a having clause:
SELECT city1, city2, quarter, round(avg(fare),0) as AvgF
FROM airfare_data
GROUP BY 1,2,3
HAVING COUNT(*) > 1
ORDER BY 1,2,3;

SELECT DISTINCT is only very, very, very rarely used with GROUP BY.
EDIT:
For your revised question:
HAVING COUNT(DISTINCT quarter) > 1

or:
HAVING MIN(quarter) <> MAX(quarter)

A: Use COUNT() window function:
SELECT city1, city2, quarter, AvgF
FROM (
  SELECT city1, city2, quarter,
         ROUND(AVG(fare), 0) AvgF,
         COUNT(*) OVER (PARTITION BY city1, city2) counter
  FROM airfare_data
  GROUP BY city1, city2, quarter
) t
WHERE t.counter = 4
ORDER BY city1, city2, quarter


text:
Q: How Apache Kafka working with Spring boot application with OAuth This is producer
private void insertQueueEmail(EmailSendingRequestDTO emailSendingRequestDTO) {
    sender.kafkaSendEmail(emailSendingRequestDTO);
}

This is consumer
  // @PreAuthorize("isAuthentication()")
  @KafkaListener(topics = "emailTopic", groupId = "foo")
  public ResponseEntity<GECEorderResponseMessageDTO> insertEmailQueue(@RequestBody
         EmailSendingRequestDTO emailSendingRequestDTO) {
       ...... //do something
  }

Its work correctly, But when add @PreAuthorize("isAuthentication()") before @KafkaListener for validating access token I get 404 not found
I need to know how can I using Kafka to send message to consumer and working with @PreAuthorize annotation


text:
Q: Broken Hyperlinks when reseting section on part this seem very basic but i've already tried lots of thing without any success.
This is the tex that i am working on, and im compiling it in LuaTeX:
\documentclass[12pt]{article}

% Linguagem
\usepackage[portuguese]{babel}

%% Table of contents
\usepackage{tocloft}
\setcounter{tocdepth}{2}    % remove subsubsection from toc

% Multicols
\usepackage{multicol}
\setlength{\columnsep}{5mm}

% enumitem
\usepackage{enumitem} % modify enumerate index
\setlist[itemize]{left = -9mm}

%% titlesec
\usepackage{titlesec}

% Part customization
\titleclass{\part}{straight}
\titleformat{\part}
    [block]                         % shape
    {\huge\bfseries\color{Emph}}            % format
    {\thepart\hspace{5mm}{$|$}}         % label
    {5mm}                           % sep
    {\huge\bfseries}                    % before-code
    [\vspace{0.5mm}]
\counterwithin*{section}{part} % Reset section on part

% Maths
\usepackage{amsmath, amssymb}
\usepackage{bm} % Boldmath

\newcommand\BM[2][align*]{{\large\boldmath\bfseries%
    \begin{#1}
        #2
    \end{#1}%
}}

% Colors
\usepackage{xcolor}

\colorlet{Emph}{ blue!40!white}
\colorlet{Background}{white!5!black}

\pagecolor{black}
\color{white}

% mytitle and myauthor
\newcommand\mytitle{{my title}}
\newcommand\myauthor{{my author}}

% title, author and date
\title{\bfseries\color{Emph}\mytitle}
\author{\myauthor}
\date{\today}

% hyperref
\usepackage{hyperref}
\hypersetup{
    % Links customization
    hidelinks=true,
    colorlinks=true,
    linkcolor=red!25!white,
    % PDF customization
    pdfpagelayout=OneColumn,
    pdftitle=\mytitle,
    pdfauthor=\myauthor
    % fix hyperref links
    hypertexnames=false
    destlabel=false,
    plainpages=false,
    naturalnames=false
}

% subsubsection customization
\renewcommand\thesubsubsection{(\roman{subsubsection})}

\begin{document}

\maketitle

% Table of Contents

\renewcommand{\contentsname}{} % remove title

\section*{Conteúdo}
\begin{multicols}{2} \tableofcontents \end{multicols}

\newpage

\part{Background}

\newpage

\part{Topologia Elementar na Reta $\mathbb{R}$}
\label{topologia elementar na reta r}

\section{Vizinhança $V_{\epsilon}$}
\label{vizinhanca}

\section*{Pontos:}
\label{pontos}

% Majorante e Minorante
\begin{multicols}{2}

    \section{Minorante}
    \label{minorante}

    \section{Majorante}
    \label{majorante}

\end{multicols}

% Infimo e Supremo
\begin{multicols}{2}

    \section{Infimo Inf}
    \label{Infimo}

    \section{Supremo Sup}
    \label{Supremo}

\end{multicols}

% Minimo e Maximo
\begin{multicols}{2}

    \section{Minimo Min}
    \label{minimo}

    \section{Maximo Max}
    \label{maximo}

\end{multicols}

% Interior e Exterior
\begin{multicols}{2}

    \section{Interior Int}
    \label{interior}

    \section{Exterior Ext}
    \label{exterior}

\end{multicols}

\section{Ponto de Acumulação}
\label{ponto de acumulacao}

\section{Fronteira Fr}
\label{fronteira}

\section*{Conjuntos:}
\label{conjuntos}

\section{Limitado}
\label{conjunto limitado}

\begin{multicols}{2}

    \section{Aberto}
    \label{conjunto aberto}

    \section{Fechado}
    \label{conjunto fechado}

\end{multicols}

% Feixe e Ponto de Acumulação
\begin{multicols}{2}

    \section{Feixe $\overline X$}
    \label{feixe}

\end{multicols}

\newpage

\part{Indução Matemática}
\label{inducao matematica}

\section{Indução por Igualdade}
\label{inducao por igualdade}

\section{Indução por Desigualdade}
\label{inducao por desigualdade}

\newpage

\part{Sucessões}
\label{sucessoes}

\section{Sucessão Monótona}
\label{sucessao monotona}

\begin{multicols}{2}

    \subsection{Crescente}
    \label{sucessao monotona crescente}

    \subsection{Decresente}
    \label{sucessao monotona decrescente}

\end{multicols}

\section{Sucessão Limitada}
\label{sucessao limitada}

\section{Sucessão Convergente}
\label{sucessao convergente}

\section{Demonstrações para Sucessões}

\begin{multicols}{2}

\BM[flalign*]{
&
    X \text{ é \hyperref[sucessao convergente]{convergente}}
\implies &\\&
\implies
    X \text{ é \hyperref[sucessao limitada]{limitada}}
&
}

\BM[flalign*]{
&
    X \text{ é \hyperref[sucessao monotona]{monotona} e \hyperref[sucessao limitada]{limitada}}
\implies &\\&
\implies
    X \text{ é \hyperref[sucessao convergente]{convergente}}
&
}

\end{multicols}

\newpage

\part{Limites}

\newpage

\part{Continuidade em $\mathbb{R}$}

\end{document}

Everything seem in place but the output pdf have lots of links in the wrong place i've already tried fixing hyperref with the following fixes:

*

*hypertexnames=false

*destlabel=false

*plainpages=false

*naturalnames=false

And even through hypertexnames=false alone previously fixed this problem in other files, in this one it seems to be useless.

A: As suggested by @UlrikeF, Adding \renewcommand\theHsection{\thepart.\thesection} just after \hypersetup{...} solves the problem


text:
Q: Storm-Crawler integration with Cassandra and build topology in Gradle I tried to implement Storm-Crawler in my project but I need to work with Cassndra and Gradle. I have fun with Storm-Crawler and ElasticSearch stack but in this situatiom I'm forced to use this solutions. I tried a several times build uber jar with gradle but without success. Did anyone build Storm-Crawler topology in gradle? I configure Apache-Storm to use Cassandra but how put data from Strom-Crawler into Cassandra?

A: Can't help with Gradle I am afraid but for the Cassandra part: do you want to store the content and metadata of the documents in it or use it for storing the info about the URLs too (as done with the status index in ES)? For the former, implement your own indexer extending AbstractIndexerBolt, for the latter, you'll need a status updater and spout, which is a bit more complex.


text:
Q: How to rename many files, using a prefix ID? I have 103 directories. These directories are named as PJA_XXX, where XXX is a number from 71 to 174. Inside each PJA_XXX folder I have a file under the next path: PJA_XXX/results/variants/variants.vcf.
I want to rename the variants.vcf file adding  the prefix of the PJA_XXX directory that contains it. So the expected result would be PJA_XXX_variants.vcf.
I think I could do it with a shell loop, but I don't know how to take the name of the PJA_XXX folder n order to rename the file.

A: You can use a loop variable, and reference it using ${loop_variable_name} in your command.
Use...
for directory_name in PJA_*; do
    echo "Processing ${directory_name}."
    mv "${directory_name}/results/variants/variants.vcf" "${directory_name}/results/variants/${directory_name}_variants.vcf"
done

...to modify the file structure like...
PJA_001
└── results
    └── variants
        └── variants.vcf
PJA_002
└── results
    └── variants
        └── variants.vcf
PJA_003
└── results
    └── variants
        └── variants.vcf
PJA_004
└── results
    └── variants
        └── variants.vcf
PJA_005
└── results
    └── variants
        └── variants.vcf

...into the file structure like this...
PJA_001
└── results
    └── variants
        └── PJA_001_variants.vcf
PJA_002
└── results
    └── variants
        └── PJA_002_variants.vcf
PJA_003
└── results
    └── variants
        └── PJA_003_variants.vcf
PJA_004
└── results
    └── variants
        └── PJA_004_variants.vcf
PJA_005
└── results
    └── variants
        └── PJA_005_variants.vcf


text:
Q: Google map SDK version 1.5 integrate with iOS 7 application when google map SDK version 1.5 integrate with iOS 7. I got this error.
ld: warning: ignoring file /Users/apps/Desktop/Map/GoogleMaps.framework/GoogleMaps, missing required architecture x86_64 in file /Users/apps/Desktop/Map/GoogleMaps.framework/GoogleMaps (3 slices)
Undefined symbols for architecture x86_64:
"_OBJC_CLASS_$_GMSCameraPosition", referenced from:
  objc-class-ref in MapViewController.o
"_OBJC_CLASS_$_GMSMapView", referenced from:
  objc-class-ref in MapViewController.o
"_OBJC_CLASS_$_GMSMarker", referenced from:
  objc-class-ref in MapViewController.o
"_OBJC_CLASS_$_GMSServices", referenced from:
  objc-class-ref in MapAppDelegate.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

I don't know how solve the problem,can anyone know help me to solve this problem.

A: The key part of the error is the bit that says: symbol(s) not found for architecture x86_64.
I am guessing you are building for the arm64bit and the Google Maps SDK doesnt have a 64 bit version.
Try building for armv7, armv7s only


text:
Q: excel string comparison issue So I am trying to create a pretty simple macro that loops through a certain row looking for a value which is identified in a different sheet.  Once that value is found it starts to look in that resultant column for a text string.  If the text string is found, it grabs the value within the same row but a couple columns over and writes it to the sheet which has the user defined look up value.  My problem is that for some reason when I am trying to compare the strings my conditional if statement is not being achieved, meaning that the part which writes the final value is never being evaluated.Here is the code and thanks in advance.
Private Sub valchange()
Dim keycells As Range
Set keycells = Worksheets("Dashboard").Range("B1")
Dim k As Integer
k = 5
        For I = 1 To 50
            If Worksheets("Rework List").Cells(3, I).Value = keycells.Value Then
                For j = 14 To 50
                    If UCase(Worksheets("Rework List").Cells(j, I)) = "*PENDING*" Then
                            Cells(j, 3).Value = Worksheets("Dashboard").Range("F" & k)
                            k = k + 1
                    End If
                Next j
            End If
        Next I
End Sub

A: other than what @vacip already told you, I'd point out the following
you wrote:

it grabs the value within the same row but a couple columns over and
  writes it to the sheet which has the user defined look up value

then I think:
Cells(j, 3).Value = Worksheets("Dashboard").Range("F" & k)

would do quite the opposite (provided the active sheet at macro start is "Rework List")!
moreover its' better to:

*

*declare rows index variables as of Long type
though not strictly necessary in your specific case (they range to a maximum of 50, which is handled by an Integer type), it's quite common you would eventually face some 33k+ rows, and that's where Long type variable must enter the scene

*store the keyword value instead of its range, and avoid all subsequent accesses to it with keycells.Value

*always adopt fully qualified range references up to the worksheet object at least (if not the workbook one)
so you could try this:
Option Explicit

Private Sub valchange()
    Dim keyVal As String
    Dim k As Long, i As Long, j As Long

    keyVal = CStr(Worksheets("Dashboard").Range("B1").Value)
    k = 5
    With Worksheets("Rework List")
        For i = 1 To 50
            If .Cells(3, i).Value = keyVal Then
                For j = 14 To 50
                    If InStr(.Cells(j, i), "pending", vbTextCompare) > 0 Then
                        Worksheets("Dashboard").Range("F" & k) = .Cells(j, 3).Value
                        k = k + 1
                    End If
                Next j
            End If
        Next i
    End With
End Sub

A: You can't use joker characters in string comparisons in VBA like that.
Instead, use the Instr() function to search for a string within another string.
If instr(1,Worksheets("Rework List").Cells(j, I),"pending",vbTextCompare)>0 Then

If the search string can be found within the second string, instr returns the first character's position. If it can't be found, it returns a 0. So if instr()>0 that means the string is there.
vbTextCompare makes sure casing (upper/lower case) is ignored. The 1 at the beginning specifies the starting position for the search.
Note that this is not the fastest thing in the world...


text:
Q: Efficient way to write a lot of lines to a text file I started off doing something as follows:
using (TextWriter textWriter = new StreamWriter(filePath, append))
{
    foreach (MyClassA myClassA in myClassAs)
    {
        textWriter.WriteLine(myIO.GetCharArray(myClassA));

        if (myClassA.MyClassBs != null)
            myClassA.MyClassBs.ToList()
                .ForEach(myClassB =>
                    textWriter.WriteLine(myIO.GetCharArray((myClassB)));

        if (myClassA.MyClassCs != null)
            myClassA.MyClassCs.ToList()
                .ForEach(myClassC =>
                    textWriter.WriteLine(myIO.GetCharArray(myClassC)));
    }
}

This seemed pretty slow (~35 seconds for 35,000 lines).
Then I tried to follow the example here to create a buffer, with the following code, but it didn't gain me anything.  I was still seeing times around 35 seconds.  Is there an error in how I implemented the buffer?
using (TextWriter textWriter = new StreamWriter(filePath, append))
{
    char[] newLineChars = Environment.NewLine.ToCharArray();
    //Chunk through 10 lines at a time.
    int bufferSize = 500 * (RECORD_SIZE + newLineChars.Count());
    char[] buffer = new char[bufferSize];
    int recordLineSize = RECORD_SIZE + newLineChars.Count();
    int bufferIndex = 0;

    foreach (MyClassA myClassA in myClassAs)
    {
        IEnumerable<IMyClass> myClasses =
            new List<IMyClass> { myClassA }
                .Union(myClassA.MyClassBs)
                .Union(myClassA.MyClassCs);

        foreach (IMyClass myClass in myClasses)
        {
            Array.Copy(myIO.GetCharArray(myClass).Concat(newLineChars).ToArray(),
                0, buffer, bufferIndex, recordLineSize);

            bufferIndex += recordLineSize;

            if (bufferIndex >= bufferSize)
            {
                textWriter.Write(buffer);

                bufferIndex = 0;
            }
        }
    }

    if (bufferIndex > 0)
        textWriter.Write(buffer);
}

Is there a better way to accomplish this?

A: I strongly suspect that the majority of your time is not spent in the I/O. There's no way that it should take 35 seconds to write 35,000 lines, unless those lines are really long.
Most likely, the majority of time is spent in the GetCharArray method, whatever that does.
A few suggestions:
If you really think I/O is the problem, increase the stream's buffer size. Call the StreamWriter constructor that lets you specify a buffer size. For example,
using (TextWriter textWriter = new StreamWriter(filePath, append, Encoding.Utf8, 65536))

That'll perform better than the default 4K buffer size. Going higher than 64K for the buffer size is not generally useful, and can actually decrease performance.
Don't pre-buffer lines or append to a StringBuilder. That might give you small performance increases, but at a huge cost in complexity. The small performance boost isn't worth the maintenance nightmare.
Take advantage of foreach. You have this code:
if (myClassA.MyClassBs != null)
    myClassA.MyClassBs.ToList()
        .ForEach(myClassB =>
            textWriter.WriteLine(myIO.GetCharArray((myClassB)));

That has to create a concrete list from whatever MyClassBs collection is, and then enumerate it. Why not just enumerate the thing directly:
if (myClassA.MyClassBs != null)
{
    foreach (var myClassB in myClassA.MyClassBs)
    {
        textWriter.WriteLine(myIO.GetCharArray((myClassB)));
    }
}

That will save you the memory required by the ToList, and the time it takes to enumerate the collection when creating the list.
All that said, it's almost certain that your GetCharArray method is the thing that's taking all the time. If you really want to speed up your program, look there. Trying to optimize writing to the StreamWriter is a waste of time. You're not going to get significant performance increases there.

A: I threw together a simple snippet that I think is a bit cleaner; but, then again, I'm not quite sure what you are trying to accomplish. Also, I don't have any of your classes available, so I can't really do any kind of tests.
This sample does basically the same thing you have; except that it uses some generic methods, and it does all the writing in one spot.
string filePath = "MickeyMouse.txt";
bool append = false;
List<MyClassA> myClassAs = new List<MyClassA> { new MyClassA() };
    List<char[]> outputLines = new List<char[]>();

foreach (MyClassA myClassA in myClassAs)
{
    outputLines.Add(myIO.GetCharArray(myClassA));

    if (myClassA.MyClassBs != null)
        outputLines.AddRange(myClassA.MyClassBs.Select(myClassB => myIO.GetCharArray(myClassB)));

    if (myClassA.MyClassCs != null)
        outputLines.AddRange(myClassA.MyClassCs.Select(myClassC => myIO.GetCharArray(myClassC)));
}

var lines = outputLines.Select(line => string.Concat<char>(line));
if (append)
    File.AppendAllLines(filePath, lines);
else
    File.WriteAllLines(filePath, lines);

Here's the StringBuilder version:
string filePath = "MickeyMouse.txt";
bool append = false;
List<MyClassA> myClassAs = new List<MyClassA> { new MyClassA() };
StringBuilder outputLines = new StringBuilder();

foreach (MyClassA myClassA in myClassAs)
{
    outputLines.Append(myIO.GetCharArray(myClassA));

    if (myClassA.MyClassBs != null)
        myClassA.MyClassBs.ForEach(myClassB=>outputLines.Append(myClassB));

    if (myClassA.MyClassCs != null)
        myClassA.MyClassCs.ForEach(myClassC => outputLines.Append(myClassC));
}

if (append)
    File.AppendAllText(filePath, outputLines.ToString());
else
    File.WriteAllText(filePath, outputLines.ToString());

A: Use buffered stream for writing
e.g. for buffered writing to Console use
TextWriter w = new StreamWriter(new BufferedStream(Console.OpenStandardOutput()));
    w.WriteLine("Your text here");

similarly for buffered writing to file use
TextWriter w = new StreamWriter(new BufferedStream(new FileStream("myFilePath.txt", FileMode.Create)));
w.WriteLine("Your text here");


text:
Q: Socket.io Client error 404 not found I am getting a 404 error (client side) on productive system. If i run the server in local network, everything is fine.

Failed to load resource: the server responded with a status of 404 (Not Found)
GET https://foo.com/socket.io/?EIO=3&transport=polling&t=MGd8e2F 404 (Not Found)

I am using socket.io Version 2.1.1 and Express 4.
Server.js
...
var http = require('http');
var https = require('https');
var app = express();
httpServer = http.createServer(app);
httpsServer = https.createServer(options, app);
...
const io = require('socket.io')(httpsServer);

httpServer.listen(process.env.SERVER_HTTP_PORT);
httpsServer.listen(process.env.SERVER_HTTPS_PORT);

io.use(function (socket, next) {
    //Middleware (express-session)
    e_session(socket.request, socket.request.res, next);
});
io.on('connection', function (client) {
   ...
}

client.js
const socket = io('https://' + window.location.hostname + ':443');

socket.on('connect', function (data) {
  socket.emit('join', 'Server Connected to Client');
});
...

I tried also in client.js:
const socket = io();
const socket = io('https://' + window.location.hostname);

Why can not the client connect to the server on the production system?

A: I found my mistake: The Load Balancer on the productive system sends the HTTP request to Port 80 but socket.io was listening to Port 443. I initiated socket.io with the wrong server:
const io = require('socket.io')(httpsServer); instead of
require('socket.io')(httpServer).