text:
Q: c# string pool reference If I have two strings with the same value, they should have the same reference, right?
here is my case:
string s1 = "aaa";
string s2 = "aaa";
Console.WriteLine(" s1: {0}; s2: {1}; equals: {2}", s1,s2, ReferenceEquals(s1, s2));

prints: s1: aaa; s2: aaa; equals: True

but take a look at this code:
string s1 = "aaa";
string s2 = new string(s1.ToCharArray());
Console.WriteLine(" s1: {0}; s2: {1}; equals: {2}", s1,s2, ReferenceEquals(s1, s2));

prints: s1: aaa; s2: aaa; equals: False

Why  in the second case, the ReferenceEquals return false?

A: I've found an answer: only literal strings are saved in the intern pool
Interning literal strings is cheap at runtime and saves memory. Interning non-literal strings is expensive at runtime and therefore saves a tiny amount of memory in exchange for making the common cases much slower.
The cost of the interning-strings-at-runtime "optimization" does not pay for the benefit, and is therefore not actually an optimization. The cost of interning literal strings is cheap and therefore does pay for the benefit.


text:
Q: Using Azure WebJobs or Azure Functions to host my console application which integrates with sharepoint online lists I am working on a sharepoint online team site collection. and i want to define a job which runs on daily basis to do the following:-

*

*Integrate with SharePoint REST API, to get all the items inside a certain list which have their Due Date = Today.

*send an email to a sharepoint group.

Now when i was working on such a task inside SharePoint on-premises, i use to follow this approach :-
1- I create a .net console app which integrate with SharePoint REST API, get the related items, and finally send the email using .NET WebClient, something as follow :-
//do the checks then send an email to the related group
    using (MailMessage myMailMessage = new MailMessage())
            {
                SPOutboundMailServiceInstance smtpServer = currentsite.WebApplication.OutboundMailServiceInstance;
                System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient(smtpServer.Server.Address);
                myMailMessage.IsBodyHtml = true;
                myMailMessage.Subject = subject;
                myMailMessage.Body = body;
                smtp.Send(myMailMessage);
                //code goes here..
            }

2- place the console application on the sharepoint server.
3- using windows task scheduler tool, i create a task which executes the console application on daily basis (@1:00 am for example).
so now in sharepoint online i am not sure how i can host my console application + how i can schedule it ?. i already converted all my code inside the console application to use the client-side module instead of server-side module. but my question is about hosting & scheduling the console application. i read about these options inside Azure mainly :-

*

*WebJobs

*Azure Functions

but i am not sure which appraoch is better to follow ? and which of the 2 tools mimic the appraoch of scheduling the console application using windows tasks scheduler?. now i read this article https://anthonychu.ca/post/azure-functions-scheduled-executables/ about Azure functions, but i got confused on what does function.jso file do? and not sure if i can run standard console application using these tools? also is there a UI to configure the trigger schedule as in the windows tasks scheduler case?
Thanks

A: As Jason said, Functions are the successor to webjobs. Azure Functions is all about taking that core purpose of the WebJobs SDK, hosting it as a service, and making it easy to get started with other languages. We also introduce the "Serverless" concept here because it made a lot of sense to do so - we know how our SDK scales, so we can do intelligent things for you. While webjobs are backend console application which deploy in Web App.

but i got confused on what does function.json file do?

The function.json file that contains the configuration metadata for the function. A function can only have a single trigger binding, and can have multiple input/output bindings. Below are examples for each of the trigger types. You could refer to this wiki.
For deploying console app to Azure WebJobs, you could refer to this article to zip your console app and upload it. To set schedule trigger, you need to add a settings.job in you console app.
{
    "schedule": "0 */15 * * * *"
}

For deploy console app to Azure Function, you could refer to the article as you have provided with a timetrigger binding.
{
  "bindings": [
    {
      "type": "timerTrigger",
      "direction": "in",
      "schedule": "*/15 * * * * *",
      "runOnStartup": false
    }
  ]
}

So I recommend to use Azure Function to host.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Error with  by running Karma test Hello I am new with Angular, Material and Karma, I build a small application an run a test. I add all the needed modules in my app.componente.ts but reach the error below.
Failed: Template parse errors:
'router-outlet' is not a known element:
1. If 'router-outlet' is an Angular component, then verify that it is part of this module.
2. If 'router-outlet' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message. ("

    [ERROR ->]<router-outlet></router-outlet>

"): ng:///DynamicTestModule/AppComponent.html@6:4

Here is a list of all imports in my app.component.
Importes of app.component.ts
import { BrowserModule } from '@angular/platform-browser';
import { RouterModule, Routes } from '@angular/router';
import {Http, HttpModule} from '@angular/http';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
import {FormsModule} from "@angular/forms";
import {NgModule} from "@angular/core";
import {  MdSidenavModule, MdButtonModule, MdInputModule, MdCardModule, MdMenuModule, MdToolbarModule, MdIconModule,
  MdCardContent, MdToolbar, MdToolbarRow, MdToolbarBase
} from '@angular/material'

imports: [
    BrowserModule,
    HttpModule,
    FormsModule,
    RouterModule,
    RouterModule.forRoot(appRoutes, { enableTracing: true } ),
    BrowserAnimationsModule,
    MdButtonModule,
    MdCardModule,
    MdMenuModule,
    MdToolbarModule,
    MdIconModule,
    MdInputModule
  ],

I have no idea how I can fix this. Does someone can give me a hint?
UPDATE
This is the test.
describe('AppComponent', () => {
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [
        AppComponent
      ],
    }).compileComponents();
  }));

  it('should create the app', async(() => {
    const fixture = TestBed.createComponent(AppComponent);
    const app = fixture.debugElement.componentInstance;
    expect(app).toBeTruthy();
  }));

app.component.html

{{ title }}

    <router-outlet></router-outlet>

A: beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [
        AppComponent
      ], imports: [RouterTestingModule], // <---
    }).compileComponents();
  }));


text:
Q: Highcharts changing tooltip datetime with formatter I have a graph that looks like the below. By default each tooltip value is in it's own tooltip "bubble", with the datetime at the bottom of the Y axis (hovering on top of the X labels).

The problem is that changing the format of the datetime to match locale is not dynamic with Highcharts. I know I could have users change the dateTimeLabelFormats to match their locale, but I'm looking to leverage moment.js and their locale formatting built in.
I only need to change the datetime in these charts and nothing else.
When I try this code below, it gives me the locale leverage I'm looking for, but the tooltips are merged into 1 box and doesn't have that same feel as default.
tooltip: {
    enabled: true,
    dateTimeLabelFormats: {
        //minute: '%e %b %H:%M',
        hour: '%e %b %H:%M'
    },
    // For locale control with moment. Combined momentjs with this answer https://stackoverflow.com/a/33939715/1177153
    formatter: function() {
        var toolTipTxt = ''+ moment.unix(this.x / 1000).format("LLL") +'';
          $.each(this.points, function(i, point) {
            toolTipTxt += '
  ' + point.series.name + ': ' + point.y+'';
        });
        return toolTipTxt;
    },
    crosshairs: true,
    shared: true
},

Is there a way to emulate default tooltip with the formatter? Individual "bubbles" for the values and the timestamp hovering at the bottom?
Is it possible to use xDateFormat with moment.js somehow?

A: I found a solution that works, right from the Highcharts API documentation for tooltip split.
The jsfiddle example from the API documentation had everything I needed (except moment.js).
I must have overlooked this 100 times today. Here's the final code that worked for me, and a screenshot of the result.
Now the tooltip's header will be in the right locale without the user changing any code.
tooltip: {
    enabled: true,
    // For locale control with moment.js - https://api.highcharts.com/highcharts/tooltip.split
    formatter: function () {
        // The first returned item is the header, subsequent items are the points
        return [moment.unix( this.x / 1000).format("LLL")].concat(
            this.points.map(function (point) {
                return "\u25CF " + point.series.name + ': ' + point.y;
            })
        );
    },
    split: true,
},


text:
Q: InterestRate is returning to 0, the reference I used is from another Form Brand new to C#, I've already posted on here once today and I appreciate all the help I can get! I have a program I am creating in Visual Basic. The form has one Master Form - the AccountForm.cs, three off shoot Forms - WithdrawlForm.cs, DepositForm.cs, and InterestForm.cs. I have two classes, Account.cs  and its derived class SavingsAccount.cs. I am trying to change the InterestRate in the string below to the interest rate inputted by the user on the InterestForm. This code is located on the SavingsAccount class .cs file.
     public new string toString()
    {
        return String.Format("Account Number: {0} Balance: {1:C} Interest Rate: {2:P}", AccountNumber, AccountBalance, InterestRate);
    }

The full SavingsAccount.cs file
namespace Assignment_6_third_attempt
{
public class SavingsAccount : Account
{
    private InterestForm interestForm = new InterestForm();

    private double interestRate = 0.0;

    #region Constructors
    public SavingsAccount(int accountNumber)
    {
        base.accountNumber = accountNumber;
    }

    public SavingsAccount() { }
    #endregion

   double InterestRate
   {
        get { return interestForm.interestRate ; }
        set { interestRate = interestForm.interestRate; }
    }

    public double Interest(double amount)
    {
        InterestRate = interestForm.interestRate;
        return InterestRate;
    }

    public void AddInterest(double amount)
    {
        //interestForm.CalculateInterest();
        AccountBalance = amount;
    }

    public new string toString()
    {
        return String.Format("Account Number: {0} Balance: {1:C} Interest Rate: {2:P}", AccountNumber, AccountBalance, InterestRate);
    }
}
}

