text:
Q: How to manually set a dynamic default field value in Django forms? I am trying to create a form where the default date field value should be changed from time to time.
I have created a model with the two field values. I intend to change these fields from time to time for thousand of pages. If i can do this in the admin panel once for all the pages then i get a little stress off.

*

*{default_start_date and default_end_date}

i would like to have these fields called as the page loads to be the default values for two other fields

*

*{start_date and end_date}

My question i dont know how i can do this? Django or Java Script? or Both?

A: You could do this using a django model and its corresponding admin interface:
class DateRange(models.Model):
    start_date = models.DateField()
    end_date = models.DateField()

admin.site.register(Author)

This would let you adjust the DateField in the admin. It also lets you call the current value of DateRange.objects.all()[0].start_date wherever you need that in your app/templates.


text:
Q: Android geofencing doesn't working with dynamically geofences loaded (volley request) I'm trying to load a geofences dynamically from an api but I have a problem.
When I load static data into my app (hard-coded for example) everything goes well (geofence triggered fastly) but If I try to load data from a remote server the geofence action doesn't trigger anymore. I use Volley to handle request.
onCreate method
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main_activity);

    // Empty list for storing geofences.
    mGeofenceList = new ArrayList<Geofence>();

    // Initially set the PendingIntent used in addGeofences() and removeGeofences() to null.
    mGeofencePendingIntent = null;

    geofencePointsRequest(this, null, null);

    buildGoogleApiClient();
}

Volley request to retrieve data
public void geofencePointsRequest(final Context context, Map<String,String> params, final ProgressDialog pDialog){
    webService = new WebService();

    CustomArrayRequest jsonObjReq = new CustomArrayRequest(
            Request.Method.GET,
            WebServiceUrl.POINTS,
            params,
            new Response.Listener<JSONArray>() {
                @Override
                public void onResponse(JSONArray response) {
                    ArrayList<Point> points = webService.getPoints(response);
                    populateGeofenceList(points);
                }
            },

            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    String errorHandler = webService.getError(error);
                    int status = (error.networkResponse.statusCode != 0) ? error.networkResponse.statusCode : 0;
                    Toast.makeText(context, "Code : " + status + " - Error : " + errorHandler, Toast.LENGTH_LONG).show();
                }
            }) {

        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            return webService.getHeaders();
        }
    };

    VolleySingleton.getInstance(context).addToRequestQueue("pointsRequest", jsonObjReq);
}

Build GoogleApiClient
protected synchronized void buildGoogleApiClient() {
    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build();
}

@Override
protected void onStart() {
    super.onStart();
    mGoogleApiClient.connect();
}

On connected I load geofences
@Override
public void onConnected(Bundle connectionHint) {
    Log.i(TAG, "Connected to GoogleApiClient");
    addGeofencesOnLoad();
}

private GeofencingRequest getGeofencingRequest() {
    GeofencingRequest.Builder builder = new GeofencingRequest.Builder();
    builder.setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_ENTER);
    builder.addGeofences(mGeofenceList);
    return builder.build();
}

public void addGeofencesOnLoad() {
    if (!mGoogleApiClient.isConnected()) {
        Toast.makeText(this, getString(R.string.not_connected), Toast.LENGTH_SHORT).show();
        return;
    }

    try {
        LocationServices.GeofencingApi.addGeofences(
                mGoogleApiClient,
                getGeofencingRequest(),
                getGeofencePendingIntent()
        ).setResultCallback(this); // Result processed in onResult().
    } catch (SecurityException securityException) {
        logSecurityException(securityException);
    }
}

I create a list of geofences (from data parsed)
public void populateGeofenceList(ArrayList<Point> points) {
    for (int i=0; i<points.size(); i++) {
        mGeofenceList.add(new Geofence.Builder()
                .setRequestId(pins.get(i).getShortId())
                .setCircularRegion(
                        points.get(i).getLocation().getCoordinates().latitude,
                        points.get(i).getLocation().getCoordinates().longitude,
                        points.get(i).getLocation().getRadius()
                )
                .setExpirationDuration(Geofence.NEVER_EXPIRE)
                .setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER)
                .build());
    }
}

EDIT: I have refactored buildGoogleApiClient position in code but the problem is always that it doesn't fire notification...
Thanks for your help

A: It seems you're not initializing Google Api Client, buildGoogleApiClient() method doesn't execute until populateGeofenceList is called and this is not done if you haven't connect to the Google Api Client.
So your problem might be Google Api Client is null so is not connecting. Check here:
 protected void onStart() {
    super.onStart();
    if (mGoogleApiClient != null) mGoogleApiClient.connect();
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Update the file sent in Firebase I wrote a program that uploads a series of data to firebase
My problem is that when new data is uploaded, the previous contents of the file in Firebase are deleted and new data is replaced.
It is possible to guide the previous data to be added to the new data
enter image description here
            String key_press ="key pressed :"+sb;

        reference= FirebaseStorage.getInstance().getReference().child("Dcument");
        reference.child("file.txt").putBytes(sb.toString().getBytes()).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
               // Toast.makeText(MyAccessibilityService.this, "file upload seuccessfully", Toast.LENGTH_SHORT).show();
            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                Toast.makeText(MyAccessibilityService.this, e.toString(), Toast.LENGTH_SHORT).show();
            }
        });

A: When you write data to a path in Cloud Storage (with Firebase or any of the other SDKs) it replaces any data that existed at that path. There is no way to tell Cloud Storage to merge the data, as it treats all files/objects as blobs and doesn't have any knowledge about the file's structure.
So you will either have to read the existing data, merge that with your update, and then write the result to Cloud Storage, or store the new data as a separate file in Cloud Storage.


text:
Q: Search for keyword in textual file C I'm having trouble reading a keyword from file that a user inputs to search for. The first part of the program asks for user input for naming the file. It then asks for sentence input. You can input sentences until you write "END". When you write "END", the appending of sentences to file should stop and the program should ask you for a keyword to search the sentences appended to the newly created textual file. I used 'gets' to ask for a word that will be searched for in the file. The program should find that word in a sentence and print back the whole sentence containing the keyword. The whole code looks like this:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
    char fileName[128];
    printf("Input your filename (end with .txt):");
    gets(fileName);

    FILE *filePointer = NULL;
    char text1[128];
    char word1[128];
    filePointer = fopen(fileName, "a");

    if(filePointer == NULL)
    {
        printf("Cannot open file!");
        exit(EXIT_FAILURE);
    }
    else{
        printf("Input your sentence: ");
        while (fgets(text1, 127, stdin) != NULL && strncmp(text1, "END\n", 5) != 0){
            printf("Input your sentence: ");
            fprintf(filePointer, "%s", text1);
        }

        int line_num = 1;
        int find_result = 0;
        char text2[128];

        filePointer = fopen(fileName, "r");

        printf("Input keyword you're looking for: ");
        gets(word1);

        while(fgets(text2, 127, filePointer) != NULL) {
            if((strstr(text2, word1)) != NULL) {
                printf("A match found on line: %d\n", line_num);
                printf("\n%s\n", tekst2);
                find_result++;
            }
            line_num++;
        }

        if(find_result == 0) {
            printf("\nSorry, couldn't find a match.\n");
        }

        if(filePointer) {
            fclose(filePointer);
        }

        return(0);
    }
}

It all works, but the problem is somewhere here:
        int line_num = 1;
        int find_result = 0;
        char text2[128];

        filePointer = fopen(fileName, "r");

        printf("Input keyword you're looking for: ");
        gets(word1);

        while(fgets(text2, 127, filePointer) != NULL) {
            if((strstr(text2, rijec)) != NULL) {
                printf("A match found on line: %d\n", line_num);
                printf("\n%s\n", text2);
                find_result++;
            }
            line_num++;
        }

I'm new at C programming, so I'm not sure where the flaw is. I know it should work in theory. It doesn't return a result when it clearly should.

A: You need to fclose() the file after writing, before reopening to read.
if (fclose(filePointer) != 0)
{
  fputs("The sky is falling.", stderr);
  return 1;
}

filePointer = fopen(fileName, "r");


text:
Q: How to show total number of notification on top of my notification icon using GCM I am creating an android app where when GCM sends a message to my application then I want to show the total new notifications number. I want it to appear on top of my notification icon like facebook or Myntra(all the updates). My notification icon is in a tablayout. So how can I change or make a marker(or anything) just to show that there are new notification?

A: you can try following,
public class BadgeNumberExample extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_badge_number_example);
        setBadge(this,5);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.badge_number_example, menu);
        return true;
    }

    public static void setBadge(Context context, int count) {
        String launcherClassName = getLauncherClassName(context);
        if (launcherClassName == null) {
            return;
        }
        Intent intent = new Intent("android.intent.action.BADGE_COUNT_UPDATE");
        intent.putExtra("badge_count", count);
        intent.putExtra("badge_count_package_name", context.getPackageName());
        intent.putExtra("badge_count_class_name", launcherClassName);
        context.sendBroadcast(intent);
    }

    public static String getLauncherClassName(Context context) {

        PackageManager pm = context.getPackageManager();

        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_LAUNCHER);

        List<ResolveInfo> resolveInfos = pm.queryIntentActivities(intent, 0);
        for (ResolveInfo resolveInfo : resolveInfos) {
            String pkgName = resolveInfo.activityInfo.applicationInfo.packageName;
            if (pkgName.equalsIgnoreCase(context.getPackageName())) {
                String className = resolveInfo.activityInfo.name;
                return className;
            }
        }
        return null;
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}


text:
Q: Elixir: File upload to a REST API with json data I'm trying to upload a file to a rest api using HTTPoison.
I can get a file upload to work with the following code, but I need to replace {"name", "value"} with a json payload or find a way to have json/nested data be sent with same request.
url = 'https://sandbox.e-signlive.com/api/packages/dc337476-9841-454a-b5d4-fe5a2b60136d/documents'

headers = [{"Authorization", "secret_key"}]

HTTPoison.post!("httpbin.org/post", {:multipart, [{"name", "value"}, {:file, "/Path/to/document.pdf"}]}, headers)

A: It seems enctype is missing:
enctype="multipart/form-data"


text:
Q: Is the i386 instruction "div ah" pointless? From https://www.felixcloutier.com/x86/div:
    ...
    temp ← AX / SRC;
    IF temp > FFH
        THEN #DE; (* Divide error *)
        ELSE
            AL ← temp;
            AH ← AX MOD SRC;
    FI;
    ...

For div ah the SRC would be ah. IMHO temp will always be larger than FFH and therefore the exception will be raised since:

*

*AX = 256*AH+AL

*temp = AX / AH = (256*AH+AL)/AH = 256 + AL/AH

*temp is over FFH
Do I miss something here?

