text:
Q: Shorten Function in Javascript I was searching a way to only display two decimals of a variable and I found the .toFixed() function, but it rounds the final number, I came across this page Display two decimal places, no rounding, where one guy says about this method: .toString().match(/^-?\d+(?:\.\d{0,2})?/)[0], which works perfectly fine, but it's too long. I tryed doing this:
function twoDecimals(i) {
i = Number(i.toString().match(/^-?\d+(?:\.\d{0,2})?/)[0]);
}

.toString() makes it a string, so I use Number() to make it back a variable
and then I do this:
var num = 12.34567;
num.twoDecimals(this);

Basically I want to make .twoDecimals() equal to .toString().match(/^-?\d+(?:\.\d{0,2})?/)[0] or even better if it has Number() surrounding all

A: Try doing
Number.prototype.twoDecimals = function(arg){
    return arg.toString().match(/^-?\d+(?:\.\d{0,2})?/)
}

This should give all objects of the Number class a new method called twoDecimals.

A: How about this
Number.prototype.twoDecimals = function(){
    return (Number)(this.toString().match(/^-?\d+(?:\.\d{0,2})?/));
}
var num = 12.34567;
console.log(num.twoDecimals()); // Print out 12.34


text:
Q: How to change SQL Server Express instance from 2008 to 2012 I have installed SQL Server 2012 Express, however, when I query select @@version, it returns SQL Server 2008 instance, how can I change the SQL Server Express to run on instance 2012?
I installed Visual Studio 2010, SQL Server 2008 Express was installed at the same time. But now I installed SQL Server 2012 Express, I need to use this newer version to restore some databases.

A: You need to check your service:

And then connect to the SQL Server 2012 version using
.\SQL2012

Also use this query to check the correct version number:
SELECT
   SERVERPROPERTY ('MachineName') AS PhysicalMachineName,
   SERVERPROPERTY ('ServerName') AS SQLServerName,
   SERVERPROPERTY ('Edition') AS ServerEdition,
   CAST(SUBSTRING(@@Version,charindex('SQL',@@version, 1),15) AS VARCHAR(255)) +  ' + '
       + CAST (SERVERPROPERTY ('productlevel')AS VARCHAR (50)) + ' + (Build'
       + CAST (SERVERPROPERTY ('ProductVersion') AS VARCHAR (50)) +')' AS ProductVersion,
    RIGHT(@@version, (Len(@@Version)-charindex('Windows',@@version, 1))+1) AS [O.S.],
 SERVERPROPERTY ('Collation') AS Collation

A: I suggest that change IP Address of SQL Server Instance protocol. In order to do use following steps:

*

*Run SQL Server Configuration Manager

*Select SQL Server Network configuration

*Select protocols for your Instance (2008 / 2012 ,...)

*select TCP/IP Item

*Select IP Addresses tab

*Change IP Addresses of SQL Server 2008 Instance with SQL Server 2012 Instance IP Address
and change IP Address of SQL Server 2012 Instance with SQL Server 2008 Instance IP Address

*Restart Database Engine 2008 and 2012

A: I answer my own question to help those encounter the same issue in future
I made a mistake, I noticed that I only have SQL Server 2012 Management Studio, but I don't have running instance. What I downloaded and installed is SQLManagementStudio_x64_ENU, but what I need to install is SQLEXPRWT_x64_ENU.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Charts for iOS: limit displayed entries number to 4 in LineChartView I'm using LineChartView to draw line charts in our application. The newest requirement is that the chart displays only 4 records at once, so the X-zoom must be limited to 4 entries. Is this achievable using this library without doing any hacky stuff? I'd rather avoid calculating zoom manually.
Thanks in advance!

A: If I understand correctly, you want to see only 4 values at a time.
This can be accomplished by using:
chartView.setVisibleXRange(minXRange: 4.0, maxXRange: 4.0)

The chart will be scrollable to the sides.
The scroll can be turned off, but then only the 4 first values will be viewable:
chartView.isUserInteractionEnabled = false

A: If you want to make the graph auto scroll along +X-axis:
let any_value_in_double = 100.00
chartView.moveViewToX(any_value_in_double)
This graph will starts moving toward the right after 4.0 values as mentioned in the above Ranges.


text:
Q: Is it safe to declare critical literals in "with (...) {...}" to sandbox code run within it? I avoid using eval() or Functions created from a string. But when I need to run some subset of Javascript that can be entered by a user I'm tempted to use it just because it will save me much work writing a lexer/parser and interpreter.
Say I'd like to run this code:
a.toLowerCase() === 'xyz' || b == 1 || /pqr/.test(c)

the native approach would be to pass it into eval() like this:
with({a: ..., b: ..., c: ...}) {
    ret = eval(code);
}

I cannot be sure that code always contains uncritical code like the above. This opens the possibilities to run malicious code.
I thought of passing an object re-defining critical Browser objects to with besides the actual data like:
var obj = {
   // list incomplete ;)
   console: true, XMLHttpRequest: true, document: true, window: true, addEventListener: true, removeEventListener: true, parent: true, top: true, history: true, ...,

   // actual data
   a: ..., b: ..., c: ...
};

with (obj) {
   ...
}

When running code within with access to the objects/methods is not possibe.
I know that it's still possible to indirectly access those methods if they are indirectly accessed though another object/function that is not re-defined. Let's assume I re-define these too.
Is it secure to sandbox code with a suffient list of objects and functions as content object?
What would be remaining the attack vectors in this case?
Edit 1:
The code should run within Firefox, Chrome, IE (10+), Opera, Safari.

A: No, this is not secure.
No matter what you do with your code's execution environment using with, it is still possible to retrieve the "real" global object using the following trick:
var window = (function(){ return this }).call(undefined);

This works because Function.call will use the global object as the value of this if it is explicitly passed as undefined or null.

A: If the shadowed variables were deleted ...

alert([1, window, document]);

var obj = {
    document: true, window: true
};

with (obj) {
  alert([2, window, document]);

  delete window;
  delete document;

  alert([3, window, document]); //restored
}

Additionally if you exposed any DOM elements the document/window objects could be reached via ownerDocument/defaultView.

A: You should make use of a global (and "static") function to avoid giving access to other unwanted/private variables (i.e. a sub-function has access to all the variables of the parent function).
Second you want to remove a few keywords from the string to be evaluated to avoid problems as described by duskwuff and Alex K. Something like this:
function exec(e)
{
    e = e.replace(/new/, "new_", "g")
         .replace(/delete/, "delete_", "g")
         .replace(/function/, "function_", "g")
         .replace(/throw/, "throw_", "g")
         .replace(/this/, "this_", "g")
         .replace(/var/, "var_", "g")
         .replace(/eval/, "eval_", "g");
    obj = { ... };
    with(obj)
    {
        eval(e);
    }
}

Note that may not work in strict mode. As mentioned by Bergi in a comment, you could also protect the variables in obj and make them non-deletable so you cannot replace them.
The replace() can include many more things... you may want to look closer at what you are trying to achieve. If the evaluation string is expected to just be an expression, then all keywords should be removed (Except true and false and null). You may also want to remove a few other functions. Here I only removed eval.
If you'd like to only match words so the word anew does not match new you can use the \b flag in the regex. I do not know how compatible this flag is across browsers.
e.replace(/\bnew\b/, "new_", "g");

This would match new but not anew.


text:
Q: Display exceptions in mod_wsgi hosted cherrypy app I have a cherrypy app with works fine on my local machine, but not on my server. If an exception is thrown in a request handler, I see the following message in my browser:

The server encountered an unexpected condition which prevented it from
  fulfilling the request.

How can I tell cherrypy to display the exception? I see no log information in the appache log or somewhere else. I would expect some flag where I can say "DEBUG=True" or something like that. But I could not find anything in the documentation.

A: If you're setting the environment configuration to either production, embedded or test_suite then automatically log.screen is set to False. Manually setting this to true will give you a full trace-back displayed on screen. Alternatively you'd have to start digging in your web server logs.


text:
Q: How to fetch drop down value on update page I am creating one IMS System. On order page I put one drop down list when I select any option from drop down it working perfectly but when it redirect to update page drop down filed data is coming blank. If anyone know solution than please help. Below is my code of create.php
<select class="form-control select_group party" data-row-id="row_1"
        id="party_1" name="name" style="width:100%;" required>
  <option value=""></option>
  <?php
      $dbc = mysqli_connect('localhost', 'root', '', 'stock')
               or die('Error connecting to MySQL server.');
      $query = "SELECT * FROM partys";
      $result = mysqli_query($dbc, $query);
      while ($row = mysqli_fetch_array($result)) {
  ?>
  <option value="<?php echo $row['name'] ?>">
      <?php echo $row['name'] ?
  </option>
  <?php } ?>
</select>

And for update.php
<select class="form-control select_group party" data-row-id="row_1" id="party_1"
        name="name" style="width:100%;" required>
  <option value=""></option>
  <?php
      $dbc = mysqli_connect('localhost', 'root', '', 'stock')
               or die('Error connecting to MySQL server.');
      $query = "SELECT * FROM partys";
      $result = mysqli_query($dbc, $query);
      while ($row = mysqli_fetch_array($result)) {
  ?>
  <option <?php if (!empty($name) && $name == $row['name']) echo 'selected = "selected"'; ?> value="<?php echo $row['name'];?>"><?php echo $row['party_id'];?>
  </option>
  <?php } ?>
</select>


text:
Q: Opacity CheckBox(VisualStudio) don't work There's no code problem, the debug doesn't have any problem but when I test, when I checked the checkbox the opacity doesn't change. Nothing happen. I'm using VisualStudio 2013 Express. Here's the code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace TP3
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {

            int carac = textBox1.Text.Length;
            label2.Text = carac.ToString();

        }

        private void label2_Click(object sender, EventArgs e)
        {

        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            Form Form1;
            Form1 = new Form1();
            if(checkBox1.Checked == true)
            {
             Form1.Opacity = 1;
            }

        }
    }
}

A: The code doesn't seem to do anything right. You are creating a new instance of Form in the checkBox1_CheckedChanged method (why do you create a new form?), you set the Opacity property on the new form, but you do not show the form any way. You need to call Show() / ShowDialog() on the Form1 to show it.
If you wish to change the opacity of the current form you can do it this way:
this.Opacity = 1;

And a call like without this would work as well:
Opacity = 1;


text:
Q: Подвисает проверка синтаксиса в TypeScript Подскажите, почему может подвисать проверка синтаксиса в visual studio code.
Т.е я правлю то, на что он указал, но VSC продолжает ругаться на это место.
Затем я делаю намеренные ошибки и он на них не реагирует.
Когда я перезапускаю VSC, то все снова работает


text:
Q: C# Exception error when changing datagridview font size using another form I have two forms, one contains the datagridview and the other one contains a trackbar to change the font size of the datagridview like this:

