text:
Q: Is there an app to display partition identifers? I'd like to know if an app exists that list all partitions, their filesystem type, and their possible identifiers.
This could help users in configuring their bootloaders.
For example:
Identifier      Grub Identifier     Filesystem Type     Size
 /dev/sda1       (hd0,2)             ext4                37GB
 /dev/sda4       (hd0,5)             NTFS                20GB

Is there an app with functionality similar to this that anyone knows of?

A: Try using di
sudo apt-get install di

then
di -a

gives something close to your requirement
Filesystem         Mount               Size     Used    Avail %Used  fs Type
/dev/sda8          /                  48.8G    14.0G    32.3G   34%  ext4
udev               /dev                1.9G     0.0G     1.9G    0%  devtmpfs
devpts             /dev/pts            0.0M     0.0M     0.0M    0%  devpts
gvfs-fuse-daemon   /home/user/.gvf     0.0M     0.0M     0.0M    0%  fuse.gvfs-fuse-daemon
/dev/sda5          /media/01CC6E45   293.0G   284.9G     8.1G   97%  fuseblk
/dev/sda6          /media/01CC6E45   390.6G   355.6G    35.0G   91%  fuseblk
/dev/sda7          /media/01CC6E45    97.7G    94.2G     3.5G   96%  fuseblk
/dev/sda2          /media/0E246764    97.6G    34.1G    63.5G   35%  fuseblk
/dev/sdb1          /media/748d0c01    20.0G     5.8G    13.2G   34%  ext4
/dev/sdb5          /media/f452a714    18.6G     7.2G    10.5G   44%  ext4
/dev/sdb4          /media/New Volu   255.5G    68.1G   187.4G   27%  fuseblk
proc               /proc               0.0M     0.0M     0.0M    0%  proc
binfmt_misc        /proc/sys/fs/bi     0.0M     0.0M     0.0M    0%  binfmt_misc
tmpfs              /run              772.7M     0.8M   771.9M    0%  tmpfs
none               /run/lock           0.0M     0.0M     0.0M    0%  tmpfs
none               /run/shm            0.0M     0.0M     0.0M    0%  tmpfs
sysfs              /sys                0.0M     0.0M     0.0M    0%  sysfs
none               /sys/fs/fuse/co     0.0M     0.0M     0.0M    0%  fusectl
none               /sys/kernel/deb     0.0M     0.0M     0.0M    0%  debugfs
none               /sys/kernel/sec     0.0M     0.0M     0.0M    0%  securityfs

but without the Grub Identifier ( although the sda8 can be seen as (hd0,8) from Filesystem column)  .And for entire disk information , all the available partitions needs to be mounted.

Another one is disktype but with more details including UUID
example  sudo disktype /dev/sdx
Partition 6: 390.6 GiB (419423445504 bytes, 819186417 sectors from 819186480+63)
    Type 0x07 (HPFS/NTFS)
    Windows NTLDR boot loader
    NTFS file system
      Volume size 390.6 GiB (419423444992 bytes, 819186416 sectors)
  Partition 7: 97.65 GiB (104855837184 bytes, 204796557 sectors from 1638372960+63)
    Type 0x07 (HPFS/NTFS)
    Windows NTLDR boot loader
    NTFS file system
      Volume size 97.65 GiB (104855836672 bytes, 204796556 sectors)
  Partition 8: 48.89 GiB (52500103168 bytes, 102539264 sectors from 1843169580+1748)
    Type 0x83 (Linux)
    Ext3 file system
      UUID 0F493AF5-3B1C-49A5-B33E-5E04F42CA0F1 (DCE, v4)
      Last mounted at "/"
      Volume size 48.89 GiB (52500103168 bytes, 12817408 blocks of 4 KiB)
  Partition 9: 3.725 GiB (3999268864 bytes, 7811072 sectors from 1945712475+165)
    Type 0x82 (Linux swap / Solaris)
    Linux swap, version 2, subversion 1, 4 KiB pages, little-endian
      Swap size 3.725 GiB (3999260672 bytes, 976382 pages of 4 KiB)

A: You don't need to install anything, just:
ls /dev/disk/by-uuid -lah

gives you for example:
lrwxrwxrwx 1 root root  10 Jun 27 10:56 7d4d0682-4f05-41d7-b3a3-871799e1014c -> ../../sda1
lrwxrwxrwx 1 root root  10 Jun 27 10:56 a22643b0-8de4-4feb-859a-1ba7eb84bf2f -> ../../sda5

A: You can try to use gparted or lparted.

A: Another choice, installed by default on 12.04:
sudo lsblk -f

There are options to display fields, remove headers, etc.
sudo blkid

may also be useful, depending upon what you find easier to parse.
I don't think it will be easy to find a standard utility to convert to the grub nomenclature. The shell program /usr/lib/grub-legacy/update-grub has some shell script functions that do the conversion.


text:
Q: Recursively touch files with file I have a directory that contains sub-directories and other files and would like to update the date/timestamps recursively with the date/timestamp of another file/directory.
I'm aware that:
touch -r file directory

changes the date/timestamp for the file or directory with the others, but nothing within it. There's also the find version which is:
find . -exec touch -mt 201309300223.25 {} +\;

which would work fine if i could specify the actual file/directory and use anothers date/timestamp. Is there a simple way to do this? even better, is there a way to avoid changing/updating timestamps when doing a 'cp'?

A:
even better, is there a way to avoid changing/updating timestamps when doing a 'cp'?

Yes, use cp with the -p option:

-p
same as --preserve=mode,ownership,timestamps
--preserve
preserve the specified attributes (default:
  mode,ownership,timestamps), if possible additional attributes:
  context, links, xattr, all

Example
$ ls -ltr
-rwxrwxr-x 1 me me  368 Apr 24 10:50 old_file
$ cp old_file not_maintains    <----- does not preserve time
$ cp -p old_file do_maintains  <----- does preserve time
$ ls -ltr
total 28
-rwxrwxr-x 1 me me  368 Apr 24 10:50 old_file
-rwxrwxr-x 1 me me  368 Apr 24 10:50 do_maintains   <----- does preserve time
-rwxrwxr-x 1 me me  368 Sep 30 11:33 not_maintains  <----- does not preserve time

To recursively touch files on a directory based on the symmetric file on another path, you can try something like the following:
find /your/path/ -exec touch -r $(echo {} | sed "s#/your/path#/your/original/path#g") {} \;

It is not working for me, but I guess it is a matter of try/test a little bit more.

A: In addition to 'cp -p', you can (re)create an old timestamp using 'touch -t'. See the man page of 'touch' for more details.
touch -t 200510071138 old_file.dat

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why are <> ALL and NOT IN aliases of each other in SQL? So the mySQL dev site tells me that <> ALL and NOT IN are aliases of each other. My question is, why exactly?
Let me be more specific:
= ALL returns true when "the comparison (here, equality) is TRUE for ALL of the values in the column that the subquery returns", i.e., each outer query row will only satisfy outer query = ALL (inner query) if all rows in the inner query have the same value and that
value equals the outer query row value.
So, outer query <> ALL (inner query) must return true when there exists at LEAST 1 value in the inner query different from the outer query.
But NOT IN would return true only if NONE of the rows of the inner query match the outer query row in question.
Have I got something fundamentally wrong?
Thanks

A:
So, outer query <> ALL (inner query) must return true when there exists at LEAST 1 value in the inner query different from the outer query.

That's not true. Just as value = ALL (query) returns true when value is equal to every value returned by query; value <> ALL (query) returns true when value is different from every value returned by query. You are apparently thinking that value <> ALL (query) would mean NOT (value = ALL (query)), but that's not the case.


text:
Q: Boot failure on PowerPC Mac with encrypted LVM I have a PowerBook G4 that was previously running Debian squeeze, and before that, OS X Leopard. It worked fine under Debian, but I disliked the GUI, so I decided to give Ubuntu a try.
I downloaded a copy of the PowerPC Desktop ISO, but the GUI was messed up: most of the screen was taken up by a large white rectangle, which was presumably supposed to be a window, but didn't load properly. Nothing happened when I clicked on the menus at the top, except for the one in the top-right corner that has shutdown options. I tried to restart it using that, but I didn't get a dialog or anything, so I finally ended up using control-command-power to force a reboot.
I then tried the alternate ISO to see if I could just use the textual installer. That worked, and I don't remember having any problems with the login screen, but after that, I had the same problems as with the live disc. I had no problems using the tty's, though, which is mostly what I did under Debian.
I later found that if you want full-disk encryption, you must set it up at install time. So I rebooted to the alternate disc and wiped the entire hard disk again, choosing the entire hard disk with encrypted LVM option during partitioning. The installation completed successfully, but now when I try to boot, I get just a black screen after the yaboot menus, no password prompt or anything. How can I fix this?

A: Typing Linux nomodeset rather than simply Linux at the yaboot prompt (or just pressing return, which in my case defaults to Linux) worked for me.
Thanks to L3top from Freenode/#ubuntu for suggesting nomodeset.


text:
Q: Stuck on why my program wont work...? Ive been trying to make an app for my girlfriend and I which will allow us to type messages and then allow th other to read it and click the button below to give a response and keep this going back and forth. I've gotten somewhat far I guess but I'm completely stuck on why it wont work now. Ive been working based on the skeleton of this code.
Originally, the code allowed me to open the application and then once I pressed the button at the bottom, it would give me an error saying that the program is no longer able to run and that I had to "force close" it. I fixed that but then when I did, the MainActivity window would keep reappearing when I would click the button. I attempted to fix that but now the application doesn't open anymore
I tried the debugger but I'm not advanced enough to figure out what it really says....
If you would like project folder or somehow upload here, I have no problem doing that. Just trying to make this as a little present for my girl. Thanks in advance!
[edit]
I should mention that there are no syntax errors
[edit]
Manifest code
     <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.chatfriends"
    android:versionCode="1"
    android:versionName="1.0" xmlns:tools="http://schemas.android.com/tools" tools:ignore="OldTargetApi">

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="16" tools:ignore="MissingPrefix"/>

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                 <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".Activity__alex" />
    </application>

</manifest>

[edit]
MainActivity:
package com.chatfriends;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

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

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

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

     public void startActivity_alex(View v){
         Intent intent = new Intent(MainActivity.this, Activity__alex.class);
         startActivity(intent);
    }
 }

Edit: Now the app runs, but when I click on the button below it gives me an error.
Here is the catlog

A: Change
   <activity
        android:name=".chatfriends.MainActivity"

to
<activity
        android:name=".MainActivity"

inside your manifest because you MainActivity is inside com.chatfriends package and not in com.chatfriends.chatfriends

A: You should define your activity name in the Manifest file as:
android:name=".MainActivity"

instead of android:name=".chatfriends.MainActivity"
Because the error stating the class com.chatfriends.chatfriends.MainActivity is not found, and you have your MainActivity class directly under com.chatfrieds package.
Edit
The error message tells you "NoSuchMethodException" onClick(View). It seems you defined onClick handler or your button in the layout XML file.
You need to add this function in your activity:
public void onClick(View view){

  // Add your code here for button click

}


