text:
Q: Algorithms and Pseudocode The following function written in pseudocode accepts INCOME as a variable and outputs the TAX corresponding to that income.
FUNCTION TAX (INCOME)

*

*IF (INCOME ≥ 60000) THEN
a. TAXDUE ← 15000

*ELSE
a. IF (INCOME ≥ 30000) THEN

*

*TAXDUE ← 5000

b. ELSE

*

*TAXDUE ← INCOME x 0.08

*RETURN (TAXDUE)
What would be the pseudocode output with an input of:
a) 23000?
b) 64000?
c) 47000?

Here are my answers:
a) 1840
b) 15000
c) 5000
Am I doing this right, or am I missing something?

A: a) INCOME=$23000$ fails IF1, passes to ELSEIF2a, fails so passes to ELSEIFb and stores $23000\times0.08=1840$ in TAXDUE in step 2b1. Control passes to the RETURN statement.
b) INCOME=$64000$ passes IF1, and stores $15000$ in TAXDUE in step 1. Control passes to the RETURN statement.
c) INCOME=$47000$ fails IF1, passes to ELSEIF2a, passes and stores $5000$ in TAXDUE in step 2a1. Control passes to the RETURN statement.
So you are correct. The pseudocode is a bit weak in it's nesting principles and flow control, but as you didn't write it...:)


text:
Q: On a press of the button : Hide keyboard in react-native I have this simple screen
when I press in button the keyboard still apear How can I do this :  " On a press of the button : Hide keyboard" ?

here is my code for button

        manage = () => {
           const { navigate } = this.props.navigation;
        if (this.state.text.length === 10) {

          navigate('service',{text: this.state.text});
        } else {
        Alert.alert('الرجاء ادخال الرقم  الوطني المكون من 10 أرقام')
        }
        }
        <Button   title='التالي'
           backgroundColor="#C1272D"
   onPress={this.manage}>
  </Button>

A: Try this
import { Keyboard } from 'react-native';

Keyboard.dismiss()//Call where ever you needed

Docs here

redpajama_set_name: RedPajamaStackExchange


text:
Q: Eclipse don't display javadoc for javax I can't find out how to make Eclipse (EE Oxygen Release (4.7.0) Build id: 20170620-1800) display javadocs for my Java EE libs (javax.websocket). I get "Note: This element neither has attached source nor attached Javadoc and hence no Javadoc could be found." information.
It works fine for Java SE libs.
Any ideas?
I could add javadoc manually, but I have no idea which one lib it is in eclipse.I have: Apache Tomcat v9.0, EAR Libraries, JRE System Library[jre1.8.0_131], Web App Libraries

A: In my case, I had to go to project -> Properties -> Libraries -> Apache Tomcat ... -> find websocket-api.jar -> attach javadoc here
Found on google info to link it to servlet-api.jar, but it didn't work, so I tried to different jar, and it worked out.


text:
Q: Django python-magic identify ppt,docx,word uploaded file as 'application/zip' I am trying to identify the file type of the files uploaded, after searching, I plan to use the python-magic to check the mime types of a file.
The FileField is used in my models, a ModelForm is used to help save the files.
After all the files have been uploaded, I check the mime type in my python shell
I find that using
magic.from_file("path_to_the_file", mime=True)

woud give the expected mime type for image,txt,pdf files that have been saved.
However, for all the docx, ppt, excel files, it would identify them as 'application/zip'
Can anyone explain why this is happening(the django auto save the ms files as zip??). And is there any good way to make the magic identify the docx, ppt, excel files as they are?
Thank you very much.

A: I too came across this issue recently. Python-magic uses the Unix command file which uses a database file to identify documents (see man file). By default this database does not include instructions on how to identify .docx, .pptx, and .xlsx file types.
You can give additional information to file command to identify these types by adding instructions to /etc/magic (see https://serverfault.com/a/377792).
This should then work:
magic.from_file("path_to_the_file.docx", mime=True)

Returns 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
One thing to note from the python-magic usage instruction on GitHub - this does not seem work for .docx, .pptx, and .xlsx file types (with the additional information in /etc/magic):
magic.from_buffer(open("testdata/test.pdf").read(1024), mime=True)

Returns 'application/zip'
It seems you need to give it more data to correctly identify these file types:
magic.from_buffer(open("testdata/test.pdf").read(2000), mime=True)

Returns 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
I'm not sure of the exact amount needed.


text:
Q: FullCalendar dayRender callback not working correctly Im using fullCalendar 1.6.4 and am having a problem setting custom colors for the weekends and today's cell.
After some searching I found that using the following styling to set background color of the weekend cells would work:
.fc-sat, .fc-sun {
    background-color: #CCCCCC;
}

But it doesn't completely. On the month view it only highlights a couple of pixels at the top and bottom of each weekend cell. in the week and day view it works better by highlighting the entire column with the exception of about 3.5 hours in the middle of the calendar. Even if i scroll the unhighlighted section remains a constant in the middle.
With regards to changing the background color of today, im using the following code:
dayRender: function (date, cell) {
    var today = new Date();
        if (date.getDate() === today.getDate()) {
        cell.css("background-color", "#FF4D4D");
    }
}

This change only works for a fraction of a second when the calendar loads, i can see the change in color very quickly before the original/standard color overrides the change.
Please advise as to what is going on and how i can fix either of these issues.
Thanks in advance,
Grant

A: I haven't looked into the dayRender event, but there should be no problem using plain old CSS to change the colors:
.fc-today{
    background-color: green;
}
.fc-sat, .fc-sun{
    background-color: yellow;
}

See jsfiddle for example, there must be something else conflicting with your styles.
Try right clicking on the day and click "Inspect Element" (on Chrome, others may vary). Look at the td with the class you are trying to style and see whats overwriting your styles.


text:
Q: If/Else statement for Date..iPhone SDK I have this bit of code here. How would I write an if/else statement to determine whether the itemDate has already passed? So if itemDate has already passed, then localnotif.fireDate should be what it is now, plus 86400 (for 24 hours) else leave as is.
NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar];
        NSDateComponents *dateComps = [[NSDateComponents alloc] init];
        [dateComps setDay:item.day];
        [dateComps setMonth:item.month];
        [dateComps setYear:item.year];
        [dateComps setHour:item.hour];
        [dateComps setMinute:item.minute];
        NSDate *itemDate = [calendar dateFromComponents:dateComps];
        [dateComps release];
        UILocalNotification *localNotif = [[UILocalNotification alloc] init];
        if (localNotif == nil)
            return;

        localNotif.fireDate = [itemDate dateByAddingTimeInterval:-(minutesBefore*60)] ;
            NSLog(@"fireDate is %@",localNotif.fireDate);

        localNotif.timeZone = [NSTimeZone defaultTimeZone];

A: *

*You can retrieve the current date using [NSDate date].

*NSDate has this really convenient method called laterDate: that compares a date with the receiver and returns which ever one is later.

*You can see if two dates are equal using isEqual:
In other words:
NSDate * notificationDate = [localNotif fireDate];
NSDate * now = [NSDate date];

if ([[now laterDate:notificationDate] isEqual:now]) {
  //in a comparison between "now" and "notificationDate", "now" is the later date,
  //meaning "notificationDate" has already passed
  notificationDate = [notificationDate dateByAddingTimeInterval:86400];
}
[localNotif setFireDate:notificationDate];


text:
Q: Cocos2d handwriting recognition....HOW...? i am trying to make a game in which i am tying to implement handwriting recognition,
what i exactly want is that when the user slides his finger on the screen a line should be created wherever he slides the finger and when he lifts his finger i want to check that the image which he created matches to any alphabet(a,b,c...z)and if yes then to which alphabet.
i tried drawing the lines using CGSprites but it is leading to a huge fps drop and later crashing of the app if the user keeps sliding his finger,but i have no idea how to recognize it.
can anyone please till me if this is anyway possible,if yes can you please provide me with some idea of how to approach this.
Thanks in Advance

A: For the line drawing I would suggest using basic OpenGL calls to draw the line. Store the points however you want with every touch moved event and then in the draw function for your node you should setup OpenGL state to meet your line drawing needs...
glEnable(GL_LINE_SMOOTH);
glLineWidth(2.5f);

then iterate over your list of points and use something like
ccDrawLine(pA, pB);

to draw the line between those points.
As for using that data to detect letters, that's a very tricky problem. You might want to look for libraries to do that for you. If you're dead set on doing it yourself, then you should start with looking for research papers on handwriting recognition.

A: For drawing the line you can also use CCRibbon
define a CCRibbon and keep a reference to it
you should use a proper image for ribbon
CCRibbon *line = [CCRibbon ribbonWithWidth: image: length: color: fade:];
then in  your touch handler when touch moves add new points to CCRibbon
[line addPointAt: width:];

A: I can think of three different solutions.

*

*Use an existing library. Maybe you will not find one written in Objective-C, but using any C or C++-Library should also be easy. For example you could use AMELiA or Lipi Toolkit.

*Write a Custom Gesture Recognizer for the different letters

*Implement it yourself. You could use neural networks or support vector machines. You can train them with some of the free datasets on the net. Markov Models are also commonly used to solve this problem. However unless you want to learn a lot of theory and have a good knowledge of mathematics I would not recommend this approach.


text:
Q: How to transform one vector drawing in node pdfkit I don't know how to draw two independent vector graphics and apply tranformation on one of them.
My code:
doc.moveTo(0, 20)
    .lineTo(200, 20)
    .rotate(45)
    .stroke();

doc.moveTo(0, 40)
    .lineTo(200, 40)
    .stroke();

All I want is, to have first drawing rotated and the second not. But both are rotated and I cannot find how to transform (rotate, scale) only one of them. Can anybody help, please?

A: Try using the graphics stack save() and restore() methods:
doc.save()
doc.moveTo(0, 20).lineTo(200, 20).rotate(45).stroke()
doc.restore()
doc.moveTo(0, 40).lineTo(200, 40).stroke()

I think methods like rotate() apply to the document, not just the line (this this case), so you can save the graphics stack, make changes, then restore the graphics stack to what it was before.
From : PDFKit - Transformations

The rotate transformation takes an angle and optionally, an object with an origin property. It rotates the document angle degrees around the passed origin or by default, the center of the page.

See: PDFKit - Saving and restoring the graphics stack


text:
Q: link to remove `#` from url without reloading the page I have this sample html page called pound.html

  something after #

  nothing after #

  no # at all

I have added in an alert so that I can tell when the page reloads.
If I click on the first link, the url changes to pound.html#something as expected.  If I click on the second link, it changes to pound.html#, again without reloaded.  But If I click on the third link, while it puts the url back to pound.html (no #) it reloads the page.
I always see single page apps where you have no # when you start up, but once you have gone somewhere else, and then returned to the home page, you are left with #.  Is there a way to make it remove the # from the url without reloading the page (like when you go back to the homepage)?

If you start on pound.html, and then click on the first link and get to pound.html#something, the browser back arrow can get you back to pound.html without reloading the page.
As mentioned in the comments, there are lots of javascript solutions here How to remove the hash from window.location (URL) with JavaScript without page refresh?
However, does anybody know if there is a way to remove to make a link do that?

A: How about:
window.location.hash = '1' // add the `#1` to URL (adds hash if its not already there)
window.location.hash = '' // just leave the `#` symbol in URL
window.history.replaceState(null,document.title,location.href.slice(0, -1))

It'll remove the last character from your URL (in this case, a #)


