text:
Q: Invoice pdf in php with wkhtmltopdf snappy Laravel Hi every body i have to make an invoice pdf in my LARAVEL project.
I succeeed to generate a pdf with this code :
  $path_name_file = '../ArchivePdf/'. $name_file . '.pdf';

        if ($document->type->type == 'A'){
            $pdf = SnappyPdf::loadView('ribbon.report.pdf-achat', ['document' =>$document])
            ->save($path_name_file);

        }else{
            $pdf = SnappyPdf::loadView('ribbon.report.pdf-new', ['document' =>$document])->save($path_name_file);

        }

My problem is in the blade view (HTML template) that i want to put an header and a footer and a main table with items
I want that the footer will be on all pages
How can i do that?
Thanks
That is my actual html view:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>PDF Devis</title>

    {{--<link href="{{ asset("/css/style_pdf.css")}}" rel="stylesheet" type="text/css" />--}}

                דקופלוס פרקט בע״מ

{{trans('dcp_pdf.num_doc')}} : {{ $document->code }}

                        {{trans('dcp_pdf.coord_cust')}}

{{trans('dcp_pdf.name')}}

{{ $document['customer']['name'] }} {{ $document['customer']['surname'] }}

{{trans('dcp_pdf.adress')}}

{{ $document['adress']['street'] }} {{ $document->adress->city->cityT[0]->texte  }}

{{trans('dcp_pdf.telephone')}}

{{ $document['customer']['phone'] }} / {{ $document['customer']['phone2']  }}

{{trans('dcp_pdf.mail')}}

{{ $document['customer']['email']  }}

                        {{trans('dcp_pdf.coord_fact')}}

{{trans('dcp_pdf.name')}}

{{ $document['customer']['name'] }} {{ $document['customer']['surname'] }}

{{trans('dcp_pdf.adress')}}

{{ $document['adress']['street'] }} {{ $document->adress->city->cityT[0]->texte  }}

{{trans('dcp_pdf.telephone')}}

{{ $document['customer']['phone'] }} / {{ $document['customer']['phone2']  }}

{{trans('dcp_pdf.mail')}}

{{ $document['customer']['email']  }}

                        {{trans('dcp_pdf.coord_livraison')}}

{{trans('dcp_pdf.name')}}

{{ $document['customer']['name'] }} {{ $document['customer']['surname'] }}

{{trans('dcp_pdf.adress')}}

{{ $document['adress']['street'] }} {{ $document->adress->city->cityT[0]->texte  }}

{{trans('dcp_pdf.telephone')}}

{{ $document['customer']['phone'] }} / {{ $document['customer']['phone2']  }}

{{trans('dcp_pdf.mail')}}

{{ $document['customer']['email']  }}

                {{ $document->type->typeT[0]->texte }} - {{ $document->code }}

                    {{trans('dcp_pdf.desc_article')}}
                    {{trans('dcp_pdf.conditionnement')}}
                    {{trans('dcp_pdf.quantity_m2')}}
                    {{trans('dcp_pdf.nb_colis')}}
                    {{trans('dcp_pdf.pu_ht')}}
                    {{trans('dcp_pdf.discount')}}
                    {{trans('dcp_pdf.total_ht')}}

                @foreach($document->items as $item)

{{  $item->material->textes[0]->texte }}

                        {{  $item->quantity }}
                        {{  $item->qte_col }}
                        {{    number_format($item->price, 2, '.', ',')  }}
                        {{    number_format($item->discount, 2, '.', ',')  }} {{  $item->typeRemise->code }}
                         {{    number_format($item->price_wo_vat, 2, '.', ',')  }}

                @endforeach
                @for ($i = $document->items->count(); $i < 20; $i++)

                @endfor

{{ $document['note'] }}

{{ $document['comment'] }}

                        {{trans('dcp_pdf.montant_ht')}}
                        {{    number_format($document->amount_wo_taxe, 2, '.', ',')  }}

                        {{trans('dcp_pdf.dont_remise')}}

                    @if ($document['customer']['code_tva'] === 1)

                            {{trans('dcp_pdf.tva')}} {{    number_format($document->taxe, 2, '.', ',')  }} %
                            {{    number_format($document->amount - $document->amount_wo_taxe, 2, '.', ',')  }}

                    @endif

                        {{trans('dcp_pdf.montant_ttc')}}
                        {{    number_format($document->amount, 2, '.', ',')  }}

                       {{trans('dcp_pdf.reglements')}}

                       {{trans('dcp_pdf.date')}}
                       {{trans('dcp_pdf.description')}}
                       {{trans('dcp_pdf.montant')}}
                       {{trans('dcp_pdf.mode_paiement')}}

                    @foreach($document->reglements as $reglement)

                            {{ $reglement->date }}
                            {{ $reglement->description }}
                            {{  number_format($reglement->amount, 2, '.', ',') }}
                            {{ $reglement->mode->modePaiementT[0]->texte }}

                    @endforeach

A: Here is the documentation about header and footer with Wkhtmltopdf support.
You can try
For Header
setOption('header-html', 'Your Header');

For Footer
setOption('footer-html', 'Your Footer');

Just make sure that you need to add <!DOCTYPE HTML> in the beginning of your header/footer HTML!


text:
Q: Error: connect ECONNREFUSED 127.0.0.1:6379 I have coding like this
const redis = require("redis");
const client = redis.createClient();

client.on("connect", function() {
  console.log("You are now connected");
});

client.set("student", "Laylaa", function(err, reply) {
  console.log(reply);
});

but there is an error like this..
events.js:291
throw er; // Unhandled 'error' event
^
Error: connect ECONNREFUSED 127.0.0.1:6379
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1145:16)
Emitted 'error' event on RedisClient instance at:
at RedisClient.on_error (E:\TEKNIK INFORMATIKA\Latihan redis\node_modules\redis\index.js:341:14)
at Socket. (E:\TEKNIK INFORMATIKA\Latihan redis\node_modules\redis\index.js:222:14)
at Socket.emit (events.js:314:20)
at emitErrorNT (internal/streams/destroy.js:106:8)
at emitErrorCloseNT (internal/streams/destroy.js:74:3)
at processTicksAndRejections (internal/process/task_queues.js:80:21) {
errno: -4078,
code: 'ECONNREFUSED',
syscall: 'connect',
address: '127.0.0.1',
port: 6379
}
is there a solution? Thanks

A: You need to first start the redis server by executing:
redis-server

in a terminal, after redis has been installed and before launching the Node.js client.
You could also add a script to your package.json:
"scripts": {
    "redis": "redis-server"
}

and run:
npm run redis

A: On Linux Ubuntu you'll need to run

sudo apt-get install redis-server

and Redis will automatically be up and running.Once it's started, Redis listens on port 6379
.

redpajama_set_name: RedPajamaStackExchange


text:
Q: TypeError: Cannot set property 'innerHTML' of null with a correct script location and div ID so i try to figured out how i can fill up a < select> with brand name from my firebase table.
but when my page load innerHTML function found null
i have :

*

*a correct place for my script - happens when my script is put in a
OnLoad section in my .js or right before the

*a correct name for my div - since it's the most common case, i rename it with 3 letter, never used anywhere else in the document

for now i have this :
<fieldset class="inline-fields" id="inline-field1">

            <select name="select-in" id="sel" class="form-control input-lg selectpicker" data-title="Marque" data-style="input-lg btn-default" data-live-search="true">

            </select>

          <input type="text" class="form-control form_after input-lg" id="form1" placeholder="Email"/>

          <input type="text" class="form-control form_after input-lg" id="form2" placeholder="Code Postal"/>

</fieldset>

and i try to target the #selsel
 in the #sel < select> but i paste the whole fieldset with bootstrap class for a more accurate information
here is the js :

like you can see, right before body ends, it use firebase to gather data, at the end, my elem output look like this
elem output screenshot
and my html ouput like this
html output screenshot
another interesting thing is, when i put the #sel id in
document.getElementById('selsel').innerHTML = html;