text:
Q: How do I create a IBM Cloud Watson Studio Instance? I have being trying to create a Watson Studio Instance however I face with the following statement:
"You do not have a resource group. To create a resource group, go to Manage - Account - Resource groups from the header."
Looking forward to your assistance


text:
Q: Buffon needle pi estimate experiment gets close to pi, but doesnt get perfect value I am working on a very typical university homework. Im supposed to write a C program to estimate the pi via Buffon Needle using Monte Carlo method. I think my program works properly, but i never ever get the pi right. It is always near typical 3.14, but sometimes its 3,148910 sometimes 3,13894. Whats the reason behind it? Can i do anything to make it more 'equal' to accurate value?
(code comments are in Polish, comments in () are in English.)
#include <stdio.h>
#include <math.h>
#include <time.h>
#include <stdlib.h>

int main(int argc, char **argv)
{
    srand(time(NULL));
    int i; //wprowadzenie licznika (counter)
    double l; // dlugosc igly (lenght of needle)
    double n;// liczba prob (number of trials)
    double L; // szerokosc miedzy liniami (width between lines)
    double x; // kat miedzy igla a normalna do linii (angle)
    double pi; // szacowana wartosc liczby pi (pi)
    double P=0; //ilość prób spełniających warunek styku igły z linią (ammount of trials that worked)
    double d; //odleglosc srodka igly od linii (distance between centre of needle and line)
    double y; //minimalizacja obliczeń
    double  stosun; //stosunek wykonanych obliczeń (ammount of trials to ammount of succesfull trials)
    printf("Program szacuje wartosc liczby pi metoda Monte Carlo na podstawie Igly Buffona. Prosze Pamietac o:\n-Podaniu liczby prób jako wartości większej od zera i całkowitej\n-Podaniu długości igły mniejszej niż szerokości między liniami\n");
    printf("Prosze podac liczbe prob:\n");
    scanf("%lf", &n);
    printf("Prosze podac dlugosc igly:\n");
    scanf( "%lf", &l);
    printf("Prosze podac szerokość miedzy liniami:\n");
    scanf("%lf", &L);
    if (n <= 0.0 || l > L)
    {
        printf("Nastąpił błąd wynikających z podania niepoprawnych danych\n");
        return 1;
    }
    printf("%f %f %f", n,l,L); //debuging midway

    for (i=0; i<n; i++)
{
    x = ((double)rand()/RAND_MAX)*3.1415;       // losowy kat w radianach (random angle in radians)

    d = ((double)rand()/RAND_MAX)*L/2;         // losowa dlugosc igly mniejsza niz odstep miedzy liniami (random needle lenght)

    y = (l/2) * sin (x);
printf("Próba%d\n", i);
    if (d<=y)
    {
        P++;
    }

}

stosun=n/P;
printf("Stosun %lf", stosun);
pi=stosun*2*l/L;
printf("liczba pi=%lf", pi);
    return 0;
}

A: The variance of Monte Carlo simulations tends to be really large. (They converge to zero error as n increases, but very slowly.) You can read about Buffon's Needle in particular here. I'd like to draw your attention to the figure where 5 different runs of 1000 tosses each are plotted. Inspecting each of them it would look like the value has already converged but to quite a wrong (and different in each case) result.
It's good to do your analysis before you start. The error estimate done rigorously in the above source is about 5.6 / n. That's the variance, so to get a standard deviation, we need a square root, which makes it even worse. After 1000 tosses you can expect π to have an error of about 0.073 (although this can easily be twice as high, or much less, just by pure chance). After a million tosses it should be correct to about ±0.002. After a hundred million you are likely to get the first three digits after the decimal point right and the first error on the fourth or (rarely) fifth. I don't know your n but the values you are getting seem well within what is typical. Edit: with n = 1,000,000, they are +3 σ and –1 σ.
Note that it's a common misconception that one can work around this by making several runs and averaging their results (which should fluctuate above and below the correct value with the same probability, after all). This of course works, but does not offer any advantage whatsoever, apart from the obvious that it can be distributed to multiple machines. The error of running 100 simulations of a thousand iterations each is exactly the same as that of running a single one with a hundred thousand iterations.
An obvious way of making the estimate better is thus increasing the number of hits. One big advantage of Monte Carlo methods is that the individual samples are usually completely independent from each other and thus allow great opportunities for parallelization (OpenMP, vectorized instructions, GPU). But the first step really should be trying to make your code run faster so that increasing n by an order of magnitude or so hurts less. For example, because you know from the analysis that the precision is never going to be really stunning, you can use float instead of double which is on some platforms up to twice as fast. Eliminate the call to sin (it's certainly more elegant if you don't need the value of π to start with). Output your summary only every 1000 steps or so.
A less obvious one is doing the analysis properly and noting how you can decrease the numerator in the variance (the denominator will be n anything you do). If I am not mistaken this experiment runs the best when the length of the needle is equal to the separation between the lines: less than that is suboptimal and more than that brings multiple crossings which you don't want. There may be other ways of how to enhance it by altering the distribution of the angle and/or the position.


text:
Q: Android RecyclerView GridLayoutManager Talkback Issue I am trying to improve accessibility of one screen which is using recyclerview with gridlayout manager.
The span size of the gridlayoutmanager is 3. Depending on the backend response, sometimes i have 2 or 1 item in list. The issue which i have faced is that the talkback is announcing like that

"item info 2, 2 of 3, in list, 3 items"

But actually i have only 2 items in the my list. I think talkback makes the calculation of item numbers according to span size. But it is misleading. Is there anyone who can help me to solve this issue?
Thanks in advance.


text:
Q: React form values not being displayed on form submission Let's say I have some properties which can be equal to some possible options.  I'll define these both in someConstants.js
const possibleOptions = [
    {key: '1', text: "some text 1", value: "some_text_1"},
    {key: '2', text:  "some text 2", value:  "some_text_2"},
];

const someProperties = {
    flags: []
};

export { someProperties, possibleOptions };

I want someProperties.flags to be updated by possibleOptions upon submission of the form someForm.js
import React from "react";
import { someProperties, possibleOptions } from "./someConstants";
import { Form } from "semantic-ui-react";
import "./styles.css";

class SomeForm extends React.Component {
    state = someProperties;

    handleSubmit = event => {
        event.preventDefault();
        this.props.onSubmit(this.state);
    };

    onChange = event => {
        const {
            target: { name, value }
        } = event;

        this.setState({
            [name]: value
        });
    };

    render() {
        return (
            <Form onSubmit={this.handleSubmit} onChange={this.onChange}>
                <Form.Dropdown
                    label="Flags"
                    placeholder="Flags"
                    name="flags"
                    fluid
                    multiple
                    search
                    selection
                    options={possibleOptions}
                />

                <Form.Button type="submit">Submit</Form.Button>
            </Form>
        );
    }
}

export { SomeForm };

These values will be displayed by showFlags.js
import React from "react";
import "./styles.css";

class ShowFlags extends React.Component {
    displayList = list => {
        return(

                {list.map(flag => (

{flag}

                ))}

        );
    }

    render() {
        return (

                {this.props.flagProps.flags}

        );
    }
}

export { ShowFlags };

The interaction of these classes can be shown further in index.js
import React from "react";
import ReactDOM from "react-dom";
import { SomeForm } from "./someForm";
import { ShowFlags } from "./showFlags";

class App extends React.Component {
    state = {
        flagProps: {},
        submitted: false
    };

    handleSubmit = fields => {
        this.setState({
            flagProps: { ...fields },
            submitted: true
        });
        console.log("handleSubmit flagProps:" + this.state.flagProps);
    };

    render() {
        return (
            <>

flagProps form

                    <SomeForm flagProps={this.state.flagProps} onSubmit={this.handleSubmit} />

The result

                    {this.state.submitted ? (
                        <ShowFlags flagProps={this.state.flagProps} />
                    ) : (

Appears on submission.

                    )}

            </>
        );
    }
}

ReactDOM.render(<App />, document.getElementById("root"));

How can I achieve this?  To summarize:
Current behavior
I am able to choose options, but submission of the form does not yield any display.  ShowFlags.render() shows nothing.
Desired behavior
I am able to choose options, and those options are displayed by ShowFlags.render() upon submission of the form.
If it matters, this is using semantic-ui.

A: Here's your fixed code:
  onChange = (event, data) => {
    this.setState({
      [data.name]: data.value
    });
  };

  render() {
    return (
      <Form onSubmit={this.handleSubmit}>
        <Form.Dropdown
          label="Flags"
          placeholder="Flags"
          name="flags"
          fluid
          multiple
          search
          selection
          options={possibleOptions}
          value={this.state.flags}
          onChange={this.onChange}
        />

        <Form.Button type="submit">Submit</Form.Button>
      </Form>
    );
  }

https://codesandbox.io/s/exciting-kare-31l7w?file=/src/SomeForm.jsx
You forgot to apply the onChange handler to the Form.Dropdown in SomeForm, though the way semantic-ui-react works is that the change handlers have the props passed down to them as the second argument to the change function. Then the new value would be data.value.
You also should set the value of the Form.Dropdown to be value={this.state.flags} so it's a fully controlled component since you are bringing it into state anyway.
I also removed the Form's onChange handler as that doesn't affect the Dropdown at all. Semantic UI React (SUI) doesn't have it listed in their Form's Props.
Having an onChange handler on the form is a html property rather than an SUI prop. Which would explain why it doesn't work for Dropdowns. As they don't have a normal input/select html element base. This would also mean that the normal SUI's data argument to the onChange handlers wouldn't exist, so you'd need to get the attributes directly off the element.
Entire form onChange has an example of a form onChange handler, which looks to be very powerful for anything that has a base element that normally goes in a form.
Base html elements being: input, select, and textarea.


text:
Q: Profiles promoted through change sets appear to work only if profile already existed in target org My experience has shown two distinct behaviors.
Case 1:
Placeholder Profile "Profile 27" created in production.
Production org copied to Sandbox.  Development and config occurs in sandbox.  Change set is used to promote code, config, Profile 27, as well as field-level and object-level security.  This works.
Case 2:
Production org copied to Sandbox.  Development and config occurs in sandbox.  Profile 28 is created in sandbox.  Change set is used to promote code, config, Profile 28, as well as field-level and object-level security.
After deployment Profile 28 exists in Production, but the FLS is foobar and must be configured by hand.
It appears that in order for object and field level security details to promote correctly with a profile, the  following must be true:
1) profile is included in change set
2) objects/fields to which profile has access are included in change set
3) profile must already exist in target org, and must have been populated to source org by copy/refresh
Is there any way of creating a new profile in a sandbox, and promoting it to the production org in such a way that Field level and Object level security is correctly promoted as well?

A: I have consistently had problems with deploying profiles. It is incredibly difficult to get them to work with anything even remotely large. Specifically, there have been times where multiple projects have been worked on at a single time within a single organization. So, two sandboxes, one project going on in each of them, and then deploying that change causes issues. This is normally due to the fact the profile metadata doesn't match what it should because the organizations have access to different objects that aren't available in each environment due to the nature of the development.
Normally, I account for a significant amount of manual work in any of our deployments related to profiles. That seems to be the best approach so far as everything else has been unreliable.

