text:
Q: Creating an interactable Map with tkinter : Need advice on creating lines between Buttons I've started learning Python to create a third party application for a video game. Before dealing with the connection between the application and the game client, I'm trying to create a map with tkinter.
I'm using Buttons and lines on a Canvas. Each Button represents a location, connected with another Button by a specific line. For example, Button1 and Button2 are connected by a line that goes from (center of Button1) to (center of Button2).
I've created a function that allows me to easily create a Button at a specific location :
from tkinter import *
root = Tk()
canvas = Canvas(root)

def system(system_name, position_x, position_y):
    Button(root, text = system_name).place(x=position_x, y=position_y, width=60, height=20)

# examples :

system("Location1", 10,10)
system("Location2", 50,50)

canvas.grid()
root.mainloop()

I would like to create a similar function to create a line between 2 buttons. It's easy to manually calculate the center positions of each button, but doing do for several thousands buttons would be quite time consuming.
Would it be possible to create a function like this :
def line(system1, system2):
    system1 = center position of system1 = (a,b)
    system2 = center position of system2 = (c,d)
    canvas.create_line((a,b),(c,d))

Any suggestion is welcome. Thank you in advance.

Edit : Gonna try to re-ask my question in more simple terms :

*

*I want to make canvas lines between buttons.

*Lines go from center to center of buttons.

*I use the following function to create buttons :
def system(system_name, position_x, position_y):
    Button(root, text=system_name).place(x=position_x, y=position_y)

*Examples :
a = system("Location1", 10,20)
b = system("Location2", 40,50)

*Question : How can I re-use the parameters of the previous examples in another function that creates a line between a and b ?

*What I imagine this function would look like:
def line(a, b):   # line between button a and button b
    c = (10 + whatever_width/2, 20 + whatever_height/2)
    d = (40 + whatever_width/2, 50 + whatever_height/2)
    canvas.create_line(c,d)

*Any idea ?


text:
Q: MacOS Ventura update changed terminal command location I recently updated my Mac to MacOS Ventura Beta, causing terminal commands like gcc, pyhton3 and pip3 to not work. Until last week I was able to use them normally, but after the update terminal asks me to download XCode Commandline Developer Tools.
The problem that came with this, is that VSCode is unable to find include files for C/C++.
I tried reinstalling VSCode, VSCode extensions related to C/C++, and even changing the #include_path for C files in VSCode, but nothing seems to work.
Any help would be very much appreciated :).

A: I wanted to put my solution here.
The new macOS Ventura is officially released now. I encountered the same issue you described. The solution was pretty simple, just to install XCode.
Run this command in Terminal.app:
xcode-select --install

*

*Let it install the XCode.

*Restart your VSCode.

You should be working correctly now.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Simple algebra rearrangment $f(x) = (x^2 + 1)^{0.5} - 1$.
Show algebraically that $f(x) = \frac{x^2}{(x^2 + 1)^{0.5} + 1}$.
Can someone help me solve this part of an exam question?
It may seem easy but I'm not sure how to start.
Thanks

A: Hint 1: $(\sqrt a - \sqrt b)(\sqrt a + \sqrt b) = a - b \,$.
Hint 2: Your $f(z)$ can be written as $(\sqrt a - \sqrt b) \,$.

A: A little extra hint: If f(x)=first expression and f(x)= second expression then the first expression = second expression and combine that with the first answer.

A: Multiply $f(x)$ by $\frac{(x^2+1)^{0.5}+1}{(x^2+1)^{0.5}+1}$.


text:
Q: Securing the archipelago before expanding the radar in Boom Beach I'm no longer expanding the radar in Boom Beach but only defending the archipelago. Is it possible to secure the area to the point where one is no longer attacked before expanding to new areas?

A: It is possible to clear out the entire area of NPC and player bases, but it is extremely difficult because it will often place higher level players in your viewable area and because the fewer attacks there are in your range, the faster new attacks show up. Personally, I quickly found it was too difficult to clear out the entire area and maintain it like that before expanding, because I would often try to replace a high level opponent only to have it replaced by another high level opponent that I was unable to defeat.

A: If you ever did secure all the bases, when you came back the next day, there would be more bases. Besides, what's the point.


text:
Q: django prefetch_related many queries Django 1.7
I have a model:
   class Model(models.Model):
       tags = models.ManyToManyField(..)

When I do Model.objects.prefetch_related().... it results in many individual queries being issued to fetch the tags, one for each model.
I'd expect 2 queries to happen: 1 to fetch the models, another to fetch the tags for all models.
How to do that?
EDITED:
I'm using a raw query like Model.objects.prefetch_related('tags').raw_query(..)

A: You should specify a field name to prefetch:
Model.objects.prefetch_related('tags')

If you use the queryset.raw() method then prefetch_related() logic doesn't work.


text:
Q: How to run a PyPi package command on Python I want to use the twitch-dl package from PyPi. After installing it, the idea is to basically run it on the terminal like this:
twitch-dl download <twitch-vod-url>

And it works well when running on the terminal but my goal is to run this command inside my Python script:
os.system('twitch-dl download <twitch-vod-url>`')

All I get is 256 as my output when I run this code. It does not download anything.


text:
Q: Django autocomplete light, taggit and the admin interface I'm trying to use autocomplete_light and taggit both on an admin form.
I've read the docs on integrating autocomplete light and taggit here,
and the docs on integrating autocomplete light in the admin here. But there seems to be little (or no) discussion on doing both at the same time.
what I've got so far.
In models.py:
from django.db import models
from taggit.managers import TaggableManager
from taggit.models import TagBase, GenericTaggedItemBase

class MyTag(TagBase):
    description = models.CharField(max_length = 250, blank = True, null = True)

class MyTagThroughModel(GenericTaggedItemBase):
    tag = models.ForeignKey(MyTag, related_name = "tagged_items")

class MyModel(models.Model):
    Name = models.CharField(max_length = 200)
    ...
    tags = TaggableManager(through = MyTagThroughModel)

In autocomplete_light_registry.py:
import autocomplete_light
from models import MyTag
autocomplete_light.register(MyTag)

How am I meant to structure admin.py?
If this was a non-admin form, the field would be given as:
tags = TagField(widget = TagWidget('MyTagAutocomplete'))

If this was a non-taggit admin form, I would add the following to the admin model class:
form = autocomplete_light.modelform_factory(MyTag)

How can I combine the two?

A:
How am I meant to structure admin.py?

Here's an example to autocomplete Tags. It shows you how autocomplete_light and taggit work on admin and non-admin forms.
models.py
from django.db import models
from taggit.managers import TaggableManager

class MyModel(models.Model):
    name = models.CharField(max_length = 200)
    tags = TaggableManager(blank=True)

autocomplete_light_registry.py
import autocomplete_light
from taggit.models import Tag

autocomplete_light.register(Tag)

forms.py
from django import forms
import autocomplete_light
from autocomplete_light.contrib import taggit_tagfield
from models import MyModel

class MyModelForm(forms.ModelForm):
    tags = taggit_tagfield.TagField(widget=taggit_tagfield.TagWidget('TagAutocomplete'))
    class Meta:
        model = MyModel
        widgets = {
            'tags': autocomplete_light.TextWidget('TagAutocomplete'),
        }

admin.py
from django.contrib import admin
import autocomplete_light
from models import MyModel
from forms import MyModelForm

class MyModelAdmin(admin.ModelAdmin):
    form = MyModelForm
    model = MyModel

admin.site.register(MyModel, MyModelAdmin)

views.py
from django.views.generic.edit import CreateView
from models import MyModel
from forms import  MyModelForm

class CreateMyModel(CreateView):
    model = MyModel
    form_class = MyModelForm

urls.py
from django.conf.urls import patterns, url
from views import CreateMyModel

urlpatterns = patterns('',
     url(r'^create/$', CreateMyModel.as_view()),
)

The quick docs seem to be more straightforward to understand than the docs you were looking at.

A: Consider using django-taggit-autosuggest instead.

It works best with the django-grapelli admin skin.


text:
Q: Removing "enter" character with batch? I use a tool called "exiftool" for reading metadata information from video file for Listing/Categorization. Exiftool output is something like this.
1920x1080
2:58:09
12421 MB

What I want is;
[1920x1080][2:58:09][12421 MB]

This is what I am trying to do for removing "enter" character;
:_Dongu2
set GELEN=%~1
set /a SAYAC2+=1
if %SAYAC2% LEQ 99 (
  if %SAYAC2% LEQ 9 (
    title Ilerleme Durumu: 00%SAYAC2% / %FSAY%
  ) else (
    title Ilerleme Durumu: 0%SAYAC2% / %FSAY%
  )
) else (
  title Ilerleme Durumu: %SAYAC2% / %FSAY%
)

setlocal DisableDelayedExpansion
set "firstLineReady="
(
    for /F "eol=$ delims=" %%a in ('exiftool -s3 -ImageSize -Duration -FileSize "%~1\%GELEN:~20,-23%.mp4"') DO (
        if defined firstLineReady (echo()
        set "firstLineReady=1"
        <nul set /p "=%%a"
    )
)>> out.txt
goto :EOF

So far I didn't work it out. I found this function from Jeb's answer on another question. This is the way I call this function
(for /f "tokens=*" %%x in (%MTEMP%) do call :_Dongu2 "%%x") && title %NAME%

and %MTEMP% file is like
Z:\Movies\000y.001y\The.Lord.of.the.Rings.The.Fellowship.of.the.Ring.(2001){0120737}[00085]
Z:\Movies\000y.001y\The.Lord.of.the.Rings.The.Return.of.the.King.(2003){0167260}[00087]
Z:\Movies\000y.001y\The.Lord.of.the.Rings.The.Two.Towers.(2002){0167261}[00086]

each movies attitude had to be on another line. out.txt had to be like;
[1920x1080][2:58:09][12421 MB][The.Lord.of.the.Rings.The.Fellowship.of.the.Ring]
[1920x1080][3:02:31][14660 MB][The.Lord.of.the.Rings.The.Return.of.the.King]
.
.
.

A: Here's a batch solution:
@echo off
<"file.txt" (
set /p a=
set /p b=
set /p c=
)
echo [%a%][%b%][%c%]

Output:
[1920x1080][2:58:09][12421 MB]

A: Directly ask exiftool to produce the required output
exiftool -p [${ImageSize}][${Duration}][${FileSize}] videoFile.mp4


text:
Q: Android: Display two ListViews via Fragments using Fragmenttransaction For my app, I'm trying to show a list, and as soon as this list ends, the second one shall begin. The Lists are being displayed using a ListAdapter, which again is part of a fragment. Everything works very well, the lists appear correctly, but I can't figure out a way to put one list under the other. I thought this shouldn't be all too hard.
Summary:
What I have:
A FragmentPagerAdapter with 3 Fragments
Two Fragments, which contain one ListView each
My searches:
Apart from multiple searches on this site, this guy came closest to what I'm seeking:
This guy here Fragmenttransaction in 1 tab of a Fragmentpageradapterhas had the same problem, but it wasn't satisfyingly answered, so I thought I can make a valid question here.
My question:
How can I place two ListViews in one Fragment? The big deal is that for example if the first ListView is bigger than the screen, I don't want the second ListView to show up before the first is completely scrolled down.
Current output:
Currently, both ListViews are in the same position, meaning that one ListView is on top of the other, making both unreadable
I thought that I can maybe use a specified layout for the FragmentTransaction. But I just can't figure out how.
This is the Fragment where I combine my top and bottom ListViews
public class LeaguePageTransactionsAdapter extends Fragment{
Global global_var;
ListView list, list_flat;
List <League> leagues = null, leaguesFlat = null;
ListAdapter adapter = null, adapter_flat = null;
View rootView;
FragmentTransaction fragmentTransaction;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    rootView = inflater.inflate(R.layout.league_page, container, false);
    fragmentTransaction = getFragmentManager().beginTransaction();
    fragmentTransaction.add(rootView.getId(), new LeaguePageTop(), "TopFragment");
    fragmentTransaction.add(rootView.getId(), new LeaguePageBottom(), "BottomFragment");
    fragmentTransaction.commit();
    return rootView;
   }

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onViewCreated(view, savedInstanceState);

}

}
This is corresponding the xml layout file.
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />

This is one of my two ListViews
public class LeaguePageTop extends Fragment{
ListView list;
List <League> leagues = null;
ListAdapter adapter = null;
View rootView;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    rootView = inflater.inflate(R.layout.league_page_top, container, false);
    return rootView;
   }

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onViewCreated(view, savedInstanceState);
    list = (ListView) rootView.findViewById(R.id.listView1);

    try {
        leagues = Leagues_Parser.parse(getActivity().getAssets().open("league_raw.xml"), 0);

    } catch (IOException e) {
        e.printStackTrace();
    }
    adapter = new LeagueAdapter (getActivity(), R.layout.list_row, leagues);

    list.setAdapter(adapter);

    list.setOnItemClickListener(new OnItemClickListener()
       {

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                long arg3) {
            // TODO Auto-generated method stub
            Global.mViewPager.setCurrentItem(1, true);
        }
       });
}

}
This is the corresponding xml file
    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <ListView
        android:id="@+id/listView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
    </ListView>
</LinearLayout>

Thank you very much for reading and thinking about it!

A: The reason is because you have set the LinearLayout in the XML file you have shown to match_parent which will occupy all available space and then comes your next ListView with it's own LinearLayout (which I presume is set to match_parent as well) and hence there is no space for it to display. FrameLayout and LinearLayout follows an eldest child first approach meaning that the first layout occupies as much space as it requests. Set the LinearLayout you have to wrap_content and I think that should solve your fragment.

A: Firstly use a view filpper.you can load your first list view in fragment and in your adapterview on item click listener you can flip view by flipper.setdisplayedchild(1) which will show your desired second list.


text:
Q: symfony3 REST API issue with yml routing using FOSRestBundle I've finally got my first API in Symfony3 which is actually working.
Very well so far but problems came when I tried using YML configs for routing instead of annotation. It is driving me crazy because it seems to work, in fact when I chance for eg the controller name, it gives me an internal server error but, when everything is "correct", it seems it's unable to find the method in my controller.
So here is my code:
General routing settings
#config/routing.yml
user_routes:
    resource: "@AppBundle/Resources/config/user_routes.yml"
    type: rest

Bundle routing settings
#AppBundle/Resources/config/user_routes.yml
user:
    type: rest
    resource: AppBundle\Controller\UserController

And finally my controller:
   <?php

    namespace AppBundle\Controller;

    use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
    use Symfony\Bundle\FrameworkBundle\Controller\Controller;
    use FOS\RestBundle\Controller\Annotations as Rest;
    use FOS\RestBundle\Controller\FOSRestController;
    use Symfony\Component\HttpFoundation\Request;
    use Symfony\Component\HttpFoundation\Response;
    use FOS\RestBundle\View\View;
    use AppBundle\Entity\User;

    class UserController extends FOSRestController
    {

    //    /**
    //     * @Rest\Get("/user")
    //     */
        public function getAction()
        {
            $restresult = $this->getDoctrine()->getRepository('AppBundle:User')->findAll();
            if ($restresult === null) {
                return new View("there are no users exist", Response::HTTP_NOT_FOUND);
            }

            return $restresult;
        }
}

Using annotation it works well and everybody's happy but when I use these settings I get a 404. I tried adding prefix: /api and name_prefix:  api_ according to Symfony official documentation but it didn't work.
I tried also adding a defaults: { _controller: AppBundle:Controller:UserController:get but error 404 was always round the corner.
As I said, if I change the name of the controller class in the user_routes.yml, I get a 500 error so it seems the routing is being read but it's evident that something is missing here and I'm unable to find it neither on the official documentation nor in other places.

A: Change the name of the action from this:
public function getAction()

to this:
public function getUsersAction()

DOCUMENTATION

A: Well, just in case it may become useful for someone, I found the solution.
The problem lay in the yml user_routes.yml.
Here is the correct configuration:
path: /user
defaults: { _controller: AppBundle:User:get }
requirements:
    _method: GET

That's it ;)


text:
Q: make root beer in the toilet From the movie Jurassic World (2015).
Two boys wandered off into a restricted area for tourists to take a closer look at other dinosaur species that live in the park. While they're out there, their aunt, who's the president of the park, is ringing alarm bells at the control room to find them. Here's the two boys' short conversation:

— Great idea.
  — No! We're gonna get arrested. They'll shave our heads, and we're
  gonna have to make root beer in the toilet.
  — What are you talking about?

What's that he saying about making root beer in the toilet? I don't understand.

A: Prisoners in the United States are, not surprisingly, prohibited alcohol.  Prisoners are an enterprising lot, and they have found a great many ways to get around that prohibition, most notably via pruno, a homemade wine made by mixing anything fermentable (sugar, fruit, bread, ketchup) in a plastic bag and waiting a few days.  The resulting alcoholic beverage is often hidden in the toilet.
In the movie, the boy who is worried says that he'll have to make root beer, a traditional (occasionally homemade) soda, in the toilet after he is arrested.


text:
Q: Redux fetch actions I create app with react and redux and I need to fetch data. Is there any way to reuse function getData() and reducer. My actions looks like this
importing constants

const getDataRequested = () => {
  return {
    type: GET_DATA_REQUESTED
  };
}

const getDataDone = data => {
  return {
    type: GET_DATA_DONE,
    payload: data
  };
}

const getDataFailed = () => {
  return {
    type: GET_DATA_FAILED
  };
}

export const getData = () => dispatch => {

  dispatch(getDataRequested());

  fetch('url')
    .then(response => response.json())
    .then(data => {
      dispatch(getDataDone(data));
    })
    .catch(error => {
      dispatch(getDataFailed(error));
    })
}

and reducer
importing constants

const initialState = {
  isLoading: false,
  isError: false,
  data: [],
}
export default (state=initialState, action) => {
  switch (action.type) {
    case GET_DATA_REQUESTED:
      return { ...state, isLoading: true };
    case GET_DATA_DONE:
      return { ...state, isLoading: false, data: action.payload };
    case GET_DATA_FAILED:
      return { ...state, isLoading: false, isError: true}
    default:
      return state;
  }
};

Every time I fetch something with different url I create new action and new reducer. Is it ok or there is some way to reuse it?

A: You can pass a url parameter to your thunk. So, you could have something like this:
export const getData = (url) => dispatch => {

    dispatch(getDataRequested());

    fetch(url)
        .then(response => response.json())
        .then(data => {
            dispatch(getDataDone(data));
        })
        .catch(error => {
            dispatch(getDataFailed(error));
        })
}

This way you can dispatch as many actions as you want changing only the url parameter, like this: getData('/user'), getData('/products').
You can also customize the way you store the state into redux by passing more parameters to the thunk. So it could be something like this:
const getDataDone = data => {
    return {
        type: GET_DATA_DONE,
        payload: data
    };
}

export const getData = (url, stateName) => dispatch => {
    dispatch(getDataRequested());

    fetch(url)
        .then(response => response.json())
        .then(data => {
            dispatch(getDataDone({ stateName: data }));
        })
        .catch(error => {
            dispatch(getDataFailed(error));
        })
}

And the reducer could be something like this:
const initialState = {
    isLoading: false,
    isError: false,
    data: {},
}
export default (state=initialState, action) => {
    switch (action.type) {
        case GET_DATA_REQUESTED:
            return { ...state, isLoading: true };
        case GET_DATA_DONE:
            return { ...state, isLoading: false, [action.payload.stateName]: action.payload.data };
        case GET_DATA_FAILED:
            return { ...state, isLoading: false, isError: true}
        default:
            return state;
    }
};

That way you can dispatch actions like getData('/user', 'user') or getData('/products', 'products') and have a state like this:
{
    user: {
        // your users data
    },
    products: {
        // your products data
    }
}

A: You can combine all actions in one function like
function getData() {
  return {
    types: [GET_DATA_REQUESTED, GET_DATA_DONE, GET_DATA_FAILED],
    callApi: fetch('/')
  }
}

but you need to connect your component and pass the function as props
function mapDispatchToProps(dispatch) {
   return {
    getData: () => dispatch(getData())
   };
}

connect(null, mapDispatchToProps)(YourComponent)

now you can use the function in your component and it will return a promise.
check out the Docs for redux: https://github.com/reactjs/react-redux


text:
Q: I'm getting InvalidCastException while actually casting nothing AutoResetEvent receiver = new AutoResetEvent(false);
Thread t = null;
            t = new Thread(new ThreadStart(() =>
            {

                while (Browser.ReadyState != WebBrowserReadyState.Complete) // error
                {
                    Thread.Sleep(10);
                }
                receiver.Set();
                t.Abort();
            }));
            t.Start();

            // Timeout
            success = receiver.WaitOne(10000);

Browser is
public WebBrowser Browser { get; set; }

I don't really understand why I get such error. The Browser.ReadyState is a enum type WebBrowserReadyState
So what do you think?
EDIT:
First:

Second:


text:
Q: Backup/archive Messages in iCloud I want a complete local backup of all my iMessages. There are several apps that allow you to backup iMessages, but only what already exists on a device, which is only be a subset of the complete set stored in iCloud. Neither iCloud backups nor computer backups include iMessages from iCloud.
I have 16GB of messages according to iCloud, but my phone only reports 8GB. Is there a way to force my phone or (ideally) Mac to download the entire message history, so it can be archived?

A: Unfortunately, the only way I know of to force older messages to download to the iPhone from iCloud for Messages (iCloud Messages syncing) is to scroll up in the conversations you want to download on the Messages app. With a conversation open in the Messages app, tapping the time/battery status bar at the top will scroll a big jump up - that at least makes the scrolling go a little quicker.
I would love to know a better way, so I hope someone else has a better answer!


text:
Q: How do I print a .bmp image multiple times? I'm working on an assembly project for class and I have some code. My problem is that I have errors because the code is not designed to print the same .bmp image multiple times.
What I need is some code that I can use so I can print my .bmp image multiple times. Any advice will be very helpful. Thanks!
I've tried some other code for printing .bmp files in assembly but wasn't successful.
If you have some sort of code for printing .bmp files, it will be very useful.
CODE:
IDEAL
MODEL small
STACK 100h
DATASEG
;================================
filename db 'test.bmp',0

filehandle dw ?

Header db 54 dup (0)

Palette db 256*4 dup (0)

ScrLine db 320 dup (0)

ErrorMsg db 'Error', 13, 10,'$'
;================================
CODESEG
;================================
proc OpenFile

    ; Open file

    mov ah, 3Dh
    xor al, al
    mov dx, offset filename
    int 21h

    jc openerror
    mov [filehandle], ax
    ret

    openerror:
    mov dx, offset ErrorMsg
    mov ah, 9h
    int 21h
    ret
endp OpenFile
proc ReadHeader

    ; Read BMP file header, 54 bytes

    mov ah,3fh
    mov bx, [filehandle]
    mov cx,54
    mov dx,offset Header
    int 21h
    ret
    endp ReadHeader
    proc ReadPalette

    ; Read BMP file color palette, 256 colors * 4 bytes (400h)

    mov ah,3fh
    mov cx,400h
    mov dx,offset Palette
    int 21h
    ret
endp ReadPalette
proc CopyPal

    ; Copy the colors palette to the video memory
    ; The number of the first color should be sent to port 3C8h
    ; The palette is sent to port 3C9h

    mov si,offset Palette
    mov cx,256
    mov dx,3C8h
    mov al,0

    ; Copy starting color to port 3C8h

    out dx,al

    ; Copy palette itself to port 3C9h

    inc dx
    PalLoop:

    ; Note: Colors in a BMP file are saved as BGR values rather than RGB.

    mov al,[si+2] ; Get red value.
    shr al,2 ; Max. is 255, but video palette maximal

    ; value is 63. Therefore dividing by 4.

    out dx,al ; Send it.
    mov al,[si+1] ; Get green value.
    shr al,2
    out dx,al ; Send it.
    mov al,[si] ; Get blue value.
    shr al,2
    out dx,al ; Send it.
    add si,4 ; Point to next color.

    ; (There is a null chr. after every color.)

    loop PalLoop
    ret
endp CopyPal

proc CopyBitmap

    ; BMP graphics are saved upside-down.
    ; Read the graphic line by line (200 lines in VGA format),
    ; displaying the lines from bottom to top.

    mov ax, 0A000h
    mov es, ax
    mov cx,200
    PrintBMPLoop:
    push cx

    ; di = cx*320, point to the correct screen line

    mov di,cx
    shl cx,6
    shl di,8
    add di,cx

    ; Read one line

    mov ah,3fh
    mov cx,320
    mov dx,offset ScrLine
    int 21h

    ; Copy one line into video memory

    cld

    ; Clear direction flag, for movsb

    mov cx,320
    mov si,offset ScrLine
    rep movsb

    ; Copy line to the screen
    ;rep movsb is same as the following code:
    ;mov es:di, ds:si
    ;inc si
    ;inc di
    ;dec cx
    ;loop until cx=0

    pop cx
    loop PrintBMPLoop
    ret
endp CopyBitmap
;================================
start:
mov ax, @data
mov ds, ax
;================================

    ; Graphic mode
    mov ax, 13h
    int 10h

    ; Process BMP file
    call OpenFile
    call ReadHeader
    call ReadPalette
    call CopyPal
    call CopyBitmap

    ; Wait for key press
    mov ah,1

    int 21h
    ; Back to text mode
    mov ah, 0
    mov al, 2
    int 10h
;================================
exit:
    mov ax, 4c00h
    int 21h
    END start

It's my first time using this website, so I'm not sure how things work here, but I can upload my project if needed.

A: Repeating is simply a matter of closing the file and then looping back in the program. To close the file you use DOS function 3Eh
proc CloseFile
  mov  ah, 3Eh
  mov  bx, [filehandle]
  int  21h
  ret
endp CloseFile

  mov  ax, 0013h       ;Graphic mode
  int  10h
Again:
  call OpenFile
  call ReadHeader
  call ReadPalette
  call CopyPal
  call CopyBitmap
  call CloseFile
  mov  ah, 01h         ;Key
  int  21h
  cmp  al, 27
  jne  Again           ;Loop until users presses <ESC>
  mov ax, 0003h        ;Text mode
  int 10h
exit:
  mov ax, 4C00h
  int 21h


text:
Q: The content of my tabs doesn't fill the whole space In my activity I create 5 tabs dynamically.
I'm trying to figure out why my loading animation doesn't fill the whole space. Right now it's only a small rectangle in the top of the tab content (see http://imageshack.us/photo/my-images/594/loadingwf.png/).
Here is the code where I create the content of each tab :
for (int i = 0; i < NewsCategory.values().length; i++) {
    View tabView = createTabView(tabHost.getContext(), NewsCategory.getValueAt(i).getName());

    tabNewslist[i] = new Newslist(this, NewsCategory.getValueAt(i));
    getLayoutInflater().inflate(R.layout.loading_anim, tabHost.getTabContentView(), true);
    tabHost.addTab(tabHost.newTabSpec(NewsCategory.getValueAt(i).getName()).setIndicator(tabView).setContent(R.id.loadingAnim));
}

And here is the XML file of the animation :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/loadingAnim"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#FFFFFF"
    android:gravity="center_horizontal"
    android:orientation="horizontal"
    android:padding="5dp" >

    <ProgressBar
        android:id="@+id/progressBar"
        style="?android:attr/progressBarStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:text="@string/loading" />

</LinearLayout>

A: I think this part of code is correct.
What do you have in your activity xml?


text:
Q: donot understand class not found exception I am creating a login page for a Library Management System.In the below piece of code i am getting a class not found exception.But i donot understand which class is it talking about and why is this exception taking place.Moreover the HomeStudent class is already defined and all the classes in the same folder in the workspace.
import java.awt.Button;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.Label;
import java.awt.Panel;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class MainClass extends Frame implements ActionListener {
    static MainClass instance ;
    Panel p = new Panel(new FlowLayout());
    Label uname = new Label("UserName");
    Label pass = new Label("Password");
    TextField tuname = new TextField(10);
    TextField tpass = new TextField(10);
    Button login = new Button("GO");
    public MainClass()
    {
        p.add(uname);
        p.add(tuname);
        p.add(pass);
        p.add(tpass);
        p.add(login);
        login.addActionListener(this);
    }
    public static void main(String[] args)
    {
         instance = new MainClass();
         instance.setVisible(true);
         instance.setSize(new Dimension(100,100));
    }

    @Override
    public void actionPerformed(ActionEvent arg0) {
        // TODO Auto-generated method stub
        //DataBase Part
        //Presently Done Simply
        //Simple If Else
        //Onlu Used for Prototyping
        if(tuname.getText().equals("user")&&(tpass.getText().equals("user")))
        {
            HomeStudent home = new HomeStudent();
            instance.setVisible(false);
            home.setVisible(true);
            home.setSize(new Dimension(100,100));
        }
    }
}

Below is the stack trace.
load: class .class not found.
java.lang.ClassNotFoundException: .class
    at sun.applet.AppletClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.applet.AppletClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.applet.AppletClassLoader.loadCode(Unknown Source)
    at sun.applet.AppletPanel.createApplet(Unknown Source)
    at sun.applet.AppletPanel.runLoader(Unknown Source)
    at sun.applet.AppletPanel.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)

