text:
Q: async.waterfall stops executing consecutively after a timeout Right now my code has a structure like this:
 async.waterfall([
    function(callback){
         if(someCondition1) {

            //do something

            if(someCondition2)){

                result1 = something

                var timeout = null;
                timeout = setTimeout(function(){
                    //do something
                    result1 = newValue;

                },timeout);
            }

            else{
                // do something
                result1 = something;
            }
         }
         else {
            //do something
            result1 = something;

         }
        callback(null,result1);
    },
    function (result1, callback) {
           //do something
           result2 = something;
           callback(null,result2);

    },
    function (result2, callback){
          //do something

    }], function (err,result) {
});

I want to implement a timeout in the first function of waterfall. My intention is that the code will parse the variable result1 into the second waterfall function in the first attempt. When timeout, the code will check the variable result1 again and overwrite it with a new value if necessary, then parse this new result1 to the second function again and run one more time.
With my current implementation, when not timeout, the code executes normally. However, after getting the new value for result1 when timeout, the code stops right away and does not execute the rest functions of waterfall with the new result1 value. Is there a way I can achieve the intended behavior? Many thanks in advance.
EDIT:
I tried the suggestion from the answer. Right now the code looks like this:
async.waterfall([
    function(callback){
         if(someCondition1) {

            //do something

            if(someCondition2)){

            //I want to return this result1 before timeout
                result1 = something;

                var timeout = null;
                timeout = setTimeout(function(){
                    //do something
                    result1 = newValue;
                    callback(null,result1);
                },timeout);
            }

            else{
                // do something
                result1 = something;
                callback(null,result1);
            }
         }
         else {
            //do something
            result1 = something;
            callback(null,result1);
         }

    },
    function (result1, callback) {
           //do something
           result2 = something;
           callback(null,result2);

    },
    function (result2, callback){
          //do something

    }], function (err,result) {
});

I want to callback the result1 before timeout, and after timeout it will callback the new result1 value. If I keep the code like above, the code will obviously wait until timeout and return only the new result1 value. However, if I put result1 in callback before timeout, then I will face the error "Callback was already called" when the timeout expires, and it cannot return the new value in timeout block.

A: async.waterfall is "one pass" only. The callbacks are not meant to be called multiple times.
The fix is to only call the callback() in the first function once. You can put it in each of your if-blocks, and in the case of someCondition2 you put the callback inside the timeout().
So long as it is not double-called it is a valid waterfall, and putting it inside the timeout will "wait" until the timeout runs before progressing along the waterfall.


text:
Q: How do I configure metric beat to report disk errors? The journald log is reporting:
Jul 22 09:39:26 zora kernel: sd 3:0:0:0: [sdd] tag#14 FAILED Result: hostbyte=DID_OK driverbyte=DRIVER_SENSE
Jul 22 09:39:26 zora kernel: sd 3:0:0:0: [sdd] tag#14 Sense Key : Medium Error [current]
Jul 22 09:39:26 zora kernel: sd 3:0:0:0: [sdd] tag#14 Add. Sense: Unrecovered read error - auto reallocate failed
Jul 22 09:39:26 zora kernel: sd 3:0:0:0: [sdd] tag#14 CDB: Read(16) 88 00 00 00 00 00 6a 35 61 50 00 00 02 60 00 00

Are there any MetricBeat modules that can be used to report this? I'd like to get a report on the number of disk errors over a period of time.
Thanks!

redpajama_set_name: RedPajamaStackExchange


text:
Q: jQuery toggle() method to hide table row not working My problem is best explained by looking at my fiddle. On load, everything is working a expected, however, when you change the dd to Dos, the only row that should show, is the dos toggle row. Currently, both Uno Toggle & Dos Toggle are being shown.
I have a constraint that I cannot use classes, so I am trying to use jQuery's :eq() selector, but I'm having issues figuring out which index number the second tr object is.
Here's my jQuery code, since it won't let me share the fiddle without showing some code.
Any help is appreciated.
 $(document).ready(function () {
$("select[title='Numero']").closest("tr").next("tr").hide(); //commented out for debugging

 $("select[title='Numero']").change(function () {
     $("select[title='Dos Toggle']").closest("tr").closest("tr:eq(1)").toggle(); //dos toggle row
     $("select[title='Uno Toggle']").closest("tr").closest("tr:eq(2)").hide();
     //$("select[title='Uno Toggle']").closest("tr").closest("tr:eq(2)").toggle(); //this is original toggle code that didn't work.
 }); //close Numero.change()
 }); // close doc.ready

A: With what you have, you could just do:
 $("select[title='Numero']").change(function () {
     $(this).closest("tr").nextAll('tr').toggle();
     //Or to be more specific not to select any other trs if at all comes after these 2 you could do the below.
     //$(this).closest("tr").nextAll('tr:lt(2)').toggle();
 });

Demo

A: I'm betting this is for a SharePoint list form...
Here is how I have targeted rows on SharePoint forms in the past, and it works in your fiddle.... DEMO
$(document).ready(function () {
     $("nobr:contains('Dos Toggle')").parent('h3').parent('td').parent('tr').toggle();

     $("select[title='Numero']").change(function () {
         $("nobr:contains('Uno Toggle')").parent('h3').parent('td').parent('tr').toggle();
         $("nobr:contains('Dos Toggle')").parent('h3').parent('td').parent('tr').toggle();
     }); //close Numero.change()

 }); // close doc.ready

A: I would start by putting css classes on the rows you're trying to show and hide. That way, you can toggle them both by just doing something like $(".numero-toggle").toggle(); inside your change function. The markup and method you're currently trying is very brittle, and if things move around or the markup changes, it will likely break.

A: So here is what I came up with using the :eq() element after all of the great contributions I recieved-
$("select[title='Numero']").change(function () {
 $("select[title='Dos Toggle']").closest("tr").closest("tr:eq(1)").toggle(); //dos toggle row
 $("select[title='Uno Toggle']").closest("tr").closest("tr:eq(3)").toggle(); //uno toggle row
}); //close Numero.change()

However, I could never get this code to toggle in SharePoint the way I wanted it to...so I ended up using @Schmalzy's suggestion-
$("select[title='Numero']").change(function(){
            $("nobr:contains('Dos')").parent("h3").parent("td").parent("tr").toggle();
            $("nobr:contains('Uno')").parent("h3").parent("td").parent("tr").toggle();
}); //close

Thanks for your help!


text:
Q: When should connect components to redux in react? For example, i have a structure of components like this:
<Parent>
      <Child_1>
            <InnerChild_1 />
      </Chidl_1>
      <Child_2>
            <InnerChild_2 />
      </Chidl_2>
</Parent>

Component <Parent> connected to redux. What a better way to update <InnerChild_1 /> with application state, send this data from <Parent> with props  or connect <InnerChild_1 /> to redux ? If connect, should i connect all my components, that's using state, to redux?

A: You should always try to use as little redux in your application as possible, in my experience. As a rule of thumb, always opt for passing props down the component chain as opposed to dispatching actions in child components. To me, redux truly shines when you need to share state across multiple container components. A typical use case is authentication/user data in an e-commerce app. In your situation, I can safely say connecting your child component would simply result in unnecessary indirection.

A: Despite every other answer stating that you should connect your top level, that's indeed an old recommendation that is only useful for very simple applications.
Use connect wherever you need to keep a component synchronized with the Redux store. In your example, if <Parent /> is not using any state and its role is merely compositional, I wouldn't connect that one. I would keep Parent a standard React component, and connect the child items individually.
For big lists or complex data structures with nested entitites, that's the way to go.
If you choose the other way, and connect at your top-most component, then any state change will cause a full re-render of your component tree, with no automatic optimization. Because connected components will implement shouldComponentUpdate for you, you'll normally get much better performance connecting multiple items to the store instead of connecting a "list" parent and re-render every item on every change.
See the React-Redux FAQ in the Redux docs:
http://redux.js.org/docs/faq/ReactRedux.html#react-multiple-components
Specifically:

Early Redux documentation advised that you should only have a few
  connected components near the top of your component tree. However,
  time and experience has shown that that generally requires a few
  components to know too much about the data requirements of all their
  descendants, and forces them to pass down a confusing number of props.

A: IMHO better use connect for Containers rather than for Components.
Container holds the Components. So connect the redux state to Container which in turn sends the state to Components as props.
In your case you can assume  <Parent /> as Container and rest of children as Components.

A: You can use either a spread operator (...props) or context.
Via spread would look like this:
<InnerChild_1
    {...this.props}
/>


text:
Q: Write a function named process_line that accepts a not -ve integer as input.Find no. of integers, their sum and product and Return the tuple (N,S,P) Write a function named process_line that accepts a non-negative integer — i — as input. Find the following information about line-i in the file:
(1) N: number of integers in the line
(2) S: sum of all integers in the line
(3) P: product of all integers in the line
Return the tuple (N, S, P).
If i is greater than or equal to the number of lines in the file, return the tuple (-1, -1, -1). Zero-based indexing is used. So, i = 0 corresponds to the first line in the file, i = 1 the second line and i = n - 1 corresponds to the last line in a file of n lines.
This is the question, I have to write the fuction:
def process_line(n):
    x = open('numbers.txt','r')
    current_line=0
    N=0
    S=0
    P=1
    for lines in x:
        if current_line == n:
            for terms in lines:
                if terms!=',':
                    N=N+1
                    S=S+int(terms)
                    P=P*int(terms)
                else:
                    pass
            break
        current_line=current_line+1

    return((N,S,P))

A: It depends how numbers.txt is laid out. You'll need something like the following (code could be shorter but this clearly shows where loops are happening):
def process_line(n):
    line = None
    with open('numbers.txt') as input_file:
        for line_number, line_content in enumerate(input_file):
            if line_number == n:
                line = line_content
                break
    if line is None: return (-1, -1, -1)
    N, S, P = (0, 0, 1)
    for character in line.split(): # this line may need to change
            integer = int(character)
            N += 1
            S += integer
            P *= integer
    return (N, S, P)

The line with the comment currently splits a series of integers of any number of digits, separated by spaces. Passing a particular separator to that function will make it split on commas or similar if that's what you need. If the numbers are weaved throughout a line of otherwise unstructured nonsense (unlikely, but possible given we have no context), you can check if character.isdigit() for each character but then integers with more than one digit will need to be sorted together somehow.

A: def process_line(i):

    c,s,p=0,0,1 #this sets the variables. for products we need default to be 1
    mfile = open('numbers.txt','r')
    x = mfile.readlines()
    if len(x)>=i and i>=0:
        line = x[i]
        for i in line:
            if(i.isnumeric()):
                c+=1
                s+=int(i)
                p*=int(i)
        return (c,s,p)
    else:
        return (-1,-1,-1)

c : the number of integers
s : sum of integers
p : product of integers
x = mfile.readlines()
if len(x)>=i and i>=0:

This line reads all the lines from text file and stores it as a list and the if statement checks if the value of i is less than number of lines in file and if its greater than 0(we dont need negative numbers)
if(i.isnumeric()):

this eliminates all the commas and reads only the integers.
Hope you can understand the above and rest. All the best for 1st Aug.


