text:
Q: Getting last record from mysql I am using mysql and facing some problem. I want to retrieve last row that is inserted.
<< Below are details >>
Below is how I created table.
create table maxID (myID varchar(4))
I inserted four values in it as below
insert into maxID values ('A001')
insert into maxID values ('A002')
insert into maxID values ('A004')
insert into maxID values ('A003')

When I execute select myID, last_insert_id() as NewID from maxID, I get output as below
myId NewID
A001   0
A002   0
A004   0
A003   0

When I tried below code,
select myId, last_insert_id() as NewID, @rowid:=@rowid+1 as myrow from maxID, (SELECT @rowid:=0) as init
I get output as below.
myId NewID  rowid
A001   0      1
A002   0      2
A004   0      3
A003   0      4

However when I use code select myId, last_insert_id() as NewID, @rowid:=@rowid+1 as myrow  from maxID, (SELECT @rowid:=0) as init where @rowid = 4, I get error as Uknown column 'myrow' in where clause
When I use where @rowid=4, I don't get any data in tables.
Link to play with data
Note: Here I am using 4 just to get desired output. Later I can get this from a query (select max(rowid) from maxID)
Please suggest me what need to do if I want to see only last record i.e. A003.
Thanks for your time.
Update:
I already have millions of data in my table so I can't add new column in it as suggested below.

A: Almost done.
You succeed in getting the insert order.
So:
select myId, @rowid:=@rowid+1 as myrow from maxID, (SELECT @rowid:=0) as init ORDER BY myrow desc LIMIT 1;

In my console I get the following:
mysql> select myId, @rowid:=@rowid+1 as myrow from maxID, (SELECT @rowid:=0) as
init ORDER BY myrow desc LIMIT 1;
+------+-------+
| myId | myrow |
+------+-------+
| A003 |     4 |
+------+-------+
1 row in set (0.00 sec)

Demo
UPDATE
Yak is right. My solution is not deterministic. Maybe it works for small amount of records. I found tons of post abount unreliability of default sorting of a SELECT statement (here for example).
Next steps:

*

*Under which conditions the default SELECT sorting matches the insertion order?

*Is it possible to obtain the last inserted record in a table without an incremental id or an insertion timestamp?

I know it's not an answer, but stating the problem limit the problem.

A: From your insert script, A004 is not the last inserted record. It's the third one. If you want to get the last record in alphabetical order (which A004 is), you must use
select myID from maxID order by myID desc limit 1

If you want the last inserted row, why don't you just use add an autoincrement column to your table? That's the point of those kinds of columns. The autoincrement column doesn't have to be the PK (it should be, but doesn't have to if you don't have the choice).

A: It seems that a SELECT is not guaranteed to return rows in any specific order (without using an ORDER BY clause, of course).
As per the SQL-92 standard (p. 373):

If an < order by clause > is not specified, then the table specified by the < cursor specification > is T and the ordering of rows in T is implementation-dependent.

Okay, MySQL is not fully SQL-92-compliant, but this is a serious hint.
Laurynas Biveinis (apparently affiliated with Percona) also states:

The order of the rows in the absence of ORDER BY clause (...) could be different due to the moon phase and that is OK.

The MySQL manual says about InnoDB:

InnoDB always orders table rows according to [a PRIMARY KEY or NOT NULL UNIQUE index] if one is present.

As far as I am concerned, I assume MySQL could also reorder rows after an OPTIMIZE TABLE or even reuse empty spaces after many deletes and inserts (I have tried to find an example of this, and have failed so far).
Given your table structure, the bottomline is, unfortunately, that so many factors could have altered the order of the rows; I see no solution to reliably determine the order they were inserted. Unless you kept all binary logs since you created the table, of course ;)
Nevertheless, you may still want to add a sequence column to your table. Existing rows would be assigned a possibly inaccurate sequence number, but at least future rows will be correctly sequenced.
ALTER TABLE maxID ADD sequence INT DEFAULT NULL;
ALTER TABLE maxID ADD INDEX(sequence);
ALTER TABLE maxID MODIFY sequence INT AUTO_INCREMENT;

http://sqlfiddle.com/#!2/63a8d/1

A: As mentioned in the MySQL help for last_insert_id, you can only use it with **auto-increment columns. This means that you cannot make MySQL find the most recently inserted row for you, unless you know something about the order of the IDs. If they are sorted like your example suggests, then you can use
SELECT *
FROM maxID
WHERE myId = max(myId)

But I suggest adding an auto-increment column to the table and then use = last_insert_id() in your WHERE clause. See also this page for information on how to obtain the last ID.

A: last_insert_id does not work because it only returns the last value generated by an auto-increment field. However I think that solution may be on the right track. I would suggest adding another column that is a auto-increment integer. You can then insert data and to retrieve the row you just inserted select the last_insert_id(). To retrieve the most recent row (inserted by any process) select the max number for the new column, or sort by it desc.
If you want to use the varchar column you can do an alphabetic sort, but that does not guarantee it will be the last row you inserted row or even the most recently inserted row.
The one other solution I can think of which may do what you need is to create a stored procedure which creates the row, inserts it into the table, and then returns it to you.
Your usage of @rowid is simply counting the order rows are returned to you. There is no guarantee that they are returned to you in the order of oldest to newest. There are a variety of things that can affect the order in which rows are stored.

A: Please use the following query.
Select * from maxID order by myId desc limit 1,1;


text:
Q: "Is there anything more you would like to say?" Will I be using proper grammar if I ask someone, "Is there anything more you would like to say?" I need to know if I'm able to use the word more instead of the word else.

A: This is grammatically correct and natural.  The meaning is almost identical, with a slight nuance of "else" meaning "something different" and "more" meaning "something additional"
But most people would use more/else interchangeably.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why I can't get the warning messages as phpmyadmin does? I can even use abc as the value of a DATETIME column .
Why is it not doing validating at all?
UPDATE
About how phpmyadmin gets the warning:
By reading its code,I find it's from show warnings,but I can't reproduce it in command line MySQL.
mysql> UPDATE `test`.`uu3` SET `id` = 'x',dt='ab1c' WHERE `uu3`.`id` =3 AND `uu3`.`id2` =4;
Query OK, 0 rows affected (0.00 sec)
Rows matched: 0  Changed: 0  Warnings: 0

mysql> SHOW WARNINGS;
Empty set (0.00 sec)

mysql> desc `test`.`uu3`;
+-------+------------------+------+-----+---------+-------+
| Field | Type             | Null | Key | Default | Extra |
+-------+------------------+------+-----+---------+-------+
| id    | int(10) unsigned | NO   |     | NULL    |       |
| id2   | int(10) unsigned | NO   |     | NULL    |       |
| dt    | datetime         | NO   |     | NULL    |       |
+-------+------------------+------+-----+---------+-------+
3 rows in set (0.02 sec)

A: No, it does the proper validation.
When I tried to add a value "abc" to the field "date_time" (whose data type is "DATETIME"), then I got this error "Warning: #1264 Out of range value adjusted for column 'date_time' at row 1".
However, the row got inserted successfully, but the value of that field got changed automatically to "0000-00-00 0000:00:00".
I'm using the version 3.3.10.2 of phpMyAdmin.
Hope it helps.


text:
Q: Android saving coordinates canvas Drawcircle and display on Different Devices class Draw extends View {
    private Paint mPaint;
    public Button mCircles;

    DrawFragment mDrawFragment;
    private Circle mCurrentCircle;
    private List<Circle> mCircle= new ArrayList<>();

    public Draw(Context context){
        this(context,null);
    }

    public Draw(Context context, AttributeSet attrs) {
        super(context, attrs);

        mPaint=new Paint();
        mPaint.setColor(Color.RED);
        mPaint.setAlpha(80);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        for (Circle circle : mCircle) {
            float x1 = circle.getCenter().x;
            float x2 = circle.getFinal().x;
            float y1 = circle.getCenter().y;
            float y2 = circle.getFinal().y;

            double radius = Math.sqrt(Math.pow(dpx1 - dpx2, 2) + Math.pow(dpy1 - dpy2, 2));

            float rad = (float) radius;

            canvas.drawCircle(dpx1, dpy1, rad, mPaint);
        }

        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                mCurrentCircle = new Circle(current);
                mCircle.add(mCurrentCircle);
                break;

            case MotionEvent.ACTION_MOVE:
                if (mCurrentCircle != null) {
                    mCurrentCircle.setFinal(current);
                    invalidate();
                }
                break;

            case MotionEvent.ACTION_UP:
                mCurrentCircle = null;
                invalidate();  break;
        }

    }

    Log.i(TAG, "onTouchEvent: at x="+current.x + ", y =" + current.y);

    return true;
}

1.I'm saving these coordinates of circles drawn on canvas and this is to mark damages on a car.
            but when i use these values to display on a bigger device , Circle positions are not intact .. what can be done?

A: All the coordinates are referenced to a device with a screen determined by pixels and pixels per inches.

*

*If you wish to use the same information on a different device, you must set a sort of anchor point which works for you as a reference.

*For example, if those circles will be drawn over a background image of a car, you should be able to reference theme to the position of that picture.

*With that information, on any other device, you should be able to redraw those circles on any device based on the fact the coordinates are not referenced to the device but are reference to the car image.

I hope this help you to re think the problem.


text:
Q: Регулярка, которая находит определенные пробелы Подскажите, как будет выглядеть регулярка, которая найдет все пробелы кроме пробелов вокруг or и and ?
Пример:
"field = 10 and field2= 100 or field10 is not null"
регулярка не должна сработать на пробелы вокруг " and " и " or "

A: Вам надо воспользоваться Lookahead и Lookbehind
(?<!or)(?<!and)\s(?!or)(?!and)

ДЕМО и объяснение
или чуть короче
(?<!or|and)\s(?!or|and)

UPDATE Чтобы не срабатывало на horror andy hodor band
 (?<!\bor|\band)\s(?!or\b|and\b)

ДЕМО


text:
Q: is there a shorter way to do this? surely, there is a shorter way to do this?
NSString *filePathA = [[NSBundle mainBundle] pathForResource:@"A" ofType:@"txt"];
NSString *myTextA= [NSString stringWithContentsOfFile:filePathA encoding:NSUTF8StringEncoding error:nil];
NSArray *arrayStructuresA = [myTextA componentsSeparatedByString:@"-"];

NSString *filePathB = [[NSBundle mainBundle] pathForResource:@"B" ofType:@"txt"];
NSString *myTextB= [NSString stringWithContentsOfFile:filePathB encoding:NSUTF8StringEncoding error:nil];
NSArray *arrayStructuresB = [myTextB componentsSeparatedByString:@"-"];

NSString *filePathC = [[NSBundle mainBundle] pathForResource:@"C" ofType:@"txt"];
NSString *myTextC= [NSString stringWithContentsOfFile:filePathC encoding:NSUTF8StringEncoding error:nil];
NSArray *arrayStructuresC = [myTextC componentsSeparatedByString:@"-"];

NSString *filePathD = [[NSBundle mainBundle] pathForResource:@"D" ofType:@"txt"];
NSString *myTextD= [NSString stringWithContentsOfFile:filePathD encoding:NSUTF8StringEncoding error:nil];
NSArray *arrayStructuresD = [myTextD componentsSeparatedByString:@"-"];

NSString *filePathE = [[NSBundle mainBundle] pathForResource:@"E" ofType:@"txt"];
NSString *myTextE= [NSString stringWithContentsOfFile:filePathE encoding:NSUTF8StringEncoding error:nil];
NSArray *arrayStructuresE = [myTextE componentsSeparatedByString:@"-"];

NSString *filePathF = [[NSBundle mainBundle] pathForResource:@"F" ofType:@"txt"];
NSString *myTextF= [NSString stringWithContentsOfFile:filePathF encoding:NSUTF8StringEncoding error:nil];
NSArray *arrayStructuresF = [myTextF componentsSeparatedByString:@"-"];

