text:
Q: Node Red - Could not connect: getaddrinfo ENOTFOUND xxx-device-hub.azure-devices.net" I'm new to node-red and I'm trying to create a simple flow of sending data to my Azure IoT hub using node-red. But whenever I send the data the get the following error "Could not connect: getaddrinfo ENOTFOUND xxx-device-hub.azure-devices.net". I tried with different Shared access keys with all permission but still the same. I am working over a proxy network. Please help as I'm not able to work because of this
you can import my node-red flow :
[
    {
        "id": "6f18f82cf1fb4430",
        "type": "tab",
        "label": "Flow 5",
        "disabled": false,
        "info": "",
        "env": []
    },
    {
        "id": "191eb7ca.b71a8",
        "type": "azureiothub",
        "z": "6f18f82cf1fb4430",
        "name": "Azure IoT Hub",
        "protocol": "mqtt",
        "x": 640,
        "y": 340,
        "wires": [
            [
                "39c7854c.56d18a"
            ]
        ]
    },
    {
        "id": "39c7854c.56d18a",
        "type": "debug",
        "z": "6f18f82cf1fb4430",
        "name": "",
        "active": true,
        "console": "false",
        "complete": "payload",
        "x": 870,
        "y": 340,
        "wires": []
    },
    {
        "id": "b73c20238ff65f0f",
        "type": "inject",
        "z": "6f18f82cf1fb4430",
        "name": "",
        "props": [
            {
                "p": "payload"
            },
            {
                "p": "topic",
                "vt": "str"
            }
        ],
        "repeat": "",
        "crontab": "",
        "once": false,
        "onceDelay": 0.1,
        "topic": "",
        "payload": "",
        "payloadType": "date",
        "x": 160,
        "y": 340,
        "wires": [
            [
                "d9b5bad69079e9ea"
            ]
        ]
    },
    {
        "id": "d9b5bad69079e9ea",
        "type": "function",
        "z": "6f18f82cf1fb4430",
        "name": "",
        "func": "msg.payload ={\"deviceID\":\"DC_Tower_Clock\",\"SAK\":\"<Shared-access-key>\",\"Protocol\":\"mqtt\",\"Data\":{\"DC_sensor1values\":[0],\"DC_sensor1timestamp\":[1651774945]}}\nreturn msg;",
        "outputs": 1,
        "noerr": 0,
        "initialize": "",
        "finalize": "",
        "libs": [],
        "x": 380,
        "y": 340,
        "wires": [
            [
                "191eb7ca.b71a8"
            ]
        ]
    }
]

A: The problem is not with the access keys, it's with the hostname for your broker.
Error ENOTFOUND means that the OS on the system you are running can not resolve xxx-device-hub.azure-devices.net to an IP address.
Make sure you have entered the right hostname and their are no typos.
You can test by trying to ping the address outside Node-RED first.

A: There were couple of issues with my flow:

*

*inside the payload I did not have the configuration right (deviceID instead of deviceId and SAK instead of key)

*I had my protocol as MQTT when it was actually HTTP

*And the main problem was actually the company proxy, as I'm able to send the messages using my personal Laptop but with the same flow with my Work Laptop I'm not able to.


text:
Q: Complex Laravel collection I'm having some issues with the Laravel Collection class.
What I'm trying to do:

*

*I have a multisite solution in which a site has "facilitators". Sometimes one facilitator appears on multiple sites, and not just one.

*I want to list all the facilitators and the website they're on the main page, but I don't want multiple users.

So what I currently do is:

*

*Get the Facilitators.

*Use Collection to collect the facilitators and use unique('name').

This gives me unique facilitators, but only picks the first one it detects and then deletes the other ones.
So lets say I have this collection:
Collection {
  #items: array:3 [
    0 => array:2 [
      "name" => "John"
      "site" => "Example"
    ]
    1 => array:2 [
      "name" => "Martin"
      "site" => "Another"
    ]
    2 => array:2 [
      "name" => "John"
      "site" => "Another"
    ]
  ]
}

With unique() I would get:
Collection {
  #items: array:3 [
    0 => array:2 [
      "name" => "John"
      "site" => "Example"
    ]
    1 => array:2 [
      "name" => "Martin"
      "site" => "Another"
    ]
  ]
}

And this is what I want to get:
Collection {
  #items: array:3 [
    0 => array:2 [
      "name" => "John"
      "site" => ["Example", "Another"]
    ]
    1 => array:2 [
      "name" => "Martin"
      "site" => "Another"
    ]
  ]
}

Does anyone have an idea how I could accomplish this with Laravel's collection class?

A: When stuck with collections always remember reduce is a powerful tool in your arsenal.
Building on Sam's answer which I couldn't get to work, I think using reduce alongside groupBy should work...
$sites = collect([
  ["name" => "John", "site" => "Example"],
  ["name" => "Martin", "site" => "Another"],
  ["name" => "John", "site" => "Another"],
]);

$sites->groupBy('name')->reduce(function ($result, $item) {
  $result[] = [
    'name' => $item->first()['name'],
    'sites' => $item->pluck('site')->toArray()
  ];

  return $result;
}, collect([]))->toArray();

And from the console...
λ php artisan tinker
Psy Shell v0.8.2 (PHP 7.0.10 ÔÇö cli) by Justin Hileman
>>> $sites = collect([
...   ["name" => "John", "site" => "Example"],
...   ["name" => "Martin", "site" => "Another"],
...   ["name" => "John", "site" => "Another"],
... ]);
=> Illuminate\Support\Collection {#698
     all: [
       [
         "name" => "John",
         "site" => "Example",
       ],
       [
         "name" => "Martin",
         "site" => "Another",
       ],
       [
         "name" => "John",
         "site" => "Another",
       ],
     ],
   }
>>> $sites->groupBy('name')->reduce(function ($result, $item) {
...   $result[] = ['name' => $item->first()['name'], 'sites' => $item->pluck('site')->toArray()];
...
...   return $result;
... }, collect([]))->toArray();
=> [
     [
       "name" => "John",
       "sites" => [
         "Example",
         "Another",
       ],
     ],
     [
       "name" => "Martin",
       "sites" => [
         "Another",
       ],
     ],
   ]

One thing to note is that you specified in your question that the sites should return a single string if there's only one site and an array if there's many.The above solution does not provide this! I think this is inconsistent and you should always return an array for the sites key, even if it only has one value as it will make it more difficult to read and manipulate later on.
However, if this is something important, you could instead check if there are many sites when using pluck to set an array and if not you could set it as a single string, like this:
$sites->groupBy('name')->reduce(function ($result, $item) {
  $result[] = [
    'name' => $item->first()['name'],
    'sites' => $item->pluck('site')->count() > 1 ? $item->pluck('site') : $item->first()['site']
  ];

  return $result;
}, collect([]))->toArray();

which would produce...
[
  [
    "name" => "John",
    "sites" => [
      "Example",
      "Another",
    ],
  ],
  [
    "name" => "Martin",
    "sites" => "Another",
  ],
]

A: you can do it by chaining to get exactly what you want, assuming $collection is the main collection
 $collection->groupBy('name')->map(function($facilitators) {
     return ['name' => $facilitators->first()['name'], 'site' => $facilitators->pluck('site')->toArray()];
})->values()->toArray();

first we group by name so it will give 2 dimensional array inside collection, then iterate to that and name will be common so get it from first element, then from all the element pluck site and convert it to array, using flatMap will make it single level nested.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Функция окрашивания ячеек с "плавающим" количеством переменных Хочу сделать через функцию заливку произвольным цветом произвольное количество ячеек и/или диапазонов. В функцию вводится цвет и сами диапазоны. Со цветом проблем нет, но как сделать "плавающие" количество диапазонов(Как например у базовых функций "IFS" и "SWITCH")? Сам информацию не нашел, а вариант с кучей переменных не очень подходит и просто звучит.
// Текущая функция выглядит сейчас так:

function zero(color, range1, range2, range3) {
 var sheet1 = sa.getActiveSpreadsheet().getSheetByName("List");
 var range0 = sheet1.getRangeList([`${range1}`, `${range2}`, `${range3}`]);
 range0.setBackground(`${color}`);}

A: Это довольно странный вопрос, т.к. код показывает не то, что задается.
Предположим, что добывать цвета мы будем итератором
/**
 *
 * @param {any[]} arr
 * @param {callback} extractor
 * @returns {@yields}
 */
const pickFromIterator_ = (arr, extractor) =>
  (function* () {
    let index = 0;
    while (true) {
      index = index >= arr.length ? 0 : index;
      yield extractor ? extractor(arr, index) : arr[index++];
    }
  })();

Обратите внимание, что мы можем переопределить порядок вывода значений с помощью extractor. Это понадобится для рандомного выбора.
Покраску всего сведем к перебору всех диапазонов
/**
 *
 * @param {string[]} colors
 * @param {string[]} rangeNames
 * @param {@yields} picker
 * @param {globalThis.SpreadsheetApp.Sheet} sheet
 */
function colorRanges_(
  colors,
  rangeNames,
  picker = pickFromIterator_(colors),
  sheet = SpreadsheetApp.getActiveSheet()
) {
  rangeNames.forEach((rangeName) =>
    sheet.getRange(rangeName).setBackground(picker.next().value)
  );
}

Чтобы запустить пример нужно реализовать вызов функции colorRanges_
/**
 * Runs the sample
 */
function run() {
  SpreadsheetApp.getActiveSheet().clearFormats();

  const colors = ['red', 'yellow', 'green'];

  const picker = pickFromIterator_(colors);
  colorRanges_(colors, ['A:A', 'C:C', 'D:D', 'E:E'], picker);

  const picker2 = pickFromIterator_(
    colors,
    (arr) => arr[Math.floor(Math.random() * arr.length)]
  );
  colorRanges_(colors, ['F:F', 'G:G', 'I:I'], picker2);

  // Continue with picker
  colorRanges_(colors, ['J:J', 'K:K', 'L:L', 'M:M'], picker);

  // Default
  colorRanges_(colors, ['N:N', 'O:O']);
}

Обратите внимание

*

*следующие две колонки будут покрашены рандомно на основании значений randomExtractor

*количество диапазонов не зависит от количества цветов задавать можно любое количество большее чем ничего.

*После комментария // Continue with picker програма продолжает использовать текущий итератор, а не начинает новый как после // Default.

Таблица с кодом https://docs.google.com/spreadsheets/d/1VwM_FpwspSedrcacAdv1P73IwOHC45X15SBNftkt2TY/edit?usp=sharing


text:
Q: why setlargeIcon does not work? I created my notification like this
    Notification notification = new NotificationCompat.Builder(this)
                                .setTicker("ticher")
                                .setContentTitle("title")
                                .setContentText("text")
                                .setSmallIcon(R.drawable.ic_action_email)
                                .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_disturb))
                                .setAutoCancel(false)
                                .build();

But setLargeIcon does not work. Large icon of notification is always app icon.
I don't know why. thanks for your help.


text:
Q: How do I translate an LDAP .xml configuration file, to a .java configuration file? I was tasked with converting an xml configuration file for the Flowable LDAP library, and adding it into the already existing Java configuration for everything else that's being used.
I'm failing to see how the xml, when converted into Java, fits into the already existing Java code. All the examples I've looked at seem to be doing it with Spring LDAP, which is slightly different.
Flowable configuration:
<bean id="processEngineConfiguration" class="...SomeProcessEngineConfigurationClass">
        ...
        <property name="configurators">
          <list>
              <bean class="org.flowable.ldap.LDAPConfigurator">

                <!-- Server connection params -->
                <property name="server" value="ldap://localhost" />
                <property name="port" value="33389" />
                <property name="user" value="uid=admin, ou=users, o=flowable" />
                <property name="password" value="pass" />

                <!-- Query params -->
                <property name="baseDn" value="o=flowable" />
                <property name="queryUserByUserId" value="(&(objectClass=inetOrgPerson)(uid={0}))" />
                <property name="queryUserByFullNameLike" value="(&(objectClass=inetOrgPerson)(|({0}=*{1}*)({2}=*{3}*)))" />
                <property name="queryGroupsForUser" value="(&(objectClass=groupOfUniqueNames)(uniqueMember={0}))" />

                <!-- Attribute config -->
                <property name="userIdAttribute" value="uid" />
                <property name="userFirstNameAttribute" value="cn" />
                <property name="userLastNameAttribute" value="sn" />
                <property name="userEmailAttribute" value="mail" />

                <property name="groupIdAttribute" value="cn" />
                <property name="groupNameAttribute" value="cn" />

              </bean>
          </list>
        </property>
    </bean>