A: It's talking about your main method.
public static void main(String args)

the String parameter MUST be a String array of args. It is what the main must take, and it is not, so that is where your error is. Just change to
public static void main(String[] args)

and you should be all set.
Hope that helps!


text:
Q: Unrecognised selector sent to instance by NSNotificationCenter When i want to update a label via NSNotificationCenter is get an Runtime error but i don't know why. Slectors are named same.
ViewController2
@IBAction func saveSettings(sender: UIButton) {
    NSNotificationCenter.defaultCenter().postNotificationName("TimeRepairID", object: nil)
}

ViewController
    override func viewDidLoad() {
    super.viewDidLoad()
    NSNotificationCenter.defaultCenter().addObserver(self, selector: "setTimeRepair", name: "TimeRepairID", object: nil)
}

func setTimeRepair(notification: NSNotification){
    CurrentTimerepair.text = String(format:"%.1f", RepairTime.sharedInstance.TimeOfRepair())
    RFPTime.text = String(RepairTime.sharedInstance.ReadyForPickup())
}

so every time i press the save button in ViewController2 the app crashes with unrecognised selector sent to instance 0x13e63bd40 know any

A: You misses : after selector name as you are passing NSNotification as argument.
override func viewDidLoad() {
    super.viewDidLoad()
    NSNotificationCenter.defaultCenter().addObserver(self, selector: "setTimeRepair:", name: "TimeRepairID", object: nil)
}

func setTimeRepair(notification: NSNotification){
    CurrentTimerepair.text = String(format:"%.1f", RepairTime.sharedInstance.TimeOfRepair())
    RFPTime.text = String(RepairTime.sharedInstance.ReadyForPickup())
}


text:
Q: what is the equation of a rotated ellipsoid? I used this equation for rotated 2D ellipse:
$$\frac{(x\cos\theta+y\sin\theta)^2}{a^2} +\frac{(x\sin\theta-y\cos\theta)^2}{b^2} =1$$
$a$, $b$ are major-axis and minor-axes length of the ellipse and $\theta$ is the rotation angle.
what is this kind of equation for the rotated ellipsoid in 3D?
we have $a$, $b$ and $c$ that are 3 axes length of ellipsoid and $\theta , \phi$ which are rotation angle in horizontal plane and vertical plane respectively. Can anyone help me please?
Thank you in advance.

