text:
Q: Property 'subscribe' does not exist on type 'OperatorFunction' I'm trying to get some data from mongodb, and keep getting this error:

Property 'subscribe' does not exist on type 'OperatorFunction'

//app.component.ts
import { Component } from '@angular/core';
import {FormGroup, FormControl, Validators, FormsModule} from '@angular/forms';
import {CommonService} from './common.service';
import {Http, Response, Headers, RequestOptions} from '@angular/http';
import { Observable } from 'rxjs/Observable';
import { map } from 'rxjs/operators';
import { from } from 'rxjs';

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
})
export class AppComponent {

    constructor(private newService: CommonService) {
    }

    Repdata;
    valbutton = "Save";

    ngOnInit() {
        this.newService.GetProcesses().subscribe(data => this.Repdata = data);
    }
}

//common.service.ts

import { Injectable } from '@angular/core';
import {Http, Response, Headers, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import { map, tap } from 'rxjs/operators';
import 'rxjs/add/operator/do';
import 'rxjs/Rx';
import { catchError } from 'rxjs/operators';

@Injectable()
export class CommonService {

    constructor(private http: Http) { }

    GetProcesses(){
        return this.http.get('http://localhost:4000/getProcesses/')
                   .pipe(map((response: Response) => response.json())),
            catchError(error => Observable.of(null))

    }
}

Property 'subscribe' does not exist on type 'OperatorFunction'

A: It seems you have a misplaced parenthesis in your common.service.ts file.
I made this code snippet for you to try it out, hope it does what you need
// common.service.ts
import {Injectable} from '@angular/core';
import {Http, Response} from '@angular/http';
import {Observable} from 'rxjs/Observable';
import {catchError, map} from 'rxjs/operators';
import 'rxjs/add/operator/do';
import 'rxjs/Rx';

@Injectable()
export class CommonService {

    constructor(private http: Http) {
    }

    GetProcesses() {
        let url = 'http://localhost:4000/getProcesses/';
        return this.http.get(url).pipe(
            map((response: Response) => response.json()),
            catchError(error => Observable.of(null))
        );
    }
}


text:
Q: PnP powershell provisioning gives 401 error with tenant-scope (fullcontrol) app permissions I want to create a new sitecollection with PnP Powershell and created an App with /_layouts/15/appregnew.aspx and granted permissions with: /_layouts/15/appinv.aspx.
This is my permission request xml:
<AppPermissionRequests AllowAppOnlyPolicy="true">
    <AppPermissionRequest Scope="http://sharepoint/content/tenant" Right="FullControl" />
</AppPermissionRequests>

The script is basically:
Connect-PnPOnline -Url $tenantAdminUrl -AppId $AppID -AppSecret $AppSecret

New-PnPTenantSite -Title "title" -Url $newSitename -Owner $adminUser -TimeZone 4 -Force -Wait -Template "STS#0"

Errormessage is:
New-PnPTenantSite : Der Remoteserver hat einen Fehler zurückgegeben: (401) Nicht autorisiert.
In C:\Users\xxx\script.ps1:112 Zeichen:4
+ New-PnPTenantSite -Title $projectItem["Title"] -Url $newS ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : WriteError: (:) [New-PnPTenantSite], WebException
+ FullyQualifiedErrorId: EXCEPTION,SharePointPnP.PowerShell.Commands.NewTenantSite

Tenant scope and FullControl but i get 401 error? How can i get the app permissions to deploy sitecollections?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Its possible to see the sql query that we are doing in browser? i have a basic doubt.
i have this example:
$sql = mysql_query("SELECT * FROM admin where id =  username='$username' and password = '$password' LIMIT 1");

Its possible to see what this sql command is doing in the browser? To see if it is correct..
Thanks.

A: $a = "SELECT * FROM admin where id =  username='$username' and password = '$password' LIMIT 1";
echo $a;
$sql = mysql_query($a); // use mysqli instead

A: if you will print the $sql it will print #resurce #4
you need to do:
$q = "SELECT * FROM admin where id =  username='$username' and password = '$password' LIMIT 1";

print_r($q);

and you see it in the network tab on the console or in the browser if you print your request


text:
Q: Compare two rows, write comment in third row if match I have a google sheet that is collecting the entries from a google form. I have two columns full of email addresses. I need to compare them and if the email from list A is found in list B as well, then I want to write "paid" in a third column, next to the email of list/column B. If the email in list A isn't found in list B then "unpaid" should appear instead.
I'm an absolute beginner and would be very thankful for simple answers.

A: you can use formulas to do this. The formula given below tries to find the match of A2 cell in the B2:B Range with match() formula and if the match is obtained then it add the "paid" string else adds "unpaid"
=IF(ISERROR(MATCH(A2,B$2:B,0)),"unpaid","paid")

this is what I get:

A: You could use an ArrayFormula.
=ArrayFormula(if(A:A, if(A:A=B:B, "PAID", "UNPAID"),""))

The advantage is that when new Google Form submissions are added to the Google Sheet, the cell value will be computed automatically for the new row.

error here as well:


text:
Q: How to find the script src link?(Beautiful Soup) tags = [{tag.name: tag.text.strip()} for tag in soup.find_all('h2')]

This returns as:
[{'h2':'My'},{'h2':'hey'}] # Returns all the h2 elements with their content.

Now I want all the links that are inside the <script src =''>  in the above format.
Suppose, For the HTML code,
<script src="https://apis.google.com/_/scs/abc-static/_/js/k=gapi.gapi.en.hvE_rrhCzPE.O/m=gapi_iframes,googleapis_client/rt=j/sv=1/d=1/ed=1/rs=AHpOoo-98F2Gk-siNaIBZOtcWfXQWKdTpQ/cb=gapi.loaded_0" nonce="" async=""></script>

The result should be
#Both Acceptable

[{'script':'https://apis.google.com/_/scs/abc-static/_/js/k=gapi.gapi.en.hvE_rrhCzPE.O/m=gapi_iframes,googleapis_client/rt=j/sv=1/d=1/ed=1/rs=AHpOoo-98F2Gk-siNaIBZOtcWfXQWKdTpQ/cb=gapi.loaded_0'}]

OR

[{'script src':'https://apis.google.com/_/scs/abc-static/_/js/k=gapi.gapi.en.hvE_rrhCzPE.O/m=gapi_iframes,googleapis_client/rt=j/sv=1/d=1/ed=1/rs=AHpOoo-98F2Gk-siNaIBZOtcWfXQWKdTpQ/cb=gapi.loaded_0'}]

A: You just need to change the tag you are finding from h2 to script. Then instead of getting the text of that element with tag.text, you are wanting the attribute value in the syntax of tag['attribute name']. So something like:
tags = [{tag.name: tag['src']} for tag in soup.find_all('script')]


text:
Q: "User-defined type not defined" error with button only, no code errors Issue:
When I click a macro assigned button in my workbook the following error appeared:

"User-defined type not defined"

The error box appears, however, it did not highlight any code that may have produced the error. When I ran the macro from the compiler, the code executed without error. I was able to figure out that when I inserted a new button and assigned the same macro to the new button, the code executed without error.
Facts about the workbook:

*

*The workbook includes multiple macros and multiple sheets as well as buttons linked to most of the macros (6 buttons)

*The workbook is saved daily with a new date as modifications are made. The same button in previous workbooks do not produce this error.

*There was an issue with one button a month ago and it was replaced, now a different button has this same issue. I would like to avoid replacing buttons every time this error occurs as I am not the end user.

*This workbook was originally created in Excel 2010 but I have been using it in Excel 2013, though I made the switch months before this issue (not sure if info is relevant).

I saw a similar issue here, however the issue for me is not in my code, only in the form control. I would just like to know if anyone has seen this before and if there is a way to avoid needing to replace the buttons every time they "go bad."


text:
Q: lua string printing In C, I have format strings, something like:
char *msg = "wlll you marry me"
fprintf(stderr, "%s, %s?", name, msg);

Now, can I do something similar in lua with format strings? I.e. I want something functionally equivalent to:
name .. ", " .. msg .. "?"

but not so ugly, in lua.
Okay, so I can do string.format("%s, %s?", name, msg), but can I go even a step further, something like perl style, where I can go:
"%name, %msg?"

Thanks!

A: According to the Lua Users Wiki article on String Interpolation, Lua does not offer a built-in native way to do this; however, there are a couple sort-of workarounds posted on that page.

Here's one simple implementation (-- RiciLake):
function interp(s, tab)
  return (s:gsub('($%b{})', function(w) return tab[w:sub(3, -2)] or w end))
end
print( interp("${name} is ${value}", {name = "foo", value = "bar"}) )

getmetatable("").__mod = interp
print( "${name} is ${value}" % {name = "foo", value = "bar"} )
-- Outputs "foo is bar"

A:
Can I do something similar [to printf] with Lua format strings?

Yes. I do this all the time:
local function printf(...) return io.stdout:write(string.format(...)) end

local function fprintf(f, ...) return f:write(string.format(...)) end

Modify to taste.


text:
Q: AWT Frame does not handle events The frame opens and close normally but mouse click doesn't work.
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

//Create a frame window that responds to mouse click
public class AWT3 extends Frame {
    String Mmsg="";
    int mouseX=0, mouseY=0;

    public AWT3() {
        addWindowListener(new MyWindowwAdapter(this));
        addMouseListener(new MyMouseeAdapter(this));
    }

public void paint(Graphics g){
        g.drawString(Mmsg, mouseX, mouseY);
    }

public static void main(String args[]){
    AWT3 awt3 = new AWT3();
    awt3.setSize(new dimension(500, 500));
    awt3.setTitle("Window framee");
    awt3.setVisible(true);
    }
}

class MyWindowwAdapter extends WindowAdapter{
    AWT3 awt3;
    public MyWindowwAdapter(AWT3 awt3) {
        this.awt3=awt3;
    }
    public void windowClosing(WindowEvent we){
        awt3.setVisible(false);
    }
}

class MyMouseeAdapter extends MouseAdapter{
AWT3 awt3;
public MyMouseeAdapter(AWT3 awt3) {
    this.awt3=awt3;
}
public void MouseClicked(MouseEvent me){
    awt3.Mmsg="the mouse is clicked";
    awt3.mouseX= me.getX();
    awt3.mouseY=me.getY();``
    awt3.repaint();
}
}

A: From what it looks like, this code won't compile. You have an error that you need to fix:
awt3.setSize(new dimension(500, 500));

to
awt3.setSize(new Dimension(500, 500));

and add the proper import java.awt.Dimension as pointed out by others.
Another mistake is that MouseClicked(MouseEvent me) is not overriding the super class method from MouseAdapter as its syntactically wrong (super class method starts with small case). Change it to mouseClicked(MouseEvent me) (add the optional @Override annotation if you wish).

A: The method name should be public void mouseClicked(MouseEvent me)
instead of public void MouseClicked(MouseEvent me).

A: mouseClicked() is when the mouse button has been pressed and released.
mousePressed() is when the mouse button has been pressed.
Your code is working. tested on java 1.7. only the problem I saw, was with out importing the java.awt.Dimension class you are trying to create a new dimension(500, 500); although the class name is in simple form you can fix this error and try the code.


text:
Q: timeout hover delay on hover different div I am trying to make the first square box onhover, then show the bigger box a little bit delay then when I move the mouse hover the big box, the big box still appears.However, my code works incorrectly.
If someone could please help me out? Thanks
Sample http://jsfiddle.net/9oLs3fyh/
    var timeout;
$("#box1").hover(function () {
    clearTimeout(timeout);
    $("#box2").delay(500).show();
}, function () {
    timeout = setTimeout(function(){
      $("#box2").delay(500).hide();
    },500);
});

if($("#box2").is(':hover')){
$("#box2").show();
}

A: var timeout;
$("#accountIcon").hover(function () {
    clearTimeout(timeout);
    $("#accountPopup").delay(500).show(500);
}, function () {
    setTimeout(function(){
      $("#accountPopup").delay(500).hide(500);
    },500);
});

if($("#accountPopup").is(':hover')){
$("#accountPopup").show();
}

DEMO
I think this is a good way to achieve that by wrap your divs inside one div

.conatiner{
    overflow:hidden;
}

var timeout;
$(".conatiner").hover(function () {
    clearTimeout(timeout);
    $("#accountPopup").delay(500).show(500);
}, function () {
    setTimeout(function(){
      $("#accountPopup").delay(500).hide(500);
    },500);
});

DEMO HERE
and while you use hover .. you can just use css with visibility and transition delay

.conatiner:hover #accountPopup{
   display: block;
   -webkit-transition-delay: 1s; /* Safari */
   transition-delay: 1s;
}