Java Engine configuration file
@Configuration
@EnableTransactionManagement
@ComponentScan(basePackages = Array("com.name.product.engine.services"))
class FlowableEngineConfig {

  @Bean
  def processEngineConfiguration(env: Environment, dataSource: DataSource, transactionManager: PlatformTransactionManager, applicationContext: ApplicationContext): ProcessEngineConfiguration = {
    val updateSchema = env.getProperty("conduct.engine.database.updateSchema", "true").trim.toLowerCase match {
      case "update" | "true" =>
        AbstractEngineConfiguration.DB_SCHEMA_UPDATE_TRUE
      case "none" =>
        null
      case x =>
        AbstractEngineConfiguration.DB_SCHEMA_UPDATE_FALSE
    }

    val engineConfig = new SpringProcessEngineConfiguration()

    engineConfig.setDataSource(dataSource)
    engineConfig.setTransactionManager(transactionManager)
    engineConfig.setTransactionsExternallyManaged(true)
    engineConfig.setDatabaseSchemaUpdate(updateSchema)

    engineConfig.setAsyncExecutorActivate(true)
    engineConfig.setAsyncExecutor(asyncExecutor())

    engineConfig.setHistoryLevel(HistoryLevel.FULL)

//    engineConfig.setCustomFormTypes(Seq[org.flowable.engine.form.AbstractFormType](
//      ISODateFormType
//    ).asJava)

    engineConfig.setExpressionManager(new SpringExpressionManager(applicationContext, null))
    engineConfig.setBeans(new SpringBeanFactoryProxyMap(applicationContext))

    // Enable safe XML. See http://www.flowable.org/docs/userguide/index.html#advanced.safe.bpmn.xml
    engineConfig.setEnableSafeBpmnXml(true)
    engineConfig.setProcessDefinitionCacheLimit(128)

    //engineConfig.setDisableIdmEngine(true)

    engineConfig.addConfigurator(new SpringFormEngineConfigurator())
    engineConfig.addConfigurator(new SpringDmnEngineConfigurator())

    engineConfig
  }

  @Bean
  def processEngine(engineConfig: ProcessEngineConfiguration): ProcessEngine = {
    engineConfig.buildProcessEngine()
  }

  @Bean
  def clock(engineConfig: ProcessEngineConfiguration): Clock = {
    engineConfig.getClock
  }

  @Bean
  def asyncExecutor(): AsyncExecutor = {
    val asyncExecutor = new DefaultAsyncJobExecutor()
    asyncExecutor.setDefaultAsyncJobAcquireWaitTimeInMillis(5000)
    asyncExecutor.setDefaultTimerJobAcquireWaitTimeInMillis(5000)
    asyncExecutor
  }

  @Bean
  def dataSource(env: Environment): DataSource = {

    val hconf = new HikariConfig()

    env.getRequiredProperty("conductor.engine.database.platform").trim.toLowerCase() match {
      case "postgresql" =>
        hconf.setDataSourceClassName("org.postgresql.ds.PGSimpleDataSource")
        hconf.addDataSourceProperty("serverName", env.getRequiredProperty("conduct.engine.database.hostname"))
        hconf.addDataSourceProperty("portNumber", env.getRequiredProperty("conduct.engine.database.port", classOf[Int]))
        hconf.addDataSourceProperty("databaseName", env.getRequiredProperty("conduct.engine.database.name"))
        hconf.addDataSourceProperty("applicationName", "conduct")

      case "h2" =>
        hconf.setDataSourceClassName("org.h2.jdbcx.JdbcDataSource")
        val dbName = env.getRequiredProperty("conduct.engine.database.name")
        hconf.addDataSourceProperty("URL", s"jdbc:h2:file:./$dbName")

      case "h2mem" =>
        hconf.setDataSourceClassName("org.h2.jdbcx.JdbcDataSource")
        val dbName = env.getRequiredProperty("conduct.engine.database.name")
        hconf.addDataSourceProperty("URL", s"jdbc:h2:mem:$dbName")

      case x =>
        throw new RuntimeException(s"Unknown database platform $x")
    }

    hconf.setUsername(env.getRequiredProperty("conduct.engine.database.username"))
    hconf.setPassword(env.getRequiredProperty("conduct.engine.database.password"))

    hconf.setMinimumIdle(env.getRequiredProperty("conduct.engine.database.minConnections", classOf[Int]))
    hconf.setMaximumPoolSize(env.getRequiredProperty("conduct.engine.database.maxConnections", classOf[Int]))

    hconf.setInitializationFailFast(env.getRequiredProperty("conduct.engine.database.initializationFailFast", classOf[Boolean]))

    hconf.setTransactionIsolation("TRANSACTION_READ_COMMITTED")

    new HikariDataSource(hconf)
  }


text:
Q: the plugin org.jetbrains.android failed to save settings and has been disabled When starting Android Studio 1.2 I get the error message:

the plugin org.jetbrains.android failed to save settings and has been
  disabled

I tried restarting and even downloaded the latest Android plugin but it didn't help. Any suggestions?

A: I had the same problem which I just solved by the following steps:

*

*Exit Android Studio

*Check if you have 2 directories .AndroidStudio1.2 and .AndroidStudio

*Delete Android .AndroidStudio directory

*Start Android Studio and open another working project

*Exit Android Studio and Start your current project.

Hope this will helps you too.
If the above doesn't help , try this answer.

A: The issue I had with this is because my project name had an escaped character in it. The Project was exported as Archie's Blah, which was turned into Archie\'sBlah, which was causing problems (even if it wasn't actively complaining about it)


text:
Q: Considering the power series $\sum_{n=1}^\infty(-1)^{n-1}\frac{x^{2n+1}}{(2n+1)(2n-1)}$. Consider the power series $\sum_{n=1}^\infty(-1)^{n-1}\frac{x^{2n+1}}{(2n+1)(2n-1)}$. Find a closed form expression for all x which converge and hence evaluate $\sum_{n=1}^\infty\frac{(-1)^{n-1}}{(2n+1)(2n-1)}$.
Attempt at the solution: The radius of convergence is 1. We can rewrite the summands by:
\begin{eqnarray}
\sum_{n=1}^\infty(-1)^n\frac{x^{2n+1}}{(2n+1)(2n-1)} &=& \frac{1}{2}\Big[(x^3-\frac{x^3}{3})  - (\frac{x^5}{3} - \frac{x^5}{5}) + (\frac{x^7}{5} - \frac{x^7}{7}) + \dots \Big]\\
&=& \frac{1}{2}\Big[(x^3  -\frac{x^5}{3}+ \frac{x^7}{5} + \dots ) + (\frac{-x^3}{3} + \frac{x^5}{5}-\frac{x^7}{7} +...)\Big]\\
&=& \frac{1}{2}\Big[x^2\int\frac{1}{1+x^2}dx + \int\frac{1}{1+x^2}dx-x\Big]\\
&=& \frac{x^2}{2}\arctan(x)+\frac{1}{2}\arctan(x) -\frac{x}{2}
\end{eqnarray}
Substituting $x=1$ then gives $\frac{\pi}{4}-\frac{1}{2}$ .

The issue I have is two fold. Firstly, when dealing with evaluations at the boundary, term by term differentiation may not be valid. In particular, we used the fact that $\arctan(x) = x-\frac{x^3}{3} + ...$ by integrating power series for $\frac{1}{1+x^2}$, valid for |x|<1. This means that the arctan formula can only be guaranteed to hold within the interior (-1,1). What are the conditions needed to talk about power series validity at boundary points?

