text:
Q: Solving a PDE containing DiracDelta I want to get the answer from a PDE:
$$\begin{align*}
\frac{\partial \rho(r,t)}{\partial t}&=Dr^{-2}\frac{\partial}{\partial r}r^2h(r)e^{-U(r)}\frac{\partial}{\partial r}e^{U(r)}\rho(r,t)-\left(\frac{\lambda}{g(\sigma)}\frac{\delta(r-\sigma)}{4\pi\sigma^2}+\frac{3\lambda}{4\pi r^6}\right)\rho(r,t)\\
U(r)&=-\frac4r\text{; }\sigma=D=\lambda=h(r)=1\\
\rho(r,t=0)&=g(r)=e^{-U(r)}\text{; }\lim_{r\to\infty}\rho(r,t)=1\text{; }\left.4\pi\sigma^2 Dh(\sigma)\frac{\partial}{\partial t}e^{U(r)}\rho(r,t)\right|_{r=\sigma}=\lambda e^{U(\sigma)}\rho(\sigma,t)
\end{align*}$$
The PDE has one DiracDelta[] function. When I tried to solve the equation with NDSolve[], it gave me
NDSolve::ndnum: Encountered non-numerical value for a derivative at t==0.

So I wanted to know the reason of message.
 Using r-sigma instead of the delta function, DiracDelta[r-sigma], I could get an answer from NDSolve without the above error message. However, it was not the answer of interest.
How can I solve the problem with DiracDelta[] function?
Thanks in advance :)
*Codes start from here :
σ = 1
rc = -4
λ = 1
sink[r_, λ_] = (3 λ)/(4 π r^6)
U[r_] = rc/r
g[r_] = Exp[-U[r]]
Dif = 1
h[r_] = 1
r0 = 1;
tmax = 0.01;
rmax = 1000 Sqrt[6 Dif tmax] + r0;

sol = NDSolve[{D[ρ[r, t], {t, 1}] ==
Dif r^-2 D[
   r^2 h[r] Exp[-U[r]] D[Exp[U[r]] ρ[r, t], {r, 1}], {r,
    1}] - (λ/g[σ] DiracDelta[r - σ]/(
     4 π σ^2) + sink[r, λ]) ρ[r,
   t], ρ[r, 0] == Exp[-(U[r] - rc/rmax)], ρ[rmax, t] ==
1, 4 π Dif h[σ] (
  D[Exp[U[r]] ρ[r, t], {r, 1}] /.
   r -> σ) == λ Exp[U[σ]] ρ[σ,
  t]}, ρ, {r, σ, rmax}, {t, 0, tmax},
  PrecisionGoal -> 4, StartingStepSize -> 0.0001,
  Method -> {"MethodOfLines",
"SpatialDiscretization" -> {"TensorProductGrid",
  "MinPoints" -> 100, "MaxPoints" -> 200}}]

ρn = First[ρ /. sol]
Plot3D[ρn[r, t], {r, σ, rmax/100}, {t, 0, tmax}, PlotRange -> All]

A: The Dirac delta makes the solution discontinuous and Mathematica cannot handle PDEs with discontinuities at the moment.
You will have to construct your own solver in Mathematica to do so. In your case, the location and magnitude of the discontinuity is known analytically, so you can construct derivative matrices that take this into account, and then use the method of lines. For example, see:
https://arxiv.org/abs/1406.4865
Let me know if you need more details.

