text:
Q: Django-registration - some activation How can I force resending activation e-mail to user? E.g. when he accidentaly deletes the mail, he clicks in link in my website, and django will send him new activation e-mail.

A: There's an admin action for doing that. From the django-registration docs:

How do I re-send an activation email?
Assuming you're using the default backend, a custom admin action is provided for this; in the admin for the RegistrationProfile model, simply click the checkbox for the user(s) you'd like to re-send the email for, then select the "Re-send activation emails" action.

There's no built-in automatic way of doing this (how should django-registration figure out that a random visitor is that guy who filled out the registration form 3 days ago and deleted his activation mail?).

A: The following view function will render a form with single email field, then check if there are any users with this email not activated yet, recreate activation code if expired (hashing stuff was copypasted from RegistrationProfile) and finally send activation email.
class ResendActivationEmailForm(forms.Form):
    email = EmailField(required=True)

def resend_activation_email(request):
    context = Context()

    form = None
    if request.method == 'POST':
        form = ResendActivationEmailForm(request.POST)
        if form.is_valid():
            email = form.cleaned_data["email"]
            users = User.objects.filter(email=email, is_active=0)

            if not users.count():
                form._errors["email"] = (_("Account for email address is not registered or already activated."),)

            for user in users:
                for profile in RegistrationProfile.objects.filter(user=user):
                    if profile.activation_key_expired():
                        salt = sha_constructor(str(random())).hexdigest()[:5]
                        profile.activation_key = sha_constructor(salt+user.username).hexdigest()
                        user.date_joined = datetime.now()
                        user.save()
                        profile.save()

                    if Site._meta.installed:
                        site = Site.objects.get_current()
                    else:
                        site = RequestSite(request)

                    profile.send_activation_email(site)

                    context.update({"form" : form})
                    return render_to_response("registration/resend_activation_email_done.html", context)

    if not form:
        form = ResendActivationEmailForm()

    context.update({"form" : form})
    return render_to_response("registration/resend_activation_email_form.html", context)

A: My (ugly) solution was to create my own login view:
from django.contrib.auth.views import login as django_login

def login(request, template_name='registration/login.html',
          redirect_field_name=REDIRECT_FIELD_NAME,
          redirect_authenticated=None,
          authentication_form=AuthenticationForm):
    """
        Redirect to redirect_authenticated if user is authenticated or
        delegate to contrib login otherwise.
    """

    form = authentication_form(data=request.POST)

    if request.method == "POST":
        if not form.is_valid():

            non_field_errors = form.non_field_errors()

            if non_field_errors:
                # test if the account is not active
                user_inactive = non_field_errors[0].find(_("This account is inactive.")) != -1

                if user_inactive:
                    return render_to_response(template_name, {
                        'form': form,
                        'user_inactive' : user_inactive,
                    }, context_instance=RequestContext(request))

    return django_login(request, template_name=template_name,
              redirect_field_name=redirect_field_name,
              authentication_form=authentication_form)

And then use the context variable in template:
{% if user_inactive %}
  Resend activation link
{% else %}
  Forgot your password?
{% endif %}

When the user clicks on the resend activation link, a form asking for the registered email appears. Submiting the form triggers a new account activation email.
Hope this helps.

A: I updated the ilya b. method resend_activation_email. The old method show error of sha deprecation in python >= 2.5
def resend_activation_email(request):

    if not request.user.is_anonymous():
        return HttpResponseRedirect('/')

    context = Context()

    form = None
    if request.method == 'POST':
        form = ResendActivationEmailForm(request.POST)
        if form.is_valid():
            email = form.cleaned_data["email"]
            users = User.objects.filter(email=email, is_active=0)

            if not users.count():
                form._errors["email"] = ("Account for email address is not registered or already activated.")

            for user in users:
                for profile in RegistrationProfile.objects.filter(user=user):
                    if profile.activation_key_expired():
                        salt = hashlib.sha1(str(random.random())).hexdigest()[:5]
                        profile.activation_key = hashlib.sha1(salt+user.email).hexdigest()
                        user.date_joined = datetime.datetime.now()
                        user.save()
                        profile.save()

                    if Site._meta.installed:
                        site = Site.objects.get_current()
                    else:
                        site = RequestSite(request)

                    profile.send_activation_email(site)

                    context.update({"form" : form})
                    return render(request, 'registration/resend_activation_email_done.html', context)

    if not form:
        form = ResendActivationEmailForm()

    context.update({"form" : form})
    return render(request, 'registration/resend_activation_email_form.html', context)


text:
Q: Yosys synthesys - is this opimum? I'm using yosys to synthesize simple circuits and show how the result varies with the cell library.
However, it looks like the result is not well optimized.
I'm using the library vsclib013.lib downloaded from: http://www.vlsitechnology.org/synopsys/vsclib013.lib
E.g. I synthesize an adder composed by 4 full adders. Since I do not use Carry_in and Carry_out I do expect that an half adder is synthesized (XOR with two inputs) for the LSB adder.
The result of the synthesis is the following.
Number of cells                 12
 cgi2v0x05                       4
 iv1v0x05                        4
 xor3v1x05                       4

It uses 4 cells that are XOR with three inputs.
This is also clear from the graph of the circuit: graph obtained using the yosys command 'show'
The circuit is simply composed by four identical full adders and there is no optimization for the Carry_in being equal to '0' and for the Carry_out not being connected.
The script I used to syntesize is:
ghdl TOP_ENTITY
hierarchy -check -top TOP_ENTITY
proc; opt; memory; opt; fsm; opt
techmap; opt
read_liberty -lib vsclib013.lib
dfflibmap -liberty vsclib013.lib
abc -liberty vsclib013.lib -D 1000 -constr constraint_file_vsclib013.txt
splitnets -ports; opt
clean
write_verilog TOP_ENTITY.v
flatten
show -stretch -format pdf -lib TOP_ENTITY.v

Thank you for any suggestion to improve the synthesys.

A: Thx for your answer.
After some tries and errors I obtained good resutls by simply using flatten.
I also added -full to the opt commands for (hopefully) good meaure.
Now, my working script is like this:
ghdl TOP_ENTITY
hierarchy -check -top TOP_ENTITY
flatten
proc; opt -full; memory; opt -full; fsm; opt -full
techmap; opt -full
read_liberty -lib vsclib013.lib
dfflibmap -liberty vsclib013.lib
abc -liberty vsclib013.lib -D 1000 -constr constraint_file_vsclib013.txt
splitnets -ports; opt -full
clean -purge
write_verilog TOP_ENTITY.v
flatten
show -stretch -format pdf -lib TOP_ENTITY.v

I also added -purge option to the clean command to get a nicer printed schematic.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Using python __init__.py to import common modules of multiple sripts I have a python package i'm working on with the below structure:
package/
  __init__.py
  script1.py
  script2.py
  script3.py

all 3 scripts have common imports for example:
import sys
import socket
import subprocess

i think it would be more efficient and also 'prettier' if those common imports could be done in the __init__.py module rather being imported time after time in each script. I've tried to move those imports to the init module , but then they're no longer recognized in their respective python scripts.
What would be the best approach to unify common imports for a python package?


text:
Q: how to use zxing library in windows phone 7 I want to scan products barcode using zxing libray in my Windows phone application .

I'm worndering how to integrate it into the project and how to use it .
thank's in advance .

A: There is a silverlight port of zxing here that works on WP7: zxing

A: Just a little addition for everybody that also searches about this topic: Stéphanie Hertrich built a small sample application that uses the zxing library together with the new Mango Camera API. This way you can search the live camera stream for barcodes and stop immediatelly if something was found. This is much more convenient for the user (just tried it for myself).
Her code is not fully tested, but it works well for a demo and finds those barcodes unbelievably fast (its really impressive, it mostly found it just after the autofocus finished).


text:
Q: How do I set header in spring boot cors? I want to enable CORS in spring boot 2. I've done this as follows:
@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowedMethods("*")
                .allowedHeaders("*");
    }
}

This work fine in most requests, but in some special request I need to set Access-Control-Allow-Origin header in response. How can I do it?

A: There are many Ways to do this like using Filter or Interceptor or Aspects. You can also use WebFilter if you are using Spring 5.
One of the ways to do so is through Interceptors. Here is a rough code.
public class AccessControlInterceptor implements HandlerInterceptor {

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        if(somecondition) {
            response.setHeader("Access-Control-Allow-Origin", "your_value");
        }
    }
}

And register this Interceptor with spring like this
@Configuration
public class MyConfig extends WebMvcConfigurerAdapter{
    @Override
    public void addInterceptors(InterceptorRegistry registry){
        registry.addInterceptor(new AccessControlInterceptor ()).addPathPatterns("/**");
    }
}

A: From Spring documentation https://spring.io/guides/gs/rest-service-cors/
Enabling CORS
Controller method CORS configuration
So that the RESTful web service will include CORS access control headers in its response, you just have to add a @CrossOrigin annotation to the handler method:
@RestController
public class GreetingController {

    @CrossOrigin(origins = "http://localhost:9000")
    @GetMapping("/greeting")
    public Greeting greeting(@RequestParam(required=false, defaultValue="World") String name) {
        System.out.println("==== in greeting ====");
        return new Greeting(counter.incrementAndGet(),String.format(template, name));
}

This @CrossOrigin annotation enables cross-origin requests only for this specific method. By default, its allows all origins, all headers, the HTTP methods specified in the @RequestMapping annotation and a maxAge of 30 minutes is used. You can customize this behavior by specifying the value of one of the annotation attributes: origins, methods, allowedHeaders, exposedHeaders, allowCredentials or maxAge. In this example, we only allow http://localhost:9000 to send cross-origin requests.
it is also possible to add this annotation at controller class level as well, in order to enable CORS on all handler methods of this class.

A: Currently you are setting Access-Control-Allow-Origin to * which is a wildcard and matches all origins.
If your request contains credential related data, e.g. by setting XMLHttpRequest.withCredentials to true:

*

*Access-Control-Allow-Origin mustn't have the value *

*An additional response header Access-Control-Allow-Credentials with the value true is expected.


text:
Q: Does setJavaScriptEnabled(false) fix Cross App Scripting Vulnerability As https://support.google.com/faqs/answer/9084685 mentioned, "WebViews that enable JavaScript and load data read from untrusted Intents can be tricked by malicious apps into executing JavaScript code in an unsafe context. "
Does this mean that setJavaScriptEnabled(false) can fix the Cross App Scripting Vulnerability problem?

A: The problem does not get solved by disabling javascript. Eg what happens if you insert html?  might deface your app or site.
The best thing to do is validate ALL data as malicious until validated otherwise...
I am not a mobile dev really but I am sure you can add some way of authenticating the sources you deal with... Javascript Web Tokens are one way to handle this type of authentication. Perhaps someone with more android dev experience can correct me?

A: well, cross scripting won't work when you disable scripting (js) at all... look at points in Option 2 under link: all are related to JS and somehow limiting its usage. when you disable JS at all then there is nothing to limiting - scripting just doesn't work (also malicious)
note that there is a pleny of methods for breaking your app, with WebView there is potentially twice much...


text:
Q: MediaPlayer start delay when click on button I want to play mp3 file from res/raw folder when user click on button
my code is below:
btn.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View arg0) {
        MediaPlayer mp = MediaPlayer.create(MainActivity.this,
        R.raw.click);
        mp.start();
    }
});