text:
Q: Base live update in Postgres Base live update in Postgres
Hello guys.
I have a Postgres database where I create my dataframe.
So my graphics work, my calculations work, almost everything is beautiful.
The only problem is that if the database changes I need to stop the Flask service and restart, only then my dashboard is updated.
I tried a lot before coming back here with this answer.
I'm taking a beating with update database.
I can't get dash to update my charts and tables by itself.
I tried on other forums but was not successful.
I'll post my code here updated and minimized.
There will be two links to the drive, one with the postgres database and the other with the code.
the code is relatively small the part that doesn't work properly.
I will send you two links:
1 - Containing the complete code:
https://drive.google.com/file/d/1c0e8UelUgGVx_IrWLFncwc2JRPraUS79/view?usp=share_link
I have a few observations for this code to work:
a) Install the libraries highlighted in the teste.py file before the imports.
b) The database access configuration I made in a file called pg_config.json, just edit and inform your bank credentials.
2 - Containing the Postgres database:
https://drive.google.com/file/d/1Fwrc0xAMfVnv0_lUSHjNTO3HnQIkUvHN/view?usp=sharing
teste.py is a table that gets information from df_data_generals

A: I did something like below with mysql. Please refer it and check does it match your requirment.
    dcc.Store(id='store-data', data=[], storage_type='memory'), # 'local' or 'session'
    dcc.Interval(id='update', n_intervals = 0, interval=1000*30)
])

@app.callback(Output('store-data','data'),
             [Input('update', 'n_intervals')])

def update_data(n):
    global jobs_2
    db = mysql.connector.connect(
        host="localhost",
        user="root",
        password="",
        database="indeed_data_dump")

    cur = db.cursor()
    cur.execute("SELECT * FROM jobs")
    columns = [col[0] for col in mycursor.description]
    data = mycursor.fetchall()
    jobs_2 = pd.DataFrame(data, columns=columns)
    db.close()
    jobs_2.to_dict()


text:
Q: Dependencies on Euclid Book II. Most of the propositions in Euclid Book II are results analogous to simple algebraic applications of the distributive property.  Upon first inspection, the propositions that are chosen to be recorded seem like random properties.  e.g. II.8 is analogous to $(A+2B)^2=4(A+B)B+A^2$.
I would understand why these propositions we recorded if future propositions depended on these in their proofs.  Although, the only propositions in Book II which depend on previous propositions are the last four.  Are there propositions in future books which depend on the remaining "unused" propositions of Book II?  Or are they included because Euclid was recording every geometric result that the Greeks knew?

A: The results of Book II are indeed hardly (if at all) used in the remaining geometric books. There are a few algebraic applications in connection with perfect numbers as well as in Book X on the
classification of incommensurable lines. This is why the content of Book II was once classified as "geometric algebra".
Unguru attacked geometric algebra by seriously misrepresenting the claims of classical historians of mathematics; you will find more on that in recent articles by Blasjo and Hoyrup on geometric algebra. Geometrically, Book II deals with transforming rectangles into squares; algebraically, this is the theory of completing the square, which is used when solving problems that we write as quadratic equations. Thus Euclid lays the foundation for the methods for solving such problems that the Greeks may have inherited from the Babylonians (who knew how to find the sides of rectangles with given circumference and area, i.e., how to solve systems of equations of the form $x+y=a$, $xy = b$;
see Hoyrups Algebra in cuneiform).
Observe that I am not saying that the Greeks solved quadratic equations in this way. If you want to know how they did that look into the works of Archimedes, Aristarch, Heron and Diophantus. Solving quadratic problems is part of logistics: basic arithmetic as well as field measurement etc.; all the maths where the sizes of lines, areas and
angles are measured in feet, square feet or degrees is part of logistics. Therefore Euclid does not say that the area of a parallelogram is the product of the base and the height (as Heron does) but that its area equals that of a rectangle with the same base and the same height.
In a similar way, Euclid's number theory books cover the part of arithmetic that can be expressed without using fractions (which are also part of logistics), which is why Euclid is making such a fuss about 1 being so special (and as indivisible as a geometric point).


text:
Q: How to create multiple drag & drop zone and pass variable between them I'm trying to create a calendar in Angular for a personal project.
I have a table with a div for each day of the month and inside this div I have my appointments.
What I want to do is be able to drag and drop my appointment from a day to another, I try with the angular cdk drag & drop but can't have something working.
Here is a cell of my table:

{{day.getDate()}}

{{schedule.title}}

in the drop function I add a console log of the day used in the cell, when I drag my appointment from a day to another the day logged is always the day before dragging.
Why ?
And anyone know how I can pass my appointment from a cell to another ?
EDIT: I'm trying to use the answer below but have some issues:
I have added the cdkDropListGroup attribute to the tbody of my table (which show all the days)
And here is one cell of the table:

{{day.getDate()}}

    <ng-container *ngFor="let scheduleWrapper of schedulesOfDay.schedulesWrapper">
      <ng-container *ngIf="scheduleWrapper.isShowed">

          >

{{getScheduleTitle(scheduleWrapper)}}

      </ng-container>
    </ng-container>

I have the cdkDropList on the entire cell, and a cdkDrag for each of my schedules.
The problem is when I drag from a cell to another in the drop function the previousContainer and container are the same, so nothing is moved. (And I also print in console the day of the cell where the element is dropped and it always show the day where the schedule was before dragging).
I think the problem is the following:
When I move an element I need to change the date of this element (because I make a new render of my elements just after).
But I can't get the specific moved element from the container, I can just have all the elements

A: One possible way to create multiple drag and drop zones is to use cdkDropListGroup attribute on the parent element.

    <app-calendar *ngFor="let date of dates" [date]="date"></app-calendar>

Once you have this setup. Your app-calendar component can have the following markup:

        {{ schedule.title }}

And then handling the drop:
  drop(event: CdkDragDrop<any>) {
    if (event.previousContainer === event.container) {
      moveItemInArray(
        event.container.data,
        event.previousIndex,
        event.currentIndex
      );
    } else {
      transferArrayItem(
        event.previousContainer.data,
        event.container.data,
        event.previousIndex,
        event.currentIndex
      );
    }
  }

These two methods moveItemInArray and transferArrayItem are from here:
import { CdkDragDrop, moveItemInArray, transferArrayItem } from '@angular/cdk/drag-drop';

Working stackblitz.


text:
Q: Can I get a byte[] from a BitmapImage in Silverlight? I'm trying to pass some representation of an image back and forth between Silverlight and a WCF service.  If possible I'd like to pass a System.Windows.Media.Imaging.BitmapImage, since that would mean the client doesn't have to do any conversion.
However, at some point I need to store this image in a database, meaning the image representation must be able to convert to and from byte[].  I can create a BitmapImage from a byte[] by reading the array into a MemoryStream and using BitmapImage.SetSource().  But I can't seem to find a way to convert the other way - from BitmapImage to byte[].  Am I missing something obvious here?
If it helps at all, the conversion code could run on the server, i.e. it doesn't need to be Silverlight-safe.

A: Use this:
public byte[] GetBytes(BitmapImage bi)
{
    WriteableBitmap wbm = new WriteableBitmap(bi);
    return wbm.ToByteArray();
}

Where
public static byte[] ToByteArray(this WriteableBitmap bmp)
{
    // Init buffer
    int w = bmp.PixelWidth;
    int h = bmp.PixelHeight;
    int[] p = bmp.Pixels;
    int len = p.Length;
    byte[] result = new byte[4 * w * h];

    // Copy pixels to buffer
    for (int i = 0, j = 0; i < len; i++, j += 4)
    {
        int color = p[i];
        result[j + 0] = (byte)(color >> 24); // A
        result[j + 1] = (byte)(color >> 16); // R
        result[j + 2] = (byte)(color >> 8);  // G
        result[j + 3] = (byte)(color);       // B
    }

    return result;
}

A: I had the same issue.
I found the ImageTools library that makes thte job way easier.
Get the library and reference it and then
                        using (var writingStream = new MemoryStream())
                        {
                            var encoder = new PngEncoder
                            {
                                IsWritingUncompressed = false
                            };
                            encoder.Encode(bitmapImageInstance, writingStream);
                            // do something with the array
                        }

A: Try using CopyPixels. You can copy the bitmap data to a byte array. However, I am honestly not sure what the format of the pixels would be...its probably dependent upon the kind of image that was originally loaded.


text:
Q: can scroll when mouse is on  ? (not only this div) - by using jScrollPane i try to use this jQuery plugin : http://jscrollpane.kelvinluck.com
but anyway can i scrolling this .scroll-pane when mouse is outside .scroll-pane ?
http://jsfiddle.net/UUrkg/

A: have a look at the scroll to animate demo. Here's explained how you can trigger the scrollpane to scroll to a specific position.
The only thing you have to do now is to bind the mousescroll event on the other event and trigger it to scroll the scrollpane


text:
Q: Setting geom_boxplot line tickness based on significant difference I'm trying to highlight the significant difference of specific groups compared to a control by making their respective boxplots and labels bold. However, I have no idea how I should start with this. Right now I have something like this:
cat <- c(replicate(50, "a"), replicate(50, "b"), replicate(50, "c"))
foo <- rnorm(150)
bar <- c(rnorm(100, 2), rnorm(50, 4))
foobar <- c(rnorm(50, 5), rnorm(100,2))
df <- data.frame("category" = cat, "foo" = foo, "bar" = bar, "foobar" = foobar) %>% gather(key = "key", value = "value", 2:4)

ggplot(df, aes(x=category, y=value)) +
  geom_boxplot() +
  facet_grid(key ~ .)

Which produces following image:

Lets say that for category "b" and "c" the measurement of "foobar" is significantly different compared to "a", and for category "c" the measurement of "c" compared to "a" as well. Is there a way to highlight these boxplots (e.g. making them bold)?
Thank you

A: Here's one way I can think of to highlight specific boxplots based on standard deviation of the set.  As long as you follow the programming logic here, you should be able to adapt to other labeling methods.
The general approach is to process your dataset to include categorical data as extra columns, then use those columns you created to apply an aesthetic to the boxplot.
# create a column for standard deviation for individual categories within the groups
df.avg <- df %>% group_by(key,category) %>% summarize(sd.val=sd(value))

# merge both datasets to "add" the summary data in long/tidy format
df.merge <- merge(df, df.avg)

# the plot
ggplot(df.merge, aes(x=category, y=value)) +
    geom_boxplot(aes(fill=sd.val), alpha=0.8) +
    facet_grid(key ~ .) +
    scale_fill_gradient(name='Std Dev', high='red', low='green')

If you only want to label a "threshold" of standard deviation (e.g. only sd values that are higher than 1.1 in red), this could work:
ggplot(df.merge, aes(x=category, y=value)) +
    geom_boxplot(aes(fill=eval(sd.val>1.1)), alpha=0.8) +
    facet_grid(key ~ .) +
    scale_fill_manual(name=NULL, values=list('TRUE'='red', 'FALSE'='white'),
        labels=list('TRUE'='High SD', 'FALSE'='Low SD'))


