text:
Q: cakephp association error? Warning (512): Model "User" is not associated with model "User" [CORE\cake\libs\model\behaviors\containable.php, line 340]
im getting this error when accessing datas of photo, friend
user has many photos and friend, photos and friend belongs to user
in photos index page, two warnings one for user mentioned above and other for 'Friend' as same friend is not associated with model 'friend'
what to do? what to check?

A: You have some mismatch with assotiations.
You can have situation similar to this:
User habtm array("Friend"=> array("className"=>"User")

And when finding users:
$this->User->find("all", array(
   "contain"=>array("User");
));

instead of:
$this->User->find("all", array(
   "contain"=>array("Friend");
));

Check this or post some code :)


text:
Q: Define functions using Node ADT I am trying to write this code, but i cant get the last part right. the question is to define a function which takes a  Node object as a parameter and returns a list of cumulative words in this linked chain. the Node ADT is already built into the program so I cannot modify it.
my code:
def get_cumulative_words_list(first_node):

    new_list=[]
    new_list.append(first_node.get_data())
    current=first_node.get_next()
    while current !=None:
        new_list.append(current.get_data())
        current=current.get_next()
    return new_list

the result im getting is:
hello

to

programming

['hello', 'to', 'programming']

what I am suppose to get is:
hello

to

programming

['hellotoprogramming', 'toprogramming', 'programming']

what do i have to modify in my code to get the expected result?
Thank you

A: Your new_list contains all the element of the ADT. From that you can generate your desired result using a list comprehension and join() like this -
def get_cumulative_words_list(first_node):
    new_list=[]
    new_list.append(first_node.get_data())
    current=first_node.get_next()
    while current !=None:
        new_list.append(current.get_data())
        current=current.get_next()
    return ["".join(new_list[i:]) for i in range(len(new_list))]

In the last line a new list is created from new_list. The "".join(new_list[i:]) returns a string by adding all the strings of that slice.
So when i is 0 and say length of new_list is 3, the "".join(... will add new_list[0], new_list[1] and new_list[2] and this string will be the first entry of the newly created list. Similarly when i is 1, it will only add new_list[1] and new_list[2].
In this way, the output will be - ['hellotoprogramming', 'toprogramming', 'programming'].

redpajama_set_name: RedPajamaStackExchange


text:
Q: Retrieve both current and previous elements using Iterator in Java I have an ArrayList in my Java code and I would like to retrieve both its current and previous elements.
This is the code I made :
    List<Graph> graphs = new ArrayList<Graph>();
    graphs.addAll(bestGraphs.values());
    ListIterator<Graph> listItr = graphs.listIterator();
    while(listItr.hasNext()) {
        if(!listItr.hasPrevious()) {
            listItr.next();
        } else {
            Graph g1 = listItr.previous();
            Graph g2 = listItr.next();
            croisementGraphs(g1, g2);
            listItr.next();
        }
    }

croisementGraphs(g1, g2); is a function that should take both the current and the previous elements (graphs) of the ArrayList.
The problem here is that both variables g1 and g2 point to the same element.
When I read the Javadoc related to the previous() function, it says :

(Note that alternating calls to next and previous will return the same element repeatedly.)

What should I do in this case ?
Thanks!

A: You can use your solution, just take the actual next item:
Graph g1 = listItr.previous();
listItr.next();
Graph g2 = listItr.next();
croisementGraphs(g1, g2);

And I think that you should read about the iterators, I am afraid you don't understand how they work. I'll try to explain it briefly:

*

*Iterators are located between items, not at them

*When next or previous is called iterators return an item they just "walked over"

Small example: lets take a list of a few items: [1,2,3], and present it in the next form: [.1.2.3.], lets show where iterator is by placing a letter x there. Now some actions and corresponding state changes:
ListIterator x = list.listIterator(); // [x1.2.3.]
x.next(); // [.1x2.3.], returns 1
x.previous(); // [x1.2.3.], returns 1
x.next(); // [.1x2.3.], returns 1
x.next(); // [.1.2x3.], returns 2

A: Calling previous moves the position of the ListIterator backwards. Hence you need to consider what position you are at.
Consider you're at position N, you call previous and it will return N and move to N-1, then you call next and it returns N and moves the pointer to it..
Hence you need to call:
    graphs.get(listItr.previousIndex());
if you want it not to move the position of the listIterator.

A: Try to call listItr.next(); twice like this:
    while(listItr.hasNext()) {
    if(!listItr.hasPrevious()) {
        listItr.next();
        listItr.next();
    } else {
        ...
    }

For more info go in link

A: You could use a reduction:
graphs.stream().reduce((g1, g2) -> {croisementGraphs(g1, g2); return g2;});

If you made croisementGraphs() return its second parameter, you could just:
graphs.stream().reduce(this::croisementGraphs);


text:
Q: How to set timestamp to aws region timezone for aws lambda python code in my python lambda code that scans dynamodb based on primary key as 'deviceId'  & sortkey timestamp( which is in YYYY-MM-DD HH:MN:SS format) , i need to scan every for last 15min data (from time now).  I am in Mumbai region (ap-south-1), how do I set local timezone in my following lambda code. since it is picking default utc datetime.The lambda ideally has to scan & if return count >= 10 then thermostat+5 .
import boto3
import math
import json
import time
from datetime import datetime,timedelta
from dateutil.tz import tzlocal
from boto3.dynamodb.conditions import Key, Attr

client = boto3.client('dynamodb')
dynamodb = boto3.resource('dynamodb')

def lambda_handler(event, context):

    #table_name= "thermostat_dynamo"
    table_name= "newsensor"
    Primary_Column_Name = 'deviceId'
    table = dynamodb.Table(table_name)
    #key_param = "thermostat"
    #thermostatVal = table.get_item(Key={key_param:event[key_param]}) ## get record from dynamodb for this sensor
    thermostatVal= 77
    #now = datetime.now()
    now = datetime.now(tzlocal())
    fifteen_min_ago =  now - timedelta(seconds=900)
    now = now.strftime('%F %T')
    fifteen_min_ago = fifteen_min_ago.strftime('%F %T')

    fe = Key('timeStamp').between(fifteen_min_ago,now);
    response = table.scan(FilterExpression=fe & Attr('temperature').lt(thermostatVal))

    if response['Count'] == 10:
    #return thermostatVal+5
        thermonew = thermostatVal + 5
        tosensor = '{"thermostat":'+'"%s"}' %thermonew
        print(tosensor)
        #response = client.publish(topic="updatehomesensor", qos=1, payload=tosensor)
        return

    elif response['Count'] < 10:
        #tosensor = '{"thermostat":'+'"%s"}' %thermostatVal
        print('{"thermostat":'+'"%s"}' %thermostatVal)
        #response = client.publish(topic="updatehomesensor", qos=1, payload=tosensor)
        return

A: All Lambda instances are set to UTC timezone. Incase you want to change that behavior you need to update environment variable.
Detailed document is below which mentions TZ as Reserved environment variable
https://docs.aws.amazon.com/lambda/latest/dg/configuration-envvars.html.
So in your case for example  you want to setup lambda to use IST [ Indian Standard Timezone ]. You need to go through following steps.

*

*In configuration tab of function scroll down to environment variables section.

*Click Edit and add variable TZ with value Asia/Calcutta [ For IST ].

It should look like below

After saving the environment variable your environment will use timezone mentioned in the TZ variable.

A: Firstly there's no native CLI command for getting a regions timezone so the timezone for the region needs to come from you.
You could create an environment variable of AWS_TIMEZONE and set the value to 'Asia/Kolkata'. You would then need to add import os and from pytz import timezone and call timezone = timezone(os.environ['AWS_TIMEZONE']) followed by updating now = datetime.now(timezone). Each region you deployed to you could set a different variable value for AWS_TIMEZONE.
However, I would recommend if you possibly could to actually store any date times in UTC as it leads to less confusion around timezone problems and is generally considered best practice.


text:
Q: Youtube Video Playing issue in Android - Code Attached This is a critical issue pertaining to an application we did. The code snippet attached here was working like a charm for the past several months. All of a sudden, it gives us the message in mediaplayer that video cannot be played.
Can anyone please suggest what need to be done, in order that this code will work for me by playing the video with no hassles.
Looking forward for your valuable comments, help and suggestions,
Please follow this link in order to view the code which was working perfectly -- http://pastebin.com/NVT8eBC0

import android.app.Activity;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnPreparedListener;
import android.net.Uri;
import android.os.Bundle;
import android.widget.MediaController;
import android.widget.VideoView;

public class videoact extends Activity implements OnPreparedListener{
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        MediaController mc = new MediaController(this);
        VideoView vv = (VideoView)findViewById(R.id.VideoView01);
        try
        {
         Uri ur = Uri.parse("http://youtube.com/get_video?video_id=ZmX7zLCrcAI&t=vjVQa1PpcFPmrj_j5y370BhPYfq3qHoWsFICYcBqEl4%3D&asv=&fmt=18");
         vv.setVideoURI(ur);
         vv.setMediaController(mc);
         vv.requestFocus();
         vv.start();
         mc.show();
        }
        catch(Exception e)
        {
         System.out.print(e.getMessage() + "error");
        }

    }

public void onPrepared(MediaPlayer mp) {
// TODO Auto-generated method stub
mp.start();
}

}

A: You can't play YouTube videos like that. Use the Android YouTube Player Api or the IFrame API in a WebView.
Using the get_video endpoint is against youtube's terms of service.
https://www.youtube.com/static?template=terms

You agree not to access Content through any technology or means other than the video playback pages of the Service itself, the Embeddable Player, or other explicitly authorized means YouTube may designate.


text:
Q: RxJs: New value only after a period of time has passed I am new to ReactiveExtensions and I do not get to work s.th. that I think should be a very common usecase. I want to receive a new value only after a specific period of time has passed without a new next value. In the bottom example this period of time is 1 second. The debounce-operator seems to do exactly what I want. I do not get it to work though.
const observable$ = new Rx.Observable(observer => {

 observer.next('start');

 setTimeout(() => {
  observer.next(1);
 }, 100);
 setTimeout(() => {
  observer.next(2);
 }, 200);
 setTimeout(() => {
  observer.next(3);
 }, 300);
 setTimeout(() => {
  observer.next(4);
 }, 400);

 setTimeout(() => {
  observer.next('end');
 }, 1500);
});

let sub = observable$
      .debounce(1000) //debounce(1000, null) does not work either
      .take(100)
      .subscribe(data => {
          console.log(data);
         },
         err => console.log(err.message),
         complete => console.log('Observable completed')
       )

What I want to get is a console-output of only:
"start"
"end"

In my IDE (Webstorm) the above code does not even compile although the documentation states that the second argument is optional. On jsbin.com i get the following error: "this.durationSelector.call is not a function" (I admit, I dont know yet how to apply schedulers in rxjs). In the documentation they use only a number, too. Most examples of debounce i found on google use only a number, i.e. this example on Stackoverflow. Why doesn't this work in my case?
Thanks for your help!
PS: I use rxjs 5.0.0-beta.6.
EDIT: With the help of the answers here I did find the actual soltion I wanted:
const observable$ = new Rx.Observable(observer => {

observer.next('start');

 setTimeout(() => {
  observer.next(1);
 }, 1100); //<-- If you change 1100 to i.e. 900 you just get "end" in the output, because there is no 1s periode during which no new value arrives.
 setTimeout(() => {
  observer.next(2);
 }, 1200);
 setTimeout(() => {
  observer.next(3);
 }, 1300);
 setTimeout(() => {
  observer.next(4);
 }, 1400);
 setTimeout(() => {
  observer.next(5);
 }, 1500);

 setTimeout(() => {
  observer.next('end');
 }, 1501);

});

let sub = observable$
      .debounceTime(1000)
      .take(10)
      .subscribe(data => {
         console.log(data);
       },
       err => console.log(err.message),
       complete => console.log('Observable completed')
);

A: It's merely a problem of the documentation being for the older version of RxJS. RxJS 4 overloads debounce here.
However, RxJS 5 splits the operator so that there are actually two, one that uses a selector function to determine the debounce length and the second debounceTime which accepts a time.
Hence your stream becomes:
let sub = observable$
      .debounceTime(1000) //debounce(1000, null) does not work either
      .take(100)
      .subscribe(data => {
          console.log(data);
         },
         err => console.log(err.message),
         complete => console.log('Observable completed')
       )

A: You can do something like this
const observable$ = new Rx.Observable(observer => {

    observer.next('start');

    setTimeout(() => {
        observer.next(1);
    }, 100);
    setTimeout(() => {
        observer.next(2);
    }, 200);
    setTimeout(() => {
        observer.next(3);
    }, 300);
    setTimeout(() => {
        observer.next(4);
    }, 400);

    setTimeout(() => {
        observer.next('end');
    }, 1500);

});

let sub = observable$
    .map(function(x, i) {
        return {
            val: x,
            index: i
        };
    })
    .debounce(function(obj) {
        let interval = obj.index === 0 ? 0 : 1500;
        return Rx.Observable.timer(interval);
    })
    .take(100)
    .subscribe(data => {
            console.log(data.val);
        },
        err => console.log(err.message),
        complete => console.log('Observable completed')
    )

The key here is to use map function to get the index of the element and then decide the waiting interval.


text:
Q: preg_replace not replacing everything im trying to get preg_replace to totally remove a string from a message
heres an example of a $message:
hello there john214

welcome to the site!

please get feel free to kick back and relax.

where john214 is a username outputted via the db
now i want to get rid of hello there john214 using preg_replace, however, my code is removing everything except for john214
heres my code:
$message = preg_replace('|hello there (.*?)|si', '', $message);

why is it not removing john214?

A: It might be because you are doing a non greedy approach.  Try this:
$message = preg_replace('|hello there(.*)|si', '', $message);

This will get rid of EVERYTHING that goes after hello there (because of the S modifier).  However, if what you want is get rid of everything in a single line that goes after hello there, you want to get rid of the s modifier as:
$message = preg_replace('|hello there(.*)|i', '', $message);

If you use the s modifier you are making the Dot metacharacter to match newlines, and that's why the first regex will consume all what goes after hello there (even jumping to new lines).

A: get rid of ? and of "s":
$message = preg_replace('~hello there .*~i', '', $message);

also, "|" is a poor choice for a delimiter, since "|" is special in the regexp language


text:
Q: Why is console animation so slow on Windows? (And is there a way to improve speed?) Well I was bored so wanted to make an animation in a console window.
Now when I setup the first bits I noticed it is very slow, something around 333ms for a whole screen to fill with characters..
I am wondering if there is a way to at least get ~20 fps?
Here is my code:
#include <stdio.h>
#include <tchar.h>
#include <Windows.h>
#include <iostream>
#include <array>

#define WIDTH (100)
#define HEIGHT (35)

bool SetWindow(int Width, int Height) {
    _COORD coord;
    coord.X = Width; coord.Y = Height;

    _SMALL_RECT Rect;
    Rect.Left = 0;              Rect.Top = 0;
    Rect.Bottom = Height - 1;   Rect.Right = Width - 1;

    HANDLE Handle = GetStdHandle(STD_OUTPUT_HANDLE);
    if (Handle == NULL)return FALSE;
    SetConsoleScreenBufferSize(Handle, coord);
    if(!SetConsoleWindowInfo(Handle, TRUE, &Rect)) return FALSE;
    return TRUE;
}

std::array<std::array<unsigned char, WIDTH+1>, HEIGHT> Screen;//WIDTH+1 = prevent cout from undefined behaviour

void Putchars(unsigned char x){
    for(int row = 0; row < HEIGHT; ++row){
        std::fill(Screen[row].begin(),Screen[row].end(),x);
        Screen[row].at(WIDTH) = 0;//here = prevent cout from undefined behaviour
    }
}

void ShowFrame(DWORD delay = 0,bool fPutchars = false, unsigned char x = 0){
    if(fPutchars)Putchars(x);
    if(delay)Sleep(delay);
    system("CLS");
    for(int row = 0; row < HEIGHT; ++row)
        std::cout << Screen[row].data() << std::flush;
}

int _tmain(int argc, _TCHAR* argv[]){//sould execute @~63 fps, yet it executes @~3-4 fps
    if(SetWindow(100,HEIGHT)){
        for(unsigned char i = 219; i != 0; --i)
        ShowFrame(16,true, i);
    }
    return 0;
}

Edit: after reading numerous answers, tips and comments I finally worked it out, thank you guys, this is my final "base" code:
#include <stdio.h>
#include <tchar.h>
#include <Windows.h>
#include <iostream>
#include <array>

#define WIDTH (100)
#define HEIGHT (34)

HANDLE current;
HANDLE buffer;

bool SetWindow(int Width, int Height) {
    _COORD coord;
    coord.X = Width; coord.Y = Height;

    _SMALL_RECT Rect;
    Rect.Left = 0;              Rect.Top = 0;
    Rect.Bottom = Height - 1;   Rect.Right = Width - 1;

    HANDLE Handle = GetStdHandle(STD_OUTPUT_HANDLE);
    if (Handle == NULL)return FALSE;
    SetConsoleScreenBufferSize(Handle, coord);
    if(!SetConsoleWindowInfo(Handle, TRUE, &Rect)) return FALSE;
    return TRUE;
}

std::array<std::array<CHAR, WIDTH+1>, HEIGHT> Screen;//WIDTH+1 = prevent cout from undefined behaviour

void Putchars(CHAR x){
    for(int row = 0; row < HEIGHT; ++row){
        std::fill(Screen[row].begin(),Screen[row].end(),x);
        Screen[row].at(WIDTH) = 0;//here = prevent cout from undefined behaviour
    }
}

void ShowFrame(DWORD delay = 0, bool fPutchars = false, CHAR x = 0){
    if(fPutchars)Putchars(x);
    if(delay)Sleep(delay);
    //system("CLS");
    _COORD coord;
    coord.X = 0;
    for(int row = 0; row < HEIGHT; ++row)
    {
        coord.Y = row;
        FillConsoleOutputCharacterA(buffer,Screen[row].data()[0],100,coord,NULL);
    }
}

int _tmain(int argc, _TCHAR* argv[]){//sould execute @~63 fps, yet it executes @~3-4 fps
    SetWindow(WIDTH, HEIGHT);
    current = GetStdHandle (STD_OUTPUT_HANDLE);
    buffer = CreateConsoleScreenBuffer (
        GENERIC_WRITE,
        0,
        NULL,
        CONSOLE_TEXTMODE_BUFFER,
        NULL
    );
    SetConsoleActiveScreenBuffer (buffer);

    if(SetWindow(WIDTH,HEIGHT)){
        for(CHAR i = 219; i != 0; --i)
        ShowFrame(250,true, i);
    }
    CloseHandle (buffer); //clean up
    return 0;
}

and it seems to work very fast :)

