text:
Q: I want to click on the image to go to another page   IconButton(
        icon: Image.asset(
          'images/Da.png',
          height: 100,
          width: 100,
          fit: BoxFit.cover,
          onPressed:() {},
        )),

I want to click on the image to go to another page.
This code doesn't work. Why?

A: You need to write Navigator.push inside IconButton onPressed.
 IconButton(
            icon: Image.asset(
              'images/Da.png',
              height: 100,
              width: 100,
              fit: BoxFit.cover,
            ),
            onPressed: () {
              Navigator.push(
                  context, MaterialPageRoute(builder: (context) => SecondPage()));
            },
          ),

A: You were using onPressed inside Image.asset which doesn't support this property, put that in IconButton instead. Here is the complete solution:
IconButton(
  onPressed: () {
    Navigator.push(context, MaterialPageRoute(builder: (_) => Page2()));
  },
  icon: Image.asset(
    'images/Da.png',
    height: 100,
    width: 100,
    fit: BoxFit.cover,
  ),
)

A:  IconButton(
            icon: Image.asset(
              'images/Da.png',
              height: 100,
              width: 100,
              fit: BoxFit.cover,
            ),
            onPressed: () {
              Navigator.push(
                  context, MaterialPageRoute(builder: (context) => AnotherPage()));
            },
          ),

You can use Named Roots and other such things to write an effective flutter code.
Here is the simple article demonstrating page routing


text:
Q: alert text & variable JavaScript Can I put both text and variable in the same alert box
I thought the code down would work but it didn't

alert('text'Variable);

A:

var name = "John Doe";

function myFunction() {
  alert('Hello ' + name);
}
<button onclick="myFunction()">Checkout</button>

A:

alert('Your text goes here'+your var goes here);

I find out the code I should have put

redpajama_set_name: RedPajamaStackExchange


