text:
Q: Change variant on lightning button when clicked? I'm trying to have my lightning:button display a different variant based on if it's clicked or not. I'm iterating through a array where each item has its button.
This is the component
<aura:attribute name="selected" type="Boolean" access="public" default="true" />
   <div class="slds-truncate" title="Select this car">
                        <lightning:button label="Select" onclick="{!c.changeColor}" variant="{!v.selected ? 'neutral' : 'success'}">
                            <c:ResourceTile resource="{#resource}" selectedResource="{!v.selectedResourceId == resource.Id}"/>
                        </lightning:button>
    </div>

This is the controller
changeColor: function(component, event, helper) {
    var btn = event.getSource();
    console.log(btn + " **this button")
    var bool = btn.get("v.variant");
    bool = false;
    component.set("v.selected", bool)

}

For some reason, all the buttons in the list change color when I click them, and not the specific button. How can I solve this?
What I'm trying to achieve is to only have ONE button selected at the time so the user knows which item in the array they have currently selected.

A: This is because v.selected is common for all button. When you change it for one place that change reflect in all buttons.
So you need to set/use a dynamic variables here. Or you can dynamically set the variant.
<lightning:button label="Select" aura:id="button" onclick="{!c.changeColor}" variant="{!v.selected ? 'neutral' : 'success'}">
    <c:ResourceTile resource="{#resource}" selectedResource="{!v.selectedResourceId == resource.Id}"/>
 </lightning:button>

//first give Id to your button. Then use cmp.find("button") to get all button and set them variant neutral. In the end change variant in current button.

btn.set("v.variant", "success"); // remember to remove it from other button as well


