text:
Q: java.util.concurrent.ExecutionException in tomcat7.x I have point tomcat code by adding following line in server.xml for tomcat5.x and it works fine.
<Host name="nsncatbranch" debug="0" appBase="D:/svn/branch/rncom/modules/web/clients/web/web/operationsmanager"
                unpackWARs="false" autoDeploy="false">

                <Logger className="org.apache.catalina.logger.FileLogger"
                    prefix="om_log." suffix=".log"
                    timestamp="true"/>

        <Context path="" docBase="D:/svn/branch/rncom/modules/web/clients/web/web/operationsmanager" debug="0"
               reloadable="false" crossContext="false" />
    </Host>

But in tomcat7.x it gives me following error.
java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].St
andardHost[nsncatbranch].StandardContext[]]
        at java.util.concurrent.FutureTask$Sync.innerGet(FutureTask.java:252)
        at java.util.concurrent.FutureTask.get(FutureTask.java:111)
        at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:1130)
        at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:782)
        at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
        at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1568)
        at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1558)
        at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334)
        at java.util.concurrent.FutureTask.run(FutureTask.java:166)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
        at java.lang.Thread.run(Thread.java:722)
Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[nsncatbranch].Stand
ardContext[]]
        at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
        ... 7 more
Caused by: java.lang.IllegalArgumentException: Servlet mapping specifies an unknown servlet name invoker
        at org.apache.catalina.core.StandardContext.addServletMapping(StandardContext.java:3204)
        at org.apache.catalina.core.StandardContext.addServletMapping(StandardContext.java:3183)
        at org.apache.catalina.deploy.WebXml.configureContext(WebXml.java:1302)
        at org.apache.catalina.startup.ContextConfig.webConfig(ContextConfig.java:1302)
        at org.apache.catalina.startup.ContextConfig.configureStart(ContextConfig.java:825)
        at org.apache.catalina.startup.ContextConfig.lifecycleEvent(ContextConfig.java:300)
        at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:119)
        at org.apache.catalina.util.LifecycleBase.fireLifecycleEvent(LifecycleBase.java:90)
        at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5161)
        at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
        ... 7 more

I am not getting upper error as i have commented invoker in web.xml. I am facing new error described below.
SEVERE: Unable to determine URL for WEB-INF/classes
javax.naming.NameNotFoundException: Resource /WEB-INF/classes not found
        at org.apache.naming.resources.BaseDirContext.listBindings(BaseDirContext.java:733)
        at org.apache.naming.resources.ProxyDirContext.listBindings(ProxyDirContext.java:546)
        at org.apache.catalina.startup.ContextConfig.webConfig(ContextConfig.java:1197)
        at org.apache.catalina.startup.ContextConfig.configureStart(ContextConfig.java:825)
        at org.apache.catalina.startup.ContextConfig.lifecycleEvent(ContextConfig.java:300)
        at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:119)
        at org.apache.catalina.util.LifecycleBase.fireLifecycleEvent(LifecycleBase.java:90)
        at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5161)
        at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
        at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:897)
        at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:873)
        at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:615)
        at org.apache.catalina.startup.HostConfig.deployDirectory(HostConfig.java:1095)
        at org.apache.catalina.startup.HostConfig$DeployDirectory.run(HostConfig.java:1617)
        at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
        at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334)
        at java.util.concurrent.FutureTask.run(FutureTask.java:166)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
        at java.lang.Thread.run(Thread.java:722)

