text:
Q: Indent, pretty-print code including Django template tags, HTML, CSS, and JavaScript In dealing with a bunch of crufty Django template files, I want to indent them.
The files contain:

*

*HTML, the bulk of the file.  Maybe a pre tag or two.

*JavaScript, inside script tags.

*CSS inside the style tags

*Django template directives inside {% ... %} pairs.

Surely there is a tool to do this.  Most of the tools do silly things when facing unexpected characters.   Which one works?
To clarify, what properly indents this code?
{% extends 'layout.html' %}
{% if admin %}

ADMIN SCREEN

{% endif %}

a

b

I've tried various tools, including the Universal Indent GUI, without success.

A: Try http://prettydiff.com/?m=beautify
See if that gets what you want.  If you specifically need to address HTML tags that do not have a closing pair, such as
, then add the &html attribute to the address above.  It should do everything you need as per the stated requirements.

A: This isn't perfect, but:

*

*Install django-vim http://www.vim.org/scripts/script.php?script_id=1487

*Highlight lines in visual mode

*press '='

Voila!  The power of vim.

A: If you use Sublime Text I recommend installing a package called HTML-CSS-JS Prettify.
You can get the package from PackageControl Here.


text:
Q: How to handle taps on a custom callout view? I am adding a callout view like this:
func mapView(mapView: MKMapView!,
        didSelectAnnotationView view: MKAnnotationView!) {
    let calloutView = UIView(frame:
        CGRect(x: 0, y: 0, width: 300, height: 120))

    calloutView.backgroundColor = UIColor.purpleColor()
    calloutView.center = CGPointMake(CGRectGetWidth(view.bounds) / 2.0, 0.0)
    calloutView.layer.anchorPoint = CGPointMake(0.5, 1.0)
    calloutView.layer.masksToBounds = false

    calloutView.userInteractionEnabled = true
    let calloutViewTapRecognizer = UITapGestureRecognizer(target: self,
        action: "onCalloutViewTap")
    calloutView.addGestureRecognizer(calloutViewTapRecognizer)

    view.addSubview(calloutView)
}

Though my onCalloutViewTap function is never called... I am curious to understand why and to get something that works to handle interactions with my callout view.

A: It's because your annotation view only detects touches inside its bounds. Since your callout view extends beyond the bounds, the subview doesn't recognize the tap. You need to override the pointInside:withEvent: method in the annotation view so your callout will actually detect the touch.
Here's an example in Objective-C:
- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent*)event
{
    CGRect rect = self.bounds;
    BOOL isInside = CGRectContainsPoint(rect, point);

    if (!isInside)
    {
        for (UIView *view in self.subviews)
        {
            isInside = CGRectContainsPoint(view.frame, point);

            if (isInside)
            {
                break;
            }
        }
    }

    return isInside;
}

EDIT:
Swift version:
override func pointInside(point: CGPoint, withEvent event: UIEvent?) -> Bool {
    let rect = self.bounds
    var isInside = CGRectContainsPoint(rect, point)

    if (!isInside) {
        for subview in subviews {
            isInside = CGRectContainsPoint(subview.frame, point)

            if (isInside) {
                break
            }
        }
    }

    println(isInside)

    return isInside;
}

A: Swift 4.0
override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
    let rect = self.bounds;
    var isInside: Bool = rect.contains(point);
    if(!isInside)
    {
        for view in self.subviews
        {
            isInside = view.frame.contains(point);
            if isInside
            {
                break;
            }
        }
    }
    return isInside;
}
 override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
    let hitView = super.hitTest(point, with: event)
    if (hitView != nil)
    {
        self.superview?.bringSubview(toFront: self)
    }
    return hitView
}

A: Removing from annotation view swift 5
override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
        let hitView = super.hitTest(point, with: event)
        if (hitView != nil)
        {
            self.superview?.bringSubviewToFront(self)
        }
        return hitView
    }
    override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
        let rect = self.bounds;
        var isInside: Bool = rect.contains(point);
        if(!isInside)
        {
            for view in self.subviews
            {
                isInside = view.frame.contains(point);
                if isInside
                {
                    break;
                }
            }
        }
        return isInside;
    }

redpajama_set_name: RedPajamaStackExchange


text:
Q: Three.js How to use quaternion to rotate camera In Three.js, I would like to use THREE.quaternion to make the camera object rotate to the selected object.
I did search the web but found no example/demo or document about how to use this quaternion class.
I try my luck with following code:
    camera = new THREE.PerspectiveCamera( 40, window.innerWidth / window.innerHeight, 1, 10000 );
    camera.position.y = 10;
    camera.position.z = 0;
    camera.position.x = radious;
    camera.useQuaternion = true;

   // I did use the TrackballTrackballControls. Maybe it causes the problem so I put it here
    controls = new THREE.TrackballControls( camera, document.getElementById(_canvasElement) );

    // function to make the camera rotate to the object
    function focusOn3DObject(obj){
        obj.useQuaternion = true;
        obj.quaternion = new THREE.Quaternion(obj.position.x, obj.position.y, obj.position.z, 1);

        var newQuaternion = new THREE.Quaternion();
        THREE.Quaternion.slerp(camera.quaternion, obj.quaternion, newQuaternion, 0.07);
        camera.quaternion = newQuaternion;
    }

But it doesn't work. Did I miss something?
Please help. Thanks in advance.

A: You can use the method applyQuaternion from ThreeJs
 const quaternion = new THREE.Quaternion(obj.position.x, obj.position.y, obj.position.z, 1);

 camera.applyQuaternion(quaternion); // Apply Quaternion

 camera.quaternion.normalize();  // Normalize Quaternion

A: I think this line wont work:
obj.quaternion = new THREE.Quaternion(obj.position.x, obj.position.y, obj.position.z, 1);

You need to set
obj.useQuaternion = true

After adding object to scene, when you rotate it will be automatically applied to obj.quaternion.
The second point is you should apply the object to your controls and not the camera. Because you want to control the object and not the camera?

A: Slerp is quite easy. It takes 4 parameters:

*

*targetRotation the actual camera rotation

*destinationRotation the object rotation

*destinationRotation new quaternion which will be the new camera rotation

*percentOfRotation this parameter is playground, I'm using 0.07 here right now, could be value between 0 (0%) and 1 (100%)

This is my rotation method:
var qm = new THREE.Quaternion();
THREE.Quaternion.slerp(camera.quaternion, destRotation, qm, 0.07);
camera.quaternion = qm;
camera.quaternion.normalize();

Hopefully this will help you. And don't bother I also worked some weeks on the perfect camera following.

A: This is how I've done it :

*

*Get the current quaternion of your camera (initialQuaternion)

*Create a clone of your camera

*Make the clone look at the target using the lookAt method

*The thing is, the lookAt method of the camera will actually make it look AWAY from the target, so you have two options :

*

*Either use the lookAt method directly, then invert the rotation

*Or compute the position the target should have so that when looking away from it, you actually look in the correct direction

*Get the new quaternion of the clone (targetQuaternion)

*By using an animation loop, do a slerp between the initialQuaternion and the targetQuaternion

A: I have tried using it:
    var newQuaternion = new THREE.Quaternion();
        THREE.Quaternion.slerp(camera.quaternion, obj.quaternion, newQuaternion, 0.01);
        camera.quaternion = newQuaternion;
        camera.quaternion.normalize();
        camera.matrixAutoUpdate();

However, I have failed to get the desired outcome. I know it is a fairly old post but I would be happy if someone could respond. I didn't see any other relevant posts other than this so really hoping for someone to respond.
Here is my problem in detail: Rotate camera to look at Selected object in three.js


text:
Q: ADD SQL QUERY STAT I'm trying to update the records from textboxes into the Access database, I'm wondering every time I hit save, it generates an error

An unhandled exception of type 'System.Data.OleDb.OleDbException' occurred in System.Data.dll
Additional information: No value given for one or more required parameters.

Highlighting .ExecuteNonQuery()
What does it mean? It's preventing me to run my code :(
Private Sub SaveButton_Click(sender As Object, e As EventArgs) Handles SaveButton.Click
        Dim empNum As String
        Dim empFname As String
        Dim empLname As String
        Dim empDept As String
        Dim empStat As String
        Dim empYears As String

        empNum = eNumText.Text
        empFname = empFnameText.Text
        empLname = empLnameText.Text
        empDept = DeptText.Text
        empStat = StatText.Text
        empYears = yearstext.Text

        con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source= c:\Databse\Company_db.accdb"
        con.Open()

        Dim SqlAdapter As New OleDbDataAdapter
        Dim Table As New DataTable

        Dim sqlQuery As String = "UPDATE tbl_empinfo " & _
        "SET FirstName=empFname, LastName=empLname, Department=empDept, " & _
        "Status=empStat, Years=empYears " & _
        "WHERE empID=empNum"

        Dim cmd As New OleDbCommand
        With cmd
            .CommandText = sqlQuery
            .Connection = con
            .Parameters.AddWithValue("FirstName", empFname)
            .Parameters.AddWithValue("LastName", empLname)
            .Parameters.AddWithValue("Department", empDept)
            .Parameters.AddWithValue("Status", empStat)
            .Parameters.AddWithValue("Years", empYears)
            .ExecuteNonQuery()
        End With

        Using cmd2 = New OleDbCommand(sqlQuery, con)
            cmd.Parameters.AddWithValue("FirstName", empFname)
            cmd.Parameters.AddWithValue("LastName", empLname)
            cmd.Parameters.AddWithValue("Department", empDept)
            cmd.Parameters.AddWithValue("Status", empStat)
            cmd.Parameters.AddWithValue("Years", empYears)
            cmd.ExecuteNonQuery()
        End Using

        sqlQuery = "SELECT * FROM tbl_empinfo "
        Dim cmd1 As New OleDbCommand
        Dim da As New OleDbDataAdapter

        With cmd1
            .CommandText = sqlQuery
            .Connection = con
            With SqlAdapter
                .SelectCommand = cmd1
                .Fill(Table)
            End With
            With DataGridView1
                .DataSource = Table
            End With
        End With

        con.Close()
    End Sub

A: You are trying to set an UPDATE command text for the SelectCommand of the Adapter. This, of course has no way to be successful. Last but not least the UPDATE command text doesn't contain a WHERE clause, and so, if executed, it updates every record in the table tbl_empinfo with the same data.
In this context there is no need to use an adapter. You could simply execute the command, providing an appropriate WHERE clause and the values for the other parameters
   Dim sqlQuery As String = "UPDATE tbl_empinfo " & _
        "SET FirstName=?, LastName=?, Department=?, " & _
        "Status=?, Years=? " & _
        "WHERE empID=?"

    Dim cmd As New OleDbCommand
    With cmd
        .CommandText = sqlQuery
        .Connection = con
        .Parameters.AddWithValue("@p1", empFName)
        .Parameters.AddWithValue("@p2", empLName)
        .Parameters.AddWithValue("@p3", empDept)
        .Parameters.AddWithValue("@p4", empStat)
        .Parameters.AddWithValue("@p5", empYears)
        .Parameters.AddWithValue("@p6", empNum)
        .ExecuteNonQuery()
    End With

After this you could call the code that reloads the data to fill your grid
    sqlQuery = "SELECT * FROM tbl_empinfo"
    Dim cmd1 As New OleDbCommand
    Dim da As New OleDbDataAdapter
    Dim Table As New DataTable

    With cmd1
        .CommandText = sqlQuery
        .Connection = con
        With da
            .SelectCommand = cmd1
            .Fill(Table)
        End With
        With DataGridView1
            .DataSource = Table
        End With
    End With

