text:
Q: Business Continuity Plan -- How can I connect to DR Server if PROD site is completely Down I have two servers in one DataCenterA (PRODUCTION SQL SERVERS AOAGs) and one server in another DatacenterB (DR BCP AOAGs).What if DataCenterA is completely Down.Now how can I let the Application stay Online.My SQL Servers has AlwaysOn Availability Groups.Can I connect to application by changing the connection string as "SQL\Instancename" in web.config file or using BCP AOAGs Listener which we created for AlwaysOn AGs BCP Listener ?
Please Guide me on this.

A: If you have:

*

*2 Datacenters

*1 Server in Each DC

*Using SQL Server AlwaysOn Availability Groups

Then the following happens:

*

*The Primary Datacenter Goes Down, Completely

How do you continue business continuity?
Assuming that the Availability Replicas are both set to Synchronous...

*

*Quorum will have most likely been lost - you'll need to force quorum on the server in the DC that is still up. This can be completed a variety of ways. Powershell: Start-ClusterNode -FixQuorum , services: net start clussvc /fq , etc.

*Connect to SQL Server now that the cluster was forced quorum. Failover the Availability Group. This will bring the listener with it. Whether Synchronous or Asynchronous is set, this can be accomplished by executing ALTER VAILABILITY GROUP [Name] FORCE_FAILOVER_ALLOW_DATA_LOSS

*Test connectivity.

Depending on the settings of the listener in the windows cluster, your clients may need to flush their dns cache (to pickup the new ip if they are legacy clients).
Once the first DC comes back online we'll want to make sure to reconfigure and re-evaluate the situation.
Resources that will help you:

*

*https://msdn.microsoft.com/en-us/library/hh781257.aspx (Solutions guide for HA/DR)

*https://msdn.microsoft.com/en-us/library/dn425173.aspx (MSIT case study for HA/DR)


text:
Q: jQuery ajax failing after the first click I set up a link that queries the Instagram API and displays images. I want it so when I click on the link again it refreshes and gets me newer images (or multiple links). But it always fails after the first click.

#olympics

#london

And this is my JS:
  $(".keywords").live('click',function()

  {
      $.ajax({
      type: "GET",
      dataType: "jsonp",
      cache: false,
      url: "https://api.instagram.com/v1/tags/olympics/media/recent?client_id=XXXXXXXXX&access_token=XXXXXXXXXXXXX",
      success: function(data) {
          for (var i = 0; i < 10; i++) {
              $(".pics").append("");
                                      }
                              }

      })
  }
  );

A: If you want to refresh the pics list on a new click you might want to empty the .pics div before appending the new images.
$(".pics").empty();
for (var i = 0; i < 10; i++) {
    $(".pics").append("");
}

since as it is now pics are appended to the list not replaced.
EDIT
Sorry $(".pics").empty(); should be before the for loop not inside it.

A: It's possible you're getting a javascript error when processing the first results as your for loop runs 10 times no matter what results are returned. This could then be stopping the second request from running.
Try changing the contents of the success callback to:
for (var i = 0; i < data.data.length; i++) {
    $(".pics").append("");
}

I changed the 10 to data.data.length, this way it will only loop over the number of results returned.
If you want to only display a max of 10 do this:
for (var i = 0; i < data.data.length && i < 10; i++) {
    $(".pics").append("");
}

A: working sample:
http://jsfiddle.net/h6NgP/
You just had a bracket error ;) minor syntax thing. works the first time in jsfiddle

A: I see problem with this
for (var i = 0; i < 10; i++) {

You've hard coded 10. Are you sure you are geeting "FRESH" list of images every time?
Or it might be the case that the new images are appended to the JSON and you are not seeing this just because you are iterating over it only 10 times.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Flask POST sign up form retrieve value of dropdown box I am using this HTML script for a sign up form in flask and the code will not let me retrieve the data in the same way I retrieve the username and password using request.form['']. I would like to pass the value of the option a user selects from a dropdown to my python program. Is there any way to solve this issue? Thanks in advance for any responses!
<select id="cell" name="carrier" data-name="cellcarrier">
                    <option value="verizon">Verizon</option>
                    <option value="att">At&t</option>
                    <option value="tmobile">T-Mobile</option>
                    <option value="sprint">Sprint</option>
                    <option value="alltel">AllTel</option>
                    <option value="boost">Boost Mobile</option>
                    <option value="cricket">Cricket</option>
                    <option value="metropcs">MetroPCS</option>
                    <option value="uscellular">US Cellular</option>
                    <option value="virginmobile">Virgin Mobile</option>
                    <option value="republicwireless">Republic Wireless</option>
                </select>


text:
Q: twitter4j and singpost lib in android 4.0 and further Can someone give me a tutorial about using twitter4j in android 4.0 and further?
I was able to use twitter4j before but now I cant, it keeps throwing this error:
"oauth.signpost.exception.OAuthCommunicationException: Communication with the service provider failed: null"
I found in web that the problem is that you can't access the network on the IU Thread anymore... And I tried but I cant fix the problem.
So I want to know how to implemment twitter in android again. Any tutorial??
Thanks!


text:
Q: Directed graph: checking for cycle in adjacency matrix There is an alternative method respect to the DFS algorithm to check if there are cycles in a directed graph represented with an adjacency matrix?
I found piecemeal information on the properties of matrices.
Maybe I can multiply matrix A by itself n times, and check if there is non-zero diagonal in each resulting matrix.
While this approach may be right, how can I extract explicitly the list of vertices representing a cycle?
And what about the complexity of this hypothetical algorithm?
Thanks in advance for your help.

A: Let's say after n iterations, you have a matrix where the cell at row i and column j is M[n][i][j]
By definition M[n][i][j] = sum over k (M[n - 1][i][k] * A[k][j]). Let's say M[13][5][5] > 0, meaning it has a cycle of length 13 starting at 5 and ending at 5. To have M[13][5][5] > 0, there must be some k such that M[12][5][k] * A[k][5] > 0. Let's say k = 6, now you know one more node in the cycle (6). It also follows that M[12][5][6] > 0 and A[6][5] > 0
To have M[12][5][6] > 0, there must be some k such that M[11][5][k] * A[k][6] > 0. Let's say k = 9, now, you know one more node in the cycle (9). It also follows that M[11][5][9] > 0 and A[9][6] > 0
Then, you can do the same repetitively to find other nodes in the cycle.

A: Depth-first search can be modified to decide the existence of a cycle. The first time that the algorithm discovers a node which has previously been visited, the cycle can be extracted from the stack, as the previously found node must still be on the stack; it would make sense to use a user-defined stack instead of the call stack. The complexity would be O(|V|+|E|), as for unmodified depth-first search itself.


text:
Q: fetch navigate event is happening multiple times in offline mode When I switch to offline mode in "applications" tab and reload the page "fetch" event with evt.request.mode = 'navigate' fires 2 times and then 1 time after 5 seconds.
My SW code is like this:

function fetchHandler(evt) {
 const waitPromise = fetch(evt.request.url).catch(err => {
  console.log(`${new Date} - error`);
  return Response.error();
 });

 evt.respondWith(waitPromise);
}

self.addEventListener('fetch', evt => {
 console.log('fetch', evt.request.url, evt.request.mode);

 const isFetch = (evt.request.method === 'GET');
 const isNavigate = (evt.request.mode === 'navigate');

 if (isFetch && isNavigate) {
  fetchHandler(evt);
 }
});

Is this an expected behaviour or not?


text:
Q: How do we create nested Vue Components passing other elements as their children In React I would do something like this:
//ParentComponent.js
(

  {this.props.children}

)

//ChildComponent.js
(

  I'm the child!

)

//App.js
import ParentComponent
import ChildComponent

<ParentComponent>
  <ChildComponent />
  Other element
</ParentComponent>

I understand they are different things, but how could I do something like this in Vue? I want to pass ChildElement in ParentComponent's content, and in ParentComponent I must be able to put its content somewhere.
What is the closest to this idea?

A: You would do that using slots.
Vue.component("parent",{
  template:"

I'm the parent component
<slot></slot>
",
})

Vue.component("child", {
  template: "

I'm the child component

"
})

new Vue({
  el:"#app"
})

  <parent>
    <child></child>
  </parent>

Example.


text:
Q: Dictionary with range as key In Python, how can I map from a range of values to one concrete value?
Basically, I want a dictionary, which I can fill with ranges and index with numbers:
rd = rangedict()
rd[(0, 10)] = 5
print rd[4] # prints 5
print rd[6] # prints 5
rd[(5, 15)] = 20
print rd[4] # prints 5
print rd[6] # prints 20

A: You could use an interval tree
pip install intervaltree
from intervaltree import Interval, IntervalTree
rd = IntervalTree()

rd[0:10] = 5
print rd[4]
print rd[5]

https://pypi.python.org/pypi/intervaltree

A: Thanks to the comments I could find a solution using the intervaltree package.
from intervaltree import IntervalTree

tree = IntervalTree()
tree.addi(0, 10, 5)
print tree[4]
print tree[6]

# need to chop before, as the library stores both intervals otherwise
tree.chop(5, 15)
tree.addi(5, 15, 20)
print tree[4]
print tree[6]


text:
Q: How to run a batch file on a schedule I want to make a batch file load fortnightly on a Friday at 9.00am. I would like to do it without task scheduler if possible.

A: Use Windows' built-in at command. Documentation here.
Or the newer schtasks and using a RunInterval (RI) of 20160 minutes. Documentation here.


text:
Q: How are Pointers, data type initialization and multiple pointer declaration handled in c++? When we make a structure for let's say a tree or a linked list, something of this nature:
struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};

What is the type for queue to store nodes of the structure? I thought it was a pointer to the struct.

std::queue<TreeNode*> q;

But if I try to initialize multiple nodes like this:
TreeNode* l = nullptr, r = nullptr;

It doesn't work and you have to do
TreeNode *l = nullptr, TreeNode *r = nullptr;

Can someone help me understand this a little better?
edit: After reading this answer Declaring multiple object pointers on one line causes compiler error

What I'm understanding is that: In both C and C++, the * binds to the declarator, not the type specifier. In both languages, declarations are based on the types of expressions, not objects.

Then how is the queue declared the way it is?

A: The second variable r is not declared as a pointer, it should be:
TreeNode *l = nullptr, *r = nullptr;

TreeNode* is a type, like a char or int, but if you delclare it in the same line you must use the * indirection operator so that the compiler knows that the specific variable is a pointer to object, not an object. When you declare it in a deque or a vector or somenthing like that,  you must also be able to tell if the tpyes admitted are pointers to object or objects, hence the declaration TreeNode* inside angular brackets.
If you think about it, it makes sense semantically speaking.

A: In std::queue<TreeNode*> q;, the brackets enclose a complete type name. (By "name," I mean the entire declarator for the type, TreeNode *, not an identifier.) When describing a type with a declarator, the form used is as if a complete normal declaration with an identifier had its identifier removed. For example, starting with a declaration TreeNode *Placeholder, the type name is TreeNode *.
In TreeNode* l = nullptr, r = nullptr;, there are no brackets to group the * with TreeNode. According to the C++ grammar, it is grouped with l. If brackets were allowed here, so that we could write <TypeNode *> l = nullptr, r = nullptr;, then that could work. The issue here is the same as if you write - a + b: The rules are simply that - is grouped with a, so the expression is -a + b, not - (a + b).
You can of course work around this with typedef TreeNode *TreeNodeP; TreeNodeP l = nullptr, r = nullptr;. This shows the effects are simply the results of how the C++ grammar is structured—there is no inherent reason a compiler could not accept any type description first and then a list of identifiers to be declared with that type, but the grammar design simply does not support that.
(One consequence of this is that it is misleading to write int* a, because the proximity of tokens in the text is different from their proximity in the grammar—* is closer to int in the text but is closer to a in the grammar, so the spacing sends the wrong message.)