A: The equation of unrotated the ellipsoid in 3D is $$\frac{x^2}{a^2}+\frac{y^2}{b^2}+\frac{z^2}{c^2}=1$$
Write the rotation matrices (you can look it up on wikipedia). You have $(x',y',z')^T=R(\theta,\phi)\cdot(x,y,z)^T$ This yield each of $x',y',z'$ as linear combinations of $x,y,z$. Now just plug in $x',y',z'$ instead of $x,y,z$ in the first equation, and you are done.


text:
Q: WebSphere JAX-WS Cross-Cell authentication We want to build a front-end web application to consume the WPS' HumanTask API using JAX-WS. This web application should be able to query current tasks for a specific user, claim tasks not claimed previously by any other user, complete tasks and so on. This web application will be deployed on a WAS 7.0 on a different cell than the one providing the HumanTask service (Currently we are using another WPS instance as the WAS but eventually it will be a simple WAS without WPS features). We synchronized LTPA generation keys by means of following steps:

*

*Login to one cell

*Go to "Security" > "Global Security". Under "Authentication" click on "LTPA"

*Under "Cross-cell single sign on"

*

*Establish a password

*Confirm the password

*Input the file name into which the LTPA keys will be exported

*Click on "Export keys"

*Log out

*Copy the generated file to the other server

*Login to the other cell

*Go to "Security" > "Global Security". Under "Authentication" click on "LTPA"

*Under "Cross-cell single sign on"

*

*Input previous password

*Confirm password

*Input the file name with the exported LTPA keys

*Click on "Import keys"

*Restart server

We developed a simple web application with GWT as a proof of concept with a simple UI and a web service client which consumes the HumanTask JAX-WS service. This web application is protected behind a Siteminder authenticator (when first entering web application Siteminder agent redirects to a web form asking for credentials). Web service client has been developed following JAX-WS standards, no additional dependencies have been added, we rely on WebSphere JAX-WS implementation (Apache Axis2). Once deployed we tested two scenarios without luck:
Scenario A:

*

*By default WPS' HumanTask service provider is attached to policy set "BPC Web Service" with default policy set binding and policy set sharing disabled.

*We configure our HumanTask service client to use same policy set as service provider.

*Log in to custom web application. When trying to query current tasks we get following exception:
com.ibm.wsspi.wssecurity.core.SoapSecurityException: security.wssecurity.WSSContextImpl.s02: com.ibm.websphere.security.WSSecurityException: Exception org.apache.axis2.AxisFault: CWWSS6521E: The Login failed because of an exception: javax.security.auth.login.LoginException: Login Failure: all modules ignored ocurred while running action: com.ibm.ws.wssecurity.handler.WSSecurityGeneratorHandler$2@6fef6fef

No error message at service provider side.
Scenario B:

*

*Change WPS' HumanTask service provider configuration enabling policy set sharing through HTTP GET. This way service provider WSDL contains information about the policy set.

*Change policy set configuration at service client to obtain policy set from provider using HTTP GET.

*Log in to custom web application. When trying to query current tasks we get following exception:
javax.xml.ws.soap.SOAPFaultException: security.wssecurity.WSSContextImpl.s02: com.ibm.websphere.security.WSSecurityException: Exception org.apache.axis2.AxisFault: CWWSS6521E: The Login failed because of an exception: javax.security.auth.login.LoginException: Login module com.ibm.ws.wssecurity.wssapi.token.impl.UNTConsumeLoginModule login() method returned false ocurred while running action: com.ibm.ws.wssecurity.handler.WSSecurityConsumerHandler$1@54a054a0

Before reaching the point where previous exception is reported we see following warning at service client logs:
CWWSS7053W: No web services security custom bindings were found. Default bindings will be used.

At service provider logs we can see following error:
CWWSS5514E: An exception while processing WS-Security message.

And a set of FFDCs are generated reporting the same exception we got at service client side.
Someone who could help us would be great!

A: We had the same problem but managed to solve it via the following steps. Essentially, you need to change the default policy set applied to the HTM JAXWS API (the default is really just an example) and use a custom provider binding which is able to extract the identity contained within the LTPA token via a "Caller". Steps below:
Create Custom Policy Set Bindings
1) Click "Services" > "Policy Sets" > "General provider policy set bindings"
2) Select the "Provider sample" binding and click "Copy..."
3) Enter the name as "LTPA Authenticated Caller" and click OK
4) Click on "LTPA Authenticated Caller" in the list of bindings
5) Click on "WS-Security", then "Caller"
6) Click "New" and enter the following details (leave other fields blank)
Name: auth_ltpa
Caller identity local part: LTPAv2
Caller identity namespace URI: http://www.ibm.com/websphere/appserver/tokentype
Click OK
Assign Policy Set and Bindings
1) Expand "Services", click "Service providers"
2) Click on "HTMJAXWSService"
3) Click the checkbox to select the HTMJAXWSService Service in the Policy Set Attachments list, then click on "LTPA WSSecurity default" in the Attach Policy Set drop down list
4) Click the checkbox to select the HTMJAXWSService Service in the Policy Set Attachments list, then click on "LTPA Authenticated Caller" in the Assign Binding drop down list
5) Save all changes to the master configuration.
Assign Policy Set and Bindings
1) Expand "Services", click "Service clients"
2) Click on the "HTMJAXWSService" link where the "Deployed asset" column matches the module containing the client you wish to configure
3) Click the checkbox to select the HTMJAXWSService Service in the Policy Set Attachments list, then click on "LTPA WSSecurity default" in the Attach Policy Set drop down list. Ensure that this setting is inherited by all child levels (i.e. the port, and all methods)
4) Click the checkbox to select the HTMJAXWSService Service in the Policy Set Attachments list, then click on "Default" in the Assign Binding drop down list
5) Save all changes to the master configuration
Conclusion
It should now be possible to call from your client through to the HTM API using LTPA authentication. In order to do this, your client application will need to be configured to either require authentication or provide authentication for unauthenticated URLs (the latter would be appropriate for applications which are expecting the SiteMinder TAI to pre-populate an authenticated user identity).
Hope this helps!


text:
Q: transferring grooving script result into test cases I am fetching data from one tag lets say 111 22222 and splitting by using space
like 111 and 22222.
I want to transfer the value to two different tags into different request
lets say
111 for Tag1 and 22222 for Tag2

A: if you have the two different values assigned to variables already you can do something like the following
def groovyUtils = new com.eviware.soapui.support.GroovyUtils(context)

//get field value from first test step response
def tagOne = 111
def tagTwo = 22222

//Define request you would like to add data to
def holderRequestOne = groovyUtils.getXmlHolder("RequestOneName#Request")
def holderRequestTwo = groovyUtils.getXmlHolder("RequestTwoame#Request")

//Find the fields in the request and set the value you would like in those fields
holderRequestOne.setNodeValue("//XPath","$tagOne")
holderRequestTwo.setNodeValue("//XPath","$tagTwo")

//Update the requests
holderRequestOne.updateProperty()
holderRequestTwo.updateProperty()

This is the way I would do it using Groovy scripts. you just need to add the respected XPaths and Test Step names.
You can also do this using the property transfer test step. Which you can find more information here:
https://www.soapui.org/docs/functional-testing/properties/transferring-properties.html
A little more information on you problem, the code you have tried and you expected outcome of that code wouldn't go amiss

A: @Tanveer as per your comment on Ross's Answer here is the solution
you have fetch Response as 111 222
log.info Response  // 111 222
String [] s = s.split(" ")
log.info s[0] //111
log.info s[1] //222

Save the value in testCase Properties in groovy script
 testRunner.testCase.setPropertyValue("tagone",s[0])
 testRunner.testCase.setPropertyValue("tagtwo",s[1])

In another testStep request where you want to use this
<xmltag1>${#TestCase#tagone}</xmltag1>
<xmltag1>${#TestCase#tagtwo}</xmltag1>

So we stored property at TestCase level and used it in another step of the same Testcase
If you want the property to be used in another test case you may store at TestSuite Level
 testRunner.testCase.testSuite.setPropertyValue("tagone",s[0])


text:
Q: Constant table creating doesn't kill memory My Lua program starts by declaring a multidim table:
function love.load()

-- változók deklarálása

Maximum_X = 32                  -- a teljes játéktér mérete
Maximum_Y = 16

i = 0                           -- ciklusváltozók
j = 0

-- játéktér létrehozása

MapTable = {}

for y = 1,Maximum_Y do

    local row = {}

    for x = 1,Maximum_X do

        row[x] = 2          -- table.insert helyett
    end

    MapTable[y] = row       -- table.insert helyett
end

end

And then, for an experiment, I do the element declaration for every possible frame.
function love.update(dt)

    for y = 1,Maximum_Y do

        local row = {}

        for x = 1,Maximum_X do

            row[x] = 2
        end

        MapTable[y] = row
    end

end

Theoretically, it creates 16 row = {} empty tables and uploads them with values in every frame, which means creating and uploading hundreds of new tables in each seconds. And there's even more operations and uploaded tables!
However, I couldn't see any increasing neither in RAM usage nor processor usage. What's the reason? Isn't

A: The answer have come from Mud:

You should see minor blips in both CPU and memory. Lua's memory consumption will vacillate up and down as garbage (memory taken up by dead, inaccessible objects) accumulates and is then collected. But you shouldn't see that much here; you're not pushing it at all. Imagine how many tables are created per frame in in World of Warcaft client with 50 addons running during a 40 man raid fight...


text:
Q: IE7/8 and the Goldilocks Approach (responsive webdesign) aren't working together ... to be more precise: the browsers don't work with the Goldilocks I tweaked a little ... :/
The Goldilocks Approach > goldilocksapproach.com
My site (in progress) > amordetango.nl/txp/test
It has to be a minor thing but I'm glossing over it ...

A: It's only because media queries are not supported by IE <= 8


text:
Q: joining two tables and overwriting one colum I am trying to join to tables as image attached shows,
table 1 will have exactly the same records as table 2 except one field with is not equal
I would like to merge them so i will have the extended table :

*

*have all records from table2, if we ignore isempty field, table 1 is always in table2

*when table1.isEmpty=1 , the merged result will have isempty=1, and that record will be overwritten
check attached images for more details

the table 3 as shown, will have all the records from table 2 but overwritten when necessary

A: SELECT A.ID, A.NAME, A.DESC, CASE B.ISEMPTY
                WHEN 1 THEN 1
                ELSE A.ISEMPTY
                END CASE AS ISEMPTY
FROM TABLE2 A
LEFT JOIN TABLE1 B ON A.ID=B.ID

A: Having trouble understanding your data. Do you want something like this?
select table1.id, table1.name, (table1.isEmpty or table2.isEmpty) as isEmpty
from table1 inner join table2 on table1.id = table2.id


text:
Q: Merging Pandas Dataframes on Multiple Conditions I am trying to merge Frame A to Frame B on the size asset life conditions specified in Frame B using pandas. I have tried both the merge and mergeasof commands but have not found a solution.
Frame A:

ID
Material
Size

0
A
9

1
B
21

2
B
14

Frame B: note (size specifies asset life)

Material
Size < 10
10 < Size < 20
Size > 20

A
5
10
20

B
1
5
10

To form Frame C:

ID
Material
Asset Life

0
A
5

1
B
10

2
B
5

A: The the first step is to normalize DataFrame B and end up with the following:
Material,LoweBound,UpperBound,AssetLife
A,0,10,5
A,10,20,10
A,20,np.Inf,20
B,0,10,1
B,10,20,5
B,20,np.Inf,10

Now a simple join should do the trick.

A: # step1: set_index('Material') and stack frameB
dfB.columns = ['Material', 'Size <= 10', '10 < Size <= 20', 'Size > 20']
obj_size_map = dfB.set_index('Material').stack()

# print(obj_size_map)
# Material
# A         Size <= 10          5
#           10 < Size <= 20    10
#           Size > 20          20
# B         Size <= 10          1
#           10 < Size <= 20     5
#           Size > 20          10
# dtype: int64

# step2. use pd.cut to create a size_tag for frame A, with frameB's columns as labels
dfA['size_tag'] = pd.cut(dfA.Size, bins=[-np.inf, 10, 20, np.inf], labels=dfB.columns[1:])

# print(dfA)
#   ID Material  Size        size_tag
# 0   0        A     9       Size <= 10
# 1   1        B    21        Size > 20
# 2   2        B    14  10 < Size <= 20

# step3. use pandas DF's index to assign a new columns
dfC = dfA.set_index(['Material', 'tag'])
dfC['Asset Life'] = obj_size_map

# print(dfC)
#                           ID  Size         size_tag  Asset Life
# Material tag
# A        Size <= 10        0     9       Size <= 10           5
# B        Size > 20         1    21        Size > 20          10
#          10 < Size <= 20   2    14  10 < Size <= 20           5

# step4. output
result = dfC.reset_index()[['ID', 'Material', 'Asset Life']]

# print(result)
#    ID Material  Asset Life
# 0   0        A           5
# 1   1        B          10
# 2   2        B           5


text:
Q: alternative to visual studio 2010 Is there any alternative to visual studio 2010 for develop with .net 4.0?
thanks

A: You can use SharpDevelop to develop .NET projects, including .NET version 4.0. SharpDevelop 4.0 final has been released 06/2011. (though the support for 4.0 is still in beta status AFAIK.)

A: Notepad and .net 4.0 compiler :-)

A: MonoDevelop is really catching up. It is not a 100% replacement of VS, because it is based on Mono. The IDE is starting to be really good (GUI designer, debugger, test framework, web and IPhone stuff etc. etc.). Supports .NET 3.5 for now.

A: Considering that .NET 4.0 only just came out (at the same time as VS 2010) I would hazard a guess at "No". :)
In general, Visual Studio is by far the best IDE I've ever used. Nothing else even comes close.