A: I had the same problem and Patrick was right the problem was in the web.xml file. I have removed the following tag:
 <servlet-mapping>
    <servlet-name>invoker</servlet-name>
    <url-pattern>/servlet/*</url-pattern>
</servlet-mapping>

and it works ok. So my suggestion is check the web.xml file again and make sure that everything in it is ok.


text:
Q: Steps for using swupdate in Yocto Project Can you please explain what all are steps are required to get started with swupdate in Yocto
I have Intel based board and I want to use swupdate for this project..
I have cloned poky, meta-intel branches, and generated core-image-minimal image, which is working
Now I cloned meta-swupdate layer and added it to bblayers.conf file. I am still not sure which is the bootloader being used for the Machine: intel-corei7-64. I have not seen neither grub or uboot.
Please help me in listing the steps for getting started.. I just know that I have to execute bitbake swupdate-image. What's next after that, which Image I have to flash..Where is the initrd image and how to copy it in the hddimg.
Thanks for your time

redpajama_set_name: RedPajamaStackExchange


text:
Q: how to stop change instance when collision stops in game maker studio? Collision Event with object obj_cu:

for all obj_lamp: change the instance into object obj_lamo_light, not performing events
for all obj_arrow: change the instance into object obj_arrow_move, not performing events

where obj_lamo_light contains 3 sub iamges and obj_Arrow_move contains 3 sub images and I want to change them back to original objects when collision stops

A: In the obj_lamp_light event, you could check whether or not your collision is still occurring, and change back if not.
if (collision_rectange(x, y, x + sprite_width, y + sprite_width, false, true) == noone)
{
    instance_change(obj_lamp, false);
}


text:
Q: System Preferences error: "There was an error in Security & Privacy preferences" When I open System Preferences (version 14.0) and then click on Security & Privacy, I get a popup error message:

Preferences Error
  There was an error in Security & Privacy preferences.

I am using macOS Sierra Version 10.12.4 (16E195) on MacBook Air (Early 2014), 1.4 GHz Intel Core i5, 4 GB 1600 MHz DDR3, Intel HD Graphics 5000 1536 MB
System Preferences info:
Version:    14.0
Obtained from:    Apple
Last Modified:    4/12/17, 18:59
Kind:    Intel
64-Bit (Intel):    Yes
Signed by:    Software Signing, Apple Code Signing Certification Authority, Apple Root CA
Location:    /Applications/System Preferences.app

I've changed the language setting, time setting, etc. over the course of use. I don't know much about programming, but I've used Terminal to change some settings manually. I've also deleted some files I needed a password to delete, to get rid of iTunes. Because I felt like it. I've logged in on another account on the same MacBook, and encountered the same issue with System Preferences > Security & Privacy.
I've already tried restarting, logging in/out. I've also noticed that I seem to be able to open any other icon in system preferences. The issue seems likely not my fault, given it is on both accounts. It is good to note that I've used command line to try to reveal hidden files and stuff, but I don't think that's it.
I was, in both logins, in an admin account with a password.
This is the Console error:
error   10:53:05.711585 -0700   accountsd   "ACDAuthenticationPluginManager: an authentication plugin of class (null) for auth type <private> could not be instantiated! Load Error: (null)"
error   10:53:05.711666 -0700   accountsd   "The authentication plugin for account <private> could not be found!"
error   10:53:05.946849 -0700   accountsd   "ACDAuthenticationPluginManager: an authentication plugin of class (null) for auth type <private> could not be instantiated! Load Error: (null)"
error   10:53:05.946930 -0700   accountsd   "The authentication plugin for account <private> could not be found!"
error   10:53:06.046644 -0700   accountsd   "ACDAuthenticationPluginManager: an authentication plugin of class (null) for auth type <private> could not be instantiated! Load Error: (null)"
error   10:53:06.046796 -0700   accountsd   "The authentication plugin for account <private> could not be found!"
error   10:53:06.075493 -0700   com.apple.preference.security.remoteservice <private>
error   10:53:06.077179 -0700   com.apple.preference.security.remoteservice <private>
error   10:53:06.096064 -0700   sharingd    SDConnectionManager:: XPC connection invalidated
error   10:53:06.127294 -0700   ReportCrash Failed to start process notifications for pid 674 (16)

I also looked at some stuff in Terminal:
$ ls /Library/Preferences/com.apple.se*
/Library/Preferences/com.apple.security.appsandbox.plist
/Library/Preferences/com.apple.security.plist
/Library/Preferences/com.apple.security.systemidentities.plist

I tried the reply marked Solved by Maxym on "Security & Privacy preference pane Error Mavericks" but clients.plist did not dissapear:
Last login: Sun May 21 12:03:18 on ttys000
talib7@Elizabeths-MacBook-Air:~$ sudo -s
Password:
root@Elizabeths-MacBook-Air:~$ cd /var/db/locationd/
root@Elizabeths-MacBook-Air:/var/db/locationd$ ls -al
total 32
drwxr-x--- 5 _locationd _locationd 170 May 21 12:18 .
drwxr-xr-x 82 root wheel 2788 May 21 10:09 ..
drwx------ 4 _locationd _locationd 136 Sep 23 2014 Library
-rw-r--r-- 1 _locationd _locationd 5226 May 21 12:18 clients.plist
-rw-r--r-- 1 root _locationd 5000 May 21 10:45 clients.plist.saved
root@Elizabeths-MacBook-Air:/var/db/locationd$ killall locationd && rm clients.plist && killall locationd
root@Elizabeths-MacBook-Air:/var/db/locationd$ ls -al
total 32
drwxr-x--- 5 _locationd _locationd 170 May 21 12:28 .
drwxr-xr-x 82 root wheel 2788 May 21 10:09 ..
drwx------ 4 _locationd _locationd 136 Sep 23 2014 Library
-rw-r--r-- 1 _locationd _locationd 5226 May 21 12:28 clients.plist
-rw-r--r-- 1 root _locationd 5000 May 21 10:45 clients.plist.saved
root@Elizabeths-MacBook-Air:/var/db/locationd$ killall locationd && rm clients.plist && killall locationd
No matching processes were found
root@Elizabeths-MacBook-Air:/var/db/locationd$ ls -al
total 32
drwxr-x--- 5 _locationd _locationd 170 May 21 12:28 .
drwxr-xr-x 82 root wheel 2788 May 21 10:09 ..
drwx------ 4 _locationd _locationd 136 Sep 23 2014 Library
-rw-r--r-- 1 _locationd _locationd 5270 May 21 12:28 clients.plist
-rw-r--r-- 1 root _locationd 5000 May 21 10:45 clients.plist.saved
root@Elizabeths-MacBook-Air:/var/db/locationd$ killall locationd && cp clients.plist.saved clients.plist && killall locationd
root@Elizabeths-MacBook-Air:/var/db/locationd$ ls -al
total 32
drwxr-x--- 5 _locationd _locationd 170 May 21 12:28 .
drwxr-xr-x 82 root wheel 2788 May 21 10:09 ..
drwx------ 4 _locationd _locationd 136 Sep 23 2014 Library
-rw-r--r-- 1 _locationd _locationd 5270 May 21 12:28 clients.plist
-rw-r--r-- 1 root _locationd 5000 May 21 10:45 clients.plist.saved

A: Because this is happening on both accounts it is likely a system wide issue with your installation of Mac OS. I would head into Recovery Mode & reinstall OS X on top of your existing install - note that this will not cause any loss of data or user accounts, but will reinstall iTunes.


text:
Q: como formatear día de la semana con acento estoy intentando dar formato a un campo de un registro de Mysql que tiene el formato fecha_hora y cuando lo intento mostrar con el día de la semana (hoy-miércoles y supongo el sábado) me muestra un símbolo raro.
    rs.execute(query)
    reg = rs.fetchone()
    #print (reg[0],reg[1],reg[2],reg[3])
    #<class 'datetime.datetime'> <class 'int'> <class 'int'> <class 'int'>
    #'2022-02-22 12:50:00' formato del registro en mysql
    #'x- mi�rcoles 23 de febrero de 2022 12:50'
    self.leFecha_Hora.setText(format(reg[0],'%A %d de %B de %Y %H:%M'))

aunque se ve que parece la fecha y hora de hoy, es un registro mysql. Lo he intentado con strptime y strftime, pero marcan error de formato. Esto lo tengo en otra parte del código
y funciona bien ...
QDateTime.currentDateTime().toString("dddd d 'de' MMMM 'de' yyyy HH:mm:ss")

esto si funciona para la fecha y hora de hoy.
No sé que mas hacer para solucionarlo, os agradecería una ayuda.


text:
Q: How to redirect a form submission to different pages based on values entered? I have a form that captures general information like name, sex, age, and email, etc..
I want to achieve something like this:

*

*If someone for example selects "female" and "40-45" then clicks submit, I want the form to go to /female-40-45. Both of the sex and age range are options within a select box.

Thanks for your help.
Not sure how to write the conditional logic for this form submission.


text:
Q: Exporting OpenXML based Charts into images Can I generate image from office OpenXml based chart definition?
My idea is to use the program dynamically generate OpenXml definition of a chart and export it as image.

A: Aspose.Cells can

*

*Generate the OpenXML or XLSX Charts,

*Manipulate the existing Charts and

*Export them into Image

Exporting Chart to Image is very simple. Just call Chart.ToImage() method and you have accomplished it.
The following sample code creates the Chart and saves the Excel file in XLSX format.
// Instantiating a Workbook object
Workbook workbook = new Workbook();

// Adding a new worksheet to the Excel object
int sheetIndex = workbook.Worksheets.Add();

// Obtaining the reference of the newly added worksheet by passing its sheet index
Worksheet worksheet = workbook.Worksheets[sheetIndex];

// Adding sample values to cells
worksheet.Cells["A1"].PutValue(50);
worksheet.Cells["A2"].PutValue(100);
worksheet.Cells["A3"].PutValue(150);
worksheet.Cells["B1"].PutValue(4);
worksheet.Cells["B2"].PutValue(20);
worksheet.Cells["B3"].PutValue(50);

// Adding a chart to the worksheet
int chartIndex = worksheet.Charts.Add(Aspose.Cells.Charts.ChartType.Pyramid, 5, 0, 15, 5);

// Accessing the instance of the newly added chart
Aspose.Cells.Charts.Chart chart = worksheet.Charts[chartIndex];

// Adding SeriesCollection (chart data source) to the chart ranging from "A1" cell to "B3"
chart.NSeries.Add("A1:B3", true);

// Saving the Excel file
workbook.Save(dataDir + "output.xlsx");

The following sample code exports the Chart into Image.
// Converting chart to Bitmap
System.Drawing.Bitmap bitmap = chart.ToImage();
bitmap.Save(dataDir + "chartBMP_out.bmp", System.Drawing.Imaging.ImageFormat.Bmp);

Note: I am working as Developer Evangelist at Aspose


text:
Q: How to capture field value when a method of a class is called in Python? I have a weird 3rd party library that requires me doing the following (A is imported from that library):
def foo(my_props):
  a = A()
  a.props = my_props
  a.post()

So what I want is to make sure that when a.post() is called, its props are set correctly. Note that this is a greatly simplified example so it's apparent it would be easy to mock foo instead. Unfortunately there is much more into it (like my_props may be modified in foo before calling a.post).
Worth noting that from looking into the source code of that import, props is not a class property. It's a simple dict, class field, set something like self.props = ... at random places in the class A.
So how can I setup my mocking to accomplish this feast? I am not even interested in post itself. I need to know how many times delete is called and what values props were set at that time.
EDIT: re-enforcing @hspandher response, ended up doing the following because unfortunately call_args stayed empty, which I hoped I could have analyzed after the call.
@mock.patch('A.props', return_value=mock.PropertyMock())
def test_foo(self, mock_props):
    call_args = []
    def capture(*args, **kwargs):
        call_args.append(args)

    mock_props.__set__ = functools.partial(capture)

    a = A()
    a.foo()

    # analyze call_args...

A: For this you don't even need mocking, lets say foo is defined in file code.py, in test file code should be like this from code import A       A.props = <mockvalue> and then your testing code. But if you to want to do something little more sophisticated like mocking post , I suggest you use python mock or fudge library

A: If you can initialize a outside of foo and pass as argument so the actual call looks like this:
def foo(my_props, obj):
    obj.props = my_props
    obj.post()

foo({'bar': 'baz'}, a)

Then you could test it like this:
def test_foo():
    a = mock.create_autospec(A)
    foo(1, a)
    assert a.props == 1
    assert a.mock_calls == [mock.call.post()]

Checking if props are set before calling post is a little more work.
You will need to convert foo to a class Foo:
class Foo(object):

    def foo(self, my_props, obj):
        self._setup_props(my_props, obj)
        self._post(obj)

    def _setup_props(self, my_props, obj):
        obj.props = my_props

    def _post(self, obj):
        obj.post()

Now you can mock Foo itself and it's foo method to check the mock_calls order:
>>> f = mock.Mock(spec=Foo, foo=Foo.foo)
>>> f.foo(f, 1, 2)
>>> f.mock_calls
[call._setup_props(1, 2), call._post(2)]


text:
Q: ISAM Table Not Found, SQL state S0000 in SQLExecDirect
*

*PHP Version: 7.0.14

*Working on Windows Server 2012

*Database files are in D: drive

*Website/Application is assigned to the Application pool correctly

*Assigned Application pool has the permissions to D: drive

Trying to connect and fetch information from ToppSpeed Database.
Created DSN correctly using Topspeed ODBC Driver.
I have created a sample script to verify if it is working or not.
odbctest.php
       $conn=odbc_connect("DSN_NAME",'',''); //Make a coonection to DSN

        if (!$conn){
            exit("Connection Failed: " . $conn);
        }

        $sql="SELECT * FROM ExampleTableName"; // Query String

        $rs=odbc_exec($conn,$sql);            //Execute Query <--- Error Line

        if (!$rs) {
            exit("Error in SQL");
        }

        while (odbc_fetch_row($rs)){
            var_dump(odbc_result($rs,1));
        }

        odbc_close($conn);

Error:

PHP Warning:  odbc_exec(): SQL error: [SoftVelocity Inc.][TopSpeed ODBC Driver][ISAM]ISAM Table Not Found, SQL state S0000 in SQLExecDirect in C:\inetpub\wwwroot\projectFolder\odbctest.php on line 9

*

*Working: When I run same file on PHP inbuilt server using command > php -S localhost:8002
and run file in a browser at http://localhost:8002/odbctest.php Everything works fine.

*Working: When I run file in command line > php odbctest.php It works fine I got data from the table.

*Not Working: I have added the website in IIS Manager, bind the website(physical path is C:\inetpub\wwwroot\projectFolder ) with the local IP
When I open that odbctest.php in a browser with local IP I am getting Table NOT Found error.
Same Script, Only difference is it is running on Command Line and not on IIS server, It is running on PHP inbuilt server and not working on IIS.
other Technical Difference is
I have put one PHP file to see PHP information on both servers.
Here is the only difference I found in that.

*

*Working On PHP inbuilt server: In PHP info Server API is: Built-in HTTP server

*Not working on IIS Server: in PHP info Server API is: CGI/FastCGI
there is not issue in DSN string because when I change the DSN string with unknown it identifies that there is something wrong in DSN string.
I think there might be some permission issue when trying to access data from IIS server (PHP runs on CGI/FastCGI).
I am wondering if there is permission issue why the error says table not found!!
I don't find any good documentation for TopSpeed Database connection error as this database is not widely used.
Any suggestion or idea? Please advise. Thank you in advance.

A: The database SQL error was not stating anything about permission,
so I created a simple another PHP script to append data to TEXT file.
I ran that PHP script with two test cases on the IIS server

*

*Test Case 1: Write in a text file which resides in the project directory(same server)
And PHP script executes correctly and it wrote data to text file.

*Test Case 2: I change the text file path with the file D:\some_directory\logfile.txt (Resides on D drive)
And when I ran it again script again I got the following error:

Warning: file_put_contents(D:\some_directory\logfile.txt):
  failed to open stream: Permission denied in
  C:\inetpub\wwwroot\project-directory\write.php on line 12

It confirms there is some problem with the Permissions
App pool assigned to the Website in IIS manager already had the permission to D: Driver. So it was not the problem.
In more research, I found that
we need to identify the USER first that we need to provide the permissions and the user is the value of "Anonymous user identity"
https://stackoverflow.com/a/32033941/5236174
https://www.iis.net/configreference/system.webserver/security/authentication/anonymousauthentication?showTreeNavigation=true
I saw that the value of Anonymous user identity was not the Application Pool!!
I changed that to the Application pool identity.
So now the website/application's anonymous user identity become the App pool and that has correct permissions.
Afthesethis changes, everything works perfectly fine as there is no permission issue.


text:
Q: How to redirect Vue/Nuxt SPA Page automatically Summery
I'm creating Vue/Nuxt application by SPA mode.
To generate /.dist file, I execute nuxt generate
pages
  ├ index.vue
  └ test.vue

I want to know how to redirect / to /test path by Nuxt.
What I tried
I tried middleware and module, but they do not work.
https://github.com/nuxt-community/redirect-module

A: One simple workaround is to use fetch hook in the index page to change rout to /test; Here is the code:
// index.vue
fetch() {
  this.$router.push('./test');
}


text:
Q: How do I initialize DataTables.js' load function AFTER creating the table with jQuery? I am creating a table with ajax. The table displays properly, and is valid html, but I can't initialize DataTables correctly.
I have this html code:

And in my ajax:
complete: $('.dat').DataTable(),

The table is formatted according to DataTables.js' table guidelines:

            Logo
            Food Name
            Stuff
            Code

            Image
            Stuff here
            Description
            Code

And part of the jquery AJAX:
success: function (z) {
    var json = $.parseJSON(z.d);

    var table = '
';
    table += "
";
    table += "
;"
    table += "          Logo	";
    table += "          Food Name	";
    table += "          Stuff	";
    table += "          Code	";
    table += "
";
    table += "
";

    $.each(json, function (i, obj) {
        //console.log(obj);
        table += "
";
        table += "
";
        table += "           Image (" + obj.Logo + ")	";
        table += "          " + obj.FoodName + "	";

        table += "          ";
        $.each(obj.Text, function (j, t) {
            table += t + "; ";
        });
        table += "          	"; // Stuff

        table += "          " + obj.Code + "	";
        table += "
";
    });
    table += "
";
    table += "
";
    $('.search_results').append(table);
    $('.dat').DataTable();
},

The html is showing up correctly without any formatting issues, and there are also no errors. The only thing I can do is use the search feature, and it doesn't clear the irrelevant content. Is DataTable() being called before the append feature? That's what I suspected, but the search feature works almost perfectly.
If so, how do I call it after the table is done being loaded? If not, what am I doing wrong?
Thanks in advance!

A: Try first removing any prior listeners and such that DataTable may have already attached to the table (especially since you're identifying it via a Class, rather than an ID).  Then, initialize the table.
So, replace this...
$('.dat').DataTable();

With this...
$('.dat').DataTable().destroy();
$('.dat').DataTable();


text:
Q: Express passing parameters to template depending on the environment I am using Express and EJS templates. In production environment I am calling some middleware's and passing result to the template. req.body is returned from appRenderer middleware and req.chunk from webpackUtils middleware. Everything works fine but in development environment I am not using any of the middleware and I don't need too pass any parameters.
...
if (process.env.NODE_ENV === 'production') {

  const appRenderer = require('./appRenderer').default
  app.use(appRenderer)

  const webpackUtils = require('./webpackUtils').default
  app.use(webpackUtils)
}

app.get('*', (req, res) => {
  res.render('index', {app: req.body, webpack: req.chunk})
})

I tried something like this but it is not working.
app.get('*', (req, res) => {
  if(process.env.NODE_ENV === 'production')
    res.render('index', {app: req.body, webpack: req.chunk})
  } else {
   res.render('index')
  }
})

How would I send parameters depending on environment? Is this even a problem, since everything is working and I can choose to render params that I passed or not in EJS template. I just don't like the idea that I am passing something that is not used?


text:
Q: DELETE a single row from a table with CASCADE DELETE picks a slow plan... but not always Schema Summary
A dozen tables related by foreign key to a central table (call it TableA). All tables have a PK that is INT IDENTITY, and Clustered. All the tables' FKs are indexed.
This looks like a star configuration. TableA has fairly static personal info such as name, & DOB. The surrounding tables each have lists of items about the person in TableA that change or grow over time: for example, a person might have several emails, several addresses, several phone numbers, etc...
In the unusual event that I want to delete from TableA (test data that gets inserted during performance checks, for example), the FKs all have CASCADE DELETE to handle removing all subordinate data lists if they exist in any of the surrounding tables.
I have three environments to play with: DEV, QA, and UAT (well, four if you count PROD, but "play" is not something I would want to do to PROD).
DEV has about 27 million people in TableA with various counts upward of 30M in the surrounding tables.
QA and UAT are only a few hundred thousand rows.
The Problem
The simple "delete from TableA where Id = @Id" takes < 1ms on DEV (the big one) and the execution plan looks fine, lots of tiny thin lines and all index seeks... but here's the rub: infrequently on DEV, and ALWAYS on QA and UAT, the simple delete takes about 1 second and the plan shows almost all the indexes are being scanned, with big fat lines showing the entire row counts.
Observations
The delete statement is issued by Entity Framework Core running inside an API so I have limited capability to mess with it (making it into a stored procedure, index hinting, using a different predicate, and other ideas...)
Despite all three environments being identical (same script created all three environments), nothing I have done so far has improved QA and UAT, but DEV is usually fast.
When DEV becomes slow, it remains slow until "something" happens. I haven't figured out what the "something" is, but when it occurs, the performance reverts to fast again and remains that way for days.
If I catch DEV at a slow time, and use SSMS to manually run a delete statement, the plan is fast (<1ms); but the deletes coming from the API use a slow plan (1s). Entity Framework is (as best I can tell) using sp_executesql to run a parameterized "delete from tableA where Id = @Id". The manual query is "DELETE FROM TableA WHERE Id = 123456789"
The row being deleted is always a recently-added row, meaning that the Id is right at the "top" and probably not within the range of the index statistics (although I speak from a position of profound ignorance on that topic and probably have my wires crossed...)
What I have tried so far
Reading up on FK cascade delete issues, it seems all the FKs need to be indexed, so I did that.
Rebuild (not just Reorg) every index.
Selectively delete the bad plans from the plan cache using DBCC FREEPROCCACHE (plan handle)
Running the excellent tools from Brent Ozar got me checking that the FKs were all is_not_trusted = 0
Looked at these (and other) previous StackExchange questions:1, 2, 3, 4
Of those, I suspect that the last one, with a description of how the cardinality estimator gets confused, might be pointing to the source of the problem, but I need help figuring out what to do next...
The plan shot below (from ssms) shows the slow plan: some of the FK indexes are being scanned (but not all) and there is an excessive memory grant.  The fast plan would show all index seeks. The whole plan is at ShowMyPlan Link
I hope someone can point out what I have missed, or what I can investigate further.
Thanks!

Bad Plan


text:
Q: Cannot turn on Windows Defender virus protection Why can't I turn on Windows Defender virus protection?
Today I noticed that my Windows Defender virus protection was off. I've been through countless blog entries, articles, and forums but I can't find anything that makes a difference.
I'm running Windows 10, Version 1803 (OS Build 17134.345)
I don't have any other antivirus software installed.
Here's the warning in Control Panel's Security and Maintenance section:

Clicking "Turn on now" brings up this blank Security Center window:

Under "Virus & threat protection", if I click "Scan now" nothing happens. If I click "Run a new advanced scan", then "Custom scan", then "Scan now" it'll prompt me to select a directory, but nothing happens after that.
Group Policy Editor
Computer Configuration > Administrative Templates > Windows Components > Windows Defender Antivirus is still "Not configured"
Registry
HKLM/SOFTWARE/Microsoft/Windows Defender -> DisableAntiSpyware
HKLM/SOFTWARE/Microsoft/Windows Defender -> DisableAntiVirus

*

*both set to 0
Command Prompt

*

*DISM.exe /Online /Cleanup-image /Restorehealth didn't report any problems

*sfc /scannow did find and repair corrupt system files, but after rebooting nothing has changed

Services
The "Restart" option for Security Center is disabled:

Update:
I went more than a week without a solution, but I was due for an upgrade anyway... New hard drive and fresh installation means the problem is gone even though it was never solved.
Unfortunately, I won't be able to test or accept an answer for this problem.

A: I had the same sort of symptoms. In the Windows Security Center, under Virus and threat protection, it said "Your virus & threat protection is managed by your organization."

I note you mentioned the Registry Keys under HKLM/SOFTWARE/Microsoft/Windows Defender. Nice spotting, but it seems like there is another key that is causing the problem for some users.
Steps to a solution:

*

*Press the Windows key and type "regedit"

*On the regedit icon that appears, right-click and select Run as Administrator.

*Navigate to the folder located at HKLM\SOFTWARE\Policies\Microsoft\Windows Defender (You can paste this into the address box at the top of the window, or navigate manually using the side directory structure)

*In this folder, there are probably two keys. Right-click and Delete the DisableAntiSpyware key.

*Exit regedit, and return to the Windows Defender settings screen (refresh it if necessary). Windows Defender should have the scan options available and working.

Solution adapted from here, with a much more detailed solution here.


text:
Q: Count using useState doesnt update state until question 6 even when answered correctly react im trying to create a quiz app in react using hooks. i want the answers to be clickable and once clicked the user will then move onto the next question. My problem is that, the score state isnt updating until question 6! i am making an API call to get the questions and answers using useEffect. i know that useState is asynchronous and thats why state doesnt update straight away, its just even if i answer the first 6 questions correctly, after question 6 the score is still showing 1. Does anyone have a way around this?
My API call using useEffect:

useEffect(() => {
  axios.get("https://my-quiz-server.herokuapp.com/api/newq").then((res) => {
      const allQuestions = res.data;
      setResult([allQuestions]);
    })
    .catch((error) => {
      console.log(error);
    });
}, [setResult]);

My Quiz component:

import React, {
  useState,
  useContext,
  useEffect
} from "react";

import {
  QuizContext
} from "../Helpers/context";

const MainQuiz = () => {
  const {
    score,
    setScore,
    result
  } = useContext(QuizContext);

  const [currentQuestion, setCurrentQuestion] = useState(0);
  const [optionChosen, setOptionChosen] = useState("");
  console.log(optionChosen);
  console.log(result);

  const nextQuestion = (correctAnswer) => {
    if (optionChosen === correctAnswer) {
      setScore((score) => score + 1);
    }
    setCurrentQuestion((currentQuestion) => currentQuestion + 1);
  };

  useEffect(() => {
    console.log("score updated", score);
  }, [score]);
  return ( <
    div className = "quiz" > {
      result.map((question, index) => {
        if (currentQuestion < question.allQuiz.length) {
          return ( <
            h3 key = {
              index
            } > {
              question.allQuiz[currentQuestion].q_prompt
            } < /h3>
          );
        } else {
          return null;
        }
      })
    } <
    div className = "answer__container" > {
      result.map((answers, index) => {
        if (currentQuestion < answers.allQuiz.length) {
          return ( <
            div className = "answer__options" > {
              " "
            } <
            button className = "question__choices"
            onClick = {
              () => {
                setOptionChosen("a");
                nextQuestion(
                  result[0].allQuiz[currentQuestion].q_correctAnswer
                );
              }
            } >
            {
              answers.allQuiz[currentQuestion].a
            } <
            /button> <
            button className = "question__choices"
            onClick = {
              () => {
                setOptionChosen("b");
                nextQuestion(
                  result[0].allQuiz[currentQuestion].q_correctAnswer
                );
              }
            } >
            {
              answers.allQuiz[currentQuestion].b
            } <
            /button> <
            button className = "question__choices"
            onClick = {
              () => {
                setOptionChosen("c");
                nextQuestion(
                  result[0].allQuiz[currentQuestion].q_correctAnswer
                );
              }
            } >
            {
              answers.allQuiz[currentQuestion].c
            } <
            /button> <
            button className = "question__choices"
            onClick = {
              () => {
                setOptionChosen("d");
                nextQuestion(
                  result[0].allQuiz[currentQuestion].q_correctAnswer
                );
              }
            } >
            {
              answers.allQuiz[currentQuestion].d
            } <
            /button> <
            /div>
          );
        } else {
          return null;
        }
      })
    } <
    /div> <
    span > {
      score
    } < /span> <
    /div>
  );
};

export default MainQuiz;


text:
Q: React-Map-GL: How to make hovered marker appear on top? I have a map with different markers and as much as I am aware the markers are rendered in the order they appear which means marker 3 is on top of marker 1 and 2.
I am using React Map Gl with mapblibre-gl and React(typescript)
I'm fine with that, but if I hover an marker I want the hovered marker to be on top(when overlaying with another marker).
I tried z-index but it does not work at all.
Maker:
<Marker latitude={station.lat} longitude={station.lng} key={station.id}>

      {station.brand ? station.brand : 'freie Tankstelle'}
      {price}

</Marker>

This marker is than pushed in an array and returned as component of many markers.
CSS:
.locDot{
    /* position: absolute; */
    height: 12px;
    width: 12px;
    display: flex;
    justify-content: center;
    align-items: flex-end;
    background-color: #1E90FF;
    border: 2px solid #fff;
    border-radius: 100%;
    /* z-index: 1; */
}