text:
Q: Not able to give remote access to mongodb server to other systems which are is in same wifi network on ubuntu When I set bindIp of mongod.conf file as my wifi router's default gateway i.e bindIp:127.0.0.1,198.168.3.1. my MongoDB server stops and I get following error when I check its status.
● mongod.service - MongoDB Database Server
   Loaded: loaded (/lib/systemd/system/mongod.service; disabled; vendor preset:
   Active: failed (Result: exit-code) since Thu 2020-01-23 17:42:38 IST; 1s ago
     Docs: https://docs.mongodb.org/manual
  Process: 3046 ExecStart=/usr/bin/mongod --config /etc/mongod.conf (code=exited
 Main PID: 3046 (code=exited, status=48)

Jan 23 17:42:38 sarvahapc systemd[1]: Started MongoDB Database Server.
Jan 23 17:42:38 sarvahapc systemd[1]: mongod.service: Main process exited, code=
Jan 23 17:42:38 sarvahapc systemd[1]: mongod.service: Unit entered failed state.
Jan 23 17:42:38 sarvahapc systemd[1]: mongod.service: Failed with result 'exit-c
lines 1-11/11 (END)

But when I set bindIp: 0.0.0.0 in mongod.conf file my MongoDB server runs smoothly and it allows remote access to my MongoDB server for other systems which are in my wifi network.
I want to give remote access to my MongoDB server to other systems which are in my wifi network. Can anyone help me with this?


text:
Q: Cast Collection Value Type I have a collection of type Collection<Lookup<int>> and I would like to convert its values to Collection\Lookup<int?>>.  What's the best way to do this?
Thank you

A: Well, a Lookup is a collection of keyed IEnumerables; basically a read-only Dictionary<TKey, IEnumerable<TValue>>. A Lookup<int> is nonsensical.
Probably the best way to tackle this would be to "de-group" each item from the Lookups into an anonymous key-value pair with a nullable value, then re-group the items.
Example:
var myCollectionOfNullableInts =
   (from g in MyCollectionOfIntLookups
   from v in g.Values
   select new {g.Key, Value = (int?)v}
   into l
   group l by l.Key into g2
   select g2).ToList();

The resulting collection SHOULD be a List<Lookup<[your key type], int?>>.

A: System.Collection.ObjectModel.Collection<T> is related to IEnumerable<T> you should be able to use the Select extension method.
Something along the lines of:
var listOfNullables = lookupsAsInt.Select(l => new Lookup<Int?>(l.Value)).ToList();

You'll need to include using System.Linq; in your class file.

A: Assuming that Lookup<T> has a constructor that takes some value T and a property called Value that returns the T in question....
var lookupsAsNullableInt = lookupsAsInt.Select(l => new Lookup<Int?>(l.Value)).ToList();

The thing is, you'd need to know how to construct a single new Lookup<int?> from a single Lookup<int>.  Then the above code does the work of transforming an enumeration of one into a List of the other.

A: Assuming members A,B,C, this will convert the original collection to a new Collection<Lookup<int?>> and test the first value.
        var nowNullable = new Collection<Lookup<int?>>(lookup.Select(l => new Lookup<int?> {A = (int?) l.A, B = l.B, C = l.C}).ToArray());
        nowNullable.First().A = null;
        Console.WriteLine(nowNullable.First().A.HasValue);


text:
Q: Word Automation reset numbering scheme I am new in programming with C# and am working with the Microsoft.Office.Interop.Word extension. My program takes several Word Documents and inserts these into a single document. I am having trouble with resetting the numbering scheme in my document Picture showing my issue
This is my code with which I am Inserting my Documents:
        word.Selection.InsertNewPage();
        Word.Paragraph para2;
        para2 = doc.Content.Paragraphs.Add(ref missing);
        para2.Range.Text = "Vertrag";
        para2.Range.Font.Bold = 1;
        para2.Range.Font.Size = 24;
        para2.Range.Font.Name = "Arial";
        para2.Format.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
        para2.Range.InsertParagraphAfter();
        //Resetting the Font to normal
        word.Selection.GoTo(ref gotoPage, ref gotoLast, ref missing, ref missing);
        word.Selection.ClearFormatting();

        //ADDING THE FOURTH PAGE
        word.Selection.InsertNewPage();
        word.Selection.GoTo(ref gotoPage, ref gotoLast, ref missing, ref missing);
        doc.Bookmarks.get_Item(ref endOfDoc).Range.InsertFile(filePathLeist, ref missing, ref oFalse, ref oFalse, ref oFalse);
        word.Selection.GoTo(ref gotoPage, ref gotoLast, ref missing, ref missing);
        //word.Selection.ClearFormatting();

        //ADDING THE FIFTH PAGE
        word.Selection.GoTo(ref gotoPage, ref gotoLast, ref missing, ref missing);
        word.Selection.InsertNewPage();
        string filePathAGB = filePathCommon + "\\effexx_WSIV_allgemein_AGB_2020_V1_0.docx";
        doc.Bookmarks.get_Item(ref endOfDoc).Range.InsertFile(filePathAGB, ref missing, ref oFalse, ref oFalse, ref oFalse);

I tried clearing the formatting between the two documents but that didn't work
Can someone tell me what I'm doing wrong and what can I do to resolve this issue?

A: This might be better done in a comment but I am also new here and not allowed to comment yet.
The following page, although old, should be helpful: Methods for Restarting Numbering Using vba by Margaret Aldis, Word MVP
Looking at your code, it looks good to me, but automatic numbering in Word is messed up. This has been true for more than twenty-five years. Word Numbering Explained by John McGhie, MVP There are two solid methods that are pretty much unbreakable. The first is attaching a numbering scheme to paragraph styles, one for each level as set forth in Shauna Kelly's tutorial "How to create numbered headings or outline numbering in Word." If your numbering in the your documents is tied to the same styles, it should integrate seamlessly.
The second method has been around for more than 25 years and is to use Sequence Fields. That one works wonderfully but would have to be set up the same way in each documents.
To fix document numbering in multiple documents to be using the same method through code is beyond my abilities. Anyone attempting it would need to know how the numbering is set up currently, I expect. Margaret Aldis suggests "you can create the list template and link each level to the appropriate style using a VBA macro." If I were attempting this, I would create a template with those styles and then transfer the styles to the document using the OrganizerCopy method and go through the numbering in the document applying the appropriate styles to the various numbered paragraphs in the document. This, though, would likely make a mess of any formatting of those paragraphs. Using the Organizer in Word. An example of a template that can do this can be downloaded from my site.
To make this easy in the future, you would want to have a document template in Word that is used as the basis for new documents that have to be merged. This template should have a numbering scheme set up and that should be used in each of the documents. I would recommend Shauna's method. To use it, your users should use the appropriate styles to apply the numbering, not the buttons on the Home tab.
Note that when discussing Word, the term "Template" is a term or art or jargon. Do not read it as having the usual meaning in ordinary English. Templates in Microsoft Word
If using Sequence fields, you could have the field stored in AutoText or some sort of Building Block. This is described in my page on numbering.


text:
Q: XCTest testing asyncronous Combine @Publishers I'm working on an iOS app (utilizing Swift, XCTest, and Combine) trying to test a function within my view model, which is calling and setting a sink on a publisher. I'd like to test the view model, not the publisher itself. I really don't want to use DispatchQueue.asyncAfter( because theoretically I don't know how long the publisher will take to respond. For instance, how would I test XCTAssertFalse(viewModel.isLoading)
class ViewModel: ObservableObject {
  @Published var isLoading: Bool = false
  @Published var didError: Bool = false
  var dataService: DataServiceProtocol

  init(dataService: DataServiceProtocol) {
    self.dataService = dataService
  }

  func getSomeData() { // <=== This is what I'm hoping to test
    isLoading = true
    dataService.getSomeData() //<=== This is the Publisher
      .sink { (completion) in
        switch completion {
          case .failure(_):
            DispatchQueue.main.async {
              self.didError = true
            }
          case .finished:
            print("finished")
         }

       DispatchQueue.main.async {
         self.isLoading = false
       }
     } receiveValue: { (data) in
         print("Ok here is the data", data)
    }
  }
}

I'd like to write a test that might look like:
func testGetSomeDataDidLoad() {
  // this will test whether or not getSomeData
  // loaded properly

  let mockDataService: DataServiceProtocol = MockDataService
  let viewModel = ViewModel(dataService: mockDataService)

  viewModel.getSomeData()

  // ===== THIS IS THE PROBLEM...how do we know to wait for getSomeData? ======
  // It isn't a publisher...so we can't listen to it per se... is there a better way to solve this?

  XCTAssertFalse(viewModel.isLoading)
  XCTAssertFalse(viewModel.didError)
}

Really hoping to refactor our current tests so we don't utilize a DispatchQueue.asyncAfter(

A: Yeah, everybody's saying, MVVM increases testability. Which is hugely true, and thus a recommended pattern. But, how you test View Models is shown only very rarely in tutorials. So, how can we test this thing?
The basic idea testing a view model is using a mock which can do the following:

*

*The mock must record changes in its output (which is the published properties)

*Record a change of the output

*Apply an assertion function to the output

*Possibly record more changes

In order to work better with the following tests, refactor your ViewModel slightly, so it gets a single value representing your view state, using a struct:
    final class MyViewModel {
        struct ViewState {
            var isLoading: Bool = false
            var didError: Bool = false
        }

        @Published private(set) var viewState: ViewState = .init()

        ...
    }

Then, define a Mock for your view. You might try something like this, which is a pretty naive implementation:
The mock view also gets a list of assertion functions which test your view state in order.
    class MockView {
        var viewModel: MyViewModel
        var cancellable = Set<AnyCancellable>()

        typealias AssertFunc = (MyViewModel.ViewState) -> Void
        let asserts: ArraySlice<AssertFunc>

        private var next: AssertFunc? = nil

        init(viewModel: MyViewModel, asserts: [AssertFunc]) {
            self.viewModel = viewModel
            self.asserts = ArraySlice(asserts)
            self.next = asserts.first
            viewModel.$viewState
                .sink { newViewState in
                    self.next?(newViewState)
                    self.next = self.asserts.dropFirst().first
                }
        }
    }

You may setup the mock like this:
let mockView = MockView(
    viewModel: viewModel,
    asserts: [
        { state in
            XCTAssertEqual(state.isLoading, false)
            XCTAssertEqual(state.didError, false)
        },
        { state in
            XCTAssertEqual(state.isLoading, true)
            ...
        },
        ...
    ])

You can also use XCT expectation in the assert functions.
Then, in your test you create the view model, your mock data service and the configured mockView.
  let mockDataService: DataServiceProtocol = MockDataService
  let viewModel = ViewModel(dataService: mockDataService)
  let mockView = MockView(
    viewModel: viewModel,
    asserts: [
        { state in
            XCTAssertEqual(state.isLoading, false)
            XCTAssertEqual(state.didError, false)
        },
        ...
        { state in
            XCTAssertEqual(state.isLoading, false)
            XCTAssertEqual(state.didError, false)
            expectFinished.fulfill()
        },
        ...
    ])

    viewModel.getSomeData()

    // wait for the expectations

Caution: I didn't compile or run the code.
You may also take a look at Entwine


text:
Q: Python Pocketsphinx: Keyword not being recognised from a .wav file I'm trying to detect the keyword temperature from a recording of me only saying the phase temperature (there are no other words present). Originally I used the keyword hello and it worked fine but whenever I try with any other word it does not. My current code is as follows:
import pocketsphinx as ps
import requests
import json
import sys, os

model_path = ps.get_model_path()
data_path = ps.get_data_path()

# Call to API
def get_temperature():
    headers = {
        'accept': 'application/json',
        'x-api-key': 'REMOVED'
    }

    response = requests.get(url=TEMPERATURE_URL, headers=headers)
    print("Response Code: ", response)

    temperature_data = response.json()
    print(temperature_data)
    temp = temperature_data[0]["value"]
    return temp

print("start")
while True:
    speech = ps.AudioFile(lm=False, kws='keyphrase.list', kws_threshold=1e-1)
    for phrase in speech:
        print("--------------------------------------------------------------")
        print(phrase.segments(detailed=True))
        print(phrase)
        if phrase.__eq__('temperature '):
            print("if equal")
            temperature = get_temperature()
            print("Temperature: ", temperature)

The contents of my keyphrase.list file is:
temperature /1e-1/

It currently starts and runs but doesn't detect anything.
Edit: Here is the audio file I am using

A: Your file has wrong format:
file client_audio.wav
client_audio.wav: RIFF (little-endian) data, WAVE audio, Microsoft PCM, 16 bit, 4 channels 20000 Hz

You have to convert it to proper format 16 bit mono 16khz before decoding, it wouldn't work otherwise.
In case threshold is small, you can try different threshold values like 1e-10, 1e-20, 1e-30, 1e-40 to balance between detections and false alarms.


text:
Q: What is the type of data returned in this code ? If this is the instance then how do we get value using this returned value? Code :
class A:
    class B:

        def __init__(self,value):
            self.value=value
    def get(self,value):
        return self.B(value)

a=A()
print(a.get(5))

Output:
<__main__.A.B object at 0x7f39df4dc5d0>

What is data type of data being returned.Is it the pointer address or the instance itself ? and how do we get the instance(I want the value) using this returned output ?
Any help is appriciated

A: When you call a.get(5) you're calling the constructor of the class B inside of a specific instance of A and returning a newly created instance of B.
We can verify this quite simply:
>>> type(a.get(5))
<class '__main__.A.B'>

However every time we call the above code, we are not getting the same instance of B:
>>> a.get(5) == a.get(5)
False

We are giving the same input to the constructor, but because they are two separately created instances, they do not equate to each other.
We can however fetch the value of the new instance simply by calling the attribute value:
>>> a.get(5).value
5

Here we can do another comparison, and we can see that it now returns True, because the values contained in the attributes are the same:
>>> a.get(5).value == a.get(5).value
True


text:
Q: How can I get to know that end of page has reached while creating a PDF file How can I come to know that the next line of my PDF will start from the next page? Is there anyway in the itext that it can handle this thing automatically. Currently I have a pdf which is being created perfectly, but when the value of a field is more than the page, then the page is being neglected and the execution starts from the next page but I have to utilize that current page as well.
The structure that I am using is as follows
I have used a PdfPCell', in which I have added 'Paragraph's... and "Paragraph"s are constructed by "Elements".
Problem:
Problem here is that the final paragraph is constructed with all of the elements(text) which is more than one page and itext neglects first page and starts execution from the next.
Suggestions Required:
Is there a way, that itext should know that the doc is multipage and it starts utilizing the first page?
Thanks in Advance.


text:
Q: Create an irregular 3D geometry from a cloud of points I have a large set of 3D points which are equally spaced in each axis. Many of these points are culled based on some criteria, and I'd like to create a 3D geometry to help visualize what's left.
I have looked at some algorithms to create a triangle mesh such as Delaunay Triangulations or a convex hull, but I'm worried that some excluded points might get caught inside the geometry. For example, a 2D slice might look like:
0 0 0 1 1 0 0
0 0 1 1 1 1 0
0 1 1 1 1 1 1
1 1 0 1 0 1 1
0 1 0 0 0 1 0

Where "1"s are included and "0"s are excluded. In this case I'm worried that the algorithm will accidentally include the "0"s on the bottom rows because they have "1"s bordering them on both sides. Note that the "0"s will always be on the edge, so we don't have to worry about holes in the geometry.
Afterwards, I will need to be able to rotate the geometry and find its intersection with a plane. I'm pretty sure I can handle the rotation and intersection part, but please keep that in mind.
I could brute force the problem by creating every triangle possible for all points on the surface, and then manually culling out any triangles that contain an excluded point. But the data set can be very large, so I hope there's a more elegant solution to this.

A: If you are only interested in closed geometries and each are on a plane do you need a mesh/triangualtion or simply a set of polygons?
Converting the 0,1 data into a binary image and running a contour algorithm on would be very simple see OPENCV

A: I think you're looking for the Point Cloud Library.


text:
Q: Writing a new column if entries match on different data frames Python I'm fairly new to Python and need some help with my data
Lets say my data 1 is
Year Population Country
1960            A
1998            A
1969 3          B
1999            B
..
2018 4          Z

And data 2 is
Year A     B     C     D
1960 2     4     3     3
1961 3     4     2     1
...
2018 3     4     1     3

Where [A, Z] are the countries
In data 1, the population is not filled for most countries and years, so I had to download the data for the population on a different set. Now I want to fill the entries in data 1 if the years and countries match on both data sets. I am struggling with this because the Columns in data 2 are each of the countries whereas in data 1, the countries are listed in only 1 column.
Any ideas? Thanks for the help!

A: You can use lookup:
df2 = df2.set_index('Year')

df1['Population'] = df1['Population'].fillna(df2.lookup(df1['Year'], df1['Country']) )


text:
Q: why parseInt here causes NumberFormatException inside the for loop at index i=4 I don't know the reason, why i=4 cause Numberformatexception, I can use try and catch to handle the Numberformatexception, but i actually don't know the reason for this mistake, and how can i fix it without using try,catch block ,can someone help, please.
public class Main {
public static void main(String[] args) {
   int i;
   int base = 0;
   for (base = 10; base >= 2; --base) {
         i = Integer.parseInt("40", base);
         System.out.println("40 to the Base " + base + " = " + i);
       }
  }
}

Output:
40 to the Base 10 = 40 // (10^0 * 0) + (10^1 * 4)
40 to the Base 9 = 36 // (9^0 * 0) + (9^1 * 4)
40 to the Base 8 = 32
40 to the Base 7 = 28
40 to the Base 6 = 24
40 to the Base 5 = 20
Exception in thread "main" java.lang.NumberFormatException: For input string: "40"
    at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
    at java.base/java.lang.Integer.parseInt(Integer.java:652)

A: 40 is not a valid base 2, 3 or 4 number.
Just compare to say octal (base 8) - counting is 0, 1, 2, 3, 4, 5, 6, 7, 10, 11 ... - 8 is not a valid octal digit. 4 is only valid for base 5 and above.
parseInt() takes a string and the base that string is in and returns the integer value. e.g. parseInt("10", 10) = 10 but parseInt("10", 8) = 8. Your problem is that "40" is not valid for base 2, 3 or 4. Likewise 50 is not valid for bases 2..5.


text:
Q: Request timeout with 200 and refresh header I have a simple php script running on Ubuntu 14, Apache 2.4.7 and PHP 5.5.9.  Every once and a while the request seems to stall, and after about 40 secs (normally < 100ms), it responds with an empty page, 200 OK and a Refresh header to the same URL.  I think it's happening more often, if there hasn't been a recent request to the script for a while.
Response:
HTTP/1.1 200 OK
Content-Type: text/html
Pragma: no-cache
Refresh: 1; URL=http://xxx.xxx.xxx.xxx/script.php?t=1407272586793
Connection: Close

Script content:
<?php
//# Provide server time
header('Access-Control-Allow-Origin: *');
echo '{"time":"'. gmdate("Y-m-d H:i:s") .' +0000"}';

There doesn't seem to be a record of the request in either the Apache access or error logs.
I'm not sure how to find at what point this is stalling.  Has anyone experienced this before, or have any suggestion on how I might debug this further?


text:
Q: do I need a linux server to deploy a mean stack application? This might seem like a dumb question but is it possible to deploy a MEAN stack application on a machine running windows ? or is it only possible with a linux machine
note: and by deploy, I mean use it in a production environment that people on an outside network would be able to access

A: You can definitely use the MEAN stack on windows. There are a couple of different ways:

*

*Just run the app using the command line from a windows server.

*Package the app as a windows service using node-windows. This will give you a real .exe file.

You'll have to go to the windows firewall settings and allow incoming traffic on whatever port you are exposing.
Here's a link to a post on the topic : http://jasonwatmore.com/post/2015/12/26/setup-the-mean-stack-on-windows


text:
Q: Correct handling of React Hooks for microphone audio I'm trying to write a React Hook to handle streaming audio to an AudioContext which is analysed with Meyda.
https://meyda.js.org/
I have managed to get the stream working and am able to pull out the data I want. However, I'm having trouble de-initialising the audio.
If someone can offer me some guidance on setting up this hook correctly I'd be most grateful.
I'm currently receiving the following error when I navigate away from a page using these hooks:

Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.

I have attempted to add a cleanup function to the end of my hook, but my attempts often ended with the audio cutting off immediately or any number of other weird bugs.
Microphone Audio Hook with Meyda Analyser
export const useMeydaAnalyser = () => {

    const [running, setRunning] = useState(false);
    const [features, setFeatures] = useState(null);
    const featuresRef = useRef(features);
    const audioContext = useRef(new AudioContext());

    const getMedia = async() => {
        try {
            return await navigator
                .mediaDevices
                .getUserMedia({audio: true, video: false});
        } catch(err) {
            console.log('Error:', err);
        }
    };

    useEffect(
        () => {
            const audio = audioContext.current;
            let unmounted = false;
            if(!running) {
                getMedia().then(stream => {
                    if (unmounted) return;
                    setRunning(true);
                    const source = audio.createMediaStreamSource(stream);
                    const analyser = Meyda.createMeydaAnalyzer({
                        audioContext: audio,
                        source: source,
                        bufferSize: 1024,
                        featureExtractors: [
                            'amplitudeSpectrum',
                            'mfcc',
                            'rms',
                        ],
                        callback: nextFeatures => {
                            if(!isEqual(featuresRef.current, nextFeatures)) {
                                setFeatures(nextFeatures);
                            }
                        },
                    });
                    analyser.start();
                });
            }
            return () => {
                unmounted = true;
            }
        },
        [running, audioContext],
    );

    useEffect(
        () => {
            featuresRef.current = features;
        },
        [features],
    );

    return features;
};

Audio View
import React, {useEffect} from 'react';
import { useMeydaAnalyser } from '../hooks/use-meyda-audio';

const AudioViewDemo = () => {
    const audioContext = new AudioContext();
    const features = useMeydaAnalyser(audioContext);

    useEffect(() => {
        // Todo: Handle Audio features
        console.log(features);
        // setAudioData(features);
    }, [features]);

    return (
        <div>
            RMS: {features && features.rms}
        </div>
    );
};

export default AudioViewDemo;

A: The error should be caused by not closing AudioContext. You need to close AudioContext in the cleanup functions.
Note that before using AudioContext, determine if the state is off, because getMedia is asynchronous, so if the component is unloaded soon after loading, AudioContext is turned off when it is used.

const getMedia = async () => {
  try {
    return await navigator.mediaDevices.getUserMedia({
      audio: true,
      video: false,
    })
  } catch (err) {
    console.log('Error:', err)
  }
}

const useMeydaAnalyser = () => {
  const [analyser, setAnalyser] = useState(null)
  const [running, setRunning] = useState(false)
  const [features, setFeatures] = useState(null)

  useEffect(() => {
    const audioContext = new AudioContext()

    let newAnalyser
    getMedia().then(stream => {
      if (audioContext.state === 'closed') {
        return
      }
      const source = audioContext.createMediaStreamSource(stream)
      newAnalyser = Meyda.createMeydaAnalyzer({
        audioContext: audioContext,
        source: source,
        bufferSize: 1024,
        featureExtractors: ['amplitudeSpectrum', 'mfcc', 'rms'],
        callback: features => {
          console.log(features)
          setFeatures(features)
        },
      })
      setAnalyser(newAnalyser)
    })
    return () => {
      if (newAnalyser) {
        newAnalyser.stop()
      }
      if (audioContext) {
        audioContext.close()
      }
    }
  }, [])

  useEffect(() => {
    if (analyser) {
      if (running) {
        analyser.start()
      } else {
        analyser.stop()
      }
    }
  }, [running, analyser])

  return [running, setRunning, features]
}


text:
Q: Use a $GET parameter from a URL, to create a new redirect URL (Wordpress) I am using a custom login page in Wordpress, and I installed a script in the functions.php that redirect to a custom "error login" page (adding parameters to the login URL), so it can display the errors in the same page instead of the native login page.
But in some cases, this login page contains some parameters already, when someone is redirected there after trying to access a private page.
For example :

*

*Regular case : They try to access : website.com/login. If there is an error when trying to login, my script redirect to website.com/login?login=empty, and they can try again.

*Problematic case : They try to access website.com/protected-page/private, they are automatically redirected to website.com/login?members=%2Fprotected-page%2Fprivate%2. If there is an error when trying to login, my script actualy redirect to website.com/login?login=empty (same as regular case), and what I'm trying to achieve, is to redirect to website.com/login?members=%2Fprotected-page%2Fprivate%2&login=empty, when an error is made.
Keeping this "?members" parameter in the URL allow the form to redirect to the previous page they were trying to access before, after a successful login. Otherwise with the regular case, they are redirected to the general dashboard.
The script that actually manage the redirect when error is this one :
add_action( 'authenticate', 'check_username_password', 1, 3);
function check_username_password( $login, $username, $password ) {
$referrer = $_SERVER['HTTP_REFERER'];

if( !empty( $referrer ) && !strstr( $referrer,'wp-login' ) && !strstr( $referrer,'wp-admin' ) ) {
if( $username == "" || $password == "" ){
    wp_redirect( get_permalink( 20 ) . "?login=empty" );
    exit;
}
}

So the important part here, that will create the error URL is :
wp_redirect( get_permalink( ID ) . "?login=empty" );

I can get my other UTL parameter with "$_GET["members"]", if I do an "echo $_GET["wlfrom"];" it displays successfully the parameter in the page. But even if it looks so simple, I don't manage to add this parameter to the URL. What I'v tried so far :
#1. wp_redirect( get_permalink( ID ) . "?members=" . $_GET["members"] . "?login=empty" );
#2. wp_redirect( get_permalink( ID ) . "?members=" . echo $_GET["members"] . "?login=empty" );
#3. $param = array('members');
wp_redirect( get_permalink( ID ) . "?members=" . $param . "?login=empty" );
//This one returns website.com/?members=array/?login=empty
#4.$param = $_SERVER["PHP_SELF"];
wp_redirect( $param . "?login=empty" );
// This one I cannot use because it displays the native login URL, not my permalink, that's why I need to use "get_permalink" for the first part of the URL

And various other solutions too. I'm a newbie, so I can't find of other solutions to create this new URL based on the previous one, I'm not sure either if using GET is the way to go also.
What should I fill up "wp_redirect" with in order to use the parameter from the current URL ?
Thank you !

A: put a hidden field in  your wordpress custom login form
<input type="hidden" name="members" value="<?php echo @$_REQUEST['members']; ?>">

and change these
wp_redirect( get_permalink( ID ) . "?login=empty" );

with
<?php
$queryarg='?login=empty';
if(isset($_REQUEST['members']) && $_REQUEST['members']!=''){
    $queryarg .='&members='$_REQUEST['members'];
}
wp_redirect( get_permalink( ID ) . $queryarg );

?>


text:
Q: Can a website find duplicate accounts if both accounts are connected to same 2FA app? Let's say I have a personal and work account on a website and use them strictly on separate devices and ISP. If I have connected 2FA for both accounts to a single 2FA app's account, say Authy for example, does the website have any chances of finding that both the accounts are connected to me, explicitly through the 2FA app?
P.S.: There is no particular website involved here, just wondering if that would be possible before I consider using a 2FA app.

A:
Let's say I have a personal and work account on a website and use them strictly on separate devices and ISP. If I have connected 2FA for both accounts to a single 2FA app's account, say Authy for example, does the website have any chances of finding that both the accounts are connected to me, explicitly through the 2FA app?

The website is completely unaware of the fact you are generating the 2FA with Authy or anything about the device that generated the 2FA code.

To make the scenario even more clear, imagine using single Authy account installed in my android, and that is connected to two Twitter accounts. Can Twitter find out both the twitter accounts are linked to one person, just because both gets 2FA codes from same Authy account from my android?

If you have two authenticators, tied to the same Authy account, then they are completely separate from one another.  The website is completely and totally unaware you are actually using Authy to handle the codes. You can even install Authy on as many devices as you want.

I believe you are mistaking the terms authenticators and accounts, when it comes to 2FA, which was the cause of confusion.

Nope; That absolutely is false. Any website that offers 2FA authentication is unable to detect how you generate the 2FA code use to authenticate your account. I wasn't actually confused.

Additionally, your opening statement assumed if I had two authenticators while I was pretty clear in my question that it involved a "single 2FA app's account". Which is why I went ahead with a clarifying comment.

Except you actually have two separate authenticators, they are just linked, to the same Authy account. I have 20 different Google Authenticators, synchronized across (Google Authenticators, Microsoft Authenticators, Last Pass, and Authy) on multiple devices.
My assumption is that each [website name here] account, would have their own Google Authenticator, linked to the same Authy account. You can replace "Google Authenticator" with any 2FA authenticator that the website (and Authy) in question supports.


text:
Q: Matching HD [something] pattern in awk This is the awk file called densel
#!/usr/local/bin/awk -f
BEGIN {
beg_ere = "^[[:space:]]*([#;!]+|@c|//)[[:space:]]+(HD) [()]([[:space:]]*).*$"
}

$0 ~ beg_ere { print "MATCH" }

I am not getting MATCH being printed when use a file with the following line
## HD [opcon]

A: $ cat tst.awk
BEGIN {
  #beg_ere = "^[[:space:]]*([#;!]+|@c|//)[[:space:]]+(HD) [()][[:space:]]*(.*)$"
   beg_ere = "^[[:space:]]*([#;!]+|@c|//)[[:space:]]+HD [[][^]]*]"
}

$0 ~ beg_ere { print "MATCH" }

$ awk -f tst.awk file
MATCH

I left your original regexp there so you can easily compare it to the working one. Your main problem was using a bracket expression [()] that includes ( and ) when you should have used literal [ and ] around a repeated bracket expression such as [^]]*. The [[:space:]]*(.*)$ would match any chars or no chars so it was doing nothing useful which is why I removed it. The ( and ) around HD were also doing nothing.


text:
Q: Power BI - DAX measure to reference a list of values. Calculate net turnover per broker - more elegant solution? Below is a simplified version of transaction data for stocks.
StockData =
DATATABLE (
    "STOCK", STRING,
    "Date", DATETIME,
    "Buyer", STRING,
    "Seller", STRING,
    "Turnover", INTEGER,
    {
         { "AAPL", "2019/04/07", "GSI", "BRC", 100 },
         { "AAPL", "2019/04/07", "CITI", "JPM", 500 },
         { "AAPL", "2019/04/07", "JPM", "GSI", 700 },
         { "AAPL", "2019/04/08", "GSI", "JPM", 300 },
         { "AAPL", "2019/04/08", "GSI", "CITI", 800 },
         { "AAPL", "2019/04/08", "JPM", "BRC", 400 },
         { "MSFT", "2019/04/07", "GSI", "GSI", 500 },
         { "MSFT", "2019/04/07", "JPM", "BRC", 700 },
         { "MSFT", "2019/04/07", "BRC", "GSI", 800 },
         { "MSFT", "2019/04/08", "GSI", "BRC", 500 },
         { "MSFT", "2019/04/08", "GSI", "JPM", 600 },
         { "MSFT", "2019/04/08", "CITI", "BRC", 500 }
    }
)

Goal is to calculate net turnover by broker per day.
I can achieve this by following DAX measure
Test BRC Net Turnover =
VAR TotalBuy = CALCULATE(SUM(StockData[Turnover]),StockData[Buyer] = "BRC")
VAR TotalSell = CALCULATE(SUM(StockData[Turnover]),StockData[Seller] = "BRC")
Return TotalBuy - TotalSell

However, to get net turnover for all  (Four) brokers in example data above I have to rewrite the measure four times with different critera, i.e., rather than using "BRC" I have to use "GSI" etc...
Real data set consists of 50 different broker codes so the solution with 50 different measures is not feasible.
How can I make this DAX function iterate over all Broker codes in my data set. Taking into consideration filters for the stock. I.e., if a typical broker code doesnt exist for MSFT but for AAPL the measure will take that into consideration.
I have tried the values function to return a list of all brokers, without any success.
Above is what I would like to achieve with one single measure.
Many thanks

A: Exemplary well-written question!

To do this, let's first create an independent calculated table to use for the different buyers and sellers.
Brokers = VALUES( StockData[Buyer] )

Now we can put Brokers[Buyer] in the Legend field and write a measure that reads that value.
Net Turnover =
VAR Broker = SELECTEDVALUE ( Brokers[Buyer] )
VAR TotalBuy = CALCULATE ( SUM ( StockData[Turnover] ), StockData[Buyer] = Broker )
VAR TotalSell = CALCULATE ( SUM ( StockData[Turnover] ), StockData[Seller] = Broker )
RETURN
    TotalBuy - TotalSell


text:
Q: Retrieve information Text/Word from HTML code using awk/sed awk/sed newbie here. I have a HTML file and from that file and I would like to retrieve a  text word.

abc NDK Version:  4.0

abc01 NDK Version:  4.0

abc045 NDK Version:  4.0

cdf NDK Version:  4.0

Manhattan NDK Version:  4.0

For eg. From the 1st line I would like to retrieve abc placed between: .txt>abc/a>
I have used the following command but as you can see that number of letters in the word keeps changing abc, abc01, abc045, cdf, Manhattan.
awk -F\/ '{print substr($4,0,3)}' list.html

So this command is getting the output for only the 3 letter word. However I want to extract the same information (abc01, abc045, cdf, Manhattan) from all the lines in the HTML code. Please help.

A: Using awk:
awk -F'[<>]' '{print $7}' urls
abc
abc01
abc045
cdf
Manhattan

A: You could try:
perl -nE '/(.*?)<\/a>/; say $1' file

Output:
abc
abc01
abc045
cdf
Manhattan

A: $ sed -n 's/.*txt>\([[:alnum:]]\+\)<.*/\1/p' list.html
abc
abc01
abc045
cdf
Manhattan

Or:
$ awk -F'(txt>|</a)' '{print $2}' list.html
abc
abc01
abc045
cdf
Manhattan

A: I use command sed or awk to extract it. Here, I save origin data into file /tmp/html.txt.
Both of them utilize regular expression and back reference
Via sed
flying@lempstacker:~$ sed -r -n 's@.*]*>(.*).*@\1@p' /tmp/html.txt
abc
abc01
abc045
cdf
Manhattan
flying@lempstacker:~$

Via awk
using function gensub
flying@lempstacker:~$ awk '{print gensub(/.*]*>(.*)<\/a>.*/,"\\1"," ",$0)}' /tmp/html.txt
abc
abc01
abc045
cdf
Manhattan
flying@lempstacker:~$

A: Using gnu grep
grep -Po "\K[^<]*" file


text:
Q: How to click dynamic button using Selenium and Python I don't know how to click this dynamic button, which has no HTML element I can use to click.
I tried to Click the button by using 'find_element_by_tag_name' but it doesn't work.
I post the Code of the button here:

A: If you know the beginning of the href you can use in the XPath starts-with:
dynamic_button_xpath = "//a[starts-with(@href, 'https://www.facebook.com/n/?')]"
driver.find_element_by_xpath(dynamic_button_xpath).click()

Hope this helps you!


text:
Q: python recode csv with condition I am a beginner in python.
I need to recode a CSV file:
unique_id,pid,Age
1,1,1
1,2,3
2,1,5
2,2,6
3,1,6
3,2,4
3,3,6
3,4,1
3,5,4
4,1,6
4,2,5

The condition is: for each [unique_id], if there is any [Age]==6, then put a value 1 in the corresponding rows of with a [pid]=1, others should be 0.
the output csv will look like this:
unique_id,pid,Age,recode
1,1,1,0
1,2,3,0
2,1,5,1
2,2,6,0
3,1,6,1
3,2,4,0
3,3,6,0
3,4,1,0
3,5,4,0
4,1,6,1
4,2,5,0

I was using numpy: like follwoing:
import numpy
input_file1 = "data.csv"
input_folder = 'G:/My Drive/'
Her_HH =pd.read_csv(input_folder + input_file1)
Her_HH['recode'] = numpy.select([Her_PP['Age']==6,Her_PP['Age']<6], [1,0], default=Her_HH['recode'])

Her_HH.to_csv('recode_elderly.csv', index=False)

but it does not put value 1 in where [pid] is 1. Any help will be appreciated.

A: You can use DataFrame.assign for new column with GroupBy.transform for test if at least one match by GroupBy.any, chain mask for test 1 with & for bitwise AND and last cast output to integers
#sorting if necessary
df = df.sort_values('unique_id')

m1 = df.assign(test=df['Age'] == 6).groupby('unique_id')['test'].transform('any')

Another idea for get groups with 6 is filter them with unique_id and Series.isin:
m1 = df['unique_id'].isin(df.loc[df['Age'] == 6, 'unique_id'])

m2 = df['pid'] == 1

df['recode'] = (m1 & m2).astype(int)
print (df)
    unique_id  pid  Age  recode
0           1    1    1       0
1           1    2    3       0
2           2    1    5       1
3           2    2    6       0
4           3    1    6       1
5           3    2    4       0
6           3    3    6       0
7           3    4    1       0
8           3    5    4       0
9           4    1    6       1
10          4    2    5       0

EDIT:
For check groups with no match 6 in Age column is possible filter by inverted mask by ~ and if want only all unique rows by unique_id values add DataFrame.drop_duplicates:
print (df[~m1])
   unique_id  pid  Age
0          1    1    1
1          1    2    3

df1 = df[~m1].drop_duplicates('unique_id')
print (df1)
   unique_id  pid  Age
0          1    1    1

A: This a bit clumsy, since I know numpy a lot better than pandas.
Load your csv sample into a dataframe:
In [205]: df = pd.read_csv('stack59885878.csv')
In [206]: df
Out[206]:
    unique_id  pid  Age
0           1    1    1
1           1    2    3
2           2    1    5
3           2    2    6
4           3    1    6
5           3    2    4
6           3    3    6
7           3    4    1
8           3    5    4
9           4    1    6
10          4    2    5

Generate a groupby object based on the unique_id column:
In [207]: gps = df.groupby('unique_id')

In [209]: gps.groups
Out[209]:
{1: Int64Index([0, 1], dtype='int64'),
 2: Int64Index([2, 3], dtype='int64'),
 3: Int64Index([4, 5, 6, 7, 8], dtype='int64'),
 4: Int64Index([9, 10], dtype='int64')}

I've seen pandas ways for iterating on groups, but here's a list comprehension.  The iteration produce a tuple, with the id and a dataframe.  We want to test each group dataframe for 'Age' and 'pid' values:
In [211]: recode_values = [(gp['Age']==6).any() & (gp['pid']==1) for x, gp in gps]
In [212]: recode_values
Out[212]:
[0    False
 1    False
 Name: pid, dtype: bool, 2     True
 3    False
 Name: pid, dtype: bool, 4     True
 5    False
 6    False
 7    False
 8    False
 Name: pid, dtype: bool, 9      True
 10    False
 Name: pid, dtype: bool]

The result is a list of Series, with a True where pid is 1 and there's a 'Age' 6 in the group.
Joining these Series with numpy.hstack produces a boolean array, which we can convert to an integer array:
In [214]: np.hstack(recode_values)
Out[214]:
array([False, False,  True, False,  True, False, False, False, False,
        True, False])
In [215]: df['recode']=_.astype(int)            # assign that to a new column
In [216]: df
Out[216]:
    unique_id  pid  Age  recode
0           1    1    1       0
1           1    2    3       0
2           2    1    5       1
3           2    2    6       0
4           3    1    6       1
5           3    2    4       0
6           3    3    6       0
7           3    4    1       0
8           3    5    4       0
9           4    1    6       1
10          4    2    5       0

Again, I think there's an idiomatic pandas way of joining those series.  But for now this works.
===
OK, the groupby object has an apply:
In [223]: def foo(gp):
     ...:     return (gp['Age']==6).any() & (gp['pid']==1).astype(int)
     ...:
In [224]: gps.apply(foo)
Out[224]:
unique_id
1          0     0
           1     0
2          2     1
           3     0
3          4     1
           5     0
           6     0
           7     0
           8     0
4          9     1
           10    0
Name: pid, dtype: int64

And remove the multi-indexing with:
In [242]: gps.apply(foo).reset_index(0, True)
Out[242]:
0     0
1     0
2     1
3     0
4     1
5     0
6     0
7     0
8     0
9     1
10    0
Name: pid, dtype: int64
In [243]: df['recode']=_     # and assign to recode

Lots of experimenting and learning here.


text:
Q: Google-Line-Chart on hover tool-tip not showing value I have used Google Line Charts in Angular2 in typescript version, When I draw the line chart, Chart is looking good but when I hover over the line chart to see what is exact value at that point, I can't see any value in tool-tip and I don't understand what can be the problem if the value has been drawn in chart but aren't showing up in tool-tip.I have attached a screenshot for the reference. Sample data array which gets convert into datatable is as follow:
Gdata = [
["TimeStamp", "Temparature"], [Sat May 13 2017 10:45:00 GMT+0530 (India Standard Time), 23.81], [Sat May 13 2017 10:50:00 GMT+0530 (India Standard Time), 23.83], [Sat May 13 2017 10:55:00 GMT+0530 (India Standard Time), 23.90], [Sat May 13 2017 11:00:00 GMT+0530 (India Standard Time), 23.85], [Sat May 13 2017 11:05:00 GMT+0530 (India Standard Time), 23.82]
];

Kindly help. Thanks in advance.

A: After going through the many options provided by google charts, I found an option called tooltip: { isHtml: true } which worked for me and now tooltip is showing within the chart area only.


text:
Q: Magento : Product Import to 1.9.3 We have magento website which is  in version2. We are developing a website which is in  version to 1.9.3. Can we export product data from admin panel of magento 2 and directly export to 1.9.3 site?

A: In my opinion, you can not export products from Magento 2 and directly import into Magento 1.x.
Reason: Magento 2 puts all custom attribute values under 1 column (additional_attributes) and saves attribute values in following format:
attribue_code1=value1,attribue_code2=value2,attribue_code3=value3..

While in Magento 1.x, each attribute is placed in individual column in csv file.
So you will need to add some efforts to convert Magento 2.x compatible csv file to Magento 1.x compatible format.
Please let me know if you have any other query.


text:
Q: Trying to Load a Contact in Metadata through Python and ArcMap Attempting to create a metadata contact and then use that contact to load in to the Resource Citation Contact and the Metadata Citation Contact metadata fields. The metadata library has an element in the form of:
"citation_contact": {
        "path": "dataIdInfo/idCitation/citRespParty",
        "type": "parent_item",
        "elements": contact_elements},

But I can not seem to properly connect this element "citation_contact" to the new contact that I defined earlier in the same script. In that script, I define a new contact as:
contact = metadata.point_of_contact
contact_name = metadata.point_of_contact.contact_name
metadata.point_of_contact.contact_name = "Bob Smith"

How do I load "Bob Smith" into either Citation Contact field?
Here is the element in the library for the contact:
"role": {
        "path": "role/RoleCd",
        "type": "attribute",
        "key": "value",
        "values": [("resource provider", "001"),
                   ("custodian", "002"),
                   ("owner", "003"),
                   ("user", "004"),
                   ("distributer", "005"),
                   ("originator", "006"),
                   ("point of contact", "007"),
                   ("principal investigator", "008"),
                   ("processor", "009"),
                   ("publisher", "010"),
                   ("author", "011")]},

    "contact_name": {
        "path": "rpIndName",
        "type": "string"},


text:
Q: Running multiple NodeJS projects at once with a batch file I have a file structure like this:
bots -|
      |- test1 -|
                |- index.js
                |- activate.bat
                |- token.txt

      |- test2 -|
                |- index.js
                |- actiate.js
                |- token.txt

      |- run_all.bat

index.js are files to be run be NodeJS with the node command.  Both index.js files require a key that is stored in token.txt file.  The index.js file reads the text file
activate.bat is simply this:
@echo off
node index.js

However I want to run both at once, and by only starting one .bat file, this is where run_all.bat comes in.
I have tried to run each file like I ran in activate.bat so:
@echo off

echo Starting all bots...

start /b node test1\index.js
start /b node test2\index.js

However I get an error:
PS C:\Users\Simon\Desktop\bot> ./run_all.bat
Starting all bots...
PS C:\Users\Simon\Desktop\bot> test1 running
test2 running
(node:10176) UnhandledPromiseRejectionWarning: Error: An invalid token was provided.
    at Promise (C:\Users\Simon\node_modules\discord.js\src\client\rest\RESTMethods.js:34:54)
    at new Promise (<anonymous>)
    at RESTMethods.login (C:\Users\Simon\node_modules\discord.js\src\client\rest\RESTMethods.js:33:12)
    at Client.login (C:\Users\Simon\node_modules\discord.js\src\client\Client.js:279:30)
    at ReadFileContext.callback (C:\Users\Simon\Desktop\bot\test1\index1.1.js:88:12)
    at FSReqWrap.readFileAfterOpen [as oncomplete] (fs.js:235:13)
(node:4836) UnhandledPromiseRejectionWarning: Error: An invalid token was provided.
    at Promise (C:\Users\Simon\node_modules\discord.js\src\client\rest\RESTMethods.js:34:54)
    at new Promise (<anonymous>)
    at RESTMethods.login (C:\Users\Simon\node_modules\discord.js\src\client\rest\RESTMethods.js:33:12)
    at Client.login (C:\Users\Simon\node_modules\discord.js\src\client\Client.js:279:30)
    at ReadFileContext.callback (C:\Users\Simon\Desktop\bot\test2\index.js:65:12)
    at FSReqWrap.readFileAfterOpen [as oncomplete] (fs.js:235:13)
(node:10176) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 3)
(node:4836) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 3)
(node:10176) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
(node:4836) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