A: The visual studio platform crashes frequeltly, Several times a day, especially when debugging.
I use sharpdevelop when debugging. It does not have all the features of VS, but it doesn't crash.

A: If you want to do your development in the cloud, check out www.coderun.com


text:
Q: Why are my 3d shapes in OpenGL/GLFW C++ missing faces So when i make a 3d triangle it just misses faces as shown below (with quad) any shape i try misses faces and you can just see straight through, (mind this is my first time using both OpenGL and GLFW)
The shape code is from a tutorial as ive tryed many shape codes to see if that was the issue and it seems it is not.

#include <glfw3.h>
#include <stdio.h>
#include <iostream>

using namespace std;

/* Begin Void prototyping */
void error_callback(int error, const char* description);
static void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods);

int main(void)
{
    GLFWwindow* window;

    /* Initializes error call-backs */
    glfwSetErrorCallback(error_callback);

    /* Initialize the library */
    if (!glfwInit())
        return -1;

    /* Create a windowed mode window and its OpenGL context */
    window = glfwCreateWindow(640, 480, "Hello World", NULL, NULL); // fullscreen glfwGetPrimaryMonitor() (first NULL)
    if (!window)
    {
        glfwTerminate();
        return -1;
    }

    /* Makes OpenGL context current */
    glfwMakeContextCurrent(window);

    /* Make the window's context current */
    glfwMakeContextCurrent(window);

    /* Receives input events */
    glfwSetKeyCallback(window, key_callback);

    /* Loop until the user closes the window */
    while (!glfwWindowShouldClose(window))
    {
        /* Render here */
        float ratio;
        int width, height;

        glfwGetFramebufferSize(window, &width, &height);
        ratio = width / (float) height;

        glViewport(0, 0, width, height);
        glClear(GL_COLOR_BUFFER_BIT);

        glMatrixMode(GL_PROJECTION);
        glLoadIdentity();
        glOrtho(-ratio, ratio, -1.f, 1.f, 1.f, -1.f);
        glMatrixMode(GL_MODELVIEW);

        glLoadIdentity();
        glRotatef((float) glfwGetTime() * 50.f, 0.f, 0.f, 1.f);

    glBegin(GL_TRIANGLES);                              // Start Drawing A Triangle
        glColor3f(1.0f,0.0f,0.0f);                      // Red
        glVertex3f( 0.0f, 1.0f, 0.0f);                  // Top Of Triangle (Front)
        glColor3f(0.0f,1.0f,0.0f);                      // Green
        glVertex3f(-1.0f,-1.0f, 1.0f);                  // Left Of Triangle (Front)
        glColor3f(0.0f,0.0f,1.0f);                      // Blue
        glVertex3f( 1.0f,-1.0f, 1.0f);                  // Right Of Triangle (Front)
        glColor3f(1.0f,0.0f,0.0f);                      // Red
        glVertex3f( 0.0f, 1.0f, 0.0f);                  // Top Of Triangle (Right)
        glColor3f(0.0f,0.0f,1.0f);                      // Blue
        glVertex3f( 1.0f,-1.0f, 1.0f);                  // Left Of Triangle (Right)
        glColor3f(0.0f,1.0f,0.0f);                      // Green
        glVertex3f( 1.0f,-1.0f, -1.0f);                 // Right Of Triangle (Right)
        glColor3f(1.0f,0.0f,0.0f);                      // Red
        glVertex3f( 0.0f, 1.0f, 0.0f);                  // Top Of Triangle (Back)
        glColor3f(0.0f,1.0f,0.0f);                      // Green
        glVertex3f( 1.0f,-1.0f, -1.0f);                 // Left Of Triangle (Back)
        glColor3f(0.0f,0.0f,1.0f);                      // Blue
        glVertex3f(-1.0f,-1.0f, -1.0f);                 // Right Of Triangle (Back)
        glColor3f(1.0f,0.0f,0.0f);                      // Red
        glVertex3f( 0.0f, 1.0f, 0.0f);                  // Top Of Triangle (Left)
        glColor3f(0.0f,0.0f,1.0f);                      // Blue
        glVertex3f(-1.0f,-1.0f,-1.0f);                  // Left Of Triangle (Left)
        glColor3f(0.0f,1.0f,0.0f);                      // Green
        glVertex3f(-1.0f,-1.0f, 1.0f);                  // Right Of Triangle (Left)
    glEnd();                                            // Done Drawing The Pyramid

        /* Swap front and back buffers */
        glfwSwapBuffers(window);

        /* Poll for and process events */
        glfwPollEvents();
    }

    glfwDestroyWindow(window);

    glfwTerminate();
    return 0;
}

/*
    Calls back the program if a GLFW function fail and logs it
*/
void error_callback(int error, const char* description)
{
    fputs(description, stderr);
}

/* Gives keys events */
static void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods)
{
    switch(key)
    {
    case GLFW_KEY_ESCAPE:
        glfwSetWindowShouldClose(window, GL_TRUE);
        break;
    case GLFW_KEY_W:
        cout << "W works!!!" << endl;
        break;
    case GLFW_KEY_A:
        cout << "A works!!!" << endl;
        break;
    case GLFW_KEY_S:
        cout << "S works!!!" << endl;
        break;
    case GLFW_KEY_D:
        cout << "D works!!!" << endl;
        break;
    }
}

Ive been trying to fix it for hours i just dont know what too do now
Im using OpenGL 3+ with GLFW and C++

A: You need to enable depth testing:
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL);

Also, be sure to clear the depth buffer in addition to the color buffer:
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);


text:
Q: Trying to populate Django app database with Faker I am trying to populate Django database with Faker.
I created a Django project (name = first_project) and then I created a Django app (name = first_app).
I created models in my app and then I created a file named 'populate_first_app.py' in my main first_project folder(the one which contains manage.py) and filled in with the following code:
import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE','first_project.settings')

import django
django.setup()

import random
from first_app.models import Topic,Webpage,AccessRecord
from faker import Faker

fakegen = Faker()
topics = ['Search','Social','Marketplace','News','Games']

def add_topic():
    t = Topic.objects.get_or_create(top_name=random.choice(topics))[0]
    t.save()
    return t

def populate(N=5):

    for entry in range(N):

        top = add_topic()
        fake_url = fakegen.url()
        fake_date = fakegen.date()
        fake_name = fakegen.company()

        webpg = Webpage.objects.get_or_create(topic=top,url=fake_url,name=fake_name)[0]

        acc_rec = AccessRecord.objects.get_or_create(name=webpg,date=fake_date)[0]

if __name__ == '__main__':
    print("populating script!")
    populate(20)
    print("populating complete!")