Notice that I have changed the name of the command and the adapter to a less confusing names. SqlCommand And SqlDataAdapter are the names of the classes equivalent to the OleDbCommand and OleDbDataAdapter but used for Sql Server. At first sight I was thinking that you were trying to use the SqlClient classes to update an MS-Access database.


text:
Q: JS/TS: object destructuring i've a variable named props.
The type extends from VariantTheme, VariantSize, VariantGradient, & React.DOMAttributes<HTMLOrSVGElement>
Then i want to make one more variable, let say htmlProps.
I want to fill the htmlProps from props.
I don't want it filled with a foreign props other than listed on React.DOMAttributes<HTMLOrSVGElement>.
Then spread the filtered prop into react component.
Here the not working code:
export interface Props
    extends
        VariantTheme,
        VariantSize,
        VariantGradient,
        React.DOMAttributes<HTMLOrSVGElement>
{
    tag?     : keyof JSX.IntrinsicElements
    classes? : string[]
}
export default function Element(props: Props) {
    const elmStyles     = styles.useStyles();

    // themes:
    const variTheme     = useVariantTheme(props);
    const variSize      = useVariantSize(props);
    const variGradient  = useVariantGradient(props);

    const Tag       = (props.tag ?? 'div');
    const htmlProps = props as React.HTMLAttributes<HTMLOrSVGElement>; // not working! Still containing strange props from VariantTheme, VariantSize, tag, classes, ...
    return (
        <Tag {...htmlProps}
            className={[
                elmStyles.main,

                // themes:
                variTheme.class,
                variSize.class,
                variGradient.class,

                ...(props.classes ?? []),
            ].filter((c) => !!c).join(' ')}
        >
            {(props as React.PropsWithChildren<Props>)?.children}
        </Tag>
    );
};

Do you have an idea to fix my code?

A: @spender already gave you the answer. Typescript only exists at compile time and what you are really doing is telling the compiler that props is now of type React.HTMLAttributes<HTMLOrSVGElement>, but you are still responsible on how the props are composed. In sum typescript does not alter how your javascript code works, it only helps you find mistakes at compile time.
One solution for your use case is to have htmlProps as a property of props and then spread these to Tag.
export interface Props
    extends
        VariantTheme,
        VariantSize,
        VariantGradient
{
    tag?     : keyof JSX.IntrinsicElements
    classes? : string[],
    htmlProps: React.DOMAttributes<HTMLOrSVGElement>, // dom attributes is now a property in props
}
export default function Element(props: Props) {
    const elmStyles     = styles.useStyles();

    // themes:
    const variTheme     = useVariantTheme(props);
    const variSize      = useVariantSize(props);
    const variGradient  = useVariantGradient(props);

    const Tag       = (props.tag ?? 'div');
    return (
        <Tag {...props.htmlProps} // you can now pass the desired props to tag
            className={[
                elmStyles.main,

                // themes:
                variTheme.class,
                variSize.class,
                variGradient.class,

                ...(props.classes ?? []),
            ].filter((c) => !!c).join(' ')}
        >
            {(props as React.PropsWithChildren<Props>)?.children}
        </Tag>
    );
};

But @spender's suggestion is a better approach.
Don't forget to update your hooks to accommodate this change.


text:
Q: Regex Espression for first names validation I have a Spring MVC application, and in my page I have an input field where the user writes his/her first name, and I would like to avoid that they type charatcters like @, ?,!,,$,%..etc.
In my validator I would like to use an expression which allow the biggest set of characters, for example apostrophes, accent marks and so on.
 @Override
public void validate(Object target, Errors errors)
{
    //the email must be unique
    super.validate(target, errors);

    User user= (User) target;

    if (!user.matches("[a-zA-Z ]"))) {
        errors.rejectValue("user.name", "user.name.invalid");
    }

}

Does anybody can help me to add a wider validation than [a-zA-Z ] ?

A: In your case it would be easiest to define a "blacklist" instead of a "whitelist", as you know, what you don't want to have in the string, but don't quite know, what you need tolerate.
As @AntonH suggested, you should check for
[^@ ?!\,$%]+

instead of a giant and possibly incomplete "whitelist" of characters and ranges.
This means "a string of length one or more containing none of the specified characters.


text:
Q: Jinja-syntax error in python application using html as index page I have a small python application, it have backend, frontend, and sqllite3 db
I run backend and frontend when I hit on the frontend url I am getting an error
  File "C:\Users\username\Downloads\files\templates\index.html", line 27, in template
{{ entry.what_to_do|safe }}
jinja2.exceptions.TemplateSyntaxError: tag name expected
192.168.0.33 - - [01/Jul/2022 11:44:15] "GET / HTTP/1.1" 500 -
192.168.0.33 - - [01/Jul/2022 11:44:15 ] "GET /favicon.ico HTTP/1.1" 404 -

any help will be appreciated

                <button onclick="location.href='/mark/{{entry.what_to_do|urlencode}}'">mark as done </button>
                <button onclick="location.href='/delete/{{entry.what_to_do|urlencode}}'">delete</button>

this is the line of code where I am getting that error


text:
Q: Looking for a gtk equivalent of ark Does there exist a GTK equivalent (or improvement) of the Linux archiving tool known as Ark? If so, where might it be found; and if not, how well-received might be a new project which acts as a front-end to tar?

A: It's called File Roller, or "Archive Manager" in the menu.


text:
Q: Angular testing - Cannot read property 'clear' of undefined I have a component like below
   <select #tabSelect (change)="tabLoad($event.target.value)" class="mr-2">
                  <option value="tab1">First tab</option>
                  <option value="tab2">Second tab</option>
                </select>

          <ng-template #tabContent></ng-template>

There are two tabs,they call tabLoad() function and sends parameter what tab clicked.
export class DemoComponent implements OnInit {

  @ViewChild('tabContent', { read: ViewContainerRef }) entry: ViewContainerRef;
  activeTab: any = 'tab1';

  constructor(private resolver: ComponentFactoryResolver) { }

  ngOnInit() {
    this.tabLoad(this.activeTab);
  }

  tabLoad(page) {
    setTimeout(() => {
      this.activeTab = page;
      this.entry.clear();
      if (page == 'tab1') {
        const factory = this.resolver.resolveComponentFactory(Tab1Component);
        console.log(this.entry);
        this.entry.createComponent(factory);
      } else if (page == 'tab2') {
        const factory = this.resolver.resolveComponentFactory(Tab2Component);
        this.entry.createComponent(factory);
      }
    }, 500);
  }

}

In this .ts fle I made a variable called entry which points to #tabContent.Tab content loads a component depends on what page is active.
I wrote a test suite for this behavior like below
fdescribe('DemoComponent', () => {
    let component: DemoComponent;
    let fixture: ComponentFixture<DemoComponent>;

    beforeEach(async(() => {
        TestBed.configureTestingModule({
            imports: [RouterModule.forRoot([]), SharedModule],
            declarations: [Tab1Component, Tab2Component],
        }).compileComponents().then(() => {
            fixture = TestBed.createComponent(DemoComponent);
            component = fixture.componentInstance;
        });
    }));
    it('should set activeTab correctly and clear entry when tabLoad is called', fakeAsync(() => {
        component.tabLoad("tab1");
        flush();
        expect(component.activeTab).toBe('tab1');
    }));
});

This test fails and says Cannot read property 'clear' of undefined when I call  this.entry.clear(); . Also  console.log(this.entry); prints undefined.
Then I decided to add fixture.detectChanges() on .compileComponents().then(() => {}) scope but still fails in the same way.But when I go to the page after ng serve everything works well.

A: The first fixture.detectChanges() calls ngOnInit and you need to call it in a fakeAsync zone for flush to take effect since the setTimeout gets created on the ngOnInit call. In essence, the timer needs to be created in a fakeAsync zone. So try putting the fixture.detectChanges() inside of the test (it block) and remove it from the .then.
beforeEach(async(() => {
        TestBed.configureTestingModule({
            imports: [RouterModule.forRoot([]), SharedModule],
            declarations: [Tab1Component, Tab2Component],
        }).compileComponents().then(() => {
            fixture = TestBed.createComponent(DemoComponent);
            component = fixture.componentInstance;
            // !! remove fixture.detectChanges() from here
        });
    }));
    it('should set activeTab correctly and clear entry when tabLoad is called', fakeAsync(() => {
        // !! add it here
        fixture.detectChanges();
        component.tabLoad("tab1");
        flush();
        expect(component.activeTab).toBe('tab1');
    }));

And like Petr said, instead of using 500ms, you can use ngAfterViewInit.
Try this:
export class DemoComponent implements OnInit, AfterViewInit { /* add AfterViewInit */

  @ViewChild('tabContent', { read: ViewContainerRef }) entry: ViewContainerRef;
  activeTab: any = 'tab1';

  constructor(private resolver: ComponentFactoryResolver) { }

  ngOnInit() {
  }

  ngAfterViewInit() {
    this.tabLoad(this.activeTab);
  }

  tabLoad(page) {
      this.activeTab = page;
      this.entry.clear();
      if (page == 'tab1') {
        const factory = this.resolver.resolveComponentFactory(Tab1Component);
        console.log(this.entry);
        this.entry.createComponent(factory);
      } else if (page == 'tab2') {
        const factory = this.resolver.resolveComponentFactory(Tab2Component);
        this.entry.createComponent(factory);
      }
  }

}

And then I don't think you would need fakeAsync and flush.


text:
Q: C# Raising an event in a .net assembly from a filesystemwatcher event handler I am having an issue with cross thread communication in .net.
I created a .NET assembly that does not have a GUI front end. This assembly calls a FileSystemWatcher that monitors  a specific folder for any files being newly created. When a file is created I want to be notified so that i can read the text from the file and  then raise an event from my own object passing that data.
The issue that is occurring is that i get the following error when I try this.
"The calling thread cannot access this object because a different thread owns it"
Below is a summary of my program.
public void start()
{
    _IncomingWatcher = new FileSystemWatcher(strMessageInboundDir);
    _IncomingWatcher.Created += DataRecieved_Created;
    _IncomingWatcher.EnableRaisingEvents = true;
 }

-----------------------------------------------------------------------

private void DataRecieved_Created(object sender, FileSystemEventArgs e)
{
   var files = Directory.EnumerateFiles(strMessageInboundDir);
   foreach (string file in files)
   {

       var data = File.ReadAllText(file);
       data = ProcessMessageMCOINToADDN(data);

       if (DataRecieved != null)
       {
          MessageData tempmessage = new MessageData
          {
             MyEventString = data
          };
          DataRecieved?.Invoke(this, tempmessage);
       }
       File.Delete(file);
    }
}

any help would be greatly appreciated.
thanks
J.W

A: You want the file or directory created, assuming its a file, the event args has the data you want.
private void DataRecieved_Created(object sender, FileSystemEventArgs e)
{

   if ( System.IO.File.Exists(e.FullPath )) // Might Be a Directory
   {

   var data = File.ReadAllText(e.FullPath);
   data = ProcessMessageMCOINToADDN(data);

   if (DataRecieved != null)
   {
      MessageData tempmessage = new MessageData
      {
         MyEventString = data
      };
      DataRecieved?.Invoke(this, tempmessage);
   }
    File.Delete(e.FullPath);

    }
}