A: Profiles are not one of the metadata components that can be deployed via changesets. I'm frankly surprised that it is even creating the profile in case 2. I would try the following and see if it works:

*

*Re-deploy the changeset after the profile exists in production

*Manually create a profile with the same name and see if FLS is applied.

A: Yes. The best way to deploy a profile that includes all the permissions, including Field Level Security, pages, etc. is using the "Full Profiles" deployment functionality of Copado Deployer appexchange app https://appexchange.salesforce.com/listingDetail?listingId=a0N3000000B3dgGEAR
and the 2 orgs does not need to be exactly the same, the tool will clean the differences for you.
kind regards.-


text:
Q: accessing forms field to upload file After uploading the image file and proceed with the details like name and description I have taxonomy reference term field and I need to have a control on that field to see if the taxonomy exists or no.
So I was thinking when clicking save button the script should run and return error... However, my problem is to find where is located the save button function.
my perfect solution is to upload an image with taxonomy and each taxonomy term should be linked to one image. 1 to 1 relation.
I have tried file.module, File.inc, Form.inc but useless.
does anyone have any solutions?

A: It's very bad pratice to modify core or contrib modules if you doesn't have a drupal expertise.
So , you can use hooks to add/modify elements to a form , in particulary hook_form_alter
Test it on submit :

function MYMODULE_form_alter($form, &$form_state, $form_id){

 if($form_id == 'id_of_my_form'){ // if you don't know it var_dump($form_id) on your page
   $form['#submit'][]  = 'my_custom_submit_callback'; // its your own function executed after core/contrib functions on submit
 }
}

function my_custom_submit_callback($form, &$form_state){

 // test your values
 if($form_state['values']['my_field_name']){
   // Deal with value
 }else{
   form_set_error('my_field_name', "Taxonomy is missing");
 }
}

NB : Clear cache registry after first creation of those function


text:
Q: ConfigParser.NoSectionError I'm relatively new to python and working with notebooks, but I am having problems with the config.txt file. I think the problem is from the notebook being in a separate file as the module I import (the config.txt file is in the same directory as the imported module). When I run the module in the notebook, I get the 'NoSectionError: No section:' error. However, when I copy and paste the code into the notebook, the code runs just fine.
Is there a problem with the working directory?
from src.data import psql_operations
db_connection = psql_operations.PostgresConnection()

class PostgresConnection:
    def __init__(self):
        config = configparser.ConfigParser()
        config.read(r....'/src/data/config.txt')
        self.host = config.get('psql database', 'host')
        self.db_name = config.get('psql database', 'db_name')
        self.user = config.get('psql database', 'user')
        self.password = config.get('psql database', 'password')
        self.port = config.get('psql database', 'port')

vs.
config = configparser.ConfigParser()
config.read(r.....'/src/data/config.txt')
host = config.get('psql database', 'host')
db_name = config.get('psql database', 'db_name')
user = config.get('psql database', 'user')
password = config.get('psql database', 'password')
port = config.get('psql database', 'port')

A: After about a week of trying to figure this out, I asked the question to find the solution an hour later. The path to the config file needed to be changed. The following needed to be added to the loaded module
import os
config.read(os.path.join(os.path.abspath(os.path.dirname(file)), '.../src/data', 'config.txt'))
The following link touches on the same problem
configparser not working in Python 3.4, NoSectionError but works fine in PyCharm


text:
Q: A query on PostgreSQL not working as it should I created 2 tables, one for drivers names and the other for their corresponding vehicles, my exercise is to pick out the driver whose registration date is less than a month away, the query should pick out only one driver but what happens is that it lists all the 3 drivers although the condition is not applied in the other 2 :
Creating schema:
create table drivers (
  id serial primary key,
  first_name varchar,
  last_name varchar
);

create table vehicles (
  id serial primary key,
  make varchar,
  model varchar,
  registration_date date,
  driver_id integer references drivers(id)
);
INSERT INTO drivers (id,first_name, last_name) VALUES (1,'John', 'Doe'),(2,'Michael', 'Doe'),(3,'Jane', 'Fonda');
INSERT INTO vehicles (make,model,registration_date, driver_id) VALUES ('Volkswagen', 'Jetta','2012-10-23',1),('Skoda', 'Octavia','2011-03-01',2),('Opel', 'Meriva','2015-08-01',3);

Query:
select d.first_name , d.last_name , v.make
from drivers d
join vehicles v
on v.driver_id= d.id
where v.registration_date::DATE  - CURRENT_DATE::DATE  < 30;

Result:
first_name  last_name   make
John         Doe        Volkswagen
Michael      Doe        Skoda
Jane         Fonda      Opel

A: A sort of convoluted example:
select
  registration_date, d.first_name , d.last_name , v.make
from
   drivers d
join
   vehicles v
on
   v.driver_id= d.id
where
   make_date(extract(year from current_date)::int, extract(month from  v.registration_date)::int, extract(day from v.registration_date)::int ) - current_date
between 0 and 29;

registration_date | first_name | last_name |    make
-------------------+------------+-----------+------------
 2012-10-23        | John       | Doe       | Volkswagen

Using make_date and extract from Date/time operators/functions. I could see turning the make_date(...) portion into a function.


text:
Q: What is the default behavior of the ENTER key press event? I have an Email Id text box. My requirement is that an user enters some valid Email ID into the Text box and Press Enter key. A status message or an error message should be displayed.
I have a button called Send after the Text box. On Click Send button or On ENTER key press(The focus should be on text box not on the Send button) it is going to make an Ajax call.
I have On Success and On Fail methods in that Ajax call. On Success I am going to display a status message saying "Successfully sent message". On Fail I am displaying some other error.
The problem is that I am  not able to see any status or error message on my page. Instead the page is getting refreshed. Is it because of the default behavior of the ENTER key press Event ?

A: Yes, it is because of the default behaviour. You can return false in your JScript  to avoid a post back from happening.


text:
Q: FastAPI - HTTP Basic Auth - Choose own usernam/pass & Base64 How can I add my username and password and add a base64 for Basic Auth. (https://fastapi.tiangolo.com/tutorial/security/http-basic-auth/)
I have read quite bit and I ended up even to setup OAuth2 with Password (and hashing), Bearer with JWT tokens but that ended up to be too much for me and all I need is only a simple Basic Auth and to add a small protection on it, basically add a base64.
The idea was to have something like this in header:
{'Authorization': 'Basic aGVsbG86d29ybGQ='} #hello:world
However my knowledge is pretty low and I am having the first issue with even configure on how to use my own username and password with:
from fastapi import Depends, FastAPI
from fastapi.security import HTTPBasic, HTTPBasicCredentials

app = FastAPI()

security = HTTPBasic()

@app.get("/users/me")
def read_current_user(credentials: HTTPBasicCredentials = Depends(security)):
    return {"username": credentials.username, "password": credentials.password}

My question:
How can I choose my own username and password and after that be ablet o use base64 to encode/decode the Authorization to be able to send to header something like:
{'Authorization': 'Basic aGVsbG86d29ybGQ='} #hello:world

A: I haven't worked with FastAPI, but I took a look at the docs. You have the following source code provided there:
from fastapi import Depends, FastAPI, HTTPException
from fastapi.security import HTTPBasic, HTTPBasicCredentials
from starlette.status import HTTP_401_UNAUTHORIZED

app = FastAPI()

security = HTTPBasic()

def get_current_username(credentials: HTTPBasicCredentials = Depends(security)):
    if credentials.username != "foo" or credentials.password != "password":
        raise HTTPException(
            status_code=HTTP_401_UNAUTHORIZED,
            detail="Incorrect email or password",
            headers={"WWW-Authenticate": "Basic"},
        )
    return credentials.username

@app.get("/users/me")
def read_current_user(username: str = Depends(get_current_username)):
    return {"username": username}

So what you have to do is to use a Depends object. This hier is a simple example, but usually your get_current_username() would do a database query to check if the user and their corresponding password exist.
You can also take a look at this git-repo https://gist.github.com/nilsdebruin/8b36cd98c9949a1a87e3a582f70146f1
I hope this helps you! :)


text:
Q: Stored Procedure for Login Authentication not working MySQL I am working Login Authentication with Stored Procedures in MySQL Database.
Below is the code, i wrote but its not working. Let me know, what is wrong.
I have below questions

*

*How to check, whether CURSOR is empty or null

*Is there any way, we write the procedure.

What I am doing..

*

*Taking two input parameters and two parameters for ouput.

*Check if the user or password is not valid, stored those values in OUT parameters
SELECT 'Invalid username and password', 'null' INTO oMessage, oUserID;

*If user and password in valid, but isActive column is 0  then
SELECT 'Inactive account', 'null' INTO oMessage, oUserID;

*If success,
SELECT 'Success', v_UserID INTO oMessage, oUserID;
SQL Code
DELIMITER $$

USE `acl`$$

CREATE
    DEFINER = `FreeUser`@`localhost`
    PROCEDURE `acl`.`checkAuthenticationTwo`(
    IN iUsername VARCHAR(50),
    IN iPassword VARCHAR(50),
    OUT oMessage VARCHAR(50),
    OUT oUserID INT
    )

    BEGIN
    DECLARE v_isActive INT;
    DECLARE v_UserID INT;
    DECLARE v_count INT;
    DECLARE cur1 CURSOR FOR SELECT UserID, IsActive FROM m_users WHERE (LoginName = TRIM(iUsername) OR Email = TRIM(iUsername)) AND `Password` = iPassword;

    OPEN cur1;
    SET v_count = (SELECT FOUND_ROWS());

    IF (v_count > 0)

        FETCH cur1 INTO v_UserID, v_isActive;

        IF (v_isActive = 0) THEN
            SELECT 'Inactive account', 'null' INTO oMessage, oUserID;
        ELSE
            SELECT 'Success', v_UserID INTO oMessage, oUserID;
        END IF;

    ELSE
        SELECT 'Invalid username and password', 'null' INTO oMessage, oUserID;
    END IF;

    END$$

DELIMITER ;

A: You definitely don't need CURSORs for that; use plain simple SELECT. A more concise version of your SP might look like
DELIMITER $$
CREATE DEFINER = `FreeUser`@`localhost` PROCEDURE `acl`.`checkAuthenticationTwo`
(
    IN iUsername VARCHAR(50),
    IN iPassword VARCHAR(50),
    OUT oMessage VARCHAR(50),
    OUT oUserID INT
)
BEGIN
    SELECT CASE WHEN IsActive = 0 THEN 'Inactive account' ELSE 'Success' END,
           CASE WHEN IsActive = 0 THEN NULL ELSE UserID END
      INTO oMessage, oUserID
      FROM m_users
     WHERE (LoginName = TRIM(iUsername)
           OR Email = TRIM(iUsername))
       AND `Password` = iPassword
     LIMIT 1; -- you better protect yourself from duplicates
    SET oMessage = IFNULL(oMessage, 'Invalid username and password');