text:
Q: Validate Hardcoded Password I am using Kotlin.
I have a stored password (val password = 1111). I have an editText (passcode) that takes a "numberPassword" input. I would like the user to input the code and if it matches I will do something.
I have tried:
if (passcode.equals(1111)) { //do something }
if (passcode = password) { //do something }
if (passcode.text.toString() == password) { //do something }
if (passcode == "1111") { //do something }
...
and many other versions switching back and forth from int to string
This should be very simple since the user is either right or wrong. I am guessing it has to do with string/int stuff. Thanks for your help!
Just Tried:
    <EditText
        android:id="@+id/passcode"
        android:layout_width="120dp"
        android:layout_height="75dp"
        android:layout_gravity="center_horizontal"
        android:textAlignment="center"
        android:hint="@string/zeros"
        android:drawableStart="@drawable/ic_key"
        android:inputType="numberPassword"
        android:maxLength="4"
        android:maxLines="1"
        android:textColor="@color/black"
        android:textColorHint="@color/light_gray"
        android:textCursorDrawable="@null"
        android:textSize="35sp"
        android:singleLine="true"
        android:autofillHints="true" />

private var passcode: EditText? = null private var password: Int = 1111
        view.submitButton?.setOnClickListener {

            if (passcode?.text.toString() == password.toString()){

                Toast.makeText(this@SplashScreen, "Valid", Toast.LENGTH_LONG).show()
       } else {
                Toast.makeText(this@SplashScreen, "Invalid", Toast.LENGTH_LONG).show()

            }
        }

Result: Invalid when I enter 1111 in edittext

A: Your password variable is not initialized as it is still null.
Set it like this:
private var passcode : EditText? = findViewById<EditText>(R.id.passcode)

A: You are comparing the whole widget to the variable password.
What you need is to compare the password variable with passcode.text.toString()
like this:
 if (passcode.text.toString() == password.toString()){
                Toast.makeText(this@MainActivity, "Correct Passcode!", Toast.LENGTH_SHORT).show()
            }else{
                Toast.makeText(this@MainActivity, "Wrong Passcode!", Toast.LENGTH_SHORT).show()
            }

redpajama_set_name: RedPajamaStackExchange


text:
Q: How Eclipse know I didn't call some method of a object? I was supposed to call recycle after use a TypedArray, but I forgot.
Then Eclipse showed a warning saying This TypedArray should be recycled after use with #recycle().
I wonder how does Eclipse know about it and how can I use this nice feature in my code.

A: The warning you see here isn't a normal Java warning, but is a Lint warning.
Lint is an error checking tool used by the Android Plugin to help you with the best practices and methods of doing things in Android.
TypedArrays can be recycled after you're done with them as a cleanup operation, and Lint simply checks to see if you've got <TypedArrayObject>.recycle() for each of the TypedArrays in your code anywhere. If you don't, it warns you about it.


text:
Q: ImportError: No module named 'setuptools' in wsl I am using wsl and Debian distribution; when I'm trying to install pybrain through setup.py  getting an error; ImportError: No module named 'setuptools.'I have already installed setuptools into my system still getting the same error.
I have used the following commands.
sudo python3 setup.py install
sudo apt-get install python3-setuptools

enter image description here


text:
Q: How to show only a subset of labels on x-axis? I am making a plot in R (not ggplot, just basic R), and I set the custom x-axis values using the following code:
plot(my_vector, level=1, labels = F, col = c("red", "green", "blue", "orange", "black"), xaxt='n')

axis(1, at=1:length(date_tot), labels=format(as.Date(date_tot, "%Y-%m-%d"), "%d-%m"), las=2, tick=F)

legend(x="topright", col=c("red", "green", "blue", "orange", "black"), legend=my_names, lwd=2, bty='n')

The output is like the following:

Since the x-axis is not well-formatted, I would like to:

*

*show only a subset of dates (eg. one every three)

*move the labels of the x-axis out of the plot (so a bit down)

How can I do so?

A: Sample:
y <- mtcars$disp
plot(y, pch = 16, xaxt = "n")
axis(1, seq_along(y), las = 2)

ind <- seq_along(y)
ind <- ind[ ind %% 3 == 0 ]
ind
#  [1]  3  6  9 12 15 18 21 24 27 30
plot(y, pch = 16, xaxt = "n")
axis(1, at = seq_along(y)[ind])

As to your second question, I cannot reproduce it ... perhaps you've adjusted par somewhere else in a way that affects margins and such. (Perhaps close and reopen your graphic device ... dev.off()?)


text:
Q: columns don't line up, using bootstrap 3 I am using twitter bootstrap version 3 and for some reason the width of the columns don't add up right.
Take a look at this shot: http://i.imgur.com/LhgqL12.png
The right column doesn't line up with the end of the carousel and I cannot figure out why!
Here's the html for the page:

Donate

Sales

Submit Tip

Gaming Wiki

About Us

                        Community

Forum

IRC Chat

Twitter

Sales Twitter

Google+

Links

                         liamdawe

View Profile

User CP

Private Messages

Admin CP 3

Logout

                <form method="get" action="/index.php?module=search" class="navbar-form navbar-right" role="search">
                    <input type="hidden" name="module" value="search">
                    <input type="text" class="form-control" name="q" placeholder="Search Articles">
                    <input type="submit" style="position: absolute; left: -9999px; width: 1px; height: 1px;"/>
                </form>

Join our Minecraft server!

Natural Selection 2 Out on the 30th for Linux!

                        You have 3 admin items needing review!

                Latest Games On Sale: Steam Sparkle 2 Evo, Steam Shadow Warrior Classic Redux, Steam Redshirt, Steam Gravity Badgers  - See all

Our News

Featured Videos

News Elsewhere

Sdasd Asdasdasdasdasdasdasdasd

by liamdawe January 17, 2014 at 1:56 pm

                            Your text here, use the uploader for an image!Your text here, use the uploader for an image!Your text here, use the uploader for an image!

In:  Interview

                            Edit  Make Editors Pick

 1 Comments

Test Hhhhhhhhhhhhhhhhhhhh

by liamdawe January 17, 2014 at 1:52 pm

                            Your text here, use the uploader for an image!Your text here, use the uploader for an image!Your text here, use the uploader for an image!

In:  Interview

                            Edit  Make Editors Pick

 0 Comments

Prev

1

/

99

Next

            <form name="form2" class="form-inline">
            Pick Page: <select class="input-mini" name="jumpmenu" onchange="window.open(this.options[this.selectedIndex].value, '_self')"><option value="/home/page=1">1</option><option value="/home/page=2">2</option><option value="/home/page=3">3</option><option value="/home/page=4">4</option><option value="/home/page=5">5</option><option value="/home/page=6">6</option><option value="/home/page=7">7</option><option value="/home/page=8">8</option><option value="/home/page=9">9</option><option value="/home/page=10">10</option><option value="/home/page=11">11</option><option value="/home/page=12">12</option><option value="/home/page=13">13</option><option value="/home/page=14">14</option><option value="/home/page=15">15</option><option value="/home/page=16">16</option><option value="/home/page=17">17</option><option value="/home/page=18">18</option><option value="/home/page=19">19</option><option value="/home/page=20">20</option><option value="/home/page=21">21</option><option value="/home/page=22">22</option><option value="/home/page=23">23</option><option value="/home/page=24">24</option><option value="/home/page=25">25</option><option value="/home/page=26">26</option><option value="/home/page=27">27</option><option value="/home/page=28">28</option><option value="/home/page=29">29</option><option value="/home/page=30">30</option><option value="/home/page=31">31</option><option value="/home/page=32">32</option><option value="/home/page=33">33</option><option value="/home/page=34">34</option><option value="/home/page=35">35</option><option value="/home/page=36">36</option><option value="/home/page=37">37</option><option value="/home/page=38">38</option><option value="/home/page=39">39</option><option value="/home/page=40">40</option><option value="/home/page=41">41</option><option value="/home/page=42">42</option><option value="/home/page=43">43</option><option value="/home/page=44">44</option><option value="/home/page=45">45</option><option value="/home/page=46">46</option><option value="/home/page=47">47</option><option value="/home/page=48">48</option><option value="/home/page=49">49</option><option value="/home/page=50">50</option><option value="/home/page=51">51</option><option value="/home/page=52">52</option><option value="/home/page=53">53</option><option value="/home/page=54">54</option><option value="/home/page=55">55</option><option value="/home/page=56">56</option><option value="/home/page=57">57</option><option value="/home/page=58">58</option><option value="/home/page=59">59</option><option value="/home/page=60">60</option><option value="/home/page=61">61</option><option value="/home/page=62">62</option><option value="/home/page=63">63</option><option value="/home/page=64">64</option><option value="/home/page=65">65</option><option value="/home/page=66">66</option><option value="/home/page=67">67</option><option value="/home/page=68">68</option><option value="/home/page=69">69</option><option value="/home/page=70">70</option><option value="/home/page=71">71</option><option value="/home/page=72">72</option><option value="/home/page=73">73</option><option value="/home/page=74">74</option><option value="/home/page=75">75</option><option value="/home/page=76">76</option><option value="/home/page=77">77</option><option value="/home/page=78">78</option><option value="/home/page=79">79</option><option value="/home/page=80">80</option><option value="/home/page=81">81</option><option value="/home/page=82">82</option><option value="/home/page=83">83</option><option value="/home/page=84">84</option><option value="/home/page=85">85</option><option value="/home/page=86">86</option><option value="/home/page=87">87</option><option value="/home/page=88">88</option><option value="/home/page=89">89</option><option value="/home/page=90">90</option><option value="/home/page=91">91</option><option value="/home/page=92">92</option><option value="/home/page=93">93</option><option value="/home/page=94">94</option><option value="/home/page=95">95</option><option value="/home/page=96">96</option><option value="/home/page=97">97</option><option value="/home/page=98">98</option><option value="/home/page=99">99</option></select></form>

 Editor's Picks

 Popular this week

 View by Category

                        <form name="form1">
                        <select onchange="window.open(this.options[this.selectedIndex].value, '_self')" class="form-control">
                            <option>Pick One</option>
                            <option value="/articles/category/17">Coming Soon</option>
<option value="/articles/category/14">Competition</option>
<option value="/articles/category/7">Crowdfunding</option>
<option value="/articles/category/13">Desura</option>
<option value="/articles/category/1">Editorial</option>
<option value="/articles/category/20">FPS</option>
<option value="/articles/category/16">First Look</option>
<option value="/articles/category/9">Free Game</option>
<option value="/articles/category/8">Game Bundle</option>
<option value="/articles/category/4">Game Sale</option>
<option value="/articles/category/6">Indie Game</option>
<option value="/articles/category/18">Indie Game</option>
<option value="/articles/category/3">Interview</option>
<option value="/articles/category/10">MMO</option>
<option value="/articles/category/0">No Category</option>
<option value="/articles/category/11">Open Source</option>
<option value="/articles/category/21">RTS</option>
<option value="/articles/category/2">Review</option>
<option value="/articles/category/5">Steam</option>
<option value="/articles/category/12">Unity3D</option>
<option value="/articles/category/15">Wine</option>

                        </select>
                        </form>

Article Search

Submit Article

                    Tweets by @gamingonlinux

                    GamingOnLinux the Linux Games website, Copyright © GamingOnLinux.com 2009-2014.

Page generated in 0.025 seconds, MySQL queries: 10

What I want is for the right panels width to extend to the end of the carousel, currently it falls short as you can see there is a gap on the right of blank space after the sidebar.

A: I think that the problem is not the right hand panel but a couple of other things.
First, the carousel is inside a .row but not inside a .col-md-12 mean there'll be a negative margin to the sides, but no padding on the col to negate that.
So add that in here:

      ...

Second, you've nested some rows (.row) for your alert boxes.  That's causing them to be pulled out of line because of the negative margin that rows have.  You either need to add a col-md-12 around each alert (because the padding on cols negates the rows negative margin) or you remove the .row completely.  That works because the div is just 100% width of the parent column which is fine.
So remove the row below:

    You have 3 admin items needing review!

Demo

A: Try to define your col-md-3 boostrap is a grid of 12, you have defined mid to be 9
also to avoid the padding of container / row create a .nopadding { padding:0 !important }


text:
Q: How to store zoom state and update incrementally in d3? d3 stores the transform state of an element and updates it when there is a zoom event.
I want to use my own object to store the transform state, and only use the d3 zoom event to update it.
Here's an example of what I've tried to do:
// My transform state object
myTransState = {x:0, y:0, k:1}

onZoomEvent(e){

// Update my transform state object with change
myTransState.x += e.transform.x
myTransState.y += e.transform.y
myTransState.k *= e.transform.k

// Reset d3 transform state
e.transform.x = 0
e.transform.y = 0
e.transform.k = 1

}

This isn't working. The increment in x and y grows large  and the plot moves far away from the mouse pointer.
I know I can use the d3 state transform directly, however I need to track the state myself for some situations (for example, separate x and y scale factors kx and ky).
Why isn't this working as expected? Is there something else that is modifying the d3 transform state after I reset it?

A: Modifying the event is not enough to reset the zoom transform, because d3 does not store the current zoom coordinates in the event.
To reset the transform, you need to call the zoom.transform
selection.call(zoom.transform, zoomIdentity)

Where the selection is the same selection that called selection.call(zoom), and zoomIdentity is the identity transform {x: 0, y:0, z:1}
Be aware that calling zoom.transform will also trigger the onZoomEvent callback. To avoid a infinite loop, you can check if the transform of the event is {x: 0, y: 0, z: 1}, and if it is the callback is cancelled.
  onZoomEvent(e){
    if(e.transform.toString() === zoomIdentity.toString()) {
       return
    }

    // Update my transform state object with change
    myTransState.x += e.transform.x
    myTransState.y += e.transform.y
    myTransState.k *= e.transform.k

    // Reset d3 transform state
    selection.call(zoom.transform, zoomIdentity)
}


text:
Q: element img with SVG Firefox Trying to make compatible all svg's images in different browsers I have an issue with Firefox.
I am using a .SVG image in an element img. Something like that:
<img src="image.svg" />

If you can see the image below,seems that the SVG is repeated. If I will used the svg as background-image, problably I will can do background-repeat: no-repeat, but in this case I need use the svg at img element and can't specify background-repeat to an element img.
How I can fix this? All answers will be apreciate.

A: I'm going to explane this strange case..
This is the code of my SVG
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" id="Capa_1" x="0px" y="0px" width="21.391px" height="18.881px" viewBox="228.645 224.748 21.391 18.881" enable-background="new 228.645 224.748 21.391 18.881" xml:space="preserve" xmlns:xml="http://www.w3.org/XML/1998/namespace">
<g>
    <path fill="#CEE4C4" d="M243.708,230.977c-3.494,0-6.328,2.83-6.328,6.323c0,3.494,2.834,6.328,6.328,6.328   c3.496,0,6.328-2.834,6.328-6.326C250.036,233.808,247.204,230.977,243.708,230.977z M244.437,242.177h-1.508v-1.805h1.508V242.177   z M244.308,239.066h-1.24l-0.129-5.723h1.498L244.308,239.066z"/>
    <g>
        <path fill="#9FAEB1" d="M237.384,237.376c0-0.024-0.004-0.051-0.004-0.076c0-0.627,0.096-1.229,0.266-1.803l-3,2.25v-3h-4v-8h12    v4.324c0.347-0.059,0.699-0.096,1.062-0.096c0.318,0,0.63,0.031,0.938,0.076v-6.305h-16v12h4v4L237.384,237.376z"/>
    </g>
</g>
</svg>

The element SVG measures are 21x19 px.
BUT! the measure of the element SVG  inside  are 22x20 px.
So, if i put the measures of svg (21x19) that don't fix the initial problem, however if i put width and height of the element  (22x20) solves the problem.

A: Ok i see what's your problem now. You should try to add for img tag the exact width and hight of the image you try to add, just to ensure it will display the expected dimension. Try it and see what happens, if not please make a jsfiddle to can help you


text:
Q: Why am I getting wrong count of number of existing files inside a directory using dirent? I wrote a small function that receives a path of a folder and should return the number of files inside it.
For some reason my answer is not correct: When printing it I saw that it prints . and ...
Can someone tell me why? Would decreasing 2 solve it?
Here is the code:
    {
    struct dirent *entry;
    DIR *dirp;
    int fileCount = 0;
    char currPath[MAX_STR];
    dirp = opendir(clientLocalPath);
    printf(" ***** printing files!!!!! ********\n");
    while((entry = readdir(dirp)) != NULL)
    {
            strcpy(currPath, entry->d_name);
            printf("%s\n",currPath);
            fileCount++;

    }
    closedir(dirp);
    return fileCount;
}

A: . is the current directory
.. is the parent directory
These 2 names you will find in every folder while scaning for file. while getting files name you can ignore these two values by checking names in your code.
For example
"..\tmp.txt" specifies a file named tmp.txt located in the parent of the current directory

A: This behaviour is perfectly normal. The . and .. indicate current and parent directories respectively. If you want to ignore them and consider the rest of the files for your fileCount variable, you can do something like this:
while((entry = readdir(dirp)) != NULL)
{
    if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0)
                    printf("\0");
    else
    {
        strcpy(currPath, entry->d_name);
        printf("%s\n",currPath);
        fileCount++;
    }
}

A: This is normal and it happens because both . and .. are part of the directories: . refers to the current one and .. to the parent.
From What is a dot only named folder?:

Every directory contains a . and a .. entry.
. means the directory itself. It is called the current directory.
.. means the directory's parent directory, that is, the directory
  that contains it.

From Why do directory listings contain the current (.) and parent (..) directory?:

Best way is to just strcmp and ignore them, if you don't want to
  list them.


text:
Q: Which environment will work fine for a game like Tic Tac Toe in iOS? I would like to make an iOS game whose features are comparable to that of a simple Tic Tac Toe game. I was wondering that which environment will suit best for my needs.

*

*using UI Cocoa components.

*using Cocos2d.

*Using OpenGL.

I want an easy-to-handle environment.

A: The key point is:

As I'm new to iOS and OpenGL, and game is not that complicated. I want a easy to handle environment.

so I would suggest going for Core Animation. In Core Animation, you could use CALayer to represent tic-tac-toe cells; layout them appropriately; and change they graphical status with an animation. Pretty straightforward.
Cocos2D would also do, since it is a plain 2D game engine, but it is more complex to learn since it will also address requirements for more complex games (hence, it offers a number of abstractions: sprites/nodes/layers/scenes/animations/spritesheets...).
OpenGL would be overkill, but it could be a good choice to learn it.
Also, have a look at this: iOS Development Course Fall 2010 Lecture 14 - Tic-Tac-Toe with Inheritance
From What Is Core Animation?:

Core Animation is a collection of Objective-C classes for graphics rendering, projection, and animation. It provides fluid animations using advanced compositing effects while retaining a hierarchical layer abstraction that is familiar to developers using the Application Kit and Cocoa Touch view architectures.
Dynamic, animated user interfaces are hard to create, but Core Animation makes creating these interfaces easier by providing:

*

*High performance compositing with a simple approachable programming model.

*A familiar view-like abstraction that allows you to create complex user interfaces using a hierarchy of layer objects.

*

*A lightweight data structure. You can display and animate hundreds of layers simultaneously.

*An abstract animation interface that allows animations to run on a separate thread, independent of your application's run loop. Once an animation is configured and starts, Core Animation assumes full responsibility for running it at frame rate.

*Improved application performance. Applications need only redraw content when it changes. Minimal application interaction is required for resizing and providing layout services layers. Core Animation also eliminates application code that runs at the animation frame-rate.

*A flexible layout manager model, including a manager that allows the position and size of a layer to be set relative to attributes of sibling layers.
Using Core Animation, developers can create dynamic user interfaces for their applications without having to use low-level graphics APIs such as OpenGL to get respectable animation performance.


text:
Q: Why does vim-plug set formatoptions for xml files? I installed vim-plug in .vim/autoload/
When I open any XML file and check the :verbose set fo? format options it says:

formatoptions=tcq
   Last set from /usr/share/vim/vimrc

After enabling vim-plug in ~/.vimrc (without plugins):
call plug#begin('~/.vim/plugged')
call plug#end()

I get this output:

formatoptions=croql
   Last set from /usr/share/vim/vim73/ftplugin/xml.vim

Why are the formatoptions different from before?

/usr/share/vim/vim73/ftplugin/xml.vim contains the code below:
setlocal formatoptions-=t
if !exists("g:ft_xml_autocomment") || (g:ft_xml_autocomment == 1)
    setlocal formatoptions+=croql
endif

But g:ft_xml_autocomment is undefined in both cases!


text:
Q: Make React useEffect hook not run on initial render According to the docs:

componentDidUpdate() is invoked immediately after updating occurs. This method is not called for the initial render.

We can use the new useEffect() hook to simulate componentDidUpdate(), but it seems like useEffect() is being ran after every render, even the first time. How do I get it to not run on initial render?
As you can see in the example below, componentDidUpdateFunction is printed during the initial render but componentDidUpdateClass was not printed during the initial render.

function ComponentDidUpdateFunction() {
  const [count, setCount] = React.useState(0);
  React.useEffect(() => {
    console.log("componentDidUpdateFunction");
  });

  return (

componentDidUpdateFunction: {count} times

      <button
        onClick={() => {
          setCount(count + 1);
        }}
      >
        Click Me
      </button>

  );
}

class ComponentDidUpdateClass extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0,
    };
  }

  componentDidUpdate() {
    console.log("componentDidUpdateClass");
  }

  render() {
    return (

componentDidUpdateClass: {this.state.count} times

        <button
          onClick={() => {
            this.setState({ count: this.state.count + 1 });
          }}
        >
          Click Me
        </button>

    );
  }
}