text:
Q: How to response xml with node js express? I want to write a function that could generate sitemap like https://www.bbc.co.uk/sitemap.xml. So here's my code
module.exports.sitemapTag = async (req, res) => {
  try {
    const defaultPath = 'https://example.com/tag';
    const tagList = [];
    const data = { tags: await TagService.getAllTag() };
    // eslint-disable-next-line no-restricted-syntax
    for (const item of data.tags) {
      const element = {
        sitemap: {
          tag: defaultPath.concat(item.tagText),
          tagNum: item.tagNumber,
        },
      };
      tagList.push(element);
    }
    const feed = xmlbuilder.create(tagList, { encoding: 'utf-8' });
    return res.status(200).send(feed.end({ pretty: true }));
  } catch (error) {
    console.log(error);
    return res.status(400).json(null);
  }
};

But the result when I accessed localhost://9191/api/v1/sitemapTag is just a string like this:
http://example.com/tag/Cookies 2 http://example.com/tag/Candy 1 http://example.com/tag/Chocolate 3

Then I tried use: console.log(feed.end({ pretty: true }));
to see what happened, my console log like this:
<?xml version="1.0" encoding="utf-8"?>
 <sitemap>
   <tag>http://example.com/tag/Cookies</tag>
   <tagNum>2</tagNum>
 </sitemap>
 <sitemap>
   <tag>http://example.com/tag/Candy</tag>
   <tagNum>1</tagNum>
 </sitemap>
 <sitemap>
   <tag>http://example.com/tag/Chocolate</tag>
   <tagNum>3</tagNum>
 </sitemap>

How could I solve this correctly?

A: That is probably because you're using the default content type (html maybe) so all the tags are hidden because it's being intepreted as HTML
you need to set content type to to text/xml before
res.header("Content-Type", "text/xml");
return res.status(200).send(feed.end({ pretty: true }));


text:
Q: Java - Parse List into String I'm trying to turn a List<Field> into simple strings, but I'm not sure how to parse them out of the array into a single String variable.
I'm currently using a method that goes through a class that uses a getDeclaredFields() method and outputs them into an array.
public static List<Field> getInheritedPrivateFields(Class<?> type) {
    List<Field> result = new ArrayList<Field>();

    Class<?> i = type;
    while (i != null && i != Object.class) {
        Collections.addAll(result, i.getDeclaredFields());
        i = i.getSuperclass();
    }

    for(Field temp : result) {
        System.out.println(temp);
    }

    return result;
}

The result I get when I output it is
[private int com.gen.e.ric.report.domain.TestCount.count,
 private java.lang.String com.gen.e.ric.report.domain.Test.facility,
 private java.lang.String com.gen.e.ric.report.domain.Test.technology,
 private java.lang.String com.gen.e.ric.report.domain.Test.component,
 private java.util.List com.gen.e.ric.report.domain.Test.etestStats,
 private java.util.Date com.gen.e.ric.report.domain.Test.startDate,
 private java.util.Date com.gen.e.ric.report.domain.Test.endDate]

What I want to get is just a long string with
int, String, String, List, Date, Date

Any help to give? Using Reflection btw.
Thanks.

A: You only want to output each Field's type, so do that:
for(Field temp : result) {
    System.out.println(temp.getType());
}

or in order to put it into a String:
String types = result.stream().map(e->e.getType().getSimpleName()).collect(Collectors.joining(","));

A: The output format is like that as Field class toString method implemented like below:
public String toString() {
    int mod = getModifiers();
    return (((mod == 0) ? "" : (Modifier.toString(mod) + " "))
        + getType().getTypeName() + " "
        + getDeclaringClass().getTypeName() + "."
        + getName());
}

Note: Class & Field class both are final so you can't override
  it also.

So, you can't change the toString definition of Field. But what you can build your own String like below:
String s = result.stream().map(e -> e.getDeclaringClass().getSimpleName()).collect(Collectors.joining(", "));
System.out.println(s);

A: You can make use of the getSimpleName(). For eg:
String.class.getSimpleName();

In your example all you need to do is :
for (Field temp : result) {
    System.out.println(temp.getType().getSimpleName());
}

So your method will now look like :
public static String getInheritedPrivateFields(Class<?> type) {
    List<Field> result = new ArrayList<Field>();

    Class<?> i = type;
    while (i != null && i != Object.class) {
        Collections.addAll(result, i.getDeclaredFields());
        i = i.getSuperclass();
    }

    return result.stream()
                 .map(field -> field.getType().getSimpleName())
                 .collect(Collectors.joining(", "));
}

A: You can use Field.getType() to get the Class of the Field, then use Class.getSimpleName() in order to get only the part you want :
List<String> types = new ArrayList<>();
Field[] declaredFields = Person.class.getDeclaredFields();
for (Field declaredField : declaredFields) {
    // Will give [class java.lang.String, class java.lang.String, int]
    // types.add(declaredField.getType().toString());

    // Will give [String, String, int]
    types.add(declaredField.getType().getSimpleName());
}
System.out.println(types);

[String, String, int]


text:
Q: What was the Center-of-Mass Energy of Rutherfords original experiment scattering $\alpha$-particles off Gold Foil? I am looking through Rutherford's paper on his experiment, The Scattering of α and β Particles by Matter and the Structure of the Atom and am having trouble figuring out the center of mass energy in his experiment given his experimental apparatus. Specifically I am only looking for initial momentum of the incident $\alpha$ particle beam so that I can recover the maximum momentum-transfer possible such an event.
Is this information noted anywhere, or should I just try to reconstruct the incident velocity of the $\alpha$-particle from his cross-section data?

A: User Jon Custer gave me an answer. The alpha particle had an energy of 4.7MeV, radiated from Radium. Source: On a Diffuse Reflection of the $\alpha$-Particles


text:
Q: SimpleSAMLPHP: because it isn't a valid IdP for this SP i am getting the following error when i am redirecting back from idp to saml-sp.
SimpleSAML_Error_Error: UNHANDLEDEXCEPTION
Backtrace:
0 /var/simplesamlphp/www/module.php:180 (N/A)
Caused by: SimpleSAML_Error_Exception: Cannot retrieve metadata for IdP 'https://openidp.feide.no' because it isn't a valid IdP for this SP.

I tried to change metadata 'https://openidp.feide.no' to 'http://192.168.0.105:81'. But still the issue is not resolved. Could someone suggest any idea to resolve it?

A: There should be an entry like following inside metadata/saml20-idp-remote.php file
 for the 'issuer' value coming inside the SAMLResponse:
$metadata['https://openidp.feide.no'] = array( <config data removed for brevity> );

Also, within config/authsources.php you should point to that 'issuer' value inside your respective SP's configuration.
'sp1' => array(
        'idp' => 'https://openidp.feide.no',
         <other config data removed for brevity>
),


text:
Q: Deploy C# application with an option for trial and full version I have developed a c# desktop application, and want to deploy it with some detailed options like

*

*User will select to install either a trial version or the full version, during installation  itself.

*User will fill his registration information during installation only, which will be saved in database.

*And used will get a check box to launch the application after setup completes.

I have developed this application in Visual Studio 2008 and currently aware of the default deployment process only. Please help with some tutorial link or detailed procedure which will guide step by step for customizing the installation package.


text:
Q: writing data with spark streaming I am consuming data from kafka using spark streaming. When I try to write the data to hdfs using method saveAsHadoopFiles as in the code, it creates a directory (named Date-Timestamp.txt) every minute with an empty _SUCCESS file in each of them. It is able to print the data that it receives but not saving it properly. I want it to write files instead of directories with correct data. Any pointers to whats going wrong here.
I will want the data to be ultimately stored in a hive table.
Will be good if someone can suggest a better method of writing this data into a hive table?
 public static void main(String args[]){
    SparkConf conf = new SparkConf().setMaster("local[2]").setAppName("LocationCoordinates");
    JavaStreamingContext jssc = new JavaStreamingContext(conf, Durations.minutes(1));
    Map<String,Integer> topicMap = new HashMap<String,Integer>();
    topicMap.put("test",1);
    JavaPairReceiverInputDStream<String, String> kafkaStream =
            KafkaUtils.createStream(jssc,
                    "ec2-54-174-149-226.compute-1.amazonaws.com:2181", "location_group", topicMap);
    String date = new SimpleDateFormat("dd-MM-yyyy").format(new Date());
    kafkaStream.print();
    kafkaStream.saveAsHadoopFiles("hdfs:/user/19491/iotdata/" + date + "-", "txt", Text.class,Text.class, TextOutputFormat.class);
    jssc.start();
    jssc.awaitTermination();

}


text:
Q: How to vertically centre Bootstrap container in viewport I am trying to vertically centre a Bootstrap container in the viewport. My code can be seen at
http://www.bootply.com/C8vhHTifcE
All my attempts to centre this have failed. Does anyone have a solution?
To clarify: I want the container vertically centered in the viewport and I want to be able to space out the rows so they fill the space.
HTML

      <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">

      </button>
      Brand

Home

About

Contact

            A HEADING

            AN ITEM

            ANOTHER ITEM

                <input value="A BUTTON" style="width:100px;" type="button">

A: DEMO: http://www.bootply.com/AGZSk1TaJc

CSS:
body {
    padding-top: 50px
}
body,
html {
    height: 100%
}
.display-table {
    display: table;
    height: 100%;
    width:100%;
    max-width:1170px;
    margin:0 auto;
}
.display-table-cell {
    display: table-cell;
    width: 100%;
    vertical-align: middle;
}
.display-table-cell > div {
    display: table;
    width: 100%;
    height: 25%;
}
.display-table-cell > div > span {
    display: table-cell;
    width:100%;
    vertical-align: middle;
}
.display-table-cell > div:nth-child(even) {
    background: #f7f7f7
}
.display-table-cell > div:nth-child(odd) {
    background: #eee
}

HTML

         <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">

         </button>
         Brand

Home

About

Contact

A HEADING

AN ITEM

ANOTHER ITEM

<input value="A BUTTON" class="btn btn-default" type="button">


text:
Q: pattern identification for time-series data I have a time-series data set with ~20 observations with one variable of interest measured everyday for several months for each observation. If I plot the variable on a timeline for each observation separately, each observation will have its own unique pattern. My goal is to categorize these patterns into several groups. I can roughly do so by just looking at the plots themselves and compare them, but I do not know how to approach this problem from the statistical standpoint. Is there any tool / technique that will identify the patterns and categorize the observations based on that?

A: The most simple approach would be to:

*

*compute statistical descriptors for each timeseries (such as mean, max, min, standard deviation or more sophicticated ones after fourier transformation in the frequency domain) and

*then cluster the time-series in the feature space using algorithms such as DBSCAN (you could as well use k-means, yet you would have to define the target number of clusters k).
Yet the resulting clusters depend on the features/descriptors you chose. The choice of features is therefore critical and must be done using domain knowledge.


text:
Q: Hyperlink problems I want to make the following text entirely into a hyperlink together. I have the first two lines as one hyperlink. How to add the third line and then make a hyperlink.
"window.open('http://dotsd1oitdev/Reports/Pages/Report.aspx?ItemPath=%2f4P%2f4P%2fProject+Status+(Selected+Projects)&PROJECT_IDS="
& l & "&rs:Command=Render&rs:Format=PDF&rc:NoHeader=true');"