text:
Q: how to begin to understand KML by analyzing the XSD I have no experience with KML or XSD. I understand sort of what KML is. it's an XML used to generate a google map.
this site supplies the XSD information for the KML.
i  opened the XSD file and i will post only a small portion of it because it's huge:
<?xml version="1.0" encoding="UTF-8"?>
<schema xmlns="http://www.w3.org/2001/XMLSchema"
  xmlns:kml="http://www.opengis.net/kml/2.2"
  xmlns:atom="http://www.w3.org/2005/Atom"
  xmlns:xal="urn:oasis:names:tc:ciq:xsdschema:xAL:2.0"
  targetNamespace="http://www.opengis.net/kml/2.2"
  elementFormDefault="qualified"
  version="2.2.0">

  <annotation>
    <appinfo>ogckml22.xsd 2008-01-23</appinfo>
    <documentation>XML Schema Document for OGC KML version 2.2. Copyright (c)
      2008 Open Geospatial Consortium, Inc. All Rights Reserved.
    </documentation>
  </annotation>

  <!-- import atom:author and atom:link -->
  <import namespace="http://www.w3.org/2005/Atom"
    schemaLocation="atom-author-link.xsd"/>

  <!-- import xAL:Address -->
  <import namespace="urn:oasis:names:tc:ciq:xsdschema:xAL:2.0"
    schemaLocation="http://docs.oasis-open.org/election/external/xAL.xsd"/>

  <!-- KML field types (simple content) -->

  <simpleType name="anglepos90Type">
    <restriction base="double">
      <minInclusive value="0.0"/>
      <maxInclusive value="90.0"/>
    </restriction>
  </simpleType>

  <simpleType name="angle90Type">
    <restriction base="double">
      <minInclusive value="-90"/>
      <maxInclusive value="90.0"/>
    </restriction>
  </simpleType>

  <simpleType name="anglepos180Type">
    <restriction base="double">
      <minInclusive value="0.0"/>
      <maxInclusive value="180.0"/>
    </restriction>
  </simpleType>

  <simpleType name="angle180Type">
    <restriction base="double">
      <minInclusive value="-180.0"/>
      <maxInclusive value="180.0"/>
    </restriction>
  </simpleType>

  <simpleType name="angle360Type">
    <restriction base="double">
      <minInclusive value="-360.0"/>
      <maxInclusive value="360.0"/>
    </restriction>
  </simpleType>

  <simpleType name="altitudeModeEnumType">
    <restriction base="string">
      <enumeration value="clampToGround"/>
      <enumeration value="relativeToGround"/>
      <enumeration value="absolute"/>
    </restriction>
  </simpleType>

  <simpleType name="colorType">
    <annotation>
      <documentation><![CDATA[

        aabbggrr

        ffffffff: opaque white
        ff000000: opaque black

        ]]></documentation>
    </annotation>
    <restriction base="hexBinary">
      <length value="4"/>
    </restriction>
  </simpleType>

  <simpleType name="coordinatesType">
    <list itemType="string"/>
  </simpleType>

  <simpleType name="colorModeEnumType">
    <restriction base="string">
      <enumeration value="normal"/>
      <enumeration value="random"/>
    </restriction>
  </simpleType>

  <simpleType name="dateTimeType">
    <union memberTypes="dateTime date gYearMonth gYear"/>
  </simpleType>

  <simpleType name="displayModeEnumType">
    <restriction base="string">
      <enumeration value="default"/>
      <enumeration value="hide"/>
    </restriction>
  </simpleType>

  <simpleType name="gridOriginEnumType">
    <restriction base="string">
      <enumeration value="lowerLeft"/>
      <enumeration value="upperLeft"/>
    </restriction>
  </simpleType>
  <simpleType name="itemIconStateType">
    <list itemType="kml:itemIconStateEnumType"/>
  </simpleType>

  <simpleType name="itemIconStateEnumType">
    <restriction base="string">
      <enumeration value="open"/>
      <enumeration value="closed"/>
      <enumeration value="error"/>
      <enumeration value="fetching0"/>
      <enumeration value="fetching1"/>
      <enumeration value="fetching2"/>

i don't really understand how to use these things to generate a map.
i was wondering if you could point me into the right direction on what exactly XSD is, and how i can use this documentation to generate a nice KML file to display a valid google map?

A: Tough one. You're right, schemas for vocabularies like KML tend to be huge, and they are often indigestible (there are rare exceptions that are written in a literary programming style). I wouldn't start from the schema. There seems to be a KML tutorial online - have you exhausted that?

A: I was in the same boat earlier and the KML Tutorial and Reference documentation provided by Google helped me a lot.

A: @Артём, once you have begun developing some KML examples, you can check them for correctness by using the KML Validator generously provided by Galdos: http://www.kmlvalidator.com/home.htm . When the validator finds something wrong, it will give you useful hints for fixing the problem. (The validator uses the KML 2.2.0 XSD schema in part to do its job.)


text:
Q: Sticking flexbox elements to each side of container (one element to the left, the other to the right) I know this is a very basic question but i can't accomplish what i want.
Background
I'm building an Angular 7 application with Angular Material (v7) components.
In Material Card titles, like this ones:

Objective
I want the icons to stick to the right, and the text to stick to the left. So, whatever the element's width is, they are sticked to each side.
BUT, I need the text able to use the remaining space if needed. For example:
|-----container (mat-card-title)-----|
|Short title-------------------|icons|
|A longer title----------------|icons|
|A muuuuuuuuch longer title----|icons|

|----------very large container (mat-card-title)-------------|
|Short title-------------------------------------------|icons|
|A longer title in a large container-------------------|icons|
|A muuuuuch longer title in a veeeery large container--|icons|

Also, I want both icons (button elements) to stick side-by-side if a break is needed because of an small width.
So far
I've tried several things, coming up to this flexbox styles to the mat-card-title element
mat-card-title {
  flex-shrink: 0;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-content: center;
}

And then, inline:
<mat-card-title>

    Latest Messages ({{count}})

    <button></button>
    <button></button>

</mat-card-title>

Question
Is this approach ok? How can i accomplish my objective?
Let me know if I should provide more information
Many thanks

A: I would get rid of the inline styles and make it a class so it's cleaner. It should look something like this:
mat-card-title {
  display: flex;
  justify-content: space-between;
  align-content: center;
}

.buttons {
  display:flex;
  justify-content: flex-end;
  flex: 0.2; //note you can also just specify a width in percentage, this is like setting a width of 20% (or however wide the buttons are)
}

<mat-card-title>

    Latest Messages ({{count}})

    <button></button>
    <button></button>

</mat-card-title>

Good luck!


text:
Q: How to a variable as a complete command (Helm Install) in Gitlab I have a following gitlab constellation.
variables:
  NAMESPACE: default

.script_install: &script_install
 - |
    helm install something . -n $NAMESPACE \
     -f values-prod.yaml \
     --set someapp.password=$ENV_PROD_PASSWORD

deploy_prod:
  stage: deploy
  image: dtzar/helm-kubectl:3.6.2
  variables:
    NAMESPACE: "prod"
  script:
    - cd helm
    - *script_install
  environment:
    name: prod
    deployment_tier: production
  when: manual

which works perfectly but now I have additional requirement that I have to write additional deploy task which would use some additional parameter for helm install. For this I don't want copy / paste all over the place, that would be a maintenance hell but my tries to reuse the command is failure I would like to show what I tried you might give tips about it.
My first try was..
variables:
  NAMESPACE: default

.script_install: &script_install
 - |
    helm install something . -n $NAMESPACE \
     -f values-prod.yaml \
     --set someapp.password=$ENV_PROD_PASSWORD

deploy_prod_no_comp_1:
  stage: deploy
  image: dtzar/helm-kubectl:3.6.2
  variables:
    NAMESPACE: "prod"
  script:
    - cd helm
    - *script_install --set component1.enabled=false
  environment:
    name: prod
    deployment_tier: production
  when: manual

deploy_prod:
  stage: deploy
  image: dtzar/helm-kubectl:3.6.2
  variables:
    NAMESPACE: "prod"
  script:
    - cd helm
    - *script_install
  environment:
    name: prod
    deployment_tier: production
  when: manual

variables:
  NAMESPACE: default

.script_install: &script_install
 - |
    helm install something . -n $NAMESPACE \
     -f values-prod.yaml \
     --set someapp.password=$ENV_PROD_PASSWORD

deploy_prod:
  stage: deploy
  image: dtzar/helm-kubectl:3.6.2
  variables:
    NAMESPACE: "prod"
  script:
    - cd helm
    - *script_install
  environment:
    name: prod
    deployment_tier: production
  when: manual

Of course that didn't work...
variables:
  NAMESPACE: default
  COMMAND: "helm install something . -n $NAMESPACE -f values-prod.yaml --set someapp.password=$ENV_PROD_PASSWORD"

deploy_prod_no_comp_1:
  stage: deploy
  image: dtzar/helm-kubectl:3.6.2
  variables:
    NAMESPACE: "prod"
  script:
    - cd helm
    - "${COMMAND} --set component1.enabled=false"
  environment:
    name: prod
    deployment_tier: production
  when: manual

deploy_prod:
  stage: deploy
  image: dtzar/helm-kubectl:3.6.2
  variables:
    NAMESPACE: "prod"
  script:
    - cd helm
    - "${COMMAND}"
  environment:
    name: prod
    deployment_tier: production
  when: manual

This works but this is ugly....is there any better way to realise this?


text:
Q: How Arrow function work inside constructor? I am bit confuse about arrow function inside constructor.
As per my knowledge: If we will use arrow function, the keyword this will not rebound to that actual function. it is inherited from the parent scope.
let's take example:
var d = {
  b: 'b',
  x: () =>{
    console.log(this); // this will return Window Object.
 }
}
d.x();

it will print Window Object. that is fine.
But in constructor function
function A(){
  this.b ='b';
  this.x = () =>{
    console.log(this);
  }
}
var c = new A()
c.x();

this print object c. but according to me it should return Window Object. Why ?

A: In the constructor this refers to the object on construction. Why else could you do this.b ='b';?
Since an arrow-function simply captures the current context, it captures the object in the constructor.