instead of selsel (wich is respectively the select#sel and the sub-div#selsel) i dont see the error but nothing came populate the select

A: Simply you can't put div inside select, the browser won't render it. Running the snippet code you've provided and inspect element

Only allowed inside select <option> or <optgroup>.
So just append <option> elements directly inside <select>, there is no point of adding them inside
, unless you want custom view of options that's another thing. And in that case you can use Select2 or bootstrap-select.
Since you are using bootstrap why you don't use jQuery.

Edit 1
Since you are using Bootstrap-select, first remove the class selectpicker from <select>

    <select name="select-in" id="sel" class="form-control input-lg" data-title="Marque" data-style="input-lg btn-default" data-live-search="true">
    </select>

Then


text:
Q: Unregistered Registration Token in Firebase I got unregistered registration token even I am sure my token is correct and I check it in my log I am using master token FirebaseInstanceId.Instance.Token.
Here is my method:
private void ConfigureFireBase()
        {

            Task.Run(() => {
                var instanceId = FirebaseInstanceId.Instance;
                Android.Util.Log.Debug("TAG", "{0} {1}", instanceId?.Token?.ToString(), instanceId.GetToken(GetString(Resource.String.gcm_defaultSenderId), Firebase.Messaging.FirebaseMessaging.InstanceIdScope));

            });

        }

I check as well OnTokenRefresh method the same token
public override void OnTokenRefresh()
        {
            var refreshedToken = FirebaseInstanceId.Instance.Token;
            Log.Debug(TAG, "Refreshed token: " + refreshedToken);
            SendRegistrationToServer(refreshedToken);
        }

but when I tried in Firebase console it gives me this error message, when I tried in http://pushtry.com/ with the same token I got not NotRegistered message
Note when I uninstall the app and install again the token working, but after while I got this error message.

A: The reason why this issue fired cause  that token is unregistered

The registration token may change when:

The app deletes Instance ID
The app is restored on a new device
The user uninstalls/reinstall the app
The user clears app data.

Reference
and this happen in debug mode only so dont worry in release mode every thing will be fine.
How you can fix the issue ?
its easy just force to refresh token call this method in your landing activity (MainActivity , Login ) , this method force firebase to call OnTokenRefresh()
private void ConfigureFireBase()
        {

#if DEBUG

            Task.Run(() =>
            {
                var instanceId = FirebaseInstanceId.Instance;
                instanceId.DeleteInstanceId();
                Android.Util.Log.Debug("TAG", "{0} {1}", instanceId?.Token?.ToString(), instanceId.GetToken(GetString(Resource.String.gcm_defaultSenderId), Firebase.Messaging.FirebaseMessaging.InstanceIdScope));

            });

            // For debug mode only - will accept the HTTPS certificate of Test/Dev server, as the HTTPS certificate is invalid /not trusted
            ServicePointManager.ServerCertificateValidationCallback += (o, certificate, chain, errors) => true;

#endif
        }

Hope this help any one face same issue

A: In my case i had used Emulator and the Firewall was blocking it. I used my mobile, enabled the developer options and it got worked.
Hope this helps.


text:
Q: Iteration over an object
*

*I need some help please regarding PDOStatement::commit (from phpnet manual)

*I don't understand Example #1, because of this part of the code:
foreach ($fruits as $fruit) {
    $sth->execute(array(
        $fruit->name,
        $fruit->colour,
        $fruit->calories,
    )
);

1#
- Does it iterate over an object, array or what?
- I've tried both ... and of course, both give errors
- Definitely, the -> operator tells me that it's an object, but I still don't understand the syntax.
- It is possible to iterate/acces simultaneously more than one property of an object?
2#
- When it is said "Insert multiple records...", I understand "more than one row", am I wrong?

*

*Thank you.

A: They iterate over array $fruits apparently. It is declared and filled out of scope of given code snippet. The $fruits contains object with given field. Do create a class, then fill $fruits. "When it is said "Insert multiple records...", I understand "more than one row", am I wrong?" - it means from 0 to N rows.


text:
Q: How can I change the value that is transmitted in post? I have this sample
CODE HTML:
  <form method="post" class="add-patient">

                <fieldset>
                    Phone*
                    <input class="required-input _phone" id="primary_phone" type="text" name="phone" maxlength="10"  value="<?php echo $prInfo->clinicphone; ?>" placeholder="1234567890">
                </fieldset>

                    <button type="Submit" id="btn-sub" class="btn btn-primary btn-save" onclick="DoSubmit()">Submit</button>

   </form>

CODE JS:
function DoSubmit(){
        var firstFormat = $("#primary_phone").val();  //ex format:(123) 123-1234
        var lastFormat = firstFormat.replace(/\s/g, ''); //the new format should be: 123-123-1234
        console.log(lastFormat);
        return true;
    }

What I want to do is transform the format text of an input before submit and pass it in the new format to POST
It is correct that we have chosen method?
What is the solution to transform this format?
Can you help me find a solution to this problem please?
Thanks in advance!

A: Something like this should get you on track
function DoSubmit(){
    var firstFormat = $("#primary_phone").val();  //ex format:(123) 123-1234
    var lastFormat = firstFormat.replace(/\D/g,"").replace(/(\d{3})(\d{3})(\d{4})/, '$1-$2-$3'); //new format: 123-123-1234
    console.log(lastFormat);
    // also do any substitution of value(s) here
    // Ex:- $("#primary_phone").val(lastFormat);
    return true;
}

$(".add-patient").submit(function() {
    DoSubmit();
});

.submit() is a shortcut for .on( "submit", handler ) in the first variation, and .trigger( "submit" ) in the third. See docs
UPDATE: Thanks @titus for pointing out about non-numeric chars.
See the updated code and this fiddle for demo.

A: Try this:
function DoSubmit(){
    var firstFormat = $("#primary_phone").val();  //ex format:(123) 123-1234
    //First, replace all non-numeric character then, replace all groups of 3 numbers (not the ending group) with the group itself fallowed by a line.
    var lastFormat = firstFormat.replace(/\D/g, "").replace(/(\d{3}(?!$))/g,"$1-");
    // Change the input's value to the new one.
    $("#primary_phone").val(lastFormat);
    return true;
}


text:
Q: How can I improve this random promo code generator script? I have this script that generates random promo codes.
    }
    $length = 10;
    $characters = '123456789ABCDEFGHJKMNPQRSTUVWXYZ';
    $charactersLength = strlen($characters);
    $event = $request->event;
    $prefix = $request->prefix;
    $quantity = $request->quantity;
    $randomString = '';
    for ($x = 0; $x <= $quantity; $x++) {
        for ($i = 0; $i < $length; $i++) {
            $randomString .= $characters[rand(0, $charactersLength - 1)];
        }

        $pin = "$prefix"."$randomString";
        $exists = Pin::where('pin', $pin)->first();
        if(!$exists){
            $new['pin'] = $pin;
            $new['event'] = $event;
            $new['user'] = '';
            Pin::create($new);
        }

        $randomString = '';
    }

It works but needs to be optimized as it can take forever to execute when the $quantity gets above a couple thousand.
I suspect the time hog is the bit that is looking if the pin exists.  I am sure there must be a more efficient way to ensure the random strings are unique.
Thoughts?  Thanks!
****** As pointed out random hash generation has been addressed here ******
Perhaps a part 2 to this question then...
Client has requested a set selection of chars for the random codes - '123456789ABCDEFGHJKMNPQRSTUVWXYZ'.  Is there a way to limit the chars output by md5 hash?

A: A much simpler way:
$randomString = sha1(rand(0, 2000));


text:
Q: Stream from Realtime Firebase DB to BigQuery Is there any extention or ways to stream data from Realtime Firebase DB to BigQuery? I have read about Stream Collections to BigQuery but the description said it can be from Cloud Firestore

A: firebaser here
There is currently no Firebase Extension for streaming data from the Realtime Database to BigQuery. It is being considered though, so I file a or feature request with our support team to express your interest in that.
But for the moment you will have to implement the functionality yourself, likely with Cloud Functions listening to changes in the Realtime Database and then calling the BigQuery API to insert the data there. Given that Extensions are open-source by definition, you could use the source of the Stream Collections to BigQuery as a template/for inspiration.


text:
Q: XmlSerializer WebResponse I have this XML with many names, like a list:
<apelidos>
    <apelido>Casmilo</apelido>
    <apelido>Castro</apelido>
</apelidos>

And I did my model like this:
namespace IdCel.Model
{
   [XmlTypeAttribute(AnonymousType = true)]
   public class apelidos
   {
       [XmlArray("apelidos")]
       [XmlArrayItem("apelidos")]
       public List<apelido> apelidosNomes { get; set; }

       public apelidos()
       {
           apelidosNomes = new List<apelido>();
       }
   }

   public class apelido
   {
       [XmlElement(ElementName = "apelido")]
       public string apelidoNome { get; set; }
   }
}

And my XmlSerializer
HttpWebRequest request = WebRequest.Create(uri) as HttpWebRequest;
XmlSerializer ser = new XmlSerializer(objetoLista.GetType());

WebResponse response = request.GetResponse();
var result = ser.Deserialize(response.GetResponseStream());

return result;

But it's not working, I do the same code with XML without list and it's working fine

A: If you just have to read the contents of the apelido tags, you are much faster when you are using Linq To XML. For example:
var xml = @"<apelidos>
                <apelido>Casmilo</apelido>
                <apelido>Castro</apelido>
            </apelidos>";

var doc = XDocument.Parse(xml);
var apelidos = from apelido in doc.Descendants("apelido")
               select apelido.Value;

This gives you an IEnumerable<string> as result containing all the names.
EDIT: To load the XML from the web you can do the following:
HttpWebRequest request = WebRequest.Create(uri) as HttpWebRequest;

WebResponse response = request.GetResponse();
var doc = XDocument.Load(response.GetResponseStream());

A: Now It's worked!
I did this:
[Serializable()]
public class apelidos
{
    [System.Xml.Serialization.XmlElement("apelido")]
    public List<string> apelido { get; set; }
}

And this:
HttpWebRequest request = WebRequest.Create(uri)
           as HttpWebRequest;

        XmlSerializer ser = new XmlSerializer(objetoLista.GetType());

        WebResponse response = request.GetResponse();
        var result = ser.Deserialize(response.GetResponseStream());

        return result;


text:
Q: X509 certificates - Are there any naming conventions? What are the naming conventions when buying certificates, if any?
When buying a cert for TLS/HTTPS for a particular Server, naturally I will default to the server's name. For example, if the server is called MOONSERVER I would set the Subject of the x509 Certificate to MOONSERVER.
Additionally, I need to use another cert for message signing. What should I call this? What are the rules for valid names? E.g. are hyphens, underscores, etc. ok? Are the names case sensitive?

A: As you are purchasing these certificates, the contents of these fields will probably be governed by the user interface of the certificate seller which will hopefully carry out some sanity check on the values you enter.
The information you should place in the Subject field depends on the application amongst other things.
HTTPS, which is just an implementation of HTTP over TLS is governed by RFC 2818 which stipulates that server identification must use the Subject Alternative Name(SAN) extension's dnsName field if present.
The CA/Browser forum, which is a consortium of commercial CAs and browser vendors, adds even stricter constraints and expects server identification to only use the SAN extension (i.e. any server DNS names in the Subject field aren't checked).  Therefore, if you have a web application where the end user uses a common web-browser (that's nearly all of us) then you will need to follow the CA/B Forum requirements and have the DNS names of your hosts in the SAN.
Note that TLS itself doesn't define any restrictions on names, therefore other applications which use TLS may have different requirements.  The same goes for non TLS usage of X.509 certificates, such as code signing.  There is guidance on the interpretation of DNS names in RFC 6125.
The rules governing what's acceptable in terms of characters etc. are in the documents which define these certificates.  That's RFC 5280 for certificates used on the Internet and X.509 for all certificates (including those used on the Internet).  The latter refers to a multitude of documents, such as X.500,X.501,X.520,X.521 and X.680.
X.520 section 6 defines many of the attributes which you can use in the Subject field.  It's a thrilling bedtime read, so if you can't spare the time, stick to the basic characters of the PrintableString type of:
A..Z a..z 0..9 (space)'()+,-./:=?

This may not be politically correct as most non-English languages won't be covered.  The alternative is to use the utf8String type which includes most characters in the world.


text:
Q: Как отнести RGB значение к 7 основным цветам? Мне нужно полученное RGB значение пикселя отнести к 7 основным цветам, каким образом это сделать на Java?

A: Наверно, как-нибудь вот так можно сделать. Задаете массив цветов, значения которого вам нужны (радуга в данном случае), а потом находите ближайший.
public int nearestRainbowColor(int color) {
    int[] rainbow = {
            0xff0000, // каждый
            0xff7f00, // охотник
            0xffff00, // желает
            0x00ff00, // знать
            0x42aaff, // где
            0x0000ff, // сидит
            0x8f00ff  // фазан
    };
    int minDiff = Integer.MAX_VALUE;
    int nearestColorIndex = 0;
    for (int i = 0; i < rainbow.length; i++) {
        if (diffBetween(color, rainbow[i]) < minDiff) {
            minDiff = diffBetween(color, rainbow[i]);
            nearestColorIndex = i;
        }
    }
    return rainbow[nearestColorIndex];
}

public static int diffBetween(int c1, int c2) {
    int r1 = c1 / 0x010000;
    int g1 = (c1 % 0x010000) / 0x00100;
    int b1 = c1 % 0x000100;
    int r2 = c2 / 0x010000;
    int g2 = (c2 % 0x010000) / 0x00100;
    int b2 = c2 % 0x000100;
    return Math.abs( r1 - r2 ) + Math.abs( g1 - g2 ) + Math.abs ( b1 - b2 );
}


text:
Q: How to receive SMS Text from mobile to Application? I developed sending SMS text to mobile using Twilio
Sending SMS from asp.net website
and it's easy, but my concern is how to receive SMS text from mobile?
Ex. Client SMS Text to

Cell Phone #: 0923#####(server CP#)
with message body: GET_REMAINING_STOCKS
Then my Application will replied 20 Stock to the sender.

I checked the other thread but I can't find the exact answer. please help

A: I'm also a Twilio developer evangelist, hello!
If you are looking to receive SMS messages in your asp.net app, then the best place to start is the quickstart guide. That should get you off the ground with receiving and responding to SMS messages in your application.
Let me know if this helps.


text:
Q: Provision headers are shown error in google chrome when using apache virtual host I have to tomcat servers running in my server. And I wanted to do a virtual host routing. So initially I tried it with one tomcat which is running in 8081 port and ajp port enabled to 8011 in the tomcat server.xml file
My conf file in the /etc/apache2/sites-available/mydomain_name.com.conf looks likes this
<VirtualHost *:80>

    ProxyRequests off
    ProxyPreserveHost On
    ServerName mydomain_name.com

    ServerAdmin ubuntu@mydomain_name.com

    ProxyPass /       ajp://localhost:8011/
    ProxyPassReverse / ajp://localhost:8011/

</VirtualHost>

Then I did
sudo a2ensite mydomain_name.com.conf
sudo service apache reload

Every thing went find, no issues. And I also ensured the port 8011 is listening.
But when I try to access the server from my personal laptop, the request is blocked by Google chrome.

I have enabled these configurations in the server too.
sudo a2enmod proxy
sudo a2enmod proxy_ajp
sudo  a2enmod proxy_http
sudo service apache2 restar

Have anyone has came across this issue ? Shedding some light would be really helpful. Because I have done some thing similar 1 year back, then this issue did not occur, and I'm only trying to direct it to the tomcat home page. Which is a bare minimal page.

A: After several frustrating hours found the issue. Hope this might help if any one came across this same issue.
Although the port 80 was opened via the aws management console security groups, internally the ports were firewall protected by the ip tables. So by removing the ip-tables entry for the port 80 I was able to make the virtual host work.


text:
Q: Pass parameter from validate to custom validator in hibernate validator I'm trying to validate a bean using custom validator. But the validator needs info that is to be passed to it from the method where validate is invoked. Is there a way to do that?
I can't pass it in initialize as it is not available at the time of bean creation.
Bean to validate
class vehicle {
   @VehicleNameValidator
   String vehicleName;
}

Annotation
@Target({ElementType.FIELD})
@Retention(RUNTIME)
@Constraint(validatedBy = VehicleNameValidatorImpl.class)
@Documented
public @interface VehicleNameValidator {
    String message() default "Invalid vehicle Name";

    Class<?>[] groups() default { };

    Class<? extends Payload>[] payload() default { };
}

custom validator
public class VehicleNameValidatorImpl implements ConstraintValidator<VehicleNameValidator, String[]> {

    @Override
    public boolean isValid(String vehicleName, ConstraintValidatorContext constraintValidatorContext) {
        boolean isValid = logicmethod()//some logic here
        return isValid;
    }
}

Main method
public static void main(String[] args) {
   String whatIwantToPass = runtimelogic(args);
   vehicle veh1 = new vehicle();
   Set<ConstraintViolation<vehicle>> constraintViolations =
   validator.validate(veh1);
}

How to I pass variable "whatIwantToPass" from main method to VehicleNameValidatorImpl.

A: In case you are using Hibernate Validator you might want to take a look at constraint validator payload. In your case it would look somewhat like this:
In your validator impl you can access the payload:
public boolean isValid(String vehicleName, ConstraintValidatorContext constraintValidatorContext) {
    boolean isValid = false;
    if ( constraintValidatorContext instanceof HibernateConstraintValidatorContext ) {
        final String payload = constraintValidatorContext
                .unwrap( HibernateConstraintValidatorContext.class )
                .getConstraintValidatorPayload( String.class );
        // do whatever you need
        isValid = logicmethod()//some logic here
    }
    return isValid;
}

And the payload can be set either on the validator factory level or per validator like this:
ValidatorFactory validatorFactory = Validation.byProvider( HibernateValidator.class )
        .configure()
        .buildValidatorFactory();

String whatIwantToPass = runtimelogic( args );

Validator validator = validatorFactory.unwrap( HibernateValidatorFactory.class )
        .usingContext()
        .constraintValidatorPayload( whatIwantToPass )
        .getValidator();

// use the validator with the constraint validator payload
vehicle veh1 = new vehicle();
Set<ConstraintViolation<vehicle>> constraintViolations = validator.validate( veh1 );

For more detailed info check this part of documentation - Passing a payload to the constraint validator

A: You could always use @Autowired or @Value annotations in the implementation of ConstraintValidator.I believe you could so something like this in your VehicleNameValidatorImpl.class
    public class VehicleNameValidatorImpl implements ConstraintValidator<VehicleNameValidator, String[]> {

        @Autowired
        LogicWrittenClass logicWrittenClass;

        @Override
        public boolean isValid(String[] roles, ConstraintValidatorContext constraintValidatorContext) {
            String whatIwantToPass  = logicWrittenClass.runtimelogic();
            boolean isValid = logicmethod()//some logic here
            return isValid;
        }
    }

But make sure that you use spring to create the validator bean otherwise the bean injection won't work as manually creating validator bean using valdiation factory  (Hibernate Validator as reference implentation) does not inject dependencies into ConstraintValidator instances.


text:
Q: Saving Changes in SlickGrid with php I have a SlickGrid set up, it is reading data from my database with PHP, my problem is arising when i try to save the data back to my database, I am trying to use JSON to give me an array that I can then use to write back to the database, i have see this thread explaining this:
Saving changes in SlickGrid
So I have the hidden form element in my code, and am using JSON to encode the data variable, the assign it to the data hidden input on the form, this form posts to a page called save_price.php, the trouble is when I print_r, or var_dump the data variable, I get null as an output, I think it might be something to do with how I am using PHP to add the content into the data variable, either that or I am doing something really obviously wrong, hopefully you can see what the problem is, there isn't a great deal of documentation online about retrieving/saving to a db with PHP, so I'm kinda stuck banging my head against the wall on this one, here's my code:

A: Ok so I found the problem, just incase anyone is struggling to get this all to work, here is the working code, it gets data from a database, then sends the changed data to another page for processing, it nees a little bit of refinements, that will happen once I've got it all implemented:
<?php
include("includes/check_session.php");
require_once('includes/functions.php');
require_once('includes/config.php');

$data = '';
$i = 0;

$query = "
    SELECT * FROM `prices`";
$result = mysql_query($query);
while($row = mysql_fetch_array($result, MYSQL_ASSOC)){
    $data .= '
        data['.$i.'] = {
            id: "'.$row['id'].'",
            title: "'.$row['title'].'",
            duration: "'.$row['duration'].'",
            percentComplete: "'.$row['percentComplete'].'",
            start: "'.$row['start'].'",
            finish: "'.$row['finish'].'",
            effortDriven: "'.$row['effortDriven'].'"
        };
    ';

    $i++;

echo $data;
}

?>
<!DOCTYPE html>

    <meta charset=utf-8>

    <?php // include("includes/cms_head_scripts.php"); ?>
    <link rel="stylesheet" href="css/slick.grid.css" type="text/css" media="screen" charset="utf-8" />
    <link rel="stylesheet" href="css/smoothness/jquery-ui-1.8.5.custom.css" type="text/css" media="screen" charset="utf-8" />
    <link rel="stylesheet" href="css/examples.css" type="text/css" media="screen" charset="utf-8" />

            pricing

<form method="POST" action="save_price.php">
    <input type="submit" value="Save">
    <input type="hidden" name="data" value="">
</form>


text:
Q: Replace in their previous place all those substrings extracted with .group() method in their original string after they have been modified how to apply the indicated modification process to each of the substrings extracted from the string called input_text with re.group() method, and then replace them in the original string input_text.
I think I should put a for loop that iterates over the lists inside the list called civil_time_unit_list
import re

def numerical_time_corrector(input_text):
    hh, mm, am_pm, output = "", "", "", ""

    input_text = re.sub(r"([0-9])h.s.", r"\1 ", input_text)
    input_text = re.sub(r"([0-9])\s*h.s.", r"\1 ", input_text)
    input_text = re.sub(r"([0-9])hs", r"\1 ", input_text)
    input_text = re.sub(r"([0-9])\s*hs", r"\1 ", input_text)

    civil_time_pattern = r'(\d{1,2})[\s|:]*(\d{0,2})\s*(am|pm)?'
    civil_time_unit_list = re.findall(civil_time_pattern, input_text)
    print(civil_time_unit_list)
    # civil_time_unit_list[list of detected schedules][lists with the 3 elements of each of the schedules]

    #process to be applied to all times detected within the input string and stored in the list
    #-----------------------------------------
    try:
        hh = civil_time_unit_list[0][0]
        if (hh == ""): hh = "00"
    except IndexError: hh = "00"

    try:
        mm = civil_time_unit_list[0][1]
        if (mm == ""): mm = "00"
    except IndexError: mm = "00"

    try:
        am_pm = civil_time_unit_list[0][2]
        if (am_pm == ""): am_pm = "am"
    except IndexError: am_pm = "am"

    if (len(hh) < 2):
        hh = "0" + hh
    if (len(mm) < 2):
        mm = "0" + mm

    output = (hh + ":" + mm + " " + am_pm).strip()
    #-----------------------------------------

    #Here the program should replace this new value in the original input string
    #input_text = ""

    #return input_text #It should return the new input_string with all values replaced
    return output #I am returning the output just to test that it works, since it should return the original string but with the replacements already done.

input_text = "el cine esta abierto hasta 23:30 pm o 01:00 am, 1:00 hs am 1:00 pm, : p m, 1: pm  5: h.s. pm"

input_text = numerical_time_corrector(input_text)
print(repr(input_text))

You can see how it erroneously prints only one of the values to be corrected in the original string, and not the original string with all its corrected values. This is the wrong output:
[('23', '30', 'pm'), ('01', '00', 'am'), ('1', '00', 'am'), ('1', '00', 'pm'), ('1', '', 'pm'), ('5', '', 'pm')]
'23:30 pm'

And this is the output I really need to get :
[('23', '30', 'pm'), ('01', '00', 'am'), ('1', '00', 'am'), ('1', '00', 'pm'), ('1', '', 'pm'), ('5', '', 'pm')]
'el cine esta abierto hasta 23:30 pm o 01:00 am, 01:00 am 01:00 pm, 00:00 pm, 01:00 pm  05:00 pm'

What should I change in my code so that this fix is applied to all the extracted substrings and then replace everything in input_text string and then return it from the function and print it to the console?

A: Try:
import re

def numerical_time_corrector(input_text):
    civil_time_pattern = r"(\d*):(\d*)\s*(?:h[ .]?s[ .]?)?\s*(a\s*m|p\s*m)?"
    return re.sub(
        civil_time_pattern,
        lambda g: "{:>02}:{:>02} {}".format(
            g[1] or "", g[2] or "", (g[3] or "").replace(" ", "")
        ),
        input_text,
    )

input_text = "el cine esta abierto hasta 23:30 pm o 01:00 am, 1:00 hs am 1:00 pm, : p m, 1: pm  5: h.s. pm"

input_text = numerical_time_corrector(input_text)
print(repr(input_text))

Prints:
'el cine esta abierto hasta 23:30 pm o 01:00 am, 01:00 am 01:00 pm, 00:00 pm, 01:00 pm  05:00 pm'

A: Well, you could do this in a two step re.sub() using PyPi's regex module. For example:
import regex as re

input_text = 'el cine esta abierto hasta 23:30 pm o 01:00 am, 1:00 hs am 1:00 pm, : p m, 1: pm  5: h.s. pm'
output_text = re.sub(r'(?:(?<!\d)(?=\d?:)|(?<!\d)(:)|(?<=:)(?!\d)|(?<=:\d?)(\D))', r'0\1\2', input_text)
output_text = re.sub(r'(\d\d:\d\d)(?:\s*h\.?s\.?)?(\s[ap])\h*(m)', r'\1\2\3', output_text)

print(output_text)

Prints:
el cine esta abierto hasta 23:30 pm o 01:00 am, 01:00 am 01:00 pm, 00:00 pm, 01:00 pm  05:00 pm


text:
Q: Kotlin Recyclerview Stack Layout Type showing wrong views I am attempting to write a recyclerview which has some of the Viewholders inside it as stacked ontop of one another.  The idea is that you can drag the topmost view above the stacked list and have drop it above where it becomes separate.
I managed to get this working using a Recyclerview with a custom RecyclerView.ItemDecoration.  However, after I drop the item, i have the adapter call notifyDataSetChange to update the background code.  This causes the the next item in the stack to appear to be the wrong one (though this does change sometimes if you touch the item and start scrolling, then it displays the correct one).
The custom RecyclerView.ItemDecoration class:
override fun getItemOffsets(
    outRect: Rect,
    view: View,
    parent: RecyclerView,
    state: RecyclerView.State
)
{
    val itemPosition = parent.getChildAdapterPosition(view)
    val adapter = parent.adapter
    if (adapter is BaseRecVAdapter)
    {
        val item = adapter.getDataModel(itemPosition)
        if (item is DragDropModel && item.mStackedPos != PMConsts.negNum)
        {
            if (item.mStackedPos != 0)
            {
                val context = view.context
                val top = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 148f, context.resources.displayMetrics).toInt()
                outRect.set(0, -top, 0, 0)
                return
            }
        }
    }
    super.getItemOffsets(outRect, view, parent, state)
}