Work well but take some time to play after button click. please, anyone, give me a solution.
Thanks

A: Loading time depends on the buffer size of the MediaPlayer (which is hardcoded in the firmware) and that there is nothing that can be done to change it. Read more here.

A: This is as a result of the buffer size of media player.
Try using SoundPool for a more responsive playback. You can see an implementation of it here.
SoundPool soundPool = new SoundPool(1, AudioManager.STREAM_MUSIC, 100);
HashMap<Integer, Integer> soundPoolMap soundPoolMap = new HashMap<Integer, Integer>();
soundPoolMap.put(soundID, soundPool.load(this, R.raw.click, 1));

Start the sound with soundPool.play(soundId, 1, 1, 1, 0, 0);

A: Option 1:
Instead of creating the media player and then calling start() method in the onClick of the button, you can initialize the mediaPlayer in onCreate() of activity.
As for the button click implementation, you need to call mediaPlayer.start() only.
Option 2:
You can use SoundPool API provided by Android. This has lower latency compared to MediaPlayer API. SoundPool are recommended mainly for playing short clips.


text:
Q: Notifications don't appear I'm trying to develop an app that shows notifications when a new item is added.The user can select if he wants the notifications and the notification sound to show using two switch buttons. The app compiled without an error, there wasn't even an error on the stack trace but when I run the app on my phone and turn on the switches, the notification doesn't appear. What is wrong?
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.NotificationManagerCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.Switch;

import java.util.Set;

import androidx.annotation.RequiresApi;

import static android.app.PendingIntent.getActivity;
import static android.content.Context.NOTIFICATION_SERVICE;
import static com.example.myevents.R.drawable.notification;