.priceTag{
    /* position: relative; */
    display: flex;
    flex-direction: column;
    background-color: #1E90FF;
    padding: 4px 6px;
    font-size: 1rem;
    font-weight: 400;
    color: white;
    margin-bottom: 18px;
    border-radius: 5px;
    /* line-height: 1rem; */
    z-index: 1;
}

.priceTag:hover{
    position: absolute;
    border: 5px solid red;
    z-index: 5;
}

Sandox:  codesandbox.io/s/vigorous-mahavira-gxk6wj?file=/src/App.tsx

A: You need to apply zIndex to marker itself, you can do this by adding className or inline styling.
I have updated the codesandbox with solution, basically we will map simple array and return Markers, based on the Marker index we will set active state and then check whats the current activeIndex in Marker inline style. If you hover over that div, set an activeIndex to its index..
But as I said, this could be simply achieved by passive active className and then giving it z-index: 1
Here is the codesandbox

A: The solution could be add this in your styles.css.
.maplibregl-marker:hover {
  z-index: 1000;
}

Here is reproducible code.


text:
Q: Using NetCDF file in PostgreSQL database? I have a NetCDF file which is 25 by 20 grids by latitude and longitude and contains hourly rainfall data at each grid. In total I have 780 hours worth of data. I was trying to use ArcGIS to create a raster, but I could only get one hour at a time. Is there a way to convert it to another file type or to a raster with all the hours so I can easily use it in my database?

