How do I add two texts into one text area?

Question: I want to insert two texts into one text area using javascript.
I am getting plain text from Wikipedia but I can't seem to two or more article sections into the text area.
I use the code bellow for inserting the text for both sections into the text area.
pText = pText.substring(0, pText.length - 2); //Remove extra newline
pText = pText.replace(/\[\d+\]/g, ""); //Remove reference tags (e.x. [1], [4], etc)
document.getElementById('textarea').value = pText

http://jsfiddle.net/LUTW4/
Comment: If you want to add text at the end of the current value of the textarea, then use `.value += "new text to add"`
Answer: document.getElementById('textarea').value += pText;

To add old text of the text area and new text , just concate it using +
This is nothing but ,
document.getElementById('textarea').value = document.getElementById('textarea').value + pText;

Fiddle:http://jsfiddle.net/LUTW4/2/
Comment: Thanks that fix it! Appreciate the help.
Answer: You can append more texts by
 document.getElementById('textarea').value = pText
 document.getElementById('textarea').value += newText

or even join both by
pText = pText+newText;
document.getElementById('textarea').value = pText


App keeps running when foreground service is stopped last

Question: I came across a behaviour in Android's process management in conjunction with foreground services, that really confuses me.
What is reasonable for me

When you swipe your app from 'Recent apps', the OS should
finish the app process in the relatively near future.
When you swipe your app from 'Recent apps' while running a
foreground service, the app stays alive.
When you stop the foreground service before swiping your app from
'Recent apps' you get the same as for 1).

What confuses me
When you stop the foreground service while having no activities in foreground (app does NOT appear in 'Recent apps'), I would expect the app being killed now.
However, this is not happening, the app process is still alive.
Example
I have created a minimal example that shows this behaviour.
The ForegroundService:
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Service
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.IBinder
import androidx.core.app.NotificationCompat
import timber.log.Timber

class MyService : Service() {

    override fun onBind(intent: Intent?): IBinder? = null

    override fun onCreate() {
        super.onCreate()
        Timber.d("onCreate")
    }

    override fun onDestroy() {
        super.onDestroy()
        Timber.d("onDestroy")

        // just to make sure the service really stops
        stopForeground(true)
        stopSelf()
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        Timber.d("onStartCommand")
        startForeground(ID, serviceNotification())
        return START_NOT_STICKY
    }

    private fun serviceNotification(): Notification {
        createChannel()

        val stopServiceIntent = PendingIntent.getBroadcast(
            this,
            0,
            Intent(this, StopServiceReceiver::class.java),
            PendingIntent.FLAG_UPDATE_CURRENT
        )
        return NotificationCompat.Builder(this, CHANNEL_ID)
            .setSmallIcon(R.drawable.ic_launcher_foreground)
            .setContentTitle("This is my service")
            .setContentText("It runs as a foreground service.")
            .addAction(0, "Stop", stopServiceIntent)
            .build()
    }

    private fun createChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val notificationManager = getSystemService(NotificationManager::class.java)
            notificationManager.createNotificationChannel(
                NotificationChannel(
                    CHANNEL_ID,
                    "Test channel",
                    NotificationManager.IMPORTANCE_DEFAULT
                )
            )
        }
    }

    companion object {
        private const val ID = 532207
        private const val CHANNEL_ID = "test_channel"

        fun newIntent(context: Context) = Intent(context, MyService::class.java)
    }
}

The BroadcastReceiver to stop the service:
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent

class StopServiceReceiver : BroadcastReceiver() {

    override fun onReceive(context: Context, intent: Intent) {

        val serviceIntent = MyService.newIntent(context)

        context.stopService(serviceIntent)
    }
}

The Activity:
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        startService(MyService.newIntent(this))
    }
}

The manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.christophlutz.processlifecycletest">

    <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <service android:name=".MyService"/>
        <receiver android:name=".StopServiceReceiver" />
    </application>

</manifest>

Try it out the following ways:

Start app, stop foreground service, remove app from 'Recent apps'
Start app, remove app from 'Recent apps', stop foreground service

You can see in Android Studio's LogCat that the app process is marked [DEAD] for case 1 but not for case 2.
Since it is pretty easy to reproduce it might be an intended behaviour, but I did not find any real mention of this in the docs.
Does anybody know what is going on here?
Answer: Android system is known for its self-awareness in terms of memory, processor power and applications processes lifetime - it decides by itself whether to kill a process of not(the same with activities and services)
Here is the official documentation regarding this matter.
Look at what it says regarding foreground

There will only ever be a few such processes in the system, and these will only be killed as a last resort if memory is so low that not even these processes can continue to run. Generally, at this point, the device has reached a memory paging state, so this action is required in order to keep the user interface responsive.

and visible processes(Foreground Service is a visible process)

The number of these processes running in the system is less bounded than foreground processes, but still relatively controlled. These processes are considered extremely important and will not be killed unless doing so is required to keep all foreground processes running.

It means that the Android OS will have your app process running as long as it will have memory enough to support all foreground processes. Even if you stop it - the system may just move it to cached processes and handle it in queue-like manner. Eventually it will be killed either way - but usually it is not for you to decide. Frankly you should not care at all what is happening with your app process after(and as long as) all the Android lifecycle methods are called. Android knows better.
Of course you ca kill the process with android.os.Process.killProcess(android.os.Process.myPid()); but it is not recommended since it disrupts proper Android elements lifecycle and proper callbacks may not be called, thus your app may misbehave in some cases.
Hope it helps.
Answer: This depends on what the foreground service actually does. If it uses threads, network connections, file I/O etc.. that consumes memory actively, even if you try to stop the service, it will not be destroyed, hence the process will stay alive. This also includes within any interface callbacks that stay alive while you're trying to stop the service. Especially threads that still run (even interrupted) and bound services block the lifecycle that is stopping the service properly.
Make sure that you have no memory leaks in your service and close every connection (database, network etc...), remove all callbacks from all interfaces before stopping your service. You can make sure that the service is going to be destroyed if onDestroy() is called.
For different processes: I believe the reason that the process stays alive is that, the system sees in a way where the service may start again for some time, so it keeps the process alive for a short time. At least, that is what I have observed, because even after onDestroy() was called, the process stayed alive, I was able to see it from the debugger.
If you want to ensure (even though this way is not recommended) that the process gets killed for sure after everything is destroyed, you can always call this to terminate the process itself:
android.os.Process.killProcess(android.os.Process.myPid());

Comment: You can reproduce the behavior with the example from the question—no connections, threads, or anything else keeps running. `onDestroy` (Service) gets called, yet the process stays alive long after everything is gone. Even if the OS was keeping the process alive in case the service gets restarted, I don't see why it doesn't do the same thing when you stop the service first, then remove the app from recents. The displayed behavior seems rather unintuitive, especially given recent changes to background execution limits, so it would be nice to know how to ensure that the process gets stopped
Comment: @DavidMedenjak Try using `getApplicationContext().startService(MyService.newIntent(this));` instead of what you are using and tell me the results please. I believe the activity stays alive because the activity context is used instead of application context. Also if you're testing on Oreo or above, try using `getApplicationContext().startforegroundService(MyService.newIntent(this));`
Answer: On Android it is the operating system who decides which applications are killed.
There is an order of priority:
Applications that have a foreground service are rarely killed, instead other apps and services are killed after a period of inactivity and that is what happens with your app.
When you finish the foreground service, this increases the possibilities of the system killing your app but in no case does it mean that it will be killed immediately.
Answer:
The Recents Screen [...] is a system-level UI that lists recently accessed activities and tasks.

You could have several activities or task from a single app in the list. It's not a Recent Apps list.
Therefore there's no direct correlation between the elements of the Recents Screen and the app process.
Anyhow, if you close the last activity of your app and don't have anything else running within the process (like a foreground service), the process just gets cleaned up.
So when you stop a running foreground (by stopService() or stopSelf() and unbinding), the system will also cleanup the process it was running in.
So it's indeed an intended behavior.


Having trouble with corrupted disk images when installing 12.04.2 via flash drive

Question: I'm trying to install ubuntu 12.04.2 Desktop 64 bit on my laptop and I'm having problems with corrupted disk images. i can boot to the flash drive but it hangs during the boot and won't continue. I've also tried installing with wubi in windows but it also ends up with a corrupted image after extracting and wont install.
Info:
Machine: Asus F50SV-X1 laptop (intel core2 duo, 4 gb ddr2 800mhz ram, nvidia gt 120m vid card)
Current OS: Windows 7 Professional 64 bit
Using a 16 gb flash drive as the install drive
I've tried making the bootable drive with unetbootin as well as universal USB installer. I've verified the md5 checksum of the iso before running unetbootin/uni usb installer.
hard drive is fine. memtest came up clean. even checked the flash drive integrity and it was fine.
I'm at a loss for what else i can do.
Answer: You didn't mention on what OS you're creating the install drive.
Avoid Unetbootin, there is a known bug in that it truncates filenames of files copied onto the USB drive without any warning or error. I've had exactly the same problems you're describing because of that.
Try md5summing the install disk directly, there is a file located in the root of it called md5sum.txt.
Do this (under linux):
cd /path/to/usb/disk/ [usually /media/something]
md5sum -c md5sum.txt | grep -v "OK$"
This will list all the files that fail the checksum. Some files will be symlinks, these cannot be created on FAT32, but that's fine as all works without them.
If you're on Windows, boot from the flash drive and select "Check CD for defects" (assuming it gets that far). There isn't any alternative to the linux way of checksumming the entire flash stick at once as far as I know.
Make sure that the flash drive you're using is OK, try a different one just in case.
Format it with FAT32, not FAT16 or NTFS.
Hope this helps.
Comment: currently using windows 7 professional. got another flash drive (SD card) formatted both to fat32. noticed that uniUSBinstaller had an update. got the new version. used that to create both bootable drives (usb and SD). same problem as before. all this with an md5 checked iso of 12.04.2 desktop amd64. created a vid to better show what is happening. https://www.youtube.com/watch?v=KOWjZ7Xg3UM it'll get to that same line on both drives and just sit there. no activity light. i've let it sit for over an hour before with no change.
Comment: This seems more like a hardware compatibility issue rather than a corrupted drive image.


Joseph Rotman, "Theory of Groups," Permutation Notation