More information on FileSystemEventArgs here:
https://msdn.microsoft.com/en-us/library/system.io.filesystemeventargs(v=vs.110).aspx


text:
Q: Stripe doesn't send e-mail when Checkout.js is used I have a requirement to send e-mail receipts when Stripe payment is used.  The e-mails do not go to the customers.
We are using https://checkout.stripe.com/checkout.js and in the e-mail settings are configured correctly:

The JavaScript invoking client side Stripe is here:
stripeHandler = StripeCheckout.configure({
      key: "{{stripe_key}}",
      image: '/static/img/framework/logo.png',
      token: function(token) {
        $("#stripe_token").val(token.id);
        $("#payment_form").submit()
      }
    });

    stripeHandler.open({
      name: 'My Company Inc.',
      description: "{{order_description|escapejs}}",
      email: "{{ order.user.email }}",
      amount: parseInt(parseFloat($('#total_cost').text) * 100)
    });

A: Whenever you collect card details via Stripe Checkout, Stripe sends you a card token back with an id like this tok_XXX.
Getting the card token is only the first step in the process of handling a payment. You then need to send that token to your server where you use the Create Charge API to create a charge and receive a payment or you save the card on a customer using the Create Customer API.
In both cases, Stripe doesn't know the email address of the customer and it's not taken from the token. You have to explicitly send it to the API if you want that email address to be used.
If you create a customer then you'd pass it in the email parameter on creation. That email would then be used to send email receipts to that customer whenever you charge their saved card.
If you create a charge immediately without creating a customer first then you have to explicitly tell Stripe to send the email receipt to that address. This is done by passing the receipt_email parameter in the API as documented here.
The last issue with your code is that, even though Stripe sends you the customer's email address back in the token callback you're not using it in the code. This means that once the token reaches your server you don't have the email address anymore and your code must simply be ignoring the empty value.
You'll want to change your handler to do something like this:
stripeHandler = StripeCheckout.configure({
  key: "{{stripe_key}}",
  image: '/static/img/framework/logo.png',
  token: function(token) {
    $("#stripe_token").val(token.id);
    $("#stripe_email").val(token.email);
    $("#payment_form").submit()
  }
});

This assumes that your form already has a second hidden input field with the id stripe_email where to set the email. You can see a full example with PHP here.
Another solution would be to call the Retrieve Token API server-side based on the token id to get the email in the email property otherwise.

A: I had the same problem and realized I hadn't set my server side code to trigger the email. Stripe has some instructions listed at Automatically send receipts using the API.
In my case, I hadn't set the receipt_email parameter. I'm using PHP so my code looks like this:
$token = $_POST['stripeToken'];
$emailR = $_POST['stripeEmail'];

$charge = \Stripe\Charge::create(array(
  "amount" => 30000,
  "currency" => "usd",
  "source" => $token,
  "description" => "Awesome Widget",
  "receipt_email" => $emailR,
  "metadata" => array("Email" => $emailR)
));


text:
Q: iTerm2 Supply PWD to coprocess in capture output trigger How do you supply PWD to a coprocess script?
For instance, given the below trigger:

When I double click the captured output, it runs the script: ~/rerun_test.sh supplying the filename that was matched: \1.
However, the application I work with does not output the present working directory (PWD) so I need to have it available to me as a variable that I can supply somehow or the other.
For semantic history when you run a command the PWD is \5 for instance:

Command runs when you activate Semantic History on any filename. Use \1 for filename, \2 for line number, \3 for text before click, \4 for text after click, \5 for pwd. You can also use interpolated string syntax.

Is there anything equivalent that I can resort to? Obviously in this context: ~/rerun_test.sh \1 \5 does not work.

A: Confirm - I guess that's a bug in iTerm2.
IMHO, the sub-shell in which your command is executed should point to the same working directory as your main shell (at that point). It doesn't, and it actually happens to be / - which is bad, and prevents your script/any editor from finding the file.
Just as a side note in case someone is using "capture output" in combination with clang or clang++: there is an ugly workaround... one can force the compiler to print absolute paths only, even if the inputs were given as relative paths:
`-fdiagnostics-absolute-paths`


text:
Q: WiX Upgrade element doesn't execute on repair I have a wxs-file containing the following snippet:
<Upgrade Id="{FE576A6C-AF60-4569-B81D-1B025F88F9D7}">
    <UpgradeVersion Property="LCGUID" OnlyDetect="yes"
        Minimum="0.0.0" IncludeMinimum="yes"
        Maximum="9.0.0" IncludeMaximum="no" />
</Upgrade>

This will look for another piece of installed software (named LC) and set the upgrade version guid to the property LCGUID. This is later used to verify that for example the correct LC is installed.
This works when "installing" or "upgrading" the software. I can see this in the logs:
MSI (c) (9C:A8) [02:28:48:422]: PROPERTY CHANGE: Adding LCGUID property. Its value is '{8023DC00-D425-4DE8-808C-C78FAD649A2F}'.

Now, when I try to do a repair, I also need this property to be filled, but the log doesn't say anything about LCGUID.
I suspect that the "Upgrade" element isn't executed when repairing. Can someone verify this and provide a possible solution?

A: If you look in the log you should see something like "Skipping FindRelatedProducts action: not run in maintenance mode", and that's what does the UpgradeCode search, so you're correct in that it does not run in maintenance/repair modes.
At first install you when upgrade searches are done, you could save that property in the registry, use a WiX 'remember property' pattern. It does mean you'll need two separate searches, when during fresh install and one for maintenance mode. In general you'd use another property for the registry search, and then have a custom action property set that just sets LCGUID to REGISTRYGUID conditioned on Installed.


text:
Q: Unknown device error installing Lexmark printer in Vista I have been using Lexmark X3650 All-In-One on my Windows Vista Desktop PC for a year without problem. Yesterday, I was prompted to plug in the USB from the printer and after that I got errors: "The USB device has malfunctioned." ,"The unknown device has been installed unsuccessfully.". Then, the printer just stoped responding. I have uninstalled the driver from Device Manager and software (using Lexmark's clean utility), rebooted, reinstalled, same thing, tried different ports/cable. Vista displays these two errors stated above immediately upon plug in.

A: This sounds suspiciously like the USB interface on your printer has given up the magic smoke that makes it work.
Assuming that other USB devices work in these ports then your computer should be fine.  The last thing you could try is to see if the printer will work on another computer, if you get the same error then I'm am afraid that chances are your printer has died.
If, on the other hand, the printer works fine then there is potentially some kind of driver corruption that will need to be looked in to.


text:
Q: Core Data Faulting and Fetching of To-Many Relationships I have several "theory" questions on Core Data behavior related to what happens with a to-many relationship and when to rely on walking the relation from a parent entity and when a fresh fetch request should be built. They're all very much related.
Background
Assume a parent entity RPBook, which has a to-many relation to RPChapter. A book has many chapters. The inverse is set in the core data model too. A basic form of manually ordered relationships is involved, so the RPChapter entity has a chapterIndex property. I am not using iOS5's new ordered relationships here (not as relevant to these questions either).
To get to the chapters in a book, one would use the chapters relationship accessor:
RPBook *myBook; // Assume this is already set to an existing RPBook
NSSet *myChapters = myBook.chapters

Usage / Setup
In an iPhone app, we'd start off with a table view showing a list of RPBook instances. The corresponding chapters wouldn't be pre-fetched as part of the fetch spec for the fetched results controller backing the table view, since those chapters are not yet needed.
I now select one of those RPBook instances, I'm taken to a new page and I have this RPBook instance reference in my view controller, which does NOT have its chapters prefetched.
Question 1: Invoking filteredSetUsingPredicate: on chapters relation right away
If I want to filter via the chapters relation using filteredSetUsingPredicate: directly, will that even work reliably, given that I didn't pre-fetch all related RPChapter instances of the current RPBook I'm looking at? Put another way, does filteredSetUsingPredicate: trigger faulting behind the scenes of all objects in that relation in order to do its thing, or will it misleadingly only give me results based on which of the chapters already happened to be in memory (if any)?
If I don't have an egregious number of associated chapters to a book, should I instead style this by invoking allObjects first? i.e.
[[self.chapters allObjects] filteredArrayUsingPredicate:predicate]

instead of just:
[self.chapters filteredSetUsingPredicate:predicate]

Question 2: Batch retrieval of all a book's chapters
In the case I have an RPBook instance, but no pre-fetched RPChapter instances related to it, how do I force all of a book's chapters to be fetched in one shot using the chapters relation? Does [myBook.chapters allObjects] do that or can I still get faults back from that call?
I want Core Data to fulfill all the faults in a batch instead of tripping faults for the odd RPChapter asked for if that will affect the behavior of using filteredSetUsingPredicate: on the chapters relation, as per Question 1 above.
Must I resort to an explicit fetch request to do this? Should I refetch the RPBook I already have, but this time, request in the fetch request, that all associated chapters also be fetched using setRelationshipKeyPathsForPrefetching:?
This last option just seems wasteful to me, b/c I already have a scope relation representing conceptually the subset of all RPChapter instances I'd be interested in. As much as possible, I'd like to just walk the object graph.
Question 3: NSFetchedResultsController of RPChapter instances on the same Thread
Setup
In this case I have an RPBook instance, but no pre-fetched RPChapter instances related to it (but they do exist in the Store). In the same view controller, I also have an NSFetchedResultsController (FRC) of RPChapter instances scoped to the very same book. So that's same thread, same managed object context.
Is an RPChapter instance from the FRC going to be the same object in memory as an RPChapter instance counterpart I retrieve from myBook.chapters, that shares the same ObjectID? Put another way, does the runtime ever fulfill managed object requests for the same ObjectID from the same MOC in the same Thread, using different physical objects in memory?
Question 4: Design pattern of installing an NSFetchedResultsController inside a Managed Object to serve queries for a relation
I'm trying to decide whether I should be able to service queries about a relationship whose contents are frequently changing (chapters in a book in my example) by using the built in chapters relation provided in my custom RPChapter managed object subclass, or if it's ever okay from a design/architecture perspective, to install an FRC of RPChapter instances onto the RPBook managed object class, to service queries efficiently about chapters in that book.
It's clearly cleaner if I could just rely on the chapters accessor in myBook instance, but it seems an FRC here might actually be more performant and efficient in situations where a large volume of destination entities in the to-many relation exist.
Is this overkill or is this a fair use of an FRC for querying an RPBook about its chapters in different ways? Somehow it feels like I'm missing the opportunity to walk the object graph simply. I'd like to be able to trust that the chapters relation is always up to date when I load my RPBook instance.

A: Question 1
Yes it will work.  When you call [book chapters] the set will get populated automatically.  When you filter on those objects they will fault in.
However, you should be using a NSFetchedResultsController here with the predicate being something like @"book == %@" instead of grabbing the array.
Question 2
The best way to force the NSManagedObjectContext to load all of the chapters would be to do a NSFetchRequest and configure the NSFetchRequest to return fully realized objects instead of faults.  This will pre-load them all in one go.  However, unless you have a TON of chapters, you are not going to get a lot of savings here.
Why?
Because when you request those chapters, even in a faulted state, Core Data is going to load the data into a cache (excluding a few edge cases like binary data) so that when you "fault" an object it is just pointers moving around in memory and no additional disk hit.
You would need, probably, thousands of chapters to see any benefit out of a pre-fetch.
Question 3
Yes.  They will be the same object.  NSManagedObject instances will always be shared when retrieved from the same NSManagedObjectContext.  That is part of the job of the NSManagedObjectContext
Question 4
You want to use a NSFetchedResultsControler that is its job.  Managing that stuff manually is wasteful and almost guaranteed to be less efficient than Core Data's implementation.
However, the relationship will always be up to date unless you are tweaking it from another thread. So if you do not expect updates then you could just use an array.  I wouldn't.


text:
Q: viewing events in winforms How can I choose which event is shown when I double click on a control in winforms designer?
For example, winforms shows the "TextChanged" event when I double click on a textbox. If I wanted to make it show the "GotFocus" event, how could I do that? I am guessing I would inherit textbox and set some property, but I cant find that property.

A: The deafult event is defined with DefaultEventAttribute class. So unless you have access to the control code, you cant change existing ones.
By inheriting you can by using that attribute.

A: Replace the [DefaultEvent] attribute by inheriting from the control:
using System;
using System.ComponentModel;
using System.Windows.Forms;

[DefaultEvent("GotFocus")]
class MyTextBox : TextBox {
}


text:
Q: How to update a table if values of the attributes are contained within another table? I've got a database like this one:

I'm trying to create a query that would enable me to update the value of the status attribute inside the incident table whenever the values of all of these three attributes: tabor_vatrogasci, tabor_policija, and tabor_hitna are contained inside the izvještaj_tabora table as a value of the oznaka_tabora attribute. If, for example, the values of the tabor_vatrogasci, tabor_policija, and tabor_hitna attributes are 3, 4 and 5 respectively, the incident table should be updated if (and only if) 3, 4, and 5 are contained inside the izvještaj_tabora table.
This is what I tried, but it didn't work:
UPDATE incident SET status='Otvoren' FROM tabor,izvjestaj_tabora
WHERE (incident.tabor_policija=tabor.oznaka
OR incident.tabor_vatrogasci=tabor.oznaka
OR incident.tabor_hitna=tabor.oznaka)
AND izvjestaj_tabora.oznaka_tabora=tabor.oznaka
AND rezultat_izvjestaja='Riješen' AND
((SELECT EXISTS(SELECT DISTINCT oznaka_tabora FROM izvjestaj_tabora)
WHERE oznaka_tabora=incident.tabor_policija) OR tabor_policija=NULL) AND
((SELECT EXISTS(SELECT DISTINCT oznaka_tabora FROM izvjestaj_tabora)
WHERE oznaka_tabora=incident.tabor_vatrogasci) OR tabor_vatrogasci=NULL) AND
((SELECT EXISTS(SELECT DISTINCT oznaka_tabora FROM izvjestaj_tabora)
WHERE oznaka_tabora=incident.tabor_hitna) OR tabor_hitna=NULL);

Does anyone have any idea on how to accomplish this?

A: Asuming INCIDENT.OZNAKA is the key and you need all 3 to be ralated for the event to open (I am Slovenian that why I understand ;) )
UPDATE incident
SET status='Otvoren'
WHERE oznaka in (
    SELECT DISTINCT i.oznaka
    FROM incident i
        INNER JOIN izvještaj_tabora t1 ON i.tabor_vatrogasci = t1.oznaka_tabora
        INNER JOIN izvještaj_tabora t2 ON i.tabor_policija = t2.oznaka_tabora
        INNER JOIN izvještaj_tabora t3 ON i.tabor_hitna = t3.oznaka_tabora
    WHERE t1.rezultat_izvjestaja='Riješen' AND t2.rezultat_izvjestaja='Riješen' AND t3.rezultat_izvjestaja='Riješen'
    )

