text:
Q: Force webpack 2 not to use Eval in production I'm having the csp error because webpack is using eval in one of my bundles.
I've tried to use all the options available for source mapping and canceling devtools.
Also I've tried configuring the compression using Webpack.optimize.UglifyJsPlugin in which you can set sourceMap: false. but I'm still getting the same error and I can see there's a line in my bundle:
t.exports=function(t){"undefined"!=typeof execScript?execScript(t):eval.call(null,t)} .

which is calling eval.
How can I force webpack not to use eval?
Thank you


text:
Q: Deadbeef player doesn't access my storage hdd I've installed both deadbeef and foobar2000 and neither one lists my storage HDD other than the main OS SSD.
Rhythmbox lists all HDDs and I can drag & drop music files with QMMP.
And I'm trying to set deadbeef as the primary music player.
How can I do that?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Modificar archivos generados por CRUD de Scaffold Buenas noches quisiera saber ¿Cómo tengo que modificar el template .t4 del controller? o lo que tenga que cambiar para poder generar los archivos con Scaffold con el nombre personalizado.

*

*El archivo con el nombre Create.cshtml se cree con el nombre Crear.cshtml

*El archivo con el nombre Delete.cshtml se cree con el nombre Eliminar.cshtml

*El archivo con el nombre Details.cshtml se cree con el nombre Detalles.cshtml

*El archivo con el nombre Edit.cshtml se cree con el nombre Editar.cshtml

*Este puede mantener el mismo nombre Index.cshtml -> Index.cshtml

Modificando el template del controller logré cambiar los métodos de acción que me crea automáticamente el Scaffold:
    // GET: Cuentas
    public ActionResult Index()
    {
        return View(db.Cuentas.ToList());
    }

    // GET: Cuentas/Details/5
    public ActionResult Detalles(string id)
    {
        //Codigo Autogenerado
        return View(cuenta);
    }

    // GET: Cuentas/Create
    public ActionResult Crear()
    {
        return View();
    }

Eso esta bien, pero como dije: no se cómo generar los archivos CRUD con los nombre que yo quiero, gracias.


text:
Q: angularjs ngoption group with another optgroup label i'm new with anjularjs. I want to group options by object with id and name. Can i group it by object.id and show object.name as optgroup label?
for example:

(function(angular) {
  'use strict';
angular.module('defaultValueSelect', [])
  .controller('ExampleController', ['$scope', function($scope) {
    $scope.data = {
     availableOptions: [
       {id: '0', name: 'Option A', group: {id:0, name:'group 0'}},
       {id: '1', name: 'Option B', group: {id:1, name:'group 1'}},
       {id: '2', name: 'Option C', group: {id:1, name:'group 1'}},
       {id: '3', name: 'Option D', group: {id:2, name:'group 1'}}
     ],
     selectedOption: {id: '0', name: 'Option A', group: {id:0, name:'group 0'}}
     };
 }]);
})(window.angular);
<!DOCTYPE html>

      <form name="myForm">
        Make a choice:
        <select name="mySelect" id="mySelect"
          ng-options="option.name group by option.group.id for option in data.availableOptions track by option.id"
          ng-model="data.selectedOption"></select>
      </form>

      <tt>option = {{data.selectedOption}}</tt>

and I want to get something like this in select:

<select>
    <optgroup label="group 0">
        <option>Option A</option>
    </optgroup>
    <optgroup label="group 1">
        <option>Option B</option>
        <option>Option C</option>
    </optgroup>
    <optgroup label="group 1">
        <option>Option D</option>
    </optgroup>
</select>

A: I could not do it using ng-options, and I did it with a ng-repeat. I had to modify the array and add a function to select for this. Yes, it seems it is not the best solution, but still.

(function(angular) {
  'use strict';
angular.module('defaultValueSelect', [])
  .controller('ExampleController', ['$scope', function($scope) {
    $scope.data = {
     availableOptions: [
       {id: '0', name: 'Option A', group: {id:0, name:'group 0'}},
       {id: '1', name: 'Option B', group: {id:1, name:'group 1'}},
       {id: '2', name: 'Option C', group: {id:1, name:'group 1'}},
       {id: '3', name: 'Option D', group: {id:2, name:'group 1'}}
     ],
     selectedOption: {id: '0', name: 'Option A', group: {id:0, name:'group 0'}}
     };

    //id of selected element
    $scope.selectedOptionId = '0';
    //modify the array
    $scope._data = [];
    for(var i = 0; i<$scope.data.availableOptions.length; i++){
      var add = true;
      if($scope._data.length>0) {
        for(var j = 0; j<$scope._data.length;j++) {
          if($scope.data.availableOptions[i].group.id == $scope._data[j].id){
            $scope._data[j].options.push(
              {
                id: $scope.data.availableOptions[i].id,
                name: $scope.data.availableOptions[i].name
              });
            add = false;
          }
        }
      }
      if(add) {
        $scope._data.push(
          {
            id: $scope.data.availableOptions[i].group.id,
            name: $scope.data.availableOptions[i].group.name,
            options: [
              {id: $scope.data.availableOptions[i].id,
               name: $scope.data.availableOptions[i].name
              }]});
      }
    };
    //looking element of the selected id
    $scope.selectOption = function(){
      for(var i = 0; i<$scope.data.availableOptions.length; i++){
        if($scope.data.availableOptions[i].id == $scope.selectedOptionId){
          $scope.data.selectedOption = $scope.data.availableOptions[i];
          break;
        }
      }
    };

 }]);
})(window.angular);
<!DOCTYPE html>

      <form name="myForm">
        Old version:
        <select name="mySelect" id="mySelect"
          ng-options="option.name group by option.group.id for option in data.availableOptions track by option.id"
          ng-model="data.selectedOption"></select>
      </form>

      <form name="_myForm">
        New versione:
        <select ng-model="selectedOptionId" ng-change="selectOption()">
          <optgroup ng-repeat="group in _data" label="{{group.name}}">
            <option ng-repeat="option in group.options" value="{{option.id}}">{{option.name}}</option>
          </optgroup>
        </select>
      </form>

      <tt>option = {{data.selectedOption}}</tt>


text:
Q: How to put it to work microphone mini jack on ubuntu 22 in iMac14 The problem is that my iMac14 don't recognize an external microphone and I don't understand why? I'm using Ubuntu 22.
This is on iMac14, don't work when I plug in microphone
I have a laptop Lenovo with Ubuntu 16 and in this case Ubuntu recognize the same external microphone. I would like know if is hardware or software problem.
This is an example on my laptop that work fine.


text:
Q: After migration to spring boot 3 we're getting could not configure Topics Error After the Migration to Spring Boot 3 we're getting a Timeout Exception when starting certain Integration Tests. The Broker seems to work as usual though.
I'am curious what was changed in the current spring kafka version, that results in this behaviour and how i can clean my logs again?
    2023-01-23 17:02:54,106 [main] ERROR  o.s.kafka.core.KafkaAdmin -  -  - Could not configure topics
java.util.concurrent.TimeoutException: null
    at java.base/java.util.concurrent.CompletableFuture.timedGet(CompletableFuture.java:1960)
    at java.base/java.util.concurrent.CompletableFuture.get(CompletableFuture.java:2095)
    at org.apache.kafka.common.internals.KafkaFutureImpl.get(KafkaFutureImpl.java:180)
    at org.springframework.kafka.core.KafkaAdmin.initialize(KafkaAdmin.java:205)
    at org.springframework.kafka.core.KafkaAdmin.afterSingletonsInstantiated(KafkaAdmin.java:174)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:972)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:915)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:584)
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:730)
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:432)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:308)
    at org.springframework.boot.test.context.SpringBootContextLoader.lambda$loadContext$3(SpringBootContextLoader.java:137)
    at org.springframework.util.function.ThrowingSupplier.get(ThrowingSupplier.java:59)
    at org.springframework.util.function.ThrowingSupplier.get(ThrowingSupplier.java:47)
    at org.springframework.boot.SpringApplication.withHook(SpringApplication.java:1386)
    at org.springframework.boot.test.context.SpringBootContextLoader$ContextLoaderHook.run(SpringBootContextLoader.java:543)
    at org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:137)
    at org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:108)
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:183)
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:117)
    at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:127)
    at org.springframework.cloud.contract.wiremock.WireMockTestExecutionListener.applicationContextBroken(WireMockTestExecutionListener.java:120)
    at org.springframework.cloud.contract.wiremock.WireMockTestExecutionListener.beforeTestClass(WireMockTestExecutionListener.java:43)
    at org.springframework.test.context.TestContextManager.beforeTestClass(TestContextManager.java:214)
    at org.springframework.test.context.junit.jupiter.SpringExtension.beforeAll(SpringExtension.java:113)
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$invokeBeforeAllCallbacks$12(ClassBasedTestDescriptor.java:395)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.invokeBeforeAllCallbacks(ClassBasedTestDescriptor.java:395)
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.before(ClassBasedTestDescriptor.java:211)
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.before(ClassBasedTestDescriptor.java:84)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:148)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:35)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:54)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:147)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:127)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:90)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.lambda$execute$0(EngineExecutionOrchestrator.java:55)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.withInterceptedStreams(EngineExecutionOrchestrator.java:102)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:54)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:114)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:86)
    at org.junit.platform.launcher.core.DefaultLauncherSession$DelegatingLauncher.execute(DefaultLauncherSession.java:86)
    at org.junit.platform.launcher.core.SessionPerRequestLauncher.execute(SessionPerRequestLauncher.java:53)
    at com.intellij.junit5.JUnit5IdeaTestRunner.startRunnerWithArgs(JUnit5IdeaTestRunner.java:57)
    at com.intellij.rt.junit.IdeaTestRunner$Repeater$1.execute(IdeaTestRunner.java:38)
    at com.intellij.rt.execution.junit.TestsRepeater.repeat(TestsRepeater.java:11)
    at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:35)
    at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:235)
    at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:54)


text:
Q: Pandas compare next row and merge based on conditions I have below dataframe. Where START+TIME=END
I want ti check id END of current row = START of next row then merge that 2 rows providing "ID" hsould the same
So the output should look like,
So the output is as below

A: I'm not sure how your data is formatted exactly but you can just replace.
I suggest you use numpy and try something along the lines :
i=0
while i != len(data):
    if data[i][4] == data[i+1][2]:
        data[i][4] = data[i+1][2]
        data[i+1].pop
    else :
        i+=1

A: Sample DF
       Start    Time   End      ID
  0    43500    60     43560    23
  1    43560    60     43620    23
  2    43620    1020   44640    24
  3    44640    260    44900    24
  4    44900    2100   47000    24

Code:
a = df["ID"].tolist()
arr = []
t = True
for i in sorted(list(set(a))):
    j = 1
    k = 0
    temp = {}
    tempdf = df[df["ID"] == i]
    temp["Start"] = tempdf.iloc[k]["Start"]
    temp["Time"] = tempdf.iloc[k]["Time"]
    temp["End"] = tempdf.iloc[k]["End"]
    temp["ID"] = tempdf.iloc[k]["ID"]

    while j < len(tempdf):
        if temp["End"] == tempdf.iloc[j]["Start"]:
            temp["End"] = tempdf.iloc[j]["End"]
            temp["Time"] += tempdf.iloc[j]["Time"]
         j += 1

    arr.append(temp)