The drag interface I made for the Adapter and the ItemTouchHelper.Callback can be found below:
interface ItemTouchHelperListener
{
    fun onItemMove(fromPosition: Int, toPosition: Int): Boolean
    fun onClearView(recyclerView: RecyclerView?, viewHolder: RecyclerView.ViewHolder?)
}

The onItem move code is as follows:
override fun onItemMove(fromPosition: Int, toPosition: Int): Boolean
    {
        var newToPosition = toPosition
        if (toPosition <= mDragUpLimit)
        {//Prevent items from being dragged above maximum movement.
            newToPosition = mDragUpLimit + 1
        }
        else if (toPosition >= mDragDownLimit)
        {//Cannot drag below stacked List...
            newToPosition = mDragDownLimit - 1
        }
        if (fromPosition < newToPosition)
            {
                for (i in fromPosition until newToPosition)
                {
                    swap(mDataList, i, i + 1)
                }
            }
            else
            {
                for (i in fromPosition downTo newToPosition + 1)
                {
                    swap(mDataList, i, i - 1)
                }
            }
            notifyItemMoved(fromPosition, newToPosition)
        return true
    }

I have a simple viewholder which is an invisible bar which i mark as the position you need to drag above in order to make a valid change to the list order.
I have the code call notifyDataSetChanged after the onClearView() method is called as I need to update the background features so that the next item in the stack is draggable and the background data feeding into the adapter is also updated. It seems the simplest way to keep the data updating smoothly, but I wonder if it is causing my problems
If someone would be able to give me a hand with this, I would be most grateful. I am tearing my hair out somewhat.  I thought I had a good system setup but it was not quite working.  I hope that this is enough information to get some help with this issue.
Thank you in advance