A: According to your description the query should look something like this:
UPDATE incident i
SET    status = 'Otvoren'
WHERE (tabor_policija IS NULL OR
       EXISTS (
          SELECT 1 FROM izvjestaj_tabora t
          WHERE  t.oznaka_tabora = i.tabor_policija
          )
       )
AND   (tabor_vatrogasci IS NULL OR
       EXISTS (
          SELECT 1 FROM izvjestaj_tabora t
          WHERE  t.oznaka_tabora = i.tabor_vatrogasci
          )
       )
AND   (tabor_hitna IS NULL OR
       EXISTS (
          SELECT 1 FROM izvjestaj_tabora t
          WHERE  t.oznaka_tabora = i.tabor_hitna
          )
       )

I wonder though, why the connecting table tabor is irrelevant to the operation.
Among other things you fell victim to two widespread misconceptions:
1)
tabor_policija=NULL

This expression aways results in NULL. Since NULL is considered "unknown", if you compare it to anything, the outcome is "unknown" as well. I quote the manual on Comparison Operators:

Do not write expression = NULL because NULL is not "equal to" NULL.
  (The null value represents an unknown value, and it is not known
  whether two unknown values are equal.)

2)
EXISTS(SELECT DISTINCT oznaka_tabora FROM ...)

In an EXISTS semi-join SELECT items are completely irrelevant. (I use SELECT 1 instead). As the term implies, only existence is checked. The expression returns TRUE or FALSE, SELECT items are ignored. It is particularly pointless to add a DISTINCT clause there.


text:
Q: Spring RestTemplate dynamic JSON propery name I need to consume an API which returns pages of objects using Spring RestTemplate. The problem is that the name of the JSON page property which holds the collection of objects is dynamic. How can I map this dynamic JSON prop to its static counterpart in my POJO?
Here's the pojo:
public class DTO<T> {
    private List<T> items;

    public List<T> getItems() {
        return items;
    }

    public DTO<T> setItems(List<T> items) {
        this.items = items;
        return this;
    }
}

Here's two examples of JSON:
{
    "forms": [{},{},{}]
}

{
    "submissions": [{},{},{}]
}

In the former case I need to map JSON forms onto POJO's items, in the latter - submissions onto items. How do I go about that?

A: try using maps like bellow
public class DTO<T> {
private Map<String,List<T>> items;

public Map<String,List<T>> getItems() {
    return items;
}

public DTO<T> setItems(Map<String,List<T>> items) {
    this.items = items;
    return this;
}
}

A: I've just aliased the JSON field whose name can vary:
public class DTO<T> {
    private Integer prettyFieldId;
    private Integer pages;
    private Integer total;

    @JsonAlias({"forms", "submissions"})
    private List<T> items;

    //getters, setters
}


text:
Q: Estrutura tabela dia e horários (tipo agenda) Preciso criar uma tabela que contenha dias e horários de funcionamento de um estabelecimento, uma espécie de agenda. Essa tabela deve representar todos os dias da semana e em cada dia conter o horário de abertura e de fechamento. O desafio está sendo em criar esta tabela de forma que não tenha dados redundantes e que facilite a busca pelo horário de funcionamento de determinado dia.
Por exemplo, vou precisar buscar o dia de funcionamento do estabelecimento na próxima quarta-feira, ou o horário de hoje. Ainda existe um outro fator que são os dias de feriado (que o horário certamente será diferente dos dias normais, levando em conta que o estabelecimento esteja aberto). O Facebook tem algo parecido, nas páginas de empresas.
Na imagem uma representação da ideia (sendo que o primeiro horário é o de abertura e o segundo o de fechamento). Usarei MySQL.

A: De acordo com comentários que você descreveu, você tem uma relação entre EMPRESA e Horários de 1 p/ Muitos, dessa forma eu faria da seguinte forma.
declare @Empresa table
(
    id int,
    nome varchar(50)
)

declare @Horarios table
(
    id int,
    idEmpresa int,
    diaSemana varchar(20),
    abertura time,
    fechamento time
)

insert into @Empresa values
(1, 'X'),
(2, 'Y')

insert into @Horarios values
(1,1, 'segunda-feira', '08:00', '18:00'),
(2,1, 'terca-feira', '08:00', '18:00'),
(3,1, 'quarta-feira', '08:00', '18:00'),
(4,1, 'quinta-feira', '08:00', '18:00'),
(5,1, 'sexta-feira', '08:00', '18:00'),
(6,1, 'sabado', '09:00', '17:00'),
(7,1, 'domingo', '09:00', '15:00'),
(8,1, 'feriado', '10:00', '13:00'),
(9,2, 'segunda-feira', '08:00', '18:00'),
(10,2, 'terca-feira', '08:00', '18:00'),
(11,2, 'quarta-feira', '08:00', '18:00'),
(12,2, 'quinta-feira', '08:00', '18:00'),
(13,2, 'sexta-feira', '08:00', '18:00'),
(14,2, 'sabado', '08:00', '18:00'),
(15,2, 'domingo', '09:00', '17:00'),
(16,2, 'feriado', '09:00', '16:00')

declare @horaInformada time = '10:00';

select nome, diaSemana, abertura, fechamento
from @Empresa e
join @Horarios h
on h.idEmpresa = e.id
where e.id = 2
and diaSemana = 'feriado'
and @horaInformada between abertura and fechamento

Mais já deixo claro que pode haver varias respostas contraditórias a essa, porque sua pergunta eu classificaria como (principalmente baseada em opiniões)... cada um pode especificar uma forma diferente de fazer isso.

A: A melhor forma seria:
id_dia(Primary key) -> int
horario -> varchar(15)

Em id_dia você coloca o número do dia da semana correspondente, e no horario o horario de funcionamento.
O id_dia deve ser o numero que corresponde ao dia da semana, exemplo:

Id_dia
(1) para domingo
(2) para segunda
(3) para terça
...
(7) para sabado

A: Aconselho a fazer três tabelas:
A primeira tabela será para inserir os dias da semana, para isso crias dois campos:
semana -> Nome Tabela
s_id   -> int
s_name -> varchar

A segunda tabela será para inserir os horários de abertura e fecho, para isso crias 4 campos:
horarios   -> Nome Tabela
h_id       -> int
h_s_id     -> int
h_abertura -> time
h_fecho    -> time

A terceira tabela será para inserir os feriados, para isso crias 5 campos:
feriados     -> Nome Tabela
f_id         -> int
f_s_id       -> int
f_diaferiado -> datetime
f_abertura   -> time
f_fecho      -> time

Depois para retornares os valores de um dia especifico basta usares um join, exemplo:
SELECT * FROM semana
LEFT JOIN horarios ON horarios.h_s_id=semana.s_id
WHERE s_name=domingo


text:
Q: Related to Angular 6 onclick button and web service calling In angular 6 onclick of button it should redirect to another component and web service of that particular component should be called. How to implement this?

A: To redirect to another component, you need to implement routing.
Your button can then use the routerLink directive to navigate to the second component.
When the second component loads, you can use its ngOnInit (or similar) lifecycle hook to call a web service.


text:
Q: EXTJS 3, how to manually control paging event? In the EXTJS 3, I am defining a data store and grid, it is working fine. now the issue is the paging, I want to manually control 'Next' button event.
I tried to use 'beforechange' event in the paging, but it doesn't work, because it is 'BEFORE'. how to manually load the store with parameter value ?
The server side is C#.
Thanks
The store is
  var store = new Ext.data.DirectStore({
            storeId: 'store',
            directFn: Report.Function1,
            autoLoad: false,
            paramsAsHash: false,
            paramOrder: 'param1|start',
            ....
            fields: [ ...   ],
            remoteSort: false,
        });