text:
Q: Forcing a UNION on an OR for optimization in SQL Server 2000 How can I get a query which uses an OR in the WHERE clause to split itself into two queries with a UNION during compilation?  If I manually rewrite it, the query using the UNION is 100x faster than the single query, because it can effectively use different indices in each query of the union.  Is there any way I can make the optimizer use this approach?
I have a query that looks something like this:
select columnlist
from table1
join table2 on joincond2
join table3 on joincond3
where conditions1
    and ((@param1 is null and cond3a) or (cond3b))

Where columnlist, joincond2, joincond3, and conditions1 are all longer expressions.  The kicker is that only one of the conditions in the OR is ever true.
I first thought I could just rewrite it to do the union, but then I am repeating columnlist, joincond2, joincond3, and conditions1, which is 20 or so lines of SQL that might need a lot of maintenance in the future.  Is there a hint I can supply or some better way to write the WHERE clause?  Thanks in advance.

A: You can group
select columnlist
from table1
join table2 on joincond2
join table3 on joincond3

into a view, and then use union.
but if you can migrate to sql2005/8,
you can use common table expression.
with cte ( columnlist )
as (
    select columnlist
    from table1
    join table2 on joincond2
    join table3 on joincond3 )
select columnlist from cte where ...
union
select columnlist from cte where ...

A: Try adding OPTION (RECOMPILE) to the query. If it's in a stored procedure then add WITH RECOMPILE to that as well. It may be that the first time that you run the query SQL Server comes up with a plan and caches it but then the second time through it's still using the old (and now poor) query plan.
You will take a minor hit because it will need to recompile every time you use the query, but it will be minuscule in comparison to the use of a poor plan.
EDIT: I've read that using WITH RECOMPILE in a stored procedure in SQL 2000 doesn't always work properly. The bug was supposedly fixed in SQL 2005. I've never encountered the bug personally though, so I don't know what the exact deal is with it. Give it a try though.


text:
Q: How-to convert an iOS camera image to greyscale using the Accelerate Framework? It seems like this should be simpler than I'm finding it to be.
I have an AVFoundation frame coming back in the standard delegate method:
- (void)captureOutput:(AVCaptureOutput *)captureOutput
didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer
       fromConnection:(AVCaptureConnection *)connection

where I would like to convert the frame to greyscale using the Accelerate.Framework.
There is a family of conversion methods in the framework, including vImageConvert_RGBA8888toPlanar8(), which looks like it might be what I would like to see, however, I can't find any examples of how to use them!
So far, I have the code:
- (void)captureOutput:(AVCaptureOutput *)captureOutput
didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer
       fromConnection:(AVCaptureConnection *)connection
{

      @autoreleasepool {
            CVImageBufferRef imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer);
            /*Lock the image buffer*/
            CVPixelBufferLockBaseAddress(imageBuffer,0);
            /*Get information about the image*/
            uint8_t *baseAddress = (uint8_t *)CVPixelBufferGetBaseAddress(imageBuffer);
            size_t width = CVPixelBufferGetWidth(imageBuffer);
            size_t height = CVPixelBufferGetHeight(imageBuffer);
            size_t stride = CVPixelBufferGetBytesPerRow(imageBuffer);

            // vImage In
            Pixel_8 *bitmap = (Pixel_8 *)malloc(width * height * sizeof(Pixel_8));
            const vImage_Buffer inImage = { bitmap, height, width, stride };

            //How can I take this inImage and convert it to greyscale?????
            //vImageConvert_RGBA8888toPlanar8()??? Is the correct starting format here??
      }
}

So I have two questions:
(1) In the code above, is RBGA8888 the correct starting format?
(2) How can I actually make the Accelerate.Framework call to convert to greyscale?

A: There is an easier option here. If you change the camera acquire format to YUV, then you already have a greyscale frame that you can use as you like. When setting up your data output, use something like:
dataOutput.videoSettings = @{ (id)kCVPixelBufferPixelFormatTypeKey : @(kCVPixelFormatType_420YpCbCr8BiPlanarFullRange) };

You can then access the Y plane in your capture callback using:
CVPixelBufferRef pixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer);
CVPixelBufferLockBaseAddress(pixelBuffer, kCVPixelBufferLock_ReadOnly);
uint8_t *yPlane = CVPixelBufferGetBaseAddressOfPlane(pixelBuffer, 0);

... do stuff with your greyscale camera image ...

CVPixelBufferUnlockBaseAddress(pixelBuffer);

A: The vImage method is to use vImageMatrixMultiply_Planar8 and a 1x3 matrix.
vImageConvert_RGBA8888toPlanar8 is the function you use to convert a RGBA8888 buffer into 4 planar buffers. These are used by vImageMatrixMultiply_Planar8.  vImageMatrixMultiply_ARGB8888 will do it too in one pass, but your gray channel will be interleaved with three other channels in the result.  vImageConvert_RGBA8888toPlanar8 itself doesn't do any math. All it does is separate your interleaved image into separate image planes.
If you need to adjust the gamma as well, then probably vImageConvert_AnyToAny() is the easy choice. It will do the fully color managed conversion from your RGB format to a grayscale colorspace. See vImage_Utilities.h.
I like Tarks answer better though. It just leaves you in a position of having to color manage the Luminance manually (if you care).

A: Convert BGRA Image to Grayscale with Accelerate vImage
This method is meant to illustrate getting Accelerate's vImage use in converting BGR images to grayscale. Your image may very well be in RGBA format and you'll need to adjust the matrix accordingly, but the camera outputs BGRA so I'm using it here. The values in the matrix are the same values used in OpenCV for cvtColor, there are other values you might play with like luminosity. I assume you malloc the appropriate amount of memory for the result. In the case of grayscale it is only 1-channel or 1/4 the memory used for BGRA. If anyone finds issues with this code please leave a comment.
Performance note
Converting to grayscale in this way may NOT be the fastest. You should check the performance of any method in your environment. Brad Larson's GPUImage might be faster, or even OpenCV's cvtColor. In any case you will want to remove the calls to malloc and free for the intermediate buffers and manage them for the app lifecycle. Otherwise, the function call will be dominated by the malloc and free. Apple's docs recommend reusing the whole vImage_Buffer when possible.
You can also read about solving the same problem with NEON intrinsics.
Finally, the fastest method is not converting at all. If you're getting image data from the device camera the device camera is natively in the kCVPixelFormatType_420YpCbCr8BiPlanarFullRange format. Meaning, grabbing the first plane's data (Y-Channel, luma) is the fastest way to get grayscale.
BGRA to Grayscale
- (void)convertBGRAFrame:(const CLPBasicVideoFrame &)bgraFrame toGrayscale:(CLPBasicVideoFrame &)grayscaleFrame
{
    vImage_Buffer bgraImageBuffer = {
        .width = bgraFrame.width,
        .height = bgraFrame.height,
        .rowBytes = bgraFrame.bytesPerRow,
        .data = bgraFrame.rawPixelData
    };

    void *intermediateBuffer = malloc(bgraFrame.totalBytes);
    vImage_Buffer intermediateImageBuffer = {
        .width = bgraFrame.width,
        .height = bgraFrame.height,
        .rowBytes = bgraFrame.bytesPerRow,
        .data = intermediateBuffer
    };

    int32_t divisor = 256;
//    int16_t a = (int16_t)roundf(1.0f * divisor);
    int16_t r = (int16_t)roundf(0.299f * divisor);
    int16_t g = (int16_t)roundf(0.587f * divisor);
    int16_t b = (int16_t)roundf(0.114f * divisor);
    const int16_t bgrToGray[4 * 4] = { b, 0, 0, 0,
                                       g, 0, 0, 0,
                                       r, 0, 0, 0,
                                       0, 0, 0, 0 };

    vImage_Error error;
    error = vImageMatrixMultiply_ARGB8888(&bgraImageBuffer, &intermediateImageBuffer, bgrToGray, divisor, NULL, NULL, kvImageNoFlags);
    if (error != kvImageNoError) {
        NSLog(@"%s, vImage error %zd", __PRETTY_FUNCTION__, error);
    }

    vImage_Buffer grayscaleImageBuffer = {
        .width = grayscaleFrame.width,
        .height = grayscaleFrame.height,
        .rowBytes = grayscaleFrame.bytesPerRow,
        .data = grayscaleFrame.rawPixelData
    };

    void *scratchBuffer = malloc(grayscaleFrame.totalBytes);
    vImage_Buffer scratchImageBuffer = {
        .width = grayscaleFrame.width,
        .height = grayscaleFrame.height,
        .rowBytes = grayscaleFrame.bytesPerRow,
        .data = scratchBuffer
    };

    error = vImageConvert_ARGB8888toPlanar8(&intermediateImageBuffer, &grayscaleImageBuffer, &scratchImageBuffer, &scratchImageBuffer, &scratchImageBuffer, kvImageNoFlags);
    if (error != kvImageNoError) {
        NSLog(@"%s, vImage error %zd", __PRETTY_FUNCTION__, error);
    }
    free(intermediateBuffer);
    free(scratchBuffer);
}

CLPBasicVideoFrame.h - For reference
typedef struct
{
    size_t width;
    size_t height;
    size_t bytesPerRow;
    size_t totalBytes;
    unsigned long pixelFormat;
    void *rawPixelData;
} CLPBasicVideoFrame;

I got through the grayscale conversion, but was having trouble with the quality when I found this book on the web called Instant OpenCV for iOS. I personally picked up a copy and it has a number of gems, although the code is bit of a mess. On the bright-side it is a very reasonably priced eBook.
I'm very curious about that matrix. I toyed around with it for hours trying to figure out what the arrangement should be. I would have thought the values should be on the diagonal, but the Instant OpenCV guys put it as above.

A: if you need to use BGRA vide streams - you can use this excellent conversion
here
This is the function you'll need to take:
void neon_convert (uint8_t * __restrict dest, uint8_t * __restrict src, int numPixels)
      {
          int i;
          uint8x8_t rfac = vdup_n_u8 (77);
          uint8x8_t gfac = vdup_n_u8 (151);
          uint8x8_t bfac = vdup_n_u8 (28);
          int n = numPixels / 8;

          // Convert per eight pixels
          for (i=0; i < n; ++i)
          {
              uint16x8_t  temp;
              uint8x8x4_t rgb  = vld4_u8 (src);
              uint8x8_t result;

              temp = vmull_u8 (rgb.val[0],      bfac);
              temp = vmlal_u8 (temp,rgb.val[1], gfac);
              temp = vmlal_u8 (temp,rgb.val[2], rfac);

              result = vshrn_n_u16 (temp, 8);
              vst1_u8 (dest, result);
              src  += 8*4;
              dest += 8;
          }
      }

more optimisations (using assembly) are in the link