When run each activate.bat alone I do not get this error,  what is going wrong?  Are my batch commands somehow mixing up the different token.txt files

A: The main problem can be solved by using option /D of command START to define the current directory for the started processes. All index.js expect obviously that the file token.txt is in current directory and that the current directory is the directory containing both files. Windows sets the current directory by default to directory of the batch file on double clicking for example on batch file activate.bat.
@echo off
echo Starting all bots...
start "" /B /D"%~dp0test1" node index.js
start "" /B /D"%~dp0test2" node index.js

The first double quoted argument string is interpreted by command START as optional title for the console window. node is started here without opening a console window. It is good practice to define always a title on using command START. In this case an empty window title specified with "" is a good choice as also on starting a Windows GUI application because no console window is opened at all.
The subdirectories test1 and test2 are always in directory containing the batch file run_all.bat. For that reason %~dp0 is used to reference the drive and path of argument 0 which is the currently executed batch file. This makes the batch file run_all.bat itself independent on what is the current directory on executing run_all.bat.
/ (forward slash) is the directory separator on Linux/Mac. But \ (backslash) should be used on Windows in file/folder paths because of / is used for options on Windows, except for applications ported from Unix to Windows without adaptation to Windows syntax. The Windows kernel functions for file/folder accesses replace all / by \ to automatically correct paths before accessing Windows file systems for compatibility reasons, but it is definitely better to write file/folder paths in Windows scripts with current directory separator and do not depend on this automatic correction of Windows kernel.
%~dp0 expands to a path string always ending with a backslash. So no additional backslash should be used on concatenating this dynamic string with a fixed file/folder name/path. Otherwise there would be two \ in series on execution. The Windows kernel functions for file/folder accesses automatically correct also \\ in a file/folder referencing string by \. But it is again better to avoid this mistake.
See the Microsoft documentation page Naming Files, Paths, and Namespaces for more details.
So command START sets now the directory containing index.js and token.txt before running node with the argument index.js.
A better solution would be using this batch file:
@echo off
echo Starting all bots...
for /F "delims=" %%I in ('dir "%~dp0index.js" /A-D-H /B /S 2^>nul') do start "" /B /D"%%~dpI" node index.js