NSString *filePathG = [[NSBundle mainBundle] pathForResource:@"G" ofType:@"txt"];
NSString *myTextG= [NSString stringWithContentsOfFile:filePathG encoding:NSUTF8StringEncoding error:nil];
NSArray *arrayStructuresG = [myTextG componentsSeparatedByString:@"-"];

NSString *filePathH = [[NSBundle mainBundle] pathForResource:@"H" ofType:@"txt"];
NSString *myTextH= [NSString stringWithContentsOfFile:filePathH encoding:NSUTF8StringEncoding error:nil];
NSArray *arrayStructuresH = [myTextH componentsSeparatedByString:@"-"];

NSString *filePathI = [[NSBundle mainBundle] pathForResource:@"I" ofType:@"txt"];
NSString *myTextI= [NSString stringWithContentsOfFile:filePathI encoding:NSUTF8StringEncoding error:nil];
NSArray *arrayStructuresI = [myTextI componentsSeparatedByString:@"-"];

NSString *filePathJ = [[NSBundle mainBundle] pathForResource:@"J" ofType:@"txt"];
NSString *myTextJ= [NSString stringWithContentsOfFile:filePathJ encoding:NSUTF8StringEncoding error:nil];
NSArray *arrayStructuresJ = [myTextJ componentsSeparatedByString:@"-"];

NSString *filePathK = [[NSBundle mainBundle] pathForResource:@"K" ofType:@"txt"];
NSString *myTextK= [NSString stringWithContentsOfFile:filePathK encoding:NSUTF8StringEncoding error:nil];
NSArray *arrayStructuresK = [myTextK componentsSeparatedByString:@"-"];

NSString *filePathL = [[NSBundle mainBundle] pathForResource:@"L" ofType:@"txt"];
NSString *myTextL= [NSString stringWithContentsOfFile:filePathL encoding:NSUTF8StringEncoding error:nil];
NSArray *arrayStructuresL = [myTextL componentsSeparatedByString:@"-"];

NSString *filePathM = [[NSBundle mainBundle] pathForResource:@"M" ofType:@"txt"];
NSString *myTextM= [NSString stringWithContentsOfFile:filePathM encoding:NSUTF8StringEncoding error:nil];
NSArray *arrayStructuresM = [myTextM componentsSeparatedByString:@"-"];

NSString *filePathN = [[NSBundle mainBundle] pathForResource:@"N" ofType:@"txt"];
NSString *myTextN = [NSString stringWithContentsOfFile:filePathN encoding:NSUTF8StringEncoding error:nil];
NSArray *arrayStructuresN = [myTextN componentsSeparatedByString:@"-"];

NSString *filePathO = [[NSBundle mainBundle] pathForResource:@"O" ofType:@"txt"];
NSString *myTextO= [NSString stringWithContentsOfFile:filePathO encoding:NSUTF8StringEncoding error:nil];
NSArray *arrayStructuresO = [myTextO componentsSeparatedByString:@"-"];

NSString *filePathP = [[NSBundle mainBundle] pathForResource:@"P" ofType:@"txt"];
NSString *myTextP= [NSString stringWithContentsOfFile:filePathP encoding:NSUTF8StringEncoding error:nil];
NSArray *arrayStructuresP = [myTextP componentsSeparatedByString:@"-"];

NSString *filePathQ = [[NSBundle mainBundle] pathForResource:@"Q" ofType:@"txt"];
NSString *myTextQ= [NSString stringWithContentsOfFile:filePathQ encoding:NSUTF8StringEncoding error:nil];
NSArray *arrayStructuresQ = [myTextQ componentsSeparatedByString:@"-"];

NSString *filePathR = [[NSBundle mainBundle] pathForResource:@"R" ofType:@"txt"];
NSString *myTextR= [NSString stringWithContentsOfFile:filePathR encoding:NSUTF8StringEncoding error:nil];
NSArray *arrayStructuresR = [myTextR componentsSeparatedByString:@"-"];

NSString *filePathS = [[NSBundle mainBundle] pathForResource:@"S" ofType:@"txt"];
NSString *myTextS= [NSString stringWithContentsOfFile:filePathS encoding:NSUTF8StringEncoding error:nil];
NSArray *arrayStructuresS = [myTextS componentsSeparatedByString:@"-"];

NSString *filePathT = [[NSBundle mainBundle] pathForResource:@"T" ofType:@"txt"];
NSString *myTextT= [NSString stringWithContentsOfFile:filePathT encoding:NSUTF8StringEncoding error:nil];
NSArray *arrayStructuresT = [myTextT componentsSeparatedByString:@"-"];

NSString *filePathU = [[NSBundle mainBundle] pathForResource:@"U" ofType:@"txt"];
NSString *myTextU= [NSString stringWithContentsOfFile:filePathU encoding:NSUTF8StringEncoding error:nil];
NSArray *arrayStructuresU = [myTextU componentsSeparatedByString:@"-"];

NSString *filePathV = [[NSBundle mainBundle] pathForResource:@"V" ofType:@"txt"];
NSString *myTextV= [NSString stringWithContentsOfFile:filePathV encoding:NSUTF8StringEncoding error:nil];
NSArray *arrayStructuresV = [myTextV componentsSeparatedByString:@"-"];

NSString *filePathW = [[NSBundle mainBundle] pathForResource:@"W" ofType:@"txt"];
NSString *myTextW= [NSString stringWithContentsOfFile:filePathW encoding:NSUTF8StringEncoding error:nil];
NSArray *arrayStructuresW = [myTextW componentsSeparatedByString:@"-"];
//none with "X"
//NSString *filePathX = [[NSBundle mainBundle] pathForResource:@"X" ofType:@"txt"];
//NSString *myTextX= [NSString stringWithContentsOfFile:filePathX encoding:NSUTF8StringEncoding error:nil];
//NSArray *arrayStructuresX = [myTextX componentsSeparatedByString:@"-"];

NSString *filePathY = [[NSBundle mainBundle] pathForResource:@"Y" ofType:@"txt"];
NSString *myTextY= [NSString stringWithContentsOfFile:filePathY encoding:NSUTF8StringEncoding error:nil];
NSArray *arrayStructuresY = [myTextY componentsSeparatedByString:@"-"];

NSString *filePathZ = [[NSBundle mainBundle] pathForResource:@"Z" ofType:@"txt"];
NSString *myTextZ= [NSString stringWithContentsOfFile:filePathZ encoding:NSUTF8StringEncoding error:nil];
NSArray *arrayStructuresZ = [myTextZ componentsSeparatedByString:@"-"];

any ideas? I was suggested to refract it, but i have no idea how to that!!
thanks
Sam
UPDATE:
[ is repetitive code like this actually bad? im just starting off? would this be considered a bad practice? or a 'don't' in the world of programming? ]

A: I would suggest creating an array and a dictionary: one to hold all of your filepaths, and one to hold your arrayStructures.
Create the filepaths array with all of the filenames that you want to load data from.
The arrayStructures dictionary should initially be an empty NSMutableDictionary with a capacity of 25 ( letters in the alphabet -1 ( not using x ) ).
Loop through the filepaths array and do the exact thing that you were doing for each iteration, except at the end of each iteration, you should call addObject: forKey: arrayStructures dictionary.
NSMutableDictionary *structures = [ [ NSMutableDictionary alloc ] initWithCapacity:25 ];
NSArray *filePaths = [ [NSArray alloc] initWithObjects: @"A", @"B", @"C", @"D", @"E", @"F", @"G", @"H", @"I", @"J", @"K", @"L", @"M", @"N", @"O", @"P", @"Q", @"R", @"S", @"T", @"U", @"V", @"W", /* no X */@"Y", @"Z" ]; // you could also just create a standalone text file and load it from there, i know this is ridiculous!

for( NSString *path in filePaths ) {
    NSString *filePath = [[NSBundle mainBundle] pathForResource:path ofType:@"txt"];
    NSString *myText = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
    [ structures addObject: [myText componentsSeparatedByString:@"-"] forKey: path ];
}

Now loop through the dictionary....
for( NSString *filePath in structures ) {
    NSArray *structure = [ structure objectForKey: filePath ];
    //...
}

A: Smells like an excellent opportunity to write a loop.
You can see that your code is repetitive, so what you need to do is extract the similar component from each element as a loop, extract the different compoenent as an input or output array, and you are done.

A: If you really want all those local variables I think this looks like a perfect opportunity to use a macro (if I dare to say)
#define MAKEARRAY( _letter ) \
  NSString *filePath ## _letter = [[NSBundle mainBundle] pathForResource:@ #_letter ofType:@"txt"]; \
  NSString *myText ## _letter = [NSString stringWithContentsOfFile:filePath ## _letter encoding:NSUTF8StringEncoding error:nil]; \
  NSArray *arrayStructures ## _letter = [myText ## _letter componentsSeparatedByString:@"-"]

MAKEARRAY( A );
MAKEARRAY( B );
MAKEARRAY( C );
:
:
MAKEARRAY( W );
//MAKEARRAY( X ); none with X
MAKEARRAY( Y );
MAKEARRAY( Z );


text:
Q: iOS App starts very slow and stalls in ImageLoaderMachO::loadCodeSignature i am developing a Swift based App for iOS 8.3 and i observed that the App starts very very slow and seems to stall in the App loading process. The App slows donwn before any of my code is executed. As matter of fact, only one thread is active, only 60k memory are used, the CPU is not busy.  See attached Screenshot.
The App waits for about 20-30 seconds and continues as expected without any exceptions or error messages.

A: All this happens because there are Security checks added by the apple.
This is not applicable for not only iOS devices but applicable for all MAC devices as well.
For any change in files there will be security, signature checks gets performed.
Depending on the machine(iPhone/Mac), internet speed it takes times to get completed.
Any subsequent call to same (no recompile, modified) file does not observe this issue.


text:
Q: How i can switch between icons with javascript when clicked? How can I switch between icons with javascript when clicked?

function mode() {
  var moon = document.getElementById("mode");
  moon.src = "https://img.icons8.com/sf-black-filled/35/fffffe/moon-symbol.png";
  moon.id = "lightmode";
  moon.onclick = lightmode();
}

function lightmode() {
  var sun = document.getElementById("lightmode");
  sun.src = "https://img.icons8.com/sf-black-filled/34/000000/sun.png";
  sun.onclick = mode();
}
body { background-color:grey }

A: You are setting up event listeners in an incorrect manner
Here is a toggle using classes and data attributes

const srcs = {
  "dark": "https://img.icons8.com/sf-black-filled/35/fffffe/moon-symbol.png",
  "light": "https://img.icons8.com/sf-black-filled/34/000000/sun.png"
};
const modeToggle = document.getElementById("modeToggle");
modeToggle.addEventListener("click", function() {
  let mode = this.dataset.mode;
  mode = mode === "dark" ? "light" : "dark"; // toggle
  this.src = srcs[mode]; // image
  this.dataset.mode = mode; // save in element
  document.body.classList.toggle("dark",mode==="dark"); // toggle page too
})
document.body.classList.toggle("dark",modeToggle.dataset.mode==="dark"); // initialise the page, possibly from localStorage
body {
  background-color: grey
}

body.dark {
  background-color: black;
}

A: this may solve your problem, please use proper names for your functions, e.g instead of mode() use changeMode() as a name
javascript:
let isChanged = false;
let mode = document.querySelector('#mode');

function changeMode(){
  isChanged = !isChanged;
  if(isChanged) {
    mode.src = "https://img.icon8.com/sf-black-filled/35/ffffffe/moon-symbol.png"
  } else {
    mode.src = "https://img.icon8.com/sf-black-filled/34/000000/sun.png"
  }
}

A: Toggling between two different images/icons/styles is very simple in Javascript. You could, for instance, create a simple Object literal with name/value pairs for both icons as per the following. A simple ternary operator determines what the src should be based upon the current src

document.querySelector('.nav-icons > img.sunmoon').addEventListener('click',function(e){
  let icons={
    sun:'https://img.icons8.com/sf-black-filled/34/000000/sun.png',
    moon:'https://img.icons8.com/sf-black-filled/35/fffffe/moon-symbol.png'
  };
  this.src = this.src==icons.moon ? icons.sun : icons.moon;
});
body {
  background-color: grey
}


text:
Q: How ignore actions name in route with ASP.NET MVC? Let's say I have following simple controller:
public class DataController: Controller
{
    [HttpGet]
    public ActionResult Index()
    {
        // some code
    }
}

Now I'd like Index action to be allways called if there is a GET request to DataContoller. I other words to ignore action name and any other parameters. For example all of following calls should be handled by Index action:

*

*https://localhost:5000/data

*https://localhost:5000/data/anything

*https://localhost:5000/data/anything/secondAnything

*https://localhost:5000/data/anything?someParameter=3
How can I achieve this?

A: You should update your RouteConfig like so:
public class RouteConfig
{
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.MapRoute(
                name: "RouteOverwrite",
                url: "data/{*catchall}",
                defaults: new { controller = "Data", action = "Index" }
            );
        }
}