df = pd.DataFrame(arr)

Output DF:
        Start   Time    End     ID
   0    43500   120     43620   23
   1    43620   3380    47000   24


text:
Q: initializing lists in a loop give 2 different ids, not one I'm using Python 3.6.9, I'm confused, why in the code below do I get 2 toggling ids?
In [1]: [id([None]*3) for _ in range(5)]
   ...:
Out[1]:
[140161829603400,
 140161829654920,
 140161829603400,
 140161829654920,
 140161829603400]

From my understanding when creating lists in the loop all lists will have the same IDs, or if done right, you can get independent lists with different IDs. How to explain this behavior?


text:
Q: I want to count number of observations within each subject in PANDAS dataframe I am quite new to using PANDAS and python in general.
I have a hierarchical data set with several subjects, each of whom have some number of observations. The total df is about half a million rows.
I want to calculate the observations number...
## toy problem

d = {'one' : Series(['a', 'a', 'a', 'b', 'b', 'b'], index = [0,1,2,3,4,5]),
     'two' : Series([1.1, 2.5, 3.3, 2.5, 3.3, 9.5], index = [0,1,2,3,4,5])}
df = DataFrame(d)

for i in df.one.unique():
    for j in range(0,len(df[df.one == i])):
        print j

So I want to assign j to a column for each row. I have no problem calculating j but I cannot figure out how to assign it. I have tried using iloc which is incredibly slow, or writing to a list and then joining this to the df, also really slow (currently running for over 30 mins and counting...). I understand that python is best with vectorised problems but I cannot think of a vector solution for this case.
What is the best way to do this? It is really easy and quick in R. I am currently migrating to Python & PANDAS under the expectation that it is faster but this doesnt appear to be the case here.
Any advice please?

A: You could use the GroupBy.cumcount method:
In [14]: df['j'] = df.groupby('one').cumcount()

In [15]: df
Out[15]:
  one  two  j
0   a  1.1  0
1   a  2.5  1
2   a  3.3  2
3   b  2.5  0
4   b  3.3  1
5   b  9.5  2


text:
Q: Set group by column without user action in table header Is there an option to automatically group table data by specific column without user action to group by column in table header.
When I click on column and set Group, table is grouped by that column and that looks awesome, now I need that option to set in code, without user interaction.
Thanks

A: Yes, you can return true in AbstractColumn.getConfiguredGrouped() of your column. You need to set getConfiguredSortIndex() too.
If you made manual changes in your table (e.g. changed column width, order, ..), you may need to reset your table to the defaults via the setting icon.

A: When you want to change the sort columns programmatically at runtime you can use the column-set of the table. Something like this:
ITable table = getTable();
ColumnSet colSet = table.getColumnSet();
IColumn<?> sortCol = colSet.getColumnByClass(MyColumn.class);
colSet.addSortColumn(sortCol, true);


text:
Q: VBA Excel Validation list over Variable Range I tried this code to set a validation list in Excel. I'm trying to substitute specific cells with variables, but I can't make it work out with fixed cells.
Thank you.
With Selection.Validation
    .Delete
    .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
    xlBetween, Formula1:="=Range(Cells(5, 15), Cells(6, 15))"
    .IgnoreBlank = True
    .InCellDropdown = True
    .InputTitle = ""
    .ErrorTitle = ""
    .InputMessage = ""
    .ErrorMessage = ""
    .ShowInput = True
    .ShowError = True
End With

A: Try this:
    .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
    xlBetween, Formula1:= "=" & Range(Cells(5, 15), Cells(6, 15)).Address

or this:
   .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
    xlBetween, Formula1:= "=$O$5:$O$6"


text:
Q: ImportError: cannot import name 'Deque' I'm trying to host my Discord.py bot on Heroku. When my bot starts the following error appears:
2020-01-31T20:49:31.501236+00:00 heroku[worker.1]: State changed from starting to up
2020-01-31T20:49:32.858327+00:00 heroku[worker.1]: State changed from up to crashed
2020-01-31T20:49:32.839912+00:00 heroku[worker.1]: Process exited with status 1
2020-01-31T20:49:32.766672+00:00 app[worker.1]: Traceback (most recent call last):
2020-01-31T20:49:32.766696+00:00 app[worker.1]:   File "bot.py", line 3, in <module>
2020-01-31T20:49:32.766815+00:00 app[worker.1]:     import discord
2020-01-31T20:49:32.766819+00:00 app[worker.1]:   File "/app/.heroku/python/lib/python3.6/site-packages/discord/__init__.py", line 23, in <module>
2020-01-31T20:49:32.766952+00:00 app[worker.1]:     from .client import Client
2020-01-31T20:49:32.766954+00:00 app[worker.1]:   File "/app/.heroku/python/lib/python3.6/site-packages/discord/client.py", line 35, in <module>
2020-01-31T20:49:32.767061+00:00 app[worker.1]:     import websockets
2020-01-31T20:49:32.767062+00:00 app[worker.1]:   File "/app/.heroku/python/lib/python3.6/site-packages/websockets/__init__.py", line 3, in <module>
2020-01-31T20:49:32.767164+00:00 app[worker.1]:     from .auth import *
2020-01-31T20:49:32.767166+00:00 app[worker.1]:   File "/app/.heroku/python/lib/python3.6/site-packages/websockets/auth.py", line 15, in <module>
2020-01-31T20:49:32.767263+00:00 app[worker.1]:     from .server import HTTPResponse, WebSocketServerProtocol
2020-01-31T20:49:32.767265+00:00 app[worker.1]:   File "/app/.heroku/python/lib/python3.6/site-packages/websockets/server.py", line 49, in <module>
2020-01-31T20:49:32.767374+00:00 app[worker.1]:     from .protocol import WebSocketCommonProtocol
2020-01-31T20:49:32.767375+00:00 app[worker.1]:   File "/app/.heroku/python/lib/python3.6/site-packages/websockets/protocol.py", line 18, in <module>
2020-01-31T20:49:32.767487+00:00 app[worker.1]:     from typing import (
2020-01-31T20:49:32.767492+00:00 app[worker.1]: ImportError: cannot import name 'Deque'

How do I fix this?

A: The websockets module is incompatible with python 3.6.0
I reproduced the problem myself:
C:\Users\Me>python
Python 3.6.0 (v3.6.0:41df79263a11, Dec 23 2016, 08:06:12) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>

C:\Users\Me>pip install websockets
Collecting websockets
  Downloading https://files.pythonhosted.org/packages/6a/bd/8555c65b3fca7310b2601d0957b36511c3c3c2e8a93a6d3f90c671b70c6a/websockets-8.0.2-cp36-cp36m-win_amd64.whl (65kB)
     |████████████████████████████████| 71kB 918kB/s
Installing collected packages: websockets
Successfully installed websockets-8.0.2
WARNING: You are using pip version 19.1.1, however version 20.0.2 is available.
You should consider upgrading via the 'python -m pip install --upgrade pip' command.

C:\Users\Me>python
Python 3.6.0 (v3.6.0:41df79263a11, Dec 23 2016, 08:06:12) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import websockets
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\Me\AppData\Local\Programs\Python\Python36\lib\site-packages\websockets\__init__.py", line 3, in <module>
    from .auth import *
  File "C:\Users\Me\AppData\Local\Programs\Python\Python36\lib\site-packages\websockets\auth.py", line 15, in <module>
    from .server import HTTPResponse, WebSocketServerProtocol
  File "C:\Users\Me\AppData\Local\Programs\Python\Python36\lib\site-packages\websockets\server.py", line 49, in <module>
    from .protocol import WebSocketCommonProtocol
  File "C:\Users\Me\AppData\Local\Programs\Python\Python36\lib\site-packages\websockets\protocol.py", line 18, in <module>
    from typing import (
ImportError: cannot import name 'Deque'

It works in 3.6.1:
https://repl.it/repls/NotableDarkorchidBloatware

A: My guess is that the version of Python you're running on Heroku doesn't have typing.Deque. Try running heroku run -a <app_name> python -V or run a python shell and on the dyno and try importing yourself. If it's a python version issue then you should be able to resolve it by defining a runtime.txt file in your project root and setting the version explicitly there (https://devcenter.heroku.com/articles/python-runtimes)


text:
Q: Very high CPU usage for Windows Audio service I'm using a Dell XPS 13 (3960) laptop, with  Windows 10 operating system.
Recently, after I was hearing loud laptop fans noises even when no high resouce programs running, I decided to check, and indeed I've seen a service called "Windows Audio" using almost 40% of the CPU.
After a restart (and not running anything) it was still doing that.
I uninstalled the audio drivers and let the OS reinstall them automatically and it seemed to repair the issue, but after a while it happened again.
It's under "Service Host: Local Service (Network Restricted)"

I've looked it up and it seems like no other issue like mine happened to anyone, and if it did, the reason had nothing to do with mine (software I don't have etc.).
Any way to check why it happens and fix it?
Edit:
If I restart the service it goes back to minimal CPU usage.

A: To see why audio service causes such a high cpu usage you need to install the Windows Performance Toolkit, which is part of the Windows 10 SDK.

(all other entries can be unselected)
Run WPRUI.exe, select First Level, CPU Usage and click on start. Capture 1 minute of the CPU usage, now click on Save to save the data into a ETL file.
Now make a double click on the generated ETL file to open the ETL in Windows Performance Analyzer (WPA.exe), drag and drop the CPU Usage (Sampled) to analyze pane:

Now load debug symbols in WPA and expand the stack of the svchost.exe which has a high value at % Weight (after blue line). Here look for function names to see what audio service does.
Often high cpu usage of audio service is caused by audio improvements from the audio driver. The best is to disable this improvements.

A: I am having the exact same issue like you. Right after booting Windows 10 17134 (1803) after an in-place-upgrade from 16299 (1709), the "Windows Audio" service uses 20% of my 16 core CPU. Restarting the service brings everything back to normal and audio works fine in both cases without any issues. Checking this with procmon, the Windows Audio service is querying the installed audio devices in the registry all few ms in a steady loop, hence the high CPU usage. After restarting the service, these steady "terror-queries" stop, hence CPU load and everything else goes back to normal.
The problem came from a audio-loopback-driver that I´ve installed (called ODeus AsioLinkPro). I´ve completely removed the driver and manually made sure that there are no leftovers in the registry and the C:\ drive. CPU usage of Windows Audio went to normal right away. I´ve then reinstalled. But the issue came back right away after installing the driver again. However, since there is no update to this driver (company does not exist anymore) and since I need it in any case AND since restarting the Windows Audio service for one time during a Windows sessions solves the issue, I´ve simply created a .BAT file with:
@echo off
echo Restarting Windows Audio to fix high CPU usage in 17134
net stop Audiosrv
net start Audiosrv

... And added it to the Task Scheduler for the system start. This solves the problem for me, although with a dirty hack. ;-)
In any case: re-installing your audio-drivers could possibly fix the issue, but if not, you can do it with the dirty hack for now. Maybe MS is issuing a bugfix for it too, since it all worked fine in 1709 for me.