text:
Q: Python regex re.split using a specific word as a delimiter I'm trying to do a .split on multiple delimiters so i'm trying to use re.split()
Other examples i've googled have shown using \b
text = "this and that;something.else\nand some more"
import re
items=re.split("[;|\.|\n|\b and \b]",text)
print items

this gives:
['this', '', '', '', '', 'th', 't', 'somethi', 'g', 'else', '', '', '', '', 'some', 'more']
I'm expecting it to use " and " as a separator and give:
['this', 'that', 'something', 'else', 'and some more']

A: since you want to obtain words try to use a negative character class:
items = re.split(" and |[^a-zA-Z ]+",text)

Note: writing [;|\.|\n|\b and \b] has no sense. A character class is as a bag where you put disordered single characters, you can't put a word (ordered characters), you can't put an assertion as a word boundary. Inside a character class | is seen as a literal and has not a special meaning. You character class is exactly the same than [abdn ;.|]


text:
Q: ImmutableJS deep setting an object I am trying to set the value of an immutable object using .set(). The value updates as it should, but I can't fetch from the object using .getIn() afterwards. I think this is because it's not deep setting the children of the object as immutable. Is there any method in immutable.js that will allow me to do this? I know I can wrap the object in fromJS() like .set(fromJS('rooms', roomMap)) but this seems messy. What is the correct way to do this?
  const state = Immutable.fromJS({
      rooms: false
  });

  const roomMap =
  {
      "roomid1": {
          "id": "roomid1",
          "name": "Room 101",
      },
      "roomid2": {
          "id": "roomid2",
          "name": "Room 102",
      },
  };

  var newState = state.set('rooms', roomMap);
  console.log(newState.getIn(['rooms', 'roomid1']));;

https://jsfiddle.net/z0a4p199/1/

A: You can't use set with Nested Structures created by fromJS.
You will need to use either mergeDeep or updateIn. In your case, you will have to use mergeDeep

const state = Immutable.fromJS({
  rooms: false
});
console.log(state.get('rooms'));

const roomMap = {
  "roomid1": {
    "id": "roomid1",
    "name": "Room 101",
  },
  "roomid2": {
    "id": "roomid2",
    "name": "Room 102",
  },
};