text:
Q: Using .NET analyzer rule CA1001 for components of a framework which does not use IDisposable I have a Unity project with Roslyn analyzers enabled, one of them is CA1001: "Types that own disposable fields should be disposable" (https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/ca1001).
This comes in handy for classes which are created and destroyed manually, to see if they properly dispose all of their fields. However in a lot of cases due to the viral nature of IDisposable the topmost objects creating these will be components, MonoBehaviour classes in the case of Unity. To satisfy the rule one would add IDisposable to the MonoBehaviour and implement the dispose pattern properly, however that does not add much value to the class, as being component of a framework which does not rely on IDisposable it will never be called.
What would seem to be the best in this case is to alter the rule somehow to check if IDisposable fields have been disposed in the OnDestroy method. Is there a way to change rule CA1001 to work like this for MonoBehaviour subclasses? Or is there any other analyzer which can do this? If not then at least could the rule be disabled for subclasses of a specific type? (The best I could do so far is to suppress the rule for files named "*Component.cs" but that's far from best.)
My question is targeted toward Unity but it actually applies to any framework not relying on the IDisposable interface.
Edit:
Example code:
public class Resource : IDisposable
{
    public void Dispose()
    {
        Debug.Log("Resource disposed");
    }
}

public class ExampleComponent : MonoBehaviour
{
    private Resource resource;

    private void Start()
    {
        resource = new Resource();
    }

    private void OnDestroy()
    {
        resource.Dispose();
    }
}

In this case resource is properly disposed in the conventional OnDestroy method but CA1001 is still triggered.

A: I think you could ignore the rule for any type derived from UnityEngine.MonoBehaviour via Exclude specific types and their derived types (in the very same link you posted)

add the following key-value pair to an .editorconfig file in your project

something like
dotnet_code_quality.CA1001.excluded_type_names_with_derived_types = T:UnityEngine.MonoBehaviour


text:
Q: I am having trouble getting this adventure story done because of this error I am a very early beginner and I have a project due soon to create a choose your own adventure story. I am not done yet but I am getting the error "Main.java not found" Any help? Thanks!
import java.util.Scanner;

class ChoicesStory {

  public static void main(String[] args) {
    new ChoicesStory();
  }

  Scanner stringReader = new Scanner(System.in);
  Scanner numberReader = new Scanner(System.in);

  public ChoicesStory() {
    System.out.println("You're lost in a dark forest.");
    System.out.println("You see a faint light in the distance resembling a fire.");
    System.out.println("Do you want to go towards the light or keep walking?");
    System.out.print("Enter 'light' or 'walk' ");
    String choice = stringReader.nextLine();

    if (choice.equals("light")) {
      lightStory();
    }

    if (choice.equals("walk")) {
      walkStory();

    }

  }

  public void lightStory() {
    System.out.println("You walk towards the fire and see an old man sitting on a log.");
    System.out.println("You ask him if he knows how to get back to your town.");
    System.out.println("You see the man pull out a knife and look at you menacingly.");

  }

  public void walkStory() {

  }

}

A: You could have possible named you file as Main.java but inside the file the class name is ChoicesStory. Both these should be the same. If you were using an IDE (ex : eclipse), then it would have already shown an error. Looks like you have run the program in command line using java Main


text:
Q: Alternative methods for finding antiderivative of $\frac x{(1+\sin x)^2}$ This problem was assigned to a student I'm tutoring as extra credit:

$$\int\frac{x}{(1+\sin x)^2}\,\mathrm dx$$

I have two potential methods in mind, though I suspect the first, which employs the Weierstrass tangent half-angle substitution, goes beyond the student's curriculum, while the second probably falls within what he's learned (or at least in my opinion, what he should absolutely know). Both methods are rather lengthy, and, while I'm convinced the "extra credit" part about this problem is correlated with that, I can't help but wonder if there are more straightforward methods to do it.
I outline my suggestions below.
Method 1:

*

*Integrate by parts to get
$$\int\frac x{(1+\sin x)^2}\,\mathrm dx=uv-\int v\,\mathrm du$$where $u=x$ and $v=\displaystyle\int\frac{\mathrm dx}{(1+\sin x)^2}$.

*Compute $v$ using the Weierstrass substitution $t=\tan\dfrac x2$, which yields
$$-\frac{2+3\tan\dfrac{x}{2}+3\tan^2\dfrac{x}{2}}{3\left(1+\tan\dfrac{x}{2}\right)^3}x+\int\frac{2+3\tan\dfrac{x}{2}+3\tan^2\dfrac{x}{2}}{3\left(1+\tan\dfrac{x}{2}\right)^3}\,\mathrm dx$$

*Compute the remaining integral by expanding like so:
$$\int\frac{\mathrm dx}{\left(1+\tan\dfrac{x}{2}\right)^2}+\int\frac{1+\tan^2\dfrac{x}{2}}{\left(1+\tan\dfrac{x}{2}\right)^2}\,\mathrm dx-\frac{4}{3}\int\frac{\mathrm dx}{\left(1+\tan\dfrac{x}{2}\right)^3}$$and with appropriate substitutions (Weierstrass and $w=1+\tan\dfrac x2$) rewrite as
$$\int\frac{2}{(1+t)^2(1+t^2)}\,\mathrm dt+\int\frac{2}{w^2}\,\mathrm dw-\frac{4}{3}\int\frac{2}{(1+t)^3(1+t^2)}\,\mathrm dt$$

*Decompose into partial fractions, etc.
Method 2:

*

*Let $x=\dfrac\pi2-y$ and rewrite the integral as
$$\int\frac x{(1+\sin x)^2}\,\mathrm dx=\int\frac{y-\dfrac\pi2}{(1+\cos y)^2}\,\mathrm dy$$

*Recalling the half-angle identity for cosine, we can rewrite the integrand as
$$\int\left(\frac y4-\frac\pi8\right)\sec^4\frac y2\,\mathrm dy=\int\left(y-\frac\pi4\right)\sec^4y\,\mathrm dy$$

*Integrate by parts
$$\int\left(y-\frac\pi4\right)\sec^4y\,\mathrm dy=uv-\int v\,\mathrm du$$this time with $u=y-\dfrac\pi4$ and $v=\displaystyle\int\sec^4y\,\mathrm dy$.

*Compute $v$ with a reduction formula or the expansion $\sec^4y=\sec^2y(1+\tan^2y)$, etc.

A: If you let $\displaystyle u=x, \;v=\int\frac{1}{(1+\sin x)^2}\,dx=\int\frac{1}{(\sin\frac{x}{2}+\cos\frac{x}{2})^2}\,dx=\int\frac{1}{(\sqrt{2}\cos\left(\frac{x}{2}-\frac{\pi}{4}\right))^2}\,dx$
$\displaystyle\hspace{1.3 in}=\frac{1}{2}\int\sec^2\left(\frac{x}{2}-\frac{\pi}{4}\right)\,dx=\tan\left(\frac{x}{2}-\frac{\pi}{4}\right)+C$, this gives
$\displaystyle\int\frac{1}{(1+\sin x)^2}dx=uv-\int v\, du=x\tan\left(\frac{x}{2}-\frac{\pi}{4}\right)-\left[-2\ln\big|\cos\left(\frac{x}{2}-\frac{\pi}{4}\right)\big|\right]+C$
$\displaystyle\hspace{2.25 in}=\color{blue}{x\tan\left(\frac{x}{2}-\frac{\pi}{4}\right)+2\ln\big|\cos\left(\frac{x}{2}-\frac{\pi}{4}\right)\big|+C}$

A: Indeed one can make the substitution $t=\tan \frac{x}{2}$ (which surely goes back to Euler or even earlier) one then gets
$$2\int \frac{t^2+1}{(t+1)^4}\arctan (2t) dt$$
Now this integral is
$$=\int\frac{1}{(t+1)^2}\arctan (2t)dt-\int\frac{2}{(t+1)^3}\arctan (2t)dt+\int\frac{2}{(t+1)^4}\arctan (2t)dt$$
Each of which can be evaluated by a standard integration by parts.

A: An alternate method would be to start as in Method 1, and then find $v$ using
$\displaystyle v=\int\frac{1}{(1+\sin x)^2}dx=\int\frac{(1-\sin x)^2}{\cos^4x}dx=\int(\sec^4x-2\sec^3x\tan x+\tan^2x\sec^2x)dx$
$\hspace{.14 in}=\tan x+\frac{2}{3}\tan^3x-\frac{2}{3}\sec^3 x+C$.
This gives
$\displaystyle\int\frac{1}{(1+\sin x)^2}dx=uv-\int v\,du$
$\displaystyle\hspace{1.2 in} =x\tan x+\frac{2}{3}x\,(\tan^3x-\sec^3x)+\frac{1}{3}\left(\sec x\tan x+\ln(1+\sin x)-\tan^2 x\right)+C$


text:
Q: batch file/ bash scripts validator Is there any online batch file/ bash scripts validator? Let you drop the code in the textarea and check syntax errors? Or upload a file for validation.

A: I doubt it, since you can just do bash -n yourscript.sh
Searching, I couldn't find one either. Plenty of hits on using -n though...


text:
Q: Python34 - creating a list with substring comparison (noobie question )
I've used BeautifulSoup to scrape a list of hrefs. I've then assigned them to a List.  I wish to extract a specific set of them to another List. There are two substrings I can use to differentiate the ones I want - they all start with "dsp" and they have something like "&tab=tabs-1" in them .
How can I transfer only those from MyList[] to MyNewList[]?
I'm used to having a where clause to work with and cant seem to find any reference - I'm assuming it must be pretty basic

A: something like this?
urls = ['http://dsp.more/&tab=tabs-1&more" ', 'http://no.mat.ch']

new_urls = [ url for url in urls if url.startswith('http://dsp') and '&tab=tabs-1' in url]
print(new_urls)


text:
Q: How to write this as one matrix? I have a rather easy question, but I do not come along.
Let $Y$ be a $(n\times 1)$-matrix, $A$ a $(n\times n)$-matrix and $B$ a $(k\times n)$-matrix.
Consider $X=(AY,BY)$.
How can I write $X$ in the form "matrix" $\cdot$ $Y$?

A: Let ${}^T$ denote the transpose of a matrix.  Assuming all entries are real, we have two options:
$$
(AY,BY) = (BY)^T AY = Y^T B^T A Y = (Y^TB^T A)Y
$$
Or
$$
(AY,BY) = (AY)^T BY = Y^TA^T B Y = (Y^TA^T B) Y
$$
So, you can select your "matrix" to be either $Y^TB^T A$ or $Y^TA^T B$.


text:
Q: Can you install Visual Studio 2008 Pro and Team System side-by-side? I have a couple of question for you..
Can I install on the same machine visual studio 2008 Professional and Team System ?
the reason is because with Team System already installed I receive an error when I work with ajax and jquery:
Error   1   Error updating JScript IntelliSense: Client-side script IntelliSense information was not generated due to an error in an external script reference. Y:\TestTemp\WebSite1\Default.aspx   1   1   Y:\TestTemp\WebSite1\

so I thought maybe my installation is corrupted ? I tried  to install the web express edition on same machine and works fine as well with ajax.
Do you know if I can install the professional version as well on the same machine?
thanks

A: I would try to fix the JavaScript Intellisense. (If you have team system, I would try to use it). The Visual Web Developer Team blog has a fix for one (registry) problem that could cause this behavior.
Have you tried to repair the install?

A: In answer to your question, no you cannot install two editions side-by-side.


text:
Q: REST API DESIGN - How to overcome the impedance mismatch between a front end client's needs and REST principles? Given the following scenario:

*

*a RESTful API

*that RESTful API has permissions/authorizations that can be granted to entire entity collections, and/or to particular entities, i.e. complex role based permission rules.

*The API is (according to RESTful principles) HATEOS-driven (resource url's are revealed through the API. Once you login and get back the "user" resource, you are able to drive the entire API through links given in responses.

*A front-end client (web app) that needs to use this API

Imagine now the front-end wants to build a menu. That menu is based on access to particular entities and/or entity collections. For example an "Administration" menu will be shown if the user has access to one of a number of different entities and/or collections.
How do I build the menu? I need to know the permissions the user has in order to build the menu propertly. I don't know all the permissions the user has because it would require walking the url's of the REST API to see all the objects the user has permissions on.
This seems like a tough thing to overcome, but maybe I am missing some obvious technique. How can this impedance mismatch overcome?

A: Your REST API can expose a resource (or it can be a part of the user resource returned after a user has been successfully signed in) which will contain information what resources the user can access and therefore what menu items should be available for this user.


text:
Q: image comparison in R I am looking for the best way to compare 2 or more images.
The images I have are now in matrix format, so basically I am comparing matrices.
They aren't square (but this isn't a problem).
This is an example of what I have with only two matrices:
#Original data
M1<-cbind(c(0,0,20,40,50,35),c(0,0,5,20,90,80),c(0,0,10,25,85,0),c(58,70,20,50,0,5))
#Data to be compared with M1
M2<-cbind(c(0,5,25,25,60,15),c(0,30,15,10,116,67),c(0,2,9,20,90,1),c(69,50,22,30,0,2))

I can check for the differences and the correlation, but I also want to be able to say for example, if:

*

*high values in M2 occur in the same positions that M1

*high values in M2 occur close to the positions in M1

*high values in M2 occur far away

Same thing for low values.
By high values I mean maximum values, for example if the max value in M1 is in position (M1_maxvalue(x,y)), than I M2 max value should be a similar value observed in M1 as well as in the same or close position M1_maxvalue(x,y).
I can extract the positions, the variation of the positions of the maximum values, however I am looking for existent methods where I can base my comparisons.
What type of calculations can I use to do such type of analysis?
I can use both image processing packages as well as matrices algorithms.

A: Sounds like a job better handled with ImageJ or SAODS9  at http://hea-www.harvard.edu/RD/ds9/ .
IIRC those apps have built-in tools for spot and blob-finding, which may save you a lot of time and pain.


text:
Q: Why this error in Android AudioTrack? AudioTrackShared: releaseBuffer: mUnreleased out of range I'm trying to broadcast audio between apps. This is my AudioRecord:
private var audiorecord: AudioRecord? = null
private val SAMPLER = 16000 //Sample Audio Rate
private val CHANNEL_CONFIG: Int = AudioFormat.CHANNEL_IN_MONO
private val AUDIO_FORMAT: Int = AudioFormat.ENCODING_PCM_16BIT
private var BUFFER_SIZE = AudioRecord.getMinBufferSize(SAMPLER, CHANNEL_CONFIG, AUDIO_FORMAT)

    audiorecord = AudioRecord(
        MediaRecorder.AudioSource.MIC,
        SAMPLER,
        CHANNEL_CONFIG,
        AUDIO_FORMAT,
        BUFFER_SIZE
    )

Send this over WebSocket connection and trying to play in a AudioTrack I got this error with non-audio: (I'm using phone, so I hear some noise, but not sound)

A/AudioTrackShared: releaseBuffer: mUnreleased out of range, !(stepCount:4 <= mUnreleased:0 <= mFrameCount:22050), BufferSizeInFrames:22050

A/libc: Fatal signal 6 (SIGABRT), code -1 (SI_QUEUE) in tid 9569 (Thread-3), pid 18292 (mple.testaudio2)

My AudioTrack:
    var BUFFER_SIZE = AudioTrack.getNativeOutputSampleRate(AudioManager.STREAM_VOICE_CALL)

    val attribBuilder = AudioAttributes.Builder()
    attribBuilder.setContentType(AudioAttributes.CONTENT_TYPE_SPEECH)
    attribBuilder.setUsage(AudioAttributes.USAGE_VOICE_COMMUNICATION)

    val attributes = attribBuilder.build()

    // Build audio format

    val afBuilder = AudioFormat.Builder()
    afBuilder.setChannelMask(AudioFormat.CHANNEL_OUT_MONO)
    afBuilder.setEncoding(AudioFormat.ENCODING_PCM_8BIT)
    afBuilder.setSampleRate(BUFFER_SIZE)

    val format = afBuilder.build()

    audioTrack = AudioTrack(
        attributes,
        format,
        BUFFER_SIZE,
        AudioTrack.MODE_STREAM,
        AudioManager.AUDIO_SESSION_ID_GENERATE
    )

I'm not sure about the audio atributes and audio formats. This code break my app. Why?

A: One possible problem is the third argument that you are passing in the constructor:
audioTrack = AudioTrack(
    attributes,
    format,
    BUFFER_SIZE, <-- this one
    AudioTrack.MODE_STREAM,
    AudioManager.AUDIO_SESSION_ID_GENERATE
)

According to the docs, this should be the buffer size in bytes. You are passing BUFFER_SIZE, which based on the name seems correct, but that variable is defined as
var BUFFER_SIZE = AudioTrack.getNativeOutputSampleRate(AudioManager.STREAM_VOICE_CALL)

So it is actually a sample rate, not a buffer size. I would recommend that you rename the variable, the name is rather misleading. You can try setting a large number for the buffer size and see if it fixes your problem.


text:
Q: LTspice - Create a subcircuit and modify its own parameters I have created a subcircuit on LTspice. Here it is:

It has a lot parameters that I would like to adjust.
Her is the netlist:

Just have to create the symbol and it is done. Here it is:

Nevertheless I do not have access to the parameters... How can I do for accessing the parameters of my components? Is it also possible to set parameter value by default?
Have a nice day :)

A: I think you had a similar question before. At any rate, just RCLick on the symbol (or Ctrl+RClick) and simply add n=<value> Lleakp=<value> ..., then optionally double click on the entry in the Vis. column to make it visible and more accessible in the schematic. If you need those values paramterized in the top level schematic, simply add your .param statements then enter n={<param>} Lleakp={<param>} ..., and so on. BTW, this is also described in the help under Schematic Capture > Editing Components.


text:
Q: Can I call wait on the same synchronized lock from another object? I would like to call a wait and notify on a different object than the one that has synchronized on a lock. Take this code for example:
Class1.foo() {
    synchronized(lock) {
        while(condition) {
            try {
                lock.wait();
            }
        }
        lock.notify();
    }

}

I am wondering if this is equivalent to:
Class1.foo() {
    synchronized(lock) {
         Class2.bar(lock);
    }
}

Class2.bar(Object lock) {
    while(condition) {
        try {
            lock.wait();
        }
    }
    lock.notify();
}

Thanks!

A: Monitors and synchronization are associated with objects, not variables:

Every object has an intrinsic lock associated with it .. A thread is said to own the intrinsic lock between the time it has acquired the lock and released the lock [as with synchronized] ..

In the given code, it can be seen that trivially inlining the method call in the latter case results in the same objects being used in the same sequence.
Class1.foo() {
    synchronized(lock) {
        while(condition) {
            try {
                lock.wait();
            }
        }
        lock.notify();
    }
}

Class1.foo() {
    synchronized(lock) {
    // >> inline from Class2.bar(Object lock) {
    //    where lock evaluates to the same object
        while(condition) {
            try {
                lock.wait();
            }
        }
        lock.notify();
    // << end inline }
   }
}

The above only argues for equivalency in the presented code and makes no further claim. That is, it assumes that Class2.bar is only called from Class1.foo (or is otherwise synchronized upon the same object during the invocation).


text:
Q: Symfony 2.1 Autologin after facebook login I'm creating an intranet, therefore all users have account automatically created for them. They then go to a url to create their password.  All that works great.  I'm now trying to allow them to "attach" their Facebook account to their user account.  This is where my troubles have started...
I've successfully gotten the user to authenticate properly after a facebook login with this
method in SecurityController
public function loginCheckFacebookAction()
{

    $request = $this->getRequest();
    $session = $request->getSession();
    $response = new Response();

    $sessionUser = $this->getUser();

    $facebook = $this->get('facebook');

    $fbUser = $facebook->getUser(); // facebook id

    if ($fbUser) {
      try {

          $em = $this->getDoctrine()->getManager();
          $repo = $em->getRepository("IntranetBundle:User");
          $user = $repo->findUserByFBID($fbUser);

          if($user){

              $targetPath = $session->get("_target_path");

               $firewall = "secured_area";

               $roles = $user->getRoles();

               $rolesArray = array();

    foreach($roles as $role):
        $rolesArray[] = $role->getRole();
    endforeach;

               $token = new UsernamePasswordToken($user, $user->getPassword(), $firewall, $rolesArray);

               $event = new InteractiveLoginEvent($this->getRequest(), $token);
               $this->get("event_dispatcher")->dispatch("security.interactive_login", $event);

               $this->get('security.context')->setToken($token);

              /*
              If I uncomment out either of the following redirects
              the redirect happens but the user is not authenticated properly
              If I comment them out I'm just rendering my error template.  The user
              however, is authenticated properly.
              */
              if(isset($targetPath)){
                  //return $this->redirect($targetPath);
              } else {
                  //return $this->redirect($this->generateUrl("ssla_intranet_homepage"));
              }

          }

      } catch (FacebookApiException $e) {

          $user = null;

      }

    // I just render this template to be able to view debug bar.
    //User is authenticated properly.

    $pageParameters = $this->getPageParameters();
    $pageParameters["page"] = "error";
    $pageParameters["error"] = array();
    $pageParameters["error"]["message"] = "Something went wrong with authentication";

    return $this->render('IntranetBundle:Error:index.html.twig', $pageParameters);
}

Do I need to register a listener for all interactive_login events that then handles all post-login redirection rather than trying to redirect within the same method?
First project using Symfony, and this is killing me. Any thoughts?
By the way, I've looked into the FOSFacebookBundle, but wanted to be able to authenticate with a number of different methods, including doctrine, gmail, facebook, and twitter.


text:
Q: My program does not compare the two variables (first_choice and second_choice) When ever I try to run and play the game, first_player (first_choice) always wins. After trying to figure it out I replace the first if statement with random print statement and it would print that every time. I don't understand what is wrong:
while True:

    import os

    print("Welcome to the rock, paper, sisers Game")
    first_player = input("Player 1 enter your name: ")
    second_player = input("Player 2 enter your name: ")
    print("Use p for paper, r for rock, and s for sisers")
    first_choice = str(input("{} Pick: ".format(first_player)))
    os.system('cls' if os.name == 'nt' else 'clear')
    second_choice = str(input("{} Pick: ".format(second_player)))
    os.system('cls' if os.name == 'nt' else 'clear')

    if (first_choice == "r" or "R") and (second_choice == "s" or "S"):
        print("{} Won!!!!!".format(first_player))

    elif (second_choice == "r" or "R") and (first_choice == "s" or "S"):
        print("{} Won!!!!!".format(second_player))

    elif first_choice == second_choice:
        print("It is a draw")

    elif (second_choice == "s" or "S") and (first_choice == "p" or "P"):
        print("{} Won!!!!!".format(second_player))

    elif (second_choice == "p" or "P") and (first_choice == "s" or "S"):
        print("{} Won!!!!!".format(first_player))

    elif (second_choice == "p" or "P") and (first_choice == "r", "R"):
        print("{} Won!!!!!".format(second_player))

    elif (second_choice == "r" or "R") and (first_choice == "p" or "P"):
        print("{} Won!!!!!".format(first_player))

Replace the first if statement print function:
while True:

    import os

    print("Welcome to the rock, paper, sisers Game")
    first_player = input("Player 1 enter your name: ")
    second_player = input("Player 2 enter your name: ")
    print("Use p for paper, r for rock, and s for sisers")
    first_choice = str(input("{} Pick: ".format(first_player)))
    os.system('cls' if os.name == 'nt' else 'clear')
    second_choice = str(input("{} Pick: ".format(second_player)))
    os.system('cls' if os.name == 'nt' else 'clear')

    if (first_choice == "r" or "R") and (second_choice == "s" or "S"):
      print("useless random text")

    elif (second_choice == "r" or "R") and (first_choice == "s" or "S"):
      print("{} Won!!!!!".format(second_player))

    elif first_choice == second_choice:
      print("It is a draw")

    elif (second_choice == "s" or "S") and (first_choice == "p" or "P"):
      print("{} Won!!!!!".format(second_player))

    elif (second_choice == "p" or "P") and (first_choice == "s" or "S"):
      print("{} Won!!!!!".format(first_player))

    elif (second_choice == "p" or "P") and (first_choice == "r", "R"):
      print("{} Won!!!!!".format(second_player))

    elif (second_choice == "r" or "R") and (first_choice == "p" or "P"):
      print("{} Won!!!!!".format(first_player))

A: You cannot do if condition == value or another_value in python. It will always be evaluated to True, since the another_value is non-empty for all of your cases.
You will have to evaluate them separately:
if condition == value or condition == another_value:

another way is to use in operator:
if condition in {value, another_value}:

A: Try wrapping your if/elif statements like this:

if ((first_choice == "r" or "R") and (second_choice == "s" or "S")):

It has to due with order of evaluation in python and it is only validating your first operation.


text:
Q: WKweb view not loading properly?     class WebViewController: UIViewController,WKUIDelegate {
    var _responseData: Data?
@IBOutlet weak var webViewMain: WKWebView!
var language: Int = 0
var movieName = String()
var urlStrng = String()
var urlMain: URL?
var data: Data?
var fileName = String()
var queue = OperationQueue()
 var pathOriginal = String()
var pathDuplocate = String()
var refreshAlert = UIAlertController()
override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.
    //creating music folder this plays key role
    webViewMain.translatesAutoresizingMaskIntoConstraints = false
    let height = NSLayoutConstraint(item: webViewMain, attribute: .height, relatedBy: .equal, toItem: view, attribute: .height, multiplier: 1, constant: 0)
    let width = NSLayoutConstraint(item: webViewMain, attribute: .width, relatedBy: .equal, toItem: view, attribute: .width, multiplier: 1, constant: 0)
    view.addConstraints([height, width])
    let webConfiguration = WKWebViewConfiguration()
    webViewMain = WKWebView(frame: .zero, configuration: webConfiguration)
    webViewMain.uiDelegate = self
    webViewMain.navigationDelegate = self
    view = webViewMain
    switch language {
    case 1:
        urlStrng = "https://cse.google.co.in/cse?cx=005819264335345607731:ta3f5zeiqpm&q=king&oq=king&gs_l=partner.3...0.0.1.177130.0.0.0.0.0.0.0.0..0.0.gsnos%%2Cn%%3D13...0.0..1ac..25.partner..3.1.288.ArU-FOKoCOI#gsc.tab=0&gsc.q=\(movieName)&gsc.page=1"
        print("\(urlStrng)")
    case 2:
         urlStrng = "https://cse.google.com/cse?cx=017716760286974932527%%3Aa5xw-xxsaic&q=vikram%%20veda&oq=vikram%%20veda&gs_l=partner.3..0.3535.6702.0.8294.11.7.0.3.3.0.688.2733.1j1j0j2j1j2.7.0.gsnos%%2Cn%%3D13...0.3027j1482321j11..1ac.1.25.partner..4.7.1281.Ja2pFYDKTV4#gsc.tab=0&gsc.q=\(movieName)%%20&gsc.page=1"
        print("\(urlStrng)")
    case 3:
        //hindi
         urlStrng = "https://www.songsmp3.co/category/search?search=\(movieName)"
        print("\(urlStrng)")
    case 4:
        //malayala
         urlStrng = "https://cse.google.com/cse?cx=017716760286974932527%%3Aa5xw-xxsaic&q=vikram%%20veda&oq=vikram%%20veda&gs_l=partner.3..0.3535.6702.0.8294.11.7.0.3.3.0.688.2733.1j1j0j2j1j2.7.0.gsnos%%2Cn%%3D13...0.3027j1482321j11..1ac.1.25.partner..4.7.1281.Ja2pFYDKTV4#gsc.tab=0&gsc.q=\(movieName)%%20&gsc.page=1"
        print("\(urlStrng)")
    case 5:
        //malayala
         urlStrng = "https://cse.google.com/cse?cx=017716760286974932527%%3Aa5xw-xxsaic&q=vikram%%20veda&oq=vikram%%20veda&gs_l=partner.3..0.3535.6702.0.8294.11.7.0.3.3.0.688.2733.1j1j0j2j1j2.7.0.gsnos%%2Cn%%3D13...0.3027j1482321j11..1ac.1.25.partner..4.7.1281.Ja2pFYDKTV4#gsc.tab=0&gsc.q=\(movieName)%%20&gsc.page=1"
        print("\(urlStrng)")
    default:break

    }
    print("\(urlStrng)")
     //urlMain = URL(string:urlStrng)
    let url : NSString = urlStrng as NSString
    let urlStr : NSString = url.addingPercentEscapes(using: String.Encoding.utf8.rawValue)! as NSString
    let searchURL : NSURL = NSURL(string: urlStr as String)!
    print(searchURL)
    let request = URLRequest(url:searchURL as URL)
    webViewMain.load(request)

}

 extension WebViewController:WKNavigationDelegate
{
    func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {

    print(error.localizedDescription)
}
func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
    print( webView.url)
    print("Strat to load")
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
    print("finish to load")
}
public func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error)
{
    print(error.localizedDescription)
}
 public func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Swift.Void)
 { if (navigationAction.navigationType == .linkActivated){
    decisionHandler(.allow)
 } else {
    decisionHandler(.cancel)
    }
    print("decidepolicy")
}
public func webView(_ webView: WKWebView, didReceiveServerRedirectForProvisionalNavigation navigation: WKNavigation!)
{

        print("didreciveserver")

}

 public func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!)
{

     print("didCommit")

}

    public func webView(_ webView: WKWebView, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Swift.Void)
   {
         print("didreciveChalange")
}
@available(iOS 9.0, *)
 public func webViewWebContentProcessDidTerminate(_ webView: WKWebView)
{
     print("didTerminate")

}