A: (1) My experience with the iOS camera framework has been with images in the kCMPixelFormat_32BGRA format, which is compatible with the ARGB8888 family of functions.  (It may be possible to use other formats as well.)
(2) The simplest way to convert from BGR to grayscale on iOS is to use vImageMatrixMultiply_ARGB8888ToPlanar8():
https://developer.apple.com/documentation/accelerate/1546979-vimagematrixmultiply_argb8888top
Here is a fairly complete example written in Swift.  I'm assuming the Objective-C code would be similar.
        guard let imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) else {
            // TODO: report error
            return
        }

        // Lock the image buffer
        if (kCVReturnSuccess != CVPixelBufferLockBaseAddress(imageBuffer, CVPixelBufferLockFlags.readOnly)) {
            // TODO: report error
            return
        }
        defer {
            CVPixelBufferUnlockBaseAddress(imageBuffer, CVPixelBufferLockFlags.readOnly)
        }

        // Create input vImage_Buffer
        let baseAddress = CVPixelBufferGetBaseAddress(imageBuffer)
        let width = CVPixelBufferGetWidth(imageBuffer)
        let height = CVPixelBufferGetHeight(imageBuffer)
        let stride = CVPixelBufferGetBytesPerRow(imageBuffer)
        var inImage = vImage_Buffer(data: baseAddress, height: UInt(height), width: UInt(width), rowBytes: stride)

        // Create output vImage_Buffer
        let bitmap = malloc(width * height)
        var outImage = vImage_Buffer(data: bitmap, height: UInt(height), width: UInt(width), rowBytes: width)
        defer {
            // Make sure to free unless the caller is responsible for this
            free(bitmap)
        }

        // Arbitrary divisor to scale coefficients to integer values
        let divisor: Int32 = 0x1000
        let fDivisor = Float(divisor)

        // Rec.709 coefficients
        var coefficientsMatrix = [
            Int16(0.0722 * fDivisor),  // blue
            Int16(0.7152 * fDivisor),  // green
            Int16(0.2126 * fDivisor),  // red
            0  // alpha
        ]

        // Convert to greyscale
        if (kvImageNoError != vImageMatrixMultiply_ARGB8888ToPlanar8(
            &inImage, &outImage, &coefficientsMatrix, divisor, nil, 0, vImage_Flags(kvImageNoFlags))) {
            // TODO: report error
            return
        }

The code above was inspired by a tutorial from Apple on grayscale conversion, which can be found at the following link.  It also includes conversion to a CGImage if that is needed.  Note that they assume RGB order instead of BGR, and they only provide a 3 coefficients instead of 4 (mistake?)
https://developer.apple.com/documentation/accelerate/vimage/converting_color_images_to_grayscale


text:
Q: Create an array of (non unique) random numbers in a certain range I'm attempting to create four arrays of random numbers, and merge those arrays into one.  The print results are just there to help me verify the data in the arrays.
The part I can't seem to get working are the parts commented "generate 116 commons and generate 46 uncommons".  The arrays don't seem to contain any data.
<?php

$common = array();
$uncommon = array();

//generate 116 random numbers in the range of 35-74 in an array called $common
for($i = 0; $i < 116; i++){
    $common[] = mt_rand(35, 74);
}

//generate 46 random numbers in the range 75-106 in an array called $uncommon
for($i = 0; $i < 46; i++){
    $uncommon[] = mt_rand(75, 106);
}

//generate 16 random numbers in the range 107-134 in an array called $rare.  No duplicates are allowed.
$rare = range(107, 134);
shuffle($rare );
$rare = array_slice($rare ,0, 16);

//generate 2 random numbers in an array called $superrare. No duplicates are allowed.
$superrare = range(135, 142);
shuffle($superrare );
$superrare = array_slice($superrare ,0, 2);

//merge the arrays and shuffle the feed
$feed = array_merge($common, $uncommon, $rare, $superrare);
//shuffle($feed);

//print results
echo "

 common: ";
print_r($common);
echo "

 uncommon: ";
print_r($uncommon);
echo "

 rare: ";
print_r($rare);
echo "

 super rare: ";
print_r($superrare);
echo "

 feed: ";
print_r($feed);

?>

A: I see that you haven't the $ mark in the for line **$**i++
//generate 116 random numbers in the range of 35-74 in an array called $common
for($i = 0; $i < 116; $i++){
    $common[] = mt_rand(35, 74);
}

//generate 46 random numbers in the range 75-106 in an array called $uncommon
for($i = 0; $i < 46; $i++){
    $uncommon[] = mt_rand(75, 106);
}


text:
Q: How to add event listener to each element in an array? So lets say that I have an array of 4 divs named elements, and to add eventlistener to each of them.
I used this elements.forEach(e => e.addEventListener('clicked', () => console.log('clicked')))
And it console logs only when i click on the last element. When i click on other elements nothing happens

A: There is no such event named clicked in Javascript, update it with click to make it works.
elements.forEach(e => e.addEventListener('click', () => console.log('clicked')))
// here ---------------------------------^^^^^^^-----


text:
Q: is there a way to stop a timer on visual studios at a certain point instead of it keep going basically I mean I want a picture to move when I press a button and the picture to sop moving at a certain point on the form application, not cancel it the picture to move then just stop with the application still running. on Microsoft visual studios c# windows form application
  using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
 private void button1_Click(object sender, EventArgs e)
        {
            timer1.Enabled = true;

        }
 private void pictureBox1_Click(object sender, EventArgs e)
        {

        }
    private void Form1_Load(object sender, EventArgs e)
        {

        }
 private void timer1_Tick(object sender, EventArgs e)
        {
            pictureBox1.Left += 2;
        }
    }
}

A: You can call timer1.Stop() to stop the timer.
You need to set the Interval property of the timer to raise the TickEvent once after that Interval is Elapsed.
In TickEvent you can Stop the Timer or do whatever you want to do.
Try This :
private void Form1_Load(object sender, EventArgs e)
{
timer1.Interval=5000;//to raise tick event for 5 sec's
timer1.Start();
timer1.Tick += new System.EventHandler(this.timer1_Tick);
}

protected void timer1_Tick(Object sender,EventArgs e)
{
//Stop the timer here
timer1.Stop();
}


text:
Q: Mysql GUI for Redhat 6 - Offline Installation with all dependencies needed I am looking for a RPM for a MySQL GUI for Redhat 6. My Problem is, that I do not have an internet connection at the target system. For this reason I am looking for an installer or rpm where all dependencies are included.
I hope you can help me.
PhpMyAdmin would be super nice -.
Thank you guys!

A: Manually
I think the easy solution is to check the phpMyAdmin requirements (which are pretty minimal if you already have a working webserver, PHP, and MySQL installation), then just download the source and uncompress to your web root.
Prepackaged kit
There are a number of prepackaged kits such as XAMPP that include all the requirements in one installer. If you already have an existing MySQL server, this will conflict with that so you'll want to back up your existing databases, migrate your databases to the new system, then remove the old MySQL server.
RPM
This might require a bit of extra work simply to make sure you satisfy all the dependencies, but the phpMyAdmin RPM should work fine. You're able to install RPM files from the disk, although of course the usual method is to download them on-demand so many people aren't aware of this option. Note that phpMyAdmin is part of the EPEL repositories.
I'm assuming you already have MySQL running on the machine, so most of the more difficult dependencies should already be installed.
On your local Redhat system, download the RPM file for phpMyAdmin. Then use rpm to find the dependencies: rpm -qpR phpmyadmin. Compare to what's already installed on the target system and download any missing dependencies manually. This is the hard part, since you'll be doing a lot of the work by hand. Once you've got all the files you need, copy them to the target system where you can install them with rpm -i <filename>.


text:
Q: How to Identify discreet check-in and check-out of an employee from the database if the company is working 24 hours I have a database that stores the employee's check-ins and check-outs.
Up until now, everything was going great and there was no problem. That's when the management decided to go 24x7.
Now, I have a problem. Why? Let's get to that.
Previously, since the company was working like any other company. So the attendance of employees was easy to process.
Suppose I have data of one employee like this
id   |empid|person        |authdatetime       |authdate  |authtime|status    |
-----+-----+--------------+-------------------+----------+--------+----------+
36409|F157 |Mohamed Mufeed|2021-08-01 17:28:50|2021-08-01|17:28:50|Check-out |
36524|F157 |Mohamed Mufeed|2021-08-02 09:37:37|2021-08-02|09:37:37|Check-in  |
36710|F157 |Mohamed Mufeed|2021-08-02 17:27:40|2021-08-02|17:27:40|Check-in  |
36711|F157 |Mohamed Mufeed|2021-08-02 17:27:48|2021-08-02|17:27:48|Check-out |
36789|F157 |Mohamed Mufeed|2021-08-03 08:02:40|2021-08-03|08:02:40|Check-in  |
36998|F157 |Mohamed Mufeed|2021-08-03 17:28:52|2021-08-03|17:28:52|Check-out |
37611|F157 |Mohamed Mufeed|2021-08-07 08:07:17|2021-08-07|08:07:17|Check-in  |
39952|F157 |Mohamed Mufeed|2021-08-17 13:22:21|2021-08-17|13:22:21|Check-in  |
40592|F157 |Mohamed Mufeed|2021-08-19 12:13:14|2021-08-19|12:13:14|Check-in  |
40784|F157 |Mohamed Mufeed|2021-08-21 08:06:08|2021-08-21|08:06:08|Check-in  |
40841|F157 |Mohamed Mufeed|2021-08-21 13:05:42|2021-08-21|13:05:42|Check-in  |
40854|F157 |Mohamed Mufeed|2021-08-21 14:21:04|2021-08-21|14:21:04|Check-in  |
40865|F157 |Mohamed Mufeed|2021-08-21 15:33:45|2021-08-21|15:33:45|Check-out |

I can get the employee's check-in and check-out by grouping the data per day taking the first and last checks. I didn't even have to look at the status field if its a check-in or
check-out.
So once this data is processed I would have the employee's attendance for the day like
this.
id   |machine_id|date      |status|punchin |punchout|duration|
-----+----------+----------+------+--------+--------+--------+
13579|F157      |2021-08-01|P     |17:28:50|17:28:50|00:00:00|
13661|F157      |2021-08-02|P     |09:37:37|17:27:40|07:50:03|
13744|F157      |2021-08-03|P     |08:02:40|17:28:52|09:26:12|
13940|F157      |2021-08-07|P     |08:07:17|08:07:17|00:00:00|
14569|F157      |2021-08-17|P     |13:22:21|13:22:21|00:00:00|
14757|F157      |2021-08-19|P     |12:13:14|12:13:14|00:00:00|
14848|F157      |2021-08-21|P     |08:06:08|15:33:45|07:27:37|

So anything that is a duration of 00:00 is considered a missing punch.
Great.
Now you see the problem. The management decided to go 24X7 so I have to get the attendance right.
Since I don't have a definite boundary of one day(00:00:00 - 23:59:59) now, the data is continuous.
So How do I get the employee's attendance data? Some employees may come like (9:00 PM - 02:00 AM).
I have developed a simple shifts mechanism so they can assign shifts to employees. But they
are not punctual - so I can't rely on them to make this work. However, something in my gut says it's the only way.
The shifts table looks like this.
employee_id|date      |from    |till    |duration|
-----------+----------+--------+--------+--------+
F157       |2021-08-01|08:00:00|17:00:00|09:00:00|
F157       |2021-08-02|08:00:00|17:00:00|09:00:00|
F157       |2021-08-03|08:00:00|17:00:00|09:00:00|
F157       |2021-08-06|08:00:00|17:00:00|09:00:00|

Here are some of the challenges that I am facing.

*

*Employee may forget to check in or check out or both.

*Employees can do multiple check-in and check-out.

So how can I answer these questions through the query?

*

*How many employees are late today?

*Who are the employees who left early from work yesterday?

*Who has a missing punch?

*Who stayed overtime?

Now I don't have a definite boundary of one day - I just know that I now need to process the data one by one.
So how can I look ahead and behind and identify if this check-out belongs to this day or yesterday ? & if there is a check-in missing or if there are multiple check-ins and so on?
I was not able to find anything to refer to, So if any of you knows any resources that would help also.