const newState = state.mergeDeep({
  rooms: roomMap
});
console.log(newState.get('rooms'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/immutable/3.8.1/immutable.min.js"></script>

A: Your room map is a plain javascript object, not an immutalblejs map.
Hence, when you do state.set('rooms', roomMap) you are setting the value of rooms to a plain javascript object.
newState.getIn(['rooms', 'roomid1']): this works only when the newState is a javascript object completely.
You have to either conver the roomMap into an immutablejs map or access the roomid1 in plain javascript way.
Alternative 1:
roomMap = Immutable.fromJS(roomMap)
state.update('rooms', (oldvalue)=>(roomMap))
newState.getIn(['rooms', 'roomid1'])

Alternative 2:
newState.get('rooms').roomid1

JS Filddle


text:
Q: Why should I use multiple origins for a cloudfront distribution? I understand, that I get a new domain for my distribution, but why would i need multiple origins for one distribution?

A: A scenario could be a single CloudFront distribution for example.com with multiple sub-applications (origins) that come together to create a single application:

*

*Static website at / (S3 configured as static website endpoint)

*Blog at /blog path (ALB)

*API at /api path (API Gateway)

*Static assets at /static path (S3 bucket)


text:
Q: How can I check if same text appears in two different files I want to check (trick or any shortcut) whether text-string exists in two files.
The content of file one is
a.txt
b.txt
c.txt
d.txt

The content of file two is
c.txt
a.txt
d.txt

How I can check if string in file one has matching string in file two?

A: With join, sort and grep
join <(sort /path/to/source) <(sort /path/to/destination) | grep '<string to check>

Tests
cat source
a.txt
b.txt
c.txt
d.txt

cat destination
c.txt
a.txt
d.txt

join <(sort source) <(sort destination) | grep 'a.txt'
a.txt

join <(sort source) <(sort destination) | grep 'b.txt'

If the requirement is to check if the content of two files is non-matching one can issue the following command
cmp --silent <(sort source) <(sort destination) || echo "files are different"

Tests
cmp --silent <(sort source) <(sort destination) || echo "files are different"
files are different

To add all lines in source file not contained in destination file in /var/tmp/unmatched file
comm -23 <(sort source) <(sort destination) > /var/tmp/unmatched

To delete from source file all lines not contained in destination file
comm -1 <(sort source) <(sort destination) >| source

Since we are in bash and if you have set noclobber as set -o noclobber, then you should use the syntax >|.

A: command
Method1:
for i in `cat p1`; do grep -i "$i" p2 >/dev/null; if [[ $? == 0 ]]; then echo "$i exsists in both files"; else echo "$i doesnt exsists in file p2"; fi; done

output
a.txt exsists in both files
b.txt doesnt exsists in file p2
c.txt exsists in both files
d.txt exsists in both files

A: Done by using below awk command
f2count=`awk 'END{print NR}' p2`
f1count=`awk 'END{print NR}' p1 `
comm_p1_p2=`awk 'NR==FNR{a[$0];next}($0 in a){print $0}' p1 p2| awk 'END{print NR}'`

if [[ $f1count -eq $f2count ]] && [[ $f1count -eq $comm_p1_p2 ]]; then echo "both files p1  and p2 content are same"; else echo "different content found on file p1  and p2"; fi


text:
Q: calling function from dialog button jquery ui DEMO
Calling a function from dialog box is getting is not a function error
Button click from dialog:
Add: {
    class: 'calendareventleft',
    text: 'Add',
    click: function() {
        var title = $("#title").val();
        var description = $("#description").val();
        var otherinfor = $("#otherinfo").val();
        $(this).ajaxcall(title, description, otherinfor);
    }
}

Button showing the dialog
$('#button').click(function() {

    $("#dialog").dialog({
        title: "qwe"
    });
    $("#dialog").html("
" + "<form>" + "Title:
" + "<input type='text' id='title' class='calendarinput'>" + "
" + "Description:
" + "<textarea id='description' class='calendarinput calendartxtarea'></textarea>" + "
" + "Additional Information:
" + "<textarea id='otherinfo' class='calendarinput calendartxtarea'></textarea>" + "</form>" + "
");
    $("#dialog")
        .dialog("open");

})

The function i need to run
function ajaxcall(title, description, otherinformation) {
    consoole.log(title);
    consoole.log(description);
    consoole.log(otherinformation);
}

A: You are calling $(this).ajaxcall(....) where it is expecting ajaxcall to be a plugin method, but it is not that is why the error.
Just call it like
ajaxcall(title, description, otherinfor);

Demo: Fiddle


text:
Q: Converting to UTC Calendar instance in Joda-Time I am using Joda-Time API for managing date and time in my web application.
I have a method which converts the milliseconds to Calendar object.
public static synchronized Calendar getUTCCalenderInstance( final Long millisecondsTime )
{
    return new DateTime(millisecondsTime).withZone(DateTimeZone.UTC).toGregorianCalendar();
}

And I am saving it in MySQL database using spring-data-jpa. But when viewed in database, it is storing the timestamp in current local timezone. How to fix this issue?
My application.properties:
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/my_db?
useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC&useSSL=false

My Java entity is:
@Entity
@Table( name = "task" )
@Data
public class TaskModel {

@Id
@GeneratedValue( strategy = GenerationType.AUTO )
@Column( name = "t_id" )
private Long id;

@Column( name = "t_name" )
private String taskName;

@Column( name = "t_description" )
private String taskDescription;

@Column( name = "t_start_date" )
private Calendar startDate;

@Column( name = "t_due_date" )
private Calendar dueDate;

@Column( name = "t_created_at" )
private Calendar createdAt;


text:
Q: Problem calculating RSI from the Binance node API I have written a program in javascript (Node) that is supposed to calculate the RSI using the Binance api.
The only thing is that my program does not calculate the "real" RSI. For example, if i set my period to be 14 days, as the formula says - I get an RSI value equal to ~28 and the real RSI being 38.
If i change the period and set it to 20, i get an RSI pretty close to the real one, with mine being 39 and the real one being 38.
I can't figure it out.what am i doing wrong. Any suggestion?
Here is my code :
const binance = require('node-binance-api')().options({
        APIKEY: 'xxx',
        APISECRET: 'xxx',
        useServerTime: true,
        test: true // True = SandboxMode
    });

    /* VARIABLES */
    let listClose = [];
    let changeUp = 0;
    let changeDown = 0;
    let last_closeHigh = 0;
    let last_closeLow = 0;
    let current_time = Date.now();
    let period = 20;

    function calculateRSI() {
        console.log("Generating RSI");
        binance.candlesticks("ETHBTC", "1d", (error, ticks, symbol) => {
            for (i = 0; i < ticks.length; i++) {
                let last_tick = ticks[i];
                let [time, open, high, low, close, volume, closeTime, assetVolume, trades, buyBaseVolume, buyAssetVolume, ignored] = last_tick;
                listClose.push(close);
                if (i == ticks.length -1 ) {
                    for (x = 0; x < ticks.length; x++) {
                        previous_close = (parseFloat(listClose[x-1]));
                        current_close = (parseFloat(listClose[x]));
                        // HIGH
                        if (current_close > previous_close) {
                            upChange = current_close - previous_close;
                            changeUp += upChange;
                            if (x == ticks.length -1) {
                                last_closeHigh = current_close - previous_close;
                            }
                        }
                        // LOW
                        if (previous_close > current_close) {
                            downChange = previous_close - current_close;
                            changeDown += downChange;
                            if (x == ticks.length - 1) {
                                last_closeLow = previous_close - current_close;
                            }
                        }
                        if (x == ticks.length-1) {
                            AVGHigh = changeUp / period;
                            AVGLow = changeDown / period;
                            Upavg = (AVGHigh * (period -1) + last_closeHigh) / (period);
                            Downavg = (AVGLow * (period -1) + last_closeLow) / (period);
                            RS = Upavg / Downavg;
                            RSI = (100 - (100 / (1 + RS)));
                            console.log(RSI);
                            return RSI;
                        }
                    }
                }
            }
        }, {
            limit: period,
            endTime: current_time
        });
    }
calculateRSI();

A: Sorry for jumping on this late...but the reason for this is using the Sandbox.
Binance Sandbox is awful and should never be used, it gives bad values.


text:
Q: Upload large files in Silverlight Is it possible to upload large files in Silverlight w/o resorting to the "chunked upload" or loading all of the file data into memmory?
I read something about uploading using Silverlight streaming API, does that work and will it truly stream the data w/o preloading all of it in mem upfront first?

A: Silverlight doesn't implement any kind of "stream upload". Before post request goes to the server all data you want to send should be writen into the stream. So if you need to send truly large file I would say  multiple posts with "transfer-encoding: chunked" (i.e chunked upload) is the way to go.

A: Chunking might help you speed up your uploads as well: Parallel upload to Azure via Silverlight Control


text:
Q: Is it possible to change ionic package name prior to ionic start? I know it's possible to change the package name by modifying the config.xml file. As seen on this question.
But is it possible to specify the package name prior to the creation of the project, like we do on cordova?
Cordova example: cordova create hello com.example.hello HelloWorld
Now, on Ionic, is it possible to do something similar?

A: Try something like this:
$ionic start -a todo -i com.carlosrojasblog.todo todo blank

change [todo] for your project name and [com.carlosrojasblog.todo] for your  own package name.


text:
Q: Update array React native I try to update the name in my data array with the value I get from my selected name in my flatlist.
So here I select the name in my flatlist, If I print the selected name in the terminal it print out the selected name, so that works fine.
const [name, setName] = useState();

<FlatList
  numColumns={1}
  horizontal={false}
  data={players}
  renderItem={({item}) => (
    <View>
      <PlayersListCard
        playersName={item.name}
        deleteIcon="add-circle-outline"
        click={() => {
          setModalVisiblePlayer(false), setName(item.name);
        }}
      />
    </View>
  )}
/>

And here I try to set the new value (name)
const updateArray = (index) => (e) => {
  let newArr = [...data];
  newArr[index] = name;
  setData(newArr);
};

And here I try to print out the name in my draggable item (renderText)
{
  data.map((item, key, index) => (
    <Draggable
      x={10}
      y={200}
      key={key}
      renderColor="blue"
      renderSize={50}
      onShortPressRelease={() => setModalVisiblePlayer(true)}
      isCircle
      textcolor="#000000"
      renderText={() => updateArray(index)}
      onDragRelease={(e) => {
        setItemPosition(key, e.nativeEvent.pageX, e.nativeEvent.pageY);
        console.log(item.X);
        console.log(item.Y);
      }}
    />
  ));
}

But their is something that I do wrong, can anyone see what?


text:
Q: Make a word insensitive case with .htaccess I've this .htaccess rule.
# Shop-homepage
RewriteRule ABCDEF/fr-CA/$ shop-homepage.php?lang=fr&country=ca&shop=ABCDEF [L,QSA]
RewriteRule ABCDEF/en-CA/$ shop-homepage.php?lang=en&country=ca&shop=ABCDEF [L,QSA]
RewriteRule ABCDEF/en-US/$ shop-homepage.php?lang=en&country=us&shop=ABCDEF [L,QSA]

How can I make ABCDEF insensitive case ?
Thanks.

A: Use NC flag . NC is use to match both uppercase and lowercase characters in URI :
RewriteRule ABCDEF/fr-CA/$ shop-homepage.php?lang=fr&country=ca&shop=ABCDEF [L,QSA,NC]
RewriteRule ABCDEF/en-CA/$ shop-homepage.php?lang=en&country=ca&shop=ABCDEF [L,QSA,NC]
RewriteRule ABCDEF/en-US/$ shop-homepage.php?lang=en&country=us&shop=ABCDEF [L,QSA,NC]


text:
Q: Replace all instances of a character in a String I'm trying to create a method that replace all instances of a certain character in a word with a new character. This is what I have so far:
public class practice {
public static void main(String[] args) {

    String test3 = updatePartialword("----", "test", 't');
    System.out.println(test3); }

public static String updatePartialword(String partial, String secret, char c) {
    String newPartial = "";
    int len = secret.length();
    for (int i=0; i<=secret.length()-1; i++){
        char x = secret.charAt(i);
        if (c==x) {
            String first = partial.substring(0,i);
            String second = partial.substring(i+1,len);
            newPartial = first+x+second;
        }

    }
        return newPartial;
}

}

I want it to return t--t, but it will only print the last t. Any help would be greatly appreciated!

A: Java already has a built in method in String for this. You can use the the replace() method to replace all occurrences of the given character in the String with the another character
    String str = "Hello";
    str.replace('l', '-'); //Returns He--o
    str.replace('H', '-'); //Returns -ello

A: I suspect you are looking for something like
public static void main(String[] args) {
    String test3 = updatePartialword("----", "test", 't');
    System.out.println(test3);
}

public static String updatePartialword(String partial, String secret, char c) {
    char[] tmp = partial.toCharArray();

    for (int i = 0; i < secret.length(); i++) {
        char x = secret.charAt(i);
        if (c == x) {
            tmp[i] = c;
        }

    }
    return new String(tmp);
}

A: In your code you overwrite the String each time you found the character. Instead of overwriting, you should expand the string each time.
public class practice {
  public static void main(String[] args) {
    String test3 = updatePartialword("----", "test", 't');
    System.out.println(test3);
}

public static String updatePartialword(String partial, String secret, char c) {
    StringBuilder sb = new Stringbuilder();
    sb.append(""); // to prevent the Stringbuilder from calculating with the chars
    for (int i = 0; i < partial.lenght; i++)
      if (secret.charAt(i) == c)
        sb.append(c);
      else
        sb.append('-');
    return sb.toString();
  }

}


text:
Q: Most efficient (cost & time) way to get a good Gavel of Judgement I'm looking for a strong gavel to play the HotA build with my season barb but I'm only finding mediocre ones. If I wanted to dedicate time specifically towards creating/finding a strong gavel, what would be the most efficient route?
Simply rifting and waiting for one to drop seems inefficient. What about cube-rerolling an existing gavel vs. upgrading 2h mighty weapons, how do they compare? Could someone create a numerical breakdown of the possible options?
This question could use a "Theorycrafting" tag, but I couldn't create it.

TL;DR: Looking for the most cost and time efficient way to roll loads of gavels in a manageable timeframe, would like numerical breakdown of options.

A: If you already have one, 4 person spit bonus bounties is the best way to go.
With a halfway decent squad, you can 20+ materials in an hour. Let's assume you get 20.
That's like finding 4 GoJ's, each one with a 10% chance to be ancient per hour.
If you don't have one, just do rifts or greater rifts (whichever you find more enjoyable) and spend all of your bloodshards on weapons.


text:
Q: Can't install Microsoft Visual C++ 2010 package (fatal error) I am trying to run the Elder Scrolls Online Launcher installer, it loads to 100% and then just quits.  I have a feeling it has to do with the Microsoft Visual C++ 2010 not being able to install.  Here is the log file for the error installing Visual c++.  What would be causing this issue? I have tried clearing permissions and various other things to no avail.
error code


text:
Q: How to avoid the default CallOutView to appear? I'm trying to make a custom Callout view for AnnotationView. I had seen this answer.
And please see the other question
I'm able to load the custom view.
But How to avoid the default CallOutView to appear??

A: In your MKAnnotationView set the canShowCallout to NO


text:
Q: "Attempted to perform an unauthorized operation" when calling NamedPipeServerStream.SetAccessControl I'm trying to use PipeSecurity to secure a NamedPipeServerStream. When I call this.pipeServer.SetAccessControl(pipeSecurity) in the snippet below I get the following exception:
Attempted to perform an unauthorized operation.
    at System.Security.AccessControl.Win32.SetSecurityInfo(ResourceType type, String name, SafeHandle handle, SecurityInfos securityInformation, SecurityIdentifier owner, SecurityIdentifier group, GenericAcl sacl, GenericAcl dacl)
    at System.Security.AccessControl.NativeObjectSecurity.Persist(String name, SafeHandle handle, AccessControlSections includeSections, Object exceptionContext)
    at System.Security.AccessControl.NativeObjectSecurity.Persist(SafeHandle handle, AccessControlSections includeSections, Object exceptionContext)
    at System.IO.Pipes.PipeSecurity.Persist(SafeHandle handle)

code:
this.pipeServer =
    new NamedPipeServerStream(
        pipeName,
        PipeDirection.InOut,
        1,
        PipeTransmissionMode.Byte,
        PipeOptions.Asynchronous);

PipeSecurity pipeSecurity = new PipeSecurity();

WindowsIdentity identity = WindowsIdentity.GetCurrent();
WindowsPrincipal principal = new WindowsPrincipal(identity);

if (principal.IsInRole(WindowsBuiltInRole.Administrator))
{
    // Allow the Administrators group full access to the pipe.
    pipeSecurity.AddAccessRule(new PipeAccessRule(
        new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null).Translate(typeof(NTAccount)),
        PipeAccessRights.FullControl, AccessControlType.Allow));
} else {
    // Allow current user read and write access to the pipe.
    pipeSecurity.AddAccessRule(new PipeAccessRule(
        WindowsIdentity.GetCurrent().User,
        PipeAccessRights.ReadWrite, AccessControlType.Allow));
}

this.pipeServer.SetAccessControl(pipeSecurity);

Any ideas of what I'm doing wrong?
This is happening in .NET Framework (targeting net451) and .NET Standard 1.6 using the System.IO.AccessControl nuget package:
https://www.nuget.org/packages/System.IO.Pipes.AccessControl/
Edit:
I was able to use an #ifdef to use the following constructor that worked for .NET Framework:

public NamedPipeServerStream (string pipeName, System.IO.Pipes.PipeDirection direction, int maxNumberOfServerInstances, System.IO.Pipes.PipeTransmissionMode transmissionMode, System.IO.Pipes.PipeOptions options, int inBufferSize, int outBufferSize, System.IO.Pipes.PipeSecurity pipeSecurity)

However, this constructor does not exist in .NET Standard. I tried using this function that was added to .NET Core:
PipesAclExtensions.SetAccessControl(PipeStream, PipeSecurity)
But that yields the same exception from before.
I created a gist to show this.

A: I just had the same issue and tried to track it down.
TL;DR
The current status (Feb-2019) is sad but true: it just does not work with the classes that are given in today's NET Standard.
Ticket references

*

*issue 30170 "unauthorized operation" on NamedPipeServerStream.SetAccessControl

*issue 31190 System.IO.Pipes.AccessControl package does not work

*issue 24040 NamedPipeServerStream: Provide support for WRITE_DAC
Also interesting in this context could be the *nix-related

*

*issue 34400 mechanism for lower privileged user to connect to a privileged user's pipe
Possible workaround
One still can use native API calls to get security set up as desired, but that's not for the faint of heart. One basically needs to implement these steps:

*

*set up a security descriptor in binary representation

*connect it to the SECURITY_ATTRIBUTES structure

*create the pipe via Windows API CreateNamedPipe()

*wrap the resulting handle into a SafeHandle

*and feed that into the right NamedPipeServerStream CTOR variant

PS: At least we now can look it up in the code where it is hitting the wall. Just imagine having that problem 20 years ago ...

A: In NET 5 you can create a NamedPipeServerStream available to all user accounts by defining it like this:
PipeSecurity pipeSecurity = new PipeSecurity();
pipeSecurity.AddAccessRule(new PipeAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), PipeAccessRights.ReadWrite, AccessControlType.Allow));
using (var pipe = NamedPipeServerStreamAcl.Create("MyAppPipeName", PipeDirection.InOut, 1, PipeTransmissionMode.Message, PipeOptions.None, 0, 0, pipeSecurity))
{
    pipe.WaitForConnection();
    // ...
}

Please note that this is for Windows operating system only.

A: Recently I encountered the same problem when translating the project to .Net Core.
I added a nuget package to help with the transition: https://www.nuget.org/packages/NamedPipeServerStream.NetFrameworkVersion/

*

*The package targets .Net Standard 2.0 and contains the original constructor from the .Net Framework (which supports PipeSecurity, HandleInheritability, and PipeAccessRights).

*I restored it from decompiled code without making any changes.

*Exceptions are fully supported, no code has been lost.

*Has a strong name.

*The source code is also available.

Install-Package NamedPipeServerStream.NetFrameworkVersion

using System.IO.Pipes;

var pipeSecurity = new PipeSecurity();
pipeSecurity.AddAccessRule(new PipeAccessRule(WindowsIdentity.GetCurrent().Owner, PipeAccessRights.ReadWrite, AccessControlType.Allow));

using var serverStream = NamedPipeServerStreamConstructors.New(pipeName, PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous | PipeOptions.WriteThrough, 0, 0, pipeSecurity);

A: I've managed to make the possible workaround JensG mentioned. I used this sample to build it:
https://code.msdn.microsoft.com/CSNamedPipeServer-4c760c2c/sourcecode?fileId=21684&pathId=1498714400
    public static class NativeNamedPipeServer
    {
        public static SafePipeHandle CreateNamedPipeServer(string pipeName, string sddl)
        {
            return NativeMethod.CreateNamedPipe(
                @"\\.\pipe\" + pipeName, // The unique pipe name.
                PipeOpenMode.PIPE_ACCESS_DUPLEX | PipeOpenMode.ASYNCHRONOUS,
                PipeMode.PIPE_TYPE_BYTE,
                1, // Max server instances
                1024 * 16, // Output buffer size
                1024 * 16, // Input buffer size
                NMPWAIT_USE_DEFAULT_WAIT, // Time-out interval
                CreateNativePipeSecurity(sddl) // Pipe security attributes
            );
        }

        /// <summary>
        /// The CreateNativePipeSecurity function creates and initializes a new
        /// SECURITY_ATTRIBUTES object to allow Authenticated Users read and
        /// write access to a pipe, and to allow the Administrators group full
        /// access to the pipe.
        /// </summary>
        /// <returns>
        /// A SECURITY_ATTRIBUTES object that allows Authenticated Users read and
        /// write access to a pipe, and allows the Administrators group full
        /// access to the pipe.
        /// </returns>
        /// <see cref="http://msdn.microsoft.com/en-us/library/aa365600(VS.85).aspx"/>
        private static SECURITY_ATTRIBUTES CreateNativePipeSecurity(string sddl)
        {
            if (!NativeMethod.ConvertStringSecurityDescriptorToSecurityDescriptor(
                sddl, 1, out var pSecurityDescriptor, IntPtr.Zero))
            {
                throw new Win32Exception();
            }

            SECURITY_ATTRIBUTES sa = new SECURITY_ATTRIBUTES();
            sa.nLength = Marshal.SizeOf(sa);
            sa.lpSecurityDescriptor = pSecurityDescriptor;
            sa.bInheritHandle = false;
            return sa;
        }

        #region Native API Signatures and Types

        /// <summary>
        /// Named Pipe Open Modes
        /// http://msdn.microsoft.com/en-us/library/aa365596.aspx
        /// </summary>
        [Flags]
        internal enum PipeOpenMode : uint
        {
            PIPE_ACCESS_INBOUND = 0x00000001, // Inbound pipe access.
            PIPE_ACCESS_OUTBOUND = 0x00000002, // Outbound pipe access.
            PIPE_ACCESS_DUPLEX = 0x00000003, // Duplex pipe access.

            // added from C# PipeOptions.cs
            WRITE_THROUGH = 0x80000000,
            ASYNCHRONOUS = 0x40000000,
            CURRENT_USER_ONLY = 0x20000000
        }

        /// <summary>
        /// Named Pipe Type, Read, and Wait Modes
        /// http://msdn.microsoft.com/en-us/library/aa365605.aspx
        /// </summary>
        [Flags]
        internal enum PipeMode : uint
        {
            // Type Mode
            PIPE_TYPE_BYTE = 0x00000000, // Byte pipe type.
            PIPE_TYPE_MESSAGE = 0x00000004, // Message pipe type.

            // Read Mode
            PIPE_READMODE_BYTE = 0x00000000, // Read mode of type Byte.
            PIPE_READMODE_MESSAGE = 0x00000002, // Read mode of type Message.

            // Wait Mode
            PIPE_WAIT = 0x00000000, // Pipe blocking mode.
            PIPE_NOWAIT = 0x00000001 // Pipe non-blocking mode.
        }

        /// <summary>
        /// Uses the default time-out specified in a call to the
        /// CreateNamedPipe method.
        /// </summary>
        internal const uint NMPWAIT_USE_DEFAULT_WAIT = 0x00000000;

        /// <summary>
        /// The SECURITY_ATTRIBUTES structure contains the security descriptor for
        /// an object and specifies whether the handle retrieved by specifying
        /// this structure is inheritable. This structure provides security
        /// settings for objects created by various functions, such as CreateFile,
        /// CreateNamedPipe, CreateProcess, RegCreateKeyEx, or RegSaveKeyEx.
        /// </summary>
        [StructLayout(LayoutKind.Sequential)]
        internal class SECURITY_ATTRIBUTES
        {
            public int nLength;
            public SafeLocalMemHandle lpSecurityDescriptor;
            public bool bInheritHandle;
        }

        /// <summary>
        /// Represents a wrapper class for a local memory pointer.
        /// </summary>
        [SuppressUnmanagedCodeSecurity,
         HostProtection(SecurityAction.LinkDemand, MayLeakOnAbort = true)]
        internal sealed class SafeLocalMemHandle : SafeHandleZeroOrMinusOneIsInvalid
        {
            public SafeLocalMemHandle() : base(true)
            {
            }

            public SafeLocalMemHandle(IntPtr preexistingHandle, bool ownsHandle)
                : base(ownsHandle)
            {
                base.SetHandle(preexistingHandle);
            }

            [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success),
             DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
            private static extern IntPtr LocalFree(IntPtr hMem);

            protected override bool ReleaseHandle()
            {
                return (LocalFree(base.handle) == IntPtr.Zero);
            }
        }

        /// <summary>
        /// The class exposes Windows APIs to be used in this code sample.
        /// </summary>
        [SuppressUnmanagedCodeSecurity]
        internal class NativeMethod
        {
            /// <summary>
            /// Creates an instance of a named pipe and returns a handle for
            /// subsequent pipe operations.
            /// </summary>
            /// <param name="pipeName">Pipe name</param>
            /// <param name="openMode">Pipe open mode</param>
            /// <param name="pipeMode">Pipe-specific modes</param>
            /// <param name="maxInstances">Maximum number of instances</param>
            /// <param name="outBufferSize">Output buffer size</param>
            /// <param name="inBufferSize">Input buffer size</param>
            /// <param name="defaultTimeout">Time-out interval</param>
            /// <param name="securityAttributes">Security attributes</param>
            /// <returns>If the function succeeds, the return value is a handle
            /// to the server end of a named pipe instance.</returns>
            [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
            public static extern SafePipeHandle CreateNamedPipe(string pipeName,
                PipeOpenMode openMode, PipeMode pipeMode, int maxInstances,
                int outBufferSize, int inBufferSize, uint defaultTimeout,
                SECURITY_ATTRIBUTES securityAttributes);

            /// <summary>
            /// The ConvertStringSecurityDescriptorToSecurityDescriptor function
            /// converts a string-format security descriptor into a valid,
            /// functional security descriptor.
            /// </summary>
            /// <param name="sddlSecurityDescriptor">
            /// A string containing the string-format security descriptor (SDDL)
            /// to convert.
            /// </param>
            /// <param name="sddlRevision">
            /// The revision level of the sddlSecurityDescriptor string.
            /// Currently this value must be 1.
            /// </param>
            /// <param name="pSecurityDescriptor">
            /// A pointer to a variable that receives a pointer to the converted
            /// security descriptor.
            /// </param>
            /// <param name="securityDescriptorSize">
            /// A pointer to a variable that receives the size, in bytes, of the
            /// converted security descriptor. This parameter can be IntPtr.Zero.
            /// </param>
            /// <returns>
            /// If the function succeeds, the return value is true.
            /// </returns>
            [return: MarshalAs(UnmanagedType.Bool)]
            [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
            public static extern bool ConvertStringSecurityDescriptorToSecurityDescriptor(
                string sddlSecurityDescriptor, int sddlRevision,
                out SafeLocalMemHandle pSecurityDescriptor,
                IntPtr securityDescriptorSize);
        }

        #endregion
    }

The create:
            var safePipeHandle = NativeNamedPipeServer.CreateNamedPipeServer(_pipeName,
                pipeSecurity.GetSecurityDescriptorSddlForm(AccessControlSections.Access));
            var stream = new NamedPipeServerStream(PipeDirection.InOut, true, false, safePipeHandle);

The trickiest part was to make asynchronous work as the original source did not have PipeOpenMode.ASYNCHRONOUS flag. Figured that out by checking .NET Core 3.0 code. Strangely enough, they have all the pipe security code in there, but just not the constructor for it. So an alternative way might be actually reflection.

A: An API has since been added to allow specifying an ACL when creating the pipe.
Pass in your PipeSecurity object to NamedPipeServerStreamAcl.Create and it should work.


text:
Q: ¿Porque no se visualiza un div usando mediaqueries en HTML? Tengo dos div uno con fondo amarillo y otro con fondo rojo, el fondo rojo se debe de ver en una resolucion mayor a 800px y el amarillo en la resolucion menor o igual a 800px, el div rojo funciona bien pero el amarillo no se visualiza al momento de verlo en un celular o acortar el ancho del navegador estoy usando mozilla firefox
<!DOCTYPE html>

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

    menu_celular

    menu_pc

A:
CSS es hojas de estilo en cascada, esto quiere decir que se iran
  aplicando una tras otra.

En las propiedades de CSS hay prioridades en cuanto a que estilo aplicar y estas dependen de la forma en que incluyas CSS en tu código, ya que puedes tener:
1) Hojas de estilo importadas en meta.
// <link rel="stylesheet" href="css/style.css">

2) Etiquetas de style dentro de meta.
//

3) Etiquetas de style dentro de las etiquetas de HTML (conocido como inline).
// <input type="text" style='display:none;'>