The command FOR runs in a separate command process with cmd.exe /C (more precisely %CompSpec% /C in background the command line:
dir "C:\Users\Simon\Desktop\bot\index.js" /A-D-H /B /S 2>nul

DIR outputs to handle STDOUT of started command process

*

*in bare format because of option /B

*the file names with extension and with full path because of option /S

*of all only non-hidden files because of option /A-D-H (attribute not directory and not hidden)

*with file name index.js found in specified directory or any subdirectory because of option /S.

The error message output by DIR to handle STDERR on not finding anything matching these criteria is suppressed by redirecting to device NUL.
Read the Microsoft documentation about Using Command Redirection Operators for an explanation of 2>nul. The redirection operator > must be escaped with caret character ^ on FOR command line to be interpreted as literal character when Windows command interpreter processes this command line before executing command FOR which executes the embedded dir command line with using a separate command process started in background.
FOR with option /F captures the output to handle STDOUT of started background command process and processes this output after started cmd.exe terminated. Empty lines are always ignored by FOR which do not occur here. Lines starting with ; are by default also ignored by FOR because of the semicolon is the default end of line option. It is impossible that a full qualified file name as output by DIR starts with a semicolon and therefore default eol=; can be kept in this case. FOR would split up by default every line into substrings using normal space and horizontal tab as string delimiters and would assign just first space/tab delimited string to specified loop variable. This behavior is not wanted here because of file path could contain also one or more spaces. Therefore line splitting behavior is disabled with delims= which defines an empty list of delimiters resulting in always getting entire full qualified file name assigned to loop variable.
FOR executes for every file name output by DIR the command START as explained above. It does not matter for START if the directory path specified with /D"..." is without or with a backslash at end.
The main advantage of this second batch file solution in comparison to first one can be seen easily: run_all.bat must not be edited on removing or adding additional directories with index.js.
But be aware that running too many node instances parallel can be counterproductive depending on what code in index.js does. So it could be useful to extend the batch file to start not more than x node and halt batch file execution until one node instance terminated itself before starting next instance on reaching useful maximum number of parallel running node instances.
For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.

*

*dir /?

*echo /?

*for /?

*start /?
PS: I suggest to specify node at least with file extension and best with full path to make the batch file independent on the environment variables PATHEXT and PATH.


text:
Q: Trying to tilt multiple divs to different, random angles I'm trying to achieve the opposite of what is described here.
I have a series of divs in a wordpress page, which I would like to appear on the page as each randomly tilted to a different slight degree.
They should also be straightened up as the user hovers on them.
Here's what I have:
    (function($) {
    $( document ).ready(function() {
        var a = Math.random() * 10 - 5;
        $('.format-aside').each(function( index ) {
            $(this).css('transform', 'rotate(' + a + 'deg)');})
        });
})(jQuery);

at first, I skipped the .each part, but this resulted in all the divs being tilted the same way. However even with the .each they still end up tilted the same way.
As to the hover effect, I have set it in the CSS page:
.format-aside:hover{-ms-transform: rotate(0deg);
-webkit-transform: rotate(0deg);
transform: rotate(0deg);}

and it worked when all of this was done in CSS (but of course then all divs tilted the same way). Now it doesn't work anymore so I figure I should add the hover effect in jQuery?

A: The reason they're all tilted the same amount is because you calculate the degree before iterating over the elements. Instead, you should calculate one angle per element:
(function($) {
$( document ).ready(function() {
    $('.format-aside').each(function( index ) {
        // rotation degree between -5 and 5
        var a = Math.random() * 10 - 5;
        $(this).css('transform', 'rotate(' + a + 'deg)');})
    });
})(jQuery);

As for the hover effect try adding the !important option to them:
.format-aside:hover {
    -ms-transform: rotate(0deg) !important;
    -webkit-transform: rotate(0deg) !important;
    transform: rotate(0deg) !important;
}

The reason for your CSS not working is because jQuery applies the rules on the elements as in-line styles. These are higher priority than any CSS selectors. Using the !important rule you can override that.


text:
Q: Why does order by primary index make this query slow? This query is getting the newest videos uploaded by the user's subscriptions, its running very slow so I rewrote it to use joins but It didn't make a difference and after tinkering with it I found out that removing ORDER BY would make it run fast (however it defeats the purpose of the query).
Query:
SELECT vid. *
FROM video AS vid
INNER JOIN subscriptions AS sub ON vid.uploader = sub.subscription_id
WHERE sub.subscriber_id = '1'
AND vid.privacy = 0 AND vid.blocked <> 1 AND vid.converted = 1
ORDER BY vid.id DESC
LIMIT 8

Running explain, it would show "Using temporary; Using filesort" in subscriptions table and its slow (0.0900 seconds).
Without ORDER BY vid.id DESC it doesn't show "Using temporary; Using filesort" so its fast (0.0004 seconds) but I don't understand how the other table can affect it like this.
All the fields are indexed (privacy blocked and converted fields don't affect performance by more than 10%).
I would paste the full explain information but I can't seem to make it fit nice in the layout of this site.

A: You're limiting the query to 8 results. When you run it without an order by, it can grab the first 8 rows it comes across that pass the condition, and then hand them back. Boom, it's done.
When you use the order by, you're not asking for any 8 records. You're asking for the first 8 records in terms of vid.id. So it has to figure out which those are, and the only way to do that is to look through the entire table and compare vid.id values. That's a lot more work.
Is there actually an index on the column? If so, it may be out of date. You could try rebuilding it.

A: Fixed it by suggesting that mysql use the primary index with USE_INDEX(PRIMARY)
SELECT vid. *
FROM video AS vid USE INDEX ( PRIMARY )
INNER JOIN subscriptions AS sub ON vid.uploader = sub.subscription_id
WHERE sub.subscriber_id = '1'
AND vid.privacy =0
AND vid.blocked <>1
AND vid.converted =1
ORDER BY vid.id DESC
LIMIT 8


text:
Q: reduction is very slow in OpenMP I am doing some optimization on my code. First i proceeded to a parallel programming with OpenMP Then i used the optimization flags provided by GNU GCC compiler. Also i included an SSE instruction to compute inverse square root. But i realized finally that the problem is that the last operation, when each thread writes the result into the reduction variable, takes ~ 80% of time. Here the parallel loop :
time(&t5);
# pragma omp parallel for shared(NTOT) private(dx,dy,d,H,V,E,F,G,K) reduction(+:dU)
for(j = 1; j <= NTOT; j++){
  if(!(j-i)) continue;
  dx = (X[2*j-2]-X[2*i-2])*a;
  dy = (X[2*j-1]-X[2*i-1])*a;
  d = rsqrtSSE(dx*dx+dy*dy);
  H = D*d*d*d;
  V = dS[0]*spin[2*j-2]+dS[1]*spin[2*j-1];
  E = dS[0]*dx+dS[1]*dy;
  F = spin[2*j-2]*dx+spin[2*j-1]*dy;
  G = -3*d*d*E*F;
  K = H*(V+G);
  dU += K;
}
time(&t6);
t_loop = difftime(t6, t5);

where rsqrtSSE() is a function based on __mm_rsqrt_ps(__m128 X) predefined function in xmmintrin.h .
If there is a solution to overcome this problem? or this is due to bandwidth limitation?
i compile with gcc -o prog prog.c -lm -fopenmp -O3 - ffast-math -march=native
Here some infos about my computer :
Architecture:          x86_64
CPU op-mode(s):        32-bit, 64-bit
Byte Order:            Little Endian
CPU(s):                4
On-line CPU(s) list:   0-3
Thread(s) per core:    2
Core(s) per socket:    2
Socket(s):             1
NUMA node(s):          1
Vendor ID:             GenuineIntel
CPU family:            6
Model:                 69
Model name:            Intel(R) Core(TM) i5-4200U CPU @ 1.60GHz
Stepping:              1
CPU MHz:               849.382
CPU max MHz:           2600.0000
CPU min MHz:           800.0000
BogoMIPS:              4589.17
Virtualization:        VT-x
L1d cache:             32K
L1i cache:             32K
L2 cache:              256K
L3 cache:              3072K
NUMA node0 CPU(s):     0-3
and with turboboost :
   CPU Avg_MHz   %Busy Bzy_MHz TSC_MHz
       -    2294   99.97    2300    2295
       0    2295  100.00    2300    2295
       1    2295  100.00    2300    2295
       2    2292   99.87    2300    2295
       3    2295  100.00    2300    2295

A: Your measurement is flawed.
The first approach, removing the line alltogether, allows the compiler to optimize away most of the computations, simply because the result is unused.
The second approach, if i understand it correctly, was to place timing instructins inside the loop itself, e.g. before/after dU += K. Unfortunately this, also has no hope of producing meaingful results. Any library timing call is orders of magintune slower than this operation. So you basically measure the time it takes to get the time. You can try that by repeating multiple timing calls and compare the difference.
From what I have seen, I suspect that the OpenMP implementations simply keep dU as thread-private variable and only after the loop is completed perform the reductions atomic/locked operations.
A better approach to determine the performance of individual lines is to use sampling. Take a look at the perf tool for linux, it can be very helpful. The results still may not always be perfectly reliable because there can be bias. Due to compiler optimizations (e.g. unrolling), and hardware optimizations (e.g. pipelining) multiple lines of code can be in the state of execution at the same time. It becomes a very difficult question to say how much time a line of code is taking.
One approach to see if you have a problem, is to try and figure out the theoretical hardware performance. For __mm_rsqrt_ps that seems difficult. You can also take a look at hardware performance counters to see if you have a lot of cache misses etc. perf can also help you with that.


text:
Q: Can I use XAMPP's apache tomcat to execute java Dynamic Web Project? I am using eclipse and I have a Dynamic Web Project .
To execute it I need apache tomcat 7.0.
But I have already installed XAMPP server that include both apache web server & apache tomcat server.
How can I mount my java web app to XAMPP's apache tomcat server?

A: There are 2 possibilities
Option 1

*

*You have two tomcat server running

*one inside eclipse and the XAMPP Tomcat

*you have to give the XAMPP Tomcat another port number
here we give it a new port (8090) and redirectPort (8444).

..XAMPP\tomcat\conf\server.xml

original
<Connector port="8080" protocol="HTTP/1.1"
                   connectionTimeout="20000"
                   redirectPort="8443" />

changed to
<Connector port="8090" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8444" />

disadvantage you have to deploy the Web application 2 times

*

*1 Eclipse deploy it to the eclipse Tomcat server

*2 Manually deploy it to your XAMPP Tomcat server.

*3 Manually start your XAMPP Tomcat server with
..XAMPP\catalina_start.bat

*4 Manually stop  your XAMPP Tomcat server with
..XAMPP\catalina_stop.bat
here Tomcat runs on 8090

Option 2 Change Eclipse settings.

*

*Windows -> Show View -> Servers

*In the servers view, right click and add new.

*It will show a pop up containing many server vendors.

*Under Apache select Tomcat v7.0 (Depending upon your downloaded server version).

*In the run time configuration point it to the XAMPP Tomcat folder (....\XAMPP\tomcat)

Advantage

*

*You need in XAMPP settings to change nothing.

*Eclipse deploy it for you.

Disadvantage

*

*on shutdown Eclipse, it will also stop XAMPP Tomcat server

*so you have to start and stop it manually with

*..XAMPP\catalina_start.bat

A: just start tomcat from ur Xampp Cpanel and put URL in browser localhost:8080, instead localhost, see [below snap and below snap
it will run http://localhost Apache , http://localhost:8080 tomcat


text:
Q: Transform array to sub-values using jolt I'm struggling to trans my input response to a specific output using jolt, below is my example
The input that describe my message
{
  "firstAttribute": true,
  "secondAttribute": "12",
  "data": {
    "propertyKey1": "1",
    "propertyKey2": [
      "a"
    ],
    "propertyKey3": "2",
    "propertyKey4": "3",
    "propertyKey_test": [
      "option1",
      "option2",
      "option3"
    ],
    "propertyKey5": "4",
    "propertyKey6": "87.0"
  },
  "Keytest1": "value1",
  "KeyTest2": "value2"
}

The used jolt Spec
[
  {
    "operation": "shift",
    "spec": {
      "data": {
        "propertyKey2": {
          "0": "propertyKey2"
        },
        "*": {
          "@": "data.&"
        }
      },
      "*": {
        "@": "&"
      }
    }
  }
]

My actual output after a jolt transfomration

{
  "firstAttribute" : true,
  "secondAttribute" : "12",
  "data" : {
    "propertyKey1" : "1",
    "propertyKey3" : "2",
    "propertyKey4" : "3",
    "propertyKey_test" : [ "option1", "option2", "option3" ],
    "propertyKey5" : "4",
    "propertyKey6" : "87.0"
  },
  "propertyKey2" : "a",
  "Keytest1" : "value1",
  "KeyTest2" : "value2"
}

The desired output is to convert every array fields to separated fields such as  propertyKey_test as below

{
  "firstAttribute" : true,
  "secondAttribute" : "12",
  "data" : {
    "propertyKey1" : "1",
    "propertyKey3" : "2",
    "propertyKey4" : "3",
    "propertyKey_test": "option1",
    "propertyKey5" : "4",
    "propertyKey6" : "87.0"
  },
  "propertyKey2" : "a",
  "Keytest1" : "value1",
  "KeyTest2" : "value2"
}

Any help would be appreciated. Thanks in advance
PS: we can receive a dynamic array fields (ex: today we have propertyKey_test:["option1","option2","option3"] tomorrow we could receive another array field for example new_field:["a","b","c"].
My goal is to check everytime if the field is an array and take just the first element as described above

A: The current desired output is not a valid JSON value, since there may not exist more than one attribute with identical key within a common object. But, if you need to differentiate the components of the "propertyKey_test" array, then using the indexes of the array as below might be preferred such as
[
  {
    "operation": "shift",
    "spec": {
      "data": {
        "propertyKey2": {
          "0": "&1"
        },
        "*": {
          "@": "&2.&"
        },
        "propertyKey_*": {
          "*": {
            "@": "&3.&2&1"
          }
        }
      },
      "*": {
        "@": "&"
      }
    }
  }
]

in order to get
{
  "firstAttribute" : true,
  "secondAttribute" : "12",
  "data" : {
    "propertyKey1" : "1",
    "propertyKey3" : "2",
    "propertyKey4" : "3",
    "propertyKey_test0" : "option1",
    "propertyKey_test1" : "option2",
    "propertyKey_test2" : "option3",
    "propertyKey5" : "4",
    "propertyKey6" : "87.0"
  },
  "propertyKey2" : "a",
  "Keytest1" : "value1",
  "KeyTest2" : "value2"
}

as output.


text:
Q: im trying to display some code into a text area, i got it to work i just dont know how to get it to display my values JAVASCRIPT // i have this right now, im trying to figure out how i could print the values into a text area
onEvent("factorsof2", "click", function( ) {
```
var num = calculate();
function calculate(num) {
   ```
   var half = Math.floor(num / 2),
    ```
  str = '1',
    ```
  i, j;

num % 2 === 0 ? (i = 2, j = 1) : (i = 3, j = 2);
```
for (i; i <= half; i += j) {

        num % i === 0 ? str += ',' + i : false;
    }

str += ',' + num;

}
  setText("text_area3", "Your factors are: " + calculate(num));

});


text:
Q: vxworks compile success but "ld" command fail I use IDE WindRiver Workbench to compile DKM project! It compiles successfully. But "ld" command fails complaining like:
Warning: module 0x1e2f0b8 holds reference to undefined symbol __GOTT_BASE__.
Warning: module 0x1e2f0b8 holds reference to undefined symbol __GOTT_INDEX__.
Warning: module 0x1e2f0b8 holds reference to undefined symbol _Assert.
Warning: module 0x1e2f0b8 holds reference to undefined symbol _Stoul.
Warning: module 0x1e2f0b8 holds reference to undefined symbol _Getpctype.
Warning: module 0x1e2f0b8 holds reference to undefined symbol _Stderr.
Warning: module 0x1e2f0b8 holds reference to undefined symbol _Getptoupper.
Warning: module 0x1e2f0b8 holds reference to undefined symbol _Getptolower.
Warning: module 0x1e2f0b8 holds reference to undefined symbol _Stod.
Warning: module 0x1e2f0b8 holds reference to undefined symbol _Flt.
Warning: module 0x1e2f0b8 holds reference to undefined symbol _Stdout.
ld(): error loading file (errno = 0xe0005).

A: You get these errors because the mentioned symbols cannot be resolved in the system symbol table.
From the VxWorks Kernel Programmer's Guide 6.8, ch. 16.3.7 (very useful chapter for loading issues)

The system symbol table is used to store the names and addresses of functions and variables already installed in the system. This has the side effect that once symbols are installed in the
  system symbol table, they are available for future linking by any module that is
  loaded. Moreover, when attempting to resolve undefined symbols in a module,
  the loader uses all global symbols compiled into the target image, as well as all
  global symbols of previously loaded modules.

Tips:

*

*Check that the order in which you are loading modules is correct. Loading will fail on that DKM if you are loading the symbols afterwards in another DKM.

[...] dependencies between modules must be taken into account when
  modules are loaded to ensure that references can be resolved for each new module,
  using either code compiled into the VxWorks image or modules that have already
  been loaded into the system.
  Failure to do so results in incompletely resolved code [...]

*

*"lkup" command is useful to find what symbols have been previously loaded


text:
Q: Animation on form React I am stuck, I am adding amination on form on every radio button click, next question should Slide Up , but this is not happening sliding is happening only on first question.
<CSSTransition classNames="fade"
    in={expanded}
    timeout={300}

    unmountOnExit
  >
        <Card variant="outlined" sx={{ bgcolor: "#bea"}} elevation={0}>
            <CardContent>

            <form onSubmit= {handleSubmit}>
                    <CardActions>
                  <Button type="submit" color="warning" variant="outlined" className={classes.button} onClick={previousQuestion}>
                      Previous</Button>
                  </CardActions>

                  <FormControl component='fieldset' className={classes.formControl}
    data-hidden={questions[currentQuestion].number !==
      currentQuestion[questions[currentQuestion].number]}>
    <FormLabel component='legend'>
      {questions[currentQuestion].question}
    </FormLabel>
    <FormLabel component='legend'>
      {questions[currentQuestion].description}
    </FormLabel>
    <RadioGroup
      aria-label='quiz'
      name='quiz'
      value={questions[currentQuestion].value}
      onChange={(e)=> handleRadioChange(questions[currentQuestion].number, e)}
      sx={{
        color: pink[800],
        '&.Mui-checked': {
          color: pink[600],
        },
      }}>
      {options.map((option) => (
        <FormControlLabel
          key={option.score}
          value={option.score}
          control={<Radio  sx={{
            color: pink[800],
            '&.Mui-checked': {
              color: pink[600],
            },
          }}/>}
          label={option.label}
        />
      ))}
    </RadioGroup>
  </FormControl>

                    <CardActions>
                    <Button type="submit" variant="outlined" color="primary" className={classes.button} onClick={handleSubmit}>
                    Submit
                </Button>
              </CardActions>

                </form>

                </CardContent>
                </Card>
                </CSSTransition>

The css is
.fade-enter {
    opacity: 0;
  }

  .fade-enter.fade-enter-active {
    opacity: 1;
    transition: opacity 0.5s ease-in-out 0.3s;
  }

  .fade-leave {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    opacity: 1;
  }

  .fade-leave.fade-leave-active {
    opacity: 0;
    transition: opacity 0.5s ease-in-out;
  }

The animation is not working. Please help in finding out. I want every question to fade Out on radio button click. But this occurs only on the first but after that there is no transition.


text:
Q: Word describing "information authored and presented as if kept current" Not expecting an exact match but would like to see what my best options are.
There's a class of written artifacts that is understood to be "frozen" at a point in time, based on the way it is authored and presented. For example, a newspaper is understood to be representative of information true at approximately the time of publish, based on the fact that it is marked with a date and it is printed on a medium that cannot be later modified. Many digital documents can also belong to this class if they indicate they are a "memo" or "status update", which are understood to be unchanging once they are authored, even though technically they could continue to be edited since they are digital files. This type of artifact can be described as "historical", as they represent a point in history, even if that point in history was just yesterday.
There's another class of written artifacts that sets the expectation that it is current, again based on the way it is authored and presented. For example, the online documentation about the Stack Exchange platform is expected to be reflective of the actual Stack Exchange service at the time I access the documentation. This class of artifacts is often digital but doesn't necessarily have to be. For example, the announcement sign outside a fast food restaurant is expected to be representative of the sales happening at that restaurant at the time I read the sign. Importantly, this information isn't necessarily correct: Maybe the Stack Exchange writers or the restaurant owners forgot to make needed updates to what's written. I am tempted to call this class of written artifact "current", though as just noted they might in fact not be actually currently true. What's essential is that they imply they are current, regardless of whether that ends up being the case.
Some other words I've been weighing include authoritative, maintained, upkept, contemporary, and present. I'm thinking an adjective would be ideal, but if there's a noun that encompasses this, that would be great too. Also fine to suggest new words derived from existing words with affixes.

A: Interesting question.
You might be chasing shadows. Most of the words you've weighed don't work well. For instance, an old source can still be authoritative, and a new source can be false right out of the gate.
But more to the point, the MacDonald's sign that says "Over a kajillion sold" isn't a quote. It's a statement that purports to be fact—as is the old newspaper headline about the sinking of the Titanic.
Let's ignore quotes that don't masquerade as empircal data: "A rose is a rose is a rose." "Good fences make good neighbors." "Winston tastes good." "By George, I think she's got it." "She loves me, yeah, yeah, yeah."
For that matter, let's ignore quotes that do: "Dewey Defeats Truman."
None of them has a go-by date. True or false, they say what they said. Records are to history what amber is to mosquitoes. That's why a statement or quote presented as fact should always be considered in context.
But you're right, sometimes an adjective helps. I like to keep it simple. You might call it a recent quote. Or an old quote. (I remember when MacDonald's signs said—and I quote—"We have sold OVER 1 MILLION.")
You could call it disproven, time-tested, discredited, prescient, or thousands of other things.
But I know of no classes of quotation that separate what something said now from what it said then. Let's see if someone else does.

A: I believe what you're looking for is called a Living Document:
https://en.wikipedia.org/wiki/Living_document

*

*A living document, also known as an evergreen document or dynamic document, is a document that is continually edited and updated.

Wikipedia is not, of course, a primary reference, so that by itself won't hold... this is mostly a slang or technical term, so here's an example of it being used:
https://www.usconstitution.net/constfaq_q93.html

Q93. "How is the Constitution a living document?"
A. The Constitution has been termed a "Living Document," but


text:
Q: Handling JSON response which is String or Array using same variable in JAVA I am getting response from JSON in two format String and Array, so am not able to handle it becuase i am not sure which format will be
Is there any way to handle string and array type response using java
Kindly let me know thanks in advance

A: I think you can use try catch exception in this case.
First, try to treat the response as String. if it occurs error, just catch error and treat the response as Array.

A: Just check the datatype of JSON's message part and accordingly use that.
Check out this example.
package test;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class jsonDeco {

    public static void main(String[] args) throws JSONException {
        // TODO Auto-generated method stub
        JSONObject a = new JSONObject("{ \"status_code\": 2002, \"sub_status_code\": 2002,"
                + " \"message\": \"Service Invoke Create Step2 Success\"} ");
        JSONObject b = new JSONObject("{ \"status_code\": 7000, \"sub_status_code\": 7001,"
                + " \"message\": [ \"Step No: Step 2: Line No: 92 Variable Name: lan-pool-ipv6-mask"
                + " Error Code: 7516 Error Detail: Lan Pool IPV6 network address is invalid Description: \" ]}");
        parseAORB(b);
    }

    public static void parseAORB(JSONObject input) throws JSONException
    {
        String code = input.getString("status_code");
        System.out.println(code);
        System.out.println(nameOf(input.get("message")));
        if(nameOf(input.get("message")).equals("String"))
        {
            System.out.println("inside string");
            String message = input.getString("message");
            System.out.println("Message is : "+message);
        }
        else if (nameOf(input.get("message")).equals("JSONArray"))
        {
            JSONArray message = input.getJSONArray("message");
            System.out.println("inside jsonarray");
            System.out.println("Message is : "+message.getString(0).toString());
        }
    }

    private static String nameOf(Object o) {
        return o.getClass().getSimpleName();
    }
}

You can pass variable a or b to test.
P.S. In the comment, both the example is wrong. In first one, there is one comma , extra at the end and in the second example, you didn't close the curly bracket }.


text:
Q: Different Liquibase checksum on same files with cyrillic symbols I use liquibase for migrations and have sql files with cyrillic comments, like example.sql:
--liquibase formatted sql

--changeset user:id1
create table example
(
    id            varchar(100) primary key
);

-- cyryllic comment here
comment on table kafka_cluster is 'Коммментарий к таблице.';

My changelog is yaml file like:
databaseChangeLog:
  - include:
      # comment
      file: db/changelog/1.0.0/schema/example.sql

When i run application on different OS(my mac and on the linux server) i always got different checksums for same files.
Liquibase version:
    compile "org.liquibase:liquibase-core:4.3.1"

I don't know why it happens, files are the same. All files are in the UTF-8 charset.
One of the answers for my question is to have all files in UTF-8 with BOM.
But it's not good for me - make sure that all sql files are with BOM.
Another solution is to move from yaml to xml.
Maybe there is a simpler solution?
Thanx.


text:
Q: CommunicationException while using the Atlassian .NET SDK I'm using the Atlassian .NET SDK to extract data from Jira OnDemand. I need to get more than 100 issues for a particular project. My problem is that if I set the maxIssues property to higher than 67, I get a CommunicationExceptions saying:

"Error in deserializing body of reply message for operation 'getIssuesFromJqlSearch'."

Any ideas how I can fix this?
var jiraConn = new Jira(url, user, password);

IEnumerable<Atlassian.Jira.Issue> jiraIssues =
     jiraConn.GetIssuesFromJql("project = MAGNAMES", 67);

foreach (var i in jiraIssues)
{
    MessageBox.Show(i.Key + " " + i.Summary);
}

Server stack trace:
     at System.ServiceModel.Dispatcher.XmlSerializerOperationFormatter.DeserializeBody(XmlDictionaryReader reader, MessageVersion version, XmlSerializer serializer, MessagePartDescription returnPart, MessagePartDescriptionCollection bodyParts, Object[] parameters, Boolean isRequest)
     at System.ServiceModel.Dispatcher.XmlSerializerOperationFormatter.DeserializeBody(XmlDictionaryReader reader, MessageVersion version, String action, MessageDescription messageDescription, Object[] parameters, Boolean isRequest)
     at System.ServiceModel.Dispatcher.OperationFormatter.DeserializeBodyContents(Message message, Object[] parameters, Boolean isRequest)
     at System.ServiceModel.Dispatcher.OperationFormatter.DeserializeReply(Message message, Object[] parameters)
     at System.ServiceModel.Dispatcher.ProxyOperationRuntime.AfterReply(ProxyRpc& rpc)
     at System.ServiceModel.Channels.ServiceChannel.HandleReply(ProxyOperationRuntime operation, ProxyRpc& rpc)
     at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
     at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs)
     at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
     at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)
  Exception rethrown at [0]:
     at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
     at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
     at Atlassian.Jira.Remote.JiraSoapService.getIssuesFromJqlSearch(getIssuesFromJqlSearchRequest request)
     at Atlassian.Jira.Remote.JiraSoapServiceClient.Atlassian.Jira.Remote.JiraSoapService.getIssuesFromJqlSearch(getIssuesFromJqlSearchRequest request) in c:\dev\atlassian.net-sdk\Atlassian.Jira\Remote\JiraSoapService.cs:line 9445
     at Atlassian.Jira.Remote.JiraSoapServiceClient.getIssuesFromJqlSearch(String in0, String in1, Int32 in2) in c:\dev\atlassian.net-sdk\Atlassian.Jira\Remote\JiraSoapService.cs:line 9454
     at Atlassian.Jira.Remote.JiraSoapServiceClientWrapper.GetIssuesFromJqlSearch(String token, String jqlSearch, Int32 maxNumResults) in c:\dev\atlassian.net-sdk\Atlassian.Jira\Remote\JiraSoapServiceClientWrapper.cs:line 39
     at Atlassian.Jira.Jira.<>c__DisplayClass8.<GetIssuesFromJql>b__7(String t) in c:\dev\atlassian.net-sdk\Atlassian.Jira\Jira.cs:line 203
     at Atlassian.Jira.Jira.<>c__DisplayClass37.<WithToken>b__36(String t) in c:\dev\atlassian.net-sdk\Atlassian.Jira\Jira.cs:line 396
     at Atlassian.Jira.Jira.<>c__DisplayClass3d`1.b__3c(String token, IJiraSoapServiceClient client) in c:\dev\atlassian.net-sdk\Atlassian.Jira\Jira.cs:line 427
     at Atlassian.Jira.Jira.WithToken[TResult](Func`3 function) in c:\dev\atlassian.net-sdk\Atlassian.Jira\Jira.cs:line 446
     at Atlassian.Jira.Jira.WithToken[TResult](Func`2 function) in c:\dev\atlassian.net-sdk\Atlassian.Jira\Jira.cs:line 427
     at Atlassian.Jira.Jira.WithToken(Action`1 action) in c:\dev\atlassian.net-sdk\Atlassian.Jira\Jira.cs:line 394
     at Atlassian.Jira.Jira.GetIssuesFromJql(String jql, Nullable`1 maxIssues) in c:\dev\atlassian.net-sdk\Atlassian.Jira\Jira.cs:line 201
     at TicketReportService.ReportService.StartService() in c:\OSSTicketReportApp\TicketReportWebApp\TicketReportService\ReportService.cs:line 92
     at TicketReportService.Program.Main() in c:\OSSTicketReportApp\TicketReportWebApp\TicketReportService\Program.cs:line 24
     at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
     at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
     at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
     at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
     at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
     at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
     at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
     at System.Threading.ThreadHelper.ThreadStart()

A: Make sure there isn't a particular problem with Issue number 68 that is preventing JiraSoapService from correctly deserializing the issue.  Perhaps there is something in a comment or other WYSIWYG field that is breaking the deserializer.


text:
Q: Update GridViewRow on button click of that row I have a GridView with checkbox, dropdown and button as templatefields.
On button click I have to update the entire row in the data base.
This is my aspx:
<asp:GridView runat="server" ID="Gdv" AutoGenerateColumns="False" Font-Size="Small" CssClass="grid" BackColor="White" BorderWidth="0px" CellPadding="4" Width="100%" AllowSorting="True" SkinID="GVSalesManager" GridLines="none" AllowPaging="true" PageSize="10" PagerStyle-ForeColor="#0066cc" PagerStyle-CssClass="gvPagerCss" PagerStyle-Font-Underline="true" PagerStyle-Wrap="true"
OnPageIndexChanging="GdvCPRetailerMap_PageIndexChanging" OnRowDataBound="GdvCPRetailerMap_RowDataBound">
 <Columns>
   <asp:BoundField ReadOnly="true" HeaderText="S.No" DataField="S.No." SortExpression="SNo">
    <ItemStyle HorizontalAlign="Center" Width="2%" />
     <HeaderStyle HorizontalAlign="Center" Font-Bold="true"  Width="2%"/>
    </asp:BoundField>

   <asp:TemplateField ItemStyle-Width="3%" ItemStyle-HorizontalAlign="Center">
      <ItemTemplate>
      <asp:CheckBox ID="chkRow" runat="server" OnCheckedChanged="chkRow_CheckedChanged" AutoPostBack="true"/>
      </ItemTemplate>
   </asp:TemplateField>

   <asp:BoundField ReadOnly="true" HeaderText="Customer Id" ItemStyle-HorizontalAlign="Center" DataField="CustomerID" SortExpression="CustomerID">
<ItemStyle HorizontalAlign="Center" Width="10%" />
<HeaderStyle HorizontalAlign="Center" Font-Bold="true"  Width="10%"/>
   </asp:BoundField>

 <asp:BoundField ReadOnly="true" HeaderText="Firm's Name" ItemStyle-HorizontalAlign="Center" DataField="Firm's Name" SortExpression="SNo">
<ItemStyle HorizontalAlign="Center" Width="20%" />
<HeaderStyle HorizontalAlign="Center" Font-Bold="true"  Width="20%"/>
  </asp:BoundField>

 <asp:BoundField ReadOnly="true" HeaderText="Retailer Name" ItemStyle-HorizontalAlign="Center" DataField="Retialer Name" SortExpression="SNo">
  <ItemStyle HorizontalAlign="Center" Width="20%" />
  <HeaderStyle HorizontalAlign="Center" Font-Bold="true"  Width="20%"/>
 </asp:BoundField>

 <asp:BoundField ReadOnly="true" HeaderText="Pesticide Licence No." ItemStyle-HorizontalAlign="Center" DataField="Pesticide Licence No" SortExpression="SNo">
 <ItemStyle HorizontalAlign="Center" Width="10%" />
 <HeaderStyle HorizontalAlign="Center" Font-Bold="true"  Width="10%"/>
 </asp:BoundField>

<asp:TemplateField HeaderText="Channel Partner-1" HeaderStyle-Font-Bold="true" ItemStyle-Width="10%" ItemStyle-HorizontalAlign="Center">
 <ItemTemplate>
<asp:DropDownList ID="ddlCP1" Enabled="false" ToolTip="Please Click on the checkbox to change the prefered CP" runat="server" AutoPostBack="true" OnSelectedIndexChanged="ddlCP1_SelectedIndexChanged"></asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>

<asp:TemplateField HeaderText="Channel Partner-2" HeaderStyle-Font-Bold="true" ItemStyle-Width="10%" ItemStyle-HorizontalAlign="Center">
 <ItemTemplate>
<asp:DropDownList ID="ddlCP2" Enabled="false" ToolTip="Please Click on the checkbox to change the prefered CP" runat="server" AutoPostBack="true" OnSelectedIndexChanged="ddlCP2_SelectedIndexChanged"></asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>

 <asp:TemplateField ItemStyle-Width="10%" ItemStyle-HorizontalAlign="Center">
 <ItemTemplate>
 <asp:Button runat="server" ID="BtnUpdateRow" Text="Update" ToolTip="Update This Record?" OnClick="BtnUpdateRow_Click" BackColor="#336699" ForeColor="#ffffff"/>
 </ItemTemplate>
 </asp:TemplateField>

  </Columns>
</asp:GridView>

This is the updatebutton event
protected void BtnUpdateRow_Click(object sender, EventArgs e)
{
    Button btn = (Button)sender;
    GridViewRow grow = (GridViewRow)btn.NamingContainer;
    //btn.
    CheckBox chkbx = (CheckBox)grow.FindControl("chkRow");

    if (chkbx.Checked != true)
    {
        labelErrormessage.Visible = true;
        labelErrormessage.ForeColor = System.Drawing.Color.Red;
        labelErrormessage.Text = "Please Check/Uncheck the CheckBox and Click Update";
        return;

    }
    else
    {
        /*--Code to update the row's record in the edatabase.--*/
        ??

        labelErrormessage.Visible = true;
        labelErrormessage.ForeColor = System.Drawing.Color.Green;
        labelErrormessage.Text = "Updated Succesfully";
        return;
    }
}

How do I read the row in which the button has been clicked and update its dropdownlist selected values in the database?

A: If you have some sort of identification data displayed in the gridview you could get the value from the row's cell like this grow.Cells[0].Text then find the record in the database and update its values.
You could also hide the id for example if this is information you dont want to show to the user. The row will still be located at index 0 but hidden.
Sample:
    else
    {
        var record = queryDatabase(grow.Cells[0].Text);

        //update record values

        updateRecord(record);

        labelErrormessage.Visible = true;
        labelErrormessage.ForeColor = System.Drawing.Color.Green;
        labelErrormessage.Text = "Updated Succesfully";
        return;
    }


text:
Q: How to make protocol associated type require protocol inheritance and not protocol adoption In my swift project I have a case where I use protocol inheritance as follow
protocol A : class{

}

protocol B : A{

}

What Im trying to achieve next is declaring another protocol with associated type, a type which must inherit from protocol A. If I try to declare it as :
protocol AnotherProtocol{
    associatedtype Type : A
    weak var type : Type?{get set}
}

it compiles without errors but when trying to adopt AnotherProtocol in the following scenario:
class SomeClass : AnotherProtocol{

    typealias Type = B
    weak var type : Type?
}

compilation fails with error claiming that SomeClass does not conform to AnotherProtocol. If I understood this correctly it means that B
 does not adopt A while Im trying to declare and asking you on how to declare an associated type which inherits from protocol A?
I made the above assumption based on fact that the following scenario compiles just fine
class SomeDummyClass : B{

}

class SomeClass : AnotherProtocol{

    typealias Type = SomeDummyClass
    weak var type : Type?
}

A: This is pretty interesting. It appears that once you constrain the type of an associatedtype in a given protocol, you need to provide a concrete type in the implementation of that protocol (instead of another protocol type) – which is why your second example worked.
If you remove the A constraint on the associated type, your first example will work (minus the error about not being able to use weak on a non-class type, but that doesn't seem to be related).
That all being said, I can't seem to find any documentation in order to corroborate this. If anyone can find something to back this up with (or completely dispute it), I'd love to know!
To get your current code working, you can use generics. This will actually kill two birds with one stone, as both your code will now compile and you'll benefit from the increased type safety that generics bring (by inferring the type you pass to them).
For example:
protocol A : class {}
protocol B : A {}

protocol AnotherProtocol{
    associatedtype Type : A
    weak var type : Type? {get set}
}

class SomeClass<T:B> : AnotherProtocol {
    typealias Type = T
    weak var type : Type?
}

Edit: It appears the above solution won't work in your particular case, as you want to avoid using concrete types. I'll leave it here in case it's useful for anyone else.

In your specific case, you may be able to use a type erasure in order to create a pseudo concrete type for your B protocol. Rob Napier has a great article about type erasures.
It's a bit of a weird solution in this case (as type erasures are normally used to wrap protocols with associatedtypes), and it's also definitely less preferred than the above solution, as you have to re-implement a 'proxy' method for each method in your A & B protocols – but it should work for you.
For example:
protocol A:class {
    func doSomethingInA() -> String
}

protocol B : A {
    func doSomethingInB(foo:Int)
    func doSomethingElseInB(foo:Int)->Int
}

// a pseudo concrete type to wrap a class that conforms to B,
// by storing the methods that it implements.
class AnyB:B {

    // proxy method storage
    private let _doSomethingInA:(Void)->String
    private let _doSomethingInB:(Int)->Void
    private let _doSomethingElseInB:(Int)->Int

    // initialise proxy methods
    init<Base:B>(_ base:Base) {
        _doSomethingInA = base.doSomethingInA
        _doSomethingInB = base.doSomethingInB
        _doSomethingElseInB = base.doSomethingElseInB
    }

    // implement the proxy methods
    func doSomethingInA() -> String {return _doSomethingInA()}
    func doSomethingInB(foo: Int) {_doSomethingInB(foo)}
    func doSomethingElseInB(foo: Int) -> Int {return _doSomethingElseInB(foo)}
}

protocol AnotherProtocol{
    associatedtype Type:A
    weak var type : Type? {get set}
}

class SomeClass : AnotherProtocol {
    typealias Type = AnyB
    weak var type : Type?
}

class AType:B {
    // implement the methods here..
}
class AnotherType:B {
    // implement the methods here..
}

// your SomeClass instance
let c = SomeClass()

// set it to an AType instance
c.type = AnyB(AType())

// set it to an AnotherType instance
c.type = AnyB(AnotherType())

// call your methods like normal
c.type?.doSomethingInA()
c.type?.doSomethingInB(5)
c.type?.doSomethingElseInB(4)

You can now use the AnyB type in place of using the B protocol type, without making it any more type restrictive.