Q: Xubuntu 18.04 does not detect external monitors connected via USB-C hub I have a Dell Latitude 5490 and two external monitors connected via a USB-C dock (Dell D6000). Both Xubuntu 18.04.1 and Windows 10 are installed on the laptop using dual boot.
The monitors are not detected by Xubuntu but they work fine with Windows 10. I have tried the suggested solution as listed below but with no luck. I have also updated the NVIDIA driver and used the latest one but did not make any difference. No luck with the X.Org X server driver either. Any suggestion is highly appreciated!
External monitor not detected with USB-C adapter
https://ubuntuforums.org/showthread.php?t=2393560
For this, I have been unable to find the similar option in the bios of my laptop.
External monitor not detected on Ubuntu 18.04
The output from xrandr

Screen 0: minimum 320 x 200, current 1920 x 1080, maximum 8192 x 8192
eDP-1 connected 1920x1080+0+0 (normal left inverted right x axis y axis) 309mm x 174mm
   1920x1080     60.02*+  60.01    59.97    59.96    59.93    47.99
   1680x1050     59.95    59.88
   1600x1024     60.17
   1400x1050     59.98
   1600x900      59.99    59.94    59.95    59.82
   1280x1024     60.02
   1440x900      59.89
   1400x900      59.96    59.88
   1280x960      60.00
   1440x810      60.00    59.97
   1368x768      59.88    59.85
   1360x768      59.80    59.96
   1280x800      59.99    59.97    59.81    59.91
   1152x864      60.00
   1280x720      60.00    59.99    59.86    59.74
   1024x768      60.04    60.00
   960x720       60.00
   928x696       60.05
   896x672       60.01
   1024x576      59.95    59.96    59.90    59.82
   960x600       59.93    60.00
   960x540       59.96    59.99    59.63    59.82
   800x600       60.00    60.32    56.25
   840x525       60.01    59.88
   864x486       59.92    59.57
   800x512       60.17
   700x525       59.98
   800x450       59.95    59.82
   640x512       60.02
   720x450       59.89
   700x450       59.96    59.88
   640x480       60.00    59.94
   720x405       59.51    58.99
   684x384       59.88    59.85
   680x384       59.80    59.96
   640x400       59.88    59.98
   576x432       60.06
   640x360       59.86    59.83    59.84    59.32
   512x384       60.00
   512x288       60.00    59.92
   480x270       59.63    59.82
   400x300       60.32    56.34
   432x243       59.92    59.57
   320x240       60.05
   360x202       59.51    59.13
   320x180       59.84    59.32
DP-1 disconnected (normal left inverted right x axis y axis)
DP-2 disconnected (normal left inverted right x axis y axis)
HDMI-1 disconnected (normal left inverted right x axis y axis)

A: Dell's D6000 dock requires a driver to be installed on Windows, and I note that there is an equivalent driver available for Ubuntu 16.04 and 18.04.
This probably isn't the answer for you on Xubuntu given it isn't the standard Ubuntu, but at least it might explain why the dock isn't working in your OS.


Q: Html().replace() : RegExp : $1 and single quote I am faced with two problems. (with jQuery)
for (var i=0; i<len; i++) {
    var e = arr[i],               //<- strings
        re = new RegExp(e,"ig");
    target.html(
        target.html().replace(
            re, "" + e + ""
        )
    );
}

*

*The original value cannot be called after replacing. (like a "$1")

*It cannot replace, if the candidate for substitution (property e) has a single quote.

A: You actually can use something similar to $1:
for (var i=0; i<len; i++) {
    var e = arr[i],               //<- strings
        re = new RegExp(e,"ig");
    target.html(
        target.html().replace(
            re, "$&"
        )
    ); //you could also have used $1 to refer to the first backreference, instead of the entire match
}

Your second problem is less clear to me. Single quotes are not special characters in regexes.
I could not replicate your other problem. Here is a working example: http://jsfiddle.net/Xsjt7/1/

A: if you want to use $1 and the arr is just an array of strings you could join it:
var arr = ["what","not make any sense","n't make any sense","it's"];
var target = $('#mydiv');

var re = new RegExp("(" + arr.join("|") +")","ig");
target.html(
    target.html().replace(re, "$1")
);


Q: Dropdown not populating from MySQL I am trying to populate a dropdown list with PHP from a MySQL database. Right now nothing is populating in my dropdown. I have made sure I have the correct database name, server name, username, and password.
Here is my PHP file queryfunction.php:
<?php
function connect(){
    $servername = "localhost";
    $username = "root";
    $password = "******";
    $database = "lab4";
    // Create connection
    $conn = new mysqli($servername, $username, $password);

    // Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }
    echo "Connected successfully";
    mysqli_select_db($database);
}

function close(){
    mysqli_close();
}

function query(){
    $mydata = mysqli_query("Select * from country");
    while($record = mysqli_fetch_array($mydata)){
        echo '<option value = "' . $record['CountryAbbreviation'] . '">' .$record['CountryAbbreviation'] . '"</option>';
    }
}
?>

Here is is my PHP file where I call this:
<?php
include_once "queryfunction.php";
connect();
?>
<!DOCTYPE html/>

Further down in the doc within a table:

    Country

        <select name="CountryDropDown">
        <?php query() ?>
        </select>
        <?php close()?>

A: Try with change this line while($record = mysqli_fetch_array($mydata)){ to this while($record = mysqli_fetch_array($mydata,MYSQLI_ASSOC)){
or show us your $record variable data


Q: Every representable presheaf is projective Let $\mathcal{C}$ be a small category and let $\hat{\mathcal{C}}$ be its category of presheaves. I want to show that every representable presheaf $y_C\in \hat{\mathcal{C}}$ (for some $C\in\mathcal{C}$) is projective. $y$ here is the Yoneda embedding. So suppose that $F,G\in \hat{\mathcal{C}}$ also, with natural transformations $f:y_C\to F$ and $g:G\to F$, with $g$ epi. Then using the axiom of choice, it is rather easy to see that for each $D\in\mathcal{C}$, there exists a function $h_D: y_C D\to GD$ such that $g_D h_D= f_D.$ If $h=(h_D)_{D\in\mathcal{C}}$ is a natural transformation ($y_C\to G$) then it is clear that $gh=f.$ My problem now is with showing that $h$ is indeed a natural transformation.
So for any map $k:D\to D'$ in $\mathcal{C}^{op}$, we need that $(Gk)(h_D) = h_{D'}(y_Ck).$ This is where I am stuck. It is not clear to my why this should hold. We know what $y_C k$ is, but not what $Gk$ behaves like. I tried involving $FD$ and $FD'$ in the diagram, but this has not helped me.
I want to show that the outer square commutes:

It is clear that the upper and lower inner squares commute since $f$ and $g$ are natural transformations, and it is clear that the left and right triangles commute by definition of $h_D$ and $h_{D'}$, but that alone does not seem to be enough for the outer square to commute.
How can I complete the proof? Any hints would be appreciated. I think I should involve the definition of $y_C$ somehow, since I have not actually used that yet.


Q: Custom form input component I want to create a custom form input component, that will work reactively.
I created a component (TS)
import { Component, forwardRef, Input, OnInit } from "@angular/core";
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from "@angular/forms";

@Component({
  selector: "app-new-input",
  templateUrl: "./new-input.component.html",
  styleUrls: ["./new-input.component.css"],
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => NewInputComponent),
      multi: true
    }
  ]
})
export class NewInputComponent implements ControlValueAccessor, OnInit {
  @Input() label: string = "";
  @Input() placeholder: string = "";
  @Input() type: string = "text";

  propagateChange: any = () => {};
  onTouch: any = () => {};
  value: string = "";

  constructor() {}

  ngOnInit() {}

  onChange(event: any) {
    this.value = event.target.value;
    this.propagateChange(this.value);
  }

  writeValue(value: string): void {
    this.value = value ? value : "";
  }
  registerOnChange(fn: any): void {
    this.propagateChange = fn;
  }
  registerOnTouched(fn: any): void {
    this.propagateChange = fn;
  }
  setDisabledState?(isDisabled: boolean): void {}
}

and the HTML
{{label}}

<input matInput [type]="type" [value]="value" [placeholder]="placeholder" (change)="onChange($event)" (keyup)="onChange($event)">

in my app component I have
  searchForm: FormGroup = this.formBuilder.group({
    name: [""]
  });

  constructor(private formBuilder: FormBuilder) {}

and in app component HTML
<form [formGroup]="searchForm">
  <app-new-input formControlName="name"></app-new-input>
</form>

{{searchForm.value | json}}

All this can be found on STACKBLITZ
So, the problem I am having is that the changes from the component input do not propagate to the parent (app component) form
Could somebody tell me what am I doing wrong?

A: Your mistake is a simple one - you are setting propagateChange in both registerOnChange and registerOnTouched. Instead, assign to onTouch in registerOnTouched.
registerOnTouched(fn: any): void {
  this.onTouch = fn;
}

registerOnTouched is getting called after registerOnChange by the framework, so you are emitting touch events when you are intending to emit change events.
DEMO https://stackblitz.com/edit/angular-ve8sri


Q: SQL Server ALTER field NOT NULL takes forever I want to alter a field from a table which has about 4 million records. I ensured that all of these fields values are NOT NULL and want to ALTER this field to NOT NULL
ALTER TABLE dbo.MyTable
ALTER COLUMN myColumn int NOT NULL

... seems to take forever to do this update. Any ways to speed it up or am I stuck just doing it overnight during off-hours?
Also could this cause a table lock?

A: You can alter a field and make it not null without it checking the fields.  If you are really concerned about not doing it off hours you can add a constraint to the field which checks to make sure it isn't null instead.   This will allow you to use the with no check option, and not have it check each of the 4 million rows to see if it updates.
CREATE TABLE Test
(
    T0 INT Not NULL,
    T1 INT NUll
)

INSERT INTO Test VALUES(1, NULL) -- Works!

ALTER TABLE Test
    WITH NOCHECK
        ADD CONSTRAINT N_null_test CHECK (T1 IS NOT NULL)

    ALTER COLUMN T1 int NOT NULL

INSERT INTO Test VALUES(1, NULL) -- Doesn't work now!

Really you have two options (added a third one see edit):

*

*Use the constraint which will prevent any new rows from being updated and leave the original ones unaltered.

*Update the rows which are null to something else and then apply the not null alter option.  This really should be run in off hours, unless you don't mind processes being locked out of the table.

Depending on your specific scenario, either option might be better for you.  I wouldn't pick the option because you have to run it in off hours though.  In the long run, the time you spend updating in the middle of the night will be well spent compared the headaches you'll possibly face by taking a short cut to save a couple of hours.
This all being said, if you are going to go with option two you can minimize the amount of work you do in off hours.  Since you have to make sure you update the rows to not null before altering the column, you can write a cursor to slowly (relative to doing it all at once)

*

*Go through each row

*Check to see if it is null

*Update it appropriately.
This will take a good while, but it won't lock the whole table block other programs from accessing it. (Don't forget the with(rowlock) table hint!)