text:
Q: Is there a good package/library to add Pagination/Sorting/Searching to my table? ASP.NET Core I am new to web development in ASP.NET Core. I have a table with information, I would like to add pagination/sorting/searching to the table. Is there an easy way to add this using some sort of library/package? Thanks

I need pagination, sorting, and searching for my ASP.NET Core table.

A:
I would like to add pagination/sorting/searching to the table. Is
there an easy way to add this using some sort of library/package?

Well, considering all the requirement you can go for jquery data table regardless of simplicity, quick implementation and free subscription. Importantly, its light weight and easy to use.
Here is the compplete example how you can implement that:
Controller:
    [HttpGet]
    public IActionResult ConAction()
    {
        var controlleractionlist = _context.Controller.ToList();
        return Json(controlleractionlist);
    }

Note: I am returning a simple list to demonstrate you , sorting, searching and paging functionality.
View:

            action
            controller
            returnType
            Action

@section scripts {

    <link rel="stylesheet" type="text/css" href="http://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.4/css/jquery.dataTables.css">

}

Output:

You could refer to official document for more details.


text:
Q: minLength 3 on autocomplete and a button to manually search with minLength 0 I'm trying to create an autocomplete functionality where the search is not triggered when less than 3 characters are typed because of the size of the result set. However there are some names that actually only have 1 or 2 letters in their first and last name.
The solution is to allow the user to click the magnifying glass within the input to submit, or 'force through' a query with a 1 or 2 character value.
Here's where I'm at:
HTML:
<input id="mainSearch" class="ui-front" name="mainSearch" type="text" data-role="autocomplete" placeholder="Recognize a UPSer">

jquery:
$('#mainSearch').autocomplete({
    appendTo: ".inputWrapper",
    minLength: 3,
    source: function (request, response) {
        var customer = new Array();
        $.ajax({
            async: false,
            cache: false,
            type: "POST",
            url: "//database//EmployeeDirectory/",
            data: { "filterText": request.term },
            error: function (data) { console.log('Error!'); },
            success: function (data) {
                for (var i = 0; i < data.length ; i++) {
                    customer[i] = {
                        label: data[i].FullName,
                        Id: data[i].UserID
                    };
                }
            }
        });
        response(customer);
    }
});

$('.bgbutton').on('click', function () {
    $('#mainSearch').autocomplete('option', 'minLength', 0);
    $('#mainSearch').autocomplete('search', '');
});

The this works upon first try. But once 2 characters are entered clicking the submit button minLength is then set to 0 for all autocomplete functions. And backspacing to one character will make a full query.
How can both Autocomplete functions have independent minLengths?

A: Without seeing all of your code it's difficult to tell for sure.  But what happens if you immediately reset the minLength to 3 at the end of your button click event?
$('.bgbutton').on('click', function () {
    $('#mainSearch').autocomplete('option', 'minLength', 0);
    $('#mainSearch').autocomplete('search', '');
    $('#mainSearch').autocomplete('option', 'minLength', 3);
});


text:
Q: Converting UIImage to Stream i am using buddy sdk
this sample tells me how to add profile picture, i try with every way but when i try to use this code
client.CreateUserAsync("username","password").ContinueWith(r => { var user = r.Result;

// upload a profile photo
Stream photoStream = GetSomePhoto();
user.AddProfilePhotoAsync(photoStream);
});

This is my Code, but it gives me over array problem
    var img = loginImagePicker.Image.AsPNG().AsStream();
    var hu = await user.AddProfilePhotoAsync(img);

this is the problem

any advice?

A: From your screenshot it seems you issue is not getting the stream, i.e
var img = loginImagePicker.Image.AsPNG().AsStream();

the above line seems to work. The problem is that your SDK, the next call, i.e.:
var hu = await user.AddProfilePhotoAsync(img);

tries to encode something (likely the image) into an URI (see source).
There's a limit on the size of an URI (the exception you're getting) so it's either because there's some bug (URI type or Buddy SDK) or there's a limit on the image size you can provide.
In any case the issue is not related to converting the UIImage to Stream, that part works - the problem is what's done on the Stream later.


text:
Q: ensureAdmin issue in an Express NodeJS server with passport I know there's the following function:
  function ensureAdmin(req, res, next) {
    if (req.user && req.user.username === "admin") {
      return next();
    } else {
      res.send("You do not have access to this web page. Please, contact to the system administrator.");
    }

in order to ensure a page is only accessed by the admin. However, I don't find anywhere how to become a user to admin. I don't know if it is worthwhile to know, but I am using MongoDB.

A: Your middleware is checking a user's username to see if it is an admin.
If you want to create an admin user, in this case, you'll want to create a user whose username is 'admin' -- that user, and only that user, will be able to access any of the ensureAdmin protected routes.


text:
Q: last time procedure executed in Oracle 11g Is it possible to know when a stored procedure was last executed?  I'm using Oracle 11g.
I've got an old app that has many years of procedures in it.  The goal is to quickly identify candidates for retirement.
Thanks,
Mike

A: There's nothing in the data dictionary that records when a package/procedure/function was last executed.
If you have candidates for deletion, you could AUDIT EXECUTE BY SESSION on those, using the DBA_AUDIT_TRAIL data dictionary view to prune the list over time -- and NOAUDIT EXECUTE those objects which get used.


text:
Q: Sonata admin – blank page on production when ModelManagerException is thrown I have defined unique constraint on one property of my entity.
/**
 * @var string
 * @ORM\Column(type="string", length=10, unique=true)
 */
protected $customID;

In Sonata admin, when new object is created with same ID, blank page on production is shown (in dev production, I can see that ModelManagerException is thrown, which is expected result).
How can I display an error on production?

A: Maybe use https://symfony.com/doc/current/reference/constraints/UniqueEntity.html for that field and it will show validation error before saving so no exception will be thrown.
Example:
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;

/**
 * @ORM\Entity
 * @UniqueEntity("customID")
 */
class YourEntity {}


text:
Q: Compile-time error or runtime error for example Class B extends A.
An object A test= new B (x,y);
Then a method that there is only on Class B is invoked on the test object.
Will it be a Compile time error or a run time error?
Overall what are the different between both errors.

A: It's a compile time error. (See here)
A compile time error is when the compiler can't understand what you wanted to do.
There is a lot of conditions to have a compile-time error but basically it's when the syntax you used either confuses the compiler or isn't valid at all.


text:
Q: onClick event can't find function in react mapped object While looping over an object using map() React can't find its own classes property!
Here is the class of the component,
import React, { Component } from 'react';
import './videolists.css';

export default class VideoLists extends Component {

  constructor() {
    super();
  }

  getDefaultLists() {
    return [
      {
        title: 'Iridescent (Official Video) - Linkin Park',
        url: 'https://www.youtube.com/watch?v=xLYiIBCN9ec',
        id: 'xLYiIBCN9ec'
      },
      {
        title: 'Ed Sheeran - I\'m A Mess (x Acoustic Sessions)',
        url: 'https://www.youtube.com/watch?v=-t2CR9qZRj0',
        id: '-t2CR9qZRj0'
      },
      {
        title: 'Ed Sheeran - Lego House [Official Video]',
        url: 'https://www.youtube.com/watch?v=c4BLVznuWnU',
        id: 'c4BLVznuWnU'
      }
    ]
  }

  itemSelected(itemObject) {
    console.log(itemObject);
  }

  render() {
    return (

              {this.getDefaultLists().map(function(item, index){
                return

                          { item.title }

                          { item.url }

;
              })}

    );
  }

}

When a user would click on an item it should call the function called itemSelected and also binding the current this element with this.
But when the application is throughing and error.
Here is the error message:

Uncaught TypeError: Cannot read property 'itemSelected' of undefined(…)

How I can call this function in this case from the loop?

A: you are losing the this context because of your map function. not only do you need to bind that, to get the data object sent though you need to actually tell it to do that. like this.

    {this.getDefaultLists().map( (item, index) => {
        return (

 this.itemSelected(item)}>
                { item.title }

                { item.url }

         );
    })}

you can try shadowing your this context, shouldn't be necessary, but worth a shot.
const self = this;
...

    {self.getDefaultLists().map( (item, index) => {
        return (

 self.itemSelected(item)}>
                { item.title }

                { item.url }

         );
    })}


text:
Q: href link not working after editing css I'm trying to update my friend's website and she needs to keep the Genbook button. I copied and pasted the code from her current site into the code I'm currently writing, and it works fine until I try to format it in CSS. Since I want it centered under her logo I need to edit the CSS. I don't understand why editing the CSS would cause the link to become inactive.
Live preview in Firefox: active and unformatted active link, without CSS (notice mouse cursor)
Live preview in Firefox: inactive and formatted inactive link, with CSS (notice mouse cursor)

#genbook {
  position: absolute;
  top: 210px;
  left: 50px;
}

Now I'm even more confused! It appears to be working on Codepen and Code Snippet. So... why would it work in preview and then not work in preview?
New question: How do I know if it's really working?

A: your code, you postet, was in a  tag and  loaded a different code into your DOM, which does not worked. You can remove it an the noscript and it will work.

#genbook {
  position: absolute;
  top: 210px;
  left: 50px;
}


text:
Q: Lua return custom data from C function Despite searching hard, i couldn't find a valid Lua C API example for calling a Lua function returning custom data from C function.
For example, I have register function "GetMyVector" and then I'm calling that from lua to retrive informations from C, what I got is a table but what I want is something like access to access variable from struct like in C, for example:
local x = GetMyVector()
print(x[1]) -- i
print(x[2]) -- j
print(x[3]) -- k
-- how to access it via like this:
print(x.i)
print(x.j)
print(x.k)

my C function pushing vector in 3 dimensional array by lua_pushnumber:
static int GetMyVector(lua_State *L)
{
    vec3_t vec;
    vec[0] = 1;
    vec[1] = 2;
    vec[3] = 3;
    lua_newtable(L);
    lua_pushnumber(L, vec[0]);
    lua_rawseti(L, -2, 1);
    lua_pushnumber(L, vec[1]);
    lua_rawseti(L, -2, 2);
    lua_pushnumber(L, vec[2]);
    lua_rawseti(L, -2, 3);
    return 1;
}

A: You probably want lua_settable. It allows to set any keys for the table. If the key is literal you can get data by x["i"] or by x.i .
The code should be something like
static int GetMyVector(lua_State *L)
{
    vec3_t vec;
    vec[0] = 1;
    vec[1] = 2;
    vec[3] = 3;
    lua_newtable(L);

    lua_pushliteral(L, "i");
    lua_pushnumber(L, vec[0]);
    lua_settable(L, -2);

    lua_pushliteral(L, "j");
    lua_pushnumber(L, vec[1]);
    lua_settable(L, -2);

    lua_pushliteral(L, "k");
    lua_pushnumber(L, vec[2]);
    lua_settable(L, -2);
    return 1;
}

A: It's a little bit extended, but thanks to @geov I have found what I was looking for, it's kinda similar to properties style like in C# i think, here you go the solution:
#define MYCLASSNAME "vec"

typedef struct {
    int i, j, k;
} MyVec_t;

typedef int(*Xet_func) (lua_State *L, void *v);

/* member info for get and set handlers */
typedef const struct{
    const char *name;  /* member name */
    Xet_func func;     /* get or set function for type of member */
    size_t offset;     /* offset of member within MyVec_t */
}  Xet_reg_pre;