Make sure you use this in Application_Start:
public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            System.Net.ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;

// register route config
            RouteConfig.RegisterRoutes(RouteTable.Routes);
        }
    }

A: you can do this by using routetable. check out system.web.routing in asp.net mvc.


text:
Q: Change build rules in Makefile to build multiple file types I want to change my Makefile to build cpp and mm files, since I have just begun adding Objective-C code into my project. This is the Makefile I have currently:
# Name of the project being built
PROJECT := modpe

# Name of process the tweak is loaded into
PROCESS := minecraftpe

# Local IP Address of device to SSH into
DEVICE := ryans-ipod-touch.local

# Path of the SDK on MacOS
SDKPATH := /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS.sdk

# Build using libc++ and C++11 support
override CXXFLAGS += -stdlib=libc++ -std=c++11 -miphoneos-version-min=7.0 -isysroot $(SDKPATH)
override LDFLAGS += -stdlib=libc++ -std=c++11 -miphoneos-version-min=7.0 -isysroot $(SDKPATH)

# Names of the tweak library, substrate filter, and debian package
TWEAK := $(PROJECT).dylib
FILTER := $(PROJECT).plist
DEB := $(PROJECT).deb
# Directory for build products like executables, object files, and dependency files
BUILD := build
# Directory for debian package filesystem layout
LAYOUT := layout
# Directory for temporary staging of the debian package structure while creating the package
STAGING := $(BUILD)/deb
SUBSTRATE := $(STAGING)/Library/MobileSubstrate/DynamicLibraries
# Name of the unstripped version
UNSTRIPPED := $(BUILD)/$(TWEAK:.dylib=_unstripped.dylib)
# List of source files and their corresponding object file paths
SRCS := $(shell find . -type f -name '*.cpp')
OBJS := $(addprefix $(BUILD)/,$(SRCS:.cpp=.o))
# Supported architectures
ARCHS := arm64
ARCHFLAGS := $(addprefix -arch ,$(ARCHS))
# Frameworks for linking
FRAMEWORKS := CydiaSubstrate Forklift
override LDFLAGS += $(addprefix -framework ,$(FRAMEWORKS))

# Compiler and linker
CLANG := clang $(ARCHFLAGS)
CLANGXX := clang++ $(ARCHFLAGS)
CC := $(CLANG)
CXX := $(CLANGXX)
LD := $(CLANGXX)
STRIP := strip

# When invoked as "make VERBOSE=1", every command gets printed as it runs
ifdef VERBOSE
_v :=
else
_v := @
endif

### Build rules ###

all: $(TWEAK)

.PHONY: all

$(TWEAK): $(UNSTRIPPED)
    @echo 'Strip $@'
    $(_v)$(STRIP) -x -o $@ $<

%.dylib: $(OBJS)
    @echo 'Link $@'
    $(_v)$(LD) $(LDFLAGS) -dynamiclib -o $@ $^

%.cpp: $(BUILD)/%.d

$(BUILD)/%.o: %.cpp | $(BUILD)/.dir
    @echo 'Compile $@'
    $(_v)$(CXX) $(CXXFLAGS) -MD -MF $(BUILD)/$*.d -c -o $@ $<

.SECONDARY: $(BUILD)/.dir

-include $(BUILD)/*.d

### Package rules ###

package: $(DEB)

.PHONY: package

$(DEB): $(TWEAK) $(FILTER)
    @echo 'Stage $@'
    $(_v)rm -rf $(STAGING)
    $(_v)mkdir -p $(STAGING)
    $(_v)cp -R $(LAYOUT)/* $(STAGING)
    $(_v)mkdir -p $(SUBSTRATE)
    $(_v)cp $^ $(SUBSTRATE)
    $(_v)chown -R root:wheel $(STAGING)
    $(_v)chmod 0755 $(SUBSTRATE)/$(TWEAK)
    $(_v)chmod 0644 $(SUBSTRATE)/$(FILTER)
    @echo 'Package $@'
    $(_v)dpkg-deb -Zgzip -b $(STAGING) $@
    $(_v)rm -rf $(STAGING)

### Install rules ###

install: $(DEB)
    @echo 'Install $(DEB)'
    scp $(DEB) root@$(DEVICE):/var/tmp/
    @echo 'Run dpkg -i /var/tmp/$(DEB) to install.'
    ssh root@$(DEVICE)

.PHONY: install

### Offline install rules ###

offline:
    @echo 'No WiFi to SSH: Using afc instead'
    $(_v)sudo afc/afcclient put ./modpe.deb /modpe.deb

.PHONY: offline

### Clean rules ###

clean:
    @echo 'Remove $(BUILD)'
    $(_v)rm -rf $(BUILD)

.PHONY: clean

### General rules ###

%/.dir:
    @echo 'Create directory $*/'
    $(_v)mkdir -p $* && touch $@

# deploys test script
deploy: $(OFFLINE)
    scp scripts/script.js root@$(DEVICE):/var/mobile/modpe/

.PHONY: deploy

So far the only thing that I know to change is the SRCS line:
SRCS := $(shell find -E . -regex ".*\.\(cpp\|mm\)")

My question is, what else can I do to make this build .mm source files with .cpp source files, rather than ignoring them?

A: You haven't given us enough information to reproduce the problem or test solutions, so you may have to do some fine-tuning, but here's an approach that should work.
You have already modified the SRCS := ... line. Once you have verified that that works, modify the OBJS := ... line:
OBJS := $(patsubst %, $(BUILD)/%.o,$(basename $(SRCS)))

Then once you have verified that that works, add a new rule:
$(BUILD)/%.o: %.mm | $(BUILD)/.dir
    @echo 'Compile $@'
    $(_v)$(CXX) $(CXXFLAGS) -MD -MF $(BUILD)/$*.d -c -o $@ $<


text:
Q: Is there a plugin in Eclipse to synchronize controller fromf xml view? I would like to know is there is an Eclipse plugin to update associated controller from fxml file or at least informing that controller miss some ?
Thank you


text:
Q: In Flash, what's the difference between the SWF header FPS and the Stage FPS? In ActionScript, what's the difference between the SWF header FPS and the Stage FPS? From what I understand, the Stage FPS is initially copied from the SWF header FPS, but is that all the header FPS is for? Can it ever override the Stage FPS?
Just to clarify, I set the header FPS using the SWF metadata tag - [SWF(frameRate="60")] - and the Stage FPS using "stage.frameRate = 60".
Also, where can I find a good description of the way Flash handles the set FPS? I'd like to know if it's a limit, an average, a target, etc.

A: uhm, it is two different things ...
the first one is included in a well defined place in the swf byte format (namely, the header), and the second one will be compiled to bytecode instructions that have to be executed on the avm in order to take effect ...
if you load an swf into a running swf, than the header framerate of the loaded swf will be completely ignored ...
this is simply historical ... flash player started as software to display animation, and thus size and frame rate had to be included into the file format, like the rest of the animation ... scripting appeared later, and script access to the stage's FPS was not available before flash player 9 ...
but yeah, the effect is similar, most of the time ... :)
concerning the second question: it's the target, if you will ... sometimes, you may get 61-62 FPS, when framerate is at 60, but, it never really exceeds it ... when too much computation power is needed, framerate will drop of course ...
greetz
back2dos


text:
Q: Display Data from firebase with angularfire2 I use angular cli, realdatabase of firebase and angularfire2.
I realize an application that records patients, lists them and gives access to each patient on a detail component. This component detail has for route: path: '/ patients /': id
Once on the detail component, I log diagnostics. The structure of my data is as follows:

I am now looking to display the diagnoses belonging to each patient in the detail component.
I tried this but no data appears. Thank you for your help
//diagnosticsService.ts :
import { Injectable } from '@angular/core';
import { Patient } from '../models/patient.model';
import { Diagnostic } from '../models/diagnostic.model';
import { AngularFireDatabase, AngularFireList, AngularFireObject} from 'angularfire2/database';

@Injectable()

export class DiagnosticsService {
diagnostics: AngularFireList<any>;

constructor(private database: AngularFireDatabase) {this.diagnostics = database.list('diagnostics');}

getDiagnostics() { return this.diagnostics; }

CreateDiagnostic(newDiagnostic: Diagnostic) { this.diagnostics.push(newDiagnostic); }

getDiagnosticByPatientid(Patientid: string){
return this.database.list('/diagnostics', ref => ref.orderByChild("Patientid").equalTo(Patientid)).valueChanges();
}

//ComponentDetail.ts :
import { Component, OnInit, Inject } from '@angular/core';
import { Patient } from '../../models/patient.model';
import { Diagnostic } from '../../models/diagnostic.model';
import { ActivatedRoute, Router } from '@angular/router';
import { PatientsService } from '../../services/patients.service';
import { DiagnosticsService } from '../../services/diagnostics.service';
import { AngularFireDatabase, AngularFireList, AngularFireObject, AngularFireAction } from 'angularfire2/database';
import { Location } from '@angular/common';
import { Observable } from 'rxjs/Observable';

@Component({
   selector: 'app-single-patient',
   templateUrl: './single-patient.component.html',
   styleUrls: ['./single-patient.component.scss'],
   providers: [PatientsService]
})

export class SinglePatientComponent implements OnInit {

  patientId: string;
  diagnosticToDisplay;

    constructor(
    private route: ActivatedRoute,
    private location: Location,
    private patientsService: PatientsService,
    private diagnosticsService: DiagnosticsService,
    private router: Router,

    ) {}