Here are some of the details regarding the requirements.

*

*In the ideal case the employee will have only one check-in and one check-out. This is 80% of the scenario and it would be as per the assigned shift without much (about 1/2 an hour tolerance) deviation.

*In case the employee forgot to check out the system should show that the check-out is missing and the effective duration would not be calculated. The check-out and check-in are matched against the shift that is defined in the shifts table that I have provided sample data for.

*In case the employee forgot to check in - this is also the same scenario as check-out.

*In case the employee forgot to check in and check out, that employee would be considered absent for the day.
I hope this answers some of dina's questions.


text:
Q: Multi-platform equivalent to QueryPerformanceCounter? In Windows, I've used QueryPerformanceCounter to measure code performance in microseconds. I would like to do the same in all platforms within Firemonkey. I found one solution, but it's only for C++.
What's the equivalent for all platforms?

A: Use TStopwatch from System.Diagnostics.

*

*On Windows it is implemented with QueryPerformanceCounter.

*On Mac OS it is implemented with mach_absolute_time.

*On POSIX platforms it is implemented with clock_gettime.


text:
Q: Windows 7, Netbeans and svn I used to use Eclipse as IDE for Java programming. Since all my Java projects are located at SVN server, i have used "Subclipse" plugin to access my code. I works fine.
Recently i have decided to switch to Netbeans (faster, more agile, cleaner interface). It has built-in support for SVN, BUT... when i enter my svn credentials (same link, same username and pass as with Subclipse) i can't checkout any project! I get this error message:
org.tigris.subversion.javahl.ClientException: RA layer request failed OPTIONS of 'https://XXXXX': could not connect to server (https://XXXX)

Why? My "Netbeans" is configured to use "system" proxy configuration (i don't have any proxy at all). Same error is shown when i tell netbeans not to use proxy. This issue sure has nothing to do with proxy, otherwise "Subclipse" wouldn't work too, right?

A: I have turned off firewall, restarted my computer and it worked! Strange...
Thank you, anyway! :)

A: *

*What version of NB do you use?

*Make shure SVN client (1.7 in NB 7.2)
and server have same version.

*Is your link correct? Maybe it contains some sepecial characters like %20 If you use normal HTTP, does this work?

*Check the svn configs of NB (by default here: C:\Users\[you]\AppData\Roaming\NetBeans\7.2\config\svn\config for NB 7.2)

*Take a look at NB logs (..\AppData\Roaming\NetBeans\7.2\var\log)

*Tools -> Options -> Miscellaneous -> Versioning -> Subversion what is set as client there?

*Did you set a certificate in the checkout window? For problems with certificates see the workaround here and here


text:
Q: Use Mac OS X dictation on a file? In Mountain Lion, Mac OS X can use its dictation/voice recognition to turn your speaking into text.
Suppose I have an audio file of my voice speaking. Is there a way to use this dictation ability to turn that audio file into a text file?
I suppose the brute force solution would be to plug headphones into the audio port and hold them up to the microphone. Is there a more software-based solution more analogous to Unix pipes?

A: You can install Soundflower. It's a great utility that creates virtual input and output devices. So you could route QuickTime player, for example, as the input for the dictation.
http://cycling74.com/soundflower-landing-page/

A: On Mavericks, you can use the dictation on an audio file if you use Soundflower plus an audio player which allows you to choose the sound output device, such as Audacity. This way you won't be affected by Mavericks muting the system sound output during dictation, because the output will go into Soundflower before it gets muted, and you set the dictation to receive only from Soundflower. This also has the advantage of other sounds that may occur (such as a reminder notification sound) not causing interference. It will also work better than previous Mac OS X versions because the enhanced dictation in Mavericks (which needs to be enabled first) does not cut off the dictation after 30 seconds.
This webpage provides the details on how to use the Mac OS X 10.9 dictation on an audio file:
http://www.leveluplunch.com/blog/2013/12/30/convert-recorded-audio-text-using-osx-dictation-audacity-soundflower/

A: In Yosemite, Whenever we try to use the dictation feature in OSX it mutes other sounds and active only the build-in microfone. You need to set some hidden preferences to make this work. Open Terminal and enter the two commands below:
defaults write com.apple.SpeechRecognitionCore AllowAudioDucking -bool NO

defaults write com.apple.speech.recognition.AppleSpeechRecognition.prefs DictationIMAllowAudioDucking -bool NO

After doing this turn off dictation in Systems Preferences, wait a few seconds and then re-enable it. You should now be able to dictate while audio is playing. I've only tried this while using a headset/headphones, it's probably not advisable without. :)
To restore your system to it's virginal state, run these commands in Terminal and then restart dictation:
defaults delete com.apple.SpeechRecognitionCore AllowAudioDucking

defaults delete com.apple.speech.recognition.AppleSpeechRecognition.prefs DictationIMAllowAudioDucking

A: As of Catalina/Big Sur, the built-in Dictation feature will no longer accept audio from any virtual microphone or system outputted audio. Oddly it often seems to ignore the microphone selected in dictation preferences and just using a different one.
But there's a solution! Just use the Voice Control feature instead of the dictation feature. This happens all offline so the quality is somewhat worse and it's not as consistent as the Dictation feature. This post touches on that topic: https://machow2.com/dictate-offline-catalina/
Reading between the lines, it seems like Apple is trying to prevent their fancy cloud-based speech to text service from being use for automated transcription... Similar to how built in macOS text-to-speech functionality (say) refuses won't output using the high quality Siri voices.

A: If you have Rogue Amoeba's Loopback software, you can create a 'virtual dictation' device and play back audio through it to the Dictation service.
They have a complete guide here, but here's the rundown:

*

*Launch Loopback and create a new 'Virtual Device' named something like Transcription.

*Add your playback app as a source (e.g. Quicktime, Music, Podcasts, whatever).

*In the Keyboard System Preference pane, under Dictation, select your new Transcription virtual device under the microphone as the audio source.

*Open an app that supports dictation like TextEdit.

*Start playing audio from the playback app

*In TextEdit, click Edit > Start Dictation...

I just tested on macOS Monterey and it seemed to work pretty well for my spoken word files.


text:
Q: Use of the & operator in C++ function signatures I'm currently reading through Accelerated C++ and I realized I don't really understand how & works in function signatures.
int* ptr=#

means that ptr now holds the address to num, but what does that mean?
void DoSomething(string& str)

from what I understand that is a pass by reference of a variable (which means passing the address) but when I do
void DoSomething(string& str)
{
  string copy=str;
}

what it creates is a copy of str. What I thought it would do is raise an error since I'm trying to assign a pointer to a variable.
What is happening here? And what is the meaning of using * and & in function calls?

A: A reference is not a pointer, they're different although they serve similar purpose.
You can think of a reference as an alias to another variable, i.e. the second variable having the same address. It doesn't contain address itself, it just references the same portion of memory as the variable it's initialized from.
So
string s = "Hello, wordl";
string* p = &s; // Here you get an address of s
string& r = s; // Here, r is a reference to s

s = "Hello, world"; // corrected
assert( s == *p ); // this should be familiar to you, dereferencing a pointer
assert( s == r ); // this will always be true, they are twins, or the same thing rather

string copy1 = *p; // this is to make a copy using a pointer
string copy = r; // this is what you saw, hope now you understand it better.

A: It's a reference which allows the function to modify the passed string, unlike a normal string parameter where modification would not affect the string passed to the function.
You will often see a parameter of type const string& which is done for performance purposes as a reference internally doesn't create a copy of the string.

A: The & character in C++ is dual purpose.  It can mean (at least)

*

*Take the address of a value

*Declare a reference to a type

The use you're referring to in the function signature is an instance of #2.  The parameter string& str is a reference to a string instance.  This is not just limited to function signatures, it can occur in method bodies as well.
void Example() {
  string s1 = "example";
  string& s2 = s1;  // s2 is now a reference to s1
}

I would recommend checking out the C++ FAQ entry on references as it's a good introduction to them.

*

*https://isocpp.org/wiki/faq/references

A: int* ptr=#

1st case: Since ptr is a memory and it stores the address of a variable. The & operator returns the address of num in memory.
void DoSomething(string& str)

2nd case: The ampersand operator is used to show that the variable is being passed by reference and can be changed by the function.
So Basically the & operator has 2 functions depending on the context.

A: You shouldn't know anything about pointers until you get to chapter 10 of Accelerated C++ !
A reference creates another name, an alias, for something that exists elsewhere. That's it. There are no hidden pointers or addresses involved. Don't look behind the curtain!
Think of a guy named Robert
guy   Robert;

Sometimes you may want to call him Bob
guy& Bob = Robert;

Now Bob and Robert both refer to the same guy. You don't get his address (or phone number), just another name for the same thing.
In your function
void DoSomething(string& str)
{
  string copy=str;
}

it works exactly the same, str is another name for some string that exists somewhere else.
Don't bother with how that happens, just think of a reference as a name for some object.
The compiler has to figure out how to connect the names, you don't have to.

A: In the case of assigning variables (ie, int* ptr = &value), using the ampersand will return the address of your variable (in this case, address of value).
In function parameters, using the ampersand means you're passing access, or reference, to the same physical area in memory of the variable (if you don't use it, a copy is sent instead). If you use an asterisk as part of the parameter, you're specifying that you're passing a variable pointer, which will achieve almost the same thing. The difference here is that with an ampersand you'll have direct access to the variable via the name, but if you pass a pointer, you'll have to deference that pointer to get and manipulate the actual value:
void increase1(int &value) {
   value++;
}

void increase2(int *value) {
   (*value)++;
}

void increase3(int value) {
   value++;
}

Note that increase3 does nothing to the original value you pass it because only a copy is sent:
int main() {
   int number = 5;
   increase1(number);
   increase2(&number);
   increase3(number);
   return 0;
}

The value of number at the end of the 3 function calls is 7, not 8.

A: While pass by reference may be implemented by the compiler by passing the address as a pointer, semantically it has nothing to do with addresses or pointers. in simple terms it is merely an alias for a variable.
C++ has a lot of cases where syntax is reused in different contexts with different semantics and this is one of those cases.

A: In the case of:
int* ptr=#

you are declaring a variable named ptr with a type of an int * (int pointer), and setting its value to the "address of the variable num" (&num).  The "addressof" operator (&) returns a pointer.
In the case of:
void DoSomething(string& str)

you are declaring the first parameter of the DoSomething() method to be of type "reference to string".  Effectively, this is the C++ way of defining "pass-by-reference".
Note that while the & operator operates similarly in these cases, it's not acting in the same way.  Specifically, when used as an operator, you're telling the compiler to take the address of the variable specified; when used in a method signature, you're telling the compiler that the argument is a reference.  And note as well, that the "argument as a reference" bit is different from having an argument that is a pointer; the reference argument (&) gets dereferenced automatically, and there's never any exposure to the method as to where the underlying data is stored; with a pointer argument, you're still passing by reference, but you're exposing to the method where the variable is stored, and potentially exposing problems if the method fails to do a dereference (which happens more often than you might think).

A: You're inexplicitly copy-constructing copy from str. Yes, str is a reference, but that doesn't mean you can't construct another object from it. In c++, the & operator means one of 3 things -

*

*When you're defining a normal reference variable, you create an alias for an object.