typedef Xet_reg_pre * Xet_reg;

// properties
static int Get_Int(lua_State *L, void *v) {
    lua_pushnumber(L, *(int*)v);
    return 1;
}

static int Set_Int(lua_State *L, void *v) {
    *(int*)v = luaL_checkinteger(L, 3);
    return 0;
}

static int Get_Number(lua_State *L, void *v) {
    lua_pushnumber(L, *(lua_Number*)v);
    return 1;
}

static int Set_Number(lua_State *L, void *v) {
    *(lua_Number*)v = luaL_checknumber(L, 3);
    return 0;
}

static int Get_String(lua_State *L, void *v) {
    lua_pushstring(L, (char*)v);
    return 1;
}

static void Property_Add(lua_State *L, Xet_reg l)
{
    for (; l->name; l++) {
        lua_pushstring(L, l->name);
        lua_pushlightuserdata(L, (void*)l);
        lua_settable(L, -3);
    }
}

static int Property_Call(lua_State *L)
{
    Xet_reg m = (Xet_reg)lua_touserdata(L, -1);
    lua_pop(L, 1);
    luaL_checktype(L, 1, LUA_TUSERDATA);
    return m->func(L, (void *)((char *)lua_touserdata(L, 1) + m->offset));
}

static int index_handler(lua_State *L)
{
    /* stack has userdata, index */
    lua_pushvalue(L, 2);                     /* dup index */
    lua_rawget(L, lua_upvalueindex(1));      /* lookup member by name */
    if (!lua_islightuserdata(L, -1)) {
        lua_pop(L, 1);                         /* drop value */
        lua_pushvalue(L, 2);                   /* dup index */
        lua_gettable(L, lua_upvalueindex(2));  /* else try methods */
        if (lua_isnil(L, -1))                  /* invalid member */
            luaL_error(L, "cannot get member '%s'", lua_tostring(L, 2));
        return 1;
    }
    return Property_Call(L);                      /* call get function */
}

static int newindex_handler(lua_State *L)
{
    /* stack has userdata, index, value */
    lua_pushvalue(L, 2);                     /* dup index */
    lua_rawget(L, lua_upvalueindex(1));      /* lookup member by name */
    if (!lua_islightuserdata(L, -1))         /* invalid member */
        luaL_error(L, "cannot set member '%s'", lua_tostring(L, 2));
    return Property_Call(L);                      /* call set function */
}

static MyVec_t *CheckMyVec(lua_State *L, int index) // get data
{
    MyVec_t *p;
    luaL_checktype(L, index, LUA_TUSERDATA);
    p = (MyVec_t *)luaL_checkudata(L, index, MYCLASSNAME);
    return p;
}

static MyVec_t *PushMyVec(lua_State *L) // push data
{
    MyVec_t *p = (MyVec_t *)lua_newuserdata(L, sizeof(MyVec_t));
    luaL_getmetatable(L, MYCLASSNAME);
    lua_setmetatable(L, -2);
    return p;
}

static int MyVec_Create(lua_State *L)   // C function which will push data
{
    MyVec_t *p;
    p = PushMyVec(L);
    p->i = luaL_checkinteger(L, 1);
    p->j = luaL_checkinteger(L, 2);;
    p->k = luaL_checkinteger(L, 3);;
    return 1;
}

static int MyVec_destroy(lua_State *L)
{
    MyVec_t *p = (MyVec_t *)lua_touserdata(L, 1);
    return 0;
}

static int MyVec_Position(lua_State *L)
{
    MyVec_t *p = CheckMyVec(L, 1);
    double   x = p->i;
    double   y = p->j;
    double   z = p->k;
    if (lua_gettop(L) > 1) {
        p->i = luaL_checknumber(L, 2);
        p->j = luaL_checknumber(L, 3);
        p->k = luaL_checknumber(L, 4);
    }
    lua_pushnumber(L, x);
    lua_pushnumber(L, y);
    lua_pushnumber(L, z);
    return 2;
}

static const luaL_Reg myvec_meta_methods[] = {
    { "__gc", MyVec_destroy },
    { 0, 0 }
};

static const luaL_Reg myvec_methods[] = {
    { "create",  MyVec_Create },
    { "position", MyVec_Position },
    { 0, 0 }
};

static const Xet_reg_pre MyVec_get[] = {
    { "i", Get_Int, offsetof(MyVec_t, i) },
    { "j", Get_Int, offsetof(MyVec_t, j) },
    { "k", Get_Int, offsetof(MyVec_t, k) },
    { 0, 0 }
};

static const Xet_reg_pre MyVec_set[] = {
    { "i", Set_Int, offsetof(MyVec_t, i) },
    { "j", Set_Int, offsetof(MyVec_t, j) },
    { "k", Set_Int, offsetof(MyVec_t, k) },
    { 0, 0 }
};

int MyVec_Register(lua_State *L)
{
    int metatable, methods;

    /* create methods table, & add it to the table of globals */
    luaL_openlib(L, MYCLASSNAME, myvec_methods, 0);
    methods = lua_gettop(L);

    /* create metatable for MyVec_t, & add it to the registry */
    luaL_newmetatable(L, MYCLASSNAME);
    luaL_openlib(L, 0, myvec_meta_methods, 0);  /* fill metatable */
    metatable = lua_gettop(L);

    lua_pushliteral(L, "__metatable");
    lua_pushvalue(L, methods);              /* dup methods table*/
    lua_rawset(L, metatable);               /* hide metatable:
                                            metatable.__metatable = methods */
    lua_pushliteral(L, "__index");
    lua_pushvalue(L, metatable);            /* upvalue index 1 */
    Property_Add(L, MyVec_get);             /* fill metatable with getters */
    lua_pushvalue(L, methods);              /* upvalue index 2 */
    lua_pushcclosure(L, index_handler, 2);
    lua_rawset(L, metatable);               /* metatable.__index = index_handler */

    lua_pushliteral(L, "__newindex");
    lua_newtable(L);                        /* table for members you can set */
    Property_Add(L, MyVec_set);             /* fill with setters */
    lua_pushcclosure(L, newindex_handler, 1);
    lua_rawset(L, metatable);               /* metatable.__newindex = newindex_handler */

    lua_pop(L, 1);                          /* drop metatable */
    return 1;                               /* return methods on the stack */
}


text:
Q: How to merge two dictionaries in javascript I have two arrays of objects:
Array1:
var myArr1 = [];
myArr1["1"]={any:1,some:1};
myArr1["2"]={any:2,some:2};
myArr1["3"]={any:3,some:3};

Array2:
var myArr2 = [];
myArr2["1"]={other:1};
myArr2["2"]={other:2};

And I want them to be merged by their keys into a new Attribute, so the result will be:
[
  {any:1,some:1,myNewAttribute:{other:1}},
  {any:2,some:2,myNewAttribute:{other:2}},
  {any:3,some:3,myNewAttribute:{other:3}}
]

I tried to achieve it with lodash's _.merge() but I failed miserably. _.merge only adds the second array after the first, but does not match their keys / ids.

A: You could map the second array to a new property and merge later.
With lodash

var data1 = [{ any: 1, some: 1 }, { any: 2, some: 2 }, { any: 3, some: 3 }],
    data2 = [{ other: 1 }, { other: 2 }, { other: 3 }];

console.log(_.merge(data1, _.map(data2, x => ({ myNewAttribute: x }))));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script>

With ES6, without lodash

var data1 = [{ any: 1, some: 1 }, { any: 2, some: 2 }, { any: 3, some: 3 }],
    data2 = [{ other: 1 }, { other: 2 }, { other: 3 }];

console.log(data1.map((a, i) => Object.assign({}, a, { myNewAttribute: data2[i] })));

A: You don't need lodash:
myArr1.map((e1, idx) => Object.assign({}, e1, {myNewAttribute: myArr2[idx]}))