La prioridad que toma CSS para elegir cual aplicar es esta:
1) Primero etiquetas de style dentro de elementos HTML (conocido como inline).
2) Archivos externos o incluidos en meta (puntos 1 y 2 de la anterior escala).
3) Estilo por defecto del navegador.

Es decir, que aunque tu codigo CSS este bien, cuando se active @media va a encontrar que debe ocultar el menu2 y mostrar el menu1, pero cuando llega a menu1 consigue que tiene display:none y lo ocultara por tener mas prioridad.

¿Como se soluciona?: pues quitamos la etiqueta de styledel elemento y la colocamos como una clase así:
<!DOCTYPE html>

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

    menu_celular

    menu_pc

De esta manera, se aplica el display:none cuando estas por debajo de los 800 width y cuando cambias a @media mostramos el menu1


text:
Q: Adding a FileField to a custom SignupForm with django-allauth I have the following custom SignupForm (simplified, works perfectly without my_file):
class SignupForm(forms.Form):
    home_phone = forms.CharField(validators=[phone_regex], max_length=15)
    my_file = forms.FileField()

    def signup(self, request, user):
        new_user = ReqInfo(
            user=user,
            home_phone=self.cleaned_data['home_phone'],
            my_file=my_file,
        )
        new_user.save()

In models.py:
class ReqInfo(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, blank=True, null=True)
    home_phone = models.CharField(
        validators=[phone_regex], max_length=15)
    my_file = models.FileField(upload_to='uploads/directory/', validators=[resume_file_validator], blank=True, null=True)

