text:
Q: Sheaves of regular functions Let $\iota\colon X\subset \mathbb{P}^N$ be a quasi-projective variety.  Denote by $\mathcal{O}:=\mathcal{O}_{\mathbb{P^n}}$ the sheaf of regular functions. I guess that the sheaf of regular functions $\mathcal{O}_X$ is isomorphic to the pullback sheaf $\iota^{-1}\mathcal{O}$, however I'm not able to find a morphism of sheaves $\mathcal{O}_X\longrightarrow \iota_{-1}\mathcal{O}$.
Can you help me?

A: It depends which pullback. If $i : X \to Y$ is a morphism, say the inclusion of a variety, $\mathcal O := \mathcal O_Y$ and $F$ is a sheaf on $Y$, we have two pullbacks : the sheaf-theoretic pullback $i^{-1}F$ and the algebraic-geometry pullback : $i^* F := i^{-1} F \otimes_{\mathcal i^{-1}\mathcal O} \mathcal O_X$, where $\mathcal O_X$ is a obvious $i^{-1} \mathcal O$-module (writing down the definition, you are essentially restricting a global function to $X$, in particular $\mathcal O_X$ is a $i^{-1}\mathcal O$ module).
When $F = \mathcal O$ you see indeed that $i^* \mathcal O = \mathcal O_X$ canonically.
If you take the other pullback this is false : for example when $X = x \in \Bbb P^n$ is a point, $i^{-1}\mathcal O = \mathcal O_{\Bbb P^n,x}$ (the stalk at $x$, which looks like power series at $x$) which is certainly not $\mathcal O_{x}$ (the structure sheaf of a point, which is a finite-dimensional vector space, of dimension $1$ if $x$ is a reduced point).


text:
Q: What is the correct syntax for XSD to restrict attrributes values in the elements list? What is the correct syntax for XSD schema to define the following restriction:
In the list of elements we have to specify that attribute can contain value of "c" unlimited number of times, but value of "b" - the zero or only one time.
For example, the correct xml looks like this:
<root>
<elem atr="c">111</elem>
<elem atr="c">222</elem>
<elem atr="b">333</elem>
<elem atr="c">444</elem>
<elem atr="c">555</elem>
</root>

And incorrect one is:
<root>
<elem atr="c">111</elem>
<elem atr="c">222</elem>
<elem atr="b">333</elem>
<elem atr="c">444</elem>
<elem atr="b">555</elem>
</root>

A: I think you can't do that. The closest is xsd:key:
<xsd:key name="idKey">
  <xsd:selector xpath="elem"/>
  <xsd:field xpath="@atr"/>
</xsd:key>

But it's not exactly what you want.
XML Schema generally has very limited means to define value-dependent constraints. Take a look at the Schematron.

A: As far as I know this is impossible. You can make atr unique though...

redpajama_set_name: RedPajamaStackExchange


text:
Q: Young man sent to Earth by aliens to help humans become adaptable I remember a science fiction story I read back in the 70s which means it was probably written in the 60s.  The plot of the story is a young man is returned to earth by an alien race.  Earth has become so dependent upon technology and medicine to maintain itself that they can no longer adapt to changes in their environment.  The returned human is there to reverse the problem.  Any idea as to what the name of this book/short story might be or who may have written it?

A: This might be  "Prodigal Sun" by Philip E.High. Radiation from the sun is causing the adaption problems, and the man releases a gas into the atmosphere to form a shield.https://www.fantasticfiction.com/h/philip-e-high/prodigal-sun.htm


text:
Q: How can I solve this bearing question? How do I answer this bearing question?
A boat is traveling from point O. It first goes to a point marked A is 20km on a bearing of 325 degrees then it travels from point A and goes to point B. B is on a bearing of 220 degrees and 19km from A.

I have tried putting this in a rectangle,l but I can't find the angle at O. How can I?
Thanks.

A:
Hint : find x and then find y...........


text:
Q: Accept mails only for a certain address with Postfix How do you configure a mail server to only accept mails on a certain address?
For example, my mail server should only accept mail on example@myths.ops and not example@harpy.myths.ops. I've looked everywhere, including the configuration files for postfix and ssmtp but couldn't seem to find an option to do this.


text:
Q: In iOS6 how to get the IP address I use the following code. It works fine on iOS 5, but in iOS 6 I didn't get the IP address.
   #import <ifaddrs.h>
   #import <arpa/inet.h>
  -(NSString *)getIPAddress {
    NSString *address = @"error";
    struct ifaddrs *interfaces = NULL;
    struct ifaddrs *temp_addr = NULL;
    int success = 0;
    // retrieve the current interfaces - returns 0 on success
    success = getifaddrs(&interfaces);
    if (success == 0) {
    // Loop through linked list of interfaces
    temp_addr = interfaces;
    while(temp_addr != NULL) {
        if(temp_addr->ifa_addr->sa_family == AF_INET) {
            // Check if interface is en0 which is the wifi connection on the iPhone
               if([[NSString stringWithUTF8String:temp_addr-    >ifa_name]isEqualToString:@"en0"]) {
                // Get NSString from C String

   address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];
            }
        }
        temp_addr = temp_addr->ifa_next;
    }
}
   // Free memory
     freeifaddrs(interfaces);
    return address;
  }

Is there any problem with WiFi connections in iOS 6? It works well in iOS 5. Thank you.

A: try this
- (void)viewDidLoad
{
[super viewDidLoad];
NSString *str =[self getIPAddress];
NSLog(@"%@",str);
// Do any additional setup after loading the view, typically from a nib.
}

-(NSString *)getIPAddress
{
struct ifaddrs *interfaces = NULL;
struct ifaddrs *temp_addr = NULL;
NSString *wifiAddress = nil;
NSString *cellAddress = nil;
NSString *addr;
if(!getifaddrs(&interfaces)) {
    temp_addr = interfaces;
    while(temp_addr != NULL) {
        sa_family_t sa_type = temp_addr->ifa_addr->sa_family;
        if(sa_type == AF_INET || sa_type == AF_INET6) {
            NSString *name = [NSString stringWithUTF8String:temp_addr->ifa_name];
           addr = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];
                          if([name isEqualToString:@"en0"]) {
                                   wifiAddress = addr;
            } else
                if([name isEqualToString:@"pdp_ip0"]) {
                                          cellAddress = addr;
                }
        }
        temp_addr = temp_addr->ifa_next;
    }
    // Free memory
    freeifaddrs(interfaces);
}
return addr;
}


text:
Q: Angular 2 route param changes, but component doesn't reload So, basically I need to reload my component after id of url parameter was changed. This is my player.component.ts:
import {Component, OnInit, AfterViewInit} from '@angular/core';
import {ActivatedRoute, Router} from '@angular/router';
declare var jQuery: any;

@Component({
  selector: 'video-player',
  templateUrl: './player.component.html',
  styleUrls: ['./player.component.less']
})

export class VideoPlayerComponent implements OnInit, AfterViewInit {
  playerTop: number;
  currentVideoId: number;

  constructor(
    private _route: ActivatedRoute,
    private _router: Router
  ) {

  }

  ngOnInit(): void {
    this._route.params.subscribe(params => {
      this.currentVideoId = +params['id'];
      console.log( this.currentVideoId );
      this._router.navigate(['/video', this.currentVideoId]);
    });
  }

  ngAfterViewInit(): void {
    if (this.videoPageParams(this.currentVideoId)) {
      console.log( "afterViewInit" );
      let params = this.videoPageParams(this.currentVideoId);
      let fakeVideoItemsCount = Math.floor(params.containerWidth / params.videoItemWidth);
      this.insertFakeVideoItems( this.currentVideoId, fakeVideoItemsCount);
      this.changePlayerPosition( params.videoItemTop );
    }

  }

  videoPageParams( id ): any {
    let videoItemTop = jQuery(`.videoItem[data-id="${id}"]`).position().top;
    let videoItemWidth = jQuery('.videoItem').width();
    let containerWidth = jQuery('.listWrapper').width();
    return {
      videoItemTop,
      videoItemWidth,
      containerWidth
    };
  }

  changePlayerPosition( videoItemTop ): void {
    this.playerTop = videoItemTop;
  }

  insertFakeVideoItems( id, fakeVideoItemsCount ): void {
    let fakeVideoItemHTML = `<div class="videoItem fake"></div>`;
    let html5playerHeight = jQuery('#html5player').height();
    let videoItemIndex = jQuery(`.videoItem[data-id="${id}"]`).index() + 1;
    let videoItemInsertAfterIndex;
    let videoItemRow = Math.ceil(videoItemIndex / fakeVideoItemsCount);
    let videoItemRowBefore = videoItemRow - 1;
    if ( videoItemIndex <= 4 ) {
      videoItemInsertAfterIndex = 0;
    } else {
      videoItemInsertAfterIndex = (videoItemRowBefore * fakeVideoItemsCount);
    }
    let videoItemInsertAfter = jQuery('.videoItem').eq(videoItemInsertAfterIndex);

    for ( let i = 0; i < fakeVideoItemsCount; i++ ) {
      $(fakeVideoItemHTML).insertBefore(videoItemInsertAfter);
    }
    jQuery(`.videoItem.fake`).css('height', html5playerHeight);

  }

}

player.component.html:
<video
    class="video"
    preload="auto"
    [attr.data-id]="currentVideoId"
    src="">
</video>

<videos-list></videos-list>

videoList.component.html
<div class="videoItem" *ngFor="let video of videos" [attr.data-id]="video.id">
    <a [routerLink]="['/video', video.id]">
        <img [src]='video.thumbnail' alt="1">
    </a>
</div>

So when I click <a [routerLink]="['/video', video.id]"> in videoList.component.html it changes route to /video/10 for example, but the part from player.component.ts which manipulates the DOM doesn't fire again - DOM manipulation doesn't update.
I tried to manually navigate to route via this._router.navigate(['/video', this.currentVideoId]); but somehow it doesn't work.
QUESTION
Is there any way to run functions that manipulate DOM each time route param changes in the same URL?

A: DOM will not update because ngOnInit is only fired once, so it will not update even if you try to "renavigate" back to the parent from the child, since the parent haven't been removed from the DOM at any point.
One option to solve this, is that you could use a Subject, that when the routing is happening, let's send the chosen video id to parent, which subscribes to the change and does whatever you tell it to do, meaning calling functions that will update the DOM, so probably what you want re-executed is the inside ngOnInit and ngAfterViewInit
You mentioned that you had tried using
this._router.navigate(['/video', this.currentVideoId])

so let's look at that. Probably have some click event that fires a function. Let's say it looks like the following, we'll just add the subject in the play
navigate(id) {
  VideoPlayerComponent.doUpdate.next(id)
  this._router.navigate(['/video', this.currentVideoId])
}

Let's declare the Subject in your parent, and subscribe to the changes:
public static doUpdate: Subject<any> = new Subject();

and in the constructor let's subscribe to the changes...
constructor(...) {
    VideoPlayerComponent.doUpdate.subscribe(res => {
        console.log(res) // you have your id here
        // re-fire whatever functions you need to update the DOM
    });
}