A: You may use ArcGIS to convert your netcdf file into geotiff files. You've stated that you are able to get one hour at a time. You'll need to just automate your approach using Arcpy (Python). ArcGIS already has Multidimension Tools Toolset to deal with NetCDF data. You can use Make NetCDF Raster Layer tool. There may be 2 approaches to do the task.
Approach-1
Use Make NetCDF Raster Layer tool such that
Input netCDF File = your nc file
Variable = prate (or whatever variable is there to depict precipitation)
X Dimension = lon
Y Dimension = lat
Output Raster Layer = Your defined output name
Band Dimension = time
Leave Dimension Values blank.
It will generate a single raster layer with 780 bands (assuming you have a single nc file having 780 hours of data). You may export this raster layer into geotiff file or simply use it as it is.
Loop through each band of this output raster layer and extract each band. For this, you may look into this link.
You'll just have to name your output files to depict exact timestamp of each band. If you are familiar with python, it should be no issue.
Approach-2
You may access the above mentioned tool using arcpy from the start as follows
arcpy.MakeNetCDFRasterLayer_md(inputfilepath, "prate", "lon", "lat", "temporaryraster", "", dimension_value, "BY_VALUE")

dimension_value here is a list that is generated from
netcdffile.getDimensionValue(dimension_type, dateband)
You may loop through each value of dimension_value and use it in above script line to make raster layer for each band from the start.


text:
Q: Joint JS - How apply an event on shapes.devs I'm new with jointjs and I try to constraint a rectangle with ports to a line.
I tried to reproduce tutorial, that works with a basic.Circle, with a basic.Rect but not with devs.Model
Could someone explian me why and how to solve this problem?
Many thanks in advance!
Here is my code :
var width=400, height=1000;

var ConstraintElementView = joint.dia.ElementView.extend({
pointermove: function(evt, x, y) {
    joint.dia.ElementView.prototype.pointermove.apply(this, [evt, 100, y]);
}
});

var graph = new joint.dia.Graph;
var paper = new joint.dia.Paper({ el: $('#myholder'), width: width, height: height, gridSize: 1, model: graph, elementView: ConstraintElementView});

var m1 = new joint.shapes.devs.Model({
position: { x: 20, y: 20 },
size: { width: 90, height: 90 },
inPorts: [''],
outPorts: [''],
attrs: {
    '.label': { text: 'Model', 'ref-x': .4, 'ref-y': .2 },
    rect: { fill: '#2ECC71' },
    '.inPorts circle': { fill: '#16A085' },
    '.outPorts circle': { fill: '#E74C3C' }
}
});

var m2=m1.clone();
m2.translate(0,300);

var earth = new joint.shapes.basic.Circle({
position: { x: 100, y: 20 },
size: { width: 20, height: 20 },
attrs: { text: { text: 'earth' }, circle: { fill: '#2ECC71' } },
name: 'earth'
});

graph.addCell([m1, m2, earth]);

A: Why does it not work?

*

*devs.Model is not rendered via ContraintElementView to the paper.

*devs.Model uses devs.ModelView for rendering, basic.Circle and basic.Rect use ContraintElementView.

*JointJS dia.Paper searches for a view defined in the same namespace as the model first. If found, it uses it. It uses one from the paper elementView option otherwise. i.e. joint.shapes.devs.ModelView found for devs.Model but no view found for basic.Circle (no joint.shapes.basic.RectView is defined)
How to make it work?

*

*define elementView paper option as a function. In that case paper don't search the namespace and uses the result of the function first.

*Note that in order to render ports devs.ModelView is still required.

i.e.
var paper = new joint.dia.Paper({
  elementView: function(model) {
    if (model instanceof joint.shapes.devs.Model) {
      // extend the ModelView with the constraining method.
      return joint.shapes.devs.ModelView.extend({
        pointermove: function(evt, x, y) {
          joint.dia.ElementView.prototype.pointermove.apply(this, [evt, 100, y]);
        }
      });
    }
    return ConstraintElementView;
  }
});

http://jsfiddle.net/kumilingus/0bjqg4ow/
What is the recommended way to do that?

*

*JointJS v0.9.7+

*not to use custom views that restrict elements movement

*use restrictTranslate paper option instead.

i.e.
var paper = new joint.dia.Paper({
  restrictTranslate: function(elementView) {
     // returns an area the elementView can move around.
     return { x: 100, y: 0, width: 0, height: 1000 }
  };
});

http://jsfiddle.net/kumilingus/atbcujxr/

A: I think this could help you :
http://jointjs.com/demos/devs


text:
Q: Подгрузка содержимого модального окна после его открытия Добрый вечер!
Суть моего вопроса, в том, что есть модальное окно, а в нем лежит iframe, который подгружает видео из ютуба.
Но подгружает все видео сразу, по открытию страницы, что занимает довольно много времени. А нужно сделать так, чтобы содержимое модального окна (сам iframe) подгружалось только после его открытия.
Код вызова:
<a href="#project<?php echo $id ?>">

        <img alt="<?php echo $program_name ?>" class="" src="images/lightbox/<?php echo $program_name ?>.jpg">

Код модального окна:
<?php
    echo '
';
?>
    <button data-remodal-action="close" class="remodal-close" aria-label="Close"></button>

            <?php
                echo '';
            ?>

<?php echo $program_name ?>

Собственно нужно, или условие перед вызовом или что-то еще.
В исходном коде, когда страница подгрузилась можно увидеть следующее:
$(document).on('opened', '.remodal', function () {
            console.log('opened');
          });

Возможно ли, вокруг этого сделать условие, "Если opened - тогда подргружаем", было бы замечательно увидеть как это сделать. Также, может быть, у вас есть другие варианты решения этой задачи.
Модальное окно используется вот такое: http://vodkabears.github.io/remodal/
Спасибо за ответы и помощь!

A: Для начала, надо положить ссылку не в src, а куда-то еще. Например, как предложил OlmerDale к комментарии, в data-src:
<iframe width="635" height="357" data-src="<?=$youtube_link?>" frameborder="0" allowfullscreen>

теперь при открытии диалога надо скопировать значение атрибута data-src в src:
$(document).on('opened', '.remodal', function () {
    $(this).find('iframe').attr('src', getSrc);

    function getSrc() { return $(this).data('src'); }
});

A: echo '';

$(document).on('opened', '.remodal', function () {
    $('#modal_video').show();
});

Попробуй так, либо меняй сам линк через JS

A: Когда то имел похожую задачку только с картинками. Клиент хотел чтобы они загружались после открытия модального окна.
Тогда я просто дописывал кусок HTML кода в модальное окно как только ловил ивент click на открытие. Ссылки на картинки хранились в аттрибуте data-image в теге кнопки на которую был навешен  ивент открытия модального окна.
Возможно такой вариант вам поможет.


text:
Q: Count unique rows in a cell full of vectors I have a cell in MATLAB where each element contains a vector of a different length
e.g.
C = {[1 2 3], [2 4 5 6], [1 2 3], [6 4], [7 6 4 3], [4 6], [6 4]}

As you can see, some of the the vectors are repeated, others are unique.
I want to count the number of times each vector occurs and return the count such that I can populate a table in a GUI where each row is a unique combination and the date shows how many times each combination occurs.
e.g.
            Count
"[1 2 3]"     2
"[6 4]"       2
"[2 4 5 6]"   1
"[7 6 4 3]"   1
"[4 6]"       1

I should say that the order of the numbers in each vector is important i.e. [6 4]  is not the same as [4 6].
Any thoughts how I can do this fairly efficiently?
Thanks to people who have commented so far. As @Divakar kindly pointed out, I forgot to mention that the values in the vector can be more than one digit long. i.e. [46, 36 28]. My original code would concatenate the vector [1 2 3 4] into 1234 then use hist to do the counting. Of course this falls apart when you got above single digits as you can tell the difference between [1, 2, 3, 4] and [12, 34].

A: You can convert all the entries to char and then to a 2D numeric array and finally use unique(...'rows') to get labels for unique rows and use them to get their counts.
C = {[46, 36 28], [2 4 5 6], [46, 36 28], [6 4], [7 6 4 3], [4 6], [6 4]} %// Input

char_array1 = char(C{:})-0; %// convert input cell array to a char array
[~,unqlabels,entry_labels] = unique(char_array1,'rows'); %// get unique rows
count = histc(entry_labels,1:max(entry_labels)); %// counts of each unique row