(Abelian/Tauberian theorems came to mind at first, but the conditions in this problem weren't strong enough. Alternatively, I noted that uniform convergence of the terms meant that the limit function of $x-\frac{x^3}{3} + ...$ had to be continuous. So $\arctan(1) = \frac{\pi}{4}$ by continuous extension. Do correct me if I'm wrong.
The other issue that I have not been able to justify is that of conditional convergence. Clearly, the arctan series is conditionally convergent at $x=1$. How do we justify the rearrangments carried out above then?

A: First, by using the standard power series,
$$
\sum_{n=1}^\infty(-1)^{n-1}\frac{t^{2n-1}}{2n-1}=\arctan t, \quad |t|<1,\tag1
$$ we multiply $(1)$ by $t$ then we are alowed to integrate termwise:
$$
\sum_{n=1}^\infty(-1)^{n-1}\frac{x^{2n+1}}{(2n-1)(2n+1)}=\int_0^x t\arctan t\: dt, \quad |x|<1,\tag2
$$ then integrating by parts on the right hand side, gives
$$
\int_0^x t\arctan t\: dt=\frac12\left(1+x^2\right)\arctan x-\frac{x}2, \tag3
$$ thus

$$
\sum_{n=1}^\infty(-1)^{n-1}\frac{x^{2n+1}}{(2n-1)(2n+1)}=\frac12\left(1+x^2\right)\arctan x-\frac{x}2, \quad |x|<1.\tag4
$$

Second, noticing the following absolute convergence,
$$
\sum_{n=1}^\infty\left|(-1)^{n-1}\frac{1}{(2n-1)(2n+1)}\right|<\infty,
$$ one may use Abel's theorem in $(4)$ with $x \to 1^-$ to obtain

$$
\sum_{n=1}^\infty\frac{(-1)^{n-1}}{(2n-1)(2n+1)}=\frac{\pi}4-\frac12 \tag6
$$

as announced.

A: $\newcommand{\angles}[1]{\left\langle\,{#1}\,\right\rangle}
 \newcommand{\braces}[1]{\left\lbrace\,{#1}\,\right\rbrace}
 \newcommand{\bracks}[1]{\left\lbrack\,{#1}\,\right\rbrack}
 \newcommand{\dd}{\mathrm{d}}
 \newcommand{\ds}[1]{\displaystyle{#1}}
 \newcommand{\expo}[1]{\,\mathrm{e}^{#1}\,}
 \newcommand{\half}{{1 \over 2}}
 \newcommand{\ic}{\mathrm{i}}
 \newcommand{\iff}{\Longleftrightarrow}
 \newcommand{\imp}{\Longrightarrow}
 \newcommand{\Li}[1]{\,\mathrm{Li}_{#1}}
 \newcommand{\ol}[1]{\overline{#1}}
 \newcommand{\pars}[1]{\left(\,{#1}\,\right)}
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\ul}[1]{\underline{#1}}
 \newcommand{\root}[2][]{\,\sqrt[#1]{\,{#2}\,}\,}
 \newcommand{\totald}[3][]{\frac{\mathrm{d}^{#1} #2}{\mathrm{d} #3^{#1}}}
 \newcommand{\verts}[1]{\left\vert\,{#1}\,\right\vert}$
\begin{align}
&\color{#f00}{\sum_{n = 1}^{\infty}
\pars{-1}^{n - 1}\,{x^{2n + 1} \over \pars{2n + 1}\pars{2n - 1}}} =
\half\sum_{n = 1}^{\infty}
\pars{-1}^{n - 1}\,{x^{2n + 1} \over 2n - 1} - \half\sum_{n = 1}^{\infty}
\pars{-1}^{n - 1}\,{x^{2n + 1} \over 2n + 1}
\\[4mm] = &\
\half\,x^{3} + \half\,x^{2}\sum_{n = 1}^{\infty}
\pars{-1}^{n}\,{x^{2n + 1} \over 2n + 1} - \half\sum_{n = 1}^{\infty}
\pars{-1}^{n - 1}\,{x^{2n + 1} \over 2n + 1}
\\[4mm] = &\
\half\,x^{3} + \half\,\pars{x^{2} + 1}x\
\underbrace{\sum_{n = 1}^{\infty}
\pars{-1}^{n}\,{x^{2n} \over 2n + 1}}_{\ds{\equiv\ \,\mathcal{J}}}\tag{1}
\end{align}

\begin{align}
\,\mathcal{J} & =
\sum_{n = 1}^{\infty}
\pars{-1}^{n}\,{x^{2n} \over 2n + 1} =
\sum_{n = 1}^{\infty}\pars{-1}^{n}\,x^{2n}\int_{0}^{1}y^{2n}\,\dd y =
\int_{0}^{1}\sum_{n = 1}^{\infty}\pars{-x^{2}y^{2}}^{n}\,\dd y
\\[4mm] &\ =\
\overbrace{\int_{0}^{1}{-x^{2}y^{2} \over 1 + x^{2}y^{2}}\,\dd y}
^{\ds{-1 + {\arctan\pars{x} \over x}}}
\end{align}

$$
\color{#f00}{\sum_{n = 1}^{\infty}
\pars{-1}^{n - 1}\,{x^{2n + 1} \over \pars{2n + 1}\pars{2n - 1}}} =
\color{#f00}{\half\bracks{\pars{x^{2} + 1}\arctan\pars{x} - x}}
$$

When $\ds{x \to 1^{-}}$, $\ds{\sum\cdots \to {\pi \over 4} - \half}$.


text:
Q: ggiraph Hover "Misaligned" in Latest Version? Since updating my packages, I've been getting strange behavior when hovering over lines created by geom_line_interactive(). Lines get the hover effect even when the mouse is far from the line, and sometimes the line won't get the hover effect when the mouse is directly over it. This seems to only be a problem for line geoms; bars, points, etc. work fine.
See example below:
library(tidyverse)
library(ggiraph)

df = tibble(
  x = rep(1:5, 4),
  y = c(1:5, (1:5)^2, 4,2,1,2,4, 5,7,8,7,5),
  group = as.character(sort(rep(1:4, 5))),
  color = as.character(sort(c(rep(1, 15), rep(2, 5))))
)

gg = ggplot(df, aes(x, y, color = color, group = group, data_id = group, tooltip = group))

girafe(ggobj = gg + geom_line_interactive() + geom_point_interactive()) # Causes a problem
girafe(ggobj = gg + geom_line_interactive()) # Still causes a problem
girafe(ggobj = gg + geom_point_interactive()) # No problem

Version numbers:
tidyverse - 1.3.2 (includes ggplot2 - 3.4.0)
ggiraph - 0.8.5
R - 4.2.2


text:
Q: What is the most efficient way to find caves in Minecraft? I'm trying to find caves in Minecraft as efficiently as possible. Where do caves tend to occur with the greatest frequency, and at what elevation are they the most common? Also, how far apart are they, on average?
I'm interested in knowing what tools would be useful for analyzing the distribution of caves in Minecraft, as well.

A: While others give methods how to find single caves or explore to find bigger nexuses, let me answer directly, how to find BIG cave nexuses.
There are mods that let you peer through walls. This is a blatant cheat but it really lets you locate caves most easily. Another method to travel quickly, by boat or running. As new chunks are loaded, you can see through the floor before they do. That way you can spot places where a whole bunch of caves connect. It seems Minecraft uses some function of cavern density - while sometimes you find caves that run for chunks with very few branching, yesterday I encountered a couple of chunks that were literally such a mess of caverns, ravines and huge chambers, so that the remaining stone between them felt more like erratic walkways in a huge void, as there was considerably more air than stone.
As for frequency of cave appearance: look at the dashed cyan line of this graph:
source
It's the frequency of air blocks per volume. In particular, caves between level 15 and 35 are nearly ten times as common as near surface (64). Although in this case the graph might be biased: I guess if you exclude "sea" biome the distribution would be more uniform.
Nevertheless, there's a rapid drop-off below 14, so don't seek them near bedrock.

A: I have no statistics, but, while digging, you can often hear faint monster noises deep underground. If you dig toward them, you should come out in a cave or dungeon.
I've also noticed that you can frequently find large caves that end up as ravines on the surface, and you can also find caves underneath ocean biomes.

A: One tip to make cave searching much easier is to carry a piston and a form of power (button, pressure plate, lever, redstone torch etc.) around with you.
If you hear any monster noises, put the piston up against a wall (or floor or ceiling) facing into the wall (in the direction you think the monsters are). Power the piston, and if it actually works, you know there's a cave on the other side of that wall.
Keep in mind that this only works if the cave is 12 blocks or less away, any more and the piston won't work causing you to think that there's probably no cave.

A: It depends on your purpose.  If your purpose is to just find a cave, any old cave, wander around on the surface and you'll generally find one quite quickly.  Most caves lead to huge underground regions which as another poster mentioned can take days (human days) to fully explore.
If your purpose is to illuminate all caves to force monsters to spawn in a trap (for instance) then creating a tunnel system that passes with 32 of every block on the interior of your system (and 16 on the exterior) will guarantee you that if mobs are spawning inside your system, you'll at least be able to hear them from one of your tunnels (mob noises travel 16 squares).  Moreover, as most caves are large or have large extents, you'll very likely intersect any significant caves in that region.
As for identifying the cave distribution, all I can suggest is using "standard" minecraft map exploration tools, of which I know nothing about.

A: One way to find caves very fast is to head over to an extreme hills biome where caves spawn most frequently. listen for strange noises as you are walking around (after you explore the caves that are on the surface) when you hear a strange noise dig down (not straight down but dig a spiral staircase down) and it is guaranteed that a cave will be on average less than 12 blocks away from where you heard the strange sound.

A: With regard to normal (i.e. flat-ish dirt and rock) terrain, I haven't noticed any particular technique other than luck/just digging and mining.
I have found that they are easier to locate where a generated feature clashes with the cave:

*

*The edges of lakes, either on the bed or where they meet the shore.

*Steep hills 'stretch'/distort the land and expose caves.

*Sand can form pits as it falls into caves, often where lava is present in the cave (Seems to destroy the sandstone cap.)

*The sea bed, once you can make breathing room.  I have found Jack-O-Lanterns to be useful for highlighting the the floor's features.
In terms of generalised location caves seem to occur from a few layers above bedrock to above sea level, i.e. wherever there is contiguous rock and dirt.  However there seems to be a larger concentration at certain depths: which might be possible to ascertain from understanding how the terrain is generated (which I don't!).
This is largely a list of anecdotal information, but it is the most efficient way I have found without utilising blind luck.

A: I locate a lot of caves all the time. Try:

*

*Turning your volume up so that you can hear possible monster noises indicating a cave nearby

*Going for a scuba-diving trip in a lake/swampland biome

*Looking for abnormalities (such as an area missing sand) in desert biomes

*Look near bedrock

*Make a quarry - you are guaranteed to find a cave using this method

*MINE!!!

A: I wouldn't say caves are really hard to find. They very often occur on the ground that you are walking on. Caves mostly occur when you are in Extreme Hills biomes and they can also have a lot of minerals for you to mine. You can find a cave by hearing the monster sounds that travel 16 blocks or you can hear a very creepy sound when you are approaching a cave. Also, never ignore a patch of dirt underground. Dig it and most likely it will lead you to a large cave or ravine.

A: One thing that works for me is walking around on the surface, listening for creepy cave noises (old train sounds, demon roars and sometimes just mob sounds) Dig down for 16 blocks and then extend it in to a 16~16 space, you will either find where the mob or cave is. The more sounds you hear while digging the hole, the bigger the cave will be, also do this listening methods in previously explored caves, you might find more within 16 blocks!
NOTE: Avoid doing this at night because of the normal mob sounds and in rare cases the moon will darken a place so much it will go to a 3~3 dark space and make a cave noise; Do not be close to a 'man made' mob spawner, because, again, a cave noise will be triggered.

A: Dig the exact block that you stand on when you spawn and then dig 15 blocks directly down. Dig 5 blocks to the right, then dig five blocks to the right again. You should hear an eerie noise. Dig one block down and be careful. You will fall into a cave that leads to 6-21 other caves. Just dig where the dirt is. The trick is to stay facing in the same direction as when you spawned before you dig. I know this won't let you find every cave but all of them are 5-10 blocks away from each other. I have found around 225 caves in every world I've been on using this technique.

A: What I do is I walk around in a forest and I fall into a random hole, and that hole is most likely a cave. But really, I'm not very sure.

A: One thing that works for me most of the time is to get an Eye of Ender and then right click with it in your hand, follow the eye and dig down.


text:
Q: How to fix 'setAttributeNode(att)' to add attribute vice modify existing? I am using the shinyJS package as well as shiny tags and traditional HTML to add the attribute 'title' to existing elements. I am able to do this without issue within the console (inspector [Google CHROME]) but when attempting to apply the same inputs via either ui.R or server.R, either nothing changes or the actual text value changes vice adding title (tooltip).
As mentioned above, I have tried the following:
shinyJS: html()
shiny: tags$HTML; tags$body(tags$script())
HTML: Adding the change in HTML file (mychange.html) and sourcing from www
The input to modify (add tooltip)
pickerInput(
inputid = "ReqTabSel6",
label = '',
choices = c('Choice 1', 'Choice 2', 'Choice 3'),
mulitple = F,
options = list(
style = "btn-info"))

Here is the correct function (as it updates when running in console under web inspector):
var addToolTip1 = document.querySelector('#form>div:nth-child(10)>div>div>div>ul>li.selected>a')
var att = document.createAttribute("title");
att.value = "I am a tooltip title";
addToolTip1 .setAttributeNode(att);

However, in R...
shinyJS
server.R
...
observeEvent(input$ReqTabSel6, {
shinyJS::html(id = NULL,
html = "var addToolTip1 = document.querySelector('#form>div:nth-child(10)>div>div>div>ul>li.selected>a')
var att = document.createAttribute("title");
att.value = "I am a tooltip title";
addToolTip1 .setAttributeNode(att);",
selector = '#form>div:nth-child(10)>div>div>div>ul>li.selected>a')
})

##This updates the actual 'choice' value from 'Choice 1' to 'Choice1I am a tooltip title')

#Changing html to read:
html = 'title = "I am a tooltip title"',

#This replaces the choice (e.g. Choice 1) value so the drop down now has:

I am a tooltip title
Choice 2
Choice 3

Would like to create the tooltip for each child (tab index) of the pickerInput choices. Should just add 'title' attribute to other attributes within the designated node.

A: Got it! Answering it myself in case another user runs in to this.
#server.R
observeEvent(input$actionbutton1,{
shinyjs::html(
html='',
add=FALSE,
selector = '#form>div>form>div>div:nth-child(5)>div>div>div>ul>li:nth-child(4)' #This is the jquerySelector. Note that it will be different for each unique application. You will need to change the 'nth-child(#)' to the specific choice within 'SelectInput' to get a tooltip specific to that choice.)
})


text:
Q: Gallery android:unselectedAlpha I have a Gallery that works perfectly, except only the first element is ever displayed at full alpha.
I have the Gallery's style set to style="android:galleryItemBackground", and android:unselectedAlpha="0.75" is also set. This works, in that the first element is shown without transparency, and the second appears to be faded some.
The issue is, when I scroll the gallery, the items never become unfaded. They're all alpha=0.75, even when they're the selected item. The items do have an OnItemClickListener set, and this listener works fine.
I am unable to find an answer to how to get this working, so I thought I'd ask here.
[ edit ]
I've also tried setting an OnItemSelectedListener and manually setting the View's alpha to 1 if the position = selectedPosition in the getView of the Adapter. No luck.

A: Add background on every of its child view
This is one example code
@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View view = null;

    if (convertView == null) {
        view = mInflater.inflate(R.layout.some_layout, parent, false);
    } else {
        view = convertView;
    }

    // have to set background to make selection alpha works
    view.setBackgroundColor(0x22ffffff);

    return view;
}

Hope it helps


text:
Q: PHP function to remove key from a query string I have a query string, like:
n1=v1&n2=v2&n3=v3
etc
I just want a php function that will accept the query string and the name (key), and remove the name value pair from the querystring.
Every example I have found uses regexes and assumes that the value will exist and that it will not be empty, but in my case (and possibly in general, I would like to know) this would also be a valid query:
n1=v1&n2=&n3
I don't know in advance how many keys there will be.
I am convinced that regexes are monsters that eat time.  Eventually all matter in the universe will end up in a regex.

A: parse_str('n1=v1&n2=&n3', $gets);
unset($gets['n3']);
echo http_build_query($gets);

NOTE: unset($gets['n3']); is just a show-case example

A:
function stripkey($input, $key) {

$parts= explode("&", $input);

foreach($parts as $k=>$part) {

    if(strpos($part, "=") !== false) {
        $parts2= explode("=", $part);

        if($key == $parts2[0]){

            unset($parts[$k]);
        }
    }
}
return join("&", $parts);

}


text:
Q: How to manage the same blog at two sites? I have two almost-identical sites. Site A has four static pages, and Site B has four static pages, but they both share a common blog-posts page.
I need the page URLs to be as follows:

http://siteA.com/page1
http://siteA.com/page2
http://siteA.com/page3
http://siteA.com/page4
http://siteA.com/blog

And
 http://siteB.com/page1
 http://siteB.com/page2
 http://siteB.com/page3
 http://siteB.com/page4
 http://siteB.com/blog (same content as blog page at Site A)

What's the best way to do this? Two Wordpress installs, one in each site's root (where one simply accepts the RSS feed from the other)? Or host all the static pages at one site and use redirects from the other site? Or something even more graceful I haven't thought of? Thanks in advance...

A: In my opinion
Site redirect is  a good option for you because manage two site is more hassle work then one.
and their is no problem comes in SEO ways but search engine don't like duplicate content.

A: You could have each install connect to the same database.
The beauty of that is that each could have a different template.

A: You could display the blog in an iframe or pull a cached html copy from siteA to siteB.


text:
Q: How to create a copy of array without modifying it old value? I have two arrays tasks and updatedTasks. When the first api call is made, one of the properties is updated. When I make a copy of tasks array and make a second API to update other property, it adds sadditional properties to updatedTasks array. The weird thing is I get the expected result, but both tasks and updatedTasks have same properties.
Code:
const _tasks = []
const _updatedTasks = []
const obj = {
    name: 'task',
  zone: 'zone'
}
const zone = 'abc'
const response = { taskList: [ obj ]};
const response2 = {time: '123'}

response.taskList.map((task)=>{
  task.zone = zone
  const obj = {...task}
  _tasks.push(obj)
})
console.log(_tasks)

const copy = [..._tasks]

copy.map((task)=>{
  const resp = response2
  task.time = resp.time
  _updatedTasks.push(task)
})
console.log(_updatedTasks)

How can I make sure, tasks just updates zone and updateTasks updates both zone and time?
Fiddle Link: https://playcode.io/944175


text:
Q: Java check equality for Strings Edited: I have tested this code in java and the printed output was "true", while the compiler compares the reference and not the value of Strings why this is "true"?
public class Main {
    public static void main(String[] args) {
        String s1 = "string";
        String s2 = "string";
        System.out.println(""+(s1==s2));
    }
}

A: The String equality rules have not changed in Java 8 and s1==s2 prints always true in this case since they both point to the same memory location in constant pool, which typically located on heap memory.
I just checked with Java6 and it's true.

A: There has been no change, the == operator checks if two references point to the same object. String literals are placed in the string pool. So "string" is placed in the string pool, s1 and s2 both point to that, hence an output of true.

A: In your edited question, you have defined two String literals. As per JLS § 3.10.5 these literals are interned:

a string literal always refers to the same instance of class String. This is because string literals - or, more generally, strings that are the values of constant expressions (§15.28) - are "interned" so as to share unique instances, using the method String.intern.

Therefore reference equality using == will always return true for s1 == s2 where:
String s1 = "string";
String s2 = "string";

The JLS states (almost exactly) the same for Java 7 and Java 6
Note though that there are some subtle differences in the way string interning works between certain JDK versions. See, for instance "intern() behaving differently in Java 6 and Java 7"

A: It is up to the compiler to decide, in this case, whether s1 == s2. The condition is testing whether s1 and s2 are the same object. This is likely to be true, as a sensible compiler would have a constant pool, but not necessarily so.
However, your intent is comparing the strings, not the objects, so equals() is the correct method and the use of == is incorrect for that.


text:
Q: How to dynamically change Core Plot's label I encountered a problem when using a custom label in Core Plot:

*

*My Core Plot supports zoom.

*The x-axis label is custom x.axisLabels
On first load, the interface is normal, but when I narrow Core Plot, the axis labels overlap together.
How to design a level on the label? For example, when the minimum level only shows a year, in level display date, the maximum level shows the date.
- (void)initPlotGraph
{
    graph = [[CPTXYGraph alloc] initWithFrame:CGRectZero];
    self.hostedGraph = graph;
    locationLabels = [[NSMutableArray alloc]init];

    graph.plotAreaFrame.paddingLeft   += 5.0;
    graph.plotAreaFrame.paddingTop    += 5.0;
    graph.plotAreaFrame.paddingRight  += 5.0;
    graph.plotAreaFrame.paddingBottom += 17.5;

    //[self setAllowPinchScaling:NO];

    // Setup scatter plot space
    plotSpace                       = (CPTXYPlotSpace *)graph.defaultPlotSpace;
    plotSpace.allowsUserInteraction = YES;
    plotSpace.delegate              = self;

    plotSpace.yRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromInt(0)length:CPTDecimalFromFloat(1+0.3)];
    plotSpace.globalYRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromInt(0)length:CPTDecimalFromFloat(1+0.3)];

    [self initPlotAxis];
 }

- (void)initPlotAxis
{
    CPTMutableLineStyle *axisLineStyle = [CPTMutableLineStyle lineStyle];
    axisLineStyle.lineWidth            = 2;
    axisLineStyle.lineColor            = [CPTColor colorWithComponentRed:CPTFloat(0.11765) green:CPTFloat(0.49804) blue:CPTFloat(0.87451) alpha:CPTFloat(1)];

    CPTMutableLineStyle *axisTickLineStyle = [CPTMutableLineStyle lineStyle];
    axisTickLineStyle.lineWidth            = 0;

    CPTLineCap *lineCap = [CPTLineCap sweptArrowPlotLineCap];
    lineCap.size        = CGSizeMake(10, 10);
    lineCap.lineCapType = CPTLineCapTypeNone;

    // Axes
    // Label x axis with a fixed interval policy
    lineCap.lineStyle     = axisLineStyle;
    lineCap.fill          = [CPTFill fillWithColor:[CPTColor colorWithComponentRed:CPTFloat(0.29019) green:CPTFloat(0.54118) blue:CPTFloat(0.76471) alpha:CPTFloat(1)]];
    CPTXYAxisSet *axisSet = (CPTXYAxisSet *)graph.axisSet;
    CPTXYAxis *x          = axisSet.xAxis;
    x.majorIntervalLength = CPTDecimalFromInt(1);
    x.axisLineStyle       = axisLineStyle;
    x.axisConstraints     = [CPTConstraints constraintWithRelativeOffset:0];
    x.axisLineCapMax      = lineCap;
    x.axisLabels          = [self buildLabelTitle];
    x.labelingPolicy      = CPTAxisLabelingPolicyNone;
    x.minorTickLocations = [NSSet setWithArray:locationLabels];

    // Label y with an automatic label policy.
    lineCap.lineStyle       = axisLineStyle;
    lineCap.fill            = [CPTFill fillWithColor:[CPTColor colorWithComponentRed:CPTFloat(0.29019) green:CPTFloat(0.54118) blue:CPTFloat(0.76471) alpha:CPTFloat(1)]];
    CPTXYAxis *y = axisSet.yAxis;
    //    y.majorIntervalLength   = CPTDecimalFromDouble(5);
    y.majorTickLineStyle    = axisTickLineStyle;
    y.minorTickLineStyle    = axisTickLineStyle;
    y.axisLineStyle         = axisLineStyle;
    y.axisLineCapMax        = lineCap;
    y.axisConstraints       = [CPTConstraints constraintWithRelativeOffset:0];

    // Set axes
    graph.axisSet.axes = [NSArray arrayWithObjects:x, y, nil];
}

- (NSMutableSet*)buildLabelTitle
{
    NSMutableSet *newAxisLabels = [NSMutableSet set];

    CPTMutableTextStyle *textStyleB = [CPTMutableTextStyle textStyle];
    textStyleB.color = [CPTColor colorWithComponentRed:CPTFloat((float)0x09/0xFF) green:CPTFloat((float)0x31/0xFF) blue:CPTFloat((float)0x4A/0xFF) alpha:CPTFloat(1)];

    plotSpace.xRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromInt(corePlotNums - 9)length:CPTDecimalFromInt(10)];
    plotSpace.globalXRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromInt(0) length:CPTDecimalFromInt(corePlotNums + 1)];

    for ( NSUInteger i = 1; i < corePlotNums + 1; i++)
    {
        CPTAxisLabel *newLabel = [[CPTAxisLabel alloc] initWithText:[[m_labelStr objectAtIndex:i-1] substringWithRange:NSMakeRange(5, 11)] textStyle:textStyleB];
        newLabel.tickLocation = CPTDecimalFromUnsignedInteger(i);
        newLabel.offset = 5;
        [newAxisLabels addObject:newLabel];
        [newLabel release];
    }

    return newAxisLabels;
}

A: If the user is allowed to change the plot ranges (i.e., by pinch zooming), use a plot space delegate to monitor changes to the plot space. Use the new plot ranges and the size of the plot area to determine what time scale to use and how many labels to display. Adjust the axis labeling properties as needed.


text:
Q: Defining a lambda function in C++11 doesn't compile inside class I was trying to create a lambda function inside a c++ class, but it is giving compilation error. Code looks like:
class Test {

  public:
    struct V {
            int a;
    };

    priority_queue<V, vector<V>, function<bool(V&, V&)>>
            max_heap([](V& a, V& b) { return true; } );

};

The compilation error I am getting is:
test.cpp:32:22: error: expected identifier before '[' token
             max_heap([](V& a, V& b) { return true; } );
                      ^
test.cpp:32:35: error: creating array of functions
             max_heap([](V& a, V& b) { return true; } );
                                   ^
test.cpp:32:37: error: expected ')' before '{' token
             max_heap([](V& a, V& b) { return true; } );
                                     ^
test.cpp:32:54: error: expected unqualified-id before ')' token
             max_heap([](V& a, V& b) { return true; } );

Any explanation?

A: You cannot construct a class member using () inside the class body.  The compiler interprets this as trying to make a function.  Since you have C++11 you can use brace initialization to overcome this like
class Test {

  public:
    struct V {
            int a;
    };

    std::priority_queue<V, vector<V>, function<bool(V&, V&)>>
            max_heap{[](V& a, V& b) { return true; } };

};


text:
Q: How to define a 2D list While defining a 2D dynamic array why can't I define it like this:
List<List<Integer>> t=new List<List<Integer>();

On doing so, I got an error saying:
Cannot instantiate the type List<List<Integer>>

I came to know that this is the best practice for it-
List<List<Integer>> t=new Arraylist<List<Integer>>();

why is it so.can someone help me understand this.

A: List is an interface an as such can not use new to create a new instance of it, you need classes  that implement it instead eg ArrayList
List<List<Integer>> t=new ArrayList<List<Integer>>();

or since java 7
List<List<Integer>> t = new ArrayList<>();

A: Because in Java, List is an Interface you can't initialize it.
You can do it like that;
List<t> list = new ArrayList<t>();

Just initialize any types that implement the List Interface


text:
Q: Materialize Results to #Temp --Edit to include entire query, with error correct.
I am trying to create a Temp Table in an existing query that can be joined to.
I am getting the following error.
(746739 row(s) affected)
Msg 208, Level 16, State 1, Line 34
Invalid object name 'POD_TB'.

This is my first attempt with temp tables, I know I am missing something simple.
Thank you in advance.
DROP TABLE #POD_TB
CREATE TABLE #POD_TB
(
Delivery varchar(60)
  ,Shipment_Number varchar(60)
  ,Shipping_Carrier varchar(60)
  ,Tracking_Number varchar(60)
  ,Ship_Method varchar(60)
  ,POD_Signature varchar(60)
  ,POD_Date varchar(60)
  ,POD_Time varchar(60)
)

INSERT INTO #POD_TB
SELECT SHIPMENTS.Delivery
  ,SHIPMENTS.Shipment_Number
  ,PROOF_OF_DELIVERY.Shipping_Carrier
  ,PROOF_OF_DELIVERY.Tracking_Number
  ,PROOF_OF_DELIVERY.Ship_Method
  ,PROOF_OF_DELIVERY.POD_Signature
  ,PROOF_OF_DELIVERY.POD_Date
  ,PROOF_OF_DELIVERY.POD_Time
FROM
SHIPMENTS
LEFT JOIN PROOF_OF_DELIVERY
ON SHIPMENTS.Shipment_Number = PROOF_OF_DELIVERY.Delivery_Or_Shipment
WHERE Load_Date IN
(
SELECT MAX(Load_Date)
FROM PROOF_OF_DELIVERY
GROUP BY Delivery_Or_Shipment
)

SELECT DISTINCT GI.GOODS_ISSUE_DOCUMENT_ID
,GI.SALES_ORDER_ID
,GI.SALES_ORDER_LINE_ID
,GI.SALES_ORDER_TYPE_CODE
,GI.DELIVERY_HEADER_ID
,GI.DELIVERY_ITEM_ID
,FD.FISCAL_MONTH_CODE
,GI.MATERIAL_NUMBER
,GI.SHIPPED_QTY
,SO.ORDERER_NAME
,SO.CREATED_BY
,SO.CONTACT_PERSON
,GI.SOLD_TO_CUSTOMER_ID
,GI.SHIP_TO_CUSTOMER_ID
,GI.ORIGINAL_COMMIT_DATE
,GI.SHIP_FROM_PLANT_ID
,GI.ACTUAL_PGI_DATE
,GI.CUSTOMER_PO_NUMBER
,GI.SHIPPED_PRICE
,(GI.SHIPPED_PRICE * GI.SHIPPED_QTY) AS EXT_SHIPPED_PRICE
,GI.SALES_ORGANIZATION_CODE
,GI.DELIVERY_NOTE_PRIORITY_CODE
,FD.FISCAL_WEEK_CODE
,DV.DIVISION_CODE
,DN.Delivery_Item_Creation_Date
,SOLD.CUSTOMER_SHORT_NAME AS SOLD_TO_CUSTOMER_SHORT_NAME
,SHIP.CUSTOMER_SHORT_NAME AS SHIP_TO_CUSTOMER_SHORT_NAME
,SHIP.Customer_Site_Name
,SHIP.REGION_NAME
,MATD.MATERIAL_DESCRIPTION
,MATD.STANDARD_COST
,(MATD.STANDARD_COST * GI.SHIPPED_QTY) AS EXT_STANDARD_COST
,MATD.GLOBAL_EVENT
,PLT.LEAD_TIME_FOR_ORIGINAL_COMMIT
,OPRM.BASE_PART_CODE
,MATD.PRODUCT_INSP_MEMO
,MATD.MATERIAL_PRICING_GROUP_CODE
,MATD.MATERIAL_STATUS AS MMPP
,PIM.PIM_PBG_GROUPING
,SOL.SHIPPING_CONDITION
,SVO.SERVICE_ORDER_NUM
,SO.CREATION_TIME AS SO_CREATION_TIME
,SOL.CREATED_TIME AS SO_LINE_CREATED_TIME
,SOL.SHIPPING_POINT
,SDT.SALES_DOCUMENT_TYPE_CODE AS SVO_DOCUMENT_TYPE_CODE
,EQU.EQUIPMENT_NUM
,EQU.SERIAL_NUMBER
,EQU.CUSTOMERTOOLID
,POD.Shipment_Number
,POD.Shipping_Carrier
,POD.Tracking_Number
,POD.Ship_Method
,POD.POD_Signature
,POD.POD_Date
,POD.POD_Time
,DATEDIFF(dd,SO.CREATION_TIME,GI.ACTUAL_PGI_DATE) AS Cycle_Time_to_PGI_Days
,DATEDIFF(hh,SO.CREATION_TIME,GI.ACTUAL_PGI_DATE) AS Cycle_Time_to_PGI_Hours

FROM GOODS_ISSUE AS GI
INNER JOIN dbo.Delivery_Notes AS DN
ON GI.DELIVERY_HEADER_ID = DN.DELIVERY_HEADER_CODE AND GI.DELIVERY_ITEM_ID = DN.DELIVERY_ITEM_CODE
INNER JOIN dbo.Customer_View AS SOLD
ON GI.SOLD_TO_CUSTOMER_ID = SOLD.CUSTOMER_CODE
INNER JOIN dbo.Customer_View AS SHIP
ON GI.SOLD_TO_CUSTOMER_ID = SHIP.CUSTOMER_CODE
INNER JOIN dbo.MATERIAL_DETAILS AS MATD
ON GI.MATERIAL_NUMBER = MATD.MATERIAL_NUMBER
INNER JOIN dbo.OPR_MATERIAL_DIM AS OPRM
ON OPRM.MATERIAL_NUMBER = GI.MATERIAL_NUMBER
LEFT JOIN dbo.SM_DATE_DIM AS FD
ON CAST(FD.CALENDAR_DAY AS DATE) = CAST(GI.ACTUAL_PGI_DATE AS DATE)
LEFT JOIN dbo.DIM_PUBLISHED_LEAD_TIME_COMMIT AS PLT
ON PLT.MATERIAL_NUMBER = OPRM.BASE_PART_CODE
LEFT JOIN dbo.PRODUCT_INSP_MEMO_DIM AS PIM
ON PIM.PRODUCT_INSP_MEMO = MATD.PRODUCT_INSP_MEMO
INNER JOIN  dbo.SM_SALES_ORDER_LINE_FACT AS SOL
ON SOL.SALES_ORDER_CODE = GI.SALES_ORDER_ID AND SOL.SALES_ORDER_LINE_CODE = GI.SALES_ORDER_LINE_ID
INNER JOIN dbo.SM_SALES_ORDER_FACT AS SO
ON SO.SALES_ORDER_CODE = GI.SALES_ORDER_ID
INNER JOIN dbo.SM_DIVISION_DIM AS DV
ON SO.DIVISION_SID = DV.DIVISION_SID
LEFT JOIN dbo.SERVICE_ORDER_FACT AS SVO
ON SVO.SERVICE_ORDER_NUM = SO.SERVICE_ORDER_NUMBER
LEFT JOIN dbo.SM_SALES_DOCUMENT_TYPE_DIM AS SDT
ON SDT.SALES_DOCUMENT_TYPE_SID = SVO.SALES_DOCUMENT_TYPE_SID
LEFT JOIN dbo.SM_EQUIPMENT_DIM AS EQU
ON EQU.EQUIPMENT_SID = SVO.EQUIPMENT_SID
LEFT JOIN #POD_TB AS POD
ON POD.Delivery = GI.DELIVERY_HEADER_ID

WHERE GI.ACTUAL_PGI_DATE > GETDATE()-32
AND GI.SOLD_TO_CUSTOMER_ID IN (0010000252,0010000898,0010001121,0010001409,0010001842,0010001852,0010001879,0010001977,0010001978,0010002021,0010002202,0010002227,0010002982,0010003118,0010003176,0010003294,0010005492,0010006904,0010007048,0010007080,0010010381,0010010572,0010010905,0010011999,0010012014,0010012048,0010012571,0010013124,0010013711,0010013713,0010013824,0010014180,0010014188,0010014333,0010015059,0010015313,0010015414,0010015541,0010015544,0010015550)

A: Interesting that you cut the query off at the exact line that the error is on :)
I'm guessing you just forgot the hash (#) when querying from the temp table:
SELECT DISTINCT GI.GOODS_ISSUE_DOCUMENT_ID
...
FROM #POD_TB    // <-- notice the #
...

Also, a temp table might not be necessary - if you can join to the "temp" query as a subquery you may get better performance (assuming you don;t need the results for subsequent queries).


text:
Q: Mixed signal PCB layout for PSoC I am developing a PCB for an analogue sensing application. It uses the internal ADC on a PSoC3. As usual, the application is very space constrained (11mm x 21mm), so I have had to make some compromises in the PCB layout which I would not have done on a larger PCB.

The board is supplied by regulated 6v, and contains two 5v linear regulators. An MCP1702 for the digital supply, and an MIC5205 for the analogue supply. The board is sensing five A1324 Hall effect sensors. Each Hall effect output signal is filtered by a 100nF + 1k RC filter. One sensor is on the PCB itself (bottom right). The other 4 plug into the right hand 6-pin connector.
The chip is acting as an SPI slave, but ADC samples are always taken between SPI transactions, so the SPI should not interfere with the analogue signals.
Sadly, I am still seeing some noise (about 1.5 LSB at 12-bits) on the analogue signals, and I wonder if there is anything I could have done differently in the layout to improve it.

Please open the image in a new tab to see it in higher resolution.

Added:
Other PCB designs I have done using the MCP3208, and the same dual 5v supplies, same sensors, and same RC filters have achieved no noticeable noise at 12 bits.
The ADC on the PSoC3 is a delta sigma type. This version of the PSoC is limited to 12 bits, but another part number has a 16-bit ADC (although with a lower sample rate).
I do care about the noise, and would really like to push it a bit further towards 12 ENOB. The reason is not accuracy, but velocity measurement. Currently this level of noise is making it impossible to do accurate position and velocity control on a robot.

Added:
Schematic. Sorry it's a bit cramped, but you can just about read the values.

A: I agree with the above.  1.5LSB of noise is pretty reasonable.  http://www.cypress.com/?docID=39346 shows a minimum SINAD of 66 dB in 12 bit mode, suggesting ENOB = 10.7.
I know this isn't a direct answer to your question, but I'm going to interpret the question as "how do I fix my problems with velocity control?" and not "How do I get more than 10.5 ENOB?".
How are you differentiating?  Do you have enough spare clock ticks to do something a hair smoother than a two-point central difference? Maybe work out something 5 samples wide, optimized in Matlab?
Also, this might sound a bit funny, but velocity noise gets worse as you sample faster
$$\frac{1LSB}{\Delta t}$$ gets
 bigger as delta t gets smaller).  Try sampling only as fast as you need to, not as fast as you can.
Not to be insulting, but also take a quick glance to make sure nothing silly is going on in your velocity control, like issues with conversions between signed and unsigned integers, and make sure that your integers are wide enough to avoid overflow errors when you differentiate.  My own control equations often get complicated enough that I sometimes explicitly cast each operation.
Lastly, though perhaps most likely, are you losing effective bits off the top by not amplifying to near full scale?  If so, you can amplify or perhaps provide a smaller Vref.

A: You'll always have some noise on an ADC, especially SA (Successive Approximation) types on the microcontroller die. Sigma-delta perform better for Gaussian noise, as they integrate it. Don't expect 12 ENOB from a 12-bit ADC.
The controller's noise is a reason why most microcontrollers don't give you a higher resolution than 10 bit, and the AVR offers the possibility to stop the microcontroller during the ADC's acquisition, which should confirm that at least some of the noise comes from the controller.
But the question is: do you care? 1.5 bit of noise on a 12-bit ADC still leaves you more than 10 bits, or better than 0.1 %. How accurate is your Hall sensor? Other components in the circuit?
edit
You seem to use the PSoC's internal oscillator, since I don't see any crystal on the schematic. It looks OK: you have the proper decoupling. Apart from the internal clock the only high speed part in the circuit seems to be the SPI, but you say that this will be silent during measurements. The rest of the board is DC or probably relatively low frequent like the Hall effect sensors. And it's a Damn Small™, which also helps: shorter traces will pick up less noise. Sure I could nitpick about the MCP1702, which I would rotate 90° CCW so that the output capacitor can be placed even closer to the pins, but that won't solve the problems.
I only see one change in the layout which might improve your S/N ratio:

In the datasheet split analog and digital ground planes are suggested for "Optimal Analog Performance" (page 10).
For the rest: it's a small board like I said, that means short traces and decoupling within a few mm. So I would like to have another look at the noise's source. Prime suspect is the PSoC's clock. The PSoC can run a very low supply voltage, and that would reduce its noise. Of course it would help much if VDDA has to be lowered as well, but I didn't read anywhere in the datasheet that VDDA shouldn't be higher than VDDD.
Next, the ADC. On page 55 of the datasheet it says 66 dB SINAD, that's 11 bits, close to what you get now. The A1324 datasheet gives us 7 mVpp noise on a quiescent voltage of 2.5 V. That's also far less than the 72 dB S/N ratio which 12-bit could give you. You may improve this a little bit with extra filtering.
You mention the better performance of the MCP3208, but that's an ADC away from the microcontroller, and that may explain how an SA ADC can do better than a sigma-delta with the same resolution.
So, the options I see: lower the digital power supply voltage and split analog and digital grounds.


text:
Q: mod_rewrite / query_string I get some basic results from a mysql database and list it on a page, on the page I've added the links with the variable user_id:
href=\"http://localhost/TESTING/template.php?user_id=$user_id\" >click here

On the template.php file I'll get the $user_id and display the relevant full data.
The thing is I don't want user_id=249 http://localhost/TESTING/template.php?**user_id=**249 to show in the url I'd like something like "http://localhost/TESTING/template.php/249".
I've been looking into this for a few days now with no success, is this possible? Or does the template file need the user_id=$user_id to be displayed in order to get the variable?
=====================
To update: I added the code
RewriteEngine On
RewriteBase /TESTING/
RewriteRule ^template.php/([0-9]+)(/)?$ template.php?user_id=$1 [L]
Changed the link variable to href="localhost/TESTING/template.php/{$user_id}" >click here
The re-write now works, but I'm not getting the variable with $user_id = $_GET["user_id"]; on the template.php page
I added the following to the template.php page to see whats being passed through the url:
<?php
ini_set('display_errors',1);
echo '$_GET Variables
';
var_dump( $_GET );
echo '
';
?>

and got the following response:
$_GET Variables
array(1) {
  ["user_id"]=>
  string(2) "21"
}
How to get the variable?
===========
To update now works! {$user_id} in the link not {user_id} - could of swore i tried both ways.

A: Note that mod_rewrite only works on an Apache server.
RewriteEngine On

RewriteBase /TESTING/

RewriteRule ^template.php/([0-9]+)(/)?$ template.php?user_id=$1 [L]

A: I don't want to be inpolite, but there are a lot of manuals in the interwebs, e.g.
http://httpd.apache.org/docs/2.0/mod/mod_rewrite.html
which explains, with examples, everything you need. What have you tried so far? So we can explain what's wrong.


text:
Q: Up to how many elements a Dictionary can store in C# I have a program in C#. I keep on adding elements to a dictionary. At a points when dictionary has 5999471 elements and when I add one more element it give out of memory exemption in mscorlib.dll.

A:
The capacity of a Dictionary is the number of elements
  the Dictionary can hold. As elements are added to a
  Dictionary, the capacity is automatically increased as
  required by reallocating the internal array.
For very large Dictionary objects, you can increase the
  maximum capacity to 2 billion elements on a 64-bit system by setting
  the enabled attribute of the gcAllowVeryLargeObjects configuration
  element to true in the run-time environment.

Source.
The gcAllowVeryLargeObjects enables arrays that are greater than 2 gigabytes (GB) in total size but only in 64bit machines.
Also keep in mind that that is the maximum amount of objects the Dictionary may hold, but your system memory may not allow you to go that far.


text:
Q: How to create a custom url on wordpress site to be called from an external server? I am developing a plug-in for wordpress, and I need to expose an url to be called from a remote server that will send me 3 get variables.
my url(s) should be like this:

http://www.example.com/api/videos/callback/?variable1=value1&variable2=value2&variable3=value3

where example.com is my website.
And when I receive the call I want to get this variables and something.
I have to receive 3 calls the first with 2 of this variables and seconde with 3 variables and the third one with 1 variable.
All of these calls will be the answer of my request sent with curl(but I think it doesn't matter).
I tried rewrite rules and add_endpoint but I didn't figure where and how to use it and if i need some additional plugin to do so.
Thank you for your help!

A: Use wp_remote_get() .
See the Wordpress Codex for more info about this function.

A: You can install wordpress plugin json api for this
https://wordpress.org/plugins/json-api/
Also please go through installation notes
https://wordpress.org/plugins/json-api/other_notes/

A: in case anyone want to know the answer, i simply used
      add_rewrite_rule('^api/videos/callback$', 'index.php', 'top');

      flush_rewrite_rules(true);

and for the variables i didn't make any thing, to access them i used $_GET and making all checks is exists i then execute my code.


text:
Q: Module view file showing invalid in Codeigniter 4 I've added the module folder in ...\app\Config\Autoload.php
public $psr4 = [
          APP_NAMESPACE => APPPATH, // For custom app namespace
          'Config'      => APPPATH . 'Config',
          'Blog'      => ROOTPATH . 'example/blog',
];

My directory:
/Home directory of main project folder
/example
    /Blog
        /Config
            /Routes.php
        /Controllers
            /Blog.php
        /Views
           /show_blog.php

Routes.php
namespace Config;

// Create a new instance of our RouteCollection class.
$routes = Services::routes();

$routes->get('blog', 'blog::index', ['namespace' => 'Blog\Controllers']);

Blog.php
namespace Blog\Controllers;

class Blog extends \CodeIgniter\Controller {

    function index() {
        echo view('Example\Blog\Views\show_blog');
    }

}

After running my_domain/index.php/blog, it's showing this error:
CodeIgniter\View\Exceptions\ViewException

Invalid file: Example\Blog\Views\show_blog.php

Didn't get any solution from this one: Codeigniter 4 View file invalid
Where am I wrong?

A: Changing Blog.php to this, worked for me.
namespace Blog\Controllers;

class Blog extends \CodeIgniter\Controller {

    function index() {
        echo view('Blog\Views\show_blog');
    }

}

Credit: CI Forum


text:
Q: How to do a SPA using servlets and jsp? I'm trying to do a single page application using servlets and jsp pages.
For the moment I have the first page, which is simple to do: a servlet that forwards to the corresponding jsp.
How should the implementation look when navigating to the second page?
I guess it should be an ajax call, the servlet would populate the necessary data, but how to display the second page jsp?

A: JSP is a server side ui technology. A Servlet listens to specific urls and redirects to JSPs pages. The JSP is compiled to a class (another servlet in fact), invoked (data will be added and inline scripts will run) and the output, whith is HTML, is send to the client (browser). To get to a different page its neccessary to query the server (servlet) for another url, resulting in another html page.
To create an SPA you need a client side technology like JavaScript. Your query the server for a single html page. The page, made of HTML and JavaScript, for example, (could even be the output of a single JSP, dont get confused) is send to the client (browser) and the JS is run. This is nomaly backed up by a framework like AngularJS, EmberJS or Backbone. Once the page is set up, the links within the page are anchors (http://example.com/#/mySecondPage), so clicking them will invoke the framework again (Ajax, querying the server for new data), but will stay on the same page. Some contents of the page might then be replaced by new content.

A: If it is a true SPA then you would just have a single JSP and handle all your functionality (after your initial page load) using Ajax.
Have you looked at using a client-side framework such as Angular to help you with this?
Depending on how rich your SPA is, you could either use the same servlet or multiple servlets to serve each page.
Unless you are doing this for a course or tutorial and have some constraints on how to achieve it, you will very probably save yourself a lot of time if you couple something like Angular with a server-side framework like Spring instead of coding servlets. As a suggestion have a look at Spring with Angular.

A: In SPA the browser only loads the document once (or a few, once per sub-application), and further communication to the server is done usually via AJAX or Websockets.
I recommend you to model your application as a thin server architecture, that is, a client application running in the browser (HTML, CSS, Javascript) consuming a web service API provided by the server.
The following are some points worth knowing;

*

*Client-side:

*

*Only presentation logic

*Represent state by URL hash. This enables bookmarking, hyperlinking and browsing history. Your client app should listen to changes in the URL hash and act in consequence. This technique is called "routing" and it is implemented by all Javascript frameworks.

*Client application is packaged server-side such it can be downloaded in a single request (in .html, .jsp, servlet, .jsp + multiple .jspf, ...)

*Consumes services provided by the server via AJAX or Websockets

*Server:

*

*Offers client application to download

*Provides a clean, stateless API to be consumed by the client application, better returning JSON (data) than HTML (presentation logic) (Why is it a bad practice to return generated HTML instead of JSON? Or is it?)

*Use a REST or JSON-RPC frameworks to create the API. There is a lot of debate on what to choose (see here or here). In my opinion the only advantage of REST over RPC is that since REST has become a "de facto" standard its interoperability is higher, so my recommendation for SPA applications is using JSON-RPC, because your code is the only client of the API.

There are lots of alternatives for both client and server frameworks.
Javascript: AngularJS, EmberJS or Backbone,...
REST: Spring, Jersey, Restlet,..
JSON-RPC: https://en.wikipedia.org/wiki/JSON-RPC#Implementations
Regarding JSON-RPC, you might want to take a look to Brutusin-RPC, a JEE microframework I have created :)

A: If you are using an Ajax request, then you need to tell the browser that redirect to the second page. Example:
response.sendRedirect("second_page.jsp");

In your servlet, you need to differentiate a request to the first page, from a request that need to be redirected to the second page. You can use parameters, or session values, for example.
if (request.getParameter("page2") != null) {
    response.sendRedirect("second_page.jsp");
} else {
    .... // include here the normal logic of your Servlet for page 1
}

Then, you can invoke your servlet with or wihout the parameter page2, to go to page 1 (without parameter), or page 2 (with parameter).


text:
Q: Rescale image in imageview In my app I can take a photo from the camera and display it in an imageview, but what I want to be able to do is rescale/resize the resolution of the image so it's not as big and does not take up so much memory in the app.
Here is the code I use for displaying the image in the imageview:
image = [info objectForKey:UIImagePickerControllerOriginalImage];
[ImageView1 setImage:image];    // "ImageView1" name of any UImageView.
[self dismissViewControllerAnimated:YES completion:NULL];

I want the image scaled down as the image can also be sent via email, so it must be nice and small.

A: You can try this code:
+ (UIImage*)imageWithImage:(UIImage*)image
           scaledToSize:(CGSize)newSize;
{
  UIGraphicsBeginImageContext( newSize );
 [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
 UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
 UIGraphicsEndImageContext();

 return newImage;
}

As far as storage of the image, the fastest image format to use with the iPhone is PNG, because it has optimizations for that format. However, if you want to store these images as JPEGs, you can take your UIImage and do the following:
NSData *dataForJPEGFile = UIImageJPEGRepresentation(theImage, 0.6);

This creates an NSData instance containing the raw bytes for a JPEG image at a 60% quality setting. The contents of that NSData instance can then be written to disk or cached in memory.
You can refer this link also: UIImage: Resize, then Crop
Hope this will helps you.


text:
Q: Facebook Graph Api publish photo to fan page album and tag author on it We are a French Mobile Agengy working on a touchy Facebook integration (Graph API and mobile SDK).
That application (iOS & Android) consist in a picture contest, where the winner is the one who gets the more likes on its picture published on the Facebook Fan Page.

*

*Each user connect via Facebook Connect.

*They can take a picture with their phone and upload it to our server for moderation.

*When the picture is validated by our review team we want to do the following interactions with Facebook :
3-1. Publish the picture to a specific album of a fan page (this part is working well, doing validation with a Facebook connected user, being admin of the fan page and granting "manage_pages" to the fbapp of this operation)
3-2. Then we want to "tag" the author on the photo - author being the facebook user which uploaded the photo to our server -, so that the picture shows off on this user timeline - not a post referencing the picture, because the "likes" must be on the picture and not on a share of it.
We are stuck on the 3-2 step, since we could not find a way to properly tag a user on a fan page picture using Graph API (either as a user or a page or an app - access_tokens).
In a more functional point of view, we want to post a picture in a Facebook Fan Page Album (via a fbapp), and have this picture integrated on both Fan Page and User (Author) timelines without having to repost this picture (to prevent likes fragmentation between picture and shares).
Hope my explanations are clear, any help will be (greatly) welcome. :)


text:
Q: ImportError: No module named conda.cli.main while setting up conda My conda module is in the path '/opt/cloudera/parcels/Anaconda/bin'
In the .bash_profile I added the following:
PATH=$PATH:/opt/cloudera/parcels/Anaconda/bin
export PATH

Yet when I type
conda --version

I get
Traceback (most recent call last):
File "/opt/cloudera/parcels/Anaconda/bin/conda", line 4, in <module>
from conda.cli.main import main
ImportError: No module named conda.cli.main

A: I show the ~/.zshrc ( or ~/.bash_profile ) which is the default shell in my Mac.
# >>> conda initialize >>>
# !! Contents within this block are managed by 'conda init' !!
__conda_setup="$('/opt/anaconda3/bin/conda' 'shell.bash' 'hook' 2> /dev/null)"
if [ $? -eq 0 ]; then
    eval "$__conda_setup"
else
    if [ -f "/opt/anaconda3/etc/profile.d/conda.sh" ]; then
        . "/opt/anaconda3/etc/profile.d/conda.sh"
    else
        export PATH="/opt/anaconda3/bin:$PATH"
    fi
fi
unset __conda_setup
# <<< conda initialize <<<

After installing Anaconda that is how it looks like. You can try source ~/.bash_profile or ~/zshrc to check if it base is activated by Anaconda.
If you want to deactivate base look at this

A: I followed the process in the continuum documentation and it worked.
Please see: https://docs.continuum.io/anaconda/install/linux


text:
Q: Find generating function for the pattern Denote $p(n)$ is the numbers of any size rectangle count on these pattern

Problem :
Find generating function that $p(n)$ is coefficient of function.

I try to read out for some $p(n)$ and get
$p(1)=1$
$p(2)=2\binom{3}{2}-1 = 5$
$p(3)=(2\binom{4}{2}-1) + \binom{3}{2}^{2}  - (2\binom{3}{2}-1) = 15$
$p(4)= (2\binom{5}{2}-1) +  (2\binom{3}{2}\binom{4}{2}-\binom{3}{2}^{2})  - (2\binom{4}{2}-1) = 35$ and so on
We found that $p(n) = \frac{1}{3}(2n^{3}-3n^{2}+7n-3)$
The problem is I cannot find a generating function that has $p(n)$ as a coefficient.
Please give me some hint or any advice. Thank you and I appreciate for any helps.

A: We derive a recurrence relation for $p(n), n\geq 1$ and calculate from it the generating function
\begin{align*}
P(x)&=\sum_{j=1}^\infty p(j)x^j\\
&=p(1)x+p(2)x^2+p(3)x^3+p(4)x^4\cdots\\
&=x+5x^2+15x^3+35x^4+\cdots
\end{align*}
In order to go from $p(n-1)$ to $p(n)$ it is convenient to add squares at the diagonal. See the graphic below.

In each step we add a new square at the diagonal. The rectangles we  count in one step do not interfere with rectangles from former steps, since the new square is always part of these rectangles. In fact this way we partition the rectangles we count when going from $p(n-1)$ to $p(n)$, so that we can simply sum them up. In general we have for $n\geq 1$:
\begin{align*}
\color{blue}{p(n)}&\color{blue}{=p(n-1)+\sum_{j=1}^{n}j(n+1-j)\qquad\qquad n\geq 2}\tag{1}\\
\color{blue}{p(1)}&\color{blue}{=1}
\end{align*}
We simplify (1) by using the summation formulas
$$\sum_{j=1}^nj=\frac{1}{2}n(n+1), \qquad\qquad\sum_{j=1}^nj^2=\frac{1}{6}n(n+1)(2n+1)$$ and obtain
\begin{align*}
\color{blue}{p(n)}&\color{blue}{=p(n-1)+\frac{1}{6}n(n+1)(n+2)\qquad\qquad n\geq 2}\tag{2}\\
\color{blue}{p(1)}&\color{blue}{=1}
\end{align*}

We obtain from (2) the generating function $P(x)$ as follows
  \begin{align*}
P(x)&=\sum_{n=1}^\infty p(n)x^n=x+\sum_{n=2}^\infty p(n)x^{n}\\
&=x+\sum_{n=2}^\infty \left(p(n-1)+\frac{1}{6}n(n+1)(n+2)\right)x^n\\
&=x+\sum_{n=1}^\infty p(n)x^{n+1}+\frac{1}{6}x\sum_{n=2}^\infty n(n+1)(n+2)x^{n-1}\\
&=x+\sum_{n=1}^\infty p(n)x^{n+1}+\frac{1}{6}xD_x\sum_{n=2}^\infty (n+1)(n+2)x^{n}\tag{3}\\
&=x+\sum_{n=1}^\infty p(n)x^{n+1}+\frac{1}{6}xD_x^2\sum_{n=2}^\infty(n+2)x^{n+1}\\
&=x+xP(x)+\frac{1}{6}xD_x^3\sum_{n=2}^\infty x^{n+2}\tag{4}\\
&=x+xP(x)+\frac{1}{6}xD_x^3\frac{x^4}{1-x}\\
&=x+xP(x)+\frac{x}{(1-x)^4}-x\\
\color{blue}{P(x)}&\color{blue}{=\frac{x}{(1-x)^5}}\tag{5}
\end{align*}

In (3) we use the differential operator $D_x=\frac{d}{dx}$ and continue successively till we get a geometric series in (4). It is convenient to use the coefficient of operator $[x^n]$ to denote the coefficient of $x^n$.

We finally obtain from (5) for $n\geq 1$
\begin{align*}
[x^n]P(x)&=[x^n]\frac{x}{(1-x)^5}\\
&=[x^{n-1}]\sum_{j=0}^\infty\binom{-5}{j}(-x)^j\\
&=[x^{n-1}]\sum_{j=0}^\infty\binom{j+4}{4}x^5\\
&=\binom{n+3}{4}\\
&\,\,\color{blue}{=\frac{1}{24}n(n+1)(n+2)(n+3)}
\end{align*}

A: Hint:
$$p(n) = 1 + 2 + 3 + \ldots + n = \sum_{i = 1}^n i = \frac{n(n + 1)}{2},$$
hence you're looking for
$$f(x) = \sum_{i = 0}^\infty \frac{i(i + 1)}{2} x^i$$


text:
Q: How to set Time picker in Material design Angular 6? I am try to set time picker module in material design angular 6 theme but I cannot set because in this theme using MAT format for material design.
I had used many module for time picker but in material theme can't set ng or md or other module.

A: Approach ignite-ui-angular
npm install -g igniteui-cli

app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';

// Here we import the IgxGridModule, so we can use the igxGrid!
import { IgxGridModule } from 'igniteui-angular';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    BrowserAnimationsModule,
    IgxGridModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

component
// app.module.ts
...
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { IgxTimePickerModule } from 'igniteui-angular';

@NgModule({
    ...
    imports: [..., BrowserAnimationsModule, IgxTimePickerModule],
    ...
})
export class AppModule {}

meeting.component.html
<igx-time-picker ></igx-time-picker>


text:
Q: Google Charts Timeline Labels display outside of box I am using google timeline chart in my project. Below the screen shot attach.
Some label display out side of bar. Any Solution that text fit in bar. Reference link Google timeline chart .


text:
Q: PHP Gettext: how to change the default MO path after setting the path of the domain? I use PHP Gettext extension for localizing a Web app. When you do:
bindtextdomain("example", "/locales");

If you're setting the locale to fr_FR, it will look for the MO in:
/locales/fr_FR/LC_MESSAGES/example.mo

Is there a way to customize that path? For instance I would like to use the following structure:
/locales/example.fr_FR.mo

A: The directory structure is fixed by gettext.

Because many different languages for many different packages have to be stored we need some way to add these information to file message catalog files. The way usually used in Unix environments is have this encoding in the file name. This is also done here. The directory name given in bindtextdomains second argument (or the default directory), followed by the name of the locale, the locale category, and the domain name are concatenated:
dir_name/locale/LC_category/domain_name.mo


text:
Q: QProcessEnvironment a value with spaces and quotes I am setting the environment for a program I will be launching using QProcess.  One of the environment variables I need to set MAY contain spaces, slashes, and quotes.  What is the right way to handle this?
I've tried escaping quotes, and adding a \" to either end of the string but my environment variable is always blank.  Can someone share a code sample of how to handle this?
I'm thinking about this:
a = "\""+a.replace(QRegExp(QLatin1String("(\\\\*)\"")), QLatin1String("\\1\\1\\\""))+"\"";

but after numerous attempts I thought I would ask for help too.
For example, if a is:
A" \ / '

and I try to set an environment variable through
environment << "a=\""+a+"\""

and pass environment as the first parameters for a qprocess run, then the variable is NOT set when the qprocess starts, due to the fact that the environment ignores the malformed string.


text:
Q: I need to add button in showcase view 'GOT IT' I need to add button in showcase view 'GOT IT'. How to show button 'GOT IT'  here?
public voidshowcase() {
    new MaterialShowcaseView.Builder(this)
        .setTarget(accident)

        .setDismissText("GOT IT")
        .setDismissTextColor(Color.parseColor("#404040"))
        .setShapePadding(140)
        .setContentText("Touch the yellow fab below to see more services")
        .setDelay(withDelay)
// optional but starting animations immediately in onCreate can make them choppy
       .singleUse(SHOWCASE_ID) // provide a unique ID used to ensure it is only shown once
        .show();
}

A: Try this out :
  private ShowcaseView showcaseView = new ShowcaseView.Builder(getActivity())
                    .setTarget(new ViewTarget(diagnostics))
                    .setOnClickListener(counterClick)
                    .setStyle(R.style.CustomShowcaseTheme)
                    .build();

            showcaseView.setButtonText(getString(R.string.next));
            showcaseView.forceTextPosition(ShowcaseView.BELOW_SHOWCASE);
            showcaseView.setContentTitle("Search and book Diagnostics");


text:
Q: Strip the last path directory from path string in Ruby/Rails Is there an easy and fast operation to just strip the last path of a directory of a path in ruby without using regex?
path examples:
has="/my/to/somewhere/id"
wants="/my/to/somewhere"

Currently I am using:
path.split('/')[0...-1].join('/')

For has I will always know the id so I could also use:
path.sub("/#{id}", '')

So my question is really, which operation is faster??

A: Well, you can use Pathname#parent method.
require 'pathname'

Pathname.new("/my/to/somewhere/id").parent
# => #<Pathname:/my/to/somewhere>
Pathname.new("/my/to/somewhere/id").parent.to_s
# => "/my/to/somewhere"

A: Using Pathname is a little bit faster than split. On my machine, running a million times:
require 'benchmark'
require 'pathname'

n = 1000000
id = "id"
Benchmark.bm do |x|
  x.report("pathname: ") { n.times { Pathname("/my/to/somewhere/id").dirname.to_s } }
  x.report("split:") { n.times { "/my/to/somewhere/id".split('/')[0...-1].join('/') } }
  x.report("path.sub:") { n.times { "/my/to/somewhere/id".sub("/#{id}", '') } }
end

I have got the following results:
              user     system      total        real
pathname:   1.550000   0.000000   1.550000 (  1.549925)
split:      1.810000   0.000000   1.810000 (  1.806914)
path.sub:   1.030000   0.000000   1.030000 (  1.030306)

A: There is a method for Pathname - split, which:

Returns the dirname and the basename in an Array.

require 'pathname'

Pathname.new("/my/to/somewhere/id").split.first.to_s
# => "/my/to/somewhere"

Hope that helps!


text:
Q: dropbox.exceptions.ApiError: ... CreateFileRequestError('validation_error', None) I want to get and save the URL of an image to a variable via dropbox API in python. I'm following this guide but I get the error shown in the title.
I searched for the function dbx.file_requests_create and probably doing something wrong with title or destination. Should the title be some existing source? Because I just set it by myself.
import dropbox

dbx = dropbox.Dropbox('Y2_M...aVP')
req = dbx.file_requests_create(title='Images', destination='/C:/Users/Dropbox/Apps/myProject/image.jpg')
print req.url
print req.id

EDIT: I found this link FileRequestError. It says:

There was an error validating the request. For example, the title was invalid, or there were disallowed characters in the destination path.

EDIT-2 [SOLVED]: Thanks to Aran-Fey and Greg for their comments, I solved the problem by replacing req = dbx.file_requests_create(title='Images', destination='/C:/Users/Dropbox/Apps/myProject/image.jpg') with

req = dbx.sharing_create_shared_link_with_settings('/image.jpg', settings=None)

Also, for people who have problem with getting the image when sharing it,  just change the last character of the link from 0 to 1 as mentioned on this and this.
You can add this line to the end newURL = req.url[:-1] + "1" to solve the matter.


text:
Q: TFileStream with offset I need to extend TFileStream so that it can work with a file not from 0 offset, but from user defined offset. I mean it must interpret user defined offset as stream beginning. My code is:

type
  TSuFileStream = class(TFileStream)
  protected
    FOffset : int64;

    procedure SetOffset(Offset : int64);

    procedure SetSize(NewSize: Longint); override;
    procedure SetSize(const NewSize: Int64); override;
  public
    constructor Create(const AFileName: string; Mode: Word); overload;
    constructor Create(const AFileName: string; Mode: Word; Rights: Cardinal); overload;

    function Seek(Offset: Longint; Origin: Word): Longint; override;
    function Seek(const Offset: Int64; Origin: TSeekOrigin): Int64; override;

    property Offset : int64 read FOffset write SetOffset;
  end;
...
constructor TSuFileStream.Create(const AFileName: string; Mode: Word);
begin
  inherited Create(AFileName, Mode);
  FOffset := 0;
end;

constructor TSuFileStream.Create(const AFileName: string; Mode: Word; Rights: Cardinal);
begin
  inherited Create(AFileName, Mode, Rights);
  FOffset := 0;
end;

procedure TSuFileStream.SetOffset(Offset : int64);
begin
  FOffset := Offset;
  inherited Seek(FOffset, soBeginning);
end;

procedure TSuFileStream.SetSize(NewSize: Longint);
begin
  inherited SetSize(FOffset + NewSize);
end;

procedure TSuFileStream.SetSize(const NewSize: Int64);
begin
  inherited SetSize(FOffset + NewSize);
end;

function TSuFileStream.Seek(Offset: Longint; Origin: Word): Longint;
begin
  Result := Seek(Int64(Offset), TSeekOrigin(Origin));
end;

function TSuFileStream.Seek(const Offset: Int64; Origin: TSeekOrigin): Int64;
begin
  case Origin of
    soBeginning: Result := inherited Seek(FOffset + Offset, soBeginning) - FOffset;
    soCurrent: Result := inherited Seek(Offset, soCurrent) - FOffset;
    soEnd: Result := inherited Seek(Offset, soEnd) - FOffset;
  end;
end;

but it does not work propertly. The problem is in Seek function but I don't know why. When I pass such stream to a third party component it works only if TSuFileStream.Offset := 0;

A: First, only override one of the method versions. As you can see from the class interface you have both longint and int64 versions of the same methods (like setSize and seek). This is in the Delphi documentation. Override the int64 versions.
Secondly, I would not override TFilestream but rather TStream directly to create a "in between stream" to work with.
In the constructor I would put 2 parameters:

*

*Actual source stream of any type

*Offset

So basically what you want to create is a proxy between the real stream and your custom version. That way, in your seek implementation all you have to add the offset (look at TMemoryStream and TFileStream to see how it's done) to the position. You also get the benefit of supporting any type of stream-source.
You should end up with a proxy that is easy to use:
mMyStream:=TMyProxyStream.Create(mRealStream,2800); //Root offset at 2800
try
  mMyStream.Read(mBuffer,1024); // After read, offset = 3824
  mMyStream.position:=0; //Reset offset back to to 2800
finally
  mMyStream.free;
end;

The seek functionality can be a bit tricky to calculate. Here is an example from a proxy class i coded for my buffer system (FOffset being an internal variable, this is the one you want to manipulate):
function TSLBufferStreamAdapter.Seek(const Offset:Int64;
         Origin:TSeekOrigin):Int64;
Begin
  Case Origin of
  soBeginning:
    Begin
      if Offset>=0 then
      FOffset:=Math.EnsureRange(Offset,0,FBufObj.Size);
    end;
  soCurrent:
    Begin
      FOffset:=math.EnsureRange(FOffset + Offset,0,FBufObj.Size);
    end;
  soEnd:
    Begin
      If Offset>0 then
      FOffset:=FBufObj.Size-1 else
      FOffset:=math.EnsureRange(FOffset-(abs(Offset)),0,FBufObj.Size);
    end;
  end;
  result:=FOffset;
end;

I update this reply now to include an update link. My library byterage has moved to google code - have a look there. Hope it helps!

A: Use TGpStreamWindow, available on my web and on Google Code.
Usage:
var
  offsetStream: TGpStreamWindow;

begin
  offsetStream := TGpStreamWindow.Create(originalStream, initialOffset, originalStream.Size - 1);
  try
    DoSomethingWith(offsetStream);
    offsetStream.SetWindow(anotherInitialOffset, originalStream.Size - 1);
    DoSomethingElseWith(offsetStream);
  finally FreeAndNil(offsetStream); end;
end;


text:
Q: Using prompt with some color picker Can I using prompt with some color color picker? Now, my code is:
case 'foreColor':
    var color = prompt('Define a base color or apply a hexadecimal color code for advanced color:', '');
    document.execCommand('foreColor', false, color);
    break;

And how can I do this color picker? I would like to define a few colors for the user to click, not typing.


text:
Q: SonarQube - unable to write message error We have just updated to TFS 2017 and I'm going through setting up SonarQube integration into pull requests for our builds.  In the process I've come across an issue that I can't seem to figure out.
We have three build servers each with two sets of build agents on them. Let's call them BA1 and BA2. Also, we are using the new SonarQube plugin for TFS not the deprecated one referenced here.
BA2 works perfectly. Haven't had a single problem with generating both incremental and full analysis reports. However, any build that is using BA1 ultimately makes it about halfway through the End Analysis step before failure with a message similar to this:
ERROR: Error during SonarQube Scanner execution
org.sonar.core.util.ContextException: Unable to write message | file=E:\workingDirectory\_work\3\.sonarqube\out\.sonar\batch-report\component-5072.pb

... //long stacktrace

Caused by: java.io.FileNotFoundException: E:\workingDirectory\_work\3\.sonarqube\out\.sonar\batch-report\component-5072.pb (The directory or file cannot be created)

I'm pretty sure it's not a permissions problem because all builds run under the same user account. It doesn't matter which project or build server it runs on. All jobs that run with BA2 are successful. All jobs that run with BA1 fail with this error. I saw a similar question here but the solution to that problem will not work for me. I don't have an issue with another job being queued into the same workspace.
Just trying to see if its possible anyone has run into this before. I've checked the build agent logs under the _diag directory but haven't been able to find anything useful. I've run out of ideas to check. Thanks for any tips.

A: Turns out that for the builds that were failing the drive (E:) was formatted as a FAT32 RAM drive. The drive wasn't full but we were still hitting some sort of limit on that drive that was causing the builds to fail.
I don't think it was a file count limit because we deleted several files from the directory and tried to add a new one and it wouldn't allow us to add one. When I deleted all files under the batch-report directory it finally allowed me to add files again. I'm assuming it was some sort of directory size limit that was causing the problem. In any case, instead of wasting time trying to figure out exactly what the cause was we reformatted the drive to NTFS and the build issues went away. Thanks everyone for the ideas and tips.


text:
Q: Superscript Citation Within Endnote Appearing on Line By Itself I am using biblatex with the memoir class, using the oxnum style so that citations appear as superscript numerals. I am also using the enotez package for endnotes. (These are generally longer text passages, not necessarily having to do with bibliographic citations.) I have defined a command \qattribute which I use at the end of quotations to put the author and title there in the body of the text, and include the citation referring to the more complete bibliographic entry. Most of the time this behaves as desired. However, whenever I have a quotation within an endnote, the superscript citation numeral does not appear next to the title as it should. Instead it appears below on a line by itself.

I don't understand why \autocite is behaving differently in the endnotes than in the main text.
I have made an MWE, with a quotation in the body of the text and a quotation within an endnote. Here is my LaTeX file:
\documentclass[10pt]{memoir}
\usepackage{hang}
\setlength\hangingleftmargin{0.2\textwidth}
\usepackage{enotez}
\setenotez{list-name={Endnotes},list-heading={\chapter*{#1}},counter-format=alph,backref=true}
\renewcommand*{\theendnote}{\alph{endnote}}
\usepackage[%
    autocite    = superscript,
    backend     = bibtex,
    sorting     = none,
    style       = oxnum,
    backref     = true,
]{biblatex}
\addbibresource{MWE.bib}
\usepackage{hyperref}
\usepackage{xifthen}
\newcommand\qattribute[3][]{%
    \par\begin{hangingpar}--\ifthenelse{\isempty{#1}}{#2{#3}}{#2, \textit{#1}{#3}}\end{hangingpar}\vskip\onelineskip}
\renewcommand\bibname{Endnotes}
\begin{document}
This enthusiasm is not necessarily spectacular or showy, but a discerning observer or participant can perceive a deep wellspring flowing from teacher to student:
                                                    \begin{quotation}
\noindent{}Students gravitate toward teachers with whom they have forged a connection.\end{quotation}
                            \protect\qattribute[Excellent
                                    Sheep]%
{William Deresiewicz}%
{\protect\autocite{C108179}}
                        \par\noindent{}

These two departments had been at odds for thirty years.\protect\endnote{\begin{quotation}
\noindent{}

What we're saying is that the company in the past has been locked in.…If we're going to work on the total needs of the customer…there has to be a way that that's seen in a lot of different places in the company.
                                                                            \end{quotation}
\protect\qattribute[The Fifth Discipline: The Art {\symbol{38}} Practice of The Learning Organization]%
                                        {Peter M. Senge}%
{}{\protect\autocite{C108184}}
\par\noindent{}                         }
                            \autocite{C108185}

\printbibliography[title={References}]
\backmatter
\printendnotes
\end{document}

Here is the accompany BibTeX file MWE.bib:
@book{C108179,
author={William Deresiewicz},
title={Excellent Sheep},
publisher={Free Press, division of Simon and Schuster Inc},
year={2014},
}
@book{C108184,
author={Peter M. Senge},
title={The Fifth Discipline: The Art {\symbol{38}} Practice of The Learning Organization},
address={New York},
publisher={Doubleday},
year={1990},
pages={pp. 264–5},
annote={},
}
@book{C108185,
author={Peter M. Senge},
title={The Fifth Discipline: The Art {\symbol{38}} Practice of The Learning Organization},
address={New York},
publisher={Doubleday},
year={1990},
}

How I can get the citation numerals to appear next to the titles on quotation attributions in the endnotes, as they do in the main text?

A: You have a spurious {}, likely due to the strange formatting you use:
\protect\qattribute[The Fifth Discipline: The Art {\symbol{38}} Practice of The Learning Organization]%
                                        {Peter M. Senge}%
{}{\protect\autocite{C108184}}

You see the {} at the beginning of the last line.
\begin{filecontents*}{\jobname.bib}
@book{C108179,
author={William Deresiewicz},
title={Excellent Sheep},
publisher={Free Press, division of Simon and Schuster Inc},
year={2014},
}
@book{C108184,
author={Peter M. Senge},
title={The Fifth Discipline: The Art {\symbol{38}} Practice of The Learning Organization},
address={New York},
publisher={Doubleday},
year={1990},
pages={pp. 264–5},
annote={},
}
@book{C108185,
author={Peter M. Senge},
title={The Fifth Discipline: The Art {\symbol{38}} Practice of The Learning Organization},
address={New York},
publisher={Doubleday},
year={1990},
}
\end{filecontents*}

\documentclass[10pt]{memoir}
\usepackage{hang}
\usepackage{enotez}

\usepackage[%
    autocite    = superscript,
%    backend     = bibtex,
    sorting     = none,
    style       = oxnum,
    backref     = true,
]{biblatex}
\usepackage{hyperref}
\usepackage{xifthen}

\setlength\hangingleftmargin{0.2\textwidth}
\setenotez{list-name={Endnotes},list-heading={\chapter*{#1}},counter-format=alph,backref=true}
\renewcommand*{\theendnote}{\alph{endnote}}

\addbibresource{\jobname.bib}

\newcommand\qattribute[3][]{%
    \par\begin{hangingpar}
    --\ifthenelse{\isempty{#1}}{#2{#3}}{#2, \textit{#1}{#3}}
    \end{hangingpar}\vspace{\onelineskip}}

%\renewcommand\bibname{Endnotes}

\begin{document}

This enthusiasm is not necessarily spectacular or showy, but a discerning
observer or participant can perceive a deep wellspring flowing from teacher to student:
\begin{quotation}
\noindent{}Students gravitate toward teachers with whom they have forged a connection.
\end{quotation}
\qattribute[Excellent Sheep]{William Deresiewicz}{\autocite{C108179}}

These two departments had been at odds for thirty years.\endnote{%
  \begin{quotation}
  \noindent{}What we're saying is that the company in the past has been locked in.…
  If we're going to work on the total needs of the customer…
  there has to be a way that that's seen in a lot of different places in the company.
  \end{quotation}
  \qattribute[The Fifth Discipline: The Art {\symbol{38}} Practice of The Learning Organization]%
             {Peter M. Senge}{\autocite{C108184}}%
}

\printbibliography[title={References}]

\backmatter
\printendnotes

\end{document}

You also need no \protect.

A different implementation, that simplifies the input.
\begin{filecontents*}{\jobname.bib}
@book{C108179,
author={William Deresiewicz},
title={Excellent Sheep},
publisher={Free Press, division of Simon and Schuster Inc},
year={2014},
}
@book{C108184,
author={Peter M. Senge},
title={The Fifth Discipline: The Art {\symbol{38}} Practice of The Learning Organization},
address={New York},
publisher={Doubleday},
year={1990},
pages={pp. 264–5},
annote={},
}
@book{C108185,
author={Peter M. Senge},
title={The Fifth Discipline: The Art {\symbol{38}} Practice of The Learning Organization},
address={New York},
publisher={Doubleday},
year={1990},
}
\end{filecontents*}

\documentclass[10pt]{memoir}
\usepackage{hang}
\usepackage{enotez}

\usepackage[%
    autocite    = superscript,
%    backend     = bibtex,
    sorting     = none,
    style       = oxnum,
    backref     = true,
]{biblatex}
\usepackage{hyperref}
\usepackage{xifthen}

\setlength\hangingleftmargin{0.2\textwidth}
\setenotez{list-name={Endnotes},list-heading={\chapter*{#1}},counter-format=alph,backref=true}
\renewcommand*{\theendnote}{\alph{endnote}}

\addbibresource{\jobname.bib}

\NewDocumentCommand{\nicequote}{momm}{%
  \begin{quotation}\noindent\ignorespaces #1\end{quotation}
  \begin{hangingpar}
  --%
  \IfNoValueTF{#2}{#3{#4}}{#3, \textit{#2}{#4}}%
  \end{hangingpar}
  \vspace{\onelineskip}%
}

\begin{document}

This enthusiasm is not necessarily spectacular or showy, but a discerning
observer or participant can perceive a deep wellspring flowing from teacher to student:
\nicequote{
  Students gravitate toward teachers with whom they have forged a connection.
}
[Excellent Sheep]{William Deresiewicz}{\autocite{C108179}}

These two departments had been at odds for thirty years.\endnote{%
  \nicequote{
    What we're saying is that the company in the past has been locked in.…
    If we're going to work on the total needs of the customer…
    there has to be a way that that's seen in a lot of different places in the company.
  }
  [The Fifth Discipline: The Art {\symbol{38}} Practice of The Learning Organization]%
  {Peter M. Senge}{\autocite{C108184}}%
}

\printbibliography[title={References}]

\backmatter
\printendnotes

\end{document}