END$$
DELIMITER ;

What it does it tries to select a row where username or email equals to iUsername and password equals to iPassword and outputs two values to output variables. Along the way it uses CASE to look at isActive value. If it's 0 then sets a message to 'Inactive' and NULL for userid. Otherwise it returns 'Success' message and real userid that has been found. Now, if a user has not been found both variables will be set to NULL. We can leverage that and use IFNULL() function to detect that fact and set a message to 'Invalid username and password'.
Here is SQLFiddle demo
Personally I'd go further and simplify it a bit more and make it a one-statement SP with the following interface:

Returns:
   userid (which is > 0) if a user with username and password if found
   0                     - username and(or) password incorrect
  -1                     - a user is inactive

The idea is that it's a presentation layer's task to produce appropriate messages for the user  and not scatter all those message literals across data layer.
CREATE DEFINER = `FreeUser`@`localhost` PROCEDURE `acl`.`checkAuthenticationThree`
(
  IN iUsername VARCHAR(50),
  IN iPassword VARCHAR(50),
  OUT oUserID INT
)
  SET oUserID = IFNULL(
  (
    SELECT CASE WHEN IsActive = 0 THEN -1 ELSE UserID END
      FROM m_users
     WHERE (LoginName = TRIM(iUsername)
           OR Email = TRIM(iUsername))
       AND `Password` = iPassword
     LIMIT 1 -- you better protect yourself from duplicates
  ), 0);

Here is SQLFiddle demo


text:
Q: Set constant for reusing HTML I am trying to set a WWW_ROOT in order to reuse HTML code in different pages. This is an example of users.php using a header, where the CSS files are not found - 404 (Not Found) and I got Notice: Undefined variable: project_end in /Applications/XAMPP/xamppfiles/htdocs/lpweb/assets/php/initialize.php on line 11

Folder structure
>localhost
  >lpweb
       >index.php
       >pages
          >users.php
       >assets
          >php
             >initialize.php
             >header.php
          >css
             >bootstrap.min.css

initialize.php
<?php
  define("PHP_PATH", dirname(__FILE__));
  define("ASSETS_PATH", dirname(PHP_PATH));

  $public_end = strpos($_SERVER['SCRIPT_NAME'], '/lpweb') + 7;
  $doc_root = substr($_SERVER['SCRIPT_NAME'], 0, $project_end); //line 11
  define("WWW_ROOT", $doc_root);
?>

header.php
<link rel="stylesheet" media="all" href="<?php echo WWW_ROOT . 'assets/css/bootstrap.min.css'; ?>"> />

users.php
<?php require_once('../assets/php/initialize.php'); ?>
<?php include(PHP_PATH . '/header.php'); ?>

A: You are mixing $public_end and $project_end
Also after reviewing your code from GitHub I believe this will work for you.
define("WWW_ROOT",$_SERVER['REQUEST_SCHEME']."://".$_SERVER['HTTP_HOST'].rtrim($_SERVER['REQUEST_URI'],'/'));

Alternatively, you can use the relative path to refer to CSS files which will make your life easy
<link rel="stylesheet" media="all" href="assets/css/bootstrap.min.css" />


text:
Q: Closing the jsp page based on user choice I have a jsp page where if the user closes the page the popup box should appear asking whether he really wants to close the page.
If he chooses to close the page then i need to redirect to another jsp page using ajax.
How do i achieve the same.
I have a sample code which asks the user when he clicks the close button but this message is getting popped up when refresh,submit or clear buttons or any other buttons are pressed.
Can anyone sggest to modify the given code or any new functionality which achieves the same.
    sample.jsp

<title>Refresh a page in jQuery</title>

Stop a page from exit with jQuery

<button id="reload">Refresh a Page in jQuery</button>

A: $(window).bind('beforeunload', function(){
  return 'Are you sure to leave';
});

$(window).bind('unload', function(){
  $.ajax({
      url:'some url',
      success:function(data){
          $("body").html(data);
      }

  })
})

you should unbind events before refresh
$('#reload').click(function() {
    $(window).unbind("beforeunload");
    $(window).unbind("unload");
    location.reload();

});


text:
Q: $L^1$-Cauchy sequence of step functions that converges a.e. also converges in $L^1$ Let $X$ be a measure space and $E$ be a Banach space.  A step function from $X$ to $E$ is a measurable function ($E$ takes the Borel measure) with finite image and whose support has finite measure.
If $(f_n)$ is a Cauchy sequence of step functions that converge a.e. to a function $f$, then do they also converge to $f$ in the $L^1$ seminorm?
The context for this question is that Lang seems to make this leap in his proof of Theorem 3.4 on page 133 of Real and Functional Analysis, and I want to know if the proof is still correct.

A: Cauchy in what sense? If they are pointwise Cauchy the here is a counterexample. On the real line with Lebesgue measure let $f_n= \sum\limits_{k=1}^{n} \frac 1 k I_{(k,k+1)}$. Then $f_n \to f=\sum\limits_{k=1}^{\infty} \frac 1 k I_{(k,k+1)}$ but $f_n$ does not tend to $f$ in $L^{1}$ because $\int |f_n-f|=\infty$ for each $n$.
If $(f_n)$ is Cauchy in $L^{1} (X,B)$ then it converges to some $g$ in $L^{1}(X,B)$ by completeness of the latter and $f=g$ in view of  the fact that some subsequence of $\|f_n -g\| \to 0$ almost everywhere.

A: As Kavi Rama Murthy points out, if the sequence is Cauchy in $L^1$, then it converges to $f$ in $L^1$.  He has provided a counterexample in the case that the sequence $\{ f_n \}$ is merely pointwise Cauchy.  In his example, the pointwise limit $f$ is not in $L^1$.  However, it is possible to construct a counterexample in which the limit function is in $L^1$.  One such example is given by setting $f_n = \frac{1}{n}I_{[0,n]}$, where $I_{[0,n]}$ is the indicator function for the interval $[0,n]$.  The sequence $f_n$ is (uniformly) Cauchy because if $n,m \geq N$, then $|f_n(x) - f_m(x)| \leq \frac{2}{N}$ for all $x$.  The sequence tends pointwise to the zero function but does not converge to $0$ in $L^1$ because $\| f_n \|_1 = 1$ for al $n$.


text:
Q: 2D vector multiplication my problem is that when i try to multiply a 2D vector by another 2D vector and store the result of the process in another 2D vector my programme crash
    int main()
{

    vector< vector<double> > Mat_1;
    vector< vector<double> > Mat_2;
    vector< vector<double> > Mat_3;
// Generate 2D vector 5 by 5
    setVector(Mat_1,5,5);
    setVector(Mat_2,5,5);

    for(int i=0; i<5;i++)
    {
        for(int j=0;j<5;j++)
        {
            Mat_3[i][j] = 0;

            for(int k=0;k<5;k++)
            {
                Mat_3[i][j] += Mat_1[i][k] * Mat_2[k][j];
            }
        }
    }

    return 0;
}

A: You didn't initialize the 3rd matrix, and you are doing indexing operations on it, that's Undefined Behaviour. You can do this....
void init_2Dvector(vector<vector<double> >& vec, int x_dim, int y_dim){
    vec.resize(x_dim);
    for(int i=0; i < vec.size(); i++)
         vec[i].resize(y_dim);
}

int main()
{

    vector< vector<double> > Mat_1;
    vector< vector<double> > Mat_2;
    vector< vector<double> > Mat_3;
// Generate 2D vector 5 by 5
    setVector(Mat_1,5,5);
    setVector(Mat_2,5,5);

// Set dimension for result
    init_2Dvector(Mat_3, 5, 5);

    for(int i=0; i<5;i++)
    {
        for(int j=0;j<5;j++)
        {
            Mat_3[i][j] = 0;

            for(int k=0;k<5;k++)
            {
                Mat_3[i][j] += Mat_1[i][k] * Mat_2[k][j];
            }
        }
    }

    return 0;
}

A: This line will cause problemS:
    Mat_3[i][j] = 0;

Since you (atleast from the code you showed) never initialize Mat_3, try adding:
setVector(Mat_3,5,5);

A: You need to initialize Mat_3.  So make sure to set its dimensions same as you did with other Matrices.
This should work once you include proper libraries and do not use using namespace std;
int main()
{
    std::vector<std::vector<double>> Mat_1;
    std::vector<std::vector<double>> Mat_2;
    std::vector<std::vector<double>> Mat_3;
    setVector(Mat_1,5,5);
    setVector(Mat_2,5,5);
    setVector(Mat_3,5,5); // here initialize

    for(int i=0; i<5;i++)
    {
        for(int j=0;j<5;j++)
        {
            Mat_3[i][j] = 0; // here assigning zeros

            for(int k=0;k<5;k++)
            {
                Mat_3[i][j] += Mat_1[i][k] * Mat_2[k][j]; // operation
            }
        }
    }
    return 0;
}

A: This works even if input matrices are different dimensions, e.g., 3x2 and 2x4.
vector<vector<double>> multiply_2d_vectors(std::vector<std::vector<double>> & v1, std::vector<std::vector<double>> & v2)
{
    int v1_row = v1.size();
    int v1_col = v1[0].size();
    int v2_row = v2.size();
    int v2_col = v2[0].size();
    // v1_col must be equal to v2_row

    std::vector<std::vector<double>> v3;
    setVector(v3,v1_row,v2_col);

    for(int i=0; i < v1_row; i++)
    {
        for(int j=0;j < v2_col;j++)
        {
            v3[i][j] = 0;

            for(int k=0; k < v1_col; k++)
            {
                v3[i][j] += v1[i][k] * v2[k][j];
            }
        }
    }
    return v3;
}


text:
Q: Necessary and sufficient conditions for rank-$1$ update of positive definite matrix to be positive definite Given $A \succ 0$, what are necessary and sufficient conditions on $\lambda \in \mathbb{R}$ for $A + \lambda u u^\top$ to be positive definite?
What happens if we relax $A \succeq 0$ and require $A + \lambda u u^\top \succeq 0$?

A: According to the Sherman-Morrison formula, $\det(A+\lambda uu^T)>0$  iff $1+\lambda u^TA^{-1}u>0$. Then the required condition is
$\lambda >\dfrac{-1}{u^TA^{-1}u}$.

A: When $A\succ0$, $A+\lambda uu^T=A^{1/2}(I+\lambda A^{-1/2}uu^TA^{-1/2})A^{1/2}$ is positive definite if and only if all eigenvalues of $I+\lambda A^{-1/2}uu^TA^{-1/2}$ are positive, i.e. if and only if
$$
1+\lambda u^TA^{-1}u>0.\tag{1}
$$
If $A$ is positive semidefinite, there are three possibilities:

*

*$\lambda\ge0$. Then $A+\lambda uu^T$ is positive semidefinite.

*$v=(I-AA^+)u=0$, i.e. $u$ lies inside the column space of $A$. Then $(1)$ applies when $A$ and $u$ are replaced by their restriction or orthogonal projection on the column space of $A$. Hence $(1)$ should be modified to $1+\lambda u^TA^+u\ge0$.