I created the following code to allow Form2 to access Form1 datagridview:
//This is for Form1, the one that contains the datagridview:
public partial class Form1: Form
{
    public Form1()
    {
        Form2 f = new Form2();
        f.dataGridFromForm1 = dataGridView1;
    }

//This is for Form2, the one that contains the trackbar:
public partial class Form2: Form
{
    public DataGridView dataGridFromForm1 { get; set;}
    private void trackBar1_Scroll(object sender, EventArgs e)
    {
        dataGridFromForm1.RowsDefaultCellStyle.Font =
        new Font(dataGridFromForm1.RowsDefaultCellStyle.Font.FontFamily,
        float.Parse(trackBar1.Value.ToString()));
        label1.Text = trackBar1.Value.ToString() + "pt";
    }
}

During the build I do not get any errors, however when I try to slide the trackbar I get the following exception:

I'm not exactly sure what I'm missing out here as I thought I had already instantiated the datagridview. Any help would be appreciated.

A: This is because you are creating a new Form2 and then discarding it. In other words, your constructor for Form1 does this:
public Form1()
{
    Form2 f = new Form2();   // creates a new Form2
    f.dataGridFromForm1 = dataGridView1; // sets the property
    // f is now out of scope
}

Your f is a local variable inside the constructor. When you are showing the form later (presumably by calling Form2 f = new Form2(); again followed by f.Show()) it has no idea what the dataGridFromForm1 is (in fact its null by default).
You haven't shown enough code (your method to show the slider form is missing), but that code should probably set the slider. Perhaps something like:
private void btnShowSlider_Click(object sender, EventArgs e)
{
      using (var f = new Form2()) {
         f.dataGridFromForm1 = this.dataGridView1;
         f.ShowDialog(this);
      }
}

Note that in the above, the slider form will be a modal window and you won't be able to click back to it until you've closed it (which is probably a good thing)
Outside of that you could have a class instance variable inside Form1 that keeps track of your Form2 form showing/hiding/disposing of it as necessary. Another option would be to pass an instance of Form1 into the constructor for Form2, so it has a reference directly. That could look like this:
public partial class Form2 : Form {
    private Form1 _form1;
    public Form2(Form1 otherForm) {
          _form1 = otherForm;
    }
    private void trackBar1_Scroll(object sender, EventArgs e)
    {
        _form1.dataGridFromForm1.RowsDefaultCellStyle.Font =
        new Font(form1.dataGridFromForm1.RowsDefaultCellStyle.Font.FontFamily,
        trackBar1.Value);
        label1.Text = trackBar1.Value + "pt";
    }
}

and creating it in Form1 like:
 Form2 f = new Form2(this);
 f.Show();

making sure to dispose/etc when you are done.
Also note that TrackBar.Value is already an int and so you shouldn't need to convert it to a string and parse it again. Something like this should suffice:
new Font(..., trackBar1.Value)

A: try replace
public Form1()
{
    Form2 f = new Form2();
    f.dataGridFromForm1 = dataGridView1;
}

to
public Form1()
{
    this.Load += (s,e) =>
        {
            Form2 f = new Form2();
            f.dataGridFromForm1 = dataGridView1;
        };
}


text:
Q: My Fusion Drive unlinked in two pieces (SSD+HDD) and I want to restore it again in one piece i have an iMac 27′ late 2012 and I have a problem with my Fusion Drive … suddenly the SSD part and the HDD unlinked and now i have two separate disks .. I ran in Terminal: diskutil list and diskutil cs list witht he following results:

Can somebody help me how to continue from here to link the two disks again in one (Fusion Drive as previous).

Update: After deleting the Logical Volume Groups I get the following partition table:

A: To recreate a Fusion Drive you have to delete both Logical Volume Groups and create a new one. This will delete all data on both volumes "Macintosh HD".

*

*Booted to Recovery Mode open in the menubar Utilities > Terminal

*In Terminal enter diskutil list and diskutil cs list.

*Check that both disks (disk0 and disk1) are the internal disks with a size of 120 GB and 1 TB/3TB depending on your Fusion drive.

*Delete both Logical Volume Groups with:
diskutil cs delete lvgUUID #with lvgUUID: the UUID of the Logical Volume Group

In your case that's:
diskutil cs delete DD7FD...
diskutil cs delete 597C4...

Please use the complete UUIDs - I'm too lazy to write them down completely.

*Rebuild the Fusion Drive with:
diskutil cs create FusionDrive disk0s2 disk1s2

This will create a new Logical Volume Group

*Enter diskutil cs list to get the new lvgUUID

*To create a new Logical Volume enter:
diskutil cs createVolume new_lvgUUID jhfs+ "Macintosh HD" 0g


text:
Q: 2 Color CSS Icons Is there a way to make css icons like Font Awesome (or any other CSS icons) have 2 colors?
I know they are fonts so the color can be changed by something like style='color: red;', but is there a way to use 2 colors for the icons like an accent color and a main color?

A: The only options you have are,

*

*You can use text-shadow to give it a different colored shadow or stroke.

*You would need to use svg icons to control the path colors.

A: You can utilize color & background-color to control 2 color on the same icon, as long as you only need 2 colors (no other background).
<i class="fa fa-motorcycle blue onred"></i>
.blue {
    color: blue;
}
.onred {
    background-color: red;
}

fiddle


text:
Q: how to make python script restart itself when it stops because of error I have a script that has to run 24/7. the script reads some emails and sends some queries to an API.
sometimes the internet connection faces some problem and the script stops working. because of circumstances I cannot just use try/except and I need to restart the whole script.
so is there any way to make the script run itself from the start when faces some errors?


text:
Q: java compare two values of diffrent classes Let's say I have an Animal class, and a cat and a dog class that extend from the animal class.
Now I want to see if the dog and the cat have the same name.
I've tried this:
if(kitty.getName().equals(doggy.getName()))

But it won't let me do this because a cat is not a dog I guess? Is there a way I can still compare? Or do I really not wanna do something like this, if so then why not?

A: It's fairly difficult to tell what your problem is from your question without sample code, but let's take the following classes:
Animal class:
public abstract class Animal
{
    String name;

    public Animal(String name){
        this.name = name;
    }

    public String getName(){
        return name;
    }
}

Cat class:
public class Cat extends Animal
{
    public Cat(String name) {
        super(name);
    }
}

Dog class:
public class Dog extends Animal
{
    public Dog(String name) {
        super(name);
    }
}

And this example code:
    Cat cat = new Cat("kitty");
    Dog dog = new Dog("doggy");

    if (cat.getName().equals(dog.getName())){
        System.out.println("true");
    }
    else{
        System.out.println("false");
    }

This will produce the behaviour that I believe you are looking for. Is this different to how your code is structured? Please provide more information so it's easier to help.

A: It would be better for you to provide more information about your program. Let's say the error message, the return type of both getName() method and how you declare your dog and cat class as well as the initialisation in main. For what you had provided, it doesn't make any sense having difficulty on using "equals()" for comparison. Of course, assuming the return type for both methods is the same(like string maybe?)


text:
Q: obtener texto interno de option seleccionado creado previamente por javascript Estoy creando n cantidad de inputs Nota credito, basicamente es un div que contiene un input readonly llamado Nota credito, abajo un select con clase "n_credito" y otro input con clase "monto".

Estoy usando un funcion on change para ejecutar lo siguiente:
$(document).on('change','.n_credito', function () {
    //console.log($(this));
    var ncredit = $('select.n_credito option:selected').text();
    //console.log(ncredit_valor);
    //var ncredit_cor = ncredit_valor.split('e: ');
    //var ncredit = ncredit_cor['1'];
    console.log(ncredit);
    $(this).closest('div').find('.monto').val(ncredit);
    $(this).closest('div').find('.monto').attr("min","0");
    $(this).closest('div').find('.monto').attr("max",ncredit);
    ncredit = 0;
});

Basicamente mete el texto del valor seleccionado en el campo monto. Sucede que cuando solo existe un uno creado asigna el valor perfectamente. Cuando hay mas de uno parece que concatena los textos de los nota de credito creados.
En la funcion on change meto el valor seleccionado en la variable n_credit. Cuando hay dos o mas campos como en la imagen y le doy al select activando la funcion onchange guarda lo siguiente en n_credit
400-- Seleccione nota de credito --


text:
Q: React router render called even when path is not matched for the route I have a parent component where I have a router with routes. Each route is wrapped with the ProtectedRoute component that checks if the component should be rendered or not.
       const matchedPath = this.props.match.path;
       return (
       <Switch>
          <ProtectedRoute
            path={`${matchedPath}/start`}
            status={this.state.exam.status}
            requiredState="NOT_STARTED"
            component={StartExamPage}
          />
          <ProtectedRoute
            path={`${matchedPath}/task/:count`}
            status={this.state.exam.status}
            requiredState="STARTED"
            component={ExamPage}
          />
          <ProtectedRoute
            path={`${matchedPath}/summary`}
            status={this.state.exam.status}
            requiredState="STARTED"
            component={Summary}
            exam={this.exam.prove}
            navigateToTask={this.navigateToTask}
            logAction={this.logAction}
            handleSubmit={this.handleSubmit}
          />
     </Switch>)

The ProtectedRoute component looks like this:
class ProtectedRoute extends React.Component {
  examStatusDefaultUrl(status) {
    switch (status) {
      case 'NOT_STARTED':
        return '/exam/start';
      case 'STARTED':
        return '/exam/summary';
      default:
        throw new Error(`Invalid state: '${status}'`)
    }
  }