And here is my AccountForm.cs file (this form is the Master Form, where account number, account balance, and interest rate are displayed.
 namespace Assignment_6_third_attempt
{
public partial class AccountForm : Form
{
    SavingsAccount savingsAccount;
    public System.Windows.Forms.Label labelInformation;

    public AccountForm()
    {
        InitializeComponent();
        labelInformation = accountInfoLabel;
    }

    private void createAccountButton_Click(object sender, EventArgs e)
    {
        Random random = new Random();
        int newAccountNumber = random.Next(0, 1000000);
        savingsAccount = new SavingsAccount(newAccountNumber);

        MessageBox.Show(savingsAccount.toString());
        accountInfoLabel.Text = savingsAccount.toString();
        depositButton.Enabled = true;
        withdrawalButton.Enabled = true;
        interestButton.Enabled = true;
    }

    private void depositButton_Click(object sender, EventArgs e)
    {
        DepositForm depForm = new DepositForm();
        depForm.ShowDialog();
        savingsAccount.Deposit((double)depForm.DepositAmount);
        accountInfoLabel.Text = savingsAccount.toString();
    }

    private void withdrawalButton_Click(object sender, EventArgs e)
    {
        try
        {
            WithdrawalForm withdrawForm = new WithdrawalForm();
            withdrawForm.ShowDialog();
            savingsAccount.Withdraw((double)withdrawForm.WithdrawAmount);
            accountInfoLabel.Text = savingsAccount.toString();
        }
        catch (InvalidOperationException ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

    private void closeAccountButton_Click(object sender, EventArgs e)
    {
        depositButton.Enabled = false;
        withdrawalButton.Enabled = false;
        accountInfoLabel.Text = "";

        savingsAccount = null; //this will clean it up off the heap.
    }

    private void interestButton_Click(object sender, EventArgs e)
    {
        InterestForm interestForm = new InterestForm(savingsAccount.AccountBalance);
        interestForm.ShowDialog();
        savingsAccount.AddInterest(interestForm.CalculateInterest());
        accountInfoLabel.Text = savingsAccount.toString();
        savingsAccount.Interest(interestForm.interestRate);
        accountInfoLabel.Text = savingsAccount.toString();
        }

    }
}

Lastly, here is my InterestForm.cs code, where the user can input a term and rate in an NumericUpDown control.
 namespace Assignment_6_third_attempt
{
 public partial class InterestForm : Form
{

    private Account account = new Account();
    //private double accountBalance;
    public double interestRate = 0.0;

    public InterestForm()
    {
        InitializeComponent();
    }

    public InterestForm(double accountBalance) : this()
    {

        //InitializeComponent();
        account.AccountBalance = accountBalance;
    }

    private void addInterestButton_Click(object sender, EventArgs e)
    {
        double interestRate = double.Parse(interestUpDown.Text);
        CalculateInterest();
        this.Close();
    }

    public double CalculateInterest()
    {
        //A = P(1 + rt)
        double accountBalance = account.AccountBalance;
        double interestRate = (double)interestUpDown.Value;
        double term = (double)termUpDown.Value;
        double estimateInterest = (accountBalance * (1 + (interestRate * term)));
        return estimateInterest;
    }

}
}

A: Edit:
Apart from all original issues mentioned, you seem to confuse the scope of your interestRate private field with interestRate local variable here:
private void addInterestButton_Click(object sender, EventArgs e)
{
    double interestRate = double.Parse(interestUpDown.Text); //this is local variable!!
    CalculateInterest();
    this.Close();
}

Note that you use local interestRate, not your class' interestRate. Again, be careful with the variable's scope. Local variable cannot be accessed globally and if you have the same variable name in the local method, you have to distinguish it with the global variable (class' field) which uses this keyword (this.VariableName is field but VariableName is local).
In your case above, simply use the class field interestRate instead of defining new local variable interestRate:
private void addInterestButton_Click(object sender, EventArgs e)
{
    interestRate = double.Parse(interestUpDown.Text); //remove the double
    CalculateInterest();
    this.Close();
}

Original:
The setter and getter of the InterestRate seems... asymmetric:
double InterestRate
{
    get { return interestForm.interestRate ; } //you get from other form
    set { interestRate = interestForm.interestRate; } //and you set from other form
}

You get interestForm.interestRate from other form and you set it to interestRate in your Form but you never use local interestRate. Change that into:
double InterestRate
{
    get { return interestRate ; }
    set { interestRate = value; }
}

That goes the same for your Interest:
public double Interest(double amount)
{
    InterestRate = interestForm.interestRate;
    return InterestRate;
}

You again use your private Form which is unused in the class apart from being constructed. Use your amount instead:
public double Interest(double amount)
{
    InterestRate = amount; //change into this
    return InterestRate;
}

Now, note also:
private void interestButton_Click(object sender, EventArgs e)
{
    InterestForm interestForm = new InterestForm(savingsAccount.AccountBalance);
    interestForm.ShowDialog();
    savingsAccount.AddInterest(interestForm.CalculateInterest());
    accountInfoLabel.Text = savingsAccount.toString();
    savingsAccount.Interest(interestForm.interestRate);
    accountInfoLabel.Text = savingsAccount.toString();
}

You have InterestForm declared there, but it is a new InterestForm, it is not your private InterestForm in your SavingAccount. In short, the InterestForm you declare and the InterestForm in your SavingAccount are two different form instances though they share the same name interestForm. Look at the access modifiers - not the name of the instance - to know the scope of your object.
That being said, the design above to use non-field InterestForm to fill up your interest is OK. I would even say, to use private InterestForm is not needed. You only need to pass the value the external InterestForm has to your SavingAccount instance, not to create private InterestForm for your SavingAccount

A: 1 - Never declare a method with the keyword "new", use override instead.  New is something I'd only allow the most senior developers to use, and they won't use it anyway except for resolving static method signature conflicts.  It will break things I promise.  That string will be different in different parts of your program and you won't know why!
2 - Create a public field in your InterestForm.cs named InterestRate or something.  When the user specifies the interest rate, set that field equal to the interest rate.  Then the SavingsAccount code can read it by calling interestForm.InterestRate.
3 - Eventually you will gag a little when you see data classes that know about their forms or view classes.  But for now, it's fine.


text:
Q: Swift: how can I keep an embedded navigation controller after a custom segue? I am trying to set up a custom segue from a view controller that is embedded in a navigation controller. When I use a show segue, everything is fine, the navigation bar remains as expected. However, when I try to use a custom segue class, the navigation bar disappears. After checking, the navigation controller is absent from the post-custom segue view controller. So it seems the problem comes from using a custom segue: how can I stay within the navigation controller with a custom segue? Here is my custom segue code, which purpose is to make the segue have a slide effect from top to bottom:
class FirstCustomSegue: UIStoryboardSegue {
override func perform() {
    var firstVCView = self.sourceViewController.view as UIView!
    var secondVCView = self.destinationViewController.view as UIView!

    // Get the screen width and height.
    let screenWidth = UIScreen.mainScreen().bounds.size.width
    let screenHeight = UIScreen.mainScreen().bounds.size.height

    // Specify the initial position of the destination view.
    secondVCView.frame = CGRectMake(0.0, -screenHeight, screenWidth, screenHeight)

    // Access the app's key window and insert the destination view above the current (source) one.
    let window = UIApplication.sharedApplication().keyWindow
    window?.insertSubview(secondVCView, aboveSubview: firstVCView)

    // Animate the transition.
    UIView.animateWithDuration(1, animations: { () -> Void in
        firstVCView.frame = CGRectOffset(firstVCView.frame, 0.0, screenHeight)
        secondVCView.frame = CGRectOffset(secondVCView.frame, 0.0, screenHeight)

        }) { (Finished) -> Void in
            self.sourceViewController.presentViewController(self.destinationViewController as! UIViewController,
                animated: false,
                completion: nil)
    }

}

}

A: I think that for a custom segue, you have to execute a navigationController.pushViewController() operation to make the new VC appear on the old NC stack. I can't see a way to make that happen with a custom segue. However, I do see a way to make it look like it happens:
class FirstCustomSegue: UIStoryboardSegue {
override func perform() {
    let firstVCView = self.sourceViewController.view as UIView!
    let secondVCView = self.destinationViewController.view as UIView!

    // Get the screen width and height.
    let screenWidth = UIScreen.mainScreen().bounds.size.width
    let screenHeight = UIScreen.mainScreen().bounds.size.height

    // Specify the initial position of the destination view.
    secondVCView.frame = CGRectMake(0.0, -screenHeight, screenWidth, screenHeight)

    // make a UIView which looks like the sourceViewController's view,
    // and add it to the destinationViewcontrollers's view,
    // in the right place so it looks as though it does not move
    let v1 = firstVCView.snapshotViewAfterScreenUpdates(false)
    v1.frame = CGRectMake(0, screenHeight, screenWidth, screenHeight)
    secondVCView.addSubview(v1)

    // push the destination VC without animation
    // but it looks the same as the first so it seems as though nothing has happened.
    self.sourceViewController.navigationController?.pushViewController(self.destinationViewController, animated: false)
    // Animate the transition.
    UIView.animateWithDuration(1, animations: { () -> Void in
            secondVCView.frame = CGRectOffset(secondVCView.frame, 0.0, screenHeight)
        }) { (Finished) -> Void in
            v1.removeFromSuperview()
        }
    }
}

That does the pushViewController without an animation, then makes it look like it is animated by putting a snapshot of the source view temporarily onto the second view. It looks OK on my iPad.


text:
Q: How can I get the thumbnail that nautilus uses for a given file? Nautilus shows me a thumbnail of a file, if its an image it will show me a preview, if its a video it will show a frame from the video, if its a document it will show me the application icon.
How can I access the image?
I see they are cached in ~/.thumbnail/ however they are all given unique names.

A: Simple Python tool to calculate the thumbnail path. Written by Raja, shared as an ActiveState code recipe. Note, however, that this code does not escape filenames with spaces or special characters; which means this code does not work for all filenames.
"""Get the thumbnail stored on the system.
Should work on any linux system following the desktop standards"""

import hashlib
import os

def get_thumbnailfile(filename):
    """Given the filename for an image, return the path to the thumbnail file.
    Returns None if there is no thumbnail file.
    """
    # Generate the md5 hash of the file uri
    file_hash = hashlib.md5('file://'+filename).hexdigest()

    # the thumbnail file is stored in the ~/.thumbnails/normal folder
    # it is a png file and name is the md5 hash calculated earlier
    tb_filename = os.path.join(os.path.expanduser('~/.thumbnails/normal'),
                               file_hash) + '.png'

    if os.path.exists(tb_filename):
        return tb_filename
    else:
        return None

if __name__ == '__main__':
    import sys
    if len(sys.argv) < 2:
        print('Usage:  get_thumbnail.py filename')
        sys.exit(0)

    filename = sys.argv[1]
    tb_filename = get_thumbnailfile(filename)

    if tb_filename:
        print('Thumbnail for file %s is located at %s' %(filename, tb_filename))
    else:
        print('No thumbnail found')

A:
the thumbnail filename is an md5 of the filename. However the filename
  is the absolute URI to the image (without a newline).
So you need to do:
echo -n 'file:///home/yuzem/pics/foo.jpg' | md5sum
And if it has spaces, you need to convert them to '%20', ex for "foo bar.jpg"
echo -n 'file:///home/yuzem/pics/foo%20bar.jpg' | md5sum

Found at Ubuntu forums. See also the Thumbnail Managing Standard document, linked from the freedesktop.org wiki.

A: I guess that you need to access the thumbnail programatically. You want to use the Gio library.
I haven't been able to find a way to check for the thumbnail and, if it doesn't exist, go for the application icon, so you need to do it in two steps. Here you have a sample (sorry, Python. I'm not fluent in C):
import gio
import gtk

window = gtk.Window(gtk.WINDOW_TOPLEVEL)
window.show()
hbox = gtk.HBox()
hbox.show()
window.add(hbox)

f = gio.File(path='/home/whatever/you/want.jpg')
info = f.query_info('*')

# We check if there's a thumbnail for our file
preview = info.get_attribute_byte_string ("thumbnail::path")

image = None
if preview:
    image = gtk.image_new_from_file (preview)
else:
    # If there's no thumbnail, we check get_icon, who checks the
    # file's mimetype, and returns the correct stock icon.
    icon = info.get_icon()
    image = gtk.image_new_from_gicon (icon, gtk.ICON_SIZE_MENU)

hbox.add (image)

window.show_all()
gtk.main()


text:
Q: Force Visual Studio to show items in item group at any time in vbproj In a C# project (csproj), you can expand an item group (for example a form), regardless of the "Show All Files" setting:

On the other hand, in a VB.NET project(vbproj), you can only expand an item group if you set the "Show All Files" setting on:

It comes handy to have this kind of files visible when using Slow Cheetah for example:

I tried to manually add to items
<InProject>true</InProject>

with no effect.
Is there any way to tell Visual Studio to show files in item group in a vbproj, regardless of the "Show All Files" setting, like in a csproj?


text:
Q: Is this Python unicode escape error? I'm learning Python encoding stuffs, I met following situation which is wired for me and I want to know why.
First of all, this is my environment: OSX 10.10.3
Output of the command echo $LC_CTYPE, $LANG is:
en_US.UTF-8, en_US.UTF-8
Output of python --version is Python 2.7.6
Then I type python to enter python shell:
>>> import sys; reload(sys); sys.setdefaultencoding('utf8')
<module 'sys' (built-in)>
>>> s16 = u'我'.encode('utf16')
>>> s16
'\xff\xfe\x11b'
>>> for c in s16:
...   ord(c)
...
255
254
17
98
>>> s16_ = '\xff\xfe\x11\x62'
>>> s16_
'\xff\xfe\x11b'

So my question is: For the last line and the 4th line, why Python output '\xff\xfe\x11b' instead of '\xff\xfe\x11\x62'?

A: When Python prints bytes (str in Python 2), it prints the corresponding ASCII character for that byte if it is printable, and hex escapes it otherwise.
\x62 corresponds to ASCII 'b'. You can see this by just looking at that byte:
>>> '\x62'
'b'

A: b is a printable character, so repr() will show the character itself, not the escaped form.

Reference: str.isprintable:

Note that printable characters in this context are those which should not be escaped when repr() is invoked on a string.


text:
Q: Determine whether the given set is closed under the usual addition and scalar multiplication, and is a (real) vector space The set of all 2 x 2 matrices of the form
\begin{bmatrix}
    x & 1 \\
    1 & x
\end{bmatrix}
Where each $x$ may be any scalar

I don't get why this doesn't close under addition textbook says thats the reason this isn't a vector space.

A: Hint:
$$\begin{bmatrix}x & 1\\1&x\end{bmatrix} + \begin{bmatrix}y & 1\\1&y\end{bmatrix}=\begin{bmatrix}x+y & \color{red}{2}\\\color{red}{2}&x+y\end{bmatrix}.$$


text:
Q: How to align multiple icons with text vertically in CSS?
I have a following div with some icons and texts (Map lengends) as
  below:

HTML code for the above:

        Legend 01

CSS for the above
.agsjsTOCNode {
    padding-top: 1px;
    padding-bottom: 1px;
    direction: rtl;
    }
    .agsjsTOCContent {
    white-space: nowrap;
}
.agsjsTOCIcon {
    vertical-align: bottom;
}
.agsjsTOCLegendLabel {
    font-size: 8pt;
    padding-left: 2px;
}

My target is to align multiple icons with text vertically in CSS as
  below:

Please see the jsfiddle:
here
Thanks in advance.....

A: If you can update your HTML structure to wrap the img element, here is a flex-based solution:

.container {
  display: inline-block;
}

.agsjsTOCNode {
    padding-top: 1px;
    padding-bottom: 1px;
    direction: rtl;
}

.agsjsTOCContent {
    display: flex;
    align-items: center;
    justify-content: center;
}

.agsjsTOCIconContainer {
  display: flex;
  flex: 1;
  justify-content: center;
}

.agsjsTOCLegendLabel {
    font-size: 8pt;
    padding-left: 2px;
}

        Legend 01

        Legend 02

        Legend 03

        Legend 04

        Legend 05

        Legend 06

A: Try flex or grid layout,
parent{
   display: flex;
   align-items: center;
}

This way any icon you use BIgger than text or smaller , the pair will be aligned every time.
https://css-tricks.com/almanac/properties/v/vertical-align/
Try some research before posting for help.

A: You can use flex.

.agsjsTOCNode {
    padding-top: 1px;
    padding-bottom: 1px;
    direction: rtl;
    display:flex;
    align-items:center;
    }
    .agsjsTOCContent {
    white-space: nowrap;
}
.agsjsTOCIcon {
    vertical-align: bottom;
}
.agsjsTOCLegendLabel {
    font-size: 8pt;
    padding-left: 2px;
}

   Legend 01
Legend 02
Legend 03

thats all

A: Just change your style for icon to this:
.agsjsTOCIcon {
    vertical-align: middle;
}


text:
Q: HTML5 - Password Regex I try to make a valid html5 pattern for a Password. It should be at least 9 characters long and contain at least one Uppercase, one lowercase, one digit and one specialcharacter of this list
()[]{}?!$%&/=*+~,.;:<>-_
I made this regex but it doesn't work... anyone can fix this?
pattern="^(?=.*\d)(?=.*[a-z])(?=.*[()[]{}?!$%&/=*+~,.;:<>-_])(?=.*[A-Z]).{9,}?$"

A: pattern="(?=.*\d)(?=.*[a-z])(?=.*[()\[\]{}?!$%&/=*+~,.;:<>_-])(?=.*[A-Z]).{9,}"

There are several errors:
^(?=.*\d)(?=.*[a-z])(?=.*[()[]{}?!$%&/=*+~,.;:<>-_])(?=.*[A-Z]).{9,}?$
# ] needs to be escaped ----^^                  ^                   ^
# otherwise it will close the character class   |                   |
# [ too but for no logical reason               |                   |
# the - is used to define a character range ----+                   |
# the range >-_ gives >?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_            |
# there's no reason to make this quantifier non-greedy -------------+

In addition, anchors ^ and $ are implicit, you don't have to put them.
Note that using ranges, you can also write the pattern like that:
pattern="(?=.*\d)(?=.*[a-z])(?=.*[!$%&(-/:-?_{}~])(?=.*[A-Z]).{9,}"


text:
Q: Поиск одинаковых символов идущих подряд (от 2 до 9) Всем привет!
Написал функцию, которая проверяет наличие одинаковых цифр идущих подряд, и показывает количество таких блоков.
Выдаёт список с циферками которые показывают сколько блоков есть и по сколько повторений в каждом.
Но меня не оставляют мысли, что можно было сделать это аккуратнее и компактнее.
Подскажите есть какие то библиотеки, функции, регулярки для подобного рода задач?
def check_repeat_digits(55533):
    a = 0
    score = 0
    score_mass = []
    sid = str(id)
    for i in sid:
        try:
            # проверка среза есть ли в нём дубликаты and предотвращаем выход за границы
            if len(set(sid[a:a+2])) == 1 and a < len(sid)-1: если ОК то
                score += 1
            # если блок одинаковых цифр прервался, заносим инфу в список, и обнуляемся
            elif score > 0:
                # +1 что бы корректно отображалось кол-во символов в блоке
                score_mass.append(score+1)
                score = 0
            else:
                a += 1
                continue
        except:
            exit()
        a += 1
    print(score_mass)

>>> [3, 2]

A: используйте регулярку
import re

res = re.findall(r"((\d)\2{1,})", "5551888337771234555")

print(res)

если вам надо искать не 2 и больше, а N и больше символов, то укажите кол-во символов в {1,}

(от 2 до 9)

будет означать {1,8}
т.е. ваш код будет выглядеть так:
import re

def check_repeat_digits(value):
    return [len(obj[0]) for obj in re.findall(r"((\d)\2{1,8})", str(value))]

A: Вам возможно понравится класс Counter из стандартной библиотеки collection. Более подробно с этим и другими полезными классами вы можете ознакомится по ссылке.
Прикрепляю альтернативу вашей функции с использованием данного класса. Если что непонятно - пишите, прокомментирую. Единственное отличие что моя реализация выходит за ограничения с поиском одинаковых цифр от 2 до 9, но мне кажется, что рассмотрев более общий вариант куда легче написать частный с дополнительным условием.
def check_repeat_digits(number):
    print([val for key, val in Counter([int(i) for i in str(number)]).items()])

A: Для общей задачи группировки есть библиотечная функция. Ну для Вашей задачи можно еще отфильтровать группы с длиной 1
import itertools
print([(len(list(g[1])), g[0]) for g in itertools.groupby('5551888337771234555')])


text:
Q: using perl to create a simple calculator I need to design a simple calculator in Perl called ex1.pl with only +, -, *, and / functions. Below is what I have.
while (@ARGV>0) {
    if ($_=~m/(\d+)\s(.)\s(\d+)/) {
        if ($2 == "+") {
            print "$1 + $3\n";
        }
        elsif ($2 == "-") {
            print "$1 - $3\n";
        }
        elsif ($2 == "*") {
            print "$1 * $3\n";
        }
        elsif ($2 == "/") {
            if ($3 == 0 ) {
                print "$1 cannot be divided by 0\n";
            }
            else {
                print "$1 / $3\n";
            }
        }
        else {
            print "operator not identified\n";
        }
    }
    else {
        print "syntax error\n";
    }
}

For example, if I type ./ex1.pl 5 + 2, It keeps reporting errors that

Use of uninitialized value in pattern match (m//) at line 4

until I press ctrl + c.  Can anyone help me identify where I did wrong??

A: The loop while(@ARGV>0) doesn't assign to $_ on which the regex match is done, so nothing is matched and the code goes to else. Also, @ARGV is never emptied so the code is in the infinite loop.
The rest of the code is syntactically correct but has to be rewritten, since it iterates over words in input while the regex is written to process the whole of it. Either the processing needs to take each argument in turn, or the command line need be assembled into a string, for that regex.
Further comments on the code in the question are posted further below.
Let me offer a different approach
use warnings;
use strict;
use feature 'say';

use Scalar::Util qw(looks_like_number);

my ($n1, $op, $n2) = @ARGV;

my $re_oper = qr{^(?:\+|-|\*|/)$};  #/

usage() if @ARGV != 3
    or not looks_like_number($n1) or not looks_like_number($n2)
    or $op !~ $re_oper;

my %calculate = (
    '+' => sub { return $_[0] + $_[1] },
    '-' => sub { return $_[0] - $_[1] },
    '*' => sub { return $_[0] * $_[1] },
    '/' => sub {
        die "Can't divide by zero" if $_[1] == 0;
        return $_[0] / $_[1]
    },
);

say $calculate{$op}->($n1, $n2);

sub usage {
    say STDERR
        "Usage: $0 number operator number\n",
        "The \"operator\" is one of +,-,\\*,/\n",
        "Note that multiplication (*) must be escaped at command line";
    exit;
}

The arguments are copied and checked for errors using looks_like_number from Scalar::Util, and a regex. I prepare the regex pattern using the qr operator so that it is specified separately, what makes testing, maintenance, and expansion easier.
Then we define a hash with anonymous subroutines as values (they are code references, see item 4. in Making references in perlref), often called a dispatch table. Thus  there is no need for a cascading if-elsif series: For a given key (the operator) the corresponding value is dereferenced and that subroutine runs.
The arguments are checked in one statement for brevity, but this is better done one by one so to be able to report to the user the exact error made (and quote input that caused it).

A few more specifics on the posted code

*

*Captured pattern for the operator need be tested using string comparison, what is done with eq operator, not with ==. See these in perlop.
So if ($2 eq '+') etc

*A regex match is by default done against the $_ variable, the default for many things in Perl.  So there is no need to write if ($_ =~ /.../) but just if (/.../). This is far clearer to read what justifies the (implicit) use of $_

*Regex pattern \d matches all kinds of digits, Unicode included. Better use [0-9]

*The pattern \s allows for one "whitespace" character.  If you combine the command line arguments into a string by $input = join ' ', @ARGV; (so to use regex on it) then that is fine. But it is still safer to allow for more spaces with \s+.

*The . in regex matches any one character. This limits possible future expansion of the script, for example to raise to power ** (etc). Consider allowing any characters between numbers, what is feasible as they are delimited on the command line by space.

*The pattern used for numbers matches only positive integers (while accidentally allowing the first one to be negative if a minus precedes it). The code above takes care of this by using looks_like_number, which utilizes all that Perl can do to recognize a number.

The question's original version had while (<>) for the loop, and the answer started with this:
The "diamond" operator (<>) reads from files submitted on the command line

Input from <> comes either from standard input, or from each file listed on the command line.

so your input 5 + 2 is taken to be filenames 5 and + and 2, and such files don't exist.
There is more complexity to this operator, about which one can read in the documentation.
The command line arguments can be accessed in @ARGV, so the simplest solution is to replace the while (<>) with foreach (@ARGV) and then process term by term.


text:
Q: How to record windows authentication popup in playwright test framework While recording test cases through the browser, the Windows Integrated Authentication window pops up, which needs a username and password for authentication. This is not being recorded by the PlayWright Headless test recorder obviously as this is not browser activity. So to automate the login process, how to handle this popup and authenticate the user, is there any workaround for this.
Could you please let me know if you have encountered this kind of issue earlier for the PlayWright test framework or any other testing framework? Any help on this and highly appreciated.


text:
Q: Matlab loadlibrary call, using a network file? On Windows, Matlab's loadlibrary appears to expect a library located on a mapped drive.
What if I want to load a library on a network file share, and in order to make my script useable by many people, I don't want to have to assume that they have all mapped their drives similarly.  I'd prefer to use a filename of the form:  \\baseName\dirname\libarary.dll
Is there a way to do that with loadlibrary?

A: Matlab understands network file names.  The issue, was with a network server with some erroneous mappings, nothing to do with matlab.


text:
Q: Write programs that read a line of input as a string and print the positions of all vowels in the string I'm a beginner in Java and I have a question regarding loops. I've been struggling with this task where it says: Write programs that read a line of input as a string and print the positions of all vowels in the string.
I have managed to print out the number of vowels in the input but I got stuck when it came to print out their positions.
Any help would be appreciated!
System.out.println("Enter your input: ");
    String input = in.nextLine();

    int sum = 0;

    for(int i = 0; i < input.length(); i++){
        char vowel = input.charAt(i);
        if(vowel == 'a'|| vowel == 'e'|| vowel == 'i'||
                vowel == 'o'|| vowel == 'u'|| vowel == 'y'){
            sum++;
        }

    }
    System.out.println(sum);

A: System.out.println("Enter your input: ");
    String input = in.nextLine();

    int sum = 0;

    for(int i = 0; i < input.length(); i++){
        char vowel = input.charAt(i);
        if(vowel == 'a'|| vowel == 'e'|| vowel == 'i'||
                vowel == 'o'|| vowel == 'u'|| vowel == 'y'){
            sum++;
            System.out.println("position ->"+i);//added line
        }

    }
    System.out.println(sum);

you just needed to add single line that prints the positions

A: Avoid char
The char type has been essentially broken since Java 2, and legacy since Java 5. As a 16-bit value, char is physically incapable of representing most of the >144,000 characters defined in Unicode.
Code point
To work with individual characters, use code point integer numbers.
Define your set of targeted vowels. Sort the array, so that we may search quickly via binary search.
int[] vowelCodePoints = "aeiouy".codePoints().sorted().toArray() ;

Get the code points of the characters in your input.
int[] codePoints = "test".codePoints().toArray() ;

Loop the array of code points of our input string, by index (zero-based counting). Test each code point to see if it is found within our array of vowel code points.
To go in the reverse direction, from code point integer to the character as text, call Character.toString.
Example code
Pull all the code together.
int[] vowelCodePoints = "aeiouy".codePoints().sorted().toArray();

int[] codePoints = "testy".codePoints().toArray();
List < Integer > indicesOfVowels = new ArrayList <>( codePoints.length );
for ( int index = 0 ; index < codePoints.length ; index++ )
{
    int position = Arrays.binarySearch( vowelCodePoints , codePoints[ index ] );
    if ( position >= 0 )
    {
        String vowel = Character.toString( codePoints[ index ] );
        System.out.println( "Vowel: " + vowel + " | Index: " + index );
    }
}

See this code run at Ideone.com.
Vowel: e | Index: 1
Vowel: y | Index: 4


text:
Q: php code in jquery script in php file I have a form filename.php and within this I have called a jquery function and I would like to include the following php code within that jquery function
<?php
  //require_once('recaptchalib.php');
  $privatekey = "your_private_key";
  $resp = recaptcha_check_answer ($privatekey,
                                $_SERVER["REMOTE_ADDR"],
                                $_POST["recaptcha_challenge_field"],
                                $_POST["recaptcha_response_field"]);

  if (!$resp->is_valid) {
    // What happens when the CAPTCHA was entered incorrectly
    die ("The reCAPTCHA wasn't entered correctly. Go back and try it again." .
         "(reCAPTCHA said: " . $resp->error . ")");
  } else {
    // Your code here to handle a successful verification
  }
  ?>

How can I do that?
Edit
I want to define a variable when the form is submitted:
<?php
  //require_once('recaptchalib.php');
  $privatekey = "your_private_key";
  $resp = recaptcha_check_answer ($privatekey,
                                $_SERVER["REMOTE_ADDR"],
                                $_POST["recaptcha_challenge_field"],
                                $_POST["recaptcha_response_field"]);

  if (!$resp->is_valid) {
    // What happens when the CAPTCHA was entered incorrectly
    $cverify = false;
  } else {
    // Your code here to handle a successful verification
    $cverify = true;
  }
  ?>

And now in js code if I have the following code and if I type correct verification code then also it alerts false
var cverify = '<?php echo json_encode($cverify); ?>';
        alert(cverify);

So how can I get checked verification when submit button is clicked?

A: On submit send an ajax request to filename.php with the entered captcha code from the formular as paramterer and in the filename.php check your captcha. If the check is correct return "true" as string else "false".
In your ajax request on complete compare the return value of filename.php against "true". If successful continue submiting the form to the server.
Please make sure that you also check your form serverside because someone could have javasctipt disabled and can therefore submit unchecked data. So you need to check the captcha on serverside again.
Ajax call:
$.ajax({
    url: "filename.php",
}).done(function(jqXHR, textStatus) {
    if (jqXHR.response != "correct") {
        alert('wrong captcha');
    } else {
        alert('correct');
    }
});

filename.php:
<?php
//require_once('recaptchalib.php');
$privatekey = "your_private_key";
$resp = recaptcha_check_answer ($privatekey,
                            $_SERVER["REMOTE_ADDR"],
                            $_POST["recaptcha_challenge_field"],
                            $_POST["recaptcha_response_field"]);

if (!$resp->is_valid) {
    // What happens when the CAPTCHA was entered incorrectly
    echo 'wrong';
} else {
    // Your code here to handle a successful verification
    echo 'correct';
}

/* EOF */

I don't know whats inside the function recaptcha_check_answer() but you need sessions to check the captcha. And I don't see that you start a session in your filename.php.


text:
Q: How to draw Dotted line between two vertices? Question: I want to draw dotted line between points E and F
MWE:
\documentclass[12pt]{article}
\usepackage{pgf,tikz,pgfplots}
\usetikzlibrary{arrows}
\begin{document}
    \begin{tikzpicture}
    \draw [line width=0.5pt] (-2,4)-- (2,4);
    \draw [line width=0.5pt] (-2,4)-- (-3,0);
    \draw [line width=0.5pt] (-3,0)-- (3,0);
    \draw [line width=0.5pt] (2,4)-- (3,0);
    \draw [line width=0.5pt] (-2,4)-- (3,0);
    \draw [line width=0.5pt] (-3,0)-- (2,4);
    \draw [line width=0.5pt] (-2.4,2.40)-- (2.40,2.40);
    \draw[color=black] (-2.00,4.4) node {$A$};
    \draw[color=black] (2.0,4.4) node {$B$};
    \draw[color=black] (-3.25,0.00) node {$C$};
    \draw[color=black] (3.25,0.00) node {$D$};
    \draw[color=black] (-2.65,2.45) node {$E$};
    \draw[color=black] (2.65,2.40) node {$F$};
    \end{tikzpicture}
\end{document}

A: Just add dotted option to corresponding draw command:
\documentclass[12pt]{article}
\usepackage{pgf,tikz,pgfplots}
\usetikzlibrary{arrows}
\begin{document}
    \begin{tikzpicture}
    \draw [line width=0.5pt] (-2,4)-- (2,4);
    \draw [line width=0.5pt] (-2,4)-- (-3,0);
    \draw [line width=0.5pt] (-3,0)-- (3,0);
    \draw [line width=0.5pt] (2,4)-- (3,0);
    \draw [line width=0.5pt] (-2,4)-- (3,0);
    \draw [line width=0.5pt] (-3,0)-- (2,4);
    \draw [line width=0.5pt, dotted] (-2.4,2.40)-- (2.40,2.40); %<-----
    \draw[color=black] (-2.00,4.4) node {$A$};
    \draw[color=black] (2.0,4.4) node {$B$};
    \draw[color=black] (-3.25,0.00) node {$C$};
    \draw[color=black] (3.25,0.00) node {$D$};
    \draw[color=black] (-2.65,2.45) node {$E$};
    \draw[color=black] (2.65,2.40) node {$F$};
    \end{tikzpicture}
\end{document}


text:
Q: Using rescue and ensure in the middle of code Still new to Ruby - I've had a look at some of the answers to seemingly similar questions but, to be honest, I couldn't get my head around them.
I have some code that reads a .csv file. The data is split into groups of 40-50 rows per user record and validates data in the rows against a database accessed via a website.
A login is required for each record, but once that user has logged in each row in the .csv file can be checked until the next user is reached, at which point the user logs out.
All that's working, however, if an error occurs (e.g. a different result on the website than the expected result on the .csv file) the program stops.
I need something that will
a) at tell me which line on the file the error occurred
b) log the row to be output when it's finished running, and
iii) restart the program from the next line in the .csv file
The code I have so far is below
Thanks in advance,
Peter
require 'csv-mapper'

loginrequired = true

Given(/^I compare the User Details from rows "(.*?)" to "(.*?)"$/) do |firstrow, lastrow|
  data = CsvMapper.import('C:/auto_test_data/User Data csv.csv') do
    [dln, nino, pcode, endor_cd, ct_cd]
  end

#Row number changed because Excel starts at 'row 1' and Ruby starts counting at 'row 0'
(firstrow.to_i-1..lastrow.to_i-1).each do |row|

  @licnum1 = data.at(row).dln
  @licnum2 = data.at(row+1).dln
  @nino = data.at(row).nino
  @postcode = data.at(row).pcode
  @endor_cd = data.at(row).endor_cd
  @ct_cd = data.at(row).ct_cd

#Login only required once for each new user-account
    if
      loginrequired == true
      logon_to_vdr #def for this is in hooks
      click_on 'P and D'
      loginrequired = false
      end

#This is the check against the database and is required for every line in the .csv file
check_ctcd #def for this is in hooks

#Need something in here to log errors and move on to the next line in the .csv file

#Compare the ID for the next record and logout if they're different
    if @licnum1 == @licnum2
        loginrequired = false
        else
    loginrequired = true`enter code here`
    click_on 'Logout'
    end
  end
end

A: It seems like you need some error logging since you apparently don't know what type of error you're receiving or where. If this script is standalone you can redirect $stderr to file so that you can read what went wrong.
# put this line at the top of your script
$stderr = File.open("/path/to/your/logfile.log","a")

When an error occurs, ruby will automatically write the error message, class, and backtrace to the log file you specify so that you can trace back the line where things are not going as expected. (When you run a script from the command line, normally this information will just get blurted back to the terminal when an error happens.)
For example, on my desktop I created a file log_stderr.rb with the following (line numbers included):
1   $stderr = File.open("C:/Users/me/Desktop/my_log.log","w")
2
3   #require a file which will raise an error to see the backtrace
4   require_relative 'raise_error.rb'
5
6   puts "code that will never be reached"

Also on my desktop I created the file raise_error.rb with the following (to deepen the backtrace for better example output):
1   # call raise to generate an error arbitrarily
2   # to halt execution and exit the program.
3   raise RuntimeError, 'the program stopped working!'

When I run ruby log_stderr.rb from the command line, my_log.log is created on my desktop with the following:
C:/Users/me/Desktop/raise_error.rb:3:in `<top (required)>': the program stopped working! (RuntimeError)
    from C:/Users/me/Desktop/log_stderr.rb:4:in `require_relative'
    from C:/Users/me/Desktop/log_stderr.rb:4:in `<main>'

If you are working in a larger environment where your script is being called amidst other scripts then you probably do not want to redirect $stderr because this would affect everything else running in the environment. ($stderr is global as indicated by the $ variable prefix.) If this is the case you would want to implement a begin; rescue; end structure and also make your own logfile so that you don't affect $stderr.
Again, since you don't know where the error is happening you want to wrap the whole script with begin; end
# at the very top of the script, begin watching for weirdness
begin
logfile = File.open("/path/to/your/logfile.log", "w")

require 'csv-mapper'

#. . .

# rescue and end at the very bottom to capture any errors that have happened
rescue => e
    # capture details about the error in your logfile
    logfile.puts "ERROR:", e.class, e.message, e.backtrace

    # pass the error along since you don't know what it is
    # and there may have been a very good reason to stop the program
    raise e
end

If you find that your error is happening only in the block (firstrow.to_i-1..lastrow.to_i-1).each do |row| you can place the begin; end inside of this block to have access to the local row variable, or else create a top level variable independent of the block and assign it during each iteration of the block to report to your logfile:
begin
logfile = File.open("/path/to/your/logfile.log", "w")
csv_row = "before csv"
#. . .

(firstrow.to_i-1..lastrow.to_i-1).each do |row|
    csv_row = row
    #. . .
end
csv_row = "after csv"

rescue => e
    logfile.puts "ERROR AT ROW: #{csv_row}", e.class, e.message, e.backtrace
    raise e
end

I hope this helps!

A: It doesn't seem like you need to rescue exception here. But what you could do is in your check_ctcd method, raise error if records doesn't match. Then you can rescue from it. In order to know which line it is, in your iteration, you could use #each_with_index and log the index when things go wrong.
(firstrow.to_i-1..lastrow.to_i-1).each_with_index do |row, i|

  @licnum1 = data.at(row).dln
  @licnum2 = data.at(row+1).dln
  @nino = data.at(row).nino
  @postcode = data.at(row).pcode
  @endor_cd = data.at(row).endor_cd
  @ct_cd = data.at(row).ct_cd

#Login only required once for each new user-account
if
  loginrequired == true
  logon_to_vdr #def for this is in hooks
  click_on 'P and D'
  loginrequired = false
  end

#This is the check against the database and is required for every line in the .csv file
  check_ctcd #def for this is in hooks
rescue => e
  # log the error and index here
...

And you can make your own custom error, and rescue only the certain type so that you don't silently rescue other errors.


text:
Q: Excel VBA Could Not Extract The URL Body I am trying to scrape and extract data from the link below by writing code in vba in excel:
http://www.tsetmc.com/Loader.aspx?ParTree=15131F
I used different techniques:

*

*MSXML2.XMLHTTP60               it does not work

*MSXML2.ServerXMLHTTP60         it does not work

*SHDocVw.InternetExplorer       beside it is too slow, it rarely works.

In Facts, when I open the link in Firefox or chrome, the page is ok and it is displayed correctly but when I request the page through "MSXML2.XMLHTTP60" or "MSXML2.ServerXMLHTTP60", the returned response is completely different from what it must be.
I am not sure but I guess the problem is related to one of the following cases:

*

*http://www.tsetmc.com/robots.txt    This site restrict the requesting.

*the site is based on asp.net and it could not be scraped.

*it is related to cookies. but in private mode of Firefox the url is displayed correctly.

In the request response, there is a "div" which is hidden and as I understood the phrase "Disallow: /WebResource.axd" in the robots.txt is related to the embedded contents and I guess the hidden div is used by server to find out if a browser is requesting or non-browser is scraping. I even set header in vba exactly similar to the browser header, but it did not work.
I should say that other links of this site have the similar behavior, for example:
http://www.tsetmc.com/Loader.aspx?ParTree=151311&i=20626178773287666
I read a lot of subjects but no solution worked.
Please help to find a solution and scrape the table in the mentioned URL.
Sub CreateMainList()

    Dim MainURL As String
    Dim XMLReq As New MSXML2.XMLHTTP60
    Dim HTMLDoc As New MSHTML.HTMLDocument
    Dim MainDiv As MSHTML.IHTMLElement
    Dim MainDivChildren As MSHTML.IHTMLElementCollection
    Dim Res As String
    Dim price As Integer

    'MainURL = ThisWorkbook.Worksheets("Home").Range("C2").Value
    MainURL = "http://www.tsetmc.com/Loader.aspx?ParTree=15131F"

    XMLReq.Open "GET", MainURL, False
    'XMLReq.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
    'XMLReq.setRequestHeader "Content-Type", "text/html; charset=utf-8"
    'XMLReq.setRequestHeader "Content-Type", "text/html; charset=utf-8"
    XMLReq.setRequestHeader "Accept-Language", "en-US,en;q=0.5"
    XMLReq.setRequestHeader "Connection", "keep-alive"
    XMLReq.setRequestHeader "accept-Encoding", "gzip , deflate"
    XMLReq.setRequestHeader "accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"
    XMLReq.setRequestHeader "DNT", "1"
    'XMLReq.setRequestHeader "Upgrade-Insecure- Requests", "1"
    XMLReq.setRequestHeader "Set-Cookie", "ASP.NET_SessionId=cd03mksrog04g2ocuaeqxweb; path=/; HttpOnly"
    'XMLReq.setRequestHeader "Cache-Control", "Max-age = 0"

    'XMLReq.setRequestHeader "Cookie", MyCookie
    XMLReq.send

    If XMLReq.Status <> 200 Then
        MsgBox "Problem" & vbNewLine & XMLReq.Status & " - " & XMLReq.statusText
        Exit Sub
    End If

    ' Get the webpage response data into a variable.
    'response = StrConv(request.responseBody, vbUnicode)

    HTMLDoc.body.innerHTML = XMLReq.responseText
    Debug.Print XMLReq.responseText

    Set XMLReq = Nothing

    Set MainDiv = HTMLDoc.getElementById("main")

End Sub

and the output is:
<!doctype html><title>.:TSETMC:. :: ÏíÏå ÈÇä ÈÇÒÇÑ íÔÑÝÊå</title>
PSB is being developed by Pooya Paridel.

ÔÑßÊ ãÏíÑíÊ ÝäÇæÑí ÈæÑÓ ÊåÑÇä
 Tehran Securities Exchange Technology Management Co

<form method="post" action="./Loader.aspx?ParTree=15131F" id="form1">

<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="" />

</form>


text:
Q: How do I create a dynamic search filter in an HTML dropdown? So the scenario is this:
I have a range of cells in google sheets -> A1:A. It has Names.
I want to create an HTML form that pulls information from those cells and lists them in a dropdown.
It should allow searching and filtering in the dropdown.
I found this tutorial that helps me create a button and filter for data. I might have a way to get the data range from there, but I can't (don't know how) to make the resulted value (after search) become the value of the cell.
<!DOCTYPE html>

<meta name="viewport" content="width=device-width, initial-scale=1">

Search/Filter Dropdown

Click on the button to open the dropdown menu, and use the input field to search for a specific dropdown link.

  <button onclick="myFunction()" class="dropbtn">Dropdown</button>

    <input type="text" placeholder="Search.." id="myInput" onkeyup="filterFunction()">
    About
    Base
    Blog
    Contact
    Custom
    Support
    Tools

I can't get the value selected to become the field value (like click it and it becomes the value).
I imagine i can get the range in the script section and pass it to the filter function.
But one problem at a time.
I am really new at HTML, so any input would help !

A: Here's one approach:
// Listen on the 'click' event inside the myDropdown element:
document.querySelector("#myDropdown").addEventListener("click", e =>{
  // If the click was triggered by an  element:
  if (e.target.nodeName !== "A"){
    return;
  }
  // Set the value of the selected text to the input value:
  document.querySelector("#myInput").value = e.target.textContent;
  // Or, you can get the href value, minus the #
  // document.querySelector("#myInput").value = e.target.getAttribute("href").slice(1);
})

Check the comments on the ADDITIONAL CODE for more details.

<!DOCTYPE html>

<meta name="viewport" content="width=device-width, initial-scale=1">

Search/Filter Dropdown

Click on the button to open the dropdown menu, and use the input field to search for a specific dropdown link.

  <button onclick="myFunction()" class="dropbtn">Dropdown</button>

    <input type="text" placeholder="Search.." id="myInput" onkeyup="filterFunction()">
    About
    Base
    Blog
    Contact
    Custom
    Support
    Tools


text:
Q: Refactoring to async with SetTimeout Vuex Action So I have this call to an API in my actions at the Vuex Store, however I want to refactor it with a setTimeout, just to give my initial state time to commit(about a second).
here's the function
Authenticate: ({commit})=>{
    return new Promise((resolve) =>{
      commit('auth_request')
      return Axios.get(util.functions.pathFromScript('authenticate.php'),{params:params() }).then(resp =>{
        state.logged_in = true
        state.restricted =false
        const data = resp.data
        const session_id = data.session_id
        console.log(session_id)
        localStorage.setItem('data',data)
        localStorage.setItem('session_id',session_id)
        commit('auth_success', params, data,session_id)
        resolve(resp)
      })
    })
  }

so basically I can't figure it out where to add the async,and the timeout here. Any help would be appreciated A LOT! Thank you in advance

A: So theres already two answers to this question.
This one:
.then(resp => setTimeout(resolve, 1000){...
from here
and:
.then(promiseTimeout(2000)).then
from here


text:
Q: Converting symbol style set for ArcGIS Desktop for use in QGIS? Is there a way to convert a symbol style set for ArcGIS for use in QGIS?
There are symbols used in Incident Command I would like to use in QGIS, but can only find a style set for use in ArcGIS.  The style set I have is saved as a .style file.


text:
Q: XmlNode.OwnerDocument.ChildNodes is empty I get a XmlElement from a web service. I get something unexpected because xmlElement.OwnerDocument.ChildNodes is empty. How is that possible?
This is the xml:
<tns1:VideoSource xmlns:tns1="http://www.onvif.org/ver10/topics">
   <MotionAlarm wstop:topic="true" xmlns:wstop="http://docs.oasis-open.org/wsn/t-1" xmlns="http://www.onvif.org/ver10/events/wsdl">
   </MotionAlarm>
</tns1:VideoSource>

A: I tested you xml with the code below and there are children like you said.  I suspect there may be some white characters that is creating an error.  If you got data from a website (probably a stream) there may be some null characters at the end of the stream that is invisible.  Make sure your stream class is using UTF8 encoding.  The default encoding in some streams is Ascii which can change characters and add padding character which may create issues.
           string input =
                "<tns1:VideoSource xmlns:tns1=\"http://www.onvif.org/ver10/topics\">" +
                  "<MotionAlarm wstop:topic=\"true\" xmlns:wstop=\"http://docs.oasis-open.org/wsn/t-1\" xmlns=\"http://www.onvif.org/ver10/events/wsdl\">" +
                  "</MotionAlarm>" +
                "</tns1:VideoSource>";

            XmlDocument doc = new XmlDocument();
            doc.LoadXml(input);
            XmlNodeList videoSource = doc.ChildNodes;
            XmlNodeList motionAlarm = videoSource[0].ChildNodes;


text:
Q: Resetting a Stream to clear any Snapshot errors I have a text field wrapped in a StreamBuilder and tied to a stream, the stream runs through a validator when data is added to the sink. There's a button which adds the text field value to the sink and any snapshot error is displayed on the InputDecoration.
The text field is inside a stateful widget which is a component of a parent stateful widget. The bloc is initialized outside of the Widget builder.
What I'm trying to do is reset the stream so that the snapshot error is no longer there when the child widget animates in and out of view. Currently, the error persists after the child widget rebuilds. Any idea on how to achieve this?
class Parent extends StatefulWidget {
    @override
    State<StatefulWidget> createState() {
      return ParentState();
    }
}

class ParentState extends State<Parent> with TickerProviderStateMixin {
    @override
    Widget build(BuildContext context) {
      return Container(
        child: Stack(
          children: <Widget>[
            child(),
            // other forms
          ],
        )
      );
    }
}

class Child extends StatefulWidget {
    @override
    State<StatefulWidget> createState() {
      return ChildState();
    }
}

class ChildState extends State<Child> {
    Bloc bloc;

    @override
    void initState() {
      super.initState();
      bloc = Bloc();
    }

    @override
    Widget build(BuildContext context) {
      return BlocProvider(
          bloc: appBloc,
          child: Container(
              child: StreamBuilder(
                  stream: bloc.input,
                  builder: (context, snapshot) {
                     return TextFormField(
                         decoration: InputDecoration(
                            errorText: snapshot.error,
                         ),
                      );
                  }
              ),
          ),
      );
   }
}

A: It looks like your validator still add error to stream. Usually validar code looks like:
...
if (value.validated) {
  sink.add(value);
} else {
  sink.addError('invalid value');
}

So as value is correct the strem will accept valid value w/o error.


text:
Q: Display all Posts and only certain Custom Post Types with meta fields I'm trying to display all posts and only certain custom posts on the homepage.
Essentially: (post_type = post) OR (post_type = exhibition AND featured = 1)
I'm stuck with the actual implementation though.
pre_get_posts and $query->set(...); don't seem to allow logic on the post_type, it seems you can only set (post OR exhibition) AND (featured=1).
I'd rather not have to set featured=1 on every single post.
Any help appreciated.

A: You can't specify OR or AND on arbitrary WP_Query arguments. Meta and Taxonomy queries let you specify OR or AND for those queries, but other arguments are all combined (post_type is a property of the post, not meta, so a meta query won't help). Refer to the documentation for each of the possible arguments and how to use them.
You'll see that some arguments support an Array as a value, like post_type, so you can pass 'post_type' => ['post', 'exhibition'] and it will get both exhibition and post posts.
However when you're doing this you can't specify that another argument or meta query only apply to one of the post types.
If the posts are going to be displayed separately, then you could just perform 2 queries. Otherwise you will need to query the database directly with wpdb. That would look something like:
global $wpdb;

$results = $wpdb->get_results(
    "SELECT
        posts.*
    FROM
        $wpdb->posts posts
    LEFT JOIN
        $wpdb->postmeta ON
            ( posts.ID = postmeta.post_id AND postmeta.meta_key = 'featured' )
    WHERE
        posts.post_type = 'post' OR
        ( posts.post_type = 'exhibition' AND postmeta.meta_value = '1' )
    "
);

I haven't tested it, but that's the rough idea. You'd need to add SQL for the posts count and any ordering as well.
There's also the posts_where and posts_join filters you could use to modify the existing query for the posts. That's a little bit more involved, but if you need to modify the main query or are relying on other WP_Query arguments and don't want to have to rewrite their SQL then you should use those filers.

A: If you are trying to return custom posts, use this.
$args = array(
          'numberposts'=> -1,
          'post_type' => 'custom post type name'
        );
$results = get_posts( $args ); //get all post data results

foreach ($results as $rel){//sift through data and find relevant meta data
  $ret = get_post_meta($rel->ID,'meta_field',true);
  if(!empty($ret)){
      //do something with this post data
  }

}

This will get all the posts that fall under that post type. Hopefully this helps get you started.


text:
Q: Why are gluons necessary? I understand that quarks are attracted to each other when they have different color charges to become neutral. I also understand that gluons are the exchange particles of the strong force by switching the color charge of two quarks, but why are they necessary? If the color charge of quarks never changed, wouldn't they still be attracted to each other and bind together to form baryons?

A: The microcosm of particles is modeled with quantum mechanical tools, and particular quantum field theory is used to model interactions. Interactions need the exchanged bosons by construction of the theories.
Take the simple interaction of an electron with another electron, which classically is described with fields and the forces between charges. At the micro level the following feynman diagrams allow to calculate the interaction between the two particles,

The virtual photon carries the force of the interaction, the dp/dt.
This is  the first order diagram in a perturbative expansion, the higher order terms give a much  smaller contribution.
One does not use feynman diagrams to calculate the binding of an electron to a proton so as to produce a hydrogen atom, because the quantum mechanical equations can be solved analytically, and the energies are not very high, but the binding of the electron to the proton is due to the exchanges of photons between them.
So at the micro level there is always the need of an exchanged particle.
Quarks are never free, they were discovered because of symmetries in the hadronic resonances produced in scattering experiments, first seen after the midlle of last century. The need of a strong interaction which does not allow freedom for quarks  at our laboratory energies led to proposing QCD , where the exchanged particles carry a charge also (the photon has zero charge) which gives rise to the strong attractive force.

Gluon interactions are often represented by a Feynman diagram. Note that the gluon generates a color change for the quarks. The gluons are in fact considered to be bi-colored, carrying a unit of color and a unit of anti-color as suggested in the diagram at right. The gluon exchange picture there converts a blue quark to a green one and vice versa. The range of the strong force is limited by the fact that the gluons interact with each other as well as with quarks in the context of quark confinement. These properties contrast them with photons, which are massless and of infinite range. The photon does not carry electric charge with it, while the gluons do carry the "color charge".

Your question :

If the color charge of quarks never changed, wouldn't they still be attracted to each other and bind together to form baryons?

gets the answer "no" , because there would be no carrier of the interaction for binding. If there were no photons, neither the hydrogen atom would exist.
Zero color gluons would not mathematically be able to build up the strong force, i.e. the attraction growing stronger with distance within a hadron..
The particular model SU(3)_colorxSU(2)_weakxU(1)_electromagnetic developed by fitting the data in a unified mathematical frame which fits known data and is predictive of new data, the standard model.


text:
Q: alternative to mysql_real_escape_string (access_denied) Im using sphinxql currently and using mysql_real_escape_string on my $query but since there is no database connection...I get an access denied. I was looking for alternatives :
$query = $_GET["query"];

$query = trim($query);
$remove = array(',','}','{',']','[',';',':','>','<','|',')','(','*','%','$','!','^','/');
$query=str_replace($remove, "", $query);
$con = mysql_connect("localhost:9306","root","");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

$res = mysql_query("SELECT * FROM test1 WHERE MATCH ('$query')");

A: you can use this function if you mysteriously want to escape values without a database connection :
<?php
function mysql_escape_mimic($inp) {
    if(is_array($inp))
        return array_map(__METHOD__, $inp);

    if(!empty($inp) && is_string($inp)) {
        return str_replace(array('\\', "\0", "\n", "\r", "'", '"', "\x1a"), array('\\\\', '\\0', '\\n', '\\r', "\\'", '\\"', '\\Z'), $inp);
    }

    return $inp;
}
?>

A:
but since there is no database connection...I get an access denied.

Run mysql_real_escape_string() after the connection has been established. There is no other way.
The fact that the escaping function requires an active connection is by design and necessary so it knows the character set it's preparing the data for. Without that information, there is room for vulnerabilities.

A: Already answered at: Alternative to mysql_real_escape_string without connecting to DB
too much php said: "It is impossible to safely escape a string without a DB connection. mysql_real_escape_string() and prepared statements need a connection to the database so that they can escape the string using the appropriate character set - otherwise SQL injection attacks are still possible using multi-byte characters.
If you are only testing, then you may as well use mysql_escape_string(), it's not 100% guaranteed against SQL injection attacks, but it's impossible to build anything safer without a DB connection."

A: Why would you need mysql_real_escape_string i you don't have a connection?
You could connect first, and assemble the query afterwards (before executing it)

A: I can use mysql_real_escape_string() function connected to a SphinxQL server this way:
$msg_sphinx = mysql_real_escape_string($msg, $db_sphinx);

$db_sphinx is the resource PHP uses to handle SphinxQL connection:
$db_sphinx = mysql_connect(DB_SPHINX_SERVER, DB_SPHINX_USER, DB_SPHINX_PASS);

So, there is no need to use an alternative to mysql_real_escape_string() function

A: Its not safe to pass direct query string to database even by replacing this set of strings. you can also add '-' or '--' in string replacement set to avoid SQL injection as '--' is used for SQL comments and its key to SQL injection.
Moreover I also tried to pass sql statement in HTML form element from one page to another but its also not worked as HTML request and response add few extra characters in the end of string.
Session variable also useless to do the same.


text:
Q: Automatic zeroes in an Excel column I'm new to Excel and I was wondering what could be done about this issue.
What I did:

*

*Created a table for a simple list.

*Keyed in Cost and Quantity

*=D5*E5 for the first item's total

The subsequent values for the Total column shows zeroes, which I don't want.
I want a list wherein the Total column is only populated after its corresponding row for Cost and Quantity is keyed in.
Secondly, I'd also like to know how to specify a dynamic range for the calculating Grand Total (since the size of list is variable) on a different cell.
Any and all help is appreciated.

A: You can use an IF statement for your first question:
=IF(AND(D5<>"",E5<>""),D5*E5,"")

& to create a dynamic range you can use OFFSET.
Press Ctrl + F3and click New.
Then enter the below formula in the refers to box :
Change Sheet1, to that of the sheet where your Grand Total Is,
Change $A$1, to the Cell where the header Grand Total is.
& Change $A:$A to the column which has the Grand Total.
=OFFSET(Sheet1!$A$1,0,0,COUNTA(Sheet1!$A:$A)-1,1)

Give the range a name, then you can use the below to sum it:
=SUM(example)

A: My solution has a  different approach:
You can try this formula for the first part of the question to avoid,  "subsequent values for the Total column shows zeros".
=IF(NOT(OR(D5="",E5="",D5=0,E5=0)),(D5*E5),"Cell Blank/Zero")

How it works:

*

*Formula will check both D5 & E5, whether they are neither blank
nor contains Zero and if not then only multiple D5 with E5.

Below is the Dynamic formula to Calculate the Grand Total.
=SUM(Sheet1!A1:INDEX(Sheet1!A:A,MATCH(9.999999E+307,Sheet1!A:A)))

How it works:
MATCH(9.999999E+307,Sheet1!A:A)

*

*Returns total number of values in entire column A of Sheet 1, which changes
according to the number of entries been updated and makes the formula Dynamic
to SUM values .

N.B.
Adjust Cell references & Sheet Name in formula as needed.


text:
Q: Pong Paddle Movement Issues I'm working on a Pong game for my portfolio right now in Java, and I'm just having a slight problem with the Pong paddle movement. Obviously, I don't want the paddles moving off-screen, so I'm trying to make it so when it reaches a certain point on its Y-axis, it will not move any farther. I've gotten it to work for the top of the screen, but not the bottom, and I can't figure out why. The conditional I'm using SHOULD work, but it will just move right off the bottom of the screen if I go far enough. Here's the conditionals for each paddle's movement. If you need more of my code, just ask.
// Check for Left Paddle movement.
if( ( wKey ) && ( paddle_left.getY() >= ( paddle_speed * 2 ) ) )
    paddle_left.setY( paddle_left.getY() - paddle_speed );
else if( ( sKey ) && ( paddle_left.getY() <= ( boardHeight - 10 ) ) )
    paddle_left.setY( paddle_left.getY() + paddle_speed );

// Check for Right Paddle movement
if( ( upKey ) && ( paddle_right.getY() >= ( paddle_speed * 2 ) ) )
    paddle_right.setY( paddle_right.getY() - paddle_speed );
else if( ( downKey ) && ( paddle_right.getY() <= ( boardHeight - 10 ) ) )
    paddle_right.setY( paddle_right.getY() + paddle_speed );

The variable paddle_speed is a constant equal to 5. Also, boardHeight is the height of the screen on which everything is drawn, which is equal to 480.
Also, this isn't as important, but I've noticed a slight delay from when I start to hold down the key to when the paddle starts moving. I know it's because of the initial key press delay set on the user's computer, but how can I compensate for this?
EDIT:
Ok, I changed my code to reflect your answer and I've got this now:
// Check for Left Paddle movement.
if( ( wKey ) && ( paddle_left.getY() >= ( paddle_speed * 2 ) ) ) paddle_left.setY( paddle_left.getY() - paddle_speed );
else if( ( sKey ) && ( paddle_left.getY() <= ( boardHeight - ((paddle_speed * 2) + paddleHeight) ) ) ) paddle_left.setY( paddle_left.getY() + paddle_speed );

// Check for Right Paddle movement.
if( ( upKey ) && ( paddle_right.getY() >= ( paddle_speed * 2 ) ) ) paddle_right.setY( paddle_right.getY() - paddle_speed );
else if( ( downKey ) && ( paddle_right.getY() <= ( boardHeight - ((paddle_speed * 2) + paddleHeight) ) ) ) paddle_right.setY( paddle_right.getY() + paddle_speed );

However, it still goes a little below screen. It does stop now, but it goes maybe 20 pixels beyond the screen still. I don't get it. I even used Paint and drew the coordinates and simulated how the logic should work, and it should stop 5 pixels from the edge of the bottom of the screen. Can you figure out why it's not?

A: It's probably because you don't take the size of your paddle into account when checking for the bottom of the screen. So if your paddle is bigger than your speed size (5) then it will be draw below the bottom of the screen.
For the key repeat delay problem you will probably have to keep flags for which keys are down. Set the flags on keyPressed() events and clear it on keyReleased() and then update the paddles using a timer.


text:
Q: ProducerFencedException kafka We are getting issues in Kafka event sending. Events sending was working as expected till 1000 request tested in parallel, but at times it throws
Kafka Timeout issue:
  "Timeout expired after 60000milliseconds while awaiting
  InitProducerId"

Following the timeout issue, we get transaction abort exception
  "message": "TransactionalId dev-dlk2-api-transactional-490aeb31:
  Invalid transition attempted from state COMMITTING_TRANSACTION to
  state ABORTING_TRANSACTION"

ProducerFencedException was thrown later on when we tried sending the events
Can anyone suggest solution or workaround for this?


text:
Q: Logo to the left, form to the right I am using Bulma and Vue, and I am trying to create a header for the site that consists of a logo on the left and a login form on the right.
This gives me a logo on the left, and then from the end of the logo until the end of the screen on the right, I have the elements shown there.
How do I do what I want? Thanks.
Template

        FreeSongs™
        <form class="navbar-menu" @submit.prevent="signin" accept-charset="utf-8" autocomplete="on">

                <FormField type="email" required="required" :tabindex="1" placeholder="Email" name="login[email]" autocomplete="email" v-model="stageName" v-validate="'required'" autocapitalize="off" autofocus="autofocus"></FormField>
                <FormField type="password" required="required" :tabindex="2" placeholder="Password" name="login[password]" autocomplete="current-password" v-model="email" v-validate="'required|email'"></FormField>
                <button class="button is-success" tabindex="3" type="submit" id="signin">Sign in</button>
                Forgot password?

        </form>

FormField Component
<template>

    {{label}}
    <input :type="type" class="input" :class="{'is-danger':this.$validator.errors.has(label)}" :tabindex="tabindex" :name="name" :id="id" :autocomplete="autocomplete" :value="value" @input="updateValue" @change="updateValue" @blur="$emit('blur')" :disabled="disabled" :required="required" :placeholder="placeholder" />
    {{ this.$parent.errors.first(label) }}

</template>

A: The documentation outlines how to do this:
https://bulma.io/documentation/components/navbar/
First, the navbar is split into two.
|navbar-brand|navbar-menu|
navbar-brand will always show on the left, the navbar-menu fills the rest of the space on the right.
Inside the navbar-menu, you can specify which side items will show with two more elements.
|navbar-start|navbar-end|

        This is on the left of the bar.

        This spans the rest of the space on the right of the bar.

            This is on the left.

Your items on the left

            This is on the right.

Your items on the right


text:
Q: How do I control Drupal 8 monolog dblog log-levels I'm using Drupal 8 with the Monolog module (1.3) for external log support and Sentry logging, while preserving core database logging (dblog/watchdog).  This all works, except that I can't find a way to control the watchdog logging level (so I'm getting a lot of debug logging in production environments).
Here is my monolog configuration (monolog.services.yml):
parameters:
  monolog.channel_handlers:
    default: ['drupal.dblog', 'drupal.raven']
    custom1: ['rotating_file_custom1']
    custom2: ['rotating_file_custom2']
    custom3: ['rotating_file_custom3']
services:
  monolog.handler.rotating_file_custom1:
    class: Monolog\Handler\RotatingFileHandler
    arguments: ['file://../logs/custom1.log', 25, 'monolog.level.debug']
  monolog.handler.rotating_file_custom2:
    class: Monolog\Handler\RotatingFileHandler
    arguments: ['file://../logs/custom2.log', 25, 'monolog.level.debug']
  monolog.handler.rotating_file_custom3:
    class: Monolog\Handler\RotatingFileHandler
    arguments: ['file://../logs/custom3.log', 25, 'monolog.level.debug' ]

I tried adding a new services handler for drupal.dblog using the DrupalHandler, but I couldn't figure out what arguments to use (arguments are required and it is expecting a LoggerInterface implementation as the first argument).
I've read through the module documentation, but it almost exclusively focuses on file/external logging.
Any suggestions?
TIA

A: I also was trying to accomplish this and it was also not clear to me. solution was to add the core dblog service with the '@' notation as first argument. What also should be mentioned is the fact, that log-levels are documented as 'monolog.level.debug' but should be implemented without the prefix 'monolog.level.' because the monolog parameters are not loaded correctly as they should. Here a working example:
parameters:
  monolog.channel_handlers:
    default: ['rotating_file_handler', 'db_warning_handler']
    locale: ['null']
  monolog.processors: ['message_placeholder', 'current_user', 'request_uri', 'ip', 'referer', 'memory_usage']

services:
  monolog.handler.db_warning_handler:
    class: Drupal\monolog\Logger\Handler\DrupalHandler
    arguments: ['@logger.dblog', 'warning']
  monolog.handler.rotating_file_handler:
    class: Monolog\Handler\RotatingFileHandler
    arguments: ['private://logs/debug.log', 30, 'debug']


text:
Q: Json.Net does not handle deserializing a null DataTable I have this class as object to serialize:
public class JsonServerToClient
{
    public JsonServerToClient()
    {
        query = new List<Query>();
    }
    public String authKey { get; set; }
    public List<Query> query { get; set; }

    public struct Query
    {
        public int error { get; set; }
        public DataTable result { get; set; }
    }

}

I use JsonConvert.SerializeObject(objectAbove); to serialize JSON.
and JsonConvert.DeserializeObject<JsonServerToClient>(text); to deserialize it.
All works fine when the result is full of data, but if it is null I get this JSON:
{
    "authKey": "pippo",
    "query": [
        {
            "error": -1,
            "result": null
        }
    ]
}

The problem is when I try to deserialize this I get an exception:
Eccezione non gestita di tipo 'Newtonsoft.Json.JsonSerializationException' in Newtonsoft.Json.dll

Ulteriori informazioni: Unexpected end when deserializing array. Path '', line 1, position 56.

A: UPDATE
This issue was fixed in Json.Net version 8.0.1.  The workaround below is no longer needed.

It appears that the DataTableConverter that ships with Json.Net (as of v6.0.3) does not handle the case where the data table itself is null.  You can work around this issue by subclassing the DataTableConverter and overriding the ReadJson method like this:
class CustomDataTableConverter : DataTableConverter
{
    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        if (reader.TokenType == JsonToken.Null)
        {
            return null;
        }
        return base.ReadJson(reader, objectType, existingValue, serializer);
    }
}

When you deserialize, be sure to specify the custom converter:
var obj = JsonConvert.DeserializeObject<JsonServerToClient>(json,
          new CustomDataTableConverter());

A: Which version of Json.NET are you using? As per this post, it seems to be fixed with Json.NET 3.5r6

A: I have same issues using Json.Net to parse DateTime field from the json response. I tried the following Json Helper class and it handled the datetime field properly.public class JsonHelper
    {
        /// <summary>
        /// JSON Serialization
        /// </summary>
        public static string JsonSerializer<T>(T t)
        {
            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
            MemoryStream ms = new MemoryStream();
            ser.WriteObject(ms, t);
            string jsonString = Encoding.UTF8.GetString(ms.ToArray());
            ms.Close();
            return jsonString;
        }
        /// <summary>
        /// JSON Deserialization
        /// </summary>
        public static T JsonDeserialize<T>(string jsonString)
        {
            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
            MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
            T obj = (T)ser.ReadObject(ms);
            return obj;
        }


text:
Q: Regular Expression in VBA I want to write regular expression to select Agree, Ban, compare and many more which are not followed by a preposition like by, to, with, on, for, from and many more.
e.g. if a text box or cell contains Agree to it should do noting but if it contains only Agree without any preposition regular expression should select it.
I have written below pattern but not able to get my expected output.
With objRgX
    .Global = True
    .Pattern = "(Agree|Align)[ ]?(^(to|with|on))"
End With


text:
Q: Round to nearest integer strange results Is there an official specification for the round function in Haskell? In GHCi version 7.0.3 I see the following behaviour:
ghci> round (0.5 :: Double)
0
ghci> round (1.5 :: Double)
2

Since both 0.5 and 1.5 are representable exactly as floating point numbers, I expected to see the same behaviour as in Python 2:
>>> round(0.5)
1.0
>>> round(1.5)
2.0

Is there a rationale for the difference, or is it a quirk of GHCi?

A: It's in the specification. You can see it in section 6.4.6 of the Haskell report:

round x returns the nearest integer to x, the even integer if x is
  equidistant between two integers.

As pointed out by @dflemstr, this is in accordance with the IEEE Standard for Floating-Point Arithmetic.


text:
Q: How to sort GRIDVIEW table (no datasource) with vb.net I create gridview myself and no connected to database.
<asp:GridView ID="GridView3" runat="server" AllowSorting="True">
   <Columns>
      <asp:BoundField HeaderText="Dene1" SortExpression="Dene1" > </asp:BoundField>
      <asp:BoundField HeaderText="Dene2" SortExpression="Dene2" > </asp:BoundField>
   </Columns>
</asp:GridView>

Protected Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
    Dim number As New System.Random()
    Dim dt As New DataTable()
    Dim dr As DataRow = Nothing

    For i = 0 To Val(TextBox1.Text)
        dr = dt.NewRow()
        dt.Rows.Add(dr)
    Next
    GridView3.DataSource = dt
    GridView3.DataBind()

    For i = 0 To Val(TextBox1.Text)
        GridView3.Rows(i).Cells(0).Text = number.Next(0, 10)
        GridView3.Rows(i).Cells(1).Text = number.Next(10, 20)
    Next
End Sub

I want to sort any column.
Private Sub GridView3_Sorting(sender As Object, e As GridViewSortEventArgs) Handles GridView3.Sorting
    Dim dt As New DataTable("GridView3")
    Dim view As New DataView(dt)

    view.Sort = String.Format("{0} {1}", "Dene1", "ASC") 'alternative-1
    view.Sort = "Dene1 ASC"                              'alternative-2
    dt.DefaultView.Sort = "Dene1 ASC"                    'alternative-3

    GridView3.DataBind()
End Sub

All alternatives do not work. The error message is "can not find column "Dene1".
How can I solve this or How can I sorting gridview table?

A: You need to give you data table column a name:
Dim dt As New DataTable()
....
....
dt.Columns[0].ColumnName = "Dene1"

A: As per JustinHui answer the datatable will need columns with a name however I have also noted something else.
Private Sub GridView3_Sorting(sender As Object, e As GridViewSortEventArgs) Handles GridView3.Sorting
    Dim dt As New DataTable("GridView3")
    Dim view As New DataView(dt)

    view.Sort = String.Format("{0} {1}", "Dene1", "ASC") 'alternative-1
    view.Sort = "Dene1 ASC"                              'alternative-2
    dt.DefaultView.Sort = "Dene1 ASC"                    'alternative-3
    Gridview3.DataSource = dt.DefaultView
    GridView3.DataBind()
End Sub

Surely you need to add the datasource of data grid otherwise what are you binding? You seem to be missing it.
Gridview3.DataSource = dt.DefaultView

A: I think you are missing the DataField attribute.  Here is my designer code from a similar implementation.
<asp:GridView ID="GridView1" HeaderStyle-BackColor="#3AC0F2" HeaderStyle-ForeColor="White"
    runat="server" AutoGenerateColumns="false" >
    <Columns>
        <asp:BoundField DataField="Id" HeaderText="Id" ItemStyle-Width="30"/>
        <asp:BoundField DataField="Name" HeaderText="Name"  ItemStyle-Width="150"/>
        <asp:BoundField DataField="Country" HeaderText="Country" ItemStyle-Width ="150"/>
    </Columns>
</asp:GridView>

Then in the code behind.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
    Dim dt As New DataTable()
    dt.Columns.AddRange(New DataColumn() {New DataColumn("Id", GetType(Integer)), New DataColumn("Name", GetType(String)), New DataColumn("Country", GetType(String))})
    dt.Rows.Add(1, "John Hammond", "United States")
    dt.Rows.Add(2, "Mudassar Khan", "India")
    dt.Rows.Add(3, "Suzanne Mathews", "France")
    dt.Rows.Add(4, "Robert Schidner", "Russia")
    GridView1.DataSource = dt
    GridView1.DataBind()
End Sub


text:
Q: Rails Asset Pipeline: How to set the Access-Control-Allow-Origin header when serving fonts in development? The rails project that is serving these font assets is on a different domain than the project that is consuming it. In production, we will easily be able to add the Access-Control-Allow-Origin header to Apache since Apache will be responsible for serving the static assets. However, in development, we have the same setup (dev.domain1.com and dev.domain2.com) except Rails is handling the serving of the font assets (I'm assuming).
How can I configure Rails to set the Access-Control-Allow-Origin header for serving these assets in development mode?

A: The answer turned out to be easier than I thought. If you were going to add this header in production, you would want to enable the headers.mod and configure Apache to set this header in the response:
Header set Access-Control-Allow-Origin "*"

The solution to this in development is identical. The reason for this is even though Rails is serving the asset, Apache is still able to set the header.