For the purpose of presenting the output in a format as asked in the question, you can use this -
out = [C(unqlabels)' num2cell(count)];

Output -
out =
    [1x4 double]    [1]
    [1x2 double]    [1]
    [1x2 double]    [2]
    [1x4 double]    [1]
    [1x3 double]    [2]

and display the unique rows with celldisp -
ans{1} =
     2     4     5     6
ans{2} =
     4     6
ans{3} =
     6     4
ans{4} =
     7     6     4     3
ans{5} =
    46    36    28

Edit: If you have negative numbers in there, you need to do little more work to setup char_array1 as shown here and rest of the code stays the same -
lens = cellfun(@numel,C);
mat1(max(lens),numel(lens))=0;
mat1(bsxfun(@ge,lens,[1:max(lens)]')) = horzcat(C{:});
char_array1 = mat1';

A: A way I can think of is to convert to strings and then use unique
Cs = cellfun(@(x)(mat2str(x)),C,'uniformoutput',false);
[Cu,idx_u,idx] = unique(Cs);

now you can count the number of occurrences with idx, for instance using
fv=tabulate(idx)

so fv, has already all the info you need, but for purposes of display I'll add:
[Cu' , num2cell(fv(:,2))]

ans =

'[1 2 3]'      [2]
'[2 4 5 6]'    [1]
'[4 6]'        [1]
'[6 4]'        [2]
'[7 6 4 3]'    [1]

A: Another suggestion I can think of is to convert each array into a concatenation of numbers, then do a histogram to count how many values you have per entry.  We would need to figure out how many unique numbers we have first, which would serve as the histogram edges through unique.
One thing I will need to note is that we are assuming that each element in your array for each cell is a single digit.  This obviously won't work if there are numbers that are two digits or more.
In other words:
%// Convert each array of numbers into a single number
numbers = cellfun(@(x) sum(x.*10.^(numel(x)-1:-1:0)), C);
%// Find unique numbers
uniNumbers = unique(numbers);

%// Get histogram
out = histc(numbers, uniNumbers);

%// Display counts
disp([uniNumbers; out]);

out would contain the counts per unique number in your cell array.  We get:
      46          64         123        2456        7643
       1           2           2           1           1

The trick with the first line of code is that I'm using the decomposition of numbers in base 10 where each digit can be uniquely represented as a sum of multiples of powers of 10.  As such, 4587 can be represented as:
4000 + 500 + 80 + 7 ==> 4*10^3 + 5*10^2 + 8*10^1 + 7*10^0

I took each number in our array, and used those as coefficients for each decreasing power of 10, then summed them all together.  As such, in your cell arrays, [1 2 3], is converted to 123, and so on.  With your example, this is the output of numbers, which is doing what I talked about above:
numbers =

  Columns 1 through 6

         123        2456         123          64        7643          46

  Column 7

          64

Compare this with your actual cell array in C:
celldisp(C)

C{1} =
     1     2     3
C{2} =
     2     4     5     6
C{3} =
     1     2     3
C{4} =
     6     4
C{5} =
     7     6     4     3
C{6} =
     4     6
C{7} =
     6     4


text:
Q: How to add new rows at bottom of tableview - chat messages I'm using the following code to add new messages every time the user types a message and click 'send'. It works great. But the problem is, new messages are inserted at the top of the table view. I want it to be inserted at the bottom.
    import UIKit

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

    @IBOutlet var messagesTable: UITableView!
    @IBOutlet var messageTextBox: UITextField!

    var messageArray = [String]()

    @IBAction func sendMessage(sender: AnyObject) {

        messageArray.append(messageTextBox.text!)
        messagesTable.reloadData()
        messageTextBox.text = ""

    }

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return messageArray.count
    }

    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        return 80
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        //self.messagesTable.contentInset = UIEdgeInsetsMake(messagesTable.frame.height,0,0,0)

        let cell = NSBundle.mainBundle().loadNibNamed("AgentMessageText", owner: self, options: nil)?.first as! AgentMessageText
        cell.messageText.text = messageArray[indexPath.row]
        return cell
    }

}

The below code insert rows to bottom. But the newly inserted rows are below the view point. That is we have to scroll to see it every time
self.messagesTable.contentInset = UIEdgeInsetsMake(messagesTable.frame.height,0,0,0)

A: A common solution to this problem is to flip the tableview (so cells stick to the bottom) then flip the cells so the content is oriented properly.
Example:
override func viewDidLoad() {
    super.viewDidLoad()

    //flips the tableview (and all cells) upside down
    messagesTableView.transform = CGAffineTransformMakeScale(1, -1)
}

...
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

   ...

   //flips the cell to appear oriented correctly
   cell.transform = CGAffineTransformMakeScale(1, -1)

For Swift 4
Just to be clear, for Swift 4.0 the above transform function is as per below
CGAffineTransform(scaleX: 1, y: -1)

A: You've to use scrollToRow to scroll to your message (use .bottom/.top/etc. acc. to your need)
Also instead of reloading your whole table view you can add just one (new) message(cell) to table view
@IBAction func sendMessage(sender: AnyObject) {
  messageArray.append(messageTextBox.text!)
  messagesTable.reloadData()
  let indexPath = IndexPath(item: messageArray.count, section: 0)
  messagesTable.scrollToRow(at: indexPath, at: .bottom, animated: true)
  messageTextBox.text = ""
}

A: For Scroll To Bottom In Your Chat App
For Swift 3.0

Write a function :
func scrollToBottom(){
    DispatchQueue.main.async {
        let indexPath = IndexPath(row: self.dataArray.count-1, section: 0)
        self.tableView.scrollToRow(at: indexPath, at: .bottom, animated: true)
    }
}

and call it after you reload the tableview data
tableView.reloadData()
scrollToBottom()

A: Swift 5. Write a function:
self.tableView.reloadData()  let index =
self.tableView.indexPathsForVisibleRows  self.tableView.scrollToRow(at: (index?.last)!, at: .top, animated: true)


text:
Q: App icon for Android in Phonegap I have an HTML5/Javascript app, and I have used PhoneGap's build service to generate the APK file for my Android.
I successfully installed the APK file on my Android and everything is fine, except that the app icon on the phone is the default Android icon. In PhoneGap Build I uploaded my PNG file to the project under the 'Details' section, and I thought that icon was supposed to be used as your app icon? I've tried several different sizes.
Let me know if there is something else I need to be doing.

A: In the Phone Gap the following should contain

www_android\res\values\strings.xml - contains the name of the app
  www_android\res\drawable-hdpi - contains a 57x57 pixel icon
  www_android\res\drawable-hdpi - contains a 57x57 pixel icon
  www_android\res\drawable-hdpi - contains a 57x57 pixel icon

Source (Step 12)
Alternatively
<?xml version="1.0" encoding="UTF-8"?>
<widget xmlns="http://www.w3.org/ns/widgets" xmlns:gap="http://phonegap.com/ns/1.0" id="com.nitobi.johngarrett" version="1.0">
<name>John Garrett Drinking Game</name>
<description>
If you're watching a Canucks game, you need play this.
</description>
<author href="http://www.nitobi.com" email="support@nitobi.com">
Tim Kim, Ryan Betts, Fil Maj
</author>
<icon src="img/beer_72.png" width="72" height="72" />
<icon src="img/beer_48.png" width="48" height="48" />
<icon src="img/beer_36.png" width="36" height="36" />
</widget>

Source

A: None of the above answers worked but I figured it out how. Create a png icon and name it "icon.png" and simply place the image under "Project_Folder/res/drawable-hdpi/", where Project_Folder is your PhoneGap application folder.
Hope that helps.


text:
Q: Enumeration & IComparable I have an object having the following structure:
 public class StockData
    {
        public string Name { get; set; }
        public double Change { get; set; }
        public DateTime LastUpdate { get; set; }
        public WorkflowStatus Status { get; set; }
    }

The Workflow status enum is defined as following:
public enum WorkflowStatus
    {
        PendingCoverage,
        PendingCompliance,
        Approved,
        Rejected
    }

Issue:
I have a grid (wpf) which binds all StockData to it and I have set a grouping on the Status field. I want the groups to be appearing in the grid as it's defined in the order of WorkflowStatus enum. This works absolutely fine and data is grouped in the order as it's defined inside the enum i.e first group is Pendingcoverage and the last is Rejected.
Now I want to remove this enum and introduce an object graph instead of the enum..which means there will be a base class called WorkflowStatus and 4 derived class called PendingCoverage, PendingCompliance, Approved and Rejected. Each derived class will be overiding the ToString property and returning an appropriate string.
Now, this does't work. For some reason it's not able to establish which group should come first and which should come subsequently. Question is how will I implement IComparable in this scenario. Should I implement IComparable (or something else) on StockData or on each individual WorkflowStatus object, and yes then how? Also why does this work in the case of enum and not in the case of an object?

A: Create your base class and add an abstract Order property to it that all sub classes must implement. Basically an integer which specifies their ordering.
You can also implement IComparable on your abstract class so that if compares objects based on their order property.
public abstract class WorkStatus : IComparable<WorkStatus> {
    public abstract int Order { get; }

    public int CompareTo(WorkStatus w)
    {
        if(w.Order < this.Order)
         return 1;
        if(w.Order > this.Order)
         return -1;
        return 0;
    }
}

For each implementation, give them a different Order value.
public class FirstStatus : WorkStatus {
   public override int Order {get { return 1; } }
}

public class SecondStatus : WorkStatus {
   public override int Order { get { return 2; } }
}

Assuming your WPF grid is just applying a standard OrderBy query, then if should work as follows.
//LINQPAD SNIPPET
void Main()
{
    List<WorkStatus> list = new List<WorkStatus>();

    list.Add(new SecondStatus()); //out of order initially.
    list.Add(new FirstStatus());

    Console.WriteLine(list.OrderBy(x => x));

}

A: I'm confused as to why IComparable is required here. You have two problems. One is getting a sorted list, the other is getting the appropriate graph:
// Takes a work status and returns the appropriate graph.
static GenericBaseGraphClass GetGraph(WorkStatus input)
{
    select(input.Status)
    {
        // Concrete derived classes go here.
    }
}

// Test data.
var someWork = new List<WorkStatus>()
{
    new SecondStatus(),
    new FirstStatus()
};

// Sort it.
var sortedWork = someWork.Sort((x,y) => x.Status > y.Status);

// Get your object graphs.
var objectGraphs = sortedWork.Select(x => GetGraph(x.Status))


text:
Q: Do the vi and emacs implementations for Windows behave like their Unix counterparts? If not, what are the significant differences?

Edit: Daren Thomas asks:

which ones?
I use gvim on Windows and MacVim on the mac. Seem similar enough to be the same to me...

By which ones, I'm guessing that you mean a specific implementation of vi and emacs for Windows. I'm not sure as I thought there were only one or two. I'm looking for the ones that are closest to the Unix counterparts.

A: I use GNU emacs built for Windows, and have found very few, if any, differences. There's the option to load your .emacs file from _emacs or .emacs (although .emacs works fine on XP and above). You can configure it to use Windows-style or Unix-style line endings by default (which I suppose you could do on a Unix system too...).
You may want to tweak such settings as Emacs's startup directory and home directory. To do the former, modify the shortcut that starts emacs. To do the latter, add a HOME environment variable - this will control where your .emacs is loaded from. For more information, check the always-excellent EmacsWiki's MsWindowsInstallation page.

A: which ones?
I use gvim on Windows and MacVim on the mac. Seem similar enough to be the same to me...

A: GNU Emacs has long been working natively on Windows as part of the main source, and can be compiled with Visual Studio (you can also find some pre-compiled binaries). As far as I know, there are no significant differences.

A: There are quite a few vi clones (e.g. vim) and also various Emacs implementations (Gnu Emacs vs. XEmacs spring to mind).
These clones differ on Unix themselves and will thus also differ on Windows.
One thing I found with vim is that the directory structure for plugins etc. is very different on Windows - ~/vim.rc translates to %HOME%\vim_rc (or similar, depends on stuff I don't understand), vim tends to save stuff like plugins under C:\Program Files\vim\... instead of ~/.vim/...

A: The Windows versions typically use the same base source code as the "regular", Unix-based versions. There may be sections of the code that are specific to Windows, just as there are sections specific to certain flavours of Unix. In general, though, the Windows versions of these packages will behave identically to the Unix ones, except where this is not possible (for example, gvim in Windows will use Windows GUI elements, of course).


text:
Q: How to merge data from different sheets that use the same template? I have one spreadsheet which has 5 sheets
All the sheets share the same template, so they are alike. The only difference is the data
I would like to make another sheet, whichs gets all the data from column A3 (from row 3 to the end) in sheet 1,2,3,4,5, and puts it in 1 column in my new sheet.
How is this possible?
I am using Google Docs, but i guess Excel and Google Docs are much alike.
Thanks

A: =CONCATENATE(Sheet1!A:A,",",Sheet2!A:A,",",Sheet3!A:A,",",Sheet4!A:A,",",sheet5!(A:A))
This will concatenate A1,A1,A1,A1,A1 for sheets 1-5 on sheet 6. Drag it down to concatenate by cells (A2 then A3). You don't need to define the ranges A:A but you can if you want.

A: By far the best answer I've found to this question is found here: http://www.jessespevack.com/systems-leadership/2015/4/22/pulling-spreadsheet-data-no-scripts-required.  In essence use ImportRange to pull in data from several other sheets. Then wrap those in an ArrayFormula so that they appear one after the other on the sheet.  Lastly wrap the ArrayFormula in a Sort so that the blank lines are all left at the end.
Say you have Sheet1, Sheet2 and Sheet3 and you would like to combine columns A through E on MergeSheet. Put the column headings in the cells MergeSheet!A1:E1
Then in cell A2 enter a formula like this:
=SORT(
    ARRAYFORMULA({
         IMPORTRANGE("https://docs.google.com/spreadsheets/d/UniqueKey","Sheet1!A2:E");
         IMPORTRANGE("https://docs.google.com/spreadsheets/d/UniqueKey","Sheet2!A2:E");
         IMPORTRANGE("https://docs.google.com/spreadsheets/d/UniqueKey","Sheet3!A2:E")
,1,TRUE}))

The URL is the url of the spreadsheet, and can be copied from the address bar of the browser.
It's best to test that the IMPORTRANGE function works for each range individually before combining them into the one long function.

A: I don't think that you have a built-in function for such functionality.
You can easily write an Apps Script that performs this
var sheets = SpreadsheetApp.getActiveSpreadsheet().getSheets();

var newData = new Array();

for (var i = 1; i <= 5; i++)  {
  var s = sheets[i];
  var r = s.getRange("A:A");
  // Go over the values and fill up a new range in sheet 6...
  var data = r.getValues();
  for(i in data){
    var row = data[i];
    newData.push(row);
  }
}

A: This is the simpliest solution to merge multiple sheets of multiple google spreadsheets (with the same columns)
=SORT(
    {
        IMPORTRANGE("unique_spreadsheet_key1";"'Your first sheet'!A2:G");
        IMPORTRANGE("unique_spreadsheet_key2";"'Your second sheet'!A2:G");
        IMPORTRANGE("unique_spreadsheet_key2";"'Your third sheet'!A2:G")
    };
    3;  TRUE
)

Based on dcb solution, but corrected (the SORT part) and without ARRAYFORMULA!

*

*You can change 3 to sort your merged sheet by the column of your need !

*unique_spreadsheet_key : just the key, doesn't neet complete url


text:
Q: Linux and Azure AD sync possible? I am currently considering to shuffle some infrastructure around, but my question boils down to:

Can I sync a list of users and passwords to Azure AD (only for Office 365) from a linux samba server?

Currently there's an on premise Windows Server that doesn't do much apart from DNS and user management for different services through the Active Directory. My thought was: why not ditch that for a Linux Server with one of the open source replacements.
Currently I'm stuck on the office 365 user sync and posts that state that Open LDAP and other possibilities will be available in the near future. Last update: 2014.

A: I don't believe there is a tool "right now" that will allow you to synchronise accounts from a Samba DC to Azure Active Directory. You should be able to set up your spare Windows Server as a secondary Domain Controller and then synchronise from that using Azure AD Connect, though.
Another option - albeit a heavyweight one - might be to go the Federation route and use your own SAML authentication server(s) to authenticate access to Office 365. This is not for the faint-hearted; I've not yet managed to get Microsoft's Federation-based authentication to work with exclusively Microsoft software in the loop, so I suspect you would be embarking on a voyage of discovery without any knowledge that the edge of the world really wasn't a gigantic waterfall...
In practical terms you might get a more hands-on answer over on Server Fault.


text:
Q: Edit box in repeat control with default value does not update on delete I have a Repeat control in which I have a edit box which has passed a default value.There is a Delete button to delete that row.
just for test I have used a computed field along with the edit box.Computed field is also passed the same value as edit box.Now both computed Field and Edit Box has same value,When I click on Delete button randomly,it gets delete but only computed field updates properly in repeat control wherever deleted,
In case of Edit box,it shows the last record disappears.
So the issue is, the value in edit box does not get update like computed field does.I have done the test by writing following code.
 <?xml version="1.0" encoding="UTF-8"?>
<xp:view xmlns:xp="http://www.ibm.com/xsp/core">

    <xp:this.data>
        <xp:dominoDocument var="document1" formName="testing">
        </xp:dominoDocument>
    </xp:this.data>
    <xp:inputText id="inputText1" multipleSeparator=",">
        <xp:this.defaultValue><![CDATA[#{javascript:var v:java.util.Vector = new java.util.Vector();
v.add('1');v.add('2');v.add('3');v.add('4');v.add('5');v.add('6');
return v;}]]></xp:this.defaultValue>
    </xp:inputText>
    <xp:br></xp:br>
    <xp:repeat id="repeat1" rows="30" var="r" indexVar="i" first="0">
        <xp:this.value><![CDATA[#{javascript:return getComponent("inputText1").getValue();}]]></xp:this.value>
        <xp:br></xp:br>
        <xp:div style="text-align:center">
            <xp:label value="#{javascript:r}" id="label1"
                style="text-align:center">
            </xp:label>
            <xp:button value="Delete" id="button1">
                <xp:eventHandler event="onclick" submit="true"
                    refreshMode="complete">
                    <xp:this.action><![CDATA[#{javascript:var v:java.util.Vector = getComponent("inputText1").getValue();
if(v != null){
var sdtString =  getComponent("inputText2").getValue();
if(v.contains(sdtString))
v.remove(sdtString);
};}]]></xp:this.action>
                </xp:eventHandler>
            </xp:button>
            <xp:inputText id="inputText2">
                <xp:this.defaultValue><![CDATA[#{javascript:getComponent("label1").getValue();}]]></xp:this.defaultValue>
            </xp:inputText>
        </xp:div>
        <xp:br></xp:br>
    </xp:repeat>
</xp:view>

This is the example code for testing to get the exact issue.
Edit 1: Real Scenario
We have an application to select multiple dates for a meeting and hence using the notes free time we mark multiple dates and then users are allowed to edit/delete the same in another window..Since, it was not possible/feasible enough to save all the fields in SSJS, we rather preferred binding each field with the data-source under the repeat control by using custom properties of the custom control (hope I am making some sense). Every fields is mapped as @chintan pointed out as follows:
dataSource[compositeData.to]

As described in the first part of the question the fields are not getting updated since we set them using default values. However, based on the suggestion we tried to set the field using the script library which does work well, however, might seem stupid but it messes the date field. When we set the value using the following:
var d:java.util.Date = new java.util.Date(compositeData.selectedDate);
getComponent("from").setValue(d);

It jumbles up the month, date and year field and shows a complete different value (the same code works well when put as the default value).
Hope this makes sense.
Any kind of solution can be appreciated.

A: inputText2's defaultValue gets executed only once at first page load. Then the XPage memorized that repeat 1 has inputText2 defaultValue 1, repeat 2 has inputText2 defaultValue 2 and so on.

Example: as you can see in print log, inputText2's defaultValue doesn't get calculated again after deleting row 3 and later row 1.
Turn it around and set inputText2's value in label1's value code:
        <xp:label
            value="#{javascript:getComponent('inputText2').setValue(r); r}"
            id="label1"
            style="text-align:center">
        </xp:label>

then it will set inputText2's value properly. You don't need inputText2's defaultValue property anymore.
As an alternative you can define inputText2's value property and bind it to a row-specific data source or viewScope variable.

A: As you described in your "Edit 1 Real Scenario", you want to edit and delete pairs of dates. I created the following example. Instead of dates I just use strings for simplicity. Keep the dates in a viewScope variable and edit/delete them right there:
<?xml version="1.0" encoding="UTF-8"?>
<xp:view
    xmlns:xp="http://www.ibm.com/xsp/core">
    <xp:this.beforePageLoad><![CDATA[#{javascript:viewScope.dates=[
    {"from":"a", "to":"b"},
    {"from":"c", "to":"d"},
    {"from":"x", "to":"y"}];}]]></xp:this.beforePageLoad>
    <xp:br />
    <xp:repeat
        id="repeat1"
        rows="30"
        var="r"
        indexVar="i"
        value="#{viewScope.dates}">
        <xp:br></xp:br>
        <xp:div>
            <xp:button
                value="Delete"
                id="button1">
                <xp:eventHandler
                    event="onclick"
                    submit="true"
                    refreshMode="complete">
                    <xp:this.action><![CDATA[#{javascript: viewScope.dates.remove(i);
                    }]]></xp:this.action>
                </xp:eventHandler>
            </xp:button>
            <xp:inputText
                id="inputText1"
                value="#{r.from}">
            </xp:inputText>
            <xp:inputText
                id="inputText2"
                value="#{r.to}">
            </xp:inputText>
            <xp:button
                value="Update"
                id="button2">
                <xp:eventHandler
                    event="onclick"
                    submit="true"
                    refreshMode="complete">
                    <xp:this.action><![CDATA[#{javascript: "";
                    }]]></xp:this.action>
                </xp:eventHandler>
            </xp:button>
        </xp:div>
        <xp:br></xp:br>
    </xp:repeat>
    <xp:text
        escape="false"
        id="computedField1">
        <xp:this.value><![CDATA[#{javascript:
            var length = viewScope.dates.length;
            var result = "";
            for (var i = 0; i < length; i++) {
                result += viewScope.dates[i].from + " - " + viewScope.dates[i].to + "<br />";
            }
            result
        }]]></xp:this.value>
    </xp:text>