DEMO

A: Try assiging class hovered (check the DEMO):
CSS
.hovered { display:block }

On mouseenter of #accountIcon assign class hovered on #accountPopup element.
Then, on mouseleave, if the target element (#accountPopup) is not visisble, just remove the class.
$('#accountIcon').on('mouseenter', function() {
    $('#accountPopup').addClass('hovered');
}).on('mouseleave', function() {
    var target = $('#accountPopup');
    if (!target.is(':visible')) {
        target.removeClass('hovered');
    }
});
$('#accountPopup').on('mouseleave', function() {
    $(this).removeClass('hovered');
});


text:
Q: Play video stored on a database I am trying to play a video that I have stored on a database using the BLOB format. I am using PHP to connect to the database. So far, this is the script that I have managed to come up with, what do I do to play the video?
<!DOCTYPE html>
<html>
<body>
<video width="420" height="345" controls>
<source src="C:\Users\Administrator\Downloads\AustralianOpen.mp4" type="video/mp4">
</video>

<?php
$username="root";
$password="mysql";
$database="test";
mysql_connect('localhost', $username, $password) or die("Not able to connect to localhost");
mysql_select_db($database) or die("Unable to select DB");

if(($result=mysql_query('Select data from media'))!=false)
{
    header('Content-Type: video/mp4');
    print $result->fetch(PDO::FETCH_COLUMN);
} else
{
    die("Video no connecting");
}
?>

</body>
</html>

A: Storing videos in a database is a pretty bad idea because of the file sizes involved. In this case, what's happening is fetch() transfers the whole content from the database buffer into PHP's memory, from which it is then echo'd. This means you need to fit the whole video into memory at once, and it needs to be transferred out to the web server before PHP's time limit is up. This may work for very small videos, but not for any video of a length worth watching.
Some databases like Postgres allow you to open a file handle to content in the database, which you could then dump directly to the client with fpassthru; that's more efficient memory wise, but will still require PHP to run the entire time the client is streaming the video. I'm also not sure whether MySQL supports that, never used it.
Last but not least, you can't just dump the video data in the middle of an HTML file.
Not to mention that for some reason you're mixing all sorts of database API syntax which doesn't belong together.
Overall, this is a bad approach. You should go back to serving video files stored on disk, which the web server can handle by itself.


text:
Q: iis 8 website not opening I have create new web site in IIS 8. I have configured my web site like this
http://ip:8080/

When I browse it from any public network it is not opening. But If I open is locally it works fine. http://localhost:8080 it is working fine. What I tried I stop all other sites, Default Web site and assign 80 port to my site then it is working fine in locally as well as publically. I don't know what is the issue.

A: Clearly you have a firewall or other network routing issue. Check all configured firewalls on your server/housing machine, as well as along your network path (router, or other perimeter network devices)
Also if trying to connect through your internet side IP you will want to check any port forward rules on your router (If behind NAT, like most connections are)

A: My problem is solved. I have opened a 8080 port on Azure management portal. And on VM I have create new rule which points to this port.


text:
Q: How do I use an IE session after intercepting it with VB.NET I apologise that this has been covered before in previous posts but I feel they may be a bit out of date as the current iterations of VB.Net do not use the Set option anymore.
I have been trying to work around this to figure it out but have been really struggling.
My problem: I have a application I am building to automate some tedious tasks. This involves multiple IE sessions which I have working in their own webbrowser controls. One of them however I get to a point then it wants to launch a popup in a new Internet explorer window. I have been toying with using the newwindow event to try and play with it but have had no success.
Below is the code I am trying to use to capture the popup window:
Shared Function IEWindowFromTitle(sTitle As String) As SHDocVw.InternetExplorer

    Dim objShellWindows As New SHDocVw.ShellWindows
    Dim win As Object, rv As SHDocVw.InternetExplorer

    For Each win In objShellWindows
        If TypeName(win.Document) = "HTMLDocument" Then
            If UCase(win.Document.Title) = UCase(sTitle) Then
                rv = win
                Exit For
            End If
        End If
    Next

    IEWindowFromTitle = rv

End Function

I am trying to call it with:
    Shared Sub thissubmakesmeasadpanda()

    Dim w As SHDocVw.InternetExplorer
    w = IEWindowFromTitle("Address Search")
    If Not w Is Nothing Then
        Debug.WriteLine(w.Document.Title)
    Else
        Debug.WriteLine("Not found")
    End If

End Sub

I seem to be getting an error when I run this though the error being:

An unhandled exception of type 'System.Runtime.InteropServices.COMException' occurred in Microsoft.VisualBasic.dll
Additional information: Unspecified error (Exception from HRESULT:
  0x80004005 (E_FAIL))

I am at a bit of a loss at this point after trying to follow a number of different posts on here most recently How to intercept and manipulate a Internet Explorer popup with VBA
and
Get IE window object by window title with VBA
There are a few tasks that will need to be completed at the end of this such as filling information into a text box and then clicking a search button, and clicking a result.
when you click the result however it comes up with a confirmation box which is not an ie window I would describe it more like being a msgbox type element that asks to confirm importing the details. Once you click ok the actions taken in the popup window then are meant to download into the webcontrol that launched the new browser.
Please note I have built the application up until this point and when I manually do the tasks it works. I tried using the newwindow event to open a new form with a browser and navigate it to the target URL however when I manually filled the text boxes and did the clicks nothing was sent back to the original webbrowser control.
Any help is greatly appreciated. The website I am trying to work with is an internal one so not something I can freely share.


text:
Q: Steam starts downloading updates while in-game and ignores throttling limit I play CS:GO fairly often and that game really requires you to pretty much have a 60 or below ping to be playable. Now, my internet isn't great, but I can usually get that - 30s to 60ish ping range.
However, recently Steam has decided that it is going to ignore my setting for no updates while in-game and my throttling limit that I set!
I'll be paying, and all of a sudden my ping will shoot above 120, making play all but impossible.
The really weird thing is that the games in the queue the "require updating" are seemingly not downloading:

and my Settings > Downloads:

Right now the only way I can stop it from doing this is by quiting out of Steam entirely - something that's very bad for competitive CS:GO. And then it will just start doing it again a bit later.
Is this a known Steam bug or do I have something new? Or, preferably, how do I fix this?

A: You can disable the download inside steam while your playing. This can be activated in your options. I would suggest to enable this option always. You'll forget it otherwise on MP games. ;-)


text:
Q: How do I pass in an array of multiple select? I use serialize(), but the data is not transmitted in the same array.
function tableoptionmain() {

var msg   = $('#list-optionform').serialize();
$.ajax({
    type: 'POST',
    async: true,
    url: 'includes/parts/list/table/main-check.php',

    data: msg,

    beforeSend: function() {
        $('#listtable-parent').empty().html('');
    },
    success: function(data) {
        $('#listtable-parent').empty().html(data);
    }
});
};

I have something like this:
name1: data1
name1: data2

I want to get something like this:
name1: data1, data2

How can I achieve this?
EDIT
HTML like this
<form method="" id="list-optionform">
<select name="name1" multiple="multiple" id="name1">
  <option value="data1">data1</option>
  <option value="data2">data2</option>
  <option value="data3">data3</option>
</select>
btn
</form>

if you select multiple options php get only the last option

A:     function tableoptionmain() {

    var msg   = $('#list-optionform').serialize();
        console.log(msg);
       // split the message string by &
        var arr = msg.split("&");
        console.log(arr);

        var str = "name1 : ";
        var len = arr.length;

        for(var  i= 0;i < len ; i++){
        // split each individual arr element by =
            var temp = arr[i].split("=");
            // add data to str
            str+= temp[1]+" , ";
        }
        // remove the last ,
        str = str.slice(0,str.lastIndexOf(" , "));
        console.log(str);

   ...  rest of the code including ajax call
    }


text:
Q: What is the compatible version for spring-data-dynamodb and spring boot I am getting this warning as the server started.
INFO 13868 --- s.DynamoDBRepositoryFactory  : Spring Data Version:          2.3.7.RELEASE
INFO 13868 --- s.DynamoDBRepositoryFactory  : AWS SDK Version:              1.11.64
INFO 13868 --- s.DynamoDBRepositoryFactory  : Java Version:                 11.0.7 - Java HotSpot(TM) 64-Bit Server VM 11.0.7+8-LTS
INFO 13868 --- s.DynamoDBRepositoryFactory  : Platform Details:             Windows 10 10.0
WARN 13868 --- s.DynamoDBRepositoryFactory  : This Spring Data DynamoDB implementation might not be compatible with the available Spring Data classes on the classpath!

https://github.com/boostchicken/spring-data-dynamodb
This is the gradle dependency.
plugins {
    id("org.springframework.boot") version "2.4.3"
    id("io.spring.dependency-management") version "1.0.11.RELEASE"
    id("com.google.cloud.tools.jib") version "2.7.1"
    id("com.github.jk1.dependency-license-report") version "1.16"
    id("java")
}

java.sourceCompatibility = JavaVersion.VERSION_11

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'com.amazonaws:aws-java-sdk-dynamodb:1.11.970'
    //implementation 'com.github.derjust:spring-data-dynamodb:5.1.0'
    implementation 'io.github.boostchicken:spring-data-dynamodb:5.2.5'
    compileOnly 'org.projectlombok:lombok'
    developmentOnly 'org.springframework.boot:spring-boot-devtools'
    annotationProcessor 'org.projectlombok:lombok'
    testImplementation('org.springframework.boot:spring-boot-starter-test') {
        exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
    }
}