  render() {
    const { component: Component, ...componentProps } = this.props;
    return (
      <Route
        {...componentProps}
        render={props => {
          return (
            componentProps.status === componentProps.requiredState ?
            <Component {...componentProps} {...props}/> :
            <Redirect to={this.examStatusDefaultUrl(componentProps.status)}/>
        )}}
      />
    )
  }
}

export default ProtectedRoute;

Since I want to log when the each page is opened, I am calling a logAction function from the componentDidUpdate in Summary component:
componentDidMount() {
    this.mounted = true;
    console.log('summary ', this.props);
    this.props.logAction({action: actions.SUMMARY_OPENED});
}

The problem I have is that the Summary's componentDidMount is called even when the component is not mounted. It is called when the task/:count route is rendered. They have the same value of the status that I check to determine if the component is going to be rendered or not in the ProtectedRoute component. So, I wonder if that is the problem and how can I solve it, so that the componentDidMount is called only when the component is actually mounted and rendered?


text:
Q: Gambit-C Scheme: cannot load a windows dll I'm having troubles with dynamically loading a windows shared library with Gambit-C Scheme.
(c-declare "#include <stdlib.h>")
(c-declare "#include <Windows.h>")
(define load-library (c-lambda () void "
    HINSTANCE lib = LoadLibrary (\"test.dll\");
    if (lib) printf (\"works!\");
"))
(load-library)

Directory structure:
--test.scm
--test.dll

GSC commands:
gsc -exe test.scm

I've tested it in pure compiled C and it loads there.
Thank you.

A: Try an absolute path. To test things place test.dll in the root of C.
If an absolute path works, you know that the problem is related to the environment variable that holds the search path of dynamic libraries.


text:
Q: SpringJUnit4ClassRunner not working after packaging in Jar but works in IDE I am packaging JUnit test cases and suites in a jar and trying to execute these using JUnit core from inside main. The issue is that when I execute these testcases after packaging in JAR, beans are not injected (which implies an issue with spring context.) However, when I execute main method from IDE, beans are injected and everything works.
These test cases have a parent class which is loading the spring context.
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { AppConfig.class } )
public abstract class BaseTest {

    @Autowired
    protected WebDriver driver;

    @PreDestroy
    public void teardown() {
        ...
    }
}

A test class and suite-
public class SomeTestClass extends BaseTest {
    @Test
    public void someTestCase() {
        ...
    }
}

@RunWith(Suite.class)
@Suite.SuiteClasses({
    SomeTestClass.class
})
public class SomeTestSuite { }

There's a main method which is being used to execute these testcases/suites with JUnitCore.
    public static void main(String...args) {
        Result result = JUnitCore.runClasses(SomeTestSuite.class);

        if (result.wasSuccessful()) {
            LOGGER.info("All tests executed successfully: {}", result);
        } else {
            LOGGER.error("There are failures");
            for (Failure failure: result.getFailures()) {
                LOGGER.error("failure: {} msg: {} desc: {}", failure, failure.getMessage(), failure.getDescription(), failure.getException());
            }
        }
    }

I am getting NullPointerException when executing this via JAR but no issues when execute main method from within IDE.
I am using IntelliJ 2017.2.x, JUnit 4.12 for testcases and maven shade plugin 3.0 to package jar.
EDIT 1
Executing jar as -
java -jar myjar.jar

NPE when executing via JAR-
2017-11-29 10:16:00,567 [TestCasesExecutor:44] ERROR junit.framework.Test  - failure: testMethodName(testClass): null msg: null desc: testMethodName(testClass)
java.lang.NullPointerException
        at com.google.common.base.Preconditions.checkNotNull(Preconditions.java:770)
        at org.openqa.selenium.support.ui.FluentWait.<init>(FluentWait.java:96)
        at org.openqa.selenium.support.ui.WebDriverWait.<init>(WebDriverWait.java:71)
        at org.openqa.selenium.support.ui.WebDriverWait.<init>(WebDriverWait.java:45)
        at com.mycom.SomeTestClass.setup(BaseTest.java:37)
        at com.mycom.testcases.SplunkGcpScoreCardTest.logoutFromGcpScorecard(SplunkGcpScoreCardTest.java:27)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
        at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
        at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
        at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:33)
        at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
        at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
        at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
        at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:252)
        at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
        at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
        at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
        at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
        at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
        at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
        at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
        at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
        at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
        at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
        at org.junit.runners.Suite.runChild(Suite.java:128)
        at org.junit.runners.Suite.runChild(Suite.java:27)
        at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
        at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
        at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
        at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
        at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
        at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
        at org.junit.runners.Suite.runChild(Suite.java:128)
        at org.junit.runners.Suite.runChild(Suite.java:27)
        at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
        at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
        at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
        at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
        at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
        at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
        at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
        at org.junit.runner.JUnitCore.run(JUnitCore.java:115)
        at org.junit.runner.JUnitCore.run(JUnitCore.java:105)
        at org.junit.runner.JUnitCore.runClasses(JUnitCore.java:62)
        at org.junit.runner.JUnitCore.runClasses(JUnitCore.java:49)
        at com.mycom.TestCasesExecutor.main(TestCasesExecutor.java:37)

Background - I have some selenium test cases for an app in production.  It creates an instance of headless chrome for execution. The reason these were wrapped as test cases is because ideally we wanted to integrate this with saucelabs (saucelabs needs selenium code wrapped as testcases for execution.) However, currently there are some constraints as to how saucelabs is setup in my organization and we can't go down that road as of today but while we figure this out, we kept writing this code. So now, I am trying to create a JAR with this code and deploy it in production. This way, I don't have to make a lot of changes when we are able to move with Saucelabs.

A: After troubleshooting through spring code and logs, I figured that it's failing because my JAR doesn't have spring.factories file in it's META-INF.
Possible solutions-

*

*Change project to spring boot, enable auto-configuration and create a JAR using spring boot maven plugin which takes care of packaging it right.

*Create spring.factories file in src/main/resources/META-INF. You can write your own (refer spring doc) or copy spring.factories from any spring dependency in your project. Related question on SO.

I went with option 2 because it seemed easy in this scenario. I didn't need anything more than just spring.factories from spring-boot dependency, so option 1 would have been an overkill.


text:
Q: How can I use powershell creating different name webjob for different location? My question is specific but I guess simple who knows PowerShell more than I.
Let me explain my question :

*

*I need 6 different webjobs under 1 web service. my webjob will be the SonicMQ listener we developed can only listens to a single queue.

*My locations [istanbul,berlin, hamburg.....]

*I am trying to create 6 different  webjobs with "-istanbul","-berlin","-hamburg" . . .  suffix by using for loop in a task via Powershell.
below task should work like that : (psode code)

var listoflocations = [istanbul,berlin.hamburg, . . ]

foreach location in  listoflocations

  powershell -create mywebjob-location

my yaml file (small part):  how can I use powershell below ?
For this purpose I spend my time with some changes Thanks to your advice.
When I run below yaml I am getting this error:

- stage: Deploy_Test

  displayName: 'Deploy test'

  dependsOn: Test

  condition: and(succeeded(), ne(variables['Build.Reason'], 'PullRequest'))

  pool:

    name: 'bmersgtsteuw-app-eurotracs-pool'

  jobs:

  - deployment: yyyOrderShipmentJob

    displayName: 'Deploy Order Shipment Job'

    environment: 'xxx-CF-Test'

    strategy:

      runOnce:

        deploy:

          steps:

            - download: current

              artifact: drop

            - task: "HOW CAN I USE POWERSHELL HERE WITH FOREACH LOOP ?  [istanbul,berlin.hamburg, . . ]"

              inputs:

                ConnectionType: AzureRM

                azureSubscription: 'ARM-Con-xxx-yyy-TST-EUW-APP'

                appType: 'webApp'

                WebAppName: 'bmeapptsteuw-app-eurotracs'

                package: '$(Pipeline.Workspace)/drop/xxx.yyy.OrderShipmentJob-$(Build.BuildNumber).zip'

                removeAdditionalFilesFlag: true

My FINAL pipeline yaml  :

trigger:
- main

pool:
  vmImage: ubuntu-latest

parameters:
  - name: locations
    type: object
    default: [Berlin,Hamburg,Südwestfalen,Weser-Ems,Ostfalen,Westfalen]

steps:
- script: echo Hello, world!
  displayName: 'Run a one-line script'
- ${{ each location in parameters.locations }}:
             - task: PowerShell@2
               inputs:
                 targetType: 'inline'
                 script: 'Write-Host ${{ location  }}'
- script: |
    echo Add other tasks to build, test, and deploy your project.
    echo See https://aka.ms/yaml
  displayName: 'Run a multi-line script'

- task: DotNetCoreCLI@2
  inputs:
    command: 'publish'
    publishWebProjects: false
    projects: '**/MyWebJob.csproj'
    arguments: '--configuration $(buildConfiguration) --output $(build.artifactStagingDirectory)\App_Data\jobs\continuous\MyWebJob-${{ location  }}'
    zipAfterPublish: false
    modifyOutputPath: false

- task: PublishBuildArtifacts@1
  inputs:
    PathtoPublish: '$(Build.ArtifactStagingDirectory)'
    ArtifactName: 'drop'
    publishLocation: 'Container'

MY DESIRE RESULT :

A: In Azure DevOps Pipeline, you can define all location values in Object type Parameters. And then you can loop the parameter to get each value one by one via parameter expression(- ${{ each location in parameters.locations }}:).
Here is an example:
parameters:
  - name: locations
    type: object
    default: [istanbul,berlin.hamburg,xx,xxx,xxxx]

jobs:
  - deployment: test
    displayName: 'Deploy Order Shipment Job'
    environment: 'xxx-CF-Test'
    strategy:
      runOnce:
        deploy:
          steps:
           - ${{ each location in parameters.locations }}:
             - task: PowerShell@2
               inputs:
                 targetType: 'inline'
                 script: 'Write-Host ${{ location  }}'

For more detailed info, you can refer to this doc: Parameters
Update:
pool:
  vmImage: ubuntu-latest

parameters:
  - name: locations
    type: object
    default: [Berlin,Hamburg,Südwestfalen,Weser-Ems,Ostfalen,Westfalen]

steps:
- script: echo Hello, world!
  displayName: 'Run a one-line script'
- ${{ each location in parameters.locations }}:
             - task: PowerShell@2
               inputs:
                 targetType: 'inline'
                 script: 'Write-Host ${{ location  }}'

             - task: DotNetCoreCLI@2
               inputs:
                command: 'publish'
                publishWebProjects: false
                projects: '**/MyWebJob.csproj'
                arguments: '--configuration $(buildConfiguration) --output $(build.artifactStagingDirectory)\App_Data\jobs\continuous\MyWebJob-${{ location  }}'
                zipAfterPublish: false
                modifyOutputPath: false

- task: PublishBuildArtifacts@1
  inputs:
    PathtoPublish: '$(Build.ArtifactStagingDirectory)'
    ArtifactName: 'drop'
    publishLocation: 'Container'


text:
Q: $DFA/NFA$ for $L(OPPOSITE)=\{uv:vu\in L\}$ I'm trying to prove that: $L(OPPOSITE)=\{uv:vu\in L\} \in L_{FA}$ given that: $L \in L_{FA}$ .
I'm trying to construct a finite automata that accepts $L(OPPOSITE)$ in order to prove it but I got stuck.
Any help will be greatly appreciated!


text:
Q: What is a 2-way heap? I'm reading a book about AI and currently learning about pathfinding(currently doing the Dijkstra algorithm)
In the sample code he's using something he calls an IndexedPriorityQueue implemented as a two-way heap. I couldn't find any information on what a two-way heap is on google.

This search algorithm is implemented using an indexed priority queue.
  A priority queue, or PQ for short, is a queue that keeps its elements
  sorted in order of priority (no surprises there then). This type of
  data structure can be utilized to store the destination nodes of the
  edges on the search frontier, in order of increasing distance (cost)
  from the source node. This method guarantees that the node at the
  front of the PQ will be the node not already on the SPT that is
  closest to the source node.

This is how it gets implemented:
//----------------------- IndexedPriorityQLow ---------------------------
//
//  Priority queue based on an index into a set of keys. The queue is
//  maintained as a 2-way heap.
//
//  The priority in this implementation is the lowest valued key
//------------------------------------------------------------------------
template<class KeyType>
class IndexedPriorityQLow
{
private:

  std::vector<KeyType>&  m_vecKeys;

  std::vector<int>       m_Heap;

  std::vector<int>       m_invHeap;

  int                    m_iSize,
                         m_iMaxSize;

  void Swap(int a, int b)
  {
    int temp = m_Heap[a]; m_Heap[a] = m_Heap[b]; m_Heap[b] = temp;

    //change the handles too
    m_invHeap[m_Heap[a]] = a; m_invHeap[m_Heap[b]] = b;
  }

  void ReorderUpwards(int nd)
  {
    //move up the heap swapping the elements until the heap is ordered
    while ( (nd>1) && (m_vecKeys[m_Heap[nd/2]] > m_vecKeys[m_Heap[nd]]) )
    {
      Swap(nd/2, nd);

      nd /= 2;
    }
  }

  void ReorderDownwards(int nd, int HeapSize)
  {
    //move down the heap from node nd swapping the elements until
    //the heap is reordered
    while (2*nd <= HeapSize)
    {
      int child = 2 * nd;

      //set child to smaller of nd's two children
      if ((child < HeapSize) && (m_vecKeys[m_Heap[child]] > m_vecKeys[m_Heap[child+1]]))
      {
        ++child;
      }

      //if this nd is larger than its child, swap
      if (m_vecKeys[m_Heap[nd]] > m_vecKeys[m_Heap[child]])
      {
        Swap(child, nd);

        //move the current node down the tree
        nd = child;
      }

      else
      {
        break;
      }
    }
  }

public:

  //you must pass the constructor a reference to the std::vector the PQ
  //will be indexing into and the maximum size of the queue.
  IndexedPriorityQLow(std::vector<KeyType>& keys,
                      int              MaxSize):m_vecKeys(keys),
                                                m_iMaxSize(MaxSize),
                                                m_iSize(0)
  {
    m_Heap.assign(MaxSize+1, 0);
    m_invHeap.assign(MaxSize+1, 0);
  }

  bool empty()const{return (m_iSize==0);}

  //to insert an item into the queue it gets added to the end of the heap
  //and then the heap is reordered from the bottom up.
  void insert(const int idx)
  {
    assert (m_iSize+1 <= m_iMaxSize);

    ++m_iSize;

    m_Heap[m_iSize] = idx;

    m_invHeap[idx] = m_iSize;

    ReorderUpwards(m_iSize);
  }

  //to get the min item the first element is exchanged with the lowest
  //in the heap and then the heap is reordered from the top down.
  int Pop()
  {
    Swap(1, m_iSize);

    ReorderDownwards(1, m_iSize-1);

    return m_Heap[m_iSize--];
  }

  //if the value of one of the client key's changes then call this with
  //the key's index to adjust the queue accordingly
  void ChangePriority(const int idx)
  {
    ReorderUpwards(m_invHeap[idx]);
  }
};

Can anyone give me more information on what a 2-way heap is?

A: "Two-way heap" simply refers to the standard heap data structure. This code shows a very common way of implementing it, namely by flattening the tree structure of the heap into an array, in such a way that the index of a node's parent is always half of the index of the node (rounded down).

A: It is implemented AS a two way heap because he omits the 0 index in the heap to make parent- child calculation easier but the key values vektor begins at 0 index so inverted heap is storing indexes that keys to   heap witch stores indexes that keys to keyVector  to get appropriate value from keyVector you will need to do something like this  keyVector[heap[invHeap[itemIndex] ] ]  the rest of the code is just standard binary heap implementation.


text:
Q: passenger error 'cannot load such file: ... union_station_hooks_core' I get the following error on my rails app:
Web application could not be started

cannot load such file -- /opt/rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/bundler/gems/passenger-e139c4cd3ebd/src/ruby_supportlib/phusion_passenger/vendor/union_station_hooks_core/lib/union_station_hooks_core (LoadError)
  /u/sf/netmon/.rbenv/versions/2.3.0/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require'
  /u/sf/netmon/.rbenv/versions/2.3.0/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require'
  /opt/rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/bundler/gems/passenger-e139c4cd3ebd/src/ruby_supportlib/phusion_passenger.rb:235:in `require_passenger_lib'
  /opt/rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/bundler/gems/passenger-e139c4cd3ebd/src/ruby_supportlib/phusion_passenger/loader_shared_helpers.rb:232:in `before_loading_app_code_step1'
  /opt/rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/bundler/gems/passenger-e139c4cd3ebd/src/helper-scripts/rack-preloader.rb:99:in `preload_app'
  /opt/rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/bundler/gems/passenger-e139c4cd3ebd/src/helper-scripts/rack-preloader.rb:156:in `<module:App>'
  /opt/rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/bundler/gems/passenger-e139c4cd3ebd/src/helper-scripts/rack-preloader.rb:30:in `<module:PhusionPassenger>'
  /opt/rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/bundler/gems/passenger-e139c4cd3ebd/src/helper-scripts/rack-preloader.rb:29:in `<main>'
Error ID
28518bd5

Looking at the file system:
-bash-4.1$ pwd
/opt/rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/bundler/gems/passenger-e139c4cd3ebd/src/ruby_supportlib/phusion_passenger/vendor/union_station_hooks_core
-bash-4.1$ tree
.

0 directories, 0 files

So obviously there is indeed no such file... how should i fix this?
My Gemfile:
source 'https://rubygems.org'

gem 'rails', git: 'https://github.com/rails/rails', branch: '4-2-stable'
gem 'actionpack-action_caching'

gem 'pg'
gem 'redis'

gem 'rubytree'

gem 'turbolinks'
gem 'jquery-rails'
gem 'jquery-datatables-rails', git: 'https://github.com/rweng/jquery-datatables-rails'
gem 'rails-timeago'
gem 'dygraphs-rails'
gem 'underscore-rails'
gem 'd3_rails'
gem 'twitter-bootstrap-rails', '= 2.2.8'
gem 'less-rails'
gem 'coffee-rails', git: 'https://github.com/rails/coffee-rails'
gem 'coffeebeans'
gem 'jquery-ui-rails'

group :assets do
  gem 'sass-rails',   git: 'https://github.com/rails/sass-rails', branch: '5-0-stable'
  gem 'therubyracer', platforms: :ruby
  gem 'uglifier', '>= 1.0.3'
end

gem 'jbuilder', '~> 1.0.1'
gem 'passenger', git: 'https://github.com/FooBarWidget/passenger', branch: 'stable-5.0'
gem 'rack-webauth'

gem 'bunny'

Installed ruby 2.3.0 via ruby-build and passenger's apache module reported no errors:
$ ./passenger-install-apache2-module

...

Validating installation...

 * Checking whether this Passenger install is in PATH... (!)

   Please add /opt/rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/bundler/gems/passenger-e139c4cd3ebd/bin to PATH.
   Otherwise you will get "command not found" errors upon running
   any Passenger commands.

   Learn more at about PATH at:

     https://www.phusionpassenger.com/library/indepth/environment_variables.html#the-path-environment-variable

 * Checking whether there are no other Passenger installations... ✓
 * Checking whether Apache is installed... ✓
 * Checking whether the Passenger module is correctly configured in Apache... ✓

Detected 0 error(s), 1 warning(s).
Press ENTER to continue.

A: seems like a quick search through the passenger github helped...
union_station_hooks_core and union_station_hooks_rails are both git submodules on the main passenger git repo. so modifying my gemfile to include submodules: true will pull in the required files.
gem 'passenger', \
  git: 'https://github.com/FooBarWidget/passenger', \
  branch: 'stable-5.0', \
  submodules: true

A: I has same problem. It is because you passenger is not full.
Full passenger will be via make.
just download needed version like this
wget http://s3.amazonaws.com/phusion-passenger/releases/passenger-5.0.26.tar.gz

And extract to /opt/passenger
Then rerun passenger-install-nginx-module and add it to PATH -
echo 'PATH=/opt/passenger/bin:$PATH' >>etc/profile
PATH=/opt/passenger/bin:$PATH
export PATH
passenger-config validate-install

And not forget correct in http section
http {
  ...
  passenger_root /opt/passenger;
  passenger_ruby /usr/bin/ruby;
  ...
}


text:
Q: How do I create an Approval Workflow that updates the List Item that started the Workflow? I'm using SharePoint 2010 and I'm trying to create a workflow for a Help Desk List that will track tickets.
Here is the (intended) business process:
User generates a new Help Desk List Item (contains description of issue) ->
A new Approval Task is created for the User's Manager (which is tracked through another List, called Help Desk Tasks) ->
When the Manager Approves or Rejects it, the Task is updated to Complete ->
If the Manager Approves it, the original Help Desk List item should have its Status set to In Development. If the Manager Rejects it, the original Help Desk List item should have its Status set to Cancelled.
Right now, this doesn't work.  I can either set it up as an Approval Workflow but it won't update the fields for the Current Item, or I can set it up as a List Workflow and I can update the fields, but the Approval Task never starts.
Am I doing something wrong or am I missing something? Any help is appreciated.

A: I discovered the answer to this question on my own.  It's due to the way SharePoint handles Tasks during a workflow.  I was using the "Assign a Task" or "Assign a To-Do" when I needed to use COLLECT DATA FROM USER.  This will return the Id of the task, which can be used later to retrieve the user's Approval or Rejection.


text:
Q: Automatically Update Django Profile when creating user I am fairly new to Django and am hoping that this is as easy as I think it should be.
I have written a custom Django app that uses SaltStack as a back end for spinning up AWS instances.  When an instance comes up, it adds the user who created it using their SSH key.
I need to give each user a UID and GID so we can create user accounts on linux hosts for them.  Right now, this requires that an admin go in for each new user created and manually update these fields in the admin interface before a user can use the tool.
What I am hoping is that when a user is created, there is a way for Django to search through the profiles for the UID/GIDs that have already been used, increment by one, and assign it to the newly created user automatically.
Here is my Profile model:
class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    linux_username = models.CharField(max_length=50, blank=True)
    linux_uid = models.CharField(max_length=10, blank=True)
    linux_gid = models.CharField(max_length=10, blank=True)
    linux_ssh_authkey = models.TextField(max_length=1000, blank=True)

@receiver(post_save, sender=User)
def update_user_profile(sender, instance, created, **kwargs):
    if created:
        Profile.objects.created(user=instance)
    instance.profile.save()

I hope this makes sense--when a user signs up, they choose a linux username and upload their SSH public key.  But, we still have to go in as admins to populate the UID and GID fields.  For example, I am 4001, if another user signed up, he would be 4002.
Is there a way to add a simple bit of code to the update_user_profile function that will auto-populate these fields?
I have tried messing around a little but cannot figure out how to poll the database for the next available UID/GID and set it for the new user.
Any help would be much appreciated!
Thanks!

A: Yes, you can override the save() method of Profile for this.
class Profile(models.Model):
   user = models.OneToOneField(User, on_delete=models.CASCADE)
   linux_username = models.CharField(max_length=50, blank=True)
   linux_uid = models.CharField(max_length=10, blank=True)
   linux_gid = models.CharField(max_length=10, blank=True)
   linux_ssh_authkey = models.TextField(max_length=1000, blank=True)

   def save(self, force_insert=False, force_update=False, using=None,
         update_fields=None):
       if not self.id:
         try:
            last_user_profile = User.objects.latest('date_joined').profile
            self.linux_uid = str(int(last_user_profile.linux_uid)+1)
            self.linux_gid = str(int(last_user_profile.linux_gid)+1)
         except User.DoesNotExist:
           self.linux_uid = '0000'
           self.linux_gid = '0000'
       return super(Profile, self).save()

The above code will get the profile of the latest user and add 1 to the UID and GID and store it. If there are no users already registered it will give default value of '0000' to both the UID and GIDs.

A: I think I found the answer, though there may be a better way to do this.  Thanks to Ajmal Noushad for pointing me in the right direction.  Here is the final code that worked for me--if there is a better way to do this, please let me know.
class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    linux_username = models.CharField(max_length=50, blank=True)
    linux_uid = models.CharField(max_length=10, blank=True)
    linux_gid = models.CharField(max_length=10, blank=True)
    linux_ssh_authkey = models.TextField(max_length=1000, blank=True)

@receiver(post_save, sender=User)
def update_user_profile(sender, instance, created, **kwargs):
    if created:
        Profile.objects.create(user=instance)

    try:
        last_user_joined = User.objects.all().order_by('date_joined').reverse()[1].profile
        instance.profile.linux_uid = str(int(last_user_joined.linux_uid)+1)
        instance.profile.linux_gid = str(int(last_user_joined.linux_gid)+1)
    except User.DoesNotExist:
        instance.profile.linux_uid = '0000'
        instance.profile.linux_gid = '0000'

    instance.profile.save()

This creates the profile for the user and automatically populates their UID with the next available UID in the list, but it is based on the user that is created last, not the highest UID.  So if you create a user and manually set the UID to 4002, and another user already has 4003, the next user will automatically get 4003 as well.  There is room for improvement, but I think this will work for now.
Thanks to all for your help!


text:
Q: Covert one polygon in a MULTIPOLYGON to a SpatialPolygonsDataFrame with R I am fairly new to GIS (recently returning after a very long hiatus).  I have a gpkg file (fixedKNPandBoundaryPAs.gpkg) for Kruger National Park, South Africa, obtained here (scroll halfway down and click 'Download all (33.7 MB)':
https://zivahub.uct.ac.za/articles/dataset/Spatial_Data/11585136
There is only one layer in the gpkg file (fixedKNPandBoundaryPAs) with Geometry type: MULTIPOLYGON.  There are 11 features, which I assume means 11 polygons.  There are eight fields which I think means every polygon has eight attributes.
I wish to extract just the polygon for Kruger National Park, not any of the neighboring nature or game reserves.  Then I wish to convert the polygon for Kruger National Park into a SpatialPolygonsDataFrame.
Below is my R code attempting to do that.  This R code is a little messy because I show the results of many steps and includes several dead ends:
# I do not know which of these libraries is critical and which are not needed
library(GISTools)
library(here)
library(mapdata)
library(mapproj)
library(maps)
library(maptools)
library(mapview)
library(raster)
library(rgdal)
library(rgeos)
library(sf)
library(sp)
library(tidyverse)
mapviewOptions(fgb = FALSE)

# Check available layers in 'fixedKNPandBoundaryPAs.gpkg'
st_layers("C:/Users/mark_/Documents/ctmm/Kruger_National_Park/fixedKNPandBoundaryPAs.gpkg")
# Driver: GPKG
# Available layers:
#               layer_name geometry_type features fields
# 1 fixedKNPandBoundaryPAs Multi Polygon       11      8

# import 'fixedKNPandBoundaryPAs' from 'fixedKNPandBoundaryPAs.gpkg'
Kruger <- st_read(dsn = "C:/Users/mark_/Documents/ctmm/Kruger_National_Park/fixedKNPandBoundaryPAs.gpkg", layer='fixedKNPandBoundaryPAs')
# Reading layer `fixedKNPandBoundaryPAs' from data source `C:\Users\mark_\Documents\ctmm\Kruger_National_Park\fixedKNPandBoundaryPAs.gpkg' using driver `GPKG'
# Simple feature collection with 11 features and 8 fields
# Geometry type: MULTIPOLYGON
# Dimension:     XY
# Bounding box:  xmin: 30.88982 ymin: -25.5303 xmax: 32.032 ymax: -22.32804
# Geodetic CRS:  WGS 84

# View the data
Kruger
Kruger[11,]

# Select just the park, not any of the nature or game reserves
# But I do not know how to convert the KNP MULTIPOLYGON into a SpatialPolygonsDataFrame
# This was a dead end for me
KNP <- Kruger[Kruger$SITE_TYPE == "National Park",]
KNP
# Simple feature collection with 1 feature and 8 fields
# Geometry type: MULTIPOLYGON
# Dimension:     XY
# Bounding box:  xmin: 30.88982 ymin: -25.5303 xmax: 32.032 ymax: -22.32804
# Geodetic CRS:  WGS 84
#   WDPAID              CUR_NME WMCM_TYPE MAJ_TYPE     SITE_TYPE    D_DCLAR LEGAL_STAT GIS_AREA                           geom
# 2    873 Kruger National Park  National       PA National Park 1926-07-26 Designated  1916915 MULTIPOLYGON (((31.38601 -2...

# Plot just the park polygon with no fill
plot(KNP["WDPAID"], col=NA)

# Split the Kruger MULTIPOLYGON into separate polygons
Kruger.polygons <- st_cast(Kruger, "POLYGON")
# Warning message:
# In st_cast.sf(Kruger, "POLYGON") :
#   repeating attributes for all sub-geometries for which they may not be constant

Kruger.polygons
# Simple feature collection with 12 features and 8 fields
# Geometry type: POLYGON
# Dimension:     XY
# Bounding box:  xmin: 30.88982 ymin: -25.5303 xmax: 32.032 ymax: -22.32804
# Geodetic CRS:  WGS 84
# First 10 features:
#        WDPAID                                CUR_NME WMCM_TYPE MAJ_TYPE      SITE_TYPE    D_DCLAR LEGAL_STAT    GIS_AREA                           geom
# 1      351116     Sabie Sands Private Nature Reserve  National       PA Nature Reserve 1965-01-27 Designated   59570.419 POLYGON ((31.60339 -24.7093...
# 2         873                   Kruger National Park  National       PA  National Park 1926-07-26 Designated 1916915.360 POLYGON ((31.38601 -24.4843...
# 3   555563989                  Pafuri Nature Reserve  National       PA Nature Reserve 1954-09-08 Designated   19755.774 POLYGON ((31.16474 -22.3293...
# 4   555570576 Rondalia-Letaba Private Nature Reserve  National       PA Nature Reserve 1965-12-15 Designated   21918.745 POLYGON ((31.06034 -23.6464...
# 5   555571052            Letaba Ranch Nature Reserve  National       PA Nature Reserve 2016-06-17 Designated   24909.868 POLYGON ((31.01752 -23.7567...
# 5.1 555571052            Letaba Ranch Nature Reserve  National       PA Nature Reserve 2016-06-17 Designated   24909.868 POLYGON ((31.06072 -23.6469...
# 6   555564082         Umbabat Private Nature Reserve  National       PA Nature Reserve 1969-05-21 Designated   14505.518 POLYGON ((31.37728 -24.1101...
# 7        9072                 Manyeleti Game Reserve  National       PA Nature Reserve 1967-12-15 Designated   17253.707 POLYGON ((31.59821 -24.6119...
# 8   555563621     Buffelshoek Private Nature Reserve  National       PA Nature Reserve 1969-03-05 Designated    4113.504 POLYGON ((31.60138 -24.6988...
# 9      300443        Klaserie Private Nature Reserve  National       PA Nature Reserve 1972-01-26 Designated   59045.239 POLYGON ((31.19972 -24.0533...

# Select just the Kruger National Park POLYGON
KNP.polygon <- Kruger.polygons[Kruger.polygons$SITE_TYPE == "National Park",]
# KNP.polygon
# Simple feature collection with 1 feature and 8 fields
# Geometry type: POLYGON
# Dimension:     XY
# Bounding box:  xmin: 30.88982 ymin: -25.5303 xmax: 32.032 ymax: -22.32804
# Geodetic CRS:  WGS 84
#   WDPAID              CUR_NME WMCM_TYPE MAJ_TYPE     SITE_TYPE    D_DCLAR LEGAL_STAT GIS_AREA                           geom
# 2    873 Kruger National Park  National       PA National Park 1926-07-26 Designated  1916915 POLYGON ((31.38601 -24.4843...

plot(KNP.polygon["WDPAID"], col=NA)

# How do I convert the KNP.polygon POLYGON into a SpatialPolygonsDataFrame?
# This does not work:
writeOGR(KNP.polygon, dsn="C:/Users/mark_/Documents/ctmm/my_KNP", layer="my_KNP", driver="ESRI Shapefile")
# Error in writeOGR(KNP.polygon, dsn = "C:/Users/mark_/Documents/ctmm/my_KNP",  :
#  inherits(obj, "Spatial") is not TRUE

# How do I convert the Kruger MULTIPOLYGON into 11 separate SpatialPolygonsDataFrames?
# This does not work:
Kruger$CUR_NME
y <- unique(Kruger$CUR_NME)
for(i in y[1:length(y)]){
 temp = Kruger[Kruger$CUR_NME == i, ]
         writeOGR(temp, dsn="C:/Users/mark_/Documents/ctmm/my_KNP", i, driver="ESRI Shapefile", overwrite_layer=TRUE)
}
# Error in writeOGR(temp, dsn = "C:/Users/mark_/Documents/ctmm/my_KNP",  :
#  inherits(obj, "Spatial") is not TRUE

A: This approach worked to create a shapefile for the park that could be imported either into QGIS or back into R which might be all I really need.
library(GISTools)
library(here)
library(mapdata)
library(mapproj)
library(maps)
library(maptools)
library(mapview)
library(raster)
library(rgdal)
library(rgeos)
library(sf)
library(sp)
library(tidyverse)

mapviewOptions(fgb = FALSE)

# Kruger National Park file 'fixedKNPandBoundaryPAs.gpkg' obtained here:
# https://zivahub.uct.ac.za/articles/dataset/Spatial_Data/11585136

# Check available layers in 'fixedKNPandBoundaryPAs.gpkg'
st_layers("C:/Users/mark_/Documents/ctmm/Kruger_National_Park/fixedKNPandBoundaryPAs.gpkg")

# import 'fixedKNPandBoundaryPAs' from 'fixedKNPandBoundaryPAs.gpkg'
Kruger <- st_read(dsn = "C:/Users/mark_/Documents/ctmm/Kruger_National_Park/fixedKNPandBoundaryPAs.gpkg", layer='fixedKNPandBoundaryPAs')

# Writes a shape file to the appropriate directory which then can be read into QGIS
st_write(Kruger[2,], "C:/Users/mark_/Documents/ctmm/my_Kruger/my_Kruger.shp")

# Read the shape file 'my_Kruger.shp' back into R
st_layers("C:/Users/mark_/Documents/ctmm/my_Kruger/my_Kruger.shp")

KNP.imported <- st_read(dsn = "C:/Users/mark_/Documents/ctmm/my_Kruger/my_Kruger.shp", layer = 'my_Kruger')
KNP.imported

plot(KNP.imported[,1])

The approach described here did not seem to work I guess because of the geom column in Kruger:
https://stackoverflow.com/questions/48511524/how-do-you-convert-from-a-multipolygon-to-a-spatial-polygons-data-frame


text:
Q: MUI two AppBar in the same page as component = 'header' and component = 'footer'. How to override styles using createTheme()? Having two appBars components in the same page is a good approach (one as header and the other one as footer)? Besides, I am using the MUI createTheme to override some styles. I am doing this to override the appBar component.
components: { ...
MuiAppBar: {
      styleOverrides: {
        root: {
          minHeight: '4.375rem',
          backgroundColor: appColors.aqua600,
        },
      },
    }, ...

This works fine, but as was wondering how could I override the style of an AppBar that is renders as 'header' and style the other appBar that is rendered as 'footer'
The component usage:
<AppBar
        component="header | footer" ...
</AppBar>

I know that can be easily done with CSS, but I was wondering if this can be done using the createTheme from MUI?

A: It can be done by overriding styles based on props using ownerState.

Overrides based on props
You can pass a callback as a value in each slot of the component's styleOverrides to apply styles based on props.
The ownerState prop is a combination of public props that you pass to the component + internal state of the component.

You can check more on docs.
So, the custom theme for MuiAppBar should be something like this:
components: {
    MuiAppBar: {
      styleOverrides: {
        root: ({ ownerState }) => {
          return {
            ...(ownerState.component === "header" && {
              backgroundColor: "#202020"
            })
          };
        }
      }
    }
  }


text:
Q: IIntelliJ Gradle sync failed: The supplied javaHome seems to be invalid. I cannot find the java executable Recently my organization has changed the jdk from Adopt to Adoptium.
Since then , my Intellij is not working.
Error:-

Gradle sync failed: The supplied javaHome seems to be invalid. I cannot find the java executable. Tried location: C:\Program Files\AdoptOpenJDK\jdk-8.0.282.8-hotspot\bin\java.exe

*

*I have changed the JDK version in settings -> Build -> Gradle -> Changed the version to 1.8.0_332.

*In JAVA_HOME (System Env Varaiable )= C:\Program Files\Eclipse Adoptium\jdk-8.0.332.9-hotspot\

*In CMD - Java Version is
openjdk version "1.8.0_332"
OpenJDK Runtime Environment (Temurin)(build 1.8.0_332-b09)
OpenJDK 64-Bit Server VM (Temurin)(build 25.332-b09, mixed mode)
I have restarted my Intellij and machine multiple times. Still the error is not going away.

A: *

*Download gradle zip file from https://gradle.org/next-steps/?version=7.0.2&format=all
and unzip and keep it in a local path

*settings -> Build, Execution,Deployment -> Build tools -> Gradle

Gradle user home -> choose the unzipped gradle (from step 1).
Apply and OK
3. Rebuild the Gradle.
This Worked For Me (and others who faced the same issue in our team)


text:
Q: How to write this query to display a COUNT with other fields I have following two tables:
Person {PersonId, FirstName, LastName,Age .... }
Photo {PhotoId,PersonId, Size, Path}

Obviously, PersonId in the Photo table is an FK referencing the Person table.
I want to write a query to display all the fields of a Person , along with the number of photos he/she has in the Photo table.
A row of the result will looks like
24|Ryan|Smith|28|6
How to write such query in tsql?
Thanks,

A: You need a subquery in order to avoid having to repeat all the columns from Person in your group by clause.
SELECT
  p.PersonId,
  p.FirstName,
  p.LastName,
  p.Age,
  coalesce(ph.PhotoCount, 0) as Photocount
FROM
  Person p
  LEFT OUTER JOIN
     (SELECT PersonId,
      COUNT(PhotoId) as PhotoCount
      FROM Photo
      GROUP BY PersonId) ph
  ON p.PersonId = ph.PersonId

A:     SELECT
       p.PersonId,
       p.FirstName,
       p.LastName,
       p.Age,
       CASE WHEN
            t.ThePhotoCount IS NULL THEN 0 ELSE t.ThePhotoCount END AS TheCount
       --the above line could also use COALESCE
   FROM
       Person p
   LEFT JOIN
         (SELECT
             PersonId,
             COUNT(*)  As ThePhotoCount
         FROM
             Photo
         GROUP BY PersonId) t
    ON t.PersonId = p.PersonID

A: SELECT P.PersonId, FirstName, LastName,Age, COUNT(PhotoId) AS Num
FROM Person P
     LEFT OUTER JOIN PHOTO PH ON P.PersonId =  PH.PersonId
GROUP BY P.PersonId, FirstName, LastName,Age

A: select Person.*, count(PhotoId) from Person left join Photo on Person.PersonId = Photo.PersonId

A: IMO GROUP BY should be the solution, something like this works for me even with other table joins:
SELECT meetings.id, meetings.location, meetings.date, COUNT( users.id ) AS attendees
FROM  `meetings`
LEFT JOIN users ON meetings.id = users.meeting_id
WHERE meetings.moderator_id =  'XXX'
GROUP BY meetings.id


text:
Q: How do I solve the "cannot implicitly convert [type] to [interface]" error when the interface has multiple generic parameters? I have the following interfaces:
public interface IQueryHandler<in TQuery, out TResult> where TResult : class
                                                where TQuery : IQuery<TResult>
{
    TResult Handle(TQuery query);
}

public interface IQuery<TResult> // Doesn't require anything special, just used to guarantee that IQueryHandlers get the right parameters.
{
}

It's intended to be used by IQueryHandlers which will take in an IQuery<TResult> which defines a query that returns an object of type TResult. The IQueryHandler's Handle method then returns a TResult.
I have the interface implemented on a DataQueryHandlers class:
public class DataQueryHandlers : IQueryHandler<GetDataById, SomeData>
{
    private IDataSource source;

    public DataQueryHandlers(IDataSource source)
    {
        this.source = source
    }

    public SomeData Handle(GetDataById query)
    {
        // Get the data here and return SomeData object
    }
}

where SomeData is a data entity, and GetDataById is an IQuery<SomeData>
However, when I try to instantiate a specific instance:
private IQueryHandler<IQuery<SomeData>, SomeData> dataQueryHandlers;
private IDataSource source;

source = new DataSource(); // some data provider

dataQueryHandlers = new DataQueryHandlers(datasource); // This line won't compile

I get a compiler error:

Cannot implicitly convert type DataQueryHandlers to
  IQueryHandler<IQuery<SomeData>, SomeData>. An explicit conversion
  exists (are you missing a cast?)

I'm sure this is a covariant/contravariant related problem, but I fail to see where the mismatch is. Is there a problem with my in/out generic modifiers? Is what I'm trying to do fundamentally incorrect in some way? Am I missing some obvious "hair on a fish" scenario here?

A: You should change your derived class to generic one to be able to do it.
Change it to this:
public class DataQueryHandlers<in TQuery, out TResult> : IQueryHandler<TQuery, TResult> where TResult : class where TQuery : IQuery<TResult>
{
    private IDataSource source;

    public DataQueryHandlers(IDataSource source)
    {
        this.source = source
    }

    public TResult Handle(TQuery query)
    {
        // Get the data here and return TResult object
    }
}

More about Generic Classes you can find MSDN


text:
Q: How to get a generated karaf kar file to be included with a maven assembly? Trying to get the maven assembly plugin to include my kar file.
This below works fine with "war" or "jar", but not with "kar".
<dependencySets>
    <dependencySet>
        <includes>
            <include>${project.groupId}:*:kar:${project.version}</include>
        </includes>
        <useProjectArtifact>true</useProjectArtifact>
        <outputDirectory>karaf/deploy</outputDirectory>
        <unpack>false</unpack>
    </dependencySet>
</dependencySets>

Thank you.

A: Try adding the kar file as a dependency in the pom.


text:
Q: jQuery: using css selector to compare position values? Can I use the following code to compare the value of the attribute "left" ?
if ($('.pager').css('left') < 100 + 'px')

Or should I different code ? (My issue is how to deal with 'px', if I should remove it or at least use it consistently in the code.
thanks

A: Just use parseInt, it will ignore the px for you:
if (parseInt($('.pager').css('left')) < 100)

Or you can use the left property within position():
var left = $('.pager').position().left;
if (left < 100) // Etc

A: Consider using a variable.
var pagerPos = parseInt($('.pager').css('left'))
if (pagerPos < 100) {...}

Remember that your if statement is in this case trying to compare a number value to a number value.  You need to use parseInt() to strip off the 'px' held in the CSS.  After that you should be golden!

A: you can use .style of the DOM element
document.getElementById("id").style.left


text:
Q: How do you properly serve an SVG file for use as a background image in IE9? I'm trying to use an SVG background to take the place of a CSS3 gradient in IE9 (which doesn't support CSS3 gradient). I've tested it locally and it works like a dream. However, when I upload these changes to the live site, it doesn't work. I've verified that the SVG file IS up on the server in its intact form.
Here's the file:
http://www.shmax.com/css/record-box-gradient.svg
And here's a simple test page, where it's used as the background of a div:
http://www.shmax.com/gradient.html?DBGSESSID=-1
View the page in both Chrome and IE9, and you'll notice that it appears in Chrome, but not in IE9. Oddly, it DOES work in IE9 when I view it on my local test machine.
One thing I've noticed is that when I view the headers for this asset in Fiddler, it says "Transport - Connection: close". Does that mean anything? Is this something I need to fix in my .htaccess?
Thanks for the help, guys.

A: Your simple test page works for me in IE9; I see a gradient in the background of the div.
Try this:

*

*Press F12 to open the Developer Tools

*What is the "Document Mode" in the 'menu bar' of the tools? If you set it to "IE9 Standards", do you see the gradient?

*Click on the Network tab for the developer tools, click on "Start Capturing", reload your test page, and then click on "Stop Capturing". Do you see a request for /css/record-box-gradient.svg in the the URLs? Is it either status 200 or 304?


text:
Q: one table or several table in mysql i have a huge data.what is the best way for store this data in database.store this data to one table or store in several table?
if i want to save data to several table i must create table for every user.

A: I think a table per users is not a good, please read above link it will hwlp you to design a better and more efficient database
MySQL :: An Introduction to Database Normalization
http://ftp.nchu.edu.tw/MySQL/tech-resources/articles/intro-to-normalization.html

A: In a relational dbms, data table size doesn't dictate the database design, but only the relations of entities.
So even with a table of billions of records holding large multi media data, you would not make this several tables, just because the table gets so big.
Maybe using an RDBMS is a wrong approach for your task. Maybe a NoSQL dbms would be better. Even a simple file system could be the way to go.
Maybe however, an RDBMS is the right approach. We don't know, because you have told us almost nothing about your database. And what seems huge to you may be considered small by your dbms.
Are you saying that you would have a huge table holding data for all users, but every user will only be interested in their own data? Then simply partition the table by user. The database design will remain the same, only the underlying storage and internal data access will be different. As long as your queries always select one user's data, you will stay within one partition and data access will be fast.
Here is how to partition a table:
alter table user_movies
add primary key (user_id, movie_id)
partition by hash(user_id) partitions 100;

A: So many factors you should be taken into consideration before making decisions. But how about this one, try "no-sql" type db, each user will be treated as key, the info about this user will be treated as value.


text:
Q: The second derivative of a holomorphic function STATEMENT: Let $f:S\rightarrow S$ be a holomorphic function defined on the unit open square centered at 0. If $f(0)=0, f'(0)=1$ what is $f''(0)$?
QUESTION: Can someone nudge me in the right direction. I tried taylor expanding $f$ and using Cauchy's inequality for complex functions, but I can't seem to derive an answer for $f''$ evaluated at 0.

A: Let $\varphi \colon \mathbb{D} \to S$ be the biholomorphic mapping with $\varphi(0) = 0$ and $\varphi'(0) > 0$. Consider the map
$$\varphi^{-1} \circ f \circ \varphi.$$


text:
Q: Adding custom method to WebAPI I am new to the WebAPI and I got stuck in a problem. I am using API controller which contains two Get methods. One is used for GetAll while other retrieves data on the basis of ID. Now what I want to do is to implement another get method which takes string and returns records. I have made that method and call that it does not work as my route was default API route which was like:
config.Routes.MapHttpRoute(name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } );

When I added a new route to call my custom GetMethod:
config.Routes.MapHttpRoute(name: "Custom", routeTemplate: "api/{controller}/{action}/{id}", defaults: new { id = RouteParameter.Optional } );

I was able to call my custom GetMethod but now I lose the restful method with id parameters. How can I use both methods?

A: Have you tried using your second route only and call as
api/customer/get/1
api/customer/getall/
api/customer/getmethod/one

In the above, customer is the controller name. You have to replace with yours.
Please check whether you have the routes in the webapiconfig.cs file. Please refer this article for more help.

A: Better not to change routes.
You can use Action Name to differentiate the calls and can add more functions. Take a look at this answer:
How to add custom methods to ASP.NET WebAPI controller?


text:
Q: Automatically populate columns with Person/Group Mobile Number SP2013 Im creating a simple contact list and im looking at ways to ensure theres little oppourtunity for the end users to enter incorrect information when i hand it back over to them.
One thing idea i was speculating about was the idea of having the user enter the persons name into a person/group column and then the mobile number column & email address column would be populated with that persons details that are stored under their name.
One idea i had for this was to set up the mobile phone number & email address columns as person/group columns and setting up a workflow that that says, when the end user is entering a new item or editing one, the form will only show one person/group column where they enter the name of the person theyre looking to add. The workflow would then set this same value in the mobile & email columns, which have been set to display as mobile number and work email respectively.
Should also point out im using sharepoint online with SPD 2013
Im still newish to sharepoint so im not too sure how the functionality and general syntax involved in creating this workflow/ if this would even work!
Any advice or help would be most appreciated!


text:
Q: C# WM_VScroll & VScroll Control I am trying to create a subclass of VScroll control and intercepting the WM_VSCROLL message to do some stuff. On msdn, and countless articles/forums, WM_VSCROLL is supposed to be 0x115, even in the windows header file that's what it is. However waiting on 0x115 doesn't bring anything. I realized it's coming through as 0x2115 instead, even this article is using it as 0x2115. Any reason/explanation as to why it's coming as 0x2115 instead? Is it because it's a WinForms control?
Thanks

A: Yes, this is pretty standard in Windows GUI class libraries, Winforms is no exception.  The native Windows control, ScrollBar in your case, send notifications to their parent.  After all, they were designed to make their parent act on the notification, not themselves.  Or in other words, you expect the parent window to scroll.
That however is not very compatible with the notion of a control class whose behavior you can modify by overriding its message handling and generation.  Or for that matter the idea of events in .NET, anybody can subscribe to the Scroll event, not just the parent.
That buys a lot of goodness, but something must be done to get the WM_VSCROLL message from the parent back to the control.  Which is what the Winforms plumbing takes care of.  It sends the message back but alters the message number to indicate that it was a reflected message, not the original.  It adds 0x2000.  The value of the (fake) WM_REFLECT message in the Winforms source code.


text:
Q: Capturar teclas pressionadas mesmo sendo pressionadas fora do app bom dia
Eu fiz um programinha aonde ele mostra a tecla digitada , é algo bem simples , apenas para eu aprender o uso do Windows form application.
Meu objetivo era que ao rodar outro app , por exemplo o word , ele aparecesse encima as teclas que iam sendo digitadas , mas ao abrir outra janela ele para de capturar.
obs: é minha primeira/segunda vez fazendo um post , perdão se ficou malfeito.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace prj1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            this.TopMost = true;
        }

        private void button1_KeyPress(object sender, KeyPressEventArgs e)
        {
            lbl1.Text = e.KeyChar.ToString();
        }

        private void bnt1_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }
    }
}