The paging is
var pager = new Ext.PagingToolbar({
            store: store,
            displayInfo: true,
            pageSize: this.pageSize,

            listeners: {
                beforechange: function (paging, params) {
                    currentPage = params.start;
                    report_search(params);
                }
            }
        });

 function report_search(page) {
    var store = Ext.StoreMgr.lookup('store');
    store.removeAll();

    store.load({
        params: {
            param1: Ext.getCmp("param1").getValue(),
            start: page.start
        }
    });
}

A: It seems that you want apply a special param to the store before load will be done.
To do this - you need:
this.store.on('beforeload', this.applyParams.createDelegate(this));
...

applyParams: function(store, options) {
    options.params = options.params || {};

    var params = {
        param1: Ext.getCmp("param1").getValue()
    };

    Ext.apply(options.params, params);
}

I hope that you don't need to reject 'Next' button click, cause store can be loaded from other places (automatically, manually from other places).


text:
Q: How to pass the payload to event hub from logic app in EventData format Event Hub Azure function is expecting EventData as input. I'm passing base64(string) from logic app, but the trigger is throwing a JSON parser failed error. My input is in the JSON format. Even if I give string as input, it throws the same error.

A: Can you provide the complete error ? also can you check the raw inputs if it's a valid JSON rather than checking it on designer run history. If it's not a valid JSON, pass it to Parse JSON so that it can construct valid JSON before you pass it to the Azure Function.


text:
Q: How to show and hide a virtual keyboard (android) With Delphi (berlin) what is the good method to show and hide a virtual keyboard under Android ?
i put on my form a native android edit. i set setShowSoftInputOnFocus(false); and i try to open manually the keyboard like
  var aVirtualKeyboardService: IFMXVirtualKeyboardService;
  TPlatformServices.Current.SupportsPlatformService(IFMXVirtualKeyboardService, IInterface(aVirtualKeyboardService));
  if (aVirtualKeyboardService <> nil) then aVirtualKeyboardService.ShowVirtualKeyboard(self);

but it's not work :( sometime the keyboard is show, sometime not :(

A: Take a look at IFMXVirtualKeyboardService. It has ShowVirtualKeyboard and HideVirtualKeyboard methods.


text:
Q: Vector parallel to a plane 3x+2z=3 I have a plane whose equation is $3x+2z=3$
My question is, is  vector: $(0,1,0)$ parallel to the plane? Or how do I determine if a vector is parallel to a certain plane?

A: Compute the CrossProduct $$[3,0,2]\times [0,1,0]$$

A: A normal to your plane comes from the coefficients of $x,y,z$  i.e. $(3,0,2)$.
If $(0,1,0)$ is parallel to the plane, then it is perpendicular to the normal, which you can check with the dot product.


text:
Q: Json encode a complex dict How would I json encode the following dict:
data = {
    'name': 'david',
    'avatar': open('file.jpg').read()
}

When I try doing json.dumps(data) I get a UnicodeDecodeError.

A: You must be using Python 2.x.  Since you have Unicode data in the string, you need to make it a Unicode string literal:
>>> import json
>>> data = {
...     'name': 'david',
...     'avatar': u'\xed\xb3\x1cW\x7f\x87\x1c\xb9*Pw\x9a#W\x05\xeaNs\xe4\xaa@\xddi\x8e\\\x15\xa8;\xcd\x91\xab\x02u\xa79rU\xa0\xee4\xf7K\xb9\x05{t\x02\xc6I\xb6\xaa\xbf\x00\x00\x00\x00IEND\xaeB`\x82...'
... }
>>> json.dumps(data)
'{"name": "david", "avatar": "\\u00ed\\u00b3\\u001cW\\u007f\\u0087\\u001c\\u00b9*Pw\\u009a#W\\u0005\\u00eaNs\\u00e4\\u00aa@\\u00ddi\\u008e\\\\\\u0015\\u00a8;\\u00cd\\u0091\\u00ab\\u0002u\\u00a79rU\\u00a0\\u00ee4\\u00f7K\\u00b9\\u0005{t\\u0002\\u00c6I\\u00b6\\u00aa\\u00bf\\u0000\\u0000\\u0000\\u0000IEND\\u00aeB`\\u0082..."}'
>>>

By placing u before the string literal, you tell Python to treat the string as Unicode.
Note that this is unnecessary in Python 3.x since all strings are now Unicode by default.

A: So you try to encode a picture in json. If you want to display it on a web page, consider using a data-url-encoding:
image = "data:image/jpg;base64,%s" % ''.join(open('file.jpg').read().encode('base64').split())
data = {
    'name': 'david',
    'avatar': image,
}
json_data = json.dumps(data)

or if you only need the binary data, simply use:
image = open('file.jpg').read().encode('base64')
data = {
    'name': 'david',
    'avatar': image,
}
json_data = json.dumps(data)

#decode
data = json.loads(json_data)
image = data['avatar'].decode('base64')


text:
Q: Python - Find min, max, and inflection points of normal curve I am trying to find the locations (i.e., the x-value) of minimum, start of season, peak growing season, maximum growth, senescence, end of season, minimum (i.e., inflection points) in a vegetation curve. I am using a normal curve here as an example. I did come across few codes to find the change in slope and 1st/2nd order derivative, but not able to implement them for my case. Please direct me if there is any relevant example and your help is appreciated. Thanks!
## Version 2 code
import matplotlib.pyplot as plt
import numpy as np
from  scipy.stats import norm

x_min = 0.0
x_max = 16.0

mean = 8
std = 2

x = np.linspace(x_min, x_max, 100)
y = norm.pdf(x, mean, std)

# Slice the group in 3
def group_in_threes(slicable):
    for i in range(len(slicable)-2):
        yield slicable[i:i+3]

# Locate the change in slope
def turns(L):
    for index, three in enumerate(group_in_threes(L)):
        if (three[0] > three[1] < three[2]) or (three[0] < three[1] > three[2]):
            yield index + 1

# 1st inflection point estimation
dy = np.diff(y, n=1) # first derivative
idx_max_dy = np.argmax(dy)
ix = list(turns(dy))
print(ix)

# All inflection point estimation
dy2 = np.diff(dy, n=2) # Second derivative?
idx_max_dy2 = np.argmax(dy2)
ix2 = list(turns(dy2))
print(ix2)

# Graph
plt.plot(x, y)
#plt.plot(x[ix], y[ix], 'or', label='estimated inflection point')
plt.plot(x[ix2], y[ix2], 'or', label='estimated inflection point - 2')
plt.xlabel('x'); plt.ylabel('y'); plt.legend(loc='best');

A: Here is a very simple and not robust method to find the inflection point of a non-noisy curve:
import matplotlib.pyplot as plt
import numpy as np
from  scipy.stats import norm

x_min = 0.0
x_max = 16.0

mean = 8
std = 2

x = np.linspace(x_min, x_max, 100)
y = norm.pdf(x, mean, std)

# 1st inflection point estimation
dy = np.diff(y) # first derivative
idx_max_dy = np.argmax(dy)

# Graph
plt.plot(x, y)
plt.plot(x[idx_max_dy], y[idx_max_dy], 'or', label='estimated inflection point')
plt.xlabel('x'); plt.ylabel('y'); plt.legend();

The actual position of the inflection point is x1 = mean - std for a Gaussian curve.
For this to work with real data, they have to be smoothed before looking for the max, by applying for example  a simple moving average, a gaussian filter or a Savitzky-Golay filter which can directly output the second derivative... the choice of the right filter depends on the data


text:
Q: How do I make a jar file from eclipse on fedora? Ok, hello everyone. In eclipse I choose a JDialog from windowBuilder then with just the standard code provided I right click the file and export, I click jar file, I "Export generated class files and resources" and save to desktop. Now I have a box on my desktop, I extract the class file and then I am stuck. Am I wrong to think it should be like windows.?..Thank you.

A: If you're trying to run it from the Gnome desktop by double-clicking it, then the steps in this article might be what you're looking for: https://nguyenvinhlinh.wordpress.com/2014/02/05/launching-executable-jar-file-by-a-double-click-in-fedora/

A: If i were you I will try on the terminal:
java -jar /path/to/yourjarfile.jar

If that file has any problem it will be shown on the terminal and maybe you find the error why is not running.


text:
Q: Unable to create array for recursive function I have a simple function checkReplies() which checks the reply_id and if the reply_id is not equal to 0, calls himself and checks again. Now I need to create a array ffor the outputs it generate, but I am unable to do it, the array outputs only the last element
function checkReplies( $rnid ){
    $r_notes = array();
    include_once('include/class.dbc.php');
    $dbo=new dbc();
    $db=$dbo->dbconnect();
    if( $rnid > 0 ):
    $qry_rn = "SELECT note_subject,note_body,reply_note_id FROM tbl_notes WHERE note_id = '$rnid' ORDER BY note_date DESC";
    $rslt_rn = $dbo->executeQuery( $qry_rn );
    $reply = '
';
    $reply .= $rslt_rn[0]['note_subject'].'
'.$rslt_rn[0]['note_body'];
    $reply .= '('.$rslt_rn[0]['reply_note_id'].')';
    $reply .= '
';

    echo $reply;
    $r_notes[] = $reply;
    checkReplies( $rslt_rn[0]['reply_note_id'] );
    endif;
    return $r_notes;
}
$display = checkReplies( $rnid );
var_dump($display);

How to create the array of the outputs ?

A: Just give your array as an optional parameter of your function. And, return the recursive call of your function.
Almost all recursives functions are built the same way : at the beggining, a condition making your recursivity stop or continue : this is called the "terminating case".
Then, if this break condition is not true, make what you got to do and return the recursive call of the function.
function checkReplies( $rnid, &$r_notes = array() ){

    include_once('include/class.dbc.php');
    $dbo=new dbc();
    $db=$dbo->dbconnect();

    if($rnid == 0)
            return $r_notes;

    $qry_rn = "SELECT note_subject,note_body,reply_note_id FROM tbl_notes WHERE note_id = '$rnid' ORDER BY note_date DESC";
    $rslt_rn = $dbo->executeQuery( $qry_rn );

    $reply = '
';
    $reply .= $rslt_rn[0]['note_subject'].'
'.$rslt_rn[0]['note_body'];
    $reply .= '('.$rslt_rn[0]['reply_note_id'].')';
    $reply .= '
';

    echo $reply;

    $r_notes[] = $reply;

    return checkReplies( $rslt_rn[0]['reply_note_id'], $r_notes );

}

$display = checkReplies( $rnid );

var_dump($display);

A: try this
$r_notes = array_merge($r_notes, checkReplies( $rslt_rn[0]['reply_note_id'] ));

instead of
$r_notes[] = $reply;

checkReplies( $rslt_rn[0]['reply_note_id'] );

I edited, sorry for the error.


text:
Q: Android Layout - Weighting I have spent hours trying to work this out, and spent a long time looking through other answers.
I'm evidently missing something simple, but really have been trying.
I cut my code down to the very basics to find the problem.
A layout has a backround, the top half of which is nice graphics, below the top half I am hoping to have the buttons.
The background is on the top, first linearlayout ( vertical ).
Then, inside this, are two vertical linear layouts.
The top vertical layout, has a weight of 1.
The bottom vertical layout, has a weight of 1.
This means to me, that the top layout should take up HALF of the screen. The buttons then going in the second layout should be ok to take up the rest of the screen.
However, when I start adding to the second layout, it no longer takes up half of the screen, but starts taking up space on the top half.
All I want to do, is to add four imagebuttons to the bottom half of the screen, centralised horizontally.
here is my code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:background="@drawable/menubackground"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">

    <!--  Layout 1, the top half -->
    <LinearLayout
        android:id="@+id/linearLayout1"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:orientation="vertical" >
    </LinearLayout>

    <!-- Layout 2, the bottom half, containing buttons -->
    <LinearLayout
        android:id="@+id/linearLayout2"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:orientation="vertical" >

        <ImageButton
            android:id="@+id/imageButton1"
            android:layout_width="fill_parent"
            android:layout_height="0dp"
            android:src="@drawable/playbtnimg" android:layout_weight="1"/>

        <ImageButton
            android:id="@+id/imageButton2"
            android:layout_width="fill_parent"
            android:layout_height="0dp"
            android:src="@drawable/achievementsbtnimg" android:layout_weight="1"/>
    </LinearLayout>