it not loading web view it showing 2 errors-:

1.) Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Completion handler passed
  to -[WingsMusic.WebViewController
  webView:didReceiveAuthenticationChallenge:completionHandler:] was not
  called' then i removed completion delegete and it load web page at
  first time an again shows below error
2.)Could not signal service com.apple.WebKit.Networking: 113: Could not find specified service

A: Under any case, you should return decisionHandler for decidePolicyFor navigationAction. Otherwise, you can see above crash


text:
Q: Thevenins theorum calculating resistance? Say I have a circuit consisting of many resistors, to get thevanins resistance is there a correct order to work them out in? For example if my circuit looked like this..
Would I do b//d then add that to a and e, then use what that gave me (call it f) and do f//c ?

A:
Would I do b//d then...

(1) By inspection, B is in series with the equivalent resistance of the remaining resistors.  Do you see why?
(2) Resistor C will not be a factor in the Thevenin resistance.  Do you see why?

A: There is more to it than just combining resistors.
I would start at the left and determine the voltage and resistance looking left. Then progress to the right. Assuming the generator voltage is v.
At the generator the voltage and resistance would be:  v and 0
At c:  the voltage would be v and the resistance 0
At a and e: v and a+e
At d: v x d/(d+a+e) and d\(a+e)
At A and B: v x d/(d+a+e) and b+d\(a+e)
Note: the \ was written as a two characters to indicate in parallel. But shows as only one