A: Vi aqui um codigo que você pode tentar.
Utilizando a dll User32 combinado com um Timer em seu Form, você pode ficar verificando as teclas que forem sendo pressionadas.
Não sei se seria a melhor forma a ser utilizada, mas eu testei e funcionou muito bem.
    public Form1()
    {
        InitializeComponent();
        timer1.Start();
    }

    [DllImport("User32.dll", CharSet = CharSet.Auto)]
    public static extern Int16 GetAsyncKeyState(int vKey);

    private void timer1_Tick(object sender, EventArgs e)
    {
        while (true)
        {
            for (int key = 0; key < 255; key++)
            {
                //caso seja diferente da tecla pressionada, irá retornar zero
                if (GetAsyncKeyState(key) == -32767)
                {
                    char keyPress = Convert.ToChar(key);
                }
            }
        }
    }


text:
Q: Is it possible to melt soft metals with household current? I'm an electronics enthusiast with an interest in welding. Just out of curiosity, I was playing around with the voltage in my house (using proper safety techniques) and I started wondering if the arc from the AC in a standard wall socket could melt some metals, like lead or copper, if non-combustible electrodes were used to strike the arc.

A: It depends how fast you want to melt soft metals.
Put a screwdriver under a power cable staple behind the wall near the breaker panel and you can even vaporize copper wire and steel in screwdriver  in milliseconds (bang) and spray it all over your plastic safety lens, as I have done in my learning phase 40 yrs ago.(newbie days in Rec Room construction)
To do it in a controlled fashion only needs some thermodynamic heat equations and sufficient thermal resistance in an insulted ceramic oven and sufficient heat.
Mass Spectrometers can convert the sample into a plasma with RF energy vacuum, helium/argon burn it and accelerate it past a grid then deflect it and measure the mass of each plasma particle deflected.
A 300W RF coil ( that looks like 1/8" copper plumbing) can make an iron rod red hot in seconds, but not melt it.
A 1000:1 turns ratio spot welder melts metal and welds it instantly by stepping up the AC current in large jaws ( 1 turn output loop) with 10kA at the tungsten electrodes.(preferred)
TIG/MIG/Plasma Welding uses a similar approach with a low current trigger voltage to bridge the gap and then the high current low voltage provides the follow-on energy with I²R [watt] * Rth [degC/W]/time[s] for thermal resistance Rth to get degC/second rise to melting point. where Arc current is inverse to R such that R=k1/I and fuse time = k2 * Amp-seconds [As]


text:
Q: How do I programmatically delete row 0 of UITableView? I have an app that has a table view.  Every minute or so I want the first row of the UITableView to disappear.  It would be nice to have it animate off.  I am assuming I need to use something like this:
let myNSIndexPath = [NSIndexPath(forRow: 0, inSection: 0)]
mainTableView.deleteRowsAtIndexPaths(myNSIndexPath, withRowAnimation:UITableViewRowAnimation.Fade)

This doesn't work.  I'm not sure exactly how to use IndexPath correctly. My table only has one section and I always want the cell at Index 0 to be removed.  What must to do to get this working correctly?

A: One way
Use removeAtIndex
yourarray.removeAtIndex(indexPath.row)

And don't forget to reload the table view
tableView.reloadData()

Second Way
yourIndexPath = [NSIndexPath(forRow: 0, inSection: 0)]
yourtable.beginUpdates() //if you are performing more than one operation use this
yourarray.removeObjectAtIndex(myNSIndexPath.row)
yourtable.deleteRowsAtIndexPaths(NSArray(object: yourIndexPath), withRowAnimation: UITableViewRowAnimation.Left)
yourtable.endUpdates() //if you are performing more than one operation use this

Took help from

*

*@Rmaddy

*https://developer.apple.com/library/ios/documentation/UIKit/Reference/UITableView_Class/

A: You can delete the first cell like this.
One way
   let myNSIndexPath = [NSIndexPath(forRow: 0, inSection: 0)]

    self.tableView.beginUpdates()
    self.arrayData.removeObjectAtIndex(myNSIndexPath.row) // also remove an array object if exists.
    self.tableView.deleteRowsAtIndexPaths(NSArray(object: myNSIndexPath), withRowAnimation: UITableViewRowAnimation.Left)
    self.tableView.endUpdates()

Second way
yourArr.removeAtIndex(0)
self.tableView.reloadData()

A: in SWIFT 4
You can delete the row like this.
    let indexPathRow=sender.tag
    let indexPath = IndexPath(row: indexPathRow, section: 0)
    arrayList.remove(at: indexPathRow)
    mainTableView.deleteRows(at: [indexPath], with: .none)


text:
Q: Spectral radius Volterra operator with an arbitrary kernel from $L^2$ How to prove that the spectral radius $r \left( V_K \right)$ of a Volterra operator with an arbitrary kernel is zero.
$$V_K : L^2 \left[a,b \right] \rightarrow L^2 \left[a,b \right]$$
$$ (V_Kf)(x) = \int_a^x K \left(x,y \right) f(y) dy, $$
where $K\left(x,y \right) \in L^2 \left( \left[ a,b \right] \times \left[ a,b \right] \right)$
I know how to prove this if the kernel is bounded, but how to act in an arbitrary case?
Thank you!

A: $$
   |V_K^nf|^2= \\
= \left|\int_{a}^{x}K(x,x_{n-1})\cdots\int_{a}^{x_2}K(x_2,x_1)\int_{a}^{x_1}K(x_1,x_0)f(x_0)dx_0 dx_1\cdots dx_{n-1}\right|^2 \\
  \le \left[\int_{a}^{x}\cdots\int_{a}^{x_2}\int_{a}^{x_1}|K(x,x_{n-1})\cdots K(x_2,x_1)K(x_1,x_0)||f(x_0)|dx_0dx_1\cdots dx_{n-1}\right]^{2}
 \\ \le\left(\int_a^x\cdots\int_a^{x_1}|K(x,x_{n-1})\cdots K(x_1,x_0)|^2dx_0dx_1\cdots dx_{n-1}\right) \\
  \times \left(\int_{a}^{x}\cdots\int_a^{x_1}|f(x_0)|^2dx_0dx_1\cdots dx_{n-1}\right) \\
 \le \|f\|_{L^2}^2 \int_a^x\cdots\int_{a}^{x_3}\int_a^{x_2}dx_1dx_2\cdots dx_{n-1} \\
 =\|f\|_{L^2}^2\frac{(x-a)^{n-1}}{(n-1)!}
$$
Therefore, after integrating in $x$ on $[a,b]$, one obtains
$$
           \|V_K^n\| \le \sqrt{\frac{(b-a)^{n-1}}{(n-1)!}}
$$
That's enough to give an infinite radius of convergence for the exterior resolvent expansion.


text:
Q: Connecting to a VPN box on my LAN, while connected via VPN I've recently configured an old laptop to sit on my home network, and I have it sending all of its traffic through an OpenVPN connection.  It's running Ubuntu 14.04.  I'm still able to connect to this laptop from other computers on the LAN via SSH and web browsers.
Now, I've also set up my wireless router to run a PPTP VPN server, so that I can connect to my home network from work (with a MacBook).  When I do that, however, I'm able to see the other computers on the LAN, but not the VPN'd laptop.
I'm assuming that when I'm connected through the VPN server, my traffic to the laptop is being routed through the wrong interface, but my networking-fu isn't strong enough to know where or how to fix this.  Any thoughts?
Some information about my setup:

*

*Router: ASUS RT-N66U with merlin firmware (192.168.1.1)

*LAN DHCP pool: 192.168.1.2-254

*Router VPN server client pool: 192.168.10.2-11

*VPN laptop (192.168.1.20)

A: It looks like I found my solution:
The problem was that my router placed VPN clients on a different subnet (192.168.10.0) than the other DHCP clients (192.168.1.0).  I changed the router's DHCP pool to 192.168.1.1-200, and the VPN client pool to 192.168.1.201-210, and now everything is working perfectly.

A: way to complicated
a simpler and way easier solution is to try Tinc VPN
http://www.tinc-vpn.org/
then you dont need OpenVPN, PPTP etc..
with tinc you can set it up on the machines you want in your little private vpn, it does not matter where.
tinc will find the nodes it self using a master node that needs to be a server that all nodes can connect to to find each other
how it works presentation
https://www.youtube.com/watch?v=R7P_vvz1AP8


text:
Q: Type object has not attribute 'get_or_create' For reasons unknown only one (out of 18) of my Django models is throwing the error "type object 'LidarReading' has not attribute 'get_or_create'".  Model declaration is below.
class LidarReading(models.Model):
    value = models.DecimalField(max_digits=10, decimal_places=2)
    roll = models.DecimalField(max_digits=12, decimal_places=4)
    pitch = models.DecimalField(max_digits=12, decimal_places=4)
    yaw = models.DecimalField(max_digits=12, decimal_places=4)
    coordinates = models.ForeignKey('FlightCoordinate', models.SET_NULL, blank=True, null=True)

    created = models.DateTimeField(auto_now_add=True, blank=True, null=True)
    modified = models.DateTimeField(auto_now=True)

Call in Django command is as follows (note that 'flight_coordinate' is a FlightCoordinate model object created using get_or_create above):
lidar, created = LidarReading.get_or_create(value=t['lidarreading_value'],
    roll=t['lidarreading_roll'],
    pitch=t['lidarreading_pitch'],
    yaw=t['lidarreading_yaw'],
    coordinates=flight_coordinate,
    created=t['lidarreading_created'])

Thanks in advance for the assistance.

A: You forget objects
lidar, created = LidarReading.objects.get_or_create(value=t['lidarreading_value'],
    roll=t['lidarreading_roll'],
    pitch=t['lidarreading_pitch'],
    yaw=t['lidarreading_yaw'],
    coordinates=flight_coordinate,
    created=t['lidarreading_created'])


text:
Q: One of Multiple DS18B20 sensor showing wrong temperature I have a 4 sensors and one of my sensor always showing wrong temperature. This is not problem with sensor but this is problem with code because I checked it.
void getTemperature() {
  float tempC;
  float tempC3;
  float tempC2;
  float tempC4;
  do {
    DS18B20.requestTemperatures();
    tempC = DS18B20.getTempCByIndex(0);
    dtostrf(tempC, 2, 2, temperatureCString);
    tempC3 = DS18B20.getTempFByIndex(1);
    dtostrf(tempC3, 3, 2, temperatureCString3);
    tempC2 = DS18B20.getTempCByIndex(2);
    dtostrf(tempC2, 4, 2, temperatureCString2);
    tempC4 = DS18B20.getTempCByIndex(3);
    dtostrf(tempC4, 5, 2, temperatureCString4);
    delay(100);
  } while (tempC == 85.0 || tempC == (-127.0));
}

Sending data.
if (c == '\n' && blank_line) {
        getTemperature();
        client.println("HTTP/1.1 200 OK");
        client.println("Content-Type: application/json");
        client.println("Connection: close");
        client.println();
        // your actual web page that displays temperature
        client.print("[");
        client.print(temperatureCString);
         client.print(",");
         client.print(temperatureCString2);
         client.print(",");
         client.print(temperatureCString3);
         client.print(",");
         client.print(temperatureCString4);
         client.print("]");

        break;
    }
    if (c == '\n') {
      // when starts reading a new line
      blank_line = true;
    }
    else if (c != '\r') {
      // when finds a character on the current line
      blank_line = false;
    }
  }
}
// closing the client connection
delay(1);
client.stop();
Serial.println("Client disconnected.");
  }