</xp:view>

Create the viewScope variable as an array of objects.


text:
Q: .NET Core 2 build is not working in .NET Core 3.1 All,
I have a build server that has .NET Core 2.2.110 installed in it. For my new application, I need .NET Core 3.1. So I've installed .NET Core 3.1 in addition to .NET Core 2.2.110.
When I hit dotnet --version I get 3.1
The build is working fine when building applications developed in .NET Core 3.1 but it's failing for the below framework applications and giving me the following error
The imported project "C:\Program Files\dotnet\sdk\3.1.100\Microsoft\VisualStudio\v16.0\WebApplications\Microsoft.WebApplication.targets" was not found
I have both 2.1 as well as 3.1 on my build machine, technically applications developed by 3.1 should use .NET Core 3.1 f/w, and apps developed by 2.2.110 should use .NET Core 2.2.110.
Also, any upgraded framework should also support previous versioned apps but in my case, it's failing.
Please help me

A: Maybe you can specify the target platform in each project.
Add the line :
<PropertyGroup><TargetFramework>netcoreapp3.1</TargetFramework>/PropertyGroup> in you .csproj file to compile with .Net 3.1 or netcoreapp2.0 for .Net 2


text:
Q: Change the file type when downloading Is Asp.Net Core 5 I have two files with js extension that need to be downloaded one after the other in one view. The problem that has  is that I in Debug mode, after I publish from the desired file and put it in IIS, the extension type of the second file is xml. and it gives an error.
The following code works correctly in Debug mode and loads the desired js
@section Scripts {
    <script type="text/javascript">
        window.$(document).ready(function() {

            window.$.getScript("/***/script-controller.js")
                .done(function(data, status, jqxhr) {

                    window.$('#layoutMain').html(ShowLoading());

                    window.$.getScript("/***/Home.js")
                            .done(function(data, status, jqxhr) {

                            })
                            .fail(function() {

                            });

                })
                .fail(function() {

                });

        })
    </script>
}