Question: In the proof of Lemma 1.4 (page 8), J. Rotman's "Introduction to the Theory of Groups," there are 2 $\mapsto$ symbols in the permutation notation.
$c_i \mapsto c_{i+1} \mapsto c_{i+1}$.
Why 2? What does the 2nd $\mapsto$ mean?
Comment: There ought to be an explanation of the notation in the book.
Comment: $a\mapsto b$ means $a$ is sent to, or mapped to, $b$ by the function in question.
Answer: He's looking at a composition of two permutations (cycles, specifically), and when he writes an expression of the form $x \mapsto y \mapsto z$, he means that the first permutation sends $x$ to $y$, and then the second permutation sends $y$ to $z$, so that the effect of the composition as a whole is $x \mapsto z$.
Answer: Thank you for the input!
In the proof of Lemma 1.4, there is a product of 2 cycles on the left and right hand sides.  This was overlooked.  Viz.,
$(a \: b)(a \: c_1 \dots c_k \: b \: d_1 \dots d_l) = (a \: c_1 \dots c_k)(b \: d_1 \dots d_l)$.
So, let $\beta = (a \: b)$, and $\alpha = $ the right-hand cycle on the LHS.  Then computing, e.g.,
$\beta \alpha(a) = \beta(\alpha(a)) = \beta(c_1) = c_1$,
$\beta \alpha(c_i) = \beta(\alpha(c_i)) = \beta(c_{i+1}) = c_{i+1}$, etc.
So, the $\beta = (a \: b)$ transposition on the left acts only on the $c_i$ or $d_j$ in $\alpha$ adjacent to $a$ or $b$.  Otherwise, it's a shift to the right for the other $c_i$ or $d_j$


2 Divs Overlap each other using JQuery Mobile in HTML5

Question: I am designing a page by using Jquery Mobile and HTML5 and i am facing the problem when i try to put 2 divs in one div for my requirements.
It works fine for Desktop Browsers but when i see result in Mobile Browser the divs overlap each other.
I am stuck with this issue from last 2 hours and need a bit hint ot solution of my problem :)
Here is link to see what i am facing :(
Here is link of desktop browser in which every thing is fine :)
Here is my HTML 5 Code.

                    Great Deal- Collect 10 nights and get 1 free at Hotels.com

                <%--
Great
--%>

                    Earn Rewards with Expedia Hotels & Flights!

                <%--<select name="subject" id="subject" data-placeholder="true" data-native-menu="false">

                    <option value="Art">Art</option>
                    <option value="Band">Band</option>
                    <option value="Choir">Choir</option>
                    <option value="Design">Design</option>
                    <option value="Drama">Drama</option>
                </select>--%>

                    myVEGAS Slots

                    Castle Clash by IGG

                    Download the free Walgreens app

                    Earn Rewards with Expedia Hotels & Flights!

                    myVEGAS Slots

                    Castle Clash by IGG

                    Download the free Walgreens app

                    Earn Rewards with Expedia Hotels & Flights!

                    myVEGAS Slots

                    Castle Clash by IGG

                    Download the free Walgreens app

            <%--
Option 3

Option 4
--%>

            © 2012 Smashing Magazine

Answer: the problem only happens when your screen is very narrow it works well on the iphone:
here.
I tried the desktop website in the minimum screen size your site works fine with is 305px screen width.
Add the following css to tweak the code for smaller screens:
@media (max-width: 305px){
    //add style here
}

or you can make a min width for the entire page because there aren't many screens with that size:
html,body{
    min-width:305px;
}


Assigned anonymous function within assigned anonymous function

Question: I do an experiment that trying to call the anonymous function within anonymous function, but it doesn't work and getting some errors :
E_NOTICE : type 8 -- Undefined variable: print -- at line 10
E_ERROR : type 1 -- Function name must be a string -- at line 10

Anyone can tell me the reason?
Here is the code:
<?php

   $print = function($key, $val){
      return 'The key: ' . $key . ', and value: ' . $val . '
';
   };

   $output = function($datas, $done_action){
      foreach($datas as $key => $val){
        echo $print($key, $val);
      }

      $done_action();
   };

   $elem1 = array('Name' => 'Aldi', 'Phone' => '087770958005', 'Address' => 'Bogor');
   $output($elem1, function(){
      echo '
Foreach function was ended!';
   });

?>

Comment: anonymous function comes from php 5.3, check your php version.
Comment: @xdazz my php version is already support
Answer: You need to supply the use keyword to use external variables inside of a closure. Your code should be:
<?php

$print = function($key, $val){
  return 'The key: ' . $key . ', and value: ' . $val . '
';
};

$output = function($datas, $done_action) use ($print) {
  foreach($datas as $key => $val){
    echo $print($key, $val);
  }

  $done_action();
};

$elem1 = array('Name' => 'Aldi', 'Phone' => '087770958005', 'Address' => 'Bogor');
$output($elem1, function(){
  echo '
Foreach function was ended!';
});

Runs without error on my php-5.3.10.


Android Threading

Question: Hey,
So im newish to android and Im lost because although my code uses AsyncTask for it's heavy lifting I am still getting a ANR error when I run my one class. So here is the relevant peices of my code:
package com.cody.color;

import android.app.Activity;
import android.os.Bundle;

public class Play extends Activity{

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    System.out.println("about to start threader");
    new GuiThreader().execute();
    System.out.println("Threader finished");
    setContentView(R.layout.colorboard_small);
}
}

package com.cody.color;

import android.os.AsyncTask;

public class GuiThreader extends AsyncTask<Void, Void, Void>{

@Override
protected Void doInBackground(Void... params) {
    // TODO Auto-generated method stub
    System.out.println("threader moving");
    GUIdriver game = new GUIdriver();
    game.play();
    return null;
}

}

Comment: Consider posting the stacktrace of exception.
Comment: Google is really powerfull in this case http://en.wikipedia.org/wiki/Stack_trace
Answer: There aren't any problems with the code above that would cause an ANR, so most likely one of the following is happening:

You are trying to modify the user interface (UI) from doInBackground
An exception is occuring in your doInBackground