after making migrations and running the code, my terminal shows:
(MyDjangoEnv) E:\Django\first_project>python populate_first_app.py
populating script!
Traceback (most recent call last):
  File "populate_first_app.py", line 34, in <module>
    populate(20)
  File "populate_first_app.py", line 28, in populate
    webpg = Webpage.objects.get_or_create(topic=top,url=fake_url,name=fake_name)[0]
  File "C:\Users\vedan\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "C:\Users\vedan\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\db\models\query.py", line 573, in get_or_create
    return self.get(**kwargs), False
  File "C:\Users\vedan\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\db\models\query.py", line 418, in get
    clone = self._chain() if self.query.combinator else self.filter(*args, **kwargs)
  File "C:\Users\vedan\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\db\models\query.py", line 942, in filter
    return self._filter_or_exclude(False, *args, **kwargs)
  File "C:\Users\vedan\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\db\models\query.py", line 962, in _filter_or_exclude
    clone._filter_or_exclude_inplace(negate, *args, **kwargs)
  File "C:\Users\vedan\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\db\models\query.py", line 969, in _filter_or_exclude_inplace
    self._query.add_q(Q(*args, **kwargs))
  File "C:\Users\vedan\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\db\models\sql\query.py", line 1358, in add_q
    clause, _ = self._add_q(q_object, self.used_aliases)
  File "C:\Users\vedan\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\db\models\sql\query.py", line 1377, in _add_q
    child_clause, needed_inner = self.build_filter(
  File "C:\Users\vedan\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\db\models\sql\query.py", line 1258, in build_filter
    lookups, parts, reffed_expression = self.solve_lookup_type(arg)
  File "C:\Users\vedan\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\db\models\sql\query    _, field, _, lookup_parts = self.names_to_path(lookup_splitted, self.get_meta())
  File "C:\Users\vedan\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\db\models\sql\query.py", line 1481, in names_to_path
    raise FieldError("Cannot resolve keyword '%s' into field. "
django.core.exceptions.FieldError: Cannot resolve keyword 'topic' into field. Choices are: Topic, Topic_id, accessrecord, id, name, url

Can someone please help me?
PS: I am a newbie and this is my first question here.
THANKYOU :)

A: Use Topic instead of topic in get_or_create() method.
webpg = Webpage.objects.get_or_create(Topic=top,url=fake_url,name=fake_name)[0]


text:
Q: Puppeteer - How to browse google.com with proxies? I am trying to browse google.com with puppeteer using proxies but Chromium seems to block me.
Code example:
const puppeteer = require('puppeteer');

(async() => {
    const proxyUrl = 'http://gate.smartproxy.com:7000';
    const username = 'xxxxx';
    const password = 'xxxxx';

    const browser = await puppeteer.launch({
        args: [`--proxy-server=${proxyUrl}`],
        headless: false,
    });

    const page = await browser.newPage();

    await page.authenticate({ username, password });
    await page.goto('https://google.com/');

    const html = await page.$eval('body', e => e.innerHTML);
    console.log(html);
    await browser.close();
})();

Error:
(node:6673) UnhandledPromiseRejectionWarning: Error: net::ERR_TUNNEL_CONNECTION_FAILED at https://google.com/...

I already checked on the proxy side and they are working.
If it's not possible with puppeteer (since they are using Chromium), do you have any alternative ideas on how to browse Google with proxies?
Thanks,

A: Try replacing https with http, and consulting the proxy service and see what documents they have or what advice they can offer. Alternatively, find out what kind of proxy it is and how it normally behaves, and give us more info.

A: Try using pluginProxy:
const puppeteer = require('puppeteer-extra');
const StealthPlugin = require('puppeteer-extra-plugin-stealth')
const pluginProxy = require('puppeteer-extra-plugin-proxy');
(async() => {
  puppeteer.use(StealthPlugin()); // Recommende
  puppeteer.use(pluginProxy({
    address: <proxy-host> ,
    port: <proxy-port> ,
    credentials: {
      username: <proxy-user> ,
      password: <proxy-pwd> ,
    }
  }));
  let browser = await puppeteer.launch({
    headless: false,
    ignoreHTTPSErrors: true // Some proxies need it
  });
  let page = await browser.newPage();
  await page.goto('https://google.com/');

  const html = await page.$eval('body', e => e.innerHTML);
  console.log(html);
  await browser.close();
})();


text:
Q: In Spring application prevent H2 from transforming identifiers case to upper I'm using Spring 2.6.2 and have tried both:
testImplementation("com.h2database:h2:2.1.214")

and
testImplementation("com.h2database:h2:1.4.200")

I create database schema's using raw SQL in JDBC connections to db during app startup e.g.
CREATE SCHEMA IF NOT EXISTS "001"
CREATE SCHEMA IF NOT EXISTS "002schema"
CREATE SCHEMA IF NOT EXISTS "3_schema"

Then Liquibase performs database migration.
When run against PostgreSQL, this works fine and schemas are created using the literal String provided. Tables inside those schemas are all lowercase too, as specified in the Liquibase changelogs.
When run against H2 in unit tests, an exception is thrown when performing database migration for 002schema. It looks like Liquibase then expects all schemas to have been upper-cased causing failure.
Exception during application start-up:
Initializing Liquibase for schema 001
Creating database history table with name: "001".DATABASECHANGELOG
Liquibase ran for schema 001
..
Initializing Liquibase for schema 002schema
Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'liquibaseMultiTenant' defined in class path resource [com/company/app/data/liquibase/LiquibaseConfiguration.class]: Invocation of init method failed; nested exception is liquibase.exception.LockException: liquibase.exception.DatabaseException: Schema "002SCHEMA" not found; SQL statement:
CREATE TABLE "002SCHEMA".DATABASECHANGELOGLOCK (ID INT NOT NULL, LOCKED BOOLEAN NOT NULL, LOCKGRANTED TIMESTAMP, LOCKEDBY VARCHAR(255), CONSTRAINT PK_DATABASECHANGELOGLOCK PRIMARY KEY (ID)) [90079-214] [Failed SQL: (90079) CREATE TABLE "002SCHEMA".DATABASECHANGELOGLOCK (ID INT NOT NULL, LOCKED BOOLEAN NOT NULL, LOCKGRANTED TIMESTAMP, LOCKEDBY VARCHAR(255), CONSTRAINT PK_DATABASECHANGELOGLOCK PRIMARY KEY (ID))]

I've tried the following options in H2 URL to prevent everything being made uppercase but none are working.
Any ideas?
spring:
  datasource:
    platform: h2
    url: jdbc:h2:mem:test;MODE=PostgreSQL;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=false;DATABASE_TO_UPPER=false;
    driver-class-name: org.h2.Driver
    username: sa
    password:

Also tried:
spring:
  datasource:
    platform: h2
    url: jdbc:h2:mem:test;MODE=PostgreSQL;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=false;DATABASE_TO_LOWER=true;CASE_INSENSITIVE_IDENTIFIERS=true;
    driver-class-name: org.h2.Driver
    username: sa
    password:

A: If the name of the schema is double quoted like  "002SCHEMA" or "002schema" then it is case sensitive, it is not sensitive otherwise without the quotes:
Are PostgreSQL column names case-sensitive?
maybe you can solve the problem by changing this:
CREATE SCHEMA IF NOT EXISTS "002schema"

to this:
CREATE SCHEMA IF NOT EXISTS "002SCHEMA"

or somehow make liquibase not use quotes on schema name


text:
Q: Hide button inside Lightning Datatable based on row value I have an LWC  datatable. I am using a Apex class to get Custom data and display them using datatable.
I have delete Button for each row. I want to hide the delete button for particular Rows.
(If the Status ="Open" then we need to show the delete button)
Is there any way to achieve this?
Js:
@track studentProgram = [
{ label: "Program Name", fieldName: "Program_Name__c", initialWidth: 350 },
{ label: "Start Date", fieldName: "Program_Start_Date__c" },
{ label: "End Date", fieldName: "Program_End_Date__c" },
{
  label: "Price",
  fieldName: "Program_Price__c",
  type: "currency",
  initialWidth: 100,
  typeAttributes: { currencyCode: "USD" }
},
{label:"Status", fieldName:"Enroll_Status__c"},
{
  label: "",
  type: "button-icon",
  initialWidth: 30,
  typeAttributes: {
    iconName: "utility:delete",
    name: "delete_student_program",
    title: "Delete Student program",
    variant: "brand"
  }
}
];

HTML:
 <lightning-datatable key-field="Id" data={programData}
                                                 hide-checkbox-column="true"
                                                columns={programColumns} draft-values={draftValues}
                                                resize-column-disabled="true" onrowaction={handleAddProgram}>
                                       </lightning-datatable>

A: You shouldn't be putting a plain button in a list for that purpose. Use an action menu, and specify the actions dynamically using getRowActions, as demonstrated in the docs.
    this.columns = [
        // Other column data here
        { type: 'action', typeAttributes: { rowActions: this.getRowActions } },
    ]

...
getRowActions(row, doneCallback) {
    const actions = [];
        if (row['isActive']) {
            actions.push({
                'label': 'Deactivate',
                'iconName': 'utility:block_visitor',
                'name': 'deactivate'
            });
        } else {
            actions.push({
                'label': 'Activate',
                'iconName': 'utility:adduser',
                'name': 'activate'
            });
        }
        doneCallback(actions);
}


text:
Q: Viral growth (variable rate) I'm modeling viral growth for a product. Let's say user A brings (on average) the following number of users each day:

*

*day 1 = 0.5

*day 2 = 0.3

*day 3 = 0.4

*day 4 = 0.1

In turn, each user referred by A brings the same amount of users (i.e., 0.5, 0.3, 0.4, 0.1), but with a 1 day lag.
So, after 1 day, the number of users is just:
$0.5$
But after 2 days, the number of users is:
$0.5 + 0.3 + (0.5\times0.5)$
Because the first user that A brought, also brings users.
And after 3 days, the number of users is:
$0.5 + 0.3 + 0.4 + (0.5\times0.5) + (0.5\times0.3) + (0.3\times0.5) + (0.5\times0.5\times0.5)$
As you can see, after 3 days, the number of terms to be added is already quite big, because new users keep bringing new users.
How can I model the total number of users by the end of X days?
I found a similar question, but it's not the same, as in this question the growth is always decreasing.
Thanks a lot in advance!!!!

A: Let's say that on the $k$-th day you have the following distribution of users:
$n_k^4$ - number of users with 4 more days to bring new users
$n_k^3$ - number of users with 3 more days to bring new users
$n_k^2$ - number of users with 2 more days to bring new users
$n_k^1$ - number of users with 1 more day to bring new users
$n_k^0$ - number of users the no longer bring new users
The total number of users on the $k$-th day is $\sum_{i=0}^4n_k^i$.
On the next day:
$n_{k+1}^4 = 0.5 n_{k}^4 + 0.3 n_{k}^3 + 0.4 n_{k}^2 + 0.1 n_{k}^1$
$n_{k+1}^3 = n_{k}^4$
$n_{k+1}^2 = n_{k}^3$
$n_{k+1}^1 = n_{k}^2$
$n_{k+1}^0 = n_{k}^0 + n_{k}^1$
Inital conditions are:
$n_0^4=1$, $n_0^3=n_0^2=n_0^1=n_0^0=0$
The above set of rules can be converted into a fairly simple code that will calculate the number of users on any given day.


text:
Q: Huge navigation bar on the iPhone I'm trying to learn how to programmatically create the UI of my application.
I added to the application a navigation controller with code, this is the code:
AppDelegate:
    var window: UIWindow?
var navigationController: UINavigationController?

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

    window = UIWindow(frame: UIScreen.main.bounds)
    if let window = window{
        let mainVC = MainVC()
        navigationController = UINavigationController(rootViewController: mainVC)
        window.rootViewController = navigationController

        window.makeKeyAndVisible()
    }
    return true
}

And this is my mainVC:
    class MainVC: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.white

        navigationController?.navigationBar.isTranslucent = false

        navigationController?.navigationBar.barTintColor = UIColor.blue
        navigationController?.navigationBar.prefersLargeTitles = true
        navigationItem.title = "Hello"
        setupTextBox()
        // Do any additional setup after loading the view, typically from a nib.
    }

    let textBox: UITextField = {
        var tBox = UITextField(frame: CGRect(x: 100, y: 100, width: 200, height: 30))
        tBox.placeholder = "Please Enter Name"
        tBox.textAlignment = .center
        tBox.borderStyle = .roundedRect
        tBox.backgroundColor = UIColor.red

        return tBox
    }()

    private func setupTextBox(){
        view.addSubview(textBox)
    }
}

The navigation bar does appear but it is huge, couldn't find a way to view it as it should be.
This is the image of the navigation bar:

What am I doing wrong?

A: Its because of navigationController?.navigationBar.prefersLargeTitles = true

You are doing well
Just must to understand that it is iPhone X with top safe area + LARGE TITLE

A: You're not doing anything wrong. That's simply how a UINavigationBar looks on iPhone X, iPhone XR and iPhone XS. All of these devices have the "X" bevel.
Here's another helpful SO post: What is the top bar height of iPhone X?

A: The large navigation bar is a style of navigation bar that is used when prefersLargeTitles is set.  So this line is causing your issue
navigationController?.navigationBar.prefersLargeTitles = true

Change that to false and you should get a smaller* navigation bar
Note: * it will still be larger than normal due to the 'notch' on the iPhone X range of devices


text:
Q: Replacing multiples of 10 in a dataset I have a problem which has proven pretty hard to solve. I have a dataset D were I want to replace all data points that can be written as y=x*10^n where x is an integer which is not larger than 10 (e.g. y=20,300,... but not 25, 375...). I want to replace these data points y with y-1. So for example I want 20 to become 19, 300 to become 299 etc.
For example say my dataset D is:
D <- c(20, 32, 200, 300.12, 40, 213, 60, 75)

Then I want my new dataset to be
Dnew
[1]  19  32 199 300.12 39 213 59 75

I have tried many ways using the gsub() function but I can't make it work.


text:
Q: Why is my program not reading the first line of code in the referenced file(fileName)? def main():
    read()

def read():

    fileName=input("Enter the file you want to count: ")

    infile=open(fileName , "r")
    text=infile.readline()
    count=0
    while text != "":

        text=str(count)
        count+=1
        text=infile.readline()

        print(str(count)+ ": " + text)

    infile.close()
main()

-the referenced .txt file has only two elements
44
33
-the output of this code should look like
1: 44
2: 33
-my output is
1: 33
2:
im not sure why the program is not picking up the first line in the referenced .txt file. The line numbers are correct however 33 should be second to 44.

A: The reason is explained in the comments:
def main():
    read()

def read():
    fileName=input("Enter the file you want to count: ")
    infile=open(fileName , "r")
    text=infile.readline()  ##Reading the first line here but not printing
    count=0
    while text != "":
      text=str(count)
      count+=1
      text=infile.readline() ##Reading the 2nd line here
      print(str(count)+ ": " + text) ##Printing the 2nd line here, missed the first
                                     ##line

    infile.close()

main()

Modify the program as:
def main():
   read()

def read():
   fileName= input("Enter the file you want to count: ")
   infile = open(fileName , "r")
   text = infile.readline()
   count = 1                             # Set count to 1
   while text != "":
      print(str(count)+ ": " + str(text))   # Print 1st line here
      count = count + 1                     # Increment count to 2
      text = infile.readline()              # Read 2nd line

   infile.close()                           # Close the file

main()

A: def main():
    read()

def read():

    fileName=input("Enter the file you want to count: ")

    with open(fileName,'r') as f:
        print('\n'.join([' : '.join([str(i+1),v.rstrip()]) for i,v in enumerate(f.readlines())]))
main()

A: I'm very confused by your read function. You start by reading the first line into text:
text=infile.readline()

Presumable at this point text contains 44.
You then immediately demolish this value before you've done anything with it by overwriting it with:
text = str(count)