As I use @DynamoDBRangeKey on top of get method, i am getting ClassNotFoundException.  Server is not started.  If i do not use @DynamoDBRangeKey, server is stated properly.
But i have to use @DynamoDBRangeKey to specify the range key.
@DynamoDBTable(tableName = "partner_signup")
public class PartnerSignup {

    @Id
    //@DynamoDBIgnore
    private ProductSignupId productSignupId;

    private String partnerId;
    private String partnerType;

    //@DynamoDBAttribute(attributeName = "partner_type")
    @DynamoDBRangeKey(attributeName = "partner_type")
    public String getPartnerType() {
        System.out.println(" partner_type    " + productSignupId.getPartnerType());
        return productSignupId != null ? productSignupId.getPartnerType() : null;
    }
}

Caused by: java.lang.ClassNotFoundException: org.springframework.data.repository.core.support.ReflectionEntityInformation
    at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:581) ~[na:na]
    at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178) ~[na:na]
    at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521) ~[na:na]

Anything i need to add or modify in the dependency? What will be the compatible version of Spring Data DynamoDB and Spring Boot.

A: On the GitHub page is a table with versions and compatibility: https://github.com/boostchicken/spring-data-dynamodb


text:
Q: How to set stack size of main Thread In case of java we have JVM parameter -Xss which sets the stack Size for a particular Thread.
We can set this parameter as JVm argument or specify it in Thread Constructor like:-
Thread(ThreadGroup group, Runnable target, String name, long stackSize)

This will allocate a new Thread object so that it has target as its run object, has the specified name as its name, and belongs to the thread group referred to by group, and has the specified stack size.
But how to set the stack size of main method which is running. Ideally main method is also in itself a thread , so how do we specify its stack size explicitly apart from using -Xss parameter ?

A: -Xss is exactly the way to do it. It tells the runtime exactly the long stackSize parameter to use when creating your main thread.
However, you can't change the stacksize of already existing threads, so the only thing you can do is to create your own "main" thread! Remember, the ordinary "main" thread is not special in anything. Just fire up another thread and let it run your main program, then finish the JVM-main thread.

A:
But how to set the stack size of main method which is running. Ideally main method is also in itself a thread , so how do we specify its stack size explicitly apart from using -Xss parameter ?

The -Xss parameter affects the main stack size as well.  You don't need to do anything special to set it.  If you really asking if you can set the main stack size separate from the -Xss parameter, you can't.
For example, you can set the -Xss parameter and see more or less stack overflow exception lines:
public class Foo {
    public static void main(String[] args) {
        foo();
    }
    private static void foo() {
        foo();
    }
}

-Xss=128k gives ~444 lines while 256k gives ~1025 lines.

A:
how do we specify [main thread's] stack size explicitly apart from using -Xss
  parameter ?

You can't.  It needs to be specified on thread creation and the only way to do that is with jvm args.

A: main thread is user thread, but a special thread. Stack size can not be specified for main thread individually. Either you specify -Xss for all threads or for a particular thread on creation.
Note possible for main, as this is not created by user but by JVM.


text: Q: How to create geojson file from an existing json file I have a json file which contains a location field which has geolocation ID of certain locations. What I want to do is to extract those geolocation fields and create a separate geojson file. Is there any way I can accomplish this task. This is the API url for JSON file >> https://search.worldbank.org/api/v2/projects?format=json&countryshortname_exact=India&source=IBRD&kw=N&rows=1


text:
Q: Adding a loop to my game I have a game that's running perfectly. I want to put a line of code that asks the player if they want to play again at the end of the game. I would also like to keep a score system for every player and computer win.
I'm having trouble with the input = Integer.parseInt(sc.nextInt()); line
import java.util.Scanner;

public class Sticks {

    public static boolean whoStart(String choice) {
        int ran = (int) (Math.random() * 2 + 1);

        String ht = "";
        switch (ran) {
            case 1:
                ht = "head";
                break;
            case 2:
                ht = "tails";
        }
        if (ht.equals(choice.toLowerCase())) {
            System.out.println("you start first");
            return true;
        } else {
            System.out.println("computer starts first");
            return false;
        }
    }

    public static int playerTurn(int numberOfSticks) {
        System.out.println(" \nthere are " + numberOfSticks + " sticks ");
        System.out.println("\nhow many sticks do you wanna take? 1 or 2?");
        Scanner in = new Scanner(System.in);
        int sticksToTake = in.nextInt();
        while ((sticksToTake != 1) && (sticksToTake != 2)) {
            System.out.println("\nyou can only take 1 or 2 sticks");
            System.out.println("\nhow many sticks do you wanna take?");
            sticksToTake = in.nextInt();
        }
        numberOfSticks -= sticksToTake;
        return numberOfSticks;
    }

    public static int computerTurn(int numberOfSticks) {
        int sticksToTake;
        System.out.println("\nthere are " + numberOfSticks + " sticks ");
        if ((numberOfSticks - 2) % 3 == 0 || (numberOfSticks - 2 == 0)) {
            sticksToTake = 1;
            numberOfSticks -= sticksToTake;
        } else {
            sticksToTake = 2;
            numberOfSticks -= sticksToTake;
        }
        System.out.println("\ncomputer took " + sticksToTake + " stick ");
        return numberOfSticks;
    }

    public static boolean checkWinner(int turn, int numberOfSticks) {

         int score = 0;
         int input;
         int B = 1;
         int Y=5, N=10;

        if ((turn == 1) && (numberOfSticks <= 0)) {
            System.out.println("player lost");
            return true;
        }
        if ((turn == 2) && (numberOfSticks <= 0)) {
            System.out.println("player won");
            score++;
            return true;
        }

        System.out.println("Your score is "+ score);
        System.out.println("Do you want to play again? Press (5) for Yes / (10) for No");

        // ----- This line -----
        input = Integer.parseInt(sc.nextInt());

        if (input == Y) {
          B = 1;
          System.out.println("Rock, Paper, Scissors");
        } else if (input == N) {
            System.exit(0);
            System.out.println("Have A Good Day!");
        }
    }

    public static void main(String args[]) {
        int turn;
        int numberOfSticks = 21;
        Scanner in = new Scanner(System.in);
        System.out.println("choose head or tails to see who starts first");
        String choice = in.next();
        if (whoStart(choice) == true) {
            do {
                turn = 1;
                numberOfSticks = playerTurn(numberOfSticks);
                if (checkWinner(turn, numberOfSticks) == true) {
                    break;
                };

                turn = 2;
                numberOfSticks = computerTurn(numberOfSticks);
                checkWinner(turn, numberOfSticks);
            } while (numberOfSticks > 0);
        } else {
            do {
                turn = 2;
                numberOfSticks = computerTurn(numberOfSticks);
                if (checkWinner(turn, numberOfSticks) == true) {
                    break;
                };
                turn = 1;
                numberOfSticks = playerTurn(numberOfSticks);
                checkWinner(turn, numberOfSticks);
            } while (numberOfSticks > 0);
        }
    }
}

A: The title of your question almost answered you what you need to add: a loop!
I suggest you to refactor your function main and extract all your game logic from it to be stored within a dedicated function for the sake of the readability. Let's call it startGame().
Your main is going to become shorter and can represent a good location to introduce this loop, such as:
public static void main(String[] a) {
    boolean isPlaying = true;
    Scanner in = new Scanner(System.in);

    while(isPlaying) {
        startGame();

        // Your message to continue or stop the game
        if(in.next().equalsIgnoreCase("No")) {
            isPlaying = false;
        }
    }
}

I recommend you to use a boolean that is checked in your while loop rather than using a break statement, as it brings a better control flow in your application.

A: Just put everything in a while(true) loop and use a break; if they choose no. Something like:
static int playerPoints = 0;

public static void main(String args[]) {
    int turn;
    int numberOfSticks = 21;
    Scanner in = new Scanner(System.in);
    while(true){

        ...

        System.out.println("You have " + playerPoints + " points!")
        System.out.println("Do you want to play again?");
        if (!in.nextLine().toLowerCase().equals("yes")){
            break;
        }
    }
}

Edit: ZenLulz's answer is better than this one, mainly because it encourages better programming practice. Mine works but isn't the best way to solve the issue.


text:
Q: Obtener los 5 últimos valores de un array en javascript Tengo un array:
aNumeros=[1, 5, 6, 7, 8, 9, 10, 12];

quiero crear otro array a partir de ese, que contenga los 5 ultimos numeros:
aNuevo= [7, 8, 9, 10, 12]

gracias de antemano

A: Lo puedes hacer utilizando la función splice, pasando como parámetro la posición desde donde quieres recortar.

let aNumeros=[1, 5, 6, 7, 8, 9, 10, 12];
let aNuevo = aNumeros.slice(aNumeros.length-5)
console.log(aNuevo)

En este caso como posición de inicio le pasamos la longitud del array(aNumeros) y le restamos 5, por lo cual siempre buscaremos los 5 últimos.

Si no hay posición de final, nos dejara  un nuevo array con los elementos desde la posición inicio y hasta el final.

Hecha un vistazo a la documentación, para ver como funciona mas detalladamente
 https://developer.mozilla.org/es/docs/Web/JavaScript/Referencia/Objetos_globales/Array/splice

A: Con el fin de dar respuesta a tu inquietud te comparto el siguiente segmento de código, espero te sea de utilidad, saludos:
<script>
  // uso del evento ready de jQuery para generar el example requerido
  $(function() {

    // arreglo inicial (en orden aleatorio)
    var aNumeros=[1, 6, 5, 8, 7, 9, 12, 10];

    // impresion de arreglo inicial
    console.log("aNumeros: " + aNumeros.toString());

    // arreglo ordenado usando function nativas de js
    var arrOrdenado = aNumeros.sort(function(a, b){return a - b});

    // impresion de arr ordenado
    console.log("arrOrdenado: " + arrOrdenado.toString());
    // uso de la function slice luego del ordenamiento para cortar

    var aNuevo = arrOrdenado.slice(arrOrdenado.length-5)
    // impresion del arr que requieres...
    console.log("aNuevo: " + aNuevo.toString());
    // fin de function ready de jQuery
  });
// fin de segmento de javascript
</script>

A: Una solucion similar a la de Eugeni Bejan, coloca -valor y te devolvera lo indicado, no es necesario obtener la longitud

let aNumeros=[1, 5, 6, 7, 8, 9, 10, 12];
console.log(aNumeros.slice(-5))


text:
Q: Excel: how to generate serial number every time when the adjacent column hits a new character I have an excel sheet like the following:
 name
 Pete
 CR
 123
 1255
 ... a couple rows of numbers
 Total
 Anna
 CR
 ... a couple rows of numbers
 Total
 Ann
 CR
 ...

What I would like to achieve is to generate an id number for each person and the resulting rows being blank and the ideal result will be like this:
 id     name
 1      Pete
        CR
        123
        1255
        ... a couple rows of numbers
        Total
 2      Anna
        CR
       ... a couple rows of numbers
       Total
 3     Ann
       CR

A: Step 1)  Insert a blank column to the left of your data column lets assume this makes Column A a blank column and column B your data list.
Step 2)  Fill in your header.  In cell A1 enter "id"
Step 3)  Enter the following formula in A2 and copy down.
=IF(B3="CR",COUNTIF($B$3:B3,"CR"),"")