You could get fancy and write a little function called map2, which takes two arrays, and invokes a callback with the two elements:
function map2(a1, a2, fn) {
  return a1.map((elt, idx) => fn(elt, a2[idx]);
}

Now you can write the solution as
map2(myArr1, myArr2, (e1, e2) => Object.assign({}, e1, {myNewAttribute: e2}))

From the perspective of program design, what we are doing here is "separating concerns". The first concern is the abstract operation of looping over two arrays in parallel and doing something with each pair of elements. That is what is represented by map2. The second concern is the specific way you want to combine the elements. That is what is represented by the function we are passing to map2. This could be made clearer and somewhat self-documenting by writing it separately:
function combineObjects(e1, e2) {
  return Object.assign({}, e1, {myNewAttribute: e2});
}

map2(myArr1, myArr2, combineObjects);

Of course, in the real world, you'd want to handle the case where the two arrays were of different length, pass an index to the callback as a third parameter for use if necessary, support a third thisArg-type parameter analogous to map, etc.

A: You can do like this:
var first = [{any:1,some:1},{any:2,some:2},{any:3,some:3}];
var second = [{other:1},{other:2},{other:3}];

for(var i = 0; i < first.length; i++){
    if(first[i] && second[i]){
         first[i]['mycustomitem'] = second[i];
    }
}

console.log(first);

A: In order to prove, what I did comment 30 minutes ago -
How to merge two dictionaries in javascript -
there is a possible reduce approach ...
... firstly provided as lodash based example ...

var
    myArr1 = [
        {any: 1, some: 1},
        {any: 2, some: 2},
        {any: 3, some: 3}
    ],
    myArr2 = [
        {other: 1},
        {other: 2}
    ],

    mergedObjectList = _.reduce(myArr1, function (collector, item_1, idx) {
        var
            item_2 = collector[idx],
            merger = _.assign({}, item_1, item_2);

        // or whatever one wants to do to `merger` with `myNewAttribute`

        collector[idx] = merger;

        return collector;

    }, _.clone(myArr2));

console.log("myArr1 : ", myArr1);
console.log("myArr2 : ", myArr2);
console.log("mergedObjectList : ", mergedObjectList);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script>

... and secondly as language core only based example ...

var
    myArr1 = [
        {any: 1, some: 1},
        {any: 2, some: 2},
        {any: 3, some: 3}
    ],
    myArr2 = [
        {other: 1},
        {other: 2}
    ],

    mergedObjectList = myArr1.reduce(function (collector, item_1, idx) {
        var
            item_2 = collector[idx],
            merger = Object.assign({}, item_1, item_2);

        // or whatever one wants to do to `merger` with `myNewAttribute`

        collector[idx] = merger;

        return collector;

    }, Array.from(myArr2));

console.log("myArr1 : ", myArr1);
console.log("myArr2 : ", myArr2);
console.log("mergedObjectList : ", mergedObjectList);

A: Try this function:

function mergeDictionary(_dctn1,_dctn2)
{
   var newDict = [];
   for(var i in _dctn1)
   {
       newDict[i] = _dctn1[i];
   }
   for(var j in _dctn2)
   {
       if(newDict[j] == undefined)
       {
            newDict[j] = _dctn2[j];
       }
       else
       {
            for(var k in _dctn2[j])
            {
                newDict[j][k] = _dctn2[j][k];
            }
       }

   }

   return newDict;
}

var myArr1 = [];
myArr1["1"]={any:1,some:1};
myArr1["2"]={any:2,some:2};
myArr1["3"]={any:3,some:3};

var myArr2 = [];
myArr2["1"]={other:1};
myArr2["2"]={other:2};

console.log(mergeDictionary(myArr1, myArr2));


text:
Q: How to get boolean value if any item in array of arrays is true or false? I have this array, which is user generated and changes over time:
const data = [["2020-09-14","15:00","60","Info","April Tucker","Other","yes"],
["2020-09-14","2:00","50","Text","April Tucker","Other","yes"]]

User picks a date which saves to sessionStorage (for example: 2020-11-21):
sessionStorage.getItem('date')
Then I use forEach method to know if the first item of array item has the same value:
 const checkForConflicts = () => {
    mydata.forEach((element) => {
      element.includes(sessionStorage.getItem('date'))
    })
  }

If I console log that I get boolean value for all item in the array.
How to return only one boolean value, true if checkForConflict returns only false values, or false value if it returned alt least one true value.

A: It might be that one of either Array.prototype.every or Array.prototype.some or even both brings you the right tool at hand.
... simplified example code ...

const data = [
  ["2020-09-14","15:00","60","Info","April Tucker","Other","yes"],
  ["2020-09-14","2:00","50","Text","April Tucker","Other","yes"]
];

console.log(
  'data.every(item => item[0] === "2020-09-14") ? ',
  data.every(item => item[0] === "2020-09-14")
);
console.log(
  'data.some(item => item[0] === "2020-09-14") ? ',
  data.some(item => item[0] === "2020-09-14")
);

data.push(
  ["2020-09-15","2:00","50","Text","April Tucker","Other","yes"]
);

console.log(
  'data.every(item => item[0] === "2020-09-14") ? ',
  data.every(item => item[0] === "2020-09-14")
);
console.log(
  'data.some(item => item[0] === "2020-09-14") ? ',
  data.some(item => item[0] === "2020-09-14")
);
.as-console-wrapper { min-height: 100%!important; top: 0; }

A: Try the some() method:

const checkForConflicts = () => {
    mydata.forEach((element) => {
      element.some(!sessionStorage.getItem('date'))
    })
  }

A: well you dont need use forEach and loop on the data
you can just findIndex of conflicting item -1 mean their is no conflict
const checkForConflicts = () => {
    return data.findIndex((element) => {
      element.includes(sessionStorage.getItem('date'))
    }) !== -1;
  }

Most importantly you have to return value in the function.

A: I would suggest an array of objects, if not, alter this code to look at the first element in the array of arrays.  Note I substituted a local for my test to show it here in a simple manner instead of the sessionStorage

const data = [{
    date: "2020-09-14",
    time: "15:00",
    somenumber: "60",
    cheers: "Info",
    name: "April Tucker",
    "note": "Other",
    says: "yes"
  },
  {
    date: "2020-09-14",
    time: "15:00",
    somenumber: "60",
    cheers: "Info",
    name: "Fred Tucker",
    "note": "Other",
    says: "yes"
  },
  {
    date: "2020-09-13",
    time: "2:00",
    somenumber: "50",
    cheers: "Text",
    name: "April Tucker",
    "note": "Other",
    says: "yes"
  }
];
let testdate = "2020-09-14";
let testdate2 = "2020-09-19";
const checkForConflicts = (item, testme) => {
  // compare as dates to forgive formatting etc.
  return (new Date(item).getTime() === new Date(testme).getTime())
};

// I used .filter in case you need to know how many conflicts but .some() might work also
let hasConflict = !!data.filter(x => checkForConflicts(x.date, testdate)).length;
console.log(hasConflict);

let conflictCount = data.filter(x => checkForConflicts(x.date, testdate)).length;
console.log(conflictCount);

let hasConflict2 = !!data.filter(x => checkForConflicts(x.date, testdate2)).length;
console.log(hasConflict2);


text:
Q: Select size attribute size not working in Chrome/Safari? How to solve problem that select attribute size, like in code:
<select size="2">
    <option value="0" selected="selected">Default</option>
    <option value="1">select 1</option>
    <option value="2">select 2</option>
    <option value="3">select 3</option>
</select>

How can I get it working in Chrome and Safari?

A: This is a known bug in webkit browsers.
The simplest way to get it to work just how you like it in Chrome and Safari would be to manually specify the styling the select itself.
Here is a working jsFiddle.

select {
  height: 36px;
  font-size: 14px;
}
<select size="2">
  <option value="0" selected="selected">Default</option>
  <option value="1">select 1</option>
  <option value="2">select 2</option>
  <option value="3">select 3</option>
</select>

A: Include height: auto and it should work.
<select size="2" style="height: auto">
    <option value="0" selected="selected">Default</option>
    <option value="1">select 1</option>
    <option value="2">select 2</option>
    <option value="3">select 3</option>
</select>

A: I use the size attribute in the HTML for "other" browsers and then specify webkit appearance in CSS. Other types of menu list options are available, textfield is not the only one. And you may need to mess with height based on font size. This makes it look about the same on all browsers.
CSS
select{
  -webkit-appearance: menulist-textfield;
  height: 45px;
}

A: I was able to fix this problem by adding the "multiple" option to the select tag.

A: Try using the css property width of the select tag :
select {
  width:value px;
}


text:
Q: Access Jekyll Website across local wifi I have created a website with jekyll. Currently I am wanting to test my website across multiple devices/computers. I have seen some tutorials and they tell me to do this:
> jekyll serve --host 192.168.0.X

But... When I do that I receive an error code stating:
jekyll 3.1.1 | Error: The Requested address is not valid in its context.
- bind (2) for 192.168.0.X:4000

Any help?
~ Surprisejedi
p.s Oh yeah I replaced the ".X" with a number (if that confused you)

A: That error message suggests that the IP of the computer where you are running jekyll serve is not 192.168.0.X. Make sure you are binding to the same IP where Jekyll executes.
For testing purposes, you can also try to bind to all network interfaces i.e. jekyll serve --host 0.0.0.0


text:
Q: Android libgdx falling objects //this is the UPDATE method
public void update(float delta) {
    handlingInput();

    deltaTime = Gdx.graphics.getDeltaTime();
    timer += deltaTime;
    if (timer >= 1) {
        buttons.add(new Buttons());
        timer -= 1;
    }

    cam.update();

    Iterator<Buttons> butts = buttons.iterator();
    while(butts.hasNext()) {
        Buttons button = butts.next();
        button.update(delta);
        if (button.getPosition().x > Gdx.graphics.getWidth()) {
            butts.remove();
        }
    }
}

This is the render method
public void render(SpriteBatch sb) {
    sb.setProjectionMatrix(cam.combined);
    sb.begin();
    for (Buttons butts: buttons) {
        sb.draw(butts.getButTexture(), butts.getPosition().x, butts.getPosition().y);
    }
    sb.end();
}

and this is the UPDATE of the falling objects
public void update(float delta) {
    position.x += (int) (300 * delta);
}

I have the falling object multiply my delta time so it does not matter if it is lagging. I also tried float, but the problem is that it doesnt go smooth, it just keeps lagging every few miliseconds. I am new and I am unsure of what I am missing!?

A: Have you tried moving the sb.setProjectionMatrix(cam.combined); out of the render method? As far as I know, it can simply be called once, when you create the SpriteBatch, and maybe it's resource expensive and making your game laggy (this might not be the cause, but I can't find anything else which could).


text:
Q: do the iPhone and iPad simulators share the same Documents folder? I'm developing for 6.1 iOS and my app is writing some files to the Documents folder.
When I look at the path to the Documents folder in the debugger, it looks like it is the same folder for both the iPhone and the iPad simulator.
Is that right?   I expected each simulator to have its own Documents folder.

A: Yes, it is right. The path for the documents folder is same.

A: Both simulators share common Documents folder (if both are similar version).
But if they are different versions (Example: iOS 5 iPhone simulator and iOS 6 iPad simulator) then both have two different Documents folder.

A: Path for ipad/iphone is same.
its only change according to ios version like supposed you have run your code for ipad on ios 5 simulator and same code run for iphone on ios 6 simulator than both have different path.

A: yes, they use the same document folder.
In simulator folder is created according the iOS version.


text:
Q: What's the meaning of "messed up"? This is a comment made by an author who used to be a porn store clerk:

I have to say that I thought it was pretty messed up when they stopped providing us with hand sanitizer. I'm not a prude by any means, but working around bodily fluids really isn't the safest thing in the world.

What does messed up mean here?

A: To over-verbalize it, if you will, "messed up" often means "indicative of misguided, mistaken, or just plain wrong thoughts about the matter at hand."
In the sample given, somebody at the company probably thought "if we cut out the hand sanitizer, we'll save thousands of dollars in a year" while totally ignoring the possibility of increased risk of infections or diseases; they mistakenly focused only on the cost instead of the safety.
When used of a person, directly, as in "(so-and-so) is pretty messed up", the same basic sense is there; the person has gotten themselves into a bad situation because of poor choices that they've made, which were avoidable with proper reasoning; and now, most likely, they can't see a way to get themselves out of it.


text:
Q: Help on basic reporting of negative binomial glm output I have run some glm.nb models in R comparing count data between genotypes of animals.
I am new to R and have not run a nb before. It was suggested to me by a colleague and unfortunately now I'm lost.
I just, please, need some simple help and guidance on the correct values to report.
I understand I will be reporting the coefficients, SE and corresponding p values that are generated from:
`Call:
glm.nb(formula = PIRI ~ Treatment_2 + Genotype_2, data = Cfos,
init.theta = 4.608310936, link = log)

Deviance Residuals:
Min       1Q   Median       3Q      Max
-2.8014  -0.6223  -0.1048   0.4419   1.4527

Coefficients:
                 Estimate Std. Error z value Pr(>|z|)
(Intercept)        3.9416     0.1538  25.635   <2e-16 ***
Treatment_2vs WT   0.1169     0.2229   0.525   0.5998
Genotype_2WT      -0.4906     0.2308  -2.125   0.0336 *
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

(Dispersion parameter for Negative Binomial(4.6083) family taken to be 1)

    Null deviance: 34.418  on 27  degrees of freedom
Residual deviance: 29.667  on 25  degrees of freedom
  (1 observation deleted due to missingness)
AIC: 259.61

Number of Fisher Scoring iterations: 1

          Theta:  4.61
      Std. Err.:  1.36

 2 x log-likelihood:  -251.612
Likelihood ratio test
Model 1: PIRI ~ Treatment_2 + Genotype_2
Model 2: PIRI ~ 1
  #Df  LogLik Df  Chisq Pr(>Chisq)
1   4 -125.81
2   2 -128.00 -2 4.3893     0.1114

`
However I'm confused as to why my Chi square is not significant when my variable genotype is.
Further, Treatment and Genotype have 2 levels. How can they both be compared to the 1 intercept?
Again I'm really sorry I know everyone here is more advanced and I need to gain a better understanding of these models, I just really need some guidance.


text:
Q: iphone copyWithZone memory leak - need help I am having a hard time figuring out what I am doing wrong, so I hope someone is able to point me in the right direction.
I am working on an App where you have a array of objects. each of these objects can have a array of objects and therefore (for navigation purpose) have a pointer to its master object.
when i am trying to do a copy of one of these objects i am experiencing a memory leak.
@interface ListItem :  NSObject <NSCopying>  {

    ListItem *MasterItem;
    NSString *strText;
    NSMutableArray *listItems;
    BOOL boolDone;
    NSDate *itemDate;

}

@property (nonatomic, retain) ListItem *MasterItem;

@property (nonatomic, retain) NSString *strText;

@property (nonatomic, retain) NSMutableArray *listItems;