Here is what I see: https://screenshots.firefox.com/IStMqTgJTI2lmLxz/192.168.0.242
When I left only one sensor i see something like this:
https://screenshots.firefox.com/sSXSYmcQbDLF9mUj/192.168.0.242
Always 3rd (id 2) sensor showing wrong temperature even when he is not there.
Some of you have any idea?


text:
Q: ionic set badge after push notification I'm using IONIC Framework and I'd like to set the badge of my application after I'm getting push notification.
Is there a way to do it when my application is closed?

A: it is for others who will run into the same problem.
I believe your talking about making badge visible with the updated badge number you've received from server.
First thing to enable it in code in init method of Push like this
var push = PushNotification.init({
                android: {
                    senderID: senderID,
                    icon: 'pushicon',
                    sound: "true",
                    iconColor: "#ED8B00"
                },
                browser: {
                    pushServiceURL: 'url'
                },
                ios: {
                    alert: "true",
                    **badge: "true",**
                    sound: "true"
                },
                windows: {}
            });

In above code we've enabled badge {will be displayed in all iPhones and supported Android Phones as well}
Now from server side.
add below part to your ios portion so will get the updatd count even your your app is in background.
This is for ios only, please add for android as per your requirements;
 {
    "aps": {
        "alert": {
            "title": "Received",
            "body": "You have received a message from Kens"
        },
        "badge": 66
    },
    "received_id": "9223",
    "pn_type": "RECEIVED"
}