  ngOnInit() {
   this.route.params.forEach((urlParameters) => {
   this.patientId = urlParameters['id'];
   this.diagnosticToDisplay =
   this.diagnosticsService.getDiagnosticByPatientid(this.patientId);
   console.log(this.diagnosticToDisplay);
}

//DetailComponent.html :
<li *ngFor="let diagnosticToDisplay  of diagnosticsToDisplay | async ">
      {{ diagnosticToDisplay?.localisation }}
</li>

A: It looks to me like you need to unwrap the observable of diagnosticsToDisplay. Remember that angularfire will return an observable that is a list. NgFor only works on lists, and so I'm surprised you're not getting an error from trying to use an observable instead of a list. With this idea in mind your html instead should read
<li *ngFor="let diagnosticToDisplay  of diagnosticsToDisplay | async ">
  {{ diagnosticToDisplay?.localisation }</li>


text:
Q: BackboneJS - Add different view or layout when .fetch() returns error? Can I add a different View or Layout in case of fetching an collection returns error?
Right now, I'm doing it like this:
this.artistsCollection.fetch({
    error: function() {
        $('div.artistsDiv').append('

');
    }
});

But I was thinking of something like:
error: function() {
    App.useLayout('artistLetter', 'artistLetter').setViews({
        '.navMenu': this.navigation,
        '.alphabet': this.alphabet,
        '.artistsDiv': this.artists
    }).render();
}

OR
error: function() {
    $('div.artistsDiv').setViews({...
    })
}

So, is there a better way to do this? Otherwise I'm gonna continue with this method, since it works even though I want to do it the right way..


text:
Q: Google Drive SDK Realtime / Multiple Cursors (IndexReference?) I'd like to implemente a user experience similar to Google Docs using realtime API.
I wonder what is the best approach to track cursors / selections from all collaborators.
It looks as if IndexReference would be the way to go but how can I track if a collaborator adds a IndexReference to a string?
In the realtime API sandbox only cursor movements from the local cursor are tracked. Are IndexReferences broadcasted to all collaborators or are they for local usage only?
Or is the preferred approach to create a collaborativeMap containing all the selections?
Is there a way to attach certain fields to a collaborator so that they get cleaned up when a collaborator leaves?

A: IndexReferences are data model objects just like any other.  You can add listeners to them to be informed of changes.
You probably want to have a map from sessionId -> cursor information.  How exactly the cursor information is represented depends on what you want to track, but it could be an index reference on a string.
You can listen to collaborator leave events to figure out when to remove a collaborator's cursor.


text:
Q: Is there a TCL cmd to grep a particular line and awk a particular word Lets say below is something i've stored in a config variable in tcl.
#set config "configuration {
test_config {
    address 1.2.3.4:https
}
}"

Using tcl cmd, either grep or awk or string cmds, how do i take out "1.2.3.4:https" into a variable.
So when i use do something like below,
#puts $output
1.2.3.4:https

I know how it can be done in simple bash though
#echo $config | grep address | awk '{print $2}'
#1.2.3.4:https

Can someone please help in tcl. I tried to explore string functions, but they are not giving my required output and I'm learning about regexp now.

A: You're probably looking for the regexp command, especially with the -line option. The trick here is to use \s* (or \s+) to match spaces and \S+ to match non-spaces.
if {[regexp -line {^\s*address\s+(\S+)} $config -> address]} {
    puts "The address is $address"
}

If there are multiple address lines, you might instead do:
foreach {-> address} [regexp -inline -all -line {^\s*address\s+(\S+)} $config] {
    puts "The address is $address"
}

A: I'm sure Donal's suggestion is the more efficient: here's a procedural way to do it:
foreach line [split $config \n] {
    lassign [regexp -inline -all {\S+} $line] first second
    if {$first eq "address"} {
        set output $second
        break
    }
}


text:
Q: .htaccess show subfolder contents on root only but don't show subfolder in address bar This is what I currently have in my .htaccess file
RewriteEngine On
RewriteRule ^$ /subfolder/ [R=301,L]

This simply redirects to the subfolder, but I would also like to prevent the subfolder showing in the browser's address bar, and I would only like this to happen on root (main domain page), and all other file requests should go normally, without any redirection at all.
I have tried many solutions here on SO, but all of them either do nothing, simply redirect to the subfolder, or redirect everything, including my style sheets and all removing all the styling and everything from the website.
Is it possible that a rewrite rule would not work on localhost? The redirection does work, but I start to be suspicious apache may not be set up correctly to do other stuff (sorry for my ignorance, I don't know much about apache and redirects).
EDIT: a bit more details: this is a PHP (WordPress) install, and this is the root is the only page I would like to redirect, but all other files (ie. CSS styling, JS scripts... etc) that are called to build this page should be called from the root, not from the subfolder. Also all further navigation to other pages on the site should work normally, without any effect of the .htaccess directive I'm setting up.

A: Assuming subfolder doesn't have another .htaccess, you can use this code in site root .htaccess:
DirectoryIndex index.php
RewriteEngine On

# externally redirect /subfolder/anything to /anything
RewriteCond %{THE_REQUEST} \s/+subfolder/(\S*) [NC]
RewriteRule ^ /%1 [R=301,NE,L]

RewriteRule ^(index\.php)?$ subfolder/index.php [NC,L]

# internally forward /anything to /subfolder/anything
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(?!subfolder/).+$ subfolder/$0 [NC,L]

# rest of the Wordpress rules go here

References:

*

*Apache mod_rewrite Introduction

*Apache mod_rewrite Technical Details

A: If some of those redirects you tried actually occurred, then your .htaccess is working.
The R=301 is what does the redirect, changing the url in the address bar. Remove it and a "rewrite" will be performed, executing the target page without changing the url in the browser.
To rewrite only the base uri '':
Options -Indexes
RewriteEngine On
RewriteRule ^/?$ /event/index.php [L]


text:
Q: Third party framework in Mac App Store Does Apple allow additional frameworks? (Dynamic libraries)

A: Yes. Those frameworks must, themselves, comply with the App Store guidelines. For example, not referencing private APIs or writing to forbidden file system locations.

A: Yes. For instance, Twitter.app uses the Growl framework. You can confirm that by inspecting /Applications/Twitter.app/Contents/Frameworks.


text:
Q: Displaying the nested foreach with if else in php codeigniter Controller
public function admin()
{
    // get the current date employee logged in details
    $data['get_attendance'] = $this->attendance_model->get_attendance();

    // get the active employee details
    $data['get_employee'] = $this->attendance_model->get_employee();

    //print_r($data['get_employee']); exit();

    // attendance page
    $data['header'] = "Employee";
    $data['sub_header'] = "Attendance employee";
    $data['main_content'] = 'attendance/admin_list';
    $this->load->view('employeelayout/main',$data);
}

Model
public function get_attendance()
{
    return $this->db->where('date',date('Y-m-d'))->get('attendance')->result_array();
}

public function get_employee()
{
    return $this->db->where('is_active',1)->get('employee')->result_array();
}

Views
<?php $count = 1 ?>
<?php foreach ($get_employee as $employee) { ?>

    <?php echo $count++ ?>
    <?php echo $employee['first_name'] . ' ' . $employee['last_name'] ?>
    <?php echo $employee['employee_number'] ?>
       <?php foreach ($get_attendance as $attendance) : ?>

           <?php if($employee['employee_id'] == $attendance['employee_id'] ) { ?>
            <?php echo date('M-Dj-Y',strtotime($attendance['date'])) ?>
            <?php echo $attendance['mark_in_time'] ?>
               mark out going
               Active
            <?php  break; ?>

       <?php } elseif($employee['employee_id'] != $attendance['employee_id'] ) { ?>
           <?php echo "i'm absent" ?>
           <?php  break; ?>
      <?php  } ?>
       <?php endforeach; ?>

    <?php } ?>

I want to display the currently logged in (present) employee and display the absent employees too. I'm getting the employee details from employee table.
and attendance details from attendance table. if an employee is absent and I want to display the absent else display the login details. where here foreach loop not displaying properly with if condition. what's wrong with the loop.

A: try this:
<?php foreach ($get_employee as $employee) : ?>

        <?php echo $count++ ?>
        <?php echo $employee['first_name'] . ' ' . $employee['last_name'] ?>
        <?php echo $employee['employee_number'] ?>
           <?php foreach ($get_attendance as $attendance) : ?>

             <?php if($employee['employee_id'] == $attendance['employee_id']) : ?>
                <?php echo date('M-Dj-Y',strtotime($attendance['date'])) ?>
                <?php echo $attendance['mark_in_time'] ?>
                   mark out going
                   Active

             <?php elseif ($employee['employee_id'] != $attendance['employee_id']) : ?>
               <?php echo "i'm absent" ?>

             <?php else : ?>

             <?php endif; ?>

          <?php endforeach; ?>

<?php endforeach; ?>

A: Apply left join in place of two different queries.
Because currently you have applied two loops and their comparisons, will consume a lot of execution time And I don't think this is the good code If you get thousands of data than definitely you can analyse the execution time.
So it's better to apply join query.


text:
Q: C# Active Directory - Query Unsuccessful Login Attempts Is there a way to return a list of Active Directory login attempts using C#? For example, I would like to somehow return a list that contains the following

*

*DC Name

*Site

*User State

*Bad Pwd Count

*Last Bad Pwd

*PWD Last Set

*Lockout Time

Essentially, I would like to know which device that is accessing Active Directory is causing a password lockout, on password updates.
I have looked at using the UserPrincipal class in System.DirectoryServices.AccountManagement but I cannot find a method that allows one to aggregate across DCs.
Thanks in advance for any help or advice!

A: There's no built in support for aggregating across multiple DCs. You have to handle that manually. This might get you started - this code will give you all domain controllers. Note - if you run this on a computer outside of the domain, it will throw an exception.
foreach (var l_DomainController in Domain.GetCurrentDomain().DomainControllers)
{
    Console.WriteLine(l_DomainController.ToString());
}


text:
Q: cpu usage per process with bash script im trying to write a bash script to read the cpu usage per process.
but, i think im doing it wrong. when i test this script, it gives me an incorrect percentage.
heres the code:
prev_total=0
prev_idle=0
prev_processtotal=0
prev_utime=0
while true; do
cpu=`cat /proc/stat | head -n1 | sed 's/cpu  //'`
user=`echo $cpu | awk '{print $1}'`
system=`echo $cpu | awk '{print $2}'`
nice=`echo $cpu | awk '{print $3}'`
idle=`echo $cpu | awk '{print $4}'`
wait=`echo $cpu | awk '{print $5}'`
irq=`echo $cpu | awk '{print $6}'`
srq=`echo $cpu | awk '{print $7}'`
zero=`echo $cpu | awk '{print $8}'`
total=$(($user+$system+$nice+$idle+$wait+$irq+$srq+$zero))
diff_idle=$(($idle-$prev_idle))
diff_total=$(($total-$prev_total))
usage=$(($((1000*$(($diff_total-$diff_idle))/$diff_total+5))/10))
process=`cat /proc/20966/stat`
utime=`echo $process | awk '{print $14}'`
stime=`echo $process | awk '{print $15}'`
cutime=`echo $process | awk '{print $16}'`
cstime=`echo $process | awk '{print $17}'`
processtotal=$(($utime+$stime+$cutime+$cstime))
diff_processtotal=$(($processtotal-$prev_processtotal))
diff_utime=$(($utime-$prev_utime))
processusage=$(($((1000*$(($diff_processtotal-$diff_utime))/$diff_processtotal+5))/10))
clear
echo "total cpu usage: $usage%"
echo "one selected process: $processusage%"
prev_total=$total
prev_idle=$idle
prev_processtotal=$processtotal
prev_utime=$utime
sleep 1
done

im kinda lost here, so any help would be very much appreciated:)

A: prev_total=0
prev_idle=0
prev_processtotal=0
prev_utime=0
while true; do
cpu=`cat /proc/stat | head -n1 | sed 's/cpu  //'`
user=`echo $cpu | awk '{print $1}'`
system=`echo $cpu | awk '{print $2}'`
nice=`echo $cpu | awk '{print $3}'`
idle=`echo $cpu | awk '{print $4}'`
wait=`echo $cpu | awk '{print $5}'`
irq=`echo $cpu | awk '{print $6}'`
srq=`echo $cpu | awk '{print $7}'`
zero=`echo $cpu | awk '{print $8}'`
total=$(($user+$system+$nice+$idle+$wait+$irq+$srq+$zero))
diff_idle=$(($idle-$prev_idle))
diff_total=$(($total-$prev_total))
usage=$(($((1000*$(($diff_total-$diff_idle))/$diff_total+5))/10))
process=`cat /proc/19240/stat`
utime=`echo $process | awk '{print $14}'`
stime=`echo $process | awk '{print $15}'`
cutime=`echo $process | awk '{print $16}'`
cstime=`echo $process | awk '{print $17}'`
processtotal=$(($utime+$stime+$cutime+$cstime))
diff_processtotal=$(($processtotal-$prev_processtotal))
diff_utime=$(($utime-$prev_utime))
processusage=$(($((1000*$(($diff_processtotal***4**))/$diff_total+5))/10))
clear
echo "total cpu usage: $usage%"
echo "one selected process: $processusage%"
prev_total=$total
prev_idle=$idle
prev_processtotal=$processtotal
prev_utime=$utime
sleep 1
done

i have a quad core and it turned out that i had to multiply the value by 4 too...
now problem solved;)


text:
Q: Question about Q-analogs I am trying to prove the following
Given $n \in \mathbb{N}$ we define $[n]_{q} = (1-q^{n})/(1-q)$.
We also define $[n]_{q} ! = [n-1]_{q} ! \cdot [n]_{q}$, with $[1]_{q} ! =1$.
Then I want to prove the following
Given compositions $\lambda$, $\mu$ we say $\mu \geq \lambda$ if
$$
\lambda_{1} = \mu_{1} + \ldots + \mu_{i_{1}}
$$
$$
\lambda_{2} = \mu_{i_{1}+1} + \mu_{i_{1}+2} + \ldots + \mu_{i_{2}}
$$
Etc, in other words if one sees $\lambda$ as a division of the interval $[1, \ldots , | \lambda | ]$ then $ \mu \geq \lambda$ if $\mu$ has the same divisions than $\lambda$ and possibly more.
For example $\lambda = (3,2,1)$ can be seen as $123|45|6$ and $\mu=2121$ can be seen as $12|3|45|6$. In this case $\mu \geq \lambda$.
Given a composition $\lambda$, we define
$$
f_{\lambda} (q) = \prod_{i=1}^{ \ell (\lambda) } [ \lambda_{i} ]_{q} !^{-1}
$$
I want to prove that
$$
f_{\lambda} \left( \dfrac{1}{q} \right) = \sum_{\mu \geq \lambda} f_{\mu} (q) (-1)^{\ell (\mu )- | \lambda |}
$$
As the function is defined multiplicatively, I know that this follows if I can prove it for $\lambda = (\lambda_{1})$.
Do anyone knows any reference in which I could look for theory that could aid me to come up with a proof?

A: After trying again induction, but this time using all the previous terms, I think I have succeded.
We want to prove
\begin{equation}
\label{Eq1}
 f_{m} \left( \frac{1}{q} \right) = \sum_{ | \lambda | = m} f_{\lambda} (q) (-1)^{\ell ( \lambda ) + | \lambda |  } \qquad (1)
\end{equation}
First, we divide the compositions of $m$ on the following sets: the ones that end with a block of size $1$, they are $2^{m-1}$, the ones that end with a block of size $2$, they are $2^{m-2}$, and so. There is only $1$ that ends with a block of size $m-1$ and only one that ends with a block of size $m$.
So
$$
\sum_{ | \lambda | = m} f_{\lambda} (q) (-1)^{\ell ( \lambda ) + | \lambda | } = \sum_{0 \leq n < m}  \sum_{ | \mu | = n}  f_{\mu} (q) (-1)^{\ell ( \mu ) +1 + | \mu | +(m-n) } \dfrac{1}{ [m - n ]_{q} !}
$$
If we assume by strong induction that $(1)$ holds for $n<m$, then this is is equal to
$$
\sum_{0 \leq n < m}   (-1)^{m-n+1} f_{n} \left( \frac{1}{q} \right) \dfrac{1}{ [m - n ]_{q} !} = (-1)^{1+m} \sum_{0 \leq n < m}   (-1)^{n} f_{n} \left( \frac{1}{q} \right) \dfrac{1}{ [m - n ]_{q} !}
$$
We add $f_{m}(1/q)$ to this, and we obtain
$$
(-1)^{1+m} \sum_{0 \leq n < m}   (-1)^{n} f_{n} \left( \frac{1}{q} \right) \dfrac{1}{ [m - n ]_{q} !} +(-1)^{2m+1} f_{m}  \left(
\frac{1}{q} \right) =
$$
$$
=
 (-1)^{1+m} \sum_{0 \leq n \leq m}   (-1)^{n} f_{n} \left( \frac{1}{q} \right) \dfrac{1}{ [m - n ]_{q} !}
$$
A straightfoward computation shows that $f_{n} (1/q) = q^{n(n-1)/2}$.
$$
(-1)^{1+m} \sum_{0 \leq n \leq m}   (-1)^{n} q^{n(n-1)/2} f_{n} \left( q \right) \dfrac{1}{ [m - n ]_{q} !}
$$
By definition $f_{n}(q) = [n]_{q}!^{-1}$, we replace on the expresion and obtain.
$$
(-1)^{1+m} \sum_{0 \leq n \leq m}   (-1)^{n} q^{(n-1)n/2} \dfrac{1}{ [n]_{q}! [m - n ]_{q} !}
$$
If we multiply this by $f_{m}(1/q)^{-1}=[m]_{q}! (-1)^{1+m}$, then we get
$$
 \sum_{0 \leq n \leq m}   (-1)^{n} q^{(n-1)n/2} \dfrac{ [m]_{q}! }{ [n]_{q}! [m - n ]_{q} !}
$$
Which by Gauss Binomial Formula (found on page 15, equation (5.5) of Quantum Calculus Victor Kac) with $a=-1$ and $x=1$ this is $0$.
So $ f_{m}(1/q) = \sum_{| \mu | = m} f_{\mu} (q) (-1)^{\ell ( \mu ) + | \lambda |}$.


text:
Q: How To Make Full Page Background Image Without Resizing Or Cropping What I need is what the following site does exactly but it's not a slideshow it's just a fading background image :
http://www.stevenharrisarchitects.com/
The image is 100% in width and 100% in height so no Cropping occurs, and this is what I want exactly.I had managed to do this part very easily with the following codes :
#bg-stat {
background: url('images/LANDING_PAGE.jpg') no-repeat center center fixed;
height: 100%;
background-size: 100% 100%;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-position: center;
filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src='images/LANDING_PAGE.jpg', sizingMethod='scale');
-ms-filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='images/LANDING_PAGE.jpg', sizingMethod='scale')";
}

I made the background-size : 100% 100% ;
It works fine, but the only problem that's left is that my client doesn't want the image to resize with the size of the window, instead it should act like on the site I mentioned above (Try resizing the window and you will see what I mean).
I don't want my background image to re-size to the 100% of width and height of my window, I want it to act just like in the above link I shared.
Also a link to my site :
http://leydenlewis.com/
Any help would be much appreciated.

A: If you need to use the background property and never want the image to be cropped, you should use background-size :contain;
div.big_background{
    position:fixed;
    top:0;
    left:0;
    width:100%;
    height:100%;
    background: url('http://placekitten.com/g/1200/800') no-repeat center top;
    background-size :contain;
}

A: Answer based on problem described above:
#bg-stat {
  width: 100%;
  height: 100%;
  background: url('images/LANDING_PAGE.jpg') no-repeat scroll 0 0 transparent;
  background-size: 100% auto;
}