</LinearLayout>

Those two buttons, are now starting to take up around 2/3rd of the vertical space. They should not be going into the top half of the screen.
I'm trying to use layouts in this way so it will work on different screen sizes.
I would like the images to scale to fit within their linear layout cell, and not be cut off at the top of sides.
Any help is much appreciated.

A: Add a weightsum attribute to your root element ie the parent LinearLayout
here is what it would look like
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:background="@drawable/menubackground"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:weightSum="2"
android:orientation="vertical">

same would be for the LinearLayout having buttons
This would help further you can read more in android documentation

A: Try adding this code where you are using ImageButtons as backgrounds.
android:adjustViewBounds="true"

Fixed a similar issue I was having.
Hope it works and happy coding.


text:
Q: grok pattern match for aceess log event I am new to ELK and grok pattern matching. I am trying to build grok pattern match for my access log event and I am getting grokparsefailure message.
Here is my event log:

111.22.333.44   2015-09-15      14:27:02        POST    /test/service/testservice      200     359     0.016
  Grok pattern (after soem reasrch I came up with this):
  %{IP:client}%{DATESTAMP_EVENTLOG:logeventtime}%{WORD:method}%{URIPATHPARAM:request}%{NUMBER:HTTPStatus}%{NUMBER:bytes}%{NUMBER:duration}

I suspected the issue might be with date match above and I tried to remove the psace between the date and time and try pattern matching and that did not work either. I removed the date and time all together and tried for the remaning and that also was giving same error. I am at a loss to where the issue is. any inputs would be helpful. Thanks!

A: Start here: http://grokdebug.herokuapp.com/discover?#
%{HOST:client} %{TIMESTAMP_ISO8601:event_date_time} %{WORD:http_method} %{URIPATHPARAM} %{NUMBER:status} %{NUMBER:bytes} %{NUMBER:duration}


text:
Q: How do I restrict chrome greasemonkey scripts to a single webpage, or just certain webpages? Is there a way to prevent chrome from running greasemonkey scripts except for on certain domains? I could do some hackery with location.href, but it would be nice if there were a cleaner solution.
When I install by dragger script.user.js into the browser, the script automatically runs for all websites.
How do I prevent this?

A: Use @match, as described here.
Example:
// ==UserScript==
// @match http://*/*
// @match http://*.google.com/*
// @match http://www.google.com/*
// @match https://www.google.com/*
// ==/UserScript==

A: using @include @exclude tags in metadata?
http://diveintogreasemonkey.org/helloworld/metadata.html
https://wiki.greasespot.net/Metadata_Block


text:
Q: How to get the svg text element in rectangle with particular width and height? I have been trying to get the SVG  with rectangular shape with text element with it in a particular width and height.
I have the output values for top and left for hello is top:22left:175
 and for test is top:195left:116 with these values how to get the desired output svg file
IF i give x and y zero to text element it doesn't start from corner of the rectangle
    <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="500" height="500" style="shape-rendering:geometricPrecision; text-rendering:geometricPrecision; image-rendering:optimizeQuality; fill-rule:evenodd; clip-rule:evenodd" version="1.0">
        <rect style="fill:none;stroke:#373435;stroke-width:2.08346" width="500" height="500"></rect>
          <g id="0.8354780427180231" transform="translate(0 0 219 109)">
         <text fill="#000000" stroke="none" stroke-width="0" stroke-linecap="round" stroke-linejoin="round" x="219" y="109" text-anchor="middle" font-size="90.75" font-family="Twine" data-textcurve="0" data-itemzoom="1 1">
      <tspan dy="0" x="49%">Hello</tspan>
    </text>
    </g>
    <g id="0.2922376764472574" transform="translate(0 0 207 109)">
     <text fill="#000000" stroke="none" stroke-width="0" stroke-linecap="round" stroke-linejoin="round" x="207" y="109" text-anchor="middle" font-size="90.75" font-family="Twine" data-textcurve="0" data-itemzoom="1 1"><tspan dy="0" x="49%">Tetst</tspan>
      </text>
        </g>

</svg>`

Desired output of SVG file should be like this:

But my output like this
enter image description here

A: What are you trying to do here?
transform="translate(0 0 219 109)"

The translate() transform function takes two parameters x and y, not four.
In addition, you are supplying both an x and y attributes for the <text> element and you are also giving the <tspan> x and dy parameters.
Because of all that, I am unsure what you are actually trying to achieve.  If you are just trying to position the two pieces of text on the page, then you really only need just one of those techniques, not all three.

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="500" height="500" style="shape-rendering:geometricPrecision; text-rendering:geometricPrecision; image-rendering:optimizeQuality; fill-rule:evenodd; clip-rule:evenodd" version="1.0">
  <rect style="fill:none;stroke:#373435;stroke-width:2.08346" width="500" height="500"></rect>

  <text fill="#000000"
        x="219" y="109"
        text-anchor="middle" font-size="90.75" font-family="Twine">Hello</text>

  <text fill="#000000"
        x="207" y="180"
        text-anchor="middle" font-size="90.75" font-family="Twine">Tetst</text>

</svg>`


text:
Q: C# dll can be used in C++/CLI project easily? I have one C++/CLI project, a GUI application, which is compiled in mixed mode (managed+unmanaged).
Now I want to write a custom user control using C# and compile it to become CSharpA.dll.
my question is:  Can this dll be used by my C++/CLI project easily?  How would I do that?

A: Yes.  Just add a reference to it.  You may find yourself wanting using namespace directives, which, like the C# using directive, will add classes in other namespaces into the search space.

A: You only have to compile your C# code into an assembly, and this assembly can be referenced from your C++/CLI App as any other assembly.


text:
Q: How to properly use a ConcurrentQueue for writing in a file on a separate thread? I have an application that receives data from outside, and I'm trying to make it so that writing this data to a file is done in a separate thread (due to the fact that writing it in the thread that received it directly caused problems with writing the data fast enough). It seems to me that ConcurrentQueue is suitable for this.
But I have a problem because writing to the file does not happen at all with the code below:
Declarations:
// Declare the queue as class members
private static ConcurrentQueue<DataBuffer> queue = new ConcurrentQueue<DataBuffer>();
private static Task consumerTask;

Consumer:
static void Consumer()
{
    // Open the binary file for writing
    using (var fileStream = File.OpenWrite("received_data.bin"))
    {
        // Try to dequeue an item from the queue
        if (queue.TryDequeue(out var dataBuffer))
        {
            // Write the data to the binary file
            fileStream.Write(dataBuffer.Buffer, 0, dataBuffer.Length);
        }
    }
}

Consumer Task started when my external interface is opened, so data is expected:
consumerTask = Task.Factory.StartNew(Consumer);

This is how I enqueue data in the event handler executed when data is received:
// Enqueue the received data in the queue
queue.Enqueue(new DataBuffer(e.Bytes, (int)e.NumBytesAvailable));

DataBuffer class, because I wanted to pass to queue data and its size:
public class DataBuffer
{
    public byte[] Buffer { get; set; }
    public int Length { get; set; }

    public DataBuffer(byte[] buffer, int length)
    {
        Buffer = buffer;
        Length = length;
    }
}

So I tried to add AutoResetEvent and in this case the write happens only once, for one received data packet:
private static AutoResetEvent queueEvent = new AutoResetEvent(false);

// Enqueue the received data in the queue
queue.Enqueue(new DataBuffer(e.Bytes, (int)e.NumBytesAvailable));
// Set the auto reset event to signal that there is data available in the queue
queueEvent.Set();

Consumer with waiting for data:
static void Consumer()
{
    // Open the binary file for writing
    using (var fileStream = File.OpenWrite("received_data.bin"))
    {
        // Wait until there is data available in the queue
        queueEvent.WaitOne();

        // Try to dequeue an item from the queue
        if (queue.TryDequeue(out var dataBuffer))
        {
            // Write the data to the binary file
            fileStream.Write(dataBuffer.Buffer, 0, dataBuffer.Length);
        }
    }
}

Could you please help?

EDIT
I am trying to use BlockingCollection, but so at first glance for some reason the data received in Consumer is messed up relative to what is added to the collection. As if a different part of the data buffer there is being read.
It is something like, the following goes into the collection: 0x112233445566778899... and I receive 0x5566778899AABBCCDD...
EDIT2
This problem may be related to the fact that the received data does not come in full packets, so the data buffer passed to the collection does not always start with the example 0x11223344556677.... and something seems to me that in Consumer I do not receive from the queue this data one by one, or some part passed to the queue got lost somewhere and I then see a packet of data that was received from an external device somewhere in the middle and that is why I see these for example 0x55667788....
private static BlockingCollection<DataBuffer> collection = new BlockingCollection<DataBuffer>();

Addidng data to collection:
// Add the received data to the blocking collection
collection.Add(new DataBuffer(e.Bytes, (int)e.NumBytesAvailable));

In Consumer:
while(true)
{
    if (collection.TryTake(out var dataBuffer, Timeout.Infinite))
    {
        // Write the data to the binary file
        fileStream.Write(dataBuffer.Buffer, 0, dataBuffer.Length);
    }
}

EDIT3
I changed it to suggested modern class Channel, but still get incorrect results. Here is the output of the first 8 bytes of the producer/consumer buffers in order as processed:
Producer: 12-AB-34-CD-56-EF-78-56
Producer: 12-AB-34-CD-56-EF-78-56
Producer: 56-EF-78-56-9A-43-BC-21
Consumer: 56-EF-78-56-9A-43-BC-21
Consumer: 56-EF-78-56-9A-43-BC-21
Consumer: 56-EF-78-56-9A-43-BC-21
Producer: 12-AB-34-CD-56-EF-78-56
Producer: 56-9A-43-BC-21-12-AB-34
Consumer: 56-9A-43-BC-21-12-AB-34
Producer: 21-12-AB-34-CD-56-EF-78
Consumer: 21-12-AB-34-CD-56-EF-78
Producer: CD-56-EF-78-56-9A-43-BC
Consumer: CD-56-EF-78-56-9A-43-BC
Producer: 21-12-AB-34-CD-56-EF-78

Code snippets for Channel:
private static Channel<DataBuffer> channel = Channel.CreateUnbounded<DataBuffer>();

channel.Writer.TryWrite(new DataBuffer(_ReceivedDataBuffer2, _ReceivedRawDataBufferPosition2));

static async Task Consumer()
{
    using (var fileStream = File.OpenWrite("received_data.bin"))
    {
        while (await channel.Reader.WaitToReadAsync())
        {
            // Try to read a DataBuffer instance from the channel
            if (channel.Reader.TryRead(out var dataBuffer))
            {
               System.Diagnostics.Debug.WriteLine("Consumer: " + BitConverter.ToString(dataBuffer.Buffer.Take(8).ToArray()));
               // Write the data to the binary file
               fileStream.Write(dataBuffer.Buffer, 0, dataBuffer.Length);
            }
        }
    }
}