ReactDOM.render(

    <ComponentDidUpdateFunction />
    <ComponentDidUpdateClass />

,
  document.querySelector("#app")
);

A: @ravi, yours doesn't call the passed-in unmount function. Here's a version that's a little more complete:

/**
 * Identical to React.useEffect, except that it never runs on mount. This is
 * the equivalent of the componentDidUpdate lifecycle function.
 *
 * @param {function:function} effect - A useEffect effect.
 * @param {array} [dependencies] - useEffect dependency list.
 */
export const useEffectExceptOnMount = (effect, dependencies) => {
  const mounted = React.useRef(false);
  React.useEffect(() => {
    if (mounted.current) {
      const unmount = effect();
      return () => unmount && unmount();
    } else {
      mounted.current = true;
    }
  }, dependencies);

  // Reset on unmount for the next mount.
  React.useEffect(() => {
    return () => mounted.current = false;
  }, []);
};

A: I made a simple useFirstRender hook to handle cases like focussing a form input:
import { useRef, useEffect } from 'react';

export function useFirstRender() {
  const firstRender = useRef(true);

  useEffect(() => {
    firstRender.current = false;
  }, []);

  return firstRender.current;
}

It starts out as true, then switches to false in the useEffect, which only runs once, and never again.
In your component, use it:
const firstRender = useFirstRender();
const phoneNumberRef = useRef(null);

useEffect(() => {
  if (firstRender || errors.phoneNumber) {
    phoneNumberRef.current.focus();
  }
}, [firstRender, errors.phoneNumber]);

For your case, you would just use if (!firstRender) { ....

A: function useEffectAfterMount(effect, deps) {
  const isMounted = useRef(false);

  useEffect(() => {
    if (isMounted.current) return effect();
    else isMounted.current = true;
  }, deps);

  // reset on unmount; in React 18, components can mount again
  useEffect(() => {
    isMounted.current = false;
  });
}

We need to return what comes back from effect(), because it might be a cleanup function. But we don't need to determine if it is or not. Just pass it on and let useEffect figure it out.
In an earlier version of this post I said resetting the ref (isMounted.current = false) wasn't necessary. But in React 18 it is, because components can remount with their previous state (thanks @Whatabrain).

A: a simple way is to create a let, out of your component and set in to true.
then say if its true set it to false then return (stop) the useEffect function
like that:

    import { useEffect} from 'react';
    //your let must be out of component to avoid re-evaluation

    let isFirst = true

    function App() {
      useEffect(() => {
          if(isFirst){
            isFirst = false
            return
          }

        //your code that don't want to execute at first time
      },[])
      return (

its simple huh...

      );
    }

its  Similar to @Carmine Tambasciabs solution but without using state :)

A: We can use the useRef hook to store any mutable value we like, so we could use that to keep track of if it's the first time the useEffect function is being run.
If we want the effect to run in the same phase that componentDidUpdate does, we can use useLayoutEffect instead.
Example

const { useState, useRef, useLayoutEffect } = React;

function ComponentDidUpdateFunction() {
  const [count, setCount] = useState(0);

  const firstUpdate = useRef(true);
  useLayoutEffect(() => {
    if (firstUpdate.current) {
      firstUpdate.current = false;
      return;
    }

    console.log("componentDidUpdateFunction");
  });

  return (

componentDidUpdateFunction: {count} times

      <button
        onClick={() => {
          setCount(count + 1);
        }}
      >
        Click Me
      </button>

  );
}

ReactDOM.render(
  <ComponentDidUpdateFunction />,
  document.getElementById("app")
);

A: This is the best implementation I've created so far using typescript. Basically, the idea is the same, using the Ref but I'm also considering the callback returned by useEffect to perform cleanup on component unmount.
import {
  useRef,
  EffectCallback,
  DependencyList,
  useEffect
} from 'react';

/**
 * @param effect
 * @param dependencies
 *
 */
export default function useNoInitialEffect(
  effect: EffectCallback,
  dependencies?: DependencyList
) {
  //Preserving the true by default as initial render cycle
  const initialRender = useRef(true);

  useEffect(() => {
    let effectReturns: void | (() => void) = () => {};

    // Updating the ref to false on the first render, causing
    // subsequent render to execute the effect
    if (initialRender.current) {
      initialRender.current = false;
    } else {
      effectReturns = effect();
    }

    // Preserving and allowing the Destructor returned by the effect
    // to execute on component unmount and perform cleanup if
    // required.
    if (effectReturns && typeof effectReturns === 'function') {
      return effectReturns;
    }
    return undefined;
  }, dependencies);
}

You can simply use it, as usual as you use the useEffect hook but this time, it won't run on the initial render. Here is how you can use this hook.
useNoInitialEffect(() => {
  // perform something, returning callback is supported
}, [a, b]);

If you use ESLint and want to use the react-hooks/exhaustive-deps rule for this custom hook:
{
  "rules": {
    // ...
    "react-hooks/exhaustive-deps": ["warn", {
      "additionalHooks": "useNoInitialEffect"
    }]
  }
}

A: I thought creating a custom hook would be overkill and I didn't want to muddle my component's readability by using the useLayoutEffect hook for something unrelated to layouts, so, in my case, I simply checked to see if the value of my stateful variable selectedItem that triggers the useEffect callback is its original value in order to determine if it's the initial render:
export default function MyComponent(props) {
    const [selectedItem, setSelectedItem] = useState(null);

    useEffect(() => {
        if(!selectedItem) return; // If selected item is its initial value (null), don't continue

        //... This will not happen on initial render

    }, [selectedItem]);

    // ...

}

A: Same approach as Tholle's answer, but using useState instead of useRef.
const [skipCount, setSkipCount] = useState(true);

...

useEffect(() => {
    if (skipCount) setSkipCount(false);
    if (!skipCount) runYourFunction();
}, [dependencies])

EDIT
While this also works, it involves updating state which will cause your component to re-render. If all your component's useEffect calls (and also all of its children's) have a dependency array, this doesn't matter. But keep in mind that any useEffect without a dependency array (useEffect(() => {...}) will be run again.
Using and updating useRef will not cause any re-renders.

A: You can turn it into custom hooks, like so:
import React, { useEffect, useRef } from 'react';

const useDidMountEffect = (func, deps) => {
    const didMount = useRef(false);

    useEffect(() => {
        if (didMount.current) func();
        else didMount.current = true;
    }, deps);
}

export default useDidMountEffect;

Usage example:
import React, { useState, useEffect } from 'react';

import useDidMountEffect from '../path/to/useDidMountEffect';

const MyComponent = (props) => {
    const [state, setState] = useState({
        key: false
    });

    useEffect(() => {
        // you know what is this, don't you?
    }, []);

    useDidMountEffect(() => {
        // react please run me if 'key' changes, but not on initial render
    }, [state.key]);

    return (

             ...

    );
}
// ...

A: @MehdiDehghani, your solution work perfectly fine, one addition you have to do is on unmount, reset the didMount.current value to false. When to try to use this custom hook somewhere else, you don't get cache value.
import React, { useEffect, useRef } from 'react';

const useDidMountEffect = (func, deps) => {
    const didMount = useRef(false);

    useEffect(() => {
        let unmount;
        if (didMount.current) unmount = func();
        else didMount.current = true;

        return () => {
            didMount.current = false;
            unmount && unmount();
        }
    }, deps);
}

export default useDidMountEffect;

A: Simplified implementation
import { useRef, useEffect } from 'react';

function MyComp(props) {

  const firstRender = useRef(true);

  useEffect(() => {
    if (firstRender.current) {
      firstRender.current = false;
    } else {
      myProp = 'some val';
    };

  }, [props.myProp])

  return (

      ...

  )

}

A: You can use custom hook to run use effect after mount.
const useEffectAfterMount = (cb, dependencies) => {
  const mounted = useRef(true);

  useEffect(() => {
    if (!mounted.current) {
      return cb();
    }
    mounted.current = false;
  }, dependencies); // eslint-disable-line react-hooks/exhaustive-deps
};

Here is the typescript version:
const useEffectAfterMount = (cb: EffectCallback, dependencies: DependencyList | undefined) => {
  const mounted = useRef(true);

  useEffect(() => {
    if (!mounted.current) {
      return cb();
    }
    mounted.current = false;
  }, dependencies); // eslint-disable-line react-hooks/exhaustive-deps
};

A: For people who are having trouble with React 18 strict mode calling the useeffect on the initial render twice, try this:
// The init variable is necessary if your state is an object/array, because the == operator compares the references, not the actual values.
const init = [];
const [state, setState] = useState(init);
const dummyState = useRef(init);