Answer based on feedback:
CSS:
#bg-stat {
  width: 100%;
  height: 100%;
}

#bg-image {
  background: url("images/LANDING_PAGE.jpg") no-repeat scroll 0 0 transparent;
  height: 100%;
  width: 100%
  min-width: 1140px; // Based on img dimensions or arbitrary
  max-height: 735px; // Based on img dimensions or arbitrary
}

A: i think you need below code:
body
{
 background: url(image/background.jpg);
 background-attachment: fixed;
 background-size: cover;
}


text:
Q: How does angular material disable global scroll on dropdown focus? https://material.angular.io/components/select/overview
On dropdown open, the global scroll is disabled. However, no position property of <html> or <body> was changed, the global scroll bar was also present.

A: It is because the select drop down body is implemented with overlays in angular.
This overlay opens up on the  complete window kindof blocking access to the  underling html content.
You can inspect the html and see a overlay container inside body tag.
Once you open the select drop down and try inspecting on the screen it will be inside this overlay container


text:
Q: Копировать файлы в папку Download Android Всем привет. Не могу реализовать копирования файла с папки приложения "addons" в папку Download на устройстве. Возможно я не верно задаю пути? Или сам метод реализован неправильно? Помогите пожалуйста.
Пути:
File src = new File("src/main/res/addons/minecraft.mcworld");
File dst = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/Download/minecraft.mcworld");

Кнопка копирования:
down.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {

            try {
                copy(src, dst);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    });

Метод:
    public void copy(File src, File dst) throws IOException {

    InputStream in = new FileInputStream(src);
    try {
        OutputStream out = new FileOutputStream(dst);
        try {
            // Transfer bytes from in to out
            byte[] buf = new byte[1024];
            int len;
            while ((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
        } finally {
            out.close();
        }
    } finally {
        in.close();
    }
}


text:
Q: When i am trying to update the text of a field, the content changes in debug information but doesn't in reallity I am trying to update the text of a textview. But the problem is that it does update the text when i inspect the element with the debugger. But in reality the content of the textview stays the same.
Could someone take a look at it, please.
Here is my xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.example.firstapp.ZoekVelg$PlaceholderFragment"
    android:id="@+id/ZoekVelgLL">

    <Button
        android:id="@+id/button_detail"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="BekijkDetailPage"
        android:text="Bekijk details" />

    <TextView
        android:id="@+id/txt"
        android:text="gewoon tekst"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />

</LinearLayout>

If i make the changes you suggested, i get a null pointer exception
the code is like this now:
public class ZoekVelg extends ActionBarActivity {

    String merk, model, uitvoering;

    TextView textview;

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

        Intent intent = getIntent();
        merk = intent.getStringExtra("merk");
        model = intent.getStringExtra("model");
        uitvoering = intent.getStringExtra("uitvoering");

        TextView txt = (TextView) findViewById(R.id.txt);
        txt.setText("even updaten");

        if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.container, new PlaceholderFragment()).commit();
        }
    }