*When you use it in a function paramater, it is passed by reference - you are also making an alias of an object, as apposed to a copy. You don't notice any difference in this case, because it basically is the object you passed to it. It does make a difference when the objects you pass contain pointers etc.

*The last (and mostly irrelevent to your case) meaning of & is the bitwise AND.

Another way to think about a reference (albeit slightly incorrect) is syntactic sugar for a dereferenced pointer.


text:
Q: Is it possible to use HTML5's pushState() across multiple domains? I have almost impossible problem, but I am hoping someone could come up with some working solution or workaround.
I have a website where I use History.js to do on-demand page changes to prevent loading full page when clicking on links. My website however has multiple domains, so cross-domain policy doesn't allow change full URL with host, only relative path can be changed/set.
Can anyone help me, how to make use of History.js and overcome cross-domain policy ? However, I can't stop using those multiple domains, so single domain is not solution.
Thanks in advance for any help.

A: That's not possible for a security reason. Allowing cross-domain pushState would allow malicious domains to masquerade as a trusted one.


text:
Q: Is "far from the end" correct? Is it right to say far from the end in the following example?

Researches on the exploitation of the DAS method are far from the end.

A: I think the expression you need is:

*

*far from (being) conclusive. (from TFD)

*

*Serving to put an end to doubt, question, or uncertainty; decisive.

'EPA Evidence on Warming Far From Conclusive'
Source: www.newsmax.com

A: Using complicated double-negatives is an incredibly bad idea in any sort of scientific or engineer writing.
Simply say:
Research on the exploitation of the DAS method have only just begun.

https://www.youtube.com/watch?v=DNPAM5ABhvs
Similar phrases include "it is early days" or "is a new field" or "is a fledgling field" or "is only getting underway."
IF that is what you mean. Try to state exactly what you mean, literally, using quantification.  For example...
"Research on DAS began only in 2012 with about 8 papers published so far." or "Research on DAS should take 10 years, but research has only been underway for 6 months."
Your current sentence tells us nothing, you know?
If you must use a double-negative, just use "far from complete" as Edwin explains.
But note that research tends not to have a "goal", so, it makes little sense (probably) to say anything at all in relation to the "end".  (For example, can you state, what year, it will end?)
So, it's very likely what you are probably trying to say is that it is early days, that it is a new field.
In short
(1) forget about complicated double-negatives in anything scientific
(2) it's extremely unlikely there is actually an "end" relevant
(3) simply, state - accurately, using numbers - what you mean.
For example, note that as a reader I literally do not know what you mean.  in fact I am now curious, how long has this research been going on?  How many people are active, how many papers have been published, what time-scale do you guess for real results?


text:
Q: Why won't my multiple elements draw on html canvas? In firefox, I'm only seeing one of them if I comment out all the others and comment out or uncomment the background, whichever is opposite the last render.  In chromium I can have two of them but they are both just black filled.  I want to be able to call these as functions inside my js file (once working I was planning to add xy-coordinate arguments).  Is this going to be possible, and where should I go to next? The basic idea that I want to accomplish is to be able to draw these colored circles generated by onClick events in certain places on the page.  Is the problem stemming just from using image patterns rather than color fill of am I fundamentally misunderstanding something about how the canvas tag is supposed to be working?
//get canvas and context
var my_board = document.getElementById('canvas');
var my_context = my_board.getContext('2d');

//make red stone pattern
function red_stone(){
    var redpat = new Image();
    redpat.src = 'redpat.png';
    var redfill = my_context.createPattern(redpat, 'repeat');

    my_context.fillStyle = redfill;
    //my_context.fillStyle = '#216263';
    my_context.strokeStyle = '#A9B83D';
    my_context.beginPath();
    //my_context.moveTo(25,25);
    my_context.arc(75,75,50,0,Math.PI*2);
    my_context.fill();
}
red_stone();

function blu_stone(){
    //make blue stone pattern
    var blupat = new Image();
    blupat.src = 'blupat.png';
    var blufill = my_context.createPattern(blupat,'repeat');

    my_context.fillStyle = blufill;
    //my_context.fillStyle = '#216263';
    my_context.strokeStyle = '#A9B83D';
    my_context.beginPath();
    my_context.arc(225,75,50,0,Math.PI*2);
    my_context.fill();
}
blu_stone();


text:
Q: itextsharp error: "The document has no pages." I set as references three dlls:

*

*itextsharp.dll: the core library

*itextsharp.xtra.dll: extra functionality (PDF 2!)

*itextsharp.pdfa.dll: PDF/A-related functionality
This project is hosted on http://sourceforge.net/projects/itextsharp/
You can find the latest release here:
http://sourceforge.net/projects/itextsharp/files/itextsharp/
I get an error when executing this code:
On pdfDoc.Close(), "The document has no pages."
Imports iTextSharp.text
Imports iTextSharp.text.html.simpleparser
Imports iTextSharp.text.pdf

    gv.DataBind()
    gv.AllowPaging = "False"
    Response.ContentType = "application/pdf"
    Response.AddHeader("content-disposition", "attachment;filename=Export.pdf")
    Response.Cache.SetCacheability(HttpCacheability.NoCache)
    Dim sw As New StringWriter()
    Dim hw As New HtmlTextWriter(sw)
    Dim frm As New HtmlForm()
    gv.Parent.Controls.Add(frm)
    frm.Attributes("runat") = "server"
    frm.Controls.Add(gv)
    frm.RenderControl(hw)
    Dim sr As New StringReader(sw.ToString())
    Dim pdfDoc As New Document(PageSize.A4, 10.0F, 10.0F, 10.0F, 0.0F)
    Dim htmlparser As New HTMLWorker(pdfDoc)
    PdfWriter.GetInstance(pdfDoc, Response.OutputStream)
    pdfDoc.Open()
    htmlparser.Parse(sr)
    pdfDoc.Close()
    Response.Write(pdfDoc)
    Response.[End]()

A: The class HTMLWorker is deprecated and should no longer be used. HTML to PDF functionality has been replaced by technology called XML Worker. I see that you include itextsharp.xtra and itextsharp.pdfa which are 2 DLLs you don't need. I don't see you including the xmlworker DLL.
As for the exception: when you get the message "The document has no pages", you are trying to create a document without any content (and that doesn't make sense). How is this possible? Well, it all depends on the content of sr. That content is either empty or it contains HTML that can't be interpreted by HTMLWorker.
Extra remark: next to itextpdf.xtra, you wrote (PDF 2!). While the xtra package contains functonality that didn't exist in PDF 1.7, it's not the PDF 2 package. The PDF 2 specification is to be expected at the earliest by the end of 2015 (a more realistic estimation is 2016). At iText, we've already implemented PDF 2.0 functionality based on the draft of the spec, but that functionality is (1) not limited to what is in the xtra package, and (2) not part of a specification that has been publicly released by ISO yet.


text:
Q: DELETE FROM table WHERE UID = x AND CAT = y I have a very simple table - 3 columns  ID | UID | CAT
I am trying to run a mysql delete to remove the rows where both UID= something AND CAT= something.  But it doesn't work.  How do I do this?
$uid = $_POST['UID'];
$cat = $_POST['CAT'];

mysql_query("DELETE FROM Categories WHERE UID = ".$uid." AND CAT=".$cat."");

A: try this:
mysql_query("DELETE FROM Categories WHERE UID = $uid AND CAT='$cat'");

A: $uid = $_POST['UID'];
$cat = $_POST['CAT'];

mysql_query("DELETE FROM Categories WHERE UID = ".$uid." AND CAT=".$cat."");

VARCHAR need to be escaped
mysql_query("DELETE FROM Categories WHERE UID = ".$uid." AND CAT='".$cat."'");

another hint use mysql_real_escape_string or another form of checking user input
$uid = mysql_real_escape_string($_POST['UID']);
$cat = mysql_real_escape_string($_POST['CAT']);

A: Do you have an active database connection?  If not, you'll need to create one before calling mysql_query().
Other than that, you may be forgetting single quotes in the query:
mysql_query("DELETE FROM Categories WHERE UID = ".$uid." AND CAT=".$cat."");

Should be:
mysql_query("DELETE FROM Categories WHERE UID = ".$uid." AND CAT='".$cat."'");

Assuming CAT is not a numeric column.


text:
Q: ClassCastException when using two Dataframes in a UDF I Am relativley new to both Object Orientend an Functional programming so please forgive me if I am asking a dumb question here. I have searched thoroughly and tried to find answer myself for hours but to no avail.
I am working withh Spark2 on scala an have the following problem.
I have two Dataframes both of which I would like to pass to a UDF which should output one resultant Dataframe. For simplicities sake I have created two "test" dataframes as input.
val seqs = List(("1234","abaab"), ("1235","aaab")).toDF

val actions = List(1,2).toDF

The actions list dataframe will be converted to an Array of Strings e.g.:
val actionsARR = actions.rdd.map(x=>(x.getInt(0)+96).toChar.toString).collect()

We then have a UDF to count the occurances of the actions in the seqs:
def countActions(sequence:String, actions:Array[String]):Array[Int] = {
  return actions.map(x => x.r.findAllIn(sequence).size)
}

put together with :
val results = seqs.map(x=>(x.getString(0), countActions(x.getString(1),actionsARR))).toDF("sequence_u_key","action_counter")

This works fine in the spark shell running one command after the other, I now try to embed the code in a further UDF which will accept Dataframes as input:
def testFun(seqsin:DataFrame, actionsin:DataFrame ): DataFrame ={

seqsin.map(x=>(x.getString(0), countActions(x.getString(1),actionsARR))).toDF("sequence_u_key","action_counter")

}

calling this with :
testFun(seqs,actions).show

works, however it is currently not yet using the Dataframe actionsin but the array allready created from it called actionsARR.
Of course I want it to take the actionsin Dataframe and convert it to the Array within the UDF , so I tried :
def testFun(seqsin:DataFrame, actionsin:DataFrame ): DataFrame ={

val acts = actionsin.rdd.map(y=>(y.getInt(0)+96).toChar.toString).collect()

seqsin.map(x=>(x.getString(0), countActions(x.getString(1),acts))).toDF("sequence_u_key","action_counter")

}

But when I call the function with my dataframes as input I get :

testFun(seqs,actions).show 17/07/19 07:31:32 ERROR Executor: Exception
  in task 0.0 in stage 38.0 (TID 64) java.lang.ClassCastException
  17/07/19 07:31:32 WARN TaskSetManager: Lost task 0.0 in stage 38.0
  (TID 64, localhost, executor driver): java.lang.ClassCastException
17/07/19 07:31:32 ERROR TaskSetManager: Task 0 in stage 38.0 failed 1
  times; aborting job 17/07/19 07:31:32 WARN TaskSetManager: Lost task
  1.0 in stage 38.0 (TID 65, localhost, executor driver): TaskKilled (killed intentionally) org.apache.spark.SparkException: Job aborted
  due to stage failure: Task 0 in stage 38.0 failed 1 times, most recent
  failure: Lost task 0.0 in stage 38.0 (TID 64, localhost, executor
  driver): java.lang.ClassCastException
Driver stacktrace:   at
  org.apache.spark.scheduler.DAGScheduler.org$apache$spark$scheduler$DAGScheduler$$failJobAndIndependentStages(DAGScheduler.scala:1435)
  at
  org.apache.spark.scheduler.DAGScheduler$$anonfun$abortStage$1.apply(DAGScheduler.scala:1423)
  at
  org.apache.spark.scheduler.DAGScheduler$$anonfun$abortStage$1.apply(DAGScheduler.scala:1422)
  at
  scala.collection.mutable.ResizableArray$class.foreach(ResizableArray.scala:59)
  at scala.collection.mutable.ArrayBuffer.foreach(ArrayBuffer.scala:48)
  at
  org.apache.spark.scheduler.DAGScheduler.abortStage(DAGScheduler.scala:1422)
  at
  org.apache.spark.scheduler.DAGScheduler$$anonfun$handleTaskSetFailed$1.apply(DAGScheduler.scala:802)
  at
  org.apache.spark.scheduler.DAGScheduler$$anonfun$handleTaskSetFailed$1.apply(DAGScheduler.scala:802)
  at scala.Option.foreach(Option.scala:257)   at
  org.apache.spark.scheduler.DAGScheduler.handleTaskSetFailed(DAGScheduler.scala:802)
  at
  org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.doOnReceive(DAGScheduler.scala:1650)
  at
  org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.onReceive(DAGScheduler.scala:1605)
  at
  org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.onReceive(DAGScheduler.scala:1594)
  at org.apache.spark.util.EventLoop$$anon$1.run(EventLoop.scala:48)
  at
  org.apache.spark.scheduler.DAGScheduler.runJob(DAGScheduler.scala:628)
  at org.apache.spark.SparkContext.runJob(SparkContext.scala:1918)   at
  org.apache.spark.SparkContext.runJob(SparkContext.scala:1931)   at
  org.apache.spark.SparkContext.runJob(SparkContext.scala:1944)   at
  org.apache.spark.SparkContext.runJob(SparkContext.scala:1958)   at
  org.apache.spark.rdd.RDD$$anonfun$collect$1.apply(RDD.scala:935)   at
  org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:151)
  at
  org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:112)
  at org.apache.spark.rdd.RDD.withScope(RDD.scala:362)   at
  org.apache.spark.rdd.RDD.collect(RDD.scala:934)   at
  testFun(:44)   ... 52 elided Caused by:
  java.lang.ClassCastException