A: Just glancing at your code, you're spawning a separate program ("CLS") once per frame. That's horrendously slow all by itself.
Contrary to some of the comments, the Windows console is capable of at least fairly reasonable speed if used even close to correctly (as in: you can update the console faster than any monitor can display the data).
Just for reference, here's a version of John Conway's Game of Life written for the Windows console. For timing purposes, it just generates a random starting screen and runs for 2000 generations, then stops. On my machine, it does 2000 generations in about 2 seconds, or around 1000 frames per second (useless, since a typical monitor can only update at around 60-120 Hz). Under 32-bit Windows with a full-screen console, it can roughly double that (again, at least on my machine). I'm pretty sure with a little work, this could be sped up some more, but I've never seen any reason to bother.
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <conio.h>
#include <io.h>

#define     ROWS        50
#define     COLS        80

// The total number of generations is really double this number.
int generations = 1000;

int civ1[ROWS+2][COLS+2], civ2[ROWS+2][COLS+2];

CHAR_INFO disp[ROWS][COLS];
HANDLE console;
COORD size = { COLS, ROWS };
COORD src = { 0, 0};
SMALL_RECT  dest = { 0, 0, COLS, ROWS };

void ClrScrn(char attrib) {
    COORD pos = { 0, 0};
    DWORD written;
    unsigned size;

    size = ROWS * COLS;

    FillConsoleOutputCharacter(console, ' ', size, pos, &written);
    FillConsoleOutputAttribute(console, attrib, size, pos, &written);
    SetConsoleCursorPosition(console, pos);
}

void fill_edges(int civ1[ROWS+2][COLS+2]) {
    int i, j;

    for (i=1; i<=ROWS; ++i) {
        civ1[i][0] = civ1[i][COLS];
        civ1[i][COLS+1] = civ1[i][1];
    }
    for (j=1; j<=COLS; ++j) {
        civ1[0][j] = civ1[ROWS][j];
        civ1[ROWS+1][j] = civ1[1][j];
    }
    civ1[0][0] = civ1[ROWS][COLS];
    civ1[ROWS+1][COLS+1] = civ1[1][1];
    civ1[0][COLS+1] = civ1[ROWS][1];
    civ1[ROWS+1][0] = civ1[1][COLS];
}

void update_generation(int old_gen[ROWS+2][COLS+2],
                       int new_gen[ROWS+2][COLS+2])
{
    int i, j, count;

    for (i = 1; i <= ROWS; ++i)
    {
        for (j = 1; j <= COLS; ++j)
        {
            count = old_gen[i - 1][j - 1] +
                old_gen[i - 1][j] +
                old_gen[i - 1][j + 1] +
                old_gen[i][j - 1] +
                old_gen[i][j + 1] +
                old_gen[i + 1][j - 1] +
                old_gen[i + 1][j] +
                old_gen[i + 1][j + 1];

            switch(count)
            {
            case 2:
                new_gen[i][j] = old_gen[i][j];
                break;

            case 3:
                new_gen[i][j] = 1;
                disp[i-1][j-1].Char.AsciiChar = '*';
                break;
            default:
                new_gen[i][j] = 0;
                disp[i-1][j-1].Char.AsciiChar = ' ';
                break;
            }
        }
    }
    WriteConsoleOutput(console, (CHAR_INFO *)disp, size, src, &dest);
    fill_edges(new_gen);
}

void initialize(void)
{
    int i, j;

    ClrScrn(0x71);
    srand(((unsigned int)time(NULL))|1);

    for (i = 1; i <= ROWS; ++i)
    {
        for (j = 1; j <= COLS; ++j)
        {
            civ1[i][j] = (int)(((__int64)rand()*2)/RAND_MAX);
            disp[i-1][j-1].Char.AsciiChar = civ1[i][j] ? '*' : ' ';
            disp[i-1][j-1].Attributes = 0x71;
        }
    }
    WriteConsoleOutput(console, (CHAR_INFO *)disp, size, src, &dest);
    fill_edges(civ1);
}

int main(int argc, char **argv) {

    int i;

    if ( argc != 1)
        generations = atoi(argv[1]);

    console = GetStdHandle(STD_OUTPUT_HANDLE);
    initialize();
    for (i = 0; i <generations; ++i)
    {
        update_generation(civ1, civ2);
        update_generation(civ2, civ1);
    }
    return EXIT_SUCCESS;
}

If nothing else, this has a ClrScrn function you may find handy.

A: Do not use cout to write to console. Use the WriteConsole from console API instead. And you can use double buffering like in normal graphical animations with SetConsoleActiveScreenBuffer.
http://msdn.microsoft.com/en-us/library/windows/desktop/ms682073.aspx
Also don't use system ("cls") to clear the screen, FillConsoleOutputCharacter is a lot faster.