A: That's correct, just like div edx it's never usable without faulting.  The criterion for 2N/N => N-bit div not overflowing its quotient is high_half(dividend) < divisor, as you showed, so using divisor = high(dividend) will always overflow (or divide by zero).  Why "DIV EDX" in MASM always generates processor exception? explains the same thing another way.
Interesting point that it's a guaranteed one-instruction way to raise #DE without requiring any instructions to put values in register, though.
(In protected mode, int 0 is not exactly the same thing.  e.g. under Linux, in user-space int 0 will #GP -> SIGSEGV because of permissions on the IDT entry, while an actual divide exception will #DE -> SIGFPE).

As Jester points out, that encoding only accounts for 1 of the 2^5 possible encodings of F6 /6  div r/m8, counting just the ModRM byte (not the vast possibilities of extra bytes that addressing modes can use).
Making it not-encodeable would take extra transistors in the decoders.  And then what do you do with that 2-byte sequence?  #UD illegal instruction exception?  That's silly, just let it raise #DE after decoding normally and getting to the execution unit like any other div instruction.  Or use it for some other special thing like mfence?
It probably wouldn't really have been a sensible design decision to have the 2-byte machine code for div ah actually mean some totally different single instruction.  In any case, that ship sailed with 8086 where it will raise #DE, not #UD; any change would break that backwards compat.  Since there are less intrusive ways to find new coding-space for new opcodes (e.g. like the illegal encodings of lds and les or whatever that VEX prefixes borrow), Intel and AMD haven't yet stooped to such insanity.  Those LES / LDS 32-bit-mode encodings already raised #ud instead of another exception, and more importantly had more spare bits so the VEX prefixes have room to actually encode some fields in those 2 or 3 byte prefixes.


text:
Q: Mongo Db getting two documens of a single collection as singel document I had single collection Employee:
The data inside the collection is
{
    "_id" : ObjectId("5b44cb8b44a531b12aa69678"),
    "Empid" : 1,
    "Empname" : "Raghu",
    "Deptid" : "D1",
    "Depname" : "IT",
    "Salary" : 15000,
    "Time" : "8 Hours"
}

{
    "_id" : ObjectId("5b44cbda44a531b12aa69679"),
    "Empid" : 1,
    "Empname" : "Raghu",
    "Deptid" : "D2",
    "Depname" : "Soft",
    "Salary" : 25000,
    "Time" : "9 Hours"
}

I want the output as
{
    "Empid" : 1,
    "Empname" : "Raghu",
{
    "Deptid" : "D1",
    "Depname" : "IT",
        {
    "Salary" : 15000,
         "Time" : "8 Hours"
    }
}
{

    "Deptid" : "D2",
    "Depname" : "Soft",
    {
         "Salary" : 25000,
         "Time" : "9 Hours"
    }
}

}

A: According to description as mentioned into above question please try executing following aggregate operation into MongoDB shell.
db.employee.aggregate(

    // Pipeline
    [
        // Stage 1
        {
            $group: {
                _id: '$Empid',
                department: {
                    $addToSet: {
                        Deptid: '$Deptid',
                        Depname: '$Depname',
                        Salary: '$Salary',
                        Time: '$Time'
                    }
                },
                doc: {
                    $first: '$$ROOT'
                },
            }
        },

        // Stage 2
        {
            $project: {
                Empid: '$_id',
                EmpName: '$doc.Empname',
                Department: '$department',
                _id: 0
            }
        }

    ]

);


text:
Q: How can I find out what version is passed to setup in setup.py? What I'm looking for is something like:
python setup.py show-version

This is so that I can create a git tag for a release as part of build-and-release fabric job.
Since that doesn't exist I've ended up with:
    import setuptools
    original = sys.modules['setuptools']

    class Fake(object):
        def __call__(self, *args, **kw):
            self.args, self.kw = args, kw

    fake_setuptools = ModuleType('fake_setuptools')
    for name in dir(setuptools):
        setattr(fake_setuptools, name, Fake())

    sys.modules['setuptools'] = fake_setuptools

    with open('setup.py') as source:
        exec(source.read())

    print(fake_setuptools.setup.kw['version'])

Which, quite frankly, is horrible!
How should I be doing this?

A: Setuptools provides a --version flag to the setup script invocation.
$ python setup.py --version

A: Alternately, if you need other metadata from the package, jaraco.packaging provides a show command which can be used to reveal any number of attributes from the package.

A: A whole bunch of information can be obtained from setup.py, including what I was looking for:
$ python setup.py --help
...
Information display options (just display information, ignore any commands)
  --help-commands     list all available commands
  --name              print package name
  --version (-V)      print package version
  --fullname          print <package name>-<version>
  --author            print the author's name
  --author-email      print the author's email address
  --maintainer        print the maintainer's name
  --maintainer-email  print the maintainer's email address
  --contact           print the maintainer's name if known, else the author's
  --contact-email     print the maintainer's email address if known, else the
                      author's
  --url               print the URL for this package
  --license           print the license of the package
  --licence           alias for --license
  --description       print the package description
  --long-description  print the long package description
  --platforms         print the list of platforms
  --classifiers       print the list of classifiers
  --keywords          print the list of keywords
  --provides          print the list of packages/modules provided
  --requires          print the list of packages/modules required
  --obsoletes         print the list of packages/modules made obsolete


text:
Q: DevTools failed to load SourceMap: From my website: https://www.fermento24.com/
When we go analyzing the website with google, I get some errors, and while 've got the gist of the other errors, this error in particular is difficult:
DevTools failed to load SourceMap: Could not load content for https://cdn.shopify.com/s/files/1/0268/0383/0855/t/12/assets/swiper.min.js.map:
HTTP error: status code 404, net::ERR_HTTP_RESPONSE_CODE_FAILURE
Now, I understand that the file in question is missing, but... WHAT is calling to this file? And how do I go and fix this? I don't think this file was really deleted, but most likely changed...
hope someone will answer


text:
Q: .NET Core 3.1, EF Core 3.1 DB First approach, Identity What is the latest recommendation for introducing Identity into your existing .NET Core 3.1 WebApi project using EF Core 3.1 DB First approach ?
So after you scaffold database to create your objects in .net project, how do properly "insert" Identity tables ?
The best solution I could find on this topic is an old SO post from almost 5y ago, so I'm wandering is there a new solution to this ?
Using Asp.Net Identity DataBase first approach
thanks


text:
Q: problems with the position of a Row I'm building a widget for an application. I have a problem to set a position of a row.
image
I don't how to set the position of the two icon button where is the black rectangle.
I tried to use main/crossAxisAlignment but I have only obtain that the row move from center to right.
Here is my code:
class CustomCardDetail extends StatelessWidget {
  CustomCardDetail({
    this.containerHeight,
    this.containerWidth,
    @required this.image,
    this.backgroundColor,
    this.colorTitle,
    @required this.title,
    this.titleFontSize,
    this.titleFontFamily,
    this.titleFontWeight,
    @required this.content,
    this.contentColor,
    this.contentFontSize,
    this.contentFontFamily,
    this.contentFontWeight,
    @required this.onPressedFavoriteButton,
    @required this.onPressedShareButton,
  });

  final double containerHeight, containerWidth, titleFontSize, contentFontSize;
  final String image, title, titleFontFamily, content, contentFontFamily;
  final Color backgroundColor, colorTitle, contentColor;
  final FontWeight titleFontWeight, contentFontWeight;
  final Function onPressedFavoriteButton, onPressedShareButton;

  @override
  Widget build(BuildContext context) {
    return Container(
      height: containerHeight,
      width: containerWidth,
      color: backgroundColor,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.start,
        children: [
          Container(
            child: Image(
              image: AssetImage(image),
            ),
          ),
          Padding(
            padding: EdgeInsets.all(15.0),
            child: Container(
              color: Colors.red,
              height: 170,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.stretch,
                children: [
                  Text(
                    title == null ? 'TITLE' : title,
                    style: TextStyle(
                      color: colorTitle,
                      fontSize: titleFontSize,
                      fontFamily: titleFontFamily,
                      fontWeight: titleFontWeight,
                    ),
                  ),
                  Padding(
                    padding: EdgeInsets.only(top: 15.0),
                    child: Text(
                      content == null ? 'CONTENT' : content,
                      style: TextStyle(
                        color: contentColor,
                        fontSize: contentFontSize,
                        fontFamily: contentFontFamily,
                        fontWeight: contentFontWeight,
                      ),
                    ),
                  ),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.end,
                    crossAxisAlignment: CrossAxisAlignment.end,
                    children: [
                      IconButton(
                        icon: Icon(
                          Icons.favorite_border,
                          color: Colors.white,
                        ),
                        onPressed: onPressedFavoriteButton,
                      ),
                      IconButton(
                        icon: Icon(
                          Icons.share_rounded,
                          color: Colors.white,
                        ),
                        onPressed: onPressedShareButton,
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }
}

thanks for help.

A: add spacer between  padding and row
Column(
                mainAxisAlignment: MainAxisAlignment.start,
                children: [
                  Container(
                    child: Image(
                      image: AssetImage(image),
                    ),
                  ),
                  Padding(
                    padding: EdgeInsets.all(15.0),
                    child: Container(
                      color: Colors.red,
                      height: 170,
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.stretch,
                        children: [
                          Text(
                            title == null ? 'TITLE' : title,
                            style: TextStyle(
                              color: colorTitle,
                              fontSize: titleFontSize,
                              fontFamily: titleFontFamily,
                              fontWeight: titleFontWeight,
                            ),
                          ),
                          Padding(
                            padding: EdgeInsets.only(top: 15.0),
                            child: Text(
                              content == null ? 'CONTENT' : content,
                              style: TextStyle(
                                color: contentColor,
                                fontSize: contentFontSize,
                                fontFamily: contentFontFamily,
                                fontWeight: contentFontWeight,
                              ),
                            ),
                          ),
                Spacer(), ////////// add spacer
                          Row(
                            mainAxisAlignment: MainAxisAlignment.end,
                            crossAxisAlignment: CrossAxisAlignment.end,
                            children: [
                              IconButton(
                                icon: Icon(
                                  Icons.favorite_border,
                                  color: Colors.white,
                                ),
                                onPressed: onPressedFavoriteButton,
                              ),
                              IconButton(
                                icon: Icon(
                                  Icons.share_rounded,
                                  color: Colors.white,
                                ),
                                onPressed: onPressedShareButton,
                              ),
                            ],
                          ),
                        ],
                      ),
                    ),
                  ),


text:
Q: Invalid Provisioning Profile Location: Xcode 6 embeds it on submission I upgraded last night to Xcode 6 GM. So I have an mac app which includes an helper app. I know that there should be only one provisioning profile in the package so I excluded it on the helper app.
If I look in the .xarchive of the product it is clean from profiles (There is only one or none profile - tried both)
But for me it somehow appears that Xcode 6 GM is including the profile when you hit submit via the organizer.

As you can see it adds the provisioning profile to both binaries (red rect) in the package and there is no way to avoid it.
I'm including the helper app via a Copy Ressource Build Phase to: "Contents/Library/LoginItems"
What am I doing wrong? Is this a Xcode issue or is my configuration not right?

A: Okay, here's a temporary solution that's far from ideal, but for now it works (unless you're on Yosemite, I'm guessing).

*

*Rename XCode 6's XCode.app to something like XCode6.app

*Download XCode 5 from the App Store (downloads as XCode.app in /Applications)

*Open XCode 6, make SURE that you're NOT code signing the Helper app, then Archive the build and close XCode 6

*Open XCode 5, open Organizer and proceed to Submit to Apple as usual

*Profit!

Note: While this works, I really hope Apple fixes whatever's breaking XCode 6, as this process will most likely break with Yosemite.
EDIT: Submitted a bug report to Apple (rdar://18318295)

A: This issue (is) seems to be fixed with Xcode 6.01
It doesn't embed an profile in the corresponding helper app:

This seems to solve the problem


text: Q: Problema de rutas con Angular y servicios web con PHP Al subir el proyecto de angular a producción aparentemente el "routerLink" funciona bien al momento de ir de una ruta a otra, pero si recargo la página o quiero modificar directamente la URL para navegar a una ruta en especifico, aparece "Not Found", tal como adjunto en la imagen, ¿Por qué puede pasar esto?


text:
Q: Get onload event of an angular.element iframe I am trying to get an onload event on an added iframe. This happens inside a service function call. Its supposed to download a file, what works fine. But I need to wait until the iframe is loaded to return a promise resolve.
The reduced code with the problem is:
iFrame = angular.element('<iframe id="blaba" style=\'position:fixed;display:none;top:-1px;left:-1px;\'/>')
angular.element(document.body).append iFrame
# onload bind here
iFrame.attr('src', url)

I tried it with
iFrame.onload = ->
  $log.info 'iframe loaded'

Also
iFrame.on 'load', (event) ->
  $log.info 'iframe loaded'

I also tried to select the Iframe via its id and bind the load event on that. But also doesn't work.
Any ideas or suggestions?
best regards

A: try
app.controller('MainCtrl', () => {
  var iFrame = angular.element('<iframe id="blaba" height="200"/>')
  angular.element(document.body).append(iFrame);
  // onload bind here
  var url = 'test.txt';
  iFrame.attr('src', url);
  iFrame.on('load', event => console.log('IFRAME LOADED'))
});

plunker: https://plnkr.co/edit/XeaYCmG6L6NG2T1zaCfN?p=preview


text:
Q: Convert arrays to son like string of objects in Nodejs I have four arrays:
var attributes = ["a","b","c","d"];
var a = [1,2,3];
var b = [34,55,66];
var c = [22,23,53];
var d = [15,78,98];

How to merge them into one json like string in Nodejs?
[{"a":1,"b":34,"c":22,"d":14},
 {"a":2,"b":55,"c":23,"d":78},
 {"a":3,"b":66,"c":53,"d":98}]

Here is my code, but anyone have a better solution? I do need preserve the quote.

var a = [1,2,3];
var b = [34,55,66];
var c = [22,23,53];
var d = [15,78,98];

var obj = "[";
for (var u = 0; u < a.length; u++) {
  var l = "\"a\":"+a[u]+",";
  var m = "\"b\":"+b[u]+",";
  var q = "\"b\":"+c[u]+",";
  var n = "\"d\":"+d[u]+"";
  if(u == (a.length-1))
    var k = "{" + l + m + q + n + "}";
  else
    var k = "{" + l + m + q + n + "},";
  console.log(k);
  obj = obj + k;
};
obj = obj + "]";
console.log(obj);

A: Assuming all the arrays are the same length, and hardcoding their names:
   var obj = []
    for (var u = 0; u < a.length; u++) {
        obj.push({
            'a': a[u],
            'b': b[u],
            'c': c[u],
            'd': d[u]
        });
    };
    obj = JSON.stringify(obj);

EDIT:  Converted the obj into a json string, the question had been mistakenly edited to ask for an array.

A: This piece of code will do the trick:
var arrays = [a, b, c, d]; // add all the arrays you want
var num = a.length; // or hardcode to the length you want

var result = [];
for(var i = 0; i < num; i++) {
    var element = {};
    attributes.forEach(function(attr, index) {
        element[attr] = arrays[index][i];
    });
    result.push(element);
}

var attributes = ["a","b","c","d"];
var a = [1,2,3];
var b = [34,55,66];
var c = [22,23,53];
var d = [15,78,98];

var arrays = [a, b, c, d];
var result = [];
var num = a.length;
for(var i = 0; i < num; i++) {
    var element = {};
    attributes.forEach(function(attr, index) {
        element[attr] = arrays[index][i];
    });
    result.push(element);
}

document.write(JSON.stringify(result));

A: var attributes = ["a","b","c","d"];
var a = [1,2,3];
var b = [34,55,66];
var c = [22,23,53];
var d = [15,78,98];

var x = [];

for (var i=0;i<3;i++) {
  var obj = {};
  for (var j=0;j<attributes.length;j++){
    obj[attributes[j]]=eval(attributes[j]+"["+i+"]");
  }
  x.push(obj);
}
console.log(x);

A: I know there are multiple answers on this question already, but none seemed to handle the key arrays as variables who's names are introduced in the attributes array.  Since I assumed that was the point of the attribute array, my solution does just that using node's global scope.  It also does not assume that all the key arrays will be the same length as that is not specified (even though the example they are).
var attributes = ["a","b","c","d"];
var a = [1,2,3];
var b = [34,55,66];
var c = [22,23,53];
var d = [15,78,98];
var arr = [];
while(true){
    var obj = {};
    for(var i=0;i<attributes.length;i++){
    if(global[attributes[i]].length)obj[attributes[i]]=global[attributes[i]].shift();
  }
  if(Object.keys(obj).length)
    arr.push(obj);
  else
    break;
}

In the following fiddle, I had to emulate node's global scope by manually creating a global array, but you get the point:
Fiddle: https://jsfiddle.net/trex005/vm1yeL5d/
Important note If the arrays are not actually in the global scope, but are in some other object, you can use that object in place of global


text:
Q: Incorrect syntax near '10' SqlConnection con = new SqlConnection(str);
int ID;
ID = Int32.Parse(Combo_Stu.SelectedValue.ToString());
double a = double.Parse(Txt_Ins.Text);
string date = dtp_Stu.Value.ToString();
SqlCommand sqlcmd1 = new SqlCommand("INSERT INTO Instalment_Billing(ID,Pay_Date, Fees) VALUES (" + ID + "," + **date** + "," + a + ")", con);
con.Open();
sqlcmd1.ExecuteNonQuery();

Incorrect syntax near '10'
I am getting this error in date
guess pls help me

A: The problem is probably that your date is unquoted, but the real solution to this problem is to use a parameterized query.

A: Whenever you get an error in a line like:
SqlCommand sqlcmd1 = new SqlCommand("INSERT INTO Instalment_Billing(" +
    "ID,Pay_Date, Fees) VALUES (" + ID + "," + date + "," + a + ")", con);

you should immediately insert some code to print it out and check whether it's valid SQL:
Console.WriteLine ("INSERT INTO Instalment_Billing(" +
    "ID,Pay_Date, Fees) VALUES (" + ID + "," + date + "," + a + ")");

or:
System.Windows.Forms.MessageBox.Show("INSERT INTO Instalment_Billing" +
    "(ID,Pay_Date, Fees) VALUES (" + ID + "," + date + "," + a + ")");

This should show you exactly where your problem lies. Most likely insertions of dates should use strings of the format 'yyyy.mm.dd' or something similar so you should, at a bare minimum:

*

*quote the date string (... + ",'" + date + "'," + ...).

*ensure that its format is okay (I'm not sure what ToString() will give you off the top of my head but I would think, given that you posted this today and it's not the tenth month or tenth day of the month, that it's probably something like yy-mm-dd and the unquoted 10 from 2010 is causing you grief).


text:
Q: Scroll page by roll click on very hight page - not working correctly https://y2z8w0l0vz.codesandbox.io/
I have div, and child div:

When I try scroll page, by click middle, roll click, scrolling doesn't work always.
I noticed that scrolling on the page doesn't work
correctly, when the page is scrolls to the middle of 'height'. If I scroll page when is scrolls on top, scrolling working.
This problem is on Chrome, Yandex (chrome engine), on Firefox scrolling work good on all 'height' of page.
how I can resolve this strange problem with scrolling?


text:
Q: Cyclic Reference issue with includes for friend class I have 2 classes: S and R. R has an intance of type S. I want to have R as friend class to have acces to S private methods.
Unfortunately I couldn't build it. Please help me how can I solve this. I tried forward declaration in more ways but it didn't work. I get the following error

R.hpp:12:15: error: 'n1::n2' has not been declared
  12 |         R(n1::n2::Sptr s);

Thanks a lot in advance!.
S.hpp:
#ifndef S_H
#define S_H
#include <memory>

namespace n1 {
  namespace n2  {
    class S  {
      friend class c1::R;
      int x;
      inline void print();
    };

    using Sptr = std::shared_ptr<S>;
  }
}

#endif

S.cpp:
#include "S.hpp"
#include "R.hpp"
namespace n1 {
  namespace n2 {
    void S::print()
    {
      std::cout<<"S-print\n";
    }
  }
}

R.hpp:
#ifndef R_H
#define R_H
#include <memory>

namespace n1  {
  namespace c1 {
    class S;
    struct R {
      R(n1::n2::Sptr s);
      void r();
      n1::n2::Sptr s_;
    };
  }
}
#endif

R.cpp:
#include "R.hpp"
#include "S.hpp"

namespace n1 {
  namespace c1 {
    R::R(n1::n2::Sptr s):s_(s)
    {}

    void R::r() {
      s_->print();
    }
  }
}

main.cpp:
#include <iostream>
#include "R.hpp"
#include "S.hpp"
#include <memory>

int main() {
  auto s = std::make_shared<n1::n2::S>();
  auto r = std::make_shared<n1::c1::R>(s);
  r->r();
  //s.print();

  return 0;
}

A: You can get the program to work(compile) by using the following modifications in your files:
S.hpp
#ifndef S_H
#define S_H
#include <memory>
 namespace n1
 {
     namespace c1
     {
         class R;
     }
 }
namespace n1 {
  namespace n2  {
    class S  {
      friend class c1::R;
      int x;
       void print();
    };

  //  using Sptr = std::shared_ptr<S>;
  }
}

#endif

S.cpp
#include "S.hpp"
//#include "R.hpp"
#include <iostream>
namespace n1 {
  namespace n2 {
    void S::print()
    {
      std::cout<<"S-print\n";
    }
  }
}

R.hpp
#ifndef R_H
#define R_H
#include <memory>
 namespace n1
 {
     namespace n2
     {
           class S;
           using Sptr = std::shared_ptr<S>;
     }
 }
namespace n1  {
  namespace c1 {
    class S;
    struct R {
      R(n1::n2::Sptr s);
      void r();
      n1::n2::Sptr s_;
    };
  }
}
#endif

R.cpp
#include "R.hpp"
#include "S.hpp"

namespace n1 {
  namespace c1 {
    R::R(n1::n2::Sptr s):s_(s)
    {}

    void R::r() {
      s_->print();
    }
  }
}

The output of the above program can be seen here.

A: *

*Remove all cross header file includes. (you appear to have done this)

*Replace missing symbols with forward declarations in the header.

*Add header file includes removed into cpp files. (you appear to have done this)

*Redefine the shared_ptr alias when you need it.


text:
Q: Why does "require" behave differently when I am in the same directory or a parent directory? While testing some code I came across a situation that I can not explain.  After hours of googling I couldn't really figure out the right questions to ask.  Any help in the right direction or the correct terminology would be appreciated..!
So,.. When I require a file that is located in the same working directory, I am able to do the fallowing:
const { ports, keys } = require('./activeConfig');
console.log(ports, keys, activeConfig);

In this situation ports, keys, and activeConfig are all defined and i can use the module as if I had done:
const { ports, keys } = require('./activeConfig');
const activeConfig = require('./activeConfig');
console.log(ports, keys, activeConfig);

However if I try to do the exact same thing from an external directory like so:
const { ports, keys } = require('../../config/activeConfig');

or
const { ports, keys } = require('./config/activeConfig');

activeConfig is no longer defined and I get an error.
Why is this behavior different depending on the location that I am importing from? Or does this have to do with the way I am exporting the module?
I would like to keep my code nice and tidy, so I would prefer to avoid having to write the second require.  Is there perhaps a different method to do this all in one line?
The module I am trying to require is a Singleton with the fallowing code:
const database = {...}
const keys = {...}
const ports = {...}
const tokens = {...}

module.exports = activeConfig = (() => {
    let _database = database;
    let _keys = keys;
    let _ports = ports;
    let _tokens = tokens;

    return {
        setDatabase: (value) => {
            if (value) {...}
            return activeConfig;
        },
        setKeys: (value) => {
            if (value) {...}
            return activeConfig;
        },
        setPorts: (value) => {
            if (value) {...}
            return activeConfig;
        },
        setTokens: (value) => {
            if (value) {...}
            return activeConfig;
        },
        updateConfig: () => {
               ...
            return activeConfig;
        },
        get database() {
            return _database;
        },
        get keys() {
            return _keys;
        },
        get ports() {
            return _ports;
        },
        get tokens() {
            return _tokens;
        },
        set database(value) {...},
        set keys(value) {...},
        set ports(value) {...},
        set tokens(value) {...}
    };
})();

A: What is happening is that your activeConfig module is declaring an implicit global variable.
The line:
module.exports = activeConfig = (() => { //...

This will leak the variable activeConfig to the global scope when you first require the module.
Afterwards, when you require the module again in other places, NodeJS will simply pull the previously exported object form the cache, and it won't execute the assignment.
Try running your code in strict mode, add "use strict" at the top of activeConfig.js and you will see that it won't let you leak the global variable.
Leaking globals is bad, I would instead recommend you to put a reference to the same instance in the object you export, so it can be "destructured" when you require it.
For example:
"use strict"
module.exports = (() => {
    // ....
    return {
       // ....
        get instance() {
            return this;
        },
    };
})();

And then when you require it:
const { ports, keys, instance: activeConfig } = require('./config/activeConfig');


text:
Q: Programmable ftp server We have a need to set up a ftp server. Many clients will upload files regularly. Each client will use a different ftp account. We will be called by an external system to provision a new client - we can either take username/password from the external aystem or generate them and pass them back. We will probably want to create a directory per client for them to upload files.
When a client uploads a file, we want to be notified, process the file, and pass it on to another external system (then rename or otherwise identify the file as processed)
So I am after suggestions for a ftp server that can have accounts added programmatically. Ideally, it would also handle the directories and new-upload notifications, but we can do these in other ways.
This would be on Red Hat Linux (ideally), or Solaris is an option.

A: Google says RedHat 9 Comes with vsftpd installed.
https://security.appspot.com/vsftpd.html


text:
Q: python test string escaped chars still exist after printing i have a function that does something like
def foo():
    return ["echo", "-e", "this\nis\nmultiline"]

this is written to a .sh file to be executed at some point and i would like to do a unitest to check that the string still has the \n in the last argument, and that it hasn't been written as
echo -e this
is
multiline

I don't know how to evaluate the string so that i get the post-print representation.
i know i could write it out, read it and check if it's correct, but it seems like unitesting really doesn't like that approach.
what would be the way of doing this?  (using python 2.7, preferably)

A: use string's function splitlines
a = "1\n2\n3"
b = r"1\n2\n3"
c = "1\\n2\\n3"

len(a.splitlines()) # 3
len(b.splitlines()) # 1
len(c.splitlines()) # 1


text:
Q: How to read a matrix from standard input in python I'm trying to read a matrix or a 2D array from standard input.
For example:
my_array = [[1, 2, 3], [1, 2, 3]]

How can I read this matrix in standard input using the stdarray or stdio modules?

A: >>> x = input("Enter Array:")
Enter Array:[[1,2,3],[4,5,6]]
>>> x
[[1, 2, 3], [4, 5, 6]]
>>> x[0]
[1, 2, 3]
>>> x[1][1]
5


text:
Q: Stripe Proration - Pay Upfront? Problem:
I had my first user upgrade to a higher priced subscription plan, under the proration settings, the user is set to be charged a higher amount next month ($84.95 instead of $67).
Question:
How can I charge the user the difference ($17.95) upfront, so they are charged this amount when they press upgrade, and then on the next billing cycle get charged just the normal amount ($67)
Is there an option to enable this in Stripe?

A: As ceejayoz mentioned, the solution here is to generate a one off invoice right after the upgrade.
Generating a one-off invoice pulls in any pending invoice items that would have been added to the regularly scheduled invoice.


text:
Q: Reverse engineering an NSMenu for a Status Bar Item I'm want to create a menu for a status bar item like the one seen in Tapbot's PastebotSync application:

Does anyone have any ideas how to achieve the custom area at the top of the menu which is flush with the top?
I've tried/thought of a few potential ways of doing it:

*

*Standard NSMenuItem with a view - isn't flush with the top of the menu

*Some hack-ish code to place an NSWindow over the area at the top of the menu - not great as it doesn't fade out nicely with the menu when it closes

*Abandoning an NSMenu entirely and using an NSView instead - haven't tried this yet but I don't really want to have to make some fake buttons or something that act as NSMenuItems

Anyone have any better ideas or suggestions?
Thanks!

A: In case anyone comes looking, I posted a solution to this at Gap above NSMenuItem custom view
Here's the code:
@interface FullMenuItemView : NSView
@end

@implementation FullMenuItemView
- (void) drawRect:(NSRect)dirtyRect
{
    NSRect fullBounds = [self bounds];
    fullBounds.size.height += 4;
    [[NSBezierPath bezierPathWithRect:fullBounds] setClip];

    // Then do your drawing, for example...
    [[NSColor blueColor] set];
    NSRectFill( fullBounds );
}
@end

Use it like this:
CGFloat menuItemHeight = 32;

NSRect viewRect = NSMakeRect(0, 0, /* width autoresizes */ 1, menuItemHeight);
NSView *menuItemView = [[[FullMenuItemView alloc] initWithFrame:viewRect] autorelease];
menuItemView.autoresizingMask = NSViewWidthSizable;

yourMenuItem.view = menuItemView;

A: I had the same need in early versions of HoudahSpot 2. I did get it working with one limitation: my code leaves the menu with square corners at the bottom.
I have since abandonned this setup, as the BlitzSearch feature in HoudahSpot grew to need a complexer UI, I ran into other limitations with using NSViews in a NSMenu.
Anyway, here is the original code taking care of those extra 3 pixels:
- (void)awakeFromNib
{
 HIViewRef contentView;
 MenuRef menuRef = [statusMenu carbonMenuRef];
 HIMenuGetContentView (menuRef, kThemeMenuTypePullDown, &contentView);

 EventTypeSpec hsEventSpec[1] = {
  { kEventClassMenu, kEventMenuCreateFrameView }
 };

 HIViewInstallEventHandler(contentView,
          NewEventHandlerUPP((EventHandlerProcPtr)hsMenuCreationEventHandler),
          GetEventTypeCount(hsEventSpec),
          hsEventSpec,
          NULL,
          NULL);
}

#pragma mark -
#pragma mark Carbon handlers

static OSStatus hsMenuContentEventHandler( EventHandlerCallRef caller, EventRef event, void* refcon )
{
 OSStatus  err;

 check( GetEventClass( event ) == kEventClassControl );
 check( GetEventKind( event ) == kEventControlGetFrameMetrics );

 err = CallNextEventHandler( caller, event );
 if ( err == noErr )
 {
  HIViewFrameMetrics  metrics;

  verify_noerr( GetEventParameter( event, kEventParamControlFrameMetrics, typeControlFrameMetrics, NULL,
          sizeof( metrics ), NULL, &metrics ) );

  metrics.top = 0;

  verify_noerr( SetEventParameter( event, kEventParamControlFrameMetrics, typeControlFrameMetrics,
          sizeof( metrics ), &metrics ) );
 }

 return err;
}

static OSStatus hsMenuCreationEventHandler( EventHandlerCallRef caller, EventRef event, void* refcon )
{
 OSStatus  err = eventNotHandledErr;

 if ( GetEventKind( event ) == kEventMenuCreateFrameView)
 {
  err = CallNextEventHandler( caller, event );
  if ( err == noErr )
  {
   static const EventTypeSpec  kContentEvents[] =
   {
    { kEventClassControl, kEventControlGetFrameMetrics }
   };

   HIViewRef          frame;
   HIViewRef          content;

   verify_noerr( GetEventParameter( event, kEventParamMenuFrameView, typeControlRef, NULL,
           sizeof( frame ), NULL, &frame ) );
   verify_noerr( HIViewFindByID( frame, kHIViewWindowContentID, &content ) );
   HIViewInstallEventHandler( content, hsMenuContentEventHandler, GetEventTypeCount( kContentEvents ),
            kContentEvents, 0, NULL );
  }
 }

 return err;
}

Sorry, I forgot that bit:
- (MenuRef) carbonMenuRef
{
    MenuRef carbonMenuRef = NULL;

    if (carbonMenuRef == NULL) {
        extern MenuRef _NSGetCarbonMenu(NSMenu *);
        carbonMenuRef = _NSGetCarbonMenu(self);

        if (carbonMenuRef == NULL) {
            NSMenu *theMainMenu = [NSApp mainMenu];
            NSMenuItem *theDummyMenuItem = [theMainMenu addItemWithTitle: @"sub"  action: NULL keyEquivalent: @""];

            if (theDummyMenuItem != nil) {
                [theDummyMenuItem setSubmenu:self];
                [theDummyMenuItem setSubmenu:nil];
                [theMainMenu removeItem:theDummyMenuItem];

                carbonMenuRef = _NSGetCarbonMenu(self);
            }
        }
    }

    if (carbonMenuRef == NULL) {
        extern MenuRef _NSGetCarbonMenu2(NSMenu *);
        carbonMenuRef = _NSGetCarbonMenu2(self);
    }

    return carbonMenuRef;
}


text:
Q: Get target style from Javascript while transitioning During a transition, is there a way to see what the target value is for a style rule which is under transition?  window.getComputedStyle gets the interpolated value, and element.style only looks at the style attribute (I think).
Here's a demo of the problem;
I'd like to retrieve the target height value of 1200px during the transition:
https://jsfiddle.net/EoghanM/xz5s3ua6/5/

setInterval(function() {
  document.body.children[0].innerHTML = getComputedStyle(document.body.children[0])['height']
}, 300)

setTimeout(function() {
  document.body.children[0].classList.toggle('changing')
}, 1000)
div {
  height: 400px;
  border: 1px solid red;
  width: 200px;
  transition: height 100s linear;
}

div.changing {
  height: 1200px;
}

A: How about using getComputedStyle on a new instance of changing class?
You can create a div with the class changing and then use getComputedStyle to get the class properties (considering that the height of changing class will be the final height after the transition of your div) like this:

and get it's properties:
const element = document.querySelector('#new-changing-div');
const heightAttribute = window.getComputedStyle(element).getPropertyValue('height');

A: I'm 99% sure all of the DOM properties and methods for requesting the element's height (clientHeight, offsetHeight, getBoundingClientRect, etc.) will only give you the interpolated value. Another solution may be to read the value from the CSS stylehseet itself using the CSSOM.
In the code below, we search through the document's stylesheets checking if the selector exists in a rule declaration and if it does, return the value of the property we're looking for. You can console.log() various parts of the stylesheets and rules below to see how the browser stores the information as objects.
Of course this is a simple example based on a simple test case. There could be multiple rules using the same selector, but this will only find the first occurrence. The solution would need to be more robust to find the exact rule you're looking for.

function getCssRuleValue(selector, property) {
  const styleSheets = document.styleSheets;

  let styleSheetsLen = styleSheets.length;

  while (styleSheetsLen--) {
    const styleSheet = styleSheets[styleSheetsLen];
    const rules = styleSheet.rules;

    let rulesLen = rules.length;

    while (rulesLen--) {
      const rule = rules[rulesLen];

      // The passed-in selector text is found in the rule text
      if (rule.cssText.indexOf(selector) > -1) {
        return rule.style[property];
      }
    }
  }

  // The selector/property was not found in any document stylesheets
  return -1;
}

setInterval(function() {
  document.body.children[0].innerHTML =
    getComputedStyle(document.body.children[0])['height']
    + '
' +
    getCssRuleValue('.changing', 'height')
}, 300)

setTimeout(function() {
  document.body.children[0].classList.toggle('changing')
}, 1000)
div {
  height: 400px;
  border: 1px solid red;
  width: 200px;
  transition: height 100s linear;
}

div.changing {
  height: 1200px;
}


text:
Q: Can't add to an ArrayList "misplaced construct(s)" I have a simple arraylist set up, but I can't seem to add objects to it.
import java.util.ArrayList;

public class Inventory {

ArrayList inventory = new ArrayList();

String item1 = "Sword";
String item2 = "Potion";
String item3 = "Shield";

inventory.add(item1);
inventory.add(item2);
inventory.add(item3);
}

There are two errors, one at the dot between inventory and add, and one at the variable names between the brackets, being
Syntax error on token(s), misplaced construct(s)

and
Syntax error on token "item1", VariableDeclaratorId expected after this token

Can anyone explain why this is happening?

A: In Java, you cannot have executable statements, such as invocations of the add method, outside a definition of a method or a constructor. Declarations are OK, but executable statements are not.
You can add these items to a named constructor, but you can also use an anonymous initialization block, like this:
public class Inventory {

    ArrayList inventory = new ArrayList();

    {   // An anonymous initialization block
        String item1 = "Sword";
        String item2 = "Potion";
        String item3 = "Shield";

        inventory.add(item1);
        inventory.add(item2);
        inventory.add(item3);
    }
}

If you use a block like that, it would be shared among all named constructors of the class, or it would become part of the implicitly generated constructor for the Inventory.

A: Your "adding" statements are just "in the air":  not inside one method or constructor.
Wrap in inside one like for instance:
public class Inventory {

   private List inventory = new ArrayList();  //prefer interface here ;)

   public Inventory(){   //statements wrap into this constructor
      inventory.add("Sword");
      inventory.add("Potion");
      inventory.add("Shield");
   }
}

A: Non declaring code has to be in a block statement like the main method.
If you would like to run the code e.g. in Eclipse with a debugger with right mouse click on the class and choosing Debug as/Java Application you could do it like this:
import java.util.ArrayList;

public class Inventory {

private List<String> inventoryItems = new ArrayList<String>();

public Inventory(){
    String item1 = "Sword";
    String item2 = "Potion";
    String item3 = "Shield";

    inventoryItems.add(item1);
    inventoryItems.add(item2);
    inventoryItems.add(item3);
}

public static void main(String[] args) {
    Inventory theInventory = new Inventory();
}

}

This way you can set a break point at the left border of the Eclipse editing area and step through the code.
Edit: As it looks to me like Adam experiments with the code I provided a solution that makes experimenting easier.

A: A more general answer would be that the class body is about declarations, not statements. There is special provision for statements occurring in class body, but they have to be marked explicitly as either class initializers or instance initializers.
As the assignments are statements and statements are allowed only inside blocks of code(methods, constructors, static initializers, etc.).
So you can do as below,
public class Inventory {

ArrayList inventory = new ArrayList();

String item1 = null;
String item2 = null;
String item3 = null;

//initializer block
{
item1="Sword";
item2="Potion";
item3="Shield";

inventory.add(item1);
inventory.add(item2);
inventory.add(item3);
}

A: The reason why your code does not work is that you tried to write code in the class body. Executable statements should be written in static initializers, methods or constructors (as I did in the example below).
Try this:
public class Inventory {

    private List inventory = new ArrayList();

    public Inventory() {

        String item1 = "Sword";
        String item2 = "Potion";
        String item3 = "Shield";

        inventory.add(item1);
        inventory.add(item2);
        inventory.add(item3);
    }
}

I defined the class member inventory in the class body and initialized it in-place (= new ArrayList();). No compiler error there because declarations are allowed in class body. The rest of the code I put into the constructor that will initialize inventory with values. I could have put it in a method, but I chose the constructor because its usual role is to initialize class members.


text:
Q: Does the JIRA REST API have a limitation with number of JIRA ids in the JQL search? I am running a request against the JIRA REST API and I am getting an error:
 Response status code does not indicate success: 400 (Bad Request).

I am thinking it has to do with a maximum number of items that can be in the JQL search query.
My query looks something like this:
search?jql=issue+in+('PROJ-741','PROJ-724','PROJ-851','PROJ-854','PROJ-856','PROJ-857','PROJ-980','PROJ-1133','PROJ-1132','PROJ-1071','PROJ-852','PROJ-727','PROJ-725','PROJ-853','PROJ-726','PROJ-434','PROJ-436','PROJ-433','PROJ-734','PROJ-733','PROJ-732','PROJ-182','PROJ-174','PROJ-173','PROJ-133','PROJ-301','PROJ-300','PROJ-281','PROJ-266','PROJ-253','PROJ-293','PROJ-287','PROJ-284','PROJ-276','PROJ-271','PROJ-262','PROJ-248','PROJ-214','PROJ-322','PROJ-323','PROJ-310','PROJ-332','PROJ-399','PROJ-600','PROJ-346','PROJ-389','PROJ-409','PROJ-521','PROJ-505','PROJ-490','PROJ-432','PROJ-486','PROJ-464','PROJ-438','PROJ-566','PROJ-534','PROJ-471','PROJ-178','PROJ-240','PROJ-210','PROJ-205','PROJ-655','PROJ-427','PROJ-419','PROJ-422','PROJ-426','PROJ-441','PROJ-442','PROJ-193','PROJ-194','PROJ-197','PROJ-195','PROJ-196','PROJ-513','PROJ-198','PROJ-514','PROJ-199','PROJ-516','PROJ-515','PROJ-200','PROJ-517','PROJ-201','PROJ-441','PROJ-188','PROJ-190','PROJ-189','PROJ-191','PROJ-192','PROJ-134','PROJ-213','PROJ-217','PROJ-219','PROJ-238','PROJ-237','PROJ-239','PROJ-221','PROJ-330','PROJ-418','PROJ-119','PROJ-463','PROJ-789','PROJ-331','PROJ-837','PROJ-959','PROJ-864','PROJ-957','PROJ-787','PROJ-445','PROJ-476','PROJ-786','PROJ-790','PROJ-791','PROJ-792')&startAt=0&maxResults=900&fields=labels,assignee,components,id,key,created,resolutiondate,customfield_10100,summary,issuetype,status,priority
I could try to batch these up into multiple queries, but I first wanted to see if there was any documented limit (I couldn't find anything mentioned in the documentation).

A: There is no restriction on the JQL queries and fields has been mentioned within Atlassian Documentation.
But if the Query is too large to be encoded as a Query Param then you should instead POST to this resource.
Your JQL has used some reserved characters hence it is returning 400 Error.
I have corrected your Query which compiles correctly and returns 200 status.
Here it is:
search?jql=issue%20in%20('PROJ-741'%2C'PROJ-724'%2C'PROJ-851'%2C'PROJ-854'%2C'PROJ-856'%2C'PROJ-857'%2C'PROJ-980'%2C'PROJ-1133'%2C'PROJ-1132'%2C'PROJ-1071'%2C'PROJ-852'%2C'PROJ-727'%2C'PROJ-725'%2C'PROJ-853'%2C'PROJ-726'%2C'PROJ-434'%2C'PROJ-436'%2C'PROJ-433'%2C'PROJ-734'%2C'PROJ-733'%2C'PROJ-732'%2C'PROJ-182'%2C'PROJ-174'%2C'PROJ-173'%2C'PROJ-133'%2C'PROJ-301'%2C'PROJ-300'%2C'PROJ-281'%2C'PROJ-266'%2C'PROJ-253'%2C'PROJ-293'%2C'PROJ-287'%2C'PROJ-284'%2C'PROJ-276'%2C'PROJ-271'%2C'PROJ-262'%2C'PROJ-248'%2C'PROJ-214'%2C'PROJ-322'%2C'PROJ-323'%2C'PROJ-310'%2C'PROJ-332'%2C'PROJ-399'%2C'PROJ-600'%2C'PROJ-346'%2C'PROJ-389'%2C'PROJ-409'%2C'PROJ-521'%2C'PROJ-505'%2C'PROJ-490'%2C'PROJ-432'%2C'PROJ-486'%2C'PROJ-464'%2C'PROJ-438'%2C'PROJ-566'%2C'PROJ-534'%2C'PROJ-471'%2C'PROJ-178'%2C'PROJ-240'%2C'PROJ-210'%2C'PROJ-205'%2C'PROJ-655'%2C'PROJ-427'%2C'PROJ-419'%2C'PROJ-422'%2C'PROJ-426'%2C'PROJ-441'%2C'PROJ-442'%2C'PROJ-193'%2C'PROJ-194'%2C'PROJ-197'%2C'PROJ-195'%2C'PROJ-196'%2C'PROJ-513'%2C'PROJ-198'%2C'PROJ-514'%2C'PROJ-199'%2C'PROJ-516'%2C'PROJ-515'%2C'PROJ-200'%2C'PROJ-517'%2C'PROJ-201'%2C'PROJ-441'%2C'PROJ-188'%2C'PROJ-190'%2C'PROJ-189'%2C'PROJ-191'%2C'PROJ-192'%2C'PROJ-134'%2C'PROJ-213'%2C'PROJ-217'%2C'PROJ-219'%2C'PROJ-238'%2C'PROJ-237'%2C'PROJ-239'%2C'PROJ-221'%2C'PROJ-330'%2C'PROJ-418'%2C'PROJ-119'%2C'PROJ-463'%2C'PROJ-789'%2C'PROJ-331'%2C'PROJ-837'%2C'PROJ-959'%2C'PROJ-864'%2C'PROJ-957'%2C'PROJ-787'%2C'PROJ-445'%2C'PROJ-476'%2C'PROJ-786'%2C'PROJ-790'%2C'PROJ-791'%2C'PROJ-792')&maxResults=900&fields=labels%2Cassignee%2Ccomponents%2Cid%2Ckey%2Ccreated%2Cresolutiondate%2Ccustomfield_10100%2Csummary%2Cissuetype%2Cstatus%2Cpriority


text:
Q: awk to remove duplicate rows totally based on a particular column value I got a dataset like:
6   AA_A_56_30018678_E  0   30018678    P   A
6   SNP_A_30018678  0   30018678    A   G
6   SNP_A_30018679  0   30018679    T   G
6   SNP_A_30018682  0   30018682    T   G
6   SNP_A_30018695  0   30018695    G   C
6   AA_A_62_30018696_Q  0   30018696    P   A
6   AA_A_62_30018696_G  0   30018696    P   A
6   AA_A_62_30018696_R  0   30018696    P   A

I want to remove all the rows if col 4 have duplicates.
I have use the below codes (using sort, awk,uniq and join...) to get the required output, however, is there a better way to do this?
sort -k4,4 example.txt | awk '{print $4}' | uniq -u  > snp_sort.txt

join -1 1 -2 4 snp_sort.txt example.txt | awk '{print $3,$5,$6,$1}' > uniq.txt

Here is the output
SNP_A_30018679  T   G   30018679
SNP_A_30018682  T   G   30018682
SNP_A_30018695  G   C   30018695

A: Using awk to filter-out duplicate lines and print those lines which occur exactly once.
awk '{k=($2 FS $5 FS $6 FS $4)} {a[$4]++;b[$4]=k}END{for(x in a)if(a[x]==1)print b[x]}' input_file

SNP_A_30018682 T G 30018682
SNP_A_30018695 G C 30018695
SNP_A_30018679 T G 30018679

The idea is to:-

*

*Store all unique $4 entries in a an array(a) and maintain a counter for that in array b

*Print the array for those entries which occur exactly once.

A: Using command substitution:  First print only unique columns in fourth field and then grep those columns.
grep "$(echo  "$(awk '{print $4}' inputfile.txt)" |sort |uniq -u)" inputfile.txt
6   SNP_A_30018679  0   30018679    T   G
6   SNP_A_30018682  0   30018682    T   G
6   SNP_A_30018695  0   30018695    G   C

Note: add awk '{NF=4}1' at the end of the command, if you wist to print first four columns. Of course you can change the number of columns by changing value of $4 and NF=4.

A: $ awk 'NR==FNR{c[$4]++;next} c[$4]<2' file file
6   SNP_A_30018679  0   30018679    T   G
6   SNP_A_30018682  0   30018682    T   G
6   SNP_A_30018695  0   30018695    G   C

A: Since your 'key' is fixed width, then uniq has a -w to check on it.
sort -k4,4 example.txt | uniq -u -f 3 -w 8  > uniq.txt

A: Another in awk:
$ awk '{$1=$1; a[$4]=a[$4] $0} END{for(i in a) if(gsub(FS,FS,a[i])==5) print a[i]}' file
6 SNP_A_30018679 0 30018679 T G
6 SNP_A_30018682 0 30018682 T G
6 SNP_A_30018695 0 30018695 G C

Catenate to array using $4 as key. If there are more than 5 field separators, duplicates were catenated and will not be printed.
And yet an another version in awk. It expects the file to be sorted on the fourth field. It won't store all lines in memory, only the keys (this probably could be dealt with also since the key field must be sorted, may be fixed later) and runs in one go:
$ cat ananother.awk
++seen[p[4]]==1 && NR>1 && p[4]!=$4 {  # seen count must be 1 and
    print prev                         # this and previous $4 must differ
    delete seen                        # is this enough really?
}
{
    q=p[4]                             # previous previous $4 for END
    prev=$0                            # previous is stored for printing
    split($0,p)                        # to get previous $4
}
END {                                  # last record control
    if(++seen[$4]==1 && q!=$4)
        print $0
}

Run:
$ sort -k4,4 file | awk -f ananother.awk

A: A simpler way to achieve this,
cat file.csv | cut -d, -f3,5,6,1 | sort -u > uniq.txt


text:
Q: C#-The variable name '@startdate' has already been declared.Variable names must be unique a query batch or stored procedure I need a way to update a cell in my datagridview and save it to database using queries but I'm getting this exception:

The variable name '@startdate' has already been declared.Variable
  names must be unique a query batch or stored procedure

Here is my code:
private void toolStripLabel1_Click(object sender, EventArgs e)
{
    try
    {
        conn.Open();
        string query2 = "UPDATE [Semester] SET [Start_Date]=@startdate, " +
                        " [End_Date]=@enddate WHERE [Sem_Num]=@sem";
        cmd = new SqlCommand(query2, conn);
        if (dataGridView1.Rows.Count > 0)
        {
            for (int i = 0; i < dataGridView1.Rows.Count; i++)
            {
                cmd.Parameters.AddWithValue("@startdate",
                                       dataGridView1.Rows[i].Cells[1].Value.ToString());
                cmd.Parameters.AddWithValue("@enddate",
                                       dataGridView1.Rows[i].Cells[2].Value.ToString());
                cmd.Parameters.AddWithValue("@sem",
                                  Convert.ToInt32(dataGridView1.Rows[i].Cells[0].Value));
                this.dataGridView1.EndEdit();
                cmd.ExecuteNonQuery();

            }
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
    finally
    {
        conn.Close();
    }
}

A: Clear the parameters in each iteration:
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
    cmd.Parameters.Clear();
    cmd.Parameters.AddWithValue("@startdate", dataGridView1.Rows[i].Cells[1].Value.ToString());
    cmd.Parameters.AddWithValue("@enddate", dataGridView1.Rows[i].Cells[2].Value.ToString());
    cmd.Parameters.AddWithValue("@sem", Convert.ToInt32(dataGridView1.Rows[i].Cells[0].Value));
    this.dataGridView1.EndEdit();
    cmd.ExecuteNonQuery();

}

Or define parameters outside the loop and set the value inside of it:
var startParam = cmd.Parameters.Add("@startdate", SqlDbType.DateTime2);
var endParam = cmd.Parameters.Add("@enddate", SqlDbType.DateTime2);
var semParam = cmd.Parameters.Add("@sem", SqlDbType.Int);

for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
    startParam.Value = Convert.ToDateTime(dataGridView1.Rows[i].Cells[1].Value);
    endParam.Value = Convert.ToDateTime(dataGridView1.Rows[i].Cells[2].Value);
    semParam.Value = Convert.ToInt32(dataGridView1.Rows[i].Cells[0].Value);
    cmd.ExecuteNonQuery();
}

A: You're adding new parameters to the same command every time you run through the loop.
You need to either clear the parameters or make a new command.


text:
Q: how to Mail a filled up form to an email address using PHP? I am trying to send a filled up form to a particular email address. But I have no Idea about it. I know a little PHP coding and as far I have studied online I found that PHP already have a mail() function. but that also have some problems. although most of that I did not understood properly.
here is the things I want to do:

*

*I want to send the filled up form to the particular email address.

*I want to send that filled up form to my mobile phone so that i can reply immediately.

*I want to send that mail to my inbox only (not spam pr junk).

I am requesting everyone to give me a details information about how I can do so.
thanks in advance..

A: You can simply use php mail function with all the parameters
for example
mail ( $to ,$subject ,  $message,  $headers );
Where $to, $subject, $message are php variables to contains their respective values.
as you are posting data from the form so you can make $message from form.
like
$message =  $_POST['FORM_FIELD_NAME'];
and $headers you set according to your requirement. For example
$headers  = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= 'From: My Name <myemail@address.com>' . "\r\n";

A: Use PHPMailer to send mails in PHP
http://phpmailer.worxware.com/
PHPMailer wiki page:
https://code.google.com/a/apache-extras.org/p/phpmailer/wiki/UsefulTutorial
Use can use Gmail, Live or any other SMTP server to send mails
Code:
<?php

require("class.phpmailer.php");

$mail = new PHPMailer();

$mail->IsSMTP();  // telling the class to use SMTP
$mail->Host     = "smtp.example.com"; // SMTP server

$mail->From     = "from@example.com";
$mail->AddAddress("myfriend@example.net");

$mail->Subject  = "First PHPMailer Message";
$mail->Body     = "Hi! \n\n This is my first e-mail sent through PHPMailer.";
$mail->WordWrap = 50;

if(!$mail->Send()) {
  echo 'Message was not sent.';
  echo 'Mailer error: ' . $mail->ErrorInfo;
} else {
  echo 'Message has been sent.';
}

?>

A: it can help you..
<?php

require("class.phpmailer.php");

$mail = new PHPMailer();

$mail->IsSMTP();  // telling the class to use SMTP
$mail->Host     = "smtp.example.com"; // SMTP server

$mail->From     = "from@example.com";
$mail->AddAddress("id@example.net");

$mail->Subject  = "First PHPMailer Message";
$mail->Body     = "Hi! \n\n This is my first e-mail sent through PHPMailer.";
$mail->WordWrap = 50;

if(!$mail->Send()) {
  echo 'Message was not sent.';
  echo 'Mailer error: ' . $mail->ErrorInfo;
} else {
  echo 'Message has been sent.';
}
?>


text:
Q: Java Thread , How it comes the answer is A? The question is from http://www.javacertifications.net/javacert/scjp1.6Mock.jsp
Questions no -20
What is the output for the below code ?
public class Test extends Thread
{
    static String sName = "good";
    public static void main(String argv[])
    {
        Test t = new Test();
        t.nameTest(sName);
        System.out.println(sName);
    }
    public void nameTest(String sName)
    {
        sName = sName + " idea ";
        start();
    }
    public void run()
    {
        for(int i=0;i  <  4; i++)
        {
            sName = sName + " " + i;

        }
    }
}

options
    A)good
    B)good idea
    C)good idea good idea
    Correct answer is : A
Explanations : Change value in local methods wouldn't change in global in case of String ( because String object is immutable).

A: None of the answers are correct, and there is no single correct answer.
The Question is very bad because it mixes two entirely separate problems:

*

*The sName parameter of the nameTest() method hides the static variable of the same name, and changes to the local variable have no effect.

*The nameTest() starts a thread which changes the static variable in its run() method, and the main() method prints the variable without waiting for that thread to finish. This is known as a race condition: it's pretty much coincidence which state of the variable will be printed - any of the following is possible:

*

*good

*good 0

*good 0 1

*good 0 1 2

*good 0 1 2 3

A: Note that method nameTest has a parameter String sName, which effectively shadows the static class member with the same name. So the line
sName = sName + " idea ";

refers to and modifies the local method parameter instead of the static class member. To access the class member from within the method, it should be qualified with the class name, i.e. Test.sName.
In the run method, the static sName member is modified, though, so eventually it becomes something like "good 0 1 2 3". However, there is a race condition between the main thread which (implicitly) starts the thread t then prints the value of sName, and the child thread which modifies the same value. Since there is no synchronization involved, it is entirely possible that the main thread prints the value before it is modified by the other thread (i.e. "good"). The outcome could also be "good 0", "good 0 1" etc. However, of all these, only "good" is listed. So A is the only possible answer.

A: The answer is at this method:
public void nameTest(String sName){
        sName = sName + " idea ";
         start();
}

There, the assignation on sName is referred to the input parameter sName, and not to the static value Test.sName.
So, when at the run() method you access the static member, you will get the initial value ("good")

A: The method nameTest is modifying the local parameter sName instead of the static parameter. hence the output is "Good".
For modifying the static parameter, I think you need to use Test.sName

A: In this case, there is a trap in the nameTest method. Note that the method parameter name is the same as the static variable name.
In Java, variables resolution says that in this case, the parameter is accessed, and the static variable his "hidden". If you want to access the static variable, you have to use Test.sName.
So, in this example, "idea" is never appended to the static sName variable. The only answer available that doesn't include "idea" is A, so 1 is the good answer.

A: This will output 'good'
When you call nameTest(sName) you are only passing in a copy of a reference so any changes so when in the context of nameTest you are working on a different variable. This means that any attempt to reassign this variable wont take affect outside nameTest. The global static variable sName is also hidden by the parameter sName.
If string was not immutable it would be possible to make changes to them.

A: In methods you always deal with local reference COPY (if you give it as an arg). you changed reference COPY, but source is still the same.
the answer can be good, good 0, good 0 1 etc.

A: Actually running the program returns
good 0 1 2 3
(actually wrote it out and tried running it in java... you should try it).
Stepping through the program, we can think of it this way:
In the function nameTest, sName is a local String variable.
Like the explanation says, Strings are immutable so doing a string concatenation with " idea " will create a new instance of a String -- "good idea " -- and assign it to the local variable sName. The class variable sName ( I think calling it shouldn't be called a global ) will remain as "good" as a result.
It then proceeds to run the thread function using start() -- which invokes run().
In the function run(), we do concatenation once again, but this time we assign to the class variable sName.
So when the run() function returns, the class variable sName is changed and the print out will reflect that.


text:
Q: firewall windows server 2012 r2 with DHCP server under windows server environment 2012 I have a DHCP server and I have a firewall under my machine, the firewall blocks all already. the problem that the DHCP server does not give an address to the client, how can I solve this problem?

A: I found the solution. the solution is the addition of an outgoing rule for DHCP that is on the UDP protocol that allows the local port 67 and for the destination one is allowed the port 68


text:
Q: ApiException which checking for location settings in FusedLocationApi I am using Google Fused Api to retrieve location in my app. So as usual before request location updates I checking for location settings status using mSettingsClient?.checkLocationSettings(mLocationSettingsRequest). This seems to be working on every device but on vivo v7 it doesn't work it gives this exception com.google.android.gms.common.api.ApiException: 10: Not implemented on this platform. I tested this with location provider and it's working in that.
I am not able to find any reason behind this.


text:
Q: rvmsudo : command not found I am following this great post to configure my rails production server on ubuntu 10.10 : rails production
When I want to execute the command :
rvmsudo passenger-install-nginx-module
I get the error : rvmsudo : command not found
Can anybody help me ? Thanks in advance !

A: Updating to the latest version helped me:
rvm get latest
rvm reload

The rvmsudo command was available after that.

A: That command is part of rvm. Have you installed rvm already? https://rvm.io. Follow the installation instructions carefully. It adds a lot to the login script, so just to be sure to be sure, logout and log back in to make sure it's setup properly. Skip the gemsets for now just to get up and running, then revisit that.

A: I finally performed a new global settings of my server and I installed passenger following carefully the instructions on the official web site here
Everything works now.


text:
Q: Проблема с функцией any() в генераторе паролей (python3) Есть следующий код:
import random as rnd
from string import ascii_letters, ascii_lowercase, ascii_uppercase, digits

def second_password_generator(main_count, length):
    symbols = "".join((set(ascii_letters) | set(digits)) - set('lI1oO0'))
    for _ in range(main_count):
        count = 3
        password = []
        for _ in range(length):
            password.append(rnd.choice(symbols))
        if any(ascii_uppercase) in password:
            count -= 1
        if any(ascii_lowercase) in password:
            count -= 1
        if any(digits) in password:
            count -= 1
        if count == 0:
            print(*password, sep="")
        else:
            main_count += 1

a, b = [int(input()) for _ in "aa"]
second_password_generator(a, b)

Проблема заключается в том, что он ничего не возвращает т.к не проверяются следующие условия (которые проверяют наличие символов в списке):
if any(ascii_uppercase) in password:
    count -= 1
if any(ascii_lowercase) in password:
    count -= 1
if any(digits) in password:
    count -= 1

А так же не выполняется условие:
else:
    main_count += 1

Что делать?

A: if any(ascii_uppercase) in password:

any работает не так, как вы думаете. Если любой элемент из переданной ему коллекции True, то он возвращает True, иначе False. Коллекция ascii_uppercase не пустая (при такой проверке строка превращается в коллекцию символов), поэтому any(ascii_uppercase) всегда будет равно True. А далее проверяется - есть ли True в password. Конечно, никакого булевского True нет в строке password (которая в этом случае тоже рассматривается как коллекция символов). Поэтому значение выражения any(ascii_uppercase) in password всегда False, оно никогда не выполняется.
Как же правильно проверить, что в password есть хотя бы один символ ascii_uppercase? Через пересечение множеств. Проверяем, что пересечение множеств символов из этих строк не пустое:
if set(ascii_uppercase) & set(password):

Также можно свести все ваши проверки в одну помощью оператора all:
if all((
    set(ascii_uppercase) & set(password),
    set(ascii_lowercase) & set(password),
    set(digits) & set(password)
   )):

A: Cпасибо СrazyElf за подсказку, однако задача была выполнена при следеющей реализации:
import random as rnd
from string import ascii_letters, ascii_lowercase, ascii_uppercase, digits

def second_password_generator(main_count, length):
    symbols = "".join((set(ascii_letters) | set(digits)) - set('lI1oO0'))
    for _ in range(main_count):
        password = []
        for _ in range(length - 3):
            password.append(rnd.choice(symbols))
        password.append(rnd.choice("".join(set(ascii_uppercase) - set('lI1oO0'))))
        password.append(rnd.choice("".join(set(ascii_lowercase) - set('lI1oO0'))))
        password.append(rnd.choice("".join(set(digits) - set('lI1oO0'))))
        rnd.shuffle(password)
        print(*password, sep='')

a, b = [int(input()) for _ in "aa"]
second_password_generator(a, b)


text:
Q: How do I allow connetction only to specific websites on windows7 (chrome and firefox) The kids are getting on my nerv.
I have to leave open access to the laptop and the apps on it.
People in the family need to access a total of 3 sites on the internet while I'm gone.
How do i only enable the sites i want and block *.* everything else?
All of the block mechanics I know rely on the blacklist concept. I need to make a whitelist and ditch everything else...

A: I have used Privoxy before to implement exactly what you are wanting.  You install and run this as a service, force your browser to use the proxy, and then use Privoxy's trustfile feature to setup a whitelist.

A: The closest workaround I was able to put in action on the fly:
Setup useless DNS addresses on your net card or on your router, and put whatever site you want with its name and ip in the hosts file.
Skype dies too as I didn't really bother to see what servers it connects to.
Some other Internet dependent or DRM software might die too i suppose.


text:
Q: Find EyeMap of an image using python opencv I tried coding for EyeMapC but couldn't get expected output.

EyeMapC = 1/3(Cb2 + Cr'2 + Cb/Cr)

where Cr' = 255 - Cr
Here's my code
from __future__ import division
import cv2
import numpy as np

img = cv2.imread('img/file.jpg')
EyeMap = cv2.cvtColor(img,cv2.COLOR_BGR2YCR_CB)
y,Cr,Cb = cv2.split(EyeMap)
Q = np.square(Cb) #,dtype=np.float64)
Cr_bar = (255-Cr)
R = np.square(Cr_bar) #,dtype=np.float64)
G = Cb/Cr
EyeC = (Q/3+R/3+G/3)
#EyeC = np.mod(EyeC,255)

cv2.imshow('EyeC',EyeC)
cv2.waitKey(0)
cv2.destroyAllWindows()

Cb2 and Cr'2 have to be normalized between [0,255] before putting in formula or the final EyeC value needs to be normalized ?
Original Image: Original Image
Output:  Output Image


text:
Q: docker php gettext not translating I'm desperate finding a solution why gettext is not translating. I followed multiple tutorials and have no clue why it is not working. Locales are installed, gettext too, activated, loaded in php.ini and still not working. Currently I'm trying to translate from english to czech.
Dockerfile
FROM php:7.4-apache
RUN apt-get update && apt-get install -y zlib1g-dev libicu-dev g++ locales gettext

RUN docker-php-ext-configure intl \
    && docker-php-ext-configure gettext \
    && docker-php-ext-install \
    intl \
    gettext
RUN sed -i -e 's/# en_US.UTF-8 UTF-8/en_US.UTF-8 UTF-8/' /etc/locale.gen && \
    sed -i -e 's/# cs_CZ.UTF-8 UTF-8/cs_CZ.UTF-8 UTF-8/' /etc/locale.gen && \
    dpkg-reconfigure --frontend=noninteractive locales && \
    update-locale LANG=en_US.UTF-8
ENV LC_ALL en_US.UTF-8
ENV LANGUAGE cs_CZ:en_US:en
ENV LANG en_US.UTF-8
RUN docker-php-ext-install pdo
RUN docker-php-ext-install pdo_mysql
RUN docker-php-ext-enable intl gettext
RUN a2enmod rewrite
RUN service apache2 restart
RUN apache2ctl restart
EXPOSE 80

Languages should be installed corrently
$ locale -a
C
cs_CZ.utf8
C.UTF-8
en_US.utf8
POSIX

File structure
index.php
│
locale
│
└───cs_CZ.utf8
│   │
│   └───LC_MESSAGES
│       │   messages.mo
│       │   messages.po
│
└───en_US.utf8
│   │
│   └───LC_MESSAGES
│       │   messages.mo
│       │   messages.po

messages.po in cs translation
# SOME DESCRIPTIVE TITLE.
# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER
# This file is distributed under the same license as the PACKAGE package.
# FIRST AUTHOR <EMAIL@ADDRESS>, YEAR.
#
#, fuzzy
msgid ""
msgstr ""
"Project-Id-Version: PACKAGE VERSION\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2020-10-05 10:15+0200\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language-Team: LANGUAGE <LL@li.org>\n"
"Language: cs_CZ.utf8\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"

#: index.php:42
msgid "HELLO_WORLD"
msgstr "Ahoj světe"

#: index.php:43
msgid "TEST_TRANSLATION"
msgstr "Testovací překlad"

messages.po is generated via msgfmt
index.php
$locale = 'cs_CZ.utf8';
$domain = 'messages';
setlocale(LC_TIME, "");
$results = putenv("LC_ALL=$locale");
if (!$results) {
    exit('putenv failed');
}

$results = setlocale(LC_ALL, $locale);
if (!$results) {
    exit('setlocale failed: locale function is not available on this platform, or the given local does not exist in this environment');
}

$results = bindtextdomain($domain, "locale/$locale");
echo 'new text domain is set: ' . $results . "\n";

$results = textdomain($domain);
echo 'current message domain is set: ' . $results . "
";

echo _("HELLO_WORLD");
echo "
";
echo _("TEST_TRANSLATION");

It returns
new text domain is set: /var/www/html/locale/cs_CZ.utf8 current message domain is set: messages
HELLO_WORLD
TEST_TRANSLATION

Is there any other way how to debug gettext? Am I missing something? Thank you!

A: So the culprit was LANGUAGE, as debian looks up this variable first, even before LC_ALL!
putenv("LANGUAGE=$locale");


text:
Q: How to handle embedded schema in Phoenix? Lets say i have user model like follow
schema "users" do
  field :user_name, :string
  field :password, :string
end

and address model like follow
schema "address" do
  field :line1, :string
  field :country, :string
end

i am using mongo db as database so i want json format like follow

{ _id: "dfd", user_name: "$$$$", password: "xxx", address: { line1 : "line1", country: "india" } }

1)how to create and validate changeset where username in user modal and country in address model are required fields?
2)how to get final changeset after validate both?

A: Assuming the mongo adapter works similarly to postgresql jsonb columns:
defmodule User do
  use Ecto.Schema
  import Ecto.Changeset

  schema "users" do
    field :user_name, :string
    field :password, :string
    embeds_one :address, Address
  end

  def changeset(model, params \\ %{}) do
    model
    |> cast(params, [:user_name, :password]
    |> cast_embed(:address)
    |> validate_required(:user_name, :password, :address)
  end
end

defmodule Address do
  use Ecto.Schema
  import Ecto.Changeset

  @primary_key false
  embedded_schema do
    field :line1, :string
    field :country, :string
  end

  def changeset(model, params \\ %{}) do
    model
    |> cast(params, [:line1, :country])
    |> validate_required([:line1, :country])
  end
end


text:
Q: C# Get pixel location from Image<,> EMGU CV 3.3 I've been working on an EMGU based project where i need to create a skeleton image with the ZhangSuen thinning algorithm, which works perfectly fine. For further analysis I want to obtain all pixel locations of the skeleton and store them in a List<Point>
I've researched a lot about performance issues when using Bitmap.GetPixel() and Bitmap.SetPixel() methods. Thats why i followed the approach of using a byte[,,] array to get the pixel locations. My approach so far looks like this:
    public static List<Point> GetSkeletonPoints(Image<Gray, Byte> src, Byte color = 255)
    {
        var SkeletonPoints = new List<Point>();
        int rows = src.Width;
        int cols = src.Height;
        byte[,,] data = src.Data;

        for(int y = rows - 1; y >= 0; y--)
        {
            for(int x = cols - 1; x >= 0; x--)
            {
              if(data[x, y, 0] != 0)
                {
                    SkeletonPoints.Add(new Point(x, y));
                }
            }
        }
        return SkeletonPoints;
    }

The skeletonpixels have the value of 255, while the background is black (0).
Now the weird thing is if i try to modify the input image like this:
src.Data[0,0,0] = 255;

absolutely nothing changes when I look at the image by using CvInvoke.Imshow("test", src);
Running the presented method results in no Point being added to the list, which means the condition in the if-statement is never fulfilled.
Running the if-statement like this if(data[x, y, 0] == 0) results in a condition that is always fulfilled and i get every single point location in the image, despite being actually black (0) or white (255).
I thought that i by mistake used a completely black image..
But then i applied the CvInvoke.FindNonZero() method to the input image and found 500 NonZero-pixels, which makes absolutely no sense to me.
I'm kinda desperate by now, maybe i'm missing something?
Any help or hint is much appreciated!! (even if it's something that doesn't solve my problem but enhances the performance of looping over images in general)


text:
Q: Need help porting C function to Python I'm trying to port a C function which calculates a GPS checksum over to Python.  According to the receiving end I am sometimes miscalculating the checksum, so must still have a bug in there.
C code is
void ComputeAsciiChecksum(unsigned char *data, unsigned int len,
                          unsigned char *p1, unsigned char *p2)
{
    unsigned char c,h,l;

    assert(Stack_Low());

    c = 0;
    while (len--) {
        c ^= *data++;
    }
    h = (c>>4);
    l = c & 0xf;
    h += '0';
    if (h > '9') {
        h += 'A'-'9'-1;
    }
    l += '0';
    if (l > '9') {
        l += 'A'-'9'-1;
    }
    *p1 = h;
    *p2 = l;
}

My attempt at a Python function is
def calcChecksum(line):
    c = 0
    i = 0
    while i < len(line):
        c ^= ord(line[i]) % 256
        i += 1
    return '%02X' % c;

A: Here is how you can set up a testing environment to diagnose your problem.

*

*Copy the above C function to a file, remove the assert() line, and compile it to a shared library with
gcc -shared -o checksum.so checksum.c

(If you are on Windows or whatever, do the equivalent of the above.)

*Copy this code to a Python file:
import ctypes
import random

c = ctypes.CDLL("./checksum.so")
c.ComputeAsciiChecksum.rettype = None
c.ComputeAsciiChecksum.argtypes = [ctypes.c_char_p, ctypes.c_uint,
                                   ctypes.c_char_p, ctypes.c_char_p]

def compute_ascii_checksum_c(line):
    p1 = ctypes.create_string_buffer(1)
    p2 = ctypes.create_string_buffer(1)
    c.ComputeAsciiChecksum(line, len(line), p1, p2)
    return p1.value + p2.value

def compute_ascii_checksum_py(line):
    c = 0
    i = 0
    while i < len(line):
        c ^= ord(line[i]) % 256
        i += 1
    return '%02X' % c;

Now you have access to both versions of the checksum function and can compare the results.  I wasn't able to find any differences.
(BTW, how are you computing the length of the string in C?  If you are using strlen(), this would stop at NUL bytes.)
As a side note, your Python version isn't really idiomatic Python.  Here are two more idiomatic versions:
def compute_ascii_checksum_py(line):
    checksum = 0
    for c in line:
        checksum ^= ord(c)
    return "%02X" % checksum

or
def compute_ascii_checksum_py(line):
    return "%02X" % reduce(operator.xor, map(ord, line))

Note that these implementations should do exactly the same as yours.

A: Have you checked out this cookbook recipe? It hints at what input you should include in "line", returns a asterisk in front of the checksum, and gives one (input, output) data pair that you can use as test data.
Are you sure that "the receiver" is working correctly? Is the problem due to upper vs lower case hex letters?


text:
Q: gnome-shell shortcut for opening new instance In gnome-shell hitting enter for a search result opens the application in the current workspace or brings up the currently open instance of the app. Is it possible to have a shortcut (like: Alt + Enter or something) that opens a new instance of the application in the current workspace or in a new workspace.

A: Did you try the Ctrl key?  This works me in Gnome 3.2.


text:
Q: Получение SIP в приложении ios Подскажите пожалуйста, какие приложения можно использовать на IOS для того, чтобы на него переадресовывать вызовы которые поступают на купленный вирт. номер.
Коротко говоря мне нужны приложения где я смогу получит SIP номер для переадресации на него купленного виртуального.
Если я что-то не так понял - просьба объяснить как это работает. Буду премного благодарен.

A: И так. Если кому данная тема будет интересна.
Я воспользовался связкой двух платформ:

*

*Sonetel для покупки вирт. номеров

*SipNet для получения SIP адреса, на который в последствии через мобильное приложение будет переадресовываться вызов на номера Sonetel'а.


text:
Q: do the core servers in Neo4j implement the leaders in a multilayer protocol? I am studying replication protocols while developing a little database in Neo4j. While reading the documentation I have read the definition "core servers" and to me it seems that they are exactly the same as leaders in a multilayer system. Am I missing something?

A: Core servers handle write transactions.
A core can have one of the following roles : leader or follower.
In a cluster there can be only one leader (and so, tere are many followers)


text:
Q: Get the path of a file dragged into a Windows Forms form I am developing an application which requires the user to drag a file from Windows Explorer into the application window (Windows Forms form). Is there a way to read the file name, path and other properties of the file in C#?

A: You can catch the DragDrop event and get the files from there. Something like:
void Form_DragDrop(object sender, DragEventArgs e)
{
    string[] fileList = (string[])e.Data.GetData(DataFormats.FileDrop, false);

    //more processing
}

A: you Should Use Two Events
1) DragDrop
2) DragEnter
Also enable "AllowDrop" Property of Panel/form to true.
 private void form_DragEnter(object sender, DragEventArgs e)
    {
        if (e.Data.GetDataPresent(DataFormats.FileDrop))
        {
            e.Effect = DragDropEffects.Copy;
        }
        else
        {
            e.Effect = DragDropEffects.None;
        }
    }

    private void form_DragDrop(object sender, DragEventArgs e)
    {
        string[] filePaths= (string[])e.Data.GetData(DataFormats.FileDrop, false);
    }


text:
Q: Hover intent not working, or i'm doing something majorly wrong I have been trying to figure out this hoverintent plugin and its stumping me. Here is what i have:
    var config = {
     over: $(this).children('.mo_url').css('display','block'), // function = onMouseOver callback (REQUIRED)
     timeout: 500, // number = milliseconds delay before onMouseOut
     out: $(this).children('.mo_url').css('display','none') // function = onMouseOut callback (REQUIRED)
};

    $('.tag').hoverIntent( config )

Im Trying to get a simple tooltip to display after a user highlight a link for a second or 2, to display the url. Is this what i should be using? any help would be much appreciated.

A: Success! It was the interval I was after. Not the timeout.
var config = {
 over: function(){$(this).children('.mo_url').css('display','block')},
 interval: 1000,  // number = milliseconds delay before function init.
 timeout: 0, // number = milliseconds delay before onMouseOut
 out: function(){$(this).children('.mo_url').css('display','none')}
};


text:
Q: Python Using Find() Method with a List I am trying to use the find() method to find the zip codes in a list from text that has been scraped from a .PDF.  Below is an example of the text and my code so far.  I am able to get it to run without errors but it does not produce an output.  I would like to be able to use 'SOC' string to find the line that contains the city, state and zip then use the replace() method and replace the state with "" and also replace the zip with "".  The issue is that while the state will always be NY and can be established with a variable or string, the zip can be a number of different zip codes and I will not know what they will be in the scraped text.  Thus I was hoping to use the find() method to go through the text and be able to compare it to a list since I can enter them all in the list and just let the code replace what it finds.
Smith, Joel
Soc Sec#: xxx-xx-1111
56 Monroe Drive
Smithville, NY 14221
27

Smith, Nicole M
Soc Sec#: xxx-xx-2222
56 Monroe Dr
Smithville, NY 14226
25

    state = "NY"
    zip = ["14206", "14215", "14218", "14221", "14226"]
# Searches for City
    if line.find('Soc') != -1:
        if line.find(str(zip)) in zip != -1:
            print(lines[indx].strip().replace(state, "").replace(zip, ""))

A: To find an element in list use in keyword. If the searched element is present in the list, it will return True,  else, it will return False.


text:
Q: PatternLayout < > escape character in log4j2 I'm trying to output a pattern that contains the characters < > in the form
08:06:41 DEBUG 69 [ch.fhnw.edu.rental.model.Movie] - <Movie 'Cars' created>
Where <Movie 'Cars' created>  is the log-message.
My PatternLayout is as follows:
            <PatternLayout pattern="%d{HH:mm:ss} %-5p %L [%c] - <%m%n>"/>

Unfortunately this produces the error

[Fatal Error] log4j2.xml:5:65: The value of attribute "pattern" associated with an element type "PatternLayout" must not contain the '<' character.

How can I escape the < > characters without hardcoding them into the source code?

A: You can use HTML entity codes for this: < for < and > for >.
Be careful where you place them:
<PatternLayout pattern="%d{HH:mm:ss} %-5p %L [%c] - <%m>%n"/>

In the above example, the > needs to be placed before the %n since %n generates a newline.


text:
Q: open explorer with javascript/html Is it possible to open an actual explorer window rather than have the look in directory on your browser?
So like the windows key + e window... preferably using html or JavaScript?
I've seen it been done in a Firefox add-on called new tab king, but i couldn't figure out how to split up this code.

A: This is not reliably possible using pure HTML/JavaScript.
In general, website maintainers cannot use JavaScript to force the browser to open an application in a specific way, because that would heavily impact the user experience.

A: No, not definitely not using HTML and hopefully not in pure JavaScript.
Probably possible using some horrid ActiveX control in Internet Explorer but you really don't want to go down that route.

A: Most, if not all, javascript is blocked from interacting with anything outside of the browser.
You maybe able to accomplish it with a flash based object. Like they use for some of the copy and paste techniques using javascript.
Its a huge security hole to open up the javascript to the windows environment.
I could ust open a hidden file browser and start coping files, or load something on to your system.