The following image is in Debug mode

The image below when published and placed in IIS


text:
Q: Authenticate App using X.509 certificate on Android My app needs to validate an X.509 certificate before sending username/password for verification.
Client X.509 certificate is already installed on Android device in "Trusted Credentials".
I am not sure now how to validate it.
I am assuming the steps would be as follows but don't know how to use the java.security.cert or similar API to do this:

*

*From the "User" tab (not System), open my X.509 certificate and get reference to it.

*Validate things like - valid expiration, issuer, revocation list etc.

Can someone help please?
Thanks
Sandeep


text:
Q: Mod Portal 2 Audio Okay so, I want to make an audio mod for Portal 2, but I'm not sure how to do it. I explored the game folder a bit but I couldn't find any distinct audio files (or at least in a format I would recognize). Does anyone have any pointers about how to do this? I'm sort of new to the world of computers, so I don't really know what all these files do, and I don't want to delete something important by accident.
Thanks - DT75

A: Portal 2 (and other Valve games) put their files in Valve Package (or VPK) files.
The Windows program GCFScape can be used to read these files, as can the command-line vpk program included in the Portal 2 Authoring Tools.
You can install the Portal 2 Authoring Tools from the Steam Library.  To find it, you will need to select Tools from the dropdown near the top of the library screen.
You will want to open the file whose name ends in _dir.vpk.  I think it's pak01_dir.vpk for Portal 2.
Basically, if you create sound files in the same path in Portal 2's sound/ directory as they are inside the VPK files, the game will use these sound files in preference to the ones inside the VPK.
In other Valve games, you can even package sounds inside your own VPK file and the game will use those in preference to its own sound files.  I'm not sure if that works in Portal 2, though.


text:
Q: How can I solve watching issue in webpack? I really hope, you can help me.
When I import a module in the index.js in a following way: ( import Test from './src/test'; ) Webpack recognizes the .web.js extension and uses it. However, if I make changes in the file system for instance I delete or rename this file, the webpack will notice that the file is missing. Nevertheless, it doesn't recompile and doesn't use the other file opportunity (test.js).
I have used webpack 3.6.0 and I tried to use in Watch mode, too. But unfortunately it doesn't work.


text:
Q: How do I access data from one buttonclick_event in the second buttonclick_event Will I just have to store the data somewhere or can the second buttonclick take advantage of the current state of the program that the first buttonclick has generated? The first buttonclick has generated local variables that the second buttonclick needs to access.
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;
using System.Diagnostics;
using System.IO;

namespace AnimalGame
{
    public partial class Game : Form
    {
        List<Animal> animalList = new List<Animal>();

        public Game()
        {
            InitializeComponent();
        }

        private void SpawnButton_Click(object sender, EventArgs e)
        {
            int cricketQuantity = Int32.Parse(CricketQuantityInput.Text);
            int frogQuantity = Int32.Parse(FrogQuantityInput.Text);
            int birdQuantity = Int32.Parse(BirdQuantityInput.Text);
            int mouseQuantity = Int32.Parse(MouseQuantityInput.Text);
            int snakeQuantity = Int32.Parse(SnakeQuantityInput.Text);
            int hunterQuantity = Int32.Parse(HunterQuantityInput.Text);

            for (var i = 0; i < cricketQuantity; i++)
            {
                animalList.Add(new Cricket());
            }
            for (var i = 0; i < frogQuantity; i++)
            {
                animalList.Add(new Frog());
            }
            for (var i = 0; i < birdQuantity; i++)
            {
                animalList.Add(new Bird());
            }
            for (var i = 0; i < mouseQuantity; i++)
            {
                animalList.Add(new Mouse());
            }
            for (var i = 0; i < snakeQuantity; i++)
            {
                animalList.Add(new Snake());
            }
            for (var i = 0; i < hunterQuantity; i++)
            {
                animalList.Add(new Hunter());
            }

            int totalAnimals = animalList.Count();
            TotalAnimalsTextBox.Text = Convert.ToString(totalAnimals);

            foreach (Animal a in animalList)
            {
                if (a is Cricket)
                {
                    Panel cricketPanel = new Panel();
                    cricketPanel.Size = new System.Drawing.Size(9, 9);
                    cricketPanel.BackColor = Color.DarkGoldenrod;
                    a.Spawn();
                    GameGrid.Controls.Add(cricketPanel, a.XCoordinate, a.YCoordinate);
                }
                else if (a is Frog)
                {
                    Panel frogPanel = new Panel();
                    frogPanel.Size = new System.Drawing.Size(9, 9);
                    frogPanel.BackColor = Color.Lime;
                    a.Spawn();
                    GameGrid.Controls.Add(frogPanel, a.XCoordinate, a.YCoordinate);
                }
                else if (a is Bird)
                {
                    Panel birdPanel = new Panel();
                    birdPanel.Size = new System.Drawing.Size(9, 9);
                    birdPanel.BackColor = Color.SaddleBrown;
                    a.Spawn();
                    GameGrid.Controls.Add(birdPanel, a.XCoordinate, a.YCoordinate);
                }

            }
        }

        private void NextMoveButton_Click(object sender, EventArgs e)
        {
            // this code needs to access the current object locations above and "move" them to another cell in
            // the grid
        }
    }

}

public abstract class Animal
{
    private int xCoordinate;
    private int yCoordinate;
    public abstract void Move();
    public void Spawn()
    {
        Random locationX = new Random(Guid.NewGuid().GetHashCode());
        var spawnX = locationX.Next(0, 50);
        Random locationY = new Random(Guid.NewGuid().GetHashCode());
        var spawnY = locationY.Next(0, 50);
        xCoordinate = spawnX;
        yCoordinate = spawnY;
    }

    public int XCoordinate
    {
        get
        {
            return xCoordinate;
        }

        set
        {
            xCoordinate = value;
        }

    }
    public int YCoordinate
    {
        get
        {
            return yCoordinate;
        }

        set
        {
            if (yCoordinate > 50)
            {
                yCoordinate = 50;
            }

            else if ( yCoordinate < 0)
            {
                yCoordinate = 0;
            }
            else
            {
                yCoordinate = value;
            }
        }
    }
}

class Cricket : Animal
{
    public override void Move()
    {
        Random direction = new Random();
        // the Cricket only moves one cell at a time.
        // 0 = Up
        // 1 = Right
        // 2 = Down
        // 3 = Left
        var selectionDirection = direction.Next(0, 4);
        switch (selectionDirection)
        {
            case 0:
                YCoordinate -= 1;
                break;
            case 1:
                XCoordinate += 1;
                break;
            case 2:
                YCoordinate += 1;
                break;
            case 3:
                XCoordinate -= 1;
                break;
        }
    }
}

class Frog : Animal
{
    public override void Move()
    {
        Random direction = new Random();
        // the Frog moves 3 cells at a time.
        // 0 = Up
        // 1 = Right
        // 2 = Down
        // 3 = Left
        var selectionDirection = direction.Next(0, 4);
        switch (selectionDirection)
        {
            case 0:
                YCoordinate -= 3;
                break;
            case 1:
                XCoordinate += 3;
                break;
            case 2:
                YCoordinate += 3;
                break;
            case 3:
                XCoordinate -= 3;
                break;
        }
    }
}

class Bird : Animal
{
    public override void Move()
    {
        Random direction = new Random();
        // the Bird moves 5 cells at a time.
        // 0 = Up
        // 1 = Right
        // 2 = Down
        // 3 = Left
        var selectionDirection = direction.Next(0, 4);
        switch (selectionDirection)
        {
            case 0:
                YCoordinate -= 4;
                break;
            case 1:
                XCoordinate += 4;
                break;
            case 2:
                YCoordinate += 4;
                break;
            case 3:
                XCoordinate -= 4;
                break;
        }
    }
}

class Mouse : Animal
{
    public override void Move()
    {
        Random direction = new Random();
        // the Mouse moves 2 cells at a time.
        // 0 = Up
        // 1 = Right
        // 2 = Down
        // 3 = Left
        var selectionDirection = direction.Next();
        switch (selectionDirection)
        {
            case 0:
                YCoordinate -= 2;
                break;
            case 1:
                XCoordinate += 2;
                break;
            case 2:
                YCoordinate += 2;
                break;
            case 3:
                XCoordinate -= 2;
                break;
        }

    }
}

class Snake : Animal
{
    public override void Move()
    {
        Random direction = new Random();
        // the Mouse moves 4 cells at a time.
        // 0 = Up
        // 1 = Right
        // 2 = Down
        // 3 = Left
        var selectionDirection = direction.Next();
        switch (selectionDirection)
        {
            case 0:
                YCoordinate -= 2;
                break;
            case 1:
                XCoordinate += 2;
                break;
            case 2:
                YCoordinate += 2;
                break;
            case 3:
                XCoordinate -= 2;
                break;
        }

    }
}

class Hunter : Animal
{
    public override void Move()
    {
        Random direction = new Random();
        // the Hunter moves 2 cells at a time.
        // 0 = Up
        // 1 = Right
        // 2 = Down
        // 3 = Left
        var selectionDirection = direction.Next();
        switch (selectionDirection)
        {
            case 0:
                YCoordinate -= 2;
                break;
            case 1:
                XCoordinate += 2;
                break;
            case 2:
                YCoordinate += 2;
                break;
            case 3:
                XCoordinate -= 2;
                break;
        }

    }
}

A: You can get all Panels from GameGrid.Controls collection. You can iterate through those controls and do your logic.
If you need to know which Animal belongs you which Panel you can create a dictionary field and map each Animal to a Panel:
public partial class Game : Form
{
    List<Animal> animalList = new List<Animal>();
    Dictionary<Animal, Panel> animalPanels = new Dictionary<Animal, Panel>();