And the logcat:
06-13 10:50:07.410: I/Adreno-EGL(30518): <qeglDrvAPI_eglInitialize:316>: EGL 1.4 QUALCOMM build:  (CL4169980)
06-13 10:50:07.410: I/Adreno-EGL(30518): OpenGL ES Shader Compiler Version: 17.01.10.SPL
06-13 10:50:07.410: I/Adreno-EGL(30518): Build Date: 02/04/14 Tue
06-13 10:50:07.410: I/Adreno-EGL(30518): Local Branch:
06-13 10:50:07.410: I/Adreno-EGL(30518): Remote Branch:
06-13 10:50:07.410: I/Adreno-EGL(30518): Local Patches:
06-13 10:50:07.410: I/Adreno-EGL(30518): Reconstruct Branch:
06-13 10:50:15.819: I/Adreno-EGL(30591): <qeglDrvAPI_eglInitialize:316>: EGL 1.4 QUALCOMM build:  (CL4169980)
06-13 10:50:15.819: I/Adreno-EGL(30591): OpenGL ES Shader Compiler Version: 17.01.10.SPL
06-13 10:50:15.819: I/Adreno-EGL(30591): Build Date: 02/04/14 Tue
06-13 10:50:15.819: I/Adreno-EGL(30591): Local Branch:
06-13 10:50:15.819: I/Adreno-EGL(30591): Remote Branch:
06-13 10:50:15.819: I/Adreno-EGL(30591): Local Patches:
06-13 10:50:15.819: I/Adreno-EGL(30591): Reconstruct Branch:
06-13 10:50:17.261: W/dalvikvm(30591): threadid=1: thread exiting with uncaught exception (group=0x416a1e18)
06-13 10:50:17.271: E/AndroidRuntime(30591): FATAL EXCEPTION: main
06-13 10:50:17.271: E/AndroidRuntime(30591): Process: com.example.firstapp, PID: 30591
06-13 10:50:17.271: E/AndroidRuntime(30591): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.firstapp/com.example.firstapp.ZoekVelg}: java.lang.NullPointerException
06-13 10:50:17.271: E/AndroidRuntime(30591):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2596)
06-13 10:50:17.271: E/AndroidRuntime(30591):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2653)
06-13 10:50:17.271: E/AndroidRuntime(30591):    at android.app.ActivityThread.access$800(ActivityThread.java:156)
06-13 10:50:17.271: E/AndroidRuntime(30591):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1355)
06-13 10:50:17.271: E/AndroidRuntime(30591):    at android.os.Handler.dispatchMessage(Handler.java:102)
06-13 10:50:17.271: E/AndroidRuntime(30591):    at android.os.Looper.loop(Looper.java:157)
06-13 10:50:17.271: E/AndroidRuntime(30591):    at android.app.ActivityThread.main(ActivityThread.java:5872)
06-13 10:50:17.271: E/AndroidRuntime(30591):    at java.lang.reflect.Method.invokeNative(Native Method)
06-13 10:50:17.271: E/AndroidRuntime(30591):    at java.lang.reflect.Method.invoke(Method.java:515)
06-13 10:50:17.271: E/AndroidRuntime(30591):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1069)
06-13 10:50:17.271: E/AndroidRuntime(30591):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:885)
06-13 10:50:17.271: E/AndroidRuntime(30591):    at dalvik.system.NativeStart.main(Native Method)
06-13 10:50:17.271: E/AndroidRuntime(30591): Caused by: java.lang.NullPointerException
06-13 10:50:17.271: E/AndroidRuntime(30591):    at com.example.firstapp.ZoekVelg.onCreate(ZoekVelg.java:40)
06-13 10:50:17.271: E/AndroidRuntime(30591):    at android.app.Activity.performCreate(Activity.java:5312)
06-13 10:50:17.271: E/AndroidRuntime(30591):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1111)
06-13 10:50:17.271: E/AndroidRuntime(30591):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2552)
06-13 10:50:17.271: E/AndroidRuntime(30591):    ... 11 more

A: The problem is that you have two instances of the layout:

*

*one is set in setContentView(R.layout.activity_zoek_velg); (inflate is done by the superclass)

*one in View currView = inflater.inflate(R.layout.fragment_zoek_velg, null); (you do the inflate without attaching it to anything)

as you do TextView lookup on the second layout you change a TextView that is never shown to the user explaining what you see in debugger.
To fix comment out the lines:
    // LayoutInflater inflater = this.getLayoutInflater();
    // View currView = inflater.inflate(R.layout.fragment_zoek_velg, null);

and use:
    TextView txt = (TextView)findViewById(R.id.txt);

which will do the lookup on the layout set by setContentView(..) call.
ps: yes the invalidate is completely unnecessary :)

A: The view that is displayed on the screen is set when you call the setContentView() method. When you inflate a view, its just created and even though the setText() method works, you don't see anything because its done on the inflated view which you dont really see.
To modify views on the current screen you can directly call findViewById(R.id.ID) and then typecast it.
Here's a code that'll work :
public class ZoekVelg extends ActionBarActivity {

    String merk, model, uitvoering;

    TextView textview;

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

        Intent intent = getIntent();
        merk = intent.getStringExtra("merk");
        model = intent.getStringExtra("model");
        uitvoering = intent.getStringExtra("uitvoering");

        //Find View and then typecast
        TextView txt = (TextView) findViewById(R.id.txt);
        txt.setText("even updaten");

        if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.container, new PlaceholderFragment()).commit();
        }
    }


text:
Q: How can I queue the laravel excel import, on traditional way, and dispatch the job again after the first chunk reading My code: (controller)
public function formatCSV(Request $request){
    $filename = $request->input('filename');
    $exported_filename = pathinfo($filename, PATHINFO_FILENAME).".csv";
    $export_filepath = 'files/scrubber/output/'.$exported_filename;
    $data = [
        'file_name'       => $filename,
        'header_row'      => 10,
        'start_row'       => 10,
        'unit_sqft_col'   => null,
        'file_path'       => storage_path('app/files/scrubber/') . $filename,
        'export_path'     => $export_filepath,
    ];

    $scrubberJob = (new ScrubberJob($data))->delay(Carbon::now()->addSeconds(3));
    dispatch($scrubberJob);

    return redirect()->route('scrubbers.index')->with('toast.success','Scrubber job is put into queue, please wait for a while..');
}

On the above controller, I am dispatching ScrubberJob.
ScrubberJob
<?php

namespace App\Jobs;

use App\Imports\ChunkScrubberImport;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Excel;

class ScrubberJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $data;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($data)
    {
        $this->data = $data;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $import = new ChunkScrubberImport($this->data);
        Excel::import($import, $this->data['file_path']);
    }
}

This job is triggering ChunkScrubberImport
ChunkScrubberImport
<?php

namespace App\Imports;

use App\Exports\ChunkScrubberExport;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToArray;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\WithStartRow;
use Maatwebsite\Excel\Concerns\WithLimit;
use Maatwebsite\Excel\Concerns\WithStrictNullComparison;
use Illuminate\Support\Facades\Storage;

use Excel;

class ChunkScrubberImport implements ToArray, WithLimit, WithStartRow, WithStrictNullComparison
{
    protected $data;
    public $scrubbed_data;

    public function __construct($data, $scrubbed_data = [])
    {
        $this->data = $data;
        $this->scrubbed_data = $scrubbed_data;
    }

    public function array(Array $rows)
    {
        $this->scrubbed_data = $rows;
        return Excel::store(new ChunkScrubberExport($this->data,$this->scrubbed_data), $this->data['export_path']);
    }

    public function startRow(): int
    {
        return $this->data['start_row'];
    }

    public function limit(): int
    {
        return 1000;
    }
}

Now, this import is triggering ChunkScrubberExport
ChunkScrubberExport
<?php

namespace App\Exports;

use App\Helpers\APRHelper;
use App\Models\Scrubber;
use Maatwebsite\Excel\Concerns\FromArray;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\RegistersEventListeners;
use Maatwebsite\Excel\Events\AfterSheet;
use Maatwebsite\Excel\Concerns\WithStrictNullComparison;

class ChunkScrubberExport implements FromArray,WithStrictNullComparison
{
    use RegistersEventListeners;
    protected $data;
    protected $scrubbed_data;

    public function __construct($data, $scrubbed_data = [])
    {
        $this->data = $data;
        $this->scrubbed_data = $scrubbed_data;
    }
    public function array(): array
    {
        $arr = $this->scrubbed_data;

        $rec_arr = $empty_col = array();
        $empty_col_checked = false;
        foreach ($arr as $ak => $av){
            //only if row is not empty (or filled with null), will get inside if condition
            if(count(array_filter($av)) != 0){
                if(!$empty_col_checked){
                    foreach($av as $k => $v){
                        if($v == ''){
                            $empty_col[] = $k;
                        }
                    }
                    $empty_col_checked = true;
                }
                $rec_arr[] = $av;
            }
        }

        foreach($empty_col as $ek => $ev){
            //get all values from a columns, which don't have value in header row
            //and check if all the values from this particular column is empty
            //if empty unset the columns
            if(empty( array_filter(array_column($rec_arr,$ev))) )
            {
                //unset array keys from whole array
                foreach($rec_arr as &$item) {
                    unset($item[$ev]);
                }
                unset($item);
            }
        }

        foreach ($rec_arr as $ak => $av) {

            foreach ($av as $k => $v) {

                //other stuff

            } //end foreach $av

        } //endforeach $rec_arr

        return $rec_arr;
    }
    public static function afterSheet(AfterSheet $event)
    {
        $active_sheet = $event->sheet->getDelegate();
        $centered_text = [
            'alignment' => [
                'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER, 'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER
            ]
        ];
        $active_sheet->getParent()->getDefaultStyle()->applyFromArray($centered_text);

    }
}

this is working fine for 1 cycle or fetch, now I have the following questions.

*

*After the first cycle, I want to update the start_row to $data['start_row'] + 1000 since 1000 is the limit, but, I don't know what might be the best place to put this one. After 1 cycle I want to trigger, scrubberjob written below
but with updated start_row
 $scrubberJob = (new ScrubberJob($data))->delay(Carbon::now()->addSeconds(3));
 dispatch($scrubberJob);

*Since, on first cycle, the file would already be created since I already know the filename, which is stored in $data['export_path']. So, instead of overwriting the old file, I want to append rows to the already existing file from the second cycle.

*How to detect the end of the file, so that no more ScrubberJob is dispatched.
By the way, I have also seen about ShouldQueue in docs but I am not sure if it could provide all the needs I have mentioned here. Or am I just complicating things and should go with shouldQueue instead? But still, that might need the solution of my question number 2


text:
Q: Transforming a polynomial into the polynomial $3^{-1}s^3-z s$ I am trying to derive asymptotics for the Laguerre polynomial and I ended up with a polynomial
$$\exp(
(c_0-c_1\lambda) s+c_2s^2
+c_3 s^3
+\mathcal{O}(N^{-1/3})
)
$$
Now my goal is to bring the polynomial in the $\exp$-function into the $\frac{s^3}{3}-\lambda s$ form.
I tried to apply the cubic transformation method but the computation gets heavy and complicated, so I don't think this will lead me anywhere. Is there a way to transform the polynomial?

A: A slightly simpler case you can work from, suppose the polynomial in the exponential is $p(s) = a_1s + a_2s^2 + s^3$ and that you want to find a change of variable $t = s + c$ such that $A_0 + A_3t^3/3 - zt = p(s)$.
Taking
\begin{align}
A_0 &= (2a_2^2 - 9a_1)a_2/27,\\
A_3 &= 3,\\
c &= a_2/3, \\
z &= a_2^2/3 - a_1
\end{align}
you have
\begin{equation}
A_0 + A_3t^3/3 - zt = a_1s + a_2s^2 + s^3.
\end{equation}
The term $A_0$ can be factored out of the exponential.


text:
Q: prevent the vector arrow from centering over the letter + subscript I want to typeset a vector with an arrow over the top that has a long subscript. My approach makes the vector arrow center over the letter including its subscripts, but I want the arrow to be centered over the letter only instead. Does anyone have an idea how to achieve this? I guess it will be kind of easy for you folks, but I couldn't find an answer by googling.
My code:
\documentclass{article}
\usepackage{amsmath}

\begin{document}

\(\Vec{H_{\mathrm{n,1}}}\)

\end{document}

my output:

I would like the vector arrow to be centered over the "H" instead of the whole thing.

A: Personally, using a vector notation with an upward slanting arrow positioned toward the center is not at all appealing to me. There are so many ways to write a vector in LaTeX. Here is a suggestion using esvect package with the c option. But you can choose any of the options you like from the link that I have added.
\documentclass[a4paper,12pt]{article}
\usepackage{amsmath,amssymb}
\usepackage[c]{esvect}

\begin{document}
\(\vv{H}_{n,1}\)

\end{document}

This is with the option f similar to tikz-cd:
\documentclass[a4paper,12pt]{article}
\usepackage{amsmath,amssymb}
\usepackage[f]{esvect}%%%%%%%%%%%%%%%% option f.

\begin{document}
\(\vv{H}_{n,1}\)

\end{document}


text:
Q: refresh canvas after every change I'm trying to copy image contents into a canvas, pixel by pixel and I want that to be visualized while it's happening. However, the canvas just stays blank while the process is undergoing and then when it's finished, the cloned image is displayed in full. Is there any way for the canvas to be "refreshed" or "reloaded" after every pixel change?
Here is part of the code I'm using:
for (var x = 0; x < w; x++) {
    for (var y = 0; y < h; y++) {
        ctx2.putImageData(ctx1.getImageData(x,y,1,1),x,y);
    }
}

...where ctx1 is the context object of the original and ctx2 - context object of the clone.
I'm interested in this only for visualization purposes. I'm aware it's probably not quite efficient.