useEffect(() => {
  // Compare the old state with the new state
  if (dummyState.current == state) {
    // This means that the component is mounting
  } else {
    // This means that the component updated.
    dummyState.current = state;
  }
}, [state]);

Works in development mode...

function App() {
  const init = [];
  const [state, setState] = React.useState(init);
  const dummyState = React.useRef(init);

  React.useEffect(() => {
    if (dummyState.current == state) {
      console.log('mount');
    } else {
      console.log('update');
      dummyState.current = state;
    }
  }, [state]);

  return (
    <button onClick={() => setState([...state, Math.random()])}>Update state </button>
  );
}

ReactDOM.createRoot(document.getElementById("app")).render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);

And in production.

function App() {
  const init = [];
  const [state, setState] = React.useState(init);
  const dummyState = React.useRef(init);

  React.useEffect(() => {
    if (dummyState.current == state) {
      console.log('mount');
    } else {
      console.log('update');
      dummyState.current = state;
    }
  }, [state]);
  return (
    <button onClick={() => setState([...state, Math.random()])}>Update state </button>
    );
}

ReactDOM.createRoot(document.getElementById("app")).render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);

A: If you want to skip the first render, you can create a state "firstRenderDone" and set it to true in the useEffect with empty dependecy list (that works like a didMount). Then, in your other useEffect, you can check if the first render was already done before doing something.
const [firstRenderDone, setFirstRenderDone] = useState(false);

//useEffect with empty dependecy list (that works like a componentDidMount)
useEffect(() => {
  setFirstRenderDone(true);
}, []);

// your other useEffect (that works as componetDidUpdate)
useEffect(() => {
  if(firstRenderDone){
    console.log("componentDidUpdateFunction");
  }
}, [firstRenderDone]);

A: All previous are good, but this can be achieved in a simplier way considering that the action in useEffect can be "skipped" placing an if condition(or any other ) that is basically not run first time, and still with the dependency.
For example I had the case of :

*

*Load data from an API but my title has to be "Loading" till the date were not there, so I have an array, tours that is empty at beginning and show the text "Showing"

*Have a component rendered with different information from those API.

*The user can delete one by one those info, even all making the tour array empty again as the beginning but this time the API fetch is been already done

*Once the tour list is empty by deleting then show another title.

so my "solution" was to create another useState to create a boolean value that change only after the data fetch making another condition in useEffect true in order to run another function that also depend on the tour length.
useEffect(() => {
  if (isTitle) {
    changeTitle(newTitle)
  }else{
    isSetTitle(true)
  }
}, [tours])

here my App.js
import React, { useState, useEffect } from 'react'
import Loading from './Loading'
import Tours from './Tours'

const url = 'API url'

let newTours

function App() {
  const [loading, setLoading ] = useState(true)
  const [tours, setTours] = useState([])
  const [isTitle, isSetTitle] = useState(false)
  const [title, setTitle] = useState("Our Tours")

  const newTitle = "Tours are empty"

  const removeTours = (id) => {
    newTours = tours.filter(tour => ( tour.id !== id))

    return setTours(newTours)
  }

  const changeTitle = (title) =>{
    if(tours.length === 0 && loading === false){
      setTitle(title)
    }
  }

const fetchTours = async () => {
  setLoading(true)

  try {
    const response = await fetch(url)
    const tours = await response.json()
    setLoading(false)
    setTours(tours)
  }catch(error) {
    setLoading(false)
    console.log(error)
  }
}

useEffect(()=>{
  fetchTours()
},[])

useEffect(() => {
  if (isTitle) {
    changeTitle(newTitle)
  }else{
    isSetTitle(true)
  }
}, [tours])

if(loading){
  return (

      <Loading />

  )
}else{
  return (

      <Tours tours={tours} title={title} changeTitle={changeTitle}
removeTours={removeTours} />

  )
 }
}

export default App

A:

    const [dojob, setDojob] = useState(false);

    yourfunction(){
        setDojob(true);
    }

    useEffect(()=>{
        if(dojob){
            yourfunction();
            setDojob(false);
        }
    },[dojob]);


text:
Q: How do I decipher the Select method docs on MSDN? I'm struggling to get my head around LINQ and have come to the conclusion that searching through dozens of examples until I find one that is near to my own application in C# is not teaching me how to fish.
So back to the docs where I immediately hit a brick wall.
Can someone please help me decipher the Enumerable.Select method as presented here on msdn
http://msdn.microsoft.com/en-us/library/bb548891.aspx and given as a tip by Intellisense?
Enumerable.Select(TSource, TResult) Method (IEnumerable(TSource>), Func(TSource, TResult))
Here is the same line broken down with line numbers if it helps to refer:

*

*Enumerable.Select

*(TSource, TResult)

*Method

*(IEnumerable(TSource>),

*Func

*(TSource, TResult))

A: It might help to look at the definition of this method in C#, from the MSDN article you refer to:
public static IEnumerable<TResult> Select<TSource, TResult>(
    this IEnumerable<TSource> source,
    Func<TSource, TResult> selector
)

The <angle brackets> denote the type parameters for this generic method, and we can start to explore the purpose of the method simply by looking at what the type parameters are doing.
We begin by looking at the name of the generic method:
Select<TSource, TResult>

This tells us that the method called Select deals with two different types:

*

*The type TSource; and

*The type TResult
Let's look at the parameters:

*

*The first parameter is IEnumerable<TSource> source — a source, providing a TSource enumeration.

*The second parameter is Func<TSource, TResult> selector — a selector function that takes a TSource and turns it into a TResult. (This can be verified by exploring the definition of Func)

Then we look at its return value:
IEnumerable<TResult>

