Q: how to disable addressbar without using windows.open in javascript or jquery or other way Hi I want to disable address bar as I don't want that user can edit anything in to the URL or modify the url.
So basically I'm emailing link to them and by clicking they can complete require task and that'why I want to stop them to make any changes.
thanks

A: The scenario you are describing (give someone a link to do something, and only that thing) is typically solved with server-side validation rather than just hiding the URL. Often, you want to make use of a "nonce", that is a one-time secret value for each allowed action that users could not guess.
So for example http://www.example.com/validate-email/?nonce=d389mxfh47c
A user could not simply change the nonce to get a desired effect. The server can look up what the correct, authorized action is for that nonce when the user accesses/submits the page.


Q: smooth scrolling of imageview I have added the images to scrollview dynamically. Following is the code:
-(void)displayimages {
    for (int i=0; i<[featuredarray count]; i++) {
        NSString *image=[[featuredarray objectAtIndex:i]objectForKey:@"img"];

        if (i==0) {
            webview=[[UIImageView alloc]initWithFrame:CGRectMake(i*290+15, 0, 270, 380)];
        }
        else {
            webview=[[UIImageView alloc]initWithFrame:CGRectMake(i*290+15, 0, 270, 380)];
        }
        webview.backgroundColor=[UIColor clearColor];
        webview.layer.borderWidth=4;
        webview.layer.cornerRadius=4;
        webview.layer.borderColor=[[UIColor whiteColor]CGColor];
        [webview setTag:i];
        webview.userInteractionEnabled=YES;
        NSURL *url = [NSURL URLWithString:image];
        [webview setImageWithURL:url placeholderImage:[UIImage
           imageNamed:@"placeholder.png"]];
        [scroll addSubview:webview];

        UITapGestureRecognizer *tap1 =
        [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handlefirstTap:)];
        tap1.delegate=self;
        tap1.numberOfTapsRequired=1;
        [webview addGestureRecognizer:tap1];
        [tap1 release];
        [webview release];
   }

   pages.defersCurrentPageDisplay=YES;
   scroll.delegate =self;

   scroll.contentSize = CGSizeMake(290*[featuredarray count],300);
   scroll.pagingEnabled = YES;
   pages.numberOfPages = [featuredarray count]-1;
   pages.currentPage =0;
}

-(void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView{
    int gallerypage = scrollView.contentOffset.x /scrollView.frame.size.width;
    CGRect frame = scroll.frame;
    frame.origin.x = frame.size.width-15*gallerypage;
    NSLog(@"frame.origin.x..%f",frame.origin.x);
    frame.origin.y =0;
    [scroll scrollRectToVisible:frame animated:YES];
}

-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    int gallerypage = scrollView.contentOffset.x /scrollView.frame.size.width;
    CGRect frame = scroll.frame;
    frame.origin.x=gallerypage*290;
    frame.origin.y =0;
    [scroll scrollRectToVisible:frame animated:YES];
}

It is showing the images well when I use pagecontroller action
-(IBAction)pagecontrolaction:(id)sender {
    int page = pages.currentPage;
    CGRect frame = scroll.frame;
    frame.origin.x=page*290;
    frame.origin.y =0;
    [scroll scrollRectToVisible:frame animated:YES];
}

but when I used touch event to imageview then it is not displaying the images smoothly. It gets stuck during scrolling.

These are the preview which shows the current image with the start of second image.

A: The two methods: scrollViewWillBeginDecelerating and scrollViewDidEndDecelerating contains two animation with different x position it is animated to:
frame.origin.x = frame.size.width-15*gallerypage;

and
frame.origin.x=gallerypage*290;

It is better if you could turn off either function: scrollViewWillBeginDecelerating or scrollViewDidEndDecelerating. Otherwise probably you should adjust the x position (must be in sync for both functions) it will be animated to.

A: if (i==0) {
            webview=[[UIImageView alloc]initWithFrame:CGRectMake(i*320, 0, 270, 440)];
        }
        else {
            webview=[[UIImageView alloc]initWithFrame:CGRectMake(i*320, 0, 270, 380)];
        }

A: You need to change your implementation for loading the images from a remote resource, thats where the biggest bottle neck lies.
I don't want to go into details but try to replace this line of code
[webview setImageWithURL:url placeholderImage:[UIImage imageNamed:@"placeholder.png"]];

With something more c.p.u friendly. Use a caching mechanism that employs multi-threading, what you want to do is move the heavy lifting (Downloading remote images) to another thread.
SDWebImage does a perfect job at this  https://github.com/rs/SDWebImage
If you are a bit hard core, you can roll your own multi-threaded image downloader using
[NSURLConnection sendAsynchronousRequest:queue: completionHandler:]

And do the image loading in the block, Or even better dispatch_async(queu, block)

A: You should checkout SYPaginator (SYPaginator is a horizontal TableView with lazy loading and view recycling.)

Simple paging scroll view to make complicated tasks easier. We use
  this in several of the Synthetic apps including Hipstamatic, D-Series,
  and IncrediBooth.

If you need more perfomance you should give MSCachedAsyncViewDrawing a try:

Helper class that allows you to draw views (a)synchronously to a
  UIImage with caching for great performance.

A: I think that happens because your images are larger in size (MB) , and you fit them into that CGRect without resizing them that specific size, also it matters how many pictures you have loaded inside the scrollview , if you load many pictures it will take a lot of memory and it will slide slowly.

A: It happens when you are trying to show an image of larger size in that case you have to use cache to get the image there and try to load image from there.For better know how to use it..use SDwebimage thats the nice way to do it and it is fast.
You can read

*

*Lazy Loading
2.paging enabled.
https://github.com/rs/SDWebImage
Need any further help.Happy to help you.