A: First of all, I'd like to point out that, in OP's specific example the DiracDelta actually doesn't play a important role i.e. its contribution to the final solution is very weak. In the following answer I'll multiply it with 10^6 for a better illustration.
OK, let's dealing with the DiracDelta. As far as I can tell, the easiest way to handle DiracDelta inside NDSolve is to use a smooth function to approximate it. In OP's case, appro' where
appro = With[{k = 1}, Erf[k #]/2 + 1/2 &];

is already an acceptable approximation:
Plot[appro'[x - σ], {x, -σ, rmax}, PlotRange -> All, Axes -> None]

σ = 1;
rc = -4;
λ = 1;
sink[r_, λ_] = (3 λ)/(4 π r^6);
U[r_] = rc/r;
g[r_] = Exp[-U[r]];
Dif = 1;
h[r_] = 1;
r0 = 1;
tmax = 0.01;
rmax = 1000 Sqrt[6 Dif tmax] + r0;

mol[n_Integer, o_:"Pseudospectral"] := {"MethodOfLines",
  "SpatialDiscretization" -> {"TensorProductGrid", "MaxPoints" -> n,
    "MinPoints" -> n, "DifferenceOrder" -> o}}

mol[tf:False|True,sf_:Automatic]:={"MethodOfLines",
"DifferentiateBoundaryConditions"->{tf,"ScaleFactor"->sf}}

sol = With[{coef = 10^6},
   NDSolve[{D[ρ[r, t], {t, 1}] ==
       Dif r^-2 D[
          r^2 h[r] Exp[-U[r]] D[Exp[U[r]] ρ[r, t], {r, 1}], {r,
           1}] - (λ/
             g[σ] coef  DiracDelta[r - σ]/(4 π σ^2) +
           sink[r, λ]) ρ[r, t], ρ[r, 0] ==
       Exp[-(U[r] - rc/rmax)], ρ[rmax, t] == 1,
      4 π Dif h[σ] (D[Exp[U[r]] ρ[r, t], {r, 1}] /.
          r -> σ) == λ Exp[U[σ]] ρ[σ, t]} /.
     DiracDelta -> appro', ρ, {r, σ, rmax}, {t, 0, tmax},
    Method -> Union[mol[True, 100], mol[4000, 4]]]];

ρn = First[ρ /. sol];
Plot3D[ρn[r, t], {r, σ, rmax/100}, {t, 0, tmax}, PlotRange -> All]

"ScaleFactor"->100 is added because of the reason mentioned here. (Well, but in OP's case, the inconsistency seems not to be that significant, I added it just in case. )
The resulting graph is:

Again, notice I've multiply DiracDelta with 10^6 for a better illustration.

A: I admire the idea of @b.gatessucks. However, I would like to note that your problem may be has a more straightforward solution. In fact the delta function, such as yours generates a solution with a kink, and fixes a specific boundary conditions in the kink points. Then one can reveal these boundary conditions, and then solve the equation at both side of the kink, where there is no delta function. There the solution is straightforward. I will illustrate this within a much more simple example to only reveal the essence. Let us consider a simple stationary equation:

with the boundary conditions y(x)->0when x turns into the both infinities. Here a and k are constants. This equation is like your one, in the sense that it contains the term delta(x)*y(x).
Now, let us integrate this equation from -b to b, where b>0 and then pass on to the limit b->0:

It is clear that the second term in the left-hand part of the equation vanishes after integration and passing to the limit, if the function is continuous, while the first one represents Limit(y'(b)-y'(-b), b->0)=[y'(0)], where the square brackets denote a jump of a function in the point. This does not vanish, if the point x=0 is a kink point of the continuous function. The term in the right-hand part of the equation also does not vanish. One finds:
[y'(0)]=k y(0).
The latter is the additional boundary condition we were looking for. We can now solve the equation outside of the point x=0 of the kink. The solution is

where A is an arbitrary constant, the sign "-" is valid to the right and "+" - to the left of the kink. Now, our additional boundary condition yields -2a=k which fixes the only value of a at which the problem has the solution, so it is the spectral condition.
I hope this helps. Have fun!


text:
Q: Javascript extending what is returned from a function? There is this function (updated with more code):
openerp.web_calendar = function(instance) {
    var _t = instance.web._t,
        _lt = instance.web._lt,
        QWeb = instance.web.qweb;

    function get_fc_defaultOptions() {
        shortTimeformat = Date.CultureInfo.formatPatterns.shortTime;
        var dateFormat = Date.normalizeFormat(instance.web.strip_raw_chars(_t.database.parameters.date_format));
        return {
            weekNumberTitle: _t("W"),
            allDayText: _t("All day"),
            buttonText : {
                today:    _t("Today"),
                month:    _t("Month"),
                week:     _t("Week"),
                day:      _t("Day")
            },
            monthNames: Date.CultureInfo.monthNames,
            monthNamesShort: Date.CultureInfo.abbreviatedMonthNames,
            dayNames: Date.CultureInfo.dayNames,
            dayNamesShort: Date.CultureInfo.abbreviatedDayNames,
            firstDay: Date.CultureInfo.firstDayOfWeek,
            weekNumbers: true,
            axisFormat : shortTimeformat.replace(/:mm/,'(:mm)'),
            timeFormat : {
               // for agendaWeek and agendaDay
               agenda: shortTimeformat + '{ - ' + shortTimeformat + '}', // 5:00 - 6:30
                // for all other views
                '': shortTimeformat.replace(/:mm/,'(:mm)'),  // 7pm
            },
            titleFormat: {
                month: 'MMMM yyyy',
                week: dateFormat + "{ '—'"+ dateFormat,
                day: dateFormat,
            },
            columnFormat: {
                month: 'ddd',
                week: 'ddd ' + dateFormat,
                day: 'dddd ' + dateFormat,
            },
            weekMode : 'liquid',
            aspectRatio: 1.8,
            snapMinutes: 15,
        };
    }
};

I want to extend what is returned. To be exact, I need to month: 'h:mm{ - h:mm}' in timeFormat object.
In Python I could do something like this (if return would be a dictionary):
def some_class(object):
    def get_fc_defaultOptions(self):
        ret = super(some_class, self).get_fc_defaultOptions()
        ret['timeFormat']['month'] = 'h:mm{ - h:mm}'
        return ret

What is equivalent or similar in JavaScript?

A: You just assign to the properties of the object it returns:
var obj = get_fc_defaultOptions();
obj.timeFormat.month = 'h:mm{ - h:mm}';

Or if you want to have a function you can call to do that:
function some_class() {
    var obj = get_fc_defaultOptions();
    obj.timeFormat.month = 'h:mm{ - h:mm}';
    return obj;
}

Usage:
var obj = some_class();
console.log(obj.timeFormat.month); // 'h:mm{ - h:mm}'

(I wouldn't call it some_class, though.)

A: You want a new class that has get_fc_options?
Well, seeing as get_fc_defaultOptions is a basic function, you'd simply make your class
function YourClass() {
    this.get_fc_defaultOptions = function () {
        var ret = get_fc_defaultOptions(); // This calls the global function
        // Your code here
        return ret;
    }
}

var instance = new YourClass();

I hope I'm understanding your question correctly, really shouldn't be answering questions after being awake 26 hours straight.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to start a PowerShell script from where it stopped? (For scanning repos by cloning) I have written a PowerShell script to scan the repos by cloning from GitHub and it's running as expected. Now I have got a new request to add a feature.ie., when a script fails due to some reasons like ctrl+c (or) switch off the machine unexpectedly, and when we run again, it should start from where it got left before, so it shouldn't perform the clone operation which was already done in previous run and it should continue from the last run only.
Is this possible in powershell or not?


text:
Q: ImportError: DLL load failed while importing _lib_engine:couldn't find specific module
error when "import nfstream" in python3.9.15(anaconda virtual env in windows11, env variants have been add to the PATH)

logs:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\HP\.conda\envs\nfstream\lib\site-packages\nfstream\__init__.py", line 17, in <module>
    from .streamer import NFStreamer
  File "C:\Users\HP\.conda\envs\nfstream\lib\site-packages\nfstream\streamer.py", line 25, in <module>
    from .meter import meter_workflow
  File "C:\Users\HP\.conda\envs\nfstream\lib\site-packages\nfstream\meter.py", line 16, in <module>
    from .engine import create_engine, setup_capture, setup_dissector, activate_capture
  File "C:\Users\HP\.conda\envs\nfstream\lib\site-packages\nfstream\engine\__init__.py", line 16, in <module>
    from .engine import create_engine, setup_capture, setup_dissector, activate_capture
  File "C:\Users\HP\.conda\envs\nfstream\lib\site-packages\nfstream\engine\engine.py", line 16, in <module>
    from _lib_engine import ffi, lib
ImportError: DLL load failed while importing _lib_engine: couldn't find specific module

1.I have tried pip uninstall nfstream, and then pip install -U nfstream

2.And I have dowload 'msvcp71.dll', 'msvcr71.dll' to windows/system32 and windows/SysWOW64

3.also I have dowload all off c++ runtime tools and development kits

enter image description here
But the error exists as well!!! Help me please, thank you very much.


text:
Q: Looking for a word the describes a common belief is often not the case What word describes the concept of how what is generally held as to be true, is in fact false (at least most of the time). I think a fictional story illustrates an example the best:
Tinkerbell lives in Never Land. Tinkerbell got lucky and secured a job as a fairy. Everyone knows being a fairy is the best job that exists in Never Land. However, after becoming a fairy, Tinkerbell learns that most fairies find the job terrible and it is actually really unenjoyable being a fairy.
Another example (completely made up):
Most people assume Olympic Athletes are fit, but in turns out this is untrue as a great deal of the time and to compete in the Olympics is determined more by connections than athletic ability.

A: I think you're looking for the word "Apocryphal".
a·poc·ry·phal
əˈpäkrəfəl
adjective
(of a story or statement) of doubtful authenticity, although widely circulated as being true.
"an apocryphal story about a former president"
synonyms:   fictitious, made-up, untrue, fabricated, false, spurious; More

A: You could try "misconception" or "popular misconception," especially if people are simply mistaken about the facts.  "Fallacy" might be more appropriate for an incorrect theory or faulty logic.  If the mistaken notion finds expression in a name, like "risk-free bungee-jumping," you could call it a "misnomer."  If you think it results from a mistaken world-view, then I think you have no choice but to refer to it with some clumsy thing like "false paradigm" or whatnot.

A: "FACTOID" (non-American English)?
fact + -oid; coined by Norman Mailer in Marilyn (1973): "facts which have no existence before appearing in a magazine or newspaper, creations which are not so much lies as a product to manipulate emotion in the Silent Majority". An inaccurate statement or statistic believed to be true because of broad repetition, especially if cited in the media.

A: To really answer this well, it would helpful to know what perspective this is judged from.
Is it someone who does not suffer from this mistaken belief? Then, I would describe it as delusion.

Many people in society have delusional ideas about the environment.

If it is commonly believed but generally false and stated neutrally (i.e., stated like an anthropologist form the outside), then I would use myth.

many people believe the myth that it's all happily ever after once you're married.

If I want to deride it, then fairy tale might be good:

A perfect government is just a fairy tale

If it is what I once believed, then I would emphasize that in the tense:

I was deluded or I was tricked into believing that if you work hard you can succeed.

But there could be other contexts that would lead me to recommend different words.

A: You're probably looking for the word "myth".
Myth http://www.merriam-webster.com/dictionary/myth

A: I initially thought "a mistaken belief" or "mistakenly believed" could be used, but I now think for my purpose "apocryphal" is the best choice. For example: Much of the information, guidelines, and mandates by governments in the USA and around the world regarding the pandemic has been shown to have been apocryphal, and although now being abandoned by most prior advocates, without acknowledgment of harm, is still clung to by some.


text:
Q: Including AFC field in functions.php Could anyone guide me in how to add an ACF field in a function please. Everything I do returns nothing.
add_action('woocommerce_after_main_content', 'custom_seo_block', 10);

function custom_seo_block() {
    return "<?php the_field('seo_content'); ?>";
}

Thanks in advance

A: add_action('woocommerce_after_main_content', 'custom_seo_block', 10);

    function custom_seo_block() {
    $value = get_field( "seo_content", $post_id );
        return $value;
    }

Get ACF field value by post id and than return it.

A: It is still not returning the data. Sorry if this is a silly question. Obviously doing something wrong here.
add_action('woocommerce_after_main_content', 'custom_seo_block', 10);

function custom_seo_block() {
    if( function_exists('acf_add_local_field_group') ):
    acf_add_local_field_group(array(
        'key' => 'group_5c52deb4b5fe0',
        'title' => 'SEO content',
        'fields' => array(
            array(
                'key' => 'field_5c52dec5d99a4',
                'label' => 'SEO content',
                'name' => 'seo_content',
                'type' => 'wysiwyg',
                'instructions' => '',
                'required' => 0,
                'conditional_logic' => 0,
                'wrapper' => array(
                    'width' => '',
                    'class' => '',
                    'id' => '',
                ),
                'default_value' => '',
                'tabs' => 'all',
                'toolbar' => 'full',
                'media_upload' => 1,
                'delay' => 0,
            ),
        ),
        'location' => array(
            array(
                array(
                    'param' => 'taxonomy',
                    'operator' => '==',
                    'value' => 'all',
                ),
            ),
        ),
        'menu_order' => 5,
        'position' => 'normal',
        'style' => 'default',
        'label_placement' => 'top',
        'instruction_placement' => 'label',
        'hide_on_screen' => '',
        'active' => 1,
        'description' => '',
    ));

    endif;
}

A: add_action('woocommerce_after_main_content', 'custom_seo_block', 10);

function custom_seo_block() {
global $post;
the_field('seo_content',$post->ID);
}


text:
Q: esp 8266 issue "Leaving... Hard resetting via RTS pin..." I'm new in arduino and esp8266
i trued to upload a simple blink example of esp
/*
  ESP8266 Blink by Simon Peter
  Blink the blue LED on the ESP-01 module
  This example code is in the public domain

  The blue LED on the ESP-01 module is connected to GPIO1
  (which is also the TXD pin; so we cannot use Serial.print() at the same time)

  Note that this sketch uses LED_BUILTIN to find the pin with the internal LED
*/

void setup() {
  pinMode(LED_BUILTIN, OUTPUT);     // Initialize the LED_BUILTIN pin as an output
}

// the loop function runs over and over again forever
void loop() {
  digitalWrite(LED_BUILTIN, LOW);   // Turn the LED on (Note that LOW is the voltage level
  // but actually the LED is on; this is because
  // it is active low on the ESP-01)
  delay(1000);                      // Wait for a second
  digitalWrite(LED_BUILTIN, HIGH);  // Turn the LED off by making the voltage HIGH
  delay(2000);                      // Wait for two seconds (to demonstrate the active low LED)
}

it's start well and the led start blinking and after a second it's stop  and i get
Error downloading http://arduino.esp8266.com/versions/2.4.1/package_esp8266com_index.json
Sketch uses 257696 bytes (24%) of program storage space. Maximum is 1044464 bytes.
Global variables use 26572 bytes (32%) of dynamic memory, leaving 55348 bytes for local variables. Maximum is 81920 bytes.
esptool.py v2.6
2.6
esptool.py v2.6
Serial port COM4
Connecting....
Chip is ESP8266EX
Features: WiFi
MAC: 84:0d:8e:a4:77:12
Uploading stub...
Running stub...
Stub running...
Configuring flash size...
Auto-detected Flash size: 4MB
Compressed 261856 bytes to 191268...

Writing at 0x00000000... (8 %)
Writing at 0x00004000... (16 %)
Writing at 0x00008000... (25 %)
Writing at 0x0000c000... (33 %)
Writing at 0x00010000... (41 %)
Writing at 0x00014000... (50 %)
Writing at 0x00018000... (58 %)
Writing at 0x0001c000... (66 %)
Writing at 0x00020000... (75 %)
Writing at 0x00024000... (83 %)
Writing at 0x00028000... (91 %)
Writing at 0x0002c000... (100 %)
Wrote 261856 bytes (191268 compressed) at 0x00000000 in 17.0 seconds (effective 123.2 kbit/s)...
Hash of data verified.

Leaving...
Hard resetting via RTS pin...

how i can make it run for ever until i stop the ide
note : after i run it again this line
Error downloading http://arduino.esp8266.com/versions/2.4.1/package_esp8266com_index.json

 disappear

A: The "hard resetting" message is fine and usually indicates that the upload was successful. If the serial output appears blank or garbled or stuck afterwards, then it's probably either a problem with the code or the serial monitor.
Make sure that your serial monitor's baud rate matches the value used by Serial.begin in your code. The top ESP32/ESP8266 example on Google uses 115200 whereas most people have their serial monitor set to 9600 because it's a common Arduino sketch value. This mismatch is the most common reason for people Googling this issue.
For other connection issues, such as COM connection issues, try these steps:

*

*Press the little "Reset" button (or "RST") on your board.

*Unplug the board's USB cable.

*Unplug anything from the TX/RX pins.

*Close all Arduino IDE windows including the serial monitor.

*Plug the USB cable back in and wait a few seconds.

*Reopen the Arduino window and choose the correct port under Tools > Port. If you see multiple unlabeled COM ports, you can use the "Get Board Info" option or simple trial and error to figure out the right port.

*Open the serial monitor and make sure the baud rate matches the one found in your code.

*Upload the sketch.

*If the upload fails, wait a few seconds and try it a second time.

A: I'm not sure if this related to newer versions of the Arduino IDE or something else, but if you power cycle the board after you see this message it will run as you expect.
I've also noticed that in my case (macOS Catalina) I also have to reset the board to be able to upload sketches.
Hope that helps.

A: try to choose board "NodeMCU 1.0 (ESP-12E Module)"


text:
Q: How to do core data fetch predicate for NSDate in swift? i want to filter it by months // fetching data
    var request = NSFetchRequest(entityName: "Users")
    request.returnsObjectsAsFaults = false;
    request.predicate = NSPredicate(format: "name = %@", txtUsername.text!)

    do {
        let results:NSArray = try context.executeFetchRequest(request) as! [NSManagedObject]

        if (results.count > 0){
            var res = results[0] as! NSManagedObject
            txtname.text = res.valueForKey("name") as! String
            txtPassword.text = res.valueForKey("password") as! String

            print(results.count)

have no idea how to predicate NSdate, my entity have three attributes and one of is of  date type so if any body knows then do please tell me with an example

A: You can do something like
Get the first date and last date of a month and then use it like
let startDate = NSDate().startOfMonth()
let endDate = NSDate().endOfMonth()
request.predicate = NSPredicate(format: "dateField >= %@ AND dateField <= %@", startDate!, endDate!)

Where startDate and endDate are NSDate variables. This will get you data for current month. Similarly you can use it for other months too.
You can use below code to get start and end date of month
extension NSDate {

    func startOfMonth() -> NSDate? {

        let calendar = NSCalendar.currentCalendar()
        let currentDateComponents = calendar.components([.Year, .Month], fromDate: self)
        let startOfMonth = calendar.dateFromComponents(currentDateComponents)

        return startOfMonth
    }

    func dateByAddingMonths(monthsToAdd: Int) -> NSDate? {

        let calendar = NSCalendar.currentCalendar()
        let months = NSDateComponents()
        months.month = monthsToAdd

        return calendar.dateByAddingComponents(months, toDate: self, options: [])
    }

    func endOfMonth() -> NSDate? {

        let calendar = NSCalendar.currentCalendar()
        if let plusOneMonthDate = dateByAddingMonths(1) {
            let plusOneMonthDateComponents = calendar.components([.Year, .Month], fromDate: plusOneMonthDate)

            let endOfMonth = calendar.dateFromComponents(plusOneMonthDateComponents)?.dateByAddingTimeInterval(-1)

            return endOfMonth
        }

        return nil
    }
}


text:
Q: 2D Runner Highscore Issue Hey Guys I'm having some Problems with my Highscore in a Unity game. Its a 2d runner in which I save the Player Distance in a Variable and want to check when the Player is dead if distance is higher than Highscore. But I have a Error and can't figure out what the problem is. Can somebody help me, I'm pretty new to c#.
Heres my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;

public class UIController : MonoBehaviour
{
    Player player;
    Text distanceText;

    GameObject results;
    Text finalDistanceText;

    private void Awake()
    {
        player = GameObject.Find("Player").GetComponent<Player>();
        distanceText = GameObject.Find("DistanceText").GetComponent<Text>();
        results = GameObject.Find("Results");
        finalDistanceText = GameObject.Find("FinalDistanceText").GetComponent<Text>();
        HighscoreNumber = GameObject.Find("HighscoreNumber").GetComponent<Text>();
        results.SetActive(false);
    }

    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        int distance = Mathf.FloorToInt(player.distance);
        distanceText.text = distance + " m";

        if (player.isDead)
        {
            results.SetActive(true);
            finalDistanceText.text = distance + " m";
            if (distance > Highscore)
            {
                int Highscore = distance
                HighscoreNumber.text = Highscore + " m";
            }
        }
    }

    public void Quit()
    {
        SceneManager.LoadScene("Menu");
    }

    public void Retry()
    {
        SceneManager.LoadScene("SampleScene");
    }

}

A: In your  second if statment inside update method you use HighScore in comparison then declare variable with the same name on the next line.

A: Couple issues that I can see.  You'll be getting an error for HighscoreNumber being assigned to before being declared.
class UIController : MonoBehaviour {
Text highScore
//...

    void Awake() {
        highScore = GameObject.Find...
    }
}

The next issue is that you're declaring a Highscore locally after you try to use it in the if statement:
// Highscore doesn't exist yet so you can't compare distance against it.
if (distance > Highscore)
{
    // The int here means you're making a new variable that only lives inside the braces and setting it to distance.
    int Highscore = distance
    HighscoreNumber.text = Highscore + " m";
}

If this UIComponent stays alive between scene loads, you could just move the declaration to the class level.
public class UIController : MonoBehavior {
    int highScore = 0  //I get set to 0 when the UIController component is created.
    //...

    void Update() {
      //...
        // Since highScore is declared at the scope of the class, the if statement and assignment inside both have access.
        if(distance > highScore) {
            highScore = distance;
        }
    }
}

The other issue is that it looks like the UIComponent may be getting disposed and re-created when you restart the scene so will likely be reset to 0 between restarts.  You'll want to look at something like the Singleton method described here:
https://www.sitepoint.com/saving-data-between-scenes-in-unity/
This is just what came up when I Googled, there's probably a bunch of examples but that should help you know what to search.
However, this will only survive as long as the game is running.  If you want to retain the high score between game launches, you'll want to look at something like this:
https://blog.unity.com/technology/persistent-data-how-to-save-your-game-states-and-settings


text:
Q: SSLEngine but without delegated task Is there a way in Java to have the same functionality as SSLEngine but without a delegated task, because my program needs to handle a lot of connections and I wrote it in NIO with the purpose to use less ram, have more connections and have better performance, so if I use delegated tasks, it will defeat the purpose and my program will use even more ram as threads, in big quantities take quite a bit of space.

A: In a word, no. There's no particular reason why you need 'big quantities' of threads of delegated tasks. One will do, if you accept the throughput implications.


text:
Q: ASP.net Identity in New ERM based Project I have been ordered to use Identity in a new Web forms based project instead of old Membership. But on the web there are very few resources related to Webforms as compared to MVC. Even on ASP.NET/Identity there are just 2 articles on webforms. What should I do in this regard. What would you do in this regard.

A: If you create a sample application from Visual Studio it sets it all up for you you can then look there to see what it does and how it's setup.


text:
Q: Calling SpringMvc Jsp Form In FancyBox I am trying to get a jsp form into fancybox my site functions ok so i know most of my configurations are correct. I also did a sample test with an image and it worked great however with a form i am having problems. Under is the code:
<%@ include file="/WEB-INF/jsp/include.jsp" %>
<%@taglib prefix="form" uri="http://www.springframework.org/tags/form"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

    <link rel="stylesheet" href="http://code.jquery.com/ui/1.9.0/themes/base/jquery-ui.css" />

  <title><fmt:message key="title"/></title>

<fmt:message key="heading"/>

<fmt:message key="greeting"/>

    <a href="<c:url value="login.htm"/>">Login

    <a href="<c:url value="officer_registration.htm"/>">Register

    Light Box Registration

    dog

A: Add data-fancybox-type="iframe" to the link,
this will put an iframe within the fancybox displaying the href you passed through.


text:
Q: Reply to multiple clients using server Here is the server code i put this under the button click event. How can i do this program is closed after sending  data with one client and restart or refresh again and connect with next client.
string val;
Process[] pname = Process.GetProcessesByName("chrome");
if (pname.Length == 0)
{
    MessageBox.Show("Application is not running");
    val = "Not Running";
}
else
{
    MessageBox.Show("Application is running");
    val = " Running";
}
TcpListener tcpListener = new TcpListener(10);
tcpListener.Start();
Socket socketForClient = tcpListener.AcceptSocket();
if (socketForClient.Connected)
{
    label1.Show();
    label1.Text="Client connected";
    //MessageBox.Show("Client connected");
    NetworkStream networkStream = new NetworkStream(socketForClient);
    System.IO.StreamWriter streamWriter =
        new System.IO.StreamWriter(networkStream);
    System.IO.StreamReader streamReader =
        new System.IO.StreamReader(networkStream);
    string data_var;
    data_var = textBox1.Text;
    string theString =val;
    streamWriter.WriteLine(theString);
    try
    {
        streamWriter.Flush();
        theString = streamReader.ReadLine();
        label1.Text = theString;
        //MessageBox.Show(theString);
        streamReader.Close();
        networkStream.Close();
        streamWriter.Close();
    }
    catch
    {
        label1.Text = "Not flushed";
    }
}
try
{
    socketForClient.Close();
    //MessageBox.Show("Exiting...");
    label1.Text = "EXIT";
    Application.Restart();
}
catch
{ }

A: Follow the recomended procedure for handling client using callback functions as show in this post
http://www.switchonthecode.com/tutorials/csharp-tutorial-simple-threaded-tcp-server


text:
Q: Italic 'et al' using natbib and agsm...HOW? I am using natbib and agsm for harvard style referencing. My related code is
\usepackage{natbib}

\bibliographystyle{agsm}

Then I am using \citep{} for citations. My problem is that in text I am getting (Author et al., 2012) and I want (Author et al., 2012). Does anyone know how to change this and get 'et al' in italics in the text?

A: This discussion is will help you change to italics. For apa-good which also uses natbib, I only had one replacement to make. Don't forget to re-Typeset the bibliography (i.e. Latex -> Bibtex -> Latex -> Latex) after your changes. how to make volume bold and et. al italic when using the apalike bibliography style


text:
Q: IBM WebSphere Solr search crashing site Currently using IBM websphere I just installed APAR fix pack 8 and switched to a different database. Local host works but now products are not populated on the site correctly and the site just crashes when I click on one of the few products that are showing.
This is the error right after I click product. I also see this error a lot "null: CWXFS2003E: Cannot process search request."
4/7/16 10:02:20:058 EDT] 0000002a SolrCore      E org.apache.solr.common.SolrException log java.lang.IllegalArgumentException: Missing value only works for numeric or STRING types
    at org.apache.lucene.search.SortField.setMissingValue(SortField.java:208)
    at com.ibm.commerce.foundation.internal.server.services.search.component.solr.SolrSearchMultipleQueryComponent.process(SolrSearchMultipleQueryComponent.java:1243)
    at org.apache.solr.handler.component.SearchHandler.handleRequestBody(SearchHandler.java:214)
    at org.apache.solr.handler.RequestHandlerBase.handleRequest(RequestHandlerBase.java:135)
    at org.apache.solr.core.SolrCore.execute(SolrCore.java:1916)
    at org.apache.solr.servlet.SolrDispatchFilter.execute(SolrDispatchFilter.java:780)
    at org.apache.solr.servlet.SolrDispatchFilter.doFilter(SolrDispatchFilter.java:427)
    at com.ibm.commerce.foundation.internal.server.services.search.servlet.solr.SolrSearchDispatchFilter.doFilter(SolrSearchDispatchFilter.java:100)
    at org.apache.solr.servlet.SolrDispatchFilter.doFilter(SolrDispatchFilter.java:217)
    at com.ibm.ws.webcontainer.filter.FilterInstanceWrapper.doFilter(FilterInstanceWrapper.java:190)
    at com.ibm.ws.webcontainer.filter.WebAppFilterChain.doFilter(WebAppFilterChain.java:125)
    at com.ibm.ws.webcontainer.filter.WebAppFilterChain._doFilter(WebAppFilterChain.java:80)
    at com.ibm.ws.webcontainer.filter.WebAppFilterManager.doFilter(WebAppFilterManager.java:908)
    at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:965)
    at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:508)
    at com.ibm.ws.webcontainer.servlet.ServletWrapperImpl.handleRequest(ServletWrapperImpl.java:181)
    at com.ibm.ws.webcontainer.servlet.CacheServletWrapper.handleRequest(CacheServletWrapper.java:91)
    at com.ibm.ws.webcontainer.WebContainer.handleRequest(WebContainer.java:878)
    at com.ibm.ws.webcontainer.WSWebContainer.handleRequest(WSWebContainer.java:1592)
    at com.ibm.ws.webcontainer.channel.WCChannelLink.ready(WCChannelLink.java:191)
    at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleDiscrimination(HttpInboundLink.java:454)
    at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleNewRequest(HttpInboundLink.java:516)
    at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.processRequest(HttpInboundLink.java:307)

A: While inspecting the changes made to SolrSearchMultipleQueryComponent, I can see that the JR55662 (also included in cumulative fix #3) disables sortMissingValue in extension index.
So, this should resolve the issue.
JR55662 should have low risk since its purpose is to add logging statement, as described in:
http://www-01.ibm.com/support/docview.wss?uid=swg1JR55662
So install cumulative fix #3 or ask IBM to deliver the single APAR in the link


text:
Q: How to replace %20 with - in django urls I have a url which contains %20. I want to replace it with - with the help of regex
I already tried replace method
url(r'^timeanalysis/(?P<name>[\w|\W]+)'.replace('%20','-'), timeseries.timeanalysis, name='timeanalysis')

I don't want to change my database.

A: This is something you need to fix at the point you generate the link, not in the urlconf.
Usually you would use a SlugField that is automatically pre-populated from the title/name, replacing spaces with dashes as necessary.


text:
Q: Findig max value for multiple columns and deleting the rest from there, code not working I have long sets of data with multiple columns, and the idea is to for each column, find the maximum value, delete the rest of the data after that maximum value, and keep the data before the max. I found an old code that claims to do exactly what I want but when I copy it/transcribe it as a macro, it simply doesn't compile.  I keep getting "compile error, expected: name parameter" from the 5th row onwards. here is the code, in case anyone with a much better understanding of vba than me can try and figure out the problem, otherwise, propose a solution for my dilemma.
I really appreciate any help you can provide.
working code:
Sub deleteaftermax()
Dim I As Integer
For I = 1 To ActiveSheet.UsedRange.Columns.Count
    If WorksheetFunction.Count(Columns(i)) > 0 Then
        Range(Columns(i).Find(What:=WorksheetFunction.Max(Columns(i)), _
LookIn:=xlFormulas, LookAt:=xlWhole).Offset(3), _
            Cells(Rows.Count, i).End(xlUp)).Clear
    End If
Next
End Sub

EDIT: the problem was easily solved by adding an underscore on line 5, thanks again for pointing this out! I will leave the code (fixed) in case anyone needs a similar approach.


text:
Q: How to diagram continuous user event maps in GUI? I'm trying to create a diagrams of user interactions. In many cases I have to take some arguments like: mousePosition.x or touchDown.duration etc, and pass it through some f(x) function to render different UI using these arguments as interface properties.
Let's take an example of basic slider interface. [-----o-----]
I want to diagram a simple behavior of manipulating slider's knob. My logic is as follows:
pre condition: mousePosition.x = knobPosition.x; knobPosition.x = n
event: mosuseDown
event: mouseMove.x
if knobPosition.xMin < mousePosition.x < knobPosition.xMax
   render: knobPosition.x = mousePosition.x
if ( mousePosition.x > knobPosition.xMax )
   render: knobPosition.x = knobPosition.xMax
if ( mousePosition.x < knobPosition.xMin )
   render: knobPosition.x = knobPosition.xMin

My first thought was to diagram this behavior through State Machine, although it becomes messy for more complex examples. Maybe there is some modeling language that was design to model these kind of behaviors?

A: Your logic is a kind of decision tree. This can best be modeled using an activity diagram. Each if-statement is a decision symbol in the diagram.


text:
Q: React.js. How to change keyword 'this' i am trying to get every image download URL from Firebase. It seems that the first 'this' is different from the second one. If i want to let the second 'this' equals to the value of the first, what should i do? Thank you so much!
getAllURL = product => {

    // Get all the images from the firebase
    var storage = firebase.storage();
    console.log(this) // first this
    const storageRef =  storage.ref(`image/${product}`)

    storageRef.listAll().then(function(result) {
      result.items.forEach(function(imageRef) {
            imageRef.getDownloadURL().then(function(url) {
             console.log(this) // second this is undefined
            }).catch(function(error) {});
     })
   })

  }

componentDidMount() {
    axios.get('/user/product')
        .then(res=>{
            if(res.data.code==0) {
                this.setState({data:res.data.data},function(){
                    for (var i = 0; i < this.state.data.length; i++){
                        this.getAllURL(this.state.data[i].productName)
                    }
                 })
            }
        })
 }

A: this is one the most confusing features in Javascript.  I'd recommended you to look more into the topic.
As for a shortcut, there're many ways to take care of that.
First method: just assigned the first this into some variable first.
getAllURL = product => {

    // Get all the images from the firebase
    var storage = firebase.storage();
    console.log(this) // first this
    var firstThis = this; // some people prefered to assign "var that = this;", lol
    const storageRef =  storage.ref(`image/${product}`)

    storageRef.listAll().then(function(result) {
        result.items.forEach(function(imageRef) {
            imageRef.getDownloadURL().then(function(url) {
                 console.log(firstThis); // use the new variable to refer to the firstThis
            }).catch(function(error) {});
        });
    });
}

Second method: make use of bind function in javascript (a bit more advanced, and much better received from a functional programming perspective)
getAllURL = product => {

    // Get all the images from the firebase
    var storage = firebase.storage();
    console.log(this) // first this
    const storageRef =  storage.ref(`image/${product}`)

    storageRef.listAll().then((function(result) {
        result.items.forEach((function(imageRef) {
            imageRef.getDownloadURL().then((function(url) {
                 console.log(this);
            }).bind(this)).catch(function(error) {}); // yet another binding to propagate "this" inside
        }).bind(this)); // another binding to force "this" on this yet another inline function to equal the first this (propagate it down)
    }).bind(this)); // this binding will force "this" inside this inline function to equals the firstThis
}

Note:  It might get less confusing if amount of inline functions is reduced
getAllURL = product => {

    // Get all the images from the firebase
    var storage = firebase.storage();
    console.log(this) // first this
    const storageRef =  storage.ref(`image/${product}`)

    storageRef.listAll().then(listAllCallback.bind(this));
}

function listAllCallback(result) {
    for (var i = 0; i<result.items.length; i++) {
        var imageRef = result.items[i];
        imageRef.getDownloadURL()
            .then(downloadUrlCallback.bind(this))
            .catch(function(error) {});
    }
}

function downloadUrlCallback(url) {
    console.log(this); // second this
}


text:
Q: laravel Autoincrement with prefix i am new to laravel framework and i would like to know if there is any way for adding prefix value in auto increment ID
for example
say there are two levels of users Admin and Regular
i want the ID to be stored with prefix values
ADXXX and REXXX
just like giving tag to a user.


text:
Q: Which process is using port 4000 (identified as remoteanything by nmap)? I've run nmap -sS [computer ip] and see that i only have one service running:
PORT     STATE SERVICE
4000/tcp open  remoteanything

What service is this? Should i close it? I've googled and only found some shady stuff: http://remote-anything.com/
Maybe it is used by some of my other programs?

A: nmap just makes a guess at the service here, as basically any application can bind to any port. To see which specific application it is in your case, run
lsof -i :4000


text:
Q: How to read a matrix from a standard input? i'm trying to read the input from the standard input (console) but my code is only reading the first number in the line
x=input("enter the matrix?")
print(read_matrix(x))

def read_matrix(matrix):
    list_of_lists = []
    for line in matrix:
        new_list = [int(elem) for elem in line.split()]
        list_of_lists.append(new_list)
    return list_of_lists

A: Assuming that you are using Python 2.7, the problem lies in the fact that you are using input to process the input typed by the user. Indeed, if you look at the related documentation (https://docs.python.org/2/library/functions.html#input), you can see that basically input corresponds to eval(raw_input()), which means that the expression argument is parsed and evaluated as a Python expression.
If you want to read the standard input as a string, you should use raw_input instead.
If you are using python 3, then input is fine.
Notice, however, that you should format the input string in such a way that read_matrix can recognize the elements in the same row, and when a new row should be added.
One possible solution (that works with python 2.7), keeping your structure of the code and assuming that the format of the input is having numbers in the same row separated by a space, and rows separated by ';' (e.g., 1 2 3; 4 5 6; 7 8 9), is:
def parse_numbers_list(formatted_string):
    list_of_lists = [map(int, row.split()) for row in formatted_string.split(';')]

    return list_of_lists

x = raw_input("enter the list of lists of numbers?")
print(parse_numbers_list(x))

For python 3, similarly:
def parse_numbers_list(formatted_string):
    list_of_lists = [list(map(int, row.split())) for row in formatted_string.split(';')]

    return list_of_lists

x = input("enter the list of lists of numbers?")
print(parse_numbers_list(x))

Notice that I changed the name of the function, as generally, the code does not check whether the input string complies with the matrix constraint -- i.e., same number of columns for every row. You can add a check to see whether every list has the same size.
Also, a complete solution should include a check on whether the input string is well-formatted.
There are of course a plethora of other ways to implement code to read a matrix from standard input, including using external libraries, e.g., numpy, but I think, as you are learning Python, it is good that you are starting with the basics.

A: Your code has two problems. First is that you do not have a way of telling cells apart. If someone enters 112 for the first row, you interpret it as [1],[1],[2] when they could have meant any of a number of things. To fix this line 4 can be changed to
new_list = [int(elem) for elem in line.split(',')]

This will cause it to split cells by commas.
The second issue is that pressing enter tells the interpreter that you are done entering input. There are two solutions to this. You could have users input matrix dimensions and use a for loop to let them enter each row, or you could use Matlab's syntax where a 2x2 matrix is entered as [[a,b],[c,d]].

A: From your example code it seems that you're using a list of lists to aggregate your data... An infinite loop with something to break out can
generate such a data structure --- to break the input loop I've used a try-except clause, because it seems to me the most natural thing to use an EOF to signal the end of input, but you can use any other possible mechanism.
In [14]: def read_matrix():
    print('Input 1 row per line, with numbers separated by spaces.\n',
          'Use a C-d to stop input.')
    matrix = []
    while True:
        try:
            matrix.append([int(n) for n in input().split()])
        except EOFError:
            return matrix
   ....:

In [15]: read_matrix()
Input 1 row per line, with numbers separated by spaces.
 Use a C-d to stop input.
1 2 3
4 5 6
Out[15]: [[1, 2, 3], [4, 5, 6]]

of course I typed a C-d (on a new line, that was eaten by the interpreter) to stop the input loop.
The function is overly compact, you may prefer to unfold the elements of the list comprehension and possibly add some consistency check (number of columns maybe?) before updating matrix
In [18]: def read_matrix(nc):
    print('Input 1 row per line, with %d numbers separated by spaces.\n'%nc,
          'Use a C-d to stop input.')
    matrix = []
    while True:
        try:
            line = input()
            numbers = [int(n) for n in line.split()]
            if not len(numbers) == nc:
                print('Wrong number of columns, repeat this line')
                continue
            matrix.append(numbers)
        except EOFError:
            return matrix
   ....:

In [19]: read_matrix(3)
Input 1 row per line, with 3 numbers separated by spaces.
 Use a C-d to stop input.
1 2 3
4 5 6 7
Wrong number of columns, repeat this line
4 5 6
Out[19]: [[1, 2, 3], [4, 5, 6]]


text:
Q: Name A Telemetry Event in App Insights I am trying to use App Insights to track button clicks:
try
{
   TelemetryClient telemetry = new TelemetryClient();
   var ev = new EventTelemetry("buttonCancel_Click");
   telemetry.TrackEvent(ev);
   telemetry.Flush();
}
catch { }

Now, in the azure dashboard the event shows up as buttonCancel_Click (which is the name of the event handler of the buttonCancel's click event). I want to use a better name like "User Cancels Subscription".
I have put the above code in the event handler called buttonCancel_Click in my asp.net web forms application.
I couldn't find any way to do that.
Thanks for your help.

A: https://learn.microsoft.com/en-us/dotnet/api/microsoft.applicationinsights.datacontracts.eventtelemetry?view=azure-dotnet
The string passes in the EventTelementry constructor is the name of the  custom event, so :
try
{
   TelemetryClient telemetry = new TelemetryClient();
   var ev = new EventTelemetry("User Cancels Subscription");
   telemetry.TrackEvent(ev);
   telemetry.Flush();
}
catch { }


text:
Q: Datatable does not reinitializes properly when reloaded to display new saved record I have a datatable where it gets populated with data from the database. When the web page loads I call my Bind() function and this function populates the datatable with data as well as it initializes the datatable .
I also have a modal popup where users can add records. When they click the save button, it saves the record and I make an attempt to repopulate and reinitialize the data table.
The problem is that when I reinitialize the datatable the second time (on the button click), the datatable does not get reinitialized properly. It displays the headings after every record (see picture below). Please note that this only happens on the button click.
This my code so far:
$(document).ready(function () {
    var dataTable;
    Bind();

    function Bind() {
        $.ajax({
            type: "POST",
            url: "Clubs.aspx/GetCustomers",
            data: '{}',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: OnSuccess,
            failure: function (response) {
                alert(response.d);
            },
            error: function (response) {
                alert(response.d);
            }
        });
    }

function OnSuccess(response) {
    var xmlDoc = $.parseXML(response.d);
    var xml = $(xmlDoc);
    var customers = xml.find("Table");
    var row = $("[id*=gvCustomers] tr:last-child").clone(true);
    $("[id*=gvCustomers] tr").not($("[id*=gvCustomers] tr:first-child")).remove();
    $.each(customers, function () {
        var customer = $(this);
        $("td", row).eq(0).html($(this).find("ClubID").text());
        $("td", row).eq(1).html($(this).find("ClubName").text());
        $("td", row).eq(2).html($(this).find("ClubEmail").text());
        $("td", row).eq(3).html("" + $(this).find("ClubID").text() + "");
        $("td", row).eq(4).html("<img id='btnID' src='/assets/img/edit.png' Style='width: 20px; height: 18px;'</>");
        $("[id*=gvCustomers]").append(row);
        row = $("[id*=gvCustomers] tr:last-child").clone(true);
    });
    //This is where I initializes my datatable
    $('table').each(function () {
        dataTable = $(this).prepend($("

").append($(this).find("tr:eq(0)"))).DataTable({
            "responsive": true,
            "searching": true,
            "aaSorting": [],
            "sPaginationType": "full_numbers",
            dom: 'lBfrtip',
            buttons: [
                {
                    extend: 'copy',
                    className: 'btn btn-success'
                },
                {
                    extend: 'excel',
                    text: 'Excel',
                    title: 'Centre Information',
                    className: 'btn btn-success',
                    orientation: 'portrait',
                    exportOptions: {
                        columns: [0, 1, 2]
                    }
                },
                {
                    extend: 'pdf',
                    text: 'PDF',
                    title: 'Centre Information',
                    className: 'btn btn-success',
                    orientation: 'portrait',
                    exportOptions: {
                        columns: [0, 1, 2]
                    }
                },
                {
                    extend: 'print',
                    text: 'PRINT',
                    title: 'Centre Information',
                    className: 'btn btn-success',
                    orientation: 'portrait',
                    exportOptions: {
                        columns: [0, 1, 2]
                    }
                }
            ]
        });
    });
}
    });

Then this is the code in the save button where I try to reinitialize the datatable
$("#btnSave").click(function () {
    dataTable.destroy();
    Bind();
    return false;
});

Please assist how I can reinitialize the datatable correctly.

A: Try storing the DataTable in a variable and destroy that before rebinding the data.
So first create a varaible that can be accessed in both functions.
var dataTable;

function Bind() {
    //rest of code
}

Then assign the correct table to the variable
dataTable = $(this).prepend($("

").append($(this).find("tr:eq(0)"))).DataTable({

And then on that button click destroy that
$("#btnSave").click(function () {
    dataTable.destroy();
    Bind();
    return false;
});


text:
Q: Open application using Shell, then wait until it opens to continue commands Basically I want to replicate the Windows 7 style Snipping Tool so when you open it, it gets a snip ready. But in Windows 8, all it does is open the program and you either have to press CTRL+N or click New. I would like to avoid using Sleep(100) or other time functions as it can be unreliable for different systems under certain loads. I tried looping
While error <> 0
AppActivate "Snipping Tool", True
application.SendKeys "^N", True
exit sub
Wend

Ok. That's not what I used, but it's along the same lines. The problem with that is it kept giving VB Debug errors (which is good and all, except for this instance) and ruined this possible solution. Any other ideas to wait for the shell to open the program before being able to run
Application.SendKeys "^N", True

I have also tried using
shell.Run FileLocation, 1 , True

but that runs the sendkeys AFTER it closes! It's nearly what I want.

EDIT: WORKING CODE BELOW
//Used to wait for 200 milliseconds in the Sub.
Public Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
Public Function IsExeRunning(sExeName As String, Optional sComputer As String = ".") As Boolean
On Error GoTo Error_Handler
Dim objProcesses    As Object

Set objProcesses = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & sComputer & "\root\cimv2").ExecQuery("SELECT * FROM Win32_Process WHERE Name = '" & sExeName & "'")
If objProcesses.Count <> 0 Then IsExeRunning = True

Error_Handler_Exit:
On Error Resume Next
Set objProcesses = Nothing
Exit Function

Error_Handler:
MsgBox "The following error has occured." & vbCrLf & vbCrLf & _
        "Error Number: IsExeRunning" & vbCrLf & _
        "Error Description: " & Err.Description, _
        vbCritical, "An Error has Occured!"
Resume Error_Handler_Exit

End Function

Sub SnipTool()

Dim wsh As Object
Set wsh = VBA.CreateObject("WScript.Shell")

wsh.Run "C:\Windows\sysnative\SnippingTool.exe"
X = 0
Select Case Mid(Application.OperatingSystem, 21)
Case 6.02
Do Until IsExeRunning("SnippingTool.exe") = True Or X = 200
//added Timeout if snipping tool fails to load. Prevents Excel freezing.
X = X + 1
Loop
Sleep (200)
AppActivate "Snipping Tool", True
Application.SendKeys "^N", True
End Select

End Sub

A: You could start the Exe then take the IsExeRunning function from here:
http://www.devhut.net/2014/10/20/vba-wmi-determine-if-a-process-is-running-or-not/
And loop on Do until IsExeRunning(SnippingToolExecutable)


text:
Q: Menu click causes form to "lose focus" and menu dropdown disappears I have noticed some strange form interactions while using a ContextMenuStrip or a MenuStrip.  I don't really know what is causing it so the following should create a repeatable test for anyone looking into this:
I've created two Windows Forms: Form1 and Form2.  Both have a MenuStrip added to them.  Both are set to StartPosition = CenterScreen.
Form1 has a simple menu like this: Form2 > Open.  Clicking "Open" will launch Form2.
Form2 has a simple menu like this: Try to open > anotherTestMenuItem

*

*Start the program.  Form1 opens.

*Open Form2 from Form1 (i.e. click Form2 > Open).

*Form2 appears.

*On Form2, try to open the MenuStrip (click Try to open).  Form1 will reappear over Form2, although Form2 still has focus (you can see this if you move Form2 a little before trying to open the menu).

If I set Form2's owner to Form1, Form2 remains visible when you try Step 4, but the menu doesn't display the first time.  All subsequent clicks seem fine.
I noticed this when I tried opening a context menu (on a form opened by another form) and it would disappear immediately, but only the first time.  Every time thereafter it would open normally.
Does anyone have any ideas as to what is going on?

A: Yes, this is a known bug in the RTM version of .NET 4.5.  This KB article mentions it:

When you click a menu item to open a child window in the application, interactions with the menu and child windows behave incorrectly.

  For example, you may experience the following:
  - When you open a shortcut menu in the child window, the main window form takes the focus.
  - You cannot use mnemonics to access a menu item.

As you can tell from the KB article, this bug was fixed quite a while ago.  The bug fix was incorporated in a maintenance release first made available on January 8th of 2013.  Be sure to allow Windows Update to deploy that update on your machine.  Or download it from here.

A: Check to see that you have:
"AutoValidate" set to "EnablePreventFocusChange"

A: Make sure you do not call the Hide method for a menu or contextmenu during its item-click handler. I was in the habit of doing this during development to get a menu off the screen while I stepped through debugging code. However when I launched a secondary form from such a menu, the first right-click in the new form would cause the focus to revert to the primary form, sometimes even if I had left-clicked or typed something in the new form. I don't recall if I found this solution online somewhere or discovered it myself. This may not be the same bug mentioned above, but this behavior still occurs in .NET 4.7.


text:
Q: Aks ImagePullbackoff not getting alerted in Pending Pods Alert I had set an alert in azure monitor for pending pods with kube pod phase set to pending in azure monitor. It only get alerted for pending pods and not ImagePullBack and CrashloopbackOFF . is there a way to get alerts for these too.

A: You can create a custom Alert for CrashLoopBackOff & ImagePullBackOff based on this Kusto Query:
KubePodInventory
  | where PodStatus == 'Pending'
  | where ContainerStatusReason in ('ErrImagePull','ImagePullBackOff')


text:
Q: Finding the equation of a plane that passes through two points and is parallel to a line Find the algebraic equation of the plane that passes through the origin, is parallel to the line $\mathbf X= (-1, 0, 2) +t(2,-1,1)$, and contains the point $P=(1,2,3)$.
I suspect you can do this with a cross-product, but our professor isn't letting us use that as he hasn't taught it to us yet. Is there a way to get another point on the plane from the parallel line, so you can make a system of equations to solve for an orthogonal vector?

A: Given the points $\{p_0,p_1\}\in \Pi$ and the line $L\to p = p_2+\lambda \vec v$, determine a plane $\Pi$ parallel to $L$.
Characterizing the plane as $\Pi\to(p-p_0)\cdot\vec n=0$ we have the properties
$$
\cases{
(p_1-p_0)\cdot \vec n = 0\\
\vec v\cdot \vec n = 0\\
\|\vec n\|=1
}
$$
The last comes from normalization purposes.
Now as
$$
\cases{
p=(x,y,z)\\
p_0=(0,0,0)\\
p_1 = (1,2,3)\\
\vec v = (2,-1,1)
}
$$
we have to solve
$$
\cases{
(1,2,3)\cdot\vec n = 0\\
(2,-1,1)\cdot\vec n = 0\\
\|\vec n\|=1
}
$$

A: The equation of a plane is usually of the form $ax+by+cz+d=0$. If the origin lies in the plane (as it does in the question), then $d=0$ and one may write the equation as $\langle (a,b,c),(x,y,z)\rangle=0$.
Now, we know $(1,2,3)$ lies in the plane. Moreover, for all $t\in \mathbb{R}$, $t\cdot(2,-1,1)$ also lies in the plane. Hence, $(a,b,c)$ must satisfy
$$a+2b+3c=0\\2a-b+c=0$$
You probably see this is a system of two equations with $3$ unknowns, so the solution is not unique. That's okay, because for any $\alpha \in \mathbb{R}\setminus\{0\}$ the equations $ax+by+cz=0$ and $\alpha\cdot(ax+by+cz)=0$ are the same.

A: Follow these steps:

*

*The origin $\boldsymbol{r}_0$ and the point $ \boldsymbol{r}_A  $ define a line that belongs to the plane. This line has direction $(\boldsymbol{r}_A - \boldsymbol{r}_0)$. The normal to the plane must be perpendicular to all the vectors on this plane.

*Define the normal $\boldsymbol{n}$ as the vector that is perpendicular to the line $X$ and the line from the previous step.
$$ \boldsymbol{n} = \boldsymbol{e} \times (\boldsymbol{r}_A - \boldsymbol{r}_0) $$
Here $\boldsymbol{e}$ is the direction vector of line $X$. Note that a simplified scalar multiple of $\boldsymbol{n}$ would do just fine.

*Find the distance $d$ of the plane to the origin. Use the equation of the plane $ \boldsymbol{n} \cdot \boldsymbol{r} = d$ that must be true for all points on the plane. Since the origin is one of the points, it stands to reason that $$ d = \boldsymbol{n} \cdot \boldsymbol{r}_0 = 0 $$

*The equation of the plane is thus found by
$$ \boldsymbol{n} \cdot \pmatrix{x\\y\\z} = 0 $$
Here $\cdot$ is the vector dot product, and $\times$ the vector cross product.

A: There are many different ways to solve this problem without cross product. The more straight could posssibly be the following.
Let's call $P=(1,2,3)$.
1) find the pencil of planes containg $O,P$
To do this, we just have to find two planes, not parallel to each other, and passing through those points. We can take for instance a plane parallel to the $z$ axis and passing through the projections of the points on $x,y$ plane: $\pi_1\; :\; 2x-y=0$ . Same way, a plane parallel to $y$ axis: $ \pi_2 \; : \; 3x-z=0$.
So the pencil is $0=\mu \pi_1 + \lambda \pi_2=(2\mu +3\lambda) x -\mu y - \lambda z$.
2)find a plane in the pencil, parallel to the given line
Just take two points on the line, the vector defined by the corresponding segment (in your case it is already given)and impose that it be normal to the normal of the pencil.
You get a simple homogeneous equation in $\mu,\lambda$.  That is
$$
\eqalign{
  & 2\left( {2\mu  + 3\lambda } \right) - ( - 1)\mu  - \lambda  = 5\mu  + 5\lambda  = 0\quad  \Rightarrow   \cr
  &  \Rightarrow \quad \mu  =  - \lambda \quad  \Rightarrow \quad \left\{ \matrix{
  \mu  = 1 \hfill \cr
  \lambda  =  - 1 \hfill \cr}  \right. \cr}
$$
Therefore the required plane is
$$
\pi :\quad  - x - y + z = 0
$$
which in fact contains $(0,0,0)$ and $(1,2,3)$ and is parallel to the line because
$(2,-1,1) \cdot (-1,-1,1)=0$.
This indicates another way to solve the problem, i.e. the system
$$
ax + by + cz = d\;:\quad \left( {\matrix{
   0 & 0 & 0  \cr
   1 & 2 & 3  \cr
   2 & { - 1} & 1  \cr
 } } \right)\left( {\matrix{
   a  \cr
   b  \cr
   c  \cr
 } } \right) = \left( {\matrix{
   d  \cr
   d  \cr
   0  \cr
 } } \right)
$$


text:
Q: How to Calculate price between two dates $pro_id = 23;
$room_id = 10;
$start_date = '2022-10-28';
$end_date = '2022-11-03';

I failed with this query
SELECT id, start_date, end_date, price
FROM Table
WHERE `pro_id`= 23 AND rooms_id= 10 AND
((start_date <= CAST('2022-10-28' AS DATE) AND end_date >= CAST('2022-11-03' AS DATE)) OR
(start_date <= CAST('2022-11-03' AS DATE) AND end_date >= CAST('2022-11-03' AS DATE)) OR
(start_date >= CAST('2022-10-28' AS DATE) AND end_date <= CAST('2022-11-03' AS DATE)))

Price Table:

+----+---------+------+------------+------------+-------+
| id | pro_id  | room | data_start | data_end   | price |
+----+---------+------+------------+------------+-------+
|  1 |      23 |   10 | 2022-10-01 | 2022-10-31 | 35000 |
|  2 |      23 |   10 | 2022-11-01 | 2022-11-30 | 37500 |
+----+---------+------+------------+------------+-------+

I want to Output
+----+---------+------+-----------+--------------+
| id | pro_id  | room | price     | actual price |
+----+---------+------+-----------+--------------+
|  1 |      23 |   10 | 35000 x 4 |     140000   |
|  2 |      23 |   10 | 37500 x 3 |     112500   |
+----+---------+------+-----------+--------------+

if I book a room from '2022-10-28' to '2022-11-03' for 7 nights then the price will count as 35000 x 4 and 37500 x 3
like 2022-10-28, 29, 30, 31 = 35000 and 2022-11-01, 02, 03 = 37500
How do I solve this issue?

A: In this case, I would suggest doing it on PHP side.
$conn = $em->getConnection();

$pro_id = 23;
$room_id = 10;
$start_date = new \DateTime('2022-10-28');
$end_date = new \DateTime('2022-11-03');

$result = [];

//loop through each day
$currentDate = $start_date;
while ($currentDate <= $end_date) {
    $sql = "SELECT id, pro_id, room, price FROM Table WHERE pro_id = ? AND room = ? AND CAST(? AS DATE) BETWEEN start_date and end_date";
    $stmt = $conn->prepare($sql);
    $stmt->bindValue(1, $pro_id);
    $stmt->bindValue(2, $room_id);
    $stmt->bindValue(3, $currentDate->format('Y-m-d'));
    $data = $stmt->executeQuery()->fetchAssociative();

    // check here if $data IS NOT EMPTY

    if (array_key_exists($data['id'], $result)) {
        ++$result[$data['id']]['dates'];
        $result[$data['id']]['actual_price'] = $result[$data['id']]['price'] * $result[$data['id']]['dates'];
    } else {
        $result[$data['id']] = $data;
        $result[$data['id']]['dates'] = 1;
        $result[$data['id']]['actual_price'] = $data['price'];
    }

    $currentDate = $currentDate->add(\DateInterval::createFromDateString('1 day'));
}

I used Doctrine ORM connection to test it out on my side. You can query as you wish.
The result array will look like this:
var_export($result);

array(
    1 => array(
        'id' => 1,
        'pro_id' => 23,
        'room' => 10,
        'price' => 35000,
        'dates' => 4,
        'actual_price' => 140000,
    ),
    2 => array(
        'id' => 2,
        'pro_id' => 23,
        'room' => 10,
        'price' => 37500,
        'dates' => 3,
        'actual_price' => 112500,
    ),
)

A: You can convert the date field data into days, then subtract them, and multiply with price.
Try it:
SELECT
pro_id, room,
price, datediff(start_date, end_date) * price as actual_price
FROM TableName
WHERE
(
start_date <= CAST('2022-10-28' AS DATE)
AND
end_date >= CAST('2022-11-03' AS DATE)
)

A: I find my answer from StackOverflow to another question
SELECT   propertie_id, rooms_id,
         SUM(price * (1 + DATEDIFF(
              LEAST(end_date,   '2022-11-03' - INTERVAL 1 DAY),
           GREATEST(start_date, '2022-10-28')
         ))) AS Total
FROM     vi_properties_price_season_wise
WHERE   propertie_id = 23 AND rooms_id = 10 AND (
              '2022-11-03' - INTERVAL 1 DAY
                           BETWEEN start_date AND end_date
           OR '2022-10-28' BETWEEN start_date AND end_date
         )
GROUP BY propertie_id, rooms_id


text:
Q: Why is wlan0 gone? I have this machine under BunsenLabs Hydrogen (Debian Jessie pre configured for Openbox) for ~6 month. Was pleased with it and everything worked fine.
About 2 week ago, a new linux-firmware-amd64 version came out, and I started to have trouble with wifi after making the PC sleep/hibernate.
However, since yesterday, I have no wifi. At all.
My first thought was that iwlwifi must have gone corrupt or something, so I reinstalled it, reboot and... nothing.
After looking around a bit, I see that wlan0 just stopped existing:
drakasan@bld219:~$ lspci | grep Network
02:00.0 Network controller: Intel Corporation Wireless 7265 (rev 61)
drakasan@bld219:~$ rfkill list
4: hci0: Bluetooth
    Soft blocked: no
    Hard blocked: no
drakasan@bld219:~$ iwconfig
eth0      no wireless extensions.

lo        no wireless extensions.

Now I m as stuck as I am baffled. How can wlan0 just disappear like that? I would have expected that tw week ago with the kernel upgrade, but not two week later. Also, booting from the old kernel doesn't work either.
Kernel: 4.9.0-0.bpo.3-amd64, can boot on 4.9.0-0.bpo.2-amd64.

A: I ended up resolving the problem by installing the jessie-backports version of firmware-iwlwifi:
sudo apt install -t jessie-backports firmware-iwlwifi


text:
Q: Solve geometrically: Arg(z(z+1)) = 0 mod(pi) Solve geometrically the following equation :
$arg(z) +arg(z+1)=0 \pmod{\pi}$
My solution:
Let: $z=x+iy$
Then: $\arg(z)+\arg(z+1)=0 \pmod{\pi} \Longleftrightarrow
z(z+1) \in \mathbb{R}$
 Then: $\operatorname{Im}((x+iy) (x+1+iy))=0$
 After simplification we get $x=-1/2 $ or $ y=0$
However, that's an algebraic method and I'm required to solve it geometrically.
Any ideas?

A: Geometrically speaking, if $z$ is in the first or fourth quadrant, then $z(z+1)$ can never lie on the $x-$axis (i.e., $z(z+1)$ can never be real). E.g. if $z$ is in the first quadrant, then $\arg(z)\in(0,\pi/2)$ and $\arg(z+1)\in(0,\pi/2)$ with $\arg(z+1)<\arg(z)$, so $\arg(z)+\arg(z+1)\in(0,\pi)$.
Notice that we can show the desired $z$ does not lie on $y-$axis (except for the origin) either with a similar way. And if $z$ lies on the $x-$axis, then $z(z+1)$ is obviously real.
Now, suppose $z$ is in the second or the third quadrant. Say $z$ lies in the second quadrant (the third quadrant case is very similar).

*

*Case 1: Suppose $z+1$ lies also in the second quadrant. Then $\arg(z)+\arg(z+1)\in(\pi,2\pi)$, so $z(z+1)$ is not real.

*Case 2: Suppose $z+1$ lies in the first quadrant. Then $\arg(z)+\arg(z+1)\in(\pi/2,3\pi/2)$. Thus, if $z(z+1)$ is real, then we must have $\arg(z)+\arg(z+1)=\pi$. This means $z$ and $z+1$ must be symmetric w.r.t. $y-$axis. Hence $Re(z)=-1/2$.


text:
Q: cannot create dynamic tables with JQuery This Code is supposed to create a table and transform it into a canvas, so that when I click a cell it changes it color to the color picker the input is taken from the text boxes and color picker and executed when submit is pressed
I want to create a table with a certain height and width.
The Problem is that I don't know how to store the values of the input boxes
to create the table.
the second problem is I want to store the color from the color picker too to change the cells color to it when I click them.Photo of the page running.
Note: I am only allowed to solve this with JQuery.

// Select color input
// Select size input

// When size is submitted by the user, call makeGrid()
var Make=$('#pixel_canvas');
var td=$('td');

var rows=$('#input_width').val();
var cols=$('#input_height').val();
td.css("padding","700px");
function change() {
    $('td').click( function() {
        $(this).css("background-color","red");
    });
}

Make.append(makeGrid());

function makeGrid() {
    var table='';

    for (var i = 0; i < rows; i++) {
         table+='
';
         for (var j = 0; j < cols; j++) {
             table+='	';
         }
         table+='
';
    }
    return table;
};
body {
    text-align: center;
}

h1 {
    font-family: Monoton;
    font-size: 70px;
    margin: 0.2em;
}

h2 {
    margin: 1em 0 0.25em;
}

h2:first-of-type {
    margin-top: 0.5em;
}

table,
tr,
td {
    border: 1px solid black;
}

table {
    border-collapse: collapse;
    margin: 0 auto;
}

tr {
    height: 20px;
}

td {
    width: 20px;
}

input[type=number] {
    width: 6em;
}
<!DOCTYPE html>

    <title>Pixel Art Maker!</title>

    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Monoton">
    <link rel="stylesheet" href="styles.css">

Lab: Pixel Art Maker

Choose Grid Size

    <form id="sizePicker">
        Grid Height:
        <input type="number" id="input_height" name="height" min="1" value="1">
        Grid Width:
        <input type="number" id="input_width" name="width" min="1" value="1">
        <input type="submit">
    </form>

Pick A Color

    <input type="color" id="colorPicker">

Design Canvas

A: To create HTML table dynamically, You need to add the number of rows in a loop. You need for that to form the string that will be added in your html.

*

*A common way to do that is to start your string with "
". Then you will add to this string the number of rows (generally using a loop) and then you will add after the loop "
" to end your string.

*But in your example, the table tag exists already in your html, so it is not necessary to start or close our string with the table tag. We will append the string describing our rows directly to the selector $(#pixel_canvas)
Then if you want to create listeners on the td tag of your table, you can use delegation event. This way, you will add a single listener for the whole table. Basically, instead of table+='	';, you can do this: $('#pixel_canvas').on('click', 'td', function(e){})

let color;

//make the Grid of pixel art
function makeGrid() {
 const table = $('#pixel_canvas');
 table.find('tr').remove(); // will delete existing table if there is

 const size = {
 height: $('#input_height').val(),
 width: $('#input_width').val()
 }

 //Construct the table
 for (let i = 0; i < size.height; i++) {
  let row = '
';
  let cell = '';
  for(let j = 0; j < size.width; j++){
   cell += '	';
  }
  row += cell;
  row += '
';
  table.append(row);
 }

}

// When size is submitted by the user, call makeGrid()
$('#sizePicker').on('submit', function(e){
 e.preventDefault();
 makeGrid()
})

//change cell color
$('#pixel_canvas').on('click', 'td', function(e){
 if($(e.target).css('background-color') !== color){
  //if color cell different from the selected color with color picker
  color = $('#colorPicker').val();
  $(e.target).css('background-color', color);
  color = $(e.target).css('background-color'); // get the color value in RGB notation
 }else{
  $(e.target).css('background-color', 'inherit');
 }
})
body {
    text-align: center;
}

h1 {
    font-family: Monoton;
    font-size: 70px;
    margin: 0.2em;
}

h2 {
    margin: 1em 0 0.25em;
}

h2:first-of-type {
    margin-top: 0.5em;
}

table,
tr,
td {
    border: 1px solid black;
}

table {
    border-collapse: collapse;
    margin: 0 auto;
}

tr {
    height: 20px;
}

td {
    width: 20px;
}

input[type=number] {
    width: 6em;
}

<!DOCTYPE html>

    <title>Pixel Art Maker!</title>
    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Monoton">

    <link rel="stylesheet" href="styles.css">

Lab: Pixel Art Maker

Choose Grid Size

    <form id="sizePicker">
        Grid Height:
        <input type="number" id="input_height" name="height" min="1" value="1">
        Grid Width:
        <input type="number" id="input_width" name="width" min="1" value="1">
        <input type="submit">
    </form>

Pick A Color

    <input type="color" id="colorPicker">

Design Canvas


text:
Q: Node JS: how to get access to ES6 class from another file? Good day. I have 3 different files: app.js, task.js, index.html.
task.js - model of the task. It contains:
module.exports = class Task {
    constructor(author, header, priority, description, id) {
        //...
    }

    //...
};

app.js contains:
const Task = require("./js/models/Task");

I can create an instance of the task in app.js:
const task = new Task();

But when i try to attach task.js to index.html:
<script src="../js/models/Task.js" type="text/javascript"></script>
and run the server, i get an error:
ReferenceError: module is not defined
module.exports = class Task

How i can create an instance of the Task?

A: The CommonJS module syntax is only supported natively by Node. It's not supported natively by the browser. You can use Browserify to bundle up CommonJS modules to a format your browser understands, should you want the syntax to work on the browser.


text:
Q: Memory mapped file and memory consumption Given the following test code (x64 environment):
    static void Test()
    {
        string fileName = @"d:\map";
        long length = new FileInfo(fileName).Length;
        using (var file = MemoryMappedFile.CreateFromFile(fileName, FileMode.Open, "mapFile", length, MemoryMappedFileAccess.ReadWrite))
        {
            byte* bytePtr = (byte*)0;
            var view = file.CreateViewAccessor(0, length, MemoryMappedFileAccess.ReadWrite);
            view.SafeMemoryMappedViewHandle.AcquirePointer(ref bytePtr);

            long count = (long)(length / sizeof(int));
            long sum = 0;
            long step =  count / 2000;

            int* ptr = (int*)&bytePtr[0];
            long currentCount = 0 ;

            Parallel.For(0, count, new ParallelOptions { MaxDegreeOfParallelism = 8 }, (i) =>
            {
                Interlocked.Add(ref sum, ptr[i]);
                Interlocked.Increment(ref currentCount) ;

                if (currentCount % step == 0)
                    Console.Write("\r{0:0.00}%", (100 * currentCount / (float)count));
            });

            Console.WriteLine(sum);

            view.Dispose();
        }
    }

Given that "d:\map" is a 40GB file, there is a very odd behavior when there is random access through the pointer "ptr".
System physical memory get fully used, and everything get slowed, with this process taking more than 2 hours to complete.
When I have sequential (and single threaded) access, the physical memory used don't top 1GB and the process takes about 8 minutes.
My question is: When using memory mapped file does the "real" memory get used? Isn't only virtual address space that gets occupied?
I'm trying to understand physical memory consumption when using memory mapped file.

A: Memory mapped files use virtual memory.  You'll have no trouble mapping many more gigabytes of VM space than you have RAM on a 64-bit operating system.  The point of a demand-page virtual memory operating system, the sum of the memory required for all running processes always greatly exceeds the amount of RAM.
Mapping it to RAM costs money, that's where the demand comes in to play.  The processor interrupts the program and yells for help when it tries to access a virtual memory address that is not mapped to RAM.  Called a page fault.
If you did not spend that money on getting at least 40 GB of RAM then you'll inevitably pay the cost of the OS dealing with these page faults.  Which requires allocating a RAM page and filling it with the content from the file.  Perf go South when it has to unmap previously mapped RAM and save its content to the file.  Followed by re-using the freed-up RAM page and loading file content from the appropriate file offset.  Very deer, the disk is slow.  A problem known as "thrashing".
It is much less of an issue when you address the memory sequentially, one page fault is good for 4096 bytes of sequential access and you'll have good odds that the disk reader head is still in the right spot when you trip a page fault.


text:
Q: Difference between performance of the two sql queries? I have a field in my table having text data type.
Is there a difference in performance for the following two sql queries:
 select * from tablename where fieldname="xyz%";
 select * from tablename where fieldname="%zyx";

If we were to implement the execution of these queries, this is what I think we would need to do:
We have to match the two regexes (xyz* and *zyx).
We will have to check the string chars one by starting from the beginning.
For the first query we will have to read the first three characters to see if there is a match but for the second one we will have to read till the we get the end of the string to determine if the match has occurred. But if we have the length of the string stored somewhere we can directly read the last three characters giving similar performance as the first case.
My question is whether commercial databases like mysql and oracle show any difference in the performance in the execution of the queries.

A: There is definitely difference between performance on all DB's.
First case will be definitely faster if column is indexed.
I had similar instance in my project where user was also allowed to search "ends with" (like your second query).
As this was frequently used operation and query was slow,

*

*We added additional column to table which stored reverse of fieldname.

*indexed this column

*whenever ends with was searched , we
searched in this new column :) (by reversing original search string)

so your second query becomes:
 select * from tablename where fieldname_rev="xyz%";

This approach made it as fast as starts with query.

A: Picking up from your comment : " I just want to know if a starts with match is diff from an ends with match".
Firstly - remember that we are not looking for the best algorithm to match a string. We are looking for the best algorithm to find all matching strings in a set of N rows. We want to do better than 'Do algorithm X, N times'.
If fieldname is NOT indexed, then there will be very little difference in performance between the two queries - the SQL engine is just going to do a match on the first 3 or last 3 bytes of the string, which is simply a matter of offsetting to the right memory location.
If the fieldname IS indexed, there will be a huge difference in performance between the two searches, because rather than examining all N rows, we can discard most of the data.
i.e. for the "xyz%" version, we can use a binary search.
We start at the middle element, which happens to be 'peter'. We can immediately discard everything before 'peter' and get the middle element on the remainder - 'samantha', and so on, until we find the entries starting 'xyz'.
With the "%xyz" version, we cannot do this, as ANY string could potentially match at the end, we need to look at every string.
As the size of our table expands, the difference between these two approaches becomes large.
The solution of creating a field/index for the reverse of fieldname allows us to use the binary search technique again. (In some databases it is actual possible to do this without creating an extra field, but through using particular index types, virtual columns, etc).
This is simplified a lot - for detail on the actual implementation of database indexes, look into B-Tree and B*Tree indexes.

A: If fieldname is indexed, most of commercial databases can transform the first query into an interval search
select * from tablename where fieldname>="xyz" and fieldname<"xy{"

which is very fast.

A: Yes, there is a difference between the following two queries:
select * from tablename where fieldname LIKE "xyz%";
select * from tablename where fieldname LIKE "%zyx";

*

*The equals ("=") operator doesn't allow wildcards in SQL - you need to use LIKE

*The queries are entirely different

*

*"xyz%" will return records that start with "xyz"

*"%xyz" will return records that end with "xyz"

*Assuming an index exists on the fieldname column, "%xyz" can not use the index - but"xyz%" could, which means it would be faster.

The fastest means of finding substrings within text is to use Full Text Search (FTS) - both Oracle and MySQL have their own native functionality, and there are 3rd party tools like Sphinx and Solr.


text:
Q: How do you make Bastille work and secure Ubuntu 12.04? It doesnt work for me `sudo bastille -x` I was able to install bastille from the normal repositories and then run the GUI. After going through the options and clicking OK to apply, it showed these errors.
Do you know why Bastille wont work on Ubuntu 12.04?
NOTE:    Executing PSAD Specific Configuration
NOTE:    Executing File Permissions Specific Configuration
NOTE:    Executing Account Security Specific Configuration
NOTE:    Executing Boot Security Specific Configuration
ERROR:   Unable to open /etc/inittab as the
      swap file /etc/inittab.bastille
      already exists.  Rename the swap file to allow Bastille
      to make desired file modifications.
ERROR:   open /etc/inittab.bastille failed...
ERROR:   open /etc/inittab failed.
ERROR:   Couldn't insert line to /etc/inittab, since open failed.NOTE:   Executing Inetd Specific Configuration

A: You might want to check the /var/log/Bastille/error-log file for the output. Not certain that Bastille failed, but do know that you probably will not see /etc/inittab in the uBuntu 12.04 out-of-the-box configuration. Think that may exist in RPM-based distribution (Fedora, Red Hat, SuSE, etc.) but not so sure about that being in Ubuntu any more.
More than likely, parts of your configuration worked, just some parts did not work as expected. You should also take heed of the warnings within the Community documentation about Bastille Linux:
"IMPORTANT: Please be aware that Bastille Linux requires advanced knowledge, is site-specific and has several options that no longer apply to Ubuntu."
found here.
Might be useful to start with the log output and see if maybe some of the options specified were not applicable to Ubuntu at present.
Have a nice day,
freecode


text:
Q: How can I increment the numerical value in my WHERE clause using a loop? I am currently using the UNION ALL workaround below to calculate old_eps_tfq regression slopes of each ticker based off its corresponding rownum value (see WHERE rownum < x). I am interested to know what the old_eps_tfq is when rownum < 4 then increment 4 by 1 to find out what old_eps_tfq is when rownum < 5, and so on (there are ~20 rownum)
Could I use PL/pgSQL for this?
SELECT * FROM(
    WITH regression_slope AS(
        SELECT
            ROW_NUMBER() OVER ( PARTITION BY ticker ORDER BY earnings_growths_ped) AS rownum,
            *
        FROM "ANALYTICS"."vEARNINGS_GROWTHS"
        --WHERE ticker = 'ACN'
        ORDER BY ticker )
    SELECT
        ticker,
        current_period_end_date,
        max(earnings_growths_ped) AS max_earnings_growths_ped,
        --max(rownum) AS max_rownum,
        round(regr_slope(old_eps_tfq, rownum)::numeric, 2) AS slope,
        round(regr_intercept(old_eps_tfq, rownum)::numeric, 2) AS y_intercept,
        round(regr_r2(old_eps_tfq, rownum)::numeric, 3) AS r_squared
    FROM regression_slope
    WHERE rownum < 4
    GROUP BY ticker, current_period_end_date
    ORDER BY ticker asc ) q

UNION ALL

SELECT * FROM(
    WITH regression_slope AS(
        SELECT
            ROW_NUMBER() OVER ( PARTITION BY ticker ORDER BY earnings_growths_ped) AS rownum,
            *
        FROM "ANALYTICS"."vEARNINGS_GROWTHS"
        --WHERE ticker = 'ACN'
        ORDER BY ticker )
    SELECT
        ticker,
        current_period_end_date,
        max(earnings_growths_ped) AS max_earnings_growths_ped,
        --max(rownum) AS max_rownum,
        round(regr_slope(old_eps_tfq, rownum)::numeric, 2) AS slope,
        round(regr_intercept(old_eps_tfq, rownum)::numeric, 2) AS y_intercept,
        round(regr_r2(old_eps_tfq, rownum)::numeric, 3) AS r_squared
    FROM regression_slope
    WHERE rownum < 5
    GROUP BY ticker, current_period_end_date
    ORDER BY ticker asc ) q

Here is my table

A: The top query SELECT * FROM (...) q sounds like useless.
Then you can try this :
WITH regression_slope AS(
    SELECT
        ROW_NUMBER() OVER ( PARTITION BY ticker ORDER BY earnings_growths_ped) AS rownum,
        *
    FROM "ANALYTICS"."vEARNINGS_GROWTHS"
    --WHERE ticker = 'ACN'
    ORDER BY ticker )
SELECT
    max,
    ticker,
    current_period_end_date,
    max(earnings_growths_ped) AS max_earnings_growths_ped,
    --max(rownum) AS max_rownum,
    round(regr_slope(old_eps_tfq, rownum)::numeric, 2) AS slope,
    round(regr_intercept(old_eps_tfq, rownum)::numeric, 2) AS y_intercept,
    round(regr_r2(old_eps_tfq, rownum)::numeric, 3) AS r_squared
FROM regression_slope
INNER JOIN generate_series(4, 24) AS max -- the range 4 to 24 can be adjusted to the need
   ON rownum < max
GROUP BY max, ticker, current_period_end_date
ORDER BY max asc, ticker asc


text:
Q: MUI Dialog Print is printing background Using Material UI with React and styled-components.  My issue is with using a Dialog and printing.  The modal overlay allows the background to be printed (which is not what we want).  NOTE: I don't have control over the HTML in the background, so as an alternative I'd like to apply white to the background when printing so the background will not be printed.  Any suggestion on how I can modify the CSS specifically for this situation?
I thought I'd do something like this but I haven't had any luck:
const useStyles = makeStyles({
  root: {
    '&[class*="MuiBackdrop-root"]': {
      backgroundColor: "white !important",
    },
  },
})

<Dialog className={classes.root}>
...
</Dialog>

Thank you for your time!


text:
Q: Inserting a list into temp table using Dapper I am trying to insert a List of integers into a temporary table using Dapper. I wrote my query based on the selected answer to this Stack Overflow question. However, I get a syntax error when running the query.
Code:
List<int> lst = new List<int> {1, 2, 3, 4};
string queryString="CREATE TABLE #Temp (ListInt int)"
                + " INSERT INTO #Temp (ListInt) VALUES (@Lst);";
dbConnection.Open();

dbConnection.Query(queryString, new {Lst = lst});

Error:
System.Data.SqlClient.SqlException (0x80131904): Incorrect syntax near ','.

How can I use Dapper to insert this list?

A: You can accomplish this via Dapper's Execute a Command multiple times feature.
The SQL query must contain only the command you want repeated, and the parameters (passed to Dapper) must be an IEnumerable of objects where each object has a property named after the parameter you're using. Finally, use Execute (not Query) when you're inserting (not retrieving) values:
List<int> lst = new List<int> {1, 2, 3, 4};
dbConnection.Open();
dbConnection.Execute("CREATE TABLE #Temp (ListInt int)");
dbConnection.Execute("INSERT INTO #Temp (ListInt) VALUES (@item);",
    lst.Select(x => new { item = x }));

Note that if you're inserting thousands of items, the INSERT statement will be executed once per item, which can be very slow. If this is the case, investigate a community extension to Dapper, such as BulkInsert that can insert 1000s of items in one INSERT statement.


text:
Q: push method not working i've been loosing my hair over this one. I want to create a dynamic array depending on how many  tags my main  has inside. Please Help me!
Here is my HTML

Here is my JS
container = document.getElementById('image-slider');
containerLength = container.childNodes.length;
images = new Array();
for(var i=0;i<=containerLength;i++){
if (container.childNodes[i].nodeName == 'A') {
    alert(container.childNodes[i]);// here I get the desired value
    images.push(container.childNodes[i]);
          //this doesn't work even if i use images.push('Hello');
}
}
alert(images[0]); //doesn't even pops out
// if I do it like this.... i get the desired result! I don't know why! but this is not what i want
images.push(container.childNodes[1]);
alert(images[0]);

A: Your entire problem can be circumvented easily:
var images = document.getElementById("image-slider").children;

Magic :p

A: If you run the debugger on this you'll notice that you are trying to reference the 12th element in the collection when the collection only has 11.
for(var i=0;i<=containerLength;i++)

should be
for(var i=0;i<containerLength;i++)


text:
Q: Rails Paperclip Invalid Path in AWS I'm using rails and paperclip in uploading in AWS S3 bucket.  The bucket name, secret keys, region are the same for both Heroku and AWS, in Heroku it's working fine i can see the image but in AWS its not working.
In AWS this is the path  and its not working.
http://s3-ap-southeast-2.amazonaws.com/assets.steel-ps.com/var/www/steelip-admin/public/ckeditor_assets/pictures/45/content_notes-icon-mac.jpg
In Heroku its working fine
http://s3-ap-southeast-2.amazonaws.com/assets.steel-ps.com/app/public/ckeditor_assets/pictures/45/content_notes-icon-mac.jpg
Notice that in AWS its adding my '/var/www/steelip-admin' which is the folder in my server.   What could be wrong.
Thanks.

A: Thanks for all the help everyone.  Basically the fix were inside the CkEditor::Picture class.  I have remove the rails_root in front of the path.
path: 'app/public/ckeditor_assets/pictures/:id/:style_:basename.:extension'

A: I just came across this one, because I was dealing with the same issue.
The fix I found was to add s3_host_name to the config.paperclip_defaults.
s3_host_name: 's3.eu-central-1.amazonaws.com',


text:
Q: I am trying to merge single digit ints into a single number I am getting an out of bounds error on the line where x is defined. What am I doing wrong?
import java.util.ArrayList;
import java.lang.Math;

public class poopy
{
    public static void main(String[] args)
    {
       ArrayList<Integer> num = new ArrayList<Integer>();
       double x;

       for(int j=1; j<5; j++)
       {
          num.add(j);
       }

       for(int i: num)
       {
           x = num.get(i) * Math.pow(10,i);
           System.out.println(x);
       }

   }
}

This is going to be for a calculator and the int ArrayList will grow every time a number button is pushed.

A: You will need to pass on the foreach loop and use an old-fashioned for loop:
   for(int i=0;i<num.size;i++)
   {
       x = num.get(i) * Math.pow(10,i);
       System.out.println(x);
   }

What happens is that you got the values of the array, but you need the indexes too. So, no foreach loop.

A: for(int i: num)

i here is the value not the index.

A: Your for (for-each) loop should be like this:
for(int i: num)
{
    x = i * Math.pow(10,i);
    System.out.println(x);
}

i instead of num.get(i)
if you want to access the items by index then you should not use the for-each loop, use the for loop as follows:
for(int i = 0; i < num.size(); i++)
{
    x = num.get(i) * Math.pow(10,i);
    System.out.println(x);
}

A: With num.get(i) method you are accessing array by its index. Elements of your array are [num[0]=1, num[1]=2, num[2]=3, num[3]=4] .
loop for(int i: num) is accessing elements of num array and store them in a variable i.