A: Razer Surround was causing this on my PC. Uninstalled and problem solved.

A: I've solved my issue by disabling rainmeter. I was using monstercat visualizer addon and it probably caused it.

A: I have Lenovo 910 2in1 laptop. I had a high CPU % used by Window audio device after updating all the drivers. I found this situation by task manager (ctrl+alt+delete). Eventually this scenario drain the battery heavily.
I rollback the audio driver to old version and basically it resolve all the issue of battery draining  now it shows 9 to 10 hours as usual.

A: I've had this issue in the past; I solved it by uninstalling the OEM drivers for the specific sound card and instead installing the drivers for the card's chipset alone; chipset drivers are usually much more stable.


text:
Q: Find converging subsequences in a metric space Let $(X,d)$ be a metric space and $\{x_n\}_n$ a sequence. I'm looking for an algorithm that takes $x\in X$ as an input and gives a $y\in X$ as an output, with this property: if $\{x_n\}_n$ admits some converging subsequence then $\{y_n\}_n$ is a converging subsequence of $\{x_n\}_n$.
I started naively with this: let $y_0=x_0$, then take $y_1=x_{i_1}$ where $x_{i_1}$ is the first such that $d(x_0,x_{i_1})<2^{-1}$, if this exists, and $y_1=y_0$ otherwise, and so on. But this doesn't work, since a converging subsequence could easly start at some $n>0$ and i will not find it in this way.
Have someone any idea? Is there such an algorithm?
Remark: this problem could be setting in a two player, perfect information game-context: player I enumerate a sequence by playing $x\in X$ at each of its turn and player II has to choose if take or not the $x$ II just played, in order to have, at the end of the game, a subsequence of $\{y_n\}_n$ such that if $\{x_n\}_n$ (the II's run) admits some converging subsequence, then $\{y_n\}_n$ is such a subsequence.


text:
Q: How do I mutate multiple columns returned by a function into another dataframe in R? I have the following dataframe songs:
|artistName   |trackName                 |id                     |duration |
|:------------|:-------------------------|:----------------------|:--------|
|Shaan        |Woh Ladki Hai Kahan       |2tO0QPdCA0jgDBshTuYYkc |306133   |
|Amit Trivedi |Zinda                     |1gEHNfJRSXpDVaEicwRRfe |241962   |
|flora cash   |You're Somebody Else      |0pdKRp2sUthTPe7RLWpPqQ |218883   |
|Iron & Wine  |Each Coming Night         |2xa9PoO42d7VjT0KqG5d3I |207773   |
|Yasser Desai |Tenu Na Bol Pawaan        |5mp7og60TpyNiKi2p9Morw |295352   |
|ERock        |Jurassic Park Meets Metal |4u0RJ8g7QM5exHIPvJ0WW3 |244000   |

I am interested in the id column. This is used by the get_track_audio_features() function from the {spotifyr} package to return a dataframe of a track's audio features. For example, one id might return:
| danceability| energy| key| loudness| mode| speechiness| acousticness| instrumentalness| liveness| valence|  tempo|type           |id                     |uri                                  |track_href                                               |analysis_url                                                     | duration_ms| time_signature|
|------------:|------:|---:|--------:|----:|-----------:|------------:|----------------:|--------:|-------:|------:|:--------------|:----------------------|:------------------------------------|:--------------------------------------------------------|:----------------------------------------------------------------|-----------:|--------------:|
|         0.47|  0.237|   2|  -15.593|    1|      0.0348|        0.837|            0.464|    0.115|   0.358| 81.268|audio_features |2xa9PoO42d7VjT0KqG5d3I |spotify:track:2xa9PoO42d7VjT0KqG5d3I |https://api.spotify.com/v1/tracks/2xa9PoO42d7VjT0KqG5d3I |https://api.spotify.com/v1/audio-analysis/2xa9PoO42d7VjT0KqG5d3I |      207773|              4|

What I would like to do is add certain audio features, for example energy and danceability into songs, corresponding to their IDs. The resulting dataframe becomes:
| id                     | artistName   | trackName            | duration | energy | danceability |
|------------------------|--------------|----------------------|----------|--------|--------------|
| 0pdKRp2sUthTPe7RLWpPqQ | flora cash   | You're Somebody Else | 2349023  | .47    | .13          |
| 1gEHNfJRSXpDVaEicwRRfe | Amit Trivedi | Zinda                | 234009   | .15    | .78          |

I thought of making use of the rowwise() function to do this and mutating everything into a single column and then separating it (since they'll be separated by commas and can be made into new columns):
song_data <- songs %>%
    rowwise() %>%
    mutate(song_data_id = toString(get_track_audio_features(id)) %>%
    separate(.,
             song_data_id,
             into =  c("danceablity", "energy"),
             sep = ",")

I thought this would work, since the first two columns of what the function returns are danceability and energy and that the rest would be discarded. However, it doesn't and instead gives me the following error:
cannot coerce type 'closure' to vector of type 'character'

How can I accomplish mutating multiple columns into my dataframe, in the shortest possible way?
Dput:
structure(list(endTime = structure(c(1588582680, 1588640040,
1588640040, 1588640280, 1588640280, 1588641240), class = c("POSIXct",
"POSIXt"), tzone = ""), artistName = c("Shaan", "Amit Trivedi",
"flora cash", "Amit Trivedi", "flora cash", "flora cash"), trackName = c("Woh Ladki Hai Kahan",
"Zinda", "You're Somebody Else", "Zinda", "You're Somebody Else",
"You're Somebody Else"), msPlayed = c(17253L, 0L, 218649L, 1504L,
218883L, 638496L), date = structure(c(18386, 18387, 18387, 18387,
18387, 18387), class = "Date"), time = structure(c(52080, 23040,
23040, 23280, 23280, 24240), class = c("hms", "difftime"), units = "secs")), row.names = c(NA,
6L), class = "data.frame")

A: Since the function returns a dataframe, we can store that into a column as a list using the map function from {purrr}. map() always returns a list.
features <- song_data %>%
  nest(data = c(id)) %>%
  mutate(audio_features = map(data, ~ get_track_audio_features(.$id))) %>%
  unnest(., audio_features)

The audio features are then stored in a column called audio_features but this is still a list. The last line, the unnest() function expands the list into separate columns. All done!

A: If you add the id to the results of get_track_audio_features() you can combine the tables with join, e.g. left_join or inner_join.


text:
Q: Does .Net Core 2.2 HttpClient remember failed DNS lookups? We are deploying a web application to an internally hosted windows kubernetes cluster. Through a mechanism I don't fully understand (but I don't believe is relevant to the question), after deployment to the K8s cluster our application is addressable by a DNS entry that includes that name and version number of the application.
As such, the exact DNS value is not created until the deployment is complete. And in fact, it takes a little while after the deployment is complete before it is addressable.
Now to the .Net Core HttpClient question...
(And in case it is relevant, the code in question is running on Windows Server 2012 via Team City)
I have written some code using .Net Core 2.2 HttpClient (via HttpClientFactory) to poll the healthcheck endpoint of the application to know when the deployment is complete. At present it waits a period of time before making any requests. It then polls periodically for a while (up to 5 minutes) before giving up.
The issue I'm having is that if the first polling request happens before the DNS entry is available it (rightly) fails with a 'no such host is known' exception. But all further requests will also fail with the same exception.
The sweet spot in my case seems to be to wait three minutes. When doing this the first request to my application will succeed and all is good. But if I only wait two minutes, it will fail, and keep failing even if I keep trying for another 5 minutes. To me it looks like once the first DNS fails, I'm doomed.
Strangely I have found that once my polling fails enough and gives up, a subsequent call to nslookup succeeds (from powershell - i.e. separate to the .Net Core console application). But then more code is executed, this time running .Net Framework 4.6 code... and it too has problems with the DNS.
So could I be correct that a DNS failure is remembered somewhere, even if it not across the board (as evidenced by the nslookup success)? And if so, how can the DNS lookup be forced to be retried?
I have tried setting PooledConnectionIdleTimeout and PooledConnectionLifetime values for the SocketsHttpHandler in question (to 20 seconds, as my pause between retries is 30 seconds), but that has not helped. But even if they were the answer and I've done something wrong with it, that wouldn't explain why a separate .Net process running straight after has the same issue.


text:
Q: Show that $\mathbb{Q}/\mathbb{Z}$ is an injective module and that it is not a projective module So this is what I have for the injectivity:
Knowing $\mathbb{Z}$ is a principal domain, $\mathbb{Q}/\mathbb{Z}$ is an injective module if and only if $\mathbb{Q}/\mathbb{Z}$ is divisible.
Checking the divisibility:
Since $\mathbb{Q}/\mathbb{Z}$ is abelian, we want to see if it is divisible as a $\mathbb{Z}-module$. Let $a+\mathbb{Z} \in \mathbb{Q}/\mathbb{Z}$ and $k \in \mathbb{Z}$ with $k \neq 0$.
Since $\mathbb{Q}$ is divisible, there exists $x \in \mathbb{Q}$ such that $kx = a$; thus $k(x+\mathbb{Z}) = a+\mathbb{Z}$. Hence $\mathbb{Q}/\mathbb{Z}$ is divisible and therefore INJECTIVE.
Is this correct? For the not projective bit, would it be enough to show that every element in $\mathbb{Q}/\mathbb{Z}$ has finite order?

A: The divisible -> injective approach is correct in this case.
Here's a general purpose observation: consider an exact sequence of modules  $0\to B\to A\to A/B\to 0$.  We know that if $A/B$ is projective the sequence has to split, so that $B$ is a summand of $A$.
But it is easy to check that $\mathbb Z$ is an essential $\mathbb Z$ submodule of $\mathbb Q$: there's no way you can make it into a summand because it intersects all nonzero submodules nontrivially.
Therefore $\mathbb Q/\mathbb Z$ can't be projective.

A: It is enough to check that $\Bbb Q/\Bbb Z$ is an injective $\Bbb Z$-module. Then it cannot be projective , see here:
Prove that no $\mathbb{Z}$-module is both projective and injective


text:
Q: How do I anchor my Horizontal Scrollbar to the top of the JScrollPane I would like to move the Horizontal scroll bar to the top of my JScrollPane. Does anyone knows how to do this ? I am on Java swing.

A: Start by reading the JScrollPane API.
At the right of the first page you will see a simple diagram showing the layout of the scroll pane. You will see:

*

*positions for the horizontal (and vertical) scrollbars

*a location titled the "column header"

So what you need to do is move the horizontal scrollbar to the column header. To this you need to:

*

*get a reference to the horizontal scrollbar. Read the API for the appropriate "getter" method

*set the scrollbar to the column header. Read the API for the appropriate "setter" method.

A: This worked for me.
jScrollPane.setColumnHeaderView(jScrollPane.getHorizontalScrollBar());


text:
Q: Precalc - Trig Identities I only need a hint as to where to go from here. My problem is this:
$$ \dfrac{1+\tan(x)}{\sin(x)}-\sec(x) $$
Here's my work trying to solve the problem, up until I got stuck. Did I make a mistake somewhere or make it more complicated than it should have been?
$$ \dfrac{(1+\tan(x))(\cos(x)}{\sin(x)\cos(x)}-\dfrac{\sin(x)}{\cos(x)\sin(x)}=\dfrac{(1+\tan(x))(\cos(x))-\sin(x)}{\cos(x)\sin(x)}=\dfrac{1+\tan(x)-\sin(x)}{{\sin(x)}}=\dfrac{1}{\sin(x)}+\dfrac{\dfrac{\sin(x)}{\cos(x)}}{\sin(x)}-\dfrac{\sin(x)}{\sin(x)}=\csc(x)+\sec(x)-1 $$

A: The problem is that you neglected $\cos(x)$ after combining the fractional expressions altogether.  So from the end of the first line,
$$\begin{aligned}
\dfrac{(1 + \tan(x))\cos(x) - \sin(x)}{\sin(x)\cos(x)} &= \dfrac{\cos(x) + \tan(x)\cos(x) - \sin(x)}{\sin(x)\cos(x)}\\
&= \dfrac{\cos(x) + \frac{\sin(x)}{\cos(x)}\cdot \cos(x) - \sin(x)}{\sin(x)\cos(x)}\\
&= \dfrac{\cos(x) + \sin(x) - \sin(x)}{\sin(x)\cos(x)}\\
&= \dfrac{\cos(x)}{\sin(x)\cos(x)}\\
&= \dfrac{1}{\sin(x)}\\
&= \csc(x)
\end{aligned}$$

A: Let $ c = \cos(x)$ and $s = \sin(x)$. Then the expression you gave is
$$
\frac{1 + s/c}{s} - \frac{1}{c}  \\
= \frac{c+s}{cs} - \frac{1}{c} \\
= \frac{c+s}{cs} - \frac{s}{cs} \\
= \frac{c+s-s}{cs} \\
= \frac{c}{cs} \\
= \frac{1}{s} \\
= \text{cosec}(x)
$$
This same technique will work with all your other similar problems. The only thing you need to know is that $c^2 + s^2 = 1$.


text:
Q: Filter elements within object in DynamoDB I have a DynamoDB table which contains objects looking like the following:
{
    'username': ...,
    'subscriptions': [
        ...
    ],
    ...
}

And I would like to filter subscriptions for each user based on some criteria, and get back the objects which have subscriptions matching the criteria, but filter those objects so that only the matching subscriptions are present.
If a user has subscribed to 50 things, but only 3 of them match, I would like to get back an object where the `subscriptions' field is only 3 elements long. I also need the other information contained in the object.
To give a more specific example, suppose that I have two elements in my table:
{
    'username': 'alice',
    'subscriptions': [
        1,
        2
     ],
     'email': 'alice@a.com'
},
{
    'username': 'bob',
    'subscriptions': [
        2,
        3
    ],
    'email': 'bob@a.com'
}

And I would like to filter to get the subscription `1'. I would like to get back
{
    'username': 'alice',
    'subscriptions': [
        1
    ],
    'email': 'alice@a.com'
}

Or perhaps some other structure which contains all the necessary information (and no other information in order to save bandwidth).
I believe I can do this with scan(), but I do not know the specifics.


text:
Q: Python Flask, redirect after rendering a template I'm trying to redirect a user after a template has been rendered. Essentially, my code waits till a variable turns to False, and then redirects the user. The code renders a loading animation and tells the user to wait. The code renders the html and css template, but then when the wait is over doesn't redirect the user to a new url. My code:
from flask import Flask, redirect, url_for, request, render_template
import json
import requests
import webbrowser
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time

global is_busy
is_busy = False

app = Flask(__name__, template_folder='template')

@app.route('/')
def main_menu():
    return redirect(url_for('enteruserid'))

@app.route('/EnterID')
def enteruserid():
    global is_busy
    return render_template('enterid.html')
def waitUntil(condition, output):
    time.sleep(1)

@app.route('/Scrape', methods=['POST', 'GET'])
def login():
   global is_busy
   if request.method == 'POST':
      id = request.form['nm']
      try:
          int(id)
          return render_template('waitingscreen.html')
          waitUntil(is_busy, False)
          return redirect(url_for('scrapingtheinternet', target_id=id))
      except:
          return redirect(url_for('notanint'))
   else:
      id = request.args.get('nm')

if __name__ == '__main__':
   app.run(debug=True)

This code doesn't include the function where the "Scraping" occurs.
enterid.html:
<!DOCTYPE html>

        <title>DCF</title>
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta name="description" content="Reverse image search discord user id's">
        <meta name="keywords" content="Discord">

    <form action = "http://localhost:5000/Scrape" method = "post">

Reverse Image Search

Enter User ID:

<input type = "text" name = "nm" />

<input type = "submit" value = "submit" />

waitingscreen.html:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content=
        "width=device-width, initial-scale=1.0">

    <title>Loader Bar</title>

Please Wait...

I'd appreciate any help. Thanks :)

A: Basically, the return statement ends the function in almost all languages.
say
def func():
    print("hi")
    return 0
    print("after return")
func()

output:
hi

Whatever after return will not be executed (although see this answer about finally).
In your context, you can try to preview "waitingscreen.html" on the frontend when you click the login button
and avoid rendering it from the backend.
Some simple JS will help.
refer: Display a 'loading' message while a time consuming function is executed in Flask
Hope it will clear your query.


text:
Q: rails model assignment with has_many :through I just can't figure out how to create a relation with a join table. I've read all the posts about them, but the main error seems to be that in the join table to models should be singular, which I have. I just can seem to create the models correctly and assign them. I have projects with datasets, and projects can have multiple datasets, while a dataset can belong to multiple projects. A dataset can be active or not, which is why I need the has_many through instead of the has_many_and_belongs_to setup.
My model definitions are:
class Project < ActiveRecord::Base
  attr_accessible :name, :user_id

  belongs_to :user
  has_many :activedatasets
  has_many :datasets, :through => :activedatasets

end

class DataSet < ActiveRecord::Base
  attr_accessible :name, :project_id, :filename, :tempfilename

  has_many :activedatasets
  has_many :projects, :through => :activedatasets

end

class ActiveDataSet < ActiveRecord::Base
  attr_accessible :active, :data_set_id, :project_id

  belongs_to :project
  belongs_to :dataset

end

When I create a new dataset I've got the project_id in the params, so I'm trying to setup the relationship like below:
class DataSetsController < ApplicationController
  def new
    @dataset = DataSet.new
    @dataset.activedatasets.project_id = params[:project_id]
  end
end

The error I'm getting seems famous:
NameError in DataSetsController#new

uninitialized constant DataSet::Activedataset

Can anybody point me in the right direction please?
Thanks for you attention.

A: You need to use:
has_many :active_data_sets
has_many :data_sets, :through => :active_data_sets

And in the DataSet model:
has_many :active_data_sets
has_many :projects, :through => :active_data_sets

Basically, rails expects you to use underscores to separate words in association names, and converts them to CamelCase. So active_data_sets becomes ActiveDataSet. Rails then uses this to work out which model class the association is with.
You also need to change your controller to this:
class DataSetsController < ApplicationController
  def new
    @dataset = DataSet.new
    @dataset.active_data_sets.build(:project_id => params[:project_id])
  end
end

Otherwise you'll get an error because you tried to set the project_id of the active_data_sets collection rather than creating a new ActiveDataSet.


text:
Q: Laptop lid closed and screen disabled once system is up I have laptop and external monitor. I set up in power settings for lid to Do nothing when is closed, besides i also set up all options to Do Nothing therefore when i close the lid when system is running and open lid again my laptop's screen turn on as well. No issue.
Nevertheless when laptop lid is closed and i run Windows 10 system then when i open laptop's lid once system is up - laptop screen is not turning on. I even do not see that screen in Display settings. How to make laptop screen enable once i open lid in this particural case?
My setup:
> HP 8760W + docking station (video: NVIDIA)
> LG 34 (external monitor)


text:
Q: Serverprocesses ending with '-d'? I just realized, that every serverprocess ends with a d?
Like:

*

*Apache: httpd

*MySQL : mysqld

*Unreal IRC : unrealircd

Why is this? Is there any reason, or is it to recognize them from each other?

A: It's a convention for programs that run in the background to perform a task.
It means Daemon - inspired by Maxwell's Daemon, an imaginary creature from the world of physics charged with reversing entropy by sorting molecules.


text:
Q: 2nd order passive low pass filter cutoff frequency with additional paralel resistor before the second capacitor How we can calculate the transfer function and cutoff frequency for this type of filter?
For second order low pass filter the natural frequency is:
$$
f_n = \frac{1}{2\pi \sqrt{R_1 R_2 C_1 C_2}}
$$
damping factor is:
$$
\zeta = \frac{R_1 C_1 + R_1 C_2 + R_2 C_2}{2 \sqrt{R_1 R_2 C_1 C_2}}
$$
and the cutoff frequency is:
$$
f_c = f_n \sqrt{(1 − 2\zeta^2) + \sqrt{4\zeta^4 − 4\zeta^2 + 2}}.
$$
But for this type of filter I don't know the cutoff frequency formula.

simulate this circuit – Schematic created using CircuitLab

A: This type of passive circuit can be easily solved and expressed in a so-called low-entropy format using the fast analytical circuits techniques or FACTs. Without writing a single line of algebra, you can "inspect" the circuit and determine the transfer function. In this approach, you determine the natural time constants of the circuit by reducing the stimulus \$V_{in}\$ to 0 V. When you do that, the left terminal of \$R_1\$ is grounded. In this configuration, remove the capacitors and "look" at the resistance from their terminals. The obtained resistance multiplied by the capacitance forms the time constant \$\tau\$ we need. Here, we have two energy-storing elements (with independent state variables) so this is a 2nd-order circuit obeying the following expression for the denominator \$D(s)\$:
\$D(s)=1+s(\tau_1+\tau_2)+s^2\tau_1\tau_{12}\$
We start with \$s=0\$ for which you open all caps. The transfer function is simply:
\$H_0=\frac{R_3}{R_3+R_1+R_2}\$
If you now apply the technique consisting of "looking" at the resistance offered by the capacitors terminals while \$V_{in}\$ is 0 V, you should find:
\$\tau_1=C_1(R_1||(R_2+R_3))\$
\$\tau_2=C_2(R_3||(R_1+R_2))\$
\$b_1=\tau_1+\tau_2=C_1(R_1||(R_2+R_3))+C_2(R_3||(R_1+R_2))\$
Then, consider shorting \$C_1\$ while you look at the resistance offered by \$C_2\$ terminals in this mode. You have
\$\tau_{12}=C_2(R_2||R_3)\$
\$b_2=\tau_1\tau_{12}=C_1(R_1||(R_2+R_3))C_2(R_2||R_3)\$
Assembling these expressions, we have the complete transfer function as there is no zero in this network.
\$H(s)=H_0\frac{1}{1+s(C_1(R_1||(R_2+R_3))+C_2(R_3||(R_1+R_2)))+s^2(C_1(R_1||(R_2+R_3))C_2(R_2||R_3))}\$
This is a second-order polynomial form obeying:
\$H(s)=H_0\frac{1}{1+\frac{s}{\omega_0Q}+(\frac{s}{\omega_0})^2}\$
in which \$Q=\frac{\sqrt{b_2}}{b_1}\$ and \$\omega_0=\frac{1}{\sqrt{b_2}}\$
If \$Q\$ is sufficiently low (low-\$Q\$ approximation) you can replace the second-order polynomial form by two cascaded poles. All appears in the below picture:

If you look at the raw expression transfer function \$H_{ref}(s)\$ (using Thévenin), it perfectly matches the low-entropy version. The difference is that you now have a well-ordered transfer function letting you calculate the values for all components depending on how you want to tune this filter. What truly matters is the low-entropy well-ordered form which tells you what terms contribute gains (attenuation), poles and zeros. Without this arrangement, there is no way you can design your circuit to meet a certain goal. To my opinion, the FACTs are unbeatable to obtain these results in one clean shot. Furthermore, as you can see, I have not written a single line of algebra. All I did was inspecting the network (through small individual sketches if necessary).
You can discover FACTs further here
http://cbasso.pagesperso-orange.fr/Downloads/PPTs/Chris%20Basso%20APEC%20seminar%202016.pdf
and also through examples published in the introductory book
http://cbasso.pagesperso-orange.fr/Downloads/Book/List%20of%20FACTs%20examples.pdf

A: Since you only have one type of energy storage component, the capacitors, and resistors, all the poles and zeros of this circuit will be on the negative real axis.  That is because the best you can do with only one type of energy  storage element is to have alternating poles and zeros on the negative real axis.  This means there is no damping and no natural frequency.  In other words with no inductors there is nothing to resonate.
A simple technique to solve this type of circuit is to assume Vout is 1.  It is easy to get the currents through R3 and C2 now.  Add these currents and multiply by R2.  Add this to 1 and you have the voltage at the top of C1.  Now you can get the current through C1. Add C1's current to R2's and C2's and multiply by R1.  Add this to the previously calculated voltage and you have Vin.  Use this to get the transfer fuction Vout/vin.  The frequency where this function is 0.707 is the cuttoff.


text:
Q: How to convert an integer to a floating point value in x86 ASM? I need to multiply an integer (two's compliment) by a floating point constant. Here is what I have:
.data
pi  dd 3.14
int dd 0ah

.code
fld pi

???

fmul ST(1), ST

How can I convert int to a floating point value for multiplying against pi?

A: You need the fild instruction. Here's one reference: http://www.website.masmforum.com/tutorials/fptute/fpuchap5.htm

A: Using the x86 FPU is really outdated now and way slower than SSE/AVX/etc.
Better to use at least SSE with cvtdq2psdoc
ex:
.data
int dd 0ah
pi  dd 3.14

.code
movss xmm0, [data] ; load 32bit data into xmm0
cvtdq2ps xmm0, xmm0 ; convert 4 float values to integers, we use only lowest float/integer
mulss xmm0, [pi]


text:
Q: How can I simulate a 150MHz crystal oscillator in LTspice I am trying to simulate a 150MHz crystal in LTspice, but I don't get any oscillation out of it. I have an equivalent circuit of a 32MHz crystal, even with that I don't get anything out of it. What am I doing wrong?

A: The comments from the other posters are critical to getting any oscillator to simulate but I also question your choice of components.
The BC547 has rather a low FT for 150MHz oscillation. Its worst case is 150MHz with a typical of 300MHz - this is too low.
Your values for C3 and C4 seem much too large - I would expect values of ~22pF.
Lastly, although it may be a 150MHz crystal it is more likely to be a 30Mhz crystal intended to be operated at the 5th overtone - in order to achieve that it is common to include a tuned circuit in the oscillator to direct which overtone to operate at. The crystal will tend to operate at any odd overtone so the gain of the amplifier at frequencies other than the intended one need to be suppressed.

As the frequency of operation of a crystal is raised the physical thickness required becomes smaller. It is normally impractical to grind a crystal for operation above 30-50Mhz as they become too fragile. To sidestep this overtone operation is used.
Crysal Oscillator Fundamentals


text:
Q: SlideShow.js is not working in IE 8 I have created Image Slider using slideShow.js as provided in this msdn article.
It is working in IE 9 and IE 10 but not working in IE 8.
My code is as below:

      <meta content="text/html; charset=utf-8" http-equiv="Content-Type">
      <title>Slide Show</title>

            This is Label

What should I do to make the slide available in IE 8? Please help.

A: The problem with slideshow.js is that it uses window.addEventListener(...) which is only implemented in IE9, 10 and 11. Therefore it won't work in IE8.
For slideshows I prefer jQuery Cycle.
window.addEventListener() on MSDN


text:
Q: 2 iOS app with different with bundle identifier in 1 onesignal app We are working on the On-demand Photography app.
So basically we have.
2 android apps (user and photographer)
2 iOS apps (user and photographer)
android push configured with firebase and firebase allows us to configure 2 android apps against one firebase key. So multiple android apps are working on 1 one signal app id.
but iOS side doest not allow us to do so, we need to configure 2 iOS apps with 1 one signal app id.
How we can make this possible?

A: Unfortunately, you can not use two OneSignal apps in a single iOS app. Instead, you can use OneSignal's data tags feature to create segments of users based on whether they are a user or a photographer, and to send them different notifications based on this.

A: Unfortunately this is not possible. You would need to create an OneSignal app for each of these two apps. A single OneSignal App can include 1 of each platform (Website, Android App, iOS App, Email, etc.).
Refer this, https://documentation.onesignal.com/docs/dashboard


text:
Q: Permissions issues with SQL 2008, Report Builder 2.0 So here's a bit of context for the horror story:

*

*Win 2003 SP2 64bit running on a VM exposed to outside world for web access.

*SQL Server 2008 Std SP2 64bit with Reporting Services (RS) installed for native mode (i.e. not sharepoint mode).

*IIS 6 .NET 3.5 web site app written to use the web services from RS. The site has been set to use Windows Authentication and nothing else.

*To save writting custom authentication since I don't need it for this demo I have set-up a local account in Win 2003, i.e. servername\myDemoUser, effectively allow fake Windows Authentication.

*Default.aspx lists folders on RS and the reports from each folder. It also has a link to the Report Builder 2 on the server.

*The rsreportserver.config has been changed so that the only <AuthenticationType> is <RSWindowsNTLM> since <RSWindowsNegoiate> can't work since it's across the internet and users will not be on the same network (hence the local account myDemoUser).

*The web site app has url of the form: http://mysite.mydomain.co.uk/ and the link on it to the Report Builder is of the form: http://mysite.mydomain.co.uk/services/reportbuilder/reportbuilder_2_0_0_0.application, in this case RS has been configured so the Web services virtual directory is "services".

*The web.config for the website app has been set to <identity impersonate="true /> for <locations> for the ASPX pages that access the RS webservice. I even added a <location path="services/reportbuilder"> with the same thing and also to allow anonymous users.

So after all the above I go to the site from a machine that isn't on the network, I get prompted by IE8 for username/password and I enter servername\myDemoUser and the correct password. The homepage is displayed and correctly shows the list of folders and reports from RS. HOWEVER if I click the RS report builder link I get the pop window saying it's doing it's clickonce verfication stuff but after a couple of seconds it shows simple message box saying there was an authentication error. The details button then shows a text file with a bunch of stacktrace stuff in which eventually says that the server returned 401 while accessing the .application file mentioned above.
I turned on failure auditing for logins on the Win 2003 VM and I can see that when the clickonce fails it is trying to use the local machine account I logged into on the external (to my network) machine instead of the credentials I entered into the browser on that machine when testing it.
Much Googling and granting of permissions to Network service, everyone etc... on various folders involved later nothing the Report Builder bit just won't install via clickonce due to permissions or the incorrect use there of.
I'm looking into maybe changing something in the RS to try and grant permissions to the report builder to anonymous but at this point I'm pretty pessimistic that I'll actually find anything. The annoying thing about this is that this a test that doesn't represent the final thing (we'll be using custom authentication in RS) but unfortunately I have to do it, 8(.
Any ideas would be most appreciated.

A: It turns out that when using fake Windows authentication in this way when the machine you are accessing the site from a machine where you have not logged into the domain then clickOnce won't work because it won't pass the details you enter into the browser as found.
So the solution is to:
1) Log into a (any) domain on the machine that is going to access the clickonce link on your site.
2) In Control Panel go to User Accounts (XP)/Store Users and Passwords (Win 2003), and manage the network passwords for a user (XP) and add in the URL, username and password.
Whenever clickonce fires up for this URL it will pass the username/password specified as opposed to the local machine account.
Either of the above will solve this problem.


text:
Q: Function object returning constant value I want to call a function with the following signature:
void foreach(std::list<float>& floats, boost::function<float(float)> action);

This function iterates the list and modifies each element by executing new_value = action(old_value). What is the shortest way to supply such an action function that returns always the same float value. I've never tried myself, but I'd guess C++11 lambdas will do the work:
foreach(floats, [](float){ return 3.14; });

What is the closest alternative in C++03, assuming I must call my function and cannot use std::fill? Is there a trick to avoid actually declaring a regular function?

A: You can use,
std::fill(floats.begin(), floats.end(), 3.14);

A:
What is the closest alternative in C++03? Is there a trick to avoid actually declaring a regular function?

The closest trick in c++03 is to declare a function or a functor class :
float DoThing1( float )
{
  return 3.13;
}

struct DoThing2
{
  float operator()(float)
  {
    return 3.13;
  }
};

A: Check out Boost.Phoenix, it implements values as nullary functions.
Probably you will have to figure out how to use it with Boost.Function if you want to.
Here's an example of such a nullary function from the Phoenix tutorial:
template <typename F>
void print(F f)
{
    cout << f() << endl;
}

int
main()
{
    print(val(3));
    print(val("Hello World"));
    return 0;
}


text:
Q: Create a new object by using string as class name Is there a way to convert a string to class name to use like the code above (I tried to use Class.forName but it didn't work)
Class c = Class.forName("SportCar");
c car= new c();
System.out.println(car.getCost());

A: You could use:
Class<?> clazz = Class.forName(className);
Car car = (Car) clazz.newInstance();

If you have a some parameterized constructor in the class then do something like
Class<?> clazz = Class.forName(className);
clazz.newInstance();
Constructor<?> constructor = clazz.getConstructor(String.class);
Car object = (Car) constructor.newInstance(new Object[] { someArgument}); // constructor args

A: You need call to newInstance method:
Class<SportCar> c = (Class<SportCar>) Class.forName("package.to.SoprtCar");
SportCar car = c.newInstance();
System.out.println(car);

A: Getting Class type from String
make sure that you have the full class name like com.mycompany.MyClass when using the for Name Methdo

A: You could create an Object having the class name SportCar. Though it is a very costly way for object creation, using reflection.
And in fact you want to use some features of SportCar, namely the method getCost.
interface Costly { BigDecimal getCost(); }

class SportCar implements Costly { ... }

Class c = Class.forName("SportCar");
Costly car= (Costly) c.newInstance();
System.out.println(car.getCost());

There are better, less artificial code patterns for a couple of different use cases.
Here one could use a factory pattern to receive a SportCar (or Costly).
For extendability, where an application with the addition of one or more libraries of still unknown classes receives an implementation class of some interface, java SPI (service provider interface) can be used.


text:
Q: How to handle special characters like "&" in XML Parsing for R? I am a newbie to XML in R So I need help to overcome this problem.
I have following XML
hp <- htmlParse('

Culture & Values
  Â Â Â Â
Â

Work/Life Balance
  Â Â
Â Â Â

')

In the above XML, I am trying to grab "title" value when div has a value "Culture & Values" using following R code but is not giving me expected output. I am getting Null value as output although I was expecting "5.0" as output.
CultureValues<-unlist(xpathApply(hp,"//div[text()='Culture & Values']/following-
sibling::span", xmlGetAttr,"title"))

Many thanks in advance.

A: You can use the following:
> xpathSApply(hp, "//*[contains(text(),'Culture ')]/following-sibling::span/@title")
title
"5.0"

or change your query to
> CultureValues<-unlist(xpathApply(hp,"//div[text()='Culture & Values']/following-sibling::span", xmlGetAttr,"title"))
> CultureValues
[1] "5.0"

& is just the entity name for &


text:
Q: How to create a Rust struct with string members? I want the members to be owned by the struct. I'm looking for the correct declaration of a struct and instantiation examples. I wasn't able to find an example.

A: If the string has to be owned by the struct, then you should use String. Alternatively, you could use an &str with a static lifetime (i.e., the lifetime of the program). For example:
struct Foo {
    bar: String,
    baz: &'static str,
}

fn main() {
    let foo = Foo {
        bar: "bar".to_string(),
        baz: "baz",
    };
    println!("{}, {}", foo.bar, foo.baz);
}

If the lifetime of the string is unknown, then you can parameterize Foo with a lifetime:
struct Foo<'a> {
    baz: &'a str,
}

See also:

*

*What are the differences between Rust's `String` and `str`?
If you're not sure whether the string will be owned or not (useful for avoiding allocations), then you can use borrow::Cow:
use std::borrow::Cow;

struct Foo<'a> {
    baz: Cow<'a, str>,
}

fn main() {
    let foo1 = Foo {
        baz: Cow::Borrowed("baz"),
    };
    let foo2 = Foo {
        baz: Cow::Owned("baz".to_string()),
    };
    println!("{}, {}", foo1.baz, foo2.baz);
}

Note that the Cow type is parameterized over a lifetime. The lifetime refers to the lifetime of the borrowed string (i.e., when it is a Borrowed). If you have a Cow, then you can use borrow and get a &'a str, with which you can do normal string operations without worrying about whether to allocate a new string or not. Typically, explicit calling of borrow isn't required because of deref coercions. Namely, Cow values will dereference to their borrowed form automatically, so &*val where val has type Cow<'a, str> will produce a &str.


text:
Q: Netsuite - currency FX rate - api export data I would like to export on a daily basis, currency (currencies object) FX rate. is it optional by OOTB API request?
In case not, can i create BI report in Netsuite and use it as API request to pull out the data?
There are other options to do that?
Thx


text:
Q: Discretizing the Wave Equation in polar coordinates I want to discretize the wave equation
$$\frac{1}{c^2}\frac{\partial^2\psi\left(\vec{r},t\right)}{\partial t^2}=\triangle\psi\left(\vec{r},t\right)$$
in polar coordinates. I find the following relations:
$$\vec{r}=r\mathbf{e}_r$$
$$\triangle=\frac{1}{r}\partial_r r \partial_r+\frac{1}{r^2}\partial_\varphi^2$$
Define:
$$r=i\Delta r,\qquad\varphi=j\Delta\varphi,\qquad t=n\Delta t$$
Thus:
$$\psi\left(r,\varphi,t\right)=\psi\left(i\Delta r,j\Delta \varphi,n\Delta t\right)\equiv\psi_{i,j}^{\left(n\right)}$$
Using the forward difference in $r$ and central differences in $\varphi$ and $t$, I get:
$$\psi_{i,j}^{\left(n+1\right)}=2\psi_{i,j}^{\left(n\right)}-\psi_{i,j}^{\left(n-1\right)}+\frac{c^2 \Delta t^2}{\Delta r^2}\left[\psi_{i+2,j}^{\left(n\right)}+\frac{1}{i}\psi_{i+2,j}^{\left(n\right)}-2\psi_{i+1,j}^{\left(n\right)}-\frac{1}{i}\psi_{i+1,j}^{\left(n\right)}+\psi_{i,j}^{\left(n\right)}\right]+\frac{c^2\Delta t^2}{i^2\Delta r^2\Delta \varphi^2}\left[\psi_{i,j+1}^{\left(n\right)}+\psi_{i,j-1}^{\left(n\right)}-2\psi_{i,j}^{\left(n\right)}\right]$$
Now this is divergent at $r=0$, did I something wrong?
And how can I set restrictions to the steps $\Delta r$, $\Delta \varphi$ and $\Delta t$?

A: If you look at the Laplacian:
$$
\nabla^2=\frac{1}{r}\,\frac{\partial}{\partial r}\left(r\frac{\partial}{\partial r}\right)+\frac1{r^2}\frac{\partial^2}{\partial\phi^2}
$$
you can clearly see that this diverges at $r=0$ so discretization of this should also diverge.
There are three solutions to remedying the divergent feature that I can think of:

*

*Choose a problem such that you don't need to worry about $r=0$ (e.g., $r_{min}=0.1$)

*Use cell-centered values for $r$ (e.g., $r_{min}=\frac12dr$)

*Use two meshes a Cartesian one for $r<1$ and a polar one for $r\geq1$, merging them at $r\simeq1$ (requires at least 1 cell of overlap).

I've never used option #3, so I cannot speak anything about it. Option #1 works in certain cases, but not for all. Option #2 I have worked with and have seen in other hydrodynamics codes that I've used, so it might be your best bet.

As far as your discretization goes, I think it might be more clear to use $r_i$ and $\phi_j$ for the positions and $dr$ and $d\phi$ for the cell widths. Using this,
$$
\frac{1}{r}\,\frac{\partial}{\partial r}\left(r\frac{\partial\psi}{\partial r}\right)=\frac{1}{r_i}\left(r_{i+1/2}\frac{\psi^n_{i+1,j}-\psi^n_{i,j}}{dr^2}-r_{i-1/2}\frac{\psi^n_{i,j}-\psi^n_{i-1,j}}{dr^2}\right)
\\
\frac{1}{r^2}\frac{\partial^2\psi}{\partial\phi^2}=\frac{1}{r_i^2}\left(\frac{\psi^n_{i,j+1}-2\psi^n_{i,j}+\psi^n_{i,j-1}}{d\phi^2}\right)
$$
where $r_{i+1/2}=\frac12\left(r_{i+1}+r_i\right)$.
Your choice for $dr$ and $d\phi$ are up to you. It might be easier to have $dr=d\phi$, but it might not be worth enforcing that behavior. The timestep, however, is limited by the Courant-Friedrichs-Levy condition. For the wave equation, your requirement is such that
$$
c^2\frac{dt}{\min(dr^2,d\phi^2)}\leq\frac12
$$
Formally, the constant can be 1 instead of $\frac12$, but for multidimensional systems, it is appropriate to use $1/n_{dim}$. For time-stepping purposes, this is going to be the slow point of your code. It might be worth looking into implicit methods instead of the explicit method you are currently working with.


text:
Q: Password validator is not working in android In my application I am accepting a password from the user which should be in following format:-

*

*case sensitive and

*must be at least 6 characters long,

*including at least

*

*one letter (a-Z),

*one number (0-9) and

*one of the following special characters:!=+*;:-,._{[()]}#%?@

So by following the tutorial given here:
http://www.mkyong.com/regular-expressions/how-to-validate-password-with-regular-expression/
I have created my own pattern as:-
private static final String PASSWORD_PATTERN = "($\\S*(?=\\S{6,})(?=\\S*[a-z])(?=\\S*[A-Z])(?=\\S*[\\d])(?=\\S*[\\W])\\S*$)";

But it is not working properly. If I enter a correct value for the password as per pattern, it still displays an error to me.
Please tell me what's happening here; what error is there?
Here is my code:-
 PWD_Validate = new PasswordValidator();
    String password = TXT_PassWord.getText().toString();

   if (PWD_Validate.validate(password))
            {
            }
                                                                                else{                                                                                }                                                                                it takes me every time in else block, even I entered a correct passwaord.

A: I'm not sure why you've deviated from the pattern that is listed within the tutorial you've linked. Your pattern starts with $ which asserts position at end of the string, so it's highly unlikely you'll match anything. Usually if you're using an assertion you use $ at the very end of the pattern and ^ to assert the beginning.
Also no where in your pattern do you have any of the special characters you've outlined as those you've said are required. If you plan on matching those I would recommend including them into your pattern.
The breakdown of your regex goes like this:
$ assert position at end of the string (you've got it at the beginning).
\S* match any non-white space character [^\r\n\t\f ]
Quantifier: Between zero and unlimited times, as many times as possible, giving back as needed [greedy]
(?=\S{6,}) Positive Lookahead - Assert that the regex below can be matched
\S{6,} match any non-white space character [^\r\n\t\f ]
 Quantifier: Between 6 and unlimited times, as many times as possible, giving back as needed [greedy]
(?=\S*[a-z]) Positive Lookahead - Assert that the regex below can be matched
\S* match any non-white space character [^\r\n\t\f ]
Quantifier: Between zero and unlimited times, as many times as possible, giving back as needed [greedy]
[a-z] match a single character present in the list below
 a-z a single character in the range between a and z (case sensitive)
(?=\S*[A-Z]) Positive Lookahead - Assert that the regex below can be matched
\S* match any non-white space character [^\r\n\t\f ]
Quantifier: Between zero and unlimited times, as many times as possible, giving back as needed [greedy]
[A-Z] match a single character present in the list below
A-Z a single character in the range between A and Z (case sensitive)
(?=\S*[\d]) Positive Lookahead - Assert that the regex below can be matched
\S* match any non-white space character [^\r\n\t\f ]
Quantifier: Between zero and unlimited times, as many times as possible, giving back as needed [greedy]
[\d] match a single character present in the list below
 \d match a digit [0-9]
(?=\S*[\W]) Positive Lookahead - Assert that the regex below can be matched
\S* match any non-white space character [^\r\n\t\f ]
Quantifier: Between zero and unlimited times, as many times as possible, giving back as needed [greedy]
[\W] match a single character present in the list below
 \W match any non-word character [^a-zA-Z0-9_]
\S* match any non-white space character [^\r\n\t\f ]
Quantifier: Between zero and unlimited times, as many times as possible, giving back as needed [greedy]
$ assert position at end of the string

To be quite honest your regex is so far off from the tutorial you've
  linked that it's not even remotely close. I would recommend you go
  back and thoroughly re-read and study the guide, for it's apparent you
  haven't applied any of it to be applicable by any means.


text:
Q: PGError: SSL connection failure, H10 error My application using heroku and postgresql is 100% down and the application crashes with an H10 error. I believe the log below is the route of the problem:
2012-08-28T19:17:44+00:00 app[web.1]: /app/vendor/bundle/ruby/1.9.1/gems/activerecord-3.2.3/lib/active_record/connection_adapters/postgresql_adapter.rb:1194:in `initialize': FATAL:  role "arseiiyfkbqalv" is not permitted to log in (PGError)

A: (I just your case as I work at the heroku data team)
You deprovisioned your dev database, but have not updated your dyno's configuration to make it connect to a new one. You can do that by running heroku pg:promote HEROKU_POSTGRESQL_<NEW COLOR> --app your-app
You can view a list of databases currently on your app by running heroku pg:info --app your-app. The database that is promoted as the primary will also show that it is DATABASE_URL.


text:
Q: Symfony replace authentication check functionality I am somewhat new to Symfony. I need to check if the user is logged in on every page request. I created a login screen and store the IP address, session id, time of login, username, id and a few more variables in the user table as well as in a session variable. Now I have to check many at every page requests for these variables variables. Can someone let me know where to do the check?

A: you probably want to create a "preExecute" method, i.e. something that is executed before any of your controller actions. Take a look here:
How to create a something like Zend preDispatch method in Symfony2

A: Symfony has a very advanced security component which you should use instead of rolling your own security. It will save you tons of headaches. Read about this security component here:
http://symfony.com/doc/current/book/security.html
I would also suggest that you use the FOSUserBundle, which is a great complement to symfony security and which provides advanced user handling. You can find this bundle here:
https://github.com/FriendsOfSymfony/FOSUserBundle

A: you can check if is granted with IS_AUTHENTICATED_ANONYMOUSLY, IS_AUTHENTICATED or IS_AUTHENTICATED_FULLY
In the controller you can use the security.context for that the check
http://symfony.com/doc/current/book/security.html#securing-a-controller


text:
Q: Concatenate rows in select query (in Advantage Data Architect) How can I concatenate rows in select query? (in Advantage Data Architect)
I tried run the following scripts:
The first script:
declare @str string;
set @str = '';
select @str = @str + field_1 from my_table1

But I get a result where all rows contain "false", like this picture:

Second script:
declare @str string;
select @str = coalesce(@str + ', ','') + field_1 from my_table1

This time, all rows are empty (note: the field from "my_table1" is not null).
Picture:

I tried to search the solution on the Internet for Advantage Data Architect, but I could not find a solution.

A: I'm assuming you want something like GROUP_CONCAT in MySQL or string_agg in Oracle / Postgres.
The general algorithm for that is something like:
DECLARE @S STRING;

DECLARE CURSOR C AS
SELECT
  CONVERT(field_1, SQL_CHAR) AS "val"
FROM
  my_table1;

OPEN C;

WHILE FETCH C do
  -- Since @S is NULL for the first row this will ensure
  -- that the result does not start with the separator.
  @S = COALESCE(@S + ', ' + C.val, C.val);
END;

CLOSE C;

SELECT @S;

A general function can be found on the ADS forum.
PS: This is the reverse of splitting a string into separate rows.


text:
Q: How do I enable AVB on Mac Catalina 10.15 I am getting a message AVB is not enabled in my midi network device browser.
Apple Support:  Browse your network for an AVB device in Audio MIDI Setup on Mac
I am following this, however, on step 3,  that option doesn't exist.  Only automatic and manual are present, and in manual you have to enter a number.  There's nothing ABV related.

A: Modern macs will generally only support AVB when you hard wire an Ethernet cable directly to a USB-4 (only USB that works) / Thunderbolt port.
Audio Video Bridging is a set of technologies that allow Ethernet to support the kind of time-sensitive data delivery needed to keep multiple connected audio devices in sync. It is not trivial.
Apple does not advertise which computers or connections support ABV. It seems most Macs today can support it, but only on a limited number of interfaces. In particular, there is no ABV support over WiFi or via a USB-to-Ethernet adapter. In fact, I cannot even get ABV to work when connected to a Thunderbolt 3 Dock.
It seems the only way to get ABV support is to connect to a built-in Ethernet port if the Mac has one or to connect via a Thunderbolt to Ethernet adapter. This is hinted at by the help message from Audio Midi Setup when you do not have AVB enabled. It says in part

See the help guide for configuration instructions if your computer does not have built-in ethernet or if it has more than one network service that can support AVB.

Unfortunately, I do not know what "help guide" it is referring to, but it does lend support to the idea that AVB is only supported by "built-in" Ethernet.

A: Most network interfaces don't support ABV so most people will see no devices. The help guide isn't clear, direct or helpful.
We would need to know your exact marketing name for your Mac and the exact full chain of how an Ethernet cable or hard wired network is attached to your Mac to confirm this is the case. Since your Mac runs Catalina, it's probably just your network setup that needs attention.
I remember this from my days of dealing with PreSonus equipment...

*

*Any Mac with with a Thunderbolt Port had support for AVB

*Requires macOS 10.10 or later

*USB-Ethernet is not supported

*Only one device is supported at a time

If you aren't seeing the option ("it doesn't exist") that means AVB isn't supported with that particular connection.


text:
Q: String was not recognized as a valid boolean C# I get the error "String was not recognized as a valid boolean" I am coding in C# and can't seems to find out what the problem is. Any insight would be very much appreciated. This is my code where it's failing:
    public static SalesInfo Parse(string stringValue)
    {
        string[] words;
        SalesInfo salesInfo = new SalesInfo();

        words = StringMethods.ParseCsvString(stringValue.Trim());
        salesInfo.ID = int.Parse(words[0]);
        salesInfo.Name = words[1];
        salesInfo.City = words[2];
        salesInfo.Senior = bool.Parse(words[3]);<----Error here
        salesInfo.Veteran = bool.Parse(words[4]);
        salesInfo.PurDate = Date.Parse(words[5]);
        salesInfo.ItemPrice = Double.Parse(words[6]);
        salesInfo.Quantity = int.Parse(words[7]);

        return salesInfo;
    }

A: bool.Parse will only parse a string of "True" or "False" (case-insensitive).
The MSDN documentation for bool.TryParse shows a good example of the types of strings that can be parsed.
If your input string is some other variation of "truthiness" you would have to write your own parser. Something like:
public static SalesInfo Parse(string stringValue)
{
    ...cut for brevity...

    salesInfo.Senior = ParseBool(words[3]);

    return salesInfo;
}

public bool ParseBool(string input)
{
    switch (input.ToLower())
    {
        case "y":
        case "yes":
            return true;
        default:
            return false;
    }
}

A: If this contains "Y" / "N" you have to do something kind of like this code sample:
void Method()
{
 string arr = new[] { "Y", "n", "N", "y"};

 foreach (string value in arr)
 {
    // If it DOES equal "y", then this is "true"; otherwise "false"
    bool boolean = value.Trim().ToLower().Equals("y");
 }
}

Trying to do something like bool.Parse("Y") will definitely throw an exception.
The weakness of the code sample above is that if the data is bad (i.e. it contains something other than a "Y" or "N") it won't detect that.
public static SalesInfo Parse(string stringValue)
{
    string[] words;
    SalesInfo salesInfo = new SalesInfo();

    words = StringMethods.ParseCsvString(stringValue.Trim());
    salesInfo.ID = int.Parse(words[0]);
    salesInfo.Name = words[1];
    salesInfo.City = words[2];
    // Solution here
    salesInfo.Senior = words[3].Trim().ToLower().Equals("y");
    salesInfo.Veteran = bool.Parse(words[4]);
    salesInfo.PurDate = Date.Parse(words[5]);
    salesInfo.ItemPrice = Double.Parse(words[6]);
    salesInfo.Quantity = int.Parse(words[7]);

    return salesInfo;
}

I like Steve's approach a lot as well. One possible variant is as follows:
public bool ParseBool(string input)
{
   if (input == null)
      throw new ArgumentNullException("input");

   switch (input.ToLower())
   {
       case "y":
       case "yes":
           return true;

       case "n":
       case "no":
            return false;

       // If the CSV file is wrong (i.e. it contains "bad" data)
       default:
           return throw new ArgumentException("bad data - not a bool");
    }
}


text:
Q: Javascript "then"ing of a member function doesn't trigger '15 I'm trying to wrap my head around javascript's then structure (supposably an easy way to implement promises if I understand correctly). Almost all answers I find are from years ago, and things seem to have updated significantly since then. Honestly, I am also having difficulty understanding documentation on promises and then, so I could easily be making a basic mistake.
I've got some test code as such:
function foo(){
   this.start = function(){
       return {
           then: function(callback){
               alert("Waiting for this to finish.");
           }
      }
   }
}
var makeItSo = new foo();
makeItSo.start().then( function() {
    alert("I waited!");
});

Although the "Waiting for this to finish" fires, the "I waited!" never does. What do I need to change in my foo function so that this works?

A: You're not invoking "callback" in your "then" function so the function that runs the "I waited" alert never runs. Try this.
function foo(){
   this.start = function(){
       return {
           then: function(callback){
               alert("Waiting for this to finish.");
               callback()
           }
      }
   }
}
var makeItSo = new foo();
makeItSo.start().then( function() {
    alert("I waited!");
});


text:
Q: call to a member function fetch() on a non-object in pdo I don't why I'm getting a call to a member function fetch() on a non-object in pdo error. It's really frustrating me!
$db= new PDO($dns,DB_USER,DB_PASS);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$workspace_id=isset($_GET['workspace']) ? (int)$_GET['workspace'] : "";

try{
    $sql="SELECT * FROM messages WHERE workspace_id = :id";
  $stmt=$db->prepare($sql);
  $stmt->bindValue(':id', $workspace_id, PDO::PARAM_INT);
  $result=$stmt->execute();
  $message=$result->fetch();
}catch(Exception $e){echo $e->getMessage();}

A: Because $stmt->execute() should return boolean value.
If you want to use the fetch you should call method from $stmt
Documentation: PDOStatement

A: execute()

Returns TRUE on success or FALSE on failure.

In your case you are try to fetch data form bool value
$result=$stmt->execute();
$message=$result->fetch();

Just need to change
 $stmt->execute();
 $message=$stmt->fetch();


text:
Q: Strange webserver issue MY OS: Ubuntu 12.10
Web server environment is: Nginx + PHP-FPM
Installed based on this tutorial
Here is nginx conf file of website
server {
set $host_path "path_to_website";

server_name  website.local;

root $host_path;
set $yii_bootstrap "index.php";

charset utf-8;
index index.php index.html;

log_not_found off;

location / {
    index  index.html $yii_bootstrap;
    try_files $uri $uri/ /$yii_bootstrap?$args;
    }

    location ~ ^/(protected|framework|themes/\w+/views) {
    deny  all;
    }

    #avoid processing of calls to unexisting static files by yii
    location ~ \.(js|css|png|jpg|gif|swf|ico|pdf|mov|fla|zip|rar)$ {
    try_files $uri =404;
}

location ~ \.php$ {
    fastcgi_split_path_info  ^(.+\.php)(.*)$;
    #let yii catch the calls to unexising PHP files
    set $fsn /$yii_bootstrap;
    if (-f $document_root$fastcgi_script_name){
        set $fsn $fastcgi_script_name;
    }
    fastcgi_pass unix:/var/run/php5-fpm.sock;
    fastcgi_index index.php;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    include fastcgi_params;
}

location ~ /\.ht {
    deny  all;
}

}
BTW, this configuration is optimized for Yii framework
The problem is, when I try to enter to the website, getting following error:
File not found.

And when I open nginx error.log file, I see following content
    2013/03/22 23:36:45 [crit] 14388#0: *4 stat() "path_to_website" failed (13: Permission denied), client: 127.0.0.1, server: website.local, request: "GET / HTTP/1.1", host: "website.local"
2013/03/22 23:36:45 [crit] 14388#0: *4 stat() "path_to_website" failed (13: Permission denied), client: 127.0.0.1, server: website.local, request: "GET / HTTP/1.1", host: "website.local"
2013/03/22 23:36:45 [crit] 14388#0: *4 stat() "path_to_websiteindex.php" failed (13: Permission denied), client: 127.0.0.1, server: website.local, request: "GET / HTTP/1.1", host: "website.local"
2013/03/22 23:36:45 [error] 14388#0: *4 FastCGI sent in stderr: "Primary script unknown" while reading response header from upstream, client: 127.0.0.1, server: website.local, request: "GET / HTTP/1.1", upstream: "fastcgi://unix:/var/run/php5-fpm.sock:", host: "website.local"

I'm 100% sure about path of website, and also added into hosts file website.local. Also chown-ed recursively whole parent directory recursively, where website located.
I can't figure out what can be problem. PLease help me to fix this problem. I can give remote acces to anyone who wants to help.
NOTE
I just replaced the real path with this path_to_website for confidence. Thats all. THere is real path

A:  set $host_path "path_to_website";

you need to define what your path_to_website is:
ie: /var/www/

*

*open terminal

*List item

*cd into the root of your www directory

*type in 'pwd', and whatever it results

*enter that into $host_path

A: An nginx log file never lies. If it says it's a "Permission denied" error, then it is. You need to

*

*make sure this folder itself "path_to_website" is readable to the user www-data (which is the user running nginx based on your screenshot). One way to try this is to run this command in a terminal:
 sudo -u www-data ls path_to_website

and see if permission is denied for www-data or just
   ls -la path_to_website

to investigate that path's permission info.

*

*It is possible that a parent folder of your "path_to_website" is not accessible by user www-data. For example, if your path_to_website is "/var/www/mysite/", maybe "/var" or "/var/www" is not readable by www-data.


text:
Q: React Multistep form with single child component I have a parent form component and a child form component. It's a multistep form where each step is a rendering of the same child component. The child component's input fields change dynamically based on the user's input. It works and I can successfully pass the input up to the state of the parent form component, but the problem is that the inputs persist to the next step.
I'm assuming this is because each step uses the same component, but I don't know how to avoid this behavior without an excessive amount of state usage to load the appropriate values for whichever step the user is at. I can clear the form as the user moves to each next step, but then the user wouldn't be able to go back to a previous step.
Any suggestions?
(I know I could just shove everything into one component or make a separate component for each step, but neither of those seem like the most efficient approach)


text:
Q: careers@stackoverflow.com rejecting requests I tried to send an email to careers@stackoverflow.com from my personal mail account; however, it appears my email was rejected, with the following message from GMail:
Delivery to the following recipient failed permanently:

    careers@stackoverfow.com

Technical details of permanent failure:
The recipient server did not accept our requests to connect. Learn more at http://mail.google.com/support/bin/answer.py?answer=7720
[allmail.0b2.net. (10): Connection refused]

I had a support question that I had preferred not to ask in a public forum such as meta. Is this email address still a valid address to contact for support on careers.stackoverflow.com?

A: You're missing a 'l' in the email address you sent your email to.


text:
Q: How to limit/lock framerate (FPS) like in FRAPS video-recording mode? Is there a way to limit or lock framerate (FPS) to a certain maximum value, just like FRAPS is able to do while recording? I am trying to play Last Bronx on Win XP, but the game runs way too fast, even with Frameskip set to "None" (there is no framelimit option).
I had some success experimenting with FRAPS (which is presumably notorious for decreasing games performance) as it has an option to lock framerate for recording purposes. It works great and locks to 60 FPS this way, but recording is tedious, takes space and I have to remember to delete my movies after playing (even if only to ensure nobody sees me getting regularly pummelled heh).
Is there a way to lock framerate in FRAPS without recording (i.e. automatically redireting recorded AVI > dev/null or something similar)? If not, is there any other software or way to lock game's framerate?
I already tried forcing vsync in AMD CCC, with no effect. Same for disabling Direct3D/DirecrDraw acceleration using dxdiag. I also launched some cpu-consuming software in background, but this usually results in stuttering and reduces playability more effectively than the framerate. Last Bronx is not DOS-based, so apparently DOSBox is also not an option.

A: Unfortunately, Fraps has no option to enable it outside of recording.
You could use Dxtory though to lock your fps. It is a tool to play games that run too fast because they do improper timing and are actually "timed" by their framerate. Which is a horrible design idea btw, if I might add that.
There is also a comprehensive guide over at the Steam Forums.

An alternative to this is Bandicam. On the feature overview on the download page it says that this feature is freely available even in the trial edition which is not restricted by time.

To make this answer complete:
For NVIDIA Users there is a Tool called "NVIDIA Inspector" which can do FPS limiting too and that Tool is actually free.

A: RadeonPro is free and will allow you to  lock the framerate. (on the tweaks tab) Not sure if it works with DX5 though. :/
http://www.radeonpro.info/download/


text:
Q: Adding initialized ViewModels to ObservableCollection displaying null property values When adding ViewModels to an ObservableCollection, which is shown on the MainWindow as an ItemsControl with the ObservableCollection as the ItemsSource. The initial values of the View are displayed as null. I know this because on debugging and changing the value of the TextBox I see that the Name field is set to null, but when I press the button to add new ViewModels it is setting the Name field but then not displaying the name. This app has been condensed for ease of debugging. So it seems that while the ObservableCollection is communicating to the view it is not receiving the proper values somehow.
MainWindow
<Window x:Class="LifeCalculator.Views.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:prism="http://prismlibrary.com/"
    prism:ViewModelLocator.AutoWireViewModel="True"
    xmlns:myControl="clr-namespace:LifeCalculator.Views" xmlns:views="clr-namespace:LifeFinanceCalculator.Views"
    Title="{Binding Title}" Height="350" Width="525">
<Grid>
    <Button Margin="47,24,373,269" Content="Add ViewModels" Command="{Binding AddCommandItem}"/>
    <ScrollViewer Margin="28,75,37,72">
        <ItemsControl ItemsSource="{Binding ListExampleItems}">
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <views:exampleView/>
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>
    </ScrollViewer>
</Grid>

MainWindowViewModel
using Prism.Mvvm;
using System.Collections.ObjectModel;
using LifeFinanceCalculator.ViewModels;
using System.Windows.Input;
using Prism.Commands;

namespace LifeCalculator.ViewModels
{
    public class MainWindowViewModel : BindableBase
    {
        private ObservableCollection<exampleViewModel> _listExampleItems;
        public ObservableCollection<exampleViewModel> ListExampleItems
        {
            get => _listExampleItems;
            set
            {
                SetProperty(ref _listExampleItems, value);
            }
        }
        public ICommand AddCommandItem { get; set; }

        public MainWindowViewModel()
        {
            _listExampleItems = new ObservableCollection<exampleViewModel>();
            AddCommandItem = new DelegateCommand(ListItem);
        }

        private void ListItem()
        {
            _listExampleItems.Add(new exampleViewModel() { Name = "Chris" });
            _listExampleItems.Add(new exampleViewModel() { Name = "Olivia" });
        }
    }
}

exampleView
<UserControl x:Class="LifeFinanceCalculator.Views.exampleView"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:prism="http://prismlibrary.com/"
             prism:ViewModelLocator.AutoWireViewModel="True">
    <Grid>
        <TextBox Text="{Binding Name}" FontSize="22"/>
    </Grid>
</UserControl>

exampleViewModel
using Prism.Mvvm;

namespace LifeFinanceCalculator.ViewModels
{
    public class exampleViewModel : BindableBase
    {
        private string _name;
        public string Name
        {
            get => _name;
            set
            {
                SetProperty(ref _name, value);
            }
        }
        public exampleViewModel()
        {
        }
    }
}

A: The ViewModelLocator used by Prism was the issue. The ViewModelLocator re-intializes the View with a new ViewModel. To solve the issue :
prism:ViewModelLocator.AutoWireViewModel = "False"


text:
Q: How to use function srand() with time.h? My program contains code that should generate a random positive integer number every time I execute it. It generates random numbers but only once. After that, when I execute same code, it gives me same values, and it is making my code useless.
I started with the rand function, and then I used the srand() function with the time.h header file, but still it is not working properly.
#define size 10
for(i=0;i<size;i++)
    Arr[i] = rand()%size;

First call (random):
6 0 2 0 6 7 5 5 8 6

Second call (random but same as previous):
6 0 2 0 6 7 5 5 8 6

Later I visited Stack Overflow questions and I read about the srand() function, and I used it as:
#include<time.h>
for(i=0;i<size;i++)
    Arr[i] = srand(time(NULL));

First call:
-10327 -10327 -10327 -10327 -10327 -10327 -10327 -10327 -10327 -10327

Second call:
-10326 -10326 -10326 -10326 -10326 -10326 -10326 -10326 -10326 -10326

It is giving me different (but not random values). I've defined Arr[i] as unsigned int, and still I am getting negative values.

A: You need to call srand() once, to randomize the seed, and then call rand() in your loop:
#include <stdlib.h>
#include <time.h>

#define size 10

srand(time(NULL)); // randomize seed

for(i=0;i<size;i++)
    Arr[i] = rand()%size;

A: Try to call randomize() before rand() to initialize random generator.
(look at: srand() — why call it only once?)

A: If you chose to srand, it is a good idea to then call rand() at least once before you use it, because it is a kind of horrible primitive psuedo-random generator. See Stack Overflow question Why does rand() % 7 always return 0?.
srand(time(NULL));
rand();
//Now use rand()

If available, either random or arc4rand would be better.

A: #include"stdio.h"
#include"conio.h"
#include"time.h"

void main()
{
  time_t t;
  int i;
  srand(time(&t));

  for(i=1;i<=10;i++)
    printf("%c\t",rand()%10);
  getch();
}

A: #include"stdio.h"//rmv coding for randam number access

#include"conio.h"

#include"time.h"

void main()
{
    time_t t;
    int rmvivek;

    srand(time(&t));
    rmvivek=1;

    while(rmvivek<=5)
    {
        printf("%c\t",rand()%10);
        rmvivek++;
    }
    getch();
}