text:
Q: How to join the circles and line to create line segment in fabric js? [enter image description here](https://i.stack.imgur.com/HEjWG.png)
I am trying to join the circles and line to create line segment in fabric js but unable to do so getting error :-
Element implicitly has an 'any' type because expression of type 'circle1' cant be used to index type 'line'.
circle1['line'] = circle2['line'] = line;
  line['circle1'] = circle1;
  line['circle2'] = circle2;

I am using these dependencies :
Angular CLI : 14.2.7,
Node : 16.14.0,
Package Manager : npm 8.3.1
Angular: 14.2.8
... animations, common, compiler, compiler-cli, core, forms
... platform-browser, platform-browser-dynamic, router.
"fabric": "^5.2.4",
 "@types/fabric": "^4.5.12",

[enter image description here](https://i.stack.imgur.com/9HbgV.png)
I am trying to create line segment by joining two circles an a line in fabric js .
Getting the error which I have explained before.


text:
Q: android- calling Intent from an Inner class i want to call a new activity from within an inner class which is defined in d class which extends Activity....
the piece of written in one of the methods of that Inner class is::
Intent intent = new Intent(this, Test2.class);
       startActivity(intent);
Test2 is placed inside the same package as my main clas is placed and eclipse is showing me d error  "The constructor Intent(test.MyTimer, Class) is undefined".......
what is the solution??

A: I'd pass the parent to the MyTimer class in the constructor then you can pass that to the Intent. The intent requires a class that derives from Context.
So your MyTimer could look like
public class MyActivity extends Activity
{
    private void StartTimer()
    {
        MyTimer timer = new MyTimer(this);
        timer.startIntent();
    }

    private class MyTimer
    {
        private Activity _context;
        public MyTimer(Activity c)
        {
            _context = c;
        }
        public void startIntent()
        {
          Intent i = new Intent(_context, MyActivity.class);
          _context.startActivity(i);
        }
    }
}

Hope that helps.

A: Just use MyActivity.this like so:
Intent i = new Intent(MyActivity.this, MyActivity.class);


text:
Q: Error: no such partition. grub rescue> cannot boot I deleted my linux partition and now im getting the error:
error: no such partition.

grub rescue>

I put my windows 7 installation disk in the cd drive but I can't boot from it as when it says Press any key to boot from CD or DVD.. and I press a key, nothing happens and the grub rescue error comes up again. How do I fix this and I need to know ASAP

A: Sounds like you deleted the partition but didn't use something like gparted so the partition table still thinks it's there.
Is there any other partitions with data on them? If not you could just format the entire drive to solve this problem, if this is not the case attempt to use something like gparted to make sure your partition table is alright or MBR repair to repair any damage.

A: Regarding your boot from CD issue, can you confirm it is a computer issue, not a disc issue. Can you try booting another disc and see if that will boot?
If you can get your Windows 7 disc working, and assuming you already have Windows installed go ahead and try this.
The MBR needs to be restored after uninstalling Linux.


text:
Q: Making div dragable after being inserted from database Wondered if anyone could help me out with this jquery ui drag/drop issue.
I have some draggable and droppable divs that clone themselves when they are dragged over to there container. I am saving the position of the div's in a database, however if I insert the exact same HTML dynamicly and reload the page the div is no longer draggable, droppable etc.
I understand that its because the jQuery is no longer bound to the div...?
So my question, how can I enable the dynamicly inserted div's to be draggable/droppable again?
I did try and implement LiveQuery but could not get it working, how would I use .live?
Here's a URL to the page (link went dead) all the drag/drop etc JS is in custom.js
Any help is really appreciated
Many thanks
EDIT: Anyone have any ideas? I really am stuck on this one :(

A: you just need to call draggable() on the items that are in your tree.  Your existing code does this already for all items having the class drag.
From your code ('custom.js'):
//Make element draggable
$(".drag").draggable( ... );

This doesn't affect the items in your tree, because they don't have the class drag.  An easy fix would be to simply add the class drag to your tree items. Alternately, you could specifically select your tree items somehow, and then apply draggable to that selection.


text:
Q: ProgressDialog is not showing when .3gp file converting to a .zip I am working on Android app.
I need to show a progress dialog box when I click on button.
In that button I am converting video file to .zip file and calculating that file size.
In this process I need to show a ProgressDialog, but it is not showing.
Screen get struck while calculating and after calculation it shows ProgressDialog and then screen navigating to the next screen.
My Code:
    save.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
                    MediaCheck.this.runOnUiThread(new Runnable() {
                        public void run() {
                    pd = ProgressDialog.show(MediaCheck.this, "",
                                    "Checking the video compatability. Please wait", true);
                        }
                    });
                    video_Path= makeZip(video_Path);
                    if (video_Path.equalsIgnoreCase("File size is too large")) {
                        pd.dismiss();
                        Toast.makeText(getApplicationContext(),
                                "Large video", Toast.LENGTH_LONG)
                                .show();
                        return;
                    }
pd.dismiss();
// Doing screen navigation here.
        }
    });

Code to make a zip and know the size
private static String makeZip(String videoPath) {
    byte[] buffer = new byte[1024];
    String[] videoFileName = videoPath.split("/");
    File directory = null;
    try {
        ContextWrapper cw = new ContextWrapper(context_this);
        // path to /data/data/yourapp/app_data/imageDir
        directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
        FileOutputStream fos = new FileOutputStream(directory
                + "/IRCMS_Video.zip");
        ZipOutputStream zos = new ZipOutputStream(fos);
        ZipEntry ze = null;
        ze = new ZipEntry(videoFileName[5]);
        zos.putNextEntry(ze);
        FileInputStream in = new FileInputStream(videoPath);

        int len;

        while ((len = in.read(buffer)) > 0) {
            zos.write(buffer, 0, len);
        }
        File videoZip = new File(directory + "/IRCMS_Video.zip");
        videoLength = videoZip.length() / (1024 * 1024);
        if (videoLength > 3)
            return "File size is too large";
        in.close();
        zos.closeEntry();

        // remember close it
        zos.close();

        System.out.println("Done");

    } catch (IOException ex) {
        ex.printStackTrace();
    }
    return directory.toString() + "/IRCMS_Video.zip";

}
}

Please help...

A: then you should try ASYNCTASK to easily perform your operation and reduce the complexity of using threads
private class Converter extends AsyncTask<String, Void, Void> { //Converter is class name
     protected String doInBackground(String... urls) {
         //THIS METHOD WILL BE CALLED AFTER ONPREEXECUTE
         //YOUR NETWORK OPERATION HERE
         return null;
     }

     protected void onPreExecute() {
         super.onPreExecute();
         //THIS METHOD WILL BE CALLED FIRST
         //DO OPERATION LIKE SHOWING PROGRESS DIALOG PRIOR TO BEGIN NETWORK OPERATION
     }

     protected void onPostExecute(String result) {
         super.onPostExecute();
         //TNIS METHOD WILL BE CALLED AT LAST AFTER DOINBACKGROUND
         //DO OPERATION LIKE UPDATING UI HERE
     }
 }

A: You are doing calculation on UI thread therfore it hangs your app. Do calculation on background thread. You can resolve this by-
save.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                pd = ProgressDialog.show(MediaCheck.this, "",
                        "Checking the video compatability. Please wait", true);
                Thread background = new Thread(new Runnable() {

                    public void run() {
                        // TODO Auto-generated method stub
                        video_Path= makeZip(video_Path);

                        MediaCheck.this.runOnUiThread(new Runnable()
                        {
                            public void run()
                            {

                                if (video_Path.equalsIgnoreCase("File size is too large")) {
                                    pd.dismiss();
                                    Toast.makeText(getApplicationContext(),
                                            "Large video", Toast.LENGTH_LONG)
                                            .show();
                                    pd.dismiss();
                                    return;
                                }
                            }
                        });
                    }
                });
                background.start();
                // Doing screen navigation here.
            }
        });


text:
Q: 16 inch MacBook Pro kernel panic when connected to LG ultrafine display I recently purchased a used LG Ultrafine 24MD4KL-B monitor on eBay. I also got Apple's thunderbolt 3 USB-c cable. The monitor charges my laptop, so I know it has power, but the display itself will not turn on. Strangely, the monitor works fine with my iPad Pro connected, so I know that the display works. Edit: I have tried all four ports on my Macbook as well as another 15 inch Macbook Pro and a Dell laptop, all of which did not work. I have tried restarting and resetting the SMC to no avail. When putting the MacBook to sleep, with the monitor plugged in, and waking it up I was able to get the following kernel panic:
panic(cpu 0 caller 0xffffff8006a9097c): Sleep transition timed out after 180 seconds while entering darkwake on way to sleep. Suspected bundle: com.apple.iokit.IOThunderboltFamily. Thread 0x26e.
Backtracing specified thread
Backtrace (CPU 0), Frame : Return Address
0xffffff81f7cf3900 : 0xffffff8006441868
0xffffff9206a93c80 : 0xffffff800633c4d1
0xffffff9206a93cf0 : 0xffffff800633ad0f
0xffffff9206a93d40 : 0xffffff800632b8d0
0xffffff9206a93d80 : 0xffffff8006a2bbec
0xffffff9206a93dc0 : 0xffffff8006a2d0cb
0xffffff9206a93df0 : 0xffffff7f8713e277
0xffffff9206a93e10 : 0xffffff7f8713deab
0xffffff9206a93e30 : 0xffffff8006a137e4
0xffffff9206a93ea0 : 0xffffff8006a135ea
0xffffff9206a93ec0 : 0xffffff800635c605
0xffffff9206a93f40 : 0xffffff800635c131
0xffffff9206a93fa0 : 0xffffff80062c013e
      Kernel Extensions in backtrace:
         com.apple.iokit.IOThunderboltFamily(7.6.1)[8BAB933D-3D4A-3CBA-B931-5358826BC215]@0xffffff7f8713c000->0xffffff7f8722ffff
            dependency: com.apple.driver.AppleSMC(3.1.9)[AB612149-B321-3B95-8741-B99E79274FCD]@0xffffff7f86da9000

BSD process name corresponding to current thread: kernel_task
Boot args: chunklist-security-epoch=0 -chunklist-no-rev2-dev

Mac OS version:
19G2021

Kernel version:
Darwin Kernel Version 19.6.0: Thu Jun 18 20:49:00 PDT 2020; root:xnu-6153.141.1~1/RELEASE_X86_64
Kernel UUID: 1D3A0F3D-D908-397B-BD16-8F48C0823A2E
Kernel slide:     0x0000000006000000
Kernel text base: 0xffffff8006200000
__HIB  text base: 0xffffff8006100000
System model name: MacBookPro16,1 (Mac-E1008331FDC96864)
System shutdown begun: NO