EDIT: I just thought of a third option:
  You can create a new table with the appropriate columns, and then export the data from the original table to the new one.  When this is done, you can then drop the original table and change the name of the new one to be the old one.  To do this you'll have to disable the dependencies on the original and set them back up on the new one when you are done, but this process will greatly reduce the amount of work you have to do in the off hours.  This is the same approach that sql server uses when you make column ordering changes to tables through the management studio.  For this approach, I would do the insert in chunks to make sure that you don't cause undo stress on the system and stop others from accessing it.  Then on the off hours, you can drop the original, rename the second, and apply dependencies etc.  You'll still have some off hours work, but it will be minuscule compared to the other approach.
Link to using sp_rename.

A: The only way to do this "quickly" (*) that I know of is by

*

*creating a 'shadow' table which has the required layout

*adding a trigger to the source-table so any insert/update/delete operations are copied to the shadow-table (mind to catch any NULL's that might popup!)

*copy all the data from the source to the shadow-table, potentially in smallish chunks (make sure you can handle the already copied data by the trigger(s), make sure the data will fit in the new structure (ISNULL(?) !)

*script out all dependencies from / to other tables

*when all is done, do the following inside an explicit transaction :

*

*get an exclusive table lock on the source-table and one on the shadowtable

*run the scripts to drop dependencies to the source-table

*rename the source-table to something else (eg suffix _old)

*rename the shadow table to the source-table's original name

*run the scripts to create all the dependencies again

You might want to do the last step outside of the transaction as it might take quite a bit of time depending on the amount and size of tables referencing this table, the first steps won't take much time at all
As always, it's probably best to do a test run on a test-server first =)
PS: please do not be tempted to recreate the FK's with NOCHECK, it renders them futile as the optimizer will not trust them nor consider them when building a query plan.
(*: where quickly comes down to : with the least possible downtime)

A: Sorry for the discouragement, but:

*

*Any ways to speed it up: No, not if you want to change the table structure itself

*or am I stuck just doing it overnight during off-hours? Yes, and that's probably for the best, as @HLGEM pointed out

*Also could this cause a table lock? Yes

Not directly relevant to you (because it's about going from NOT NULL to NULL), but interesting read on this topic: http://beyondrelational.com/blogs/sankarreddy/archive/2011/04/05/is-alter-table-alter-column-not-null-to-null-always-expensive.aspx
And finally some ancient history - on an equivalent question in a forum in 2005, the same suggestion was made as @Kevin offered above - using a constraint insteadof making the column itself non-nullable: http://www.sqlteam.com/Forums/topic.asp?TOPIC_ID=50671


Q: Where can I find the GCP cloud service ID's that is required to list down the sku's for each cloud service? I'm planning to create a table in bigquery which would categorize the SKU's of each cloud services in billing. Basically I'd like to replicate the strategy suggested in one of the presentation at last Cloud Next '19, specifically this one -> https://youtu.be/UocD6uY2-js
Since there's a lot of sku's available, i'm planning to fetch this data directly from the billing api ( GET https://cloudbilling.googleapis.com/v1/{parent=services/*}/skus ), but the problem is, it requires for me to provide the service id of the cloud service I'd like to list down the SKU's. Now I don't know where can I find those service id's.
Does anybody know where can I find the service id's for each of the cloud services in google cloud? let's say for GAE or GCE, etc. ?
Here's the link to the Cloud Billing API explorer, https://developers.google.com/apis-explorer/#search/%20billing/cloudbilling/v1/cloudbilling.services.skus.list

A: There appears to be a an API called services.list.  This API returns the services as a JSON array of service objects.  Each object instance includes a field called serviceId which appears to the identifier of the service (eg. DA34-426B-A397) and I believe that this is what you are looking for.


Q: Push was rejected due to missing or corrupt local objects I have a lfs local repo with its remote bitbucket. I work with Unity and Visual studio and my routine is assisted commit with visual studio.  My current commits are not allowed to be push-ed.
Git throws missing files errors but when I follow the path the files are there and ok.
How do I resolve this issue?

A: As seen here, your error should be like:
(missing) code.tar.gz (f2b4bf22bcb011fef16f80532247665d15edbb9051***)
Uploading LFS objects:   0% (0/1), 0 B | 0 B/s, done.
hint: Your push was rejected due to missing or corrupt local objects.
hint: You can disable this check with: 'git config lfs.allowincompletepush true'
error: failed to push some refs to 'git@gitlab.example.com:group/project.git'

Following this issue, start with
 git lfs fetch --all

See if the error persists then.
If it does, try it from a fresh cloned repo (git lfs clone my-repo)

From the discussion:

*

*git lfs fetch --all could not work, since what is missing was never pushed in the first place

*a new git lfs clone, followed by reporting the old repository local work did get added, committed and pushed successfully.


Q: How do you duplicate a file in XCode? Anyone know a good solution?
So far I have not found a better way than using File>New file and then copying contents from old file to new.
You can probably duplicate in Finder and re-import but that's almost same amount of work: switching to finder, duplicate, import new files.
Doing this with one class is not so hard, but what to do if you need to generate 10+ similar Classes based on superclass.
In Eclipse you select file and then copy/paste it in same folder. In finder there's Duplicate.
There's a menu Edit > Duplicate. But it's ALWAYS disabled. I tried selecting various files, classes, methods. It's still disabled.

A: "Duplicate" is enabled for targets in XCode (pretty much nothing else that I know of).
If you have a substantial number of subclasses with the same starting point to replicate, why not make a class template from it?  Then you can just use file->New to make new instances.  It's fairly quick to do.
This is probably the simplest example:
http://www.macresearch.org/custom_xcode_templates
Otherwise, I'd simply duplicate the files in Finder as many times as you need, name them, and drag them into XCode en-masse.

A: In XCode 4.2 (I know this is an old question) there is Duplicate under the File menu.
Select the file (you can select multiple files but it doesn't appear to do anything useful) in the Project Navigator and then File->Duplicate.  Hooray!

A: Careful!
When you use duplicate ( CMD + Shift + S ) - Xcode have a problem with indexing headers.
Also when u want to make a refactoring it can be next error window:

So there a couple of ways what to do, to fix that.

*

*Delete derived data from menu Window > Projects. Restart Xcode.

*Product > Clean

A: In Xcode 4.5 we can duplicate using File-> Duplicate or cmd + shift + S

A: You could use "Save As..."; you'd still have to go back and re-add the original files to the project, though.
It wouldn't be such a bad way to do a bunch of related classes, though: edit file, Save As "class2", edit file, Save As "class3", etc., then "Add Existing Files" and re-add all of the files but the last to your project.

A: I use the following perl script to duplicate a file pair in the Terminal.  You give it the base name of the original and new file, and it copies the header and implementation (c/cpp/m/mm) file, then replaces all occurances of the base name with the new name, then adds them to subversion.  You still have to add the new files in to Xcode and adjust the creation date in the comment (I've got a Keyboard Maestro macro for that), but its quicker than doing a lot of the steps manually.  I operate with a Terminal window and four tabs pre-set to the Project, Source, Resources, and English.lproj directory which gives quick access for a lot of operations.
#!/usr/bin/perl

use lib "$ENV{HOME}/perl";
use warnings;
use strict;

our $cp = '/bin/cp';
our $svn = '/usr/bin/svn';
our $perl = '/usr/bin/perl';

our $source = shift;
our $add = 1;
if ( $source =~ m!^-! ) {
    if ( $source eq '-a' || $source eq '--add' ) {
        $add = 1;
        $source = shift;
    } elsif ( $source eq '-A' || $source eq '--noadd' ) {
        $add = undef;
        $source = shift;
    } else {
        die "Bad arg $source";
    }
}
our $dest = shift;

die "Bad source $source" unless $source =~ m!^(.*/)?[A-Za-z0-9]+$!;
die "Bad dest $dest" unless $dest =~ m!^(.*/)?[A-Za-z0-9]+$!;
my $cpp;
$cpp = 'c' if ( -e "$source.c" );
$cpp = 'cpp' if ( -e "$source.cpp" );
$cpp = 'mm' if ( -e "$source.mm" );
$cpp = 'm' if ( -e "$source.m" );
die "Missing source $source" unless -e "$source.h" && -e "$source.$cpp";
die "Existing dest $dest" if -e "$dest.h" && -e "$dest.$cpp";

our $sourcename = $source; $sourcename =~ s!.*/!!;
our $destname = $dest; $destname =~ s!.*/!!;

print "cp $source.h $dest.h\n";
system( $cp, "$source.h", "$dest.h" );
print "s/$sourcename/$destname in $dest.h\n";
system( $perl, '-p', '-i', '-e', "s/$sourcename/$destname/g", "$dest.h" );

print "cp $source.$cpp $dest.$cpp\n";
system( $cp, "$source.$cpp", "$dest.$cpp" );
print "s/$sourcename/$destname in $dest.$cpp\n";
system( $perl, '-p', '-i', '-e', "s/$sourcename/$destname/g", "$dest.$cpp" );

if ( $add ) {
    print "svn add $dest.$cpp $dest.h\n";
    system( $svn, 'add', "$dest.$cpp", "$dest.h" );
}

A: In my case, one of my folder changed from one place to another place.
I have "Home" folder in Controller folder, but unfortunately it's moved from Controller folder to Manager folder.
I checked many times everything fine, but I'm getting Command PrecompileSwiftBridgingHeader failed with a nonzero exit code
But after 2 hours i realised, my folder structure changed.


Q: QGIS does not read all .csv Excel columns When I import my data from Excel into QGIS, the GPS points are found. However, not all columns that are present in the Excel are shown in the Attribute Table. At times, they have completely disappeared, other times the headers and data have moved around mixing up the headers.
When the data IS there, when I go to categorize the data, it does not show all column options, meaning I cannot categorize on the data that I actually want to categorize on.
Would anybody know what might be going on?
I have tried uploading in many different shapes and formats (at the moment 30+ times).

A: Maybe something went wrong when exporting the Excel to .csv. Typically there could be a mix up between decimal seperators, especially if they are also used in a field that contains text. Have you tried using ; instead of , as a comma seperator?
If your Excel is a bit more complex, or if you just want to spare the extra step to export to .CSV. You can use the 'Spreadsheet Layers' Plugin (link). It's quite powerfull.
Once you have installed it, the direct import of Excel files can be starte here:

Make sure to check the right columns for X and Y (they are usualy detected, if the column-names are meaningfull) and make sure there's just a single table in the Excel-Sheet (check out the 'End of file detection, too).


Q: Python: Log pixel-intensity values from a video-file I read in a video as a grayscale. I mark a circular contour on each frame of the video and try to record the intensity of each pixel on this contour:
    frameCount += 1
    currentTimestamp = timestamp + frameCount/fps
    file = open("myRecord.txt", "a+") #a+ to append to file
    file.write(str(currentTimestamp))
    circleSegment = get_circle_segment(center_pt, 60, 360) #this function returns a list of tuples, where each tuple (x,y) contains x- and y-coordinates of a point along the circular contour
    for el in circleSegment:
        pixel = gray_frame[el[1],el[0]]
        #log information
        file.write('\t' + str(pixel))
    file.write('\n')
    file.close()

This works perfectly for a circular arch of up to 180° and even beyond (I have tested with 181° as well). However, as soon as I go beyond a certain value, e.g. 270° or 359° or 360° (a complete circle, which is what I want), the data logged simply contains chinese characters.
I have no idea what may cause this issue! Can it be that as soon as my txt-file goes beyond 1,000 KB something goes wrong?
after comments, this code works:
 frameCount += 1
    currentTimestamp = timestamp + frameCount/fps
    storeData = []
    storeData.append(currentTimestamp)
    circleSegment = get_circle_segment(center_pt, 60, 360)
    for el in circleSegment:
        pixel = gray_frame[el[1],el[0]]
        storeData.append(pixel)

    #log information
    file = open("myRecord.txt", mode="a+") #a+ to append to file
    for element in storeData:
        file.write('\t' + str(element))
    file.write('\n')
    file.close ()


Q: Is there a maximum Time Stamp Validity Duration when a client is set to a future datetime vs the server We set our Security on our custom Binding as below:
var lSecurity = lCustomBinding.Elements.Find<TransportSecurityBindingElement>();
                lSecurity.LocalClientSettings.DetectReplays = false;
                lSecurity.LocalServiceSettings.DetectReplays = false;
                lSecurity.LocalClientSettings.TimestampValidityDuration = TimeSpan.FromDays(7);
                lSecurity.LocalServiceSettings.TimestampValidityDuration = TimeSpan.FromDays(7);
                lSecurity.LocalClientSettings.MaxClockSkew = TimeSpan.FromDays(7);
                lSecurity.LocalServiceSettings.MaxClockSkew = TimeSpan.FromDays(7);

Now we find that if we test the above by setting the client back anywhere from now to 7 days back, it works. However, the moment we set the client anything more than 9 hours into the future, we get an exception.
The only thing we found was some obscure reference at the end of another thread:
http://social.msdn.microsoft.com/Forums/en/wcf/thread/7c3a7a7e-b9a5-4198-9a29-c6d4e408d36d
Does anybody have any ideas?
UPDATE:
The Exception we get is now added below. It seems as though the server rejects the client message:
System.ServiceModel.Security.MessageSecurityException occurred
  Message=An unsecured or incorrectly secured fault was received from the other party. See the inner FaultException for the fault code and detail.
  Source=mscorlib
  StackTrace:
    Server stack trace:
       at System.ServiceModel.Channels.SecurityChannelFactory`1.SecurityRequestChannel.ProcessReply(Message reply, SecurityProtocolCorrelationState correlationState, TimeSpan timeout)
       at System.ServiceModel.Channels.SecurityChannelFactory`1.SecurityRequestChannel.Request(Message message, TimeSpan timeout)
       at System.ServiceModel.Security.SecuritySessionSecurityTokenProvider.DoOperation(SecuritySessionOperation operation, EndpointAddress target, Uri via, SecurityToken currentToken, TimeSpan timeout)
       at System.ServiceModel.Security.SecuritySessionSecurityTokenProvider.RenewTokenCore(TimeSpan timeout, SecurityToken tokenToBeRenewed)
       at System.IdentityModel.Selectors.SecurityTokenProvider.RenewToken(TimeSpan timeout, SecurityToken tokenToBeRenewed)
       at System.ServiceModel.Security.SecuritySessionClientSettings`1.ClientSecuritySessionChannel.RenewKey(TimeSpan timeout)
       at System.ServiceModel.Security.SecuritySessionClientSettings`1.ClientSecuritySessionChannel.SecureOutgoingMessage(Message& message, TimeSpan timeout)
       at System.ServiceModel.Security.SecuritySessionClientSettings`1.ClientSecurityDuplexSessionChannel.Send(Message message, TimeSpan timeout)
       at System.ServiceModel.Channels.ClientReliableChannelBinder`1.DuplexClientReliableChannelBinder`1.OnSend(TDuplexChannel channel, Message message, TimeSpan timeout)
       at System.ServiceModel.Channels.ReliableChannelBinder`1.Send(Message message, TimeSpan timeout, MaskingMode maskingMode)
       at System.ServiceModel.Channels.SendReceiveReliableRequestor.OnRequest(Message request, TimeSpan timeout, Boolean last)
       at System.ServiceModel.Channels.ReliableRequestor.Request(TimeSpan timeout)
       at System.ServiceModel.Channels.ClientReliableSession.Open(TimeSpan timeout)
       at System.ServiceModel.Channels.ClientReliableDuplexSessionChannel.OnOpen(TimeSpan timeout)
       at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout)
       at System.ServiceModel.Channels.ServiceChannel.OnOpen(TimeSpan timeout)
       at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout)
       at System.ServiceModel.Channels.ServiceChannel.CallOpenOnce.System.ServiceModel.Channels.ServiceChannel.ICallOnce.Call(ServiceChannel channel, TimeSpan timeout)
       at System.ServiceModel.Channels.ServiceChannel.CallOnceManager.CallOnce(TimeSpan timeout, CallOnceManager cascade)
       at System.ServiceModel.Channels.ServiceChannel.EnsureOpened(TimeSpan timeout)
       at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
       at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
       at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)
    Exception rethrown at [0]:
       at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
       at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
       at CompuLoan.Maintenance.IMaintenanceService.IsLicensed(String pHardwareId, Boolean pUseLicense)
       at CompuLoan.Maintenance.MaintenanceServiceClient.IsLicensed(String pHardwareId, Boolean pUseLicense) in C:\Development\compuloan\Source\CompuLoan\Service References\Maintenance\Reference.cs:line 5156
       at CompuLoan.App.IsLicensed(Boolean pUseLicense) in C:\Development\compuloan\Source\CompuLoan\App.xaml.cs:line 365
  InnerException: System.ServiceModel.FaultException
       Message=The security context token is expired or is not valid. The message was not processed.
       InnerException:

A: This is expiration of the session key, which is different than timestamp. For example of you turn establishSecurityContext off (or not use CreateSecureConversationSecurity) you should not get this exception.
Otherwise try to increase additional values such as InactivityTimeout, IssuedCookieLifetime, NegotiationTimeout, SessionKeyRenewalInterval and SessionKeyRolloverInterval.
If you turn on WCF trace on the server and see the exact stack trace of the error maybe we can dril down to the exact property.


Q: In a makefile how do I make a variable within a rule become global? I have a makefile with separate rules that set a variable of the same name. How do I set this variable to become global from within the rule so that I can use it later.
rule1: test_var=/path/to/folder/

rule2: test_var=/path/to/another/folder/

$(info test_var is $(test_var))

When I call "make rule2" it says "test var is "
But I want "test var is /path/to/another/folder"
Thanks!
EDIT
I may have simplified my approach too much, I thought I had it with the global variable idea but make maybe shouldn't be used that way. Here is the problem below.
When I run this code I get the error *** No rule to make target '/file_i_want_compiled.c', needed by 'out/IceCream'. Stop
LINK:= -lpthread
C_SRCS =
C_SRCS += folder1/file1.c
C_FLAGS:= -stf=gnu11

OBJ_PATH= out/objects/

rule1: path = /path/to/rule1folder
.PHONY : rule1
rule2: path = /path/to/rule2folder
.PHONY : rule2

C_SRCS_NO_DIR := $(notdir $(C_SRCS))
C_OBJS        := $(C_SRCS_NO_DIR:%.c=$(OBJ_PATH)%.o
C_OBJS        += $(path)/file_i_want_compiled.o

out/IceCream: GEN_ICECREAM $(C_OBJS) $(OBJ_PATH)IceCream.o
    $(CC) $(C_FLAGS) $(C_OBJS) %(OBJ_PATH)IceCream.o -o $@ $(LINK)

/path/to/rule1folder
&
/path/to/rule2folder
both have their own unique file_i_want_compiled.c
I call make with make rule1 for example

A: You're actually setting the variable correctly, but the info statement is not being evaluated in the context of the recipe.  You can check this by looking at the very lengthy output of  make -d rule1.  Notice that the info statement is evaluated before any rules.
You can have it print out in the context of the rule by doing something like
rule1: test_var=/path/to/folder/

rule2: test_var=/path/to/another/folder/

rule%:
    $(info test_var is $(test_var))


Q: How to run sentiment So, that I can get result for every file separately I am working on Sentiment Analysis. I have 542 text files and have to get sentiment scores for each of the files separately But in 1 Loop. How can I add for loop that prints results separately?
Here is the code:
path = 'C:/Users/Hamza/OneDrive/Desktop/talha.R/Project 5/text.files'
setwd(path)
getwd()

fileslist = list.files(pattern = ",*.txt")

datalist = lapply(fileslist, function(x) readLines(x))

datafr = do.call("rbind", datalist)

view(datalist[1])

filename <- datalist
filename <- trimws(filename)

filetext <- glue(read_file(filename))
filetext <- gsub("\\$", "", filetext)

tokens <- tibble(text = filetext) %>% unnest_tokens(word, text)
tokens %>%
  inner_join(get_sentiments("loughran")) %>%
  count(sentiment) %>%
  spread(sentiment, n, fill = 0) %>%
  mutate(sentiment = positive - negative)

This is the sample of the result:

I want this same output for 542 files. Thanks in advance.


Q: A function from a matrix to its characteristic polynomial. Maybe it's a known fact, but I would like to know whether the function sending a square matrix of order $n$ to its characteristic polynomial is continuous. If this is true, there are some resources where I can find this?
Thanks in advance.

A: The characteristic polynomial is monic of degree $n$, so it has $n$ nontrivial coefficients. Therefore we can identify the image of $\phi$ with (a subspace of) $\mathbb{R}^n$; consider the map
$$\pi:\mathbb{R}[X]\longrightarrow\mathbb{R}^n:\sum_{i=0}^{n-1}c_iX^i\longmapsto(c_0,\ldots,c_{n-1}).$$
Now if we define $\phi(A)\in\Bbb{R}[X]$ to be the characteristic polynomial of $A$, for any $A\in M_n(\Bbb{R})$, then we get a map
$$\pi\circ\phi:\mathbb{R}^{n\times n}\longrightarrow\mathbb{R}^n:A\longmapsto(c_0(A),\ldots,c_{n-1}(A)),$$
where $c_i(A)$ is the $i$-th coefficient of the chararacteristic polynomial of $A$.
Each coefficent $c_i(A)$ is a polynomial in the coefficients of $A$, so as functions the $c_i$ are polynomials (in $n\times n$ variables!). In particular they are continuous maps from $\mathbb{R}^{n\times n}$ to $\mathbb{R}$. It then follows that $\phi$ is continuous, so the answer to your question is yes.

A: The function that takes you from an $n\times n$ matrix to its characteristic polynomial is simply
$$
\begin{align}
\phi:\mathbb R^{n\times n} &\to \mathbb R[x]\\
A &\mapsto \det(A-x I_n)
\end{align}
$$
Where $I_n$ is the $n\times n$ identity matrix.  As for whether this function is "continuous", well, how do you define continuity on such a map?  What topology do we impose on $\mathbb R[x]$?


Q: Who is responsible for maintaining IIS for web apps? IIS/Web Applications has been a tricky issue in the shops I've worked in over time.
On one hand, IIS is a service built into the server (by in large) and is typically the responsibility of the server administrators to maintain and configure. When an issue comes up, they know what needs to happen, or can at least diagnose to the point where they say, "Something is wrong with the web app" and have the developer debug their code.
However, each web application on the server is unique and has a lot of nuances that gets can be complex based on the issues at hand.
On the other hand, each web application is unique in many ways and had specific issues that need to be dealt with and the developer is the person that knows the most about the application. If the web.config file needs to be modified for debugging, or an IIS starts giving grief to the web application, the developer should know where the issue lies and fix it accordingly, either due to IIS or the application itself.
However, allowing a developer to go in and tweak with IIS on their own becomes a serious issue because some settings/optimizations can seriously muck up with the server performance and stability.
So where does the balance lie? Should the server admins be IIS gurus and handle all of those issues and I simply send the site files over deployment, or should the developer assume responsibility for the server and IIS issues and deal with them accordingly?

A: Sounds like what you really need is someone with expertise on both sides of the fence.

A: In my experience (with smaller-sized companies), the IT/sysadmin staff doesn't have the time, interest, or webapp-specific knowledge to properly maintain IIS setups. They'll take things as far as the operating system and hand off IIS to me, the developer.
Obviously, I need to be "more than just a coder" to make this work properly; I have to be aware of system-level issues (security and whatnot). I've been doing low-level systems management for years so I'm confident with this sort of task (in fact, I've taught professional sysadmins a few things over the years). However, not every developer has this capability.
Still, from what I've seen, there are more developers with sysadmin skills then there are sysadmin with (webapp) development skills.
As always, YMMV.

A: I would personally not want a developer to mess around with IIS, especially if it meant that it might cause problems with another application with another developer having to trouble-shoot, on and on.
If there are IIS problems, have the SysAdmin look into it, and if there is a problem with a particular app, send it back to the dev. If the dev has an issue, bring it up to the SysAdmin, who can then attempt to make an informed decision as to whether to make any changes and figure out how it will affect everyone.

A: We (the sysadmins) treat our developers just as we would a 3rd party vendor - when they want us to deploy an app, they have to provide documentation if they expect it to be supported.  This includes common troubleshooting routines and a support escalation path (uptime requirements combined with a documented developer responsibility in the case an unacceptable outage).
It's obviously not black and white, but it's done a lot to ease the tension between devs and admins.  The devs now realize that they have to provide software of a quality inversely proportional to their willingness to be paged after hours, and the devs now have tools and docs to go through without feeling on the hook for tools they didn't create.
So, in your scenario, that would mean the devs create their app on their own IIS server and then provide the software and documentation for the admins to install on the production server.

A:
Should the server admins be IIS gurus
  and handle all of those issues and I
  simply send the site files over
  deployment, or should the developer
  assume responsibility for the server
  and IIS issues and deal with them
  accordingly?

Answer: find one person and annoint them "WSA" (Web Server Administrator). They could be an admin or a developer; it really doesn't matter. But they need to immerse themselves in both aspects of the job, and the rest of the team (on both sides) needs to respect their expertise.
It's no different than how DBAs straddle the line between IT/dev. Given the importance of web servers in an organization with a web-based product, I think this is a critical, and often overlooked, role.
Since the web is still young (compared to databases), it's hard to recruit this individual. You will most likely need to grow/groom someone into the role.

A: With new utilities like the Web Deployment Tool (that will become the standard builtin way to publish a web app starting in Visual Studio 2010), Microsoft seems to be heading down the path toward letting developers or at least installation engineers choose things like IIS settings (certs, app pool settings, etc).  They get built into the msdeploy installation package and automatically applied to the IIS server when the package is deployed to servers.
Seems like a reasonable compromise.  Developers don't go manually mucking with settings on the live production servers, and sys admins don't have to have the webapp-specific knowledge.  And yet the desired IIS settings are clearly visible to sysadmins who want to understand what is going to happen prior to the package getting installed.


Q: How can we stop ListDensityPlot to show results outside data range when using InterpolationOrder -> 0? I have this data
b = .1 {{1, 1}, {0, 1}};
pts = Tuples[Range[-20, 20], 2] . b;
data = {#[[1]], #[[2]], Sin[#[[1]] #[[2]]]} & /@ pts;

I would like to use ListDensityPlot with InterpolationOrder -> 0
ListDensityPlot[data, InterpolationOrder -> 0]

There are some data points outside the data range! the date range should be like this
ListDensityPlot[data, InterpolationOrder -> 1]

A: Background
Look into RegionFunction.

RegionFunction is an option for plotting functions that specifies the
region to include in the plot drawn.

If you know how to define the region analytically, that could be faster (Solution 2). Here I first take the more general route of using ConvexHullRegion

ConvexHullRegion is also known as convex envelope or convex closure.
The convex hull mesh is the smallest convex set that includes the
points $p_i$.

Region check happens using RegionMember
Solution 1
With[
    {reg = ConvexHullRegion[pts]},
    ListDensityPlot[
        data,
        InterpolationOrder -> 0,
        RegionFunction -> Function[{x, y, z},RegionMember[reg, {x,y}]]
    ]
]

Solution 2
Defining the RegionFunction by hand
ListDensityPlot[
        data,
        InterpolationOrder -> 0,
        RegionFunction -> Function[{x, y, z}, x-2 < y  < x + 2]
    ]
]

Solution 3
See solution by @valarmorghulis, they figured out that pre-defining the RegionFunction makes all the difference and has the best performance. Replicating my version of his solution here for completeness.
With[
    {regfunc = RegionMember[ ConvexHullRegion[pts]]},
    ListDensityPlot[
        data,
        InterpolationOrder -> 0,
        RegionFunction ->(regfunc[{#1,#2}]&)
    ]
]

Performance
Using RegionMember[ ConvexHullRegion[pts], {x,y}] much slower than Function[{x, y, z}, x-2 < y  < x + 2].
Using AbsoluteTiming I compare the two solutions.
Sol 1

Sol 2

Sol 3

A: in light of the Answer by @rhermans, the performance can be boosted like the one below, but it would be nice to boost it without using two superimposed graphics and directly obtain using ListDensityPlot
reg = ConvexHullRegion[pts];

then
Show[ListDensityPlot[data, InterpolationOrder -> 0],
  Graphics[{White,
    Polygon[{{-4, -4}, {-4, 4}, {4, 4}, {4, -4}} ->
      reg[[1]]]}]] // AbsoluteTiming

Update
For arbitrarily shaped data, we can predefine the RegionMember  and results much faster though don't know why
Block[{RegFun = RegionMember[ConvexHullRegion[pts]]},
  ListDensityPlot[data, InterpolationOrder -> 0,
   RegionFunction -> (RegFun[{#1, #2}] &)]] // AbsoluteTiming

Adding it in the RegionFunction makes it 20 times slow
Block[{reg = ConvexHullRegion[pts]},
  ListDensityPlot[data, InterpolationOrder -> 0,
   RegionFunction ->
    Function[{x, y, z}, RegionMember[reg, {x, y}]]]] // AbsoluteTiming


Q: How can I let my list return the list within a specific range So I'm trying to move every '1' in list board to the bottom list of lists. Here is what I mean,
If my input in this,
board = [[" "," ","1"," "],
         [" "," ","1"," "],
         ["1","1"," "," "],
         ["1"," "," ","1"]]

my output should return
[[" "," "," "," "],
 [" "," "," "," "],
 ["1"," ","1"," "],
 ["1","1","1","1"]]

If u do not understand, I basically have to move every '1' in the list to the lowest list in board in python.
Here is what I have so far,
board = [[" "," ","1"," "],
         [" "," ","1"," "],
         ["1","1"," "," "],
         ["1"," "," ","1"]]
def summ(board: [list[str]]):
    j = []
    for x in board:
        for i in x:
            j.append(i.count('1'))
    return sum(j)
def remove(board):
    r = []
    for x in board:
        for i in x:
            r.append(i.removesuffix('1'))
    return r
def new(board):
    s = list('1'* summ(board))
    return [remove(board) + s]
print(new(board))

and the output I get is this
[[' ', ' ', '', ' ', ' ', ' ', '', ' ', '', '', ' ', ' ', '', ' ', ' ', '', '1', '1', '1', '1', '1', '1']]

What should I change??

A: It is simple. just transpose array, sort it and transpose back again.
board = [[" "," ","1"," "],
         [" "," ","1"," "],
         ["1","1"," "," "],
         ["1"," "," ","1"]]
boardT=list((map(list, zip(*board))))
boardS=[sorted(L) for L in boardT]
boardR=list((map(list, zip(*boardS))))
print(boardR)

#ans=[[' ', ' ', ' ', ' '],
     [' ', ' ', ' ', ' '],
     ['1', ' ', '1', ' '],
     ['1', '1', '1', '1']]


Q: What's the advantage of malloc? What is the advantage of allocating a memory for some data. Instead we could use an array of them.
Like
 int *lis;
 lis = (int*) malloc ( sizeof( int ) * n );

 /* Initialize LIS values for all indexes */
 for ( i = 0; i < n; i++ )
 lis[i] = 1;

we could have used an ordinary array.
Well I don't understand exactly how malloc works, what is actually does. So explaining them would be more beneficial for me.
And suppose we replace sizeof(int) * n with just n in the above code and then try to store integer values, what problems might i be facing? And is there a way to print the values stored in the variable directly from the memory allocated space, for example here it is lis?

A: Your question seems to rather compare dynamically allocated C-style arrays with variable-length arrays, which means that this might be what you are looking for: Why aren't variable-length arrays part of the C++ standard?
However the c++ tag yields the ultimate answer: use std::vector object instead.
As long as it is possible, avoid dynamic allocation and responsibility for ugly memory management ~> try to take advantage of objects with automatic storage duration instead. Another interesting reading might be: Understanding the meaning of the term and the concept - RAII (Resource Acquisition is Initialization)

"And suppose we replace sizeof(int) * n with just n in the above code and then try to store integer values, what problems might i be facing?"
- If you still consider n to be the amount of integers that it is possible to store in this array, you will most likely experience undefined behavior.

A: The answer is simple. Local1 arrays are allocated on your stack, which is a small pre-allocated memory for your program. Beyond a couple thousand data, you can't really do much on a stack. For higher amounts of data, you need to allocate memory out of your stack.
This is what malloc does.
malloc allocates a piece of memory as big as you ask it. It returns a pointer to the start of that memory, which could be treated similar to an array. If you write beyond the size of that memory, the result is undefined behavior. This means everything could work alright, or your computer may explode. Most likely though you'd get a segmentation fault error.
Reading values from the memory (for example for printing) is the same as reading from an array. For example printf("%d", list[5]);.
Before C99 (I know the question is tagged C++, but probably you're learning C-compiled-in-C++), there was another reason too. There was no way you could have an array of variable length on the stack. (Even now, variable length arrays on the stack are not so useful, since the stack is small). That's why for variable amount of memory, you needed the malloc function to allocate memory as large as you need, the size of which is determined at runtime.
Another important difference between local arrays, or any local variable for that matter, is the life duration of the object. Local variables are inaccessible as soon as their scope finishes. malloced objects live until they are freed. This is essential in practically all data structures that are not arrays, such as linked-lists, binary search trees (and variants), (most) heaps etc.
An example of malloced objects are FILEs. Once you call fopen, the structure that holds the data related to the opened file is dynamically allocated using malloc and returned as a pointer (FILE *).

1 Note: Non-local arrays (global or static) are allocated before execution, so they can't really have a length determined at runtime.

A: More fundamentally, I think, apart from the stack vs heap and variable vs constant issues (and apart from the fact that you shouldn't be using malloc() in C++ to begin with), is that a local array ceases to exist when the function exits. If you return a pointer to it, that pointer is going to be useless as soon as the caller receives it, whereas memory dynamically allocated with malloc() or new will still be valid. You couldn't implement a function like strdup() using a local array, for instance, or sensibly implement a linked representation list or tree.

A: I assume you are asking what is the purpose of c maloc():
Say you want to take an input from user and now allocate an array of that size:
int n;
scanf("%d",&n);
int arr[n];

This will fail because n is not available at compile time. Here comes malloc()
you may write:
int n;
scanf("%d",&n);
int* arr = malloc(sizeof(int)*n);

Actually malloc() allocate memory dynamically in the heap area

A: Some older programming environments did not provide malloc or any equivalent functionality at all.  If you needed dynamic memory allocation you had to code it yourself on top of gigantic static arrays.  This had several drawbacks:

*

*The static array size put a hard upper limit on how much data the program could process at any one time, without being recompiled.  If you've ever tried to do something complicated in TeX and got a "capacity exceeded, sorry" message, this is why.

*The operating system (such as it was) had to reserve space for the static array all at once, whether or not it would all be used.  This phenomenon led to "overcommit", in which the OS pretends to have allocated all the memory you could possibly want, but then kills your process if you actually try to use more than is available. Why would anyone want that? And yet it was hyped as a feature in mid-90s commercial Unix, because it meant that giant FORTRAN simulations that potentially needed far more memory than your dinky little Sun workstation had, could be tested on small instance sizes with no trouble.  (Presumably you would run the big instance on a Cray somewhere that actually had enough memory to cope.)

*Dynamic memory allocators are hard to implement well.  Have a look at the jemalloc paper to get a taste of just how hairy it can be.  (If you want automatic garbage collection it gets even more complicated.) This is exactly the sort of thing you want a guru to code once for everyone's benefit.

So nowadays even quite barebones embedded environments give you some sort of dynamic allocator.
However, it is good mental discipline to try to do without.  Over-use of dynamic memory leads to inefficiency, of the kind that is often very hard to eliminate after the fact, since it's baked into the architecture.  If it seems like the task at hand doesn't need dynamic allocation, perhaps it doesn't.
However however, not using dynamic memory allocation when you really should have can cause its own problems, such as imposing hard upper limits on how long strings can be, or baking nonreentrancy into your API (compare gethostbyname to getaddrinfo).
So you have to think about it carefully.

A:
we could have used an ordinary array

In C++ (this year, at least), arrays have a static size; so creating one from a run-time value:
int lis[n];

is not allowed. Some compilers allow this as a non-standard extension, and it's due to become standard next year; but, for now, if we want a dynamically sized array we have to allocate it dynamically.
In C, that would mean messing around with malloc; but you're asking about C++, so you want
std::vector<int> lis(n, 1);

to allocate an array of size n containing int values initialised to 1.
(If you like, you could allocate the array with new int[n], and remember to free it with delete [] lis when you're finished, and take extra care not to leak if an exception is thrown; but life's too short for that nonsense.)

Well I don't understand exactly how malloc works, what is actually does. So explaining them would be more beneficial for me.

malloc in C and new in C++ allocate persistent memory from the "free store". Unlike memory for local variables, which is released automatically when the variable goes out of scope, this persists until you explicitly release it (free in C, delete in C++). This is necessary if you need the array to outlive the current function call. It's also a good idea if the array is very large: local variables are (typically) stored on a stack, with a limited size. If that overflows, the program will crash or otherwise go wrong. (And, in current standard C++, it's necessary if the size isn't a compile-time constant).

And suppose we replace sizeof(int) * n with just n in the above code and then try to store integer values, what problems might i be facing?

You haven't allocated enough space for n integers; so code that assumes you have will try to access memory beyond the end of the allocated space. This will cause undefined behaviour; a crash if you're lucky, and data corruption if you're unlucky.

And is there a way to print the values stored in the variable directly from the memory allocated space, for example here it is lis?

You mean something like this?
for (i = 0; i < len; ++i) std::cout << lis[i] << '\n';


Q: Dimension of $\dim_{\mathbb C}\mathbb C[X,Y]/I(Y^2-X^2,Y^2+X^2)$ I'm trying to solve the question 1.36 from Fulton's algebraic curves book:

Let $I=(Y^2-X^2,Y^2+X^2)\subset\mathbb C[X,Y]$. Find $V(I)$ and
  $\dim_{\mathbb C}\mathbb C[X,Y]/I$.

Obviously $V(I)=\{(0,0)\}$ and by a corolary in the same section we know that $\dim_{\mathbb C}(\mathbb C[X,Y]/I)\lt \infty$, but I don't know how to calculate $\dim_{\mathbb C}(\mathbb C[X,Y]/I)$.
I need help in this part.
Thanks in advance

A: Given a ring $R$, every element of $R[x]$ is a sum of elements $a_0+a_1 x + a_2 x^2 + \ldots +a_n x^n$ where $a_i \in R$.  Using this twice, we have that a basis for $\mathbb C[x,y]$ is the monomials $x^iy^j$ where $i,j\in \mathbb N$  Since $I=(x^2+y^2,x^2-y^2)=(x^2,y^2)$, we have that every monomial where either $i$ or $j$ is at least $2$ will be in $I$, and so every element of $\mathbb C[x,y]/I$ is of the form $a + bx + cy + dxy +I$.  In fact, the elements of $I$ are spanned by the monomials where either $i$ or $j$ are at least $2$, and so $\{1,x,y,xy\}$ is a basis for $\mathbb C[x,y]/I$, and so the dimension is $4$.

A: Hint: Note that $Y^2=\bigl((Y^2-X^2)+(Y^2+X^2)\bigr)/2$ belongs to $I$, which in turn implies that $X^2=(Y^2+X^2)-Y^2\in I$. In other words $(X^2,Y^2)\subseteq I$, and a similar reasoning shows the reversed inclusion. Having this, what can you say about the higher order terms of an arbitrary polynomial modulo $I$?


Q: Restful Webservice method for get request I am trying to write a web service method for get request and its return type is ResponseEntity. But when i trying to run this from Postman then its gives response body as Not acceptable. following is the result and code of my method.
<html>
    <head>
        <title>Error</title>
    </head>
    <body>Not Acceptable</body>
</html>

Code:-
 @GetMapping("/v1/showMyDetails.html")
 public ResponseEntity tryingGetWithAnnotation(){
     ResponseEntity responseEntity = null;
     JSONObject jsonObj = new JSONObject();
     jsonObj.put("name","nikhil");
     responseEntity = new ResponseEntity(jsonObj,HttpStatus.OK);
     return responseEntity;
 }

Thanks in Advance


Q: RestSharp double-nested elements not being Deserialized So I am attempting to use the default XmlDeserializer from RestSharp to deserialize the following XML structure. For the life of me, I am unable to get the 'Picks' to be deserialized at all.
<PlayerList>
   <Player>
      <PlayerName>Name</PlayerName>
      <PlayerRank>5</PlayerRank>
      <Picks>
         <PickID>1</PickID>
         <Status>Active</Status>
         <CreatedDate>2012-08-30 09:43:38</CreatedDate>
      </Picks>
      <Picks>
         <PickID>2</PickID>
         <Status>Disabled</Status>
         <CreatedDate>2012-08-30 09:49:33</CreatedDate>
      </Picks>
   </Player>
</PlayerList>

The closest I ever came was to define them in the "Player" class as...
public class Player {
    /*other properties*/
    public List<Picks> Picks { get; set; }
}

Which did return a single "Picks" object with all of its properties set to null (or DateTime minimum).
What is the proper way to structure the serializable C# classes to get the data returned from each of the Picks? I wonder if it has something to do with the "Picks" objects having a plural name...
Thanks!

A: Eventually realized what the issue was with this. The change necessary to get this to work was to make these changes to the "Player" class...
public class Player {
    /* other properties */
    List<Picks> PickList { get; set; }
}

The issue was occurring because RestSharp was confused because the Property's name ("Picks") was the same as the Object Type ("Picks") that it was trying to deserialize.


Q: How to make a few div elements responsive I'm having trouble with making some of my div elements responsive.
The image with the magnifying glass is refusing to resize when the window is smaller, for example on a ipad. I have tried other methods of resizing but resulting in failure.
Website link: http://onlinestaff.net

A: You can try something like this to make divs responsive and their position relative to the size of screen:

A: Problem: The magnifying-glass-image on your website uses the attribute max-width:none which causes the image to be displayed in full size even on smaller screens.
Solution: When making images responsive we usually use the CSS attribute max-width:100% to ensure that big images scale down to fit on the screen (or better: fit into the parent container)


Q: Windows Server 2008 Sync time on start up Hello I have Windows Server 2008 Enterprise. I need on system start up sync time. I'm user in administrators group. I've tried to add task to schedule. I give the task my account rights, but it not helps. It says that access denied. I need to run .bat file or w32tm /resync. But if I run the .bat file with context menu "Run as administrator..." everything is ok.
Any suggestions? Please!!
Thank's in advance.

A: On the scheduled task properties, on the General page, did you check off "Run with highest privileges?"

A: You could also try to run it as System instead of your account. I had to do something like that with a task. To run it as System, since mine was on a DC, I had to export the task and in the XML I edited this part:
  <Principals>
    <Principal id="Author">
      <UserId>SYSTEM</UserId>
      <RunLevel>HighestAvailable</RunLevel>
   </Principal>

Where UserId was my username and now I've set it up for SYSTEM. Import the task and you should have that as the User and set it to Run with highest privileges.
Hope this helps.

A: I wouldn't even use a scheduled task.  There are options within w32tm itself to set a specific interval for time sync.  You can specify any time interval you want, for instance you could set your server to update it's time from your designated NTP servers every 5 mintues.  Then your server would be in sync no matter what.

A: You don't need to configure a scheduled task to synchronise time.
If your server is not joined to a domain, it will automatically sync to time.windows.com. To make it sync with a different server, use this command in a command prompt window:
net time /setsntp:ntp1.example.net,ntp2.example.net

If your server is joined to a domain it will automagically sync to the nearest Domain Controller.
If your server is the Domain Controller which holds the PDC Emulator FSMO role, you must configure it to sync to another NTP server using the "net time..." command above.


Q: What really lambda looks like? (not a linq lambda expression) I read this thread in converting a lambda to linq. And I am thinking about what slawekwin said in comment.
this already is linq (which is using lambda expressions)
Can someone please give me an example of what really lambda looks like?. Not in Linq Lambda Expression. Thanks

A: Lambda functions are a language construct of defining a function.
LINQ is a library of functions. Many of these functions takes functions as parameters to compare or select elements from your lists. Therefore it is very common to use lambda functions to specify these parameter functions. Simple because that makes puts the definition of what it is supposed to do where you actually use it. But there is nothing preventing you from NOT using lambda functions with LINQ.


Q: Reducing size of an array (by creating a new one) - how does arrayList do it? In one of my classes, I have a method like so:
public void setArray(int size){

myArray = new int[size]  //myArray is declared already

}

Now, if I call this and pass in, say, 500 like so:
setArray(500);

And then, later on in my app, I need only an array with, say 50 elements, at the moment, I simply call it again and pass in 50 as my argument.
This array is referenced many times within my app and I'm wondering if the CG will collect the old one?
I know I should really use an arrayList, unfortunately, this would be a major undertaking as my code is now thousands of lines and 18 classes in size (so I guess I've learned for my next project!)
How does arrayList achieve this 'behind the scenes'?  Can I emulate the arrayList behavour?  Does it simply create a new array like I've done?

A: You are describing the behavior of a dynamic array.
The easiest way to implement this data structure is to create a new array once the array is full or below some threshold (only 1/4 of the cells are occupied, for example), and copy existing values into the new array.
If you want to know how it is done in java, and what optimizations are being made - you might want to have a look on the ArrayList class source.

A: You can read the source for ArrayList here: SOURCE
And you are right, it keeps an array and replaces it as needed to allow room for more objects. But it also stores the length so the array can be longer than is needed. That allows the ArrayList to grow a little without having to re-create the actual array everytime. If the ArrayList gets smaller, it doesn't have to re-create. It just changes the length as stored.
You can read the code to see how they decide when to change the array itself. Whenever they do that, they have to copy the old one's contents over.
You are right, BTW, that the old arrays get garbage collected as long as there are not variables referencing them. It sort of depends on how your code works. If that code you show and the definition is the only reference, then it will get GC'ed when you make a new array and store it.

A: The official implementation of ArrayList never reduces the size of an array, only increases the capacity when needed.
When an element is removed from the ArrayList, it ensures that the posterior elements return one position and sets null for the free element on the right.


Q: NoSuchPropertyException in signed build I am animating a Map Marker via the following code:
final Property<Marker, LatLng> property =
        Property.of(Marker.class, LatLng.class, "position");
final ObjectAnimator animator =
        ObjectAnimator.ofObject(otherMarker, property, typeEvaluator, toLatLng);

This works fine in a debug build but fails with the following stack trace in a signed build:
0
android.util.NoSuchPropertyException: No accessor method or field found for property with name position
1
at android.util.ReflectiveProperty.<init>(ReflectiveProperty.java:71)
2
at android.util.Property.of(Property.java:55)
3
at com.myapp.fragment.MapWrapperFragment.j(MapWrapperFragment.java:1090)
4
at com.myapp.ActivityA.l(ActivityA.java:860)
5
at com.myapp.fragment.FragmentA$22.onClick(FragmentA.java:377)
6
at android.view.View.performClick(View.java:4438)
7
at android.view.View$PerformClick.run(View.java:18422)
8
at android.os.Handler.handleCallback(Handler.java:733)
9
at android.os.Handler.dispatchMessage(Handler.java:95)
10
at android.os.Looper.loop(Looper.java:136)
11
at android.app.ActivityThread.main(ActivityThread.java:5001)
12
at java.lang.reflect.Method.invokeNative(Native Method)
13
at java.lang.reflect.Method.invoke(Method.java:515)
14
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
15
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
16
at dalvik.system.NativeStart.main(Native Method)

What could be the reason for this? I am not sure if it's relevant, but I am using Proguard.

A: Proguard is either removing or renaming the field, since it doesn't know about any access done via reflection. That's why it fails at runtime.
You should probably add a -keep (or -keepnames) rule to prevent this.

A: I stumbled across the same issue but the provided proguard changes did not do it for me. I guess because I use the new play services ('com.google.android.gms:play-services-maps:7.0.0') and they probably have a different internal structure
What worked for me was:
-keep class com.google.android.gms.** { *; }


Q: How do I check if any file in an item list exist using msbuild? I would like to run a task if any file in an item list is missing. How do I do that?
My current script has a list of "source" files @(MyComFiles) that I translate another list of "destination" files @(MyInteropLibs), using the following task:
<CombinePath BasePath="$(MyPath)\interop"
             Paths="@(MyComFiles->'%(filename).%(extension)')">
    <Output TaskParameter="CombinedPaths"
            ItemName="MyInteropLibs" />
</CombinePath>

I want to check if any of the files in @(MyInteropLibs) is missing and run a task that will create them.

A: If you only need to create the missing files, and not get a list of the files that were missing you can you the touch task, which will create if the files don't exist.
<Touch Files="@(MyInteropLibs)" AlwaysCreate="True" />

If you only want to create the missing files, and avoid changing timestamps of the existing files, then batching can help
<Touch Files="%(MyInteropLibs.FullPath)" AlwaysCreate="True"
       Condition=" ! Exists(%(MyInteropLibs.FullPath)) "/>

If you want a list of the files created then
<Touch Files="%(MyInteropLibs.FullPath)" AlwaysCreate="True"
       Condition=" ! Exists(%(MyInteropLibs.FullPath)) ">
    <Output TaskParameter="TouchedFiles" ItemName="CreatedFiles"/>
</Touch>
<Message Text="Created files = @(CreatedFiles)"/>

A: I am not very experienced with MSBuild so there may be better solutions than this but you could write a FilesExist task that takes the file list and passes each file to File.Exists returning true if they do exist and false otherwise and thenn react based on the result
Sorry I can't provide code to help out, my knowlege of MSBuild sytax is not strong

A: You can find out pretty easily using Exec.
To test if ALL of a set of files exists: The DOS FOR /D command accepts a semicolon-separated list of files - i.e. a flattened item array.
<!-- All exist -->
<Exec
  Command="for /D %%i in (@(MyFiles)) do if not exist %%i exit 1"
  IgnoreExitCode="true">
  <Output TaskParameter="ExitCode" PropertyName="ExistExitCode"/>
</Exec>

To test if ANY of a set of files exists: The DOS DIR command accepts a semicolon-separated list of files. It sets the %ERRORLEVEL% to 0 if it finds any files in the list, nonzero if it finds none.  (This is the simpler case, but it does not address the original question...)
<!-- Any exists -->
<Exec Command="dir /B @(MyFiles)" IgnoreExitCode="true">
  <Output TaskParameter="ExitCode" PropertyName="DirExitCode"/>
</Exec>

Then most likely you will want to define a boolean property based on the output.
EDIT: BTW this is a code smell.  Usually when you find yourself wanting to do this, it's an indication that you should set the Outputs property of the target so it will loop over the items.


Q: Como deletar um documento específico de uma collection no MongoDB? O método remove() usado dessa forma: db.nome_da_collection.remove(), remove todos os documents de uma collection, como eu faço pra remover um document específico?

A: Se você quiser remover pelo id pode usar a seguinte query:
db.collection.remove({"_id": ObjectId("5798ffcd60b2d8a4066b482d")});

Você pode remover usando a mesma estrutura de um find. Por exemplo, você pode remover todos os registros que estiverem com a quantidade maior que 10.
db.collection.remove({quantidade : {$gt :10}})


Q: Django function based view allow is_active user whereas ClassBasedView does not allow is_active user I have 2 views. One is function based and the other is class based. When I call the function based view with an is_active user, django does not throw any errors but when I call the class based view it returns 403 error.Any help will be highly appreciated. Thanks
from rest_framework.permissions import IsAuthenticated
from rest_framework.decorators import api_view, permission_classes

@require_POST
@permission_classes([IsAuthenticated,])
def test_function_based_view(request):
    return JsonResponse({
        'success': "True",
    })

class TestClassBasedView(APIView):

    permission_classes = (permissions.IsAuthenticated,)

    def post(self, request):
        return JsonResponse({
            'success': "True",
        })

Django Version 1.11.21

A: It is possible that the problem is not that the class based view is returning a 403 error, but rather that the function based view is not checking the permissions correctly. This might be caused because @require_POST does not take the permissions into consideration.
Replace @require_POST in your function based view with @api_view(('POST',)).


Q: Reducer not always deleting the correct item My delete callback is sending the correct id but I tested out the reducer with a few console logs and it's not working correctly.So I have a list of components in a menu that I can add to the "board".  I notice that if I add only notes for example, it will delete the last one every time. But if I had one note, then one todo list, and another note, if I try to delete the first note, it will delete that one correctly.
reducer
export default function reducer(state: any, action: any) {
  switch (action.type) {
    case "ADD_COMPONENT":
      return {
        ...state,
        components: [...state.components, action.payload],
      };
    case "DELETE_COMPONENT":
      return {
        ...state,
        components: state.components.filter(
          // actual code
          (component: any) =>  component.id !== action.payload),
          //test code to check what ids were being passed in
          //(component: any) => { console.log(component.id, action.payload), console.log(component.id !== action.payload), component.id == action.payload }),
      };

    default:
      return state;
  }
}

The Delete case has a line I was using to test to see what ids were being passed in.
The context
import React, { createContext, useReducer, useState } from "react";
import ComponentReducer from "./ComponentReducer";

const NewComponentState: NewComponentsState = {
  components: [],
  addComponent: () => {},
  deleteComponent: () => {},
};

export const NewComponentContext =
  React.createContext<NewComponentsState>(NewComponentState);

export const NewComponentProvider: React.FC = ({ children }) => {
  const [state, dispatch] = useReducer(ComponentReducer, NewComponentState);

  const addComponent = (component: any) => {
    dispatch({
      type: "ADD_COMPONENT",
      payload: component
    });
  };
  const deleteComponent = (id: any) => {
    dispatch({
      type: "DELETE_COMPONENT",
      payload: id,
    });
  };

  return (
    <NewComponentContext.Provider
      value={{ components: state.components, deleteComponent, addComponent }}
    >
      {children}
    </NewComponentContext.Provider>
  );
};

The Note component that I've been using to test this
import { Menu,Transition } from "@headlessui/react";
import React, { useState, Fragment, useContext } from "react";
import NoteColorChanger from "./NoteColor";
import Draggable from 'react-draggable';
import { NewComponentContext } from "../../../Context/NewComponentContext";

interface INote {
  id: any
}
const Note: React.FC <INote> = ({ id }) => {
  const [content, setContent] = useState<string>()
  const [title, setTitle] = useState<string>()
  const [color, setColor] = useState<any>()
  const [position, setPosition] = useState<any>({x: 0, y: 0})

  const { components, deleteComponent } = useContext(NewComponentContext)

  const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    setContent(event.target.value)
  };

  const handleColor = (notecolor: any) => {
    setColor(notecolor)
  }

  const trackPosition = (pos:any) => {
    setPosition({x: pos.x, y: pos.y})
  }

  const deleteNote = () => {
    deleteComponent(id)
  }

  return (
    <div className={`${color} h-64 w-64 bg-yellow-200 text-black rounded-lg p-2 shadow-lg`}>

Note

        <Menu>
          <Menu.Button>
            <div className={`hover:${color} p-1 rounded-lg ease-in-out duration-100`}>
              <svg
                xmlns="http://www.w3.org/2000/svg"
                className="h-6 w-6"
                fill="none"
                viewBox="0 0 24 24"
                stroke="currentColor"
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  strokeWidth={1}
                  d="M5 12h.01M12 12h.01M19 12h.01M6 12a1 1 0 11-2 0 1 1 0 012 0zm7 0a1 1 0 11-2 0 1 1 0 012 0zm7 0a1 1 0 11-2 0 1 1 0 012 0z"
                />
              </svg>

          </Menu.Button>
          <Transition
            as={Fragment}
            enter="transition ease-out duration-100"
            enterFrom="transform opacity-0 scale-95"
            enterTo="transform opacity-100 scale-100"
            leave="transition ease-in duration-75"
            leaveFrom="transform opacity-100 scale-100"
            leaveTo="transform opacity-0 scale-95"
          >
            <Menu.Items
              as="div"
              className={`bg-gray-100 font-Inter w-64 shadow-lg rounded-lg absolute translate-y-24 -translate-x-2 z-50`}
            >
              <Menu.Item>
                {({ active }) => (
                  <div
                    id="color"
                    className={` flex items-center py-2 px-3 rounded-lg w-full`}
                  >
                    {<NoteColorChanger handleColor={handleColor}/>}

                )}
              </Menu.Item>
              <Menu.Item>
                {({ active }) => (
                  <button
                    id="Todo"
                    onClick={() => console.log(id)}
                    className={`${
                      active ? "bg-blue-500 text-white" : "text-black"
                    } flex items-center py-2 px-3 rounded-lg w-full`}
                  >
                    <svg
                      xmlns="http://www.w3.org/2000/svg"
                      className="h-6 w-6 mr-3"
                      fill="none"
                      viewBox="0 0 24 24"
                      stroke="currentColor"
                    >
                      <path
                        strokeLinecap="round"
                        strokeLinejoin="round"
                        strokeWidth={2}
                        d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"
                      />
                    </svg>
                    Edit Title
                  </button>
                )}
              </Menu.Item>
              <Menu.Item>
                {({ active }) => (

                    <svg
                      xmlns="http://www.w3.org/2000/svg"
                      className="h-6 w-6 mr-3"
                      fill="none"
                      viewBox="0 0 24 24"
                      stroke="currentColor"
                    >
                      <path
                        strokeLinecap="round"
                        strokeLinejoin="round"
                        strokeWidth={2}
                        d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"
                      />
                    </svg>
                    Delete Note

                )}
              </Menu.Item>

            </Menu.Items>
          </Transition>
        </Menu>

      <textarea
        className={`${color} bg-yellow-200 font-Inter w-full h-48 border-none focus:border-none focus:ring-0 resize-none`}
        onChange={() => {handleChange}}
      />

  );
};
export default Note;

Menu where the components are created
import React, { useContext, Fragment, useState } from "react"
import { NewComponentContext } from "../../Context/NewComponentContext"
import { Menu, Transition } from '@headlessui/react'
import Note from "./Note/Note";
import TodoList from "./Todo/TodoList";
import Photo from "./Photo/Photo";

const NewComponentMenu = () => {
    const { addComponent } = useContext(NewComponentContext)

    const newComponent = (componentType: number) => {
        addComponent({id: Math.floor(Math.random() * 100000000), componentType: componentType})
    }
    return (

        <Menu>
          <Menu.Button>

              <svg
                xmlns="http://www.w3.org/2000/svg"
                className="h-6 w-6 text-blue-50"
                viewBox="0 0 20 20"
                fill="currentColor"
              >
                <path
                  fillRule="evenodd"
                  d="M10 3a1 1 0 011 1v5h5a1 1 0 110 2h-5v5a1 1 0 11-2 0v-5H4a1 1 0 110-2h5V4a1 1 0 011-1z"
                  clipRule="evenodd"
                />
              </svg>

          </Menu.Button>
          <Transition
            as={Fragment}
            enter="transition ease-out duration-100"
            enterFrom="transform opacity-0 scale-95"
            enterTo="transform opacity-100 scale-100"
            leave="transition ease-in duration-75"
            leaveFrom="transform opacity-100 scale-100"
            leaveTo="transform opacity-0 scale-95"
          >
            <Menu.Items as="div" className="w-60 shadow-lg rounded-lg bg-white">

Items

              <Menu.Item>
                {({ active }) => (
                  <button
                    id="Todo"
                    onClick={() => newComponent(1)}
                    className={`${
                      active ? "bg-blue-500 text-white" : "text-black"
                    } flex items-center py-2 px-3 rounded-lg w-full`}
                  >
                    <svg
                      xmlns="http://www.w3.org/2000/svg"
                      className="h-6 w-6 mr-3"
                      fill="none"
                      viewBox="0 0 24 24"
                      stroke="currentColor"
                    >
                      <path
                        strokeLinecap="round"
                        strokeLinejoin="round"
                        strokeWidth={2}
                        d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-3 7h3m-3 4h3m-6-4h.01M9 16h.01"
                      />
                    </svg>
                    Todo list
                  </button>
                )}
              </Menu.Item>
              <Menu.Item>
                {({ active }) => (

 setComponent(<Moodboard />) }
                    className={`${
                      active ? "bg-blue-500 text-white" : " text-black"
                    } flex items-center py-2 px-3 cursor-pointer rounded-lg`}
                  >
                    <svg
                      xmlns="http://www.w3.org/2000/svg"
                      className="h-6 w-6 mr-3"
                      fill="none"
                      viewBox="0 0 24 24"
                      stroke="currentColor"
                    >
                      <path
                        strokeLinecap="round"
                        strokeLinejoin="round"
                        strokeWidth={2}
                        d="M14.828 14.828a4 4 0 01-5.656 0M9 10h.01M15 10h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"
                      />
                    </svg>
                    Mood Board

                )}
              </Menu.Item>
              <Menu.Item>
                {({ active }) => (

 newComponent(2) }
                    className={`${
                      active ? "bg-blue-500 text-white" : " text-black"
                    } flex items-center py-2 px-3 cursor-pointer rounded-lg`}
                  >
                    <svg
                      xmlns="http://www.w3.org/2000/svg"
                      className="h-6 w-6 mr-3"
                      fill="none"
                      viewBox="0 0 24 24"
                      stroke="currentColor"
                    >
                      <path
                        strokeLinecap="round"
                        strokeLinejoin="round"
                        strokeWidth={2}
                        d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"
                      />
                    </svg>
                    Image

                )}
              </Menu.Item>
              <Menu.Item>
                {({ active }) => (

 newComponent(3)}
                    className={`${
                      active ? "bg-blue-500 text-white" : " text-black"
                    } flex items-center py-2 px-3 cursor-pointer rounded-lg`}
                  >
                    <svg
                      xmlns="http://www.w3.org/2000/svg"
                      className="h-6 w-6 mr-3"
                      fill="none"
                      viewBox="0 0 24 24"
                      stroke="currentColor"
                    >
                      <path
                        strokeLinecap="round"
                        strokeLinejoin="round"
                        strokeWidth={2}
                        d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"
                      />
                    </svg>
                    Note

                )}
              </Menu.Item>
            </Menu.Items>
          </Transition>
        </Menu>

    );
  };

  export default NewComponentMenu;

component where the menu items are created
import React, { useContext } from "react";
import { NewComponentContext } from "../Context/NewComponentContext";
import NewComponentMenu from "./NewComponents/NewComponentMenu";
import Note from "./NewComponents/Note/Note";
import Photo from "./NewComponents/Photo/Photo";
import TodoList from "./NewComponents/Todo/TodoList";

const Board = () => {
    const { components } = useContext(NewComponentContext);

    const componentList  = components.map((component, i) => {
      if (component.componentType == 1) {
        return (

            <TodoList id={component.id} />

        );
      }
      else if (component.componentType == 2) {
        return (

            <Photo id={component.id} />

        )
      }
      else {
        return (

            <Note id={component.id} />

        )

      }
    });

    return (

        <NewComponentMenu />

{componentList}

    );
  };

  export default Board;

A: It is really a good practice to use key attribute while rendering a collection, it helps react to rerender collections of components correctly. So i can assume you should try to add unique key attribute to the place, where you render Note component, e.g <Note key={'some unique id'} />

A: There is an issue with your delete case in reducer. You are not returning the boolean, so no items will be returned,
case "DELETE_COMPONENT":
      return {
        ...state,
        components: state.components.filter(
          (component: any) => {
              console.log(component.id, action.payload)
              console.log(component.id !== action.payload)
              return component.id !== action.payload // here is the fix
            })
      };


Q: Undefined Control Sequence Problem I have the following code:
\title{Improvement of the Cascadic Multigrid Algorithm with a Gauss Seidel
Smoother to Efficiently Compute the Fiedler Vector of a Graph Laplacian}
\author{Shivam Gandhi \href{email: shivam.jgandhi@gmail.com}
   \and \href{Tufts University Department of Mathematics}}
\date{November 2015}

However, it is returning the following error:
Undefined control sequence.
\@author ->Shivam Gandhi \href
                               {email: shivam.jgandhi@gmail.com} \and \href ...
l.19 \maketitle

The control sequence at the end of the top line
of your error message was never \def'ed. If you have
misspelled it (e.g., `\hobx'), type `I' and the correct
spelling (e.g., `I\hbox'). Otherwise just continue,
and I'll forget about whatever was undefined.

I am using ShareLaTeX for writing the paper, so it may be the compiler. Any ideas on how to fix this problem?
Thanks.

A: You may want something like this
\documentclass[a4paper]{article}
\usepackage{hyperref}
\begin{document}
\title{Improvement of the Cascadic Multigrid Algorithm with a Gauss Seidel
Smoother to Efficiently Compute the Fiedler Vector of a Graph Laplacian}
\author{Shivam Gandhi
  \href{mailto:shivam.jgandhi@gmail.com}{shivam.jgandhi@gmail.com}
  \and \href{http://math.tufts.edu/}{Tufts University Department of Mathematics}}
\date{November 2015}
\maketitle
\end{document}


Q: expand div onClick Hello i am trying to make an expandable div when i'm clicking on a button:
and i want to make the animation with steps, the first step is clicking on the button, the second one the div width expand, and the step 3 the div height expand for get the full page.
and the text inside the div have to change like hide the first text and display the second one when the steps are finish
Anyone have an idea how to do it?
There is a sketch of the steps i want to make:

A: requires jQuery animate
$('.blue').click(function(){
    //expand red div width to 200px
    $('.red').animate({width: "200px"}, 500);
    setTimeout(function(){
        //after 500 milliseconds expand height to 800px
        $('.red').animate({height:"800px"}, 500);
    },500);
    setTimeout(function(){
        //after 1000 milliseconds show textarea (or textbox, span, etc)
        $('.red').find('input[type="textarea"]').show();
    },1000);
});

A: This can be done really easily with CSS. This video explains it very well. There are a ton of other neat tricks in that video, but I linked to the part where she explains a light box.

.container {
  padding: 100px;
}
.red,
.blue {
  width: 20px;
  height: 20px;
  float: left;
  background-color: blue;
}
.red {
  background-color: red;
  font-size: 0;
  color: white;
  width: 50px;
  transition: 1s height, 1s margin, 1s font-size, 1s 1s width;
}
.blue:focus ~ .red {
  height: 100px;
  width: 150px;
  font-size: inherit;
  margin-top: -40px;
  transition: 1s width, 1s 1s height, 1s 1s margin, 1s 1s font-size;
}
.red .hint {
  font-size: 14px;
  padding: 4px;
  transition: 1s 1s font-size;
}
.blue:focus ~ .red .hint {
  font-size: 0;
  transition: 1s font-size;
}

text1Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt

A:    $(window).load(function(){
    $(".blue").click(function(){
        $(".red").animate({width:'400px'},1000).animate({height:'400px',top:'150px'},1000).text("qwqwqwq");
    })
})

` .blue{
        width: 100px;
        height: 100px;
        background-color: blue;
    }
.red{
    width:200px;
    height:100px;
    background-color: red;
    left:100px;
    }
div{
    display: inline-block;
    margin:0;
    padding: 0;
    position: absolute;
    top:300px;

    }`


Q: Count numbers and display a alert dialog I'm trying to create a timer here
How do I create a jscript to count from 1 to 60 and to use alert when I've reached 30 using for loop and while loop method

A: what about this
for( var i = 1;i<=60;i++)
  {
    if(i == 30){
      alert("value is:"+i);
    }
   }

A: both answers are count from 0 to 59.
Op want to count from 1 to 60
So,
 for(i=1; i<=60;i++)
      if(i==30) alert(i);
 i=1;
 while(i<=60){
      if(i==30) alert(30);
      i++;
 }

A: // using for loop
for (i = 0; i < 60; i++) {
    if (i === 30) {
       alert('reached 30');
    }
}

// using while loop
var c=0
while (c < 60) {
    if (c === 30) {
       alert('reached 30');
    }
    c++;
}


Q: ValueError: check_hostname requires server_hostname I was going to install pandas and epanettools on my computer using the code shown below with python 3.8.5 and I received one Error exception.
Code:
pip install epanettools
pip install pandas

Actually, I could install epanettools on my old computer and I bought a new computer and I wanted to do the same thing on my new computer, but it didn't work and the error exception shown below after running the code shown above:
Error: Exception:
ERROR: Exception:
Traceback (most recent call last):
  File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\site-packages\pip\_internal\cli\base_command.py", line 180, in _main
    status = self.run(options, args)
  File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\site-packages\pip\_internal\cli\req_command.py", line 204, in wrapper
    return func(self, options, args)
  File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\site-packages\pip\_internal\commands\install.py", line 318, in run
    requirement_set = resolver.resolve(
  File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\site-packages\pip\_internal\resolution\resolvelib\resolver.py", line 127, in resolve
    result = self._result = resolver.resolve(
  File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\site-packages\pip\_vendor\resolvelib\resolvers.py", line 473, in resolve
    state = resolution.resolve(requirements, max_rounds=max_rounds)
  File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\site-packages\pip\_vendor\resolvelib\resolvers.py", line 341, in resolve
    name, crit = self._merge_into_criterion(r, parent=None)
  File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\site-packages\pip\_vendor\resolvelib\resolvers.py", line 172, in _merge_into_criterion
    if not criterion.candidates:
  File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\site-packages\pip\_vendor\resolvelib\structs.py", line 139, in __bool__
    return bool(self._sequence)
  File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\site-packages\pip\_internal\resolution\resolvelib\found_candidates.py", line 143, in __bool__
    return any(self)
  File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\site-packages\pip\_internal\resolution\resolvelib\found_candidates.py", line 129, in <genexpr>
    return (c for c in iterator if id(c) not in self._incompatible_ids)
  File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\site-packages\pip\_internal\resolution\resolvelib\found_candidates.py", line 30, in _iter_built
    for version, func in infos:
  File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\site-packages\pip\_internal\resolution\resolvelib\factory.py", line 258, in iter_index_candidate_infos
    result = self._finder.find_best_candidate(
  File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\site-packages\pip\_internal\index\package_finder.py", line 879, in find_best_candidate
    candidates = self.find_all_candidates(project_name)
  File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\site-packages\pip\_internal\index\package_finder.py", line 824, in find_all_candidates
    page_candidates = list(page_candidates_it)
  File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\site-packages\pip\_internal\index\sources.py", line 134, in page_candidates
    yield from self._candidates_from_page(self._link)
  File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\site-packages\pip\_internal\index\package_finder.py", line 783, in process_project_url
    html_page = self._link_collector.fetch_page(project_url)
  File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\site-packages\pip\_internal\index\collector.py", line 512, in fetch_page
    return _get_html_page(location, session=self.session)
  File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\site-packages\pip\_internal\index\collector.py", line 422, in _get_html_page
    resp = _get_html_response(url, session=session)
  File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\site-packages\pip\_internal\index\collector.py", line 120, in _get_html_response
    resp = session.get(
  File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\site-packages\pip\_vendor\requests\sessions.py", line 555, in get
    return self.request('GET', url, **kwargs)
  File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\site-packages\pip\_internal\network\session.py", line 449, in request
    return super().request(method, url, *args, **kwargs)
  File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\site-packages\pip\_vendor\requests\sessions.py", line 542, in request
    resp = self.send(prep, **send_kwargs)
  File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\site-packages\pip\_vendor\requests\sessions.py", line 655, in send
    r = adapter.send(request, **kwargs)
  File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\site-packages\pip\_vendor\cachecontrol\adapter.py", line 53, in send
    resp = super(CacheControlAdapter, self).send(request, **kw)
  File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\site-packages\pip\_vendor\requests\adapters.py", line 439, in send
    resp = conn.urlopen(
  File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\site-packages\pip\_vendor\urllib3\connectionpool.py", line 696, in urlopen
    self._prepare_proxy(conn)
  File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\site-packages\pip\_vendor\urllib3\connectionpool.py", line 964, in _prepare_proxy
    conn.connect()
  File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\site-packages\pip\_vendor\urllib3\connection.py", line 359, in connect
    conn = self._connect_tls_proxy(hostname, conn)
  File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\site-packages\pip\_vendor\urllib3\connection.py", line 500, in _connect_tls_proxy
    return ssl_wrap_socket(
  File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\site-packages\pip\_vendor\urllib3\util\ssl_.py", line 432, in ssl_wrap_socket
    ssl_sock = _ssl_wrap_socket_impl(sock, context, tls_in_tls)
  File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\site-packages\pip\_vendor\urllib3\util\ssl_.py", line 474, in _ssl_wrap_socket_impl
    return ssl_context.wrap_socket(sock)
  File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\ssl.py", line 500, in wrap_socket
    return self.sslsocket_class._create(
  File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\ssl.py", line 997, in _create
    raise ValueError("check_hostname requires server_hostname")
ValueError: check_hostname requires server_hostname

Could you please tell me how to resolve this error? Appreicate a lot if any advices!

A: I fixed the problem.

Go to --> windows setting --> Network& Internet --> Proxy --> Switch Turn on (Use a Proxy server) to Turn Off

A: Are you using proxy software, like V2ray, SSR...?
If so, close the software, and try again.

A: On Linux, the problem can be resolved by replacing https with http in the proxy settings environment variable export https_proxy=http://123.123.123.123:8888. Note, it is proxy settings for https, but an http address is used.

A: So far no one has suggested that the pip version is one of the culprits as well.
If your virtual environment is having a recent version of pip (e.g. 21.3.1), try to download the older version same as the one installed in the main python directory (e.g. pip version 19.0.3).
For Windows, copy it to the venv\Lib\site-packages folder and unzip the contents, then cd into that folder then enter the commands python setup.py install to downgrade the pip version.

A: SSL Trust Issues:
pip install numpy -i http://pypi.douban.com/simple --trusted-host pypi.douban.com

https://jhooq.com/pip-install-connection-error/

A: On windows,the problem can be resolved by add 'pypi.org' to the proxy whitelist in the proxy settings

A: maybe you can try to replace ip to proxy server hostname if commands run in unix and you know server hostname


Q: Samba4 DC cannot enable TLS encryption I've created my SSL certificate through an intermediate and have attached the certificate, key and (chain) CA to the Samba4 config under [General]. Upon restarting Samba though, the LDAP server is no longer functional. This issue only seems to occur when I use my trusted certificate, self-signed certificates work fine.
In smb.conf I have added the following:
tls enabled  = yes
tls keyfile  = tls/dc1.example.com-key.pem
tls certfile = tls/dc1.example.com-cert.pem
tls cafile   = tls/ca-chain-root.pem

When testing it with the following I get an OK response and should be good to go:
openssl verify /usr/local/samba/private/tls/dc1.example.com-cert.pem -CAfile /usr/local/samba/private/tls/ca-chain-root.pem

Once these changes take effect, LDAP stops running, nmap confirms that there is nothing on port 636 now as well, the test below returns nothing because LDAP is not active:
openssl s_client -showcerts -connect localhost:636 -CAfile /usr/local/samba/private/tls/ca-chain-root.pem

I'm sure I'm missing something simple here, I've correctly generated SSL certificates for the rest of my servers with no issues. Any help would be appreciated.
OpenSSL commands used to generate the certificate:
openssl genrsa -out intermediate/private/dc1.example.com-key.pem 2048
openssl req -config intermediate/openssl.cnf -key intermediate/private/dc1.example.com-key.pem -new -sha256 -out intermediate/csr/dc1.example.com-csr.pem
openssl ca -config intermediate/openssl.cnf -extensions server_cert -days 3750 -notext -md sha256 -in intermediate/csr/dc1.example.com-csr.pem -out intermediate/certs/dc1.example.com-cert.pem