@property (nonatomic, retain) NSDate *itemDate;

@property BOOL boolDone;

@end

@implementation ListItem
@synthesize strText, listItems, boolDone, MasterItem, itemDate;

- (id) init
{
    if ( self = [super init] )
    {
        self.strText = nil;

        self.listItems = nil;

        self.itemDate = nil;

        self.boolDone = FALSE;

        self.MasterItem = nil;
    }
    return self;

}

-(id)copyWithZone:(NSZone *)zone
{

    ListItem *another = [[[self class] allocWithZone:zone] init];

    another.MasterItem = [MasterItem copyWithZone:zone];
    another.listItems = [listItems copyWithZone:zone];
    another.strText = [strText copyWithZone:zone];
    another.itemDate = [itemDate copyWithZone:zone];
    another.boolDone = boolDone;
    return another;
}

-(void) dealloc
{
    if (itemDate != nil)
        [itemDate release];

    if (MasterItem != nil)
        [MasterItem release];

    if (strText != nil)
        [strText release];

    if (listItems != nil)
        [listItems release];

    [super dealloc];
}

@end

when i am calling this, the memory leaks:
ListItem *itemMasterToSave = [itemMaster copy];
[itemMasterToSave release];

A: The line
another.MasterItem = [MasterItem copyWithZone:zone];

should be
another.MasterItem = [[MasterItem copyWithZone:zone] autorelease];

and for every lines of property setting.
Also, you forgot to release NSDate property.
Tips: you do not need to do nil checking because it's taken care by objective c runtime already.


text:
Q: htaccess: how to redirect all pages to a holding page I have to put a site down for about half an hour while we put a second server in place. Using .htaccess, how can I redirect ANY request to domain.com to domain.com/holding_page.php?

A: Options +FollowSymlinks
RewriteEngine on
RewriteCond %{REQUEST_URI} !/holding_page.php$

RewriteRule $ /holding_page.php$l [R=307,L]

Use 307 (thanks Piskvor!) rather than 302 - 307 means:

The requested resource resides
  temporarily under a different URI.
  Since the redirection MAY be altered
  on occasion, the client SHOULD
  continue to use the Request-URI for
  future requests.

A: As I came across this problem, here is the solution I used (brief explanations in the comments):
RewriteEngine On
RewriteBase /

# do not redirect when using your IP if necessary
# edit to match your IP
RewriteCond %{REMOTE_ADDR} !^1\.1\.1\.1

# do not redirect certain file types if necessary
# edit to match the file types needed
RewriteCond %{REQUEST_URI} !\.(jpe?g?|png|gif|css)

# this holding page that will be shown while offline
RewriteCond %{REQUEST_URI} !^/offline\.html$

# use 503 redirect code during the maintenance job
RewriteRule ^(.*)$ /offline.html [R=503,L]
ErrorDocument 503 /offline.html

# bots should retry accessing your page after x seconds
# edit to match your maintenance window
Header always set Retry-After "3600"

# disable caching
Header Set Cache-Control "max-age=0, no-cache, no-store"

Besides the additional conditions and headers, the main idea is to use a 503 status code when you are doing a maintenance job.
The 503 code stands for Service Unavailable, which is exactly the case during the maintenance. Using this will also be SEO friendly as the bots won't index the 503 pages, and they will come back later-on after the specified Retry-After to look for the actual content.
Read more details here:

*

*Use a 503 HTTP status code (from a person who worked at Google) - https://plus.google.com/+PierreFar/posts/Gas8vjZ5fmB

*Redirect Site to Maintenance Page using Apache and HTAccess - http://www.shellhacks.com/en/Redirect-Site-to-Maintenance-Page-using-Apache-and-HTAccess

*HTTP 503: Handling site maintenance correctly for SEO - https://yoast.com/http-503-site-maintenance-seo/

A: This works better...
Options +FollowSymlinks
RewriteEngine on
RewriteCond %{REQUEST_URI} !/holding_page.php$
RewriteRule $ /holding_page.php [R=307,L]


text:
Q: .mdb is not opening when created using java i am creating a .mdb file using java as i am working with MS-ACCESS database files. But i am facing one problem. Suppose a created a file named file.mdb using new File("file.mdb").createNewFile();. No doubt it creates the file successfully, but when i try to open it, it says Unrecognized file. Can you help me?
If you dont know this solution then give me knowledge about any other database which creates database file (e.g. oracle doesnt create database files) so that i can create that file through java and access it.

A: As you have discovered,new File("file.mdb").createNewFile(); creates a zero-length file, and that is not a valid Access database file. Even an "empty" Access database contains system tables and other required information.
If you were using the UCanAccess JDBC driver then you could simply do the following to automatically create the database if it doesn't already exist:
String connStr = "jdbc:ucanaccess://C:/path/to/file.mdb;newdatabaseversion=V2003";
try (Connection conn = DriverManager.getConnection(connStr)) {
    // ... do stuff here
}

For more information on how to set up UCanAccess see
Manipulating an Access database from Java without ODBC
On the other hand, if you absolutely need to stick with the JDBC-ODBC Bridge (which is obsolete and has been removed from Java 8) then you'll probably need to use ADOX code similar to the second example in my related answer here.


text:
Q: Javascript continue statement in while loop causes an infinite loop I'm trying to create a while loop with a continue statement. However it seems to be causing an infinite loop and I can't figure out why.
The code below to me seems like it should start with the var tasksToDo at 3 then decrement down to 0 skipping number 2 on the way.
var tasksToDo = 3
while (tasksToDo > 0) {
    if (tasksToDo == 2) {
        continue;
    }
    console.log('there are ' + tasksToDo + ' tasks');
    tasksToDo--;
}

A: conitnue, will go back to the while loop. and tasksToDo will never get decremented further than 2.
var tasksToDo = 3
while (tasksToDo > 0) {
if (tasksToDo == 2) {
 tasksToDo--;             // Should be here too.
 continue;
}

console.log('there are ' + tasksToDo + ' tasks');
tasksToDo--;
}

A: continue causes the loop to skip the decrement and begin all over again. Once tasksToDo hits 2, it stays 2 forever.

A: continue makes you go back to the beginning of the loop. You probably wanted to use break instead.
Or maybe make your decrement before the if block.

A: It's not very clear what you're doing but from what I understand, you're trying to avoid executing logic inside while for tasksToDo = 2
var tasksToDo = 3
while (tasksToDo > 0) {
    if (tasksToDo != 2) {
        console.log('there are ' + tasksToDo + ' tasks');
    }
    tasksToDo--;
}

It wouldn't make sense to add a break in case tasksToDo = 2 since it would be easier to add that condition to the while (tasksToDo > 2).
Code here might be totally different to your real code though so I could be missing something.

A: you are using continue; that continue your loop forever
use  break; to exit instead of continue;

A: Should it be like this?
var tasksToDo = 3
while (tasksToDo > 0) {
if (tasksToDo == 2) {
 continue;
 console.log('there are ' + tasksToDo + ' tasks');
 }
tasksToDo--;
}

A: The "continue;" statement prevent the execution of all remaining declarations in the code block.
Therefore the "tasksDo--" decrement is not executed after the loop reaches "i == 2" any more.
This creates an infinite loop!
use the "for" loop instead
the "for" loop solution for this case
var tasksToDo;

for (tasksToDo = 3; tasksToDo > 0; tasksToDo--){
    if (tasksToDo == 2) { continue; }
    console.log('there are ' + tasksToDo + ' tasks');
}

(the for loop accepts the decrement as its 3rd statement!)


text:
Q: Can't output data from fetch In general, there is a Left page and the SearchFilms component function, so the problem is that I cannot pull out the result and get it and display it on the left page, the api of the key has been removed on purpose. I'm a beginner, so I don't know how and what to do.
import React, {Fragment, useEffect, useState} from "react";
import {Container, TextField, Typography} from "@material-ui/core";
import SearchFilms from "../companents/searchFilm";

export const Left = () =>{
    const [keyword, setKeyword] = useState ('')
    console.log(setKeyword)
    const [page, setPage] = useState(1)
    console.log(setPage)
    function  handleSearch(e) {
        setKeyword(e.target.value)
        setPage(1)
    }
    SearchFilms(keyword, page)

    return(
        <Fragment>
            <Container fixed style={{paddingTop: "9%"}}>
                <form className="" noValidate autoComplete="off">
                    <TextField id="outlined-basic" label="Поиск" variant="outlined" onChange={handleSearch}/>
                </form>

            </Container>
        </Fragment>
    )
}

import {useEffect, useState} from "react";
import {Typography} from "@material-ui/core";

export default function SearchFilms(keyword, page)  {
    const [data, setData] = useState([]);
    useEffect(() => {
        const headers = {
            'Content-Type': 'application/json',
            'X-API-KEY': '17d4a3d9-ab7d-4038-843b-8a95e22b6c7b'
        }
        fetch(`https://kinopoiskapiunofficial.tech/api/v2.1/films/search-by-keyword?keyword=${keyword}&page=${page}`, {method:'GET',headers:headers})
            .then(response => response.json())
            .then(data => setData())
    }, [keyword, page])
    return (

{data}

    )
}

A: Setting state
You are not passing data to setData: then(data => setData())
Change to:
.then(data => setData(data))