    ...

            // For each animal.
            a.Spawn();
            GameGrid.Controls.Add(birdPanel, a.XCoordinate, a.YCoordinate);
            animalPanels.Add(a, birdPanel);
    ...

    private void NextMoveButton_Click(object sender, EventArgs e)
    {
        // Access GameGrid.Controls.

        // Or animalPanels.
    }
}


text: Q: How to merge rows with similar values in datagaridview Good day everyone, can anyone help me with merging rows with similar values in datagridviewrow... I am making an application where if you select multiple items with similar item names, it must not add another row, instead it will just merge with the same row with same values, and it will add up the quantity and total. for clarity, this is the image.


text:
Q: UL overlap, float:left image
Possible Duplicate:
Why do my list item bullets overlap floating elements

I've been having this problem with ul's next to a floating image
Here is the code i've been using
 Hello world isn't this amazing

One

Two

Three

Four

Five

Six

Extra sample text here

Result

If it's changed to

The list carries on past the image, not what i want
Also trying this below gives the wrong result

Photoshop of what i want

A: While using list-style-position: inside on the , also remove the padding-left of . The padding is usually defined by the browser. As an alternative, you could leave list-style-position: outside and increase the margin-left of  until the bullets aren't overlapping.

A: you can put the ul inside a div and make the div float left after the image

A: This is a great reference for how CSS works: CSS2.1#floats

 is a block element so you can make the  float next to the image without any extra div like so using inline styles:

A: The simplest way is to add margin-right: 20px; to your image. Or, if you need to move only your list and leave the surrounding text in place, add margin-left: 40px; to the
.

A: Another fugly, but working solution is to put each li in a separate ul, and set overflow:hidden on the uls, like so: http://jsfiddle.net/xA9n8/


text:
Q: What encoding does FileIO.WriteTextAsync(file, text) use? Windows.Storage.FileIo.WriteTextAsync method has two overloads, with and without text encoding.
However, MSDN pages of the method (either the main page or the page for either overload) does not specify what encoding is used by the method without encoding parameter.
So what encoding is used by default?
Additional question: Stuff like this is probably documented somewhere. So how to find the relevant information from MSDN? Is it organized according to some pattern I don't see?

A: Take a look at the overloaded method with encoding parameter:

Remarks
This method attempts to automatically detect the encoding of a
  file based on the presence of byte order marks. If an encoding cannot
  be detected, the encoding specified by the caller is used.

And that is how the first method works just without the last sentence:

This method attempts to automatically detect the encoding of a
  file based on the presence of byte order marks.

If an encoding cannot be detected, Encoding.Default Property is used.


text:
Q: How to modify DLL toString method? How can i make doubly linked lists print in this order:
1<->2<->3<->4<->5<-> etc..
For example i have a code here that print in this order:
<-1-><-2-><-3-><-4-><-5->
What should i modify in my toString(); function ?
  @Override
        public String toString() {
            String ret = new String();
            if (first != null) {
                DLLNode<E> tmp = first;
                ret += tmp + "<->";
                while (tmp.succ != null) {
                    tmp = tmp.succ;
                    ret += tmp;
                }
            } else
                ret = "Empty list";
            return ret;
        }


text:
Q: Why does $request->get() return null? I am sending a post request to laravel via an angularjs form,
AngularJS:
<input type="text" ng-model="app.person.firstName">
<input type="text" ng-model="app.person.lastName">

$http.post('/tests', person).success(function(data) {
    console.log(data);
  }).error(function() {
    console.log("Oh no!");
});

Laravel with $request->all() (works):
 $input = $request->all();
 $first = $input['firstName'];
 $last = $input['lastName'];
 ....
 return json_encode($this->data_object);
 // returns correct object

Laravel with $request->get() (returns null):
 $input = $request->get('firstName');
 return json_encode($input);
 // returns null

Why does $request->get('firstName') return null when $request->all() returns an object with a firstName index?

A: There's currently a bug in Laravel where $request->get() only works for actual GET and POST data.
It doesn't work when the post body is JSON (which is what Angular does).
You can use $request->input('firstName') instead.


text:
Q: How to execute reports which involve a stored procedure calling out to a linked server I wrote a stored procedure that calls openquery to a linked server to get data from a remote postgresql server and fill a table with that data. This is working fine. The stored procedure needs 3 parameters.
When I try to call the stored procedure from Report Builder 3.0 gives me error

7350 (cannot get the column OLE DB provider MSDASQL from linked server "name").

I already verify the allow in-process parameter in MSDASQL.
I can't find a solution for this. If I run the stored procedure from Mgmt Studio, it works fine. I'm using SQL Server 2012.
The report only have to show the file data by row. I can run the stored procedure and the report separately and works but I have to do this manually, my requirement needs a report subscription, so have to be automatic.
Any idea how to solve this or a workaround?
PD: sorry for my english, and thank you in advance.

A: Well I had to make separates works, so create a job that run the store procedure, generate the info on a table, and then run report reading the info from the table. This works.
Thank you all.


text:
Q: Correct grammar with LIKE condition in SQLite With SQLite I can:
select my_column from my_table where substr(word,1,1) like '%I%';

so I'll have all the string results whose first character is I. But now I want to have results whose first character is I and F and J. I have tried:
select my_column from my_table where substr(word,1,1) like '%I%'&'%F%'&'%J%';

but that doesn't work.
What grammar should I use to find results with those first letters?

A: Here's the right answer: SELECT mycolumn FROM mytable WHERE upper(substr(word,1,1)) IN ('I', 'F', 'J');


text:
Q: Would you be so kind as to answer me? vs Could you be so kind as to answer me? The phrases "Would you be so kind as to answer me?" and "Could you be so kind as to answer me?" could they be used interchangeably?

A: There are many here who would say that they are interchangeable in everyday speech, but strictly speaking they don't mean the same thing.
could asks about the possibility of an action.
would requests that the action be performed.
As one comment says, this form of phrasing is hardly ever used. "Would you please answer me?" is what a native English speaker would say under most circumstances.


text:
Q: What's wrong with my Keil v5 compiler that target is sometimes gets created and sometimes not? I want to perform blinky program operation on STM32F103C8T8 using Keil v5 Compiler. I am generating C source code using STM cubemx and making Pin13 on/off with delay of 100ms. My code is here
The problem is that when I click on rebuild option the code the target is created without any error
]2
and when I click on rebuild option another time(Without any change in anything), the target is not created showing multiple errors. The target is created when I click "rebuild" option after N no of trials (sometimes 1 or 2 and sometimes 100).

I am getting mainly 2 types of errors
1. error :command line:#564:cannot open embedded assembler output file'':no such file or directory
2.error: A1620E: error writing to file :permission denied
So how to resolve them?


text:
Q: Android - Enum method set two data types for each option I have this enum type method, right now it returns one color as an int for each option but I want each option to return one color as an int and one string. Here is what I have, I would really appreciate some help so that it will also return a string value:
enum Direction {
    NORHT(Color.RED), SOUTH(Color.YELLOW);

    Direction(int c) {
        color = c;
    }

    private int color;

    public int getColor() {
        return color;
    }
}

So how could I edit this to also return a sting let say "getting colder" for north and "getting warmer" for south?
Its this line Im having tourble with, not sure where to add the string.
Thanks for the help in advance.

A: You need to simply add another parameter to the constructor of the enum and pass it along when defining each of your values for the enum.
   enum Direction {
        NORTH(Color.RED, "Getting Colder"),
        SOUTH(Color.YELLOW, "Getting Warmer");

        Direction(int c, String m) {
            color = c;
            message = m;
        }

        private int color;
        private String message;

        public int getColor() {
            return color;
        }

        public String getMessage(){
            return message;
        }
    }


text:
Q: ASP .NET MVC - Cannot nest foreach loops in view to display lists I am creating a website using ASP.NET MVC and I would like to display a list of objects that I retrieve from the database and another list for each object that was retrieved.
Here is my model:
public class JournalViewModel
{
    public JournalViewModel()
    {
        Issues = new List<Issue>();
    }

    public int Id { get; set; }

    [Required]
    public string Title { get; set; }

    [Required, DataType(DataType.MultilineText)]
    public string Description { get; set; }

    public string FileName { get; set; }

    public string ContentType { get; set; }

    public byte[] Content { get; set; }

    [Required, ValidateFile]
    public HttpPostedFileBase File { get; set; }

    public int UserId { get; set; }

    [Required, DataType(DataType.MultilineText)]
    public string IssueDescription { get; set; }

    [Required]
    public string IssueTitle { get; set; }

    [Required]
    public int IssueNumber { get; set; }

    public int IssueId { get; set; }

    public ICollection<Issue> Issues { get; set; }
}

My controller:
public ActionResult Index()
{
    var userId = (int)_membershipService.GetUser().ProviderUserKey;

    List<Journal> allJournals = _journalRepository.GetAllJournals(userId);
    var journals = Mapper.Map<List<Journal>, List<JournalViewModel>>(allJournals);
    return View(journals);
}

And my view:
@model List<Journals.Model.JournalViewModel>

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

@section Style
{

}

Publisher - List of Journals

    @Html.ActionLink("Create New", "Create")

@if (Model.Count == 0)
{

  Click @Html.ActionLink("here", "Create") to publish your first Journal.

}
else
{

                Title
                Description
                File
                Action

            @foreach (var item in Model)
            {

                        @Html.DisplayFor(modelItem => item.Title)

                        @Html.DisplayFor(modelItem => item.Description)

                        @Html.ActionLink(item.FileName, "GetFile", new { Id = item.Id }, new { target = "_blank" })

                        @Html.ActionLink("Edit", "Edit", new { id = item.Id }) |
                        @Html.ActionLink("Delete", "Delete", new { id = item.Id })

                @foreach (var issue in item.Issues)
                {

                            @Html.DisplayFor(i => issue.IssueTitle)

                }
            }

}

This view used to work fine until I added this code:
@foreach (var issue in item.Issues)
{

            @Html.DisplayFor(i => issue.IssueTitle)

}

And now it has stopped working. What I am doing wrong?
Also, is there a way to retrieve an error message from this view?

A: Remove @ before the nested foreach cycle. You have to also review your code and figure out the place where standard exception was suppressed. It can be either customErrors section configuration in web.config or Application_Error method in the Global.asax.cs file. When standard exceptions are not suppressed you can see the error page which allows you to understand what is the issue.

A: I have removed the @ before the nested foreach as @Alexey Andrushkevich suggested and my page is working now.
Note: I was not being able to get any errors, because someone else had added this "great" error handling code in Global.asax.cs:
protected void Application_Error(object sender, EventArgs e)
{
    // Get the exception object.
    Exception exc = Server.GetLastError();

    if (exc.GetType() == typeof(HttpException))
    {
        if (exc.Message.Contains("Maximum request length exceeded."))
            Response.Redirect(String.Format("~/Error/RequestLengthExceeded"));
    }

    Server.ClearError();
}

Thanks to this, no error messages from the web pages were surfacing.