System uptime in nanoseconds: 223335921325
last loaded kext at 52609271958: >!AThunderboltPCIUpAdapter 2.5.4 (addr 0xffffff7f89906000, size 49152)
loaded kexts:
org.virtualbox.kext.VBoxNetAdp  6.1.4
org.virtualbox.kext.VBoxNetFlt  6.1.4
org.virtualbox.kext.VBoxUSB 6.1.4
org.virtualbox.kext.VBoxDrv 6.1.4
@kext.AMDRadeonX6000    3.1.0
@kext.AMDRadeonServiceManager   3.1.0
>!AGraphicsDevicePolicy 5.2.6
@AGDCPluginDisplayMetrics   5.2.6
@fileutil   20.036.15
>!AHV   1
|IOUserEthernet 1.0.1
|IO!BSerialManager  7.0.6f7
>pmtelemetry    1
>!AUpstreamUserClient   3.6.8
>AGPM   111.4.4
>!APlatformEnabler  2.7.0d0
>X86PlatformShim    1.0.0
@Dont_Steal_Mac_OS_X    7.0.0
>!A!IKBLGraphics    14.0.7
>AGDCBacklightControl   5.2.6
>!AThunderboltIP    3.1.4
>ACPI_SMC_PlatformPlugin    1.0.0
>BridgeAudioCommunication   6.70.7
>!ABacklight    180.3
>!AHIDALSService    1
>!A!ISlowAdaptiveClocking   4.0.0
>!ATopCaseHIDEventDriver    3430.1
>!AMuxControl2  5.2.6
>!AAVEBridge    6.1
>!ABridgeAudio!C    6.70.7
>!AGFXHDA   100.1.429
>!A!ICFLGraphicsFramebuffer 14.0.7
>!AFIVRDriver   4.1.0
>!AMCCSControl  1.14
>!A!IPCHPMC 2.0.1
@filesystems.autofs 3.0
>BCMWLANFirmware4355.Hashstore  1
>BCMWLANFirmware4364.Hashstore  1
>BCMWLANFirmware4377.Hashstore  1
>!ABCMWLANBusInterfacePCIe  1
>!AFileSystemDriver 3.0.1
@filesystems.hfs.kext   522.100.5
@BootCache  40
@!AFSCompression.!AFSCompressionTypeDataless    1.0.0d1
@!AFSCompression.!AFSCompressionTypeZlib    1.0.0
>!AVirtIO   1.0
@filesystems.apfs   1412.141.1
@private.KextAudit  1.0
>!ASmartBatteryManager  161.0.0
>!AACPIButtons  6.1
>!ASMBIOS   2.1
>!AACPIEC   6.1
>!AAPIC 1.7
$!AImage4   1
@nke.applicationfirewall    303
$TMSafetyNet    8
@!ASystemPolicy 2.0.0
|EndpointSecurity   1
>!AThunderboltPCIUpAdapter  2.5.4
@kext.AMDRadeonX6100HWLibs  1.0
@kext.AMDRadeonX6000HWServices  3.1.0
|IOUSBUserClient    900.4.2
|IOAVB!F    850.1
@!AGPUWrangler  5.2.6
>IOPlatformPluginLegacy 1.0.0
>!AHDA!C    283.15
|IOHDA!F    283.15
@kext.AMDRadeonX6000Framebuffer 3.1.0
>!ABacklightExpert  1.1.0
>!AActuatorDriver   3440.1
>!AHIDKeyboard  209
|IOSlowAdaptiveClocking!F   1.0.0
>!AHS!BDriver   3430.1
>IO!BHIDDriver  7.0.6f7
>!AMultitouchDriver 3440.1
>!AInputDeviceSupport   3440.8
>!AThunderboltEDMSink   4.2.3
>!AThunderboltDPOutAdapter  6.2.6
>!AGraphicsControl  5.2.6
>X86PlatformPlugin  1.0.0
|IONDRVSupport  576.1
>!ASMBusPCI 1.0.14d1
|IO!BHost!CUARTTransport    7.0.6f7
|IO!BHost!CTransport    7.0.6f7
>!A!ILpssUARTv1 3.0.60
>!A!ILpssUARTCommon 3.0.60
>!AOnboardSerial    1.0
@kext.AMDSupport    3.1.0
@!AGraphicsDeviceControl    5.2.6
|IOAccelerator!F2   438.7.3
>!ASMBus!C  1.0.18d1
|IOGraphics!F   576.1
>IOPlatformPlugin!F 6.0.0d8
@plugin.IOgPTPPlugin    840.3
|IOEthernetAVB!C    1.1.0
@kext.triggers  1.0
>usb.IOUSBHostHIDDevice 1.2
>usb.cdc.ecm    5.0.0
>usb.cdc.ncm    5.0.0
>usb.cdc    5.0.0
>usb.networking 5.0.0
>usb.!UHostCompositeDevice  1.2
>!ABCMWLANCore  1.0.0
>mDNSOffloadUserClient  1.0.1b8
>IOImageLoader  1.0.0
|IO80211!FV2    1200.12.2b1
>corecapture    1.0.4
|IOSkywalk!F    1
|IOSurface  269.11
@filesystems.hfs.encodings.kext 1
|IOAudio!F  300.2
@vecLib.kext    1.2.0
|IOSerial!F 11
>!AXsanScheme   3
>usb.!UVHCIBCE  1.2
>usb.!UVHCI 1.2
>usb.!UVHCICommonBCE    1.0
>usb.!UVHCICommon   1.0
>!AEffaceableNOR    1.0
|IOBufferCopy!C 1.1.0
|IOBufferCopyEngine!F   1
|IONVMe!F   2.1.0
>!AThunderboltPCIDownAdapter    2.5.4
>!AThunderboltDPInAdapter   6.2.6
>!AThunderboltDPAdapter!F   6.2.6
>!AHPM  3.4.4
>!A!ILpssI2C!C  3.0.60
>!A!ILpssDmac   3.0.60
>!A!ILpssI2C    3.0.60
>!AThunderboltNHI   5.8.6
|IOThunderbolt!F    7.6.1
>usb.!UHostPacketFilter 1.0
|IOUSB!F    900.4.2
>usb.!UXHCIPCI  1.2
>usb.!UXHCI 1.2
>!AEFINVRAM 2.1
>!AEFIRuntime   2.1
>!ASMCRTC   1.0
|IOSMBus!F  1.1
|IOHID!F    2.0.0
$quarantine 4
$sandbox    300.0
@kext.!AMatch   1.0.0d1
>!AKeyStore 2
>!UTDM  489.120.1
|IOSCSIBlockCommandsDevice  422.120.3
>!ACredentialManager    1.0
>!AFDEKeyStore  28.30
>!AEffaceable!S 1.0
>!AMobileFileIntegrity  1.0.5
@kext.CoreTrust 1
|CoreAnalytics!F    1
|IOTimeSync!F   840.3
|IONetworking!F 3.4
>DiskImages 493.0.0
|IO!B!F 7.0.6f7
|IO!BPacketLogger   7.0.6f7
>!ASSE  1.0
>KernelRelayHost    1
>!ASEPManager   1.0.1
>IOSlaveProcessor   1
|IOUSBMass!SDriver  157.140.1
|IOSCSIArchitectureModel!F  422.120.3
|IO!S!F 2.1
|IOUSBHost!F    1.2
>usb.!UCommon   1.0
>!UHostMergeProperties  1.2
>!ABusPower!C   1.0
|IOReport!F 47
>!AACPIPlatform 6.1
>!ASMC  3.1.9
>watchdog   1
|IOPCI!F    2.9
|IOACPI!F   1.4
@kec.pthread    1
@kec.corecrypto 1.0
@kec.Libm   1

Is there anything I might be able to try before I try and call LG support for a repair?
Thanks!


text:
Q: how to install simplejson for python 2.5 on win7 64-bit when I try to install simplejson for Python 2.5 (64-bit distribution) on my box running Win7 64-bit I'm getting this error:

AttributeError: MSVCCompiler instance has no attribute '_ MSVCCompiler__root'

I'm using pip and I've got Python 2.7 64-bit installed as well and I was able to install simplejson for Python 2.7.
Can anyone tell me what I need to do to get around this?
Thanks,


text:
Q: Angular and html5 mode true I have an angular app built on top of Angular-Seed with the add of Express as a web server in order to make it works on Heroku.
Everything is working fine, but I need to introduce the html mode in order to get rid of the "#" symbol in the url. I read that I need some back-end modifications (because when I simply add the html mode, refreshing a page leads to 404 error) but I am not an expert of Node/Express so I don't have a clue on what to do.
Can you please guys help me out?
EDIT:
What I did until now:
Added this line in my angular route:
 $locationProvider.html5Mode(true).hashPrefix('!');

Added this line in my index.html head:
 <base href="/">

Now the css seems to work, but any other url does not!

A: I solved the issue!
I had to change my express server with this code:
var express = require('express');
var app = express();

app.use(express.static(__dirname + '/app'));

app.all('/*', function(req, res) {
    res.sendfile('app/index.html');
});

app.listen(3001);

After that I had to switch from the $cookies to Store directive, here's the reference

A: you have to use base url of html5 to make it works. you can get more info from here
Maybe you missed this one from your head section of html.
<base href="/app/">


text:
Q: Converting some LISP to C# I'm reading Paul Graham's A Plan for Spam and want to understand it better but my LISP is really rusty. He has a snippet of code that calculates probability as such:
(let ((g (* 2 (or (gethash word good) 0)))
      (b (or (gethash word bad) 0)))
   (unless (< (+ g b) 5)
     (max .01
          (min .99 (float (/ (min 1 (/ b nbad))
                             (+ (min 1 (/ g ngood))
                                (min 1 (/ b nbad)))))))))

My question is twofold: (1) is there a web resource that will convert LISP to a different language? (my preference would be a C based language) or failing that (2) can someone rewrite that code snippet in C# for me?

A: Adding on to Gonzola's answer, don't forget that Lisp provides infinite precision integers and rationals, while C# likes to truncate.  You'll need to cast 'nbad' and 'ngood' to float first to get comparable (though not identical) results.
You may also want to put the whole converted program in a checked region.  C# doesn't even warn on fixnum overflow -- the first approximation would be to treat overflow as if you're memory constrained (in Lisp, if overflow yeilds too big a number to fit in remaining memory, similar behavior results).
checked {
    var fbad = (double)nbad;
    var fgood = (double)ngood;
    var g = 2 * (gethash(word, good) | 0);
    var b = gethash(word, bad) | 0;

    if( (g + b) >= 5)
    {
        return Math.Max(
            0.01,
            Math.Min(0.99,
                    Math.Min(1, b / fbad) /
                    (Math.Min(1, g / fgood) + Math.Min(1, b / fbad))));
    }
}

A: I think it's something like this (warning, possible errors ahead. This snippet is intended as a guide, not a solution):
var g = 2 * (gethash(word, good) | 0);
var b = gethash(word, bad) | 0;

if( (g + b) >= 5)
{
    return Math.Max(
        0.01,
        Math.Min(0.99,
            Math.Min(1, b / nbad) /
            (Math.Min(1, g / ngood) + Math.Min(1, b / nbad))));
}


text:
Q: JavaFX Change list of labels on button click I have a list of Labels in a JavaFX app that I've preset with a holder value as such:
for(int i = 0; i < 4; i++) {
  lblUserNames.add(new Label("Username goes here"));
}

and I'm trying to change the label to display the username on the click of a button by using
public void setUsername(int index, String lblUserName) {
   this.lblUserNames.set(index, new Label(lblUserName));
}

But it's still showing the holder text instead of updating to show the usernames; and yet when I print out the list of labels, the values have indeed changed.
I had it working before when I had just an array of labels (Label[]) and could use ".setText(lblUserName). I changed it to an ArrayList so that more users can be added and the code wouldn't have to change much, but now I can't use setText() anymore.
I've seen similar questions for changing the text for just a Label but the solution is to use setText() which won't work with an ArrayList of Labels. Is there any way to update and replace the holder text with the new labels for an ArrayList?

A: When you replace the label in your list, you are not replacing it in the UI. The original label is still shown in the UI. Just call setText(...) on the existing label:
public void setUsername(int index, String lblUserName) {
   this.lblUserNames.get(index).setText(lblUserName);
}


text:
Q: Show that there exist infinitely many $i$ such that $a_i-1$ is divisible by $2^{2015}$ Let $(a_n)$ be a sequence defined by: $a_o=2, a_1=4, a_2=11$ and $\forall n \geq 3$, $$a_n = (n+6)a_{n-1}-3(2n+1)a_{n-2}+9(n-2)a_{n-3}$$
Show that there exist infinitely many $i$ such that $a_i-1$ is divisible by $2^{2015}$

A: $$a_n = (n+6)a_{n-1}-3(2n+1)a_{n-2}+9(n-2)a_{n-3}$$
can be written as
$$a_n-(n+3)a_{n-1}+3(n-1)a_{n-2}=3\left(a_{n-1}-(n+2)a_{n-2}+3(n-2)a_{n-3}\right)$$
So, we can have
$$a_n-(n+3)a_{n-1}+3(n-1)a_{n-2}=-3^{n-1}.$$
This can be written as
$$a_n-na_{n-1}+n\cdot 3^{n-1}=3\left(a_{n-1}-(n-1)a_{n-2}+(n-1)\cdot 3^{n-2}\right).$$
So, we can have
$$a_n-na_{n-1}+n\cdot 3^{n-1}=3^n.$$
This can be written as
$$a_n-3^n=n(a_{n-1}-3^{n-1}).$$
So,
$$a_n-3^n=n!,$$
i.e.
$$a_n=3^n+n!.$$
Now $a_n-1=3^n-1+n!$.
Note here that $3^{2^k}-1$ is divisible by $2^{k+2}$ (you can prove this by induction on $k$). Also, $n!$ is divisible by $i$ at least when $n\ge i$.
Thus, we know that $a_i-1$ is divisible by $2^{2015}$ at least when $i=2^{2015+m}$ where $m=0,1,2,\cdots$.
Hence, it follows from this that there are infinitely many $i$ such that $a_i-1$ is divisible by $2^{2015}$.


text:
Q: C# How can I make the application receive my input I have tried to do a simple Console application in C# where i input a value to get the same amount of stars printed out in console. For example if i input value 5 i console, i would like it to print out 5 stars: *****
1   =>  *
2   =>  **
3   =>  ***
Edit:
enter using System;