It places an incremental number in column A in row above "CR" in column B.
Proof of concept:


text:
Q: SQL Server SQL Agent I'm looking to schedule some scripts from my SQL Server 2012 installation. I have installed the SQLManagementStudio_x64_ENU.exe from http://www.microsoft.com/en-us/download/details.aspx?id=43351, since that is the full version, not express.  It didnt install a Database Engine though. I went back and installed the SQLEXPR_x64_ENU.exe database engine only, but when I go to start the SQL Agent service, I get the error "The edition of SQL Server that installed this service does not support SQL Server Agent"
Did I use the wrong database engine? Or install in the wrong order?

A: While the first comment is correct. I believe you can schedule scripts from Windows Task Scheduler utilizing the sqlcmd utility even on SQL Server Express.


text:
Q: Printing a List of byte array from a webservice in a single job I'm trying to print to a thermal usb printer connected to a machine running windows, a list of commands received one by one from one webservice. The problem is that I need to create a single PrintJob with all data received, and not a job for every byte[] received. Here is my code:
...//communicated with webserver and received data using "message" variable

PrintService defaultPrintService = PrintServiceLookup.lookupDefaultPrintService();

System.out.println("Default printer: " + defaultPrintService.getName());

if (defaultPrintService != null) {
    sendMessage("connected"); //send message to the server to start receiving data to print
    DocFlavor flavor = DocFlavor.BYTE_ARRAY.AUTOSENSE;

        while (!message.contentEquals("done")) {
                try {
                    message = (String) in.readObject();

                    if (!message.contentEquals("done")) {
                        Doc doc = new SimpleDoc(message.getBytes(), flavor, null);
                        DocPrintJob job = defaultPrintService.createPrintJob();
                        job.print(doc, null);
                    }
                } catch (Exception e) {
                    // Handle exception
                    e.printStackTrace();
        }
}

What happens there is that windows create one printjob for each message received (ok, I knew that since the beginning) and this take minutes to print some lines.
The other problem is, if I print direct to the printer through network, it prints fine. Through USB, it just print some commands like line feed and paper cut, not the text (like it does via network).
What am I missing?
Thank you people!
UPDATE
I've concatenated all received strings into a single one, and them tried to print the getBytes() from that String. Now the printer prints fine, but again, some commands where not executed and the layout got messy and looks like charset got wrong, because accented chars are also not working


text:
Q: Why won't @override work? What is wrong with piece of code?
@Override
protected void onCreate(Bundle savedInstanceState) {

Eclipse states that @override cant be where it is.
It says that 'Bundle' is wrong.  I am lost.

A: it should be
 @Override public void onCreate(Bundle savedInstanceState){

 }

onCreate is public, not protected.

A: So maybe the problem is compiler compliance level: 1.5 instead of 1.6 ?
@Baleisen which level is set for your project?

A: I don't know much about the android framework but:
First make sure your class extends a Class such as (Activity) which contains onCreate. Then try to call super.onCreate, to double check that Class you are extending contains onCreate! You could be pointing to another class with the same name. Your compiler says that there is nothing to override, if you are sure it is wrong, then either your compiler is out dated or the framework.
    @Override
    protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            //yourCode
    }

Also if your extending and extended class, make sure, this method, I posted is in the class extending the class. It could freak out on this.

A: What your class extends ? And which android SDK version you're compiling ?

A: This has happened to me before and the problem was the Android SDK hadn't loaded into Eclipse fully.
Also, do you have this import in your file?  The parent onCreate method is in Activity.
import android.app.Activity;


text:
Q: How to import module into a python unit test I know this has been asked a lot of times, been looking at it for the last two hours and still can't figure it out. Would be very grateful for a solution to my actual problem rather than a link to someone else problem if possible.
Here goes...
/src
    /moduleA
        __init__.py
        messages.py
    /tests
        testA.py

messages.py
def get_messages(paramA):
    if paramA:
        return "A"
    else:
        return "B"

testA.py
import unittest
from moduleA import messages

My unit test will simply check whether A or B is returned from the get_messages(...) function.
As I understand it, moduleA is a module as it has an __init__.py file. VSCode does not complain about the from moduleA import messages line in my test however when I try to execute testA.py I get the following error message...
ImportError: No module named moduleA.
Also tried running it with python -m
Would be very grateful if someone can tell me what I'm doing wrong. I can change my file structure around if that would help. Perhaps the examples I've been reading are for Python 3 and I'm using 2.7?
Thanks.

A: Here's my suggestion on how to take care of this: ValueError: Attempted relative import in non-package not for tests package
So you'll need to add a __init__.py to your test directory, back up one directory to  src then run python -m test.testA and you should be good to go.
Also, once you see that to run successfully, you'll see that you have a syntax error in get_messages: you're missing a colon after else.

A: Firstly, we should check configuration before running the file.
Cross check with spaces like:
ENVIRONMENT=mock
PYTHONPATH=./src


text:
Q: How to add together numerical values that are stored in strings? I'm trying to add 1 to my JavaScript variable, but the following code doesn't give expected results:
var val1 = document.getElementById('<%= rng1.ClientID %>');
var val2 = val1.value + "1";
alert(val2.value);

How can I do this?

A: The simplest and also preferred way would be to use + to cast to a number.
Examples:
+'234'; // 234
+'042'; // 42! It does not convert to octal

In your case:
var val1 = +(document.getElementById('<%= rng1.ClientID %>').value); // () added just for the looks
var val2 = val1.value + 1; // if val1 is 5, val2 will be 6 hooray!
alert(val2); // just val2, since it's a plain number not an html input element

A: you can use the function parseInt() to transform the string stored in val1.value into a number:
var val2 = parseInt(val1.value) + 1;

Note that Number(val1.value) will also convert your value into a number.
-edit-
As yc suggest, is highly recommended to use parseInt(val1.value, 10) + 1; because if your string starts with a "0" the string is interpreted as octal. eg. parseInt("0123") == 83 and not 123

A: parseInt($('.scpContainer').height()+200)

A: you must add number, so try it without quotes :-)

A: In an external JavaScript file you can't use the <%=ControlID.ClientID %> to get the client id.
If there you using an external JavaScript file you need to pass client id value to that function.


text:
Q: LBNF, C function declaration / definition, reduce reduce conflict I'm trying to represent in LBNF that C/C++ function declarations have the following (approximate) form (<sym> denotes optionallity, and [rule] is a zero-or-more list):
type ident ( [type <id>] );

While function definitions have the form:
type ident ( [type id] ) { [stmt] }

Currently, I have the following LBNF:
entrypoints Program ;
Program.   Program ::= [TopDef] ;

FnDef.     TopDef ::= Type Ident "(" [Arg] ")" Block ;
FnDecl.    TopDef ::= Type Ident "(" [Par] ")" ";" ;
separator nonempty TopDef "" ;

Param.     Par ::= Type ;
NParam.    Par ::= Type Ident ;
separator Par "," ;

Arg.       Arg ::= Type Ident;
separator  Arg "," ;

-- Types ---------------------------------------------------

Int.       Type ::= "int" ;
--- more types...
separator  Type "," ;

Which causes reduce/reduce conflicts as expected.
Is there a way to solve this in the parser / lexer?
I could solve it with the following grammar:
FnDef.     TopDef ::= Type Ident "(" [Arg] ")" Block ;
FnDecl.    TopDef ::= Type Ident "(" [Arg] ")" ";" ;
separator nonempty TopDef "" ;

Arg.       Arg ::= Type Ident;
Arg.       Arg ::= Type;
separator  Arg "," ;

And then check in the type checker that function definitions have identifiers for each argument, but this feels less satisfying...
How is this typically handled in a language like C ?

A: The way you mention which you find unsatisfying is, in fact, the way it's usually accomplished.
But you can produce an LALR(1) grammar which is precise. Here's a complete bison specification without conflicts:
%token TYPE ID
%%
prog       :
           | prog decl ';'
decl       : TYPE ID def_list block
           | TYPE ID def_list ';'
           | TYPE ID dec_list ';'
block      : '{' prog '}'
def_list   : '(' ')'
           | '(' type_ids ')'
dec_list   : '(' type_opt_ids ')'
type_opt_id: type_only
           | type_id
type_ids   : type_id
           | type_ids ',' type_id
type_opt_ids
           : type_only
           | type_ids ',' type_only  /* SEE BELOW */
           | type_opt_ids ',' type_opt_id
type_id    : TYPE ID
type_only  : TYPE

The key is to avoid forcing the parser to make a decision. As it is passing over the list of parameters, it can keep reducing a type_opt_ids as long as it doesn't hit an anonymous parameter. If it hits one,  it reduces a type_ids and continues for the rest of the parameters, whether they are anonymous or not. At the end, the definition only allows type_ids but the declaration (explicitly) accepts either.
To make that work, the semantic type for type_id and type_only would need to be the same, since both type_ids and type_opt_ids must be lists of that type. Otherwise, you would need to convert type_ids to type_opt_ids in the production marked with /* SEE BELOW */
(I apologize for not converting that to your formalism, but I wanted to test it with bison to verify that it is, in fact, conflict-free. It should be easy enough to convert.)

Note that C++ is happy to allow function definitions without parameter names, but C is not. On the other hand, C allows function definitions without types, or with the type declarations between the parameter-name list and the body. But that's a side issue, really.


text:
Q: Facebook integation in an ios app How to integrate facebook in an iOS application ?
I have tried it once but I didn't understand how to generate a key from a developer account.
If it is possible then please provide me with a document which describes everything in detail
Thanks in advance.

A: You can integrate facebook using the FBGraph method. Here you have to first import the JSON and the FBGraph frameworks. After that write the following code :-
NSString *client_id = @"130902823636657";
self.fbGraph =[[FbGraph alloc] initWithFbClientID:client_id];

[fbGraph authenticateUserWithCallbackObject:self andSelector:@selector(fbGraphCallback:) andExtendedPermissions:@"user_photos,user_videos,publish_stream,offline_access,user_checkins,friends_checkins"];