This badge count will automatically get updated to apps badge count even app is in background.(but badge field should be in integer).
Thanks hope this helps and solve your problem.

A: I had the same problem, resolved this by hitting the POST url from postman instead of the UI given on apps.ionic.io and it worked


text:
Q: Issue with Twitter streaming API I'm kind of new to Twitter streaming API. And I'm trying to get this beautiful and minimalist Scala wrapper for streaming API to get work.
But unfortunately I end up getting this weird error
HttpMethodDirector - Failure authenticating with BASIC 'Firehose'@stream.twitter.com:443
org.apache.commons.httpclient.HttpException: There was a problem connecting, HTTP code received was: 401 HTTP/1.1 401 Unauthorized

I checked the Authorization header and it all looks OK to me.
oauth_signature_method -> HMAC-SHA1,
oauth_signature -> YVbrIgokxdhbZ1AixdlLGaLWrfw=,
oauth_consumer_key -> ********************************,
oauth_version -> 1.0,
oauth_token -> ********************************************************,
oauth_timestamp -> 1379582015,
oauth_nonce -> wKqKGNNCtU2ND1j5xYR0oiTraBrF7i6m

The signature generation mechanism is also looks good to me as compared to
twitter official doc
You can further look to the actual .scala where the place it get generated
Can someone point me out where the issue is?