using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace kvadrat
{
    class Program
    {
        static void Main(string[] args)
    {
        Console.Write("Hur stor kvadrat vill du ha? ");
        int size = Convert.ToInt32(Console.ReadLine());

        for (int y = 0; y < size; y++)
        {
            for (int x = 0; x < size; x++)
            {
                Console.Write("*");
            }
            Console.WriteLine("");
        }
        Console.ReadKey();
    }
}

}

A: This duplicates what you have. It's unclear in the question what else you need.
string input = Console.ReadLine();
int intValue;
if (int.TryParse(input, out intValue))
{
    Console.WriteLine(new string('*', intValue));
}

A: I got an answer of my question.
        {
        Console.Write("Hur stor kvadrat vill du ha? ");
        int size = Convert.ToInt32(Console.ReadLine());

        for (int y = 0; y < size; y++)
        {
            for (int x = 0; x < size; x++)
            {
                Console.Write("*");
            }
            Console.WriteLine("");
        }
        Console.ReadKey();
    } code here


text:
Q: Как перенести строку в коде SqlCommand command = new SqlCommand("INSERT INTO [Table_tovar] (id_category, name_tovar,price,id_klient,image,id_status,year)
                VALUES(@id_category, @name_tovar, @price, @id_klient, @image, @id_status, @year) ", sqlConnection);

A: Самый простой и быстрый способ - использовать verbatim префикс(символ @)
SqlCommand command = new SqlCommand(@"INSERT INTO [Table_tovar] (id_category, name_tovar,price,id_klient,image,id_status,year)
                VALUES(@id_category, @name_tovar, @price, @id_klient, @image, @id_status, @year) ", sqlConnection);

A: Переносить строку можно двумя способами:

*

*Использовать конкатенацию (+):
string sample = "this is " +
                "a " +
                "string";

*Использовать @ перед началом строки:
string sample = @"this is
a
string";

В этом случае обратите внимание, что если вы решите выровнять строку:
string sample = @"this is
                  a
                  string";

То все пробелы будут включены в нее:
this is                          a                           string


text:
Q: Quasicrystals - Projections from higher dimensional regular crystal lattices Why are quasicrystals projections from higher dimensional regular crystal lattices?
See for example wikipedia:

»Mathematically, quasicrystals have been shown to be derivable from a
  general method, which treats them as projections of a
  higher-dimensional lattice.«

Mathematics aside, is there a physical reason, why this has to be the case?

A: In the modern crystallography there is a notation of aperiodic crystals (or quasicrystals). They are crystals with normal basis $\mathbf a,\mathbf b,\mathbf c$ and a set of propagation (or wave) $\mathbf k$-vectors that are incommensurate with the metric $\mathbf a,\mathbf b,\mathbf c$. The atomic positions (or/and occupancies) are modulated according to $$\vec{x}(t_n)=\vec x_0+\sum_k a\cos(k t_n),$$where $x_0$ is the position in zeroth cell, $\mathbf t$ is a vector pointing to an $n$th cell. The extra dimension is simply the phase $x_4=k t_n/(2\pi)$ for one propagation $\mathbf k$-vector. The idea is that you can recover translational invariance by applying a returning translation along the 4th dimension $x_4$.
For each symmetry operator $A$ of the 3D-space group you can define a returning $\mathrm{phase}(A)/(2\pi)$ which runs from 0 to 1 (for each $\mathbf k$-vector), similar to the 3D-fractional coordinates of atoms. One can then construct a 3D+1 (for one-$\mathbf k$ case) superspace group that fully describes the aperiodic crystal symmetry and structure. There are many experimental examples of aperiodic structures and you can also look at the math behind at e.g. this page , this one and references therein.
There is no principal difference between the situation with one $\mathbf k$-vector and the case with two or three $\mathbf k$-vectors that occurs in quasicrystals. For instance icosahedral phase of $\mathrm{AlMn}$ has 3 $\mathbf k$-vectors that corresponds to 3+3 Bragg indices, i.e. 3D+3=6D space.

A: The QSN and Its Mapping to E8
The Quasicrystalline Spin Network (QSN) is a 3D quasicrystalline point space on which we model physics. The QSN is deeply related to the E8 crystal. The following is a brief explanation of the relationship between the various related objects.
We begin with an 8-dimensional crystal called the E8 lattice. The E8 lattice is an 8D point set representing the densest packing of spheres in 8D. The basic cell of the E8 lattice, the Gosset polytope, has 240 vertices and accurately corresponds to all particles and forces in our (3D) reality and their interactions, specifically the way they can all transform from one to another through a process called gauge symmetry transformation.
FOR GRAPHICS AND FULL ARTICLE:
http://www.quantumgravityresearch.org/portfolio/a-deep-link-between-3d-and-8d
There are many research papers on this website that relate to quasicrystalline mathematics.


text:
Q: MySQL inner join not returning all records I have the following 5 tables
appointments

id
user_id
client_id
date
notes

1
4
8
2022-04-19
test

2
4
16
2022-04-19
test

3
4
29
2022-04-19
test

appointments_services

id
appointment_id
service_id

1
1
7

2
2
10

clients

id
first_name
last_name

8
john
doe

16
john
doe

29
john
doe

users

id
first_name
last_name

4
john
doe

services

id
name
color

7
visit
ff0000

10
charge
ff0000

And I have the following query:
SELECT a.id, a.user_id, a.client_id, a.date, a.notes,

aserv.id AS asid,
aserv.appointment_id AS asappid,
aserv.service_id AS asservid,

c.id AS cid,
c.first_name AS cfirstname,
c.last_name AS clastname,

u.id AS uid,
u.first_name AS ufirstname,
u.last_name AS ulastname,

s.id AS sid,
s.name AS sname,
s.color AS scolor

FROM appointments AS a

INNER JOIN appointments_services AS aserv
ON a.id = aserv.id

INNER JOIN clients AS c
ON a.client_id = c.id

INNER JOIN users AS u
ON a.user_id = u.id

INNER JOIN services AS s
ON aserv.service_id = s.id

with the above query one row (appointment_id 3) will not display because it doesnt have a record in appointments_services table.
How can I change my sql query to display all records even if they dont have a connection within all tables?


text:
Q: Background color and background image below element The idea was to make the not valid error tip that comes up when people fail to fill out a required field show up like a speech bubble. So the arrowhead image shows in the center and underneath the text and would point into the field that they missed.
Fiddle here
HTML:
Please fill the required field.

CSS:
.wpcf7-not-valid-tip {
        background: red;
        color: white;
        padding: 10px;
        width: 100px;
        background-position: 0 0;
        background-repeat: no-repeat;
        background-image: url('http://s24.postimg.org/qacevkf7l/green_error_arrow.png');
}

As you can see I have a background color and the arrow image that needs to sit in the middle of the element and below it but, of course, if you position it using background-position, the image is hidden as it cannot overflow outside of the element itself. This would be easy if I could easily edit the HTML but I would prefer not to as I am using a plugin and want to be free to update the plugin in the future.
QUESTION:
Is there a pure CSS solution?
If not (and I suspect there isnt) what is the cleanest way to solve this issue? Would I use add_filter to alter the html to put a div around the tooltip that i could then add the bg image to? Something with css "content:", a js solution?

A: Got the answer elsewhere.Will accept unless someone can think of something better.
http://jsfiddle.net/D2KFX/2/
This works perfectly using CSS (albeit adding content with the content: declaration) by drawing a triangle with borders instead of using an image for it.
CSS
.wpcf7-not-valid-tip {
        background: red;
        color: white;
        padding: 10px;
        width: 100px;
}
/* Updated code */
.wpcf7-not-valid-tip {
    position: relative;
}
.wpcf7-not-valid-tip:after {
    top: 100%;
    border: solid transparent;
    content: " ";
    height: 0;
    width: 0;
    position: absolute;
    pointer-events: none;
    border-color: rgba(255, 0, 0, 0);
    border-top-color: red;
    border-width: 10px;
    left: 50%;
    margin-left: -10px;
}


text:
Q: Discord.js display only User How do I filter out the bots in this code so that only users are displayed?
const Discord = require('discord.js')
const token = require('./token.json').token
const client = new Discord.Client();

setInterval(async () => {
  let membersCount = client.guilds.cache.map(guild => guild.memberCount).reduce((a, b) => a + b, 0)
  await client.user.setPresence({
    activities: [{
      name: `mit ${membersCount} usern`,
      type: ActivityType.Playing
    }],
    status: "online"
  })
}, 1000 * 60 * 10);

client.login(token)

A: You can use the client.users property then using the Array.prototype.filter() function.
Example:
client.users.cache.filter(user => !user.bot).size

Full Example:
const Discord = require('discord.js')
const token = require('./token.json').token
const client = new Discord.Client();

setInterval(async () => {
  let membersCount = client.users.cache.filter(user => !user.bot).size;
  await client.user.setPresence({
    activities: [{
      name: `mit ${membersCount} usern`,
      type: ActivityType.Playing
    }],
    status: "online"
  })
}, 1000 * 60 * 10);

client.login(token)


text:
Q: How do you submit a Javascript generated bitmap image via POST? If I create a dynamic bitmap on the clientside via javascript, how can I submit this via POST or GET ( and then parse out values from the bitmap on the serverside? NodeJS, PHP etc )
From Making Images Byte-by-Byte in Javascript
var src =  'data:image/bmp;base64,' + myBase64EncodedData;

A: Just upload the base 64 data. Parse it on the server side form there any way you like.
HTML:
<form id="uploadImage" method="POST">
  <input type="hidden" name="imageData64" id="imageData64"/>
  <input type="submit" value="upload"/>
<form>

JS:
document.getElementById('uploadImage').onsubmit = function() {
  document.getElementById('imageData64').value = myBase64EncodedData;
};

Or you could do the same with an ajax request.
You probably don't want to use GET though. Partly because it's not appropriate, you aren't retrieving anything form the server.  But more because GET puts some limits on URL length, so your image data may not fit. POST has no such limit since the request can have a body, unlike GET.

A: You can use post like this..
HTML

Click on button

JS
    $(function() {
        $("#button").click(function() {
              postImageData();
            });
    });

            function postImageData(){
var img = document.getElementById('myimage')
var myBase64EncodedData  = getBase64Image(img);
                $.ajax({
                    type: 'POST',
                    url: 'http://same_domain_url.com/',
                    data: {
                        'imagedata': myBase64EncodedData
                          },
                    success: function(msg){
                        console.log('posted' + msg);
                    }
                });
            }

php
 $imagedata=$_POST['imagedata'];

For getBase64Image function refer to this SO question
Get image data in JavaScript?


text:
Q: Hardware Checks after Air Conditioning Failure We had an overnight air conditioning failure. We discovered that the temperature in the server room had reached about 110-115°F (43-46°C). We powered off everything that hadn't already and had the A/C fixed.
Now that it's fixed, I'm concerned of the damage done by the extended exposure to the high temperature. I'd like to run a series of tests on all of our machines to ensure that machines aren't damaged before we return to relying on them. My plan is as follows:

*

*Run memtest86 to check if any DIMMs were damaged (have already done this and essentially found no issues)

*Run Prime95 to check if any CPUs are damanged (presumably this will come in the form of unexpected interrupts or hardware faults)

*Run smartctl -a and badblocks on all disks and check output for any anomalies

This list feels a little thin, and I'm not confident these will all properly exercise the hardware to ensure we won't run into any heat-induced issues in the future.
Is this battery of tests sufficient? Are there any others I should consider?

A: 46.5 degree celsius.
Start not with a check but reading the paperwork for your main servers.
You will find out that is likely quite within their operating temperatures. No joke. Hardware is done for multiple purposes and there are HOT places on earth - you really want to tell a guy in Texas on a really hot day that no, he NEEDS air conditioning?
Heck, just checking the servers I got:
https://supermicro.com/Aplus/system/1U/1123/AS-1123US-TR4.cfm
Temperature range given to 95 farenheit. And CPU's are temperature throttled - if anything they would have shut down.
You rather should check discs for integrity and make sure the backups are ok - CPU's will not overhead and damage so easily. Not since 15 years or so, since then everyone puts thermal throttling circuits in. I had a couple of CPU Cooler failures and they resulted in the CPU shutting down the mobo FAST.


text:
Q: Re-reflowing a populated PCB I've printed, populated and baked a test PCB with most components that I needed. I left off a GPS chip and associated passives because the GPS chip itself costs more than the rest of the board, and I'm testing unrelated functionality at the moment (and I thought there would be a good chance that I'd have to change something). That said, the stencil was made with the GPS components in mind, and those pads are now covered with solder.
Would simply covering all the pads with flux, populating the components and reflowing again work?
I'm doing all of this by hand, and would prefer to avoid having populate another 100+ BOM lineitem board. The IC itself is an LGA 69 package, and the passives are mostly 0402.

A: If you are only doing a few for your development then I would suggest you manually solder the missing parts on, using an iron or a hot air tool.  Put on the flux as you said and then reflow just the added components.
Modules sometimes try to use a slightly higher temperature solder so the standard reflow profile will not remelt them, however as mentioned in the comments components will not just drop off unless they are heavy and on the bottom of a hot board.
When wave soldering surface mount components it is usual to use a glue dot to hold the parts in place but with IR reflow this is usually not done as it would need a dot dispenser in addition to the solder stencil process.
Multiple reflow cycles are not recommended but I would certainly think that taking the occasional risk may be worth it on a development board, worst case is it does not work.

A: Check if your components can tolerate double reflow. Certain modules cannot (GPS, RF modules etc), most discrete components can (Think a double sided, double loaded PCBs).


text:
Q: R converting data table to integer vector I have some code which, when I run it on one machine, gives me a new data table (segData) with a subset of columns from the original data table (data) as specified within the c(), which is the output I want, but when I run it on a different machine (the one I am currently using), it makes segData an integer vector instead, with the values from inside the c(). It feels like whatever has gone wrong, it's going to be something very obvious as the problem and code are both seemingly trivial. Here is my code:
library(data.table)
data <- fread("segData2.csv")
segData <- data[, c(3:7, 9:15)]

Am I going mad here?


text:
Q: How to connect to MySQL db from python 3 on Ubuntu 16 I'm a new Python developer but have successfully worked with python and mysql on a Windows machine.   I am struggling to figure it out on my new Ubuntu platform (v 16.04).   Here's what I've done .
My machine has both python 2.7 and 3.5 installed in usr/bin
I installed this mysql library
sudo apt-get install python-mysqldb

I got no errors.
I get into python3
and do
import MySQLdb

It gives an error no module named MySQLdb
I get into python (2.7)
The import works and I can do some queries.
So I don't really get what's going on with these multiple versions of python.   I don't want to work in python 2.7.  Did I install a mysqldb that only works in python 2.7?
Assuming the library isn't the correct one,  I went to the Oracle Mysql site and downloaded the correct package for my Ubuntu distro and then tried to install it following their instructions:
sudo dpkg -i mysql-connector-python_2.1.6-1ubuntu16.10_all.deb

This won't install because :
dpkg: regarding mysql-connector-python_2.1.6-1ubuntu16.10_all.deb containing mysql-connector-python:
 mysql-connector-python conflicts with python-mysql.connector
  python-mysql.connector (version 2.0.4-1) is present and installed.
So now I'm in trouble the first package only works in python 2.7 but it's presence seems to now interfere with installing the mysql-connector-python.
I tried running
sudo apt-get remove python-mysqldb

which completes without errors.  But my next attempt at
sudo dpkg -i mysql-connector-python_2.1.6-1ubuntu16.10_all.deb
still fails with the same message.
So I'm confused about a number of things:
Installing things when both pythons are on my machine and knowing which one (or both) they will affect.
Is the mysql-connector from Oracle the preferred one to use for Python 3.5 development?  I saw some mention that it has bugs and that people use this python-mysqldb one instead but then I've seen some mention that it isn't supported for python 3.
So at this point I don't know which to use, how to get rid of what I've installed that is wrong, how to install the correct one.  And then ultimately I'd like to see a couple lines of python that show me how to import the right package and test a connection.

A: I followed the pointer suggested and chose to use mysqlclient because I may want to use Django and because it seems that compatibility with MySQLdb is important- maybe because its some kind of reference implementation of python sql driver...
Anyway Here's what I did.
$sudo apt-get install libmysqlclient-dev
$cd to project dir (myproj)
$virtualenv -p /usr/bin/python3 env
$source env/bin/activate
(env) pip install mysqlclient
(env) deactivate

TO use this python environment:
$source env/bin/activate
(env)python3
>>> import MySQLdb
>>> db = MySQLdb.connect(host="localhost", user="u", passwd="secret", db="mydb")
>>> cur = db.cursor()
>>> cur.execute("select * from a-table")
>>> for row in cur.fetchall():
       print(row[0])
>>> db.close()

A: Python3 only answer.
Django and MySQL can be connected using different packages.
One being python3-pymysql
Step 1:
Run the command:-
    sudo apt-get install python3-pymysql
Step 2:
Create and activate a python 3 virtual enviornment
If you are using virtualenv
    $ `virtualenv -p python3 venv`
    $ `source venv/bin/activate`
    $ `pip install pymysql`

If you are using virtualenvwrapper
    $ `mkvirtualenv venv --python=/usr/bin/python3`
    $ `pip install pymysql`

Step 3:
Import the package and test for connections
 $ python
 >>> import pymysql
 >>> conn = pymysql.connect("localhost", "root", "password", "test_db")
 >>> x = conn.cursor()
 >>> sql = """SELECT * FROM `table1`"""
 >>> x.execute(sql)

A: You can connect with mysql-connector-python library as below:
1: Install mysql connector
`pip install mysql-connector-python`

2: Create yaml or ini file for credentials (say credentials.yml)
 `mysql:
   username: "<username>"
   password: "<password>"
   hostname: "<host>"
   db: "<databaseName>"`

3: Create python class for connecting from mysql
`import mysql.connector
 import yaml

 class MySQLConnection:
     def __init__(self):
         credentials = yaml.load(open("credentials.yml"),
         Loader=yaml.FullLoader)
         self.host = credentials['mysql']['hostname']
         self.user = credentials['mysql']['username']
         self.password = credentials['mysql']['password']
         self.db = credentials['mysql']['db']
         self.conn = mysql.connector.connect(host=self.host,
         user=self.user,
         password=self.password,
         database=self.db)
         print("INFO: Database connected!!!")`


text:
Q: Java - what does annotation referencing itself do? I stumbled across into the source code for the "Documented" Java Annotation recently.  It looks like this:
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Documented {
}

What the purpose of "@Documented" within Documented itself?

A: From the documentation:

Indicates that annotations with a type are to be documented by javadoc and similar tools by default. This type should be used to annotate the declarations of types whose annotations affect the use of annotated elements by their clients. If a type declaration is annotated with Documented, its annotations become part of the public API of the annotated elements.

@Documented is a meta annotation - it annotates another annotation type. When an annotation type is annotated by @Documented, tools like javadoc should include the annotation when it is used somewhere in the code.
For example, the @Deprecated annotation type is annotated with @Documented. It's pretty important to know if something is deprecated, so @Deprecated is considered part of the public API and should be included in the documentation.
On the other hand, @SuppressWarnings is just a hint for the compiler and not important for the API, so it is not annotated by @Documented.
The @Documented annotation type also annotates itself. Basically that just means that you will see any usage of @Documented in the documentation. This is done so that you can see if any annotation type will be documented or not.


text:
Q: ¿ Cómo puedo crear un condicional con dos condiciones de dos variables diferentes en una sola? De ante mano doy las gracias si me podrían orientar en mi función:
Necesito crear una función que cumpla una condición.
Requiero hacer un condicional en donde X es un array de dos columnas y 20 filas, y la condición es que dado t que es un array con dos números:
Ponga 0 si la primera variable de X es menor el primer elemento en t y que la segunda variable en X sea mayor que el segundo elemento en t. En otro caso 1.
El código que tengo es así:
for col in X:
   y_new= X[col].apply(lambda x: 0 if X[:,0] < t[0] else (0 if X[:,1]> t[1] else 1))

X
array([[0.5 , 0.65],
       [0.75, 0.34],
       [0.37, 0.5 ],
       [0.57, 0.74],
       [1.  , 0.69],
       [0.1 , 0.61],
       [0.04, 0.36],
       [0.56, 0.45],
       [0.46, 0.01],
       [0.46, 0.97],
       [0.26, 0.83],
       [0.47, 0.01],
       [0.34, 1.  ],
       [0.85, 0.41],
       [0.  , 0.72],
       [0.66, 0.08],
       [0.3 , 0.19],
       [0.71, 0.  ],
       [0.3 , 0.77],
       [0.17, 0.96]])

Pero no me funciona. ¿Cómo puedo arreglarla?
Gracias.

A: primero hay que recordar que en Python no existen los arrays, salvo que estés trabajando con numpy y la variable X sea de tipo numpy.array, segundo las listas no tienen un metodo apply() solo los DataFrames y no estas trabajando con uno. Por ultimo tu expresión lambda esta mal, incluido X[:,0] (no se para que haces eso). Para tu problema vamos a solucionarlo utilizando la función map() junto a una expresión lambda, para acceder a cada elemento usaremos la sintaxis X[0],X[1] para acceder al primer y segundo elemento correspondientemente.
la funcion map() nos devolverá una lista con los valores obtenidos de acuerdo a la expresión lambda pasada
Por lo que veo comparas con t, por lo tanto si dices que debe ser mayor a 0.5 y menor a 0.3 t=[0.5,0.3]
t = [0.5,0.3]

#pondra 0 si el primer valor es menor que 0.5 el segundo es mayor 0.3, de lo contrario 1
y_new = map(lambda x: 0 if x[0]<0.5 and x[1]>0.3 else 1, X)

#es lo mismo que
#y_new = map(lambda x: 0 if x[0]<t[0] and x[1]>t[1] else 1, X)

#para ver sus elementos lo convertimos a lista
y_new = list(y_new)

#imprimimos
print(y_new)

Dando como resultado
[1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 1, 1, 1, 0, 0]

En un comentario dijiste que era un Numpy.array(), en este caso también funciona la expresión lambda :)
import numpy as np

X = np.array([[0.5 , 0.65],
       [0.75, 0.34],
       [0.37, 0.5 ],
       [0.57, 0.74],
       [1.  , 0.69],
       [0.1 , 0.61],
       [0.04, 0.36],
       [0.56, 0.45],
       [0.46, 0.01],
       [0.46, 0.97],
       [0.26, 0.83],
       [0.47, 0.01],
       [0.34, 1.  ],
       [0.85, 0.41],
       [0.  , 0.72],
       [0.66, 0.08],
       [0.3 , 0.19],
       [0.71, 0.  ],
       [0.3 , 0.77],
       [0.17, 0.96]])

y_new = map(lambda x: 0 if x[0]<0.5 and x[1]>0.3 else 1, X)

#es lo mismo que
#y_new = map(lambda x: 0 if x[0]<t[0] and x[1]>t[1] else 1, X)

y_new = list(y_new)
print(y_new)

Salida
[1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 1, 1, 1, 0, 0]

Si quieres obtener los su valor boleano podemos hacerlo transformándolo con la función bool(), esto mediante una compresión de lista
y_new = [bool(val) for val in y_new]
print(y_new)

Salida
[True, True, False, True, True, False, False, True, True, False, False, True, False, True, False, True, True, True, False, False]

Y como te dije en un comentario puedes negar eso
y_new = [not bool(val) for val in y_new]
print(y_new)

Salida
[False, False, True, False, False, True, True, False, False, True, True, False, True, False, True, False, False, False, True, True]

A: Entendiendo que lo que quieres es lo siguiente:
teniendo un array t = [m1, m2] y un array X = [xn, yn] crear una función que devuelva una lista de ceros y unos la cual se genera por comparar cada columna de X con sus respectivos valores en t, entonces:
from numpy import array

X = array([[0.5 , 0.65],
       [0.75, 0.34],
       [0.37, 0.5 ],
       [0.57, 0.74],
       [1.  , 0.69],
       [0.1 , 0.61],
       [0.04, 0.36],
       [0.56, 0.45],
       [0.46, 0.01],
       [0.46, 0.97],
       [0.26, 0.83],
       [0.47, 0.01],
       [0.34, 1.  ],
       [0.85, 0.41],
       [0.  , 0.72],
       [0.66, 0.08],
       [0.3 , 0.19],
       [0.71, 0.  ],
       [0.3 , 0.77],
       [0.17, 0.96]])

t = array([0.40,0.20])  #valores para prueba

def comparaArray(arr, values):
    resultado = []
    for n1, n2 in arr:
        print(n1 ,' < ',values[0],' and ',n2,' > ',values[1])
        if (n1 < values[0] and n2 > values[1]):
            resultado+=[0]
            print('Agregado al resultado: 0')
        else:
            resultado+=[1]
            print('Agregado al resultado: 1')
    return resultado

print(comparaArray(X,t))
#[1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 0]

Lo que hice fue deconstruir arr en dos variables n1, n2, donde son respectivamente los valores de cada columna de X y compararlas con los valores datos en el array t.
Espero haber entendido bien el asunto y darte una buena respuesta ~
pd: ignoren la cantidad excesiva de prints solo fue para probar la logica

A: Respuesta
Aquí una solución usando solamente numpy, la variable t es cortesía de @Christian
import numpy as np

X = np.array([[0.5 , 0.65], ..., [0.17, 0.96]])
t = np.array([0.5, 0.3]) # Cortesia de @Christian

X = X.transpose()
Y = ~ ( (X[0] < t[0]) & (X[1] > t[1]) ) * 1
print(Y)
# array([1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 1, 1, 1, 0, 0])

Explicación
La idea central reside en X.transpose() es decir convertir las "columnas" en "filas" para operarlas más convenientemente en numpy
array([[0.5 , 0.75, 0.37, 0.57, 1.  , 0.1 , 0.04, 0.56, 0.46, 0.46, 0.26,
        0.47, 0.34, 0.85, 0.  , 0.66, 0.3 , 0.71, 0.3 , 0.17],
       [0.65, 0.34, 0.5 , 0.74, 0.69, 0.61, 0.36, 0.45, 0.01, 0.97, 0.83,
        0.01, 1.  , 0.41, 0.72, 0.08, 0.19, 0.  , 0.77, 0.96]])

Chequemos que implica esta expresión
(X[0] < t[0]) & (X[1] > t[1])
# array([False, False,  True, False, False,  True,  True, False, False,
#        True,  True, False,  True, False,  True, False, False, False,
#        True,  True])

Quiere decir que si estos límites se cumplen deben ser Verdadero... pero se está pidiendo que esto sea cero o dicho de otra forma Falso es por eso que se emplea el operador ~ para negar la expresión.
 ~ ( (X[0] < t[0]) & (X[1] > t[1]) )
 # array([ True,  True, False,  True,  True, False, False,  True,  True,
 #        False, False,  True, False,  True, False,  True,  True,  True,
 #        False, False])

Finalmente, la expresión se multiplica por 1 (*1) para convertir los booleanos a número
 Y = ~ ( (X[0] < t[0]) & (X[1] > t[1]) ) * 1

Nota: En esta respuesta Contar con Python las letras de cada palabra de una cadena comento más sobre este aspecto


text:
Q: Proportion vs. Number of Female Professors I have the following problem, where I am asked to consider two universities $H$ and $Y$, each having $100$ professors.  Construct an example where, in each of the categories "assistant professors", "associate professors", and "full professors", the proportion who are women is higher at $H$ than at $Y$ and yet $Y$ has more female professors than $H$.
It seems that there must be a fourth category (e.g. adjunct), at least at Y and possibly at H.  If not, then take $x_1$ and $y_1$ to be the number of assistant professors at H and Y respectively, $x_2$ and $y_2$ to be the number of associate professors, and $x_3$ and $y_3$ to be the number of full professors.  If $\frac{x_1}{100} \gt \frac{y_1}{100}, \frac{x_2}{100} \gt \frac{y_2}{100}, \textrm{and} \frac{x_3}{100} \gt \frac{y_3}{100}$, then $\frac{x_1+x_2+x_3}{100} \gt \frac{y_1+y_2+y_3}{100}$ and $x_1+x_2+x_3 \gt y_1+y_2+y_3$.  Can someone corroborate or refute this line of argument?

A: Let's say $Y$ has $98$ full professors, $45$ of which are women.  $H$ has two full professors, with one woman.
$Y$ has one professor of each other type, no women.
$H$ has $49$ professors of each other type, and $1$ women associate and one woman assistant.
Then what $H$ has a higher percentage at each level.
But overall, $Y$ has $100$ professors, $45$ of them women. $H$ has $100$ professors, and a mere $3$ of them women.
The overall percentage is a weighted average of the percentages at each level. But the weights are in proportion to the number of professors of each type. So we can make the overall average be close to the "best" percentage for $Y$, while make the overall percentage be close to the worst percentage for $H$.


text:
Q: Merging Arrays Using Javascript I apologise if this question has already been asked on here before but I cant find it.
Im having trouble merging two arrays together and im an absolute beginner with javascript.
I need to do this in pure javascript and not use any library code.
Here is the code;
var greetings = [
  'Hello',
  'Bonjour',
  'Ola',
],

names = {
  'One': 'Bill',
  'Two': 'John',
  'Three': 'Paul',
};

What I would like the result to appear as would be the following in an unordered list as well as each statement being in there own seperate list item;

Hello Bill

Bonjour John

Ola Paul

If anyone could answer this question, as well as comment the code so I can understand how it works that would be perfect.

A: You can not guarantee the order of enumeration when using a for-in statement.
As such, you'd need to have a separate array that specifies the order.
var greetings = [
  'Hello',
  'Bonjour',
  'Ola',
],

names = {
  'One': 'Bill',
  'Two': 'John',
  'Three': 'Paul',
},

order = [
   'One',
   'Two',
   'Three'
],

items = [];

for( var i = 0, len = order.length; i < len; i++ ) {
   items.push( greetings[i] + ' ' + names[ order[i] ] );
}

document.body.innerHTML = ( "

" + items.join("

") + "

" );

But this would be a pain. You should use 2 Arrays instead.
Example: http://jsfiddle.net/rktyF/1/
EDIT: I got rid of the
 since it's unnecessary.

A: Use for … in, e.g. as follows:
var i = 0, lst = [];
for(pos in names) {
  lst.push(greetings[i++] + " " + names[pos]);
}

A: I don't get the point of { 'One': 'Bill', 'Two': 'John', 'Three': 'Paul', }...
Why not [ 'Bill', 'John', 'Paul' ] ?
If you do it that way, it would be :
var ul = document.createElement( 'ul' ),
li;
for ( var i = 0, l = greetings.length; i < l; ++i ) {
    li = document.createElement( 'li' );
    li.innerHTML = greetings[ i ] + ' ' + names[ i ];
    ul.appendChild( li );
}

A: I'm hoping that you mean..
names = ['Bill', 'John', 'Paul'];

..because the names you show in your question isn't an array. It's an object.
Also, for future reference, Array's start at 0, not 1, so..
names[1];

..would be John, even though Bill is first.
var i = 0, // Arrays start at 0.
    ul = document.createElement('ul'), // Create the unordered list.
    greetings = [ 'Hello', 'Bonjour', 'Ola' ], // Make some greetings.
    names = [ 'Bill', 'John', 'Paul' ]; // Make some names.

for (; i < names.length; i++) {
    var li = document.createElement('li'); // Create a list item.

    li.innerHTML = greetings[i] + ' ' + names[i]; // Set the HTML.

    ul.appendChild(li); // Make the list item part of the list.
};

document.body.appendChild(ul); // Put the list inside the body of the document.

That should work.
I have a demo set up here.

A: Seems @patrick beat me to the general solution, but I'll just leave this here anyway:
var greetings = [
  'Hello',
  'Bonjour',
  'Ola'
],

names = {
  'One': 'Bill',
  'Two': 'John',
  'Three': 'Paul'
};

var words = ["One", "Two", "Three", "Four", "Five",
             "Six", "Seven", "Eight", "Nine"];
var i, greet;
var ul = document.createElement("ul");
for (i = 0; greet = greetings[i++];) {
    var li = document.createElement("li");
    li.appendChild(document.createTextNode(
        greet + " " + names[words[i]]))
    ul.appendChild(li);
}

You can now insert ul into the appropriate position in the DOM. Its structure:

Hello John

Bonjour Paul

Ola undefined


text:
Q: Apply viewport width size to a div on hover using Jquery I have three divs lined up horizontally. Each get their width size from a JQuery update size function. But, instead of loading like this, I want them to load at 300px and animate to viewport size on hover (similar to how the opacity animates on hover).
Here's what I have so far:
http://werdnaworks.com/test/

A: On each
s hover animate() both width and opacity. But you also have to set the parent width equal to total
s width so you can keep them inline.
var $div = $('div'),
    divW = $div.width(),//300px
    divLen = $div.length,
    windowW = window.innerWidth;

$('body').width(divW*divLen);

$div.hover(function(){
    $(this).stop().animate({width:windowW, opacity:1},'fast');
    $('body').stop().animate({width:windowW+(divW*divLen-1)},'fast');
},function(){
    $(this).stop().animate({width:divW, opacity:0.5},'fast');
    $('body').stop().animate({width:divW*divLen},'fast');
});

Please see this fiddle.
You may also want to automatically scroll to the
 being hovered. You can do so with animate scrollLeft.
$div.hover(function(){
    var offsetLeft = $(this).offset().left;
    $(this).stop().animate({width:windowW, opacity:1},'fast');
    $('body').stop().animate({width:windowW+(divW*divLen-1), scrollLeft:offsetLeft},'fast');
},function(){
    $(this).stop().animate({width:divW, opacity:0.5},'fast');
    $('body').stop().animate({width:divW*divLen},'fast');
});

Check this fiddle


text:
Q: COMException + background thread + WPF I am trying to use a COM component & activeX component in a WPF application.
I am using these components via the background thread, so UI remains responsive.
But the problem is I sometimes get a COM Exception while using these components. (not always)
Is this expected behavior or am I doing something wrong?
Should I move the code to UI thread, but it ends up being time consuming.
thanks


text:
Q: How do I make a text box in a form not visible until after I click compute in C#? So in the beginning, the user has to input data but in the form. It has textboxes and labels where the answers to the calculations go. I have it so that when it clicks, it computes certain labels and textboxes show up and when the user clicks reset they disappear using:
txtTaxesPaid.Visible = true;

txtTaxesPaid.Visible = false;

My problem is that in the beginning the ones that are not visible. When I click reset they show up. How do I make them not visible in the very beginning?

A: You can set Textboxes Visible property from Properties window in the designer.Or you can do it in Form Load event programatically:
private void Form1_Load(object sender, EventArgs e)
{
   txtTaxesPaid.Visible = false;
}

If you don't see Form Load method just double click your Form in the designer and you will see, or find Load event from Properties > Events window.

A: Option 1: (shortest and most straight forward)
In VS designer of your form - locate those controls and set the visible property to false.
Option 2:
In your form_load event you can set the initial state of your controls.
Option 3:
You can force to invoke the method of the button which already contain the reset commands from your form_load event.
Option 4: (I think is the preferable choice)
- Create a method for reset..
- call the method from form_load or from your "reset" button or anywhere else you want.
private void ResetControls()
{
   txtMyControl.Visible=false;
   //here comes more logic for what to do upon reset.
}

private void form_load(...
{
  ResetControls();
}

private void btnReset_Click(...
{
  ResetControls();
}


text:
Q: JPA2: how to get count between the two ids I have Group table which has columns id, name, timestamp. When there is an update of a group, the timestamp is also updated with current.
I am trying to display the count of groups between two ids using a query.
 Select Count(g) from Area.Group g where g.id between ?2 and ?3 order by g.timestamp desc

The group table has:
        id  name    timestamp
        ==  ====    ======================
        271 News    20170912123733302+0000
        272 Groups  20170831121326734+0000
        273 A law   20170906075010972+0000
        274 Test    20170906135003580+0000
        275 Topic   20170906135139874+0000
        276 Too     20170906135315684+0000
        299 Q       20170911110126882+0000
        300 R       20170911110254626+0000
        301 S       20170911113756910+0000
        302 T       20170911130306836+0000
        303 Test    20170911135557812+0000
        304 Tf      20170911135724170+0000
        305 Ifti    20170911140254131+0000
        306 Ghdu    20170911140358890+0000
        307 Gifts   20170911140751073+0000
        308 It      20170911140752881+0000
        309 E       20170912123713640+0000
        310 Ye      20170911162441817+0000
        311 Asd     20170912052132275+0000

by using the two ids, I am trying to get the count (the order is in decreasing order of timestamp). For example, ids between 271 and 303. The count that I am looking here is 10.
        id  name    timestamp
        ==  ====    ======================
        271 News    20170912123733302+0000
        309 E       20170912123713640+0000
        311 Asd     20170912052132275+0000
        310 Ye      20170911162441817+0000
        308 It E    20170911140752881+0000
        307 Gifs    20170911140751073+0000
        306 Ghdu    20170911140358890+0000
        305 Ifti    20170911140254131+0000
        304 Tf      20170911135724170+0000
        303 Test    20170911135557812+0000

Any help is really appreciated.

A: Group is a reserved  word you should avoid naming table with these words but if you need  then  the word should be inside backtics
Select Count(*) from `Group` g where g.id between ?2 and ?3 order by g.timestamp desc

Once you have corrected  the GROUP column name remain the aspect related  the use of between
NB: the ORDER BY  work  on the result of the select   don't perform a filter ..   so you must count the number of rows between  271 and 303  on the original  raw table data ..
Using the where  ... between on  column g.id mean that the sequence of the values is evaluated  on g.id  column indipendently of the order by you choose .
In fact in your sample looking to the values ordered  by g.id  you have 11 rows


text:
Q: MySQL driver module issue with Movable Type I am able to get mt-check to run, but it says that DBD::MySQL module is not installed.  Here is what it says:
DBI (version >= 1.21)
Your server has DBI installed (version 1.52).

DBD::mysql
Your server does not have DBD::mysql installed, or DBD::mysql requires another module that is not installed. The DBD::mysql database driver is required to use MySQL Database. Please consult the installation instructions for help in installing DBD::mysql.

However, when I run sudo cpan DBD:mysql it says that it is up-to-date:
CPAN: Storable loaded ok (v2.19)
Going to read /Users/.../.cpan/Metadata
Database was generated on Thu, 01 Jul 2010 04:28:19 GMT
DBD::mysql is up to date (4.014).

When I try to run mt.cgi I get an error:
install_driver(mysql) failed: Can't locate DBD/mysql.pm in @INC...

When I checked perl -V (or sudo perl -V) the @INC value doesn't include the path that is listed by cpan for being correctly installed.
Is the issue that it is installed for me (user) rather than the system?  Do I need to reinstall the module?  Have you come across this?
If it helps, I am using Mac OS 10.5.5 with MT 4.3.2.I
Any help is greatly appreciated.
Thanks!

A: I'm posting on this old question because getting Movable Type to run on MacOS X has been a challenge for me, and I am in the business of providing technical support for Movable Type.
Successful installation procedures vary by build of MacOS X. This means that the easiest way to get Movable Type running on MacOS X 10.5.5 may not be the easiest for 10.6 (Snow Leopard), 10.7 (Lion), 10.8 (Mountain Lion), etc.  Successful installation procedures differ if you are running MacOS X Server instead of MacOS X, especially prior to Mountain Lion.
In terms of getting MacOS X 10.5.5 to run Movable Type 4.3x, which was the original question, I'd recommend reading and following Install Movable Type on a Mac written by Beau Smith back in May 2009.  This contains very specific instructions for MacOS X 10.5.5.  I successfully installed Movable Type on that build of MacOS by following these instructions.

A: try running sudo cpan force install DBD::mysql

A: I have had similar experiences as Dave, with configs changing by each version of OSX. The latest issue was after upgrading from Mountain Lion to Mavericks (10.9). I got the same error the original user reported. HaloWebMaster's answer was close to what I needed, but my OSX does not have cpan as an available Terminal command by default, so I resolved it this way:
sudo perl -MCPAN -e shell
# enter password, then hit enter to accept defaults at all prompts if CPAN needs to set up
cpan[1]> install DBD::mysql

This ended with /usr/bin/make install  -- OK, and then I typed exit to exit CPAN shell.
At this point, I reloaded mt.cgi and everything was back to normal.

A: The problem maybe with PERL. I SOLVED this problem using the tutorial - http://codesphpjs.blogspot.com/2015/04/install-movabletype-on-wamp-server.html
installing Strawberry Perl was solution


text:
Q: Awk variable passing question This is the code I wrote to resolve DNSs and output to a file. Is there a way to forgo the while loop entirely and just write in awk? It works perfectly but it seems very cumbersome and inefficient, takes about 10 mins for 25k lines of IPs. Will gladly elaborate on script if clarity is needed.
#!/bin/bash

while read line; do
  echo -en " ${startCount} / ${endCount} IPs resolved\r"
  ip=$(echo ${line} | cut -d "," -f1)
  col2=$(nslookup ${ip} | fgrep "name" | sed -e 's/\t/,/g' -e 's/name = //g' -e 's/.uncc.edu.//g' | cut -d "," -f2)
  if [[ ! -z ${col2} ]]; then
    echo "${line}" | awk -F"," -v var="${col2}" '{print $1","var","$2","$3","$4","$5","$6}' >> ${outFile}
  else
    echo "${line}" | awk -F"," '{print $1",""UNRESOLVED"","$2","$3","$4","$5","$6}' >> ${outFile}
  fi
  ((startCount++))
done < ${1}

A: Try this:
gawk -F, '
    # spawns nslookup as a coprocess, passes the IP into its stdin
    # then reads the output of the coprocess to find the hostname
    function get_name(ip,      line, name) {
        name = "UNRESOLVED"
        print ip |& "nslookup"
        close("nslookup", "to")
        while (("nslookup" |& getline line) > 0) {
            if (match(/name =(.+)\.uncc\.edu\./, line, m))
                name = m[1]
        }
        close("nslookup")
        return name
    }
    { print $1, get_name($1), $2, $3, $4, $5, $6 }
' "$1" > "$outfile"

ref: https://www.gnu.org/software/gawk/manual/html_node/Two_002dway-I_002fO.html


text:
Q: In the Django admin, how can I set up searching profiles by username? I'd like to be able to search user profiles by username in the Django admin. Essentially, in admin.py, I'd be doing something like:
class UserProfileAdmin(admin.ModelAdmin):
   search_fields = ['username']

But this won't work since user is a foreign key in the my usual user profile set up.
Is there a quick way to achieve this without having to add a username field to my UserProfile model?

A: This should do what you want:
class UserProfileAdmin(admin.ModelAdmin):
    search_fields = ['user__username']

assuming the name of your field that is foreignkey is user


text:
Q: Wrong index being used when selecting top rows I have a simple query, which selects top 200 rows ordered by one of the columns filtered by other indexed column. The confusion is why is that the query plan in PL/SQL Developer shows that this index is used only when I'm selecting all rows, e.g.:
SELECT * FROM
(
 SELECT *
 FROM cr_proposalsearch ps
 WHERE UPPER(ps.customerpostcode) like 'MK3%'
 ORDER BY ps.ProposalNumber DESC
)
WHERE ROWNUM <= 200

Plan shows that it uses index CR_PROPOSALSEARCH_I1, which is an index on two columns: PROPOSALNUMBER & UPPER(CUSTOMERNAME), this takes 0.985s to execute:

If I get rid of ROWNUM condition, the plan is what I expect and it executes in 0.343s:

Where index XIF25CR_PROPOSALSEARCH is on CR_PROPOSALSEARCH (UPPER(CUSTOMERPOSTCODE));
How come?
EDIT: I have gathered statistics on cr_proposalsearch table and both query plans now show that they use XIF25CR_PROPOSALSEARCH index.

A: Including the ROWNUM changes the optimizer's calculations about which is the more efficient path.
When you do a top-n query like this, it doesn't necessarily mean that Oracle will get all the rows, fully sort them, then return the top ones.  The COUNT STOPKEY operation in the execution plan indicates that Oracle will only perform the underlying operations until it has found the number of rows you asked for.
The optimizer has calculated that the full query will acquire and sort 77K rows.  If it used this plan for the top-n query, it would have to do a large sort of those rows to find the top 200 (it wouldn't necessarily have to fully sort them, as it wouldn't care about the exact order of rows past the top; but it would have to look over all of those rows).
The plan for the top-n query uses the other index to avoid having to sort at all.  It considers each row in order, checks whether it matches the predicate, and if so returns it.  When it's returned 200 rows, it's done.  Its calculations have indicated that this will be more efficient for getting a small number of rows.  (It may not be right, of course; you haven't said what the relative performance of these queries is.)
If the optimizer were to choose this plan when you ask for all rows, it would have to read through the entire index in descending order, getting each row from the table by ROWID as it goes to check against the predicate.  This would result in a lot of extra I/O and inspecting many rows that would not be returned.  So in this case, it decides that using the index on customerpostcode is more efficient.
If you gradually increase the number of rows to be returned from the top-n query, you will probably find a tipping point where the plan switches from the first to the second.  Just from the costs of the two plans, I'd guess this might be around 1,200 rows.

A: If you are sure your stats are up to date and that the index is selective enough, you could tell oracle to use the index
SELECT  *
FROM   (SELECT /*+ index(ps XIF25CR_PROPOSALSEARCH) */  *
        FROM     cr_proposalsearch ps
        WHERE    UPPER (ps.customerpostcode) LIKE 'MK3%'
        ORDER BY ps.proposalnumber DESC)
WHERE  ROWNUM <= 200

(I would only recommend this approach as a last resort)
If I were doing this I would first tkprof the query to see actually how much work it is doing,
e.g: the cost of index range scans could be way off
forgot to mention....
You should check the actual cardinality:
SELECT count(*)  FROM cr_proposalsearch ps  WHERE UPPER(ps.customerpostcode) like 'MK3%'

and then compare it to the cardinality in the query plan.

A: You don't seem to have a perfectly fitting index. The index CR_PROPOSALSEARCH_I1 can be used to retrieve the rows in descending order of the attribute PROPOSALNUMBER. It's probably chosen because Oracle can avoid to retrieve all matching rows, sort them according to the ORDER BY clause and then discard all rows except the first ones.
Without the ROWNUM condition, Oracle uses the XIF25CR_PROPOSALSEARCH index (you didn't give any details about it) because it's probably rather selective regarding the WHERE clause. But it will require to sort the result afterwards. This is probably the more efficent plan based on the assumption that you'll retrieve all rows.
Since either index is a trade-off (one is better for sorting, the other one better for applying the WHERE clause), details such as ROWNUM determine which execution plan Oracle chooses.

A: This condition:
WHERE UPPER(ps.customerpostcode) like 'MK3%'

is not continuous, that is you cannot preserve a single ordered range for it.
So there are two ways to execute this query:

*

*Order by number then filter on code.

*Filter on code then order by number.

Method 1 is able to user an index on number which gives you linear execution time (top 100 rows would be selected 2 times faster than top 200, provided that number and code do not correlate).
Method 2 is able to use a range scan for coarse filtering on code (the range condition would be something like code >= 'MK3' AND code < 'MK4'), however, it requires a sort since the order of number cannot be preserved in a composite index.
The sort time depends on the number of top rows you are selecting too, but this dependency, unlike that for method 1, is not linear (you always need at least one range scan).
However, the filtering condition in method 2 is selective enough for the RANGE SCAN with a subsequent sort to be more efficient than a FULL SCAN for the whole table.
This means that there is a tipping point: for this condition: ROWNUM <= X there exists a value of X so that method 2 becomes more efficient when this value is exceeded.
Update:
If you are always searching on at least 3 first symbols, you can create an index like this:
SUBSTRING(UPPER(customerpostcode), 1, 3), proposalnumber

and use it in this query:
SELECT  *
FROM    (
        SELECT  *
        FROM    cr_proposalsearch ps
        WHERE   SUBSTRING(UPPER(customerpostcode, 1, 3)) = SUBSTRING(UPPER(:searchquery), 1, 3)
                AND UPPER(ps.customerpostcode) LIKE UPPER(:searchquery) || '%'
        ORDER BY
                proposalNumber DESC
        )
WHERE   rownum <= 200

This way, the number order will be preserved separately for each set of codes sharing first 3 letters which will give you a more dense index scan.