ie you read two lines before printing anything at all.

A: You should print the value of text before you overwrite it with the next readline.
Simply move the print statement before readline:
while text != "":

    count+=1
    print(str(count)+ ": " + text)
    text=infile.readline()


text:
Q: Update SQL Query with populated variables from AJAX functions over multiple PHP Pages i try to get help with that question.
All in all Q: It doesnt Update my DB entry like this Step by Step Order how i think it could be done.
its a bit difficult to explain, but i try to explain it step by step with minimal and readable Code. I use the original code, its hard to convert it in reproducible Examples.
A.1 Page ma_aktuelle_ReadOut.php
 There is a php Part
 <?php echo "   ";
?>

When i click this link the following javascript function is called and ask me "really stop?"

When i cklick "yes" it opens the second Page.
A 2 Page ma_Testende.php
On this Page are 2 AJAX JS Functions.
The first Ajax is asking for "Datum" via type:get from the following next page and wait till success (see Page B 3):

B 3 Page ma_get-TesterID_Testende.php
<?php
$cinfo = array(
    "Database" => $database,
    "UID" => $username,
    "PWD" => $password
);
$conn = sqlsrv_connect($server, $cinfo);
                $sqlreadZeit = "Select TOP 1 CID,Datum from DB.dbo.TesterCycleCount where TesterID = '".$_GET['TesterID']."' order by Datum DESC";
                $result1 = sqlsrv_query($conn, $sqlreadZeit);
                $zeiten_arr = array();
                while ($row = sqlsrv_fetch_array($result1, SQLSRV_FETCH_ASSOC)) {
                $CID = $row['CID'];
                $Datum = $row['Datum']->format('d.m.Y h:m:s');
                $zeiten_arr[] = array("CID" => $CID, "Datum" => $Datum);
                                }
    header('Content-type: application/json');
  echo json_encode($zeiten_arr);
?>

Back with the "Datum" the second AJAX is called (see Page A 2)
With the "Datum" and "TestaufstellungID" as variable it should be call the next Page and Update the DB entry with the populated variablles.
B. 4 Page ma_TestendeSQL.php
<?php
$cinfo = array(
    "Database" => $database,
    "UID" => $username,
    "PWD" => $password
);
$conn = sqlsrv_connect($server, $cinfo);

$TestaufstellungID = $_GET['TestaufstellungID'];
$Testende= $_GET['Datum'];
$Testdatum = date('Y-d-m');

$stop = $connection->prepare("WITH UpdateTestende AS (
  SELECT TOP 1  * from DB.dbo.Testergebnisse
  WHERE TestaufstellungID = :TestaufstellungID
  ORDER BY TestergebnisID DESC
)
update UpdateTestende
set Testende = :Testende,
Datum = :Testdatum");
$stop->execute(array(':TestaufstellungID' => $TestaufstellungID, ':Testdatum' => $Testdatum, ':Testende' => $Testende));

    header('Content-type: application/json');
?>

The php variable $Testende get the populated "Datum" from the Ajax functions. All in all at the end it should be Update, when i click on the link the ( Page A 1) my DB entry with the populated "Datum" which i get from the first Ajax call ( Page A 2 ) from the SQL Query ( Page B 3) back to the second AJAX Call ( Page A 2 )  than with the data: {TestaufstellungID:TestaufstellungID, Datum: Datum}  to the last page ( Page B 4)
But it doesnt Update my DB entry like this Step by Step Order how i think it could be done.
Encapsulated is the SQL-Code working fine. With the Code header('Content-type: application/json'); the browser tell me the following when i click on the link from ( Page A 1 )
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
Thats why i posted all the Step i think on one point the variables are not passed right to the next page or they are empty becasue the code is not executed in the right order Server/Client PHP/JS or Asynchronous problem...
The console.log tell me nothing. At the moment i have no idea where to start with the debugging?
Hope someone can help me. thx
Edit: iam pretty sure the ajax call is empty, but i dont see it in which step the values getting empty
Edit2:
AJAX Call is empty or is not starting.
Further invstigation:  The Ajax alert me the error part with empty exception and dont alert me the success part. So it doesnt  go to the page ma_get-TesterID_Testende.php or it doesnt  return back the Datum .
Could be not enabled Cross-Site-Scripting be the Problem?
But in another Page is a similiar Ajax Call working fine.
$(document).ready(function(){

var TesterID = "<?php echo $_GET['TesterID']; ?>"; /* value der Tester erhalten */

        $.ajax({ /* AJAX aufrufen */
            url: 'ma_get-TesterID.php',
            type: 'get', /* Methode zum übertragen der Daten */
            data: {TesterID:TesterID}, /* Daten zu übermitteln */
            dataType: 'json',
            success:function(response){ /* Die zurückgegebenene Daten erhalten */

                var len = response.length;

                $("#Teststart").empty(); /* Die erhaltenden Daten werden bei der ID angezeigt */
                for( var i = 0; i<len; i++){
                    var CID = response[i]['CID'];
                    var Datum = response[i]['Datum'];

                    $("#Teststart").append("<option value='"+Datum+"'>"+Datum+"</option>");

                }
            }
        });

    $("#TesterID").change(function(){ /* Wenn du änderst und vom Select Feld auswählst */
        var TesterID = $(this).val(); /* value der Tester erhalten */

        $.ajax({ /* AJAX aufrufen */
            url: 'ma_get-TesterID.php',
            type: 'get', /* Methode zum übertragen der Daten */
            data: {TesterID:TesterID}, /* Daten zu übermitteln */
            dataType: 'json',
            success:function(response){ /* Die zurückgegebenene Daten erhalten */

                var len = response.length;

                $("#Teststart").empty(); /* Die erhaltenden Daten werden bei der ID angezeigt */
                for( var i = 0; i<len; i++){
                    var CID = response[i]['CID'];
                    var Datum = response[i]['Datum'];

                    $("#Teststart").append("<option value='"+Datum+"'>"+Datum+"</option>");

                }
            }
        });
    });

});

In this example the Ajax Call starts when i change the value from a Dropdown selection Form.    Is there a difference?
How this Ajax should work i try to explain in my other question step by step, how it my application should be execute.
Update SQL Query with populated variables from AJAX functions over multiple PHP Pages
Edit 3:
JQuery Version:
https://code.jquery.com/jquery-3.4.1.js

A: One alternative is use $_SESSION superglobal; I offer it as this question is tagged as PHP rather than AJAX/JSON, and to avoid encode-decode common issues with JSON values or arrays. If you're able to, change your strategy and use client-side to broadcast data and stop normal flow in an error response event.
With a started session_start() you can use an inner temporary array in $_SESSION to attach/detach step by step data, in this example "step" array, like this:
<?php
// step 1
$_SESSION['step'][1]['TesterID']            = 64;
$_SESSION['step'][1]['var2']                = 'bar';
// step 2
$_SESSION['step'][2]['TestaufstellungID']   = 65;
$_SESSION['step'][2]['var4']                = 100;
$_SESSION['step'][2]['var5']                = 256.04;
?>

When you send data, over AJAX, is not necesarry to convert it to JSON, because you can work with $_POST object. Meanwhile, response can give to you every $_SESSION['step'] values in JSON format.
<?php
header("Content-type:application/json")
// conditions goes here
if ( $conditions == true ) {
    echo json_encode($_SESSION['step']);
}
?>

This way, and considering is a "step by step" process, you can chose to save an json_encode() object updating in every step, or use session superglobal to save it only when process finish, considering all "step" array or just relevant values, users id in this case
https://www.php.net/manual/es/reserved.variables.session.php
https://www.php.net/manual/es/function.session-id.php
https://www.php.net/manual/es/function.json-encode.php


text:
Q: populating pandas columns based on values in other columns My dataframe contains these columns
ID   Address1   Address1-State   Address1-City  Address2  Address2-State  Address2-City   Address    State      City
 1    6th street   MN              Mpls
 2                                               15th St      MI           Flint
 3                 MA              Boston          Essex St   NY            New York
 4    7 street SE  MN              Mpls           8th St      IL             Chicago

Now I want to populate Address field in such a way that if Address1 is blank,populate Address2 and the state city fields of Address2
In the above case final dataframe would be like this
 ID     Address   State    City
  1      6th street   MN    Mpls
  2      15th St      MI    Flint
  3      Essex St     NY     New York
  4     7 street SE  MN     Mpls

Currently,I am doing this
def fill_add(address1,address2):
if address1!='':
    address=address1

elif address1=='' and address2!='':
    address=address2
elif address1=='' and address2=='':
     address=''

return address

def fill_add_apply(df):
df['Address']=df.apply(lambda row:fill_add(row['Address1'],row['Address2']),axis=1)

Do I have to do the same for all the other columns?Is there a better way?
Just to clarify, in ID=3 Address,State,City should be "Essex St NY New York" because Address 1 is blank so it should choose Address2 and the city and state of Address2.
In short, if Address1 is blank it should choose Address2,Address2-State and  Address2-City,even if Address1-State and  Address1-City are not blank.

A: 1st modify your column , then using groupby +first
df=df.replace('',np.nan)#prepare for first

df.columns=df.columns.str.replace('\d+','')
df.columns=df.columns.str.split('-').str[-1]
newdf=df.groupby(level=0,axis=1).first()
newdf.loc[df.iloc[:,1].isnull(),:]=df.groupby(level=0,axis=1).last()
newdf
Out[40]:
       Address      City  ID State
0  6th street       Mpls   1    MN
1      15th St     Flint   2    MI
2    Essexb St  New York   3    NY
3  7 street SE      Mpls   4    MN

A: (Given you do not have any duplicate index)
Select indices you want to fill with Adress1:
Address1_index = df.loc[!df.Address1.empty() and !df.Address1-State.empty() and !df.Address1-City.empty()].index

then put Address1 data in your desired columns:
df.loc[Adress1_index, ["Adress", "State", "City"]] = df.loc[Adress1_index, ["Adress1", "Adress1-State", "Adress1-City"]]

Now select indices you want to fill with address2:
Address2_index = df.loc[df.Adress1.empty() or df.Adress1-State.empty() or df.Adress1-City.empty()].index

then fill these also:
df.loc[Adress2_index, ["Adress", "State", "City"]] = df.loc[Adress2_index, ["Adress2", "Adress2-State", "Adress2-City"]]

Remove columns that you do not want:
df.drop(["Address1", "Adress1-State", "Adress1-City", "Address2", "Adress2-State", "Adress2-City"], axis = 1, inplace = True)

A: import numpy as np

df=df.replace('',np.nan)

addr_1=['ID','Address1','Address1-State','Address1-City']
addr_2=['ID','Address2','Address2-State','Address2-City']

new_df=pd.DataFrame(df[addr_1].values.copy(),columns=['ID','Address','State','City'])

new_df.loc[new_df['Address'].isnull(),:]=df.loc[df['Address1'].isnull(),addr_2].values

#print(new_df)
    ID  Address     State   City
0   1   6th street  MN      Mpls
1   2   15th St     MI      Flint
2   3   Essex St    NY      New York
3   4   7 street SE MN      Mpls


text:
Q: Arrays using commander Hei guys!
I need help with the commander node.js library. I need create this CLI which accepts 3 flags, --input, --output and --pattern, like:
commander
  .version('3.0.0')
  .usage('[options] <file ...>')
  .option('-i, --input', 'Array of files to be extracted')
  .option('-o, --output', 'Output file name')
  .option('-p, --pattern', 'Pattern name to be used in the extraction')
  .parse(process.argv);