If you post the LogCat output or stacktrace when you get the error then it will be easier to identify.
Comment: I am trying to edit the UI in doInBackground (changing button colors) so how should I implement that?
Comment: Override the `onPostExecute` method of `AsyncTask` to update the UI at the end of your `doInBackground` operation (`AsyncTask` will automatically call it and run it on the UI thread). If you want to update the UI while the `doInBackground` is executing, then call `publishProgress(Progress progress)` from `doInBackground`, and override the `onProgressUpdate(Progress progress)` method of AsyncTask and do your UI updates in there.
Answer: welcome to the world of JAVA programming :) When you encounter an error your best tool to solve it is usually going to be a stacktrace. You need to learn how to analyze a stacktrace and also to include it in your questions...
What is a stacktrace you ask? The simplistic answer is that a stacktrace is an error message (although it contains a lot more info than only that). In case of an exception it tells the programmer WHAT happened, WHERE it happened and WHEN it happened. If you want to program in JAVA you need to get yourself quite familiar with them. I recommend you read some JAVA tutorials before diving into Android development.
As for your code, without the stacktrace I cannot say more... there is no obvious error except the fact that game.play(); looks like it might contain some changes to the UI, which are not allowed in another thread than the main thread (that's why AsyncTask has onPostExecute());

Android Threading


Finding Elements

Question: Can anyone help. Im trying to select some elements on a form but as the elements are being dynmaically added this is starting to cause problems.
The element(s) I need to select is the second input element within each child div.
Ive been trying something along the lines of this (without much luck):
<code>$("#parentdiv :input:first-child").addClass("bad")
</code>
Thanks,
Comment: That would select only the second element in the whole set, not the second element for each parent. Showing us your DOM structure would be a good idea by the way.
Comment: If it's the second input element, pretty sure you don't want to use `first-child`. And you could just try doing `$($("#parent input")[1]).addClass("bad")`. Gets you the second input every time.
Comment: The original post would also only select the first element in the whole set (the first comment is closer to the answer). What you want to do is to set a class on all containing divs, then select the 2nd input in each div using `$(".containing-div :input:nth-child(2)").addClass("bad")`.
Answer: <code>$('#parentdiv :input:nth-child(2)').addClass("bad")
</code>
Comment: This is actually slightly wrong in that it will only select the 2nd child of `#parentdiv` and apparently (according to http://api.jquery.com/nth-child-selector/) all other children are counted whereas `:eq(1)` only counts elements matching the attached selector. One improvement would be to use a class instead of `#parentdiv`, although it could be `#parentdiv .containing-div :input:eq(1)`.

Finding Elements


Finding vehicle fuel-air equivalence ratio with OBD

Question: I'm trying to write an app that communicates with the OBD port in a car and (among other things) find the AFR, but my car doesn't seem to support the fuel-air equivalence ratio command 01 44. I see that there are two sets of PIDs for the oxygen sensors that give a fuel-air equivalence ratio. The first set is PIDs 01 24 through 01 2B, which give

Oxygen Sensor [1-8]
AB: Fuel–Air Equivalence Ratio
CD: Voltage

The second set is PIDs 01 34 through 01 3B. These look similar, but instead give the following data:

Oxygen Sensor [1-8]
AB: Fuel–Air Equivalence Ratio
CD: Current

Is the fuel-air ratio the same value on all of the sensors (at least ideally), or are they designed to measure different values? Which PID(s) should I use to calculate the AFR or FAR, and what calculations are required apart from what I see in the link (which is 2/65536 * (256A + B) for the ratio)? What are the voltage and current values, and are they of any use to me in this situation?
Any help is much appreciated.
Comment: See https://github.com/pires/obd-java-api/blob/master/src/main/java/com/github/pires/obd/commands/fuel/WidebandAirFuelRatioCommand.java .It may helps you
Comment: I'm actually using that API in my app, but it doesn't support any of these commands. I was going to write my own and experiment with the results to see what these commands do
Answer: Depending on what you are trying to achieve, the oxygen sensor may not be the right choice, regardless of reading.
Oxygen sensors are usually located in the exhaust manifolds or exhaust piping. They read data from the exhaust gasses leaving the engine. This is helpful in determining if the engine is running correctly.
However, if you are trying to determine the AFR entering the engine, which is what it sounds like, the oxygen sensors would not be very helpful. A very high or very low reading could indicate that the intake AFR is not correct, but getting an actual number would be difficult.
Answer: I am totally agree with SouthShoreAK answer which your approach is not correct for what you want. Nevertheless, If you insist on these PIDs, here are some tips about it:
All the OBD PIDs definitions are within ISO 15031 part 5 (which you have to buy it of find it somehow!). Please consider that the OBD data are mostely used (even the main reason!) for emissions-related diagnostics.
Firstly you can check mode 1 PID 00 to check the supported PIDs in your vehicle. you will get a single response from main controller and they are bitwise. You can check wikipedia to see how you can parse this PID.
below is some info about PID 0x24 - 0x2B and 0x34 - 0x3B:

PID 0x13 shall only be supported by a given vehicle if PID 0x1D is not supported. In no case shall a vehiclesupport both PIDs.
The PIDs 0x24 - 0x2B or 0x34 - 0x3B data should be parsed using PID 0x13 or 0x1D.
You cannot parsing these data without accessing ISO and parsing methods in wikipedia in this case is very lazy-defined and might not be correct.


How to resolve 'No transaction is currently active' in spring, even after using @transactional annotation?

Question: //--Service class--

@Service
public class myService implements myInterface {

    @Autowired
    private MyDao myDao;

    //some code
    myDao.updateMethod(/*some arguments*/);
    //some code
}

//--Dao class--

@Repository
public class MyDao {

    @Transactional(transactionManager = sample_a)
    public void updateMethod(/*some arguments*/){
        newUpdateMethod(/*some arguments*/);
    }
    @Transactional(transactionManager = sample_a)
    public void newUpdateMethod(/*some arguments*/){
        /* Actual call to DB taking place */
    }

}

When I call updateMethod from service class it is giving transaction related exception- InvalidDataAccessApiUsageException - No transaction is currently active, Am I using @Transactional in right way? I also read somewhere @Transactional should not be used in class with @Repository annotation, but I have other methods with @Transactional in Dao class and they are working fine.
Comment: https://stackoverflow.com/questions/1079114/where-does-the-transactional-annotation-belong
Comment: When asking about an exception, you need to post the actual code causing it, and its complete and exact stack trace. Debugging partial pseudo-code is impossible.
Comment: @JBNizet The code and stack trace is complicated for me and big to put here. Can you give your views about the flow of the code?
Answer: The above code is working fine, the problem was in transactional manager. I was using a different transactional manager. The table that I was using to update data was in different database.


marmalade SDK and integration new libraries in that

Question: I am new to the marmalade SDK.
I have custom Library of an iOS feature and i want to integrate that library with the marmalade SDK is there any way to add custom Libraries in the default marmalade SDK ?
I should convert my objective C code to the marmalade SDK's compatible language or it can be generate automatically as per working of marmalade juice ?
Answer: To integrate marmalade follow marmalade tutorial. and yes you will have to convert code.


How to defeat a Fatui Skirmisher - Cryogunner Legionnaire?

Question: My main team is Keqing, Beidou, Chongyun and Barbara, so mostly Electro.
When I am doing a quest and the dialog leads me to fighting the Fatui, often one of these chaps is in the group.

It's my understanding the best way to break the cryo shield is to cause a reaction with it, however, Hydro and Electro do cause reactions but don't seem to take the shield away.
This means I have to just tank the enemy with food and attack it with physical damage until it dies. I am in combat so I'm unable to swap my team members.
Do these enemies really require having a Pyro hero in your team? Or is the only real option I have to waypoint away, change my team and return to the area?
Comment: I got no pyro in my party as well and, after killing the water ones, simply kill them with brute physical force while being shielded. The shield blocks only most damage, not all like a hilicurl shield. For more information see https://genshin-impact.fandom.com/wiki/Fatui_Skirmishers
Comment: I have reworked the final part of the answer since there was some confusion on how reactions actually work and why some reactions work better than others.
Answer: Sadly, the fastest reaction to destroy the Cryogunner shield is indeed Pyro. So, if you don't have Pyro at hand, either you find a way to be creative or you have to resort to slowly abuse reactions that will do thick damage past the shield.
One option that comes to mind is to use some external source of Pyro damage. If for example you can have another enemy ignite some grass, then swirl could do wonders - but it does require some other enemy that uses Pyro. Another option is to use attacks that can partially bypass shields (Xiao Bane of All Evil comes to mind, Jean Gale Blaze can also slowly work), but those are also not always available. Other than that... there aren't many other options right now.
Some players currently believe that the missing Dendro element will be tied to poison/damage over time and that could mean it will bypass shields somehow (and considering the new mechanics that bypass player shields in Abyss that could make sense) but until then, your best option is sadly to bail out and return with a Pyro character if you can.

Further clarification.
To really understand how shields work, you can refer to the wiki here.
Over-simplified version follows.
There are three types of shields:

"Armor" type shield: gives increased defense but does not nullify damage. Example: Lawachurls
"Force" type shield: gives full damage immunity until broken. Example: Abyss Mage.
"Directional" shield: those are the actual shields some mobs hold, they only defend from a specific direction.
The third type can be safely ignored for this argument

A shield can be reduced either by damage or elemental reactions. Both scale with a factor that is dependent on the shield element and mob type.
Fatui Skirmisher shields are considered "Armor" shields (with some further differences for the Anemoboxer)  - this is why you can cause damage to their hp even when the shield is on. In most cases Armor shields have a damage ratio of 0, meaning that raw damage does not decrease the shield gauge.
For this reason damage won't reduce a Cryogunner shield gauge, leaving reactions as the only way to counter the shield.
With that said, let's look at the standard elemental damage coefficient table.

Again, skipping the actual formula, this should easily show that to destroy a Pyro shield Hydro is the best option, followed by Electro (again, ignoring other factors like application speed and so on).
Problem is that while basically every enemy shield uses this table, there are exceptions. And Skirmisher are one of those.

And here is the issue I mentioned. Skirmisher reaction coefficient is 2 for a specific element and "almost zero" for every other option. So, while for regular shields the max difference is a 4:1 ratio (Pyro VS Anemo on a Cryo shield)... for the Fatui the ratio can be as bad as 40:1 (Pyro vs anything else on the same Cryo shield) - ten times as bad. This basically means that with the sole exception of a single, working element, most reaction are basically "useless" at removing the shield.
Answer: I hate fighting these guys in Inuzama because it'll be raining half the time which applies wet effect to my entire team and causes them to be permanently frozen by this guy...
Anyway, the first thing you wanna do when engaging the Fatui is to defeat the hydrogunner first because he can heal the others.
Then next for the cryogunner, obviously pyro is the most effective against his shields but if you don't have a good pyro you can also try geo. If you have a geo traveler or zhongli, you can generate a constant shield and just keep hitting him until he eventually dies.
If you insist on keeping your current team line up, then Beidou will be your best bet (I also use Beidou in my team as a sub-dps tank, so I would know haha). When he starts his frost attack, run away first and count to about 3 seconds, then approach him and activate Beidou's elemental skill. Try to time it so you get a max damage perfect parry. Then feel free to rough him up a little, but start running again when he readies his gun. Beidou's perfect parries deal so much damage that you should be able to kill him with a few cycles of the above steps. Most likely, he'll die before his shield goes down haha.
Good luck!
Answer: Despite the things SPArcheon have said. Keep in mind that Fatui Skirmisher's shield is different than other shield. Their shield can only be destroy by applying special element or deal a huge amount of damage(don't have a specific number), which is more than the HP of the Fatui. Pyro shield can be destroy by applying Hydro, Cryo by Pyro, Electro by Cryo, Hydro by Electro.
Other shield can be destroy by applying any of the reactions. You could think of that, the shield is a compose of elements. You could deal damage and break the shield, or you could apply reactions, because reactions will consume elements.
By the way, someone have tested, if you could freeze the one with Cryo shield(which normally can't be freeze by apply Hydro), and use claymore or Charge attack to cause Shatter, it will be even faster than using Pyro(If you could keep the rate of frozen) , because Shatter will consume the Cryo element in the shield(It doesn't work on Cryogunner, as I have said in earlier section.)


Enabling SSH remotely on Ubuntu 18.04

Question: Suppose I have a server that has Ubuntu 18.04 installed. If I want to enable ssh on it, do I have to physically be in the server room to do it? Or can I do it remotely? I have a Windows laptop and just downloaded PuTTY. For the host name would I put the ip address of the nameserver? So if it is:
                               nameserver 22.214.171.124

is that the ip address I would enter into PuTTY?
Edit   Actually would it be the ip from sudo lshw -C network?
Comment: What are you asking?  How are you currently interacting with your server?
Comment: @NmathL I physically go into the server room and access it there. I want to access it remotely.
Comment: A proper install of Ubuntu Server or Ubuntu Core already has an ssh server installed (enabled). An install of Ubuntu Desktop does not. A frankensystem built up from a minimal image or Ubuntu Base also does not. There are many excellent tutorials on how to use ssh already -- have you looked at any of those?
Comment: @user535733: Basically I want to use Putty on my windows laptop to access the server. That should be possible right/
Comment: Name server is the server the resolves names, also called DNS, it's not the IP of your server. Type ifconfig on your Ubuntu to get its IP address. Then put that in Putty to connect to it.
Comment: Suppose you want to call my home. My home does not have a phone. Can you install a phone in my home without coming to my home?
Answer: SSH has a server part and client part. Your Ubuntu server should be having SSH server installed already and configured for you to be able to connect remotely using Putty (SSH client here).
To install SSH server, if it is not already installed, you have to be at the physical location of the server to login and install the needed packages.
I don't wish to enlist other tougher ways to get into the machine without SSH as it will be out of scope of the question asked.

Enabling SSH remotely on Ubuntu 18.04


Unable to "rm" a file named "() - ." due to "No such file or directory"

Question: A script I wrote named a file "() - ." according to Filezilla.  Filezilla was unable to delete it from the server so I tried to "rm "() - ." from inside the containing folder and received "rm: cannot remove `() - .': No such file or directory".  I then used "ls" which shows...
 () -  .                                               03_The_Kill_30_Seconds_to_Mars.mp3                 Crooked X (Crooked X) - 08 Nightmare.mp3
01 Attack - 30 Seconds to Mars.mp3                     03 Wave of Mutilation - Pixies.mp3                 Danzig (Danzig) - 01 Twist Of Cain.mp3

It lists the file in question though here it looks like it might contain a leading space and mabey two spaces between the "-" and the ".".  So I tried to "rm" many combinations of spaces mixed between the other characters with no success.
I also tried renaming it but with the same error.
My fallback is to replace it with a 0KB file of the same name but, I'd rather delete it, (read- I'm OCD and it's irritating me that it shows up in "ls")
Thanks for any help.
Running: Ubuntu 12.04 LTS Server Edition
Comment: if you can type rm and then the first symbol of the name then hit tab bash and zsh will fill it in.  `rm \ \(\)\ -\ \ .` this was my test
Answer: Since the filename contains spaces, you need to include the filename in quotation marks.
One problem why you cannot delete the file is because you might not have permissions to do it.
So try sudo rm " () -  .".
This should do the trick.  Also look out for a trailing space after '.'
Comment: Thanks for the reply, still had the same error though.
Answer: From the terminal... First, let's test before trying. Create a similar file with this command:
touch \(\)

Then to remove that file:
rm \(\)

The \ symbol is used for special characters.
In your case, as long as the file is the only file that starts with (), you should use this command
rm -i \(\)*

The -i makes it interactive (asks your permission).
Comment: I made `\(\)` and "rm"ed it then tried `rm -i \(\)*` with no luck then changed it to `rm -i \ \(\)*` suspecting the beginning space and it "rm"ed it. Thanks!
Comment: As an update to my issue, I have also found that some ftp clients do remove files named like `() -  . ` even though filezilla couldn't delete it, Notepad++ nppftp plugin was able to.  I found that interesting.  Thanks again for all the help.
Comment: you're lucky it ended up being a space. Next time, in case it is some unprintable char, you could still use wildcards `rm *\(*`
Answer: What I usually do in cases like that is to use tab-completion to make sure everything gets escaped properly.   The steps would be:

open a terminal and navigate to the folder with the bad filename in it
type "rm \ "  (a backslash followed by one space)
hit tab
that should expand the filename with the necessary escapes

This is assuming that's the only filename you have that starts with a space - if there's more than one, you might need to manually type and escape the first couple of characters so it can distinguish which one you mean.
Answer: An alternate solution (even though properly using rm may be preferable) is to use midnight commander, e.g.
$ sudo apt-get install mc
$ mc

Then,

move to the directory containing the file (use up/down arrows to select directories and enter to cd to them),
select the file you want to delete (CTRL-T)
delete the file (F8)


My character controller is automatically applying gravity in unity?

Question: I am working in Unity using C# and I have encountered a problem with my code. The Character Controller that I attached to my player is automatically dragging the player down. I am aware that the CC is causing this behaviour as without the CC enabled or present, my player remains fixed in space. Unfortunately, having read the Unity documentation on the CC, I'm unable to find anywhere that describes this functionality or how to turn it off.
I would prefer to not have to remove the CC altogether, as it is useful for many first person mechanics, but I'm pretty stumped and can't work out where I am going wrong. I need the gravity to be under my control due to problems that it's causing with my jump mechanics. Thank you in advance for any ideas, please see the video bellow for a demonstration of the problem.
public CharacterController controller;
public float walkSpeed = 3f;
public float runSpeed = 6f;
public float gravity = -9.81f;
public float jumpHeight = 4f;

void Start()
{
}

void Update()
{

    if ((Input.GetButtonDown("Jump")))
    {
        Vector3 antigravity = new Vector3(0, Mathf.Sqrt(jumpHeight * -2f * gravity), 0);
        controller.Move(antigravity);
    }

    if ((Input.GetAxis("Horizontal") != 0) || (Input.GetAxis("Vertical") != 0))
    {
        float xInput = Input.GetAxis("Horizontal");
        float zInput = Input.GetAxis("Vertical");
        float running = Input.GetAxis("Fire3");

        Vector3 move = transform.right * xInput + transform.forward * zInput;

        if (running > 0)
        {
            controller.Move((move * runSpeed * Time.deltaTime));
        }
        else
        {
            controller.Move(move * walkSpeed * Time.deltaTime);
        }
    }
}

I have not interacted with the CC in any other way except through the code above.
https://youtu.be/8gprUJLzvHk
Answer: I just discovered the same issue, "normally" the character controller does not apply gravity.... all the information and tutorials will tell you to roll your own which I have.
But if you apply root motion and bake the Y into the animation it does apply Physics.Gravity... I can only guess that it is applying SimpleMove() instead of Move() on the CharacterController internally if root motion is applied but Y is baked.
Only solutions I can see are:

Set gravity to Zero in the project settings (not very flexible).

Don't bake the Y into your animations with root motion.
Comment: I genuinely just figured I was going mad... :') I'm glad this wasn't all in my imagination.
Answer: Okay, so I took a different approach and changed my code, the following code is now functional although I have no idea what was causing the original issue still.
public CharacterController controller;
private float speed;
public float walkSpeed = 5f;
public float runSpeed = 10f;
public float turnSpeed = 90f;
public float jumpSpeed = 8f;
public float gravity = 9.8f;
private float vSpeed = 0f;

void  Update()
{
    if (Input.GetButton("Fire3"))
    {
        transform.Rotate(0, Input.GetAxis("Horizontal") * turnSpeed * Time.deltaTime, 0);
        Vector3 vel = transform.forward * Input.GetAxis("Vertical") * runSpeed;
        if (controller.isGrounded)
        {
            vSpeed = 0;
            if (Input.GetButtonDown("Jump"))
            {
                vSpeed = jumpSpeed;
            }
        }
        vSpeed -= gravity * Time.deltaTime;
        vel.y = vSpeed;
        controller.Move(vel * Time.deltaTime);
    }
    else
    {
        speed = walkSpeed;
        transform.Rotate(0, Input.GetAxis("Horizontal") * turnSpeed * Time.deltaTime, 0);
        Vector3 vel = transform.forward * Input.GetAxis("Vertical") * walkSpeed;
        if (controller.isGrounded)
        {
            vSpeed = 0;
            if (Input.GetButtonDown("Jump"))
            {
                vSpeed = jumpSpeed;
            }
        }
        vSpeed -= gravity * Time.deltaTime;
        vel.y = vSpeed;
        controller.Move(vel * Time.deltaTime);
    }

Answer: This happens because the character controller has a gravity so when you enable it, it uses gravity to the player and drag your player down. To fix this, you will need to write in the script that the player's position is upwards.
public float walkSpeed = 3f;
public float runSpeed = 6f;
public float gravity = -9.81f;
public float jumpHeight = 4f;

if ((Input.GetButtonDown("Jump")))
{
    Vector3 antigravity = new Vector3(0, Mathf.Sqrt(jumpHeight * -2f * gravity), 0);
    controller.Move(antigravity);
}

if ((Input.GetAxis("Horizontal") != 0) || (Input.GetAxis("Vertical") != 0))
{
    float xInput = Input.GetAxis("Horizontal");
    float zInput = Input.GetAxis("Vertical");
    float running = Input.GetAxis("Fire3");

    Vector3 move = transform.right * xInput + transform.forward * zInput;

    if (running > 0)
    {
        controller.Move((move * runSpeed * Time.deltaTime));
    }
    else
    {
        controller.Move(move * walkSpeed * Time.deltaTime);
    }

    void Update()
    {
        transform.position = new Vector3(0, 15, 0); //Set your player position
    }

} // If this doesn't help, tell me what's the problem.

Comment: This has not worked unfortunately, also, I should have clarified that the code I posted previously is already within the Update() method. transform.position has no effect on my player controller, neither does disabling gravity in the CC's attached rigid body.


What is the quickest way to get a trapezohedron?

Question: They're 2M when bought - is there a faster way to gain/earn/find a trapezohedron other than grinding for the gil necessary to buy it?
Answer: If you are patient, and don't mind getting really bored... Setup Vanille as your party leader, preferably with the Improved Debuffing weapon, and a whole lot of haste.  Pick a fight with the big adamantoise right outside the Eden Palace, immediately summon your Eidelon to take out the legs, then send the eidelon home and spam the Death spell.  I usually setup the other two party members as synergists to quickly pickup haste and faith.
Interestingly enough - I killed this guy before I ever walked into the Eden Palace, and he never crashed through the glass, it let me loot both treasure spheres located right there!
Some more tips for this technique can be found online.
Comment: Spamming death on those things made a good 2 or 3 days for me and my gf in the plains...took for-ev-er.
Comment: By the time you get higher in levels, you can just beast them down faster than you would death them.
Answer: You can always grind Tortoises and hope for many 60k item drops. Either way I guess it will take some time.
Kr


Prove: $T:V \to V$ is bijective if and only if $T$ is injective.

Question: I know that if $T$ is bijective then $T$ is injective.
But how to prove when $T$ is injective, then $T$ is bijective?
I know that that $R(T)$ is a subspace of $V$, and for each vector in $R(T)$, let's say $u$ , there is a $v$ in $V$ that $T(v)=u$. But, what's next? I don't know how to prove $R(T) =V$.
Am I on the right track? Thanks
Comment: are you assuming V is finite dimensional?
Comment: I double checked the question, yes, V is a finite dimensional  vector space
Comment: It holds only when the space is finite dimensional. Then its also equivalent to surjectivity.
Comment: This follows immediately from the dimension theorem of linear maps, i.e. $\dim(V)=\dim(\ker(T))+\dim(\text{im}(T))$ and  the fact that $T$ is injective if and only if $\dim(\ker(T))=0$. Use this theorem wisely, it's a powerful tool!
Answer: This is true if you assume $V$ is a finite $n \in \mathbb{Z}_+$ dimensional vector space i.e. $V$ has a basis set of $n$ vectors $B = \{b_1, \ldots, b_n\}$. You also need that $T : V \to V$ is linear. Otherwise, the statement is just false: take $V = \mathbb{R}$ and $T(x) = e^x$. This is an injection that is not a surjection.
Now if $T : V \to V$ is linear, consider the set $T_B = \{T(b_n), \ldots, T(b_n)\}$. $T$ is injective and $B$ and $T_B$ are finite sets; so $T_B$ has exactly $n$ vectors also. Next, using linearity, you can show that $T_B$ is linearly independent because $B$ is. So, $T_B$ forms a basis for $V$ and any $v \in V$ can be written as
$$
v = \alpha_1 T(b_1) + \cdots + \alpha_n T(b_n) = T(\alpha_1 b_1 + \cdots + \alpha_n b_n)
$$ demonstrating the surjectivity of $T$.
P.S. This fact is not necessarily true for infinite dimensional vector spaces. The set of all infinite real sequences $\mathbb{R}^\mathbb{N}$ is a real vector space and the shift map $\sigma : \mathbb{R}^\mathbb{N} \to \mathbb{R}^\mathbb{N}$ given by
$$
\sigma : \langle x_0, x_1, x_2, x_3, \ldots \rangle \mapsto \langle 0, x_0, x_1, x_2, \ldots \rangle
$$ is injective and linear. But it is not surjective: it misses sequences with non-zero first elements.
Comment: I am actually not sure if T is linear or not.my question handout isn't giving any extra information other than above. Is it possible to prove it while T is not specified as a linear transformation?
Comment: You need linearity because otherwise, the statement is false. Consider $V = \mathbb{R}$ and $T(x) = e^x$ for example. It is injective but is not bijective because it misses every non-positive number.
Comment: Yeah, I think you are right, We have to assume T is linear to prove it. But how to prove T(B) is linearly independent? which property you are using?
Comment: @DesiredOB linearity of the map $T$ is used. If you have $\alpha_1 T(b_1) + \cdots \alpha_n T(b_n) = 0$, then by linearity $T(\alpha_1 b_1 + \cdots + \alpha_n b_n) = 0$. But $T(0) = 0$ also. So by injectivity what must be true?
Comment: So $α_1b_1+⋯+α_nb_n$ =0, and 0 is in V, so 0*B = 0, and by injectivity $α_1=...a_n=0$ is the only solution for $α_1T(b_1)+⋯+α_nt(b_n)=0$, which means linearly independence?
Comment: Not quite, injectivity of $T$ is used to get $\alpha_1 b_1 + \cdots + \alpha_n b_n = 0$ first because $0$ is the only value mapped to $0$ by $T$. Then because $b_1, \ldots, b_n$ are linearly independent, you get the $\alpha_i = 0$. By the way, if you like my answer, consider upvoting it or accepting it on the top left corner of the answer.
Comment: Ah. Got it now. Thanks
Answer: If a linear transformation $T$ is injective, then $\ker(T)=\{0\}$. Applying the rank-nullity theorem, the rank of $T$ is exactly $\dim(V)$. The only full-dimensional subspace of a vector space $V$ is $V$ itself, thus $T$ is surjective as well.
Answer: $R(T)\subseteq V$ is a subspace of $V$ that means
$\dim R(T) \leq \dim V$
Assume $T$ is not bijective we want to show  $\dim R(T) < \dim V$
$T$ is not bijective so there are $v_1 \neq v_2$ in $V$ and $T(v_1)= T(v_2)$
$\Rightarrow T(v_1-v_2)=0\Rightarrow \ker T\neq \{0\}\Rightarrow \dim (\ker T)\geq 0$
Now because $\dim(\ker T)+\dim(Im(T)) = \dim(V)$
It follows that $\dim (Im(T))< \dim(V)$
Which means $R(T)=Im(T)\neq V$
Contradiction to the fact $T$ is injective


Selecting mysql database cells in c#

Question: What im trying to do is select a cell where my username is and compare the password to the text this is done in unity c# but im using Mysql Reference it should be like any type of c#. Now im trying to do something similar in vb when you read the value in the reader it will look like this in vb
rdr(0) but i can't seem to do this in c# here is my code. For anyone worried about where the password goes I planned on adding encryption later.
void Login_Data(string un, string pw) {
        con = new MySqlConnection(connectionString);
        con.Open();
        Debug.Log("Mysql state: " + con.State);

        string sql = "SELECT * FROM `users` WHERE '" + un + "'";
        cmd = new MySqlCommand(sql, con);
        rdr = cmd.ExecuteReader();

        while (rdr.Read()) {
                if (rdr[3] == pw) // this is the problem it keeps warning
//me i like my stuff clean but i dont risk errors if (rdr[3] == pw) also
//it did give me an error but not here.

                {
                    username = un;
                    MessageBox.Show(username + ", Has Logged in!", "API");
                    usertext.text = "User: " + username;
                    m_uid.text = "UserID: " + rdr.GetString("uid");
                }
        }
}

Warning CS0252  Possible unintended reference comparison; to get a value comparison, cast the left hand side to type 'string'
I don't understand this warning or why its occurring
Comment: Its warning you with....what warning? Also, this is a terrible way to validate user login...(1) your database shouldn't store a plaintext password and (2) is should not ***send that password to the requestor!***
Comment: sharing is caring.. but seriously, it always helps to provide all the info
Comment: just note im not the best at c# im far from it.
Comment: i just started on this script im still figuring out how to use mysql.
Comment: i added the warning happy?
Comment: i know i just forgot to add some info when i created the post.
Comment: What is the value of the variable _un_ This code should fail with a syntax error. Are you posting your exact code?  _WHERE '" + un + "'_
Comment: https://coding.abel.nu/2014/09/net-and-equals/
Comment: draco18s i'll try that
Comment: the other code is just a button listener for when the submit button is click it sends the values so say un = "big bob" think of it like that.
Comment: Please get a book or read a tutorial on ADO.NET, this stuff is simply too complicated to try to guess your way through it.
Comment: I don't guess my way through it if i did that i would never get anywhere. im primarily a vb developer but c# is simple. im not doing .NET in this this is UnityEngine C# and has little reference support for older .NET frameworks.
Answer: Here's a one line fix :
.... if (rdr[3].ToString() == pw).....

The reason you are getting the error is because you are comparing a data-cell to a data-type...
But let's learn a little more, shall we?
Firstly, your SQL statement makes no sense. Let's take a look at it:
"SELECT * FROM `users` WHERE '" + un + "'"

So, you are using the Where clause. Let's speak of general grammar. When we use any word related to WH, aren't we supposed to give information about something? Like, you cannot just say :

Brian went to New Jersey Where...

Instead, you could say :

Brian went to New Jersey Where he left his browser cookies.

Same rule applies to SQL statements. When you use the Where clause, you are actually checking if some value matches with given value....
Here's what a proper usage of a Where statement looks like :
Select * From Table Where Column1 = 'Some Value'

Moving on...
You are using a IDataReader here which is pretty much unnecessary. Why not just compare all the values within the SQL statement itself ? Just use an AND to do multiple comparisons...
And as you mentioned you are storing Usernames and Passwords in the database. The best practice is to store the Username and the hash of the password. For that, you have tons of options to choose from such as Argon2, bcrypt, scrypt, or PBKDF2.
Last but not the least, the biggest problem with your code is the following line :
MessageBox.Show(username + ", Has Logged in!", "API");

After struggling for years, developers came with patters such as MVVM for scalability, performance and what not. Then why are you living in the 17th century? Always remember :

You will spend 20% time writing the codes & 80% time in maintaining it.

So, don't write such UI related codes in the UI thread itself. If you are familiar with the MVVM pattern, you already know what i'm talking about...
Anyways, hope your learned something... And if i was wrong somewhere, feel free to correct it. Kapeesh ?
Comment: i just implemented an encryption system its secure to the max.
Comment: @Kilo Don't just hash, [salt and hash](https://crackstation.net/hashing-security.htm#salt).
Comment: @Kilo Good cryptography isn't enough. If two people have the same password, it doesn't matter what crypto system you use: they're going to have the same hash. That's why you need the salt.
Comment: @Draco18s, agreed :)
Comment: @draco18s Don`t worry its a custom script with good cryptography but if base64 is something i need to worry about then be open about it and ill look for something better.
Comment: @Kilo, one quick suggestion : You should add special characters such as `$@~` with each string(password) passed before hashing+salting them for a stronger encryption.
Comment: "The reason you are getting the error is because you are comparing a data-cell to a data-type" Not quite right; reader(x) returns and object and you can't compare an object to a string. DataReaders don't have cells. The best way is `reader.GetString(x)` see https://learn.microsoft.com/en-us/dotnet/framework/data/adonet/retrieving-data-using-a-datareader
Comment: I broke this system down and put this project to rest a while ago, I'm feeling the ich to revive it. I want to put the knowledge that I've learned recently into it. I also want to know more about not coding on the UI thread so much, but I just get dead ends.
Comment: thanks man i also found another fix as well draco18s commented on how strings work in c# my vb knowledge got in the way! thanks for the answer yours was similar to mine! mine is just a bit straight forward and less talking.
Comment: If the answer helped, you can mark it as the answer for future reference... Happy coding buddy
Answer: I now know that strings like this pw.Equals(rdr[3]) can't be contained like this if (rdr[3] == pw)
void Login_Data(string un, string pw) {
    try {

        con = new MySqlConnection(connectionString);
        con.Open();
        Debug.Log("Mysql state: " + con.State);

        string sql = "SELECT * FROM `users` WHERE uname='" + un + "'";
        cmd = new MySqlCommand(sql, con);
        rdr = cmd.ExecuteReader();

        while (rdr.Read())
        {
                if (pw.Equals(rdr[3]))
                {
                    username = un;
                    MessageBox.Show(username + ", Has Logged in!", "API");
                    usertext.text = "User: " + username;
                    m_uid.text = "UserID: " + rdr.GetString("uid");
                }
        }
 }

it worked out thanks to draco18s and zack raiyan they gave me some new knowledge.

Selecting mysql database cells in c#


If $p$ is a prime and $a^2 ≡ 1$(mod $p$), prove that $a ≡ ± 1 $(mod $p$)

Question: If $p$ is a prime and $a^2 ≡ 1$(mod $p$), prove that $a ≡ ± 1 $(mod $p$)

We are currently studying modular arithmetic and congruence and I came across this proof on my study set that I'm really not sure how to approach. We have gone over equivalence relations in mod arithmetic, equivalence classes (complete set of residues), and have gone through several mod arithmetic examples w/o variables. Looking through my notes and book I'm still not sure how to proceed with this problem, any help is appreciated.
Comment: This is based on the prime property. If $p$ divides $ab$, then $p$ divides at least one of $a$ or $b$.
Comment: It's trivial a,d has nothing to do with modular arithmetic: in a field, a polynomial of degree $n$ has at most $n$ roots, and $\pm 1$ *are* roots of $x^2-1$.
Comment: Does this answer your question? [Square root modulo prime: does any number always have 0 or 2 square roots?](https://math.stackexchange.com/questions/4556333/square-root-modulo-prime-does-any-number-always-have-0-or-2-square-roots)
Answer: This is actually a very classical result. The only square roots of $1$ modulo a prime are $+1$ and $-1$. The proof is easy, and I'll give you the beginning. Suppose that $a^2 \equiv 1 \mod p$ where $p$ is an odd prime (for the case $p = 2$, it's trivial).
$$a^2 - 1 \equiv 0 \mod p$$
$$(a - 1)(a+1) \equiv 0 \mod p$$
Thus, $p | (a-1)$ or $p | (a+1)$, but not both because $\text{gcd}(a - 1, a + 1)$ is always at most $2$.
Take the needed cases.
$\textbf{Edit}$
And yes, as someone mentioned in the comments, you can always use the fact that an $n$-degree polynomial has at most $n$ roots in a field, assuming you're allowed to use theorems from Abstract Algebra.
Answer:
If $D$ is an integral domain, then $a^{2} =1$ has exactly two solutions: $a^{2} =1 \iff a^{2} - 1 = 0 \iff (a+1)(a-1) = 0$ and since $D$ does not have zero divisors, we have $a = \pm 1$ as the only possible solutions. In relation to your problem, $D = \mathbb{Z}_{p}$ is known to be an integral domain.
Also, the hypothesis implies that $a \in G = \mathbb{Z}_{p-1}$ - a cyclic group and so if $a^{2} = 1 = b^{2}$ and $a$ and $b$ are non-identity elements, then $G$ would have two distinct subgroups of the same order, which is not possible in a cyclic group.


(a) Prove that $f_n(x) → f(x)$ uniformly on $E$ as $n → ∞.$

Question: Let $E ⊂ R$ be a compact (i.e., closed bounded) set of real numbers. Suppose $\{f_n\}$ is a sequence of real-valued continuous functions which converges pointwise on $E$ to a function $f$ that is also continuous on $E.$ Suppose further that the sequence $\{f_n\}$ is monotonic: $f_{n+1}(x) ≤ f_n(x)$ for all $x ∈ E$ and all $n = 1,2,....$
(a) Prove that $f_n(x) → f(x)$ uniformly on $E$ as $n → ∞.$
(b) Show by example that the hypothesis of compactness is essential.
We have that each of the $f_n$ and the $f$ is uniformly continuous, which I thought may be useful, but am not exactly sure how.
Comment: This is the Dini theorem. You can find the proof in a book of real analysis =)
Answer: Example that compactness is essential:
Take $f_n(x)=\chi_{[0,n]}$.
To do the original proof, have a look at Dini's theorem. (My proof would be exactly same as given here- so I didn't bother writing it out.)
Comment: Your $f_n$ is not continuous.
Comment: @Thursday: That's not a big deal- you can "smoothen" $f_n$'s to get sequence of continuous functions- this is a standard trick.


TES IV: Oblivion + Nehrim - save game corruption

Question: Lately I've been playing Oblivion with Nehrim, the total conversion mod, and it has started to crash at various times and corrupt most of my newly created games. I'm running Steam GoTY version (which should always have the latest patch) + Nehrim with latest English patch. I'm about 100 hours into the game, and until now, Nehrim was running without any issues of such sort.
I've come up with three possible reasons for this:

CPU overclocking - proved to not be the case, as resetting clocks to stock values does nothing to help the issue. Having OC'ed my CPU a couple of days ago, the possibility had made me worried.
Save game bloating - I've been playing Nehrim while exploring every corner of the world, but with 100 hours in the game, I've covered only Middlerealm (about 1/3rd of the mod's content). The latest save is 3.8MB in size.
Damaged/corrupted game files - I had made a backup of vanilla Oblivion before installing Nehrim, and so I tried reinstalling Nehrim over the backup files. It did not help the issue.

Just to be sure, I'm running Windows' error check tool on my game partition (came up with nothing), but I'm the most worried about the second, save game bloating possibility. Is there any fix for that? Is there something else I should take in concern, or any possible fix I should try? Any help will be appreciated.
Answer: For the save game bloating (which could be the reason for the crashes), you might want to try this mod:
Clean up by kuertee

Description
Prevents saved-game file-size bloating by cleaning the game of actor
and item references that are no longer required. (e.g. inactive
references created from dropped items that were picked-up by the
player.)
Cleans long-dead actors that may have been corrupted somehow.
Details
The cleaning process used is the game's inherent behaviour of
removing items that no longer has any "links" to the game world.
Normally, dead actors and "dynamically created" items that were not
picked up by the player will be removed from the world, when the cell
they are in resets. (Dynamic items are those created at game-time as
opposed to those created in the Construction Set. Examples of these
items are: those created by PlaceAtMe, those dropped by the Player,
those dropped by dying NPCs: e.g. shields, etc.)
However, there are cases when these actors and dynamically created
items will (for some reason or another) stay in the game world
forever. And actors not cleaned up by the game properly will never
respawn, causing a "broken" game experience. Saved-game bloat is the
result of these. And saved-game bloating may be the cause of some game
crashes.

To prevent crashes, I'd recommend Streamline's Streampurge feature (memory purging on an intelligent, scheduled basis - can be configured to do a memory purge before a save, which can help with stability; more info here) and Fast Exit 2 by Scanti. You can choose to enable only Streampurge and Streamsave and not the other Streamline features in sl.ini (Streamline's configuration file).
If you are running a 64-bit OS and have 4 GB or more RAM, you might want to try the 4GB EXE Patcher on Oblivion.exe . More info on the Steam forums thread on this link here.
You could also try OSR (Oblivion Stutter Remover):

This plugin makes Oblivion not "stutter" as much, and generally feel smoother or perform better. It prevents or mitigates a number of issues related to stuttering and framerates, and can reduce the frequency of stutter related crashes.

Make sure you set MaximumFPS = 0 in 'sr_Oblivion_Stutter_Remover.ini' to avoid it putting an artificial cap in your framerate. Aside from that, try using it with the default options. If it still crashes, you might want to try to replace the default Oblivion heap (memory manager) with one of OSR's. In 'sr_Oblivion_Stutter_Remover.ini', set bReplaceHeap = 1 and change iHeapAlgorithm to 1, 2 or 5 - read 'sr_Oblivion_Stutter_Remover.txt' for more info and other OSR tweaks that you could try.
Note that Streamline, Clean-up, Fast Exit 2 and OSR requires OBSE (Oblivion Script Extender)
After installing any new mods, make sure to run BOSS (Better Oblivion Sorting Software). BOSS properly sorts the load order of the mods, avoiding crashes and mod conflicts. It also provides a large number of usage notes for many mods, including requirements, incompatibilities, updates and bug warnings.
More info on configuration and mods that can help stabilize and prevent crashes in Oblivion here: http://tescosi.com/wiki/Oblivion/Stabilization_and_Optimization
Comment: Thanks, I'll try those suggestions and report back on how it helped or not with the problem. It seems that in Nehrim most indoor areas are never reset, though.
Comment: Sorry, but those methods turn out to be of no help. All they did was turning my installation even more unstable.
Comment: Explanation: Streamline unfortunately seems to be Nehrim-incompatible and 4GB patcher doesn't work with Steam version of the game. .ini edits don't help with the save corruption issue. I appreciate your help, however, as the said tools might be of use under different circumstances.
Comment: I edited my answer to link to a discussion in the Steam forums about using the 4GB patcher on the Steam version of the game. You can also choose to enable only Streampurge and Streamsave and not the other Streamline features in sl.ini. Also, try not using Streamline, and only Clean-up. Note that Streamline, Clean-up and Fast Exit 2 requires [OBSE (Oblivion Script Extender)](http://tesnexus.com/downloads/file.php?id=37952). I'm adding another mod suggestion which you could also try:[Oblivion Stutter Remover](http://www.tesnexus.com/downloads/file.php?id=23208)(will edit my answer for more info)
Comment: @winta About the 4GB EXE patcher, upon further reading the thread about it in the Steam forums, it appears that the Steam version filename of the EXE file to patch is also `Oblivion.exe`. In that case, it should work just like in the non-Steam retail DVD version (just patch Oblivion.exe). I also added more info on OSR (Oblivion Stutter Remover) in my answer.
Comment: I set up Nehrim with my saves on another PC, and it seems that my issue is computer-specific. In the meantime, I ran Wrye Bash and it listed my savegames as "without bloat". I'm going to reinstall and clean up once again and try 4GB patcher and other suggestions. It's possible that Streamline is not compatible with Nehrim, as any mods that rely on original .esm and .esp files won't work. It crashed the .exe file upon startup when I tried it yesterday.


How to use custom Android.mk with new gradle build system

Question: I know how use custom Android.mk with old gradle:
    sourceSets.main {
        jniLibs.srcDir 'src/main/jni'
        jni.srcDirs = [] //disable automatic ndk-build call
    }

    // call regular ndk-build(.cmd) script from app directory
    task ndkBuild(type: Exec) {
        commandLine '/.../android-ndk-r10e/ndk-build', '-C', file('src/main').absolutePath
    }

    tasks.withType(JavaCompile) {
        compileTask -> compileTask.dependsOn ndkBuild
    }

It's not working with new gradle: com.android.tools.build:gradle-experimental:0.2.0 :
Error:Cause: com.android.build.gradle.managed.AndroidConfig_Impl

Answer: with the new gradle-experimental plugin, your configuration would be:
model {
    //...
    android.sources{
        main.jni {
            source {
                srcDirs = ['src/main/none']
            }
        }
        main.jniLibs {
            source {
                srcDirs = ['src/main/libs']
            }
        }
    }
    //...
}

// call regular ndk-build(.cmd) script from app directory
task ndkBuild(type: Exec) {
    commandLine '/.../android-ndk-r10e/ndk-build', '-C', file('src/main').absolutePath
}

tasks.withType(JavaCompile) {
    compileTask -> compileTask.dependsOn ndkBuild
}

Note that version 0.3.0-alpha7 of the gradle-experimental plugin is out.
Comment: I don't suppose anyone knows how to do this with gradle-experimental 0.6.0-alpha5? Trying to set the source dirs gives me an error "Attempt to read a write only view...".
Comment: Okey, and what's about `Application.mk`? For example i have flags `APP_CFLAGS += -DSTDC_HEADERS`
`APP_PLATFORM := android-23`
Comment: the snippet I put is to make the new plugin work like the former one for you, by keeping your Makefiles and calling ndk-build. If you want to migrate to a full gradle solution, it's a different question, you can look at my tutorial here: http://ph0b.com/new-android-studio-ndk-support/
Comment: can you try `srcDirs.removeAll() ; srcDirs.add()` ? I haven't tested it yet, but if it works, I'll update my answer accordingly. Thanks.
Comment: "ndLine '/.../"...Why do you have three periods there?
Comment: the ... is a placeholder you should replace with the absolute path to your ndk install
Answer: Add this to your build.gradle file. This will cause the ndk-build to run as part of project build using the specified .mk file.
android{
     externalNativeBuild {
         ndkBuild {
             path 'src/main/jni/Android.mk'
         }
     }
}

Answer: In addition to the previous response:
With Experimental Plugin version 0.7.0-alpha1 this works on Windows
model {

    // ...

    android.sources.main {
        jni {
            source {
                srcDirs = ['src/main/none']
            }
        }
        jniLibs {
            source {
                srcDirs = ['src/main/libs']
            }
        }
    }

    // ...

}

task ndkBuild(type: Exec) {
    def cmdline = "${System.env.ANDROID_NDK_HOME}/ndk-build -C \"" + file('src/main').absolutePath + "\" > ndk-build-log.txt 2>&1"
    commandLine 'cmd', '/c', cmdline
}

tasks.withType(JavaCompile) {
    compileTask -> compileTask.dependsOn ndkBuild
}


How to detect a player right-clicking with an item?

Question: I want to make a "lightning rod" in Minecraft. I'll have a stick or something that when right-clicked, it summons lightning one block in front of player.
How can I detect a player right-clicking with a specific item in hand?
Comment: [Related/possible duplicate](http://gaming.stackexchange.com/q/226476/107806)
Comment: The answer depends on what the "something" you're right clicking with is. There are easy ways to detect placing down blocks, casting fishing rods, blocking with swords, etc.. Harder to detect if you're using a blaze rod or item that doesn't already do something special with right clicked, but still possible.
Comment: I want to use a stick, but now that you say it, a sword would be great!
Comment: @CollinFitch Also, does this need to work in 1.8.8 or are you using the snapshots? (Makes a difference, but not a huge one)
Comment: /testfor isn't for events, it detects entity presence.
Comment: So do you want to make a lightning rod or detect the player?
Answer: Well..you could use a fishing rod,and test for the entity when you right click the rod.
The fishing rod bobber is an entity which gets summoned when you right click the fishing rod. The bobber's entity name is "unknown". So just /testfor @e[type=Unknown]
 Normal items can't be tested for right click because they don't do anything. The only way to do it,it's to do it with plugins
Comment: adding that to the answer can be a better choice
Comment: How exactly can s/he "use a fishing rod,and test for the entity when you right click the rod"?
Comment: Well,the fishing rod bobber is an entity which gets summoned when you right click the fishing rod. The bobber's entity name is "unknown". So just /testfor @e[type=Unknown]


Building Expression to search in child properies (collection) of object

Question: I have a search setup to return matching Record objects based on criteria. It builds an Expression Tree based on the type of criteria and queries the database to return matches. Previously, it only matched on top-level properties, but now I'm trying to search within child properties of Record and build an Expression that may be combined with others in a query. The objects look like this:
public class Record
{
    public virtual ICollection<Attribute> Attributes { get; set; }
}

public class Attribute
{
    public Guid AttributeId { get; set; }
    public string Value { get; set; }

    public virtual Record Record { get; set; }
}

One of the possible criteria is a value pair of AttributeId and Value, for which I would return all Record rows which have an Attribute matching both values. For example, if I was just writing a simple LINQ query it would look like this:
Guid searchId = Guid.NewGuid();
string searchValue = "asdf";

IQueryable<Record> records = GetSomeQueryToRecords();
IEnumerable<Record> recordsThatMatch = records
    .Where(r => r.Attribute.Any(a => a.AttributeId == searchId && a.Value == searchValue));

I need to instead build this into my Expression tree so it will work both in-memory and for EF Core queries. The Expression returned by GetExpression would end up being combined with other Expressions using AndAlso to build a large query down the line. I have tried this:
ParameterExpression record = Expression.Parameter(typeof(Record));
Expression searchExpression = GetExpression(record, searchId, searchValue);

Expression<Func<Record, bool>> lambda = Expression.Lamda<Func<Record, bool>>(searchExpression, record);
recordsThatMatch = records.Where(lambda);

private Expression GetExpression(ParameterExpression parameter, Guid searchId, string searchValue)
{
    // Get the Record.Attributes Memboer.
    MemberExpression attributes = Expression.Property(parameter, nameof(Record.Attributes));

    // Get the "record.Attributes.Any(predicate)" Method.
    MethodInfo anyMethod = typeof(Enumerable).GetMethods()
        .Where(m => m.Name == nameof(Enumerable.Any))
        .Where(m => m.GetParameters().Length == 2)
        .Single();

    // Make Method generic.
    anyMethod = anyMethod.MakeGenericMethod(typeof(Attribute));

    ParameterExpression attribute = Expression.Parameter(typeof(Attribute));

    Expression idEqualExpression = Expression.Equal(
        Expression.Property(attribute, nameof(Attribute.AttributeId)),
        Expression.Constant(searchId)
    );

    Expression valueEqualExpression = Expression.Equal(
        Expression.Property(attribute, nameof(Attribute.Value)),
        Expression.Constant(searchValue)
    );

    Expression attributeMatchExpression = Expression.AndAlso(idEqualExpression, valueEqualExpression);

    return Expression.Call(null, anyMethod, attributes, attributeMatchExpression);
}

I get an ArgumentException with Expression.Call though, because honestly I don't know how to use it for this particular instance and it has many overrides. I believe I should be passing null since I actually want a static method as .Any() is an extension method.
Answer: You have forgot to create 'LambdaExpresson'. Also Expression.Call can besimplified.
private Expression GetExpression(ParameterExpression parameter, Guid searchId, string searchValue)
{
    // Get the Record.Attributes Memboer.
    MemberExpression attributes = Expression.Property(parameter, nameof(Record.Attributes));

    ParameterExpression attribute = Expression.Parameter(typeof(Attribute));

    Expression idEqualExpression = Expression.Equal(
        Expression.Property(attribute, nameof(Attribute.AttributeId)),
        Expression.Constant(searchId)
    );

    Expression valueEqualExpression = Expression.Equal(
        Expression.Property(attribute, nameof(Attribute.Value)),
        Expression.Constant(searchValue)
    );

    Expression attributeMatchExpression = Expression.AndAlso(idEqualExpression, valueEqualExpression);

    var matchLambda = Expression.Lambda(attributeMatchExpression, attribute);

    return Expression.Call(typeof(Enumerable), nameof(Enumerable.Any), new [] {typeof(Attribute)}, attributes, matchLambda);
}


Best way to let user select something underneath another an object

Question: For an application I'm developing I've been thinking about an aspect of the UI. Imagine I have an application that lets me draw shapes. I can select drawn shapes by clicking inside of them. But there's a major problem: overlapping shapes are allowed. If one shape completely overlaps the other, a user can still see it because the shape is transparent but there is no way for her to select it. Being able to still somehow select it is required.
Apart from having a list of shapes wherein the overlapped shape can be selected, is there a mechanism that is commonly employed or considered intuitive? I've been thinking about this for a while and googling around. I can think of one option: when a shape is clicked I could display little buttons next to the shape that hide the shape or show the overlapping shape again. But I feel this is not really ideal because it might be unintuitive/undiscoverable.
Any ideas?
Thanks in advance,
Joshua
Comment: I think you should add a mockup to understand better the process.
Answer: A layers palette is the most commonly used, I would suggest, the only anomaly I've come across, bizarrely, is Balsamiq, which favours a right-click and locking of objects.
Comment: A right click that showed a menu that included a list of all possible items to be selected would work very easily.
Answer: If the user is more experienced, You can implement shortcuts for changing the order of objects. It's friendly and fast solution.
The window can also be opened by right clicking
Another commonly using option is previously mentioned layers.


Views go off screen in iPad simulator

Question: I have an iPhone app I am working on to make universal for iPhone and iPad.  I've created a second main view and xib file for the iPad version and detect the iPad and set screen size.  Here is my code for that:
<code>if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad){

    CGRect  rect = [[UIScreen mainScreen] bounds];

    [window setFrame:rect];

mainNav =  [[iPadMainNavigation alloc] initWithNibName:@"iPadMainNavigation" bundle:nil];
}
else{
    mainNav =  [[MainNavigation alloc]  initWithNibName:@"MainNavigation" bundle:nil];

}
</code>
So far I haven't changed any other views other than the main screen, however when I navigate to other views they are slightly too big and go off screen (top and to the right).  For example, I have grouped table cells that go off the screen to the right and you can't see their ends, or the tab bar on top is only about 2/3 visible.
I've checked to make sure I'm not zoomed in at all.  Can anyone give me any advice on why this might be happening?
Comment: That was it!! My navigation controller was auto-resizing its subviews. Thank you!!
Answer: You need to work with struts and springs of your view in the IB.

Views go off screen in iPad simulator


weird behaviour with addChild

Question: i am trying to add one Box to my application using the following code
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" minWidth="955" minHeight="600"
                >
    <mx:HBox height="100%" width="100%" backgroundColor="red"  borderColor="black"/>
    <mx:Script>
        <![CDATA[
            import mx.collections.ArrayCollection;
            import mx.containers.Box;
            import mx.events.FlexEvent;

            protected function button1_clickHandler():void
            {
                var box:Box = new Box();
                box.setStyle("backgroundColor","blue");
                box.height = 100;
                box.width = 100;
                //box.addChild(new Button());
                addChild(box);
                trace("children  "+numChildren);
            }

        ]]>
    </mx:Script>
    <mx:Button label="click" click="button1_clickHandler()" x="200" y="200" />
</mx:Application>

this code is work in flexBuilder.but it doesn't work while compiling in command prompt(using mxmlc command).
please suggest me on this issue, because my work is fully depending on command prompt.
thanks in advance
vengatesh s
Answer: This totally depends on the compiler you are using. If you are using the Flex 4+ compiler I would suggest you to try using addElement instead of addChild. The same code above just changes to
protected function button1_clickHandler():void
{
    var box:Box = new Box();
    box.setStyle("backgroundColor","blue");
    box.height = 100;
    box.width = 100;
    /********** ----------- CHANGE----------------------********/
    // This is the only change from your code
    addElement(box);
    /********** ----------- CHANGE----------------------********/
    trace("children  "+numChildren);
}

Comment: here i don't use the Flex4+ compiler, i just use the Flex3.3 SDK.
Comment: It seems like you are starting a new project! Is there a specific reason you are using an older Flex version?
Comment: this is sample snippet only. i have to do some modification in my older project which is so huge.So i need it.
Comment: Can you be more specific about the error the mxmlc compiler is giving you? It would be good to know the exact error. Are you saying that this application code ( the same one as above doesnt get compiled ? ) Or is it your larger application which doesnt get compiled? Can you paste the compiler error here?

weird behaviour with addChild


Switch turns between the Player and AI in Unity

Question: I've recently started using Unity for a resource management stealth game. The stealth part is turn based, similar to Hitman Go. I have a simple character controller and a simple patrolling AI over a specific path. However, these movements work in real time and I want to change that to turn based. The AI should wait for the player to finish his/her move and then move itself. The same goes for the player.
Both the player and AI should be able to move to their adjacent waypoints only when the movement of the other part is complete.
How should I go about that?
Thank you
The language that I'm writing in is UnityScript.
Answer: As a very simple solution, firstly you can create an empty gameobject. Name it as TurnController. With a simple script you can add a boolean variable on it. Lets name it as isPlayerTurn. For player movement you can check this, if it is true player can move. At the end of his/her move (maybe clicking end turn button or when it reachs the max distance to move or something else) you can set isPlayerTurn false. Ofcourse AI should check (Maybe in Update function. But can change by your design) if it is true, AI can do what it needs to do. And at the finish of its turn, it should change isPlayerTurn back to true. I know it is a very simple solution but hope it helps for begining. And I hope I didnt misunderstand your question.
Answer: Write the ai as a player instance and have it emulate player input.
(Instead you could also implement a common interface on both classes.)
Spawn a game object with a GameManager behaviour script that stores a reference to the current player (or ai). Then have the GameManager update the current player every frame by checking their input. If the (human) player gives input while it is not his turn, his input will just be ignored.
This way, the player and ai do not have to know if it is their turn.


$|x|^p/p^p\le e^{-x}+e^{x}$ for all $p$ positive and $x\in \mathbb R$

Question: I wish to prove the following inequality
$$|x|^p/p^p\le e^{-x}+e^{x}$$
for all $p$ positive and $x\in \mathbb R$.
My partial progress:
Taking the $p$-th root and $\log$, it suffices to show
$$f(x):=(1/p)\log(e^{-x}+e^{x})- \log (|x|/p)$$
is non-negative. But I have trouble in analyzing the derivative and minimal value of this function. Maybe there is some other trick to approach this? Maybe we should consider this as a two-variable problem?
Comment: Wlog take $x > 0$. Then $x/p < e^{x/p} \implies (x/p)^p < e^x$ by the positivity of $p$. Since $e^{-x}>0,$ we can add it to the upper bound.
Comment: Scince both numbers can change you should consider this a 2 variable problem.
Answer: Assume $x\ge0$ wlog. We maximize the LHS w.r.t. $p$ by log differentiating:
$$\frac{\mathrm d}{\mathrm dp}p\ln(x/p)=\ln(x/p)-1=0\Leftrightarrow p=x/e\Leftrightarrow x=pe$$
It is easy to observe this is a relative maximum, as the second derivative gives:
$$\frac{\mathrm d^2}{\mathrm dp^2}p\ln(x/p)=-\frac1p<0$$
Substituting it in, we see it suffices to check
$$(x/p)^p\le e^{-x/e}\le e^x+e^{-x}$$
which can be done by moving everything to one side and verifying the derivative is positive.
Comment: Thanks! But I guess the zero to the equation in the first line should be $x=pe$?
Comment: Ah yes my bad. Thanks for the catch.


How can I link a profile page in Ruby on Rails

Question: I'm currently building a marketplace with Ruby on Rails. Right now I'm trying to build a profile page with devise (based on this tutorial: https://www.youtube.com/watch?v=BEkpwM-GvMQ) .
For devise I've created the user model.
For the profile page I've created the users controller.
For the marketplace I've created the scaffold page(pages).
Every user has a id and the profile page is basically based on that id.
Does somebody know how I can link somebodys profile page in his navbar?
app/controllers/users_controller.rb
    class UsersController < ApplicationController

  def show
    @user = User.find(params[:id])
    @user_pages = @user.pages
  end

end

app/views/layouts/application.html.erb (basically the navbar)
    <!DOCTYPE html>

    <meta name="viewport" content="width=device-width,initial-scale=1">
    <%= csrf_meta_tags %>
    <%= csp_meta_tag %>

    <%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>
    <%= javascript_pack_tag 'application', 'data-turbolinks-track': 'reload' %>
    <%= stylesheet_pack_tag 'application', 'data-turbolinks-track': 'reload' %>

          <%= image_tag("navbar/logo.png") %>
          <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">

          </button>

            <% if !user_signed_in? %>

                <%= link_to 'Login/Register', new_user_session_path, class:"btn", style:"background-color: #00188A; color: white;" %>

            <% end %>

            <% if user_signed_in? %>

              Profile

                      <%= link_to "My Profile",  users_path , class:" dropdown-item" %>

                      <%= link_to "Edit Profile", edit_user_registration_path, class:" dropdown-item" %>

                      <%= link_to "Settings", edit_user_registration_path, class:" dropdown-item" %>

                      <%= link_to "Logout", destroy_user_session_path, method: :delete, class:" dropdown-item" %>

            <% end %>

<% if notice %>
          <%= render 'layouts/alerts' %>
<% end %>

 <%= yield %>

app/views/users/show.html.erb
    <%= @user.email %>

<% @user_pages.each do |pages| %>
    <%= link_to pages.title, page_path(pages) %>
<% end %>

app/config/routes.rb
Rails.application.routes.draw do
  devise_for :users
  resources :pages
  resources :users
  root to: 'pages#index'
  # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
end

When I clicK on the My-Profile link on the navbar (<%= link_to "My Profile",  users_path , class:" dropdown-item" %>) I land on this page:
profile page bug
Thank you for reading. It would help me allot if somebody would know how to fix this.
Comment: need to go to the page for the current user `user_path(current_user)` instead of users_path which would show all users
Answer: The users_path links to the index page which shows all the users. The reason you are seeing the error is because you only have the show action setup in the controller. To link to a specific users profile page, you would link to the show path which would be user_path(@user). You need to pass the @user in order for rails to know which user to show on the page.
The link would look something like this:
<%= link_to "My Profile", user_path(@user), class:" dropdown-item" %>


Can someone help me identify this spiral staircase system?

Question: I am thinking of buying this spiral staircase to use to get to our loft, but was curious if any of you could identify the type of staircase that it is.

What is pictured is the section that sits on the floor, supposedly after that each step is a separate bolt-on unit.  Also odd about this setup is that there is no center pole.  I cannot seem to find a photo of a similar setup all put together.  The guy that is selling this does not know that much about it.
I would go check it out in person, however it is 3 hours away!  I welcome any information you guys can offer.
Comment: Perhaps you should ask the seller what type of staircase it is?
Answer: This isn't a spiral staircase, but rather a helical staircase.  The difference is the lack of the centre pole (As you noticed.  It's otherwise known as a newel) and that it has handrails on both sides, whereas a spiral staircase only has a handrail on the outside.
I was able to find this example of what appears to be a similar design, though it looks wider than your's.


insanely large GDT blocks with mdadm partitions

Question: I have a 4 drive USB3.0 external ext4 mdadm lvm RAID-5 array connected to my Ubuntu 16.10 box (ripped from a broken Synology). Disk manager shows the array is fine and all the logical partitions are visible, however only 2 (of the 5) mount properly. The other 3 throw exit status 32 errors and dmesg says:

Number of reserved GDT blocks insanely large: 8189

A filesystem check on the partitions gives

Corruption found in superblock. (reserved_gdt_blocks = 8189)

I've attempted to restore the superblocks on the partitions from backups using the e2fsck -b command but none of them work, but I'm not sure that's the real issue, Ubuntu isn't happy with the GDT block size.
Comment: parted result:
Error: /dev/md127: unrecognised disk label
Model: Linux Software RAID array (md)
Disk /dev/md127: 8987GB
Sector size: (logical/physical): 512B/512B
Partition Table: unknown
Disk flags:
Comment: mdadm --examine --scan /dev/md127 gives no result
Comment: Could you please [edit] your post, when you want to clarify something or add information? It's best to have everything relevant in one place. Additionally, comments may be deleted for various reasons. Thanks.
Answer: It seems like a cap was put on the number of reserved GDT blocks allowed in all LTS releases of Ubuntu. This apparently has something to do the stability or reliability of accessing such drives.
I am not sure how to override this limit, or even if overriding the limit was possible. Instead, I used an older Unsupported Release of Ubuntu that did not have the GDT Block Restriction, such as Ubuntu 15.10 Wily Werewolf, to access the files on my Synology RAID drive.
The discussion from [Mount] GDT blocks insanely wide. (resolved) tipped me off as to what was happening.


Can I move a kitchen waste vent? If so what is allowed?

Question: I an adding a large opening between my kitchen and living room just above countertop level, but realized the sink vent is there.
I want to move it ~30" away. See photos. My plan would be to use two street 1/16 elbows to get the 2" ABS into the wall, then run it through the wall vertically.
Is this allowed? Anything I'm missing?
Comment: It is not clear to me that it would be a good idea to move the location of where the vent connects to the 2" horizontal drain to a location downstream of the sink. (The vent MIGHT need to be at or UPSTREAM of the sink.) Maybe it would be better to cut off the existing vent 2 ft or 2.5 ft above the floor and go laterally in the wall to outside the opening and then go vertically. (And instead of making a new penetration in the large beam, go back to the original vent routing through the beam? The top of the opening would be a little lower to accommodate the upper horizontal run of vent.)
Comment: Does anything above the sink drain into that stack?
Answer: If that vent is only venting the lav, you can use an AAV
Its approved by IPC, and many jurisdictions these days.


Porting CDate(long) from VB6 to C#

Question: I have been tasked with converting an old VB6 program to to C#. One function I have been having trouble porting over is the calculation of a birthdate from a filed that was read from a binary file:
.BirthDate = CDate((CLng(recPatient.birthDateByte2) * 256) +
                         (recPatient.birthDateByte1 + 366))

The only function I could find that is remotely similar is:
DateTime BirthDate = DateTime.ToDateTime((long)recPatient.birthDateByte2) * 256)
                                       + (recPatient.birthDateByte1 + 366));

However ToDateTime(long) just returns an InvalidCastException.
Now I can build the string manually but I can not find any documentation anywhere on VB6's CDate(long).
What am I doing wrong?
Answer: Try to use
  DateTime.FromOADate((double)recPatient.birthDateByte2 * 256
                     + recPatient.birthDateByte1 + 366)

instead.
Here is a small piece of documentation about CDate(long). It is not from MS and not about VB6, but since CDate is part of all VBA implementations I have seen so far, I suspect it won't make a big difference.
Answer: The old VB6 long data type becomes System.Int32, or simply int in C#
long in C# is System.Int64
double is System.double, which is a 64-bit floating point variable type

Porting CDate(long) from VB6 to C#


Fstab mounting fails when remote share is OFF

Question: I have an entry in fstab to mount at boot a remote share which works fine when the local box boots finds remote box ON. The issue is when the local box starts and the remote box is OFF. The workaround is to mount manualy which is a bit annoying. I am just wondering if there is a better way to acomplish this task, something like an auto mounting when the remote box status change to ONLINE.
Thanks!
Comment: There's no way you can mount a share at system startup if the machine exporting that share is not up at that time. It's like trying to access a web page while the web server is down :). You must repeat the mount when server becomes available. However. You may write a script that checks if the share is available and mounts it if yes, and put that script in crontab so that it executes every 5 minutes or so...
Answer: Not exactly what you asked for, but at least your boot won't hang when the remote is down. Otherwise you'd need to write a short script to check for remote up, and then mount share.
Edit your /etc/fstab and try adding nofail like the example I show below...
//caspurr.local/usb_storage  /media/my_username/caspurrshare  cifs  nofail,gue
st,uid=1000,iocharset=utf8  0  0

Comment: @BradThompson No sooner did I post this answer, and I corrected it. Changed from noauto to nofail. Sorry for the confusion.
Comment: Thanks heynnema, I tried that, no work... noauto - The filesystem will NOT be automatically mounted at startup, or when mount passed -a. You must explicitly mount the filesystem.
Comment: @BradThompson Status please...
Comment: sorry, what you mean 'status' ?
Comment: @BradThompson Did my answer solve your problem?
Comment: No. There are no errors but the share is not mounted (obviously). My original question was dumb. Thanks!