A: I managed to do it eventually by using the setIntervalX function described here, with 1 millisecond delay. Draws line by line, instead of pixel by pixel but it's good enough for me and likely more efficient. Code would probably be neater with the generator function Jon suggested in the comments above but I've battled this long enough already and I just need something that works :)
var x = 0;
setIntervalX(function(){drawVerticalLine(ctx1,ctx2,x++,image_height)},1,image_width);

function setIntervalX(callback, delay, repetitions) {
    var r = 0;
    var intervalID = window.setInterval(function () {

       callback();

       if (++r === repetitions) {
           window.clearInterval(intervalID);
       }
    }, delay);
}

function drawVerticalLine(ctx1,ctx2,x,image_height) {
    for (var y = 0; y < image_height; y++) {
        ctx2.putImageData(ctx1.getImageData(x,y,1,1),x,y);
    }
}


text: Q: how can i switch from my amd itegrated graphics to my dedicated graphics card (rtx 3060) I bought a lenovo legion 5 with rtx 3060 and ryzen 5600h and I want to switch from radeon integrated graphics to my 3060


text:
Q: how javascript interpreter understands the data type of a variable? I want to know , how javascript interpreter knows the datatype of a variable when execution . In case of Java and other languages , we use to declare the data type with but in javascript we simply declare it as "var".
var number1 = 2;
var number2 = 3;

var number3 = number1+number2;

console.log(number3);

Output is 5 . Why not 23?
Thanks.

A: Because neither is a string.
The type of a variable is associated with that variable's internal representation.
During source parsing variables are lexed according to the language grammar. No quotes, not a string, so it's a number. Since both are numbers, the result is a number.

A: your variables are interpreted as a number because you did not make it a string using "".
var number1 = 2;
var number2 = 3;

var number1_ = "2";
var number2_ = "3";

var number3 = number1+number2;
var number3_ = number1_+number2_;

console.log(number3); // 5
console.log(number3_); // 23

A: Because 2 and 3 are numbers. Declaring a variable with var doesn't mean "remove the type", or "set the type to a string", it just means that it can hold any type. You assigned a number to number1, and a number to number2. So adding these together the JS interpreter knows it's adding two numbers together.

A: Because it's a number type:
typeof 4
--> "number"

typeof '4'
--> "string"

A: JavaScript variables are containers for storing data values.
when you assign a number to a container it's interpreter know it as number
else if you assign a string it considered as string
var x = '2' ;
var y = '3'
console.log(typeof x) // string
console.log(typeof y) // string

console.log(x+y) // '23'

and now assign a number to each one :
var x = 2 ;
var y = 3
console.log(typeof x) // number
console.log(typeof y) // number

console.log(x+y) // 5

A: I want to directly answer your question of how the javascript interpreter knows the datatype of a variable.
The thing you need to know about javascript unlike, lets say, java is that a variable in JS doesn't hold the type.  In JS it's the value that holds the type.  And the value's type cannot be changed.  But it can be coerced.
So even though a variable's value is intrinsicly a number, like the number 5, a new string "5" can be created from it through implicit coercion without you explicitly changing the variable's type because the variable itself never held the type to begin with.
It's not that the variable changes to a string, but rather a new string value will be created and used for the variable depending on the context of the expression you are using it in.
Look up javascript coercion for more info.


text:
Q: Landscape ask for "At least three machines with more than one disk" I'm currently plaing on a Proof of Concept about Ubuntu OpenStack, after some battle with landscape I continue to see that it ask for 3 servers but I have 3 of that with 2 disks and 2 NICs.
What's wrong?

A: As shown in the screenshot, you only have two servers available in MAAS. The first one "creamy-scent.maas" is already used, (probably this is where Landscape itself is deployed?).
You need at least three which are in the Ready state in MAAS.


text:
Q: How to convert a string to a dict from a list? I have tried several ways to convert a dict-like str from a list to a dict, but cannot figure out how to interpret the error message correctly.
I have a list:
list = [(45, "{'kingdom': 'Plantae', 'phylum': None, 'class': None, 'order': None, 'family': None}"), (12383, "{'kingdom': 'Plantae', 'phylum': None, 'class': None, 'order': 'Fagales', 'family': None}"), (12384, "{'kingdom': 'Plantae', 'phylum': None, 'class': None, 'order': 'Primulales', 'family': None}"), (12385, "{'kingdom': 'Plantae', 'phylum': None, 'class': None, 'order': 'Magnoliales', 'family': None}"), (12386, "{'kingdom': 'Plantae', 'phylum': None, 'class': None, 'order': 'Celastrales', 'family': None}")]

and want to convert the dict-like string into a dict, so I can access the values by key.
I have tried:
test = (list[0][1]).replace("'", "\"")
dict(test)

but get the following error:
ValueError: dictionary update sequence element #0 has length 1; 2 is required

I also tried json.loads()
test2 = json.loads(test)

which returned:
JSONDecodeError: Expecting value: line 1 column 34 (char 33)

When I manually insert the string in the dict() function, the string successfully converts to a dict but not when using the list index.
I would appreciate it if someone could explain why there is this difference and how I can convert the string directly into a dict.
Thanks for any help

A: You can use ast.literal_eval:
from ast import literal_eval

lst = [(45, "{'kingdom': 'Plantae', 'phylum': None, 'class': None, 'order': None, 'family': None}"), (12383, "{'kingdom': 'Plantae', 'phylum': None, 'class': None, 'order': 'Fagales', 'family': None}"), (12384, "{'kingdom': 'Plantae', 'phylum': None, 'class': None, 'order': 'Primulales', 'family': None}"), (12385, "{'kingdom': 'Plantae', 'phylum': None, 'class': None, 'order': 'Magnoliales', 'family': None}"), (12386, "{'kingdom': 'Plantae', 'phylum': None, 'class': None, 'order': 'Celastrales', 'family': None}")]

output = [(num, literal_eval(dct_rep)) for num, dct_rep in lst]

print(output) # [(45, {'kingdom': 'Plantae', 'phylum': None, 'class': None, 'order': None, 'family': None}), ...]
print(output[0][1]['kingdom']) # Plantae

The list comprehension converts each dict representation into a true dict. After that you can access the data in a more natural way.

A: I would look at eval
test_dict = eval(list[0][1])

Note: This is not recommended in production code as this can run any python code


text:
Q: Find derivative of Taylor series How would one differentiate a function in this form?
$$f(x) = f(a)+{\frac {f'(a)}{1!}}(x-a)+{\frac {f''(a)}{2!}}(x-a)^{2}+{\frac {f'''(a)}{3!}}(x-a)^{3}$$
I'm sorry if this is something obvious, I'm not great with maths. I tried searching for the answer with no luck.

A: Differentiate with respect to $x$ ? On the left you have simply $f'(x)$ and on the right you have polynomial in $x$ ($a$ is a constant with respect to the derivative in $x$), so you get
$$0+f'(a)+f''(a)(x-a)+\frac{f'''(a)}{2}(x-a)^2$$.