EDIT 4
According to suggestions from the comments, I went back to using BlockingCollection. Below is the minimal, reasonably cleaned-up code with which I handle this, to demonstrate that I use only one producer thread and one consumer. For testing purposes, I have added writing the data to a file also before passing it to the collection. This way I can compare the data before the queue and after the queue.
First, two more words about the received data. Normally, a data buffer with e.Bytes contains about 65 kB of e.NumBytesAvailable data. In these bytes I have packets of about 1.5 kB consisting of: data + sequence number + read_status.
In the saved files I can see the differences. In the file saved by Consumer, I can see that, for example, I have the correct sequence of packets ..., 41, 42, 43, after which packet 44 is no longer whole and there is a jump to, say, packet 56, then there are further packets 57, 58, 59, 60, after which there is a return to the previously missed packets, but not all of them, for example, from 48, 49, 50,..., 80, so in this sequence there are again packets 57, 58, 59, 60 saved, and packets 45 to 47 are not present in the file at all.
This type of rearrangement appears, of course, non-stop in this file after taking data out of the queue.
The data in the file before the queue is in the correct order and continuity.
using System;
using System.IO;
using System.Management;
using System.Collections.Concurrent;
using System.Threading.Tasks;

namespace test_app_1
{
    public class USB
    {
        // -----------------------------------------------------------------
        // Type of commands handled by FPGA constants:
        const byte CMD_DDC_REGISTER = 0x30;

        // -----------------------------------------------------------------
        // Type of application operations constants:
        const int MODE_NOP = 0;
        const int MODE_DDC_RAW_SAVE_TO_FILE = 16;

        // default operation mode:
        private int _OperationMode = MODE_NOP;

        // -----------------------------------------------------------------
        // Events declarations:
        public event EventHandler<CustomEventArgs> OnFtdiConnected;
        public event EventHandler OnFtdiDisconnected;
        public event EventHandler<CustomEventArgs> OnFtdiOpenedAndConfigured;

        public FtdiFifo FtdiFifo;
        private readonly string _AllowedSerialNumber = "FT786P7IA";
        public bool FtdiOpened = false;

        private byte[] _CommandBytes = new byte[10];

        private byte[] _ReceivedRawDataBuffer = new byte[150000];
        private uint _ReceivedNumberOfBytes = 0;

        static private FileStream _FileStream;
        static private FileStream _FileStreamBeforeQueue;

        private static Task consumerTask;
        private static BlockingCollection<DataBuffer> collection = new BlockingCollection<DataBuffer>();
        private DataBuffer producerDataBuffer;

        // -----------------------------------------------------------------
        // USB class constructor:
        // * configures automatic detection of events related to connected USB devices
        // -----------------------------------------------------------------
        public USB()
        {
            // ------------ autodetect USB hardware ------------------------
            // Set up the query to listen for device arrival and removal events
            WqlEventQuery query = new WqlEventQuery("SELECT * FROM __InstanceOperationEvent WITHIN 1 WHERE TargetInstance ISA 'Win32_USBHub'");

            // Set up the event watcher
            ManagementEventWatcher watcher = new ManagementEventWatcher(query);

            // Add event handlers to be notified when a device is connected or removed
            watcher.EventArrived += new EventArrivedEventHandler(Handler_DeviceChangedEvent);

            // Start listening for events
            watcher.Start();
        }

        // -----------------------------------------------------------------
        // EVENT HANDLER: for USB FTDI device connection events
        // -----------------------------------------------------------------
        private void Handler_DeviceChangedEvent(object sender, EventArrivedEventArgs e)
        {
            using (var moBase = (ManagementBaseObject)e.NewEvent.Properties["TargetInstance"].Value)
            {
                string devicePNPId = moBase?.Properties["PNPDeviceID"]?.Value.ToString();

                switch (e.NewEvent.ClassPath.ClassName)
                {
                    case "__InstanceDeletionEvent":
                        //BeginInvoke(new Action(() => UpdateUI(eventMessage)));
                        if (devicePNPId == @"USB\VID_0403&PID_6010\" + _AllowedSerialNumber.Substring(0, _AllowedSerialNumber.Length - 1)) //remove last character (A - channel indicator) from the serial number
                        {
                            FtdiOpened = false;
                            // Raise the event
                            OnFtdiDisconnected?.Invoke(this, EventArgs.Empty);
                        }
                        break;
                    case "__InstanceCreationEvent":
                        //BeginInvoke(new Action(() => UpdateUI(eventMessage)));
                        if(devicePNPId == @"USB\VID_0403&PID_6010\" + _AllowedSerialNumber.Substring(0, _AllowedSerialNumber.Length - 1)) //remove last character (A - channel indicator) from the serial number
                        {
                            // Raise the event
                            OnFtdiConnected?.Invoke(this, new CustomEventArgs(_AllowedSerialNumber.Substring(0, _AllowedSerialNumber.Length - 1)));
                        }
                        break;
                    case "__InstanceModificationEvent":
                    default:
                        break;
                }
            }
        }

        // -----------------------------------------------------------------
        // EVENT HANDLER: Handles event triggered when FTDI is configured
        // for synchronous 245 mode; generates event for detector class
        // -----------------------------------------------------------------
        private void Handler_OnFtdiOpenedAndSetToFifoMode(object sender, CustomEventArgs e)
        {
            OnFtdiOpenedAndConfigured?.Invoke(this, new CustomEventArgs(e.Value));
        }

        // -----------------------------------------------------------------
        // Open and configure FTDI device
        // -----------------------------------------------------------------
        public void OpenAndConfigureFTDI()
        {
            // FTDI object
            FtdiFifo = new FtdiFifo();

            // FTDI device detection
            FtdiFifo.OnFtdiOpenedAndSetToFifoMode += Handler_OnFtdiOpenedAndSetToFifoMode;
            FtdiFifo.IdentifyDevice(); // FTDI device detection
            if (FtdiFifo.IsDeviceAllowed(_AllowedSerialNumber)) // Is the connected device allowed? (_AllowedSerialNumber)
            {
                // FTDI chip configuration to FIFO mode
                FtdiFifo.OpenInFifoMode(_AllowedSerialNumber);

                FtdiOpened = FtdiFifo.Opened;

                // Subscription to Events:
                FtdiFifo.OnFtdiBytesReceived += Handler_OnFtdiBytesReceived;

                // Start the consumer task
                consumerTask = Task.Run(Consumer);
            }
        }

        // -----------------------------------------------------------------
        // EVENT HANDLER: for FTDI USB data reception
        // -----------------------------------------------------------------
        void Handler_OnFtdiBytesReceived(object sender, FtdiBytesReceivedEventArgs e)
        {
            switch (_OperationMode)
            {
                case MODE_DDC_RAW_SAVE_TO_FILE:

                    _ReceivedNumberOfBytes = e.NumBytesAvailable;
                    Array.Copy(e.Bytes, 0, _ReceivedRawDataBuffer, 0, _ReceivedNumberOfBytes);

                    // Add the received data to the blocking collection
                    producerDataBuffer = new DataBuffer(_ReceivedRawDataBuffer, (int)_ReceivedNumberOfBytes);
                    collection.Add(producerDataBuffer);

                    // TEST PURPOSE ONLY - writing to separate file the same data which is enqueued in collection
                    // Data "before queue" and "after queue" can be compared later
                    _FileStreamBeforeQueue.Write(_ReceivedRawDataBuffer, 0, (int)_ReceivedNumberOfBytes);

                    break;

                default:
                    break;
            }
        }
        // -----------------------------------------------------------------
        // A method that fetches data from a queue and writes it to a file.
        // It works in a dedicated Task.
        // -----------------------------------------------------------------
        static void Consumer()
        {
            while (true)
                {
                    foreach (DataBuffer dataBuffer in collection.GetConsumingEnumerable())
                    {
                        _FileStream.Write(dataBuffer.Buffer, 0, dataBuffer.Length);
                    }

                }
        }

        // -----------------------------------------------------------------
        // A method that sends a measurement start command to the device.
        // Used for button click handling.
        // -----------------------------------------------------------------
        public void DdcEnableConv()
        {
            _OperationMode = MODE_DDC_RAW_SAVE_TO_FILE;

            String FileName = "ddc_readout_" + DateTime.Now.ToString("yyyy_MM_dd_HH_mm_ss") + ".bin";
            String FileName2 = "ddc_readout_before_queue_" + DateTime.Now.ToString("yyyy_MM_dd_HH_mm_ss") + ".bin";
            _FileStream = new FileStream(FileName, FileMode.Create, FileAccess.Write);
            _FileStreamBeforeQueue = new FileStream(FileName2, FileMode.Create, FileAccess.Write);

            Array.Clear(_CommandBytes, 0, _CommandBytes.Length);      // zeroing command array
            _CommandBytes[0] = CMD_DDC_REGISTER;                      // setting command byte (first byte)
            _CommandBytes[1] = 0x07;                                  // setting command byte (first byte)

            _CommandBytes[9] = 0x01;

            FtdiFifo.SendDataIntoFifo2(_CommandBytes);                // sending data through FTDI
        }

        // -----------------------------------------------------------------
        // A method that sends a measurement stop command to the device.
        // Used for button click handling.
        // -----------------------------------------------------------------
        public void DdcDisableConv()
        {
            _OperationMode = MODE_DDC_RAW_SAVE_TO_FILE;

            Array.Clear(_CommandBytes, 0, _CommandBytes.Length);      // zeroing command array
            _CommandBytes[0] = CMD_DDC_REGISTER;                      // setting command byte (first byte)
            _CommandBytes[1] = 0x07;                                  // setting command byte (first byte)

            _CommandBytes[9] = 0x00;

            FtdiFifo.SendDataIntoFifo2(_CommandBytes);                // sending data through FTDI
        }

    }
}

// -----------------------------------------------------------------
// A class that defines an object used to transfer measurement data
// received from the FTDI (producer) to a Task that writes the data
// to a file (consumer).
//
// Allows two arguments to be sent: the data buffer and the length
// of valid data in the buffer.
// -----------------------------------------------------------------
public class DataBuffer
{
    public byte[] Buffer { get; set; }
    public int Length { get; set; }

