text:
Q: How to measure and monitor available network bandwidth without stealing network bandwidth? Please note that I am not asking for well known usual bandwidth monitoring tools like ntop, iperf, vnstat etc.
I would like to measure periodically and reliably the max. available bandwidth of a network uplink, but without "stealing" bandwidth and without disturbing other traffic on this same connection.
Is this possible at all?
Usually I do adhoc measurements with rsync or iperf, but from what I understand these kind of tests also saturate the bandwidth of the connection and this makes it not possible to do this, say, every minute.
I have a not so stable uplink with several remote desktop connections and every bit counts, but I also would like to collect meaningful logfiles to be able to present information about this connection not offering the contracted bandwith at all.
So how do I collect this data without killing the already weak network connections going on here?

A:
Is this possible at all?

No, this is not possible. By definition, measuring bandwidth requires actually sending/receiving traffic, and since networking gear has a finite amount of information it can pass in a certain time period, you will be consuming a certain amount of that finite resource.
Sure, you could turn on QoS in your switch/routing gear and de-prioritize your bandwidth testing traffic, but then you'll not be getting accurate statistics on bandwidth available.

So how do I collect this data without killing the already weak network
  connections going on here?

You do your testing during periods of low load.
The other thing you may consider doing is setting up something like Cacti to monitor and graph bandwidth usage over time - this will give you quite a bit of data to work with.

A: Back in the mists of time, I heard about this tool: bing. It has some limits but it may be of help even though, of course, it needs to send some traffic through the links we are trying to determine the effective bandwidth of.
Hope this helps!


text:
Q: pyenv install: build failed trying to install python 3.5.0 on OS X 11.6 Trying to install python version 3.5.0 with pyenv so that I can install an older version of scipy.
This is the error I'm receiving:
(base) ➜  ~ pyenv install 3.5.0
Installing openssl-1.0.2k...

BUILD FAILED (OS X 11.6 using python-build 20180424)

Inspect or clean up the working tree at /var/folders/_5/fskpxlbd7ng8vv8p8t9z7l3r0000gn/T/python-build.20220404133720.51020
Results logged to /var/folders/_5/fskpxlbd7ng8vv8p8t9z7l3r0000gn/T/python-build.20220404133720.51020.log

Last 10 log lines:
      _dgram_write in libcrypto.a(bss_dgram.o)
      _RAND_query_egd_bytes in libcrypto.a(rand_egd.o)
      ...
ld: symbol(s) not found for architecture i386
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make[4]: *** [link_a.darwin] Error 1
make[3]: *** [do_darwin-shared] Error 2
make[2]: *** [libcrypto.1.0.0.dylib] Error 2
make[1]: *** [shared] Error 2
make: *** [build_crypto] Error 1
(base) ➜  ~

I'm guessing I don't have build dependencies but not sure how to determine which ones/how to install? Installing newer versions of python with pyenv is working fine.
Already tried:
Uninstall the old tools
$ sudo rm -rf /Library/Developer/CommandLineTools
Reinstall Xcode Command line tools
$ xcode-select --install
Install python using pyenv
$ pyenv install 3.5.0

redpajama_set_name: RedPajamaStackExchange


text:
Q: Sorting large text file in python Sort the content of a file based on second field, e.g.
Input file:
Jervie,12,M

Jaimy,11,F

Tony,23,M

Janey,11,F

Output file:
Jaimy,11,F

Janey,11,F

Jervie,12,M

Tony,23,M

We need to use external sort.
Input file can be of size 4GB. RAM is 1GB.
I used this but it does not work as it treats all the content as int. Also I have doubt related to the buffer size in each turn of the external sort. How to decide on that?
This sorts file with integers only.
file = open("i2.txt","r")
temp_files = []
e = []
while True:
    temp_file = tempfile.TemporaryFile()
    e = list(islice(file,2))
    if not e:
        break
    e.sort(key=lambda line: int(line.split()[0]))
    temp_file.writelines(e)
    temp_files.append(temp_file)
    temp_file.flush()
    temp_file.seek(0)
file.close()

with open('o.txt', 'w') as out:
    out.writelines(imap('{}\n'.format, heapq.merge(*(imap(int, f) for f in temp_files))))
out.close()

I am able to create temporary files sorted on the second field, but how do I merge them based on that?

A: I did it with the following code :
Divide the big file into smaller files. Here it is assumed that max 4 lines can be read. So I initially divide the file into lines of 4 and sort them and write into temp files. Then read these files in pairs 2 lines from each file and merge them. Corner cases are not handled but, this should be a starter for others to think.
f = open("i1.txt", "r")
temp_files = []
e = []
while True:
    temp_file = tempfile.NamedTemporaryFile()
    e = list(islice(f, 4))
    if not e:
        temp_file.close()
        break
    # e.sort(key=lambda line:int(line.split()[1]))
    e.sort(key=lambda line: int(line.split()[1]))
    temp_file.writelines(e)
    temp_files.append(temp_file)
    temp_file.flush()
    temp_file.seek(0)
f.close()

aux = []
z = 0
while len(temp_files) != 1:
    while z < len(temp_files)-1:
        tem = tempfile.NamedTemporaryFile()
        t1 = temp_files[z]
        t2 = temp_files[z+1]
        t1.seek(0)
        t2.seek(0)
        n = 2
        e1 = None
        e2 = None
        while True:
            if not e1:
                e1 = list(islice(t1, 2))
            if not e2:
                e2 = list(islice(t2, 2))
            if not e1 and not e2:
                break
            elif e1 and not e2:
                tem.writelines(imap('{}'.format,e1))
                e1 = None
                continue
            elif not e1 and e2:
                tem.writelines(imap('{}'.format,e2))
                e2 = None
                continue
            i = 0
            j = 0
            while i<len(e1) and j<len(e2):
                l1 = e1[i]
                l2 = e2[j]
                if int(l1.split()[1]) == int(l2.split()[1]):
                    tem.writelines(imap('{}'.format,[l1,l2]))
                    i+=1
                    j+=1
                elif int(l1.split()[1]) < int(l2.split()[1]):
                    tem.writelines(imap('{}'.format,[l1]))
                    i+=1
                else:
                    tem.writelines(imap('{}'.format,[l2]))
                    j+=1
            if i>=len(e1):
                e1 = None
            else:
                e1 = e1[i:]
            if j>= len(e2):
                e2 = None
            else:
                e2 = e2[j:]
        z+=2
        aux.append(tem)
        t1.close()
        t2.close()
        tem.flush()
        tem.seek(0)
    temp_files = aux
    z = 0
    aux = []
with open("o.txt",'w') as out:
    out.writelines(imap('{}'.format,temp_files[0]))