My issue:
When I add a a user in myurl/accounts/signup it tells me that the my_file field is Required, even though I select a file.

A: The signup.html template allauth uses did not have
enctype="multipart/form-data"

After adding it, it works like a charm.


text:
Q: Dash not displaying properly I can only get unity to display properly at a lower (ugly-looking) resolution. Is there a way to fix this. I cannot go full screen. I can not find any bug reports that have similar problems.
I have blacklisted intel_ips because it had failed to i915 symbols.
This is common problem in linux and the solution on many websites and bug reports (which has worked up until now) is to blacklist intel_ips.
I am using a gateway laptop. 64 bit oneiric ocelot fully updated. installed from the daily build yesterday. this problem is not present when intel_ips is not blacklist and I resume normal boot from grub2 menu. but i cannot get a higher resolution than 1440x900 and the native resolution 1600x900.
I cannot post images because of the spam mechanism thing but basically there is a second dash menu that tries to show and they interlap and there is no fullscreen corner button at the bottom.
lshw -C video
  *-display
       description: VGA compatible controller
       product: Core Processor Integrated Graphics Controller
       vendor: Intel Corporation
       physical id: 2
       bus info: pci@0000:00:02.0
       version: 18
       width: 64 bits
       clock: 33MHz
       capabilities: msi pm vga_controller bus_master cap_list rom
       configuration: driver=i915 latency=0
       resources: irq:41 memory:f0000000-f03fffff memory:d0000000-dfffffff ioport:1800(size=8)

A: Try installing the latest drivers for your video card:
1) Add the repo:
sudo apt-add-repository ppa:glasen/intel-driver

2) update sources and packages
sudo apt-get update
sudo apt-get upgrade

3) install the xserver-xorg-video-intel drivers
sudo apt-get install xserver-xorg-video-intel


text:
Q: Raw BGR image after JPG compression is the same length? Ok. This is a bit odd. Long story short. I am fething raw BGR images from a camera, compressing them to JPG with OpenCV and sending with UDP protocol to a PC. This is how I compress images:
// memblock contains raw image
IplImage* fIplImageHeader;
fIplImageHeader = cvCreateImageHeader(cvSize(160, 120), 8, 3);
fIplImageHeader->imageData = (char*) memblock;

// compress to JPG
vector<int> p;
p.push_back(CV_IMWRITE_JPEG_QUALITY);
p.push_back(75);
vector<unsigned char> buf;
cv::imencode(".jpg", fIplImageHeader, buf, p);

This is how I send them with UDP:
n_sent = sendto(sk,&*buf.begin(),(int)size,0,(struct sockaddr*) &server,sizeof(server));

This is how I receive them in a PC:
int iRcvdBytes=recvfrom(iSockFd,buff,bufferSize,0,
(struct sockaddr*)&cliAddr,(socklen_t*)&cliAddrLen);
// print how many bytes we have received
cout<<"Received "<<iRcvdBytes<<" bytes from the client"<<endl;

I am getting this output:
    Received 57600 bytes from the client
    Received 57600 bytes from the client
    ...

If I remove the JPG compression at the program fetching images from camera, the output is the same:
    Received 57600 bytes from the client
    Received 57600 bytes from the client
    ...

However, when I save the received image on a disk, it's size is around 7.8KB while uncompressed raw image saved to disk takes about 57KB space.
What's going on here?

A: The "size" you pass to send is the size of the compressed buffer, right?  It's not obvious from your code snippets where "size" comes from (as ypnos suggests, I would have expected buf.size() ).

A: You don't use buf.size() when sending the packet. So you send more data than is actually contained in buf. In some cases you will get a segfault for that.


text:
Q: When do we consider states under a $U(1)$ transformations to be physically different? Consider the Goldstone model of a complex scalar field $\Phi$. It has $U(1)$ global symmetry, so if
we apply the transformation $\Phi \to e^{i\alpha} \Phi$ the Lagrangian is left invariant.
Furthermore, we have an infinite set of possible vacua all with the same non-zero vacuum expectation value.
But the vacuum changes under a $U(1)$ transformation, so $U(1)$ symmetry is spontaneously broken.

*

*In this case we assume that for each value $\alpha$,
$e^{i\alpha} |0 \rangle$ corresponds to a different state,
right?

*But since we can't measure a phase, wouldn't it be more natural to
consider them the same states? On the other hand, if I think of the
real and imaginary parts as two independent fields, I would say that
they shouldn't be the same states.

Let's now couple $\Phi$ to a gauge field, such that the Lagrangian is invariant under local $U(1)$ transformations.
Then we do consider  $e^{i\alpha} | \Psi \rangle$ to be all the same states, right?  But then, doesn't this mean that the Higgs vacuum is unique?

A: You are wrong from this assumption:

We assume that for each value $\alpha$,
     $e^{i\alpha}\Phi | 0 \rangle$ corresponds to a different state.

The wave function of the symmetry broken vacuum (the Higgs vacuum) is not $e^{i\alpha}\Phi | 0 \rangle$ as you assumed, but a coherent state $|v\rangle$ (a boson condensate), obtained by applying the shift operator $D(v)$ to the symmetric vacuum state $|0\rangle$:
$$|v\rangle=D(v)|0\rangle=e^{v\Phi^\dagger-v^*\Phi}|0\rangle,$$
where  $v=|v| e^{\text{i}\alpha}$ is the vacuum expectation value (VEV) of the boson operator $\Phi=\int\text{d}^dx\Phi(x)$. Note that in the Higgs vacuum state $|v\rangle$, the operators $\Phi$ and $\Phi^\dagger$ are raised to the exponent and the phase factor $e^{\text{i}\alpha}$ is not exposed as an overall factor of the wave function. One can indeed show that $\forall x:\langle v|\Phi(x)|v\rangle=v$ using the boson commutation relation $[\Phi(x),\Phi(x')^\dagger]=\delta(x-x')$ and the definition of the symmetric vacuum state $\Phi(x)|0\rangle=0$ (see this Wikipedia page for more about coherent states). The Higgs vacuum state transforms nontrivially under the U(1) symmetry action: $|v\rangle\to|ve^{\text{i}\theta}\rangle$. The new vacuum is orthogonal to the old one $\langle v|v e^{\text{i}\theta}\rangle=\delta(\theta)$ (in the thermodynamic limit). So the two states are indeed physically different under the U(1) transformation.


text:
Q: Local fonts are not importing in .scss file I have been trying to build a website using a static site generator. I want to import a font that I downloaded from the web into one of my .scss files. I have been trying to do this for hours now without any success and I am not able to understand where I am going wrong. Any help would be greatly appreciated.
So, my file structure looks like this:

*

*Assets

*

*scss

*

*style.scss

*fonts

*

*geometry-soft-pro

*

*Geometry_Soft_Pro-Bold_N-webfont.woff

*Geometry_Soft_Pro-Bold_N-webfont.woff2

*stylesheet.css
Now, the contents of the Assets/fonts/stylesheet.css are:
@font-face {
    font-family: "Geometry_Soft_Pro-Bold_N";
    src: url("Geometry_Soft_Pro-Bold_N-webfont.woff2") format("woff2"),
         url("Geometry_Soft_Pro-Bold_N-webfont.woff") format("woff");
    font-weight: normal;
    font-style: normal;
}

This file was auto generated by fontsquirrel when downloaded a web-font kit from there.
Now, in style.scss, I am importing the stylesheet.css using the following code snippet:
@import "../fonts/geometry-soft-pro/stylesheet";

I removed the .css in the path above following this recommendation since I am importing a .css file into a .scss. (Also, I have tried keeping .css and it doesn't work either)
I am trying to use the font for a title using the following code snippet:
#home-title {
  font-family: "Geometry_Soft_Pro-Bold_N", $fonts;
  margin: 0;
  font-size: 5em;
  text-align: center;

}

And the result that I am getting is not the geometry_soft_pro font that I was expecting.
To test against the scenario that my font is being overridden somewhere else in my stylesheets, I have verified using inspect element on my browser. The font-family is not overridden anywhere. This seems like such a trivial issue and I have spent hours trying to fix it. I have run out of ideas on how to go ahead. Any kind of help would really greatly appreciated. Thank you very much!

A: I found the answer to my own question. In retrospect, I realised that I had this problem since I had not read Hugo's documentation (and my theme's documentation) properly in the first place.
The public directory (the directory finally responsible building the static site) that Hugo builds does not retain the root's file structure. The files are rearranged and their location changes. The location depends on how Hugo's static site generator generates the public directory from the project's source code. So, it's important to follow Hugo's recommendations as to where certain files are to be kept such that they can be referenced in the public (generated directory) directory. Hugo suggests that files like those of font and images should be kept in a folder named "static" in project's root. I was making the mistake of putting my font files in folder called "assets".