*$\lambda<0$ and $v=(I-AA^+)u\ne0$. Then $A+\lambda uu^T$ is not positive semidefinite. In particular, we have $v^T(A+\lambda uu^T)v=\lambda\|v\|^4<0$.

In other words, when $A\succeq0$, $A+\lambda uu^T$ is positive semidefinite if and only if (a) $\lambda\ge0$ or (b) $(I-AA^+)u=0$ and $1+\lambda u^TA^+u\ge0$.


text:
Q: How to correctly type my react context provider? I'm trying to implement a context provider in my react web app but the problem is that the typing is wrong. I'm expecting to have the type of User or null but the type is { }. The following code is the implementation of the context provider. How can I make it so that the context provider only returns a User or null?
import React, { createContext, useState, useEffect } from 'react'

interface User {
    username: string,
    id: number,
    token: string,
}

const AuthContext = createContext([{}, () => {}])

const AuthProvider = ({children}: {children: React.ReactNode} ) => {
    const [user, setUser] = useState<User | null>(null)

    useEffect(() => {
          if(sessionStorage.getItem('state')) {
              let x: string | null = sessionStorage.getItem('state')

              if (x !== null) {
                let y: User = JSON.parse(x!.toString())
                setUser(y)
              }
        }
    }, [])

    useEffect(() => {
        sessionStorage.setItem('state', JSON.stringify(user))
    }, [user])

    return (
        <AuthContext.Provider value={[user!, setUser]}>
            {children}
        </AuthContext.Provider>
    )
}

export { AuthContext, AuthProvider }

A: You can use generics to type the context. Pass in a type variable to createContext<TYPE>(). It would look like this:
interface User {
  username: string
  id: number
  token: string
}

const AuthContext = createContext<
  [User | null, React.Dispatch<React.SetStateAction<User | null>>]
>([null, () => {}])

You can see it in action here.


text:
Q: MakeScreenshot leaking? Good evening all!
In a current project, i'm experiencing a rather worrying memory leak that i just can't seem to plug.
I left the application running overnight with standard usage going on and when i awoke 8 hours later, it was eating up ~750MB memory whereas it started at ~50MB. Windows Task Manager isn't suited for checking for leaks other than allowing you to find out that one exists in the first place.
I cleared up a few other memory leaks already, with the major one being related to Firemonkeys' TGlowEffect. It isn't detected by ReportLeaksOnShutdown but the memory usage of it becomes extremely excessive on dynamically modified object (e.g. rotation or scale changes).
I've tracked it down to a timer (and disabling it stops the leak completely), and i require assistance in fixing it if possible.
Description: This code uses the Firemonkey MakeScreenshot function to save the visual appearance of a TPanel (SigPanel) to a TMemoryStream. This stream data is then uploaded to a remote FTP server using standard code (see below). Inside SigPanel, there are 4 TLabel children, 1 TRectangle child, and 6 TImage children.
Notes: CfId is a global string and is generated based upon a random extended float value that is then hashed along with the DateTime in format yyyymmdd_hhnnsszzz. This generation is done when the form is created, and it repeats until it get's a valid CfId (i.e. doesn't contain characters illegal for use in Windows filenames). Once it gets a valid CfId, it doesn't run again at all (as there's no further need for me to generate a new ID). This allows me to almost completely eliminate the chance of duplicate CfId.
The code in the timer is as follows;
var
  i : Integer;
  SigStream : TMemoryStream;
begin
  SigStream := TMemoryStream.Create;
  SigPanel.MakeScreenshot.SaveToStream(SigStream);
  SigPanel.MakeScreenshot.Free;
  if VT2SigUp.Connected then
  begin
    VT2SigUp.Put(SigStream,'Sig_'+CfId+'.png',False);
  end else
  begin
    VT2SigUp.Connect;
    VT2SigUp.Put(SigStream,'Sig_'+CfId+'.png',False);
  end;
    SigStream.Free;
end;

With the timer NOT running, the code functions completely without leaks and ReportMemoryLeaksOnShutdown does NOT generate a message. With the timer enabled and being allowed to "run" at least once, i'm getting a lot of leakage which increases the more times the timer runs. The reported leaks are as follows;
Small Block Leaks

1 - 12 Bytes: Unknown x 1
13 - 20 Bytes: TList x 5, Unknown x 1
21 - 28 Bytes: TFont x 2, TGradientPoint x 8, TGradientPoints x 4, Unknown x 4
29 - 36 Bytes: TObjectList<FMX.Types.TCanvasSaveState> x 1, TBrushBitmap x 4,
TBrushGrab x 4, TPosition x 24, TGradient x 4, UnicodeString x1
37 - 44 Bytes: TBrushResource x 4
53 - 60 Bytes: TBrush x 4
61 - 68 Bytes: TBitmap x 5
69 - 76 Bytes: TD2DCanvasSaveState x 1
205 - 220 Bytes: TCanvasD2D x 1

Sizes of Medium and Large Block Leaks
200236

As the timer runs, these values are multiplied n times (n being the number of times the timer has run). The medium and large blocks have n worth of 200236 (e.g. if the timer has run 3 times, it's 200236, 200236, 200326).
Of Interest, if i remove the code associated with MakeScreenshot, the leak no longer exists, and memory usage remains at a somewhat normal level. Beside the usual memory usage, there's nothing out of the ordinary and no leaks are reported. I've tried multiple samples of code, both with saving to a stream and uploading from there, or saving to stream > File and then uploading the file, but there appears to be a leak within the function itself. I even added MakeScreenshot.Free once i discovered a leak here, but i simply can't seem to plug it, and of course, i've used try..finally in one of my code "test runs".
I've even run the code with GDI+ as the canvas type and the same leak occurs there (with the only change being that the D2D leaks reference GDI+ instead).
I'd very much appreciate any research or notes anyone has on this, and moreover, a solution to the issue.

A: You are not freeing the bitmap that MakeScreenshot creates.
procedure TForm1.Button1Click(Sender: TObject);
var
  ms: TMemoryStream;
begin
  ms := TMemoryStream.Create;
  Panel1.MakeScreenshot.SaveToStream(ms);
  ms.Free;
end;

The above code does not keep a reference to the created bitmap, hence has no chance to free it. Instead change your design like the below:
procedure TForm1.Button2Click(Sender: TObject);
var
  ms: TMemoryStream;
  bmp: TBitmap;
begin
  ms := TMemoryStream.Create;
  bmp := Panel1.MakeScreenshot;
  bmp.SaveToStream(ms);
  ms.Free;
  bmp.Free;
end;

With the below code you're in fact creating two bitmaps and freeing one of them.
  SigPanel.MakeScreenshot.SaveToStream(SigStream);
  SigPanel.MakeScreenshot.Free;

In the end, your code would be more like the below:
var
  i : Integer;
  Bmp: TBitmap;
  SigStream : TMemoryStream;
begin
  SigStream := TMemoryStream.Create;
  try
    Bmp := SigPanel.MakeScreenshot;
    try
      Bmp.SaveToStream(SigStream);
      if not VT2SigUp.Connected then
        VT2SigUp.Connect;
      VT2SigUp.Put(SigStream, 'Sig_'+CfId+'.png', False);
    finally
      Bmp.Free;
    end;
  finally
    SigStream.Free;
  end;
end;

A: I tried using it in fmx, but it didn't work so I took a similar function from FMXexpress, which was also memory leaked and modified it.
I transformed the function into a procedure where you pass 2 parameters. The first is an object where you want the makescreen and the second the target object. At the end it clears the memory.
class Procedure MakeScaleScreenshot(Sender: TControl; SetImg: TImage);

Class Procedure MakeScaleScreenshot(Sender: TControl; SetImg: TImage);
var
  fScreenScale: Single;
  Result:TBitmap;
function GetScreenScale: Single;
  var
    ScreenService: IFMXScreenService;
  begin
    Result := 1;
    if TPlatformServices.Current.SupportsPlatformService(IFMXScreenService,
      IInterface(ScreenService)) then
    begin
      Result := ScreenService.GetScreenScale;
    end;
  end;

begin
  fScreenScale := GetScreenScale;
  Result := TBitmap.Create(Round(Sender.Width * fScreenScale), Round(Sender.Height * fScreenScale));
  Result.Clear(0);

  if Result.Canvas.BeginScene then
  try
    Sender.PaintTo(Result.Canvas, RectF(0, 0, Result.Width, Result.Height));
  finally
    Result.Canvas.EndScene;
    SetImg.Bitmap:=Result;
  end;

 Result.FreeHandle;
 Result.DisposeOf;

end;

//how to use

Procedure
Begin
  {TControl source screen}, {Img destiny of the TImage type}
  MakeScaleScreenshot(Image1,Image2);
end;


text:
Q: Text on horizontal bar chart - d3 I have a horizontal bar chart on which i'm displaying the field name. If the name(text) exceeds the bar , the text has to be in black color like in below. How would i do that?

A: This is not a trivial thing to do. You would have to

*

*Add the text.

*Determine its actual dimensions using .getBBox() or something similar.

*Remove the text.

*Split the text into separate segments (e.g. tspans) depending on its actual width and the width of the bar.

*Add those segments with the respective styles.

That is, you would have to manually break up the text into the parts that you want different styles for and then assign those styles.

A: I've managed to do it using two text labels. Top label is wrapped in svg so it clips its length. Here is working example - http://jsfiddle.net/cuckovic/C6SSj/
bar.append("text")
    .attr("class", "below")
    .attr("x", 12)
    .attr("dy", "1.2em")
    .attr("text-anchor", "left")
    .text(function(d) { return d.sharedLabel; })
    .style("fill", "#000000");

bar.append("rect")
    .attr("class", "malebar")
    .attr("height", barWidth-gap)
    .attr("x", 10);

bar.append("svg")
    .attr({
        height: barWidth-gap
    })
    .append("text")
    .attr("class", "up")
    .attr("x", 12)
    .attr("dy", "1.2em")
    .attr("text-anchor", "left")
    .text(function(d) { return d.sharedLabel; })
    .style("fill", "#ffffff");


text:
Q: Converting .bin to image coefficients and creating binary image using MATLAB and C I'm working on a homework assignment and we were given a .bin file that contained the data for a gray scale image. The objective here is to write C code that will convert this from a gray scale to a binary image. First thing was to open the greyscale image in MATLAB which I managed to do via:
A = fread(file, 256*256, 'uint8=>uint8');
A = reshape(A, 256, 256).';
imshow(A);

Great. I have my image coefficients which I split into 4 arrays and stuffed into C header files. I had to do it this way because the micro controller we're using for this class - the MSP430 - can't handle them all at once. I imported the first header file, set up my variables, and here is where all the heavy lifting is done:
for (i = 0; i == 16384; i++){
    if (suzi[i] >= 95){ //95 is given threshhold
        temp = 0b0000000;
    }
    else{
        temp = 0b00000001 << shiftby; //will right shift by 7, then 6, then 5 until 0 and then wrap back to 7
    }

    current = previous | temp; //updates the 8 bit data with the latest bit
    if(shiftby > 0){
        shiftby--; //decrements shifts until 0
    }
    else{
        shiftby = 7; //wraps back to 7
        suziarr[arrayindex] &= 0b00000000; //makes sure this value is 8 0s
        suziarr[arrayindex] |= current; //sets bits to match current 8 bit value
        current = 0b00000000;
        arrayindex++; //this is why the array will be 1/8 the size
    }

    previous = current; //update state

}

The temp, suzi, suziarr, previous, and current variables are declared as type unsigned char. suzi is also a const and is one of the arrays I stuffed into header files. suzi is set to length 13684 and suziarr is set to length 2048. For whatever reason, I get the exact same numbers no matter which of the 4 sets of data I use, so something is wrong here. What am I missing?

A: The loop
for (i = 0; i == 16384; i++)

will not iterate. It should be
for (i = 0; i < 16384; i++)


text:
Q: css text gradient I've had  alittle look around and can't find anything about this.
If i have a paragraph of text, is there a way, maybe with CSS3 to gradually change the colour of the text as it goes down to the page? instead of the way that gradient does it, because that only does it on the word not the whole paragraph of text.
So i want some text to start off white and then fade into black as it gets to the end of the paragraph.
I'm really not sure it can be done... Maybe there is a java script that can do it.
Thanks.

A: Here's a simple solution with basic CSS. You can add an overlay div with linear-gradient from white to transparent. This div will take the full width and height of the desired text.
Example:

      Some text

      Some text

      Some text

      Some text

A: You can do it using CSS but it will only work in webkit browsers (Chrome and Safari):

p {
    background: linear-gradient(red, blue);
    -webkit-background-clip: text;
            background-clip: text;
    -webkit-text-fill-color: transparent;
}

blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah

A: I was able to do something similar in pure css, however, it does not work in IE, since it does not support mix-blend-mode css property:
http://caniuse.com/#feat=css-mixblendmode
The code snippet is below. Hope it helps someone.

"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."

A: In 2021, we can do this cross-browser!
p {
    background-image: linear-gradient(red, blue);
    color: transparent;
    background-clip: text;
    -webkit-background-clip: text;
}

Some things to note:

*

*A lot of the old examples use -webkit-text-fill-color rather than color. The two are actually functionally identicial[1] (and both support transparent!), -webkit-text-fill-color just takes precidence. The reason this was used in old examples was because it provided a graceful fallback for non-webkit browsers --- any non-webkit browser that ignored the gradient or clip instructions would also ignore the -webkit-text-fill-color instruction, meaning that you wouldn't be left with transparent text on unsupported browsers. I guess this is a problem with this cross browser implementation, in that that we can't do a fallback like this, but it'll really only be a problem for really old browsers like IE11.

*background-clip is now standards tracked and implemented in other browsers (e.g. Firefox), but strangely the Chrome folks have chosen to keep the text clip option only available on their own vendor prefixed version, which is why we still need both[2].

I have tested this, and it does work in Chrome 95 & Firefox 91.

A: The easiest way for cross-browser text gradients is to use an image.
http://webdesignerwall.com/tutorials/css-gradient-text-effect

A: This do
 .p {
      background: linear-gradient(to right, #911a80, #d42b45);
      background-clip: text;
      color: transparent;
    }


text:
Q: handleEventsForBackgroundURLSession never called when a downloadTask finished I am using AFURLSessionManager, and set the manager as a singleton instance.
- (AFURLSessionManager *)backgroundSession
{
    static AFURLSessionManager *backgroundSession = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
    NSURLSessionConfiguration *config = [NSURLSessionConfiguration backgroundSessionConfiguration:@"com.testBackground.BackgroundDownload.BackgroundSession1234"];
    backgroundSession = [[AFURLSessionManager alloc]initWithSessionConfiguration:config];
    [backgroundSession setDownloadTaskDidWriteDataBlock:^(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, int64_t bytesWritten, int64_t totalBytesWritten, int64_t totalBytesExpectedToWrite){
        NSLog(@"i am downloading my id = %d progress= %f",downloadTask.taskIdentifier, totalBytesWritten*1.0/totalBytesExpectedToWrite);
        [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;

    }];
    [backgroundSession setDownloadTaskDidFinishDownloadingBlock:^NSURL *(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, NSURL *location){
        NSLog(@"download finished");
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        return location;

    }];
    });
    return backgroundSession;
}
//assign a download task
NSURLSessionDownloadTask *task = [manager1 downloadTaskWithRequest:request progress:&progress destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
        return targetPath;
    } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
    NSLog("%download success");
}];
[task resume];