public class Settings extends AppCompatActivity {
    Switch simpleswitch1;
    Switch simpleswitch2;
    private Notification notification;
    NotificationManager manager;
    Notification myNotication;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_settings);

        simpleswitch1 = (Switch) findViewById(R.id.simpleswitch1);
        simpleswitch2 = (Switch) findViewById(R.id.simpleswitch2);
        simpleswitch1.setChecked(false);
        simpleswitch2.setChecked(false);
        simpleswitch1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @TargetApi(Build.VERSION_CODES.O)
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked){{
                    int notifyID = 1;
                    String CHANNEL_ID = "my_channel_01";// The id of the channel.
                    CharSequence name = "channel 1";// The user-visible name of the channel.
                    int importance = NotificationManager.IMPORTANCE_HIGH;
                    NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID, name, importance);

                    Intent intent = new Intent(Settings.this, Visitor.class);
                    intent.putExtra("yourpackage.notifyId", notifyID);
                    PendingIntent pIntent = PendingIntent.getActivity(Settings.this, 0, intent,
                            PendingIntent.FLAG_UPDATE_CURRENT);

// Create a notification and set the notification channel.
                    Notification notification =
                            new NotificationCompat.Builder(Settings.this)
                                    .setSmallIcon(R.drawable.notification)
                                    .setContentTitle("My Events")
                                    .setContentText("Νέα εκδήλωση κοντά σας!")
                                    .setChannelId(CHANNEL_ID).build();

                    NotificationManager mNotificationManager =
                            (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
                    mNotificationManager.createNotificationChannel(mChannel);

// Issue the notification.
                    mNotificationManager.notify(notifyID , notification);

                }

A: I think that you have the issue because the notifications are work with a channel.
Check this post, it works for me
Notification not showing in Oreo


text:
Q: Prove $(x^2-2)\sin(x)+2x\cos(x)\geq 0$ for $x$ on $[0,\pi/2)$ Originally comes from the question
How to prove $\dfrac{\sin(A)}{A} +\dfrac{\sin(B)}{B}+\dfrac{\sin(C)}{C}< \dfrac{9*3^{0.5}}{2\pi}$.
The goal is proving $\frac{\sin(x)}{x}$ concave down on $[0,\pi/2)$, which I find it non-trivial.

A: Divide both sides of the inequality by $\cos x$ and use the inequality $\tan x>x$.

A: $(x^2 - 2)x + 2x \geq 0 \Rightarrow (x^2 - 2)\tan x + 2x \geq 0 \Rightarrow \ \cdots$

A: Here is a logical approach.
Take $f(x) = (x^2 - 2)\sin(x)$ and $g(x) = -2x\cos(x)$
If $x^2\sin(x) - 2\sin(x) + 2\cos(x) \ge 0$ is true then,
$x^2\sin(x) - 2\sin(x) \ge -2\cos(x)$ must also suffice (be true). Which means
$f(x) \ge g(x)$
Now:
$f(0) = 0$ and $g(0) = 0$ therefore $f(0) = g(0)$ Now, take the respective first derivatives.
$f'(x) = x^2\cos(x) + 2x\sin(x) - 2\cos(x)$
$g'(x) = 2x\sin(x) - 2\cos(x)$
$f'(x) \ge g'(x)$ is the assumption we will use.
$x^2\cos(x) + 2x\sin(x) - 2\cos(x) \ge 2x\sin(x) - 2\cos(x)$
Add $-2\cos(x)$ and subtract $2x\sin(x)$ to/from both sides. You are left with
$x^2\cos(x) \ge 0$ on the interval $[0, \pi/2]$
Which is a true inequality, therefore $f'(x) > g'(x)$ on $(0, \pi/2)$ is true.
Since $f(0) = g(0)$, and we know that $f'(x) > g'(x)$ on $(0, \pi/2)$ this means $f(x)$ grows faster than $g(x)$ which means $f(x) > g(x) \implies f(x) - g(x) > 0$
$\implies (x^2 - 2)\sin(x) + 2x\cos(x) \ge 0$ on $[0, \pi/2)$


text:
Q: Jquery slider uneven steps and formatting I'm trying to achieve this exact result:
Adjustable Slider
In other words, I need a Jquery slider with this uneven steps code...
var steps = [0, 2000, 3000, 5000, 7500, 10000, 15000, 20000, 300000];

$("#slider").slider({
range: "min",
value: 0,
min: 0,
max: steps.length,
step: 1,
slide: function(event, ui) {
    $("#amount").text(steps[ui.value]);
}
});

... Included with the code below that performs the $ and separator. How do I do this?
https://jsfiddle.net/emphase/r4tvxucx/2/
Thanks alot!

A: I expanded on your code with the fiddle you provided.  I just added the call to addCommas() to the slide callback.
I also added an array initSteps to initialize the range slider's min and max values.  The values are the indexed which correspond to the value in the steps array.

var steps = [0, 2000, 3000, 5000, 7500, 10000, 15000, 20000, 300000]; // Uneven step values
var initSteps = [1, 2]; // Index to value in steps for initializing the range slider

$("#slider").slider({
    range: true,
    min: 0,
    max: steps.length-1,
    step: 1,
    values: initSteps,
    slide:function(event, ui){
        $("#amount1").val("$" + addCommas(steps[ui.values[0]].toString()));
        $("#amount2").val("$" + addCommas(steps[ui.values[1]].toString()));
    }
});

$("#amount1").val("$" + addCommas(steps[initSteps[0]].toString()));
$("#amount2").val("$" + addCommas(steps[initSteps[1]].toString()));

function addCommas(nStr)
{
 nStr += '';
 x = nStr.split('.');
 x1 = x[0];
 x2 = x.length > 1 ? '.' + x[1] : '';
 var rgx = /(\d+)(\d{3})/;
 while (rgx.test(x1)) {
  x1 = x1.replace(rgx, '$1' + ',' + '$2');
 }
 return x1 + x2;
}
body {padding: 50px;}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css" />

        Min Price:
        <input type="text" id="amount1" name="minPrice" style="border: 0; color: #3D80E9; background:#F2F2F2; font-weight: bold;" />

        Max Price:
        <input type="text" id="amount2" name="maxPrice" style="border: 0; color: #3D80E9; background:#F2F2F2; font-weight: bold;" />


text:
Q: how do i calculate correlation between corresponding columns of two matrices and not getting other correlations as output I have these data
> a
     a    b    c
1    1   -1    4
2    2   -2    6
3    3   -3    9
4    4   -4   12
5    5   -5    6

> b
     d    e    f
1    6   -5    7
2    7   -4    4
3    8   -3    3
4    9   -2    3
5   10   -1    9

> cor(a,b)
           d            e             f
a  1.0000000    1.0000000     0.1767767
b -1.0000000    -1.000000    -0.1767767
c  0.5050763    0.5050763    -0.6964286

The result I want is just:
cor(a,d) = 1
cor(b,e) = -1
cor(c,f) = -0.6964286

A: I would probably personally just use diag:
> diag(cor(a,b))
[1]  1.0000000 -1.0000000 -0.6964286

But you could also use mapply:
> mapply(cor,a,b)
         a          b          c
 1.0000000 -1.0000000 -0.6964286

A: The first answer above calculates all pairwise correlations, which is fine unless the matrices are large, and the second one doesn't work.  As far as I can tell, efficient computation must be done directly, such as this code borrowed from borrowed from the arrayMagic Bioconductor package, works efficiently for large matrices:
> colCors = function(x, y) {
+   sqr = function(x) x*x
+   if(!is.matrix(x)||!is.matrix(y)||any(dim(x)!=dim(y)))
+     stop("Please supply two matrices of equal size.")
+   x   = sweep(x, 2, colMeans(x))
+   y   = sweep(y, 2, colMeans(y))
+   cor = colSums(x*y) /  sqrt(colSums(sqr(x))*colSums(sqr(y)))
+   return(cor)
+ }

> set.seed(1)
> a=matrix(rnorm(15),nrow=5)
> b=matrix(rnorm(15),nrow=5)
> diag(cor(a,b))
[1]  0.2491625 -0.5313192  0.5594564
> mapply(cor,a,b)
 [1] NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA
> colCors(a,b)
[1]  0.2491625 -0.5313192  0.5594564

A: mapply works with data frames but not matrices. That is because in data frames each column is an element, while in matrices each entry is an element.
In the answer above mapply(cor,as.data.frame(a),as.data.frame(b)) works just fine.
set.seed(1)
a=matrix(rnorm(15),nrow=5)
b=matrix(rnorm(15),nrow=5)
diag(cor(a,b))
[1]  0.2491625 -0.5313192  0.5594564
mapply(cor,as.data.frame(a),as.data.frame(b))
    V1         V2         V3
 0.2491625 -0.5313192  0.5594564

This is much more efficient for large matrices.


text:
Q: Typescript index signature, change type of some properties I'd like to be able to use index signatures to allow any string property in an object, but override specific properties with different types, something like:
type Filter = {
    eq?: string | number;
    // other operators
}

type Filters = {
    [field: string]: Filter[];
    $or: Filters[]; // does not work
    $and: Filters[]; // does not work
}

The interface is similar to MongoDb's query client.
Answers here almost get me to what I want, one of the answers lets you subtract (but not override) a property.
TypeScript: object with any keys except one
Is there any way to do what I want here?


text:
Q: When "dev-master" should be used in composer.json? I'm starting to use Symfony2 and following many tutorials. I found that when they installed some new features using composer.json, they "always" declared dev-master. I don't know the reasons why they always use it. An example from DoctrineFixturesBundle:
{
    "require": {
        "doctrine/doctrine-fixtures-bundle": "dev-master"
    }
}

Actually, I have googled and found some people written that If we use the dev-master instead of any stable version. It would be some conflicts in the future because the version today maybe 1.5.0 and tomorrow maybe 1.6.0.
So, what we really use in practical works - dev-master or specified version and why?

A: You should use a specific ( tagged stable at best ) version wherever possible.
While composer.lock does lock the dependency to a specific commit even when using dev-master ... every composer update will update the dependency to the latest version and afterwards update the lockfile.
If your lockfile somehow gets deleted/lost and it is not backuped / under version control you can easily end up with a non-working project after running composer install or composer update!
A simple example would be symfony/symfony itself ... new commits might introduce new BC (backward compatibility) breaks in the dev-master branch any time leaving your application in a non-functional state.


text:
Q: drupal hook_theme() how to name the arguments's key in hook_theme,
eg:
     function user_theme() {
   return array(
    'user_picture' => array(
  'arguments' => array('account' => NULL),
  'template' => 'user-picture',
   ),
    'user_profile' => array(
  'arguments' => array('account' => NULL),
  'template' => 'user-profile',
  'file' => 'user.pages.inc',
    ),
 'user_list' => array('arguments' => array('users' => NULL, 'title' => NULL),),
     );
}

why the arguments array's key is  "account" ,"users" "title", how to get them. could i named them in other stuff. thank you.

A: You can use whatever you want, just like you can when you define a function like this:
<?php
function yourfunction($whatever, $you, $want) {

}
?>

The only thing that matters both for function definitions and theme arguments is the order (in D6, not anymore in D7) in which they are defined.


text:
Q: Fetch and build libpng-android from CMake I'm developing a C++ library for Android, and I have as dependency the libpng. I'm using the modified library for Android https://github.com/julienr/libpng-android.git, which has a build.sh file in order to compile for the different architectures. Or it can be compiled using ndk-build.
I'm Fetching the library from CMake using FetchContent, this effectively download the sources files, but it doesn't build properly. I'm setting the BUILD_COMMAND but it doesn't work.
FetchContent_Declare( png
        GIT_REPOSITORY      https://github.com/julienr/libpng-android.git
        GIT_TAG             master
        UPDATE_DISCONNECTED TRUE
        STEP_TARGETS        update
        BUILD_COMMAND       "${NDK_PATH}/ndk-build.cmd NDK_PROJECT_PATH=${png_SOURCE_DIR}"

FetchContent_GetProperties(png)
if (NOT png_POPULATED)
    FetchContent_Populate(png)
    add_subdirectory("${png_SOURCE_DIR}" "${png_BINARY_DIR}" EXCLUDE_FROM_ALL)
endif()

It seems that the BUILD_COMMAND do nothing.
So, How can I fetch and build the libpng-android from CMake, and then import that result as an imported library?

A: To complete the Tsyvarev comment with references, according to the doc...

The following options are explicitly prohibited (they are disabled by the
FetchContent_Populate() command):

*

*CONFIGURE_COMMAND

*BUILD_COMMAND

*INSTALL_COMMAND

*TEST_COMMAND
ref: https://cmake.org/cmake/help/latest/module/FetchContent.html#command:fetchcontent_getproperties (just the paragraph above)

A: Thanks to @Tsyvarev and @Mizux I can follow the correct way to do it.
FetchContent_Declare( libpng
        GIT_REPOSITORY      https://github.com/julienr/libpng-android.git
        GIT_TAG             master
        UPDATE_DISCONNECTED TRUE
        STEP_TARGETS        update)

FetchContent_GetProperties(libpng)
if (NOT libpng_POPULATED)
    FetchContent_Populate(libpng)
    add_subdirectory("${libpng_SOURCE_DIR}" ${libpng_BINARY_DIR} EXCLUDE_FROM_ALL)
endif()

exec_program("${CMAKE_ANDROID_NDK}/ndk-build.cmd"
        ${libpng_BINARY_DIR}
        ARGS NDK_PROJECT_PATH=${libpng_SOURCE_DIR} APP_ABI=${ANDROID_ABI})

and then linking the libraries
target_link_libraries( project
        PRIVATE
            ${libpng_SOURCE_DIR}/obj/local/${ANDROID_ABI}/libpng.a
        )


text:
Q: Integrate $\int\frac{1}{2-3\cos2x}dx$? I've have no idea how to even approach this question. I've attempted to use $\frac{1}{5\tan^2(x)-1}$ but i'm really just grasping at straws here.

A: let $\displaystyle \mathcal{I} = \int \frac{1}{2-3 \cos 2x}dx = \int\frac{1}{2-3\left(\frac{1-\tan^2 x}{1+\tan^2 x}\right)}dx = \int \frac{\sec^2 x}{5\tan^2 x-1}dx$
substitute $\tan x= t$ and $\sec^2 xdx = dt$
so $\displaystyle \int\frac{1}{5t^2-1}dt = \frac{1}{5}\int \frac{1}{t^2-\frac{1}{\sqrt{5}}}dt = \frac{1}{2\sqrt{5}}\ln \bigg|\frac{\sqrt{5}t-1}{\sqrt{5}t+1}\bigg|+\mathcal{C}$


text:
Q: Enable disable textbox using jQuery I am very new to jQuery, please consider me as a novice. I have an PHP form where in I have a Radio button. Based on the which radio is selected I would like to disable the textbox. Below is the scenario:
Radio Button : Cash and Cheque
Textbox: Cheque No and Cheque Date
By default, Textbox Cheque No and Cheque Date are set to be disabled and Radio Cash is Checked.

*

*When the user clicks on Cheque Radio, textbox cheque no and cheque date must be enabled and if possible it should be made as required.

*When the user clicks back on Cash, textbox Cheque No and Cheque Date must be disabled and required property must be removed.

I have added JQuery 1.12.3 min to my header.php
Header.php
!-- JQuery 1.12.3 JS -->

MainPage.php

    Mode

        <input type='radio' name='rbPayMode' id='bd' value='0' checked>Cash
        <input type='radio' name='rbPayMode' id='bd' value='1'>Cheque

    Cheque No
    <input type="number" name="txtChequeNo" pattern="^[0-9]" min="0" step="1" class="form-control" placeholder="Enter Cheque No" disabled>

    Cheque Date
    <input type="date" name="txtChqueDate" class="form-control" placeholder="Enter Cheque Date" disabled>

Please Help

A: You can do it like following.

$(':radio[name=rbPayMode]').change(function () {
    var prop = this.value == 0;
    $('input[name=txtChequeNo], input[name=txtChqueDate]').prop({ disabled: prop, required: !prop });
});

        Mode

            <input type='radio' name='rbPayMode' id='bd' value='0' checked>Cash
            <input type='radio' name='rbPayMode' id='bd' value='1'>Cheque

        Cheque No
        <input type="number" name="txtChequeNo" pattern="^[0-9]" min="0" step="1" class="form-control" placeholder="Enter Cheque No" disabled>

        Cheque Date
        <input type="date" name="txtChqueDate" class="form-control" placeholder="Enter Cheque Date" disabled>


text:
Q: matching - and commas I am trying to validate given input based on these parameters
There is 1 condition that I am not able to figure out how to validate
I cannot have two dashes without a comma // 123-455-908 is invalid
and I am not able to add the condition for that in Reg
I have this regular expression
/^([0-9]+[-,]{0,1})*$/

and this is my code
let regexp, x, y
 regexp = /^([0-9]+[-,]{0,1})*$/
 x = "123,,"
regexp.test(x)

These are allowed :

123-234,456
  123-345
  123,456
  12
  1

These are not allowed :

123--234
  123-345-456
  123,,
  123,,455
  -123-34
  ,123

anything that has anything other than number, dashes or commas is not allowed
These are some examples and I hope you get the point
Any help on this will be appreciated

A: You can do this way with starting ^ and ending $ boundary, REGEX
^\d{1,}(?:-|,)?(?:\d+,?\d+)?$

const regex = /^\d{1,}(?:-|,)?(?:\d+,?\d+)?$/gmi;
const str = `123--234
123-345-456
123,,
123,,455
-123-34
,123

123-234,456
123-345
123,456
12
1`;
let m;

while ((m = regex.exec(str)) !== null) {
  // This is necessary to avoid infinite loops with zero-width matches
  if (m.index === regex.lastIndex) {
    regex.lastIndex++;
  }

  // The result can be accessed through the `m`-variable.
  m.forEach((match, groupIndex) => {
    console.log(`Found match: ${match}`);
  });
}

A: How about this one?
^(\d{1,3}-)?\d{1,3}(,(\d{1,3}-)?\d{1,3})*$

(\d{1,3}-)?\d{1,3} validates one instance of a code, while (,(\d{1,3}-)?\d{1,3})* handles repetition.

A: Maybe it is just me, but I feel it is easier to break a regexp down into smaller parts when trying to validate a string for multiple requirements.
One pro of doing it this way is that each regular expression becomes super simplified
But then this brings on a con which is you have more regular expressions in your code.

let tests = [
'123-234,456',
'123-345',
'123,456',
'12',
'1',
'123--234',
'123-345-456',
'123,,',
'123,,455',
'-123-34',
',123',
'abc-123',
'a,b,c',
'abc']

function evaluate(str) {
  // Remove anything that isn't a number, ',' or '-'
  // they will be the same length nothing was removed
  if(str.replace(/[^0-9,-]/g, '') != str) return false
  // Make sure there is no more than one '-'
  if((str.match(/-/g) || []).length > 1) return false
  // Make sure there is no more than one ','
  if((str.match(/,/g) || []).length > 1) return false
  // Make sure the string doesn't start with a ','
  if(str.match(/^,/) != null) return false

  // All tests have passed return true as it is a valid string
  return true
}

tests.forEach(i => console.log("Valid:", evaluate(i), i))


text:
Q: Library to compress text data and store it as text I want to store web pages in compressed text files (CSV). To achieve the optimal compression, I would like to provide a set of 1000 web pages. The library should then spend some time creating the optimal "dictionary" for this content. One obvious "dictionary" entry could be <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">, which could get stored as %1 or something like that because it is present on almost all web pages. By creating a customized dictionary like this, the compression rates should be 99% in my case.
My question is, does a library for doing this exist on Windows with MIT or similar liberal licensing exist? If not, are there any general purpose compression libaries you would recommend. I have tried a bit with zlib, but it outputs binary data. If I would convert this binary data into text, I am worried that the result might be longer than the original text.
EDIT: I need to be able to store the text in CSV files and still be able to import them into a database or even Excel.

A: *

*"text files (not binary)" is a little too general. If you mean that some
byte values (00,1A or whatever) can't be used, then any binary method +
something like base64 coding can be used. (Although I'd suggest a more efficient method
from Coroutine demo source).

To be specific, you can use any general-purpose compressor to compress your
base file, then base file + target file, then diff these, and you'd get
a dictionary compression (binary), which can be then converted to "text"
with base64 or yenc or whatever.

Alternatively, there're some coders with build-in support for that, for example
http://compression.ru/ds/ppmtrain.rar
http://code.google.com/p/lzham/

*If you actually want to have common phrases replaced with references, and
all other things left untouched (what is kinda implied, but not equals to "text output"),
you can use text preprocessors like:
http://xwrt.sourceforge.net/
http://compression.ru/ds/liptify.rar
(There were more afair).

*Also a hybrid method is possible. You can use a general-purpose LZ compressor like in [1], for example lzma, then replace its entropy coding with something text-based.
For example, in http://nishi.dreamhosters.com/u/lzmarec_v1_bin.rar
there's an utility which removes LZMA's entropy coding, and its pretty easy to convert
its output to text.


text:
Q: Numbering outside the pdf zone in latex I use MikTeX and I use the editor TeXnicCenter. I compile my code with XeLaTeX to generate a pdf.

I wanna do like this. Could you tell me the code?

A: Try
\documentclass[12pt]{article}
    \usepackage[a4paper]{geometry}
    \usepackage{lineno,lipsum}
    \newcounter{toto}
    \newcommand{\markl}{\stepcounter{toto}\marginpar{(\thetoto)}}
\begin{document}
I am trying to see if this works.\markl
I am trying to see if this works.
I am trying to see if this works.
I am trying to see if this works.
I am trying to see if this works.
I am trying to see if this works.
I am trying to see if this works.\markl
I am trying to see if this works.
I am trying to see if this works.
I am trying to see if this works.
I am trying to see if this works.
I am trying to see if this works.
I am trying to see if this works.
I am trying to see if this works.
I am trying to see if this works.\markl

\end{document}

Please consider making a MWE next time.


text:
Q: Can I upload file with this code in codeigniter? $judul = $_POST['judul'];
$idKategori = $_POST['kategori'];
$idPropinsi = $_POST['propinsi'];
$img = $_FILES['img']['name'];
$img_tmp = $_FILES['img']['tmp_name'];
$idUser = $_POST['user'];
$isi = $_POST['isi'];
$date = $_POST['date'];

if(empty($img)) {
    $query = mysql_query("INSERT INTO `artikel`(`idArtikel`, `idKategori`, `idPropinsi`, `judul`, `idUser`, `isi`, `date`) VALUES ('','$idKategori','$idPropinsi','$judul','$idUser','$isi','$date')");
}else{
    if(move_uploaded_file($img_tmp,"../../../img/".$img)) {
        $query = mysql_query("INSERT INTO `artikel`(`idArtikel`, `idKategori`, `idPropinsi`, `judul`, `img`, `idUser`, `isi`, `date`) VALUES ('','$idKategori','$idPropinsi','$judul','$img','$idUser','$isi','$date')");
    }else{
        echo "Failed to upload image";
    }
}

if($query) {
    header("location:../../index.php?page=artikel");
}else{
    echo "failed to update this post";
}

But the result is

move_uploaded_file(http://localhost/mvc/kuliner/assets/img/Green Nature Wallpapers 04.jpg): failed to open stream: HTTP wrapper does not support writeable connections

A: No!
Basically rewriting this code to work with Codeigniter is a lot more work than writing it from scratch using examples found in the CI documentation. Link provided in comment above (http://www.codeigniter.com/userguide2/libraries/file_uploading.html).
There are several reasons as both file upload, redirection, database handling, user output etcetera are done differently in CI using CI's methods and the MVC structure of programming.

A: This is how I do my uploads in CI (Using Dropzone).
Create Dropzone Controller
class Dropzone extends CI_Controller {

public function __construct() {
   parent::__construct();
   $this->load->helper(array('url','html','form'));
}

public function upload() {
    if (!empty($_FILES)) {
    $tempFile = $_FILES['file']['tmp_name'];
    $temp = $_FILES["file"]["name"];
    $path_parts = pathinfo($temp);
    $t = preg_replace('/\s+/', '', microtime());
    $fileName = $path_parts['filename']. $t . '.' . $path_parts['extension'];
    $targetPath = UPLOADPATH;
    $targetFile = $targetPath . $fileName ;
    echo $fileName;
    move_uploaded_file($tempFile, $targetFile);
    // if you want to save in db,where here
    // with out model just for example
    // $this->load->database(); // load database
    // $this->db->insert('file_table',array('file_name' => $fileName));
    }
}
}
   // Usage : <form action="<?php echo site_url('/dropzone/upload');" class="dropzone"  >

 /* End of file dropzone.js */
 /* Location: ./application/controllers/dropzone.php */

Secondly Add the following HTML, (mainly to a form so as to submit file name

            Drop file Here
            <input type="hidden" id="file" name="file"/>

Then a little Js to do the magic
Dropzone.options.uploadFile = {
    paramName: "file", // The name that will be used to transfer the file
    url:"<?php echo site_url('/dropzone/upload');?>",
    maxFiles:1,
    acceptedFiles:'image/*,application/pdf,.docx,.doc,.xls,.xlsx,.csv',
    dictMaxFilesExceeded:"You can only upload one file per Response",
    init: function() {
        this.on("sending", function(file) {
           // $('button#submit').attr('disabled','');// Requires Jquery
        });
        this.on("complete", function(file) {
            //$('button#submit').removeAttr('disabled'); // Requires JQuery
        });
        this.on("success", function(file,xhr) {
            //$('input[type="hidden"]#file').val(xhr); // Requires Jquery
        });
     }
};

Remember to include dropzone.js and jquery.js if needed.

A: You can upload files using the PHP function. But at first, you should make the directory or folder by yourself.
Here is my code, I did not add the validation part. I have created the uploads folder in the root directory.
$file = $_FILES['verfication_image'];
$file_name_with_extenstion = $file['name'];
$file_name = pathinfo($file_name_with_extenstion, PATHINFO_FILENAME);
$extension = pathinfo($file_name_with_extenstion, PATHINFO_EXTENSION);
$file_tmp_location =$_FILES['verfication_image']['tmp_name'];
$upload_name = $file_name.time().".$extension";
if(move_uploaded_file($file_tmp_location,"uploads/".$upload_name)){
    echo "The file has been uploaded.";
}else{
    echo "There was an error.";
}

I would suggest using the Codeigniter version of uploading the file as it is simple to add validation. I have added my Codeigniter code with validation,
$file = $_FILES['verfication_image'];
$file_name_with_extenstion = $file['name'];
$file_name = pathinfo($file_name_with_extenstion, PATHINFO_FILENAME);
$extension = pathinfo($file_name_with_extenstion, PATHINFO_EXTENSION);
$upload_name = $file_name.time().".$extension";

$config['upload_path'] = 'uploads/';
$config['file_name'] = $upload_name;
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 1024;
$config['max_width'] = 1024;
$config['max_height'] = 768;

$this->load->library('upload', $config);//Load the libary with the configuration

if(!$this->upload->do_upload('verfication_image')){
    echo($this->upload->display_errors());//validation error will be printed
}else{
    echo "The file has been uploaded.";
}

For more details, please follow the official guideline File Uploading class


text:
Q: Access data inside JSON in PHP I have a variable $output in PHP with this inside:
   {
"results": [
    {
        "address_components": [
            {
                "long_name": "6",
                "short_name": "6",
                "types": [
                    "street_number"
                ]
            },
            {
                "long_name": "",
                "short_name": "",
                "types": [
                    "route"
                ]
            },
            {
                "long_name": "",
                "short_name": "",
                "types": [
                    "locality",
                    "political"
                ]
            },
            {
                "long_name": "Barcelona",
                "short_name": "Barcelona",
                "types": [
                    "administrative_area_level_2",
                    "political"
                ]
            },
            {
                "long_name": "Catalunya",
                "short_name": "CT",
                "types": [
                    "administrative_area_level_1",
                    "political"
                ]
            },
            {
                "long_name": "Spain",
                "short_name": "ES",
                "types": [
                    "country",
                    "political"
                ]
            },
            {
                "long_name": "0830",
                "short_name": "0830",
                "types": [
                    "postal_code"
                ]
            }
        ],
        "formatted_address": "Barcelona, Spain",

"status": "OK"
}

I want to access the data inside "formatted_address" and store it's value in a variable in PHP so i can later store it on my database. I have tried so many things, but no success.
this is what i tried:
$info= json_decode($output);
echo $info->results;
echo $info->results[0];
echo $info.results;
echo $info['results']
etc... etc...

Could you please tell me how exactly do i access this information in PHP?
Help please!

A: Almost!
$info->results[0]->formatted_address
Also, try using var_dump for better output on php objects.

A: Or as one line:
echo json_decode($output)->results[0]->formatted_address;


text:
Q: Ruby array inject I am trying to log the average running time of 10 threads by using the inject method but it's giving me this error:
undefined method `+' for #<Thread:0x10b211590 dead> (NoMethodError)
    from /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/open-uri.rb:301:in `inject'
    from client_test.rb:13:in `each'
    from client_test.rb:13:in `inject'
    from client_test.rb:13

Here's the code:
require 'open-uri'
program_start_time = Time.now
threads = 10.times.map do
  Thread.new do
    time = Time.now
    open('http://ca.yahoo.com/?p=us').read.length
    Time.now-time
  end
end

threads.map &:join
puts threads.inject() { |sum, e| sum + e.value}.to_f / threads.size
puts Time.now - program_start_time

A: You need to provide an initial value for inject in this case, since if you don't, the initial value is simply the first element in the array:
puts threads.inject(0) { |sum, e| sum + e.value}.to_f / threads.size

A: You didn't provide an initial value for sum in
threads.inject() { |sum, e| sum + e.value}.to_f / threads.size

Fix it with
threads.inject(0) { |sum, e| sum + e.value}.to_f / threads.size


text:
Q: Why is col-sm-* applying to xs screens? I am using bootstrap for a project, and I am using different column widths for xs, sm, and md screens. When I apply col-xs-* and col-md-* , the columns resize perfectly for xs, md, and lg screens. When I add col-sm-*, the columns resize perfectly for sm, md, and lg, but I lose the xs configuration and it's replaced with the sm layout.
Can anyone help me out? How can I keep the xs layout along with the sm layout?

          ...

              ...

              ...

          ...

            ...

A: It is Boostrap 3.4.1. It turns out the problem was I didn't have this line in the head. This solved it!
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">


text:
Q: Disable kwallet popups from chrome I've edited ~/.kde/share/config/kwalletrc and added
[Auto Deny]
kdewallet=Chromium

In the KDE Wallet Configuration in system settings I've unchecked "Enable the KDE wallet subsystem". This also seems to add:
[Auto Deny]
kdewallet[$d]

However I'm still getting a popup when I visit my first page in google chrome. How can I stop it?
I've noticed there are actually two locations for wallets. One in ~/.kde/share/apps/kwallet/ and one in ~/.local/share/kwalletd/. At one point when I changed the KDE colour theme I noticed the popup for chrome was different to the GUI I got through system settings. There's also a duplicate
KDE Wallet Configuration I can get by running kwalletmanager->Settings->Configure Wallet where I get the same options but their own set of values. Even after unchecking "Enable the KDE wallet subsystem" here as well I still get a popup from chrome. What's going on with the mess of multiple config locations and settings pages?

A: The easiest solution to this Problem got served by the later KDE Plasma Versions. I currently use Version 5.12.7.
1. Go to:
System Settings -> Account Details (Personalization) -> KDE
    Wallet
2. Uncheck the Box "Enable the KDE wallet subsystem"
3. Apply

A: You can completely disable the KWallet backend by adding the following command-line flag to Chrome: --password-store=basic
For instance (if you're using Ubuntu's Chromium build), edit /etc/chromium-browser/default (system-wide) or ~/.chromium-browser.init (per-user) and add the flag to CHROMIUM_FLAGS. E.g.:
# Default settings for chromium-browser. This file is sourced by /bin/sh from
# /usr/bin/chromium-browser

# Options to pass to chromium-browser
CHROMIUM_FLAGS="--password-store=basic"

If you're using ArchLinux's Chromium build, edit ~/.config/chromium-flags.conf and add:
--password-store=basic

A: No matter what distro you're on this might work.
Open "google-chrome" file with a text editor (I used kate <3)
kdesu kate /opt/google/chrome/google-chrome

Paste this at the end of file with quote sign

"--password-store=basic"

So it must look like this
else
  exec -a "$0" "$HERE/chrome"  "$@" "--password-store=basic"
fi

SAVE AND EXIT. DONE!
(I tried it on OpenSUSE Thumbleweed with success! :D)

A: I found a simple solution, that works a 100% of the time, on any version of KDE:

I couldn't find any way to get kwallet off my system. There are some dependency issues and pacman won't let you remove the package.
  However I managed to avoid the irritating pop ups.
  First you need to remove any existing wallet. Delete the files under ~/.kde/share/apps/kwallet/.
Next time you do anything that interests Kwallet, it will pop up again. But this time it will ask you for an encryption method, blowfish or gpg. Select blowfish and when asked for a password, provide an empty password.
It won't ask for password anymore.
  This method worked for me on kwallet 5.13. Hopefully it will work for you too.

A: I solved this one out in the KWalletManager by creating a new wallet named test and replacing the .salt file from the existing wallet named kdewallet, with the .salt file of the newly created wallet test.
So
cd /home/'username'/.kde4/share/apps/kwallet
mv kdewallet.salt .kdewallet.salt;cp test.salt kdewallet.salt

And now the existing wallet named kdewallet has the password for the newly created test wallet.
Distro: Mageia 5.

A: One way is just to give chrome a fake dbus socket (Also you will probably need to disable password manager... you can use Paster Password Manager as an alternative)
env DBUS_SESSION_BUS_ADDRESS=none chrome

A: A quick solution is to just change KWallet's password to a blank one:
KDE's Application Menu (or Launcher, etc.) > System > KWalletManager > Change Password... > OK > Yes
This ends KWallet's password pop-ups when starting Chrome/Chromium.


text:
Q: __doPostBack triggers Microsoft JScript runtime error: Access is denied I have this javascript code:
    function checkUploadedFile() {
        var inputFile = $("#fuUploadProfile").val();
        if (inputFile != "") {
            __doPostBack('btnUploadProfile', '');
        } else {
            $("#lblMessage").show();
            return false;
        }
    }

here are the controls:
<asp:Label ID="lblMessage" runat="server" CssClass="srn_error">*Required</asp:Label>
<asp:FileUpload ID="fuUploadProfile" runat="server" CssClass="srn_file" />
<asp:Button ID="btnUploadProfile" ClientIDMode="Static" runat="server" Text="Upload" class="srn_button" OnClientClick="checkUploadedFile();" />

Even though I already have selected a file to upload, I get the "Microsoft JScript runtime error: Access is denied." only when using IE9.
What am I doing wrong?

A: after much thorough searching of the code, it was due to a javascript that was loaded, which was triggering the 'click' event of the asp.net FileUpload control. it seems that IE does not play well with javascript events that trigger a DOM control.
after I disabled the javascript function, it was working perfectly.


text:
Q: How to fix Jupyter notebook dependancies? ModuleNotFoundError: No module named 'boto3' I am running EMR cluster(AWS) but I do not understand how notebook imports packages. I am running PySpark kernel.
import boto3
No module named 'boto3'
Traceback (most recent call last):
ModuleNotFoundError: No module named 'boto3'

print (sys.version) shows
3.7.6 (default, Feb 26 2020, 20:54:15)
[GCC 7.3.1 20180712 (Red Hat 7.3.1-6)]

print(sys.executable) shows
/tmp/1594625399736-0/bin/python

I have both Conda and pip3 install of boto3.
How to solve this?

A: Are you using pyspark? If yes, then you need to install the packages in the spark context. Refer to this AWS document: https://aws.amazon.com/blogs/big-data/install-python-libraries-on-a-running-cluster-with-emr-notebooks/
similarly install any dependency packages if you see module not found error on import. Make sure the versions are compatible.

A: sc.list_packages()
Package                    Version
-------------------------- -------
beautifulsoup4             4.9.0
boto                       2.49.0
cycler                     0.10.0
jmespath                   0.9.5
kiwisolver                 1.2.0
lxml                       4.5.0
matplotlib                 3.2.2
mysqlclient                1.4.2
nltk                       3.4.5
nose                       1.3.4
numpy                      1.19.0
pandas                     1.0.5
pip                        9.0.1
py-dateutil                2.2
py4j                       0.10.9
pyparsing                  2.4.7
pyspark                    3.0.0
python-dateutil            2.8.1
python37-sagemaker-pyspark 1.3.0
pytz                       2020.1
PyYAML                     5.3.1
setuptools                 28.8.0
six                        1.15.0
soupsieve                  1.9.5
wheel                      0.29.0
windmill                   1.6

I have boto.

A: sc.install_pypi_package("boto3")


text:
Q: How to disable contextMenu from QWebEngineView? I want to disable the right click menu which appears by default when you create a QWebEngineView.
import sys
from PyQt5.QtWidgets import QApplication
from PyQt5.QtWebEngineWidgets import QWebEngineView
from PyQt5.QtCore import QUrl

app = QApplication(sys.argv)

webBrowser = QWebEngineView()

#Some line here to delete the contextMenu

webBrowser.load(QUrl("https://stackoverflow.com/"))
webBrowser.show()

sys.exit(app.exec_())

In the doc we can find a class QWebEngineContextMenuData which "provides context data for populating or extending a context menu with actions..." but nothing to delete in here?

A: To disable the default widgets menu then the contextMenuPolicy must be set to Qt::NoContextMenu:
webBrowser.setContextMenuPolicy(Qt.NoContextMenu)


text:
Q: Php, mysql join and count records For some reason I cant make this work:
I have two tables. First called tasks:
id     name         project_id     list_id
==========================================
1      First Task   1              1

And second one is called Lists:
id    project_id     name          position
===========================================
1     1              My List       1
2     2              Second List   2

and here is my query:
SELECT
  tl.*,
  COUNT(t.id) AS total
FROM
  lists AS tl
  LEFT JOIN tasks AS t
    ON tl.id = t.list_id
WHERE tl.project_id = 1
ORDER BY tl.position;

and no matter what I always end up with total 0
here is resulting array
Array
(
    [0] => stdClass Object
        (
            [id] => 1
            [project_id] => 1
            [name] => My List
            [position] => 1
            [total] => 0
        )

)

the value of [total] => 0 should be  [total] => 1

A: I was using incorrect ID in Where clause. It was hard coded to,1 and it should have been dynamic, acquired from URL.


text:
Q: Getting date in '2015-08-04'{"Y-M-D"} format. How to change the specified date format into UTC format? I am getting the date format in this way:- '2015-08-04' using knockout.js. How to change the specified date format into UTC format like "2015-08-08T19:20:18+00:00"?
Like in Javascript we are having date function like date.getDate() to get the particular date from the UTC format?
But after getting the date in the above specified format using the knockout.js, I am not able to get the particular date like date.getDate() using JavaScript.
Is there any function in knockout.js to get a date or month or only year from the specified date format?

A: If you want a Date object, just pass it in through new Date():
new Date('2015-08-04')
-> Tue Aug 04 2015 01:00:00 GMT+0100 (GMT Daylight Time)

If you want a UTC string, do the above and call toISOString() on it:
new Date('2015-08-04').toISOString()
-> "2015-08-04T00:00:00.000Z"


text:
Q: zip longest for python 2.7 I have 3 very large files(+100 MB) file_hash, cert_hash and url_data each has one string per line. The problem is that size of data in all these files are not same. I have used izip_longest function to read all these files at once (can't load these files in memory) but I wanted to iterate it for the longest file (file_hash is longest) and suppose all data from cert_hash has been read it should start taking the values from beginning of cert_hash file and similarly if url_data got's over it also starts reading from beginning. I have tried using fillvalue parameter but it takes only one value, I wanted to give different value for cert_hash and url_data if they get over.

A: You should cycle cert_hash and url_data if you want them to restart. For example:
>>> from itertools import cycle, izip
>>> for t in izip("abcdef", cycle("ghi"), cycle("jklm")):
    print t

('a', 'g', 'j')
('b', 'h', 'k')
('c', 'i', 'l')
('d', 'g', 'm')
('e', 'h', 'j')
('f', 'i', 'k')

Note that you no longer use izip_longest, as cycle is infinite.

If you want to restart at the end rather than the start, here is a tweak to the cycle equivalent implementation that achieves that:
>>> def zigzag(iterable):
    """zigzag('ABCD') --> A B C D C B A B C D  ..."""
    forward = []
    for element in iterable:
        yield element
        forward.append(element)
    backward = forward[-2:0:-1]
    while True:
        for element in backward:
            yield element
        for element in forward:
            yield element

>>> z = zigzag("ABCD")
>>> for _ in range(10):
    print next(z)

A
B
C
D
C
B
A
B
C
D


text:
Q: Trying to boot a windows 8.1 ISO from usb My hard drive randomly decided to stop booting my windows os so I downloaded a windows 8.1 ISO and installed it to my USB using Unetbootin. In my BIOS, launch csm is disabled as well as fast boot. My USB is formatted to fat32 with the unetbootin program.
What happens is when I try to boot from my USB, the windows flag will pop up with the spinning icon below it, and then a black screen forever.
I don't know how this screwed up so bad at this point. I have Ubuntu installed and I can still use that, but I'd like to get windows back if possible.

A: Try to create the bootable USB stick using Rufus with NTFS format and create boot disk using ISO image and locate the ISO image to your Windows 8.1 ISO file.

A: Rufus generally works pretty well, I would try that first.
I've also tried using the Windows 7 USB/DVD Download Tool.  It sometimes succeeds where Rufus fails.
If neither tool works, try creating the USB from a whole different computer.

A: On some BIOSes programs like Rufus and UnetBootin, which extract the image and use their own Syslinux or grub-like boot systems, refuse to work. I have had this problem many times on some older computers.
A process that works for me a large portion of the time, (And is my perfered method) is to write the image directly to the device.
WARNING: This process will destroy your data on the drive, and wipe any installed partition tables. To restore your drive to full working order, you might have to use gParted or another partition system. (Windows sometimes does this, but if it your USB device comes back with less space then it started with, you need to use something like GParted for Linux...) I am not responsible for any data loss, nor drive corruption as a result of using this guide.
DISCLAIMER: I am not responsible for any data loss, nor drive corruption as a result of using this guide.
NOTE: You will also have to be an Administrator on Windows and have access to use sudo on Linux.
First, you need the program you want to use based on the OS you are using.
For Windows I recommend Win32 Disk Imager.
For Linux, The command line dd tool.
Instructions for Win32 Disk Imager
This process is quick and easy, once downloaded, extract the .zip folder and find Win32DiskImager.exe start it and allow it to be run as Administrator.
In the Image File Section, click the blue folder and change Files of Type to "." in the drop-down box at the bottom of the dialog. Navigate too and select the Windows8.1 ISO you are using.
Select the drive you will be writing the data to, this box is to the right of the Image File Section area, Make sure the USB drive has enough space for the ISO!
Double check that the drive letter is correct and click "Write". Wait for the progress bar to finish, close the "Complete" box and the program, then Eject the drive using the icon in the System tray.
Instructions for dd on Linux
This one is a bit more involved. First you need to know the /dev point for the USB device. The easiest way is to use the answer to this SuperUser Question. Normally it is /dev/sdb.
First you must unmount the USB device.
sudo umount </dev/ point>

You must also define the partition, for example /dev/sdb1
Once you have that, use the cd command to get the directory the ISO is stored under. You can then use dd to write the ISO to the Flash drive.
sudo dd if=<Windows ISO FULL file name> of=</dev/ of usb> bs=4M

Where you replace the various parts as necessary. Type your user password and if you can run sudo commands, the terminal will "freeze" DO NOT PANIC, this means it is working. This will take upwards of half an hour to complete.
For either of these commands, if you don't have sudo access, the terminal will warn you and possibly say you don't have access to sudo, and it has been reported.
After the command line returns and is awaiting your input again, you can unplug the device from the Linux system.
Conclusion
Plug your drive into the computer you want to install Windows 8.1 on, and select it to boot from. (Either by F12 on the boot splash screen or through the BIOS settings) Hope this works for you!

A: Sometimes I have uses using a USB3 port, So try switching to a USB2 and see if this improves the issue.
It will be much slower, yet you would still be able to fix your issue.
Also, Check for a BIOS update!


text:
Q: How do (relative) paths work with the subfile package? I am trying to understand how (relative) paths need to be used with the subfiles package. In particular, it's not clear how content that I usually would include with \include, \input, \includegraphics, and \bibliography should be included within subfiles.

*

*Does it matter whether a subfile uses \include or \input or \import to add content with a path relative to the subfile directory or does it do the same thing because of internal subfile processing? The package documentation notes that \import is used to address issues with standalone compilation of subfiles not located in the directory of the "main file" containing \usepackage{subfiles}:

Sometimes it is desirable to put a subfile together with its images
and supplementary files into its own directory. The difficulty now is
that these additional files have to be addressed by different pathes
depending on whether the main file or the subfile is typeset. As of
version 1.3, the subfiles package handles this problem by using the
import package.

*For each use of \subfile in the main file, do I need to first change the \graphicspath to ensure the graphics path is set to the directory containing that respective subfile? In the example found at the bottom of page 5 of the documentation, no graphics path change is required, although this post suggests that it IS required, causing confusion.

*While I have a project-wide .bib file that each subfile uses to generate citations and bibliography, do I need to somehow specify the path of the .bib file relative to each subfile if I want (a) a single overall bibliography when the main file is compiled and (b) only those entries pertaining to the specific subfile when a given subfile is compiled? This post seems close to answering this but it's unclear exactly how this works.

A: I was using subfiles to write a rather extensive portfolio consisting of eight chapters, an appendix with additional literature and a dossier containing lots of external PDF's. All of these were created as subfiles to the main file. I currently am reworking that portfolio into a book using the same setup. Both portfolio and book are based on The Orange Book by Legrand. a public template that can be found on Overleaf among others.
The Orange Book uses a structure.tex file that defines a lot of the layout of the book to be created. It essentially is the preamble of the main file. That file is loaded into the main file using the command \input{structure.tex}. Since the bibliographic environment is also included in the structure.tex file the first few lines of the main document look like this:
\documentclass[11pt,fleqn]{book}

\input{structure.tex} % Insert the commands.tex file which contains the majority of the structure behind the template
\addbibresource{hb_specialist_new.bib} % BiblateX bibliography file
\input{appendix/woordenlijst}

\usepackage{subfiles}

As you can see I load three separate files into my main tex file. The last file woordenlijst contains the glossery entries used in all chapters in this book. The bibliography source file is loaded the usual way. Both structure.tex and hb_specialist_new.bib files are located in the same directory as the main.tex file. The woordenlijst.tex file is located in a subfolder called appendix.
The the chapters are in subfolders to the main folder and contain their figures in subfolders to their folder. So two folders deep relative to the main folder. The folder structure is in short like this:
Parent folder containing the `main.tex`, `structure.tex` and `hb_specialist_new.bib` files
|_ figures folder that contain images for chapter heading and main file
|_ appendox folder containing `woordenlijst.tex`
|_ domein1 folder containing `chapter_one.tex`
   |_ figures1 folder containing the figures used in chapter one
|_ domein2 folder containing `chapter_two.tex`
   |_ figures2 folder containing the figures used in chapter two
|_ etc.

The main.tex file loads the chapter files using the line (here given for the first two chapters):
%----------------------------------------------------------------------------------------
%   CHAPTER 1
%----------------------------------------------------------------------------------------

\chapterimage{lancaster1.jpg} % Chapter heading image

\subfile{domein1/zien_weten}

%----------------------------------------------------------------------------------------
%   CHAPTER 2
%----------------------------------------------------------------------------------------

\subfile{domein2/zien_begrijp}

Since the Orange Book template uses pictures in the chapter heading that file is included in this example to show how a relative path is used in the chapter file. That image file has to be included in the heading of the chapter files, when you use the package subfiles. When you use the package import you can remove that image loading line.
\documentclass[../hbspec_main_mhc]{subfiles}

\chapterimage{../figures/lancaster1.jpg} % Chapter heading image

\begin{document}

\chapter{Weten en begrijpen}\index{Weten en begrijpen}
\label{chp:weten}

As you can see, the path to the image heading is given by its relative path.
Inside the chapter file graphics are loaded using the line:
{\includegraphics[width=0.95\linewidth]{figures1/Emotional-Intelligence-Competencies.png}}

Remember that the folder figures1 is a subfolder of the domein1 (chapter one) folder. On compilation these images are loaded from their respective paths.
To answer your questions in summarise:

*

*It doesn't matter how you include another file into a subfile as long as you maintain path integrity throughout your folders and subfolders.

*You don't need to change the \graphicspath when you use the relative path structure inside \includegraphics. But if you want to, the both answers in the question you referred to, are very useful.

*As long as you load the bibliography.bib file in the preamble of the main file, all subfiles have access to that file and the bibliography will be created for all subfiles in the main file.

Note I currently use the package import inside the main.tex file. Switching from subfiles to import is rather easy to achieve changing the lines loading the chapter files. The main file now contains these lines to load the first chapter:
%----------------------------------------------------------------------------------------
%   CHAPTER 1
%----------------------------------------------------------------------------------------

\chapterimage{lancaster1.jpg} % Chapter heading image

\subimport{domein1}{zien_weten}

In the heading of the first chapter the preamble lines aren't required anymore, so the first line in the chapter file reads:
\chapter{Weten en begrijpen}\index{Weten en begrijpen}
\label{chp:weten}

A: To alleviate some of the confusion: most posts before 2020 refer to old versions of the subfiles package, which required more work. Information in more recent posts is probably more reliable than information in older ones.
include vs. input vs. import with subfile package

``Does it matter whether a subfile uses \include or \input or \import
to add content with a path relative to the subfile directory or does
it do the same thing because of internal subfile processing?''

Yes, it matters, these commands do different things. \input tells LaTeX to replace the \input command by the contents of the file; if this file refers to other files, the path information is interpreted relative to the file containing the \input command, even if the file is located in another directory. \include is similar in this respect, but does some additional things. \import, however, takes care that the input and the graphics paths are modified such that the path given in any \input, \include, \includegraphics, \import and \subfile statement in the imported file is interpreted relative to the imported file. \subfile essentially is an \import command, but additionally skips the preamble of the imported file. So the idea of \import and \subfile is that any path information in the imported/subfiled file is relative to this file, no matter which other document uses the file.
graphics paths with subfile package

``Do I need to first change the \graphicspath to ensure the graphics
path is set to the directory containing that respective subfile?''

No, this is something \import and \subfile take care of.
how to use a project-wide bibfile
The following example assumes that you use classic BibTeX, and the following project structure:
main.tex
allrefs.bib
part1/details.tex

main.tex:
\documentclass{article}
\bibliographystyle{plain}
\usepackage{subfiles}
\begin{document}
This is the main file, citing~\cite{a}, but also~\cite{b}.
\subfile{part1/details}
\bibliography{allrefs}
\end{document}

allrefs.bib:
@Article{a,
  author =  {Morris, B.},
  title =   {Whipping the whip},
  journal = {JWCS},
  year =    {2022}
}
@Article{b,
  author =  {Henk, V.},
  title =   {Hipping the hop},
  journal = {JWCS},
  year =    {2022}
}

part1/details.tex:
\documentclass[../main]{subfiles}
\begin{document}
\section{The details}
This is a subfile, but can also be processed as a main file.
It sites~\cite{b}.
\ifSubfilesClassLoaded{%
  \bibliography{../allrefs}% <<< path relative to this file
}{}
\end{document}

In the main directory, you can typeset main.tex with the commands
pdflatex main; bibtex main; pdflatex main; pdflatex main

while the subfile can be typeset with
cd part1; pdflatex details; bibtex details; pdflatex details; pdflatex details

This results in the documents main.pdf (left) and part1/details.pdf (right).


text:
Q: File Directory and Downloading File URL error I am using the below code to read files I have saved on my server in folders.
<?php
    if ($handle1 = opendir('../files/policies/fire')) {
        while (false !== ($file1 = readdir($handle1))) {
            if ($file1 != "." && $file1 != "..") {
                $thelist1 .= '
'.$file1.'
';
            }
        }
        closedir($handle1);
    }
?>

Fire Fighting Files:

<?php echo $thelist1; ?>

The code reads the files in the directory as it should. The issue I am having is once I click the link it searches or attempts to open the file in the root directory
It does not use the sub-dir to open the file but the root dir. The structure is as follow
/File
  /policies
    /FA

When I click the link it tries finding the file as below
/files/OHS_EHSR-020%20Employee%20Health%20and%20Safety%20Rules.pdf

and the file is saved as
/files/policies/FA/OHS_EHSR-020%20Employee%20Health%20and%20Safety%20Rules.pdf

Any suggestions would help. Please note my code I am using I took from this site as well
ADDING Full Code of two blocks this is why I cannot fix the directories to static in my code:

                  <?php
                  if ($handle = opendir('../files/policies/FA')) {
                      while (false !== ($file = readdir($handle))) {
                          if ($file != "." && $file != "..") {
                              $thelist .= '
'.$file.'
';
                          }
                      }
                      closedir($handle);
                  }
                  ?>

First Aid Files:

<?php echo $thelist; ?>

                      <?php
                      if ($handle1 = opendir('../files/policies/fire')) {
                          while (false !== ($file1 = readdir($handle1))) {
                              if ($file1 != "." && $file1 != "..") {
                                  $thelist1 .= '
'.$file1.'
';
                              }
                          }
                          closedir($handle1);
                      }
                      ?>

Fire Fighting Files:

<?php echo $thelist1; ?>

A: readdir returns relative path not absolute, so you need to prepend /files/policies to the $file variable and use it in your link
update:
$dir = '/files/policies/fire';

if ($handle1 = opendir('..' . $dir)) {
  while (FALSE !== ($file1 = readdir($handle1))) {
    if ($file1 != "." && $file1 != "..") {
      $filepath = $dir . DIRECTORY_SEPARATOR . $file1;
      $thelist1 .= '
' . $file1 . '
';
    }
  }
  closedir($handle1);
}

this should work for you


text:
Q: using math.random method to create dice method ı basically created a program for a bet game and ı wanted to use math.random method to obtain possible face values.
my question is that math.random is always same value so ı cannot use it repeatedly.
how can ı use math.random method repeatedly. ı dont want to get same value for my dice;
import java.util.Scanner;
public class Lab06d
{
  public static double money(double userMoney, int option, double bet )
  {
    //variable
    int dice1;
    int dice2;
    //codes
    dice1 = (int) Math.random() * 6 + 1;
    dice2 = (int) Math.random() * 6 + 1;
    System.out.println("dice sum: " + dice1 + dice2 );
    if(option == 1)
    {
      if((dice1 + dice2) % 2 == 1)
        userMoney = userMoney + ( bet / 2);
      else
        userMoney = userMoney - ( bet / 4);
    }
    if(option == 2)
    {
      if((dice1 + dice2) % 2 == 1)
        userMoney = userMoney - ( bet / 4);
      else
        userMoney = userMoney + ( bet / 2);
    }
    if(option == 3)
    {
      if((dice1 == 1 && dice1 == 1) || (dice1 == 6 && dice1 == 6))
        userMoney = userMoney + ( bet);
      else
        userMoney = userMoney - ( bet);
    }
    return userMoney;
  }
  public static void main(String[] args)
  {
    // variables
    double userMoney;
    int option;
    double bet;
    //codes
    Scanner scan = new Scanner (System.in);

    System.out.println("enter your money: ");
    userMoney = scan.nextInt();
    System.out.println("enter your option 1 for odd 2 for even 3 for extreme: ");
    option = scan.nextInt();
    System.out.println("enter your bet: ");
    bet = scan.nextInt();
    System.out.println(money(userMoney, option, bet));
    userMoney = money(userMoney, option, bet);
  }
}

A: (int) Math.random() * 6 + 1

means the same as
((int) Math.random())    *    6   +   1.

You're first rounding down, then multiplying and adding.
As Math.random() returns as number 0 <= x < 1, it is always casted to 0.
Notice that (int) always rounds down, so (int) 3.999 would become 3 for example, as well as (int)-3.9 would become -4.
Add braces like this:
 (int)     (Math.random() * 6 + 1)

You can also wrap it into a function like this:
static int throwDice() {
    return (int) (Math.random() * 6 + 1);
}

Operators in Java have a specific precedence to them, like multiplication comes before addition in mathematics, unless you use braces. You can look it up here. When in doubt (or to clarify), use braces.

A: The problem is at the time of initializing dice 1, dice 2. You must remember that you can't pass a primitive type by reference to a method. So you must wrap the COMPLETE DATA, which in this case is Math.random()*6+1 and parse the integer type. So, the code would be
dice1 = (int)(Math.random()*6+1);
dice2 = (int)(Math.random()*6+1);


text:
Q: Python Yahoo-Finance Try-Except with Continue for Problem Tickers in a List I am trying to pull the closing stock prices for certain dates from yahoo finance using python DataReader. I have a list of stocks symbols that contain some problem symbols as well that may not be recognized by yahoo finance. So I am using try-except with continue statement to ignore the problematic ticker.
The aim is to save the data into Data Frame and in CSV.
The problem is I only get last symbol data without its name.
a_list = ['WTC.AX', 'WOW.AX','AAB.TO','XXX.XO','ABT.TO','QCD.TO' ]

for code in a_list:
    try:
        data = wb.get_data_yahoo(code,start, end)
        Close_prices= data['Close']

    except Exception as ex:
        print(ex)
        continue
    finally:
        Close_prices

Output :

No data fetched for symbol XXX.XO using YahooDailyReader

print(data)

print(Close_prices)

I expected to see results similar to  :
Date     2018-06-29

Symbols

AAB.TO     0.130000

AAV.TO     4.110000

ABT.TO     6.930000

AC.TO     21.250000

ACD.TO     9.180000

But what I get is either :
                High        Low       Open      Close  Volume  Adj Close
Date
2018-06-29  26.530001  26.530001  26.530001  26.530001       0  26.018112

or this :
Date
2018-06-29    26.530001
Name: Close, dtype: float64

Only the last price data with no stock ticker/symbols.
Thanks in Advance.


text:
Q: get nativePath of file using FileReference I am developing an application using Adobe AIR.
How can we get absolute path of file or "nativePath" of file (as we call it in Flex/AIR) when we use FileReference to browse a file ?
I know there are security concerns related to this but is there any hack or is there a direct solution that I am unaware of?
Please help me out.
Thanks.

A: Since File extends FileReference, you can do this:
var file:File = new File();
file.addEventListener(Event.SELECT, onSelect);
file.browse();

private function onSelect(e:Event):void
{
   trace(e.target.nativePath);
}

A: This way the last used folder will be opened and you have a filename in your dialog (if you need that):
//Save dialog:
var oFile:File = new File();
oFile.save(aData, 'MyData.txt');
oFile.addEventListener(Event.COMPLETE, onComplete);

function onComplete(e:Event):void{
    trace(e.target.nativePath);
}


text:
Q: Read output from a Python Executed Script I am currently creating a program to extract file from drives. I would like to ask how I read an output that is displayed using python shell? For example:
while i<len(drives):
    print 'Searching for file in:', drives[i]
    print ''
    for root, dirs, files in os.walk(drives[i]):
        for file in files:
            if file.endswith(".vmdk"):
                print os.path.join(root, file)
            if file.endswith(".vbox"):
                print os.path.join(root,file)
    i+=1

I would like to read the output of print os.path.join(root,file) input this to another command. Is this possible?

A: I do not know how you can capture the output of print os.path.join(root, file), but you could also save the output of the call to os.path.join(root,file) in a variable before printing. Then you can use this variable to call your command. E.g:
while i<len(drives):
    print 'Searching for file in:', drives[i]
    print ''
    for root, dirs, files in os.walk(drives[i]):
        for file in files:
            if file.endswith(".vmdk") or file.endswith(".vbox"):
                filePath = os.path.join(root, file)
                print filePath
                // call your command here using 'filePath'
    i+=1


text:
Q: Why does the "Add" method of Entity Framework Collections behave differently across versions? I just upgraded from EF 4 (Object Context) to EF 6 (dbContext).. and my application throwing exceptions all over the place. I have narrowed it down to this:
user.PaymentMethod.Add(paymentMethod)
In the old version, the paymentMethod.User property was immediately assigned the user Object... but in the new version.. paymentMethod.User is null after this line of code.
I have had to change the code to this:
paymentMethod.User=user
Since many of the subsequent lines of code operate on the user object before SaveChanges() - this is causing havoc everywhere.
Im not sure if the application was written badly, or if there is something fundamental I am missing here about the newer EF version (or dbContext) [apologies Im not sure if its the newer EF version or the change to dbContext that is making the difference here]


text:
Q: Python replace with regex I have two strings which contains the following substrings: myStringA and myStringBB; and a dictionary d which maps A and BB to some other values, lets say d["A"] = "X" and d["BB"] = "YY". I want to replace both of these strings by the following strings:
ThisIsMyStringX and ThisIsMyStringYY;. So that I want to replace A and BB (which are known for me) by the values from dictionary and leave ; if present at the end and add ThisIs and the beginning. How can I achieve that?

A: You can use regex match-groups to achieve these replacements (a Match group is a Part of an regex encapsulated by brackets). For example:
import re

regex=re.compile("foo(bar)")
match = regex.match("foobar")
print(match.group(1))

will print "bar".
Here ist a working programm that solves your specific Problem:
import re

dict = {
   "A": "X",
   "BB": "YY"
}
myStringA = "myStringA"
myStringBB = "myStringBB"

regex = re.compile("my(\w+)(A|BB)")

match = regex.match(myStringA)
print("ThisIsMy"+ match.group(1) +
dict[match.group(2)])

match = regex.match(myStringBB)
print("ThisIsMy"+ match.group(1) +
dict[match.group(2)])


text:
Q: Message element is not interactable from selenium import webdriver
import time
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import random
import select

driver = webdriver.Chrome('ChromeDriver')
driver.get("https://devbusiness.tunai.io/login")
time.sleep(2)
driver.maximize_window()

#log in credentials
username = driver.find_element(By.NAME, "loginUsername");
username.send_keys("xxxxx");

password = driver.find_element(By.NAME, "loginPassword");
password.send_keys("xxxxx");

login = driver.find_element(By.XPATH,"//*[@id='app']/div/div/div/div/div/div[2]/form/div[4]/button");
login.submit();
time.sleep(3)

driver.get("https://devbusiness.tunai.io/dashboard/my_salon_user")
time.sleep(3)

randomUsername = random.choice(["dayon.salon3@tunai","dayonmanager@tunai","Dayon.der@tunai"])
driver.find_element(By.XPATH, "//tbody[@role='rowgroup']/tr[@role='row']/td/a[text()='"+ randomUsername +"']").click()
print("Username selected: ", randomUsername)
time.sleep(5)

driver.find_element(By.XPATH,"//*[@id='page-content']/div/div[3]/div/div[2]/div/div/div[2]/div/div[1]/header/a").click()
time.sleep(5)

# Get the list of elements
elements = driver.find_elements(By.CLASS_NAME,'custom-control-input')

# Select a random element from the list
random_element = random.choice(elements)
driver.execute_script("arguments[0].click();", random_element)

# Click on the selected element
random_element.click()
print("Element selected: ", random_element)
time.sleep(5)

driver.find_element(By.XPATH,"//*[@id='accKey']").click()
time.sleep(5)

I've been add "argument.click[]","webdriver wait until EC to be clickable" but still showing "Element not interactable. What would be the other possible solution? Hope someone could clarify for me. Thanks and have a nice day.

A: The problem is that you have picked an option randomly from the list but haven't used it correctly. The usage random.choice(element) is incorrect.
You can use the below code as a reference for the problem that you are facing. Here //tbody[@role='rowgroup']/tr[@role='row']/td[2]/a is thy xpath for the table cell that contains all username fields (plus some other elements)
randomUsername = random.choice(["dayon@tunai","dayon.salon3@tunai","dayonmanager@tunai"])
driver.find_element(By.XPATH, "//tbody[@role='rowgroup']/tr[@role='row']/td/a[text()='"+randonUsername+"']").click()

in this first ine, this will first create a variable with a random value from your list.
Then it will pass the variable with the randomized option in the xpath for the table cell and click it. A new dialog with "Blocked Permissions" will open

A: To click on specific username listed on table you need to use unique xpath to click.
After login added this code.
driver.get("https://devbusiness.tunai.io/dashboard/my_salon_user")
time.sleep(3)
randomtext = random.choice(["dayon@tunai","dayon.salon3@tunai","dayonmanager@tunai"])
element = driver.find_element(By.XPATH,"//table[@id='__BVID__74']/tbody//tr//td[2]//a[text()='{}']".format(randomtext))
element.click()


text:
Q: How to compare two PowerPoint (2010) text only like in word
*

*Source (smart art, animation, formatting , casing)

*Draft (smart art converted to shape, changed  formatting and casing, removed animation and transition and so on)

While I trying a compare to in PowerPoint that results is came all the changes. But I need only text changes (text inserted, text deleted)
Is there any way to change setting of track changes ?
Kindly help me...


text:
Q: Writing to a file py if anyone can help me I need my code to display as such:
Hammad | Won | 5

The code I'm using is:
f = open("Statistics.txt", "a")

f.write(str(player_name) +''+ str(Outcome)+''+str(max_guesses)+"\n"

f = open("Statistics.txt", "r")

print(f.read())

f.close()

I need the output to be:
Hammad | Won | 6

Instead I'm getting:
Hammad Won 6

A: Try replacing the write line with:
f.write(f'{player_name} | {Outcome} | {max_guesses}\n')

A: Replace f.write with this
f.write(str(player_name)+'|'+str(Outcome)+'|'+str(max_guesses)+"\n"

A: Python does not add | character automatically while string concatenation, you have to do it manually,
f.write(str(player_name) +' | '+ str(Outcome)+' | '+str(max_guesses)+"\n")

PS : f.write need a closing parenthesis(all functions do)


text:
Q: How can i return NSError in a Objective c like completionBlock of a function in swift In swift i want send NSError in a method completion block like in objective c.

A: Closure is same as objective c block. you can try this:
func myFunc(withCompletionHandler completionHandler:((NSError?) -> Swift.Void)?){
        var error:NSError? = nil
        //DO YOUR TASK AND ASSAIGN ERROR TO var error

        completionHandler?(error)
    }


text:
Q: Nilpotency class of dihedral group $D_{16}$
Using only upper central series, find the degree of nilpotency of the dihedral group $G = D_{16}$. (Answer: $3$)

So I need to find the non-negative integer $c$ such that $Z^c(G) = G$, where $Z^c(G)$ is defined as $$Z^0(G) = 1, Z^1(G) = Z(G), Z^2(G) / Z^1(G) = Z(G / Z^1(G)), Z^3(G) / Z^2(G) = Z(G / Z^2(G)), \cdots$$
And the upper central series is $$Z^0(G) \leq Z^1(G) \leq Z^2(G) \leq \cdots$$
I can rule out $c = 1$ since $Z^1(G) = Z(G) \neq G$ because $G$ is not a commutative group. If $c = 0$, then there are no elements in $G$ besides the identity that commute with every other element in the group, but I believe this is false since a rotation eight times commutes with every other rotation or reflection operations.
So now I want to check if $Z^2(G) = G$. I know that $$Z^2(G) / Z^1(G) = Z(G / Z^1(G)) = Z^2(G) / Z(G) = Z(G / Z(G))$$
I Googled the center of $D_{16}$, and it came out to be $Z(G) \cong \Bbb Z_2$. So then I have $$Z^2(G) / \Bbb Z_2 = Z(G / \Bbb Z_2)$$. Since the index of $\Bbb Z_2$ is $8$, $G/\Bbb Z_2 \cong \Bbb Z_8$. So $$Z^2(G) / \Bbb Z_2 = Z(\Bbb Z_8)$$. The center $Z(\Bbb Z_8) = \Bbb Z_8$ since $\Bbb Z_8$ is a commutative group. So then $$Z^2(G) / \Bbb Z_2 = \Bbb Z_8$$.
I'm not sure what to do from here. However, this procedure seems fairly long and I was wondering if there's a faster method to compute the nilpotency degree using upper central series.

A: Hint: $D_{16}/Z(D_{16})$ is isomorphic to $D_8$ and $D_8$ has nilpotency class $2$.
Let $\alpha$ be the elements of order $8$ and $\beta$ be an involution not contained in $<\alpha>$. It is easy to see that $\alpha^\beta=\alpha ^{-1}$. That means that $Z(G)$ does not contains such involution. Hence $Z(G)\leq <\alpha>$. If $\alpha^i$ is the generater of $Z(G)$, $(\alpha^i)^\beta=(\alpha^i)^{-1}$. Thus, $Z(G)=<\alpha^4>$.
Let $\bar G=G/Z(G)$. Then $\bar G=\{\bar \alpha,\bar \beta|\bar \alpha^4= \bar \beta^2=1 \ and \ {\bar \alpha}^{\bar \beta}=  {\bar \alpha}^{-1} \}$. Hence, $\bar G $ is isomorphic to $D_8$. I left you to observe that $D_8$ has nilpotency class $2$ as it is easy. Actually any nonabelian group of order $p^3$ has this property.


text:
Q: MySQL Semi synchronous replication stuck I have a mysql semi-synchronous replica-set with a master and 2 slaves. The replication happens fine to only one of the nodes but the other node is always stuck with the following status. Slave_IO_State: Waiting for master to send event
Master does not send any data and I see the following in the master mysqld error logs.
2018-05-14T06:43:51.880292Z 113 [ERROR] Semi-sync master failed on
   net_flush() before waiting for slave reply
2018-05-14T06:43:51.880985Z 113 [Note] Stop semi-sync binlog_dump to slave (server_id: 111)
2018-05-14T06:44:41.754052Z 1343 [Note] While initializing dump thread
   for slave with UUID <770ca92e-5730-11e8-9f7a-000d3a064af1>, found a
   zombie dump thread with the same UUID. Master is killing the zombie
   dump thread(113).
2018-05-14T06:44:41.863759Z 1343 [Note] Start binlog_dump to
   master_thread_id(1343) slave_server(111), pos(, 4)
2018-05-14T06:46:11.934785Z 1382 [Note] While initializing dump thread
   for slave with UUID <770ca92e-5730-11e8-9f7a-000d3a064af1>, found a
   zombie dump thread with the same UUID. Master is killing the zombie
   dump thread(113).
2018-05-14T06:46:11.934894Z 1382 [Note] Start binlog_dump to
    master_thread_id(1382) slave_server(111), pos(, 4)
2018-05-14T06:47:11.985863Z 1408 [Note] While initializing dump thread
    for slave with UUID <770ca92e-5730-11e8-9f7a-000d3a064af1>, found a
    zombie dump thread with the same UUID. Master is killing the zombie
    dump thread(113).

and so on....
my slave_net_timeout is 60 s on the slave and I can clearly see that after every 60 s the slave is trying to reconnect, but the master acknowledges and holds the connection but does not send any data. As a side effect, the number of slave connections to master continuously grows. I also see the following in Show Processlist for the master:
|  113 | repl_user | 172.19.0.12:58174 | NULL | Binlog Dump GTID | 3189 | Waiting to finalize termination | NULL
| 1343 | repl_user | 172.19.0.12:35394 | NULL | Binlog Dump GTID | 418 | starting | NULL |
| 1382 | repl_user | 172.19.0.12:35572 | NULL | Binlog Dump GTID | 328 | starting | NULL |

Any pointers and to debug this further will be greatly appreciated. Thanks!


text:
Q: Analogy of a class being a cookie cutter and objects being cookies I came across the analogy of the class being a cookie cutter and the cookies being objects while reading Code Complete. I fail to see why this analogy was drawn.How is it related to the concept of objects being run time instances of their classes?

A: The analogy is a bad one, because it can convey the essence of classes and objects if you apply the right mental mapping, but that mapping is not obvious to arrive at, and perhaps not even the most convincing one.
A class is like a cookie-cutter in that it has the power to create multiple items that are alike in some ways: they all have the same number and type of fields, while their values can differ. You can compare this to all cookies having the same shape, but it is unclear how the differences between individual cookies map to the differences between objects that are class-mates; in my mind, two Cartesian coordinates with different X and Y values are much more different than similar, certainly much less alike than two cookies with the same shape.


text:
Q: HttpClient: кросс-доменные запросы API
Есть сервис аутентификации, разработанный на PHP и развернутый на хостинге XX.XX.XX.XX, командой backend. И у этого сервиса есть API
POST: http://XX.XX.XX.XX:8081/login

body {
username
password
}

возвращающий cookie PHPSESSID.

ЗАПРОС С ПОМОЩЬЮ REST-CLIENT (расширение chrome)
Если с помощью Rest Client сделать этот запрос

то как видите, запрос проходит и необходимый cookie возвращается.

ЗАПРОС С ПОМОЩЬЮ HttpClient
Теперь если выполнить этот запрос из приложения-Angular, развернутого естественно на localhost:4200 с помощью кода:
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';

@Injectable()
export class AuthService {
  readonly endpoint = 'http://XX.XX.XX.XX:8081/login';

  constructor(private readonly httpClient: HttpClient) { }

  post(userName: string, password: string) {
    console.log('AuthService.post has been executed!');

    const body = new HttpParams()
      .set('username', 'name')
      .set('password', 'pass');

    const headers = new HttpHeaders()
      .append('Content-Type', 'application/x-www-form-urlencoded');

    const options = {
      headers: headers
    };

    return this.httpClient.post(this.endpoint, body, options);
  }
}

то в консоль отображается:

ВОПРОС
Как правильно настроить HttpClient для выполнения этого кросс-запроса. Backend-разработчики уверены, что у сервиса CORS-настройки правильно настроены, но если этого не так, то на какие настройки обратить их внимание?


text:
Q: Prompt a User to Set Up iCloud I am starting to implement iCloud, and I would like to prompt the user to set up iCloud account if he doesn't have it set up yet.
How do I do this?
Thanks

A: See this question.
So in your case it would be the following bit of code:
NSURL *url=[NSURL URLWithString:@"prefs:root=CASTLE"];
[[UIApplication sharedApplication] openURL:url];