A: The derivative is really simple: it is identical to the original, but the first term is deleted (because it is a constant), and all the other coefficients are shifted to the left (except for the factorial denominator)
$$f(x) = f(a)+{\frac {\color{Blue}{f'(a)}}{1!}}(x-a)+{ \frac {\color{Red}{ f''(a)}}{2!}}(x-a)^{2}+{\frac {\color{Magenta}{f'''(a)}}{3!}}(x-a)^{3}
\\
\\
f'(x) ={\color{Blue}{f'(a)}}+ { \frac {\color{Red}{f''(a)}}{1!}}(x-a)+{\frac {\color{Magenta}{f'''(a)}}{2!}}(x-a)^{2}+{\frac {f''''(a)}{3!}}(x-a)^{3}$$
You can check it, by deriving each term of the summation.

A: Each term has the form $$t_n(x) = \frac{(x-a)^n}{n!}  \lim_{x \rightarrow a} \left( \frac{{\rm d}^n}{{\rm d}x^n} f(x) \right)$$
The derivative of such term is
$$t_n'(x) = \left( \frac{{\rm d} }{{\rm d}x} \frac{ (x-a)^n}{n!} \right) \lim_{x \rightarrow a} \left( \frac{{\rm d}^n}{{\rm d}x^n} f(x) \right)$$
with the result
$$ t_n'(x) = \frac{(x-a)^{n-1}}{(n-1)!} \lim_{x \rightarrow a} \left( \frac{{\rm d}^n}{{\rm d}x^n} f(x) \right) $$
In the end $f'(x) \approx  \sum \limits_{n=1}^\infty t_n'(x) $


text:
Q: CakePHP find conditions not working I have an action for CommentsView in which i want to retrieve all the comments with a condition that Comment.post_id = Post.id but when i debug it, it gives me an empty array.
Action CommentsView:
public function commentsview()
{

    $commentsview = $this->Comment->find('all', array('conditions'=>array('Comment.post_id' => 'Post.id')));

    if (!empty($this->params['requested']))
    {
        return $commentsview;
    }

}

A: You are providing the condition for a join which is passed differently.
The conditions arguments are for a WHERE clause.
But you only need to specify:
$comments = $this->Comment->find('all',
    array(
        'conditions'=>array(
            'Comment.post_id' => $post_id
        )
    )
);

Or when you are fetching the comments from the PostsController
$comments = $this->Post->Comment->find('all',
    array(
        'fields'=>array(
            'Comment.*'
        )
        'conditions'=>array(
            'Post.id' => $post_id
        )
    )
);

A: change your function to this:
public function commentsview($post_id=null) {

    $commentsview = $this->Comment->find('all', array('conditions'=>
                                            array('Comment.post_id' => $post_id))
                                        );
    debug($commentsview);
    exit;

}

Visit this URL: yourapp.com/comments/commentsview/37
The comments will be output. Now you know it's working. Then you can pass it to the view or do whatever.
You have asked similar questions several times. This is a BASIC concept.


text:
Q: Метод init и множественное наследование python Есть два класса которые наследуются третьим. Не видит инит второго класса
class Sellary(object):
    """Sellary Class """

    def __init__(self, value):
        self.value = value

    def get_sellary(self):
        return "{}$".format(self.value)

class User(object):
    """ USER CLASS """

    def __init__(self, name, sername):
        self.name = name
        self.sername = sername

    def __repr__(self):
        return "This is {} {}".format(self.name, self.sername)

class Developer(User, Sellary):
    """ THis is a Developer Class who extends User, Sellary"""

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

    def __repr__(self):
        return "hello I'm a Developer {} {}".format(self.name, self.sername, self.get_sellary())

if __name__ == '__main__':
    John = Developer('John', 'Doe', value=10000)
    print(John)

Последний аргумент value не присваивается, подскажите как этим пользоваться)
TypeError: __init__() got an unexpected keyword argument 'value'

A: В ответе @AndrioSkur синтаксическая ошибка. Вызывать инициализаторы действительно надо явно, но вызов будет иметь такой вид.
class Developer(User, Sellary):
    def __init__(self, name, sername, value):
        Sellary.__init__(self, value)
        User.__init__(self, name, sername)

A: init по умолчанию узнаеться через MRO(то есть с левого класса). Если вам надо 2 init вызывает их явно.
__init__(self, name, surname, value):
     super(User, self).__init__(name, surname)
     super(Sellary, self).__init__(value)

Хотя воообще говоря, я не уверен в корректности такого подхода...

A: Тема не новая, но правильный ответ так и не появился.
Может я и не дока, но мой вариант хотя бы рабочий:
class Square:
    def __init__(self, edge_length):
        self._edge_length = edge_length

class Triangle:
    def __init__(self, tri_base, tri_height):
        self._tri_base = tri_base
        self._tri_height = tri_height

class Pyramid(Square, Triangle):
    def __init__(self, edge_length, tri_base, tri_height):
        Square.__init__(self, edge_length)
        Triangle.__init__(self, tri_base, tri_height)

Python 3 все работает ошибок не появилось.
Вообще строго говоря тут такой вариант уже был, но почему-то не зашел!
Я намеренно не стал править исходный код про Develop'ера.


text:
Q: Where to add DNS for my domain i.e. ns1.mydomain.com (Any disadvantages?) My VPS hosting provider has agreed that I can use their DNS servers to present a more professional look by giving out vanity nameservers to my clients.
For example, they have said I need a DNS records directing ns1.MyDomain.com to the IP of ns1.VPSProvider.com.
Therefore any DNS queries sent to ns1.MyDomain.com will then be sent to the IP for ns1.VPSProvider.com instead and they will respond
The domain is registered with 123-reg. Therefore, how/where do I add a dns record for ns1.MyDomain.com would it be with 123-reg's help? Is it just a CNAME record of ns1?
Secondly, are their any disadvantages by having a vanity nameserver like this e.g. spam, google, rdns etc

A: You cannot use CNAME records since the right-hand side of a NS record cannot be an alias (RFC 1035, section 3.6.2).You have to use A and AAAA records and keep them in synch with VPSProvider.com. Not easy because they can change suddenly.
Frankly, if you do not know the DNS at all, it is better to not use "vanity name servers", specially for paying customers...

A: You need to create two A records pointing ns1.mydomain.com to the ip address of ns1.vpsprovider.com, and ns2.mydomain.com to the ip address of ns2.vpsprovider.com.  CNAME entries add extra dns lookups, and should be avoided when creating nameservers (and infact break RFCs).
If you're using these vanity nameservers for your own domain and not just for other people's domains, then you'll also need to set the ns records for your domain to your own nameservers and the ip addresses of the nameservers provided.  You'll want to do all this on your vps provider's nameservers rather than 123-reg's because you'll no longer be using 123-reg for anything other than domain registration.
There are no disadvantages in having a nameserver setup like this other than the fact that you then have to use the control panel of the vps provider to change your dns rather than the 123-reg control panel (though that may actually be an advantage).
I don't recall if 123-reg provide .uk nameservers or not.  If they do, and your domain is a .uk domain, then there will be a small theoretical loss of speed by switching to a .com nameserver.  However this won't be noticable.


text:
Q: Routes in Laravel with or without a forward slash? What's the recommended approach for declaring routes: with a forward slash or is it better to leave it out? Are there any benefits to using one over the other or is it just a matter of preference?
Is it better to use this:
 Route::get('/read', function(){
        $user = User::findOrFail(1);
            return $user;
    });

Or this instead:
Route::get('read', function(){
    $user = User::findOrFail(1);
        return $user;
});

Thanks in advance.

A: It comes down to preference. When passing the route, it actually trims the forward slashes off, then formats it properly. In Illuminate/Routing/Router.php, all routes go through the prefix function, which looks like this:
protected function prefix($uri)
{
    return trim(trim($this->getLastGroupPrefix(), '/').'/'.trim($uri, '/'), '/') ?: '/';
}

So if you create a group prefix /test/ and and a uri of /route, it becomes test/route


text:
Q: Symfony 2 / Oracle Querybuilder result is case sensitive I have a strange behavior with a query result in Symfony 2.
I have data like this in an Oracle Database, in this exact order :

*

*BU 4 2015

*bU 2

*BU C

*BU S

*BU 4 2014

notice, the lower case in the second data
I Just want to display this list by alphabetical order, without any case sensitive support.
The wanted result :
- BU C
- bU 2
- BU 4 2014
- BU 4 2015
- BU S

Now, here is the Querybuilder, made with Symfony 2.5.12 :
 $queryBuilder = $this->createQueryBuilder('e');
 $queryBuilder->orderBy('e.name');

But the query, show my list in this order :
- BU C
- BU 4 2014
- BU 4 2015
- BU S
- bU 2

*

*When i play the query displayed in symfony 2 profiler in my Oracle database client, i get the wanted result.

*When i dump the query builder result, I get the wrong order list.
I manage to solve my problem by this
$queryBuilder = $this->createQueryBuilder('e');
$queryBuilder
    ->select(e)
    ->addSelect('UPPER(e.name) as HIDDEN name')
    ->orderBy('name');

So, I just want to know why I get this strange behavior with the querybuilder ?
Thanks.

A: First of all, your "wanted result" is not actually in alphabetical order. A case-insensitive sort would yield the following order:
bU 2
BU 4 2014
BU 4 2015
BU C
BU S

Second of all, the way to do a case-insensitive sort with Oracle SQL is to use UPPER() or LOWER() on the column(s) you want to sort by, like so:
SELECT *
FROM e
ORDER BY UPPER(e.name);

Finally, the way to do a case-insensitive sort with Doctrine QueryBuilder is exactly how you have done it: by adding UPPER(e.name) as HIDDEN name and then sorting by that field.
There is no strange behavior by QueryBuilder in this example.


text:
Q: mysql : выборка из двух таблиц с count() во второй Смысл выборки состоит в том,чтобы из одной таблицы выудить количество уникальных позиций, из второй - количество позиций,соответствующих выборке из первой таблицы.
Вот такой запрос работает корректно:
SELECT t1.*,COUNT(t2.*) as cnt FROM t1 JOIN LEFT t2 ON t1.field=t2.field GROUP BY t1.field

Вопрос : является ли такой запрос оптимальным?
Не будет ли при каждой итерации в правой таблице подсчитываться общее количество позиций соответствующие условию ,а  потом выполнятся группировка ? То есть не будет ли излишней работы ?
Вроде бы MYSQL отрабатывает быстро, но и позиций мало в таблице.


text:
Q: How to show tab close button in GVIM? Please let me know how to show the close button on each tab page in GVIM.
Also, is it possible to set a warning if I am closing GVIM with multiple tab pages open?

A: Showing the close button
The 'tabline' option can include a %X marker for the close tab button, but that only works for the console version of the tab line. :help 'guitablabel' explicitly states:

Note that syntax highlighting is not used for the option.  The %T and %X items are also ignored.

So, to literally get what you want, you'd have to switch to the (uglier) text-based tab line with
:set guioptions-=e

But note that using the mouse (even though you may be customized to that by other applications like web browser tabs) is discouraged in Vim. If you right mouse button-click on a GUI tab label, you can alternatively also choose |Close tab| from the popup menu.
Preventing tab close
(Note that asking multiple questions is frowned upon here; please ask them separately.)
I don't think this is possible; there is a VimLeavePre event that you could hook into, but it cannot prevent the closing of Vim; the action (e.g. :qall!) cannot be undone. If you are used to closing Vim always via a mapping or command, you could overwrite that and include a check in there (using tabpagenr('$') > 1).
If you're concerned with losing your window / tab layout, rather have a look at Vim sessions (which can be persisted automatically in the background). This will allow to re-launch Vim with the previously opened windows.

A: Short Answer
Use buffers effectively!
Long answer
You might consider use :tabclose to close your tabs. This has the benefit of closing the tab (and keeping you away from your mouse) but also being just annoying enough to motivate a workflow change over to using buffers and splits. As for a warning about closing a tab with multiple windows, I see little benefit if you have 'hidden' set then the buffers are still there so no harm. If you do not have 'hidden' than any modified buffers will be prompted before they are closed.
Why not tabs
Tab pages are great. However it all comes down to vim treating tab pages as more of view-ports into a group of windows or workspaces. Tab pages just don't scale well. Just open some other GUI editor and open up 20 or so tabs. It becomes tricky to deal with. I have had over a 100 buffers open and switch between them without worrying. Buffers just scale in ways that tabs do not. Buffers and splits also work well with smaller windows which is often the case when using terminals.
Don't just take my word for it. Here are some more supporting information:

*

*Vimcast's Drew Neil: How to use tabs

*"proper" usage of buffers

*Take a look at Bram Moolenaar: Seven habits of effective text editing Video

*On stackoverflow: Using Vim's tabs like buffers

*Buffers, windows, and tabs
Quick Buffer Tips and Tricks

*

*set hidden will hide buffers when abandoned.

*Use :sb to switch to a buffer you already opened.

*:sb and :b both can take partial names and globs. e.g. :sb foo*

*Take a look at 'switchbuf' and change to your preferences.

*Learn to love :sp, :new, and all type of split commands.

*Learn some <c-w> commands to make your life with splits easier.

*Use capital letter marks to jump back to buffers where you know you will jump back to.

*Use tags to jump to definitions.

*Possibly use cscope along with tags

*Use <c-6> to switch to the previously edited file.

*Use <c-o> and <c-i> to move older/newer positions in your jump list.

*Possibly make use of one of the many buffer plugins out there. e.g CtrlP
For more information see:
:h :sb
:h windows
:h 'hidden'
:h 'swb'
:h ctrl-6
:h ctrl-o
:h tags
:h cscope
:h tab-page-commands

A: If you need this, you are probably doing it wrong. You don't need mouse with vim.
But how about
nnoremap <MiddleMouse> :tabclose<CR>

Other then that see TabLineSet.vim : A Vim7 tabline customization  which has

closers         : add hot spots ("!") to the tab for click-to-close


text:
Q: Log file batch script with expire date I have a small problem with a log file. It must save in log a current date and a expire date which is 10 days. Something like this:
date: 27.08.2014 expire date: 06.09.2014.

I have tried script:
PowerShell $date = Get-Date; $date=$date.AddDays(-1); $date.ToString('yyyy-MM-dd')

but I cant figure out, how to insert it in a log.txt file.
Have tried >>C:\log.txt
Please help!

A: This is one way: it just adds the part at the end of the line.
PowerShell $date = Get-Date; $date=$date.AddDays(-1); $date.ToString('yyyy-MM-dd') >>"c:\log.txt"


text:
Q: Copy and paste Excel data into one column I have an Excel 2010 sheet with 300 or so columns. I need all of the data to be pasted into one column (not merged). Is there any way to do this other than copying one column, scrolling to the bottom on the first, pasting, and repeating for every column?

A: Try this (you may need to change ; to ,):

A: You can use following code. It will paste all values to the column A:
Sub test()
    Dim lastCol As Long, lastRowA As Long, lastRow As Long, i As Long

    'find last non empty column number'
    lastCol = Cells(1, Columns.Count).End(xlToLeft).Column

    'loop through all columns, starting from column B'
    For i = 2 To lastCol
        'find last non empty row number in column A'
        lastRowA = Cells(Rows.Count, "A").End(xlUp).Row
        'find last non empty row number in another column'
        lastRow = Cells(Rows.Count, i).End(xlUp).Row

        'copy data from another column'
        Range(Cells(1, i), Cells(lastRow, i)).Copy
        'paste data to column A'
        Range("A" & lastRowA + 1).PasteSpecial xlPasteValues

        'Clear content from another column. if you don't want to clear content from column, remove next line'
        Range(Cells(1, i), Cells(lastRow, i)).ClearContents
    Next i

    Application.CutCopyMode = False
End Sub

A: Try this macro
Sub combine_columns()

Dim userResponce As Range

Columns(1).Insert ' insert new column at begining of worksheet
lrowEnd = 1    'set for first paste to be cell A1
    'get user selection of data to combine
Set userResponce = Application.InputBox("select a range with the mouse", Default:=Selection.Address, Type:=8)
    'this IfElse can be removed once macro is tested.
If userResponce Is Nothing Then
    MsgBox "Cancel clicked"
Else
    MsgBox "You selected " & userResponce.Address
End If

Set a = userResponce
   'this loops through the columns selected and pastes to column A in a stacked foormat
For Each b In a.Columns
Rng = "A" & lrowEnd
    Range(b.Address).Copy
     Range(Rng).PasteSpecial
lrowEnd = Cells(Rows.Count, "A").End(xlUp).Row + 1  'find next blank row
Next

End Sub