A: Try using out of the core processing with Blaze (http://blaze.readthedocs.io/en/latest/ooc.html)


text:
Q: php resize image after upload and crop it to the center i have a user profile in php and i want to give users the choice of changing their profile picture. But when they submit their new picture via $_POST i want the picture to be resized to:

height:110px | width:relevant to the height (if the width is bigger than height)
width:110px | height:relevant to the width (if the height is bigger than width)

when the resize is done, i want to crop the picture so it becomes 110px x 110px but i want it to be centered.
For example if the user uploads a picture with 110px width and 200px height (dimensions after the resize) the new image after crop will be 110x110 cropped by 90px from right. What i want is to cropped 45px from left and another 45px from right so it will be centered
the function will accept .png, .gif and .jpg images and will save the new image only in jpg format no matter what the initial format was.
I searched a lot to create such a function and i found an answer but any time i atempt to change some minor detail everything stop working properly.
My code so far:
<?php

$userfile_name = $_FILES["sgnIMG"]["name"];
$userfile_tmp = $_FILES["sgnIMG"]["tmp_name"];
$userfile_size = $_FILES["sgnIMG"]["size"];
$filename = basename($_FILES["sgnIMG"]["name"]);
$file_ext = substr($filename, strrpos($filename, ".") + 1);
$large_image_location = $target_path . $filename;
$ext = '';

if ($file_ext == 'jpg') {
    $ext = 1;
} else if ($file_ext == 'gif') {
    $ext = 2;
} else if ($file_ext == 'png') {
    $ext = 3;
} else {
    $ext = 0;
}

$target = $target_path . basename($_FILES["sgnIMG"]["name"]);

if (move_uploaded_file($userfile_tmp, $target)) {
    $newImg = resize110($target, $ext);
    if (isset($_POST['imupd']) && ($_POST['imupd'] == 'up')) {
        $sql = "UPDATE users SET avatar='" . str_replace('im/users/', '', $newImg) . "' WHERE id=" . $_SESSION['sesID'] . "";
        $result = mysql_query($sql);
        if ($result) {
            echo '';
        } else {
            echo '';
        }
    }
} else {

}

function getHeight($image)
{
    $sizes = getimagesize($image);
    $height = $sizes[1];
    return $height;
}

function getWidth($image)
{
    $sizes = getimagesize($image);
    $width = $sizes[0];
    return $width;
}

function resize110($image, $ext)
{
    chmod($image, 0777);
    $oldHeight = getHeight($image);
    $oldWidth = getWidth($image);
    if ($oldHeight < $oldWidth) {
        $newImageHeight = 110;
        $newImageWidth = ceil((110 * $oldWidth) / $oldHeight);
        imagecopyresampled($newImage, $source, -ceil(($newImageWidth - 110) / 2), 0, 0, 0, $newImageWidth, $newImageHeight, $oldWidth, $oldHeight);
    } else {
        $newImageHeight = ceil((110 * $oldHeight) / $oldWidth);
        $newImageWidth = 110;
        imagecopyresampled($newImage, $source, 0, -ceil(($newImageHeight - 110) / 2), 0, 0, $newImageWidth, $newImageHeight, $oldWidth, $oldHeight);
    }
    $newImage = imagecreatetruecolor(110, 110);
    chmod($image, 0777);
    return $image;
    switch ($ext) {
        case 1;
            $source = imagecreatefromjpeg($image);
            break;
        case 2;
            $source = imagecreatefromgif($image);
            break;
        case 3;
            $source = imagecreatefrompng($image);
            break;
    }

    imagejpeg($newImage, $image, 90);
    return $image;
}

A: I looked around a lot and combined different parts of code i found. So this script will take a jpg,gif of png image, resize it to 110px width if width is greater of 110px height if height is greater. The ascpect ratio will remain so the remaining pixels will be divided by 2 will be used to center the image.
for a different size just change 110 everywhere.
==================================================================================
<?php

// pfpic  ->  the name of the <input type="file" name="pfpic"/> where user chooses file

$target_path = "im/users/";                                // the directory to store the uploaded and then resampled image
$userfile_name = $_FILES["pfpic"]["name"];                  // the name that the image file will have once uploaded
$userfile_tmp = $_FILES["pfpic"]["tmp_name"];                   // the temporary name the server uses to store the file
$userfile_size = $_FILES["pfpic"]["size"];                  // the size of the file that we want to upload
$filename = basename($_FILES["pfpic"]["name"]);             // the full name of the file
$file_ext = substr($filename, strrpos($filename, ".") + 1);  // the file extension
$large_image_location = $target_path.$filename;                  // the full path to the file
$ext='';

if($file_ext=='jpg')
{
    $ext=1;
}
else if ($file_ext=='gif')
{
    $ext=2;
}
else if ($file_ext=='png')
{
    $ext=3;
}
else
{
    $ext=0;
}

    $target = $target_path.basename(sha1($_SESSION['sesID']).'.'.'jpg');
    if($ext!=0)
    {
        if(move_uploaded_file($userfile_tmp,$target))
        {
            $newImg=resize110($target,$ext);
            echo '';
        }
        else
        {
            echo 'the file could not be uploaded, please try again';
        }
    }
    else
    {
        echo 'this file extension is not accepted, please use "jpg", "gif" or "png" file formats';
    }

    function getHeight($image)
    {
        $sizes = getimagesize($image);
        $height = $sizes[1];
        return $height;
    }

    function getWidth($image)
    {
        $sizes = getimagesize($image);
        $width = $sizes[0];
        return $width;
    }

    function resize110($image,$ext)
    {
        chmod($image, 0777);
        $oldHeight=getHeight($image);
        $oldWidth=getWidth($image);
        switch ($ext)
        {
            case 1;
                $source = imagecreatefromjpeg($image);
            break;

            case 2;
                $source = imagecreatefromgif($image);
            break;

            case 3;
                $source = imagecreatefrompng($image);
            break;
        }
        $newImage = imagecreatetruecolor(110,110);
        $bgcolor = imagecolorallocate($newImage, 255, 255, 255);
        imagefill($newImage, 0, 0, $bgcolor);       // use this if you want to have a white background instead of black

        // we check tha width and height and then we crop the image to the center
        if($oldHeight<$oldWidth)
        {
            $newImageHeight = 110;
            $newImageWidth = ceil((110*$oldWidth)/$oldHeight);
            imagecopyresampled($newImage,$source,-ceil(($newImageWidth-110)/2),0,0,0,$newImageWidth,$newImageHeight,$oldWidth,$oldHeight);
        }
        else
        {
            $newImageHeight = ceil((110*$oldHeight)/$oldWidth);
            $newImageWidth = 110;
            imagecopyresampled($newImage,$source,0,-ceil(($newImageHeight-110)/2),0,0,$newImageWidth,$newImageHeight,$oldWidth,$oldHeight);
        }

        //we save the image as jpg resized to 110x110 px and cropped to the center. the old image will be replaced
        imagejpeg($newImage,$image,90);

        return $image;

    }

?>


text:
Q: Aggregative entity with hibernate I have 3 tables:

*

*User - contains person's login and password.

*Person - contains name and surname.

*Role - specifies roles.

User binded with Person one-to-one.
User binded with role many-to-many.
I want create aggregative entity, contains all info e.g.:
public class AggregatedUser {

    private User user;
    private Person person;
    private List<Role> roles;
}

Have following questions.

*

*Is it true way dealing with Hibernate?

*How can I implement it?


text:
Q: Python: Deleting duplicates from Dataframe When I output dfges, I get duplicates for a given element. For example, for Madrid the messages are all displayed three times each. Does anyone know a way to work around this problem or remove the duplicates? Is it possibly due to the upper For loop?
import ssl
import smtplib
import pandas as pd
from GoogleNews import GoogleNews
ssl._create_default_https_context = ssl._create_unverified_context

googlenews = GoogleNews()
googlenews.set_encode('utf_8')

Nachrichten = [
        df = pd.DataFrame(table_new)
    nachrichten.append(df)

dfges = pd.concat(nachrichten, axis='index')
´´´

A: Seems you need a dfges.drop_duplicates(inplace=True). This will remove all duplicate rows. Note that two rows are considered duplicates only if they have the same values in each field (except the index).
See the doc for other details:
https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.drop_duplicates.html
Provide an example of your Dataframe dfges if you need more help.

A: As articles can be tagged with multiple locations e. g. "Munich" and "Madrid", hence appear multiple times in your df, you should detect and delete duplicates using drop_duplicates(subset=...) based on the 'Title' (and more criteria), as otherwise no duplicates are deleted add at all.
Your code could look like this:
...
dfges = pd.concat(nachrichten, axis='index')
dfges.drop_duplicates(subset=['Title'], keep='last', inplace=True)
print(dfges)
...


text:
Q: No directive found for `bcrypt` I'm following official Lighthouse documentation on how to setup GraphQl into my project.
Unfortunately, I'm stacked with the following error:
No directive found for `bcrypt`
Following schema I have created so far:

type Query {
    users: [User!]! @paginate(defaultCount: 10)
    user(id: ID @eq): User @find
}

type User {
    id: ID!
    name: String!
    email: String!
    created_at: DateTime!
    updated_at: DateTime!
}

type Mutation {
    createUser(
        name: String!,
        email: String! @rules(apply: ["email", "unique:users"])
        password: String! @bcrypt
    ): User @create
}

The query I'm trying to execute is following:
mutation {
  createUser(
    name:"John Doe"
    email:"john@test.com"
    password: "somesupersecret"
  ) {
    id
    email
  }
}

A: Okay dug up - there is no more @brypt directory in \vendor\nuwave\lighthouse\src\Schema\Directives\ instead, there is @hash directive which is working like a charm and uses driver you specify in config/hashing.php configuration file


text:
Q: How to resolve dependency? I have a class:
@Injectable()
export class SearchByAddressParcel implements SearchAddress {
    private _response;

    get response() {
        return this._response;
    }

    set response(value) {
        this._response = value;
    }

    constructor(private CloudService: CloudEsService, private searchConfig: SearchConfig) {}

    search(): Observable<any> {
        return this.CloudService.search(this.searchConfig.parameters);
    }
}

This class has injection private CloudService: CloudEsService, private searchConfig: SearchConfig.
I resolve this class in provider:
 providers: [
        SearchByAddressParcel,
        { provide: SearchByAddressParcel, useClass: SearchConfig },
    ],

But how to resolve SearchConfig and pass it as parameter for SearchByAddressParcel?
@Injectable()
export class SearchConfig {
    constructor(public config: SearchParameters) {

   }
}

I have tried this:
providers: [
    SearchByAddressParcel,
    SearchConfig,
    { provide: SearchConfig, useValue: { layers: [37], types: [4, 5, 6], helpSearch: false, searchText: '', searchType: 2 } },
    { provide: SearchByAddressParcel, useClass: SearchConfig },
],

Then I have tried this:
export const SEARCH_PARAMETERS = new InjectionToken<SearchParameters>('SEARCH_PARAMETERS');

@Injectable()
export class SearchConfig {
    private layers: number[];
    private types: number[];
    private searchType: number;
    private _searchText: string;

    constructor(@Inject(SEARCH_PARAMETERS) config: SearchParameters) {
}

Provider:
  providers: [
        SearchConfig,
        SearchByAddressParcel,
        { provide: SEARCH_PARAMETERS, useValue: { layers: [37], types: [4, 5, 6], helpSearch: false, searchText: '', searchType: 2 } },
        { provide: SearchByAddressParcel, useClass: SearchConfig },
    ],

Problem is provider can not resolve CloudEsService for  SearchByAddressParcel.

A: Your use of providers is partially wrong: you have multiple registrations for the same token, and useClass is not to be used like that.
First, you should try to follow Angular's naming conventions and name your services with the Service suffix (probably, your classSearchByAddressParcel should become an AddressSearchService or something like that).
Second: your SearchByAddressParcel seems to be a class to be used as a single instance. Since Angular v5 (if I remember correctly) you can just use the {providedIn: 'root'} shortcut: you don't need an entry in providers.
@Injectable({ providedIn: 'root' })
export class SearchByAddressParcel implements SearchAddress {
    private _response;

    get response() {
        return this._response;
    }

    set response(value) {
        this._response = value;
    }

    constructor(private CloudService: CloudEsService, private searchConfig: SearchConfig) {}

    search(): Observable<any> {
        return this.CloudService.search(this.searchConfig.parameters);
    }
}

What providedIn does is very much like inserting an automatic registration in the base AppModule of your application. The provider is exactly like: { provide: SearchByAddressParcel, useClass: SearchByAddressParcel }.
Now, to allow Angular to build an instance of SearchByAddressParcel you need to tell him how to resolve CloudEsService (I assume it's another providedIn: 'root') and SearchConfig.
Because of the latter, we need just ONE provider in our AppModule, the one for SearchConfig.
If SearchConfig it's a compile time constant, or if you can read it from the page, you can leverage useValue:
// in app.Module.ts
const config = new SearchConfig(... your settings ...);

@NgModule({
  // ...
  providers: [
    { provide: SearchConfig, useValue: config }
  ]
})
// ...

If it's not, you can use a factory method. Some examples you can find in the Dependency Injection Guide, in the official Angular docs, especially https://angular.io/guide/dependency-injection-providers#factory-providers.
Try to take the time to read the whole thing: it's worth gold.


text:
Q: Source code for Docker Swarm load balancer This question is quite code-specific rather than concept explanation.
I want to study how Docker Swarm's embedded DNS and Load Balancer is implemented, especially the roundrobin part.
I tried searching in Docker github repo with some keywords such as "loadbalancing", "balancer", "roundrobin" etc. but no result.
I found Docker libnetwork that has keyword RoundRobin but I don't know how it is used in Docker engine.
Can anyone please help me to point out which files I should look at?

A: You should search for ingress, Also try following 2 files:
docker/daemon/network.go
docker/api/types/swarm/network.go


text:
Q: Validation In java script Currently I'm attempting to create a regular expression to validate an user input field which requires the input to contain at least one of each of the following:

*

*an upper-case character

*a digit

*one of the following special characters: & @ ! # +
I attempted to create a regular expression that will validate the input correctly:
/^([a-zA-Z+]+[0-9+]+[&@!#+]+)$/i.test(userpass);

However, the input is not validated correctly.  How should I go about doing that?

A: Try this:
/[a-z]/i.test(userpass) && /[0-9]/.test(userpass) && /[&@!#+]/.test(userpass)

A: you can simplify the regex with lookahead
 ^(?=.*[&@!#+])(?=.*[A-Z])(?=.*\d).+$
  ------------- --------- -------
      |        |         |->match only if there's a digit ahead
      |        |->match only if there's a uppercase alphabet ahead
      |->match only if there's any 1 of [&@!#+]

[A-Z] would match a single uppercase letter
\d would match a single digit

OR use search
if(input.search(/\d/)!=-1 && input.search(/[&@!#+]/)!=-1) && input.search(/[A-Z]/)!=-1)


text:
Q: libGDX 1.4.1 can't slow down animations This is what I have:
...
private Array<Sprite> fireballFadeOutAnim;
private Array<Sprite> bucketFadeOutAnim;
private TextureAtlas fballAnimSheet;
private TextureAtlas bucketAnimSheet;
private Animation catch_animation;
private Animation visual_feedback;
private float elapsedTime = 0f;

...

@Override
public void create () {

    ...
    fballAnimSheet = new TextureAtlas("animations/fireball_fadeout.txt");
    bucketAnimSheet = new TextureAtlas("animations/bucket_fadeout.txt");
    fireballFadeOutAnim = fballAnimSheet.createSprites("fireball_fadeout");
    bucketFadeOutAnim = bucketAnimSheet.createSprites("bucket_fadeout");

    catch_animation = new Animation(1/15f, fballAnimSheet.getRegions(), Animation.PlayMode.NORMAL);
    visual_feedback = new Animation(1/15f, bucketAnimSheet.getRegions(), Animation.PlayMode.LOOP);

    ...
}

@Override
public void render () {

    ...
    // Set the anim_elipsed_time
    elapsedTime += Gdx.graphics.getDeltaTime();

    ...
    // I try to draw them later on (under the render method) like this:
    // Start and draw animation of fireball catch
    batch.begin();

    batch.draw(catch_animation.getKeyFrame(elapsedTime, true), fireBallRect.getX(), fireBallRect.getY());
    batch.end();
}

I can see both animations happening extremely fast (they look like a white-flash), they do not loop even if the animation mode is set to "LOOP".
What am I doing wrong ? I can't seem to be able to slow them down or to have them LOOP. Thanks much.
Edited:
As requested, I upload all the code
public class MainActivity extends ApplicationAdapter {

    public enum State {
        PAUSE,
        RUN,
        RESUME,
        STOPPED
    }
    public static State state = State.RUN;

    private SpriteBatch batch;
    private OrthographicCamera camera;
    private Stage stage;
    private Texture backgroundImage;
    private Texture bucketImage;
    private Texture fireballImage;
    private Texture heart;
    private TextureRegion criticalTexture;
    private Sprite backgroundSprit;
    private Sprite bucketSprite;
    private Sprite fireballSprite;
    private Sprite heartSprite;
    private Rectangle bucketRect;
    private Rectangle fireBallRect;
    private Rectangle bucketSpriteRect;
    private ShapeRenderer bucketRenderer;
    private ShapeRenderer fireballRenderer;
    private Button pauseButton;
    private Array<Rectangle> fireballArray;
    private Skin progressBarSkin;
    private long lastFireballTime;
    public static Sound bucket_tap;
    public static Sound bucket_drag;
    private Sound fireball_missed_sound;
    private Sound catchFireball;
    private Sound pauseBtnSound;
    private Music bgMusic;
    private float volume = 0.30f;                // music and sfx volume control
    public static int w;
    public static int h;
    private int barLength = 325;
    private int numberOfFails = 10;               // change numberOfFails to increase or decrese
                                                  // the total num. of missed fireballs the player
    private int deductedBarSegment = barLength / numberOfFails;

    private int numOfBallsLeft = numberOfFails;   // use this var to check how many fballs left

    private long fireballFrequency = 1000000000L; // change fireballFrequency to increase or decrease
                                                  // the number of fireballs on the screen

    private int fireballSpeed = 400;              // change the fireballSpeed to increase or decrease
                                                  // the speed at which the fireballs fall

    private InputProcessor gameInputProcessor;    // this sets the game input controller for the bucket
    private InputMultiplexer multiplexer;         // this sets the input processors from the game and UI

    /************************************ Animation Properties ************************************/

    private TextureAtlas fballAtlas;
    private TextureAtlas bucketAtlas;
    private Animation catch_animation;
    private Animation visual_feedback;
    private float elapsedTime = 0f;
    private Actor feedbackPanel;

    /**********************************************************************************************/

    @Override
    public void create () {

        // Parse Test
        //ParseObject testObject = new ParseObject("TestObject");
        //testObject.put("foo", "bar");
        //testObject.saveInBackground();

        // Catch the dynamic size of the screen based on the device that's ran on
        w = Gdx.graphics.getWidth();
        h = Gdx.graphics.getHeight();

        // Set up the camera
        camera = new OrthographicCamera();
        camera.setToOrtho(false, (float)w, (float)h);

        // Instantiate the batch
        batch = new SpriteBatch();

/***************************** These renders are for debugging only *****************************/

        bucketRenderer = new ShapeRenderer();
        fireballRenderer = new ShapeRenderer();

/**************************************************************************************************/

/******************************************** Stage and HUD ***************************************/

        stage = new Stage();

        pauseButton = new Button(new TextureRegionDrawable(
                new TextureRegion(new Texture(Gdx.files.internal("images/pase_button_red.png")))),
                new TextureRegionDrawable(new TextureRegion(new Texture(Gdx.files.internal("images/pase_button_white.png")))));
        pauseButton.setX(flipCoordinates(w, 150));
        pauseButton.setY(flipCoordinates(h, 170));

        pauseButton.act(Gdx.graphics.getDeltaTime());

        stage.addActor(pauseButton);

        pauseButton.addListener(new ChangeListener() {
            @Override
            public void changed (ChangeEvent event, Actor actor) {

                // Do something when the pauseButton is pressed
                // Control multiple touches on the pauseButton
                if(state == State.RUN) {

                    state = State.PAUSE;
                    pauseBtnSound.play();

                    // Set the pauseButton icon to the white version
                    //pauseButton.setColor(Color.WHITE);
                }
                else {
                    state = State.RUN;
                    pauseBtnSound.play();
                }

            }
        });

        // Add the critical_life indicator to the stage as an actor
        criticalTexture = new TextureRegion(new Texture(Gdx.files.internal("images/critical_life.png")));

        feedbackPanel = new Actor() {

            public void draw(Batch batch, float alpha) {

                batch.draw(criticalTexture, getX(), getY(), getOriginX(), getOriginY(), getWidth(), getHeight(),
                        getScaleX(), getScaleY(), getRotation());

            }

        };

        feedbackPanel.setBounds(w / 2, h / 2,
                criticalTexture.getRegionWidth(), criticalTexture.getRegionHeight());

        // Set up an Action for the critical life actor

        feedbackPanel.addAction(forever(sequence(scaleTo(2, 2, 0.5f), scaleTo(1, 1, 0.5f), delay(0.5f))));

        feedbackPanel.act(Gdx.graphics.getDeltaTime());
        stage.addActor(feedbackPanel);

/**************************************************************************************************/

/*********************************** Set up the Input Controllers *********************************/

        // The multiplexer helps target several input processes (in this case, the stage and the
        // InputProcessor.class)

        multiplexer = new InputMultiplexer();
        multiplexer.addProcessor(stage);
        multiplexer.addProcessor(new GameInputProcessor());

        // InputAdaptor
        Gdx.input.setInputProcessor(multiplexer);

/**************************************************************************************************/
        backgroundImage = new Texture("images/bg.jpg");
        bucketImage = new Texture("images/bucket_small.png");
        fireballImage = new Texture("images/fireball_small.png");
        heart = new Texture("images/heart.png");

/*************************************** Animations Setup *****************************************/

        fballAtlas = new TextureAtlas("animations/fireball_fadeout.txt");
        bucketAtlas = new TextureAtlas("animations/bucket_fadeout.txt");

        catch_animation = new Animation(0.50f, fballAtlas.getRegions());
        visual_feedback = new Animation(0.15f, bucketAtlas.getRegions());

/**************************************************************************************************/

        // Instantiate all sounds
        bucket_tap = Gdx.audio.newSound(Gdx.files.internal("sounds/bucket_tap.ogg"));
        bucket_drag = Gdx.audio.newSound(Gdx.files.internal("sounds/bucket_drag.ogg"));
        fireball_missed_sound = Gdx.audio.newSound(Gdx.files.internal("sounds/fireball_missed.ogg"));
        catchFireball = Gdx.audio.newSound(Gdx.files.internal("sounds/fastSteam.ogg"));
        pauseBtnSound = Gdx.audio.newSound(Gdx.files.internal("sounds/pauseBtn_sound.ogg"));
        bgMusic = Gdx.audio.newMusic(Gdx.files.internal("sounds/music_bg.mp3"));
        bgMusic.setLooping(true);
        bgMusic.play();   //                  <----------- turn bg music on/off

        // Instantiate the progressBarSkin
        progressBarSkin = new Skin();
        progressBarSkin.add("progressBarBg", new Texture("images/progress-bar_bg.png"));
        progressBarSkin.add("progressBar", new Texture("images/progress-bar_dynamic_red.png"));

        // Create bg sprite
        backgroundSprit = new Sprite(backgroundImage);
        //backgroundSprit.setPosition((float)w / 2, (float)h / 2);
        //backgroundSprit.setSize((float)w, (float)h);

        // Bucket sprite
        bucketSprite = new Sprite(bucketImage);

        // Fireball sprite
        fireballSprite = new Sprite(fireballImage);

        // Heart sprite
        heartSprite = new Sprite(heart);

        // Set the bucketRect into the rect from the bucketSprite (THE GREEN ONE)
        bucketSpriteRect = bucketSprite.getBoundingRectangle();
        bucketSpriteRect.x = w / 2 - 100 / 2;
        bucketSpriteRect.y = 20;
        bucketSpriteRect.setSize(200, 200);

        // Set the collision rectangle (THE RED ONE)
        bucketRect = new Rectangle();
        bucketRect.x = bucketSpriteRect.getX() + 70;   // <---- adjust position left/right
        bucketRect.y = bucketSpriteRect.getY() + 150;  // <---- adjust position up/down
        bucketRect.setSize(100, 10);

        // Set a rectangle for each fireball sprite (THE WHITE ONE)
        fireBallRect = new Rectangle();
        fireBallRect.x = fireballSprite.getX();
        fireBallRect.y = fireballSprite.getY();
        fireBallRect.width = 55;
        fireBallRect.height = 55;

        fireballArray = new Array<Rectangle>();

    }

    @Override
    public void render () {

        // Devide the Render method into a few switch cases based on the game's state
        switch (state) {

            case RUN:

                // Do all the batch drawing here
                Gdx.gl.glClearColor(1, 1, 1, 1);
                Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
                elipsedTime += Gdx.graphics.getDeltaTime();

                batch.setProjectionMatrix(camera.combined);
                batch.begin();
                batch.draw(backgroundSprit, 0, 0, w, h);
                batch.draw(bucketSprite, bucketSpriteRect.x, bucketSpriteRect.y,
                        bucketSprite.getWidth() - 160, bucketSprite.getHeight() - 140);

                for(Rectangle fireball: fireballArray) {
                    batch.draw(fireballSprite, fireball.x, fireball.y,
                            fireballSprite.getWidth() - 20, fireballSprite.getHeight() - 20);
                }

                batch.draw(progressBarSkin.getSprite("progressBarBg"), 200, flipCoordinates(h, 170));
                batch.draw(progressBarSkin.getSprite("progressBar"),
                        210, flipCoordinates(h, 162), barLength, 6); // <---- modify x, x, <x>, x to adjust the length of the life-bar
                batch.draw(heartSprite, 95, flipCoordinates(h, 200), 90, 76);

                stage.act(Gdx.graphics.getDeltaTime());
                stage.draw();

                batch.end();

/***************************************Debugging Rectangles************************************/
                // Draw rects around sprites

//        bucketRenderer.begin(ShapeRenderer.ShapeType.Line);
//        bucketRenderer.setColor(Color.GREEN);
//        bucketRenderer.rect(bucketSpriteRect.getX(), bucketSpriteRect.getY(),
//                bucketSprite.getWidth() - 160, bucketSprite.getHeight() -140);
//        bucketRenderer.end();
//
//        bucketRenderer.begin(ShapeRenderer.ShapeType.Line);
//        bucketRenderer.setColor(Color.RED);
//        bucketRenderer.rect(bucketRect.getX(), bucketRect.getY(), 100, 10);
//        //bucketRenderer.point(bucketRect.getX(), bucketRect.getY(), 0f);
//        bucketRenderer.end();
//
//        fireballRenderer.begin(ShapeRenderer.ShapeType.Line);
//        fireballRenderer.setColor(Color.WHITE);
//        fireballRenderer.rect(fireBallRect.x, fireBallRect.y,
//                fireballSprite.getWidth() - 20, fireballSprite.getHeight() - 20);
//        fireballRenderer.end();

                // To avoid sprite flickering, surround batch.draw with a game state check
                if (state != State.PAUSE) {

                    Iterator<Rectangle> iter = fireballArray.iterator();
                    while(iter.hasNext()) {
                        fireBallRect = iter.next();
                        fireBallRect.y -= fireballSpeed * Gdx.graphics.getDeltaTime();

                        // Remove the fireBallRect from the array as soon as it leaves the screen
                        if(fireBallRect.y + 106 < 0) {
                            iter.remove();

                            // The player missed the fireball, play a the fireball_missed_sound
                            fireball_missed_sound.play();

                            // Subtract a ball from the total number allowed to be missed
                            numOfBallsLeft --;

                            // Call life deduction
                            deductLifePoints();

                            // Check to see if this is the last fball left to fail
                            if (numOfBallsLeft == 1) {

                            }

                            // Check to see if life points are 0 or < 0
                            if (numOfBallsLeft <= 0) {

                                // Game over logic
                                barLength = 0;

                                // Set the game state to PAUSED
                                //state = State.PAUSE;
                                //bucketSprite.setColor(Color.RED);
                                batch.begin();
                                batch.draw(bucketSprite, bucketSpriteRect.x, bucketSpriteRect.y,
                                        bucketSprite.getWidth() - 160, bucketSprite.getHeight() - 140);
                                batch.end();
                            }
                        }

                        // Collision detector
                        if(bucketRect.overlaps(fireBallRect)) {

                            catchFireball.play(volume);

                            // Start and draw animagion of fireball catch
                            batch.begin();

                            batch.draw(catch_animation.getKeyFrame(elapsedTime, true), fireBallRect.getX(), fireBallRect.getY());
                            batch.end();

                            // Remove the fireball that collides with the bucket
                            iter.remove();
                        }

                    }

                }

                // Touch input controller
                if(Gdx.input.isTouched()) {
                    Vector3 touchPos = new Vector3();
                    touchPos.set(Gdx.input.getX(), Gdx.input.getY(), 0);
                    camera.unproject(touchPos);

                    if(touchPos.y <= 250) {

                        bucketSpriteRect.setX(touchPos.x - 115);
                        bucketRect.setX(touchPos.x - 50);  // <---- adjust position left/right on touch

                    }

                }

                if(TimeUtils.nanoTime() - lastFireballTime > fireballFrequency) {

                    fireBallRect = new Rectangle();
                    fireBallRect.x = MathUtils.random(50, w - 270);
                    fireBallRect.y = h;
                    fireBallRect.width = 75;
                    fireBallRect.height = 75;
                    fireballArray.add(fireBallRect);
                    lastFireballTime = TimeUtils.nanoTime();

                }

/**************************************************************************************************/
                break;
            case PAUSE:

                // Pause the game here
/******************************** Redraw the sprites to avoid flickering **************************/

                batch.begin();
                batch.draw(backgroundSprit, 0, 0, w, h);
                batch.draw(bucketSprite, bucketSpriteRect.x, bucketSpriteRect.y,
                        bucketSprite.getWidth() - 160, bucketSprite.getHeight() - 140);

                for(Rectangle fireball: fireballArray) {
                    batch.draw(fireballSprite, fireball.x, fireball.y,
                            fireballSprite.getWidth() - 20, fireballSprite.getHeight() - 20);
                }

                batch.draw(progressBarSkin.getSprite("progressBarBg"), 200, flipCoordinates(h, 170));
                batch.draw(progressBarSkin.getSprite("progressBar"),
                        210, flipCoordinates(h, 162), barLength, 6); // <---- modify x, x, <x>, x to adjust the length of the life-bar
                batch.draw(heartSprite, 95, flipCoordinates(h, 200), 90, 76);
                //pauseButton.draw(batch, 1);
                stage.act(Gdx.graphics.getDeltaTime());
                stage.draw();

                batch.end();

/**************************************************************************************************/

                break;
            case RESUME:

                break;
            default:

                break;
        }

    }

    /************************************* Implement Dispose **************************************/
    @Override
    public void dispose() {

        batch.dispose();
        bucketRenderer.dispose();
        fireballRenderer.dispose();
        backgroundImage.dispose();
        bucketImage.dispose();
        fireballImage.dispose();
        bucket_tap.dispose();
        bucket_drag.dispose();
        catchFireball.dispose();
        bgMusic.dispose();
        fireball_missed_sound.dispose();
        progressBarSkin.dispose();
        fballAtlas.dispose();
        stage.dispose();

    }

    /************************************* Flip Coordinates Method ********************************/

    public static float flipCoordinates(float height, float xORy) {

        float newPosition = height - xORy;
        return newPosition;
    }

    /************************************** Deduces Life Points ***********************************/
    private void deductLifePoints() {

        barLength -= deductedBarSegment;
    }

    /************************************** Set the Game's state **********************************/
    public void setGameState(State s) {

        this.state = s;
    }

    /******************************** Android's Lyfe-Cycle Overrides ******************************/
    @Override
    public void pause() {

        super.pause();
        this.state = State.PAUSE;

    }

    @Override
    public void resume() {

        super.resume();
        this.state = State.PAUSE;
    }
}

A: The first parameter of the Animation constructor is the frameDuration in seconds. You are passing it 1/15f, which is really fast. Try something greater, like 0.15f.


text:
Q: UITextView - anyway to figure out if entire string is visible? I'm wondering, is there anyway to figure out if the entire string is visible within a UITextView? (without measuring the size of the string itself since the UITextView is an irregular shape).

A: I don't quite know what you mean about TextView being an irregular shape, though I've written a method which returns a BOOL result to let you know if the string will be visible or not. If you set the font attributes you're using within this, it works out the calculation based on them.
-(BOOL)isStringFullyVisibleWithinTextViewWithString:(NSString*)yourString{

    CGSize textViewSizeOversize = CGSizeMake(textView.frame.size.width, textView.frame.size.height+100);

    NSDictionary *stringAttributes = [NSDictionary dictionaryWithObject:[UIFont systemFontOfSize:13] forKey: NSFontAttributeName];

    CGSize stringAreaSize = [yourString boundingRectWithSize:textViewSize options:NSStringDrawingTruncatesLastVisibleLine|NSStringDrawingUsesLineFragmentOrigin attributes:stringAttributes context:nil].size;

    CGFloat stringAreaHeight = stringAreaSize.height;

    if (stringAreaHeight < textView.frame.size.height){
      return YES;
    }

    return NO;
}

I'm not aware of any solution that would return the answer you're looking for without measuring the string (which of course this method does).
I hope this helps,
Cheers,
Jim.


text:
Q: aligning the table row in HTML My problem is that I can't find a way to fix the table row height,
if the username exceeded it overlaps to the other column.
check the last two row

and it's also scrollable at side and the username is still in their position.

code for single row:

18993

    <input type="checkbox" class="checkboxes" name="user_select[]">
    TestingalksdjaskldjsalkdjalskdjaksduqwoieuoqweuowqeiTesting@gmail.com

    Tested091237871
    Field staff
    Testing
    Tested

             N/A

    Active
     N/A
     N/A
     N/A

CSS:
.headcol {
    position: absolute;
    width: 18em;
    border-right: 2px solid #fff;
    background-color: #fff;
    z-index: 0;
}

table tr td {
    /* background: #fff; */
    padding: 6px;
    text-align: left;
    vertical-align: middle;
    border-bottom: 1px solid #ddd;
}

how can I align and wrap the text base on the width of the username column?

A: It happens because there is a white space between those nodes (the checkbox and the text node). The line breaks at white space.
There are two way to handle this.
As mentioned by @Supraja Ganji: Use word-break.
table tr td {
    word-break: break-all;
}

or prevent the whole line from breaking, and hide anything that overflows:
table tr td {
    white-space: nowrap;
    overflow: hidden;
}

A: Your username is too long and doesnot contain any space, so it is not wrapping.
for td give word-break: break-all
table tr td {
    /* background: #fff; */
    padding: 6px;
    text-align: left;
    vertical-align: middle;
    border-bottom: 1px solid #ddd;
    word-break: break-all;
}

A: Using a div inside td is a very bad idea.
Using a div instide a td is not worse than any other way of using tables for layout. (Some people never use tables for layout though, and I happen to be one of them.)
If you use a div in a td you will however get in a situation where it might be hard to predict how the elements will be sized. The default for a div is to determine its width from its parent, and the default for a table cell is to determine its size depending on the size of its content.
The rules for how a div should be sized is well defined in the standards, but the rules for how a td should be sized is not as well defined, so different browsers use slightly different algorithms.
Let me know if you require any further help

A:

.headcol {
    position: relative;
    width: 18em;
    border-right: 2px solid #fff;
    background-color: #fff;
    z-index: 0;
}
.innerHead {
    word-break: break-all;
    overflow: hidden;
}

18993

    <input type="checkbox" class="checkboxes" name="user_select[]">
    TestingalksdjaskldjsalkdjalskdjaksduqwoieuoqweuowqeiTesting@gmail.com

    Tested091237871
    Field staff
    Testing
    Tested

             N/A

    Active
     N/A
     N/A
     N/A


text:
Q: How do I retain the state in a web app during use of authenticator app on mobile device I have a web app that works with Google Drive. In the beginning, you have to log into Google Drive in order to be able to access it. This brings up the Google Login screen, first asking for email, then password, then (if 2FA is configured) for the code from the Google Authenticator app. If the user is doing that on a mobile device s/he has to leave the web app, open the authenticator app, retrieve the code and return to the web app.
My problem is now, that the web app will then reload and lose the state it was in so that the user has to start over with the login process and the code will most likely expire.
Because the app opens a the Google Login screen over which I have no control, I also can't restore the state manually.
Is there any way to prevent losing the state of the login process when leaving the web app?
Thanks all
Marc


text:
Q: Insert and Update XML with DOM I'm saving game data on a XML
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<games>
  <player id="1">
    <name>Player 1</name>
    <level>2</level>
    <score>1000</score>
  </player>
  <player id="2">
    <name>Player 2</name>
    <level>4</level>
    <score>7500</score>
  </player>
</games>

How I can insert a new player node at the end of the xml and then update the xml?

A: Element player = document.createElement("player");
player.setAttribute("id","3");

Element name = document.createElement("name");
name.setTextContent("Player 3");
player.appendChild(name);

Element level = document.createElement("level");
level.setTextContent("4");
player.appendChild(level);

Element score = document.createElement("score");
score.setTextContent("10000");
player.appendChild(score);

Element games = document.findElementsByTag("games").item(0);
games.appendChild(player);


text:
Q: Implementing correct GetHashCode I have the following class
public class ResourceInfo
{
    public string Id { get; set; }
    public string Url { get; set; }
}

which contains information about some resource.
Now I need the possibility to check if two such resources are equal by the following scenario (I`ve implemented IEquatable interface)
public class ResourceInfo : IEquatable<ResourceInfo>
{
    public string Id { get; set; }
    public string Url { get; set; }

    public bool Equals(ResourceInfo other)
    {
        if (other == null)
            return false;

        // Try to match by Id
        if (!string.IsNullOrEmpty(Id) && !string.IsNullOrEmpty(other.Id))
        {
            return string.Equals(Id, other.Id, StringComparison.InvariantCultureIgnoreCase);
        }

        // Match by Url if can`t match by Id
        return string.Equals(Url, other.Url, StringComparison.InvariantCultureIgnoreCase);
    }
}

Usage: oneResource.Equals(otherResource). And everything is just fine. But some time have passed and now I need to use such eqaulity comparing in some linq query.
As a result I need to implement separate Equality comparer which looks like this:
class ResourceInfoEqualityComparer : IEqualityComparer<ResourceInfo>
{
    public bool Equals(ResourceInfo x, ResourceInfo y)
    {
        if (x == null || y == null)
            return object.Equals(x, y);

        return x.Equals(y);
    }

    public int GetHashCode(ResourceInfo obj)
    {
        if (obj == null)
            return 0;

        return obj.GetHashCode();
    }
}

Seems to be ok: it makes some validation logic and uses the native equality comparing logic. But then I need to implement GetHashCode method in the ResourceInfo class and that is the place where I have some problem.
I don`t know how to do this correctly without changing the class itself.
At first glance, the following example can work
public override int GetHashCode()
{
    // Try to get hashcode from Id
    if(!string.IsNullOrEmpty(Id))
        return Id.GetHashCode();
    // Try to get hashcode from url
    if(!string.IsNullOrEmpty(Url))
        return Url.GetHashCode();

    // Return zero
    return 0;
}

But this implementation is not very good.
GetHashCode should match the Equals method : if two objects are equal, then they should have the same hashcode, right? But my Equals method uses two objects to compare them. Here is the usecase, where you can see the problem itself:
var resInfo1 = new ResourceInfo()
{
    Id = null,
    Url = "http://res.com/id1"
};
var resInfo2 = new ResourceInfo()
{
    Id = "id1",
    Url = "http://res.com/id1"
};

So, what will happen, when we invoke Equals method: obviously they will be equal, because Equals method will try to match them by Id and fail, then it tries matching by Url and here we have the same values. As intended.
resInfo1.Equals(resInfo1 ) -> true

But then, if they are equal, they should have the same hash codes:
var hash1 = resInfo.GetHashCode(); // -263327347
var hash2 = resInfo.GetHashCode(); // 1511443452

hash1.GetHashCode() == hash2.GetHashCode() -> false

Shortly speaking, the problem is that Equals method decides which field to use for equality comparing by looking at two different objects, while GetHashCode method have access only to one object.
Is there a way to implement it correctly or I just have to change my class to avoid such situations?
Many thanks.

A: Your approach to equality fundamentally breaks the specifications in Object.Equals.
In particular, consider:
var x = new ResourceInfo { Id = null, Uri = "a" };
var y = new ResourceInfo { Id = "yz", Uri = "a" };
var z = new ResourceInfo { Id = "yz", Uri = "b" };

Here, x.Equals(y) would be true, and y.Equals(z) would be true - but x.Equals(z) would be false. That is specifically prohibited in the documentation:

*

*If (x.Equals(y) && y.Equals(z)) returns true, then x.Equals(z) returns true.

You'll need to redesign, basically.


text:
Q: How to bind two nested structures using pybind11 typedef struct _Names
{
    int a;
    int b;
    int c;
} Names;

typedef struct _values
{
    Names names;
}values;

binding code I have is
py::class_<Names>(m, "Names")
    .def(py::init<>())
    .def_readwrite("a", &Names::a)
    .def_readwrite("b", &Names::b)
    .def_readwrite("c", &Names::c);

py::class_<values>(m, "values")
    .def(py::init<>())
    .def_readwrite("names", &values::names);

but I am unable to access names.a or names.b or names.c.
How can I bind names with Names structure?

A: welcome to SO!
Hum, it should work. My guess is that your python code doesn't instantiate the class values correctly.
I have
#include <iostream>
#include <pybind11/pybind11.h>
#include <pybind11/numpy.h>

namespace py=pybind11;

typedef struct _Names
{
    int a;
    int b;
    int c;
} Names;

typedef struct _values
{
    Names names;
} values;

// Wrapping code
PYBIND11_MODULE(wrapper, m) {
    py::class_<Names>(m, "Names")
        .def(py::init<>())
        .def_readwrite("a", &Names::a)
        .def_readwrite("b", &Names::b)
        .def_readwrite("c", &Names::c);

    py::class_<values>(m, "values")
        .def(py::init<>())
        .def_readwrite("names", &values::names);
}

And if I compile it (see example 1 in this github repo if you need directions) to a file called wrapper, I can use it from python as
import wrapper

b = wrapper.values()  # <-- don't forget the parenthesis !
b.names.a = 30
print(b.names.a)  # prints 30

I'm guessing you didn't put parenthesis after wrapper.values which causes (in my case) b to contain the class definition instead of an instance of it.
Hope it helps :)


text:
Q: Django Sort by backward foreign key I currently have the following models
class ChatRoom(models.Model):
      creator = models.ForeignKey('User') # points to the initial user

class Message(models.Model):
      room = models.ForeignKey('ChatRoom')
      text = models.CharField(max_length=500)
      date = models.DateTimeField()
      from = models.ForeignKey('User') # points to some user

For any given user who logs into my website, I want to display a list of the chat rooms they have created, ordered by the date of their last message (latest activity) along with the last message entered to the chatroom
So something like
Your chat rooms
---------------
science - "hey guys, anyone know how to do calculus?" 5m
art     - "hey guys, I like art" 10m

How would I perform this query in django? Keep in mind that a person might have many, many, many chat rooms and thus we can't just load all the chat_rooms with ChatRoom.objects.all() and manually iterate through it.

A: You need to have a additional relation to your last message, otherwise you will not be able to order by them.
class ChatRoom(models.Model):
      creator = models.ForeignKey('User') # points to the initial user
      # you will need to set this in view or with signals.(don't forget to handle delete)
      last_message = models.ForignKey('Message')

And that you can do this
ChatRoom.objects.filter(...).order_by('last_message__date')


text:
Q: How redirect after registration? I have 2 different pages one  is for employee and other one is for employer ,
After signup I need to redirect page based on user role:-

*

*If user role is employee redirected to employee page

OR

*

*If user role is employer redirected to employer page,

A: You can use register_new_user hook which is the last hook before WordPress perform the redirect to check your email page.
In the callback function you will get user ID, using it get the user data and check if user belongs to specific role.
Example:-
function wpse_228545_register_redirect( $user_id ) {
    $user_data = get_userdata($user_id); //Get the user data
    $roles = !empty($user_data->roles) ? $user_data->roles : array();
    $page_slug = '';

    if ( in_array('employee', $roles) ){
        $page_slug = 'employee';
    } else if ( in_array('employer', $roles) ) {
        $page_slug = 'employer';
    }

    if ( $page_slug ) {
        //You can use get_permalink() and get_page_by_path()
        //if you have different URL structure Or want to change in future.
        wp_safe_redirect( site_url( $page_slug ) );
        exit;
    }

    return;
}
add_action('register_new_user', 'wpse_228545_register_redirect');


text:
Q: Converting coordinates to another form, bug fix I am converting coordinates to another format, but there was an error
longitude = (lon - 4294967295) / 6356752.3142 * (180/math.pi)
unsupported operand type(s) for -: 'list' and 'int'

I will be grateful for advice

A: You can't perform a mathematical operation like subtraction on a list AKA an iterable type and an integer. You're trying to do:
[0,1,2,3,..,n] - 4294967295

What you might have meant is:
(lon[i] - 4294967295)

Where i is the index number for whichever value of the list you wanted.

A: If lon is a list, rather than a numpy array, you can't perform subtraction directly. List comprehension would do it,
longitude = [(l - 4294967295) / 6356752.3142 * (180/math.pi) for l in lon]

which iterates through lon and applies the proper arithmetic on the iterates. Otherwise, using numpy, you can do it directly
import numpy as np
lon = np.array(lon)
longitude = (lon - 4294967295) / 6356752.3142 * (180/math.pi)

A: Try just converting your lon from a list (which doesn't support arithmetic operations like +, -, etc.) to a numpy array (which does support arithmetic operations):
lon = np.array(lon)
longitude = (lon - 4294967295) / 6356752.3142 * (180/math.pi)


text:
Q: Why context menu doesn't opens in fragment? I'm trying to create context menu inside fragment. My sequence of actions:
1)Create resource directory and menu file (context_menu.xml)
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/download"
    android:title="Download"/>

<item android:id="@+id/hello"
    android:title="Hello"/>

<item android:id="@+id/bye"
    android:title="Bye"/>

2)Setup button inside oncreateView()
val button = view.findViewById<Button>(R.id.download_button)
    registerForContextMenu(button)
    button.setOnClickListener {
        Toast.makeText(requireContext(), "Click", Toast.LENGTH_SHORT).show()
    }

Button works. Toast appears.
3)Override method onCkeateContextMenu() inside my fragment
override fun onCreateContextMenu(
    menu: ContextMenu,
    v: View,
    menuInfo: ContextMenu.ContextMenuInfo?
) {
    super.onCreateContextMenu(menu, v, menuInfo)
    requireActivity().menuInflater.inflate(R.menu.context_menu, menu)
}

Pressing the button does not open the menu. What could be the problem?

A: After registering the context menu with registerForContextMenu(), you need to start the action mode with activity.startSupportActionMode(someCallback)


text:
Q: Measuring direction of a three phase motor (400VAC, 50 Hz) within a 5V-circuit I've got a lot of motor controller boards, without the actual motor, and I'm interested in measuring at the output terminals (U,V, W) to see if there's any voltage. This to just check rudimentally if the boards work.
Since it's three phase output, I also need to check the phase order: U-V-W = forward, W-V-U = backward.
The actual direction is simple to test with a small PIC, but how can I reduce the dangerous voltages to a 5V compatible level? I don't think relays will work due to the fast switching (and tremendous amount of noise), so is there any other safe way?


text:
Q: Setting item ubiquitous strange behaviour The thing is, i have a UIManagedDocument in some local directory. Im setting it ubiquitous.
Here is the code :
-(void)queryGatheredInfo:(NSNotification*)notification{
    NSLog(@"Query gathered info!");
    [[NSNotificationCenter defaultCenter]removeObserver:self name:NSMetadataQueryDidFinishGatheringNotification object:self.documentQuery];
    NSLog(@"Removed AppDelegate as an observer for NSMetadataQueryDidFinishGatheringNotification.");
    [self.documentQuery disableUpdates];
    NSMetadataQuery* tempQuery=[notification object];
    if(tempQuery.resultCount){
        NSLog(@"Query Found Items:");
        for (int i=0;i<tempQuery.resultCount;i++){
            NSMetadataItem* item=[tempQuery resultAtIndex:i];
            NSURL* itemURL=[item valueForAttribute:NSMetadataItemURLKey];
            NSString* itemFSName=[[self filePackageURLForCloudURL:itemURL]lastPathComponent];
            NSLog(@"Item %d: %@",i,itemFSName);
            if([itemFSName isEqualToString:kUSER_DOCUMENT_NAME]){
                NSLog(@"FOUND A SAVED DOCUMENT IN iCLOUD!");
                [self loadDocumentFromiCloudAtURL:[itemURL URLByDeletingLastPathComponent]withPersistentStoreOptions:[self getPersistentOptionsFromDocumentMetadataAtURL:itemURL]];
                break;
            }
        }
    }else{
        NSLog(@"Query did not found a document in iCloud!");
        if([[NSFileManager defaultManager]fileExistsAtPath:[[self localDocumentURL]path]]){
            NSLog(@"Document was found in local documents directory.");
            [self transferFileFromLocalDirectory:[self localDocumentURL] ToiCloudDirectory:[[self iCloudDocumentsURL]URLByAppendingPathComponent:kUSER_DOCUMENT_NAME]];
        }else{
            NSLog(@"Creating new document in iCloud!");
            [self createNewDocumentIniCloud];
        }
    }
    [self.documentQuery stopQuery];
}
-(void)transferFileFromLocalDirectory:(NSURL*)localURL ToiCloudDirectory:(NSURL*)iCloudURL{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSError* error=nil;
        BOOL flag=[[NSFileManager defaultManager]setUbiquitous:YES itemAtURL:localURL destinationURL:iCloudURL error:&error];
        if(flag){
            NSLog(@"Successfully set document ubiquitous");
            UIManagedDocument* doc=[[UIManagedDocument alloc]initWithFileURL:iCloudURL];
            doc.persistentStoreOptions=[self getPersistentOptionsFromDocumentMetadataAtURL:[iCloudURL URLByAppendingPathComponent:@"DocumentMetadata.plist"]];
            [self openDocument:doc];
        }else{
            NSLog(@"There was an error setting document Ubiquitous.\n%@",error);
        }
    });
}

And after this, it starts to download copies of itself for 2 times. So at the end i get the 3 same items in my core data. But if i delete the app, and run it again, it finds document in icloud, loads it, and it looks alright, no duplicate items.
My question is: what's happening when i set my document ubiquitous? why does it load duplicates?
Here is output when the item is set ubiquitous:
2013-12-01 22:02:56.452 iGymPRO[5517:60b] iCloud is available
2013-12-01 22:02:56.456 iGymPRO[5517:60b] Added AppDelegate as an observer for NSMetadataQueryDidFinishGatheringNotification.
2013-12-01 22:02:56.458 iGymPRO[5517:60b] Query started!
2013-12-01 22:02:56.500 iGymPRO[5517:60b] Query gathered info!
2013-12-01 22:02:56.502 iGymPRO[5517:60b] Removed AppDelegate as an observer for NSMetadataQueryDidFinishGatheringNotification.
2013-12-01 22:02:56.503 iGymPRO[5517:60b] Query did not found a document in iCloud!
2013-12-01 22:02:56.569 iGymPRO[5517:60b] Document was found in local documents directory.
2013-12-01 22:02:56.609 iGymPRO[5517:1803] Successfully set document ubiquitous
2013-12-01 22:02:56.983 iGymPRO[5517:3e03] -[PFUbiquitySwitchboardEntryMetadata setUseLocalStorage:](754): CoreData: Ubiquity:  mobile~5815F60F-67BF-4FD1-8376-B509672B469D:UserDataDocumentContent
Using local storage: 1
2013-12-01 22:02:57.055 iGymPRO[5517:60b] Opened document
2013-12-01 22:02:57.057 iGymPRO[5517:60b] Removing delegate as an observer for UIDocumentStateChangedNotification
2013-12-01 22:02:57.059 iGymPRO[5517:60b] Listening to UIDocumentStateChangedNotification
2013-12-01 22:02:57.060 iGymPRO[5517:60b] Managed Object Context is ready to use! Dismissing loading screen
2013-12-01 22:02:57.925 iGymPRO[5517:4707] -[PFUbiquitySwitchboardEntryMetadata setUseLocalStorage:](754): CoreData: Ubiquity:  mobile~5815F60F-67BF-4FD1-8376-B509672B469D:UserDataDocumentContent
Using local storage: 0
2013-12-01 22:03:02.650 iGymPRO[5517:4707] -[PFUbiquitySetupAssistant finishSetupWithRetry:](811): CoreData: Ubiquity:  <PFUbiquitySetupAssistant: 0x1463c2f0>: Retrying after delay: 60
2013-12-01 22:04:09.390 iGymPRO[5517:470b] -[PFUbiquitySwitchboardEntryMetadata setUseLocalStorage:](754): CoreData: Ubiquity:  mobile~5815F60F-67BF-4FD1-8376-B509672B469D:UserDataDocumentContent
Using local storage: 0
2013-12-01 22:04:13.875 iGymPRO[5517:470b] -[PFUbiquitySetupAssistant finishSetupWithRetry:](811): CoreData: Ubiquity:  <PFUbiquitySetupAssistant: 0x1463c2f0>: Retrying after delay: 120
2013-12-01 22:06:59.170 iGymPRO[5517:4717] -[PFUbiquitySwitchboardEntryMetadata setUseLocalStorage:](754): CoreData: Ubiquity:  mobile~5815F60F-67BF-4FD1-8376-B509672B469D:UserDataDocumentContent
Using local storage: 0
2013-12-01 22:13:34.370 iGymPRO[5517:4227] __45-[PFUbiquityFilePresenter processPendingURLs]_block_invoke(305): CoreData: Ubiquity:  Librian returned a serious error for starting downloads Error Domain=LibrarianErrorDomain Code=1 "The operation couldn't be completed. (LibrarianErrorDomain error 1 - Unable to initiate download.)" UserInfo=0x1467b370 {Item Errors={
    "file:///private/var/mobile/Library/Mobile%20Documents/476DPCGZ25~trenbolone~SP~iGym/CoreData/UserDataDocumentContent/mobile~5815F60F-67BF-4FD1-8376-B509672B469D/UserDataDocumentContent/GxrbFeXHGcfBNM0uvaCzuqHE4XmcYCiCKbgWv7OTybM=/receipt.0.cdt" = "Error Domain=UBErrorDomain Code=10 \"The operation couldn\U2019t be completed. (UBErrorDomain error 10 - Error Domain=UBErrorDomain Code=10 \"The operation couldn\U2019t be completed. (UBErrorDomain error 10 - The item can't be found on disk, is not yet scanned or was deleted)\" UserInfo=0x14570a30 {NSDescription=The item can't be found on disk, is not yet scanned or was deleted})\" UserInfo=0x1463c6a0 {NSDescription=Error Domain=UBErrorDomain Code=10 \"The operation couldn\U2019t be completed. (UBErrorDomain error 10 - The item can't be found on disk, is not yet scanned or was deleted)\" UserInfo=0x14570a30 {NSDescription=The item can't be found on disk, is not yet scanned or was deleted}}";
}, NSUnderlyingError=0x1470d510 "The operation couldn't be completed. (UBErrorDomain error 10 - The item can't be found on disk, is not yet scanned or was deleted)", NSDescription=Unable to initiate download.} with userInfo {
    "Item Errors" =     {
        "file:///private/var/mobile/Library/Mobile%20Documents/476DPCGZ25~trenbolone~SP~iGym/CoreData/UserDataDocumentContent/mobile~5815F60F-67BF-4FD1-8376-B509672B469D/UserDataDocumentContent/GxrbFeXHGcfBNM0uvaCzuqHE4XmcYCiCKbgWv7OTybM=/receipt.0.cdt" = "Error Domain=UBErrorDomain Code=10 \"The operation couldn\U2019t be completed. (UBErrorDomain error 10 - Error Domain=UBErrorDomain Code=10 \"The operation couldn\U2019t be completed. (UBErrorDomain error 10 - The item can't be found on disk, is not yet scanned or was deleted)\" UserInfo=0x14570a30 {NSDescription=The item can't be found on disk, is not yet scanned or was deleted})\" UserInfo=0x1463c6a0 {NSDescription=Error Domain=UBErrorDomain Code=10 \"The operation couldn\U2019t be completed. (UBErrorDomain error 10 - The item can't be found on disk, is not yet scanned or was deleted)\" UserInfo=0x14570a30 {NSDescription=The item can't be found on disk, is not yet scanned or was deleted}}";
    };
    NSDescription = "Unable to initiate download.";
    NSUnderlyingError = "Error Domain=UBErrorDomain Code=10 \"The operation couldn\U2019t be completed. (UBErrorDomain error 10 - The item can't be found on disk, is not yet scanned or was deleted)\" UserInfo=0x145d6340 {NSDescription=The item can't be found on disk, is not yet scanned or was deleted}";
}

and this is output when i delete and run my app ( when everything loads fine)
2013-12-01 22:32:49.748 iGymPRO[5525:60b] iCloud is available
2013-12-01 22:32:49.754 iGymPRO[5525:60b] Added AppDelegate as an observer for NSMetadataQueryDidFinishGatheringNotification.
2013-12-01 22:32:49.756 iGymPRO[5525:60b] Query started!
2013-12-01 22:32:49.897 iGymPRO[5525:60b] Query gathered info!
2013-12-01 22:32:49.898 iGymPRO[5525:60b] Removed AppDelegate as an observer for NSMetadataQueryDidFinishGatheringNotification.
2013-12-01 22:32:49.899 iGymPRO[5525:60b] Query Found Items:
2013-12-01 22:32:49.959 iGymPRO[5525:60b] Item 0: Data Document
2013-12-01 22:32:49.960 iGymPRO[5525:60b] FOUND A SAVED DOCUMENT IN iCLOUD!
2013-12-01 22:32:50.031 iGymPRO[5525:60b] Opening document from iCloud
2013-12-01 22:32:54.203 iGymPRO[5525:5003] -[PFUbiquitySwitchboardEntryMetadata setUseLocalStorage:](754): CoreData: Ubiquity:  mobile~5815F60F-67BF-4FD1-8376-B509672B469D:UserDataDocumentContent
Using local storage: 1
2013-12-01 22:32:54.259 iGymPRO[5525:60b] Opened document
2013-12-01 22:32:54.260 iGymPRO[5525:60b] Removing delegate as an observer for UIDocumentStateChangedNotification
2013-12-01 22:32:54.261 iGymPRO[5525:60b] Listening to UIDocumentStateChangedNotification
2013-12-01 22:32:54.262 iGymPRO[5525:60b] Managed Object Context is ready to use! Dismissing loading screen
2013-12-01 22:33:57.635 iGymPRO[5525:1803] -[PFUbiquitySwitchboardEntryMetadata setUseLocalStorage:](754): CoreData: Ubiquity:  mobile~5815F60F-67BF-4FD1-8376-B509672B469D:UserDataDocumentContent
Using local storage: 0

A: Happy to be corrected on this but I don't think this is the correct way to set a UIManagedDocument up to synch via iCloud.  If you have a UIManagedDocument in a local directory you need to migrate the store itself to iCloud using the persistentStoreCoordinators migratePersistentStore method in order to recreate the log files in iCloud.
I am quite surprised it works at all when you delete and reinstall the app.


text:
Q: (WiX) Program files shortcut for per-machine install Following the example here, I added a shortcut to the ProgramMenuFolder that launches my application.  (My code is actually simpler because I don't need the extra folder.)
<DirectoryRef Id='ProgramMenuFolder'>
  <Component Id='cmpStartMenuShortcut'
             Guid='MY GUID HERE'>
    <Shortcut Id='StartMenuShortcut'
              Name='$(var.ProductName)'
              Icon='MainIcon.ico'
              Description='$(var.ProductName)'
              Target='[ClientDir]myapp.exe'
              WorkingDirectory='ClientDir'/>
    <RegistryValue Action='write' Type='integer' Root='HKCU'
                   Key='Software\Company\Product Name'
                   Name='installed' Value='1' KeyPath='yes'/>
  </Component>
</DirectoryRef>

Since my installation is per machine (ALLUSERS=1, Package/@InstallPrivileges='elevated', and @InstallScope='perMachine') the ProgramMenuFolder is the folder for all users on the machine.
My question has to do with the registry value.  My understanding is that it's needed simply to provide a KeyPath for the component that contains the shortcut.  The sample uses HKCU, which is a per-user location.
Isn't it a mistake to use a per-user value as a KeyPath for a per-machine component?
If a machine has two admins, and admin #1 installs the product, and admin #2 attempts a repair, then Windows Installer won't see the registry value and think that the shortcut is missing and it will install a duplicate, right?
So I tried changing the RegistryValue/@Root to HKLM, but then WiX complains:

error LGHT0204 : ICE38: Component cmpStartMenuShortcut installs to user profile. It's[sic] KeyPath registry key must fall under HKCU.
error LGHT0204 : ICE43: Component cmpStartMenuShortcut has non-advertised shortcuts. It's[sic] KeyPath registry key should fall under HKCU.
error LGHT0204 : ICE57: Component 'cmpStartMenuShortcut' has both per-user and per-machine data with a per-machine KeyPath.

I don't understand why the key must be under HKCU.

A: That style of shortcut is for a target that might not be installed now nor at the time it is invoked. It creates the classic .lnk shortcut file. It is useful for shortcuts to targets that your installer is not responsible for but might be useful for users of your product to use (e.g. cmd.exe).
Alternatively, a shortcut for a target you are installing or advertising will be uninstalled when the target is unadvertised (product is uninstalled). For example, WiX installs a shortcut to wix.chm called WiX Documentation. The Shortcut element for an advertised shortcut can be made a child of the File element.
Here is a hand-written example:
<Component Id="ProductComponent">
   <File Source="$(var.ConsoleApplication1.TargetPath)" KeyPath="yes">
     <Shortcut Id="$(var.ConsoleApplication1.TargetName)Shortcut"
               Name="$(var.ConsoleApplication1.TargetName)"
               Advertise="yes"
               Description="Starts $(var.ConsoleApplication1.TargetName)"
               Directory="ProgramMenuFolder" />
   </File>
</Component>

To insert the Shortcut element into heat's output, pass it the path to an XSL transform. Snippet:
<xsl:template match="wix:File[contains(@Source,'\myapp.exe')]">
  <xsl:copy-of select="." />
  <Shortcut Id='StartMenuShortcut'
          Advertise="yes"
          Name='$(var.ProductName)'
          Icon='MainIcon.ico'
          Description='$(var.ProductName)'
          WorkingDirectory='ClientDir'/>
</xsl:template>

A: What I would recommend doing is simply making the folder as you said, but not placing the shortcut directly under it. Instead make a shortcut element under the component holding the file. You can use the Directory attribute to specify where you want the shortcut to appear.


text: Q: Animating Contour maps with FuncAnimation I am trying to animate a contour map using the matplotlib function: FuncAnimation. I am not to clear about how the fargs parameter is supposed to be set up, as the documentation isn't very specific regarding this parameter.


text:
Q: Trying to submit html form data via xmlhttprequest I am trying to put together a simple login prompt for a bit of in house testing and I have found myself stuck.  I have the login prompt made via HTML and am trying to send it off via xmlhttprequest.  Here is my JS code:
var xhr = new XMLHttpRequest();

function loginResults() {
  var loginUser = document.getElementById("username").value;
  var loginPass = document.getElementById("password").value;
  //console.log(loginUser + loginPass);
  xhr.open("post", "https://test.com/api/login/");
  var loginData = "username=" + loginUser + "&password=" + loginPass
  xhr.send(loginData);
  //console.log(loginData);
  xhr.addEventListener("readystatechange", processRequest, false);
}

function processRequest(e) {
  if (xhr.readyState == 4 && xhr.status == 200) {
    var response = JSON.parse(xhr.responseText);
    console.log(response);
  }
}

The issue is that the xhr.send completely fails using this method.  However if I replace the variables sent with the plain text then everything works fine.  Like this:
var loginData = "username=" + "test@test.com" + "&password=" + "test1234"

What is the difference between pulling the info via the form data and having the login hard coded like that?  The request payload is exactly the same in both instances.
EDIT
Here is the gist of my HTML form:
    <form name="isLogin" id="isLogin" onSubmit="loginResults()" method="post">

Email

<input type="text" id="username" placeholder="Enter Email" name="username" required>

Password

<input type="password" id="password" placeholder="Enter Password" name="password" required>

<button id="submitLogin"  type="submit">Login</button>

A: The reason the request gets cancelled is you aren't intercepting the standard form submission. When you click the Login button, Chrome fires off the AJAX request, then also submits the form. Since this leads to a page load, Chrome cancels the AJAX request.
What you need to do is prevent the default event handling. A clean way to do this is to add the submission handling in your script:

document.getElementById("isLogin").onsubmit = function(e) {
  e.preventDefault();
  // AJAX here
  console.log("form submission intercepted");
};
<form name="isLogin" id="isLogin" method="post">

    Email
    <input type="text" id="username" value="test@test.com" name="username" required>
    Password
    <input type="password" id="password" value="test1234" name="password" required>
    <button id="submitLogin" type="submit">Login</button>

</form>

A: You need to escape values before concatenating them to the URL querystring:
    var loginUser = encodeURIComponent(document.getElementById("username").value);
    var loginPass = encodeURIComponent(document.getElementById("password").value);

Secondly, i wouldn't recommend passing password directly through querystring.
The secure way to pass it is preferably salted-and-hashed.


text:
Q: Better way to add time to a timestamp in MySQL I like to add a 5 minutes to a timestamp:
SELECT timestamp+300 FROM table

works with minutes (5*60 = 300) But if I like to add a month or a year I can't calculate in seconds.
I came up with this query:
SELECT UNIX_TIMESTAMP(FROM_UNIXTIME(timestamp) + INTERVAL 5 MINUTE) FROM table

So I can go with years as well:
SELECT UNIX_TIMESTAMP(FROM_UNIXTIME(timestamp) + INTERVAL 2 YEAR) FROM table

Is this "the" solution or is there a more, elegant way?


text:
Q: MSSQL Single user mode block I am a web design so I dont understand almost nothing of servers and stuff.
I was working with MSSQL Server and ASP.NET to create a form that save its information in a database. But it was failing because my account in MSSQL was asking "Please change your password" because it had a "Enforce password expiration". I needed the "sa" account password to change it (I was using SQL Authentication) but I didnt know about the "sa" password.
I searched in Internet and I found out about "single user mode". I  added the "-m" to the startup parameters but I am so stupid that I forgot about stop sql agent.
Result? I cant use MSSQL now. Neither with administration account. Is there any way to solve this problem?
I am so sorry about this and thanks so much to who try to help me. :)

A: Did you add this via configuration manager? You should be able to just edit the startup parameters again and restart the service, and it should come back online in multi user mode.
Edit: Just checked and this definitely works.

*

*Launch SQL Server Configuration Manager

*Right click your SQL Instance > Properties

*On the Startup Parameters tab, remove the -m flag youve added

*Click OK, OK to apply

*Right click the service and click restart

You will be back in multi user mode.


text:
Q: Wordpress plugin dev w/ JS library dependencies? Best long term approach w/ source management? What is the best approach to Wordpress plugin development when your plugin requires numerous javascript library dependencies?
My example: I'm developing a plugin which makes heavy use of the Backgrid.js library in the plugins administration area. Basic dependencies of Backgrid.js are Backbone.js and Underscore.js. Not a problem because Wordpress includes recent versions of both in recent versions.
The problem? In my Backgrid.js implementation I'm also having to use many of the available extensions, like backgrid-paginator to get pagination working. Many of the extensions are listed here: https://github.com/wyuenho/backgrid/wiki#extensions
My head scratcher is how to best manage this plugin long-term with my source control management. Because I did NOT want to go the long route of downloading each individual extension myself, I simply used Bower (http://bower.io/) within my plugin directory to quickly download these dependencies. This creates a /bower_components directory in my plugin folder where all these dependencies sit.
Now let me preface, I'm pretty new to using Bower. But I'm also pretty new to Wordpress development so I'm not completely up to speed with best practices for this platform. Only working on it due to a client necessitating it.
Of course now my Wordpress plugin is filled with loading scripts such as:
wp_enqueue_script('backgrid-paginator', CUSTOM_PLUGIN__PLUGIN_URL . 'bower_components/backgrid-paginator/backgrid-paginator.min.js', array( 'jquery','backbone','underscore','backgrid', 'backbone-pageable'));
wp_enqueue_style('backgrid-paginator-css', CUSTOM_PLUGIN__PLUGIN_URL . 'bower_components/backgrid-paginator/backgrid-paginator.min.css');

What is the best approach in managing this plugin long term with source control? I'm a little bit of a novice with Bower and everything on Google only talks about using Bower with Wordpress theme development. Nothing speaks to using it with plugin development.
Thinking now, is the best approach to create a Bower bower.json in my plugin directory, which includes all these dependencies? I'll add this bower.json file then to my source control for the plugin, but a README installation requirement will be including that the plugin requires XXX dependencies and the easiest way is to just run: bower install in the plugin's directory to grab everything?
Is that the best approach? I'm trying to consider long term and make whoevers job it will be to take over responsibility for the plugin easier! :)

A: To my knowledge WordPress has no real standard for managing JavaScript and CSS dependencies outside of the enqueuing them in the right order.
Using Bower for managing the dependencies is definitely a good idea. It will keep your repo clean of vendor files and make it easy to update libraries later on.
If you want to make your life a little bit easier, you can also look into Grunt JS or Gulp JS which are build tools. You can use these to compress, uglify, etc all your JavaScript and CSS files into distributable items (e.g. all.min.js & all.min.css). This will make it easier to add/remove libraries.
Using these will also keep your enqueue statements cleaner.


text:
Q: Fontspec error: My favorite fonts could not be identified I'm trying to add Persian text to my document, however, my favorite fonts (which already have been installed on Windows 10 and I use them on Microsoft Word) can not be identified.
! fontspec error: "font-not-found"!! The font "XB Niloofar" cannot be found.!!
! fontspec error: "font-not-found"!! The font "Yas" cannot be found.!!
! fontspec error: "font-not-found"!! The font "IranNastaliq" cannot be found.!!

Here is the document I'm trying to compile:
\documentclass[11pt]{exam}
\usepackage{xepersian}

\settextfont[Scale=1]{XB Niloofar}
\setdigitfont[Scale=1]{Yas}
\setlatintextfont[Scale=0.9]{Times New Roman}
\defpersianfont\nastaliq[Scale=1]{IranNastaliq}

\begin{document}
\textbf{سلام}
\end{document}

A: The recommended way to load fonts in fontspec is by filename.  You can try:
\settextfont[Scale = 1.0 ,
             BoldFont = *Bd ,
             ItalicFont = *It ,
             BoldItalicFont = *BdIt ,
             Extension = .ttf
            ]{XB Niloofar}

If your fonts are named XB Niloofar.ttf, XB NiloofarBd.ttf, etc.
If that still doesn't work, see if \setmainfont with the same options does.  This is probably not what you want, but it can confirm that the issue is or is not with fontspec.
You can run fc-match "XB Niloofar" to see if XeTeX can find the font and luaotfload-tool --find "XB Niloofar" to see if LuaTeX can.
Also make sure the fonts are installed for all users, in the %WINDIR%\Fonts\ directory.  Separately, if you have any local font caches in %HOMEDRIVE%%HOMEPATH%\.texlive2019\texmf-var\, delete them.


text:
Q: Drawing in LaTeX I really like Tikz for drawing little and easy diagrams in my LaTex documents.
However, I am not very skilled so I'm looking for someone to give me a help to realize this drawing (without colors: D). Thank you all for the help!

A: Thank you so much anakrich! I hadn't posted any code because I didn't know how to start XD I tried to play with your code to get something more stylish :P Here is the modified code:
\begin{tikzpicture}[scale=1]

% Cylinder
\begin{scope}[fill=teal!20]
    \fill[draw, rounded corners=2mm] (0,0) rectangle (2,3);
    \fill (1.9,1.25) rectangle (3,1.5)
    (3,1) rectangle (3.75,1.75)
    (3.75,1.75) rectangle (7,0.5);
    \node [shape=isosceles triangle, fill=black,rotate=90,scale=0.3] at (2.5,1.25){};
    \node [shape=isosceles triangle, fill=black,rotate=-90,scale=0.3] at (2.5,1.5){};
\end{scope}

% Cylinder Boundary
\draw[thick] (2,1.25) -- (3,1.25);
\draw[thick] (3,1.25) -- (3,1);
\draw[thick] (3,1) -- (3.75,1);
\draw[thick] (3.75,1) -- (3.75,0.5);
\draw[thick] (3.75,0.5) -- (6.98,0.5);
\draw[thick] (6.98,0.5) -- (6.98,0.6);
\draw[thick] (6.98,1.65) -- (6.98,1.75);
\draw[thick] (6.98,1.75) -- (3,1.75);
\draw[thick] (3,1.75) -- (3,1.5);
\draw[thick] (3,1.5) -- (2,1.5);

% Piston
\begin{scope}[fill=gray!60]
    \fill (3.1,1.1) rectangle (4.1,1.65);
    \fill (3.85,1.65) rectangle (7.0,0.6);
    \fill (7,1) rectangle (8,1.25);
\end{scope}

% Piston Boundary
\draw[thick] (7,1) -- (8, 1);
\draw[thick] (7,1.25) -- (8, 1.25);
\draw[thick] (3.85,0.6) -- (7, 0.6);
\draw[thick] (7,0.6) -- (7, 1);
\draw[thick] (7,1.25) -- (7, 1.65);
\draw[thick] (3.1,1.65) -- (7, 1.65);
\draw[thick] (3.1,1.65) -- (3.1, 1.1);
\draw[thick] (3.1,1.1) -- (3.85, 1.1);
\draw[thick] (3.85,1.1) -- (3.85, 0.6);

% Sled
\fill [yellow] (8,0.75) rectangle (10,1.5);
\fill [black]
(8.4,0.6) circle (0.15)
(8.7,0.6) circle (0.15)
(9.3,0.6) circle (0.15)
(9.6,0.6) circle (0.15);
\draw[thick] (10,1.2) .. controls (10.25,1.2) and (10.25,2) .. (10.5,2);

% Sled Boundary
\draw[thick] (8,0.75) -- (10,0.75);
\draw[thick] (10,0.75) -- (10, 1.5);
\draw[thick] (8,1.5) -- (10,1.5);
\draw[thick] (8,0.75) -- (8, 1.5);

% Ground
\draw[thick] (8,0.45) -- (10,0.45);
\fill [pattern = north east lines] (8,0.25) rectangle (10,0.45);

% Text
\node [align=center,anchor=north] at (1,0) {Serbatoio ad\\aria compressa};
%\node [anchor=north] at (2.75,0) {Valvola};
\node [align=center,anchor=north] at (5.3,0) {Sistema cilindro - pistone\\con sezione a scalino};
\node [align=center,anchor=north] at (9,0) {Slitta di\\alaggio};
\node[red] at (2.85,2) {Pressione};
\node[red] at (6.75,2) {Contro-Pressione};
\node [align=center] at (9.75,2.5) {Cavo di\\traino};

% Arrows
\foreach \y in {0.7,0.9,1.35,1.55}
\draw[thick, red,<-] (7,\y) -- (7.5,\y);
\foreach \y in {1.15, 1.35, 1.55}
\draw[thick, red,->] (2.75,\y) -- (3.1,\y);
\draw [thick, red,->] (2.75,0.95) .. controls (3.5,1) and (3,0.7) .. (3.85,0.7);
\end{tikzpicture}

Again, thank you so much !!!

A: Since you are a beginner and I had some time to kill, I am going to provide you with a very basic starting point for your diagram. Actually, it replicates the diagram fairly well. You could play around with this and the PGF manual.
Hope you tikz more and help others in future in LaTeX Stack Exchange.

\documentclass[margin=1mm]{standalone}
\usepackage{tikz}
\usetikzlibrary{shapes.geometric}
\begin{document}
 \begin{tikzpicture}[scale=1.3]
  \begin{scope}[fill=teal!20]
   \fill[rounded corners=2mm] (0,0) rectangle (2,2);
   \fill (2,1.25) rectangle (3,1.5)
   (3,1) rectangle (3.75,1.75)
   (3.75,1.75) rectangle (7,0.5);
   \node [shape=isosceles triangle, fill=black,rotate=90,scale=0.3] at (2.5,1.25){};
   \node [shape=isosceles triangle, fill=black,rotate=-90,scale=0.3] at (2.5,1.5){};
  \end{scope}
  \begin{scope}[fill=gray!60]
   \fill [rounded corners=1mm] (3.1,1.1) rectangle (4.1,1.65);
   \fill [rounded corners=1mm] (3.85,1.65) rectangle (7.0,0.6);
   \fill (7,1) rectangle (8,1.25);
  \end{scope}
  \fill [yellow] (8,0.75) rectangle (10,1.5);
  \fill [black]
  (8.4,0.6) circle (0.15)
  (8.7,0.6) circle (0.15)
  (9.3,0.6) circle (0.15)
  (9.6,0.6) circle (0.15);
  \draw[thick] (10,1.2) .. controls (10.25,1.2) and (10.25,2) .. (10.5,2);
  \foreach \y in {0.8,0.9,1.0,1.3,1.4}
   \draw[red,<-] (7,\y) -- (7.5,\y);
  \foreach \y in {1.15, 1.35, 1.55}
   \draw[red,->] (2.75,\y) -- (3.1,\y);
  \draw [red,->] (2.75,0.95) .. controls (3.5,1) and (3,0.7) .. (3.85,0.7);
  \node [align=center,anchor=north] at (1,0) {Serbatoio ad\\aria compressa};
  \node [anchor=north] at (2.75,0) {Valvola};
  \node [align=center,anchor=north] at (5.5,0) {Sistema cilindro - pistone\\con sezione a scalino};
  \node [align=center,anchor=north] at (9,0) {Slitta di\\alaggio};
  \node[red] at (2.75,2) {Pressione};
  \node[red] at (6.75,2) {Contro-Pressione};
  \node [align=center] at (9.75,2) {Cavo di\\traino};
 \end{tikzpicture}
\end{document}


text:
Q: How can I add a link to my Xamarin.Forms application so it opens a web page? I know how to code the buttons, how to use Command but what I would like some advice on is if there's a way to open a web page from the C# code in my application?  Is this something I need to do async and is there some function I can call that will do this that works in forms back-end code?

A: This is would open a web page in your default browser
Device.OpenUri(new Uri("http://something.com"))

I don't think it should be async function in any way
If you want to write in as async download Xamarin.Essentials plugin and write it as
public async Task<bool> OpenBrowser(Uri uri)
 {
        return await Browser.OpenAsync(uri, BrowserLaunchMode.SystemPreferred);
 }

This method returns after the browser was launched and not necessarily closed by the user. The bool result indicates whether the launching was successful or not.
Read on learn.microsoft.com for more information.


text:
Q: Azure Service Fabric local deployment results in DnsService error: DnsService UDP listener is unable to start The Problem
I am developing an Azure Service Fabric stateless service. While I have deployed locally before, I am currently encountering the following error:
DnsService UDP listener is unable to start. Please make sure there are no processes listening on the DNS port 53.

Things I have tried

*

*Redeploying locally

*Both stopping and resetting the cluster from the tray menu

*Removing the cluster from my machine

*Checking to make sure the cluster manifest has the DnsService parameter IsEnabled set to True

*Starting a new application from scratch

*Azure Service Fabric (OneBox) has constantly failed DnsService has not provided a solution

Edit:

*

*Stopping and disabling the ICS service isn't helpful in my case because ICS restarts when I restart my machine.

Other relevant info
I can deploy successfully to an Azure cluster, so I am fairly certain that the problem lies in the local cluster. But removing the cluster and redeploying does not solve the error!
How do I solve this DnsService error?

A: As the error message suggests:
Please make sure there are no processes listening on the DNS port 53.
From the error message show in the screenshot you provided, is it possible to see other services are listening on the port 53, for that reason the service does not work.
This github issue describe the problem.
In summary, the problem is likely to be the Internet Connection Sharing (ICS) service or other service listening on port 53. You have to stop these services to make DNS service work correctly.
To find out the service using the port 53, you can follow the answer from this question:
How can you find out which process is listening on a port on Windows?

A: I uninstalled Docker per @Taran's answer to another question. This was the most resilient answer as I was then able to deploy successfully x 10. :-)


text:
Q: echo for style in table row and table data <tr <?php if($isOverDeadline)
    {
      echo ' style="background-color:#CC3300"';
    }
  ?>><td width="250" <?php
      if($isOverDeadline)
      {
    echo ' style="color:#fff"';
      }
      ?>><?php echo $something; ?>

I find that the nested php blocks inside tr and td do not work. Could someone tell me what is wrong ?

A: *Check whether isOverDeadline is true or false *
<?php $isOverDeadline = true; ?>
<tr <?php if($isOverDeadline)
    {
      echo ' style="background-color:#CC3300"';
    }
  ?>><td width="250" <?php
      if($isOverDeadline)
      {
    echo ' style="color:#fff"';
      }
      ?>><?php echo $something; ?>

A: What I've typically done in the past, to avoid such possible issues is:
<?php

    // This is merely a convenience method for short circuiting,
    // you could use print() as it always returns 1, however e()
    // is just shorter.
    function e($arg)
    {
        echo $arg;
        return true;
    }

    $isOverDeadline = true;
    $something = "Hello world";

?>

<tr style="<?php $isOverDeadline and e('background-color: #cc3300;'); ?>">
    <td style="<?php $isOverDeadline and e('background-color: #ffffff;'); ?>"
        width="250"><?php e($something); ?>

This uses short circuit evaluation to minimize inlined PHP. As you can see, some IDEs or syntax hilighters will barf on it, but I run NetBeans and it looks good.
Keep in mind, my example will result in empty style attributes when $isOverDeadline is false, but you can modify as necessary (the generating code looks cleaner without having to deal with prepending spaces, etc.)
You can even replicate else:
<tr style="background-color: <?php ($isOverDeadline and e('#f00')) or e('#0ff'); ?>">

Which will be red on true, cyan on false.

A: You should escape the double quotes like this
    echo ' style=\"background-color:#CC3300\"';


text:
Q: Can I use branch for different projects in single repo? I have some projects with independent code, but similiar purpose. Can I create a giant git repo and create different branch to hold different projects?
For example I want to create a repo named database, and create different branches to hold source code of MySQL, PostGres and ClickHouse. Does it make sense?

A: Some git operations will be slower due to the size of such a repository, but it is perfectly fine.
Git even comes with a lot of built-in support for creating and working with repositories like this:

*

*git switch --orphan for creating new orphan branches

*get merge --allow-unrelated-histories for merging between branches with different roots

*get worktree for checking out branches in a separate folder

*git submodule easily handles submodules that point into the same repository


text:
Q: Converting types for sorting : any runtime cost? I'm just getting to grips with Go (started two days ago and wrote less than 1000 lines), and I'm still wondering about some idioms.
I needed to sort a slice of strings by descending length. I did like so :
func ... {
    ... do business ...

    sort.Sort(stringsLongestFirst(severalThousandStrings))

    ... carry on and be happy, because it works ...
}

type stringsLongestFirst []string

func (b stringsLongestFirst) Len() int           { return len(b) }
func (b stringsLongestFirst) Less(i, j int) bool { return len(b[i]) > len(b[j]) }
func (b stringsLongestFirst) Swap(i, j int)      { b[j], b[i] = b[i], b[j] }

First of all I wonder if this is the most idiomatic way to do it.
And then, most of all, I wonder about what happens under the hood when I write stringsLongestFirst(severalThousandStrings). Does the string slice somehow get smartly reinterpreted as a stringsLongestFirst type, or do I have to count with some copying overhead ?
(edited : removed the excerpt from the specification, that was ill-suited to the case at hand)

A: The types you are converting is neither a numeric type or a string: []string and stringsLongestFirst are slice types.
So the conversion should incur no more overhead than copying the slice header (which is 12 or 24 bytes, depending on the word size), which would happen anyway when packing it as an interface{} variable in order to call Sort.  The backing array is not copied, which is why severalThousandStrings appears to be sorted after the call.