My problem is with the input flag. I need send several files, for that i need an array data type.
The problem is: I just can't figure it out how to make this:
node ./bin/extract -i ../files/*.PDF

become an array with all my files that are inside my files directory. I already try to run every sample in the documentation, and i didn't find the solution for my problem. Also, i searched in the issues and didn't find either... what is strange, maybe i am doing something wrong and you guys could help??
Thanks!

A: You can use Coercion  to achieve it:
function scanDir(val) {
    files = fs.readdirSync(val);
    return files;
}

program
    .version('0.0.1')
    .option('-s, --scan [value]', '', scanDir)
    .parse(process.argv);

console.log(' scan: %j', program.scan);

And call it like:
node app.js -s /foo


text:
Q: where can I get windbg for windows 7 64bit without the whole sdk? I am looking for windbg.  Without the whole Windows SDK
I saw this link
https://stackoverflow.com/questions/2736250/getting-windbg-without-the-whole-wdk
But the accepted answer, from dave black, (since MS has updated the content), seems to just be for Windows 8, and seems to be more than just windbg. (I doubt windbg is 1GB+)
I tried the sdksetup.exe files  and it shows a suitcase.

And anyhow I don't even want the whole SDK.
And when I click that it just shows a suitcase
Then when it does seem to load, it doesn't offer just the SDK

A: As was mentioned in the Stack Overflow answer you referenced in your question, you can download the tools from this page.
Once you've downloaded and run sdksetup.exe, waited for the suitcase screen to pass, you just need to click "Next" a couple of times.  You'll get to this screen:

From there you can deselect everything except "Debugging Tools for Windows"

A: Windbg for windows 7 - download
x86: http://download.microsoft.com/download/A/6/A/A6AC035D-DA3F-4F0C-ADA4-37C8E5D34E3D/setup/WinSDKDebuggingTools/dbg_x86.msi
x64: http://download.microsoft.com/download/A/6/A/A6AC035D-DA3F-4F0C-ADA4-37C8E5D34E3D/setup/WinSDKDebuggingTools_amd64/dbg_amd64.msi
Windbg for windows 10 (WinDbg 10.0.18362.1) - download
x86: https://download.microsoft.com/download/4/2/2/42245968-6A79-4DA7-A5FB-08C0AD0AE661/windowssdk/Installers/X86%20Debuggers%20And%20Tools-x86_en-us.msi
x64: https://download.microsoft.com/download/4/2/2/42245968-6A79-4DA7-A5FB-08C0AD0AE661/windowssdk/Installers/X64%20Debuggers%20And%20Tools-x64_en-us.msi
Windbg preview (WindbgX) from Microsoft Store
https://www.microsoft.com/store/p/windbg/9pgjgd53tn86
Source:
https://github.com/yanglr/advDotnetDebugging/blob/main/README.md


text:
Q: Devise Error Messages not showing up Bootstrap template I am using a Wrapbootstrap downloaded template, with devise for user registration and log in but am not getting any errors to pop up.
In all my views for devise I am calling  <%= devise_error_messages! %>
In my model the following validations:
    validates :first_name, presence: true
    validates :last_name, presence: true
    validates :phone_number, presence: true

Here is my Devise_helper.rb
    module DeviseHelper
   def devise_error_messages!
   return '' if resource.errors.empty?

    messages = resource.errors.full_messages.map { |msg| content_tag(:li, msg) }.join
    html = <<-HTML

 <button type="button"
    class="close" data-dismiss="alert">x</button>
   #{messages}

    HTML

    html.html_safe
   end
 end

Here is my Registration New view page:

         <form class="reg-page">

Register a new account

Already Signed Up? Click <%= link_to "Sign In", login_url %> to login your account.

        <%= form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %>
        <%= devise_error_messages! %>

        First Name*
        <%= f.text_field :first_name, autofocus: true, :class=> "form-control margin-bottom-20" %>

        Last Name*
        <%= f.text_field :last_name, autofocus: true, :class=> "form-control margin-bottom-20" %>

        Phone Number*
        <%= f.text_field :phone_number, autofocus: true, :class=> "form-control margin-bottom-20" %>

        Email Address *
        <%= f.email_field :email, autofocus: true, :class=> "form-control margin-bottom-20" %>

        Password *
        <% if @validatable %>
        (<%= @minimum_password_length %> characters minimum)
        <% end %>
        <%= f.password_field :password, autocomplete: "off", :class=> "form-control margin-bottom-20" %>

        Confirm Password *
        <%= f.password_field :password_confirmation, autocomplete: "off",:class=> "form-control margin-bottom-20" %>

         <%= f.submit "Sign up", :class=> "btn-u" %>

        </form>

        <% end %>

And when I submit an uncomplete form a query string like this is generated: http://localhost:3000/login?utf8=%E2%9C%93&authenticity_token=v%2BKndd3om3fBChpsZ6riw%2FVBiVM1ehVbKgBF9tIlg6PB6p30oei7OU3toqthjU1TY67yI3gmzjigxGe5DWfX7w%3D%3D&user%5Bemail%5D=&user%5Bpassword%5D=fwf&user%5Bremember_me%5D=0&commit=Log+in

A: Try with this in your helper file:
message_html << "
 <button type="button" class="close" data-dismiss="alert">x</button>"
message_html.html_safe

Also, check for flash message in your layout page or corresponding login page as:
  <% if flash[:alert] %>
     <%= flash[:alert] %>
  <% end %>

A: There reason for this was because the template I was using had its own Javascript for error messages that was overriding the error messages of devise. Both error messages were not showing up until I removed the JS included in the Wrapbootstrap template and it works now


text:
Q: AngularJS : How do I switch views from a controller function? I am trying to use the ng-click feature of AngularJS to switch views. How would I go about doing this with the code below?
index.html

            click me

controller.js
  function Cntrl ($scope) {
        $scope.someFunction = function(){
            //code to change view?
        }
    }

A: There are two ways for this:
If you are using ui-router or $stateProvider, do it as:
$state.go('stateName'); //remember to add $state service in the controller

if you are using angular-router or $routeProvider, do it as:
$location.path('routeName'); //similarily include $location service in your controller

A: The provided answer is absolutely correct, but I wanted to expand for any future visitors who may want to do it a bit more dynamically -
In the view -

        Go to edit

In the controller -
$scope.changeView = function(person){
    var earl = '/editperson/' + person.id;
    $location.path(earl);
}

Same basic concept as the accepted answer, just adding some dynamic content to it to improve a bit.  If the accepted answer wants to add this I will delete my answer.

A: In order to switch between different views, you could directly change the window.location (using the $location service!) in
index.html file

            edit

            preview

Controller.js
function Cntrl ($scope,$location) {
        $scope.changeView = function(view){
            $location.path(view); // path not hash
        }
    }

and configure the router to switch to different partials based on the location ( as shown here https://github.com/angular/angular-seed/blob/master/app/app.js ). This would have the benefit of history as well as using ng-view.
Alternatively, you use ng-include with different partials and then use a ng-switch as shown in here ( https://github.com/ganarajpr/Angular-UI-Components/blob/master/index.html )

A: Without doing a full revamp of the default routing (#/ViewName) environment, I was able to do a slight modification of Cody's tip and got it working great.
the controller
.controller('GeneralCtrl', ['$route', '$routeParams', '$location',
        function($route, $routeParams, $location) {
            ...
            this.goToView = function(viewName){
                $location.url('/' + viewName);
            }
        }]
    );

the view
...

HOME

...

What brought me to this solution was when I was attempting to integrate a Kendo Mobile UI widget into an angular environment I was losing the context of my controller and the behavior of the regular anchor tag was also being hijacked. I re-established my context from within the Kendo widget and needed to use a method to navigate...this worked.
Thanks for the previous posts!

A: I've got an example working.
Here's how my doc looks:

    <link rel="stylesheet" href="css/main.css">

        <ng-view></ng-view>

Here's what my partial looks like:

    Welcome! Please Login!
    <form ng-submit="auth()">
        <input class="input login username" type="text" placeholder="username" />

        <input class="input login password" type="password" placeholder="password" />

        <input class="input login submit" type="submit" placeholder="login!" />
    </form>

Here's what my Ctrl looks like:
app.controller('Index', function($scope, $routeParams, $location){
    $scope.auth = function(){
        $location.url('/map');
    };
});

app is my module:
var app = angular.module('app', ['ngResource']).config(function($routeProvider)...

Hope this is helpful!

A: Firstly you have to create state in app.js as below

.state('login', {
      url: '/',
      templateUrl: 'views/login.html',
      controller: 'LoginCtrl'
    })

and use below code in controller

 $location.path('login');

Hope this will help you

A: This little function has served me well:
    //goto view:
    //useage -  $scope.gotoView("your/path/here", boolean_open_in_new_window)
    $scope.gotoView = function (st_view, is_newWindow)
    {

        console.log('going to view: ' + '#/' + st_view, $window.location);
        if (is_newWindow)
        {
            $window.open($window.location.origin + $window.location.pathname + '' + '#/' + st_view, '_blank');
        }
        else
        {
            $window.location.hash = '#/' + st_view;
        }

    };

You dont need the full path, just the view you are switching to

A: The method used for all previous answers to this question suggest changing the url which is not necessary, and I think readers should be aware of an alternative solution.  I use ui-router and $stateProvider to associate a state value with a templateUrl which points to the html file for your view.  Then it is just a matter of injecting the $state into your controller and calling $state.go('state-value') to update your view.
What is the difference between angular-route and angular-ui-router?


text:
Q: SKEmitterNode particles clumping together on creation I have an SKEmitterNode that is acting strange in different versions of iOS. If you look at the screenshot below, you will see that when my scene is loaded, the emitter I am using dumps an odd group of rain drops when the scene first loads.

The strangest part is that this happens in some versions of iOS like 8.1 and 9.2, but in some other versions like 9.0 and 7.0 it runs as expected. (meaning no initial clump of drops, just randomly spaced drops.)
Here is my code in didMoveToView:
 let rainEmitterPath:NSString = NSBundle.mainBundle().pathForResource("homeScreenRain", ofType: "sks")!
    self.rainEmitter01 = NSKeyedUnarchiver.unarchiveObjectWithFile(rainEmitterPath as String) as! SKEmitterNode
    self.rainEmitter01.position = CGPointMake(device.x/2, device.y + 50)
    self.rainEmitter01.targetNode = self
    self.rainEmitter01.particleZPosition = 6.0
    self.rainEmitter01.particleBirthRate = 300
    self.rainEmitter01.particleSpeed = 5000 * worldScale
    self.rainEmitter01.particleSpeedRange = worldScale * 1000
    self.rainEmitter01.particleScale = worldScale
    self.rainEmitter01.particleScaleRange = worldScale
    self.rainEmitter01.particlePositionRange = CGVector(dx: device.x + 100, dy: 5)
    //self.rainEmitter01.advanceSimulationTime(7.0)
    self.addChild(rainEmitter01)

I have tried using the advanceSimulationTime method, but for some reason the group of drops still falls even after the delay.
I have also tried varying the y size of the position range because I figured that my height of 5 was causing this, but nothing changed even when I make the height equal to the size of the screen, and a height of 5 still works in other versions of iOS.
Anyone know why this is happening and a solution/workaround?
Thanks in advance.