text:
Q: How to pass the keystore to the JDBC I would like to connect with the oracle databases. I've created the small project, that the connection works fine.
public void makeCon() {
        String url = "jdbc:oracle:thin:@(DESCRIPTION = (ADDRESS_LIST = (ADDRESS = (PROTOCOL = TCPS) (HOST =example.com) (PORT = 8080))) (CONNECT_DATA = (SERVER = DEDICATED)(SID = somesid)))";
        Properties props = new Properties();
        props.setProperty("user", "username");
        props.setProperty("password", "pass");
        props.setProperty("javax.net.ssl.trustStore", "C:\\Users\\user1\\Desktop\\src\\main\\resources\\local.keystore");
        props.setProperty("javax.net.ssl.trustStoreType", "JKS");
        props.setProperty("javax.net.ssl.trustStorePassword", "secretpassword");
        try {
            Connection conn = DriverManager.getConnection(url, props);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

This connection works fine, I was able to do some query. Right now I would like to connect on my main project. I've there connection that based on application properties, and everything works fine, but right now when I want to change the database that will connect with SSO oracle, that does not work.
 @Bean(name = "sql")
  @ConfigurationProperties(prefix = "spring.datasource")
  public DataSource getDataSource() {
    return DataSourceBuilder.create().build();
  }

  @Bean(name = "sqlDataNamed")
  public NamedParameterJdbcTemplate namedParameterJdbcTemplate(DataSource pricingDataSource) {
    JdbcTemplate template = new JdbcTemplate(getDataSource());
    template.setFetchSize(500);
      return new NamedParameterJdbcTemplate(template);
  }

I've tried to add this keystore to the JdbcTemplate or to the Datasource somehow, but I couldnt do it. The documentation does not show how to put the properties. System.setProperties does not work, after that there is an error:
Root exception is javax.net.ssl.SSLHandshakeException:
sun.security.validator.ValidatorException: PKIX path building failed:
sun.security.provider.certpath.SunCertPathBuilderException:
unable to find valid certification path to requested target

Thanks in advice


text:
Q: Power automate does not take into account the last row of the answers file (excel) DESCRIPTION :
1- a microsoft forms is filled
2- a table in excel is updated accordingly
3- I have added a column where I put a condition "if" and a cross if put in the cell or not (if date is matching the filling date). This column is part of the table
4- using Power automate emails are sent where "x" is present in the different rows.
PROBLEM : the flow does work for all the rows with "x" appart from the last row (the one just fullfilled by the form). It seems that the execiution of the flow goes to fast and do not take into account the last answer of the form.
DESCRIPTION :
1- a microsoft forms is filled
2- a table in excel is updated accordingly
3- I have added a column where I put a condition "if" and a cross if put in the cell or not (if date is matching the filling date). This column is part of the table
4- using Power automate emails are sent where "x" is present in the different rows.
PROBLEM : the flow does work for all the rows with "x" appart from the last row (the one just fullfilled by the form). It seems that the execiution of the flow goes to fast and do not take into account the last answer of the form.


text:
Q: Css-footer and background I've been working on website recently and have come across a major problem :http://jimbob.webatu.com/index.html(you'll need to see the coding on the webpage).I've set my website up so that there are two main columns but are centered into the middle.The id wrap is what centers everything together and the two columns float left or right:
     #wrap    {
     width:750px;
     margin:0 auto;
     background-color:#6E6E6E;
     border-left:3px solid #A9E2F3;
     border-right:3px solid #A9E2F3;
     }
     #main    {
     float:left;
     width:496px;
     background:white;
     border-top-right-radius:5px 5px;
     border-bottom-right-radius:5px 5px;
     }
     #sidebar {
     float:right;
     width:250px;
     } `

Recently though i tried to add a footer bar like with the navigation bar at the top. this has been set to stay in the warp overall by using "clear:both" and have been trying to make it avoid the "wrap" id altogether.However something has gone wrong and the div's that control the "wrap"and "secondborder" won't fully close. Also as you may see a gray bar has appeared behind and the "wrap"background won't apply(I've set the sidebar background to nothing so that the "wrap" background applies to it. This makes it look a bit neater).I cannot paste the required coding as there is too scattered and is too long(look at the page source on the webpage).
Can anyone provide a solution to the "wrap" background and the "footer" not centering? I have only been learning html and coding for the past 3 months so please forgive me if this is a stupid mistake I've made. The link again to my website where the problem is : http://jimbob.webatu.com/index.html

A: Add the overflow: hidden; to your #wrap as such
#wrap {
    width: 750px;
    margin: 0 auto;
    background-color: #6E6E6E;
    border-left: 3px solid #A9E2F3;
    border-right: 3px solid #A9E2F3;
    height: auto;
    overflow: hidden;
    }

In order for your #footer to act like a footer at the bottom of your page you will have to take it out of your #sidebar and place it after the closing  for #sidebar. This should fix your problems.
To fix the #sidebar being cut off you need to float it left as opposed to right as suc,
#sidebar {
    float: left;
    width: 250px;
    }

Hopefully this helps.

A: Generally speaking you need to clear after your floating div's. This tells the browser to stop the floating for the next element. Looking at your HTML I'd add before the

Also, before you close #wrap add another

A: I just added a new div to your secondborder element:

 that sorted the problem. You were floating and not clearing the sidebar or the main div.


text:
Q: awk: non-terminated string I'm trying to run the command below, and its giving me the error. Thoughts on how to fix? I would rather have this be a one line command than a script.
grep  "id\": \"http://room.event.assist.com/event/room/event/" failed_events.txt |
head -n1217 |
awk -F/ ' { print $7 } ' |
awk -F\" ' { print "url \=  \"http\:\/\/room\.event\.assist\.com\/event\/room\/event\/'{ print $1 }'\?schema\=1\.3\.0\&form\=json\&pretty\=true\&token\=582EVTY78-03iBkTAf0JAhwOBx\&account\=room_event\"" } '
awk: non-terminated string url =  "ht... at source line 1
 context is
     >>>  <<<
awk: giving up
 source line number 2

The line below exports out a single column of ID's:
grep  "id\": \"http://room.event.assist.com/event/room/event/" failed_events.txt |
    head -n1217 |
    awk -F/ ' { print $7 } '

156512145
898545774
454658748
898432413

I'm looking to get the ID's above into a string like so:
" url = "string...'ID'string"

A: take a look what you have in last awk :
 awk -F\"
 '  #single start here
    { print "  #double starts for print, no ends

        url \=  \"http\:\/\/room\.event\.assist\.com\/event\/room\/event\/
 '   #single ends here???

        { print $1 }'..... #single again??? ...
(rest codes)

and you want to print exact {print } out? i don't think so. why you were nesting print ?

A: Most of the elements of your pipe can be expressed right inside awk.
I can't tell exactly what you want to do with the last awk script, but here are some points:

*

*Your "grep" is really just looking for a string of text, not a
regexp.

*You can save time and simplify things if you use awk's
index() function instead of a RE. Output formats are almost always
best handled using printf().

Since you haven't provided your input data, I can't test this code, so you'll need to adapt it if it doesn't work.  But here goes:
awk -F/ '
  BEGIN {
    string="id\": \"http://room.event.assist.com/event/room/event/";
    fmt="url = http://example.com/event/room/event/%s?schema=whatever\n";
  }

  count == 1217 { nextfile; }

  index($0, string) {
    split($7, a, "\"");
    printf(fmt, a[0]);
    count++;
  }' failed_events.txt

If you like, you can use awk's -v option to pass in the string variable from a shell script calling this awk script.  Or if this is a stand-alone awk script (using #! shebang), you could refer to command line options with ARGV.


text:
Q: Sampling an MVar, can I avoid unsafePerformIO? I have
sample :: MVar a -> IO [a]
sample v = do
   a <- takeMVar v
   pure (a:unsafePerformIO (sample v))

which appears to be a legitimate use of unsafePerformIO to me. But I am very interested to know how to avoid it! Is there a pattern for this use already?

A: You can implement a similar function using a thread, a Chan and getChanContents:
sample :: MVar a -> IO [a]
sample v = do
   c <- newChan
   forkIO $ forever $ takeMVar v >>= writeChan c
   getChanContents c

The thread/getChanContents approach is slightly better, since at least you can rely on the MVar being continuously taken. Instead, the unsafePerformIO approach will run takeMVar at impredictable points, making the putMVars blocking in a similarly impredictable way. Of course, the getChanContents approach will buffer all the data, possibly requiring more memory.
However, both approaches are essentially similar to lazy IO, which is best to be avoided, in my opinion.


text:
Q: Highcharts gauge not showing colour as expected I have 3 stops at 0.4, 0.6 and 0.8 (red, green, blue). The maximum is 100 (for percent)
If I set the data as 50, I expect it to be green but it seems to be a mix of the green and red. It's only when I get to 60 that it's bright green that I expect.
Anyway to remove the gradient?
https://jsfiddle.net/sy3r2hj7/1/
var gaugeOptions = {

    chart: {
        type: 'solidgauge'
    },

    title: null,

    pane: {
        center: ['50%', '85%'],
        size: '140%',
        startAngle: -90,
        endAngle: 90,
        background: {
            backgroundColor: (Highcharts.theme && Highcharts.theme.background2) || '#EEE',
            innerRadius: '60%',
            outerRadius: '100%',
            shape: 'arc'
        }
    },

    tooltip: {
        enabled: false
    },

    // the value axis
    yAxis: {
        stops: [
            [0.40, '#ff0000'],
            [0.60, '#00ff00'], // yellow
            [0.80, '#0000ff'] // red
        ],
        lineWidth: 0,
        minorTickInterval: null,
        tickAmount: 2,
        title: {
            y: -70
        },
        labels: {
            y: 16
        }
    },

    plotOptions: {
        solidgauge: {
            dataLabels: {
                y: 5,
                borderWidth: 0,
                useHTML: true
            }
        }
    }
};

// The speed gauge
var chartSpeed = Highcharts.chart('container-speed', Highcharts.merge(gaugeOptions, {
    yAxis: {
        min: 0,
        max: 100,
        title: {
            text: 'Speed'
        }
    },

    credits: {
        enabled: false
    },

    series: [{
        name: 'Speed',
        data: [60],
        dataLabels: {
            format: '
{y}
' +
                   'km/h
'
        },
        tooltip: {
            valueSuffix: ' km/h'
        }
    }]

}));

A: Instead of using stops property, you can change the color of the point programmatically, based on some condition:
    events: {
        render: function() {
            var point = this.series[0].points[0];
            if (point.y < 40) {
                point.graphic.attr({
                    fill: '#ff0000'
                })
            } else if (point.y < 60) {
                point.graphic.attr({
                    fill: '#00ff00'
                })
            } else {
                point.graphic.attr({
                    fill: '#0000ff'
                })
            }
        }
    }

Live demo: https://jsfiddle.net/BlackLabel/fw594Lmg/


text:
Q: HTML - bootstrap module wont load Can you please see why my module does not load? The module is loaded under
. When I call it in the third last column. When I test this code it wont work. Can you help me to see what went wrong? Thank you.
Stefan
<!DOCTYPE html>

    <link href='https://fonts.googleapis.com/css?family=Lato:100,300'      rel='stylesheet' type='text/css'>
    <link rel="stylesheet" href="css/bootstrap.min.css">
    <link rel="stylesheet" href="css/style.css">

  <button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">
    Launch demo modal
  </button>

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

My favorite App

          hello how are you
          ...

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

Jane Doette

Front-end Ninja

Featured Work

test

Link to project

Appify

Link to project

Appify

Link to project

A: i think all you need is bootstrap.js, and make sure bootstrap path corect

A: Read bootstrap documentation for model.
Bootstrap documentation of model


text:
Q: get OpenFileDialog button pressed I'm using an OpenFileDialog to let the user chose a file to open.
it works, but if I chose a file and insted of pressing OK I press CANCEL it still opens the file because I picked up one.
I found this code in the MSDN, but I can't see ::DialogResult::OK in my apllication
if ( openFileDialog1->ShowDialog() == ::DialogResult::OK )
  {
     if ( (myStream = openFileDialog1->OpenFile()) != nullptr )
     {
        // Insert code to read the stream here.
        myStream->Close();
     }
  }

my code is:
fileD1->ShowDialog();
while(!fileD->FileName->Lenght!=0)
{
}
and here I open the file

any other idea of how to know which button I pressed?
I'm using c++ and visual studio 2008

A: save the return of this ->> openFileDialog1->ShowDialog()
into a value and then check the value
DialogResult::OK
or
DialogResult::CANCEL


text:
Q: Deriving a QM expectation value for a square of momentum $\langle p^2 \rangle$ I already derived a QM expectation value for ordinary momentum which is:
$$
\langle p \rangle=  \int\limits_{-\infty}^{\infty} \overline{\Psi}  \left(- i\hbar\frac{d}{dx}\right) \Psi \, d x
$$
And I can read clearly that operator for momentum equals $\widehat{p}=- i\hbar\frac{d}{dx}$. Is there an easy way to derive an expectation value for $\langle p^2 \rangle$ and its QM operator $\widehat{p^2}$?

A: Well, $\widehat{p^2} = \hat{p}^2= \hat{p} \hat{p}$.
So, in the position basis it is $-\hbar^2 \frac{d^2}{dx^2}$, and $\langle p^2 \rangle = \int_{-\infty}^\infty \bar{\Psi}\left(-\hbar^2 \frac{d^2}{dx^2} \right)\Psi dx$.
Note: $\hat{p}$ is technically not equal to $-i\hbar d/dx$, but rather in the position basis $\langle x | \hat{p}| x' \rangle = -i\hbar d/dx \delta(x-x')$.

A: The expectation value for some operator $A$ is given by
$$\langle A\rangle = \int \Psi^*A\Psi.$$
If we set $A=p$ then we get the expression you've written above. Now just set $A = p^2$ to get what you want.

A: Between any two vectors $| \psi_1 \rangle$, $| \psi_2 \rangle \in \mathcal H$ $$\langle \psi_1 | \hat p^2 | \psi_2 \rangle = \langle \psi_1 | \hat p | \psi_2' \rangle = \langle \hat p \psi_1 | \psi_2' \rangle = \langle \hat p  \psi_1 | \hat p \psi_2 \rangle.$$
In the first equality, $|\psi_2'\rangle = \hat p | \psi_2 \rangle \in \mathcal H$ by definition of a linear operator acting on a vector space. In the second, we used that $\hat p$ is hermitian. In particular, for an expectation, $$\langle \psi | \hat p^2 | \psi \rangle = \langle \hat p  \psi | \hat p \psi \rangle = \int_{\mathcal D} ( \hat p \psi)^* (\hat p \psi)\,\mathrm{d}x,$$ so one need only really compute $\hat p \psi(x)$.


text:
Q: Maintain aspect ratio and relative position in a Visio group I'm currently creating a custom container shape in Visio 2010 but having some trouble getting the correct resizing behavior.
My container consists of a main rectangle and a small triangular shape at the top right (see image). Both these shape are grouped.

When resizing this group, I want the rectangle to resize, but the triangle should keep its original size ans aspect ratio and remain "attached" to the side of the rectangle.
When I set the triangle's resize behavior to "Use group setting" (default), it gets deformed when resizing:

When I set the triangle's resize behavior to "Reposition only", it does not maintain attached to the rectangle:

Is there any way I can get the desired behavior?

A: If you want to keep the triangle in the same relative position, and at the same absolute size, you'll need to use the shapesheet.
The formulae you're interested in will be the PinX, PinY, Width, and Height for the rectangle.  The Width and Height should stay the same, so the formula should just be =GUARD(0.25 in.), where you replace 0.25 with whatever the width or height should be.
When you grouped the shapes, Visio automatically set up formulas to stretch the sub shapes, and move them as a proportion of the size of the group shape.  So if you look at the PinX formula for the Triangle, it might be something like: =Sheet.1!Width*0.95 .  That just means the triangle's X location will always be at 95% of the width of the parent shape.
But that's not what you want.  What you want is for the triangle always to sit on the right edge of the rectangle.  So to do that your formula just has to calculate to be the right edge of the rectangle (its width) plus half the width of your triangle (the Pin location default is the midpoint of your shape).
So to make your formula you need the ID of the rectangle sub shape, which you can find by accessing the Format->Special dialog for the rectangle.  Once you get that number, the PinX formula for the triangle should just be =GUARD(Sheet.RectangleID!Width+(Width/2))
I think the PinY for the triangle should be all set as it is, as long as the width and height are guarded.

A: Edit the shapesheet for the triangle so the width is a function of the height. W=H*AspectRatio
Make sure you protect the cell so that it does not change.

A: Seems like that's the intended behavior: http://blogs.msdn.com/b/visio/archive/2007/01/30/working-with-resizemode.aspx.


text:
Q: How do I add a filter to wp_list_categories() to make links nofollow? How can I add a rel="nofollow" attribute to my category widget listings?
I'm currently filtering the call to wp_list_categories with this code in my functions.php...
function my_wp_list_categories($cat_args){
    $cat_args['title_li'] = '';
    $cat_args['exclude_tree'] = 1;\
    $cat_args['exclude'] = 1;
    $cat_args['use_desc_for_title'] = 0;
    return $cat_args;
    }
add_filter('widget_categories_args', 'my_wp_list_categories', 10, 2);

Update: When I try this...
add_filter('wp_list_categories','wp_rel_nofollow');

My links come out with escape slashes...

  Chinese Tea

A: try:
add_filter('wp_list_categories','esc_wp_rel_nofollow');

function esc_wp_rel_nofollow($output){
   return   stripslashes(wp_rel_nofollow($output));
}


text:
Q: Stabilising chain of submodules Take $S$ to be a commutative ring with unit, and $N \subset M$ to be $S$-modules. I am interested in the necessary and sufficient condition for it to be the case that for every collection of submodules $\{M_i\}_{i=1,\dots,n}$, such that $M_i \cap N = 0$, they form a stabilising chain,
$$M_1 \subset M_2 \subset \cdots \subset M_{n}.$$
I believe a necessary and sufficient condition is that every $M_i$ such that $M_i\cap N=0$ is finitely generated. I know that if every submodule was finitely generated, then $M$ would be Noetherian, and thus I am guaranteed this stabilising chain.
However, if I am only requiring that $M_i$'s such that $M_i \cap N = 0$ be finitely generated, this does not exclude the possibility of submodules which are not finitely generated to exist in $M$ so $M$ is not being required to be Noetherian, and so I am not guaranteed this stabilising chain. How can I approach this?

A: EDIT: This answer is completely wrong, so don't bother reading it. I'll leave it up for the record; details are in the comments, but I amateurishly confused the set $M \setminus N \cup \{ 0 \}$ with the submodule that it generates.
Let $M_N$ be the smallest submodule of $M$ containing $\left( M \setminus N \right) \cup \{ 0 \}$. The submodules of $M_N$ are exactly the submodules $M_i \leq M$ s.t. $M_i \cap N = \{ 0 \}$. The property in question is thus equivalent to whether $M_N$ is Noetherian or not. There are two cases.

*

*Trivially, $M_N$ could simply be $M$ itself, i.e. $M$ has a generating set in $M \setminus N$.

*$M_N$ could be a proper submodule of $M$. Since $M \setminus M_N = N \setminus \{ 0 \}$, this works out to say that at least one non-identity of element $N$ cannot be written as a linear combination of elements of $M_N$ over $S$.


text:
Q: Why is EF losing it's connection details on aws lambda startup We have an API using entity framework, this is running in AWS lambda on the public.ecr.aws/lambda/dotnet:5.0 image. We are having an issue with it making a connection to a remote server on an internal network. If I test the setup on an EC2 windows server then it runs fine, but on the lambda function it is returning the following errors:
[Debug] Microsoft.EntityFrameworkCore.Database.Connection: Opening connection to database 'DatabaseXYZ' on server '10.0.10.30'.
[Debug] Microsoft.EntityFrameworkCore.Infrastructure: 'EFDbContext' disposed.
[Error] Microsoft.EntityFrameworkCore.Database.Connection: An error occurred using the connection to database '' on server ''.

We can't work out why we are getting this error. It is a very similar setup to our other dotnet apps running on lambda which use RDS databases, the only difference is that this DB is running on-prem via a VPN - as mentioned above the API works if we load it on a EC2 instance but we want to use this on Lambda - and need to understand why the issue is occurring.
The lambda is also setup in the vpc on private subnets.
As a test I ran this code as an image in Lambda and was able to connect and query just fine.


text:
Q: Print value result on same line (Python) I have this to do:
import psutil
import read_config

mem = psutil.virtual_memory()

print('Total RAM: ', (round(mem[0] / (1024 * 1024))), '(MB)')  # total

ram_usage = read_config.ram_usage

while ram_usage is True:
    mem = psutil.virtual_memory()
    print('Used RAM: ', (round(mem[3] / (1024 * 1024))), '(MB)', end="")  # used

The problem is that if I execute, the output is this:
Total RAM:  3949 (MB)
Used RAM:  3069 (MB)Used RAM:  3069 (MB)Used RAM:  3069 (MB)Used RAM:  3069 (MB)Used RAM:  3069 (MB)

How can I solve the Used RAM problem ? I want to print on the second line just value of used RAM, not to print the line everytime the condition is satisfied.
Thanks

A: To detect if the value has changed, simply save the old value and then print conditionally:
old_mem = 0
while ram_usage is True:
    mem = psutil.virtual_memory()
    if mem[3] != old_mem:
        old_mem = mem[3]
        print('Used RAM: ', (round(mem[3] / (1024 * 1024))), '(MB)')

This would however detect very small changes. If you just want to print when the displayed value would change, first convert to MB and then compare:
old_mem = 0
while ram_usage is True:
    mem = psutil.virtual_memory()
    mem_mb = round(mem[3] / (1024 * 1024))
    if mem_mb != old_mem:
        old_mem = mem_mb
        print('Used RAM: ', mem_mb, '(MB)')


text:
Q: Inserting values into different database using select and union I am trying to insert three column's values (v1, v2, v3) from three different tables (v1 from table1, v2 from table2, v3 from table3) into db1.dest_table from another db2.
Schema is ready at destination. I want to insert the values into another database table. I did union and used select statement and then tried to insert.
But after executing the below code I get this error:

Msg 120, Level 15, State 1, Line 63
  The select list for the INSERT statement contains fewer items than the insert list. The number of SELECT values must match the number of INSERT columns.

INSERT INTO dffwarehouse.[dbo].[dest_table] (v1, v2, v3)
    SELECT v1 FROM [dbo].[table1]
    UNION ALL
    SELECT v2 FROM [dbo].[table2]
    UNION ALL
    SELECT v3 FROM [dbo].[table3];

I want columns (v1, v2, v3) in database db2, table dest_table.

A: Sample data and desired results would help.  If you want each value in a separate columns, with the other values NULL, then you can use UNION ALL:
INSERT INTO dffwarehouse.[dbo].[dest_table] (v1, v2, v3)
    SELECT v1, NULL, NULL FROM [dbo].[table1]
    UNION ALL
    SELECT NULL, v2, NULL FROM [dbo].[table2]
    UNION ALL
    SELECT NULL, NULL, v3 FROM [dbo].[table3];

If you want all combinations, use CROSS JOIN:
INSERT INTO dffwarehouse.[dbo].[dest_table] (v1, v2, v3)
    SELECT t1.v1, t2.v2, t3.v3
    FROM [dbo].[table1] t1 CROSS JOIN
         [dbo].[table2] t2 CROSS JOIN
         [dbo].[table3] t3;

A: You could use inner join if there any relationship between those tables.


text:
Q: Is this loop problematic for the analog readings? Two single-ended output transducers Tr1 and Tr2 are powered from the same power supply and their output is connected to shielded twisted pair. Their ground and the shield connected at the source ground which is recommended. The transducers' grounds are internally connected to their DC power ground. The transducers are floating with respect to earth and they are grounded on the data-acquisition side to AIGND. The AIGND is tied to the earth. Below is the drawing for the system:

The data-acquisition device multiplexes each differential inputs one by one by one and establishes the connection to the inAmp as shown above.
So far so good, but when I looked at this configuration carefully I noticed a loop following the points A-->B-->C-->D--A.
My question is, this is not a ground loop since the source is not earth grounded in source side. But is this loop still problematic? If so each traducer should use a separate power supply?
edit for a comment:

A:
My question is, this is not a ground loop since the source is not
  earth grounded in source side. But is this loop still problematic? If
  so each traducer should use a separate power supply?

Firstly if point A is connected to measurement ground via a 10 k resistor then the other 10 k resistor is superfluous. Get rid of it. Now there isn't a loop. However, that loop would not be a problem because it would not carry plant earth fault currents i.e. only one point was hard grounded. Each transducer does not need to use a seperate power supply normally but, as always with a question like this, there can be exceptions when devices are not specified.

Their ground and the shield connected at the source ground which is
  recommended

If this is recommended then so be it but, the normal default procedure is to ground the shield/screen at the receiver end because it is that shield that needs to be tied to local receiver ground to minimize common-mode noise at the receiver end.


text:
Q: How I do specific merging between 2 text files(or 1 text file and 1 string) in C language? I have 2 text files or 1 text file and 1 string with next form:
file1.txt
Line1 ....
Line2....
{
line3..
line4 ..
}
line5..
file2.txt or a string
line1 ...
line2 ...
{
}
line5...
line11 ...
Result: another .txt file or the same file1.txt
Line1 ....
Line2....
{
line3..
line4..
}
line 5...
line11 ...
I would like to do a specific merge in C and what is between this characters { } I don't want to be overwritten, only what is before and after these (if they are different line, of course). Any hint will be great!


text:
Q: How can I add an xml configuration file to a docker image via a Dockerfile? I built a .jar file that accesses an .xml file
I add this jar file to docker via a Dockerfile
But how do I add this xml file to the docker image?

A: ADD test-harness.xml test-harness.xml
This basically adds the .xml file to the Docker image and makes it accessible to the jar file which was added in a similar way.

A: According to the Dockerfile best practices, the COPY command is preferred on the ADD command:

Although ADD and COPY are functionally similar, generally speaking, COPY is preferred.

recommended reading for your task:

*

*The "ADD or COPY" section in the Dockerfile best practices.

*Docker Tip #2: The Difference between COPY and ADD in a Dockerfile


text:
Q: Python - Win32Com Client Dispatch Hanging as Scheduled Tasks I have a Python Script, which uses win32com.client.dispatch and redemption in order to connect to an instance of Outlook and harvest some data from a public folder.
When I execute this script on command line it works just fine.
Adding it as a scheduled task, it appears to get hung at the line Outlook = win32com
I added Event Log statements along the way to see where it is getting hung, other than that I don't have much in the way of error logs (since it doesnt actually fail)
Is there any sort of security settings I should be concerned about or anything I am not thinking of? Everything works fine with a standard python call in the CMD.

A: Scheduler runs as a service, and office apps (Outlook included) should nto be used in a service.


text:
Q: How do I show different images based on a variable? I am working on a school assessment, where my goal is to be able to select an image and show that image on a grid based on which grid cell is clicked.
I have mostly been trying to fix my issue with different variations on the getElementsByClassName tag to change the source of the image shown in the cell. Currently, I have an array of the source of every different Image, and changing it using a function. Storing the images in html would not be an option for me because I would have to store all 23 images 9 times, but I have not managed to get it to work in CSS either. Previously, I had my images inside divs but I thought that it would work better if I attempted to change the background image tag but that didn't work either.

function clickitem(itemnum) {
    "use strict";
    selected_item = itemnum;
}
function gridclick(gridpos) {
    "use strict";
    document.getElementsByClassName("grid-img " + gridpos).style.backgroundImage = images[selected_item];
}

My main issue is that my images just won't show up. No error messages in console just nothing.

A: document.getElementsByClassName only works for a single class.
If you want to you multiple classes try document.querySelectorAll('.craft-grid,.1')
--
But I recommend you to do this instead:

function gridclick(el) {
    el.style.backgroundColor = el.style.backgroundColor == "red" ? "" : "red"; //clicked element style
    console.log(el.getAttribute('data-something')); // data attribute
    console.log([...el.parentElement.children].indexOf(el)); // index of the element relative to the parent
}
.craft-grid{
  cursor:pointer;
}

1

2

Use the element as reference is enough. If you want the element to have some data use the data attribute.