We now know this method will return a TResult enumeration.
To summarise, we have a function that takes an enumeration of TSource, and a selector function that takes individual TSource items and returns TResult items, and then the whole select function returns an enumeration of TResult.
An example:
To put this into concrete terms, lets say that TSource is of type Person (a class representing a person, with a name, age, gender, etc), and TResult is of type String (representing the person's name). We're going to give the Select function a list of Persons, and a function that, given a Person will select just their name. As the output of calling this Select function, we will get a list of Strings containing just the names of the people.
Aside:
The last piece of the puzzle from the original method signature, at the top, is the this keyword before the first parameter. This is part of the syntax for defining Extension Methods, and all it essentially means is that instead of calling the static Select method (passing in your source enumeration, and selector function) you can just invoke the Select method directly on your enumeration, just as if it had a Select method (and pass in only one parameter — the selector function).
I hope this makes it clearer for you?

A: The way to think of Select is as mapping each element of a sequence.  Hence:
Enumerable.Select<TSource, TResult>: the Select method is parameterised by its source and result types (the type of thing you are mapping and the type you are mapping it to)
IEnumerable<TSource>: the sequence of things to map
Func<TSource, TResult>: the mapping function, that will be applied to each element of the source sequence
The result being an IEnumerable<TResult>, a sequence of mapping results.
For example, you could imagine (as a trivial example) mapping a sequence of integers to the string representations:
IEnumerable<string> strings = ints.Select(i => i.ToString());

Here ints is the IEnumerable<TSource> (IEnumerable<int>) and i => i.ToString() is the Func<TSource, TResult> (Func<int, string>).

A: I'm of the opinion that the later chapters of C# in Depth do a good job of explaining LINQ, and what it all means. Plus the rest of the book teaches a lof of other very useful C# knowledge.


text:
Q: noUiSlider + Rails 7 app = Uncaught ReferenceError: noUiSlider is not defined I have a Rails 7 application and I am trying to install noUiSlider (https://refreshless.com/nouislider/).  Installed via yarn and can confirm the source files are in my app.  In my /app/javascript/application.js file I added:
import noUiSlider from 'nouislider'

yet when I try and initialize a slider I get:
Uncaught ReferenceError: noUiSlider is not defined

I can see in my application JS file:
  // ../../node_modules/nouislider/dist/nouislider.js
  var require_nouislider = __commonJS({
    "../../node_modules/nouislider/dist/nouislider.js"(exports2, module4) {
      (function(global, factory) {
        typeof exports2 === "object" && typeof module4 !== "undefined" ? factory(exports2) : typeof define === "function" && define.amd ? define(["exports"], factory) : (global = typeof globalThis !== "undefined" ? globalThis : global || self, factory(global.noUiSlider = {}));
      })(exports2, function(exports3) {
        "use strict";
        exports3.PipsMode = void 0;
....

I seem to be missing something obvious here or a Rails 7 specific issue.


text:
Q: При запросе telebot показывает ошибку import telebot
from telebot import types
from pyowm import OWM
from pyowm.utils import config
from pyowm.utils import timestamps

city = ''
message = ''

bot = telebot.TeleBot("***")

# Кнопки

@bot.message_handler(commands=['start'])
def start(message):
    markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
    itemhelp = types.KeyboardButton('/help')
    itemweather = types.KeyboardButton('/weather')
    markup.add(itemhelp, itemweather)
    bot.send_message(message.chat.id, 'Выбери команду:'.format(message.from_user), reply_markup=markup)

@bot.message_handler(commands=['help'])
def send_welcome(message):
    bot.reply_to(message, 'Ты можешь у меня узнать прогноз погоды на сегодня, просто напиши команду: "/weather"')

@bot.message_handler(func=lambda message: True)
def echo_all(message):
    if message.text == '/weather':
        bot.send_message(message.from_user.id, 'В каком городе хочешь узнать погоду?')
        bot.register_next_step_handler(message, reg_city)

def reg_city(message):
    global city
    city = message.text

    # Уникальный ключ API для получения информации с сайта 'ОpenWeather'

    owm = OWM('***')
    mgr = owm.weather_manager()

    observation = mgr.weather_at_place(city)
    w = observation.weather

    # Характеристика погоды

    temperature = w.temperature('celsius')['temp']
    temperature2 = w.temperature('celsius')['temp_max']
    humidity = w.humidity
    speed = w.wind()['speed']

    # Подсказки как одеваться в зависимости от температуры воздуха

    if temperature >= 10 and temperature <= 15:
        bot.reply_to(message, 'Можешь одеваться чутка свободнеe!')
    elif temperature >= 0 and temperature <= 9:
        bot.reply_to(message, 'Одевайся тепло, на улице холодно и следи за ветром. Он коварный.')
    elif temperature >= -10 and temperature <= -1:
        bot.reply_to(message, 'Не ну это пипец, очень тепло одевайся, можно лего заболеть.')
    elif temperature >= 16:
        bot.reply_to(message, 'Ух ты, на улице очень тепло, одевайся как хочешь.')

    #вывод погоды:

    bot.send_message(message, f'В городе {city} сейчас: {temperature} градусов, максимальная температура: {temperature2} по Цельсию, {humidity} % влажности, Скорость ветра: {speed} М/С.' )

bot.infinity_polling()

Ошибка в том, что после запроса /weather и ввода города выдает ошибку с api bot'а, пересоздавал ключ но бесполезно.


text:
Q: How to get the img elements from within a div tag using JavaScript? Below is my HTML:

Using:
document.getelementById("mover");

only gives me this div, how can I get all the images from this div using JavaScript?

A: Let me know if this works out for you:


text:
Q: Set up an automated approval workflow I have a set of documents which require approval, they are going to be put onto my sharepoint site so that when users log on they simply select the document which is required and an email is sent to the appropriate person for approval.
How can I go about setting this up?  As from my understanding users have to keep uploading their documents to the sharepoint list which contains the workflow.
An ideal example would be:
The document 'Database approval form' is already in my library.
1) The user goes onto my sharepoint site and selects the document.
2) An email is sent to management for approval.
3) Management approves.
4) Workflow complete.

Notice that there is no need for the user to upload the 'Database approval form' to the library, as it already exisits.
Any help is much apprechiated.
Thanks,
Sandeep

A: If I understand you correctly, you can create a simple sharepoint designer workflow and publish that on your site.


text:
Q: Presiono boton submit y me cambia de tab Hola tengo 2 tabs en una pagina con formularios y botones de consulta  en cada una ..al presionar el boton del tab2 realiza la consulta pero se coloca en el tab 1 y tengo que hacer click en el tab 2 para ver el resultado...como puedo resolver esto
agrego codigo

Anual x Area

Tipo de Combustible

Estadística de área por año

Combustibles DIESEL Y NAFTA

        <form  method="POST" action="chartarea.php" name="frm">

                          Seleccione Area
                          <select class="form-control" name="area" id="area" autofocus>
                             <option></option>
                             <option>SERVICIOS PUBLICOS</option>
                             <option>ESPACIOS VERDES</option>
                             <option>OBRAS MUNICIPALES</option>
                             <option>OBRAS PRIVADAS</option>
                             <option>PARQUE AUTOMOTOR</option>
                             <option>SEGURIDAD</option>
                          </select>

                        Seleccione año
                        <select class="form-control"  name="año" id="año" value="<?php if (isset($año)) echo $año ?>">
                           <option></option>
                           <option>2016</option>
                           <option>2017</option>
                           <option>2018</option>

                        </select>

                    <button name="btConsulta" class="btn btn-primary" type="submit">Consulta</button>
                       <button class="btn btn-default icon-btn" href="#" class="fa fa-fw fa-lg fa-times-circle" type="submit">Nuevo</button>
                    <button class="btn btn-primary icon-btn" type="button">Salir </button>

          </form>

Comparativo Anual

        <button id="btnp" class="btn btn-success">Imprimir</button>

Estadística comparativa x área

Combustibles DIESEL O NAFTA

        <form  method="POST" action="chartarea.php" name="frm">

                          Seleccione Area
                          <select class="form-control" name="area2" id="area2" autofocus>
                             <option></option>
                             <option>SERVICIOS PUBLICOS</option>
                             <option>ESPACIOS VERDES</option>
                             <option>OBRAS MUNICIPALES</option>
                             <option>OBRAS PRIVADAS</option>
                             <option>PARQUE AUTOMOTOR</option>
                             <option>SEGURIDAD</option>
                          </select>

                        Seleccione Combustible
                        <select class="form-control"  name="combus" id="combus" value="<?php if (isset($año)) echo $año ?>">
                           <option></option>
                           <option>TODO DIESEL</option>
                           <option>TODO NAFTA</option>

                        </select>

                        <?php echo 'Iniciando ejecución
';
                        include './prueba.php';
                        ?>

                    <button name="btConsulta" class="btn btn-primary" type="submit">Consulta</button>
                       <button class="btn btn-default icon-btn" href="#" class="fa fa-fw fa-lg fa-times-circle" type="submit">Nuevo</button>
                    <button class="btn btn-primary icon-btn" type="button">Salir </button>

          </form>

Comparativo Anual

        <button id="btnp" class="btn btn-success">Imprimir</button>

los tabs se llaman home y menu1 y cuando presiono el boton btConsulta me devuelve al tab home y deberia quedarse en el tab menu1...Desde ya gracias

A: El problema es la clase active.  Cada vez que haces un POST debes de chequear de donde viene ese POST y agregar la clase active respectivamente asi:

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

  <li class="<?php if (!isset($_POST['combus'])) echo 'active' ?>">Anual x Area

  <li class="<?php if (isset($_POST['combus'])) echo 'active' ?>">Tipo de Combustible

Estadística de área por año

Combustibles DIESEL Y NAFTA

        <form  method="POST" action="chartarea.php" name="frm">

                          Seleccione Area
                          <select class="form-control" name="area" id="area" autofocus>
                             <option></option>
                             <option>SERVICIOS PUBLICOS</option>
                             <option>ESPACIOS VERDES</option>
                             <option>OBRAS MUNICIPALES</option>
                             <option>OBRAS PRIVADAS</option>
                             <option>PARQUE AUTOMOTOR</option>
                             <option>SEGURIDAD</option>
                          </select>

                        Seleccione año
                        <select class="form-control"  name="año" id="año" value="<?php if (isset($año)) echo $año ?>">
                           <option></option>
                           <option>2016</option>
                           <option>2017</option>
                           <option>2018</option>

                        </select>

                    <button name="btConsulta" class="btn btn-primary" type="submit">Consulta</button>
                       <button class="btn btn-default icon-btn" href="#" class="fa fa-fw fa-lg fa-times-circle" type="submit">Nuevo</button>
                    <button class="btn btn-primary icon-btn" type="button">Salir </button>

          </form>

Comparativo Anual

        <button id="btnp" class="btn btn-success">Imprimir</button>

Estadística comparativa x área

Combustibles DIESEL O NAFTA

        <form  method="POST" action="chartarea.php" name="frm">

                          Seleccione Area
                          <select class="form-control" name="area2" id="area2" autofocus>
                             <option></option>
                             <option>SERVICIOS PUBLICOS</option>
                             <option>ESPACIOS VERDES</option>
                             <option>OBRAS MUNICIPALES</option>
                             <option>OBRAS PRIVADAS</option>
                             <option>PARQUE AUTOMOTOR</option>
                             <option>SEGURIDAD</option>
                          </select>

                        Seleccione Combustible
                        <select class="form-control"  name="combus" id="combus" value="<?php if (isset($año)) echo $año ?>">
                           <option></option>
                           <option>TODO DIESEL</option>
                           <option>TODO NAFTA</option>

                        </select>

                        <?php echo 'Iniciando ejecución
';
                        include './prueba.php';
                        ?>

                    <button name="btConsulta" class="btn btn-primary" type="submit">Consulta</button>
                       <button class="btn btn-default icon-btn" href="#" class="fa fa-fw fa-lg fa-times-circle" type="submit">Nuevo</button>
                    <button class="btn btn-primary icon-btn" type="button">Salir </button>

          </form>

Comparativo Anual

        <button id="btnp" class="btn btn-success">Imprimir</button>


text:
Q: How do I study Stein & Shakarchi's Complex Analysis I'm currently self-studying some complex analysis. My background is limited: single- and multivariable calculus, linear algebra, introductory Fourier analysis and matrix theory. Each course, with multivariable calculus being a bit of an exception, has emphasized theory and proofs. I've also done the first four chapters of "Baby Rudin" in my spare time.
The complex analysis book by Stein and Shakarchi is interesting. At times, the book omits quite a few steps that are not so obvious to me. I'm not unfamiliar with this from Rudin who I found was very clear despite the rather terse style. This book will sometimes omit more than I would like. For example, on pages 42-45 the book gives two examples of how real integrals can be solved using Cauchy's theorem, and I had to do a significant amount of filling in the steps and this made me kind of lose track of the bigger idea. I don't like being spoon-fed things because I like to think but at times filling in the steps too much gets in the way of the learning. At least this is how I experience it.
My gripe with the book, however, is with the exercises. Many of the exercises, I find, are very difficult. With Rudin, I struggled because the material was abstract: working so rigorously in general metric spaces was extremely challenging for me but I still managed to do at least half the exercises in each chapter. I can at best a third of the exercises in S&S.
Any advice on how to better absorb the material in this book? It seems to have a pretty interesting approach with many interesting topics (Zeta function, prime number theorem, Riemann mapping theorem, elliptic functions) including some that appear early (Runge's theorem, Hadamard's factorization theorem). So there's plenty of wonderful mathematics here but the exercises are making studying this terribly difficult.

A: Generally, one takes a "complex variables" course before taking "complex analysis", just as one takes calculus before taking real analysis. So it kind of depends on what your goal is. If you want to learn how to deal with complex functions, like taking derivatives, path integrals, infinite series etc. I would buy a book with "complex variables" or "theory of functions of a complex variable" in the title. A complex analysis book is going to be driven more towards theorem proving. Generally the proofs you get in a calculus class (like calc I, calc II, calc III) are not really proofs at all but more
like proof-sketches. In general it takes an entire semester of real analysis (sometimes called advanced calculus) to prove all the results in a semester of calculus. For instance, in real analysis I you generally prove all the results from Cal I. I can't speak to your class in particular but there just really isn't enough time in a semester to do all that. Generally they teach you how to use calculus first, as that's all a lot of professions need, and then they leave the rigorous development of calculus to later courses. It's similar with complex functions. You've bought the real analysis I analog of complex functions and not the Cal I analog of complex functions. The author is going to assume you are very experienced in mathematical thinking/proofs and is going to make leaps in certain areas based on that assumption. If your goal is theorem proving, I would buy a book on real analysis first ( I probably wouldn't go with rudin), as certain results from it are going to be pre-requisites in a sense, and possibly a book on theorem proving. "Mathematical thinking: Logic and Proofs) is a good one. In general Math Majors will take a "proofs course" on how to write proofs and proof methods/strategies prior to taking theorem driven courses like analysis and abstract algebra.
I should add that as a math major I maintained a perfect gpa in my classes with virtually no attendance. I just read the book. So it is certainly doable. That is, you don't need to actually take the class in order to learn the material. I wouldn't get discouraged in that sense. The one nice thing about learning it at a university is the sequence/order in which you should study certain material is laid out for you. It's going to be extremely difficult to follow a complex analysis text without having learned real analysis first.


text:
Q: Can we see when was the last time a permission set license was used in salesforce We have limited number of permission set licences and don't want to buy new licences. So i wanted pulled all the users using that permission set licence using soql query.
SELECT Name, Id FROM User WHERE Id IN
(SELECT AssigneeId FROM PermissionSetLicenseAssign WHERE PermissionSetLicense.MasterLabel ='Sales Console User') AND
IsActive=true
ORDER BY Name

But lets say out of all the assigned users to this permission set only some of them has been actually using it. So i want to see who is actually using assigned licences. So that i can remove licences from those users who are not actually using it; and then assign those license to users who would use them.
As per my research and knowledge its not possible but want community experts to confirm.
Regards

A: In theory, Event Monitoring could help you, but you'd have to enable it, set up the logs, and wait a while, plus figure out how to parse the data. Basically, Event Monitoring can allow you to see which resources users are using.
If I were in a situation where I needed to do something like this, I'd probably create some sort of page that users could use to request permission to a license, which would enable the user to do so, and then automatically disable the license after a period of time, like 30 days or so. Users that are still using the feature would have to re-enable it every thirty days, and those that stop using it would eventually have their licenses revoked.
Other than that, I don't have a long-term solution that would work besides Event Monitoring, and it would take some effort to set up this feature and build the automation you'd want to have to keep your data current. And, of course, make sure you're removing this license from deactivated users so they don't continue to count towards your limit; we currently have a trigger that removes all feature licenses and permission sets upon deactivation to keep our license count down.


text:
Q: What determines priority in protocol conformance? just curious about something.
private enum CodingKeys: String, CodingKey {
    case id = "page"
}

If I were to place String after the CodingKey protocol I would get an error saying I need to place String before.. well what determines the priority and why does that even matter? Thanks in advance.

A: Protocol conformance order does not matter. In your case you are getting an error when you place String after CodingKey is because String is not a protocol. It is a struct. Look at the error message what you get in Xcode:

Raw type 'String' must appear first in the enum inheritance clause

By placing String after the enum declaration will define its raw value.
To prove the point let's define two protocols:
protocol Protocol1 { }

protocol Protocol2 { }

And try to change the order they conform to your CodingKeys enum. This would be valid:
private enum CodingKeys: String, CodingKey, Protocol1, Protocol2 {
    case id = "page"
}

And this is valid too:
private enum CodingKeys: String, CodingKey, Protocol2, Protocol1 {
    case id = "page"
}

A: It's a language requirement that for a declaration of Enumerations with Cases of a Raw-Value Type the raw-value type must come before any adopted protocol.
See https://docs.swift.org/swift-book/ReferenceManual/Declarations.html#ID364


text:
Q: Converting RGB Colors to closest ACI Color in C# I am currently writing a Programm that interacts with dxf files. Therefore I need a Routine that takes RGB Color Values and gives back the closest Color in the AutoCAD Color Index (ACI)
Has anybody some Code or an example how to do that?   It would be nice if it was in C#, but it is not necessary.
Thanks in advance.

A: Take the RGB values of all the ACI colors from some source (for example http://www.jtbworld.com/lisp/DisplayColorProperties.htm) and create an array of ACI colors. To get an ACI color by index, simply pick the color from that list.
To do a "closest" match backwards lookup from RGB, simply do a pass over that array and return the color with minimum distance (for example by checking the squared distances of the 3 color channels:  if your color is r,g,b and the aci color is R,G,B then the distance is
dist = (r-R)*(r-R) + (g-G)*(g-G) + (b-B)*(b-B);

Whichever color in the ACI array that has the smallest dist, is the closest match to r,g,b.
Edit: as has been pointed out: RGB distance isn't good as a visual/perceptive difference. To match for visual difference, convert to HSV/HSL or if you are really ambitious a more exotic color space like CIE XYZ where "distance" closely represents similarity. There are good libraries these days for color space conversion such as Colorful https://www.nuget.org/packages/Colourful/

A: I wouldn't bother with a hard-coded array of ACI colors as Anders proposes. You can get an AutoCAD Color object from each legal index and extract the RGB values from that as a System.Drawing.Color with the ColorValue property.
Here's a full solution based on the rest of Anders' response, substituting Math.Pow(r - R, 2) for (r - R)*(r - R) since it seems to me to more clearly express the Pythagorean intent of the "distance" calculation.
byte r = 1, g = 203, b = 103; // input color
double minDist = double.MaxValue;
short match = 0; // this will end up with our answer
for (short i = 1; i <= 255; ++i)
{
    var color = Autodesk.AutoCAD.Colors.Color.FromColorIndex(ColorMethod.ByAci, i);
    System.Drawing.Color rgb = color.ColorValue;
    double dist =
        Math.Pow(r - rgb.R, 2) +
        Math.Pow(g - rgb.G, 2) +
        Math.Pow(b - rgb.B, 2);
    if (dist < minDist)
    {
        minDist = dist;
        match = i;
    }
}

A: Here is how you convert RGB to ACI
var color = Autodesk.AutoCAD.Colors.Color(r, g, b);

A: I am not sure if this thread/question is still valid but I have also been looking for some way to convert a color to ACI on the internet, but failed. In my case, I need a method that preferably avoids external libraries and CAD functions.
I cannot help with C#. I normally work with Lazarus/Free Pascal and after lots of trial I came down with a function that seems to be working quite well for me. So I am posting my codes here in case they can be helpful to you or to someone else.
My Codes are as follow:
Function RGB2ACIDXFColor(MyColor : TColor) : Integer ;
Var
   OldCol, LowR, MidR, HiR : String ;
   RCol, GCol, BCol, LowCol, MidCol, HiCol : Integer ;
   StPt, HRatio, VRatio, Hemis : Integer ;
Begin
Result := 10 ;
{Break Color Component (BGR Color)}
{IntToHex & Hex2Dec are functions from Lazarus Libraries}
OldCol := IntToHex(MyColor,6) ;
BCol := Hex2Dec(Copy(OldCol,1,2)) ;
GCol := Hex2Dec(Copy(OldCol,3,2)) ;
RCol := Hex2Dec(Copy(OldCol,5,2)) ;

{Find Color Component Priorities}
LowCol := RCol ;
LowR := 'R' ;
If (GCol < LowCol) Then
Begin
     LowCol := GCol ;
     LowR := 'G' ;
End; //If
If (BCol < LowCol) Then
Begin
     LowCol := BCol ;
     LowR := 'B' ;
End; //If

HiCol := RCol ;
HiR := 'R' ;
If (GCol > HiCol) Then
Begin
     HiCol := GCol ;
     HiR := 'G' ;
End; //If
If (BCol > HiCol) Then
Begin
     HiCol := BCol ;
     HiR := 'B' ;
End; //If

MidCol := GCol ;
MidR := 'G' ;
If ((HiR = 'G') AND (LowR = 'R')) OR
   ((HiR = 'R') AND (LowR = 'G')) Then
Begin
     MidCol := BCol ;
     MidR := 'B' ;
End; //If
If ((HiR = 'G') AND (LowR = 'B')) OR
   ((HiR = 'B') AND (LowR = 'G')) Then
Begin
     MidCol := RCol ;
     MidR := 'R' ;
End; //If

{Refer to CAD color table}
{Find Color Row}
VRatio := Round((5 * (255 - HiCol)) / 255) ;
VRatio *= 2 ;
{Find Color Hemisphere}
If (LowCol = 0) Then Hemis := 0 Else Hemis := 1 ;

{Find Color Start Column And Incrementation}
If (LowR = 'B') Then
Begin
     HRatio := Round((8 * GCol) / (GCol + RCol)) ;
     Result := 10 ;
End; //If
If (LowR = 'G') Then
Begin
     HRatio := Round((8 * RCol) / (RCol + BCol)) ;
     Result := 170 ;
End; //If
If (LowR = 'R') Then
Begin
     HRatio := Round((8 * BCol) / (BCol + GCol)) ;
     Result := 90 ;
End; //If

HRatio *= 10 ;
Result += HRatio + VRatio + Hemis ;
If (Result > 249) Then Result -= 240 ;
End; //Sub

I am sure you will be able to translate that into C#, and hope that this will be useful to somebody.
Cheers,
J-Eric J.


text:
Q: Swift 3- Displaying a list of previously shown local notifications within the UI I am wondering if there is a way to show notifications within the user interface of my swift app. I have background notifications working however I want to see a list of previously alerted notifications in a tableview/viewController, sort of like a mini notification center.
Any help would be appreciated!


text:
Q: Java Kryo weird behavior depending on String length I'm serializing an object into a file using Kryo 2.22 library (I'm using the UnsafeInput/Output for performance).
My object contains many fields including 1 String. When this string contains up to ~35 characters, no problem. Once I double this to ~70 characters, I get the following exception when deserializing from the file:
Exception in thread "main" com.esotericsoftware.kryo.KryoException: Encountered unregistered class ID: 63
Serialization trace:
handCards (vo.ShortHandVO)
    at com.esotericsoftware.kryo.util.DefaultClassResolver.readClass(DefaultClassResolver.java:119)

When doubling the String's length, I just copied the initial content (i.e. no additional / special characters introduced).
My first guess was thus that it is related to the increased object size: I doubled the Kryo buffer size but the exception is still thrown.
I have now lost hours finding the problem and I'm getting hopeless. Any hint / suggestion would be very much appreciated !
Many thanks,
Thomas
UPDATE: I finally found the issue: I was serializing a child class and deserializing the parent class. What didn't help is that Kryo inconsistently throws an exception (in this case, it was dependent on the String's size)


text:
Q: Install nuget package to a custom folder I have created an ASP.NET 5 app in Visual Studio Community Edition. Then I tried to install the nugget package angularjs.TypeScript.DefinitelyTyped using the command Install-Package angularjs.TypeScript.DefinitelyTyped as well as through the NuGet Package Manager. Both these commands dropped the package in the C:\Users\john\.dnx\packages folder.
I changed the repositoryPath in the nuget.config. Still the packages are saved in the same folders and not under the project.
How can I save the nuget packages under the project and not under c:\users.
<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <packageSources>
    <!--To inherit the global NuGet package sources remove the <clear/> line below -->
    <clear />
    <add key="api.nuget.org" value="https://api.nuget.org/v3/index.json" />
  </packageSources>
  <config>
    <add key="repositoryPath" value="C:\Projects\HelloWorld\src\Scripts"/>
  </config>
</configuration>

This is where the packages are dropped.

C:\Users\john\.dnx\packages\angularjs.TypeScript.DefinitelyTyped\4.2.8

But I want it under C:\Projects\HelloWorld\src

A: This is part of the not very well documented global.json. This global.json file creates a packages sub dir relative to it, where all the nuget packages end up when you restore them.
{
    "packages": "packages",
    "sdk": {
        "version": "1.0.0-beta8",
        "runtime": "coreclr",
        "architecture": "x64"
    }
}


text:
Q: How to diagnose XSLT problems with Firefox? Is there a way to see error messages / debug information on what happens when Firefox 3 applies an XSLT transformation? In Firefox I am getting only the content of the text nodes of the XML document. The stylesheet is in the same directory and is bound with <?xml-stylesheet ...>. In Internet Exporer it works fine and Altova XML Spy does not complain, either. I just don't know how to find out what's wrong.

A: It turned out that the culprit was the NoScript plugin. In case of XSLT errors you would usually get an error page as well as an entry in the error console in the extras menu. But all I got in this case is a crossed out icon in the status bar. 8-}


text:
Q: What is Pressley and Segal's "basic inner product" for compact simple Lie algebras of types B and C? In Pressley and Segal's book Loop Groups, they define a "basic inner product" $\langle-,-\rangle$ on a simple Lie algebra to be (minus) the Killing form scaled so that $\langle h_\alpha,h_\alpha\rangle=2$ where $h_\alpha$ is the coroot associated to a long root.
[Aside I believe there is some terminological confusion possible here: they surely mean $h_\alpha$ to be an element of the Lie algebra, rather than an element of $\mathfrak{t}^*$; Terry Tao defines a coroot to be such a thing, appropriately scaled. But others take a coroot to be a rescaled root, for instance Wikipedia.]
They give the examples of $\mathfrak{su}(n)$ and $\mathfrak{so}(2n)$, which are $-\mathrm{tr}(XY)$ and $-\frac12\mathrm{tr}(XY)$, respectively. To avoid confusion, this trace is taken in the defining representation, thinking of these as matrix Lie groups.
But I haven't been able to find a source that gives the basic inner product for $\mathfrak{so}(2n+1)$ or $\mathfrak{sp}(n)$, where the latter are given as $n\times n$ quaternionic matrices. Once one knows the appropriate matrices $h_\alpha$, then it is obvious. And it is sufficient to know these for low ranks, for instance $\mathfrak{so}(5)$, since then matters stablise.
I tried asking for these actual matrices over at M.SE, but despite rather a detailed answer, I still have no joy, as it presumes a lot of "common knowledge" of Lie theory I don't have, and also is slightly loose with terminology and suggestions. I was hoping for something super explicit like writing out the analogues of the Pauli matrices. This seemed like material too basic for MO, but despite a lot of searching, no lecture notes or textbook I've found actually gives this information! Nor have I found student exercises that ask for them. To me this seems like a perfect example of what MO was intended for: a place for researchers to ask colleagues about a basic fact they need from an area they are unfamiliar with. So I'm cutting my losses, forgetting the exercise of trying to work this stuff out for myself, and asking outright:

What is the basic inner product on $\mathfrak{so}(2n+1)$ and $\mathfrak{sp}(n)$?

My motivation is that eventually I'm going to be doing physics-style calculations, and need explicit representatives for absolutely everything. So a characterisation in terms of anything else is insufficient: I want a formula. A reference to a place where this is recorded in the literature would be the best answer, but I despair that such a thing exists.

A: Section 4 of
Gawȩdzki, Krzysztof; Reis, Nuno, Basic gerbe over non-simply connected compact groups, J. Geom. Phys. 50, No. 1-4, 28-55 (2004). ZBL1067.22009.
lists, in an absolutely concrete way, the simple Lie algebras realized as matrix Lie algebras, together with all roots and coroots. From these you can get the normalization.
For example, let's look at $\mathfrak{so}(2n+1)$. Let $e_i$ be the $(2r+1)\times (2r+1)$ matrix with a block
$$
\begin{pmatrix}0 &-1\\1& 0\end{pmatrix}
$$
on the diagonal at the $(2i-1)$th and $2i$th position. Then, the roots are the matrices $\pm e_i \pm e_j$ for $i\neq j$ and $\pm e_i$, and the coroots are $\pm e_i \pm e_j$ for $i\neq j$ and $\pm 2e_i$. You can check that $\mathrm{tr}(X^2)=-4$ for all coroots $X$. Thus, the basic inner product for $\mathfrak{so}(2n+1)$ is
$$
-\frac{1}{2}\mathrm{tr}(XY)
$$
just as in the even case.

A: I found a reference that gave the correct inner products explicitly, without requiring the reader to assemble the relevant facts: Chapter II, section 1.2 (bottom of page 583) of:

*

*McKenzie Y. Wang, Wolfgang Ziller, On normal homogeneous Einstein manifolds, Annales scientifiques de l'École Normale Supérieure, Série 4, Tome 18 (1985) no. 4, pp. 563-633. https://doi.org/10.24033/asens.1497
Giving:

*

*$\mathfrak{su}(n)$: $-\mathrm{tr}(AB)$

*$\mathfrak{so}(n)$ ($n\geq 5$): $-\frac12 \mathrm{tr}(AB)$; and for $\mathfrak{so}(3)$: $-\frac14 \mathrm{tr}(AB)$

*$\mathfrak{sp}(n)$: $- \mathrm{Tr}(AB)$
Here the trace $\mathrm{Tr}$ for quaternion matrices is the reduced trace, namely $\mathrm{Tr}(X) = 2\Re \mathrm{tr}_{\mathbb{H}}(X)$, which can be checked by looking at the Dynkin index of the embedding $\mathfrak{sp}(2) \hookrightarrow \mathfrak{su}(4)$, which is 1, and the index of the standard embeddings $\mathfrak{sp}(n) \hookrightarrow \mathfrak{su}(n+1)$ (also 1).


text:
Q: creating JPA annotated entity for join table using only the ID fields I'm trying to figure out a cleaner way of saving a join table back to the database using only the entity id of the two joined tables.  I can make my code work as is, but I feel like there should be a cleaner manner.
Imagine I have an entity which represents a simple sql join table, so something like this:
@Entity
@Table(name = "FOOBAR")
public class FooBar{

    @ManyToOne(fetch = FetchType.Lazy)
    @JoinColumn(name = "FOO_ID)
    public Foo foo;

    @ManyToOne(fetch = FetchType.Lazy)
    @JoinColumn(name = "BAR_ID)
    public Bar bar;

    public FooBar(Foo foo, Bar bar){
       this.foo=foo;
       this.bar=bar;
    }
}

I have a method which takes a Foo id and a Bar id, and wants to pass a FooBar object to my save method to save the join.
A naive implementation would query the database to find the Foo and Bar objects based off of their ids, pass those into the FooBar constructor, and then pass the new FooBar to the save method.
However, this is silly, the only things my join table needs is the foo and bar ids, not the full DB objects.  I have everything I need already without hitting the DB to fetch Foo and Bar.
In fact I could simply construct a Foo object and bar object using their a public ID, ignoring all the other fields of the objects, create a FooBar object from these two 'empty' foo and bar objects, and pass that to save and it would work just fine without extra DB hits.
However, it somehow feels a little unclean to do this.  I'm creating two 'dummy' objects this way.  My foo and bar objects may have some nullable = false columns which my DB contract promises will never be null, so it feels wrong constructing a foo object that does have null fields for these columns; as if I'm breaking the contract for these objects.  I don't want a constructor for either object that accepts only an ID because; I want to force them to be constructed in a manner that abides by my contract any time someone constructs them.  I would prefer not to have to knowingly create objects that violate my promise.
I'm wondering if there is a way through JPA, or some quickly written abstraction I could do, to build my FooBar object using only the foo and bar ids in a way that is clean and communicative and does not violate any of the Foo/Bar constraints.  After all since both Foo and Bar are lazy loaded when I first get a FooBar object all it really contains are the foo and bar ids until I call the getter; so I contain as much information already as a FooBar object from the DB would have.
can I create a FooBar object with only their ID and have that object tied to the DB, so it would lazy load the Foo and Bar objects if the getter were called just like a FooBar I get from the DB does?

A: Having a class for a join table is overkill.
JPA has the ManyToMany annotation, which creates the relationship for you.
You basically need to choose one of the entities to "own" the relationship.  This is more or less which class defines the table being used for the join.
In this case, I'll choose Foo as the one that owns the relationship.
In Foo, you can do this:
@ManyToMany
@JoinTable(name="FOOBAR", joinColumns=@JoinColumn(name="FOO_ID"),
    inverseJoinColumns=@JoinColumn(name="BAR_ID"))
public Set<Bar> bars;

and in Bar:
@ManyToMany(mappedBy="bars")
public Set<Foo> foos;

Note, although I used Set, you can use List instead.
Note: ManyToMany is Lazy by default... and I suggest leaving it that way.

A: The entityManager#getReference seems to be what you are looking for. It creates and returns an object that can be used wherever a reference to an entity is required and can (but in your case, will not have to) have all its state fetched lazily.


text:
Q: Why is Source provider empty in Read method I have the following code in which I am initializing my variables and then calling the Read method of ISampleProvider manually. On checking, I saw that sourceProvider.HasData(0) is returning False and sourceProvider.Read(buffer,offset,count) is returning 0 despite sourceProvider being initialzed before the call.
    public void init(AudioFileReader sourceProvider, int cutOffFreq,float oldRMS)
    {
        this.sourceProvider = sourceProvider;
        this.cutOffFreq = cutOffFreq;

        filter_LowPass();

        //Reading filtered bytes
        float []buff = new float[sourceProvider.Length];

        float sum=0;

        int r = Read(buff, 0, (int)sourceProvider.Length)/2;

        MessageBox.Show("Read: " + r);  Here this value is being shown 0
        for (int i = 0; i < r; i++)
            sum += buff[i] * buff[i];

        sum = (float)Math.Sqrt(sum / (float)r);
        MessageBox.Show("sum: " + sum);   //Output is coming NaN
        gain = (float)(oldRMS / sum);
        MessageBox.Show("Gain: " + gain); //Output is coming NaN
    }

    private void filter_LowPass()
    {
        channels = sourceProvider.WaveFormat.Channels;
        filters = new BiQuadFilter[channels];

        for (int n = 0; n < channels; n++)
            if (filters[n] == null)
                filters[n] = BiQuadFilter.LowPassFilter(44100, cutOffFreq, 1);
            else
                filters[n].SetLowPassFilter(44100, cutOffFreq, 1);
    }

    public int Read(float[] buffer, int offset, int count)
    {
        int samplesRead = sourceProvider.Read(buffer, offset, count);
        MessageBox.Show("Inside read: " + samplesRead); //Output is coming 0
        MessageBox.Show("Source Provider: " + sourceProvider.HasData(0)); //Output is coming False

        for (int i = 0; i < samplesRead; i++)
            buffer[offset + i] = gain * filters[(i % channels)].Transform(buffer[offset + i]);

        return samplesRead;
    }

My problem is coming when I am calling the Read method..the parameters buff,offset and count are correctly given


text:
Q: Big O Runtime for Sorted Array Insert (Beginner) The Big O runtime for inserting an item into a sorted array is O(N)
However, I was wondering why it isnt O(N^2) because wouldnt you have to first
find the correct index to place the inserted item which is O(N), then shift the rest of the data down by one to make room for this inserted item which is also O(N)?

A: No, that's O(N) + O(N), which is still just O(N).


text:
Q: Using javascript Promise asynchronously Here's the problem - I call a function and that optionally displays a dialog multiple times and waits for the user to press OK. Then after that - I want to do something else.
I think the solution requires use of Promise. But the async nature of the dialog.alert() call, is throwing me off.
function a()
{
if ( condition_ok )
{
   // there could be multiple dialogs
   //
   for ( int i = 0; i < 2; ++i )
      dialog.alert("press ok").then ( ()=> { console.log("done"); } );
  }
}
a();
// call b() after all the dialogs have been closed in a()
b();

A: If you are in an environment that has arrow functions (which your code suggests you do) but doesn't support async/await (which is an excellent answer by @guest271314) you can use the following instead
function a() {
    var p = Promise.resolve();
    if (condition_ok) {
        // there could be multiple dialogs
        //
        for (var i = 0; i < 2; ++i) {
            p = p
            .then(() => dialog.alert('press ok'))
            .then(() => {
                console.log('done');
            });
        }
    }
    return p;
}
a().then(b);

Note: each dialog will wait for the previous to "close", which I think is what your code intended

A: You can use async/await or Promise.all() and Array.prototype.map()
async function a() {
  if ( condition_ok ) {
    // there could be multiple dialogs
    //
    for ( let i = 0; i < 2; i++ ) {
      let curr = await dialog.alert("press ok");
      console.log("done");
    }
  }
  return
}
// call b() after all the dialogs have been closed in a()
a().then(() => b(), err => console.error(err));

A: Use Promise.all().
let targets = []
for (let i = 0; i < 2; i++) {
    targets.push(dialog.alert('press ok'))
}
Promise.all(targets).then(([result1, result2]) => {
    b();
})

A: The problem you are facing is that you need to wait for all your asynchronous alerts to be done before calling b. You could store all your asynchronous calls in an array and then use Promise.all() to make sure all of them are done before calling b. Here is how you could do that

// Faking data/objects - START
const condition_ok = true;
const dialog = {
  alert() {
    return new Promise((resolve, reject) => {
      resolve("Done");
    })
  }
}
const b = () => {
  console.log("Call b()")
}
// Faking data/objects - END

function a() {
  let promises = [];
  if (condition_ok) {
    for (let i = 0; i < 2; ++i) {
      promises.push(dialog.alert("press ok").then(() => {
        console.log(`Done with alert() for ${i}`);
      }));
    }
  }
  return promises;
}

Promise.all(a()).then(results => {
  // call b() after all the dialogs have been closed in a()
  b();
});


text:
Q: Ruby on Rails through Heroku object associations :belongs_to :has_many Real newb question here: I've got courses
class Course < ActiveRecord::Base

attr_accessible :name, :number

has_many :posts

validates :name, presence: true

validates :number, presence: true

validates :number, :format => { :with => /\A\d\d[-]?\d\d\d\z/}

end

and I've got posts
class Post < ActiveRecord::Base

attr_accessible :comments, :course_id, :difficulty, :enjoyability, :hours, :professor, :ranking, :semester, :usefulness

belongs_to :course

end

Almost everything I have was auto-generated by Rails. There are a couple of things I try to do that I can't get to work:

*

*When I "show" a course, I want to show each post associated with that course. However, everything I've tried has given me an error.

*After even entering one post into the database (heroku forced me to use PostgreSQL) the index form no longer renders.
I'm almost positive I'm missing something with my associations between them. Does anybody have any ideas as to what I'm doing wrong?

A: You may get all posts through Course instance:
@course = Course.find(params[:id])
@posts = @course.posts


text:
Q: SObject row was retrieved via SOQL without querying the requested field: Campaign_Design_Profile__c.Related_Opportunity_ID__c I need help troubleshooting the below apex. I have this class being called in a custom JSON Builder on a custom object. I'm logging successful runs in the log in the developer console, but in the record, the canvas is giving me an error:
Error

Error: Campaign_Design_Profile__c.Related_Opportunity_ID__c  An
  unexpected error has occurred. Your development organization has been
  notified.

Code
//Products are Gathered from a related list of opportunities.

    global class TestJsonBuilder extends pandadoc.JsonBuilder{
    global TestJsonBuilder()
    {
        super(Campaign_Design_Profile__c.getSobjectType(), null);
    }

    global override List<pandadoc.Recipient> getRecipients(sObject record) {
        List<pandadoc.Recipient> recipients = new List<pandadoc.Recipient>();
        return null;
    }

    global override List<pandaDoc.Item> getItems(sObject record) {
        List<pandadoc.Item> items = new List<pandadoc.Item>();
        Campaign_Design_Profile__c cdp = (Campaign_Design_Profile__c) record; // create a local copy of our record to use.

        //select each opportunity in the record filter on Campaign_Design_Profile__c id
        List<Opportunity> Opp = [SELECT Id,Name,AccountId
                                    FROM Opportunity where Id = :cdp.Related_Opportunity_ID__c
                                   ];
        //loop though all my related Opportunities
        for(Opportunity Opportunity :Opp)
            {
                //we need to get each product for the Opportunities now fitler on opportunityid
               List <OpportunityLineItem> products = [SELECT OpportunityId, Name, Description,ProductCode,TotalPrice,Product2Id
                                                FROM OpportunityLineItem where OpportunityId = :Opportunity.Id ];
                    //loop though each product now like we did for opportunity
                for(OpportunityLineItem product :products)
                {
                    //create pandadoc items and add to our output list.
                 pandadoc.Item pi = new pandadoc.Item(
                        product.ProductCode,     // String   Optional    Item SKU or null
                        product.Name,            // String   Required    Item Name
                        product.TotalPrice,       // Decimal  Required    Item Price
                        product.Quantity,        // Decimal  Required    Item Quantity
                        product.Description     // String   Optional    Item Description or null
                    );

                    //Possible Overloads for Pandadoc.Items.Item
                    // pandadoc.Item.Item(sku, name, price, qty, description)
                    // pandadoc.item.Item(sku, name, price, qty, description, discount)
                    // pandadoc.item.Item(sku, name, price, qty, description, discount, customFields)

                    items.add(pi);
                }
            }
        return items;

    }
}

A: So this is a relation field Campaign_Design_Profile__c.Related_Opportunity_ID__c
when it is relation it must have to be Campaign_Design_Profile__r.Related_Opportunity_ID__c

A: global override List<pandaDoc.Item> getItems(sObject record) {
    List<pandadoc.Item> items = new List<pandadoc.Item>();
    Campaign_Design_Profile__c cdp = (Campaign_Design_Profile__c) record;
...

The argument sObject record should be prepared, it means prior passing it to this method all the fields, particularly Related_Opportunity_ID__c, must be included to the SOQL query. For example:
Campaign_Design_Profile__c campaignDesignProfile = [SELECT Id, Related_Opportunity_ID__c FROM Campaign_Design_Profile__c];
List<pandaDoc.Item> items = new TestJsonBuilder.getItems(campaignDesignProfile);


text:
Q: How to manage deployment process in IBM Watson Assistant when multiple developers are involved? We have separate skills for each environment dev, qa, prod. We use the v1 API, i.e., we don't have an assistant. Whenever development is completed in dev skill, we export and import in qa skill.
Recently, we faced issues when some issue happens in qa and we need to fix it in dev skill. We had 2 options:

*

*Loose the ongoing development process and take up qa skill.

*Make the fix in dev and manually do those changes in qa skill.

Is there a better way to handle these scenarios? I have checked using v2 + assistant i.e., using one skill multiple assistants but even then we will face this issue.

A: I would suggest that you always download the skill as JSON file. If you use a version control system, then this file should be managed in there.
You can diff the changes, edit the skill in an editor, find / replace names, etc. Thus, you could apply the fixes from dev to qa.
The JSON file with the skill can even contain training data such as counterexamples. The skill file is independent of the API version (v1 / v2).
Update: Here is the official IBM Watson Assistant recommendation on the development process.


text:
Q: Powershell - Get Last Logon I have a quick script I am trying to reuse from getting computers lastlogon.  Due to time constraints I am posting it here for assistance.  I am trying to use the display name and even tried using the sam, but no luck.
$results = @()
$CompanyUsers = import-csv c:\bin\users.csv

foreach ($i in $CompanyUsers)
    {
    $results += Get-Aduser -Filter $i.sam -Properties * | select Name, Lastlogondate
    #$results += Get-Aduser -Filter {displayname -eq $i.displayname} -Properties * | select Name, Lastlogondate
    }

$results | export-csv c:\bin\Userslogon.csv

I get syntax errors. I can manually put in the values so I am thinking it has to do with data types extracted from the array.  Suggestions would be appreciated!
SAM ERROR:
Get-Aduser : Error parsing query: 'xxx001' Error Message: 'syntax error' at position: '1'.
At C:\bin\Get-UserLastLogon.ps1:19 char:14
+     $results += Get-Aduser -Filter $i.sam -Properties * | select Name, Lastlogondat ...
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ParserError: (:) [Get-ADUser], ADFilterParsingException
    + FullyQualifiedErrorId : Error parsing query: 'kal001' Error Message: 'syntax error' at posi
   tion: '1'.,Microsoft.ActiveDirectory.Management.Commands.GetADUser
DISPLAYNAME ERROR:
Get-Aduser : Property: 'displayname' not found in object of type:
'System.Management.Automation.PSCustomObject'.
At C:\bin\Get-UserLastLogon.ps1:20 char:17
+     $results += Get-Aduser -Filter {displayname -eq $i.displayname} -Properties  ...
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Get-ADUser], ArgumentException
    + FullyQualifiedErrorId : Property: 'displayname' not found in object of type: 'System.Manage
   ment.Automation.PSCustomObject'.,Microsoft.ActiveDirectory.Management.Commands.GetADUser
Thanks for the suggestions.  I found a way to get this to work:
# Create array of users
$results = @()
$Users = Get-Content C:\bin\fullnames.txt

# Get last logon date
foreach($i in $Users)
    {
    $results += Get-ADUser -ldapfilter "(displayname=$i)" -Property * | Select-Object -Property name, samaccountname, lastlogondate
    }

# Export results to csv file
$results | export-csv c:\bin\logonusers.csv

A: Try one of these:
Get-Aduser -Filter "samaccountname -eq '$i.sam'" -Properties *

Get-Aduser -Filter "displayname -eq '$i.displayname'" -Properties *

The samaccountname will be faster, since that's an indexed property.

A: # Create array of users
$results = @()
$Users = Get-Content C:\bin\fullnames.txt

# Get last logon date
foreach($i in $Users)
    {
    $results += Get-ADUser -ldapfilter "(displayname=$i)" -Property * | Select-Object -Property name, samaccountname, lastlogondate
    }

# Export results to csv file
$results | export-csv c:\bin\logonusers.csv