- (void)fbGraphCallback:(id)sender
{
if ((fbGraph.accessToken==nil)||([fbGraph.accessToken length]==0)) {

    [fbGraph authenticateUserWithCallbackObject:self andSelector:@selector(fbGraphCallback:) andExtendedPermissions:@"user_photos,user_videos,publish_stream,offline_access,user_checkins,friends_checkins"];            }
else
{
    NSMutableDictionary *Variables=[[NSMutableDictionary alloc] initWithCapacity:2];
    FbGraphFile *graph_File=[[FbGraphFile alloc] initWithImage:imageCollage.image];
    [Variables setObject:graph_File forKey:@"file"];
    [Variables setObject:@"" forKey:@"message"];


text:
Q: MySql - how to combine where clauses for both tables for one to many join? I have 2 tables :
sellers
id|name

locations
id|seller_id|name

Now I want to get sellers and join locations and combine attributes from both tables in where clause.
Initial query is :
SELECT
    sellers.id
FROM sellers
JOIN locations.seller_id = sellers.id

I must add one more part because I don't want duplicated data :
SELECT
    sellers.id
FROM sellers
JOIN locations on locations.seller_id = sellers.id
WHERE (
    SELECT id from locations
    WHERE locations.seller_id = sellers.id
    LIMIT 1
)

Now I can do the following
SELECT
    sellers.id
FROM sellers
JOIN locations on locations.seller_id = sellers.id
WHERE (
    SELECT id from locations
    WHERE locations.seller_id = sellers.id
    LIMIT 1
)
AND (
    sellers.name = 'test'
    OR
    locations.name = 'test'
)

*

*problem here is that MySql will join first location and if name of that location is not "test" and there is location with name "test" for that seller it would not be not in results.

Any ideas?
UPDATED :
example with data :
sellers
id|name
1|test
2|test2

locations
id|seller_id|name
1|1|test3
2|2|test4
3|2|test
4|2|test

result should be
[1, 2] but with my query it is [1]

A: If you make your SQL simpler, the answer becomes simpler.
SELECT DISTINCT
    sellers.*
FROM sellers
    INNER JOIN locations on locations.seller_id = sellers.id
WHERE
    sellers.name = 'test'
    OR
    locations.name = 'test'

A: You can use Group By with Having:
SELECT sellers.id,
       sellers.name,
       SUM(locations.name = 'test') AS has_test_location
FROM sellers
    INNER JOIN locations on locations.seller_id = sellers.id
GROUP BY sellers.id, sellers.name
HAVING sellers.name = 'test' OR
       has_test_location


text:
Q: How can I solve Exercise 8.15a) in Introduction to PDE's (Tveito, Winther)? I am struggling with a) on the following exercise, taken from Introduction to PDE's (Tveito, Winther):

On a): I tried computing $((1+x)X_1'(x))' = X_1'(x) + (1+x)X_1''(x)$ by hand and seeing if it equals $\beta^2 X_1(x)$, but I got
$((1+x)X_1'(x))' = \frac{(1 - 4 \beta^2) \cos(\beta \log(1 + x)) + 4 \beta \sin(\beta \log(1 + x))}{4 (1 + x)^{3/2}} $.
I feel like this should be trivial and that I'm doing something silly, but I can't see what. Hints?


text:
Q: Splitting an array into n parts and then joining them again forming a histogram I am new to Matlab.
Lets say I have an array a = [1:1:1000]
I have to divide this into 50 parts 1-20; 21-40 .... 981-1000.
I am trying to do it this way.
E=1000X
a=[1:E]
n=50
d=E/n
b=[]
for i=0:n
   b(i)=a[i:d]
end

But I am unable to get the result.
And the second part I am working on is, depending on another result, say if my answer is 3, the first split array should have a counter and that should be +1, if the answer is 45 the 3rd split array's counter should be +1 and so on and in the end I have to make a histogram of all the counters.

A: You can do all of this with one function: histc. In your situation:
X = (1:1:1000)';
Edges = (1:20:1000)';
Count = histc(X, Edges);

Essentially, Count contains the number of elements in X that fall into the categories defined in Edges, where Edges is a monotonically increasing vector whose elements define the boundaries of sequential categories. A more common example might be to construct X using a probability density, say, the uniform distribution, eg:
X = 1000 * rand(1000, 1);

Play around with specifications for X and Edges and you should get the idea. If you want the actual histogram plot, look into the hist function.
As for the second part of your question, I'm not really sure what you're asking.


text:
Q: Is there an easier way to make a scoretable and then give points for its position? I'm doing a game like Mario Party in which you have several minigames and then depending on your position you receive a certain quantity of points. I made a system in which you order the scores in a list and then depending on your punctuation or if someone has the same quantity of points you receive certain points.
private List highScoreEntryList;//scoretable list
private class HighscoreEntry //class for the list
{
    public int score;
    public string name;
}

public void AddToList()
{
    //adding puntuations
    highScoreEntryList = new List<HighscoreEntry>() {
         new HighscoreEntry{score = player1score, name = "Player1" },
         new HighscoreEntry{score = player2score, name = "Player2" },
         new HighscoreEntry{score = player3score, name = "Player3" },
         new HighscoreEntry{score = player4score, name = "Player4" }
     };

    //order the puntuation
    for (int i = 0; i < highScoreEntryList.Count; i++)
    {
        for (int j = i + 1; j < highScoreEntryList.Count; j++)
        {
            if (highScoreEntryList[j].score > highScoreEntryList[i].score)
            {
                HighscoreEntry tmp = highScoreEntryList[i];
                highScoreEntryList[i] = highScoreEntryList[j];
                highScoreEntryList[j] = tmp;
            }
        }
    }

    //check player with same puntuations and giving points, the points are directly changed in the score

    for (int i = 0, tmp = 0; i < highScoreEntryList.Count; i++)
    {
        for (int j = i + 1; highScoreEntryList[i].score == highScoreEntryList[j].score; j++)
        {
            tmp++;
            iqual = true;
        }
        if (iqual == true)
        {
            for (int j = i; j <= tmp; j++)
            {
                if (tmp == 1)
                {
                    highScoreEntryList[j].score = 75;
                }
                else if (tmp == 2)
                {
                    highScoreEntryList[j].score = 50;
                }
                else if (tmp == 3)
                {
                    highScoreEntryList[j].score = 25;
                }
                iqual = false;
            }
        }
        else if (iqual == false)
        {
            if (i == 0)
            {
                highScoreEntryList[0].score = 125;
            }
            else if (i == 1)
            {
                highScoreEntryList[1].score = 75;
            }
            else if (i == 2)
            {
                highScoreEntryList[2].score = 50;
            }
            else if (i == 3)
            {
                highScoreEntryList[3].score = 25;
            }

            tmp++;
        }
        i = tmp - 1;

    }

With the checking added the script don't work more.
Could you help me?
Thanks.

A: You can use Linq and its OrderBy methods.
using UnityEngine;
using System.Collections.Generic;
using System.Linq;
public class HighscoreEntry
{
    public int score;
    public string name;
}
public class OrderScores : MonoBehaviour
{
    public List<HighscoreEntry> highScoreEntryList;

    public void Start()
    {
        highScoreEntryList = new List<HighscoreEntry>() {
            new HighscoreEntry{score = 1000, name = "Player5" },
            new HighscoreEntry{score = 1000, name = "Player1" },
            new HighscoreEntry{score = 2222, name = "Player4" },
            new HighscoreEntry{score = 2222, name = "Player2" },
            new HighscoreEntry{score = 1111, name = "Player3" },
            new HighscoreEntry{score = 3333, name = "Player6" }
        };

        List<HighscoreEntry> orderedRoundScores = OrderList(highScoreEntryList);

        foreach (HighscoreEntry entry in orderedRoundScores)
        {
            Debug.Log("Name: " + entry.name + ", Score: " + entry.score);
        }

        List<HighscoreEntry> scores = ScoresBasedOnPosition(orderedRoundScores);

        foreach (HighscoreEntry entry in scores)
        {
            Debug.Log("Name: " + entry.name + ", Score: " + entry.score);
        }
    }

    public List<HighscoreEntry> OrderList(List<HighscoreEntry> list)
    {
        list = list.OrderBy(o => o.name).ToList();
        list = list.OrderByDescending(o => o.score).ToList();
        return list;
    }

    public List<HighscoreEntry> ScoresBasedOnPosition(List<HighscoreEntry> allPlayers)
    {
        int[] positionRelatedScores = new int[] { 125, 75, 50, 25, 10 };
        int currentPositionRelatedScoresIndex = 0;

        List<HighscoreEntry> scoresBasedOnPositionList = new List<HighscoreEntry>();

        int previousScore = -1;

        for (int x = 0; x < allPlayers.Count; x++)
        {
            int playerScore = allPlayers[x].score;

            if (x > 0 && previousScore != playerScore)
            {
                currentPositionRelatedScoresIndex++;
                if (currentPositionRelatedScoresIndex >= positionRelatedScores.Length)
                {
                    break;
                }
            }

            scoresBasedOnPositionList.Add( new HighscoreEntry { name = allPlayers[x].name, score = positionRelatedScores[currentPositionRelatedScoresIndex]});

            previousScore = playerScore;
        }

        return scoresBasedOnPositionList;
    }

}

In that example it orders them by name first so that matching scores are now sorted alphabetically then reorders  them by Score Descending keeping the alphabetical order on matching names.
Edit: Added new method ScoresBasedOnPosition to loop through the ordered list and then assign a score depending on their position within the ordered list and if their round score matches the previous players round score.
Output
Name: Player6, Score: 3333
Name: Player2, Score: 2222
Name: Player4, Score: 2222
Name: Player3, Score: 1111
Name: Player1, Score: 1000
Name: Player5, Score: 1000

Name: Player6, Score: 125
Name: Player2, Score: 75
Name: Player4, Score: 75
Name: Player3, Score: 50
Name: Player1, Score: 25
Name: Player5, Score: 25

More information available from the Documentation


text:
Q: Running App on dev machine won't run when deployed I have a simple C# 4.5.1 x64 application which calls unmanaged dlls via a /clr C++ wrapper. App runs fine on my development machine. If I copy to Windows Server 2008 or Windows Server 2012 (with Framework 4.5.1 installed) I get an error that the wrapper won't load.
I have installed DependencyWalker on the deployment machine and I get this:
LoadLibraryExW("MyWrapper.dll", 0x000.., LOAD_WITH_ALTERED_SEARCH_PATH) called from ...
Loaded "MyWrapper.dll" at ... Successfully hooked module.
Loaded "XX.dll" at ... Successfully hooked module. (Dependency for MyWrapper.dll)
Loaded "YY.dll" at ... Successfully hooked module. (Dependency for MyWrapper.dll)
Unloaded "MyWrapper.dll"
Unloaded "XX.dll"
Unloaded "YY.dll"
LoadLibraryExW("MyWrapper.dll", 0x000.., LOAD_WITH_ALTERED_SEARCH_PATH) returned null. The specified module cannot be found.

Does anyone know why everything is loaded then unloaded and then cannot be found?

A: Make sure you have all the necessary redistributables (vcredist.exe) installed and you deploy a release build.
Any unmanaged c/c++ dll and also c++/cli dll links to msvcr. It is automatically installed with Visual Studio on the developer machine. It must be installed on the deployment machine together with the app. Make sure to redistribute the correct vcredist.exe version which corresponds to your version (and service pack) of VS. For vs2008 it resides in %ProgramFiles%\Microsoft SDKs\Windows\v6.0A\Bootstrapper\Packages). Note: Dependency walker does not show missing dll if it is loaded using LoadModule() or methods are loaded using [DllImport("Sample.dll")] in c#. In that case, open the unmanaged dll directly in Dependency walker and check missing deps. Make sure, unmanaged dll is in search path of your app.


text:
Q: How to get previous directory in bash script? I'm now writing bash script to get project directory in my project. Following is my folder structure. When I go api folder and type pwd, I will get "/Users/ppshein/Documents/projects/api" but what I want is I want to get "/Users/ppshein/Documents/projects/my-layers" from api folder.
├── README.md
├── api
├── node_modules
├── package.json
├── report
├── serverless.yml
├── webpack.config.js
└── my-layers

Is there anyway we can do in bash script?

A: You can get the parent directory like so:
parent="$(dirname "$(pwd)")"

Then
"${parent}/my-layers"

See Getting the parent of a directory in Bash for more details about how you can get the parent directory

A: I prefer to use this trick
BASE_DIR=$(dirname $(readlink -m $0))
this will get the dir that contains your script with variable ${BASE_DIR}. normally, it's the root dir of your project, or at least you could find something to work with. ../ something like that.
The good news is that it doesn't use a command like pwd which maybe environment-related. So that you could execute your script anywhere you like, especially useful in a crontab.


text:
Q: Modifying a structure member with pointers in C I'm trying to assign a value to a member of a structure in a very roundabout way. Here are the steps I'm taking:

*

*In main, create an array of structure pointers.

*(Still in main) Pass a pointer to that array to a function.

*Inside the function, create a structure and add a pointer to it to the array.

*(Still inside function) Assign a value to a member of the structure that was just created.

I'm very new to C, so I don't have a very good understanding of pointers. I thought that this process would allow me to see the value that was assigned from main, but when I print it it appears to be empty. What am I doing wrong (barring the obvious - I'm making this way too complicated)?
Here's the code:
#include <stdio.h>
#include <string.h>

struct MyStruct {
    char name[9];
};

void give_name(struct MyStruct ** structlist_ptr) {
    struct MyStruct new_struct;
    structlist_ptr[0] = &new_struct;
    strcpy(structlist_ptr[0]->name, "confused");
}

int main(void) {
    struct MyStruct * struct_list[1];

    give_name(struct_list);
    printf("%s\n", struct_list[0]->name); /* Appears to print random characters */

    return 0;
}

A: The major problem is this assignment:
structlist_ptr[0] = &new_struct;

With that you make *structlist_ptr (the usual way to use "reference" pointers) point to the local variable new_struct.
Once the function returns, the life-time of the local variables will end as they go out of scope. They will, in a manner of speaking, cease to exist. That leaves you with a stray and invalid pointer. Attempting to dereference it will lead to undefined behavior.


text:
Q: create htmlhelper instance of another type I have HtmlHelper extension method which can accept one template parameter of type T. Next, inside method i want to return editors for some fields in the object marked with special attribute. The problem is that i call this method for instance of HtmlHelper<TModel>, but inside the method i need instance of HtmlHelper<T> to use its Editor method. I've tried to create the default instance like this:
var html = new HtmlHelper<T>(new ViewContext(), new ViewPage());

but, of course, it doesn't work.
So, how could i create correct instance?

A: I don't think you need to re-instance it.
did you try something like this:
public static IHtmlString MyExtensionMethod<T>(this HtmlHelper html, T model) where T : IMyModel
{
    //your logic that returns a new HtmlString with html.TextBox for example
}


text:
Q: Under the help dropdown on each StackExchange page, should we add the name/abbreviation of the community to the term "Meta" I propose that under the help dropdown near the top of the page (next to reputation, at least in the desktop interface), the third entry, which says "Meta" in most (all?) communities other than here on Meta (where it says "What is Meta") should be changed to clarify that it targets the specific community Meta rather than the overall Meta.
This could be achieved by adding the community name (or perhaps an abbreviation for long community names) before Meta (e.g., "Physics Meta" or "UX Meta" or "ELL Meta".
Additionally, the sub-description of "discuss workings and policies of this site" only adds ambiguity.  "site" could mean the overall network website, or the topic's website.  If anything, it seems "site" might actually suggest the entire website is the target, since we have the term "community" specifically for the separate topic websites.
So in addition, we should at the very least we change the word "site" to say "community" in the description.
However, we can also change "this site" to the name of the community, either as a companion to enhancing the actual link text, or as an alternative.
With the help menu already a confusing mix of scopes [Tour, About Us, and Business inform only on SE as a whole, while Help Center (ideally) and Meta aim towards community-specific information)], and with this site being geared towards informing, it would seem only natural for us to prioritize removing such ambiguities.
Though this tweak aims immediately towards helping established users, who would most likely know the existence of both Meta sites and be most seeking to quickly choose their intended target, it really is of benefit to anyone who may click on the link, helping all users better understand the structure of Stack Exchange.
I wish to see the navigation and help at Stack Exchange improved, and hopefully this recommendation can be a small step towards doing so.  Cheers!


text:
Q: Is it possible to code a device driver in Java? Introduction
I heard something about writing device drivers in Java (heard as in "with my ears", not from the internet) and was wondering... I always thought device drivers operated on an operating system level and thus must be written in the same language as the OS (thus mostly C I suppose)
Questions

*

*Am I generally wrong with this
assumption? (it seems so)

*How can a driver in an "alien"
language be used in the OS?

*What are the requirements (from a
programming language point of view)
for a device driver anyway?

Thanks for reading

A: A device driver could be a lot of things
I actually write device drivers in java for a living: drivers for industrial devices, such as scales or weighing devices, packaging machines, barcode scanners, weighing bridges, bag and box printers, ... Java is a really good choice here.

Industrial devices are very different from your home/office devices (e.g. scanners, printers). Especially in manufacturing (e.g. food), companies opt more and more for a centralized server which runs an MES application (e.g. developed in Java) The MES server needs to interface with the devices of the production line, but also contains business logic. Java is a language that can do both.
Where your home/office devices are often built-in to your computer or connected with an USB cable, these industrial devices usually use Ethernet or RS232 connectors. So, in essence, pretty much every language could do the job.
There is not much standardisation in this area yet. Most vendors prefer to create their own protocol for their devices. After all they are hardware builders, not software geniuses. The result is that there is a high diversity of protocols. Some vendors prefer simple plain-text protocols, but others prefer complex binary protocols with CRC codes, framing, ... Sometimes they like to stack multiple protocols (e.g. a vendor specific handshaking algorithm on top of an OPC layer). A strong OOP language has a lot of advantages here.

E.g. I've seen java print at a continuous speed of 100ms/cycle. This includes generating a unique label, sending it to the printer, receiving a confirmation, printing it on paper and applying it to the product using air pressure.

In summary, the power of java:

*

*It is useful for both business logic as complex interfacing.

*It is just as reliable in communication with sockets as C.

*Some drivers can benifit from Java's OOP power.

*Java is fast enough.

A: It's not impossible, but possibly hard and possibly makes not much sense.
Possible is it, because Java is a normal programming language, as long as you have some way to access the data, it's no problem. Normally in a modern OS the kernel has a layer to allow raw access to hardware in some way. Also already exist drivers in userspace, at least the userspace-part should be no problem to implement in Java.
It makes possibly not too much sense, because the kernel has to start a JVM to execute the driver. Also JVM-implementations normally eat up much memory.
You could also use Java-code compiled to be executed natively on the platform (not with the help of a JVM). This is usually not that efficient, but it could be suitable for a device-driver.
The question is, does it make sense to implement the driver in Java? Or stated in another way: What is the benefit you hope for, if you use Java for implementing the driver instead of another alternative? If you can answer this question, you should find a way to make it possible.
At the end the hint to JNode, a project that tries to implement a complete OS purely based on Java.

A: Have you perhaps heard a reference to the JDDK?
Writing a device driver 100% in Java is not possible without native code to provide the interaction between (1) the OS-specific driver entry points and conventions, and (2) the JVM instance.  The JVM instance could be started "in-process" (and "in-process" may have different meanings depending on the OS and on whether the driver is a kernel-mode or user-mode driver), or as a separate user-land process with which a thin, native driver adaptation layer can communicate and onto which the said driver adaptation layer can offload actual user-land work.

A: You have a too narrow view of device drivers.
I have written such device drivers on top of MOST in an automotive application. A more widespread use might be drivers for USB devices if Java ever gets a decent USB library.
In these cases there is a generic low-level protocol which is handled in native code, and the Java driver handles the device specifics (data formats, state machines, ...).

A: For the motivation, please remember that there is plenty of fast languages which are better than C for programming; they might not be as fast as C, but they are safe languages: if you make a mistake you don't get undefined behavior. And "undefined behavior" includes executing arbitrary code supplied by some attacker which formats your HD.
Many functional languages are usually compiled to native code.
Device drivers contain the most bugs in an OS kernel - I know that for Linux (Linus Torvalds and others keep saying so) and I heard that for Windows. While for a disk or Ethernet driver you need top-notch performance, and while in Linux drivers today are the bottleneck for 10G Ethernet or SSD disks, most drivers don't need that much speed - all computers wait at the same speed.
That's why there are various projects to allow writing drivers which run outside of the kernel, even if that causes a slowdown; when you can do that, you can use whatever language you want; you will just then need Java bindings for the hardware control library you use - if you were writing the driver in C, you would still have a library with C bindings.
For drivers in kernel mode proper, there are two problems that I've not yet seen mentioned:

*

*Garbage Collection, and that's a tough requirement. You need to write an in-kernel Garbage Collector; some GC algorithms rely on Virtual Memory, and you cannot use them. Moreover, you probably need to scan the whole OS memory to find roots for the GC. Finally, I would only trust an algorithm guaranteeing (soft) real-time GC, which would make the overhead even bigger.
Reading the paper which was mentioned about Java Device Drivers on top of Linux, they just give up, and require programmers to manually free memory. They try to argue that this will not compromise safety, but I don't think their argument is convincing - it's not even clear whether they understand that Garbage Collection is needed for a safe language.

*Reflection and class loading. A full Java implementation, even when running native code, needs to be able to load new code. This is a library you can avoid, but if you have an interpreter or JIT compiler in kernel (and there's no real reason that makes it technically impossible).

*Performance. The paper about a JVM on Linux is very bad, and their performance numbers are not convincing - indeed, they test a USB 1.1 network driver, and then show that performance is not so bad! However, given enough effort something better can surely be done.
Two last things:

*

*I'd like to mention Singularity, which is a complete OS written in a C# variant, with just a Hardware Abstraction Layer in a native language.

*About picoJava, it's a bad idea to use it unless your system is a really memory constrained one, like a smart card. Cliff Click already explained why: it gives better performance to write a good JIT, and nowadays even smartphones can support that.

A: There are a couple of ways this can be done.
First, code running at "OS level" does not need to be written in the same language as the OS. It merely has to be able to be linked together with OS code. Virtually all languages can interoperate with C, which is really all that's needed.
So language-wise, there is technically no problem. Java functions can call C functions, and C functions can call Java functions. And if the OS isn't written in C (let's say, for the sake of argument that it's written in C++), then the OS C++ code can call into some intermediate C code, which forwards to your Java, and vice versa. C is pretty much a lingua franca of programming.
Once a program has been compiled (to native code), its source language is no longer relevant. Assembler looks much the same regardless of which language the source code was written in before compilation. As long as you use the same calling convention as the OS, it's no problem.
A bigger problem is runtime support. Not a lot of software services are available in the OS. There usually is no Java virtual machine, for example. (There is no reason why there technically couldn't be, but usually, but usually, it's safe to assume that it's not present).
Unfortunately, in its "default" representation, as Java bytecode, a Java program requires a lot of infrastructure. It needs the Java VM to interpret and JIT the bytecode, and it needs the class library and so on.
But there are two ways around this:

*

*Support Java in the kernel. This would be an unusual step, but it could be done.

*Or compile your Java source code to a native format. A Java program doesn't have to be compiled to Java bytecode. You could compile it to x86 assembler. The same goes for whatever class libraries you use. Those too could be compiled all the way to assembler. Of course, parts of the Java class library requires certain OS features that won't be available, but then use of those classes could be avoided.

So yes, it can be done. But it's not straightforward, and it's unclear what you'd gain.
Of course another problem may be that Java won't let you access arbitrary memory locations, which would make a lot of hardware communication pretty tricky. But that could be worked around too, perhaps by calling into very simple C functions which simply return the relevant memory areas as arrays for Java to work on.

A: Writing Solaris Device Drivers in Java covers a A RAM disk device written in Java.
Another one for Linux.  Goes more in depth on why you might want a DD in Java as well (since some people were wondering by the looks of the other posts and comments)

A: It is possible to compile java code to hardware native (i.e. not JVM bytecode) instructions. See for instance GCJ. With this in hand, you're a lot closer to being able to compile device drivers than you were before.
I don't know how practical it is, though.

A: Possible?
Yes but only in special circumstances. Because you can write an operating system in Java and C#, and then, should be able to write device drivers for it. The memory hit to these drivers and operating systems would be substantial.
Probable?
Not likely. Atleast not in the world of Windows or MacOS or even Linux... At least not anytime soon. Because languages like C# and Java depend on the CLR and JVM. The way these languages work means that they cannot effectively be loaded into ring0.
Also, the performance hit would be rather large if managed languages were employed in device drivers.

A: Device drivers have to be written in a language which can execute in the kernel, either compiled into it, or loaded as a module at runtime. This usually precludes writing device drivers in Java, but I suppose you theoretically could implement a JVM inside a device driver and let it execute Java code. Not that any sane person would want to do that.
On Linux there are several user-land (i.e. non-kernel) implementations of filesystems which uses a common abstraction layer called (fuse) which allows user-land programs to implement things which are typically done in the kernel.

A: The Windows Driver Foundation (WDF) is a Microsoft API that does allow both User and Kernel mode device drivers to be written.  This is being done today, and it is now compatible with w2k and later (used to not have w2k as a supported target).  There is no reason that JNI calls can't be made to do some work in the JRE . . . ( assuming that JNI is still the way to call Java from C/C++ . . . my knowledge is dated in that arena).  This could be an interesting way to have high level algorithms directly munch on data from a USB pipe for something to that effect . . . cool stuff!

A: PCIe user space device drivers can be written in Pure Java. See JVerbs for details about memory-based direct hardware access, in the context of OFED. This is a technique that can be used to create very high performance systems.
You can examine the PCI bus to determine the memory regions for a given device, what ports it has, etc. The memory regions can be mapped into the JVM's process.
Of course, you're responsible for implementing everything yourself.
I didn't say easy. I said possible.  ;)
See also Device Drivers in User Space, which discusses using the UIO framework to build a user space driver.

A: First of all, note that I'm not an expert on device drivers (though I wrote a few myself back in the day), much less an expert on Java.
Let's leave the fact that writing device drivers in a high-level language is not a good idea (for performance and possibly many other reasons) aside for a moment, and answer your question.
You can write device drivers in almost any language, at least in theory.
However, most device drivers need to do plenty of low-level stuff like handling interrupts and communicating with the OS using the OS APIs and system calls, which I believe you can't do in Java.
But, if your device communicates using, say, a serial port or USB, and if the OS doesn't necessarily need to be aware of the device (only your application will access the device*), then you can write the driver in any language that provides the necessary means to access the device.
So for example you probably can't write a SCSI card driver in Java, but you can write a driver for a proprietary control device, USB lava lamp, license dongle, etc.
* The obvious question here is, of course, does that count as a driver?


text:
Q: Icon not displaying correctly I have some D3 code which creates rectangles, put some text into it and connects each node based on some logic. Now, for each node I want to display an icon if the execution_type of that node is 'Manual". The icon needs to be similar to this example: http://output.jsbin.com/eFAZABe/6
After looking at this example, I checked out Font Awesome and found that "fa-user" provides that kind of icon I am looking for.
So, I came up with the following code:

var d3cola = cola.d3adaptor().convergenceThreshold(0.1);

var width = 960, height = 700;

        // REMOVE OLD SVG
  d3.select("#wkfsvg").remove();
        d3.select("#stats").remove();
  // ADD NEW SVG
  var outer = d3.select("body").append("svg")
   .attr({ width: width, height: height, "pointer-events": "all" })
   .attr("id","wkfsvg");

        d3.select("body")
            .insert("div", "#wkfsvg")
            .attr("id", "stats")
            .attr("class", "tooltip");

  //  document.getElementById('wkfsvg').parentNode.style.overflow = 'scroll'

    outer.append('rect')
       .attr({ class: 'background', width: "100%", height: "100%" })
       .call(d3.behavior.zoom().on("zoom", function(d) {
          vis.attr("transform", "translate(" + d3.event.translate + ")" + " scale(" + d3.event.scale + ")");
       }));

var vis = outer
      .append('g')
      .attr('transform', 'translate(250,250) scale(0.3)');

   outer.append('svg:defs').append('svg:marker')
   .attr({
                id: 'end-arrow-approve',
                viewBox: '0 -5 10 10',
                refX: 8,
                markerWidth: 6,
                markerHeight: 6,
                orient: 'auto'
            })
            .append('svg:path')
            .attr({
                d: 'M0,-5L10,0L0,5L2,0',
                'stroke-width': '0px',
                fill: 'black'});

        outer.append('svg:defs').append('svg:marker')
            .attr({
                id: 'end-arrow-reject',
                viewBox: '0 -5 10 10',
                refX: 8,
                markerWidth: 10,
                markerHeight:10,
                orient: 'auto'
            })
            .append('svg:path')
            .attr({
                d: 'M0,-5L10,0L0,5L2,0',
                'stroke-width': '0px',
                fill: 'red'
            })

var nodes = [
    {
        "nodes": "Initiate",
        "status": "startend",
        "creation_date": "",
        "performer_name": "",
        "execution_type": "Automatic"
    },
    {
        "nodes": "Find the Next Approver",
        "status": "completed",
        "creation_date": "",
        "performer_name": "",
        "execution_type": "Automatic"
    },
    {
        "nodes": "Check for Manager",
        "status": "completed",
        "creation_date": "",
        "performer_name": "",
        "execution_type": "Automatic"
    },
    {
        "nodes": "Set Status & ACL for IT Project Manager",
        "status": "completed",
        "creation_date": "",
        "performer_name": "",
        "execution_type": "Automatic"
    },
    {
        "nodes": "Set Status & ACL for IT Sign Off Approvers",
        "status": "completed",
        "creation_date": "",
        "performer_name": "",
        "execution_type": "Manual"
    },
    {
        "nodes": "IT Project Manager Approves",
        "status": "completed",
        "creation_date": "",
        "performer_name": "",
        "execution_type": "Manual"
    },
    {
        "nodes": "Finance Approver",
        "status": "pending",
        "creation_date": "",
        "performer_name": "",
        "execution_type": "Manual"
    },
    {
        "nodes": "Send Email for Completion",
        "status": "future",
        "creation_date": "",
        "performer_name": "",
        "execution_type": "Manual"
    },
    {
        "nodes": "Send to Requestor",
        "status": "future",
        "creation_date": "",
        "performer_name": "",
        "execution_type": "Manual"
    },
    {
        "nodes": "Send Email to Requestor",
        "status": "completed",
        "creation_date": "",
        "performer_name": "",
        "execution_type": "Manual"
    },
    {
        "nodes": "Set ACL on Form for Requestor",
        "status": "future",
        "creation_date": "",
        "performer_name": "",
        "execution_type": "Manual"
    },
    {
        "nodes": "Set Completion ACL on Form",
        "status": "future",
        "creation_date": "",
        "performer_name": "",
        "execution_type": "Manual"
    },
    {
        "nodes": "Set Completion ACL on PO",
        "status": "future",
         "creation_date": "",
        "performer_name": "",
        "execution_type": "Manual"
    },
    {
        "nodes": "Set Completion ACL on Attachments",
        "status": "future",
         "creation_date": "",
        "performer_name": "",
        "execution_type": "Manual"
    },
    {
        "nodes": "Set ACL on Attachment",
        "status": "completed",
         "creation_date": "",
        "performer_name": "",
        "execution_type": "Manual"
    },
    {
        "nodes": "Update Comments of PM Rejection",
        "status": "future",
         "creation_date": "",
        "performer_name": "",
        "execution_type": "Manual"
    },
    {
        "nodes": "Update Comments of FA Rejection",
        "status": "future",
         "creation_date": "",
        "performer_name": "",
        "execution_type": "Manual"
    },
    {
        "nodes": "Update Comments of PM",
        "status": "completed",
         "creation_date": "",
        "performer_name": "",
        "execution_type": "Manual"
    },
    {
        "nodes": "Update Comments of FA",
        "status": "future",
         "creation_date": "",
        "performer_name": "",
        "execution_type": "Manual"
    },
    {
        "nodes": "Update Comments of Requestor",
        "status": "future",
         "creation_date": "",
        "performer_name": "",
        "execution_type": "Manual"
    },
    {
        "nodes": "End",
        "status": "startend",
         "creation_date": "",
        "performer_name": "",
        "execution_type": "Manual"
    }
];

var edges = [
    {
        "source": 1,
        "target": 2,
        "type": "approve",
        "source_name": "Find the Next Approver",
        "target_name": "Check for Manager"
    },
    {
        "source": 2,
        "target": 4,
        "type": "approve",
        "source_name": "Check for Manager",
        "target_name": "Set Status & ACL for IT Sign Off Approvers"
    },
    {
        "source": 2,
        "target": 3,
        "type": "approve",
        "source_name": "Check for Manager",
        "target_name": "Set Status & ACL for IT Project Manager"
    },
    {
        "source": 3,
        "target": 5,
        "type": "approve",
        "source_name": "Set Status & ACL for IT Project Manager",
        "target_name": "IT Project Manager Approves"
    },
    {
        "source": 4,
        "target": 6,
        "type": "approve",
        "source_name": "Set Status & ACL for IT Sign Off Approvers",
        "target_name": "Finance Approver"
    },
    {
        "source": 10,
        "target": 8,
        "type": "approve",
        "source_name": "Set ACL on Form for Requestor",
        "target_name": "Send to Requestor"
    },
    {
        "source": 11,
        "target": 12,
        "type": "approve",
        "source_name": "Set Completion ACL on Form",
        "target_name": "Set Completion ACL on PO"
    },
    {
        "source": 5,
        "target": 9,
        "type": "approve",
        "source_name": "IT Project Manager Approves",
        "target_name": "Send Email to Requestor"
    },
    {
        "source": 12,
        "target": 13,
        "type": "approve",
        "source_name": "Set Completion ACL on PO",
        "target_name": "Set Completion ACL on Attachments"
    },
    {
        "source": 13,
        "target": 7,
        "type": "approve",
        "source_name": "Set Completion ACL on Attachments",
        "target_name": "Send Email for Completion"
    },
    {
        "source": 0,
        "target": 14,
        "type": "approve",
        "source_name": "Initiate",
        "target_name": "Set ACL on Attachment"
    },
    {
        "source": 14,
        "target": 1,
        "type": "approve",
        "source_name": "Set ACL on Attachment",
        "target_name": "Find the Next Approver"
    },
    {
        "source": 15,
        "target": 10,
        "type": "approve",
        "source_name": "Update Comments of PM Rejection",
        "target_name": "Set ACL on Form for Requestor"
    },
    {
        "source": 5,
        "target": 15,
        "type": "reject",
        "source_name": "IT Project Manager Approves",
        "target_name": "Update Comments of PM Rejection"
    },
    {
        "source": 16,
        "target": 10,
        "type": "approve",
        "source_name": "Update Comments of FA Rejection",
        "target_name": "Set ACL on Form for Requestor"
    },
    {
        "source": 9,
        "target": 17,
        "type": "approve",
        "source_name": "Send Email to Requestor",
        "target_name": "Update Comments of PM"
    },
    {
        "source": 17,
        "target": 4,
        "type": "approve",
        "source_name": "Update Comments of PM",
        "target_name": "Set Status & ACL for IT Sign Off Approvers"
    },
    {
        "source": 6,
        "target": 18,
        "type": "approve",
        "source_name": "Finance Approver",
        "target_name": "Update Comments of FA"
    },
    {
        "source": 18,
        "target": 11,
        "type": "approve",
        "source_name": "Update Comments of FA",
        "target_name": "Set Completion ACL on Form"
    },
    {
        "source": 6,
        "target": 16,
        "type": "reject",
        "source_name": "Finance Approver",
        "target_name": "Update Comments of FA Rejection"
    },
    {
        "source": 8,
        "target": 19,
        "type": "approve",
        "source_name": "Send to Requestor",
        "target_name": "Update Comments of Requestor"
    },
    {
        "source": 19,
        "target": 2,
        "type": "approve",
        "source_name": "Update Comments of Requestor",
        "target_name": "Check for Manager"
    },
    {
        "source": 7,
        "target": 20,
        "type": "approve",
        "source_name": "Send Email for Completion",
        "target_name": "End"
    }
];

 d3cola
       .avoidOverlaps(true)
       .convergenceThreshold(1e-3)
       .flowLayout('x', 150)
       .size([width, height])
       .nodes(nodes)
       .links(edges)
       .jaccardLinkLengths(150);

var link = vis.selectAll(".link")
             .data(edges)
             .enter().append("path")
          //   .attr("class", "link");
    .attr("class", function(d) { return "link " + d.type; })
    .attr("marker-end", function(d) {
    return "url(#end-arrow-" + d.type + ")"
    console.log("url(#end-arrow- :" + "url(#end-arrow-" + d.type)
    })

var margin = 10, pad = 12;
/* var node = vis.selectAll(".node")
            .data(nodes)
            .enter().append("rect")
            .classed("node", true)
            .attr({ rx: 5, ry: 5 })
            .call(d3cola.drag); */

var node = vis.selectAll(".node")
            .data(nodes)
            .enter().append("rect")
            .attr('class',function(d){
         /*     var N = edges.length;
              for (var i = 0; i < N; i++){
                if (edges[i].source_name === d.nodes){
                  return edges[i].status;
                }
              } */
     return d.status;
            })
            .attr({ rx: 5, ry: 5 })
            .call(d3cola.drag);

var label = vis.selectAll(".label")
            .data(nodes)
            .enter().append("text")
            .attr("class", "label")
               //   .attr("x",0)
               //   .attr("y",70)
                  .attr("font-family","FontAwesome")
                //  .attr('font-size', function(d) { return '70px';} )
                  .text(function (d) {
                      if(d.execution_type == 'Manual')
                          return d.nodes+' \uf007' ;
                      else
                          return d.nodes;
                  })
            .call(d3cola.drag)
            .each(function (d) {
                    var b = this.getBBox();
                    var extra = 2 * margin + 2 * pad;
                    d.width = b.width + extra;
                    d.height = b.height + extra;
             });

/**************FontAwesome****************/
/*var icons = ["fa-user"];
var s = d3.select("#wkfsvg");
var rect = s.selectAll("rect");
rect.selectAll("i").data(icons)
  .enter().append("i")
  .attr("class", function(d){
    return "fa fa-user";
  }) */

/***********************************/

label.on("dblclick", function(d){
    d3.select('#stats').html("" + d.nodes  + "
"
          + "Status: "+d.status+"
"
          + "Performer Name: "+d.runtime_performer_name+"
"
          + "Completion Date: "+d.runtime_creation_date);
    console.log("Double Clicked");

});

var lineFunction = d3.svg.line()
                .x(function (d) { return d.x; })
                .y(function (d) { return d.y; })
                .interpolate("linear");

var routeEdges = function () {
           d3cola.prepareEdgeRouting();
           link.attr("d", function (d) {
                 return lineFunction(d3cola.routeEdge(d));
           });
                if (isIE()) link.each(function (d) { this.parentNode.insertBefore(this, this) });
            }
        d3cola.start(50, 100, 200).on("tick", function () {
              node.each(function (d) { d.innerBounds = d.bounds.inflate(-margin); })
                  .attr("x", function (d) { return d.innerBounds.x; })
                    .attr("y", function (d) { return d.innerBounds.y; })
                    .attr("width", function (d) {
                        return d.innerBounds.width();
                    })
                    .attr("height", function (d) { return d.innerBounds.height(); });

                link.attr("d", function (d) {
                    cola.vpsc.makeEdgeBetween(d, d.source.innerBounds, d.target.innerBounds, 5);
                    var lineData = [{ x: d.sourceIntersection.x, y: d.sourceIntersection.y }, { x: d.arrowStart.x, y: d.arrowStart.y }];

                    return lineFunction(lineData);
                });
                if (isIE()) link.each(function (d) { this.parentNode.insertBefore(this, this) });

                label
                    .attr("x", function (d) { return d.x })
                    .attr("y", function (d) { return d.y + (margin + pad) / 2 });

            }).on("end", routeEdges);

        function isIE() { return ((navigator.appName == 'Microsoft Internet Explorer') || ((navigator.appName == 'Netscape') && (new RegExp("Trident/.*rv:([0-9]{1,}[\.0-9]{0,})").exec(navigator.userAgent) != null))); }
  .background {
        stroke: white;
        stroke-width: 1px;
        fill: white;

    }

    .node {
        stroke: black;
        stroke-width: 1.5px;
        cursor: move;
        fill: lightcoral;
    }

    .link {
        fill: none;
        stroke: #000;
        stroke-width: 3px;
        opacity: 0.7;

    }

    .label {
        fill: black;
        font-family: Verdana;
        font-size: 25px;
        text-anchor: middle;
        cursor: move;
    }

 .link.reject {
  stroke-dasharray: 0,2 1;
  stroke: red;
  fill: none;
  stroke-width: 3px;
  opacity: 0.7;

 }

    .completed {
       fill: #66FF99;
    }
 .future {
    fill: #99CCFF;
 }
 .pending {
    fill: #CC66FF;
 }
 .startend {
    fill: #CC6666;
 }

 div.tooltip {
   text-align: left;
   width: 300px;
   height: 60px;
   padding: 5px;
   color:black;
   font: 12px sans-serif;
   background: #ccddff;
   border: 0px;
   pointer-events: none;
 }
<link href="http://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet"/>

There are couple of problems with this code:

*

*Instead of the icon, a blank square is displayed in each rectangle which has "execution_type" as "Manual".

*I am not able to align the icon (which is blank square right now) to the top right corner inside the rectangle.

Can someone please help with this?

A: *

*change the font family and appear your icon
    .label {
    fill: black;
    font-family: FontAwesome;
    /*font-family: Verdana;*/
    font-size: 25px;
    text-anchor: middle;
    cursor: move;
}

and remove the .attr("font-family","FontAwesome") part from javascript
var label = vis.selectAll(".label")
    .data(nodes)
    .enter().append("text")
    .attr("class","label")
       //   .attr("x",0)
       //   .attr("y",70)
       //.attr("font-family","FontAwesome")
       //  .attr('font-size', function(d) { return '70px';} )
          .html(function (d) {
              if(d.execution_type == 'Manual')
                  return d.nodes + ' <tspan dx="0" dy="-10">\uf007</tspan>';
              else
                  return d.nodes;
          })

*use "tspan" in your string and you are able to move your icon by dx and dy


text: Q: How to import Kmail filters into Evolution? Is there a way to import filters defined in Kmail into Evolution? I know how to export them (Tools → Import/export → Kmail/config), and extract the filters (extract config/filters which describes them in .ini format); but I don't know how to import filters into Evolution.


text:
Q: Alternative for proxy.conf.json in vue without vue-cli? I want to make requests to api on another website.
I know that in Angular you can have a file proxy.conf.json with something like this
{
  "/api": {
    "target": "website.com",
    "secure": false,
    "changeOrigin": true,
    "logLevel": "debug"
  }
}

Is there a way to do this in vue if I don't use vue-cli?

A: Ended up using express server with webpack dev middleware and express-http-proxy


text:
Q: If two elements are different there is a functional under where the image is different I have the following exercise in functional analysis:
Let E be a normed space and $x,y$ different vectors. Prove or disprove finding a counterexample that it exist a function $f \in E^*$ such that $f(x) \not= f(y)$.
I tried do define a function on $<x,y> \subset E $ with different images for $x,y$ and than to extend this with hahn Banach to $E$, but I dont know how to define this. Is this statement even true or is there a counter example?

A: Yes, the statement is true, and your approach is kind of the way to go. But it is better to state the problem in the following equivalent and more useful way:

Given $x\in E$ there exists $f\in E^*$ such that $f(x)\ne0$.