text:
Q: Why does CouchDb-python (or do I) confuse strings and dictionaries? I'm trying to use the Python wrapper for CouchDB to update a database. The file is structured as a nested dictionary as follows.
doc = { ...,
   'RLSoo': {'RT_freq': 2, 'tweet': "They're going to play monopoly now.
     This makes me feel like an excellent mother. #Sandy #NYC"},
    'GiltCityNYC': {},
  ....}

I would like to put each entry of the larger dicitionary, for example RLSoo into its own document. However, I get an error message when I try the following code.
 for key in doc:
      db.update(doc[key],all_or_nothing=True)

Error Message
TypeError: expected dict, got <type 'str'>

I don't understand why CouchDB won't accept the dictionary.

A: According Database.update() method realization and his documentation, first argument should be list of document objects (e.g. list of dicts). Since you doc variable has dict type, direct iteration over it actually iterates over all his keys which are string typed. If I understood your case right, probably your doc contains nested documents as values. So, try just:
db.update(doc.values(), all_or_nothing=True)

And it all first level values are dicts, it should works!


text:
Q: Most efficient way to create an edit-dialogue that loads through AJAX I have several AJAX APIs that read data from the back-end and most of them have a counterpart for writing back the edited content too.
Examples:

*

*getSalaries / editSalaries,

*getParticipants / editParticipants,

*getPermissions / editPermissions and a couple more.

Each of the API corresponds to 1 or 2 MySQL tables in the back-end.
To create dialogues for each one of these read-edit-write functionalities, I do not want to write a whole bunch of HTML/JS/jQuery that will be very similar except for some changes in the labels/textbox-IDs.
Is there a way that I can specify a table in JSON format where each cell takes in:

*

*The label-name to display,

*Field in the AJAX's data to populate and

*A type of HTML control to display

And some UI-library that automatically handles the reading of data from the back-end, filling that data in the dialogue, then reading the edited values and calling the AJAX for writing back to the back-end?
Example: I should be able to specify a table in JSON as:
{
   "rows":
   [
       // Row 1
       [
          // Column 1
          {"label": "Participant-name", "ajax-field": "pname", "html-control": "text"},
          // Column 2
          {"label": "Age", "ajax-field": "age", "html-control": "text"},
          // Column 3
          {"label": "Sex", "ajax-field": "sex", "html-control": "option"}
       ],
       // If more than 1 row here, then rows for one entity should be
       // grouped together in a field-set without name.
   ],
   "read-url": "/getParticipants",
   "write-url": "/editParticipants"
}

Benefit of such a solution would be that:

*

*It is much easier to write JSON than HTML (XML is way too verbose).

*I do not have to write the code to ajax-read/display and UI-read/ajax-write over and over again.

I think most of my code can fit into tabular format (with Add/Delete/Save/Cancel buttons).


text:
Q: In VSCode, how can I select current element and it"s surroundings like in WebStorm? In WebStorm you can select an element and it's surrounding when you do Alt + Arrow Up.
How can you achieve that in VSCode ?

A: You can try with VSCode buit in Emmet: Balance (outward) command: Ctrl+Shift+A
If the shortcut does not work, follow these steps:

*

*Press Ctrl+Shift+P to open the Command Palette

*Type Emmet

*Select Emmet: Balance (outward)
This will select the tag where you have your cursor currently in, and all its contents (I understand that by its surroundings you mean the tag contents and the tag itself).
If the tag has as a content a combination of text and tags and your cursor is in the text, the command will select all the content. A new hit of the command will grow the selection to include the tag itself.


text:
Q: R set.seed() 's scope My R script calls sub-functions which contains set.seed(). What is the scope of the set.seed()? Will it also affect to main program that calls it?
More specificly
# main program
callsubfun()

... some statement ...

sample.int(100,20)

# sub function
callsubfun <- function(x,y,...){
   set.seed(100)
   ... do the work ...
   return(something)
}

A: Here's why you should NOT do that:
> set.seed(100)
> rnorm(1)
[1] -0.5021924
> rnorm(1)
[1] 0.1315312

> rand <- function() set.seed(100)
> rand()

> rnorm(1)
[1] -0.5021924   # Ouch!

A: set.seed is indeed global. But note this from the example in ?set.seed:
## If there is no seed, a "random" new one is created:
rm(.Random.seed); runif(1); .Random.seed[1:6]

This means you can call rm(.Random.seed, envir=.GlobalEnv) either at the end of your function or after you call the function to decouple the rest of the program from the call to set.seed in the function.
To see this in action, run the following code in two different R sessions. The outputs should be the same in both sessions. Then re-run the code again in two new R sessions with the rm line uncommented. You'll see the output in the two new sessions now differ, indicating that the call to set.seed in the function hasn't transferred the reproducibility to the main program.
subfun <- function() {
    set.seed(100)
    rnorm(1)
    #rm(.Random.seed, envir=.GlobalEnv)
}

subfun()
#[1] -0.5022

rnorm(1)
# [1] 0.1315

A: BondedDust's answer is ok, but not alway is Ouch!
You can use set.seed() in order to reproduce your
algorithm. i.e. anyone can reproduce your results.
I recommend you use set.seed if you wanted to share your
code. For example if you wanted some help in stackoverflow, we could
reproduce exactly your code.
set.seed(123)
rand<-rnorm(10)
plot(density(rand))

If you use another seed, you get other results
set.seed(234)
rand<-rnorm(10)
plot(density(rand))

Both are correct but it could be easier to help you if the seed was known.
By the way, just use set.seed once in your rutine because you could generate
dependence in your random numbers. We desire independent random numbers
in simulation.

A: set.seed function gives the specific random state for all code after itself. However, the code before it will not be affected.
Here is a minimal example.
rnorm(1)
#> [1] -0.1020965
set.seed(123)
rnorm(1)
#> [1] -0.5604756
rnorm(1)
#> [1] -0.2301775
rnorm(1)
#> [1] 1.558708

Created on 2018-10-20 by the reprex
package (v0.2.0).
rnorm(1)
#> [1] 0.4665633
set.seed(123)
rnorm(1)
#> [1] -0.5604756
rnorm(1)
#> [1] -0.2301775
rnorm(1)
#> [1] 1.558708

Created on 2018-10-20 by the reprex
package (v0.2.0).

*

*You will find all code next to set.seed are fixed at a given random state.

*But the codes before set.seed are different between the two trials, which support my opnion.


text:
Q: Foreman: List VMs of a compute reourse From Satellite 6/Foreman GUI, I can get the full list of VMs running on a compute resource. However, I cannot find a relevant command in hammer-cli. Do I miss something, or I just can't do it with hammer-cli?

A: AFAIK you cant do it with hammer-cli, so you dont miss something.

A: Looking at the API for 1.13 (most recent version of Foreman), there's no way of getting that information. https://theforeman.org/api/1.13/index.html .
hammer

relies on the API, therefore there's no way to do it.
Time to write a plugin? http://projects.theforeman.org/projects/foreman/wiki/How_to_Create_a_Plugin


text:
Q: 'QLineEdit' object has no attribute 'LineEdit'
def browse_base(self):
option=QFileDialog.Options()
file=QFileDialog.getOpenFileName(widget,"Open Single File","CC","All Files(*)",options=option)
self.base_addr.lineEdit.setText(file[0])

I have a problem here: 'QLineEdit' object has no attribute 'LineEdit'
And i don`t know what i need to do

A: It looks like you're assuming that self.base_addr has a lineEdit attribute that is a QLineEdit, but it seems that self.base_addr itself is already a QLineEdit (which has no lineEdit attribute), so that using just self.base_addr.setText(file[0]) should probably work.
However, this may just be the tip of the iceberg, but it is very hard to tell from the code in your question.


text:
Q: You and X others like this I am putting a system together and I would like to get the amount of rows of users that doesn't include the session['id'] user so I can show the link a bit like facebooks.
Example: You and x.. others likes this
Obviously just using the standard num rows grabs all the records from the database but I'd like to exclude the session.
$likes = mysqli_query($mysqli, "
    SELECT feedback_streamid,feedback_userid,feedback_rating FROM streamdata_feedback
        WHERE feedback_streamid=".$streamitem_data['streamitem_id']."
        AND feedback_rating=1 ORDER BY feedback_id LIMIT 10")

        or die("SELECT Error: ".mysqli_error($mysqli));

$numRowslikes = mysqli_num_rows($likes);
while ($row = mysqli_fetch_array($likes)) {
    $likesmemberid = rawfeeds_user_core::getuser($row['feedback_userid']);
    $user1_id = $_SESSION['id'];
    $user2_id = $row['feedback_userid'];
    if ($user2_id == $_SESSION['id']) {
        echo '
You and '.$numRowslikes.' Others likes this  ';
    } else {
    echo '  ';

    }
}

A: It sounds like you could just change your query to exclude the current user's ID, then use num_rows() as normal.
WHERE feedback_userid NOT IN ('whatever_id_here')


text:
Q: What am I missing with this API connection request string? I have my api_key in a ".env". I could be overthinking it. Here's my code as it currently stands, works without hiding the api_key. My syntax is incorrect when I pull from process.env.API_KEY.
function call_api(finishedAPI, ticker) {
    request('https://cloud.iexapis.com/stable/stock/' + ticker + '/quote?token= + 'api_key', { json: true }, (err, res, body) => {
        if (err) {return console.log(err);}
        if (res.statusCode === 200){
           finishedAPI(body);
        };
    });
};

I know there's a simpler way to do this and my research to google cues aren't firing on all cylinders. I'll buy you coffee or a tomato basil panini from Starbucks :-)

A: Should be. It also looks like your trying to use a callback incorrectly.
NOTE though, it's easy to tell you should always state the lang used. Just makes things easy for everyone.
function call_api(ticker, finishedAPI) {
    request({url: 'https://cloud.iexapis.com/stable/stock/' + ticker + '/quote?token= + 'api_key'}, { json: true }, (err, res, body) => {
        if (err) {return console.log(err);}
        if (res.statusCode === 200){
           finishedAPI(body);
        };
    });
};

function main(){
  call_api(ticker, function(fromCallapi){
     if(fromCallapi) console.log(fromCallapi);
  })
}

A callback would be called within another method or operation, and would returned to caller once the operation is completed by, passing the process, variable, or method back to it's caller.
NOTE the param finishedAPI should be renamed as callback it best practice to indicate that the process, variable, or method will be returning the result back to caller. Please note, that overly using callbacks can be overall affect the performance of you application and can hang processes. Hope that helps
UPDATE
If you have plan on using .env you'll need to use require('dotenv').config(path: '/path/to/.env') once loaded for example to access a variable named VARIBLE_NAME, you would access the env variable using process.env.VARIBLE_NAME

A: function call_api(finishedAPI, ticker) {
request('https://cloud.iexapis.com/stable/stock/' + ticker + '/quote?token=' + API_KEY, { json: true }, (err, res, body) => {
if (err) {return console.log(err);}
if (res.statusCode === 200){
finishedAPI(body);
};
});
};


text:
Q: Backup Maintenance Plan Overhead Longer than Actual Backups I created a maintenance plan to perform transaction log backups on a single database. The plan is scheduled as a job that runs every fifteen minutes. The plan has two steps:

*

*clean up log backup files older than two days old

*back up the transaction log to a new backup file

The job consistently takes a minimum of two minutes to complete, regardless of the amount of data being backed up or the number of old backups being purged. I started logging the job to see if there was anything noteworthy, and it confirmed that most of the time taken is not for the job tasks.
Microsoft(R) Server Maintenance Utility (Unicode) Version 12.0.6433
Report was generated on "IP ADDRESS".
Maintenance Plan: MN_LogBackup
Duration: 00:02:06
Status: Succeeded.
Details:

Maintenance Cleanup on Local server connection
Cleanup Database Backup files
Age: Older than 2 Days
Task start: 2022-05-04T12:00:58.
Task end: 2022-05-04T12:01:11.
Success
Command:EXECUTE master.dbo.xp_delete_file 0,N''X:\Backup'',N''trn'',N''2022-05-02T12:00:44''

GO

Backup Database on Local server connection
Databases: Database
Type: Transaction Log
Append existing
Task start: 2022-05-04T12:01:54.
Task end: 2022-05-04T12:02:08.
Success
Command:BACKUP LOG [Database] TO  DISK = N''X:\Backup\Database_backup_2022_05_04_120140_6920216.trn'' WITH NOFORMAT, NOINIT,  NAME = N''Database_backup_2022_05_04_120140_6920216'', SKIP, REWIND, NOUNLOAD,  STATS = 10

GO

This run only backed up 50MB. Is this standard behavior for maintenance plans? For comparison, a 36GB backup from earlier this morning took ninety seconds more to complete. The timing was the same - the backup task didn't start until 01:52 into the execution.
Additional information:
SQL Server is running on a WSFC hosted on two VMs. There are no simultaneous issues with network or I/O congestion. This happens consistently, on every run of the job (unless the job fails). It has been happening for months (I started logging in August 2021, but it had been ongoing at that point).


text:
Q: Bootstrap 3: How to precisely center text under a circular image? I'm using bootstrap 3, the text is not perfectly aligned under a circular image, this is more obvious on different screens and in bootstrap modals and in different languages, I don't want to start adding margin-left because if I do that, I'll be faulty on some screen. Is there a better way?

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">

       Arabic

       Dari

       Pashto

       Kurdish

       Farsi

       Tigrinya

       Amharic

       English

A: The easy fix to your code is just to add text-center class to all col-xs-* classes. That will center inner images and text inside the col-xs-* wrappers. Note I have added some background color to help visualize the effect.

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">

         Arabic

         Dari

         Pashto

         Kurdish

         Farsi

         Tigrinya

         Amharic

         English

A: You can add a custom class .center to your outermost .container div. This will align the image and text to center using text-align: center;.

.center {
  text-align: center;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">

         Arabic

         Dari

         Pashto

         Kurdish

         Farsi

         Tigrinya

         Amharic

         English

A: You could use only one row and then center the image and the text.

             Arabic

Update: you can still use the columns... I've added them to the short version of your example

A: Flexbox
CSS
display : flex;
justify-content : center;
align-items : center


text:
Q: Comments plugin does not position well in FF or Chrome Seems that my comments plugin does not position well on my page. Instead of being centered the left margin of the plugin is at the center in Firefox and Chrome. Displays well in IE. The problem started two days and I did not change my code.
Page: http://www.yimago.com/radio1/
Code I used:

<fb:comments-count href=http://www.yimago.com/radio1/></fb:comments-count> comments

Hello:
Added this to my CSS:
.fb_iframe_widget iframe {position:relative; left:0px;}

Seems to solve my problem. Hope this help others.

A: Added this to my CSS:
.fb_iframe_widget iframe {left: 0px;}

Seems to solve my problem.


text:
Q: How can I pass a result of a query to a function? I want to do something like this
function A(){
    session database_handler(....);

    result res = database_handler << "SELECT ....";

    functionB(res);
}

what should the parameters of functionB be?
Passing it as a pointer does not work, neither as in the example.
Thanks

A: You can safely copy cppdb::result but you may iterate over it only in one location. i.e. cppdb::result holds a reference (counted) to the result object so if you iterate over rows in functionB you can't iterate over them in functionA
So you can safely define
void functionB(cppdb::result res);

However it would be the same in terms of iterating as
void functionB(cppdb::result &res);

Also the last one faster as it does not involve reference counting overhead.

A: One simple way is to create a structure similar to your result set.
populate that structure and pass a structure pointer to function.
other way is to declare your function as functionB(result res) i.e. it accepts parameters of type result and then extract query result from "res"


text:
Q: How we can find the sum of all roots for $x^2+\cos x=2019$ How to find the sum of all real roots such that, $$x^2+\cos x=2019$$
Firstly I think to use numerical methods , but this shortcut is weak and depend on % error .As result, im searching for an algebraic way to solve such exercise.
As result , is there any hint to crack this task ?

A: You can easily establish that $f(x)=x^2+\cos x -2019$ has a unique root in $[0,+\infty[$, lets say  $z>0$. Since $f$ is even, it will also have a unique root in $]-\infty, 0]$, which will be $-z$. Therefore, the sum of all roots is zero.

A: In fact, you don't even have to look for the number of roots. Observe that $$x^2=(-x)^2\qquad \cos(x)=\cos(-x)$$ This implies that if $x_1$ is a root for your equation, so is $-x_1$. Therefore, you just have to evaluate $$\sum(x_1-x_1)=0$$


text:
Q: First time I've built a class, but IDE is throwing up a syntax error; not shown when functions/variables are extracted from class? Finally, I'm getting into OOP and attempting to put together my first class. However, my IDE (NetBeans) throws up an error on the last function's (sanitize()) closing parentheses. This doesn't happen when all the class contents are extracted from the class.
Here's my code:
class db_class {

    $error_log = false;

    function connect($db_host, $db_user, $db_pass) {
        $connect = mysql_connect($db_host, $db_user, $db_pass);
        return $connect;
    }

    function select_db($db_database) {
        $select_db = mysql_select_db($db_database);
        return $select_db;
    }

    function array_prepare($data) {
        $size = sizeof($array);

        foreach($array as $k => $v) {
        $keys[] = $k;
        }

        $size_md = sizeof($array[$keys[0]]);
        for($i = 0; $i < $size_md; $i++) {
            $value .= '(';
            for($j = 0; $j < $size; $j++) {
                    $value .= "'".$array[$keys[$j]][$i]."',";
            }
            $value = rtrim($value, ',');
            $value .= '), ';
        }
        $value = rtrim($value, ',');

        return $value;
    }

    function sanitize($data) {
        if(is_array($data))
        foreach($data as $k => $v)
            $data[$k] = sanitize($v); //recursive
        elseif(is_string($data))
            $data = mysql_real_escape_string($data);
        return $data;
    } // <- where the error is thrown up

}

I really don't see what I've done wrong, and the suggestions offered by NetBeans are many (it offers like 10 explanations for the syntax error). Can anyone pick up what could be causing this issue?
Any help would be greatly appreciated!

A: You're missing a visibility declaration on your property.
In other answers they have you use var, however I would advise you to use PHP5 visibility declarations; public, protected or private.  The visibility of the variable should be based on the need for that piece of data.  As a general rule though, you should limit the amount of properties that are declared public.  Ultimately, you have no control over the data that can be assigned to a public property.
Furthermore, you should put a visibility declaration on your functions as well.  Not having any visibility declaration will mark them as public, this is probably not what you'll want for all functions in a class.


text:
Q: Chromedriver Slow on Javascript Execution Background
I'm using Selenium Webdriver .Net for coding and MSTest is being used from within Visual Studio 2012 and MSTest cmd in order to run the tests.
I have encountered a strange issue in Chromedriver, where Javascript execution extremely slowdown the test execcution. Eg:- I'm using javascript to WaitForAjax, ScrollToElemet and functions in my tests.
When I execute one test at a time, it executes very fast. But when I execute them as a suite, The first test executes fast and starting from the second test, the execution slows down significantly.
My Configuration is as follows:

*

*Chrome Version: 41.0.2272.118 m

*Chrome Driver: 2.14

*Selenium .Net: 2.44

*Windows: 7 Enterprise 64 bit

Any help would be appreciated to resolve this issue.
Thanks
Here's the functions as requested
public static IWebElement ScrollToElement(this IWebElement element)
    {
        try
        {
            IJavaScriptExecutor executor = (IJavaScriptExecutor)driver;
            executor.ExecuteScript("window.scrollTo(" + element.Location.X + "," + (element.Location.Y - 500) + ");");
        }
        catch (Exception)
        {
        }
        return element;
    }

public static void WaitForAjax(this IWebDriver driver, int timeout = 60)
    {
        IJavaScriptExecutor javascript = driver as IJavaScriptExecutor;
        if (javascript == null)
        {
            // Log a warning
        }
        else
        {
            try
            {
                var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(60));
                wait.Until(drv => (bool)(drv as IJavaScriptExecutor).ExecuteScript("return jQuery.active == 0"));
            }
            catch (WebDriverTimeoutException ex)
            {
                Assert.Inconclusive(string.Format("Ajax Calls Didn't Complete After: {0} seconds. Exception message: {1}", timeout, ex.Message));
            }
        }
    }


text:
Q: How would I isolate or just store the second element in a for loop inside a batch file? I'm using a loop inside a Windows batch file to return PID numbers and I only want to use the second PID number. How do I set the second element, the second PID number as a variable or just use it in a command in the loop instead of echo?
The code..
for /f "tokens=2 delims=," %%a in ('tasklist /FO CSV ^| findstr /I cmd.exe') do (
    echo PID:%%a
)

I tried indexing the element like this PID:%%a[1]. It didn't work.

A: Perhaps you want deal like this code ?
@echo off
SetLocal EnableDelayedExpansion
@for /f "tokens=2 delims=," %%a in ('tasklist /FO CSV ^| findstr /I cmd.exe') do (
    set /A count+=1
    Set "PID[!count!]=%%~a"
)

@For /L %%i in (1,1,%count%) do echo PID[%%i] = !PID[%%i]!
echo( I want this PID = !PID[2]!
pause


text:
Q: Hide next track/slide duration from Now Playing I have a radio App, and i playing it with AVPlayer.
I display the Name radio in MPNowPLaying.
I want hide button next/previous track and slide bar with PLayback Duration. How can i do it? I want display like in pictures below:

A: You can't hide them. But starting in iOS 7.1 you can disable them:
// Disable previous track button
[MPRemoteCommandCenter sharedCommandCenter].previousTrackCommand.enabled = NO;
// Disable next track button
[MPRemoteCommandCenter sharedCommandCenter].nextTrackCommand.enabled = NO;

For the playback duration, just don't set anything for MPMediaItemPropertyPlaybackDuration in your [[MPNowPlayingInfoCenter defaultCenter] setNowPlayingInfo:]
On top of that, you can show custom info (and even an artwork) on the now playing screen:
NSMutableDictionary *songInfo = [[NSMutableDictionary alloc] init];
[songInfo setObject:someTitle forKey:MPMediaItemPropertyTitle];
[songInfo setObject:someArtist forKey:MPMediaItemPropertyArtist];
[songInfo setObject:someAlbum forKey:MPMediaItemPropertyAlbumTitle];

MPMediaItemArtwork *albumArt;
if (song.artwork){
    albumArt = [[MPMediaItemArtwork alloc] initWithImage: someArtwork];
}
else {
    albumArt = [[MPMediaItemArtwork alloc] init]; // make sure to remove the artwork if none is found for the current track
}
[songInfo setObject:albumArt forKey:MPMediaItemPropertyArtwork];
[[MPNowPlayingInfoCenter defaultCenter] setNowPlayingInfo:songInfo];


text:
Q: Changing % formatting to f-string colors = ['black', 'white']
sizes = ['S', 'M', 'L']
for tshirt in ('%s %s' % (c, s) for c in colors for s in sizes):
    print(tshirt)

black S
black M
black L
white S
white M
white L

So I am trying to remove those %s %s and instead have a f string formatting. Can someone be kind enough to show how this is done. Thanks

A: >>> colors = ['black', 'white']
>>> sizes = ['S', 'M', 'L']
>>> for c in colors:
...    for s in sizes:
...        print(f'{c} {s}')

Another approach is to use itertools.product:
>>> for c, s in itertools.product(colors, sizes):
...     print(f'{c} {s}')

A: You can write the variable names in curly brackets ({...}):
for tshirt in (f'{c} {s}' for c in colors for s in sizes):
    print(tshirt)
Although it is a bit strange to use a generator in this case for a for loop: you can unfold this into (two) nested for loops, like in @nosklo's answer (although this of course does not change anything about the usage of the literal string interpolation [PEP-498].


text:
Q: Не видна переменная внутри функции Переменная q внутри функции f - локальная, т.е. доступна внутри тела функции.
Вопрос: почему она недоступна в функции obj.func?

var qwe = 1;
function f() {
    var q = {};
    var qwe = 2;
    debugger;
    var obj = {
        a: q,
        func: function() {
            // тут q не видна, а qwe === 1.
            debugger;
        }
    };
    obj.func();
    debugger;
}

f();

Вроде как, при создании obj.func, ее [[Scope]] должен ссылаться на объект переменных функции f (т.к. func создана в контексте функции f), но из кода видно, что ссылается на глобальный объект (Переменная qwe равна 1, а не 2).

A: На самом деле проверка несколько некорректна.
Отладчик показывает реальное состояние скопов.
Пример в хроме:

Как можно заметить в момент вызова функции доступны два скопа:

*

*Локальный скоп функции

*Глобальный скоп.

Некорректность проверки заключается в том, что функция пуста, нет обращений к переменным из скопа функции f, соответственно нет замыканий.
При проверке: поиск осуществляется в доступных в данный момент скопах, и там действительно нет переменной q, а переменная qwe - находится в глобальном скопе и имеет значение 1.

Если же изменить код, добавив в него замыкание. Предстанет совсем другая картина:

Как можно отметить, добавился скоп Closure, в котором и хранится используемая переменная q из скопа f.
И при проверке - он будет определена и иметь значение - пустой объект.
Также стоит обратить внимание, что раз переменная qwe не замкнута, она по прежнему будет отдавать 1 при проверке.

A: Давайте не будем никому верить на слово, а просто запустим код.

var qwe = 1;
function f() {
    var q = { test: "Test" };
    var qwe = 2;
    var obj = {
        a: q,
        func: function() {
            // тут q не видна, а qwe === 1.
            console.log(q); // видна
            console.log(qwe); // 2
        }
    };
    obj.func();
}

f();

A: Переменные были удалены сборщиком мусора (Оптимизация в V8 и её последствия).

A: если хочешь переменные за пределы функции видеть просто не обЪявляй что это переменная. пример
(не var i = 10; а просто i = 10; без var ) я сам так делаю


text:
Q: Parameter that's a list of interface{} I'm trying to create a function that prints out the len of a list passed into it, regardless of the type of the list.  My naive way of doing this was:
func printLength(lis []interface{}) {
    fmt.Printf("Length: %d", len(lis))
}

However, when trying to use it via
func main() {
    strs := []string{"Hello,", "World!"}
    printLength(strs)
}

It complains saying
cannot use strs (type []string) as type []interface {} in argument to printLength

But, a string can be used as a interface{}, so why can't a []string be used as a []interface{}?

A: You can use reflect package - playground
import (
    "fmt"
    "reflect"
)
func printLength(lis interface{}) {
    fmt.Printf("Length: %d", reflect.ValueOf(lis).Len())
}


text:
Q: How to Search Replace when filename URLs are different I want to search-replace a line that contains different addresses but I just want to search-replace a specific portion. Like
Search: < img border="0" src="*http://2.bp.blogspot.com/-OKZyRpnFLgw/UtqngoauEwI/AAAAAAADOlM/aXCJiiTRkaM/*s1600/005.JPG"/ >
Replace: < img border="0" src="*http://2.bp.blogspot.com/-OKZyRpnFLgw/UtqngoauEwI/AAAAAAADOlM/aXCJiiTRkaM/*s420/005.JPG"/ >
I just want to change the bold text. The Italic text changes in every file address.
I cant just simply search replace s1600 with s420 because it changes many other entries, I just want to make this change if it appears in < img address.
Help!

A: Using a Find what of (< img[^>]*?)s1600 and a Replace with of \1s420 will work on the line you give; you should have Regular expression selected. It will replace a single occurrence of s1600 between an < img and the next >. If you expect two or more s1600 between the strings then run the replace multiple times.
The Find what may not be strict enough. If text such as pqrs1600 or s160000 should not be altered then you could try (< img[^>]*?)\bs1600\b.
If the s1600 always occurs between a * and a \ as in the example then the Find what may be better as (< img[^>]*?\*)s1600/ and then the  Replace with should be \1s420/.
The basic idea in each case is to match the text that identifies where the item is and to capture that text using the round braces. The [^>]*? matches zero or more characters that are not a >, the *? parts indicates a non-greedy match, so it matches the smallest sequence possible before the next part of the regular expression.


text:
Q: Managing dependencies in Angular JS karma grunt testing My controller :
/**
 * @description
 * Controller for Comparative Analysis dashboard.
 */

(function (define) {

    define([], function () {

        /**
      * Constructor function.
      *
      * @param {Object} $scope Object that binds model to view.
      * @param {Object} $log object(angular service) to log info,waring and error messages.
      *

      */
        //var caDashboardController = function ($scope, $log, configService, caCommonService, caConsumptionChartService) {
        var caDashboardController = function ($scope, $log) {

   }
        return ["$scope", "$log", caDashboardController];

    });

})(define);

My Module :
(function (define, angular) {

    'user strict'

    define([

        'myAnalytics/comparativeAnalysis/dashboard/controllers/caDashboardController',

        ], function (caDashboardController) {

        var moduleName = "AnalyticsApp.comparativeAnalysis";

        angular.module(moduleName, ['ngRoute', 'ngResource', 'kendo.directives'])
        .config(['$routeProvider', function config($routeProvider) {

            $routeProvider.when('/comparativeAnalysis', {
                controller: 'caDashboardController',
                templateUrl: 'app/myAnalytics/comparativeAnalysis/dashboard/comparativeAnalysisdashboard.html'
            });

        }])
            .controller("caDashboardController", caDashboardController);

        return moduleName;
    });

})(define, angular);

My Unit test case Spec :
(function (define) {
    'use strict';

    define([
        'kendo',
        'angularRoute',
        'angularResource',
        'moment',
        'myAnalytics/comparativeAnalysis/dashboard/comparativeAnalysisModule'
    ],
    function () {

        describe('Test for comparative Analysis Dashboard Controller', function () {

              var scopeMock, logMock, ctrl, configServiceMock, caCommonServiceMock, caConsumptionChartServiceMock;

                var serviceResponse = null;

                var deferredCompareResult;

                beforeEach(module('AnalyticsApp.comparativeAnalysis'));

                beforeEach(inject(function ($rootScope, $log, caCommonService, caConsumptionChartService) {
                    scopeMock = $rootScope.$new();
                    logMock = $log;

                    //configServiceMock = { comparativeAnalysisUrl: '/COMPARATIVEANALYSISURL/' };
                    configServiceMock = { csrServiceUrl: '/CSRSERVICEURL/' };//$injector.get('configService');
                    caCommonServiceMock = caCommonService;
                    caConsumptionChartServiceMock = caConsumptionChartService;
                }));

                describe('Successful Server response tests', function () {

                    beforeEach(inject(function ($controller, $q) {

                        deferredCompareResult = $q.defer();
                        deferredCompareResult.resolve(serviceResponse);

                        //spyOn(caCommonServiceMock, 'getData').and.returnValue(deferredCompareResult.promise);
                        //spyOn(caConsumptionChartServiceMock, 'getChartData').and.returnValue(deferredCompareResult.promise);

                        ctrl = $controller('caDashboardController',
                        {
                            '$scope': scopeMock,
                            '$log': logMock
                            //'configService': configServiceMock
                            //'caCommonService' :caCommonServiceMock,
                            //'caConsumptionChartService': caConsumptionChartServiceMock
                        });

                    }));

                    it('$scope should be configured', function () {
                        expect(ctrl).toBeDefined();
                    });

                    it('Consumption Graph Data should be set', inject(function ($rootScope) {
                        //expect(ctrl).toBeDefined();
                        //expect(scopeMock.caViewModel.chartData).toBeDefined();
                        ////scopeMock.caViewModel.search('');
                        //expect(caConsumptionChartServiceMock.getChartData).toHaveBeenCalled();
                        //$rootScope.$apply();
                        //expect(scopeMock.caViewModel.chartData).toBe(null);
                    }));

                });
            });
        });
    })(define);

In Ctrl I am just referring '$scope' and '$log' --
ctrl = $controller('caDashboardController',
                    {
                        '$scope': scopeMock,
                        '$log': logMock
                        //'configService': configServiceMock
                        //'caCommonService' :caCommonServiceMock,
                        //'caConsumptionChartService': caConsumptionChartServiceMock
                    });

I am getting few errors ;
Error: [$injector:unpr] Unknown provider: configServiceProvider <- configService <- caCommonService

Error: Declaration Location

Error: Expected undefined to be defined.

Please help me How I can configure this. As you can see I am not using anything in my Controller. Its almost empty, But still I am getting this errors..
I have no reference for configService But error is related to that.

A: (function (define) {
    'use strict';

    define([
        'kendo',
        'angularRoute',
        'angularResource',
        'myAnalytics/comparativeAnalysis/dashboard/services/caCommomService',
        'myAnalytics/comparativeAnalysis/dashboard/services/caConsumptionChartServic',
        'myAnalytics/comparativeAnalysis/dashboard/controllers/caDashboardController',
    ],

    function (moment,caCommomService,caConsumptionChartServic,caDashboardController) {
        var abcController;
        beforeEach(inject(function ($rootScope,$controller, $q, $timeout) {
            scope = $rootScope.$new();
            q = $q;
            timeout = $timeout;
            abcController = $controller(caDashboardController, {
                $scope: scope,
                abcService: caConsumptionChartServic
            });
    }));
    // you are using requirejs dependencies so try to pass direct files and use no to get main module.
}


text:
Q: How do check that applications on two different Servers are using the same version of a dll? How I have two programs that use the same dll on different servers.  How do I check that both servers are using the same dll version? In this case, I want to make sure Exchange and Blackberry Enterprise Server are using the same version of a dll.
Sorry, I didn't really ask this question right the first time.

A: Use tasklist /M command to list all DLL modules loaded for a specific process
edit: If you want to show the specific version of a DLL used by a process, I recommand using the graphical tool Process Explorer from Sysinternals. Once you run the tool, click on a specific process and it will gives you the list of DLLs (with version) that are hooked to this process.

A: Ummm... look at the file information? It's on the Details or Version tab of the file properties, depending on which version of Windows you're running.


text:
Q: I need an API. Where should I start? I'm building a PHP application from scratch (using Kohana3 framework). I'm going to architect it so that I can use an API to access the data internally. At the same time, I want to eventually offer it to the public.
I plan on using the RESTful access method. However, I'm having a hard time finding clear information on how to properly secure the API. In other words, how do I implement API signatures and access?

A: You could try frapi. It will quickly allow you to build your RESTful API, which you can then use for your application, and at a later date expose the same API publicly.

A: OAuth would be a good choice. So would a single key/value pair. You might also want to look at Mashape but not entirely sure it fits what you are trying to do.

A: I think a good place to start would be reading over general information about digital signing.  Wikipedia is a great resource http://en.wikipedia.org/wiki/Public_Key_Infrastructure or http://en.wikipedia.org/wiki/X.509.
On a basic level I would give each client a private Key.  In the client library I would encrypt the key. When a client makes a request verify that the key is the one that you issued to that particular client.

A: Take a look at 3scale (http://www.3scale.net/) to do this - it handles authentication, access control, policies, rate limits etc. and is free for significant traffic. We have a PHP module to plugin to the system to enable these features. (Disclaimer - I work there - but hope it's useful!)

A: I have made a PHP REST API using CodeIgniter with Basic Authentication, (providing "company id" and "API Key" as username/password). Later we found that it was necessary to provision session keys that were directly related to an API Key, only with an expiration time.
Basically, we queried different types of data in our datastore (nosql variety :) depending on what the "method" was provided in the URL. We accessed this by using the "segment" ability provided by CodeIgniter.
Then we wrapped each response with a "json_encode" that was returned and we also used an HTTPS connection for security.
For the client class we wrapped everything in calls such $client->get_my_data($api_key), with a layer underneath using PHP Libcurl, which works really well to provide the Basic Auth.
Hope this helps,
CURL_GET
    private function curl_get($url, $apikey, $co)
    {
        $curl_handle = curl_init();
        curl_setopt($curl_handle, CURLOPT_URL, $url);
        curl_setopt($curl_handle, CURLOPT_CONNECTTIMEOUT, 2);
        curl_setopt($curl_handle, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl_handle, CURLOPT_USERPWD, $co.":".$apikey);
        curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl_handle, CURLOPT_DNS_USE_GLOBAL_CACHE, FALSE);

        $buffer = curl_exec($curl_handle);
        $error = curl_error($curl_handle);
        curl_close($curl_handle);
        // check for success or failure
        if (empty($buffer)) {
        //echo 'Something went wrong :( error: '.$error.'<Br>';
        } else {
        return $buffer;
        }
    }

A: Your question is a bit bigger than this; but I can offer one small observation about REST.
I have found with REST, that is that it is best to use artificial keys for the underlying data model, rather than natural keys.
For example, consider the RESTfull url:  https://server/yourApp/viewUser/1234.html this would show the user with id 1234.  However if you used natural keys you might have a URL something like this https://server/yourApp/viewUser/Bob.html or worse if instead of Bob its "Bob X" or "Bob?key=Value".  You don't want to have to think about generating invalid URLs.


text:
Q: Combine query in WP_User_Query() I am new user of WP_User_Query(). I don't know how to express whole situation. If I use below code I am getting good result.
$users = new WP_User_Query(array(
        'meta_query' => array(
            'relation' => 'OR',
            array(
                'key' => 'last_name',
                'value' => $_POST['search'],
                'compare' => 'LIKE',
            ),
        )
    ));

If I use below code I am getting good result also.
$users = new WP_User_Query(array(
        'meta_query' => array(
            'relation' => 'OR',
            array(
                'key' => 'organisation',
                'value' => 519,
                'compare' => 'LIKE',
            ),
        )
    ));

I am trying to combine these two query like below.
$users = new WP_User_Query(array(
        'meta_query' => array(
            'relation' => 'OR',
            array(
                'key' => 'last_name',
                'value' => $_POST['search'],
                'compare' => 'LIKE',
            ),
            array(
                'key' => 'organisation',
                'value' => 519,
                'compare' => 'LIKE',
            ),
        )
    ));

But I am not getting expected output.
How can I combine these two queries ?


text:
Q: extract valus of another dataframe if value of one column is partially match in R Sorry I didn't clarify my question,
my aim is if dt$id %in% df$id , extract df$score add to new column at dt,
I have a dataframe like this :
df <- tibble(
score = c(2587,002,885,901,2587,3371,3372,002),
id = c("AR01.0","AR01.1","AR01.12","ERS02.00","ERS02.01","ERS02.02","QR01","QR01.03"))

And I have another dataframe like
dt <- tibble(
id = c("AR01","QR01","KVC"),
city = c("AM", "Bis","CHB"))

I want to mutate a new column "score"
I want to got output like below :

id
city
score

AR01
AM
2587/2/885

ERS02
Bis
901/3371

KVC
CHB
NA

or

id
city
score
score2
score3

AR01
AM
2587
2
885

ERS02
Bis
901
3371
NA

KVC
CHB
NA
NA
NA

I tried to use ifelse to achieve but always got error,
do any one can provide ideas? Thank you.

A: A simple left_join (after mutateing id values in df) is required:
library(dplyr)
library(stringr)
left_join(df %>% mutate(id = str_extract(id, "[\\w]+")), dt, by = "id") %>%
  group_by(id) %>%
  summarise(across(city,first),
            score = paste(score, collapse = "/"))
# A tibble: 3 × 3
  id    city  score
  <chr> <chr> <chr>
1 AR01  AM    2587/2/885
2 ERS02 NA    901/2587/3371
3 QR01  Bis   3372/2

For the second solution you can use separate:
library(dyplr)
library(stringr)
library(tidyr)
left_join(df %>% mutate(id = str_extract(id, "[\\w]+")), dt, by = "id") %>%
  group_by(id) %>%
  summarise(across(city,first),
            score = paste(score, collapse = "/")) %>%
  separate(score,
          into = paste("score", 1:3),
          sep = "/" )
# A tibble: 3 × 5
  id    city  `score 1` `score 2` `score 3`
  <chr> <chr> <chr>     <chr>     <chr>
1 AR01  AM    2587      2         885
2 ERS02 NA    901       2587      3371
3 QR01  Bis   3372      2         NA

A: You could create groups by extracting everything before the . using sub to group_by on and merge the rows with paste separated with / and right_join them by id like this:
library(tibble)
df <- tibble(
  score = c(2587,002,885,901,2587,3371,3372,002),
  id = c("AR01.0","AR01.1","AR01.12","ERS02.00","ERS02.01","ERS02.02","QR01","QR01.03"))

dt <- tibble(
  id = c("AR01","QR01","KVC"),
  city = c("AM", "Bis","CHB"))

library(dplyr)
df %>%
  mutate(id = sub('\\..*', "", id)) %>%
  group_by(id) %>%
  mutate(score = paste(score, collapse = '/')) %>%
  distinct(id, .keep_all = TRUE) %>%
  ungroup() %>%
  right_join(., dt, by = 'id')
#> # A tibble: 3 × 3
#>   score      id    city
#>   <chr>      <chr> <chr>
#> 1 2587/2/885 AR01  AM
#> 2 3372/2     QR01  Bis
#> 3 <NA>       KVC   CHB

Created on 2022-10-01 with reprex v2.0.2


text:
Q: TinyMce v.6 how to remove "br" tags added after each paragraph I'm using version 6 of TinyMce and I can't find a way to avoid adding
 after each paragraph
Inserting a line of text and pressing enter creates a new paragraph, but a
 is always added between one and the other.
In the old versions it was enough to add these two parameters:

*

*force_p_newlines = true;

*forced_root_block = false;

But now both are deprecated and I can't find a way to achieve the same result
The guide says that force_p_newlines is no longer available that forced_root_block should be used instead, but even setting forced_root_block: "p" which should already be like this by default, nothing changes
I tried to change the default tag which is
 with a
, but I always find the
 nested between the various divs in the output.
My current initialization is:
tinymce.init({
  selector:'#myTextarea',
  plugins: "link",
  toolbar: "undo redo | bold italic link ",
  menubar: false,
  forced_root_block: "p",
    forced_root_block_attrs: {
      class: "m-0",
    },
  force_br_newlines: false,
});

I'm using bootstrap 5 and I've used the forced_root_block_attrs attribute to eliminate paragraph margins by attributing class "m-0" to all
 tags

A:     tinymce.init({
  selector:'#myTextarea',
  plugins: "link",
  toolbar: "undo redo | bold italic link ",
  menubar: false,
  forced_root_block: "",
    forced_root_block_attrs: {
      class: "m-0",
    },
  force_br_newlines: true,
force_p_newlines: false,
});

try this may be work?


text:
Q: Is there an Excel Keyboard Shortcut for freezing the top row? Is there an Excel Keyboard Shortcut for freezing the top row?
I'm currently using Excel 2010.

A: There's no built-in shortcut for this. You can try the following options, though:

*

*Press Alt + W, then F, then R. This is the equivalent of selecting it with the mouse from the View tab.

*

*optional: bind this sequence to a shortcut using an Excel macro or, say, an AutoHotkey script.

*Add that command to the Quick Access toolbar at the top of the window.

Which one works best for you depends on how much time you want to spend on it, and whether you're faster with the keyboard or with the mouse.

A: As indrek mentioned, create a macro and assign the macro a shortcut. (could be better ways to write this but it worked for me in excel 2007).
IF you want the shortcut available to any file you open, you will need to create it in a 'Personal Macro Workbook' without going into excruciating detail on this process, one way to auto create this is by recording a new macro, and selecting 'Personal Macro Workbook' instead of storing it in 'This Workbook' from the record macro window.
Sub freezetoprow()
Range("a1").Activate
With ActiveWindow
    .SplitColumn = 0
    .SplitRow = 1
End With
ActiveWindow.FreezePanes = True
End Sub

A: I don't have 2010 but in 2007 it's under view tab then half way across it's freeze cells.  I do know that Microsoft had an interactive help solution where you click where it was on the previous version you had and it shows on the new version... now IF they have that between 2007 to 2010 I am not sure.  Of course you can always help... :-)

A: Using excel 2013
Go to:
'File'
    'Options'
         'Quick Access Toolbar'
Scroll down to 'Freeze Panes' and double click or select it and click 'Add'
I am not sure if this option is available in later versions


text:
Q: how to custom angular ng-grid cell like this? RT,now in a table the last cell have 3 states,such as 'edit','submit','cancel'...
so how to show that depend on cell state?
PS:my En is so poor,but thanks first!
sorry cannot upload pic,so just code some words to show what mean.

        name
        age
        options

        foo
        21
        submitdelete

        bar
        21
        cancel

        bar
        21
        editdelete


text:
Q: Taking JSON sub arrays I am quite confused with JSON, I can easily take first level arrays values, but having problem with subs.
I am using $.getJSON and code is
$.getJSON('http://www.authenticjobs.com/api/?api_key=4c4f1d5934d66ca872dfa2a0cfd3a20b&method=aj.jobs.search&perpage=3&format=json&callback=?', function(data) {
var listings = "";

$.each(data.listings.listing, function(index, listing) {

    listings += "
" + listing.company.name + " needs a " + listing.title + "";

        if (listing.location != "") {
            listings += " in " + listing.location;
        }

    listings += "
";

});

$("#authentic-jobs ul").append(listings);

});

Visual data is here: http://cloud.ignatynikulin.com/2v0F2p2x111r0X3k4441
I can't get company location name.
I ve tried listing.company.location.name but it's not working and also don't make any sense.
Thank you!
Answer will be (thank you GregL):

Since listing.company.location is a nested object (visualised by the
  {} in the picture you attached), so you just want to check if the
  object is not something like undefined, null or similar (what are
  called "falsey values" in Javascript).

A: I think I created a jsFiddle that works here.
The key is to use:
    if (listing.company.location) {
        listings += " in " + listing.company.location.name;
    }

A: listings += " in " + listing.company.location.name;


text:
Q: How hive find given decimal value is incorrect to defined decimal type and return NULL On Hive shell when I fire query
select cast(1234.0 as decimal(7,6)) it return NULL.
also 1234.0 with decimal(7,5),decimal(7,4) is invalid and Hive return NULL. But with Decimal(7,0),Decimal(7,1),Decimal(7,2),Decimal(7,3) it worked. Can any body tell me how Hive works with decimal

A: Decimal(magnitude,scale)

means a decimal with magnitude total significant digits, of which scale are to the right of the decimal point.  So Decimal(7,3) can contain a number of up to 7 significant digits, of which 3 are to the right of the decimal (i.e. mmmm.sss) while Decimal(7,4) still has 7 total digits but 4 are to the right of the decimal point, leaving only three for the integer part (mmm.ssss).
This latter format is not capable of representing the number 1234.0 as it has too many digits to the left of the decimal point.


text:
Q: Android: Search a specific nearby place type using maps api I am creating a Google Maps app. In my app I am searching for nearby ATM by using Places type "atm". It all works perfectly, but I have to find specific nearby ATM such as Axis bank ATM so please solve my problem using following code.......
public class MainActivity extends FragmentActivity implements OnMapReadyCallback,
        GoogleApiClient.ConnectionCallbacks,GoogleApiClient.OnConnectionFailedListener,
        LocationListener {

    private GoogleMap mMap;
    GoogleApiClient mGoogleApiClient;
    Location mLastLocation;
    Marker mCurrLocationMarker;
    LocationRequest mLocationRequest;
    String[] mPlaceType=null;
    String[] mPlaceTypeName=null;
    Spinner mSprPlaceType;
    double mLatitude=0;
    double mLongitude=0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Array of place types
        mPlaceType = getResources().getStringArray(R.array.place_type);

        // Array of place type names
        mPlaceTypeName = getResources().getStringArray(R.array.place_type_name);

        // Creating an array adapter with an array of Place types
        // to populate the spinner
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, mPlaceTypeName);

        // Getting reference to the Spinner
        mSprPlaceType = (Spinner) findViewById(R.id.spr_place_type);

        // Setting adapter on Spinner to set place types
        mSprPlaceType.setAdapter(adapter);

        Button btnFind;

        // Getting reference to Find Button
        btnFind = (Button) findViewById(R.id.btn_find);

        // Getting Google Play availability status
        int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());

        if (status != ConnectionResult.SUCCESS) { // Google Play Services are not available

            int requestCode = 10;
            Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode);
            dialog.show();

        } else { // Google Play Services are available

            if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                checkLocationPermission();
            }
            // Obtain the SupportMapFragment and get notified when the map is ready to be used.
            SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                    .findFragmentById(R.id.map);
            mapFragment.getMapAsync(this);
        }

        // Setting click event lister for the find button
        btnFind.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                int selectedPosition = mSprPlaceType.getSelectedItemPosition();
                //String type = mPlaceType[selectedPosition];
                String type = "atm";
                StringBuilder sb = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
                sb.append("location="+mLatitude+","+mLongitude);
                sb.append("&radius=5000");
                sb.append("&types="+type);
                sb.append("&sensor=true");
                sb.append("&key=******************************");

                // Creating a new non-ui thread task to download json data
                PlacesTask placesTask = new PlacesTask();

                // Invokes the "doInBackground()" method of the class PlaceTask
                placesTask.execute(sb.toString());

            }
        });
    }

    /** A method to download json data from url */
    private String downloadUrl(String strUrl) throws IOException {
        String data = "";
        InputStream iStream = null;
        HttpURLConnection urlConnection = null;
        try{
            URL url = new URL(strUrl);

            // Creating an http connection to communicate with url
            urlConnection = (HttpURLConnection) url.openConnection();

            // Connecting to url
            urlConnection.connect();

            // Reading data from url
            iStream = urlConnection.getInputStream();

            BufferedReader br = new BufferedReader(new InputStreamReader(iStream));

            StringBuffer sb  = new StringBuffer();

            String line = "";
            while( ( line = br.readLine())  != null){
                sb.append(line);
            }

            data = sb.toString();

            br.close();

        }catch(Exception e){
            Log.d("Exception while downloading url", e.toString());
        }finally{
            iStream.close();
            urlConnection.disconnect();
        }

        return data;
    }

    /** A class, to download Google Places */
    private class PlacesTask extends AsyncTask<String, Integer, String>{

        String data = null;

        // Invoked by execute() method of this object
        @Override
        protected String doInBackground(String... url) {
            try{
                data = downloadUrl(url[0]);
            }catch(Exception e){
                Log.d("Background Task",e.toString());
            }
            return data;
        }

        // Executed after the complete execution of doInBackground() method
        @Override
        protected void onPostExecute(String result){
            ParserTask parserTask = new ParserTask();

            // Start parsing the Google places in JSON format
            // Invokes the "doInBackground()" method of the class ParseTask
            parserTask.execute(result);
        }
    }

    /** A class to parse the Google Places in JSON format */
    private class ParserTask extends AsyncTask<String, Integer, List<HashMap<String,String>>>{

        // Invoked by execute() method of this object
        @Override
        protected List<HashMap<String,String>> doInBackground(String... jsonData) {

            JSONObject jObject;

            List<HashMap<String, String>> places = new ArrayList<>();
            PlaceJSONParser placeJsonParser = new PlaceJSONParser();

            try{
                jObject = new JSONObject(jsonData[0]);

                /** Getting the parsed data as a List construct */
                places = placeJsonParser.parse(jObject);

            }catch(Exception e){
                Log.d("Exception",e.toString());
            }
            return places;
        }

        // Executed after the complete execution of doInBackground() method
        @Override
        protected void onPostExecute(List<HashMap<String,String>> list){

            // Clears all the existing markers
            mMap.clear();

            for(int i=0;i < list.size();i++){

                // Creating a marker
                MarkerOptions markerOptions = new MarkerOptions();

                // Getting a place from the places list
                HashMap<String, String> hmPlace = list.get(i);

                // Getting latitude of the place
                double lat = Double.parseDouble(hmPlace.get("lat"));

                // Getting longitude of the place
                double lng = Double.parseDouble(hmPlace.get("lng"));

                // Getting name
                String name = hmPlace.get("place_name");

                // Getting vicinity
                String vicinity = hmPlace.get("vicinity");

                if(name.contains("axis")){

                }

                LatLng latLng = new LatLng(lat, lng);

                // Setting the position for the marker
                markerOptions.position(latLng);

                // Setting the title for the marker.
                //This will be displayed on taping the marker
                markerOptions.title(name + " : " + vicinity);

                // Placing a marker on the touched position
                Marker m = mMap.addMarker(markerOptions);

            }
        }
    }

    public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
    public boolean checkLocationPermission() {
        if(ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED){

            if(ActivityCompat.shouldShowRequestPermissionRationale(this,
                    Manifest.permission.ACCESS_FINE_LOCATION)){

                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                        MY_PERMISSIONS_REQUEST_LOCATION);
            }else {
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                        MY_PERMISSIONS_REQUEST_LOCATION);
            }
            return false;
        }else{
            return true;
        }

    }

    @Override
    public void onConnected(Bundle bundle) {

        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(1000);
        mLocationRequest.setFastestInterval(1000);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);

        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_FINE_LOCATION)==PackageManager.PERMISSION_GRANTED){
            LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest,this);
        }

    }

    @Override
    public void onConnectionSuspended(int i) {

    }

    @Override
    public void onLocationChanged(Location location) {
        mLatitude = location.getLatitude();
        mLongitude = location.getLongitude();
        LatLng latLng = new LatLng(mLatitude, mLongitude);

        mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
        mMap.animateCamera(CameraUpdateFactory.zoomTo(12));

    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
            if (ContextCompat.checkSelfPermission(this,
                    Manifest.permission.ACCESS_FINE_LOCATION)
                    ==PackageManager.PERMISSION_GRANTED){
                buildGoogleApiClient();
                mMap.setMyLocationEnabled(true);

            }
        }
        else {
            buildGoogleApiClient();
            mMap.setMyLocationEnabled(true);
        }

    }

    protected synchronized void buildGoogleApiClient() {
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
        mGoogleApiClient.connect();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String permissions[], int[] grantResult){
        switch (requestCode){
            case MY_PERMISSIONS_REQUEST_LOCATION: {

                if(grantResult.length > 0
                        && grantResult[0] == PackageManager.PERMISSION_GRANTED){
                    if(ContextCompat.checkSelfPermission(this,
                            Manifest.permission.ACCESS_FINE_LOCATION)
                            == PackageManager.PERMISSION_GRANTED) {
                        if(mGoogleApiClient == null){
                            buildGoogleApiClient();
                        }
                        mMap.setMyLocationEnabled(true);
                    }

                }else {
                    Toast.makeText(this, "permisison denied", Toast.LENGTH_LONG).show();
                }
                return;
            }

        }
    }
}

A: I think you should be able to this by comparing the name of the place returned with the text you want (in this case axis). By that I mean, when you execute the above query, you are returned the name of the places; (here it would be name of all the banks ATMs). What you could do is to check if the returned names contains the word axis. The code below could be a good start point.
protected void onPostExecute(List<HashMap<String, String>> list) {
        if (list.size()>0){
            for (int i = 0; i < list.size(); i++) {
                HashMap<String, String> hmPlace = list.get(i);
                final String name = hmPlace.get("place_name");
                String vicinity = hmPlace.get("vicinity");
                if (name.contains("axis")){
                   //do some awesome stuff here
                   LatLng latLng = new LatLng(lat, lng);

                   // Setting the position for the marker
                   markerOptions.position(latLng);

                  // Setting the title for the marker.
                 //This will be displayed on taping the marker
                 markerOptions.title(name + " : " + vicinity);

                // Placing a marker on the touched position
                Marker m = mMap.addMarker(markerOptions);
                }
            }
        }
    }// onPostExecute
}// end of the parserTask class

A: This is working absolutely fine for me:
sb.append("&name="+"\"axis+bank+atm\"");


text:
Q: What type of dumb terminal? Question:
What type of dumb terminal should I get for a 100 user environment?  Or is a dumb terminal not cut out for the following requirements?
User software requirements:

*

*Internet access

*Microsoft Office

*Microsoft SharePoint

*Microsoft Dynamics

*Adobe Photoshop

*Visual Studio

I.T. requirements

*

*Central management of all users

*Central management of all software installations and updates

General requirements

*

*Users should be able to continue to work if they lose internet connection to the servers or if the servers go down for whatever reason.  In some form of offline mode, where their work gets sync'ed back to the servers as soon as connectivity is returned.

*Users should be able to be portable, i.e. they should be able to work from home, or from there car, or on a beech, or in the office at their desk, or even at someone else's desk.

*I understand that thin clients, disk-less clients exist, but I am not sure which type of dumb terminal will allow the above.  Or even, if the above is possible at all using dumb terminals.

*A smooth desktop like user experience.
Current environment:
We currently have full desktop's to RDS into a full desktop sessions generated on a server.  It seems all that desktop power is being wasted by simply getting the desktops to connect to an RDS session.  When running the same apps on the desktop, the user experience is a lot more pleasurable than the user experience of the same applications over RDS.

A: What you want cannot be done with dumb terminals because a dumb terminal is something that is meant to be in a fixed location and requires a network connection all the time to work.
That basically means you will need a Rich client.
Given you mention portability, a laptop is most likely going to be your best bet.
A laptop can be carried everywhere and files can be accessible through various means, such as dropbox or a VPN connection. In addition, network shares can be configured to work offline in the case that when the connection is dropped, the files remain available and is synced back when the connection is restored, but this is not the best option. In my opinion dropbox or similar services will work best for this reason, but if centralized rights is a requirements, then network shares with offline files is the way to go, optionally using VPN.
A desktop can also be used, but its not that mobile. That said, you can use both laptops and desktops at the same time. Users can have a roaming profile and be able to work on any desktop, or have their own laptop if they also need to be outside with it.

A: The biggest problem with your requirements is the requirement of being able to work with intermittent Internet.  That alone means that you have to use a full PC for each user.  The fact that all users must have simultaneously available Office, SharePoint, Dynamics, Photoshop, and Visual Studio means that you can't use cheap PCs.
If you allow the constant Internet connection requirement, then Remote Desktop Services (formerly called Terminal Services) becomes a good option.
If your requirements weren't application-based, that is, if some workers can do some work entirely within browsers, then they can use ChromeBooks or very locked-down generic Windows PCs.  Some call centers work this way.


text:
Q: Database design for an exam I am designing database for an exam, and I am stuck. I do not know how to do it.
Here is the relevant information:

*
*Student answers 10 questions.

*Each question has 3 options (answers) and student chooses one.

*Only one answer is correct, other 2 are wrong.

* Students can take this exam only once. They can not try again.

*There will be no other exams, this is the only one.

I need help with database design.
What I have tried so far on my own:
Table Students
ID bigint (primary key, identity)
Name nvarchar(MAX)

Table Questions
ID bigint (primary key, identity)
TextOfTheQuestion nvarchar(MAX)

Table Answers
ID bigint (primary key, identity)
TextOfTheAnswer nvarchar(MAX)
QuestionID bigint (foreign key to Questions.ID)
isCorrectAnswer bit

Table StudentChoices
StudentID bigint (primary key, foreign key to Students.ID)
AnswerID bigint (primary key, foreign key to Answers.ID)

This is my personal design for learning purposes. I am trying to learn Entity framework + C# on my own.

A: Easy on the bigint and nvarchar(MAX)
Table Student:

ID int (primary key, identity)
Name nvarchar(800)

Table Question:

ID smallint (primary key, identity)
TextOfTheQuestion nvarchar(800)
CorrectAns tinyint FK (to AnswerNum.Num)
tested and can make a composite FK to Answer  QuestionID, AnsNum
I was not sure could do this but it would mean you have to create the question
Then populate Answer
Then come back and edit question for CorrectAns so may not be the way you want to go

Table Answer:

QuestionID smalling PK FK (to Question.ID)
AnswerNum tinyint   PK FK (to AnswerNum.Num)
TextOfTheAnswer nvarchar(800)

Table StudentChoice:

StudentID int       (primary key, foreign key to Student.ID)
QuestionID smallint (primary key)
AnswerNum tinyint
(QuestionID, AnswerNum) REFERENCES Answer (QuestionID, AnswerNum)

Table AnswerNum:

Num tinyint PK
-- just values 1, 2, 3
-- this way you can change number of questions in the future

This is how you score
When the primary query comes out clean it is sign of a good db design
  select Student.Name, count(*) as score
  from student
  left join StudentChoice
         on Student.ID = StudentChoice.StudentID
  left join Question
         on Question.QuestionID = StudentChoice.QuestionID
        and Question.CorrectAns = StudentChoice.AnswerNum
            -- CorrectAns in Question makes this a whole lot easier
  group by Student.Name

A: I think you've pretty much nailed it on your initial schema.
However, since we're dealing with an MCQ scenario, you don't require an "Answers" table - the answer can be included in the question (along with the two incorrect answers - see below). This will greatly simplify matters.
Another smaller change that I would recommend is having a Question_ID field as the PRIMARY KEY in the Question table.
I've prepared a schema below - it's MySQL I'm afraid, I don't use Microsoft SQL Server very often and don't have an instance to hand. It shouldn't be too hard to "translate".
A few comments.
Instead of using just "ID" as a field name in every table, I recommend that you use "Table_Name_ID" - it makes your SQL clearer and also helps with debugging - if you receive a message saying something like "... error with ID on insert..." - you don't know to which table's ID is the message referring, whereas if you name them explicitly, the error message becomes meaningful.
CREATE TABLE Student (Student_ID int, Name VARCHAR(25));
CREATE TABLE Question (Question_ID int, Name VARCHAR(25), Question_Text
                       VARCHAR(64000), Answer1 VARCHAR(4096),
                       Answer2 VARCHAR(4096), Answer3 VARCHAR(4096),
                       Correct_Answer TINYINT);
CREATE TABLE Student_Response (Student_ID int, Question_ID int,
                               Student_Answer TINYINT);

If you have the questions formulated such that they are marked 'A', 'B' or 'C', you will need to modify TINYINT to CHAR(1).
You'll notice that I use relatively long and (hopefully) easy to understand names for my FOREIGN KEYs &c. There are two reasons for this:

*

*Programmers don't have to go digging through documentation to find out what an entity is - it is self-explanatory,

*Absolutely essential for debugging - which is where the vast majority of applications spend most of their time. Getting a message that "... constraint SYS00003433 has been violated..." isn't exactly helpful. Oracle is great for giving unnamed constraints its own "special" system generated names.
You'll also notice that I use singular table names. I recommend that you do the same - that way you never have to think about "Hmmm... is it student or students?" Either way, pick a standard and stick to it.
If you Google "database design best practices", you'll get any number of sites - take the time and trouble to read a few of them and see what the consensus is - if lots of people think it's a good idea, it probably is!
ALTER TABLE Student_Response
  ADD CONSTRAINT fk_sr_student FOREIGN KEY (Student_ID)
    REFERENCES Student (Student_ID);
ALTER TABLE Student_Response
  ADD CONSTRAINT fk_sr_question FOREIGN KEY (Question_ID)
    REFERENCES Question (Question_ID);

This unique constraint is to eliminate the possibility of two answers to the same question.
ALTER TABLE Student_Response
  ADD CONSTRAINT uq_sr_student_question
    UNIQUE (Student_ID, Question_ID);

Even though you specifically rule it out, it should be relatively easy to add an exam (same exam, different times) table or possibly an "attempt" table for that and then have an exam table for different exams - i.e. databases101, databases201.
Maybe you should consider a date or even a datetime field associated with attempt - take the same exam in the morning and afternoon?
At the end of the day, one could design till the cows come home. Avoid compulsive designing disorder - by that I mean choose (in advance) a point at which you'll be satisfied with the functionality of your system and stop there. I know how easy it is to fall into the trap of continually adding "bits and bobs" and getting no real work done.

A: "Designing database" exam task solution most probably should show how a student can express domain business rules by means of DB data integrity tools (PK,FK).
Your solution covers most of them. Missing rules are:
(1) Only one Answer is solution to a Question. Bit flag doesn't help without triggers or extra app code.
(2) A Student can choose only one Answer to a Question.
Table Students:

ID int (primary key, identity)
Name nvarchar(200)

Table Questions:

ID int (primary key, identity)
TextOfTheQuestion nvarchar(4000)
SolutionID int
foreign key (SolutionID) to Answers(ID)

I added SolutionID, this way Answer has exactly one solution.
Table Answers:

ID int (primary key, identity)
QuestionID int (foreign key to Questions.ID)
TextOfTheAnswer nvarchar(4000)

To meet (2) StudentChoices' PK must be (StudentID,QuestionID) which means Student answered the Question and his Answer was ... .
Table StudentChoices:

StudentID int (primary key, foreign key to Students.ID)
QuestionID int (primary key)
AnswerID int

Now a problem arises, AnswerID and QuestionID must not contradict each other, i.e. AnswerID must belong to Question referenced by QuestionID. We can achieve it by declaring FK at StudentChoices:
foreign key (QuestionID, AnswerID) to Answers(QuestionsID, ID)

To be able to target Answers(QuestionsID, ID) in the above FK, this pair of attributes must be declared Unique at Answers:
unique (QuestionID,ID) -- target of FK from Questions, StudentChoices

It's absolutly save to declare such Unique because every superset of PK is unique. Using the same unique we also ensure that SolutionID belongs to the Answer to exactly this Question by replacing FK at Questions with
foreign key (ID,SolutionID) to Answers(QuestionsID, ID)

A: As I review the structure you have now I would change the identity columns from BigInt to Int. I suggest you review how many Students, Questions, Answers and Choices you expect and select data types with appropriate sized ranges.
I would also replace nvarchar(max) with a more reasonable sized field. As there are limitations with functions on nvarchar(max). I'd only use it as a last resort.
As for the table structure itself I would makes changes to the Student choices table.

*

*I would add an Identity column as a primary key to uniquely identify
a single row. This makes life easier for applications.

*I would add a Question Id column. So that you can see Student A, for
Question B selected Answer C.

*Optional: If you added a unique index on Student ID & Question id, Students could only select 1 answer per question.
Other things to think about: Will this database be used for many different exams? (consider exam id) Or could a student sit the same exam twice? How would you handle that?

A: As others mentioned you should use reasonable datatypes, e.g. no BIGINT for students/question (there will never be more than 2 billion students), probably no NVARCHAR(MAX) for questions/answers. You should also add NOT NULL constraints when possible.
A clean logical data model would result in this:
Table Student
StudentID int (primary key, system assigned?)
-- of course there will be an official registration number
-- issued by the univerity which is probably not based on a sequence
Name nvarchar(200) not null
-- of course there will be lots of other columns like last_name/first_name/birthdate/...

Table Question
QuestionID smallint (primary key, system assigned?)
TextOfTheQuestion nvarchar(4000) not null

CorrectAnswer tinyint not null check (CorrectAnswer between 1 and 3)
-- for a 100% clean model you might:
-- drop the check, remove the NOT NULL
-- and do a foreign key to Answers(QuestionID, AnswerID) instead
-- But then you got a circular reference and this is hard to load

Table Answer
QuestionID int (foreign key to Questions(QuestionID))
AnswerID tinyint check (AnswerID between 1 and 3)
TextOfTheAnswer not null nvarchar(4000)
Primary key (QuestionID, AnswerID)

Table StudentChoice
StudentID int (foreign key to Students.StudentID)
QuestionID smallint (foreign key to Answers.AnswerID)
AnswerID tinyint -- NULLable as student might not have answered question (yet)?
Primary key (StudentID, QuestionID)

Then a query to get the (correct) answered questions will look like this:
select s.Name,
   count(sc.AnswerID) as AnsweredQuestions
   count(q.AnswerID) as CorrectAnswers
from student as s
left join StudentChoice as sc
       on s.StudentID = sc.StudentID
left join Question as q
       on q.QuestionID = sc.QuestionID
      and q.CorrectAns = sc.AnswerId
group by Student.Name

Of course this might get more and more complicated, e.g. regarding the actual questions (in ascending order of complexity):

*

*Are there exactly 10 questions?

*Or are there multiple sets of 10 questions?

*Or are 10 questions randomly chosen from a larger set of questions?

A: Rather than address the specific data model aspect of the question (there are already five answers that do a good job of that), I will address the stated goal of this question (after all, context is important).

This is my personal design for learning purposes. I am trying to learn Entity framework + C# on my own.

Now, I do understand that there could very well be other factors and details that have not been shared that make pursuing this specific data model the most appropriate course of action. However, I only know what has been shared (the statement above), so with that in mind:
IF you are doing this model just to learn Entity Framework (EF), C#, and possibly MVC / ASP.NET / etc, then you might be better served by considering one of the following approaches:

*

*Given that you have already asked several data modeling questions, using the actual data model that those questions pertain to might make it easier to focus on learning the .NET stuff. The data model in this particular question is a contrived situation and so it hasn't been tested with real data and real users; it lacks certain complexities that rise to the surface as a system starts getting used. So you could spend quite a bit of time re-thinking various aspects of this model after its initial conception when you should instead be focusing on how to use Entity Framework to interact with the real-world business rules that you are hopefully already familiar / comfortable with.

*If you really do need / want a system to manage students taking an exam, there is no need to reinvent the wheel when many such systems already exist and can be studied. There is an entire class of software called Learning Management Systems (LMSs) and at least one of them is Open Source and is pretty popular, so they have already gone through the initial growing pains of finding little things that didn't work. And you certainly don't need the full data model as it handles much more than you need to learn EF, so just take the parts that you need to start building a .NET app around it.
The system I am thinking of is called Moodle and can be found on GitHub at:
https://github.com/moodle/moodle/blob/master/lib/db/install.xml
That link goes directly to their data model. It is actually a description of the data model that they then render into one of 6 or so different RDBMS's dialects. But it is easy enough to read that you can easily see the tables, indexes, relationships, etc. You can even install Moodle so that it creates the SQL Server version of that model. Their code is all PHP so you might need to download that separately, but they do have a binary for Windows (be sure to read the "Which version do I choose?" section on the left).
Again, I understand that you might have one or more reasons for needing to stick with the data model that you are asking about in this Question. So, these are just points to consider maybe for the future if not now, or perhaps for others searching on "exam / testing data models" that might be unaware of Open Source options such as Moodle.
BUT, regardless of which specific path you choose, you will definitely need to also learn more about performance tuning, the pros and cons of the various data types, etc since you are using an ORM (i.e. Entity Framework). Be sure to look up "plan cache bloat", and keep in mind that EF does indeed have the option, for each object and action, to call a Stored Procedure instead of dynamically generating the SQL :-).


text:
Q: Connecting to Oracle using UCP and DataDirect driver I am trying to connect to a Oracle database using UCP with DataDirect JDBC driver for oracle.
What is the URL tha tI need to use. I am currently using the following.
<property name="URL" value="jdbc:datadirect:oracle:TNSNamesFile=C:\\Oracle\\11.2.0\\client_1_X64\\network\\admin\\tnsnames.ora;TNSServerName=TESTA"/>

I get the error
Caused by: java.sql.SQLException: [DataDirect][Oracle JDBC Driver]A host name must be specified if a port number is specified.
Why do I get this error?
Is it possible to use UCP with DataDirect JDBC driver?

A: It appears your URL is correct, here is the sample URL from the documentation:
jdbc:datadirect:oracle:TNSNamesFile=c:\\oracle\\NETWORK\\ADMIN\\tnsnames.ora;
    TNSServerName=FITZGERALD.SALES

You can go here for more information on connecting to Oracle database using UCP with DataDirect JDBC :
http://media.datadirect.com/download/docs/jdbc/alljdbc/userguide/jdbcoracle.11.08.html#974893
One thing you might try is using a hostname and port number, here's a sample URL:
jdbc:datadirect:oracle://server3:1521;ServiceName=ORCL;User=test;
Password=secret


text:
Q: How to logoff from a SharePoint 2010 site using a c# client? I found this Remote Authentication in SharePoint Client Object Model which has examples to popup a IE window in order to get all the cookies for remote SharePoint access.  Ideally, the program popups a window to the site, asks the user to login, and then disappears.  The program then can insert items into the SharePoint site.
Problem Description
I observed that this example application pops up a window but redirected to our company's example SharePoint site, instead of my site, and it didn't ask me to log in.  Then if I close this window manually the clientContext (from ClaimClientContext.GetAuthenticatedContext(siteUrl)) in the example code will be null pointer.  To fix this, I first manually open an IE window, go to my site, I will be automatically logged in (which I think that's the problem since the example application wasn't able to get a cookie because there was no logging in), then if I manually log off from the IE window, run the example application, it will pop up a window, seems it automatically log in and then the window disappeared and the items can be added to the list.
My Question
Is there a way to programmatically log off the SharePoint site from the application at first?

A: Problem is in authorization cookie. You must delete FedAuth cookie to "logout".


text:
Q: ChDir (Environ("USERPROFILE") & "\Desktop") Run-time error '76' I'm getting Run-time error '76': Path not found in VBA. This used to work for me and the only thing that I changed recently was adding my folders to Onedrive (which I feel it could be the cause).
ChDir (Environ("USERPROFILE") & "\Desktop")
When I use the Immediate window I can print the path without issue there, however I'm getting my company domain as shown below. I don't understand why is not processed by the macro.
Could someone help guide me the way out of this?
print(Environ("USERPROFILE") & "\Desktop")
C:\Users\myname.DOMAIN\Desktop

A: I cannot duplicate the problem on my machine, but you can try this workaround which strips out anything after the [first] period...
Dim sProfile As String
Dim vSplit As Variant
sProfile = Environ("USERPROFILE")
vSplit = Split(sProfile, ".")
sProfile = vSplit(0)

MsgBox sProfile & "\Desktop"


text:
Q: Send email using Cloud Functions and Nodemailer How can I send an email to a person using Cloud Functions and Nodemailer?
On my app there's a contact screen where users can ask questions and send feedback to the app, and when the user presses a button, the Cloud Function gets triggered. However, I don't seem to recieve any emails whatsoever, I even checked the "Spam" folder.
What am I doing wrong?
My code for the Cloud Function looks like this:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const nodemailer = require('nodemailer');

admin.initializeApp(functions.config().firebase);

const transporter = nodemailer.createTransport({
  service: 'gmail',
  auth: {
    user: 'exampleemail@gmail.com',
    pass: 'exampleemailpassword'
  }
});

exports.sendEmail = functions.https.onRequest((request, response) => {
  const { sender, phone, message } = request.query;

  const mailOptions = {
    from: sender.toLowerCase(),
    to: 'exampleemail@gmail.com',
    subject: 'New feedback email',
    text: `${message} Phone: ${phone}`
  };

  // eslint-disable-next-line consistent-return
  transporter.sendMail(mailOptions, (err, info) => {
    if (err) {
      response.send(err.toString());
    }
    response.send('Email sent');
  });
});

A: I see what you are doing wrong, you can't use gmail's SMTP transport service in server environments other than your own computer

Gmail has a limit of 500 recipients a day (a message with one To and
one Cc address counts as two messages since it has two recipients) for
@gmail.com addresses and 2000 for Google Apps customers, larger SMTP
providers usually offer about 200-300 recipients a day for free.

So I would recommend you to use a service like EmailJS to send emails

A: I was doing it wrong, I had to return a code to the HttpRequest in order to run the function property. Then, it works
exports.sendEmail = functions.https.onRequest((request, response) => {
  cors(request, response, () => {
    const { sender, phone, message } = request.query;

    const mailOptions = {
      from: sender.toLowerCase(),
      to: 'exampleemail@gmail.com',
      subject: 'New feedback email',
      text: `${message} \nEmail: ${sender.toLowerCase()}\nPhone: ${phone}`
    };

    return transporter.sendMail(mailOptions, (error, info) => {
      if (error) {
        return response.status(500).send({
          data: {
            status: 500,
            message: error.toString()
          }
        });
      }

      return response.status(200).send({
        data: {
          status: 200,
          message: 'sent'
        }
      });
    });
  });
});