A: It looks like you're attempting to connect to the Firehose stream which is not publicly available. I work at Gnip and we have the Firehose and provide access to data from it (for a price). You should try connecting to a different method, in the documentation you provided they talk about available methods here.


text:
Q: Put Scripts at the Bottom Yslow recommends that you should put scripts at the bottom of the page.
Where exactly should I put them, after the body end tag?
My whole site runs in jquery, so all the javascript files are needed at the beginning. If I move them to the end, it might stop my site from working. That being the case, where instead should i put these scripts for best performance?

A: You should put them right before the closing body tag. Make sure your scripts are being initiated properly using
$(document).ready()

And you should have no issues.

A: you should put them just before the ending body tag </body>


text:
Q: Laravel Modules + VueJS, routes are being overwritten Well, I have a problem with my routes, all requests related to the Modules folders don't work. I'm using laravel-modules package.
In my project-folder/routes/web.php I must use a wildcard route because my front is in VueJs SPA:
Route::get('/{any}', 'ApplicationController')->where('any', '.*');

Ok, I was using my API routes into the main api.php file, working fine, but when I put in Modules/ModuleName/Routes/api.php the route doesn't work.
If I remove the Route::get('any') from main web.php it works,
I believe the routes are having some kind of conflict.
+-----------+------------------------------+--------------------------------------------------------------------------------+--------------+
| Method    | URI                          | Action                                                                         | Middleware   |
+-----------+------------------------------+--------------------------------------------------------------------------------+--------------+
| GET|HEAD  | api/opportunity/channel-sale | App\Modules\Opportunity\Http\Controllers\OpportunityController@channelSaleList | api,auth:api |
| GET|HEAD  | api/opportunity/flow-steps   | App\Modules\Opportunity\Http\Controllers\OpportunityController@flowStepList    | api,auth:api |
| GET|HEAD  | api/opportunity/kanban       | App\Modules\Opportunity\Http\Controllers\OpportunityController@kanbanList      | api,auth:api |
| GET|HEAD  | api/user                     | Closure                                                                        | api,auth:api |
| GET|HEAD  | {any}                        | App\Http\Controllers\ApplicationController                                     | web          |
+-----------+------------------------------+--------------------------------------------------------------------------------+--------------+