text:
Q: Use Inno Setup UI as a self-extractor only - No installation I use Inno Setup for many "standard" installers, but for this task I need to extract a bunch of temp files, run one of them, then remove them and exit the installer (without actually installing anything).
Basically I'm looking to make a self-extractor with without it being an "installer", and am after the best user experience possible with inno setup.
I have the following code which almost works fine:
[Files]
Source: "dist\*"; Flags: recursesubdirs ignoreversion dontcopy;

[Code]
function InitializeSetup(): Boolean;
var
  ResultCode: Integer;
begin
  Result := True;
  MsgBox('Please wait a minute or two...', mbInformation, MB_OK);
  ExtractTemporaryFiles('{tmp}\*');
  Exec(ExpandConstant('{tmp}\MyScript.exe'), '', '', SW_HIDE, ewWaitUntilTerminated, ResultCode);
  Abort();
end;

The problem is that the best I can do here is show a message box "Please wait a minute or two...", the user clicks [Ok], then waits as nothing appears to happen with nothing on-screen at all, then MyScript.exe starts.
What I'd like instead is a Wizard page saying "Please wait as temporary files are extracted..." with a npbstMarquee style progress bar, then is disappears once the files are extracted and my script starts.
I don't think there's a way to tell Inno Setup to display a progress bar while ExtractTemporaryFiles() is going (which would be ideal) and working this into a custom wizard page has got me baffled.

A: *

*"Install" the files to {tmp}, instead of using ExtractTemporaryFiles;

*Execute the files extracted to {tmp} from Run section (or use AfterInstall parameter or CurStepChanged to trigger Pascal Script code after files are installed);

*Set Uninstallable to no;

*Set CreateAppDir to no;

*Use [Messages] section to edit the wizard texts that are too installer-centric for your needs.

[Setup]
Uninstallable=no
CreateAppDir=no

[Files]
Source: "dist\*"; DestDir: {tmp}; Flags: recursesubdirs

[Run]
FileName: "{tmp}\MyScript.exe"

Notes:

*

*The {tmp} folder gets automatically deleted, when the "installer" is closing;

*No need for ignoreversion flag, when installing to new empty folder.

A related question: Inno Setup installer that only runs a set of embedded installers

For an answer your literal question, see Inno setup: ExtractTemporaryFile causes wizard freeze. Or a more generic question on the topic: Inno Setup: How to modify long running script so it will not freeze GUI?

A: It seems that ExtractTemporaryFiles() essentially locks up the UI until it's finished, so there's no way to get a progress bar (or Marquee) animated in here.
Also getting a message on the screen at all while ExtractTemporaryFiles() is in progress was difficult. I solved it like this:
const
  WM_SYSCOMMAND = 274;
  SC_MINIMIZE = $F020;
//-------------------------------------------------------------------
procedure MinimizeButtonClick();
begin
  PostMessage(WizardForm.Handle, WM_SYSCOMMAND, SC_MINIMIZE, 0);
end;
//-------------------------------------------------------------------
procedure CurPageChanged(CurPageID: Integer);
var
  ResultCode: Integer;
begin
  if CurPageID = wpPreparing then
  begin
    MinimizeButtonClick();
    Exec(ExpandConstant('{tmp}\MyScript.exe'), '', '', SW_HIDE, ewWaitUntilTerminated, ResultCode);
  end;
end;
//-------------------------------------------------------------------
function NextButtonClick(CurPageID: Integer): Boolean;
var
  ProgressPage: TOutputProgressWizardPage;
begin
  if CurPageID = wpReady then
  begin
    ProgressPage := CreateOutputProgressPage('Preparing files...', '');
    ProgressPage.Show;
    try
      ProgressPage.Msg1Label.Caption := 'This process can take several minutes; please wait ...';
      ExtractTemporaryFiles('{tmp}\*');
    finally
      ProgressPage.Hide;
    end;
  end;
  Result := True;
end;
//-------------------------------------------------------------------
procedure CurStepChanged(CurStep: TSetupStep);
begin
  if CurStep = ssInstall then
  begin
    //MinimizeButtonClick() is called here as the Wizard flashes up for a second
    // and minimizing it makes that 1/2 a second instead...
    MinimizeButtonClick();
    Abort();
  end;
end;

I then changed the text on the "Ready" page to suit using the [Messages] section.
The result is:

*

*one wizard page asking the user if they want to continue

*one wizard page telling the user "please wait..." while the temp files are extracted

*once the files are extracted the wizard is hidden and MyScript.exe from the temp folder is run

*once MyScript.exe finishes the wizard exits cleanly and deletes the temp files


text:
Q: odd determinants How many 4 × 4 matrices with entries from {0, 1} have odd determinant?
is there a short way of finding the answer to this question or do we have to solve it by hit and trial or using lengthy methods.
if there is a short formula based answer to this,then please help me with this
thank you

A: This is the same as asking how many $4\times 4$ matrices with coefficients in $\mathbb{Z}/2\mathbb{Z}$ have nonzero determinant.
This is a standard argument: pick a nonzero vector for the first row, pick a vector not in the span of the first vector for the second row, etc.  This gives us $(2^4-2^0) (2^4-2^1) (2^4-2^2) (2^4-2^3)$ possibilities.


text:
Q: property 'baseurl' is declared but never used ionic recently I have updated my ionic project, but now I see a warning like this: Property 'BaseURL' is declared but never used.
and my app not working
this is the declaration in the ts file  @Inject('BaseURL') private BaseURL)
and i use it in the html to import some photos from a server
<img src="{{BaseURL+dish.image}}" />


text:
Q: access denied error while creating database in mysql through php I wish to create a database in mysql via php but I get access denied error. This is the code:
<form action = "createdb.php" method = "post">
database name to be created

<input type = "text" name = "dbname" />

<input type = "submit" name = "submit" value = "submit"/>
</form>

<?php
if(isset($_POST['submit'])){
$server = 'localhost';
$uname = 'root';
$pass = 'jooko';
$dbname = $_POST['dbname'];
$createdb = "CREATE DATABASE `$dbname`";
$connect = mysql_connect(`$server`,`$uname`,`$pass`);
//$queryuse = "USE '$dbname'";

$result = mysql_query($createdb, $connect);
if(!$result){echo mysql_error();}
?>

Any help will be appreciated. Thank you.

A: Deprecation notice: Don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO, or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
Also the backticks in your function arguments will cause problems. This is how todo it with PDO.
<form action = "createdb.php" method = "post">
    database name to be created

    <input type = "text" name = "dbname" />

    <input type = "submit" name = "submit" value = "submit"/>
</form>

<?php
if($_SERVER['REQUEST_METHOD'] == 'POST'){
    $server = 'localhost';
    $uname = 'root';
    $pass = 'jooko';
    $dbname = $_POST['dbname'];

    try {
        $pdo = new PDO("mysql:host=".$server.";", $uname, $pass);
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        $dbname = "`".str_replace("`", "``", $dbname)."`";
        $pdo->query("CREATE DATABASE IF NOT EXISTS ".$dbname);

        echo 'Database created.';
    }catch (Exception $e){
        echo $e->getMessage();
    }
}
?>

If you are still having access denied problems then check the root password is correct.

A: I did it. The problem was the back quotes in the $connect variable for the login data. Had to remove the back quotes for the $uname and $pass ...have no clue why it had to be that way but it works. Thanks though.


text:
Q: Why do electrons in a current spread apart, from their point of view? There are many videos explaining how special relativity causes magnetism, with the most relevant part being that from the reference frame of the electrons, the positively charged ions in the wire have gotten closer together, and the negatively charged electrons have spread apart, a non-zero electric charge in a wire. We can determine that this must happen using the fact that in a lab reference frame, the wire is electrically neutral, and applying a Lorentz transformation to the electrons and ions. However, the electrons must see a different mechanism causing the space between them to increase. They need to see something pushing them apart. They don't know that the wire needs be electrically neutral in another reference frame. What's this mechanism that they see? Does it have anything to do with the period of time when they're accelerating?
I saw a bunch of questions that seemed similar to this one, but I didn't find any of the answers to be satisfactory. They all seemed to just explain how we know that the wire must be charged in different reference frames, using the Lorentz tranformation.

A: In the accelerating frame of an electron accelerating in an uniform electric field there is:

*

*a Coulomb-force

*an inertial force (not real force)

Those two cancel out, so that the electron does not accelerate in the accelerating frame.
But some other electron accelerates in said frame. The force that causes the acceleration must be the sum of the Coulomb-force on that electron and the inertial force on that electron.
Now if we assume that the Coulomb-force on all electrons is the same (according to electrons), then we know that according to some electron electrons ahead of it have less inertia and electrons behind of it have more inertia.
The location dependent inertia is related to location dependent speed of light, which can be demonstrated in an accelerating rocket by measuring the two way speed of light of middle-rear-middle path and middle-front-middle path, the latter path will be faster).

A: The Lorentz transformation does not model some mechanism actually increasing or decreasing distances - it is just the expression of a symmetry in the laws of physics, where there is no absolute time and no abolute space, and so in our case here no absolute measure of distances.
Meaning there is no "one true" distance between the electrons, that the electrons in their own frame would have to consider and use as a reference in order to decide whether they have been pushed apart (which is exactly what you hint by saying that the electrons do not need to know that there is a frame of reference where the wire is neutral).
The electrons see whatever spatial distances they see in their own frame, and the lab observer sees its own corresponding distances. The Lorentz transformation just connects the two points of view.

A: I don't think there's any local explanation of this. In principle you can add/remove charge carriers from the whole circuit, leaving it with a net electric charge, and the remaining carriers will still be evenly spaced in the steady state, so it isn't any particular density in any frame that they prefer, but just a lack of inhomogeneity. The way in which inhomogeneities disappear is complicated, with transient voltage spikes bouncing around the circuit until they thermalize.
If you imagine a current being spun up in a circular wire by a highly symmetric emf, so that there are never any inhomogeneities, then the local explanation in any small part of the wire would be that the electrons in front are accelerated slightly sooner than the electrons in back (relativity of simultaneity).


text:
Q: Laravel Yajra Datatables raw SQL Using Yajra Datables, Laravel is returning "Memory exhausted..." error message.
Actually how do we applying the filtering & sorting directly to the SQL instead of letting the server-side handle the filtering & sorting.
Laravel controller
// Table1 has 200,000 rows, the query itself is also slow
$rs = DB::select("select *
from Table1");
$numrow = count($rs);

if ($numrow > 0) {
    foreach ($rs as $row) {
        $column1 = $row_customers->column1;

        $arr['col1'] = $column1;

        $arrs[] = $arr;
    }
}

$response = Datatables::of($arrs)->make(true)->getData(true);

return response()->json($response);

Laravel view
$('#Table1').DataTable({
    processing: true,
    serverSide: true,
    responsive: true,
    cache: false,
    ajax: {
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        },
        "url": "/GetTable1",
        "type": "POST",
        error: function(jqXHR, ajaxOptions, thrownError) {
            console.log('error.jqXHR', jqXHR);
            console.log('error.ajaxOptions', ajaxOptions);
            console.log('error.thrownError', thrownError);
        }
    }
    /* ... */
});

A: Instead of using Datatables::of(), try Datatables::eloquent() instead, this can make your query faster especially during sorting and filtering as it actually include it in the SQL statement during query instead of filtering it after getting all results.
You can refer more on https://yajrabox.com/docs/laravel-datatables/master/engine-eloquent#facade