I found that when I switch the app to the background the download task is running but when it was finished, the system call handleEventsForBackgroundURLSession will never be called.I am feeling that I have missed some setting or options. Any idea will be useful for me, thanks a lot.
- (void)application:(UIApplication *)application handleEventsForBackgroundURLSession:(NSString *)identifier completionHandler:(void (^)())completionHandler;

A: You probably have figured this out already but anyway, the exact same thing has happened to me while writing some test code to play with the background transfer service APIs (without AFNetworking). The solution was simply to change the identifier string for my background session configuration. Somehow the one I was using got bugged and the system wouldn't trigger the handleEventsForBackgroundURLSession callback. And not even restarting the device fixes it... however just changing the identifier does.
My theory is that my code created multiple instances of NSURLSession with the same configuration, which Apple clearly advices against (they say in the documentation that it has an undefined behavior if you do). I was obtaining the NSURLSessionConfiguration in the view controller's viewDidLoad method without a dispatch_once block, so it's certainly plausible that that happened.

A: As stated by Apple:

If an iOS app is terminated by the system and relaunched, the app can use the same identifier to create a new configuration object and session and retrieve the status of transfers that were in progress at the time of termination. This behavior applies only for normal termination of the app by the system. If the user terminates the app from the multitasking screen, the system cancels all of the session's background transfers. In addition, the system does not automatically relaunch apps that were force quit by the user. The user must explicitly relaunch the app before transfers can begin again.

Hope it helps.
Stefan


text:
Q: Creating simple collision detection I've created a very simple program where I drew a maze using paint (the method fillRect was used to create the walls of the maze), and I've created a sprite that is moved using keyListener. I want to implement a simple (as I'm in my first year of commuter science) collision detection to keep the sprite from moving through the walls of the maze. Because the maze is drawn in almost 400 lines of code, I won't include it.
import java.awt.*;
import java.applet.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

public class IndeProj extends Applet implements KeyListener {

    //KEY LISTENER INFO FOR MY SPRITE
    public int x = 10;
    public int y = 575;
    public boolean keyUp;
    public boolean keyDown;
    public boolean keyLeft;
    public boolean keyRight;

    public void paint(Graphics g) {
        //drawMaze
        drawMazeHorizontalLines(g);
        drawMazeVerticalLines(g);

        //SPRITE STUFF
        addKeyListener(this);
        this.MoveRect(g,x,y);

    }

    public void drawMazeHorizontalLines(Graphics g)
    {
        //This method draws the horizontal lines of the maze using the method `fillRect(x,y,w,h)`
    }

    public void drawMazeVerticalLines (Graphics g)
    {
        //This method draws the vertical lines of the maze using `fillRect(x,y,w,h)`
    }

    public void MoveRect(Graphics g, int x, int y) //Draws Sprite
    {
        g.setColor(Color.green);
        g.fillRect(x,y,20,20);
        g.setColor(Color.yellow); //Sprite body
        g.fillRect(x,y,20,20);
        g.setColor(Color.green); //Sprite eyes
        g.fillRect(x,y,7,7);
        g.fillRect((x+13),y,7,7);
        g.setColor(Color.blue); //Sprite pants
        g.fillRect(x,(y+13),20,7);
        g.setColor(Color.black); //Sprite mouth
        g.fillRect((x+6),(y+9),8,2);
    }

    public void keyPressed(KeyEvent e) //Moves Sprite
    {
        if (e.getKeyCode() == KeyEvent.VK_DOWN) {
            y+=1;
            y+=0;
        } if (e.getKeyCode() == KeyEvent.VK_UP) {
            y-=1;
            y-=0;
        } if (e.getKeyCode() == KeyEvent.VK_LEFT) {
            x-=1;
            x-=0;
        } if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
            x+=1;
            x+=0;
        }
        repaint();
    }
    public void keyReleased(KeyEvent e) //Stops Sprite
    {
         keyUp = keyDown = keyLeft = keyRight = false;
    }
}

I want to make it so that the sprite stops when it hits a wall (using x and y coordinates), the sprite will stop moving.

A: here is a simple way of collision detection, the map is a grid of ints each int has
the wall it contains.
If you do this wrong you will get magical one way walls.
/* could use enums for this */
public static int WALL_LEFT = 1;
public static int WALL_RIGHT = 2;
public static int WALL_TOP = 4;
public static int WALL_BOTTOM = 8;

public int[][] createSimpleMap(){
    int[][] map = new int[2][2];
    map[0][0] = WALL_LEFT | WALL_RIGHT | WALL_TOP;
    map[0][1] = WALL_LEFT | WALL_RIGHT | WALL_TOP;
    map[1][0] = WALL_LEFT | WALL_BOTTOM;
    map[1][1] = WALL_RIGHT | WALL_BOTTOM;
    return map;
}

to do the collision detection just detect if the wall is present.
public boolean canMoveUp(x,y){
    return (this.map[x][y] & WALL_TOP) ==0;
}

A: The way I would do it is by using rectangular collision boxes. The playerX and playerY is the player's coords:
while(true) {
    while(!((playerX > 50 && playerX < 100) && (playerY > 50 && playerY < 100))){
        //Put code to let they players walk here, and boundaries will be enforced.
    }
}

That would be a rectangular box that you cant go within the boundaries of.

A: If your applet is double buffered, then you can do the following before they move:
Color c = new Color(buffer.getRGB(desiredPlayerX, desiredPlayerY));
if(c.equals(<Whatever color you used for the maze walls>)){
    // Don't allow the movement of the player
}else{
    x = desiredPlayerX;
    y = desiredPlayerY;
}

This method does seem a little "hacky" though, and I'm sure there are better ways to implement it, but this is a possible quick solution.


text:
Q: Fixtures for Mongoengine with Django not working I am using Mongoengine(version: 0.9.0 ) with Django(version: 1.8).
This is my settings.py
DATABASES = {
 'default': {
   'ENGINE': 'django.db.backends.dummy'
    }
  }
MONGO_DBNAME = "mydatabasename"
MONGO_HOSTNAME = "localhost"

connect(MONGO_DBNAME, host=MONGO_HOSTNAME)

I want to have fixtures for the application. I have created initial_data.json in myapp/fixtures/ location.
When I run the command python manage.py dumpdata , I get the following error :

CommandError: Unable to serialize database: settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details.

Questions:
1) Any workaround for this problem ?
2) Is there any other way to load the initial data ?
References at this link
Thank you