A: I am not sure why are you setting the frame when you start scrolling, but if I were in your place I would do the logic as per below:
-(void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView{
    // do nothing
}

-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {

    int gallerypage = scrollView.contentOffset.x /scrollView.frame.size.width;
    CGFloat xoffset = 290 * gallerypage;
    [UIView animateWithDuration:0.5
                     animations:^{
                         scrollView.contentOffset = CGPointMake(xoffset, 0);
                     }
                     completion:^(BOOL finished){
                         NSLog(@"Done!");
                     }];
}

Hope it helps.

A: You should definitely resize your image in background prior to loading it into UIImageView. Also you should set UIImageView content mode to the none-resizing one. It gave me significantly scrolling improvement after other ways were already implemented (async cache and others).


Q: Runtime Error 1004 / Error 438 when getting the Text property of a copied button, setting the property works though I've inserted a large number of form controll buttons (with the text "") into an excel worksheet by copy'n'pasting (from another workbook).

These buttons are connected to this macro (which is located in PERSONAL.XLSB):
Option Explicit

Sub ChangeSomething()
    ' The button which called the macro.
    Dim b As Button
    Set b = ActiveSheet.Buttons(Application.Caller)

    ' Do run the code if the button was not already active.
    If b.Text <> "x" Then        ' SEEMS TO BE THE PROBLEM
        ' Do something

        ' Mark the button as activated.
        b.Text = "x"
        b.Font.Bold = True

    ' If the button was already activated, deactivate it.
    Else
        'Mark the button as deactivated.
        b.Text = " "
    End If
End Sub

This set up worked properly before. But since copying, I get Runtime Error 1004 "Unable to set the Text property of the Button class".
When handled, the exception seems to be Error 438 "Object Doesn't Support This Property or Method".

The Debugging marks the line:
If b.Text <> "x" Then

What puzzles me is that getting the text property seems to throw the runtime error, but setting the value runs just fine:
b.Text = "x"

The correct Button in the correct Worksheet of the correct Workbook is changed.

As soon as I change the text of the button manually to something other than "", the macro also seems to work.
Unfortunately, the inserted buttons do not appear to be included in the list returned by ActiveSheet.Buttons, so I can not loop over them to change their values.

I'm not sure if that's appropriate, but I've uploaded here a sample file.

A: I'm not sure your question has the right details. If these buttons are indeed Form Controls - and I think they must be because I believe ActiveX controls don't return a Caller - then their parent object is Shapes, and you would call the Text property from the Shape.TextFrame.Characters object.
I wonder if your original worksheet had aCollection object called Buttons
which contained, perhaps, a list of the buttons in the form of a class object, called Button (hence your error message) and which exposes the properties that are called in your code.
Without that collection and class, the code would be more like this:
Public Sub ChangeSomething()
    Dim btn As Shape

    With Application
        'Check for correct data types.
        If Not TypeOf .ActiveSheet Is Worksheet Then Exit Sub
        If IsObject(.Caller) Then Exit Sub

        'Acquire button
        On Error Resume Next
        Set btn = .ActiveSheet.Shapes(.Caller)
        On Error GoTo 0

        'Check for a found button
        If btn Is Nothing Then Exit Sub
    End With

    'Check for non-actionable button.
    With btn.TextFrame.Characters
        If .Count = 0 Then
            .Text = "x"
            Exit Sub
        End If
    End With

    'If we've reached here, it's an actionable button.
    Debug.Print "Do something."

    'Clear the button text.
    btn.TextFrame.Characters.Text = ""

End Sub

I rather suspect some half-copied code here, and the rest of the project remains elsewhere.


Q: iOS swift pointer CGPoint startPoint1;
CGPoint startPoint2;
CGPoint startPoint3;
CGPoint startPoint4;

- (void)Method {
    CGPoint* startPoint = NULL;

    if (panGesture.view == ...) {
       startPoint = &startPoint1;
    } else if (panGesture.view == ...) {
       startPoint = &startPoint2;
    }

    if (panGesture.state == UIGestureRecognizerStateBegan) {
       *startPoint = [panGesture locationInView:...]
    } else if (panGesture.state == UIGestureRecognizerStateChanged) {
       CGPoint endPoint = [panGesture locationInView:...];
       *startPoint = endPoint;
    }
}

CGPoint* startPoint = NULL;
startPoint = &startPoint1;
*startPoint = endPoint;

This three lines of code in Swift 3.0 is how to express Or how do I write the above code into swift

A: The problem is that Swift doesn't have pointers in the C sense. Well, it does, sort of, but it's not worth invoking them just to do what you're trying to do. The simplest approach is to rewrite the core of your method to call a function that takes an inout parameter.
So let's take the reduction you ask about in your last three lines:
CGPoint* startPoint = NULL;
startPoint = &startPoint1;
*startPoint = endPoint;

To do that, we need a general way to set one CGPoint to another by indirection, expressed as a func (because that is the only way to work with an inout parameter). To make it truly general, we may as well make this a generic, so we're not confined to CGPoint alone:
func setByIndirection<T>(_ thing1 : inout T, to thing2: T) {
    thing1 = thing2
}

And now we can test it, doing exactly what you asked to do:
var startPoint = CGPoint.zero
let endPoint = CGPoint(x:5, y:5)
setByIndirection(&startPoint, to: endPoint)
print(startPoint) // 5,5

So you see, the use of the inout parameter has allowed us to pass into the function a "pointer" to the CGPoint whose value is to be set, which is what your code is trying to accomplish at its heart.
If you're willing to "damage" your original endPoint, you don't even need to write setByIndirection; you can use the built-in swap:
var startPoint = CGPoint.zero
var endPoint = CGPoint(x:5, y:5)
swap(&startPoint, &endPoint)

A: In swift, I would use enums and an array. I simplified the code a litte, but I guess you'll get it:
var points = [CGPoint(), CGPoint()]
enum indexEnum:Int {
    case startPoint = 0
    case endPoint   = 1
}

func method() {
    var inx:indexEnum

    if (1==1) {
        inx = .startPoint
    } else {
        inx = .endPoint
    }

    if (2==2) {
        points[inx.rawValue] = CGPoint(x:10,y:10)
    } else {
        points[inx.rawValue] = CGPoint(x:20,y:20)
    }
}


Q: Laravel 4 NotFoundHttpException [2014-04-28 12:34:46] production.ERROR: exception 'Symfony\Component\HttpKernel\Exception\NotFoundHttpException' in C:\wamp\www\ppdb\vendor\laravel\framework\src\Illuminate\Routing\RouteCollection.php:140
Stack trace:

#0 C:\wamp\www\ppdb\vendor\laravel\framework\src\Illuminate\Routing\Router.php(1021): Illuminate\Routing\RouteCollection->match(Object(Illuminate\Http\Request))
#1 C:\wamp\www\ppdb\vendor\laravel\framework\src\Illuminate\Routing\Router.php(989): Illuminate\Routing\Router->findRoute(Object(Illuminate\Http\Request))
#2 C:\wamp\www\ppdb\vendor\laravel\framework\src\Illuminate\Routing\Router.php(968): Illuminate\Routing\Router->dispatchToRoute(Object(Illuminate\Http\Request))
#3 C:\wamp\www\ppdb\vendor\laravel\framework\src\Illuminate\Foundation\Application.php(738): Illuminate\Routing\Router->dispatch(Object(Illuminate\Http\Request))
#4 C:\wamp\www\ppdb\vendor\laravel\framework\src\Illuminate\Foundation\Application.php(708): Illuminate\Foundation\Application->dispatch(Object(Illuminate\Http\Request))
#5 C:\wamp\www\ppdb\vendor\laravel\framework\src\Illuminate\Http\FrameGuard.php(38): Illuminate\Foundation\Application->handle(Object(Illuminate\Http\Request), 1, true)
#6 C:\wamp\www\ppdb\vendor\laravel\framework\src\Illuminate\Session\Middleware.php(72): Illuminate\Http\FrameGuard->handle(Object(Illuminate\Http\Request), 1, true)
#7 C:\wamp\www\ppdb\vendor\laravel\framework\src\Illuminate\Cookie\Queue.php(47): Illuminate\Session\Middleware->handle(Object(Illuminate\Http\Request), 1, true)
#8 C:\wamp\www\ppdb\vendor\laravel\framework\src\Illuminate\Cookie\Guard.php(51): Illuminate\Cookie\Queue->handle(Object(Illuminate\Http\Request), 1, true)
#9 C:\wamp\www\ppdb\vendor\stack\builder\src\Stack\StackedHttpKernel.php(23): Illuminate\Cookie\Guard->handle(Object(Illuminate\Http\Request), 1, true)
#10 C:\wamp\www\ppdb\vendor\laravel\framework\src\Illuminate\Foundation\Application.php(606): Stack\StackedHttpKernel->handle(Object(Illuminate\Http\Request))
#11 C:\wamp\www\ppdb\public\index.php(49): Illuminate\Foundation\Application->run()
#12 C:\wamp\www\ppdb\index.php(19): require_once('C:\wamp\www\ppd...')
#13 {main} [] []

Tried to create a form with laravel , and seems fine when i load the page , the problem is when i try to submit the form this error is getting in log file.
Can anyone please check to solve this issue?
Thanks in advance

A: I missed  to add post routing in routes.php
Route::post('search', 'SearchController@index');

Post routing did the job for me.
Cheers!


Q: Change file system of Eclipse for procedure/support of "New Web dynamic project" I want to change file system of Eclipse for change "support" or "User interface" (UI) of New Dynamic WEB Project.
I have Windows 7 but I am interested also on Linux.
Should be easy change file system in Linux and not in Windows.

*

*What do I would to change?
In Eclipse, I press NEW-> Dynamic Web Project, put the name and press Next.
We have, in default, this window:

Now I have to remove src folder and put new folders src\main\java and src\main\resource.
So I will have a folder "Source Folders" of Maven project because I will convert in it.
So the result is:

- Why not do New Maven Project so I will have these directory
   java resource.
Why I not like the pom.xml of new Maven Project that is in default:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>bla</groupId>
  <artifactId>bla</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>asd Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
  <build>
    <finalName>bla</finalName>
  </build>
</project>

Miss the plugin of maven:
<build>
      <finalName>${project.artifactId}</finalName>
        <plugins>
          <plugin>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.1</version>
            <configuration>
              <source>1.8</source>
              <target>1.8</target>
            </configuration>
          </plugin>
          <plugin>
            <artifactId>maven-war-plugin</artifactId>
            <version>2.4</version>
            <configuration>
              <warSourceDirectory>WebContent</warSourceDirectory>
              <failOnMissingWebXml>false</failOnMissingWebXml>
            </configuration>
          </plugin>
        </plugins>

      </build>

If I do, from project Dynamic WEB project and will convert to Maven Project. I will have this pom.xml that is generated from Eclipse:
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>HibernateExample</groupId>
  <artifactId>HibernateExample</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>
  <name>HibernateExample</name>
  <url>http://maven.apache.org</url>

  <build>
  <finalName>${project.artifactId}</finalName>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.1</version>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
        </configuration>
      </plugin>
      <plugin>
        <artifactId>maven-war-plugin</artifactId>
        <version>2.4</version>
        <configuration>
          <warSourceDirectory>WebContent</warSourceDirectory>
          <failOnMissingWebXml>false</failOnMissingWebXml>
        </configuration>
      </plugin>
    </plugins>

  </build>
</project>

For me like too the second pom.xml and not get error of miss plugin maven.
So today I've got an idea:

*

*Why not change the program files (say inside folder Eclipse) and change line of folder " Source
Resource"?
So I will have the new default windows (see second image) in every time when I create Dynamic WEB Project.
I hope the title is correct.


Q: Using Django REST Framework with sessions-based CSRF I am using Django + Django REST Framework in an environment where I cannot use cookie-based CSRF tokens; therefore I must run with CSRF_USE_SESSIONS = True.
The DRF web UI, however, depends on this cookie for all interactions. It appears this is set by reading the csrftoken cookie and settings the X-CSRFToken header on the subsequent request, which is then consumed by django.middleware.csrf.CsrfViewMiddleware.process_view() if the hidden field is not included in the request body. This is set in this code from rest_framework.templates.rest_framework.base.html:
<script>
  window.drf = {
    csrfHeaderName: "{{ csrf_header_name|default:'X-CSRFToken' }}",
    csrfCookieName: "{{ csrf_cookie_name|default:'csrftoken' }}"
  };
</script>

DRF forms that do not use POST do contain the CSRF token in the form body, so not having the cookie means the web interface does not have access to the CSRF token at all, causing all PUT, PATCH, and DELETE requests to fail with a 403 response.
I believe this is a bug in DRF, but it is possible this is intended behavior. Can someone explain how DRF is intended to be used with CSRF_USE_SESSIONS = True?

A: This was fixed in https://github.com/encode/django-rest-framework/pull/6207 and released as part of DRF 3.9.2. More complete context can be read at https://github.com/encode/django-rest-framework/issues/6206.


Q: Print vowels from the vector I need to execute the vowels from the LETTERS R build-in vector
"A", "E", etc.

> LETTERS

  [1] "A" "B" "C" "D" "E" "F" "G" "H" "I" "J" "K" "L" "M" "N" "O" "P" "Q" "R" "S" "T" "U"
   "V" "W" "X"
  [25] "Y" "Z"

Maybe, someone knows how to do it with if() or other functions. Thank you in advance.

A: Looks like you need extract vowels, does this work:
> vowels <- c('A','E','I','O','U')
> LETTERS[sapply(vowels, function(ch) grep(ch, LETTERS))]
[1] "A" "E" "I" "O" "U"
>


Q: Convert number into amount of space I have a number and want it to generate to a string with corresponding space
For Example:
var NumberOfSpace = 3;

// This will result in a string with 3 empty space
// the result will be "   "
var space = convertToSpace(NumberOfSpace);

A: You can simply use the String.prototype.repeat method:
" ".repeat(3);

A polyfill for older browsers.

A: Here is a convertToSpace function
var convertToSpace = function (spaces) {
  var string = "";
  for (var i = 0; i < spaces; i++) {
    string += " ";
  }
  return string;
}

A: A concise option:
function convertToSpace(n) {
  return new Array(n + 1).join(' ')
}

A: Using Array#fill and Array#reduce

The fill() method fills all the elements of an array from a start index to an end index with a static value.
The reduce() method applies a function against an accumulator and each value of the array (from left-to-right) to reduce it to a single value.

var NumberOfSpace = 3;

function convertToSpace(param) {
  return new Array(param).fill(' ').reduce(function(a, b) {
    return a + b;
  });
}
var space = convertToSpace(NumberOfSpace);
console.log(space);


Q: webkit framework iphone i am not able to add webkit framework in my application. Getting error which says no such framework is available.

A: The WebKit framework is not available on iPhone - it's only for Macs. The nearest you can get is adding a UIWebView to your app, which gives you a WebKit-based HTML window.


Q: SQLite Trigger issue - "No such column" I have a sqlite database with a table named Achievements, it stores whether certain achievements have been met in a simple quiz I am building (iphone project to learn objective-c).  The table structure is:
ID    Name           Completed
=============================
1     FiveInARow     0
2     TenInARow      0
3     AllCorrect     0
4     UnderASecond   0
5     AllCompleted   0

The ID is the primary key, Name is a VARCHAR and Completed is BOOL (0 for false and 1 for true).
I am trying to add a trigger onto the update statements of this table, such that when a Completed column is set to 1 (i.e. achievement completed - this is the only update that will happen on the table) there will be a calculation to see whether all of the other achievements have been completed and if so also update the AllCompleted achievement (ID 5) to 1.
The trigger I created is:
CREATE TRIGGER "checkAllAchievements" AFTER UPDATE ON "Achievements"
WHEN (Select SUM(Completed) from Achievements) = (Select COUNT(Completed) -1 from Achievements)
BEGIN UPDATE Achievements SET Completed = 1 WHERE Name= 'AllCompleted';
So what I am trying to do is take the sum of the completed row and compare it to the total count minus 1, if they match then it means that all achievements apart from the AllCompleted achievement are achieved so we can also set that to true.  The trigger gets created fine.
Now on to the problem - When I attempt to update the table with the following statement
UPDATE Achievements SET Completed = 1 WHERE ID = 1
I receive the error message "No such Column Completed".
Am I trying to do something that is fundamentally wrong?  Is it not possible for me to achieve this using a trigger?  Any advice?
Thanks.

A: Double check that you spelled everything exactly as it is in the database.  In your example, you state the table name is "Achievements" however reference "Achievement" in two places.
Fixing that should solve your issue.  Final SQL is as follows:
CREATE TRIGGER "checkAllAchievements"
AFTER UPDATE ON Achievements
WHEN (SELECT SUM(Completed) FROM Achievements) = (SELECT COUNT(Completed)-1 FROM Achievements)
BEGIN
  UPDATE Achievements SET Completed=1 WHERE Name='AllCompleted';
END;

A: typically this would be a mutation in the table you are updating...
the trigger should just set the value something like
new_rec.completed := 1;

not try to do another update.
(excuse my Oracle syntax)

A: I think you should not update a table from a trigger on updating of that table, could be a infinite recursion. Maybe SQLite doesn't like that, but give a bad diagnositic


Q: Google Amp Contact form error when submitting Anyone can help me work out in using the AMP Contact form?
I am doing a subscribe form using Mailchimp and SendEngine and I embedded the form to my HTML page.
Here is the screenshot of the error:

A: This happens when you try to submit to a domain different than your AMP site.
You need to whitelist your AMP domain on your server to enable CORS or contact Administrator if it's a shared hosting for your AMP domain to be whitelisted for CORS. Read further about CORS on AMP.
Also check out specs on CORS Whitelisting.


Q: How to return the id of a mui datagrid row from an onClick event I'm trying to use a material-ui datagrid that's being populated by a sql database to be able to edit what's inside of the database, I want that to be done via a form instead of simply editing the rows and cells individually.
I want to pass the id of the specific row as an argument into a function that will patch that row, using the id I can actually select the row inside of the database and then use a dialog form to update the individual data columns.
I've looked into the docs and anything that it seems to say would work just doesn't. I can't import the GridApi from @mui/x-data-grid-pro or @mui/x-data-grid-premium despite those being installed to make it work, getRowId seems to be a means of setting the row id rather than getting it, and the code snippets I've been able to find don't work either
<DataGrid
onComponentMount={getComponents()} {/*Calls on the database to get the rows and places the resulting array into the rows variable using sqlalchemy and fastapi */}
rows={rows}
columns={columns} {/* contains columns id, description, stock */}
pageSize={6}
rowsPerPageOptions={[6]}
onRowClick={()=>{selectComponents(((index) => {index.api.getRowIndex(index.rows.id)}))}}
/>

A:     onRowClick={(rows)=>{selectComponents(rows.id)}}

This is the answer. Now when I click a row, it will return the row id as an argument in my function. Now I can simply click a row and use that info to open a dataform modal that comes pre-filled out with info that can change and then either be pushed to the database or canceled without saving


Q: make table out of several files and combine into one matrix table I have these files (https://github.com/learnseq/RNAseqcollection.git) that I want to merge(combine) the second column of each into one table with reference name. I have two issues: how to enforce column conversion from factor to another type (because I'm getting error when I try) and how to join them with shorter code.
I want this out put (for example one row of the output):
    Geneid      MCL1.DG MCL1.DI  MCL1.DK MCL1.LA MCL1.LC MCL1.LE MCL1.DH MCL1.DJ MCL1.DL MCL1.LB MCL1.LD MCL1.LF
1   100008567     0        0        0      0       0       0       0        0       0      0       0      0

I tried this:
files = list.files(path=".", pattern="MCL")
file1 = read.table("MCL1-DG.txt", col.names=c("Geneid","MCL1-DG" ))
file2 = read.table("MCL1-DI.txt", col.names=c("Geneid","MCL1-DI" ))
file3 = read.table("MCL1-DK.txt", col.names=c("Geneid","MCL1-DK" ))
file4 = read.table("MCL1-LA.txt", col.names=c("Geneid","MCL1-LA"))
file5 = read.table("MCL1-LC.txt", col.names=c("Geneid","MCL1-LC"))
file6 = read.table("MCL1-LE.txt", col.names=c("Geneid","MCL1-LE"))
file7 = read.table("MCL1-DH.txt", col.names=c("Geneid","MCL1-DH"))
file8 = read.table("MCL1-DJ.txt", col.names=c("Geneid","MCL1-DJ"))
file9 = read.table("MCL1-DL.txt", col.names=c("Geneid","MCL1-DL"))
file10 = read.table("MCL1-LB.txt", col.names=c("Geneid","MCL1-LB"))
file11 = read.table("MCL1-LD.txt", col.names=c("Geneid","MCL1-LD"))
file12 = read.table("MCL1-LF.txt", col.names=c("Geneid","MCL1-LF"))

out.file = merge (file1, file2, by=c("Geneid"))
out.file2 <- merge(out.file, file3, by=c("Geneid"))
out.file3 <- merge(out.file2, file4, by=c("Geneid"))
out.file4 <- merge(out.file3, file5, by=c("Geneid"))
out.file5 <- merge(out.file4, file6, by=c("Geneid"))
out.file6 <- merge(out.file5, file7, by=c("Geneid"))
out.file7 <- merge(out.file6, file8, by=c("Geneid"))
out.file8 <- merge(out.file7, file9, by=c("Geneid"))
out.file9 <- merge(out.file8, file10, by=c("Geneid"))
out.file10 <- merge(out.file9, file11, by=c("Geneid"))
out.file11 <- merge(out.file10, file12, by=c("Geneid"))

A: This seems to work quite well:
files = list.files(path=".", pattern="MCL")

table_list <- lapply(X = files, FUN = read.table, header=TRUE)

combined <- Reduce(f = merge, x = table_list)

We first loop over the table names with lapply and read each one in, returning a list. By using header=TRUE we can avoid having to rename each one and instead deduce the column names from the first row of each file. Then we can use Reduce to repeatedly merge each table with the next one. merge is smart enough to assume that the shared column name is the thing we want to merge on, so we don't need to specify arguments there either.
I didn't download all the files but here's the output from running this code on the first 3:


Q: Detect if a fs writable stream is full I'm opening a writable stream to a device (e.g: /dev/disk2) with fs.createWriteStream(). Assuming I don't know the device size in advance, how could I correctly detect if the device can't receive more data (e.g: the device doesn't have any more space)?
If I simulate such scenario, I eventually get an EIO error emitted from the stream:
Error: EIO: i/o error, write
  at Error (native) errno: -5, code: 'EIO', syscall: 'write', type: 'write'

But then an EIO is too generic, and can be thrown in other situations as well.
I'm inspecting the properties of the stream object once the error is thrown but there doesn't seem to exist a flag I could use to determine this.


Q: Does passing a value type in an "out" parameter cause the variable to be boxed? I'm aware that boxing and unboxing are relatively expensive in terms of performance. What I'm wondering is:
Does passing a value type to a method's out parameter cause boxing/unboxing of the variable (and thus a performance hit)? Can the compiler optimize this away?
  int number;
  bool result = Int32.TryParse(value, out number);

A: No boxing, compiler uses the ldloca.s instruction which pushes a reference to the local variable onto the stack (http://msdn.microsoft.com/en-us/library/system.reflection.emit.opcodes.ldloca_s(VS.71).aspx)
.method private hidebysig static void Func() cil managed
{
    .maxstack 2
    .locals init (
        [0] int32 num,
        [1] bool flag)
    L_0000: nop
    L_0001: ldstr "5"
    L_0006: ldloca.s num
    L_0008: call bool [mscorlib]System.Int32::TryParse(string, int32&)
    L_000d: stloc.1
    L_000e: ret
}

A: No, there is no Boxing (required/involved).
When you do Box a variable, changes to the boxed instance do not affect the original. But that is exactly what out is supposed to do.
The compiler 'somehow' constructs a reference to the original variable.

A: As others have pointed out, there's no boxing here. When you pass a variable as an argument corresponding to an out or ref parameter, what you are doing is making an alias to the variable.  You are not doing anything to the value of the variable.  You're making two variables represent the same storage location.
Boxing only happens when a value of a value type is converted to a value of a reference type, and there's no conversion of any kind in your example. The reference type must of course be System.Object, System.ValueType, System.Enum or any interface. Usually it is pretty clear; there's an explicit or implicit conversion in the code. However, there can be circumstances where it is less clear. For example, when a not-overridden virtual method of a struct's base type is called, there's boxing. (There are also bizarre situations in which certain kinds of generic type constraints can cause unexpected boxing, but they don't usually come up in practice.)

A: There is no boxing; what the out parameter does is specifies that number must be assigned to within the TryParse method. Irrespective of this, it is still treated as an int, not an object.


Q: Test Custom Gradle plugin after Evaluate I'm developing a Gradle custom plugin and I'm having issues on how to test it.
The plugin creates an extension to receive configuration and after evaluation (project.afterEvaluate {) creates a tasks with the received configuration, those values are @Input on tasks.
Following the documentation https://docs.gradle.org/current/userguide/custom_plugins.html to create a test for the plugin, I use the following to create the project and apply the plugin
@Before fun setup() {
  project = ProjectBuilder.builder().build()
  project.pluginManager.apply("my.plugin.name")

and then test that extension got created:
assertTrue(project.extensions.findByName("name") is MyConfigType)

and the task got created:
assertTrue(project.tasks.findByName("mytask") is MyTaskType)

The issue I'm having is that the task is only created afterEvaluate, so this test is failing. As far as I understood, it has to be afterEvaluate so that it can receive the configuration values.
So the only way I could see if I could on the test force this project to be evaluated, but how?
Is there maybe a different way to receive values?

A: I posted my similar question in the gradle forums and was able to solve the issue:
https://discuss.gradle.org/t/unit-test-plugins-afterevaulate/37437/3
Apparently afterEvaluate is not the best/right place to perform the task creation. If you have a DomainObjectCollection in your extension and want to create a task for each element in the collection, task creation should be done in the all-Callback of the collection:
final MyExtension extension = project.getExtensions().create("extension", MyExtension.class);
extension.configurations.all((c) -> {
  // register task here
});

If you have simple properties in the extension that are feed to the task as input, you should use lazy configuration:
public class MyExtension {
  public final Property<String> property;
  public final NamedDomainObjectContainer<Configuration> configurations;

  @Inject
  public MyExtension(final ObjectFactory objectFactory) {
    property = objectFactory.property(String.class).convention("value");
    configurations = objectFactory.domainObjectContainer(Configuration.class);
  }
}

public abstract class MyTask extends DefaultTask {

  @Input
  private final Property<String> property = getProject().getObjects().property(String.class);

  public Property<String> getProperty() {
    return property;
  }
}

And the apply method:
public class MyPlugin implements Plugin<Project> {

  @Override
  public void apply(final Project aProject) {
    final MyExtension extension = aProject.getExtensions().create("extension", MyExtension.class);
    aProject.getTasks().register("myTask", MyTask.class).configure((t) -> {
      t.getProperty().set(extension.property);
    });
  }
}

A: You should call project.evaluationDependsOn(":"):
@Before fun setup() {
  project = ProjectBuilder.builder().build()
  project.pluginManager.apply("my.plugin.name")
  project.evaluationDependsOn(":") // <<--
  ...
}

It executes your afterEvaluate callback.


Q: Socket programming: Struct sockaddr VS struct sockaddr_in I have seen the question similar question below:
struct sockaddr_un v/s sockaddr - C(Linux)
But I am still very unclear about what the difference is between sockaddr_in and sockaddr, every socket method/function I.e bind, connect, seems to use sockaddr and not sockaddr_in, are these structures interchangeable? if only sockaddr is used then why is there the _in one? I prefer the _in seems more detailed and sorted.
Delete the post or so if I have broken any rules ;(
most of the time the 3rd parameter is the addr_len is this used to quickly differentiate between ipv4 and ipv6?

A: The sockaddr is a generic socket address. If you remember, you can create TCP/IPv4, UDP/IPv4, UNIX, TCP/IPv6, UDP/IPv6 sockets (and more!) through the same operating system API - socket().
All of these different socket types have different actual addresses - composed of different fields.
sockaddr_in is the actual IPv4 address layout (it has .sin_port and .sin_addr). A UNIX domain socket will have type sockaddr_un and will have different fields defined, specific to the UNIX socket family.
Basically sockaddr is a collection of bytes, it's size being the maximum of sizes of all supported (by the O/S) socket/address families such that it can hold all of the supported addresses.

A: Taking a look at sockaddr_in
struct sockaddr_in
  {
    __SOCKADDR_COMMON (sin_);
    in_port_t sin_port;         /* Port number.  */
    struct in_addr sin_addr;        /* Internet address.  */

    /* Pad to size of `struct sockaddr'.  */
    unsigned char sin_zero[sizeof (struct sockaddr) -
               __SOCKADDR_COMMON_SIZE -
               sizeof (in_port_t) -
               sizeof (struct in_addr)];
  };

And if we see sockaddr
* Structure describing a generic socket address.  */
struct sockaddr
  {
    __SOCKADDR_COMMON (sa_);    /* Common data: address family and length.  */
    char sa_data[14];       /* Address data.  */
  };

So actually, they are not exchangeable, but but they have the same size so you can use it with no problem and cast between those structures.
But remember you must know what you are doing or probably will get segfaults or unexpected behavior.


Q: Call function on Main Module I have a VB.NET script that creates mail accounts using smartermail webservice, i know nothing of VB.Net but i have a little knowledge of programming. I created a new project on Visual Studio 2012 and know i need to call the function that creates the accounts on the main module to run it, that's a console app project.
Main Module (Module1.vb) is as follows:
Module Module1
      Sub Main()
      End Sub
End Module*

My function is:
 Sub fnc_CriaContas_Email_Lote()

It's on the file cria_contas_lote.vb in the same directory.
Content of cria_contas_lote.vb:
Sub fnc_CriaContas_Email_Lote()

    Dim oPainelWS As PainelControle.svcSmarterMail
    Dim sRetorno As String = ""

    Try
        'oPainelWS = New PainelControle.svcSmarterMail("xxx.xxx.xxx.xxx")
    Catch ex As Exception
        Console.WriteLine("Erro ao efetuar a conexão no servidor remoto: " & ex.Message)
        Exit Sub
    End Try

    Dim sNomeArquivo As String = "C:\dir\emails.xlsx"
    Dim sSQL As String = ""

    Dim stringExcel As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & sNomeArquivo & ";Extended Properties=Excel 12.0"
    Dim oExcel As New OleDbConnection(stringExcel)

    Try
        oExcel.Open()
    Catch ex As Exception
        Console.Write("O arquivo não foi localizado ou ocorreu um erro de abertura no servidor. Arquivo: " & sNomeArquivo)
        Console.Write(vbCrLf & "================================================")
        Console.Write(vbCrLf & ex.Message)
        Console.Write(vbCrLf & "================================================")

        Exit Sub
    End Try

    Dim oDataSet As New DataSet
    Try
        Dim oExcelAdapter As New OleDbDataAdapter("select * from [contas_pop$]", oExcel)
        oExcelAdapter.Fill(oDataSet, "conteudo")
    Catch ex As Exception
        Console.Write("A tabela CONTAS_POP não foi localizada. Renomeie sua WorkSheet para CONTAS_POP")
        oExcel.Close()
        Exit Sub
    End Try
    oExcel.Close()

    Dim oDataview As DataView = oDataSet.Tables("conteudo").DefaultView

    Dim lTotal As Long = 0
    Dim lErro As Long = 0
    Dim oLinha As DataRow
    Dim iTamanhoCaixa As Integer = 1024
    Dim sComCopia As String

    For Each oLinha In oDataSet.Tables("conteudo").Rows

        If Not (Trim(oLinha("conta").ToString) = "") Then

            Console.Write("Criando [" & Trim(oLinha("conta").ToString) & "]...")
            sRetorno = ""
            sComCopia = Trim(oLinha("enviar_copia").ToString)
            iTamanhoCaixa = oLinha("tamanho_mb")

            sRetorno = CriaContaPOP(Trim(oLinha("conta").ToString), Trim(oLinha("apelidos").ToString), Trim(oLinha("password").ToString), iTamanhoCaixa, oLinha("nome").ToString, sComCopia, "admin", "password")
            'sRetorno = oPainelWS.CriaContaPOP(oLinha("conta"), Trim(oLinha("apelidos").ToString), oLinha("senha"), iTamanhoCaixa, "", sComCopia, "", "")
            Console.WriteLine("Retorno: " & sRetorno)
            'If Not (sRetorno = "OK") Then
            'Exit Sub
            'End If

            Threading.Thread.Sleep(100)

        End If

    Next

End Sub

Public Function CriaContaPOP(ByVal sConta As String, ByVal sApelidos As String, ByVal sSenha As String, ByVal iTamanhoCaixaKB As String, ByVal sNome As String, ByVal sForwardTo As String, ByVal sAdminUsuario As String, ByVal sAdminSenha As String) As String

    If Not (iTamanhoCaixaKB > 1) Then
        Return "ERRO: Tamanho da caixa postal não pode ser inferior a 1 KB"
    End If

    Dim aContaNome As String() = Split(sConta, "@")
    Dim sContaNome As String = ""
    Dim sDominio As String = ""
    sContaNome = aContaNome(0)
    sDominio = aContaNome(1)

    Dim oUsuarios As New svcUserAdmin
    Dim oUsuarioInfo As New SettingsRequestResult
    Dim oResultado As New GenericResult

    oResultado = oUsuarios.AddUser2(sAdminUsuario, sAdminSenha, sContaNome, sSenha, sDominio, sNome, "", False, iTamanhoCaixaKB)
    If (oResultado.Result = False) Then
        Return "ERRO: Não foi possivel incluir a conta de e-mail: " & oResultado.Message
    End If

    If Not (sForwardTo.ToString = "") Then
        Dim arrInfo(0) As String
        arrInfo(0) = "forwardaddress=" & sForwardTo.ToString
        oResultado = oUsuarios.SetRequestedUserSettings(sAdminUsuario, sAdminSenha, sConta, arrInfo)
        If (oResultado.Result = False) Then
            Return "ERRO: Não foi possivel incluir a conta de e-mail: " & oResultado.Message
        End If
    End If

    Return "OK"

End Function

A: What have you tried? Because as it stands it sounds like all you need to do is
Module Module1

    Sub Main()
        fnc_CriaContas_Email_Lote()
    End Sub

    Sub fnc_CriaContas_Email_Lote()
        ' Do something.
    End Sub

End Module

If "fnc_CriaContas_Email_Lote" is a class then you might have to do something like:
Module Module1

    Sub Main()
        dim email as new cria_contas_lote()

        email.fnc_CriaContas_Email_Lote()
    End Sub

End Module

Without seeing the cria_contas_lote file its hard to know.
Edit: Below is how you can call it all from just the module
    Imports System.Data.OleDb

Module Module1

Sub Main()

    fnc_CriaContas_Email_Lote()

End Sub

Sub fnc_CriaContas_Email_Lote()

    Dim oPainelWS As PainelControle.svcSmarterMail
    Dim sRetorno As String = ""

    Try
        'oPainelWS = New PainelControle.svcSmarterMail("xxx.xxx.xxx.xxx")
    Catch ex As Exception
        Console.WriteLine("Erro ao efetuar a conexão no servidor remoto: " & ex.Message)
        Exit Sub
    End Try

    Dim sNomeArquivo As String = "C:\dir\emails.xlsx"
    Dim sSQL As String = ""

    Dim stringExcel As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & sNomeArquivo & ";Extended Properties=Excel 12.0"
    Dim oExcel As New OleDbConnection(stringExcel)

    Try
        oExcel.Open()
    Catch ex As Exception
        Console.Write("O arquivo não foi localizado ou ocorreu um erro de abertura no servidor. Arquivo: " & sNomeArquivo)
        Console.Write(vbCrLf & "================================================")
        Console.Write(vbCrLf & ex.Message)
        Console.Write(vbCrLf & "================================================")

        Exit Sub
    End Try

    Dim oDataSet As New DataSet
    Try
        Dim oExcelAdapter As New OleDbDataAdapter("select * from [contas_pop$]", oExcel)
        oExcelAdapter.Fill(oDataSet, "conteudo")
    Catch ex As Exception
        Console.Write("A tabela CONTAS_POP não foi localizada. Renomeie sua WorkSheet para CONTAS_POP")
        oExcel.Close()
        Exit Sub
    End Try
    oExcel.Close()

    Dim oDataview As DataView = oDataSet.Tables("conteudo").DefaultView

    Dim lTotal As Long = 0
    Dim lErro As Long = 0
    Dim oLinha As DataRow
    Dim iTamanhoCaixa As Integer = 1024
    Dim sComCopia As String

    For Each oLinha In oDataSet.Tables("conteudo").Rows

        If Not (Trim(oLinha("conta").ToString) = "") Then

            Console.Write("Criando [" & Trim(oLinha("conta").ToString) & "]...")
            sRetorno = ""
            sComCopia = Trim(oLinha("enviar_copia").ToString)
            iTamanhoCaixa = oLinha("tamanho_mb")

            sRetorno = CriaContaPOP(Trim(oLinha("conta").ToString), Trim(oLinha("apelidos").ToString), Trim(oLinha("password").ToString), iTamanhoCaixa, oLinha("nome").ToString, sComCopia, "admin", "password")
            'sRetorno = oPainelWS.CriaContaPOP(oLinha("conta"), Trim(oLinha("apelidos").ToString), oLinha("senha"), iTamanhoCaixa, "", sComCopia, "", "")
            Console.WriteLine("Retorno: " & sRetorno)
            'If Not (sRetorno = "OK") Then
            'Exit Sub
            'End If

            Threading.Thread.Sleep(100)

        End If

    Next

End Sub

Public Function CriaContaPOP(ByVal sConta As String, ByVal sApelidos As String, ByVal sSenha As String, ByVal iTamanhoCaixaKB As String, ByVal sNome As String, ByVal sForwardTo As String, ByVal sAdminUsuario As String, ByVal sAdminSenha As String) As String

    If Not (iTamanhoCaixaKB > 1) Then
        Return "ERRO: Tamanho da caixa postal não pode ser inferior a 1 KB"
    End If

    Dim aContaNome As String() = Split(sConta, "@")
    Dim sContaNome As String = ""
    Dim sDominio As String = ""
    sContaNome = aContaNome(0)
    sDominio = aContaNome(1)

    Dim oUsuarios As New svcUserAdmin
    Dim oUsuarioInfo As New SettingsRequestResult
    Dim oResultado As New GenericResult

    oResultado = oUsuarios.AddUser2(sAdminUsuario, sAdminSenha, sContaNome, sSenha, sDominio, sNome, "", False, iTamanhoCaixaKB)
    If (oResultado.Result = False) Then
        Return "ERRO: Não foi possivel incluir a conta de e-mail: " & oResultado.Message
    End If

    If Not (sForwardTo.ToString = "") Then
        Dim arrInfo(0) As String
        arrInfo(0) = "forwardaddress=" & sForwardTo.ToString
        oResultado = oUsuarios.SetRequestedUserSettings(sAdminUsuario, sAdminSenha, sConta, arrInfo)
        If (oResultado.Result = False) Then
            Return "ERRO: Não foi possivel incluir a conta de e-mail: " & oResultado.Message
        End If
    End If

    Return "OK"

End Function

End Module

Your issue is your missing the following types:

*

*PainelControle.svcSmarterMail

*svcUserAdmin

*SettingsRequestResult

*GenericResult

These are not built in .Net types and must be defined in either another file.  Once you've found the missing classes just add them into the project and you should be good to go.

A: I think you want to make Sub Main run ENTIRE function, and DON'T EXIT as sub main is executed.
I have written answer of your question here : VB.net program with no UI
Sub Main()
    'Write whatever you want, and add this code at the END:
    Application.Run
End Sub


Q: Jquery mobile theme on dynamic pages My theme is not being carried out on the dynamic pages that are created in the code I have below. on the first menu page it works then all other pages have the default theme not the one I have set in siteData.theme.
How can I set this?
    var siteData = build;
    $(this).find('[data-role="header"] h3').html(siteData.name);
    $.mobile.activePage.find('[data-role=header] h3').html(siteData.name);
    $('div[data-theme]', '#index').data('theme', siteData.theme);

    //reset all the buttons widgets
    $.mobile.activePage.find('.ui-btn')
        .removeClass('ui-btn-up-a ui-btn-up-b ui-btn-up-c ui-btn-up-d ui-btn-up-e ui-btn-hover-a ui-btn-hover-b ui-btn-hover-c ui-btn-hover-d ui-btn-hover-e')
        .addClass('ui-btn-up-' + $('div[data-theme]', '#index').data('theme'))
        .attr('data-theme', $('div[data-theme]', '#index').data('theme'));

    //reset the header/footer widgets
    $.mobile.activePage.find('.ui-header, .ui-footer')
        .removeClass('ui-bar-a ui-bar-b ui-bar-c ui-bar-d ui-bar-e')
        .addClass('ui-bar-' + $('div[data-theme]', '#index').data('theme'))
        .attr('data-theme', $('div[data-theme]', '#index').data('theme'));

    //reset the page widget
    $.mobile.activePage.removeClass('ui-body-a ui-body-b ui-body-c ui-body-d ui-body-e')
        .addClass('ui-body-' + $('div[data-theme]', '#index').data('theme'))
        .attr('data-theme', $('div[data-theme]', '#index').data('theme'));

    $.each(siteData["pages"], function (i, v) {

        if (!$('#' + v["id"]).length) {

            // Build nav.
            $.mobile.activePage.find('[data-role=content]').append('' +
                '' + v["name"] +
                '').trigger('create');

            var components = {};

            var newPage = $("

Back" +
                "
" + v["name"] + "
" +
                "
" +
                "
" + pagecontent +
                "
" +
                "
" +
                "
" + v["name"] + "
" +
                "
" +
                "
");

            newPage.appendTo($.mobile.pageContainer);

        }

    });

});

A: From your code it looks like siteData.theme holds the theme name i.e. 'b' so you can just add:
$('[data-role=page]').page({
        theme: siteData.theme
    });

To your script.
This will not however change the header and footer from the default theme. You could just in the newPage creation add data-theme=siteData.theme depending on whats in siteData.theme of course.


Q: How to insert array object property value into HTML? I wanted to make a simple carousel using DOM manipulation, I don't know if I can do this or not in Angular, but the idea is I created an array of objects with properties that I want to pass to the HTML using interpolation, and I don't know how to do it yet. Here's my code:

carousel

                              <fa-icon [icon]="faChevronLeft" class="mr-2"></fa-icon>

                              <fa-icon [icon]="faChevronRight" class="mr-2"></fa-icon>

{{carousel.description}}

 {{carousel.name}}, {{carousel.affiliation}}

import { Component } from '@angular/core';
import { Router } from '@angular/router';
import {faChevronLeft, faChevronRight, IconDefinition} from '@fortawesome/free-solid-svg-icons';

@Component({
  selector: 'app-carousel',
  templateUrl: './carousel.component.html',
  styleUrls: ['./carousel.component.scss']
})
export class CarouselComponent implements OnInit {
  faChevronLeft: IconDefinition = faChevronLeft;
  faChevronRight: IconDefinition = faChevronRight;
  carousel = [
    {
      id: 1,
      name: 'captain america',
      affiliation: 'camp lehigh',
      description: 'language!',
      image: 'http://picsum.photos/200'
    },
    {
      id: 2,
      name: 'thor',
      affiliation: 'asgard',
      description: 'i am god of thunder!',
      image: 'http://picsum.photos/200'
    },
    {
      id: 3,
      name: 'tony stark',
      affiliation: 'stark industries',
      description: 'and i....am..iron man!',
      image: 'http://picsum.photos/200'
    }
  ];

  constructor(
  ) {}

  ngOnInit() {
  }

  carouselPrev() {
     // i want to make this a control by making the id/index +1
  }

  carouselNext() {
    // i want to make this a control by making the id/index -1
  }
 }

A: You can achieve it using ngFor with index.
Live example: https://stackblitz.com/edit/angular-b5qvwy
Some code:
Basic HTML

{{list[i].name}}

<

>

Basic TS code
 export class AppComponent  {
      list = [
        {
          name: "Jhon"
        },
        {
          name: "Joe"
        },
        {
          name: "Marth"
        }
      ];

      i = 0;

      prev(){
        if(this.i > 0){
          this.i--;
        }
      }

      next(){
        if(this.i < this.list.length -1){
          this.i++;
        }
      }
    }

For your example, simply do that in the html:

carousel

                              <fa-icon [icon]="faChevronLeft" class="mr-2"></fa-icon>

                              <fa-icon [icon]="faChevronRight" class="mr-2"></fa-icon>

{{carousel[i].description}}

 {{carousel[i].name}}, {{carousel[i].affiliation}}


Q: Error occurred during initialization of VM java/lang/NoClassDefFoundError: java/lang/Object in Redhat I am using Redhat 6. I am in strange problem.
I was working with java 1.6. I updated my system with yum updated automatically openjdk 1.8 got install. I removed the package fro UI.
Now when I typed java -version. I get this error
 Error occurred during initialization of VM
 java/lang/NoClassDefFoundError: java/lang/Object.

I thought my java is corrupted and I remove java using yum remove java*. Again I installed java.
I downloaded the bin file of java 1.6 and extracted it in my home folder. edited .bash_profile and gave the path.
run .bash_profile Using . .bash_profile
Now when I type
java -version I get

java version "1.6.0_45" Java(TM) SE Runtime Environment (build
  1.6.0_45-b06) Java HotSpot(TM) 64-Bit Server VM (build 20.45-b01, mixed mode)

but when i restart my system and again I type
java -version I get the same error saying
Error occurred during initialization of VM
java/lang/NoClassDefFoundError: java/lang/Object

How do i resolve it?


Q: Count how many arguments passed as positional If I have a function
def foo(x, y):
    pass

how can I tell, from inside the function, whether y was passed positionally or with its keyword?
I'd like to have something like
def foo(x, y):
    if passed_positionally(y):
        print('y was passed positionally!')
    else:
        print('y was passed with its keyword')

so that I get
>>> foo(3, 4)
y was passed positionally
>>> foo(3, y=4)
y was passed with its keyword

I realise I didn't originally specify this, but is it possible to do this whilst preserving type annotations? The top answer so far suggests using a decorator - however, that does not preserve the return type

A: You can create a decorator, like this:
def checkargs(func):
    def inner(*args, **kwargs):
        if 'y' in kwargs:
            print('y passed with its keyword!')
        else:
            print('y passed positionally.')
        result = func(*args, **kwargs)
        return result
    return inner

>>>  @checkargs
...: def foo(x, y):
...:     return x + y

>>> foo(2, 3)
y passed positionally.
5

>>> foo(2, y=3)
y passed with its keyword!
5

Of course you can improve this by allowing the decorator to accept arguments. Thus you can pass the parameter you want to check for. Which would be something like this:
def checkargs(param_to_check):
    def inner(func):
        def wrapper(*args, **kwargs):
            if param_to_check in kwargs:
                print('y passed with its keyword!')
            else:
                print('y passed positionally.')
            result = func(*args, **kwargs)
            return result
        return wrapper
    return inner

>>>  @checkargs(param_to_check='y')
...: def foo(x, y):
...:     return x + y

>>> foo(2, y=3)
y passed with its keyword!
5

I think adding functools.wraps would preserve the annotations, following version also allows to perform the check over all arguments (using inspect):
from functools import wraps
from inspect import signature

def checkargs(func):
    @wraps(func)
    def inner(*args, **kwargs):
        for param in signature(func).parameters:
            if param in kwargs:
                print(param, 'passed with its keyword!')
            else:
                print(param, 'passed positionally.')
        result = func(*args, **kwargs)
        return result
    return inner

>>>  @checkargs
...: def foo(x, y, z) -> int:
...:     return x + y

>>> foo(2, 3, z=4)
x passed positionally.
y passed positionally.
z passed with its keyword!
9

>>> inspect.getfullargspec(foo)
FullArgSpec(args=[], varargs='args', varkw='kwargs', defaults=None,
kwonlyargs=[], kwonlydefaults=None, annotations={'return': <class 'int'>})
                                             _____________HERE____________

Update Python 3.10
In Python 3.10+ new ParamSpec type annotation was introduced (PEP 612), for better specifying parameter types in higher-order functions. As of now, the correct way to annotate this decorator would be like this:
from functools import wraps
from inspect import signature
from typing import Callable, ParamSpec, TypeVar, TYPE_CHECKING

T = TypeVar("T")
P = ParamSpec("P")

def check_args(func: Callable[P, T]) -> Callable[P, T]:
    """
    Decorator to monitor whether an argument is passed
    positionally or with its keyword, during function call.
    """

    @wraps(func)
    def inner(*args: P.args, **kwargs: P.kwargs) -> T:
        for param in signature(func).parameters:
            if param in kwargs:
                print(param, 'passed with its keyword!')
            else:
                print(param, 'passed positionally.')
        return func(*args, **kwargs)

    return inner

Which correctly preserves type annotation:
if TYPE_CHECKING:
    reveal_type(foo(2, 3))

# ─❯ mypy check_kwd.py
# check_kwd.py:34: note: Revealed type is "builtins.int"
# Success: no issues found in 1 source file

A: Adapted from @Cyttorak 's answer, here's a way to do it which maintains the types:
from typing import TypeVar, Callable, Any, TYPE_CHECKING

T = TypeVar("T", bound=Callable[..., Any])

from functools import wraps
import inspect

def checkargs() -> Callable[[T], T]:
    def decorate(func):
        @wraps(func)
        def inner(*args, **kwargs):
            for param in inspect.signature(func).parameters:
                if param in kwargs:
                    print(param, 'passed with its keyword!')
                else:
                    print(param, 'passed positionally.')
            result = func(*args, **kwargs)
            return result
        return inner
    return decorate

@checkargs()
def foo(x, y) -> int:
    return x+y

if TYPE_CHECKING:
    reveal_type(foo(2, 3))
foo(2, 3)
foo(2, y=3)

Output is:
$ mypy t.py
t.py:27: note: Revealed type is 'builtins.int'

$ python t.py
x passed positionally.
y passed positionally.
x passed positionally.
y passed with its keyword!

A: It is not ordinarily possible. In a sense: the language is not designed to allow you to distinguish both ways.
You can design your function to take different parameters - positional, and named, and check which one was passed, in a thing like:
def foo(x, y=None, /, **kwargs):

    if y is None:
        y = kwargs.pop(y)
        received_as_positional = False
    else:
        received_as_positional = True

The problem is that, although by using positional only parameters as abov, you could get y both ways,
it would be shown not once for a user (or IDE) inspecting the
function signature.
I hav a feeling you just want to know this for the sake of knowing - if
you really intend this for design of an API, I'd suggest you'd rethink
your API - there should be no difference in the behavior, unless both
are un-ambiguously different parameters from the user point of view.
That said, the way to go would be to inspect the caller frame, and check
the bytecode around the place the function is called:

In [24]: import sys, dis

In [25]: def foo(x, y=None):
    ...:     f = sys._getframe().f_back
    ...:     print(dis.dis(f.f_code))
    ...:

In [26]: foo(1, 2)
  1           0 LOAD_NAME                0 (foo)
              2 LOAD_CONST               0 (1)
              4 LOAD_CONST               1 (2)
              6 CALL_FUNCTION            2
              8 PRINT_EXPR
             10 LOAD_CONST               2 (None)
             12 RETURN_VALUE
None

In [27]: foo(1, y=2)
  1           0 LOAD_NAME                0 (foo)
              2 LOAD_CONST               0 (1)
              4 LOAD_CONST               1 (2)
              6 LOAD_CONST               2 (('y',))
              8 CALL_FUNCTION_KW         2
             10 PRINT_EXPR
             12 LOAD_CONST               3 (None)
             14 RETURN_VALUE

So, as you can see, when y is called as named parameter, the opcode for the call is CALL_FUNCTION_KW , and the name of the parameter is loaded into the stack imediately before it.

A: You can trick the user and add another argument to the function like this:
def foo(x,y1=None,y=None):
  if y1 is not None:
    print('y was passed positionally!')
  else:
    print('y was passed with its keyword')

I don't recommend doing it but it does work

A: In foo, you can pass the call stack from traceback to positionally, which will then parse the lines, find the line where foo itself is called, and then parse the line with ast to locate positional parameter specifications (if any):
import traceback, ast, re
def get_fun(name, ast_obj):
    if isinstance(ast_obj, ast.Call) and ast_obj.func.id == name:
        yield from [i.arg for i in getattr(ast_obj, 'keywords', [])]
    for a, b in getattr(ast_obj, '__dict__', {}).items():
        yield from (get_fun(name, b) if not isinstance(b, list) else \
                        [i for k in b for i in get_fun(name, k)])

def passed_positionally(stack):
    *_, [_, co], [trace, _] = [re.split('\n\s+', i.strip()) for i in stack]
    f_name = re.findall('(?:line \d+, in )(\w+)', trace)[0]
    return list(get_fun(f_name, ast.parse(co)))

def foo(x, y):
    if 'y' in passed_positionally(traceback.format_stack()):
        print('y was passed with its keyword')
    else:
        print('y was passed positionally')

foo(1, y=2)

Output:
y was passed with its keyword

Notes:

*

*This solution does not require any wrapping of foo. Only the traceback needs to be captured.

*To get the full foo call as a string in the traceback, this solution must be run in a file, not the shell.

A: At the end, if you are going to do something like this:
def foo(x, y):
    if passed_positionally(y):
        raise Exception("You need to pass 'y' as a keyword argument")
    else:
        process(x, y)

You can do this:
def foo(x, *, y):
    pass

>>> foo(1, 2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: foo() takes 1 positional argument but 2 were given

>>> foo(1, y=2) # works

Or only allow them to be passed positionally:
def foo(x, y, /):
    pass

>>> foo(x=1, y=2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: foo() got some positional-only arguments passed as keyword arguments: 'x, y'

>>> foo(1, 2) # works

See PEP 570 and PEP 3102 for more.


Q: iOS app localization I want to localize my app. Should I create a new app in itunesconnect for each country or there is a way to automatically detect the country where user is? Actually my app is game based on Unity3d - is it possible to do it on Unity3d?

A: Before Unity starts write these lines to pass the current language into unity
NSUserDefaults* defs = [NSUserDefaults standardUserDefaults];

NSArray* languages = [defs objectForKey:@"AppleLanguages"];

NSString* preferredLang = [languages objectAtIndex:0];

[[NSUserDefaults standardUserDefaults] setObject: preferredLang forKey: @"language"];

[[NSUserDefaults standardUserDefaults] synchronize];

A: Definitely don't create a new app for each locale. iOS apps are localizable and iTunes Connect allows you to enter different metadata for each language.

A: You dont need to make a new app for each language. Try following a guide like SmoothLocalize's tutorial or This one.
Then you'll have a Localizable.strings file you need to translate. I usually use SmoothLocalize.com as my translation services, because its cheap and super easy, but you can look around for others or even try to find individual translators yourself.


Q: EF 4 - Lazy Loading Without Proxies I´ve read that proxies are used when wee need to use Lazy Loading and Change Tracking. In other words, to use Lazy Loading I must enable proxies.
So far so good.
the point is that I can use the code bellow to setup the context to not use a proxy and even yet use lazy loading.
ctx = new SchoolEntities();
ctx.ContextOptions.ProxyCreationEnabled = false;
ctx.ContextOptions.LazyLoadingEnabled = true;

Is the ProxyCreationEnabled property related only to change tracking proxy or am I missing something?
Could someone please explain this with some details?
Thanks!
EDIT1
I´m not using POCO/DbContext. I´m using a regular edmx EF model with ObjectContext. I know the importance of proxies for POCO entities regards to change tracking and lazy loading. By why to use Proxies in a regular EDMX model?

A: When using POCO entities with the built-in features of Entity Framework, proxy creation must be enabled in order to use lazy loading. So, with POCO entities, if ProxyCreationEnabled is false, then lazy loading won't happen even if LazyLoadingEnabled is set to true.
With certain types of legacy entities (notably those the derive from EntityObject) this was not the case and lazy loading would work even if ProxyCreationEnabled is set to false. But don't take that to mean you should use EntityObject entities--that will cause you more pain.
The ProxyCreationEnabled flag is normally set to false when you want to ensure that EF will never create a proxy, possibly because this will cause problems for the type of serialization you are doing.
The LazyLoadingEnabled flag is normally used to control whether or not lazy loading happens on a context-wide basis once you have decided that proxies are okay. So, for example, you might want to use proxies for change tracking, but switch off lazy loading.


Q: Custombox and modal using JS I have a modal using custombox that works using a button :

        <link href="assets/plugins/custombox/dist/custombox.min.css" rel="stylesheet">
        <link href="assets/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
        <link href="assets/css/core.css" rel="stylesheet" type="text/css" />
        <link href="assets/css/components.css" rel="stylesheet" type="text/css" />
        <link href="assets/css/icons.css" rel="stylesheet" type="text/css" />
        <link href="assets/css/pages.css" rel="stylesheet" type="text/css" />
        <link href="assets/css/menu.css" rel="stylesheet" type="text/css" />
        <link href="assets/css/responsive.css" rel="stylesheet" type="text/css" />

                                                            Collapsible Group Item #1

                                                        test

  <button  data-toggle="modal" data-target="#accordion-modal">Accordion in Modal</button>

I am trying to initiate this modal inside jquery, inside a datatables button with no luck.
This is the part of the code in my function :
    buttons: [
      {
            text: 'My accordion Button',
            className: "btn-sm",
            action: function ( e, dt, node, config ) {
              Custombox.open({
                target: '#accordion-modal',
                effect: 'fadein'
     });
      e.preventDefault();
            }
        }
    ]

The code above works to open other simple modals but not this one. This has to do I guess with the
data-toggle="modal" data-target="#accordion-modal"

that is contained in the button. From what I understand the data-target is replaced by "target" in js, but the data-toggle is not triggered anywhere. How do I trigger it properly? I attempted to initiate it with $('#accordion-modal').modal('show') but I am not sure where exactly I should put this. If I put it in the beginning it just flashes for a second

A: Looks like I only needed :
  {
                text: 'My accordion Button',
                className: "btn-sm",
                action: function ( e, dt, node, config ) {
$('#accordion-modal').modal('show');

          e.preventDefault();
                }
            }


Q: Detecting when right mouse button was clicked only My table has 4 columns, and I only want column 1 to be allowed to be clicked. Also, this code also allows the LEFT mouse button to be used, I only want the RIGHT button.
    private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {
    // TODO add your handling code here:
    int iCol = jTable1.getSelectedColumn();

    if(iCol == 1 && evt.getModifiers() == InputEvent.BUTTON3_MASK)
    {
        if(evt.getClickCount() == 2)
        {
            int iRow = jTable1.getSelectedRow();

            File iFile = new File(jTable1.getValueAt(iRow, iCol).toString());

            String iPath = iFile.getAbsolutePath();
            File iDir = new File(iPath.substring(0, iPath.lastIndexOf(File.separator)));

            if(Desktop.isDesktopSupported()) {
                try {
                    Desktop.getDesktop().open(iDir);
                } catch (IOException ex) {
                    Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }
}

I'm sorry if this question turned out as 2.

A: Lets start with, left button is normally represented by MouseEvent.BUTTON1, then move onto MouseEvent#getModifiers is usually used to provide information about what keys are currently pressed and we begin to see the major problems.
The method you really want is MouseEvent#getButton
Try run the following example for some ideas ;)
public class TestMouseClicked {

    public static void main(String[] args) {
        new TestMouseClicked();
    }

    public TestMouseClicked() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException ex) {
                } catch (InstantiationException ex) {
                } catch (IllegalAccessException ex) {
                } catch (UnsupportedLookAndFeelException ex) {
                }

                JFrame frame = new JFrame();
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new MousePane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class MousePane extends JPanel {

        private JToggleButton leftButton;
        private JToggleButton middleButton;
        private JToggleButton rightButton;

        public MousePane() {
            setLayout(new GridBagLayout());

            leftButton = new JToggleButton("Left");
            middleButton = new JToggleButton("Middle");
            rightButton = new JToggleButton("Right");

            add(leftButton);
            add(middleButton);
            add(rightButton);

            ButtonGroup bg = new ButtonGroup();
            bg.add(leftButton);
            bg.add(middleButton);
            bg.add(rightButton);

            addMouseListener(new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent e) {
                    System.out.println(e.getButton());
                    if (e.getButton() == MouseEvent.BUTTON1) {
                        leftButton.setSelected(true);
                    } else if (e.getButton() == MouseEvent.BUTTON2) {
                        middleButton.setSelected(true);
                    } else if (e.getButton() == MouseEvent.BUTTON3) {
                        rightButton.setSelected(true);
                    }
                }
            });

        }

    }

}

A: Concerning the clicking only of a specific column:

1. create the table using you own model.
final JTable table = new JTable( new MyTableModel(data, columnNames));

2. create the new model overriding the function you need (i.e. isCellEditable)
public class MyTableModel extends DefaultTableModel {

    private static final long serialVersionUID = -8422360723278074044L;

    MyTableModel(Object[][] data, Object[] columnNames )
    {
      super(data,columnNames);
    }

    public boolean isCellEditable(int row,int cols)
     {
       if(cols==1 ){return true;}
          return false;
     }
}


Q: Laravel 5.1 AJAX Response always causes a connection reset I have a problem with a Laravel AJAX response.
The request is GET not POST
This is the API URL:
http://example.com/app/public/index.php/api/userdata
and I never receive an AJAX response.
In my Chrome browser I get the following error net::ERR_CONNECTION_RESET,
but when I go to the API URL directly from Chrome
I get the JSON response and it's correct.
This only happens for AJAX requests
and I also have "Provisional headers are shown" in my AJAX request.
I'm using Ember for AJAX requests, but I also tried using jQuery $.getJSON
and I got the same result.
I read some discussion about "Laravel Connection Reset" and I tried to disable opcache but this is still happening.
This is my enviroment

*

*PHP Version 7.0

*Laravel 5.1.39(LTS)

*Ubuntu 14.04.4 LTS

*jQuery 1.11.3

*Ember 2.0.2

This is my controller code :
 public function index()
  {
      $inputs = Input::all();
      $userData = UserData::inMyCompany();
      if(isset($inputs['filters']))
      {
          foreach($inputs['filters'] as $field => $value)
          {
              $userData->where($field, '=', $value);
          }
      }
      $userData->with([
         'userDataRelation1',
         'userDataRelation2',
      ]);
      $userData = $userData->get();
      return Response::json($userData);
  }

This is my JavaScript code :
<script src='https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js'></script>
     <script>
     $(document).ready(function(){
         var url = 'http://example.com/app/public/index.php/api/userdata?filters[id]=633';
         $.getJSON(url, function(response){
             console.log(response);
         });
     });
     </script>

Why does the AJAX request always return a "Connection Reset" ?
What is the possible cause for this ?
How to fix the problem ?
Thanks in advance.


Q: 2D fused Lasso with Matlab CVX I wrote a 2D fused lasso code here.
[m n] = size(circle);
cvx_begin
    variable theta(m, n);
    minimize( norm(circle-theta, 'fro'));
    subject to
        sum(sum(abs(theta(:,1:n-1)-theta(:,2:n)))) == 0;
        sum(sum(abs(theta(1:m-1,:)-theta(2:m,:)))) == 0;
cvx_end

Weirdly, the program report,

In cvxprob (line 28)   In cvx_begin (line 41)  Error using cvxprob/newcnstr (line 192) Disciplined convex programming error:
    Invalid constraint: {convex} == {constant}

Error in  ==  (line 12) b = newcnstr( evalin( 'caller', 'cvx_problem',
  '[]' ), x, y, '==' );

After I remove abs() in the constraint, the program could run, but that's not what constraints I expect to be.

A: I think you can try stacking the matrices into vectors, then use L1 norm. In CVX, it's just norm(variable, 1). It will do the same as you wrote here: sum of absolute elementary-wise differences.


Q: ActionController::UnknownFormat in HelpController#about as a Ruby newbie I am still getting to grips with the language. I have created a broadcast controller for a simple database that is already being used in production. However, I am getting the above mentioned error. Below is the code I have used:
show.html.erb

<%= notice %>

   <%= link_to 'Edit', edit_broadcast_path(@broadcast) %> |
   <%= link_to 'Back', broadcasts_path %>

Index.html.erb
index.html.erb
broadcasts_controller.rb
boradcast controller
help controller
  class HelpController < ApplicationController
skip_before_action :authenticate_user!

  def about
  #render text: "Hello"
  end

end
I am not sure if I am missing any files or configs, I will add them in the comments if need be. Thanks

A: Incoming requests may use headers or parameters to indicate to Rails what format, called "MIME type", the response should have. For instance, a typical GET request from entering a URL into your browser will ask for an HTML (or default) response. Other types of common responses return JSON or XML.
In your case your "about" action does not have any explicit responders, and because of that Rails can't match the requested format (which is what the error message is trying to convey). You will probably just want to add an HTML template app/views/help/about.html.erb with your content. Rails should identify the HTML template and handle things from there.
More info
In Rails you need to respond with a specific format, and it is easy to setup your controller actions to handle a variety of formats.
Here is a snippet you might find in a controller which can respond in 3 different ways.
respond_to do |format|
  format.html { render "foo" } # renders foo.html.erb
  format.json { render json: @foo }
  format.xml { render xml: @foo }
end

You can see more examples and deeper explanations in the documentation here.
ActiveRecord helps because it comes with serializers out of the box which can create JSON and XML representations of your objects.


Q: How to check if the same letter is used more than once in a word (hangman project, javascript) I have almost finished the javascript logic for my personal hangman project i am creating. One of the final issues i am having is getting the program to recognize if the same letter is used in the "chosen word". For example, when "ninja" is selected as the "chosen word", and the user selects "n", i would like my counter variable to recognize that there are two "n's", and add 2 to the score instead of one.
My code thus far:
var secretWords = ["batman", "Donkey kong", "ninja",
"programming"];
 var chosenWord = secretWords[Math.floor(Math.random()*secretWords.length)];
var guesses = 8;
 console.log(chosenWord);
 var letters = chosenWord.length;
var counter = 0;
var gameOver = guesses === 0;
console.log(guesses);
console.log(counter);

while(guesses !== 0){
const guess = prompt("GUESS A LETTER")
var guessLowerCase = guess.toLowerCase();
var isGuessedLetterInWord =
chosenWord.includes(guessLowerCase);
if (isGuessedLetterInWord) {
alert('nice'); counter ++;

 } else {
alert('wrong'); guesses --;

}
}

if(counter === chosenWord.length){
 alert("You Win!!");
}

if (guesses === 0){
alert("LOSER!");
}

A: A simple hack would be to split the string by letter and count.
let occurances = chosenWord.split(guessLowerCase).length - 1

Or you could use regular expression to search for all occurances:
let occurances = [...chosenWord.matchAll(new RegExp(guessLowerCase, 'g'))].length


Q: Accessing data from a List using jsp I have a bean that has the follwing:
public DeptLibraryEntry(int id, String type, String name, String info, Boolean avail){
    this.id = id;
    this.type = type;
    this.name = name;
    this.info = info;
    this.avail = avail;
    this.log = new ArrayList<Log>();
}

and another bean called Log.It is the following:
    public Log(String num, String name, String dateBorrowed, String dateReturned){
    this.num = num;
    this.name = name;
    this.dateBorrowed = dateBorrowed;
    this.dateReturned = dateReturned;
}

I want to list the "num","name","dateBorrowed" and "dateReturned" in a JSP.
I am trying the following code in my JSP:
<c:forEach items="${entries}" var="entry">

${entry.Log.num}

</c:forEach>

I've tried some variations of this but can't seem to get it. Any help would be appreciated!

A: Thiss assumes that entries is a list/collection of DeptLibraryEntry.
Note that log (and not Log, capitalization is important!) is itself a list of items, so to get the value of each item you have to iterate over it again
<c:forEach items="${entries}" var="entry">
  <c:forEach items="${entry.log}" var="logItem">

${logItem.num}

     ....
  </c:forEach>
</c:forEach>

Of course, your classes will need to have the appropiate getters to access the properties.


Q: How to change row names based off input from different dataframe Say I have df1 that contains names in column 1 and numerical values in the other columns, and I have df2 that contains the same set of names in column 2 and a unique corresponding identifier in column 1.
The order of the names in the dfs don't match so I need a way to replace df1 names with df2 identifiers.
I know I can do something similar with the dplyr rename function but my dataframes are HUGE so that's a lot to manually write out. I thought this could be done in base R with a simple for/if loop using logical arguments but I feel like there has to be an easier way? Any help, tips or tricks would be appreciated.
For example:
View(df1)

Name
Value
etc.

Heart
2
...

Brain
5
...

Blood
10
...

Lung
3
...

...
...
...

View(df2)

ID
Type

H
Heart

L
Lung

Br
Brain

Bl
Blood

...
...

After code:
View(df1)

Name
Value
etc.

H
2
...

Br
5
...

Bl
10
...

L
3
...

...
...
...


Q: need help in mvvmcross windows phone 8 fluent binding with conversion I'm Little stuck in getting the fluent binding/conversion to Work. I have the following to work
set.Bind(TextBackStartColor).For(v => v.Text).To(vm => vm.TextBackStartColor).TwoWay()

but when I try to add a WithConversion, I need some help in how to get the converter called
set.Bind(TextBackStartColor).For(v => v.Text).To(vm => vm.TextBackStartColor).TwoWay().WithConversion("Test")

In xaml the converter works fine, in Android and Touch the above converter works fine.
I've tried in
CORE:
public sealed class TestValueConverter : MvxValueConverter<string, string>
{
  protected override string Convert(string value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
    string test = (string)value + "test";

    return test;
  }

  public string ConvertBack(string value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
  {
    return value;
  }
}

and the corresponding Phone/NativeConverters:
namespace DCS.Phone.NativeConverters
{
  public class NativeTestValueConverter : MvxNativeValueConverter<TestValueConverter>
  {
  }
}

I've also tried in
Phone/Converters
public sealed class TestConverter : IValueConverter
{
  public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
  {
    string test = (string)value+"test";

    return test;
  }

  public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
    throw new NotImplementedException();
  }
}

But my converters are never getting called.
As I said my bindings works very well, so what am I missing in Phone project to get the converters called?

A: Android and iOS both automatically pick up the ValueConverter names - the mechanism they do this by is described in https://github.com/MvvmCross/MvvmCross/wiki/Value-Converters#referencing-value-converters-in-touch-and-droid
Windows platforms don't do this by default - because Windows uses Xaml binding by default.
If you want to add this use of named value converters, then you can do this using code in your Windows Setup.cs like:
       // call this in InitializeLastChance
       Mvx.CallbackWhenRegistered<IMvxValueConverterRegistry>(FillValueConverters);

       // add this method
       private FillValueConverters(IMvxValueConverterRegistry registry)
       {
            registry.Fill(ValueConverterAssemblies);
       }

       // add this property
       protected virtual List<Assembly> ValueConverterAssemblies
       {
            get
            {
                var toReturn = new List<Assembly>();
                toReturn.AddRange(GetViewModelAssemblies());
                toReturn.AddRange(GetViewAssemblies());
                return toReturn;
            }
        }


Q: How to to solve the responsiveness of mouseover and mouseout I am sliding a div whenever there is a mouse over event and sliding it back(hiding) when there is mouse out event.
If I do too fast mouse out and mouse over, the div keeps oscillating. How do I fix this problem?
 $(document).ready(function() {
   $("#in").ready(function(){
     $("#out").mouseover(function () {
       $("#in").animate({"height":"toggle",},200);
     });
   });
   $("#in").ready(function(){
     $("#out").mouseout(function () {
       $("#in").animate({"height":"toggle",},200);
     });
   });
 });

Google

A: you can use stop() method:

Stop the currently-running animation on the matched elements.

$("#out").mouseover(function () {
     $("#in").stop(true, true).animate({"height":"toggle"},200);
});

A: First of all, you should take the advice given by me and by Raminson.  The stop() function will halt all currently running animations on the given element and prevent the behavior you were seeing.
Another 2 things can be said about the code you posted.

*

*You have a trailing comma in the parameters you gave to the .animate() function.
{"height":"toggle",}.  Now that might work on Chrome and Firefox, but in IE that will probably not work and more over it probably won't tell you where or why it's not working.  You should never have trailing commas in an array or object in JavaScript....

*You wrapped your jQuery call in the document ready handler (as you should) but then you wrapped your code within another ready handler for each element.$("#in").ready()... $("#out").ready().   This is unnecessary.   You only need one ready function to make sure the DOM and jQuery are loaded.


Q: Empty Object ID for first DrEdit Doc in PHP Google API Drive SDK Example Ive worked through several errors to get this far with the Google API Drive PHP DREdit example, and attempted the setup on this.
The OAuth2 appears to connect ok, and loading the DrEdit demo page.  However on first save the doc has no ID, and the DrEdit frontends /public/js/controller.js handles this with:
...
if ($routeParams.id ) {
    editor.load($routeParams.id);
} else {
    // New doc, but defer to next event cycle to ensure init
    $timeout(function () {
            editor.create();
        },
        1);
}

To me, this means get the ID the second time the doc is saved because it won't be present at the first time. Chrome console output (not expanded) shows on first menu File > Save:

Object {id: ""} controllers.js:14
Creating new doc angular-1.0.0.js:5525
Updating editor Object {content: "", labels: Object, editable: true, title: "Untitled document", description: ""…}content: nulldescription: ""editable: truelabels:
ObjectmimeType: "text/plain"resource_id: nulltitle: "Untitled document"proto:
Object angular-1.0.0.js:5525`

Then second save in the File menu:

Saving file true angular-1.0.0.js:5525
Saving Object {content: "", labels: Object, editable: true, title: "Untitled document", description: ""…} angular-1.0.0.js:5525
Saved file Object {data: Object, status: 200, headers: function, config: Object} angular-1.0.0.js:5525
Object {id: "[object Object]"} controllers.js:14
Loading resource [object Object] Object {} angular-1.0.0.js:5525
Saving file false angular-1.0.0.js:5525
Saving Object {content: "abc", labels: Object, editable: true, title: "Untitled document", description: ""…} angular-1.0.0.js:5525
PUT http://company.com/svc?newRevision=true 500 (Internal Server Error)

I'm concerned with the Object {id: "[object Object]"}  but a little stuck.  $routeParams.id on first go does not appear to have a valid file ID but not sure if its supposed to until the second save.  PHP SLIM framework consequently complains with
ErrorException Undefined property: stdClass::$id

How do I diagnose further?

A: It appears that there maybe a bug in the sample leading to this error. Please file an issue in the GitHub project's issue tracker so we can follow up.


Q: COUNT DISTINCT / nunique within groups I want to count the number of distinct tuples within each group:
df = pd.DataFrame({'a': ['A', 'A', 'A', 'A', 'B', 'B', 'B', 'B'],
              'b': [1, 2, 1, 2, 1, 2, 1, 2],
              'c': [1, 1, 2, 2, 2, 1, 2, 1]})
counts = count_distinct(df, by='a', columns=['b', 'c'])
assert counts == pd.Series([4, 2], index=['A', 'B'])

In other words, counts should report that for group 'A', there are four distinct tuples and for group 'B', there are two.
I tried using df.groupby('a')['b', 'c'].nunique(), but nunique works only with a single column.
I know I could count distinct tuples by df.groupby(['b', 'c']), but that means I have use a slow apply with a pure python function (the number of groups of column 'a' is large).
I could convert the 'b' and 'c' columns into a single column of tuples, but that would be super slow since it will no longer use vectorized operations.

A: I think your logic is equivalent to count the size of data frames grouped by column a after dropping the duplicated values of combined columns a, b and c, since duplicated tuples within each group must also be duplicated records in the data frame assuming your data frame contains only columns a, b and c and vice versa:
df.drop_duplicates().groupby('a').size()

# a
# A    4
# B    2
# dtype: int64


Q: I defined an templated class. Can I see the (source) code that occurs after it is instantiated? C++ I defined an templated class.
I'd like to see source code that results when the class is instantiated. For example, imagine I have a class like std::vector from the standard library:
template <typename T>
class Vector { ... } // this is in the .h and .inl

Then I instantiate it
vector<int> v = new vector<int>();

Can I see the inlined code that the compiler will create?

A: There's no source code, template instantiation isn't a text-replace step. To inspect the generated code you should use a disassembler/debugger or dump (if the compiler supports it) the generated code. Template instantiation is a compilation step and although it can get pretty complex, it generates code and not text.
Macros undergo a process similar to what you described: they're processed in the pre-processing stage and they're just plain text substitutions


Q: Is it safe to have various Perl installations on one machine share a cpan_home? I have a dated system perl 5.8.8 on a Linux machine and installed a 5.12.4 from ActiveState. Both perl's cpan_home is ~root/.cpan. I was about to change the new perl's cpan_home, but then I realized I didn't know whether I really have to do this or whether it would just result in multiple copies of modules being downloaded to different directories when in fact they could be shared.
So can they? Is it safe? With regard to compiling? Or do I have to go for separate cpan_home directories?
Note that I tried perlbrew first but it failed with Can't load '../lib/auto/IO/IO.so' for module IO: ../lib/auto/IO/IO.so: wrong ELF class: ELFCLASS64 at ../lib/XSLoader.pm line 70. So instead of pursueing the issue I went for ActivePerl, which installs easily.

A: I have a dozen builds of Perl on my system, and they all use ~/.cpan. I have never had a problems, but I cannot say that it is safe. It depends on the settings therein. Specifically,

*

*build_dir_reuse should (probably) be zero.

*makepl_arg shouldn't contain INSTALL_BASE.

*mbuildpl_arg shouldn't contain --install_base.

"Install base" overrides where the modules are installed. If you start installing the modules for all your builds in one location, you will have problems due to incompatibilities between versions, releases and builds of Perl.
If you want to share .cpan and have a local install directory, you can probably get away with using PREFIX=/home/username/perl5 LIB=/home/username/perl5/lib instead of INSTALL_BASE=/home/username/perl5. It uses a smarter directory structure.
By the way, local::lib causes "install base" to be used, so you'll run into problems if you use local::lib with multiple installs of Perl.


Q: Get object property stored in listview from another page wpf This is my class :
class Discussion
{
    public String name {get; set;}
    public String discussionId { get; set; }
    public List<Message> liste {get; set;}

    public Discussion(String name, String discussionId)
    {
        this.name = name;
        this.discussionId = discussionId;
    }

I create some instance of this class and I store them in a listview.
When I double click on a listViewItem (it only show the name property), I navigate to another page that need to know the discussionId.
How can I get this property ?
This is how I navigate to the new page :
public partial class DiscussionPage : Page
{
    public DiscussionPage()
    {
        InitializeComponent();

        try
        {
            SqlDataReader read = Broker.sqlcommand("SELECT DISCUSSION.TITRE, USER1.NOM FROM dbo.DISCUSSION, dbo.USER1 WHERE USER1.ID = DISCUSSION.ID_CREER;").ExecuteReader();
            while (read.Read())
            {
                Discussion d = new Discussion(read["TITRE"].ToString(), read["NOM"].ToString());
                listDiscussion.Items.Add(d);
            }
        }
        catch (Exception)
        {

            throw;
        }
    }

    private void ListView_MouseDoubleClick(object sender, MouseButtonEventArgs e)
    {
        DependencyObject clickedObj = (DependencyObject)e.OriginalSource;

        while (clickedObj != null && clickedObj != listDiscussion)
        {
            if (clickedObj.GetType() == typeof(ListViewItem))
            {
                Discussion selectedDiscussion = (Discussion)listDiscussion.SelectedItem;
                this.NavigationService.Navigate(new MessagePage(selectedDiscussion));
                break;
            }
            clickedObj = VisualTreeHelper.GetParent(clickedObj);
        }
    }

    private void openAddDiscussion(object sender, RoutedEventArgs e)
    {
        addDiscussion add = new addDiscussion();
        add.Show();
    }
}

I need to know discussionId to load the content of this page :
public partial class MessagePage : Page
{
    public MessagePage(Discussion SelectedDiscussion)
    {
        InitializeComponent();
        try
        {
            SqlDataReader read = Broker.sqlcommand("SELECT MESSAGE.TEXT FROM dbo.MESSAGE WHERE MESSAGE.ID_POSSEDER = \'" + SelectedDiscussion.discussionId + "\'").ExecuteReader();
            while (read.Read())
            {
                Message m = new Message(read["TEXT"].ToString());
                showMessage.Items.Add(m);
            }
        }
        catch (Exception)
        {
            throw;
        }
    }
}

Full code added, still don't work with SelectedValue:

incoherent Accessibility: parameter type 'commApp.Classes.Discussion' is less accessible than method 'commApp.MessagePage.MessagePage (commApp.Classes.Discussion)'

A: Without a good, minimal, complete code example, it's impossible to know for sure what the best approach is.
However, if you have set your ListView up correctly and the ItemsSource is a collection of Discussion objects, then by default the SelectedValue property will return the Discussion object instance reference that corresponds to the selected item in the list.
In that case, you would just change your code to look like this:
private void ListView_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
    DependencyObject clickedObj = (DependencyObject)e.OriginalSource;

    while (clickedObj != null && clickedObj != listDiscussion)
    {
        if (clickedObj.GetType() == typeof(ListViewItem))
        {
            Discussion selectedDiscussion = (Discussion)listDiscussion.SelectedValue;
            this.NavigationService.Navigate(new MessagePage(selectedDiscussion));
            break;
        }
        clickedObj = VisualTreeHelper.GetParent(clickedObj);
    }
}

I.e. just use the SelectedValue property instead of SelectedItem. If you have deviated from the default by setting the SelectedValuePath property, then you will want to use the ItemContainerGenerator object to get the correct reference:
private void ListView_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
    DependencyObject clickedObj = (DependencyObject)e.OriginalSource;

    while (clickedObj != null && clickedObj != listDiscussion)
    {
        if (clickedObj.GetType() == typeof(ListViewItem))
        {
            Discussion selectedDiscussion =
                (Discussion)listDiscussion.ItemContainerGenerator
                    .ItemFromContainer((ListViewItem)listDiscussion.SelectedItem);

            this.NavigationService.Navigate(new MessagePage(selectedDiscussion));
            break;
        }
        clickedObj = VisualTreeHelper.GetParent(clickedObj);
    }
}

If neither of those seem to apply in your case, please edit your question so that it includes a good code example, with which a better answer can be provided.


Q: Oracle SQL - Return rows with a value based on multiple values in a second field I need to return the rows that contain the employee names (in one field) who are only classified as Managers (not as Workers, or as Managers and Workers).
Managers and Workers values are in a second field.
So it might look like this:
+----------+------------+
| 'Miller' |  'Manager' |
| 'Jones'  |  'Manager' |
| 'Jones'  |  'Worker'  |
+----------+------------+

In this instance I just want it to return 'Miller'.
I can get one or both, but not the ones where an employee is only classified as a Manager.
Any thoughts?

A: One method uses aggregation:
select name
from t
group by name
having min(classification) = max(classification) and min(classification) = 'manager';

A: Method with a subquery which should work well when there are not only 'Managers' and 'Workers' in the table:
SELECT t1.name FROM t t1
WHERE
    t1.classification='Manager'
    AND NOT EXISTS (
        SELECT 1 FROM t t2 WHERE t1.name=t2.name AND t2.classification='Worker'
    )

A: Count the number of titles. If they have a title of 'Manager' and there's only one title, select the individual:
SELECT *
  FROM PEOPLE p
  INNER JOIN (SELECT NAME, COUNT(TITLE) AS TITLE_COUNT
                FROM PEOPLE
                GROUP BY NAME) c
    ON c.NAME = p.NAME
  WHERE p.TITLE = 'Manager' AND
        c.TITLE_COUNT = 1;

dbfiddle here