I don't know what to do.

A: You have two options here, either pass a regular expression to the any route to ignore API prefixed routes
Route::get('/{any}', 'ApplicationController')->where('any', '^(?!api).*$');

Or set a fallback to the ApplicationController
Route::fallback('ApplicationController');

From the docs
Fallback Routes
Using the Route::fallback method, you may define a route that will be executed when no other route matches the incoming request. Typically, unhandled requests will automatically render a "404" page via your application's exception handler. However, since you may define the fallback route within your routes/web.php file, all middleware in the web middleware group will apply to the route. You are free to add additional middleware to this route as needed:
Route::fallback(function () {
    //
});

The fallback route should always be the last route registered by your application.


text:
Q: Launching certain command/script when connecting to Linux desktop via RDP I need certain Bash command and Bash script to be executed automatically when the X-server is starting (the OS is Lubuntu 20.04). The problem stems from the fact I never sit at this computer, but log-in to it via XRDP in stead. This Archlinux article recommends to include the commands/scripts to be executed when initiating X-server via XRDP into one of the following files (in order of preference):

*

*~/.xinitrc

*/etc/X11/xinit/xinitrc

*/etc/xrdp/startwm.sh

I tried all three variants. None has worked. Should I run them manually after the RDP connection has been established, the command and the script work nicely, so it is not them. Any suggestions on what else can be tried?