    public DataBuffer(byte[] buffer, int length)
    {
        Buffer = buffer;
        Length = length;
    }
}

A: The ConcurrentQueue<T> does not include waiting/blocking capabilities, so it's not a sufficient tool by itself for implementing a producer-consumer scenario. The tool that you probably need is the BlockingCollection<T>. The standard way of consuming a BlockingCollection<T> is the GetConsumingEnumerable method:
foreach (DataBuffer dataBuffer in collection.GetConsumingEnumerable())
{
    // Write the dataBuffer to the file
}

This method return an enumerator that blocks the current thread while the collection is empty. This is great if the consumer runs on a dedicated thread, but sometimes there is no particular reason for doing all the consuming work on the same thread. In that case a Channel<T> is preferable, because it can be consumed with a non-blocking enumerator, freeing a thread while the channel is empty. The standard way of consuming a Channel<T> is the ReadAllAsync method:
await foreach (DataBuffer dataBuffer in channel.Reader.ReadAllAsync())
{
    // Write the dataBuffer to the file
}

A third option is the ActionBlock<T> from the TPL Dataflow library, which is essentially a combination of an asynchronous buffer (like the Channel<T>) and a processing loop.
ActionBlock<DataBuffer> actionBlock = new(dataBuffer =>
{
    // Write the dataBuffer to the file
});

The TPL Dataflow is intended mainly for more complex scenarios, that involve multiple interconnected blocks that communicate with each other, but there is nothing wrong with using a single ActionBlock<T> like in the above example. The only gotcha that I am aware of is that the action of the ActionBlock<T> swallows exceptions of type OperationCanceledException, instead of propagating them through the Completion property of the block.


text:
Q: How to implement Dump as the one provided by LinqPad? Given (new [] {"a", "b"}).Dump(), LinqPad provides some very useful print results.
It seems that this extension method is a short hand for Console.WriteLine.
Question> how to implement this dump for myself?

A: This thread might be of use to you.
Is there a library that provides a formatted Dump( ) function like LinqPad?

A: With a lot of hard work.
Dump is not a shortcut for Console.WriteLine; it's an extremely complicated recursive method which turns arbitrary object graphs into HTML, with special support for collections, DataTables, Images, and a couple of other types.
It also has special output code to format collections of complex objects into tables, and to prevent recursive expansion.

A: You can grab the Object Dumper class that is included in the Visual C# 2008 Samples. It won't be in the pretty HTML format used by LINQPad and the other types of output it supports, but the purpose is similar.


text:
Q: Search Form Place Holder Text Incosistent Between Browsers I'm working on my wordpress search form and I can't seem to get any consistency across different browsers with regards to the text. It changes color and boldness between chrome, firefox and safari. This is only happening with the placeholder text.
Anyone have a solution for making my search form placeholder text consistent between browsers. Take a look at my code below.
<form method="get" id="searchform" class="searchform wpex-searchform" action="<?php echo esc_url( home_url( '/' ) ); ?>" role="search">

<input type="search" class="field" name="s" value="<?php echo esc_attr( get_search_query() ); ?>" id="s"  placeholder="The Appreciation of Beauty and Good Taste..."/>

<button type="submit" class="submit" id="searchsubmit"><img src="<?php bloginfo('template_url'); ?>/images/search.png" alt="Search"/></button>

</form>

CSS
input[type="search"] {
    background: #FFFFFF;
    box-sizing: border-box;
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    border: 1px solid #E8E8E8;
    font: 11px 'Helvetica Neue', Helvetica, Arial, sans-serif;
color: #BBB;
    font-weight: 500;
    display: block;
    padding: 7px 10px;
    width: 100%;
    -webkit-appearance: none !important;
    border-radius: 4px;
    box-shadow: 0px 1px 2px #ccc;
    max-width: 300px;
}

input[type="search"]::-webkit-search-cancel-button {
    -webkit-appearance: none;
}

input[type="search"]::-webkit-search-decoration {
    display: none;
}

input[type="search"]:focus {
    outline: none;
}

.wpex-searchform {
position: relative;
}

.wpex-searchform #searchsubmit {
border: none;
outline: none;
background: none;
-webkit-appearance: none;
position: absolute;
right: 5px;
top: 50%;
font-size: 12px;
margin-top: -10px;
cursor: pointer;
}

.wpex-searchform #searchsubmit:hover {
}

A: This might help. It looks like you aren't targeting the placeholder text itself in your CSS.
Taken from the answer link:
::-webkit-input-placeholder { /* WebKit browsers */
    color:    #999;
}
:-moz-placeholder { /* Mozilla Firefox 4 to 18 */
    color:    #999;
    opacity:  1;
}
::-moz-placeholder { /* Mozilla Firefox 19+ */
    color:    #999;
    opacity:  1;
}
:-ms-input-placeholder { /* Internet Explorer 10+ */
    color:    #999;
}


text:
Q: ThreadPoolTaskExecutor giving ConnectionPoolTimeOutException Getting this error even though the total count of active thread is less than the corepoolsize.
ThreadPool which I have created :
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
    executor.setCorePoolSize(1500);
    executor.setMaxPoolSize(2000);
    executor.setQueueCapacity(500);
    executor.setThreadNamePrefix("MakeShoppingRequest");
    executor.setKeepAliveSeconds(10);
    executor.setAllowCoreThreadTimeOut(true);
    executor.initialize();

Exception:
**org.springframework.ws.client.WebServiceIOException: I/O error: Timeout waiting for connection from pool; nested exception is org.apache.http.conn.ConnectionPoolTimeoutException: Timeout waiting for connection from pool**
    at org.springframework.ws.client.core.WebServiceTemplate.sendAndReceive(WebServiceTemplate.java:561)
    at org.springframework.ws.client.core.WebServiceTemplate.marshalSendAndReceive(WebServiceTemplate.java:390)
    at org.springframework.ws.client.core.WebServiceTemplate.marshalSendAndReceive(WebServiceTemplate.java:383)
    at jdk.internal.reflect.GeneratedMethodAccessor66.invoke(Unknown Source)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:344)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:198)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)
    at org.springframework.aop.interceptor.AsyncExecutionInterceptor.lambda$invoke$0(AsyncExecutionInterceptor.java:115)
    at java.base/java.util.concurrent.FutureTask.run$$$capture(FutureTask.java:264)
    at java.base/java.util.concurrent.FutureTask.run(FutureTask.java)
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
    at java.base/java.lang.Thread.run(Thread.java:834)
Caused by: org.apache.http.conn.ConnectionPoolTimeoutException: Timeout waiting for connection from pool
    at org.apache.http.impl.conn.PoolingHttpClientConnectionManager.leaseConnection(PoolingHttpClientConnectionManager.java:316)
    at org.apache.http.impl.conn.PoolingHttpClientConnectionManager$1.get(PoolingHttpClientConnectionManager.java:282)
    at org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:190)
    at org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:186)
    at org.apache.http.impl.execchain.RetryExec.execute(RetryExec.java:89)
    at org.apache.http.impl.execchain.RedirectExec.execute(RedirectExec.java:110)
    at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:185)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:83)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:56)
    at org.springframework.http.client.HttpComponentsClientHttpRequest.executeInternal(HttpComponentsClientHttpRequest.java:87)
    at org.springframework.http.client.AbstractBufferingClientHttpRequest.executeInternal(AbstractBufferingClientHttpRequest.java:48)
    at org.springframework.http.client.AbstractClientHttpRequest.execute(AbstractClientHttpRequest.java:66)
    at org.springframework.ws.transport.http.ClientHttpRequestConnection.onSendAfterWrite(ClientHttpRequestConnection.java:83)
    at org.springframework.ws.transport.AbstractWebServiceConnection.send(AbstractWebServiceConnection.java:48)
    at org.springframework.ws.client.core.WebServiceTemplate.sendRequest(WebServiceTemplate.java:658)
    at org.springframework.ws.client.core.WebServiceTemplate.doSendAndReceive(WebServiceTemplate.java:606)
    at org.springframework.ws.client.core.WebServiceTemplate.sendAndReceive(WebServiceTemplate.java:555)
    ... 15 more


text:
Q: Determine folder Size With this code I determine the file size if the checkbox is NSOnState, but with a folder value is always 0. The directory is correct.
Can you help me?
unsigned long long resultsize=0;
if(imagehistoryS.state == NSOnState) {
    NSString *path = [NSString stringWithFormat:@"Users/Giovanni/Desktop/test", [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) objectAtIndex:0]];
    NSNumber *fileSize = [[[NSFileManager defaultManager] attributesOfItemAtPath:path error:nil] objectForKey:NSFileSize];
    resultsize += [fileSize doubleValue];
}
[result setStringValue:[NSString stringWithFormat:@"Total size items selected: %f", resultsize]];

A: You're passing in a string, and yet specifying the NSUserDomainMask. I've tried this and it works.
NSUInteger resultSize = 0;

NSFileManager *fm = [[NSFileManager alloc] init];

NSURL *LibraryURL = [[fm URLsForDirectory:NSLibraryDirectory inDomains:NSUserDomainMask] lastObject];
NSURL *previewsURL = [LibraryURL URLByAppendingPathComponent:@"/Caches/com.apple.Safari/Webpage Previews"];

resultSize = [[[fm attributesOfItemAtPath:[previewsURL path] error:nil] objectForKey:NSFileSize] unsignedIntegerValue];

NSLog(@"Size: %lu", resultSize);

This is for an ARC environment.
Note, I'm using NSURLs instead of NSString filepaths as much as possible. Also, you don't need to hardcode the user's name in the search path.
Updated to show the specific folder as requested in the comments

A: In you stringWithFormat you are missing the format specifier %@.


text:
Q: Example of a subalgebra $\mathfrak{h}$ of a semisimple algebra $\mathfrak{g}$ s.t. $\mathfrak{h}$ is not semisimple. Nilpotent and solvable Lie algebras have the property that their subalgebras are also nilpotent and solvable correspondingly. That is not true for semisimple algebras.
Does this example works?
Take $\mathfrak{g}=sl_n(\mathbb{C})$ and $\mathfrak{h}=sl_n(\mathbb{C})\cap UT_n(\mathbb{C})$ where $UT_n(\mathbb{C})$ is an algebra of upper triangular matrices. We can see that $\mathfrak{h}$ is solvable since $\mathfrak{h}$ consists of upper triangular matrices.

A: Yes, your example works. But there are many, many more examples. E.g. just notice that for any non-zero element $x$ of any Lie algebra $\mathfrak g$ (over any field $k$), the one-dimensional subspace spanned by $x$, $\mathfrak h := k\cdot x$, is a Lie subalgebra of $\mathfrak g$ (since $[x,x]=0 \in k\cdot x$). Being abelian and non-zero, it is of course not semisimple.
Another example: In the structure theory of semisimple Lie algebras, the Cartan subalgebras play an important role. Again, they are abelian subalgebras, hence not semisimple. Likewise, your example is a special case of a Borel subalgebra, which is a maximal solvable subalgebra, also important in the structure theory and also not semisimple. But as said, there are many more.


text:
Q: How to reflect xib file's constraints in my Table View? I'm so stuck with creating various cell types in my Table View.
This is my way to do it.

*

*Create a TableView and put a prototype cell and give it a identifier(let's say "cell1" here)

*Create a TableViewCell file with xib file and give them the same identifier as I gave to the prototype cell("cell1")

*In the xib file, I put one imageView and label to the cell. Then set some constrains to them. Also connected them to the TableView cell file as outlets.

*In the TableViewCell file, I added those two imageView and label as subview to self.

*In the TableViewController file, I registered the Nib.

*In the TableViewController file, I set a text to the label I created in the xib file(in the "cellForRowAt" method)
I created a custom cell file with xib file and set a imageView and Label to the cell in the xib file. Then I gave an sample image to the image View and set some constrains to the imageView and label.
And then I registered my Nib into my TableViewComtroller file in View did load method.
Finally, the custom cell I created in my xib file appears on my TableView BUT the constrains I set up in the xib file completely disappears. It seems like the imageView and label are located kind of randomly. And also the sample image I set up for the imageView doesn't appear neither.
Could someone possibly help me out please?

A: As you had not provided any screenshot I can refer you a reference here with this link I had used TableView With sections in which Header cell is From Xib
I didn't faced such issue about my Constraints You can check this file as reference and hope you get where you are mistaking , if still you find issue please Comment
https://github.com/RockinGarg/Expandable-TableView-.git