Maybee I am doing something fundamentatly wrong by trying to pass two Dataframes to a function , coverting one to an array and then using them in the function ? or maybee I am missing something simple ?
Oh, I can succesfully create a function that takes a single Dataframe and converts and returns this as an array.
Any help would be appreciated
Best Regards
James


text:
Q: Помогите, пожалуйста, с jquery Всем привет, всегда находил ответы в инете на свои вопросы, сейчас не могу. В общем так: есть количество товара редактируемое кнопками + и -, количество находится в type="text", нужно сделать так чтобы при количестве 1 кнопка - была недоступна, а для количества >1 доступна. Для 1 записи я решил так
$('#plus').click(function(){
    val=parseInt($('#kolichestvo').val());
    val2= val + 1;
    $('#kolichestvo').val(val2);

    if (val2>1){ $('#minus').removeAttr('disabled'); }
});

$('#minus').click(function(){
    val=parseInt($('#kolichestvo').val());
    val2= val - 1;
    $('#kolichestvo').val(val2);
    if (val2<=1){ $('#minus').attr('disabled','disabled'); }

});
<button id="minus" disabled>-</button>
<input type="text" value="1" id="kolichestvo" disabled>
<button id="plus">+</button>

а как сделать если у меня потом количество и каждая кнопка выводится циклом из БД, то есть так
do {

echo <button id="minus">-</button><input id="kolichestvo" type="text" value="'.$data['kolichestvo'].'" disabled size="1"><button id="plus">+</button></td> } while ($data=  mysql_fetch_assoc($zapros));

нужно чтобы кнопки + и - работали только с тем полем, которое выводится вместе с ними. Спасибо.
A: Привязку можно реализовать так, так же как и статус кнопки ещё на выводе.
<?php

do {
    if($data['kolichestvo']==1)$button_state = 'disable';
print(
        '<button id="minus" target="'.$data['id'].'" '.$button_state.' >-</button>'.
        '<input id="kolichestvo" type="text" name="'.$data['id'].'" value="'.$data['kolichestvo'].'" size="1">'.
        '<button id="plus"target="'.$data['id'].'" >+</button>'.
);
    echo
}while ($data=  mysql_fetch_assoc($zapros));

И соответственно потом в JS обрабатывать.
$('#minus').click(function(){
    var id = this.getAttr('target'); //точно не помню имя функции.
    var val = parseInt($('#kolichestvo [name='+id+']').val())-1;
    $('#kolichestvo [name='+id+']').val(val);
    if(val==1){
        this.attr('disable','true')
    }
});

$('#plus').click(function(){
    var id = this.getAttr('target');
    var val = parseInt($('#kolichestvo [name='+id+']').val())+1;
    $('#kolichestvo [name='+id+']').val(val);
    if(val!=1){
        $('#minus [target='+id+']').removeAttr('disable')
    }
});


text:
Q: Need help writing an xpath string to match multiple, but not all, table cells Note: The question has been updated since some of the early answers were given. It's still the same question, just hopefully clearer.
I'm trying to get a site scraper working properly and I'm having problems coming up with a suitable xpath string for some table cells.

    Uninteresting section
     I don't care about this

     I don't care about this

    Interesting section
     I want this-1

     I want this-2

     I want this-n

    Uninteresting section
     I don't care about this

     I don't care about this

I want the contents of all the Data fields in the interesting section.
There can be an arbitrary number of these. I don't care about anything else in the code, but I need all these.
In the example above:
 I want this-1
 I want this-2
 I want this-n
If it's relevant, I'm using xml.dom.minidom and py-dom-xpath with Python 2.7.

A: You can get all the n tds after the section (including other sections) with
 //tr[@class="Entry"]//tr/td[contains(text(), "Section title")]/following::td[@class = "Data"]/text()

Then you can get all the m tds of the next sections that you don't want with
//tr[@class="Entry"]//tr/td[contains(text(), "Section title")]/following::td[@class="Label"][1]/following::td[@class = "Data"]/text()

and then you can use in Python the first n - m tds.
You could try to do the same in XPath with the position and count functions:
  //tr[@class="Entry"]//tr/td[contains(text(), "Section title")]/following::td[@class = "Data"][position() <= (count(//tr[@class="Entry"]//tr/td[contains(text(), "Section title")]/following::td[@class = "Data"]/text())  - count(//tr[@class="Entry"]//tr/td[contains(text(), "Section title")]/following::td[@class="Label"][1]/following::td[@class = "Data"]/text()) )]/text()

And if you had XPath 2.0 you could do it elegant with the except operator:
 //tr[@class="Entry"]//tr/td[contains(text(), "Section title")]/following::td[@class = "Data"]/text() except  //tr[@class="Entry"]//tr/td[contains(text(), "Section title")]/following::td[@class="Label"][1]/following::td[@class = "Data"]/text()

A: //tr[@class="Entry"]/td[@class="Data"]/text()

A: //tbody[tr/td[contains(text(),"Section title")]]/tr/td[@class="Data"]/text()

Updated. What this does:

*

*Get tbody with tr with td that contains "Section title"

*From those get texts of each td with class="Data"


text:
Q: Decomposition with given closures Let $(X,\mathcal T)$ be a topological space. About the subsets $A,B,C$ of $X$ it is known that $$\mathrm {cl} (C)= A \cup B\,, \quad \mathrm {cl} (A) = A\,, \quad \mathrm {cl} (B) = B\,.$$
Does it always imply that there exist two subsets of $X$, $C_A$ and $C_B$ such that $$C = C_A \cup C_B\,, \quad \mathrm {cl} (C_A) = A\,, \quad \mathrm {cl} (C_B) = B \; ?$$
If this is not true in general, is it true at least for Euclidean spaces?


text:
Q: I can't order the controls i make a windows where i can create a new user, but i cant order the internal controls.
Code example:

            <%--Boton close--%>

                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Formulario de clientes

                    Nombre:
                    <input type="text" class="form-control" id="inputInsertName" placeholder="Ingrese su Nombre">

                    Apellido:
                    <input type="text" class="form-control" id="inputInsertApellido" placeholder="Ingrese su Apellido">

Can i help me with this?

A: I think you're trying to align the controls within your BootStrap Modal window. Place all your body controls within
. Here is the link to the working Demo
 Refer here for more details.
Here is the code

        <button type="button" class="close" data-dismiss="modal">×Close</button>

Formulario de clientes

             Nombre:
             <input type="text" class="form-control" id="inputInsertName" placeholder="Ingrese su Nombre">

             Apellido:
             <input type="text" class="form-control" id="inputInsertApellido" placeholder="Ingrese su Apellido">

        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>


text:
Q: How to read variables from CSV in terraform I am having a CSV file with few values.
I want to read that values into variables in terraform.
I have used giving locals with file path . But it shows path not found. How can I read variables from CSV in terraform.
I am having my git structure like below.

where Key_vault folder is having my terraform codes.And adf_confg is having my csv file.
my main.tf is like this.

I am getting error: Invalid value for "path" parameter: no file exists at ./adf_config/datasets.csv; this function works only with files that
│ are distributed as part of the configuration source code, so if this file will be created by a resource in this
│ configuration you must instead obtain this result from an attribute of that resource

A: If your Terraform module is in the Key_Vault directory and your CSV file is in adf_config then the path from the Terraform module to the CSV file must start with ../ to traverse to the parent directory.
I would also typically suggest using path.module to be explicit that we're writing a path relative to the current module, although when your module is the root module it doesn't really make any difference because path.module will always be . (the current directory) in that case. Using path.module can help with refactoring this configuration into a child module later though, since it will already be clear what this path is relative to.
locals {
  datasets = csvdecode(file("${path.module}/../adf_config/datasets.csv"))
}


text:
Q: Normal And UpsideDown Triangle of stars in C++ I need to create a upsidedown triangle and a normal triangle and it should look like this:
***********
 *********
  *******
   *****
    ***
     *
     *
    ***
   *****
  *******
 *********
***********

I created something but I get 5 new lines and than the other triangle:
***********
 *********
  *******
   *****
    ***
     *

     *
    ***
   *****
  *******
 *********
***********

Here is the C++ code , Hope someone can resolve my issue :
int n,i,j;

cout<<"Give the Number N of Stars ";
cin>>n;

for(i=1; i<=n; i++)
{
    for(j=1;j<=i-1;j++)
        cout<<" ";
     for(j=i;j<=n-i+1;j++)
        cout<<"*";
     cout<<"\n";
}

for(i=1;i<=n;i++)
{
    for(j=i;j<=n-1;j++)
        cout<<" ";
    for(j=1;j<=2*i-n;j++)
        cout<<"*";
    cout<<"\n";
}

A: Your outer loop is making i go from 1 to n (which means n rows), but there are less than n rows since each row, the number of stars decreases by 2, not 1. The extra lines are the result of this. There are no stars in the extra lines because in this loop:
for(j=i;j<=n-i+1;j++)
    cout<<"*";

once i exceeds half the size of n, the loop will not print any stars, since the initial value of j is greater than the terminating condition for j.


text:
Q: Module '@google-cloud/firestore' is not listed as dependency in package.json I am using TypeScript for writing my Firebase Cloud Functions. In my code I need to refer firestore data types like CollectionReference, QuerySnapshot etc. For example:
export const Employee: CollectionReference = admin.firestore().collection('Master/Admin/Employees');
or
async function convertToCsv(snapshot: QueryDocumentSnapshot[])

To use these types in my code, I am using the following lines on the top of the file (.ts):
import { QueryDocumentSnapshot, Timestamp, Query, CollectionReference } from '@google-cloud/firestore';

This code works fine when I run firebase function locally on my PC using:

firebase serve --only functions

But when I try to deploy the same code on my firebase server, I get the following tslint error and code deployment fails.
Module '@google-cloud/firestore' is not listed as dependency in package.json

if I add the dependency in package.json
"dependencies": {
    "body-parser": "^1.18.3",
    ...
    "@google-cloud/firestore": "~1.0.1"
  },

My functions get deployed, but on execution, I get the following error:
Error: Argument "value" is not a valid QueryValue. Detected an object of type "Timestamp" that doesn't match the expected instance. Please ensure that the Firestore types you are using are from the same NPM package.
    at Validator.(anonymous function).err [as isQueryValue] (/user_code/node_modules/firebase-admin/node_modules/@google-cloud/firestore/build/src/validate.js:93:27)
    at Query.where (/user_code/node_modules/firebase-admin/node_modules/@google-cloud/firestore/build/src/reference.js:916:25)
    at /user_code/lib/services/reports/index.js:53:22

The compiled java script line where it fails is (see **):
const firestore_1 = require("@google-cloud/firestore");
let query = collection
                    .where('divisionCode', '==', divisionCode)
                    **.where('zzLastUpdateOn', '>=', firestore_1.Timestamp.fromDate(startDate))**
                    .where('zzLastUpdateOn', '<=', firestore_1.Timestamp.fromDate(endDate))
                    .where('zzIsDeleted', '==', false);

I really have no clue what to do here, please help. Please know I am very new to TypeScript and JavaScript world.

Please know that other functions in a same project, where i am adding value into Timestamp field is working fine. And this function also works fine in Cloud Function simulation mode on desktop (local host).

Your help will be appreciated!!!

A: The following change in my code has helped to clear the problem.
Instead of using the "Timestamp", I am now using "firestore.Timestamp". This change has helped me move further in my development.
Now my code looks like this:
TypeScript Code:
let query: Query = collection
                .where(...)
                .where('zzLastUpdateOn', '>=', firestore.Timestamp.fromDate(startDate))
                .where('zzLastUpdateOn', '<=', firestore.Timestamp.fromDate(endDate))
                .where(...);

And Generated Java Script Code:
let query = collection
                    .where(...)
                    .where('zzLastUpdateOn', '>=', firebase_admin_1.firestore.Timestamp.fromDate(startDate))
                    .where('zzLastUpdateOn', '<=', firebase_admin_1.firestore.Timestamp.fromDate(endDate))
                    .where(...);

My sugestion is based on https://stackoverflow.com/a/52609487/6943737 query.


text:
Q: PuTTY and PowerTerm scripting Problem, Open a just in time URL via Samba share I'm sshing into a fedora server using Powerterm (an expensive overly priced, license based, terminal emulator). The server uses an ancient form of (what I'm told is similar to) cobalt. I have no control over the server's programming but I'd like at least to not have to pay hundreds of dollars for a PuTTY like terminal emulator every time Windows changes their OS.
The software on the server is capable of building spreadsheets and exporting to Excel on a Windows machine via a samba share, but I can't seem to get that to work using PuTTY. I've logged the hidden command that the server sends to PowerTerm and it looks like this
_[P$sExcel.psl "\\serverFQDN\user\spdsht123.xls"_[\

and this was logged in the SSH in/out along with octal stuffs
.......1.[1;1H.P

$sExcel.psl "\\s

erverFQDN\user\s

pdsht123.xls".\

The file gets built but doesn't run, understandably, b/c nothing is scripted on PuTTY to listen for that specific character/string (not sure which is which). There are 2 files on the server that may also come into play somewhere but I can't see the code so I'm just guessing, or possibly just a copy in case someone were to delete them.
[me@erver PSL]$ cat excel.psl
exec "excel.exe $p1"
[me@erver PSL]$ cat PT.psl
exec "$p1"

Putty Settings
SSH -p22
Backspace Key - Control-H
FKeys and Keypad - SCO
Translation is Default Latin-1, West Europe ISO-8859-1:1998
Terminal-type string sends ansi

Initially I thought I could forward and tunnel the smb ports but since the filename is sent by the server live at that minute I'd have to script PuTTY to listen for a specific string ie. _[P$sExcel.psl and open the file using the default windows program associated with the URL. Then I noticed that PuTTY doesn't support this and I've tried countless PuTTY forks to no avail.
Any help would be appreciated.

A: These PSL files are specific to PowerTerm Pro so you're unlikely to get them to work with anything except that product.
http://www.filesuffix.com/en/extension/psl
Basically what happens is the PSL file is pushed through the PowerTerm shell to your local computer where the command(s) inside it are executed locally on your computer. This command:
$sExcel.psl "\\s

erverFQDN\user\s

pdsht123.xls".\

Is actually doing this:
exec "excel.exe \\serverFQDN\user\spdsht123.xls"

So what are your options?
1. open the file manually
This runs Excel and then tells it to open the file at \\serverFQDN\user\spdsht123.xls.
You can manually go to this path and just run these files yourself in Windows Explorer:
\\serverFQDN\user\spdsht123.xls

2. This isn't possible in PuTTY
This capability will apparently never be implemented in PuTTY. It's discussed here in this post titled: Escape sequence to execute command on the client side.
3. DoIt
You can use a tool called DoIt which you can use in a similar fashion to PowerTerm. You can read more about it here. DoIt is classified as a remote-execution daemon for Windows.


text:
Q: Command '"export' not found when starting a terminal app in Ubuntu Every time I start my terminal I get this message; how to get rid of it?
Command '"export' not found, did you mean:
  command 'mexport' from deb mblaze (0.6-1)
Try: sudo apt install <deb name>

A: I wondered why your machine did not have the export command... then I noticed that your error message actually says "export. Your post was not code-formatted at first so the quotation mark was hard to spot.
You have a typo in your ~/.bashrc or your  ~/.bash_profile file: "export where it should be export or "export.  Fix it and the error should be gone.
Similar questions:

*

*How to get rid of this: "[-f: command not found" in terminal?

*How to avoid "bash: q: command not found" every time I 'su'?

Note: The shape of the quotation marks - " instead of " - tells me that you probably copy-pasted the line from some document or webpage, or you edited the file with a word processor that adds fancy quotes, as @Kusalananda said in the comments. You have always to be careful about the formatting, as word processors often perform "smart" character substitution, mangling your code in the process; an infamous example is --someoption being transformed into —someoption (the two hyphens having been replaced with a mdash).


text:
Q: Open tab in background and get data from it - Chrome extension Can someone can give me how to open an url in background and how can I get data from it. The URL that I want to open is in a page that also I get data from it. I use XPath to get data.
This is my code :
Popup.js
chrome.tabs.query({
active: true,
currentWindow: true }, function(tabs){
if(tabs[0].url.indexOf("extranet.louvre-hotels.fr")!=-1)
{
    chrome.tabs.sendRequest(tabs[0].id, {
        action: "getDOM"
    }, function(response)

    {
        chrome.tabs.getSelected(null, function(tab) {
    // get response
        });
    });
}

});
Manifest.json
{
"manifest_version": 2,

"name": "SymaExtract",
"description": "SymaExtract",
"version": "1.0",
"browser_action": {
    "default_icon": "icon.png",
    "default_popup": "popup.html"
},
"permissions": [
    "webNavigation",
    "tabs",
    "background",
    "http://localhost/extract.php",
    "http://*/*"

],
"background": {
    "scripts": ["background.js"]
},
"content_scripts": [
{
  "matches": ["http://*/*"],
  "js": ["dom.js"]
}

]
}
Background.js
chrome.tabs.create({url: 'url_that_i_want_to_open'});

A: What do you mean by "open the tab in the background"?
Do you want to hide the fact from the user that some kind of page fetching is happening in the background? If so, I think its not possible with current Chrome extension APIs.
Please check this question: How to fetch javascript heavy pages from chrome extension
I faced the same problem a few months ago.
If you don't care whether user notices that a new tab/window is opened, then just create new tab and do not set focus on it. Doing so is straightforward, check the extension documentation.
BTW, in my opinion, Xpath is not the way to go. I think CSS is better suited to parse the data.
Also check this recent answer: Chrome extension: How to open a link in new tab?


text:
Q: flex items overlapping in Safari (iPad) I cannot solve problem with simple task:

*

*Container is 100% width but with padding-right and box-sizing overflow

*Container is flex row

*Container has two children with dynamic content

*First child has size of content

*Second child takes the rest of width

Expected result:

iPad result:

Example is https://codepen.io/anon/pen/zaMwvr

#wrap {
  width: 100%;
  border: 1px dashed orangered;
  box-sizing: border-box;
  padding-right: 300px;
  position: relative;
}

#padding-view {
  width: 300px;
  position: absolute;
  background: coral;
  right: 0;
  height: 100%;
}

#flex {
  display: flex;
}

LALALCALCULATEDDYNAMICLY

{Long text here}

A: Try adding flex-shrink: 0 or min-width: auto to .dynamic (revised codepen).


text:
Q: Flutter - Unable to save data to Firebase Firestore I'm building an app with Flutter. On the registration page I create account with Auth and try to save user's information with Firestore. User account is created with Auth but I cannot open a document for user information in Firestore.
My codes:
await _auth.createUserWithEmailAndPassword(
  email: _emailController.text,
  password: _passwordController.text,
);
inspect("user ID: " + _auth.currentUser!.uid);
_firestore.collection("Users").doc(_auth.currentUser!.uid).set({
  "ID": _auth.currentUser!.uid,
  "Email": _emailController.text,
  "Phone": _phoneController.text,
  "Name": _nameController.text,
  "Surname": _surnameController.text,
  "Photo": "https://firebasestorage.googleapis.com/v0/b/teen-software-stock-tracking.appspot.com/o/default.jpg?alt=media&token=0eec2e1f-2ccf-4bda-8664-3d3f018621b3",
  "Level": 0,
  "ProductRight": 10,
  "AddedProduct": 0,
  "AccountCreate": FullDate.toString(),
});
_auth.signOut();

Why could this be? I would be glad if you help. Thanks in advance for your help.

A: Try await on storing the data to Firestore.
await _firestore.collection("Users").doc(_auth.currentUser!.uid).set({
  "ID": _auth.currentUser!.uid,
  "Email": _emailController.text,
  "Phone": _phoneController.text,
  "Name": _nameController.text,
  "Surname": _surnameController.text,
  "Photo": "https://firebasestorage.googleapis.com/v0/b/teen-software-stock-tracking.appspot.com/o/default.jpg?alt=media&token=0eec2e1f-2ccf-4bda-8664-3d3f018621b3",
  "Level": 0,
  "ProductRight": 10,
  "AddedProduct": 0,
  "AccountCreate": FullDate.toString(),
});


text:
Q: Resize images in div if the div has no text but only one or two images I am trying to build a chat application, so i came across this little problem:
This is a div element with text and an image which will be styled normally

lets try that again shall we

This is a div element with an image and no text, since there is only one image i want to style the size of that image

just like this
My first question on stack overflow, be nice thanks!

A: I have added the code, which picks up all the nodes in the DOM with the class name msg checks for the condition (the one you specified in the question) and modifies the only img messages.

const arr = document.getElementsByClassName('msg');
for (let i = 0; i < arr.length; i++) {
  if (arr[i].innerText.length === 0 && arr[i].children.length == 1 && arr[i].children[0].classList.contains('emojione')) {
    arr[i].children[0].classList.add('big-img');
  }
}
.big-img{
  transform: scale(1.5)
}

  lets try that again shall we