A: Mongoengine itsn a backend(in django terminology). Its has own models (schemas) and DOM (like ORM in docuemnt db's) but it dont have a Django backend adapters.
You can use it. But there is issue while workind with out-of-box Django solution like Tests, Fixtures, etc.
You need to write your own loader, sadenly but true.
I see 2 options here:

*

*You can try to use Django MongoDB Engine

*You can write your own loader for mongodb

Ill write my own fixture loader for tests.
I have a json file where mapped all fixture file ill need to load to db.
So a fast example here:
import bson
import os
from django.conf import settings
from mongoengine.connection import get_db

def _get_db(self):
    self.db = get_db()

def _load_fixtures(self, clear_before_load=True):
    """
    Load to db a fixtures from folder fixtures/{{DB_NAME}}/{{COLLECTION_NAME}} before each test.
    In file fixtures.json mapped collection name and file name for it.
    """
    fixture_path = lambda file_name: os.path.join(settings.FIXTURES_DIR, self.db.name, file_name)
    with open(settings.COLLECTION_FIXTURES_PATH) as file_object:
        db_collections = loads(file_object.read())
        for collection_name, filename in db_collections.items():
            collection = self.db[collection_name]
            if clear_before_load:
                collection.remove()
            path = fixture_path(filename)
            if os.path.exists(path) and os.path.isfile(path):
                with open(path, 'r') as raw_data:
                    collection_data = bson.decode_all(raw_data.read())
                    for document in collection_data:
                        collection.save(document)

A: There is no support for fixtures on mongoengine, and I don't think the mongoengine team is continuing the plugin as of version 0.9.0.
What I ended up doing to load initial data for mongoDB is to create a script called startup.py in my project folder.
startup.py:
from {{app}}.models import Sample

def init():
    if Sample.objects(name="test").count() == 0: # a flag to prevent initial data repetition
        Sample(name="test").save()

Next is to run this script on Django's startup. The entry point of Django project is when DJANGO_SETTINGS_MODULE is first loaded at wsgi.py:
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "{{project_name}}.settings")

import {{project_name}}.startup as startup
startup.init()

application = get_wsgi_application()

With this setup, when you run python manage.py runserver, the init() on startup.py will run and the data you set will be inserted to the DB.
Hope this helps.


text:
Q: C# Recompile a Decompiled .dll So, I just decompiled a .dll using .NET Reflector. I now have a folder containing all of the .cs files (called, for example, "MyAssembly"), and subfolders functioning as sub-namespaces also containing .cs files. I edited a few of the .cs files now and want to recompile back to a .dll. Is there a way to compile the entire MyAssembly folder back into a .dll?

A: Create a new C# project of the correct type (Dll, Application, etc) in Visual Studio.  The free version is available here if you don't already have it.  Then manually add the .cs files to the project.  If there are any resource files that the code depends on you will have to extract those also and add them to the new project.  You will probably have to add any assembly references if the code relies on anything that isn't included by default.  Once that is done you should be able to recompile the code.  There may be errors, as decompiling is far from perfect.


text:
Q: Number theory: Solving $2^n-1\equiv0\pmod{n+1}$. If $n$ satisfies the congruence
$$2^n-1\equiv0\pmod{n+1},$$
then what is $n$? Or if you can't know what $n$ is, then what can be said about $n$?
Thank you in advance.

A: A number $n$ satisfys $2^n\equiv 1\ (\ mod\ (n+1)\ )\ $, if and only if $n+1$ is a fermat-pseudoprime to base $2$.
In particular, if $n+1$ is an odd prime, the congruence holds. But it can also hold, if $n+1$ is composite, the smallest example is $n=2046$.
Note , that there are infinite many composite fermat-pseudo-primes to base $2$.
Another way to classify the numbers satisfying the congruence : $n$ satisfies the congruence if and only if $n+1$ is odd and $ord_2(n+1)|n$. $ord_2(k)$ denotes the order of $k$ to base $2$. This is the smallest positive number $s$ with $2^s\equiv 1\ (\ mod\ k\ )$

A: Hint:
Use Fermat's_little_theorem and Fermat_pseudoprime
Let $n=p-1$, where $p -$ prime. Then
$$2^{p-1}\equiv1 (\bmod p)$$
Let $n=p-1$, where $p-$ composite number. Then
$p \in $ A001567


text:
Q: Gathering NDR Email addresses I am looking to gather all NDRs from out an outlook account and write the email addresses of the fails to either a table within a database or even just an excel document for the purposes of data cleaning.
Has anyone done anything like this previously and would be willing to push me in the right direction?

A: Well, you didn't say if you wanted an open source app (not aware of any), but I have written this commercial product:
http://www.ListNanny.NET
ListNanny will extracted the bounced addresses, classify the NDR, and provide you with some helpful information on why it bounced.
The only catch is that the email needs to be in it's RFC2822 format (like you donwload over IMAP or POP3). It can't read native Outlook .msg files.
Does that help?


text:
Q: join is giving duplicated in result set We want to join on part#. the first table has most of the data we want. the second has sales data per part. the first table just browsing it gives this
TRUL02A           I          2,014    CRW                16.00-
CORGDFOIL         I          2,014    CRW             7,090.00-
FISTAS            I          2,014    CRW             5,716.00-
HWCR1             I          2,014    CRW            70,403.00-
HWFE1             I          2,014    CRW            52,317.00-
RO060             I          2,014    CRW            12,669.00-
MYCBOCB           I          2,014    CRW                66.00-
MY6BOCB           I          2,014    CRW                  .00
MA20X3UL          I          2,014    CRW               167.00-
MA20X3CS1         I          2,014    CRW            72,978.00-

no dupes of part number but when join on the
sales amt per part table we get duplicates.
SELECT
  ALL       T01.IAPRT#, T01.IA101, T01.IAPRLC, T01.IAUM, T01.IAPR$C,
T01.IARCC1,
T01.IARCC2, T01.IARCC3, T01.IARCC4, T01.IARCC5,
T01.IARCC6,
            T01.IARCC7, T01.IARCC8, T01.IARCC9, T01.IARC10,
T01.IARC11,
            T01.IARC12, T01.IARC13, T01.IARC14, T01.IARC15,
T02.IQYER#,
            T02.IQA01, T02.IQA02, T02.IQA03, T02.IQA04, T02.IQA05,
T02.IQA06,
T02.IQA07, T02.IQA08, T02.IQA09, T02.IQA10, T02.IQA11,
T02.IQA12,
T02.IQA13, T02.IQA14
  FROM      ASTDTA.ICPRT1 T01 LEFT OUTER JOIN
            ASTDTA.ICSUM1 T02
ON        T01.IAPRT# = T02.IQPRT#

WHERE     IAORDF = '1'
  AND     IARCC6 = 'INV'
  AND     T02.IQYER# = 2014

Gives duplicate data:

 AB25X5CL         2.5x5x1 CLEAR ACRYLIC BASE          CAC        EA          REC
 AB25X5CL         2.5x5x1 CLEAR ACRYLIC BASE          CAC        EA          REC
 AB25X5CL         2.5x5x1 CLEAR ACRYLIC BASE          CAC        EA          REC


text:
Q: Importing contacts from addressbook in android is slow? I have written code for importing all the contacts with details (Name,Mobile number,DOB,anniversary and email address) from device addressbook to my application database.The code is running fine and getting all details but its a very slow process for large number of contacts.For example on samsumg Galaxy s4 with 8000 contacts it takes upto 20 minutes.The code I am using is following:
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null,
                    null, null, null);