Rendering
Also, if data is an array, you can't render it like {data}. You should map over it:

  {data.map((item, index) => (

 {item}

  )}

One additional thing:
You are not destructuring props: export default function SearchFilms(keyword, page). By default React component gets one argument: props. If your props contain keyword and page keys, destructure them:
export default function SearchFilms({keyword, page})

One more additional thing:
You are not rendering your component SearchFilms. You can't call a react functional component like you do in: SearchFilms(keyword, page)
You should render it like:
return(
        <Fragment>
            ...
          <SearchFilms keyword={keyword} page={page} />
        </Fragment>
    )


text:
Q: change object value in threads using python I am very new to Python, thus am possibly asking a simple question.
I am wrting a multiprocess code with Python:
from multiprocessing import Process
from multiprocessing import Queue

class myClass(object):

    def __init__(self):
        self.__i = 0
        self.__name = 'rob'
        return

    def target_func(self, name, q):
        self.__name = name
        print 'Hello', self.__name
        self.__i += 1
        print self.__i
        q.put([self.__i, self.__name])
        return

    def name(self):
        return self.__name

    def i(self):
        return self.__i

if __name__ == '__main__':
    mc = myClass()

    q = Queue()

    p = Process(target = mc.target_func, args = ('bob', q,))
    p.start()
    ret = q.get()
    p.join()

    p2 = Process(target = mc.target_func, args = ('tom', q,))
    p2.start()
    ret = q.get()
    p2.join()

I expect the print out should be
Hello bob
1
Hello tom
2

But actually, the print out is
Hello bob
1
Hello tom
1    <------------------ Why it's not 2?

May I know what am I wrong?
Many thanks.

A: target_func is called in separated process. mc is copied to each subprocess; not shared between processes.
Using Thread, you will get expected(?) result. For safety you should use lock; I omitted it in following code.
from threading import Thread
from Queue import Queue

....

if __name__ == '__main__':
    mc = myClass()

    q = Queue()

    p = Thread(target = mc.target_func, args = ('bob', q,))
    p.start()
    ret = q.get()
    p.join()

    p2 = Thread(target = mc.target_func, args = ('tom', q,))
    p2.start()
    ret = q.get()
    p2.join()

A: Processes don't share memory, unlike threads. The name __i in the second process refers to a different variable, whose initial value was copied from the original process when you launched the subprocess.
You can use the Value or Array data types to transfer information from one process to another, or you can use the Queue to push data from the subprocess back the the original. All of these classes are included in the multiprocessing module
http://docs.python.org/2/library/multiprocessing.html#multiprocessing.Queue
http://docs.python.org/2/library/multiprocessing.html#multiprocessing.Value
http://docs.python.org/2/library/multiprocessing.html#multiprocessing.Array

A: The value of the variable is still the same since each process you create gets a full copy of the memory space of the parent process, including a copy of the mc class instance that you created earlier. Hence, when you modify the instance variable of mc from within each process, it does not affect the variable in your main process. Here's a more concise example of this behavior:
from multiprocessing import Process

class A(object):

  def __init__(self):
      self.var = 1
      print "Initialized class: ",self

  def test(self):
      print self
      print "Variable value:",self.var
      self.var += 1

if __name__ == '__main__':

  a = A()

  p1 = Process(target = a.test)
  #Creates a copy of the curent memory space and will print "Variable value: 1"
  p1.start()

  p2 = Process(target = a.test)
  #Will still print "Variable value: 1"
  p2.start()


text:
Q: Transition triggert when UIKit accordion is ist triggert I have 2 transitions - 1 for an image, 1 for a DIV. Both transition: all .25s linear; for a smaller size. The transition starts, when the surrounded DIV ist sticked and gets 2 additional UIKit classes.
And I have a UIKit accordion, simple with only 1 <li>.
Now, when the surrounding DIV IS sticked and the elemnts inside have a smaller size and I click the accordion, the transition of the 2 elements is triggert. The elements are getting larger and smaller again.
How can I get the transition of xthe 2 elements not to be triggert when using the accordion?


text:
Q: wait exits after trap I need to handle SIGTERM and keep script running.
#!/bin/bash
trap 'echo do-nothing' SIGTERM
sleep 10m &
wait $!

Why after SIGTERM script exits and how to make it run until sleep 10m & is  finished?

A: Solved with this:
#!/bin/bash

trap 'echo SIGTERM' SIGTERM
sleep 1m &
echo waiting
wait $!
echo Got signal but still waiting
wait $!
echo bye

output:
waiting
SIGTERM
Got signal but still waiting
bye

It will "swallow" one SIGTERM signal and exit after sleep 1m & is finished.

A: The signal will always transfer the execution point away from the wait to the trap, and apparently will pick up at the next statement, having broken the wait.
Maybe this?
#!/bin/bash
trap 'echo nope; wait $pid' term
sleep 10m & pid=$1
wait $pid
echo "Done - exited with code '$?'"
date


text:
Q: how to install previous version of xarray I am reading other's pickle file that may have data type based on xarray. Now I cannot read in the pickle file with the error "No module named core.dataset".
I guess this maybe a xarray issue. My collaborator asked me to change my version to his version and try again.
My version is 0.8.2, and his version 0.8.0. So how can I change back to his version?
Thanks!

A: Use "conda install xarray==0.8.0" if you're using anaconda, or "pip install xarray==0.8.0" otherwise.


text:
Q: Reading from CSV and calculating average (python) I am really struggling with a programming task I have been handed, I have been asked to read from a CSV file which shows the names of beaches and a rating and then work out the average rating. Any help I could get with this would be great also Ithe task given to me am at a beginner level so please don't judge.

A: For reading CSV files, check out Python's standard library csv(https://docs.python.org/3.7/library/csv.html)
This content will have enough tutorials and readings that will guide you through your assignment.
As for taking sums and averages, Python's built-in functions(https://docs.python.org/3.7/library/functions.html) will do you enough good.
If you are stuck with any of them, feel free to add comments.
Good luck!


text:
Q: javascript / css fade out Hi guys not sure if this is java script or CSS but i got a picture inside a box and when the user hover over it it will change colour(Got 4 of these). My question is how do i get it so when the user dose hover over a box everything else fades out.
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">

A: It's javascript... The easiest method is using jQuery. (which, by your other questions, I see you are familiar with).
Assuming all div's have the class meh:
var $mehs = $('.meh');
$mehs.hover(function(){
  $mehs.not(this).fadeTo(200, 0.25);
}, function(){
  $mehs.fadeTo(200, 1);
});

I've used fadeTo(), as this will maintain your layout (fadeOut() will set the element to display:none; and affect your page layout)

A: Something like this:
$(document).ready(function() {
    $(".meh").on('mouseover', function(){
        $("Whatever it is that you want to fade").fadeOut('slow');
    });
});


text:
Q: Get orientation angle from rotation matrix (camera/marker) When i get my rvecs from the function estimatePoseSingleMarkers how can I get the angle for the orientation of my marker ?
On Stackoverflow and others forums, the function Rodrigues seems to be necessary, but I don't understand what exactly the function does.
After apply this function, I understood that I need to convert the result of the function Rodrigues into a euler angles.
I expect to have a float vector representing an angle like 45.6 ° for example.
But I have strange values: 1.68175 -0.133805 -1.5824
For this values, I put my marker in front of my camera so the values does not correspond.
Here my code :
cv::Mat R;
cv::Rodrigues(rvecs[i], R); // R is 3x3

std::vector<float> v = rotationMatrixToEulerAngles(R);
for(size_t i = 0; i < v.size(); i ++)
     std::cout << v[i] << std::endl;

The function rotationMatrixToEulerAngles is from : https://learnopencv.com/rotation-matrix-to-euler-angles, I try others things but I still have strange values, so I don't get it something... I want to have something like [180, 90 ,0] or [45,0,152] etc.
If someone can explain me by steps how from the rvecs I can get a vector of angles (on angle for each axe).
UPDATE :
I test many differents code propose in internet, I read article but I havn't good values.
I got now "good" float values like 190.45 or 80.32 etc. because I multiply by (180/M_PI) but the values are wrong.
When I put my marker in front of my camera, I should have [0 , 0, 0] I think, but I havn't that.
What is the problem ?

A: I found the problem : I need to put rvecs[i][0] [i][1] [i][2] in a vector and then use cv::Rodrigues with this vector and use the function rotationMatrixToEuleurAngles


text:
Q: Why I can't modify border in TableRow? I'm trying to modify the border of a table row with border-radius but it doesn't work!
Here is my code:
function generateTableAntipasti() {
//Build an array containing Customer records.
var antipasti = new Array();
antipasti.push(["Antipasti"]);
antipasti.push(["Patatine"]);
antipasti.push(["Kellogs"]);
antipasti.push(["Ciao"]);
antipasti.push(["Hello"]);
antipasti.push(["Bye"]);

//Create a HTML Table element.
var table = document.createElement("Table");
table.border = "1";
table.className = "Antipasti";
table.cellSpacing = 20;

//Add the data rows.
for (var i = 0; i < antipasti.length; i++) {
    row = table.insertRow(-1);
    var cell = row.insertCell(-1);
    cell.innerHTML = antipasti[i];
}

var dvTable = document.getElementById("dvTable");
dvTable.innerHTML = "";
dvTable.appendChild(table);
}

this is the code for JAVASCRIPT
table {
    width: 100%;
    padding-left: 50px;
    padding-right: 50px;
    border: 0px;
}

tr {
    width: 80%;
    height: 120px;
    border-width: 0px;
    border-color: orange;
    border-radius: 20px;

    box-shadow: 0px 4px 4px 4px #707070;
}

table tr td {
    color: black;
    padding-left: 15px;
    padding-right: 15px;
}

this is the code for CSS
This is the image of the site.1
Thank you so much!


text:
Q: Can't extract next page link using xpath within puppeteer I'm trying to figure out a way to scrape next page link from a webpage using xpath within puppeteer. When I execute the script, I can see that the script gets gibberish result even when the xpath is correct. How can I fix it?
const puppeteer = require("puppeteer");
const base = "https://www.timesbusinessdirectory.com";
let url = "https://www.timesbusinessdirectory.com/company-listings";

(async () => {
    const browser = await puppeteer.launch({headless:false});
    const [page] = await browser.pages();
    await page.goto(url,{waitUntil: 'networkidle2'});
    page.waitForSelector(".company-listing");
    const nextPageLink = await page.$x("//a[@aria-label='Next'][./span[@aria-hidden='true'][contains(.,'Next')]]", item => item.getAttribute("href"));
    url = base.concat(nextPageLink);
    console.log("========================>",url)
    await browser.close();
})();

Current output:
https://www.timesbusinessdirectory.comJSHandle@node

Expected output:
https://www.timesbusinessdirectory.com/company-listings?page=2

A: First of all, there's a missing await on page.waitForSelector(".company-listing");. Not awaiting this defeats the point of the call entirely, but it could be that it incidentally works since the very strict waitUntil: "networkidle2" covers the selector you're interested in anyway, or the xpath is statically present (I didn't bother to check).
Generally speaking, if you're using waitForSelector right after a page.goto, waitUntil: "networkidle2" only slows you down. Only keep it if there's some content you need on the page other than the waitForSelector target, otherwise you're waiting for irrelevant requests that are pulling down images, scripts and data potentially unrelated to your primary target. If it's a slow-loading page, then increasing the timeout on your waitFor... is the typical next step.
Another note is that it's sort of odd to waitForSelector on some CSS target, then try to select an xpath immediately afterwards. It seems more precise to waitForXPath, then call $x on the exact same xpath pattern twice.
Next, let's look at the docs for page.$x:

page.$x(expression)
expression <string> Expression to evaluate.
returns: <Promise<Array<ElementHandle>>>
The method evaluates the XPath expression relative to the page document as its context node. If there are no such elements, the method resolves to an empty array.
Shortcut for page.mainFrame().$x(expression)

So, unlike evaluate, $eval and $$eval, $x takes 1 parameter and resolves to an elementHandle array. Your second parameter callback doesn't get you the href like you think -- this only works on eval-family functions.
In addition to consulting the docs, you can also console.log the returned value to confirm the behavior. The JSHandle@node you're seeing in the URL isn't gibberish, it's the stringified form of the JSHandle object and provides information you can cross-check against the docs.
The solution is to grab the first elementHandle from the array returned by the function and then evaluate on that handle using your original callback:
const puppeteer = require("puppeteer");

const url = "https://www.timesbusinessdirectory.com/company-listings";

let browser;
(async () => {
  browser = await puppeteer.launch({headless: true});
  const [page] = await browser.pages();
  await page.goto(url);
  const xp = `//a[@aria-label='Next']
    [./span[@aria-hidden='true'][contains(.,'Next')]]`;
  await page.waitForXPath(xp);
  const [nextPageLink] = await page.$x(xp);
  const href = await nextPageLink.evaluate(el => el.getAttribute("href"));
  console.log(href); // => /company-listings?page=2
})()
  .catch(err => console.error(err))
  .finally(() => browser?.close())
;

As an aside, there's also el => el.href for grabbing the href attribute. .href includes the base URL here, so you won't need to concatenate. In general, behavior differs beyond delivering the absolute vs relative path, so it's good to know about both options.


text:
Q: ReferenceError - Function not defined when using onchange attribute I'm trying to change the value of an input based on what was selected on a dropdown menu, but it always returns "undefined". Here is the HTML:
<select id="dropdown">
   <option id="AU">Australia</option>
   <option id="CH" >Switzerland</option>
</select>
<input type="text" id="regionInput">

And the JS:
document.getElementById('dropdown').setAttribute("onchange","myFunction()");

function myFunction(){

 var country = document.getElementById('dropdown').options[document.getElementById('dropdown').selectedIndex].text;
 var region = document.getElementById('regionInput').value;

 if (country == "Australia"){
  region = 'test';
   } else {
    region = 'test 2';
  }
}

Any help would be greatly appreciated !

A: It sounds like you're defining the function a local scope of another function. Code called from onXXX attributes is executed in the global scope.
You can use addEventListener and provide a function reference:
document.getElementById('dropdown').addEventListener("change",myFunction);

Notice that the event name doesn't begin with on, and you don't put () after the function name (that will call the function instead of passing a reference).

A: Try removing the quotation mark "" in myFuction() like this: document.getElementById('dropdown').setAttribute("onchange", myFunction() );


text:
Q: Can not connect to my webserver on my own IP Lately I'm having trouble connecting to my VPS Webserver.
Every morning when I try to connect to my webserver via pop ,visit a website that runs on the server or even ping the server, I get no response.
When I connect to the server console via my hosting company's website and let the server reboot everything is fine again.. until the morning after, then I have to reboot it again or else I can't get any connection to it.
This problem is only on my own IP address, not when I try to connect/ping the server from any other IP address (e.g. my neighbours house)
Does anyone have an idea what could cause this?
Server info:

*

*CENTOS 6.6 x86_64 kvm

*Cpanel WHM 11.50.0 (build 23)

A: Are you trying the FQDN or the IP of your server?
You can do a few things to troubleshoot this:

*

*Check that you haven't put your webserver in /etc/hosts with the wrong IP

*Try to connect through the same IP but from a different device e.g. a smartphone connected via your Wi-Fi; if it doesn't work either, the problem is your ISP so you should contact them about the issue

A: I'd suggest to check your firewall on your server. It seems you get automaticaly banned somehow.


text:
Q: Visualize Live animated moving Marker I have a mapping solution that is using OpenStreetMaps, Leaflet JS API and PostGIS Database. I have an API that is called from tracking device. Device send data (Longitude and Latitude) with an interval of 30 seconds. I have plotted the data on the map as marker and draw polyline by joining the marker. Now I need to plot live and animated marker of tracking. I am looking for a a solution similar to the following gif image.

https://i.imgur.com/KrOy634.gif
There is a Plugin of Leaflet JS API Called Moving Marker but I was unable to resolve. It use three parameters (2 location and duration of animation). I can add the location but can not control the duration.
var myMovingMarker = L.Marker.movingMarker([[48.8567, 2.3508],[50.45, 30.523333]],
                        [20000]).addTo(map);

myMovingMarker.start();

What is the best way to visualize the live moving tracking? I know if there is a Speed parameter in device data then it can be possible. Unfortunately there is no Speed parameter from device data.

A: To do this properly I have found that you need to obtain the point to point route and then iterate over the points to animate the marker across the path over the period between your location polling. The basic approach I have used is to obtain the route from the start to end location using a service suchs as OSRM. Typically you will need to translate the encoded polyline into a set of points and then create a timer which updates the marker location periodically to the point in the polyline that is the proportion of the time between location updates. So if you have 300 points in your polyline route between points and your location update is every 30 secs you would set up a timer that triggers each second and moves the marker to the index of the point array at ( secs_since_geocode/30 * number of points ).
This could be smoothed even more be animating the transition from the starting marker location to the new marker location although the approach would need to ensure to be completed before the next timer event moves the marker again.
It's rough and ugly but you can see something that works ( need to wait about 20 secs ) at https://jsfiddle.net/pscott_au/1wt2o9Lw/
Basically what I am trying to achieve is to provide some kind of transition for the marker between getting the location GPS coordinates which would typically be polled at some interval ( say 30 secs ). Ideally you wish to show the marker moving smoothly between the locations in between these updates. If driving you would ideally want to show the marker animating along the expected drive path and so need to obtain a path from a routing service. I am using the public OSRM service although you would ideally set up your own backend for this or use a commercial offering.
So when a new location is obtained the approach is to get the route from the last location to the new location and then step toward that location along the path. More recent OSRM versions include an option to provide the result as a list of lat/lng points so no need to decode the encoded polyline. So just need to create a queue of points and then pop locations off at small interval of say 500ms to move the marker.
The other answer is excellent and provides a good approach to smoothing the animation even further.
 The path is constructed from the returned result as follows:
    $.ajax({
  url: url,
 success: function(data){

 //console.log( 'Got route ' + JSON.stringify(data.route_geometry) );
 // if we assume that we have 30 secs until the next geo location then we need to animate
 // across this path for this duration - to demonstrate we will animate every 2 secs over 20 secs
 // so to calculate the index offset we will divide the number of points in our path by 20
route_geometry = [];
// console.log( data.route_geometry );
var inc_offset = $(data.route_geometry ).size() / 20;
for (i = 0; i < 20; i++) {
   console.log(i + ' x inc_offset of ' + inc_offset );
   route_geometry.push( data.route_geometry[ Math.round(i*inc_offset ) ] );
 }

 }
});

Over the next couple of days I will refine and clean this up and then update this answer.

A: Your code works for me, see http://playground-leaflet.rhcloud.com/tozo/edit?html,output

I can add the location but can not control the duration.

Erm, it's the second parameter, with a value of 20000 msecs?


text:
Q: How to read not unique named ranges from the one of the sheet of workbook How to read the named range from one of the sheet in workbook.Named range is present in multiple sheet of workbook with same name.
I tried with the workbook as a whole,not able to set the scope at sheet level
String cname = "TestName";
Workbook wb = getMyWorkbook(); // retrieve workbook

// retrieve the named range
int namedCellIdx = wb.getNameIndex(cellName);
Name aNamedCell = wb.getNameAt(namedCellIdx);

// retrieve the cell at the named range and test its contents
AreaReference aref = new AreaReference(aNamedCell.getRefersToFormula());
CellReference[] crefs = aref.getAllReferencedCells();
for (int i=0; i<crefs.length; i++) {
    Sheet s = wb.getSheet(crefs[i].getSheetName());
    Row r = sheet.getRow(crefs[i].getRow());
    Cell c = r.getCell(crefs[i].getCol());
    // extract the cell contents based on cell type etc.
}


text:
Q: Select MySQL Month() for null column Got a question to ask. How do i get to list all of my left table to display the data when i use the left join even when some row got null value in it?
Heres my query:
SELECT *, SUM(transactions.debit_credit) current_spending
FROM (`budget`) LEFT JOIN `categories` ON `budget`.`category`=`categories`.`idcategory`
LEFT JOIN `user_category` ON `budget`.`category`=`user_category`.`idcategory`
LEFT JOIN `category_transaction` ON `budget`.`category`=`category_transaction`.`idcategory`
LEFT JOIN `transactions` ON `category_transaction`.`idtransaction`=`transactions`.`idtransaction`
WHERE `user_category`.`iduser` = '1'
AND MONTH(transactions.transaction_date) = '11'
GROUP BY `budget`.`idbudget`;

When I remove AND MONTH(transactions.transaction_date) = '11' the query works fine accept it displays all data instead of just 1 month of transaction.
Help?? Please?? Any idea how??

A: Your where clause turns your left join into an inner join because you filter the data on a condition of a joined table.
Instead put that condition in the on clause of your join
SELECT *, SUM(transactions.debit_credit) current_spending
FROM (`budget`)
LEFT JOIN `categories` ON `budget`.`category`=`categories`.`idcategory`
LEFT JOIN `user_category` ON `budget`.`category`=`user_category`.`idcategory`
                         AND `user_category`.`iduser` = '1'
LEFT JOIN `category_transaction` ON `budget`.`category`=`category_transaction`.`idcategory`
LEFT JOIN `transactions` ON `category_transaction`.`idtransaction`=`transactions`.`idtransaction`
                        AND MONTH(transactions.transaction_date) = '11'
GROUP BY `budget`.`idbudget`;


text:
Q: Dagger 2 injecting parameters of constructor I saw the following example on the Dagger 2 website:
class Thermosiphon implements Pump {
  private final Heater heater;

  @Inject
  Thermosiphon(Heater heater) {
    this.heater = heater;
  }

  ...
}

and the documentation:

When a new instance is requested, Dagger will obtain the required
  parameters values and invoke this constructor.

When I write a Module to provide a Thermosiphon like
@Module
public class ThermosiphonModule {

    @Provides
    @Singleton
    Thermosiphon provideThermosiphon() {
        return new Thermosiphon(???);
    }

}

the Thermosiphon constructor still requires a Heater as an argument, rendering the whole 'automatic injection of constructor dependencies' useless.
I tried
return new Thermosiphon(null);

and
return new Thermosiphon();

(empty constructor) and hoped for Dagger2 to pick up that I wanted the missing Heater to be injected, yet the Heater of the provided Thermosiphon is always null;
I verified though my HeaterComponent / HeaterModule are working fine and are able to provide a Heater.
Do I completey misunderstand the whole feature of 'Dagger satisfies constructor dependencies for you' or am I missing something?

A: If you're using modules, then if you have two provider modules bound to the same component, then you'll be able to allow them to see the heater as a constructor parameter.
@Module
public class HeaterModule {
    @Provides
    @Singleton
    Heater heater() {
        return new Heater(); // if not using @Inject constructor
    }
}

@Module
public class ThermosiphonModule {
    @Provides
    @Singleton
    Thermosiphon thermosiphon(Heater heater) {
        return new Thermosiphon(heater); // if not using @Inject constructor
    }
}

@Singleton
@Component(modules={ThermosiphonModule.class, HeaterModule.class})
public interface SingletonComponent {
    Thermosiphon thermosiphon();
    Heater heater();

    void inject(Something something);
}

public class CustomApplication extends Application {
    private SingletonComponent singletonComponent;

    @Override
    public void onCreate() {
        super.onCreate();
        this.singletonComponent = DaggerSingletonComponent.builder().build(); //.create();
    }

    public SingletonComponent getSingletonComponent() {
        return singletonComponent;
    }
}

But with constructor injection, you will also be able to provide objects of that given scope, or unscoped objects, as long as they have a @Inject constructor.
For example,
@Singleton
@Component // no modules
public interface SingletonComponent {
    Thermosiphon thermosiphon();
    Heater heater();

    void inject(Something something);
}

And
@Singleton
public class Heater {
    @Inject
    public Heater() {
    }
}

And
@Singleton
public class Thermosiphon {
    private Heater heater;

    @Inject
    public Thermosiphon(Heater heater) {
        this.heater = heater;
    }
}

Or
@Singleton
public class Thermosiphon {
    @Inject
    Heater heater;

    @Inject
    public Thermosiphon() {
    }
}

A: For one, since you've annotated the constructor of Thermosiphon with @Inject, you don't need an @Provides method. Dagger uses this constructor to create an instance when needed. Just annotate the Thermosiphon class itself with @Singleton to preserve the singleton behavior.
If you do want to use an @Provides method, and to answer your question fully, you can specify the Heater as a parameter to the method:
@Module
public class ThermosiphonModule {

    @Provides
    @Singleton
    Thermosiphon provideThermosiphon(Heater heater) {
        return new Thermosiphon(heater);
    }

}


text:
Q: Automatically log user out of Facebook after inactivity As per FB policies, when a user logs out of my site they are logged out of FB too.
However, my sessions are destroyed after 20mins inactivity, can I somehow destroy the FB session too?
The issue is: another user goes onto the site not knowing that another user is still logged into FB, and my system trying to be a good UI logs them auto back in if it sees a FB user active.

A: Assuming you're using the JSSDK, there's a method to log the user out. You can call this when you're invalidating your session, assuming you can trigger some client-side code when that happens.
See https://developers.facebook.com/docs/reference/javascript/FB.logout/


text:
Q: Parse REST API shwoing sent but device doesn't show Push My iOS app is not receiving Parse notifications sent through Python and the REST API that parse tells us. Parse does say the push is sent and has targeted the test device.
Here is my Python code:
import json,httplib
connection = httplib.HTTPSConnection('api.parse.com', 443)
connection.connect()
connection.request('POST', '/1/push', json.dumps({
                                                 "channels": [
                                                              "gen"
                                                              ],
                                                 "data": {
                                                 "alert": "Testing",
                                                 "sound": "shsshort.mp3",
                                                 }
                                                 }), {
                   "X-Parse-Application-Id": "KEY_REMOVED_FOR_SECURITY",
                   "X-Parse-REST-API-Key": "KEY_REMOVED_FOR_SECURITY",
                   "Content-Type": "application/json"
                   })
result = json.loads(connection.getresponse().read())
print result

Thank you for your help in advanced!

A: If the Parse indicates that the push has been sent, then you back end code should be fine.
Most likely you are using wrong provisioning profile when signing the app. That's why it does not receive the push notification.

Make sure that you are code signing your app with the correct
  provisioning profile. If you have uploaded a Development Push
  Notification Certificate to Parse, you will only receive push
  notifications if you built your app with a Development Provisioning
  Profile. If you have uploaded a Production Push Notification
  Certificate, you should sign your app with a Distribution Provisioning
  Profile. Ad Hoc and App Store Distribution Provisioning Profiles
  should both work when your app is configured with a Production Push
  Notification Certificate.

Also double check all the points described in the Troubleshooting Push Notification section of Parse Push documentation.


text:
Q: The morphism induced in the derived category and in the homotopy category During a lecture my professor made an observation, she said that it can happen the following fact but she never explained how/why: let $\mathcal{A}$ a category; there are examples of morphisms $f\colon A^\bullet\to B^\bullet$ of complexes such that the morphism induced by $f$ in the derived category $D(\mathcal{A})$ is zero but the morphism induced by $f$ in the homotopy category $K(\mathcal{A})$ is not zero.
I'd like to understand how this can happen. Can anyone give me any examples please?

I'd like to precise that I know things like cone, cylinders, exact triangles.


text:
Q: jQuery Inputmask - decimal value negative or positive with mask in input element I'm trying to add a inputmask to an input element which allows the user to enter a decimal between -90 and 90 with 0 to 4 numbers after the decimal separator (side note: I'm using jQuery validate for min & max value validation).
I was able to make it work for positive values using this code:
$("#id").inputmask("99,9{0,4}");

I tried to extend it to allow negative values with the following code:
$.mask.definitions['~']='[+-]';
$("#id").inputmask("~99,9{0,4}");

Which did not work; The value started always with a "–" and it was not possible to replace it with a "+" or to remove it.
My last try was this:
$('#id').inputmask('decimal', {
        radixPoint: ".",
        integerDigits: 2,
        digits: 4,
        digitsOptional: true,
        autoGroup: true,
        allowPlus: true,
        allowMinus: true
    });

This works almost, but I have the following problems:

*

*The input element does not contain a visible mask (something like __.____)

*The user must enter the "-" or "+" sign as first character, it is not possible to add a minus to the start of the input.

My goal is to have an input element with a visible mask, preferably in the following format __.____, which  allows the user to enter negative or positive values. The user should be able to add a minus sign to the start of the input (after (and before) he entered the number).
Edit: Added fiddle
JSFiddle

A: $("input.percentage").inputmask({
    alias: "percentage",
    digits: "2",
    rightAlign: false,
    suffix: "%",
    integerDigits: 5,
    digitsOptional: true,
    allowPlus: true,
    allowMinus: true,
    placeholder: "0",
    min: -1000,
    max: 1000,
    numericInput: true
  });

I used max and min to allow minus for the input with two decimal points.


text:
Q: passing parameters from 2 select queries to another select query I'm trying to compare two different values of the same column in a select query.
This is my code, and I'm only passing one value (from the nearest select query). Can you help me out how can I pass the second value from the other query?
to make it a bit more clear, I want to compare the startTime with endTime=null (the time our user logged in to our website and didn't finish an order) to the startTime with endTime!=null (user logged in and registered an order).
SELECT
  notFinished,
  finished,
  DATEDIFF(notFinished, finished) as dateDifference,
  emailAddress,
  phone,
  __key__.id
FROM  (
  SELECT
    startTime AS finished
  FROM
    [datastore_dump.Orders]
  WHERE
    emailAddress IN (
    SELECT
      emailAddress
    FROM
      [datastore_dump.Orders]
    WHERE
      endTime IS NULL)
    AND endTime IS NOT NULL and emailAddress is not null ),
(
  SELECT
    emailAddress,
    phone,
    __key__.id,
    startTime AS notFinished
  FROM
    [datastore_dump.Orders]
  WHERE
    endTime IS NULL)

Thank you!

A: consider below logic:
SELECT
  emailAddress, startTime, endTime, DATEDIFF(endTime, startTime) AS daysDifference
FROM (
  SELECT
    emailAddress, startTime, endTime, status,
    LAG(status) OVER(PARTITION BY emailAddress ORDER BY startTime) AS prevStatus
  FROM (
    SELECT
      emailAddress, startTime, endTime,
      IF(endTime IS NULL, "not-finished", "finished") AS status
    FROM [datastore_dump.Orders]
  )
)
WHERE status = "finished"
AND prevStatus = "not-finished"

what it does is:
1. qualifies status of each record as finished or not-finished based on endTime
2. finds previous status for each record - prevStatus
3. for the records with status finished and previous status not-finished - calculated diff
Hope this is close to what you asked

A: This type of logic is easier to express in standard SQL (uncheck the "Use Legacy SQL" box under "Show Options") using a WITH clause. To get you started, you might want something like this:
WITH CompletedOrders AS (
  SELECT
    startTime AS finished
  FROM
    datastore_dump.Orders
  WHERE
    emailAddress IN (
    SELECT
      emailAddress
    FROM
      datastore_dump.Orders
    WHERE
      endTime IS NULL)
    AND endTime IS NOT NULL and emailAddress IS NOT NULL
), IncompleteOrders AS (
  SELECT
    emailAddress,
    phone,
    __key__.id,
    startTime AS notFinished
  FROM
    datastore_dump.Orders
  WHERE
    endTime IS NULL)
SELECT ...

As a working example, you can try:
WITH Orders AS (
  SELECT 'foo@example.com' AS email, CURRENT_TIMESTAMP() AS time
  UNION ALL SELECT 'bar@example.com' AS email, NULL AS time
  UNION ALL SELECT
    'baz@example.com',
    TIMESTAMP_SUB(CURRENT_TIMESTAMP(), INTERVAL 1 HOUR) AS time),
CompletedOrders AS (
  SELECT * FROM Orders WHERE time IS NOT NULL),
IncompleteOrders AS (
  SELECT * FROM Orders WHERE time IS NULL)
SELECT
  (SELECT COUNT(*) FROM CompletedOrders) AS completed_count,
  (SELECT COUNT(*) FROM IncompleteOrders) AS incomplete_count;
+-----------------+------------------+
| completed_count | incomplete_count |
+-----------------+------------------+
|               2 |                1 |
+-----------------+------------------+


text:
Q: Django : What is the role of ModelState? Sorry for not being this as programming question, but this caught my eye when I was trying to introspect my class objects.
I found this
{'user_id': 1, '_state': <django.db.models.base.ModelState object at 0x10ac2a750>, 'id': 2, 'playlist_id': 8}

What is the role of _state and what ModelState does?

A: From the Django source code, _state is an instance variable defined in each Model instance that is an instance of ModelState that is defined as:
class ModelState(object):
    """
    A class for storing instance state
    """
    def __init__(self, db=None):
        self.db = db
        # If true, uniqueness validation checks will consider this a new, as-yet-unsaved object.
        # Necessary for correct validation of new instances of objects with explicit (non-auto) PKs.
        # This impacts validation only; it has no effect on the actual save.
        self.adding = True

So basically this instance variable is used to know if the Model instance was already written to a db (knowing that Django support multiple db backends) and to hold the db used, this instance variable attribute adding is set to false after saving the model instance, and it's used mostly (as the comment in the code above) for validating if the primary keys is unique.


text:
Q: why is translation not working on theme? Background
I am using the theme Rookie from Sportpress.
I created a child theme.
Translation files are existing, especially german in my case.
Wordpress is set to german language.
The Problem
Translation is working fine everywhere except on themes provided templates like the search results page content or pagination.
Affected are the SRP title, nothing found page title and nothing found page content. They just stay in default english language.
Pagination is affected too.
The search form in the content of a nothing found page is translated fine. I guess because it's Wordpress default template.
Code
here some affected code lines from the parent theme.
Search Title

<?php printf( __( 'Search Results for: %s', 'rookie' ), '' . get_search_query() . '' ); ?>

Nothing Found title:

<?php _e( 'Nothing Found', 'rookie' ); ?>

Nothing found text:

<?php _e( 'Sorry, but nothing matched your search terms. Please try again with some different keywords.', 'rookie' ); ?>

Pagination:
<?php if ( get_next_posts_link() ) : ?>

<?php next_posts_link( __( '← Older posts', 'rookie' ) ); ?>

            <?php endif; ?>

            <?php if ( get_previous_posts_link() ) : ?>

<?php previous_posts_link( __( 'Newer posts →', 'rookie' ) ); ?>

            <?php endif; ?>

Findings
I checked that the .mo entry for german is existing with the Loco translate plugin.
I replaced the Search Result Title Search Results for: %s with the Category Title Category: %s, which gets translated on a category page (because category archive title is provided from Wordpress), but also not on the SRP!
What could be a reason for this behaviour?
Workaround
the parent theme is loading the domain via
load_theme_textdomain( 'rookie', get_template_directory() . '/languages' ); and points to right location where all translation files (.pot, de_DE.po and de_DE.mo) are existing.
I copied the relevant .po and .mo files over to wp-content/languages/themes/ directory and things are working now.
But is this the real best solution?

A: I downloaded the free Rookie parent theme and have no problem displaying translations of "Search Results for: %s" on a successful search results screen.
This works in the WordPress languages folder at wp-content/languages/themes/rookie-de_DE.mo as well as Loco Translate's custom directory. It works there if the files are named correctly because the parent theme correctly loads the "rookie" text domain using "load_theme_textdomain".
Are your files named correctly under the WordPress languages directory? Unlike the de_DE.mo file inside the theme folder, the system location requires the prefix so files should be named rookie-de_DE.mo

A: Putting files in wp-content/languages/themes/ is not a good idea because on the next update, the file will be overwritten.
The best way to correct that is to put the .mo file in the child theme with the name de_DE.mo.
Then, if e.g. you put the file in the directory wp-content/themes/rookie-child/languages, put this code in wp-content/themes/rookie-child/functions.php :
add_action("after_setup_theme", function () {

    load_theme_textdomain( 'rookie', get_stylesheet_directory() . '/languages' );

}, 5);