int count = cur.getCount();
if (cur.getCount() > 0) {
    while (cur.moveToNext()) {
first_name = "";
first_name = "";

                    name = cur
                            .getString(cur
                                    .getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));

                    first_name = name == null ? "" : name;

                    // birthday
                    Cursor bdc = cr
                            .query(android.provider.ContactsContract.Data.CONTENT_URI,
                                    new String[] { Event.DATA },
                                    android.provider.ContactsContract.Data.CONTACT_ID
                                            + " = "
                                            + id
                                            + " AND "
                                            + Data.MIMETYPE
                                            + " = '"
                                            + Event.CONTENT_ITEM_TYPE
                                            + "' AND "
                                            + Event.TYPE
                                            + " = "
                                            + Event.TYPE_BIRTHDAY,
                                    null,
                                    android.provider.ContactsContract.Data.DISPLAY_NAME);
                    if (bdc.getCount() > 0) {
                        while (bdc.moveToNext()) {
                            birthDate = bdc.getString(0);
                        }
                    }

                  if (bdc != null)
                    bdc.close();

                Cursor ann = cr
                        .query(android.provider.ContactsContract.Data.CONTENT_URI,
                                new String[] { Event.DATA },
                                android.provider.ContactsContract.Data.CONTACT_ID
                                        + " = "
                                        + id
                                        + " AND "
                                        + Data.MIMETYPE
                                        + " = '"
                                        + Event.CONTENT_ITEM_TYPE
                                        + "' AND "
                                        + Event.TYPE
                                        + " = "
                                        + Event.TYPE_ANNIVERSARY,
                                null,
                                android.provider.ContactsContract.Data.DISPLAY_NAME);
                if (ann.getCount() > 0) {
                    while (ann.moveToNext()) {
                        anniversaryDate = ann.getString(0);
                    }
                }
               if (ann != null)
                    ann.close();

                Cursor cur1 = cr.query(
                        ContactsContract.CommonDataKinds.Email.CONTENT_URI,
                        null,
                        ContactsContract.CommonDataKinds.Email.CONTACT_ID
                                + " = ?", new String[] { id }, null);

                if (cur1.moveToNext()) {
                    email1 = cur1
                            .getString(cur1
                                    .getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
                    if (email1 == null)
                        email1 = "";
     if (cur1 != null)
            cur1.close();

if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                                    null,
                                    ContactsContract.CommonDataKinds.Phone.CONTACT_ID
                                            + " = ?", new String[] { id },
                                    null);
                    if (pCur.moveToNext()) {

                        phone = pCur
                                .getString(pCur
                                        .getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                        if (phone == null)
                            phone = "";
                    }

How Can I improve my above code to run more faster?Can someone guide me what am I doing wrong in my code?

A: put them in a new thread, after you get the result, give it to Handler to display on UI; It will not make your code faster, but at least, it won't stuck your UI.


text:
Q: distribution of electric charges In electricity courses, in the lesson on static fields, at some point all teachers say "let's consider a large rectangular metal plate where the density of charges is uniform", and then they proceed to show, using Gauss's law, that the electric field is uniform in the volume above the plate.
I don't see why a large metal plate, electrostatically charged, would "obviously" have roughly uniform electric charge density on its surface, away from the borders.
A classical argument explains that there can be no charge inside the volume of the plate, because it would create an electric field, and therefore a current until things settle. On the faces, the e-field is everywhere perpendicular to the surface, therefore no force is exerted on the charges there, and the configuration, whatever it is, is stable. But why would the charges necessarily be uniformly distributed on the sides (except for local border effects)?
Mathematically speaking, on one side, to compute the distribution of charges, one would have to find the one which minimizes the electrostatic potential energy (thanks to V. for the insight). I suppose there exist softwares to compute these distributions, but I don't know of any.


text:
Q: Python Arrays sorting folder names Hi could anyone explain to me how to sort the folder names in order of creation?
    list1=["New folder", "New folder 1", "New folder 10", "New folder 2"]

    sorted(list1)
    print("output ",list1)

The outputs is currently:
>>  ["New folder", "New folder 1", "New folder 10", "New folder 2"]

I would like it show:
["New folder", "New folder 1", "New folder 2", "New folder 10"]

The reason I need this order is because I am opening directories via these folder names in order.
Below is the code I am using to grab these folder names maybe there is a way to sort them in the required order as I make the array?
     itrprev = iter(os.walk(previousdir))
        root, dirs, files = next(itrprev)
    for next_root, next_dirs, next_files in itrprev:  # get second element onwards
        print("Next dir full path: : ", next_root)
        singlefoldername = os.path.split(next_root)
        fullfoldername = os.path.abspath(next_root)

A: Using sorted() returns a copy of a sorted object. You were just returning the sorted copy and doing nothing with it. You need .sort() to modify the string.
You also need to create a key function to specify that you are sorting by the numbers at the end, not alphanumerically.
import re

def order(x):
    try:
        # This searches and returns the first number found in the folder name
        return int(re.search("\d+", x).group(0))
    except (ValueError, TypeError, AttributeError):
        return 0

list1.sort(key=order)

output  ['New folder', 'New folder 1', 'New folder 2', 'New folder 10']

Edit - to account for letters as well:
Please see the attached answer.

https://stackoverflow.com/a/4836734/14141223
And have a read through the thread for alternatives

And for your other query. Sort after you have all the folder names, not as you're adding them.

A: As the items in your list are all strings, "sorted" sorts the items by alphabetical order. All strings start with "New folder".
The very first item ends up right there, so its the first in line. The second one is obviously "New folder 1". The third one is "New folder 10" because, as alphabetical order means items are read character by character, character 11 of "New folder 10" is "1", and character 11 of "New folder 2" is "2".
There are (I guess) many ways of solving your problem, one may be:
sorted_list = sorted(list1, key=lambda x: int(x.split(" ")[-1]))

Edit: I've been correctly rectified in my answer by 2 members. First, the function to be used is sorted not sort.
Next up, my code will raise an error with the "New folder" that's missing an int, as the lambda will try to convert "folder" to a number.
You can try:
def sorter(x):
    try:
        i = int(x.split(" ")[-1])
        return i
    except ValueError:
        return 0

sorted_list = sorted(list1, key=lambda x: sorter(x))

A: It's sorting these folders alphabetically since the values here are strings.
As a string, the correct order is:
New folder 1
New folder 10
New folder 2

So this could be hard problem if you don't know the format of the folders to begin with.
The easiest solution is to rename the folders:
New folder 01
New folder 02
New folder 10

But if you don't have standard naming format (some folders have numbers, some dont) then you'll have to conditially split the string at the number. Parse int on the number, and use that to flip the positions.
But that also becomes really weird logic if you start having numbers between strings ("New 1 Folder") or especially if you have anything with a date (New Folder 3-20-2021).

A: You need to create a custom sort function. The function will check if the end of each name is an ordered number or not, then proceed to sort accordingly. Defaults to ASC.
def customer_sort(foldername):
    foldername_list = foldername.split(' ')
    if not foldername_list[-1].isnumeric():
        return 0
    return int(foldername_list[-1])

Result
list1 = ["New folder", "New folder 1", "New folder 10", "New folder 2"]
sorted(list1, key= lambda item: customer_sort(item))
# ['New folder', 'New folder 1', 'New folder 2', 'New folder 10']


text:
Q: Removing node from graph structure c# I'm self-learning c# and I'm a little confused on nodes in graph structures.  I've cobbled together this code so far, but I have no idea how to remove and entire node from the list:
public class Graph
{
    private int _V;
    private int _E;
    private LinkedList<Int32>[] adj;

    public Graph(int V)
    {
        this._V = V;
        adj = new LinkedList<Int32>[_V];
        for (int v = 0; v < _V; v++)
        {
            adj[v] = new LinkedList<Int32>();
        }
    }

    public void AddEdge(int v, int w)
    {
        _E++;
        adj[v].AddFirst(w);
        adj[w].AddFirst(v);
    }

    public void RemoveEdge(int v, int w)
    {
        _E--;
        adj[v].Remove(w);
        adj[w].Remove(v);
    }

    public IEnumerable<Int32> Adj(int v)
    {
        return adj[v];
    }

    public int V()
    {
        return _V;
    }

    public bool isLeaf(int v)
    {
        return adj[v].Count() == 1;
    }

    public int adjacencies(int v)
    {
        return adj[v].Count();
    }

    public String toString()
    {
        StringBuilder s = new StringBuilder();
        String NEWLINE = Environment.NewLine;
        s.Append(adj[1].Count + NEWLINE);
        s.Append(_V + " vertices, " + _E + " edges " + NEWLINE);
        for (int v = 0; v < _V; v++) {
            s.Append(String.Format("{0:d}: ", v));
            foreach (int w in adj[v]) {
                s.Append(String.Format("{0:d} ", w));
            }
            s.Append(NEWLINE);
        }
        return s.ToString();
    }

}

So, if I have four nodes where node 1 has an edge to 2, 2 has edges to both 3 and 4, and 3 and 4 share an edge with each other, I want to remove node 1 completely since it's a leaf.  I can remove the edge easily enough, but that node still remains in my list (just without an edge).  How do I get rid of 1 completely?  I thought I should be able to just do a adj.Remove(1), but that throws an error.
I realize this is probably super easy, but the answers I've looked through in here seem to be describing something different or I'm simply not getting how this works.
Thanks!

A: Arrays do not support removal. If you really need to encode the concept of "does not exist" into adj, then you could set adj[v] to a value that represents "does not exist". For example,
adj[v] = null.

Alternatively, you could store adjacencies in a Dictionary<Int32>. Instead of
private LinkedList<Int32>[] adj;

you would have
private Dictionary<Int32, LinkedList<Int32>> adj;

and you could remove vertex v by
adj.Remove(v); // don't forget to remove the edges

In either case, you would probably want to update the other methods to handle such "removed" vertices.


text:
Q: determine if a set of points form an approximate line I am making a line/arc detection algorithm.
I found  this pesky set of points :
[(215, 69), (217, 70), (220, 67), (223, 65), (226, 64), (229, 62), (232, 60), (236, 57), (239, 56), (242, 54), (245, 52), (248, 50), (251, 48), (254, 47), (257, 45), (260, 43), (264, 40), (267, 39), (270, 37), (273, 35), (276, 33), (279, 31), (282, 29), (285, 28), (288, 26), (291, 24)]
I need to determine if these form a line or a curve. I plotted the set , it looks like this:
Set of green points on a line
They clearly represent a line.
However, I tried all sorts of tests to determine if they are line or curve.

*

*I tested whether the angles between each of the points are approximately equal. However, because the line a bit zig zagged, there are some outlier points that are not equal

*I tested the cross product  of any 3 sequential point of the line to check if they are collinear
for k in range(0,len(pts-3),1):
cp1=pts[k]
cp2=pts[k+1]
cp3=pts[k+2]
c1,c2,c3= (cp1.x,cp1.y),(cp2.x,cp2.y),(cp3.x,cp3.y)
cros= (p2.x - p1.x)*(p3.y - p1.y) - (p3.x - p1.x)*(p2.y - p1.y)
print(abs(cros))

Some of them have really significant cross products. Again because the line is a zig zagged line me thinks.
This zig zagged ness is throwing my algorithm off!
So how do I determine if a zigged zagged line is a line or a curve?

A: Assuming points are sorted based on proximity to the end of the line, we could compare gradients of each line with their neighbor in order to determine whether they sit on a line. The good thing about the gradient is how we can specify a tolerance level to define whether a line is too off to be considered part of the line.
An Example in JS given points is a multi dimensional array:
function calculateIsLine() {
let startingGradient=getGradientFromPoint(0);//we get a baseline and compare to every other point. If it is for example, inverted or completely off,
//we can confirm it doesn't line up.

console.log("Starting Gradient: "+startingGradient);

for (let i = 0; i < points.length-1; i++) {//ignoring last point as no point after it.
    if(Math.abs(startingGradient-getGradientFromPoint(i))>0.5){//0.5 is our tolerance level
        console.log("Conflicting Point: "+points[i]+" "+getGradientFromPoint(i));

        return false;
    }

}
return true;

}
function getGradientFromPoint(offset){
    return (points[offset+1][1]-points[offset][1])/(points[offset+1][0]-points[offset][0]);//gradient formula

}

Working Snippet

let points = [];
let pointsString = "[(215, 69), (217, 70), (220, 67), (223, 65), (226, 64), (229, 62), (300, 60), (236, 57), (239, 56), (242, 54), (245, 52), (248, 50), (251, 48), (254, 47), (257, 45), (260, 43), (264, 40), (267, 39), (270, 37), (273, 35), (276, 33), (279, 31), (282, 29), (285, 28), (288, 26), (291, 24)]";

let conflictingPointIndex;

function setup() {
  let canvas = createCanvas(500, 100);
  let arrayPoints = pointsString.split("(");

  arrayPoints.splice(0, 1);

  for (let i = 0; i < arrayPoints.length; i++) {
    arrayPoints[i] = arrayPoints[i].substr(0, arrayPoints[i].indexOf(")")).replace(" ", "");
    let stringPoint = arrayPoints[i].split(",");
    for (let j = 0; j < 2; j++) {
      if (!points[i])
        points[i] = [];
      points[i][j] = parseInt(stringPoint[j]);

    }
  }
  points.sort((p1, p2) => {
    return p1[0] - p2[0];

  });
 // console.log(points);

}
function draw() {
  background(0);
  console.log(calculateIsLine());
  for (let i = 0; i < points.length; i++) {
    if (i === conflictingPointIndex + 1)
      stroke(255, 0, 0);
    else stroke(255);
    point(points[i][0], points[i][1]);
  }
  noLoop();

}

function calculateIsLine() {
  let startingGradient = getGradientFromPoint(0); //we get a baseline and compare to every other point. If it is for example, inverted or completely off,
  //we can confirm it doesn't line up.
  console.log("Starting Gradient: " + startingGradient);
  for (let i = 0; i < points.length - 1; i++) { //ignoring last point as no point after it.
    if (Math.abs(startingGradient - getGradientFromPoint(i)) > 1.6) { //0.5 is our tolerance level
      console.log("Conflicting Point: " + points[i] + " " + getGradientFromPoint(i) + " " + Math.abs(startingGradient - getGradientFromPoint(i)));
      conflictingPointIndex = i;
      return false;
    }

  }
  return true;

}

function getGradientFromPoint(offset) {
  return (points[offset + 1][1] - points[offset][1]) / (points[offset + 1][0] - points[offset][0]); //gradient formula

}
<script src="https://github.com/processing/p5.js/releases/download/0.6.1/p5.js"></script>

I wasn't able to think of an approach to use for curves. But hopefully, you may be able to think of an approach similar to this. Someone else may also have a solution regarding curves.