Q: MYSQL - MAX() returns wrong date I have a mysql table like this
+----------+----------+-------------------+
| entrykey | user_key |     validfrom      |
+----------+----------+-------------------+
|        1 |        3 | 2016-4-1 0:0:0.0  |
|        2 |        3 | 2016-12-1 0:0:0.0 |
|        3 |        2 | 2016-12-1 0:0:0.0 |
|        4 |        2 | 2016-3-1 0:0:0.0  |
+----------+----------+-------------------+

now I am trying to get only the row for each user where the validfrom is the newest. So I am doing a query like this:
SELECT entrykey, user_key, max(validfrom)
FROM table
Group by user_key;

It is working fine for almost all of my data, just this two examples I posted here in the table select the wrong row which is older. So for user_key 3 it selects entrykey 1 and for the user_key 2 it selects entrykey 4.
What am I doing wrong?

A: I guess the validform should be 2016-03-01 instead of 2016-3-01 because it is not converted into date before compare.

A: I am totally agree with the point made in the accepted answer (+1 for that). But, even if op somehow convert validfrom from string to DateTime, his attempt won't give him the desired result.
Let's examine the query given in question:
SELECT entrykey, user_key, MAX(STR_TO_DATE(validfrom, '%Y-%c-%e')) as date1
FROM table
Group by user_key;

Now, this query will return user_key with maximum value of validfrom for that particular user_key. But the entrykey won't be the entrykey with max validfrom. (Check the first result in demo link)
In order to achieve above task, following query will work just fine!
SELECT t1.entrykey, t1.user_key, t2.maxdate as MaxDate
FROM t t1
inner join (select user_key,MAX(STR_TO_DATE(validfrom, '%Y-%c-%e')) as maxdate
            from t
            Group by user_key
            ) t2
on t1.user_key = t2.user_key and t1.validfrom = t2.maxdate;

Click here for Demo with DateTime as datatype of validfrom
Click here for Demo with STR_TO_DATE() function
Hope it helps!


Q: .htaccess Php rewrite url I try to realize a system of rewriting URLs in .htaccess.
Then here is my goal:
If I have an url of this form: http://localhost/view.php?Id=456
Then I want to transform it to: http://localhost/456
I use this rule in htaccess:
RewriteRule ^ ([a-zA-Z0-9] +) $ view.php? Id = $ 1
Now this works very well!
But my problem I want to add points to id ie instead of 456 I can put: my.book
That is to say: http://localhost/my.book

A: Try this:
RewriteRule ^([a-zA-Z0-9\.]+)$ view.php?Id=$1

Basically what I did is I added \. with your pattern. This will make sure your regex matches any letter (small/caps), decimal numbers and periods (.). Hope this helps :)

A: RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([a-zA-Z0-9\.]+)$ view.php?id=$1 [QSA,L]

You need RewriteCond %{REQUEST_FILENAME} !-f before the RewriteRule line to tell the server that the RewriteRule written below to be executed if the input passed in the URL is not an actual file. Because server searches for a file matching the input you pass in the URL and also it won't work in case you pass my.book in the URL since web server recognizes . as prefix for extension like .php or .html or like so and thereby it results in Not Found error if there is no file named my.book exists. So, you also need to escape . in the URL.
To allow .'s in the input, you need to add . with escape sequence \ in the character class group like ^([a-zA-Z0-9\.]+)$. Note, allowing this can result in escaping the extension in the URL, that is, passing view.php in the URL won't navigate to the actual file. Rather, it will be considered as a value in the query string.


Q: Google code downloading source This might be an extremely stupid question, but for the life of me, I cannot figure out how to download this:
http://code.google.com/p/xmppframework/source/browse/#hg%253Fstate%253Dclosed
There is nothing under the "downloads" tab. And when I try to "clone" it using my terminal it says "HG command not found".
Any ideas??

A: hg is the executable for Mercurial, you're going to need to download and install Mercurial.
Once you have it installed you can use it to clone the project:
hg clone https://xmppframework.googlecode.com/hg/ xmppframework


Q: How To classify Read and Unread news in Feed Reader? I am working on a RSS Feed module in WPF Application. I am getting news items in xml document from the httpWebResponse. I want to calssify the unread feeds. How can we identify the user read or Unread the news article ?

A: It depends on how the web pages linked by RSS feed are opened.
If they are opened within your app using a WebBrowser control, then you must track history of read feeds yourself within your app. See WPF WebBrowser Recent Pages.
You can use the Navigated event of the WebBrowser control.
If they are opened using a particular web browser, then you can eventually read somehow the history of that particular browser. But when the history gets deleted, your read/unread status gets deleted as well.


Q: How to invert the green channel of an image in Python? How do I invert one channel of an RGB image? In this case my image is a normal map for a 3D engine, saved in an image format like JPEG or TIFF, and I want to invert the green channel — that is, completely reverse the highs and lows in the green band.

A: You can accomplish this by installing and using Pillow, which can work with most image formats (JPEG, PNG, TIFF, etc.).
from PIL import Image
from PIL.ImageChops import invert

image = Image.open('test.tif')
red, green, blue = image.split()
image_with_inverted_green = Image.merge('RGB', (red, invert(green), blue))
image_with_inverted_green.save('test_inverted_green.tif')

After loading the image from your file, split into its channels with Image.split, invert the green channel/image with ImageChops.invert, and then join it together with the original red and blue bands into a new image with Image.merge.
If using a format that's encoded in something other than RGB (such as PNG, which has an additional transparency channel), the image-opening line can be amended to:
image = Image.open('test.png').convert('RGB')

Testing with this image:

Produces this:

(ImageChops, by the way, looks like a very odd term, but it's short for "image channel operations".)

A: I assume you have a numpy (or torch tensor) image - you can index on the green channel (assuming channels are your last dimension)
img[:, :, 1] = 255 - img[:, :, 1]

I am assuming by invert you want 0 -> 255 and 255 -> 0

A: T(r) = L – 1 – r

L=256

L-1=255(Max)

r=Each pixel of the image

s=255-r

s= T(r) =255-r


Q: PHP is ignoring code like var_dump(), die(), etc This is a very weird situation like I've never seen in my life.
For some reason PHP is ignoring a lot of code inside a static function.
Here is the example:
static function describe($tableName, $columns = '*') {
    var_dump($tableName);
    die();
    $md5 = ...code...
    if (!empty($content = Cache::get($md5))) {
        return unserialize($content);
    }

I keep getting the error
Parse error: syntax error, unexpected '=', expecting ')'

in
if (!empty($content = Cache::get($md5))) {

And yes it recognises the class Cache and its function.
Can anyone guide me?

A: Prior to PHP 5.5, empty() function can only support strings.
Any other input provided to it like: a function call e.g.
if (empty(myfunction()) {
 // ...
}

would result parse error.
As per documentation:

Note: Prior to PHP 5.5, empty() only supports variables; anything else
  will result in a parse error. In other words, the following will not
  work: empty(trim($name)). Instead, use trim($name) == false.

Better way, get your $content variable first and then check if it is not empty.
Rather than initialising it and checking its emptiness simultaneously.
You can separate the if statement in two parts like this:
if ($content = Cache::get($md5) && !empty($content)) {
 return unserialize($content);
}

A: Try this,
if (!empty($content) && $content = Cache::get($md5)) {
        return unserialize($content);
}

OR : To get easy readability
if (!empty($content){
   if($content = Cache::get($md5)){
       return unserialize($content);
   }
}


Q: How do I superimpose a conditional formated heatmap based on one set of values over a different set of values in Excel 2013 I would like one cell to be formatted with a gradient color based on the value in another cell.  For example, I would like cells A1 and A2 to be highlighted based on the values in B1 and B2.  If I choose the red to yellow to green highlighting (i.e., "Color scales" under "Conditional Formatting") in Excel I would expect that if B1 = 1 and B2 = 2 then A1 would be highlighted red and A2 would be highlighted green.  Essentially, I want to build a heatmap with one set of values in a table and superimpose that heatmap over a separate, equally sized table of values.
I have seen a variety of posts discussing how to get a cell formatted in a non-dynamic way based on another cell (e.g., here and here) but I cannot find a description of how to do what I want to do here.  Is it possible?
If it's not possible to set up a formula for this I would be happy to copy the color-scale colors in B1:B2 over to A1:A2, but I can't find a way to do that, either.

A: This should work when you paste it in Developer -> Visual Basic, under the sheet you're working in. Make sure to change the range.
Sub Worksheet_Change(ByVal Target As Range)
    Set Rng = Range("A1:B2")
    If Application.Intersect(rng1, rng2) Is Not Nothing Then
        Dim Min, Max, Index As Double
        Dim Red, Green As Integer
        Dim Cell As Range
        Dim Rng As Range
        Min = Minimum(Rng)
        Max = Maximum(Rng)
        For Each Cell In Rng
            Index = (Cell.Value - Min) / (Max - Min)
            Red = 255 * ListMin(1, 2 - 2 * Index)
            Green = 255 * ListMin(1, 2 * Index)
            Cell.Offset(RowOffset, ColumnOffset).Interior.Color = RGB(Red, Green, 0)
        Next Cell
    End If
End Sub
Function Maximum(Cells As Range)
    Maximum = Application.WorksheetFunction.Max(Cells)
End Function
Function Minimum(Cells As Range)
    Minimum = Application.WorksheetFunction.Min(Cells)
End Function
Function ListMax(ParamArray Values() As Variant)
    ListMax = Application.WorksheetFunction.Max(Values)
End Function
Function ListMin(ParamArray Values() As Variant)
    ListMin = Application.WorksheetFunction.Min(Values)
End Function

Most of this should be fairly self-explanatory, feel free to comment if you have any questions.


Q: Using graphql-codegen adds query to query? I'm trying to use graphql-codegen to add types to my graphql queries
I have this in my package.json
"@graphql-codegen/add": "^3.1.0",
"@graphql-codegen/cli": "^2.3.0",
"@graphql-codegen/typescript-operations": "^2.2.1",
"@graphql-codegen/typescript-react-apollo": "^3.2.2",

I have a codegen.yml
overwrite: true
schema: http://localhost:3000/api/graphql
documents: 'queries/*.ts'

generates:
  generated/index.tsx:

    config:
      reactApolloVersion: 3
      withHooks: false
    plugins:
      - "typescript"
      - "typescript-operations"
      - "typescript-react-apollo"

I'm using keystonejs which has a graphql api
My query is like
export const ALL_PRODUCTS_QUERY = gql`
    query ALL_PRODUCTS_QUERY{
    allProducts{
        id
        price
        description
        name
        photo{
        id
        image{
            publicUrlTransformed
        }
        }
    }
    }
`

And in my package.json I have
"codegen": "graphql-codegen --config codegen.yml"

If I run yarn codegen I get the types generated in generated/index.tsx
For ALL_PRODUCTS_QUERY I get
export type All_Products_QueryQuery = { __typename?: 'Query', allProducts?: Array<{ __typename?: 'Product', id: string, price?: number | null | undefined, description?: string | null | undefined, name?: string | null | undefined, photo?: { __typename?: 'ProductImage', id: string, image?: { __typename?: 'CloudinaryImage_File', publicUrlTransformed?: string | null | undefined } | null | undefined } | null | undefined } | null | undefined> | null | undefined };

Why does the Query get added to the name so its now All_Products_QueryQuery and why is it not an interface
I thought it would be an interface to describe the query


Q: Файлы установки Windows не запускаются после перезагрузки Устанавливаю Windows XP на ноутбук Toshiba Satellite. Ноутбук старый, изначально на нем стояла Vista. Потом кто-то поставил Windows 7. Но Windows 7 драйверов для видеокарты при установке видимо не нашлось, поэтому все выглядело мягко говоря страшно. Драйверов win7 на видекарту (ATI Radeon) не нашлось и на официальном сайте. Поэтому решил поставить Windows XP. Объединил разделы через Acronis, так как там в общем всего 60 Гб. Раздел автоматически сделался активным и основным. Еще раз отформатировал диск. Начал установку XP. Копирование файлов установки прошло нормально. Дальше ноут пошел на перезагрузку. После перезагрузки черный экран и мигающий курсор в левом верхнем углу. Почему не запускается установка не понятно. Может кто сталкивался с таким.
A: Это от недостатка драйверов в дистрибутиве ХР.Проблема может быть решена несколькими способами:
*
*Вернуть назад Висту (но где её сейчас найдёшь, и кому она нафиг нужна?)
*Попробовать поставить Windows7, с драйверами от Висты (процентов на 95 подходят)
*Поставить пиратскую сборку ХР, со всеми навороченными драйверами (чего не советую, но рассматриваю как способ)
*И наконец - самое сложное. Через NLite собрать самому под свой ноутбук дистрибутив ХР со всеми необходимыми драйверами. Если драйверов нет у Тошибы, то их можно найти у изготовителя чипсета, которого я не знаю, потому что модель ноутбука вы не указали.


Q: Auto Align of button Hi
On our website I have a page where there are Buy Now buttons
https://www.nutricentre.com/m-300-herbs-hands-healing.aspx
The styling that controls this is
.item .price {
    color:#8c9c54;
    font-size:14px;
    font-weight: bold;
    /*
        position: absolute;
        bottom: 48px;
        left: 0px;
        width: 150px;
    */
    text-align: center;
    margin-bottom: 45px;
}

.item a.blue_btn {
    position: absolute;
    bottom: 10px;
    left: 15px;
    cursor: pointer;
}

Any idea how I can get this aligned in a straight line regardless of the text above?

A: You don't have to change the css of the button, but from the whole item:
just add:
.item{
    height: 380px;
}

Of course, you have to care about the maximum item-height: your value must not be less, or the price won't be visible anymore.
In this case, min-height would be the better alternative.

A: I would recommend setting a min-height: 370px; for the easiest solution.
You do not want to set a static height for this because if you have an item with a longer description it will not automatically add space but just cram everything in.

A: Add a static height to .item
height:375px;

The height:auto; declaration tells .item to expand as big as it needs to be to fit everything in, so the tops of the divs line up, but since they are different heights, the bottoms are staggered.
As some of my co-responders have noted, min-height is also an acceptable option, until you have an item with enough text that item expands past the min-height value, at which point they will begin to expand and stagger again.

A: This should point you in the right direction: http://jsfiddle.net/v9grm/
Create a grid and with the help of display: table make the columns the same height. Then place the button at the bottom of the column with position: absolute.


Q: Autorotate not working after reload view controller I'm trying to make an iPhone app, but i found some issue that auto-rotate is not working after I reload the view controller.
here is the code for loading the app for first run:
//AppDelegate.m:<br />
-(BOOL) application:(UIApplication *)application
        didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    iPhoneScanViewController = [[iPhoneScan alloc] init];
    iPhoneScanViewController.ENAD = self;
    [window addSubview:iPhoneScanViewController.view];
    [self.window makeKeyAndVisible];
    [[UIApplication sharedApplication] setStatusBarHidden:YES];
}

the view controller loads, autorotate is working.
then sometimes I need to reload the view controller, this is what I use:
-(void) resetIphoneScan {
    if (iPhoneScanViewController) {
        [iPhoneScanViewController release];
    }
    iPhoneScanViewController = [[iPhoneScan alloc] init];
    iPhoneScanViewController.ENAD = self;

    for (UIView *view in [window subviews])
    {
        [view removeFromSuperview];
    }

    [window addSubview:iPhoneScanViewController.view];
    [self.window makeKeyAndVisible];
}

After I reload / resetIphoneScan, the autorotate won't work. I've spend a few days on this problem and I haven't found solution for that. I really appreciate any help.
Thanks in advance.

A: I would suggest that rather than reload the entire root VC, you have separate data classes which you can reset as necessary - after all, the VC is really for displaying it all.


Q: ExtJS: Ext.Window Prototypal inherited objects cannot be destroy [ExtJS 3.4.0]
I have a class with prototypal intheritance to Ext.Window, something like this:
function Cls_MyWindow() {

    .....

    var SaveButton = new Ext.Button({...});
    var CancelButton= new Ext.Button({...});

    .....

    Cls_MyWindow.prototype.width = Ext.getBody().getWidth() - 800;
    Cls_MyWindow.prototype.height = Ext.getBody().getHeight() - 350;
    Cls_MyWindow.prototype.plain = true;
    Cls_MyWindow.prototype.buttons = [SaveButton, CancelButton];

    .....

}

Cls_MyWindow.prototype = new Ext.Window;
Cls_MyWindow.prototype.constructor = Ext.Window;

When this window is shown, it can be closed by pressing the CancelButton or the built-in "x" button of Ext.Window.
When I close it with CancelButton, SaveButton and CancelButton get destroyed normally.
But, if is closed by the "x" button, the buttons cannot be destroyed, the loop is taking forever causing my application to crashed.
After some investigation I found, in ext-all-debug.js, this:
Ext.Panel = Ext.extend(Ext.Container, {

    .....

    if(Ext.isArray(this.buttons)){
        while(this.buttons.length) {
            Ext.destroy(this.buttons[0]);
        }
    }

    .....

}

which invoke Ext.destroy, this:
Ext.apply(Ext, function(){

    .....

    destroy : function(){
        Ext.each(arguments, function(arg){
            if(arg){
                if(Ext.isArray(arg)){
                    this.destroy.apply(this, arg);
                }else if(typeof arg.destroy == 'function'){
                    arg.destroy();
                }else if(arg.dom){
                    arg.remove();
                }
            }
        }, this);
    },

    .....

}());

What appears to be is that, this.buttons -from pressing CancelButton- are Ext.Component thus, it get destroyed normally.
While this.buttons -from pressing "x"- are not, which leads to the questions.

*

*Why this.buttons are not the same objects when it is destroy via different way?

*What are the solution/options I have, if I want/need to retain the inheritance?

Shedding me some lights is most appreciated. Thank you in advance.

A: If we stay within Ext 3.4.0 boundaries, not reaching back to the plain javascript then you haven't done inheritance correctly. Inheritance is already implemented in Ext, so you do not need to go down to prototypes, creating constructors as instances of parent classes, and so on.
Let's suppose you want to define MyWindow class inheriting from Ext.Window:
Ext.define('MyWindow',{
    extend:'Ext.Window'
   ,method:function(){/* some stuff */}
   ,closable:false // don't create close box
   ,closeAction:'hide'
   // etc
});

To create an instance:
var win = Ext.create('MyWindow', {
    width:800
   ,height:600
});
win.show();

For more info see Ext.define docs.

A: After days, I've found an answered from Inheritance using prototype / “new”.
The code around my first code block at the bottom part is where I got it wrong.
Cls_MyWindow.prototype = new Ext.Window;
Cls_MyWindow.prototype.constructor = Ext.Window;

The "new" at "new Ext.Window" operator there is my mistake.

*

*Why this.buttons are not the same objects when it is destroy via different way?

Answer:
Because of the new operator, when I created a new instance of Cls_MyWindow total of 2 constructors get called: one of the Cls_MyWindow, another of Ext.Window. Which then cause them to have "their own prototype of buttons" where SaveButton and CancelButton available in Cls_MyWindow as Ext.Button objects and in Ext.Window as a plain Object
Closing Cls_MyWindow with CancelButton -> The buttons can be destroyed in Ext.Window.destroy's way. Closing it with "x" -> The buttons cannot be destroyed.
Solution:
I change my code to
//Cls_MyWindow.prototype = new Ext.Window; the old one
Cls_MyWindow.prototype = Ext.Window.prototype;
Cls_MyWindow.prototype.constructor = Ext.Window;

and everything works perfectly


Q: denormalizing JSON with jq I have JSON that looks like this:
    [
      {
        "fields": {
          "versions": [
            {
              "id": "36143",
              "name": "ST card"
            },
            {
              "id": "36144",
              "description": "Acceptance test card",
              "name": "AT card"
            }
          ],
          "severity": {
            "value": "B-Serious",
            "id": "14231"
          }
        }
      },
      {
        "fields": {
          "versions": [
            {
              "id": "36145",
              "name": "ST card"
            }
          ],
          "severity": {
            "value": "C-Limited",
            "id": "14235"
          }
        }
      }
    ]

I want to convert it with jq to this:
    [
      {
        "id": "36143",
        "name": "ST card"
        "value": "B-Serious"
      },
      {
        "id": "36144",
        "name": "AT card"
        "value": "B-Serious"
      },
      {
        "id": "36145",
        "name": "ST card"
        "value": "C-Limited"
      }
    ]

Note that the first object has 2 versions, and the same severity. I have tried jq's group_by and map functions but haven't been too successful. Please help :)

A: This should work.  You wouldn't want to use a group_by here, you would do that if you were trying to go from more to less, we're going the other way.
You're combining the different versions with the corresponding severity.  Here's how you could do that.
map(.fields | (.versions[] | { id, name }) + { value: .severity.value })


Q: How to test basic example of async function in useEffect I have a simple component, it fetches async list of posts.
export const Posts = () => {
  const [list, dispatch] = useReducer(listReducer, []);

  useEffect(() => {
    fetchList(dispatch);
  }, []);

  return (

      {list.map((el) => (

{el.title}

      ))}

  );
};

In other file i keep the logic:
export const fetchList = async (dispatch) => {
  try {
    const result = await api.get('/list/') /* AXIOS */
    dispatch({ type: LIST_SUCCES, payload: result.data.list })
  } catch (error) {
    dispatch({ type: LIST_FAILURE })
  }
}

export const listReducer = (state, action) => {
  switch (action.type) {
    case LIST_SUCCES:
      return action.payload
    case LIST_FAILURE:
      return []
    default:
      throw new Error()
  }
}

I've tried multiple libraries but i'm just unable to write a test. How can i write Posts.test.js to check if post are fetched and displayed, i'm triggering async fetchList after first mount of the component (so it is not componentDidMount), and after data are fetched i dispatch action from that async function and update the list.

A: Here is the unit test solution:
index.tsx:
import React, { useReducer, useEffect } from 'react';
import { listReducer, fetchList } from './reducer';

export const Posts = () => {
  const [list, dispatch] = useReducer(listReducer, []);

  useEffect(() => {
    fetchList(dispatch);
  }, []);

  return (

      {list.map((el) => (

{el.title}

      ))}

  );
};

reducer.ts:
import axios from 'axios';
const LIST_SUCCES = 'LIST_SUCCES';
const LIST_FAILURE = 'LIST_FAILURE';

export const fetchList = async (dispatch) => {
  try {
    const result = await axios.get('/list/'); /* AXIOS */
    dispatch({ type: LIST_SUCCES, payload: result.data.list });
  } catch (error) {
    dispatch({ type: LIST_FAILURE });
  }
};

export const listReducer = (state, action) => {
  switch (action.type) {
    case LIST_SUCCES:
      return action.payload;
    case LIST_FAILURE:
      return [];
    default:
      throw new Error();
  }
};

index.spec.tsx:
import React from 'react';
import { Posts } from './';
import { mount } from 'enzyme';
import axios from 'axios';
import { act } from 'react-dom/test-utils';

describe('Posts', () => {
  afterAll(() => {
    jest.restoreAllMocks();
  });
  it('should render list correctly', async () => {
    const mResponse = { data: { list: [{ id: 1, title: 'jest' }] } };
    jest.spyOn(axios, 'get').mockResolvedValueOnce(mResponse);
    const wrapper = mount(<Posts></Posts>);
    expect(wrapper.find('ul').children()).toHaveLength(0);
    await act(async () => {
      await new Promise((resolve) => setTimeout(resolve, 0));
    });
    wrapper.update();
    expect(wrapper.find('ul').children()).toHaveLength(1);
    expect(wrapper).toMatchInlineSnapshot(`
      <Component>

            jest

      </Component>
    `);
  });

  it('should render empty list when request list data failed', async () => {
    const mError = new Error('Internal server error');
    jest.spyOn(axios, 'get').mockRejectedValueOnce(mError);
    const wrapper = mount(<Posts></Posts>);
    expect(wrapper.find('ul').children()).toHaveLength(0);
    await act(async () => {
      await new Promise((resolve) => setTimeout(resolve, 0));
    });
    wrapper.update();
    expect(wrapper.find('ul').children()).toHaveLength(0);
    expect(wrapper).toMatchInlineSnapshot(`
      <Component>

      </Component>
    `);
  });
});

Unit test result with coverage report:
PASS  src/stackoverflow/59197574/index.spec.tsx (12.494s)
  Posts
    ✓ should render list correctly (105ms)
    ✓ should render empty list when request list data failed (37ms)

 › 1 snapshot written.
------------|----------|----------|----------|----------|-------------------|
File        |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
------------|----------|----------|----------|----------|-------------------|
All files   |    95.83 |    66.67 |      100 |       95 |                   |
 index.tsx  |      100 |      100 |      100 |      100 |                   |
 reducer.ts |    92.86 |    66.67 |      100 |    91.67 |                21 |
------------|----------|----------|----------|----------|-------------------|
Snapshot Summary
 › 1 snapshot written from 1 test suite.

Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   1 written, 1 passed, 2 total
Time:        14.409s

Source code: https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/59197574


Q: Oracle Performance: Partition Split vs Insert Append I am currently refactoring a data loading process in Oracle 12c and am exploring partitioning as a solution. My data is categorised by date and I have ~500k records per date which seems to fit the "minimum optimal" for partitioning, or so I am told. The original plan was to use a staging table to load the data, then add a dummy partition to the main table and perform a partition exchange. However, my data load contains data from several days rather than from one day. Preliminary research suggests there are two methods to solve this problem:
Option 1: Perform the partition exchange, then split the large partition in a loop
ALTER TABLE MAIN_TABLE ADD PARTITION DUMMY_PARTITION VALUES LESS THAN (TO_DATE('1-1-9999', 'DD-MM-YYYY'));

ALTER TABLE MAIN_TABLE
EXCHANGE PARTITION DUMMY_PARTITION
WITH TABLE STAGING_TABLE
WITHOUT VALIDATION UPDATE GLOBAL INDEXES;

BEGIN
   FOR row IN (select distinct to_char(DATE_FIELD+1, 'YYYYMMDD') DATE_FIELD from PARTITIONED_TABLE order by DATE_FIELD)
   LOOP
      EXECUTE IMMEDIATE 'ALTER TABLE MAIN_TABLE SPLIT PARTITION DUMMY_PARTITION AT (TO_DATE('''||row.DATE_FIELD||''', ''YYYYMMDD'')) INTO (PARTITION p'||row.DATE_FIELD||', PARTITION DUMMY_PARTITION) UPDATE GLOBAL INDEXES';
   END LOOP;
END;
/

Option 2: Perform an insert append
INSERT /*+ append */ INTO MAIN_TABLE SELECT * FROM STAGING_TABLE;

Somehow, it seems like splitting the partition is a slower process than doing the insert. Is this expected behaviour or am I missing something?

A: There is a fast split optimization, depending on the circumstances. However from your description, I would simply do the INSERT /+* APPEND */
You may want to employ some parallelism too, if you have the resources and you are looking to speed up the inserts.


Q: How does Ubuntu LVM encryption work? While installing Ubuntu Server, during the partition step one of the options is "use entire disk and set up encrypted LVM" (see screenshots). Can anyone explain - or at least point to the necessary web pages - how it works under the hood? What kind of tools/technologies/algorithms are used? How exactly does this possibly prevent thieves from getting access to the data in the hard disk?
And finally, how does this compare with Ubuntu's home directory encryption?

A: LUKS


Q: Rails and state_machine gem, when before_transition fails, transition to an error state I am using the state_machine gem to track the status of an object.  I have a before_transition process to run and if that has any errors, I would like to set the object's state to "errored" so it is no longer an active object and I am notified that something went wrong.  Below is a simplified code snippet to demonstrate what I am trying to do:
class Status < ActiveRecord::Base
  state_machine :initial => :pending do
    state :pending
    state :processed
    state :errored

    event :process do
      transition :pending => :processed
    end
    event :error do
      transition all => :errored
    end

    before_transition :on => :process, :do => :processing_task
    after_failure :on => :process, :do => :log_error
  end

  def processing_task
    puts "Processing Task Started"
    ...do some processing...
    false  #to force the before_transition task to fail
  end

  def log_error
    puts "Error detected, logging results"
    #LogUtility to store error
    error
  end
end

When I run status.process I receive the following:
BEGIN
Processing Task Started
Error detected, logging results
UPDATE SQL COMMAND, state = 'errored'
ROLLBACK

I tried to disable transactions state_machine :initial => :pending, :use_transactions => false' but that didn't make a difference.  I feel like I should be able to transition an errored state when detecting an error during a before_transition process??
UPDATE
I tried to do something like this:
def custom_process
  begin
    process!
  rescue => e
    puts e      #debugging purposes
    #log error
    error       #transition to error state
  end
end

Then i can call object.custom_process and this accomplishes my goal but I'm creating my own transition outside the state machine, which feels a little weird to me.  If this is the only way, I can implement it like this but was hoping to keep everything inside the state machine.


Q: Creating dynamic order basket using php javascript I am creating an ePos system, that adds any item user clicks to the basket and calculate the total in the end all done without total page refresh.
I tried using $_SESSION and storing as order ( [item] => [price] ) but failed, as i need to refresh.
what I need is:

*

*to display added Items [id name Qnty price]

*calculate total price of added items.

please advice me on the best method to do this.
thanks
this is what I attempter in javascript
function addItem(name, price, id)
                {

                var table=document.getElementById("basket");
                var row=table.insertRow(-1);
                var cell1=row.insertCell(0);
                var cell2=row.insertCell(1);
                var cell3=row.insertCell(2);
                cell1.innerHTML=name;
                cell2.innerHTML=1;
                cell3.innerHTML=price;
                }

but my issue was, i could not find a way to add decimals, parseFloat made alot of bugs for me

A: You should not need to refresh the page in order to save information into the PHP Session object.  PHP Session information is stored on the server, so you can do an asynchronous HTTP request to the backend, and store information the PHP Session.  I would suggest using the jQuery.ajax function (http://api.jquery.com/jQuery.ajax/) to do your async HTTP requests.  If you are not familiar with jQuery, I highly suggest you get familiar with it.  I also suggest you look into how AJAX works.
Also, if you are using the PHP session, if you are not using some kind of framework which does session management, you must make sure to call session_start() before using the $_SESSION variable.


Q: Using readAllBytes to read a file's bytes, but output is not changing when I change the file If I have a directory called "files" and I have 2 txt files in there. The files have different names, but have the same exact contents. With this code, I am not getting the same byte[] when I readAllBytes. Should I be getting the same output when I print bytes? If not, what method could I use to compare byte strands in this way? I am trying to do this: if I have 2 files with content in common but not all the same, in this case, should I have commonalities in the two byte strands also? What method would accomplish this?
public class Main {
    public static final File CWD = new File(System.getProperty("user.dir"));
    public static final File files = new File(CWD, "files");

    public static void main(String[] args) {
        for (File file: files.listFiles()){
            try {
                byte[] bytes = Files.readAllBytes(file.toPath());
                System.out.println(bytes);
                System.out.println(file.toString());
            }
            catch (IOException e){
                System.out.println("File is empty");
            }
        }
    }
}

A: You are trying to print byte[] as a String which uses String.valueOf(bytes) and appears as something like: [B@23ab930d which is [B followed by the hashcode of the array. Hence different byte arrays have different string values. Compare these:
byte[]a=new byte[]{65};
System.out.println(new String(a));
=> A
System.out.println(a);
// Prints something like:
[B@6438a396

Change to print the byte array contents converted as a String:
System.out.println(new String(bytes));

OR: read the text file as a String directly:
String contents = Files.readString(file.toPath());
System.out.println(contents);


Q: Existence of Nonnegative Solutions of Linear Systems of Equations and Inequalities with particular constraints Suppose we have an $n \times m$ nonnegative matrix $A$, where each row sums to $1$. I wonder whether there exists an $m \times n$ nonnegative matrix $X$ that satisfies the following constraints:

*

*each row of $X$ sums to $1$.

*the diagonal entries of matrix $AX$ are all equal and they are larger or equal to any other entries of the matrix.

If the solution does not always exist, would be interesting to know necessary and sufficient conditions for such a solution to exist.
There are existence and uniqueness results for linear equations here and there, but this problem is about existence of a matrix with some particular constraints. Has been a while and still have no clue how to attack it.

A: The question can be cast as the following feasibility problem (linear program):
\begin{equation*}
X \ge 0,\quad (AX)_{ii}=y,\ 1\le i \le n,\quad Xe=e,\quad (AX)_{ij} \le y,\ \forall i,j.
\end{equation*}
This is a linear program with $nm+1$ variables, and $(2n+1)m$ constraints. For a given $A$ whether the feasible set is empty of not can be determined by using a linear programming solver (see also this MO post).


Q: Error inserting date and time in SQL Server 2005 datetime c#? Problem saving to SQL Server 2005:
cmd = new SqlCommand("INSERT into survey_Request1(sur_no,sur_custname,sur_address,sur_emp,sur_date,sur_time,Sur_status)values(" + "'" + textBox9.Text + "'" + "," + "'" + textBox8.Text + "'" + "," + "'" + textBox5.Text + "'" + "," + "'" + textBox1.Text + "'" + "," + "Convert(Datetime,Convert(char(15),"+"'" + dateTimePicker2.Value +"'"+")" + "," + "'" + dateTimePicker1.Value.ToLongTimeString() + "'" + "," + "'" + "Active" + "'" + ")", conn);
cmd.ExecuteNonQuery();

A: You should ALWAYS use parametrized queries - this prevents SQL injection attacks, is better for performance, and avoids unnecessary conversions of data to strings just to insert it into the database.
Try somethnig like this:
// define your INSERT query as string *WITH PARAMETERS*
string insertStmt = "INSERT into survey_Request1(sur_no, sur_custname, sur_address, sur_emp, sur_date, sur_time, Sur_status) VALUES(@Surname, @SurCustName, @SurAddress, @SurEmp, @SurDate, @SurTime, @SurStatus)";

// put your connection and command into "using" blocks
using(SqlConnection conn = new SqlConnection("-your-connection-string-here-"))
using(SqlCommand cmd = new SqlCommand(insertStmt, conn))
{
    // define parameters and supply values
    cmd.Parameters.AddWithValue("@Surname", textBox9.Text.Trim());
    cmd.Parameters.AddWithValue("@SurCustName", textBox8.Text.Trim());
    cmd.Parameters.AddWithValue("@SurAddress", textBox5.Text.Trim());
    cmd.Parameters.AddWithValue("@SurEmp", textBox1.Text.Trim());
    cmd.Parameters.AddWithValue("@SurDate", dateTimePicker2.Value.Date);
    cmd.Parameters.AddWithValue("@SurTime", dateTimePicker2.Value.Time);
    cmd.Parameters.AddWithValue("@SurStatus", "Active");

    // open connection, execute query, close connection again
    conn.Open();
    int rowsAffected = cmd.ExecuteNonQuery();
    conn.Close();
}

It would also be advisable to name your textboxes with more expressive names. textbox9 doesn't really tell me which textbox that is - textboxSurname would be MUCH better!


Q: List Title Column - Rename, Hide or Remove Completely I've been dealing with SharePoint for a short while now and looking at many questions new admins, devs and users have it seems a number of them are related to the Title column that comes standard with new lists.

*

*Some answers suggest renaming the title field in the definition.

*Some answers suggest renaming the title field per list

*Some answers suggest hiding the column.

*I have seen one answer suggesting taking off the Required and/or Deleting the column but SharePoint Online doesn't seem to allow this option.

So in SharePoint online you can remove the Required option and rename the field but you can't remove it and you can't change the Type.
Title is such a generic name that I find clients often asking "What should go into the title field?"
My question is this: What has become common practice with regards to the Title field? Rename it, hide it or delete it (the first 2 for SO)
I understand that simply renaming the column in the Edit Column view doesn't change the underlying name as can be seen in the URL in the Edit Column view, and this has implications when developing add-ins.

A: I thought I would list a few other reasons as to why the Item Title column is so important to SharePoint.

*

*This is the main column that gives users the ability to open and work with the items in lists. Note that this column appears in the view settings 3 times as you can display the text, text (linked to item), and text (linked to item with edit menu).

*This column also is integrated with Email Alerts as it shows up in the subject line, body and is included in a hyperlink back to the Item you were emailed.

It is in your best interest to make use of this column rename it as the main Title/Name text for your items. Sometimes the context of your content can help you think of useful names for this single line of text column.
If I have areas where there is no use for it I simply hide the column with content types and provide a useful default value that makes sense for that list.

A: The first option would be to rename. Remember, the title field is associated with the edit menu (the "..." menu), so completely removing that field removes the menu as well. The only times I hide it is when there simple is no need for a single line of text field as a major element for the list. If there is no need for a single line of text field, I simple modify the list content type and hide it.


Q: Spring, Annotation for Creating Current Date in Hibernate? in my Spring Application using JPA Hibernate Annotions.
In that mysql Database have table and one column called CreateDate
This column value will be added when record is inserted.
So is their any annotation for creating current Date and time?
other wise in our Hibernate bean writing setter method in that add
    private Date currrent;
    public void setCurrent(Date current)
    {
      this.current = new Date();
    }

A: I think you're looking for this:-
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "curr", length = 10)
public Date getCurrrent() {
    return this.currrent;
}

A: What Jelies mentioned is the correct approach. You simply instantiate the date object with
private Date currrent = new Date();

during object creation and then persist it.
To add on to that, its not safe to use @Temporal(TemporalType.TIMESTAMP) for storing the date and time, if there is a chance of you comparing the field current with any java.util.Date objects as the saved field will be loaded as java.sql.Timestamp. The reason is mentioned here.

Note: This type is a composite of a java.util.Date and a separate nanoseconds value. Only integral seconds are stored in the java.util.Date component. The fractional seconds - the nanos - are separate. The Timestamp.equals(Object) method never returns true when passed a value of type java.util.Date because the nanos component of a date is unknown. As a result, the Timestamp.equals(Object) method is not symmetric with respect to the java.util.Date.equals(Object) method. Also, the hashcode method uses the underlying java.util.Date implementation and therefore does not include nanos in its computation.
  Due to the differences between the Timestamp class and the java.util.Date class mentioned above, it is recommended that code not view Timestamp values generically as an instance of java.util.Date. The inheritance relationship between Timestamp and java.util.Date really denotes implementation inheritance, and not type inheritance.

The work around is to use TypeDef. This post discusses about the issue and the workaround. The code used there will be good enough for you.

A: I think the easiest way to achieve that is to initialize your field with the new Date():
private Date currrent = new Date();

IMHO, I don't recommend changing the behavior of the setter method, other developers will not expect that.
If you want this field to be filled immediately before the entity is persisted/updated, you can define a method with @PrePersist or @PreUpdate JPA annotations to populate current property then.


Q: How do I make my custom class compatible with For Each? Is it possible to make a custom container class implemented purely in VBScript (no COM objects) work with the For Each statement? If so, what methods must I expose?

A: In short, no
Why? To create an enumerable collection class to get something like
Class CTest
    ....
End Class

Dim oTest, mElement
    Set oTest = New CTest
    ....
    For Each mElement In oTest
        ....
    Next

the class MUST follow some rules. We will need the class to expose

*

*A public readonly property called Count

*A public default method called Item

*A public readonly property called _NewEnum, that should return an
IUnknown interface to an object which implements the IEnumVARIANT interface and that must have the hidden attribute and a dispatch ID of -4
And from this list or requirements, VBScript does not include any way to indicate the dispatch ID or hidden attribute of a property.
So, this can not be done
The only way to enumerate over the elements stored in a container class is to have a property (or method) that returns

*

*an object that supports all the indicated requirements, usually the same object used to hold the elements (fast, but it will expose too much information)

*an array (in VBScript arrays can be enumerated) holding references to each of the elements in the container (slow if the array needs to be generated on call, but does not return any non required information)


Q: Contact us form: Mail not received I'm trying to create a contact us form with PHP. The problem is that, I'm not receiving the email in my account. When the submit button is clicked it takes me to the mail.php page where a "thank you" message is shown.
The code is as shown below:

Contact Us

    <form action="mail.php" method="POST" class="form-horizontal">

            First Name:

                <input type="text" class="form-control" id="fname" placeholder="First Name*" name="fname" required="required">

            Last Name:

                <input type="text" class="form-control" id="lname" placeholder="last Name" name="lname" >

            Email ID:

                <input type="text" class="form-control" id="email" placeholder="Email Address*" name="email" required="required">

            Message:

                <textarea id="form_message" name="message" class="form-control" placeholder="Message*" rows="4" required="required" data-error="Please, leave us a message."></textarea>

                <button type="submit" class="btn btn-primary">Submit</button>

    </form>

The code for mail.php:
<?php
$firstname = $_POST['fname'];
$lastname = $_POST['lname'];
$email = $_POST['email'];
$message = $_POST['message'];
$formcontent="From: $fname $lname \n Message: $message";
$recipient = "rubeena.ajeed@gmail.com";
$subject = "Contact Form";
$mailheader = "From: $email \r\n";
mail($recipient, $subject, $formcontent, $mailheader) or die("Error!");
echo "Thank You!";
?>

A: Please try using SMTP ?
PHPmailler.class
Download : https://github.com/PHPMailer/PHPMailer


Q: Yang-Mills equations are not elliptic How does one prove that the Yang-Mills equations (from classical Yang-Mills theory) are not elliptic?
Alternatively, how does one calculate the principal symbol of the Yang-Mills equations?
Can someone please present a proof of nonellipticity or derive the principal symbol, or point out where this has been shown in the literature.

A: In fact Yang-Mills equations are elliptic modulo gauge transformations. In simple terms this can be explained as follows (credit: Jonathan Evans, http://www.homepages.ucl.ac.uk/~ucahjde/yangmills.htm). For example, in
magnetostatics the vector potential satisfies the equation
$$\nabla\times(\nabla\times\vec{A})=\nabla(\nabla\cdot \vec{A})-\nabla^2\vec{A}=\mu_0\vec{J}. \tag{1}$$
The equation is not elliptic because of the ﬁrst term. However, using the gauge freedom $\vec{A}\to\vec{A}^\prime=\vec{A}+\nabla f$, we can find such $\vec{A}^\prime$ that solves $\nabla\cdot \vec{A}^\prime=0$. All what is needed is to solve the Poisson’s equation for $f$:
$$ \nabla^2 f=-\nabla\cdot \vec{A}.$$
Then (1) becomes an elliptic equation for $\vec{A}^\prime$. What such kind of "good gauge" exists in general case of Yang-Mills equations is explained in http://projecteuclid.org/euclid.cmp/1103920742 (Removable singularities in Yang-Mills fields, by K.K. Uhlenbeck).


Q: R: Removing Non-Corresponding Rows in Data Frames I have two data frames - germany_yields and italy_yields. If a specific date that appears in one of germany_yields's rows is not present in any of italy_yields's rows, then I would like to remove this row from germany_yields (and vice versa).
For example, here are five rows taken from either of the frames:
germany_yields:                        italy_yields:

            Date Yield                             Date Yield
642 Jan 06, 2008 4.087                 642 Jan 06, 2008 4.461
643 Dec 30, 2007 4.193                 643 Dec 30, 2007 4.522
644 Dec 23, 2007 4.368                 644 Dec 16, 2007 4.563
645 Dec 16, 2007 4.268                 645 Dec 09, 2007 4.601
646 Dec 09, 2007 4.304                 646 Dec 02, 2007 4.420
647 Dec 02, 2007 4.105                 647 Nov 25, 2007 4.439

The date Dec 23, 2007 is present within germany_yields (row 644), but not within italy_yields. I would therefore like to remove row 644 from germany_yields. How can I do this?
For reference, here is the code I have so far:
germany_yields <- read.csv(file = "Germany 10-Year Yield Weekly (2007-2020).csv")
italy_yields <- read.csv(file = "Italy 10-Year Yield Weekly (2007-2020).csv")

germany_yields <- germany_yields[, -(3:6)]
italy_yields <- italy_yields[, -(3:6)]

colnames(germany_yields)[1] <- "Date"
colnames(germany_yields)[2] <- "Yield"
colnames(italy_yields)[1] <- "Date"
colnames(italy_yields)[2] <- "Yield"

A: The easiest approach is to use %in%:
germany_yields[germany_yields$Date %in% italy_yields$Date, ]

A: We can also use dplyr
library(dplyr)
germany_yields %>%
      filter(Date %in% italy_yields$Date)


Q: Workflow Lookup List view threshold Alert me I have a workflow from a Document Library that copy the file to another Document Library and then "Update Item in" on this other Document Library through lookup. However the workflow won't work because where the file is copied the Document Library has more than 5k files and the List View Threshold is setup for only 5k.
I tried to create a specific field on both Document Library that the workflow could do the lookup, but I still get the same error. I was wondering how to make the workflow lookup on a different Document Library with exceeded list view threshold without changing  the list view threshold limit.
This is the erro that I get from  the workflow status:
"The attempted operation is prohibited because it exceeds the list view threshold enforced by the administrator."

A: A better solution would be to parse out your document libraries so they aren't exceeding the list view threshold. Assuming you're running 2013 since you tagged it in your post, you could have the workflow do a REST API call to the destination library and check the item count. If it returns >5000, alert the document library manager to archive some old files - or save the file to an alternate library using an If/Then block.
The SPD Workflow to do this:
Build {...} Dictionary (Output to Variable: requestHeaders)
then Call [site url]/_api/web/Lists/GetByTitle('[Library Name to Query]') HTTP web service with request (ResponseContent to Variable: responseContent|ResponseHeaders to Variable: responseHeaders|ResponseStatusCode to Variable: responseCode)
then Get d/ItemCount from Variable: responseContent (Output to Variable: count)

If Variable: count is less than 5000
  [Proceed as normal]
If Variable: count is greater than or equal to 5000
  [Save to secondary library and notify admin to do some cleanup]

(Here's some background on REST API if you haven't used it before)


Q: Prevent centring on focused input in hidden overflow area It is hard to explain with words so here's a fiddle I made to explain the problem better: http://jsfiddle.net/j2zurbbv/1/. When the first timeout fires the container div is not 'scrolled' which is the behaviour I want. However when the input is outside of the visible part of the div (as it is with the second timeout) the container div centres about this input.
Container css:
#container {
  overflow: hidden;
  height: 200px;
  position: absolute;
  width: 200px;
}

For the record I have only tested this on Chrome 37.0

A: Managed to work it out. Counter the scrolling that the browser does by doing document.getElementById('container').scrollTop = 0; whenever you programatically focus on an element outside of the visible area of an overflow: hidden div AND whenever a user inputs in such an element. Demonstrative JSFiddle (without prevention of input scrolling) http://jsfiddle.net/j2zurbbv/2/.


Q: Index page is not re rendering/refreshing on search in Rails I am making a simple search in rails on the index page. My problem is that on debug I get the correct results but they don't show on the frontend.
def index
 if !params[:category].present? and !params[:title].present?
  @services = Service.take(4)
 else
   if params[:category] != "Find Service" and params[:title].present?
    @services = Service.where(category: params[:category], title: params[:title]).take(4)
   elsif params[:category] == "Find Service" and params[:title].present?
    @services = Service.where(title: params[:title]).take(4)
   elsif params[:category] != "Find Service" and !params[:title].present?
    @services = Service.where(category: params[:category]).take(4)
   else
    @services = Service.take(4)
   end
  end
 end

My view index.html.erb
<%= form_with(url: "services", method: "get") do |form| %>

     <input type="submit" value="" class="main-listing__form-field agent-submit" style="width: 10% ;float:right">
     <%= form.text_field "title", id: "search_agent", class: "main-listing__form-field ", placeholder: "Search by Name or Location...", style: "width: 75% ;float:right; background: transparent; color: white!;" %>

        <%= form.select("category",options_for_select(["Find Service", "Assembly", "Carpet Cleaning", "Electrical", "House Cleaning", "HVAC", "Handyman", "IT", "Junk Removal", "Lawn Care","Moving", "Painting", "Plumbing", "Staging", "Photography", "Videography", "Inspectors"], :selected => "Find Service"), {include_blank: false}, { :class => 'ht-field listing-sort__field' }) %>

<% end %>

Recently viewed & more

 <% @services.each do |service| %>
  <%= render 'services/service_card', :f => service %>
 <% end %>

Pro SEM services

 <% @services.each do |service| %>
  <%= render 'services/service_card', :f => service %>
 <% end %>

This is _service_card

<%= f.user.profile.first.first_name %>

Level 1 Seller

      <% byebug %>

<%= f.description %>

       (5)

Starting At $ <%= f.packages.first.price%>

Please help me regarding this. Looking forward. It is working fine without search, but with search it doesn't update the results and show same results.


Q: Select statement over multiple columns I have an SQLite database with a table help with columns i_id, issue, url, steps, kw1, kw2, [...], kw12. kw1 - kw12 contain one word and can be null.
When I do:
sqlite> select issue,url,steps from help where kw1='adobe';

I get:
blank popup|blankpopup.html|S
missing pdfs|missingpdfs.html|S
printall not populating|printall.html|A

this is right. When I move to another keyword like 'ie' that is in multiple fields across kw1 - kw12, how do I do a select statement where instead of searching just kw1, it searches kw1 through to kw12?
I know what fields 'ie' is in. I have an Excel sheet of how the database is built but the people using the database don't.

A: If I understand right, you just need to use Or keyword and search thru all the kw-fields
sqlite> select issue,url,steps from help where kw1='ie' or kw2='ie' or kw3='ie' or kw4='ie' or kw5='ie' or kw6='ie' or kw7='ie' or kw8='ie' or kw9='ie' or kw10='ie' or kw11='ie' or kw12='ie';


Q: Diy 18650 4s battery pack [How to charge, how to build?] I'm building a bluetooth portable speaker.
However, I have some questions about building my first 18650 battery pack.
I have 4 pcs of Panasonic unprotected NCR18650B 18650 3.7V 3400mAh.

My goal is to build a 4s 18650 pack with these batteries, and the battery pack must:
- be inside the portable speaker
- Fully protected
- Safe
My question is, how do I design this battery pack?
I have a idea, but want to know if it is a good way to build it?:

I also have some others questions:
During my searches on internet some people use balanced charge, is it necessary to it use in my case? If yes how?
Do I need to use a power adapttor or lithium li-ion battery charger adaptor?
Thanks for your future help
Cordially,

So i recap, if i have correctly understand,
A BMS board is designed for protect the cells against Overcharge, over discharge, over current, short circuit protection, right?
But for protect the batteries pack life, it need to be balance charge right?
Which board can you advice me for protect and balance my batteries pack? (I have Panasonic unprotected NCR18650B 18650 3.7V 3400mAh)
I found a board on aliexpress, what do you think?

Or i have an other idea,
what do you think if i put a balanced charger in the speaker,
does it possible the wires stay always connected to the charger and the speaker circuits?
Does it is necessary to have a bms for protect my batteries because they are original unprotected ?

Another question,
Please, can you advice me a reliable BMWS for protect my batteries pack?
I'am not there to save money, the safety of the pack is my priority.

I checked the existing BMS on the market, but i noticed that Over-discharge Protection is too low compared to my batteries specs.
The common bms on internet cut the current at approximately 2.55 this is too low for my batteries.
Indeed minimum voltage of my batteries  is 2.75 V.
So i found a new BMS with balance charge function: link
I have several questions, i made a wiring diagram and i want to know if  don't have made mistakes:

However, several questions remain vague in my mind:
The Positive cable and the negative cable are the same cables to charge the battery pack and use it? On the diagram (Output / Input Positive + and Output / Input Negative -)
Can i use the battery pack at the same time as it charging? For me it seems odd to me because I wonder what the intensity and the voltage sent to electric circuit of the bluetooth speaker. On the diagram (Intensity: A?
Voltage Rating: V?)
Those of the adapter or the battery?

A: That BMS looks identical to one that I've used and it does NOT do balancing or proper charging.  Just protecting from over current, over voltage and under voltage - all of which are very important.
You will need to add balance wires and get a balance charger for this battery.
Balance wires are easy - they go exactly where the bms wires go - one to each pos and neg of each cell.  The balance charger will have a slot for those wires.
I recommend looking at the IMAX b6 charger because it is the cheapest balance charger I have seen and seems to work reasonably well up to batteries with 6s or less.


Q: Controlling relays with logic gates Pretty new to electrical engineering world, so probably rather simple question. I´m designing control system for tractor trailer hydraulic system. The system is 12 V and solenoids what I am using there are 2 A. Also I´m using few digital inductive sensors(IFS241) which output also 12 V. Since There are some logic behind the operations, I was thinking to use 18 V AND CMOS logic gate (NTE4081B) and 20 V NOT CMOS logic gate (CD4069UB) to run relays. But here is the problem that logic gate outputs only 500 mW and already one relay needs 400 mW (DS1E-M-DC12V). Do you have some ideas how to boost this signal, or how I should control the relays with logic?
Thank you for you advice.

A: Provided that the logic is simple, the task may be easily accomplished using relays alone.

A: To replace some simple logic such as CD4069UB with higher drive, you can use transistors. Such as MOSFETs or BJTs. Even the most basic transistors can give you power of 400 mW or more. This way, you can control the amount of output power you can drive by choosing a transistor (output current limited by open channel of transistor). If you drive relay when the output of inverter is high, you should take P channel inverter ( PMOS inverter on the picture). If you drive them low, you can use N side inverter. If however you need to have low output impedance on both LOW and HIGH output, use CMOS logic (P and N transistor). Here are all representations of inverter with BJT or MOSFETs. To drive the output of an AND gate, you can invert its output and then use the output inverter as before as a buffer.  Also, don't forget to add diodes if you want to control an inductance load. More info here.


Q: TortoiseHg - infinite cloning of repository I've encountered a quite troubling problem. I've tried to clone repository from the server and I was able to start cloning, but it never ends, and no files are being downloaded on my hard drive. I'm using pagaent with my private key. I've tried it on 3 different PC, and it didn't helped, but I know it is working because some people were able to clone this repository.


Q: Running a program in eclipse Each time I try to run a new program, an old program 'client.java' is run by eclipse. How do I change this setting? How do we tell eclipse which program to run? I tried using the arrow beside run button but it dosen't list out my new program.

A:
Right Click To the class -> Run As-> JAVA Application

A: You can change the default behavior by going to Window > Preferences > Run/Debug > Launching and in the 'Launch Operation' section, select the radio button for Launch the selected resource or active editor and then select Launch the associated project underneath.

A: Firs of all make sure that your program has a main class.
Then click in the black button next to the run button -> Run As-> JAVA Application.
If this doesn work make sure you have all this properly set up.
Run Configurations


Q: Matplotlib ticks sans-serif for all plots I'm trying to achieve sans-serif axes labels and ticks in matplotlib with pgf. I want to control that by rcParams so I have it working for all subsequent plots. Currently, I'm using
"pgf.rcfonts":False,
"pgf.texsystem": "pdflatex",
"text.usetex": True,
"font.family": "sans-serif",

which I adapted from the mpl docs. It does set all my text in the figure to sans-serif. However, the numbers are kept with a serif font. I want them to be sans-serif. As soon as i force the formatter, its sans-serif. Any way to get it to do that automatically? MinEx follows...
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.ticker import FormatStrFormatter

#define style
style = {
        "pgf.rcfonts":False,
        "pgf.texsystem": "pdflatex",
        "text.usetex": True,
        "font.family": "sans-serif"
        }
#set
mpl.rcParams.update(style)

#get data
data = np.random.random(100)
#set up plot
f,ax = plt.subplots()
ax.plot(data)
#label something
ax.set_xlabel('Runner')

The label is sans now. The ticks are not! But when calling
ax.xaxis.set_major_formatter(FormatStrFormatter('%d'))

they are.

A: According to the pgf texsystem example, you need to use the "pfg" backend (mpl.use("pgf")) and choose the font you want to use:
style = {
        "pgf.texsystem": "pdflatex",
        "text.usetex": True,
        "pgf.preamble": [
         r"\usepackage[utf8x]{inputenc}",
         r"\usepackage[T1]{fontenc}",
         r"\usepackage{cmbright}",
         ]
        }

Alternatively you may use a formatter, which does not format the ticklabels as latex math (i.e. does not put them into dollar signs).
One may adapt the default ScalarFormatter not to use latex math by setting
ax.xaxis.get_major_formatter()._usetex = False
ax.yaxis.get_major_formatter()._usetex = False

A: The problem is LateX related. You just need to load the extra cmbright package that enable sans-serif math fonts.
On Debian-like systems:
sudo apt install texlive-fonts-extra

On Fedora:
sudo dnf install texlive-cmbright

Then try your code with this style:
style = {
        "text.usetex": True,
        "font.family": "sans-serif"
        "text.latex.preamble" : r"\usepackage{cmbright}"
        }


Q: Divergence of alternating series Say I have an alternating series $\sum (-1)^n a_n$. If $\lim_{n \rightarrow \infty} a_n=\infty$ or if it does not tend to $0$, then, does $\sum (-1)^n a_n$ diverge?? I know that if this holds then $\sum a_n$ diverges, but if I add this $(-1)^n$ would that still be divergent?

A: Yes it is divergent since

*

*for $n=2k \implies (-1)^{2k}a_{2k} \to \infty$

*for $n=2k+1 \implies (-1)^{2k+1}a_{2k+1} \to -\infty$

A: Yes, it still diverges, because you don't have $\lim_{n\to\infty}\bigl\lvert(-1)^na_n\bigr\rvert=0$.

A: If a series $\sum_nb_n$ converges, then $b_n\to 0$. Now, let $b_n = (-1)^na_n$. If $(a_n)$ doesn't tend to zero, then $(b_n)$ doesn't. So, your series cannot converge.


Q: Creating network visualization dashboards I'm a Network Engineer, I want to create a custom data network visualization dashboard that includes interactive charts and graphs with drill down options and such. I'm a bit overwhelmed by the proliferation of languages and different ways of accomplishing this. What are some languages/libraries I should learn to accomplish this task, as well as good tutorials for your recommendations. I have intermediate coding experience.
Thanks!

A: I recommend using D3js, force directed graph is perfect for creating a network visualization, there are some examples here: D3 force directed graph


Q: Export image as SVG in GIMP I have a project I have been working on (an image) within GIMP and I would like to export it as an SVG. Is this possible, or am I going to have to stick with exporting multiple sizes of an image?
I know GIMP can read SVGs, but can it export them?

A: If you need to convert a raster image to a vector image autotrace is a command line tool which does exactly that.
It's available as a debian package on Debian and Ubuntu named autotrace
An example of using it is:
autotrace input.jpg --output-file output.svg --output-format svg

Update:
I've also had success with potrace where autotrace was having trouble.

A: Even though Gimp is not a vector program, you can actually export single paths as SVG file with the Export Path menu item.
Here is a photo tutorial that explains in detail how to do it.

A: GIMP v2.8 does not natively export bitmaps to SVG files. There used to be a plugin to do so but this project apparently is discontinued. We could import an image as a bitmap object to Inkscape  and save it as an SVG file. The image will then remain a bitmap file, i.e. it will get aliasing artifacts on scaling (see below).
But Inkscape can do even more. We can import the bitmaps we had already put so much work in to Inkscape and convert them with a few mouse clicks to nice vector graphics.
Here is how to do that:

*

*Open Inkscape.

*Choose "File - Import" to import a bitmap file.

*Choose to "embed" the image.

*Select the image with the select tool (↖).

*Select Path - Trace Bitmap... for settings (below shown for 2 colors = "Scans" ):

*Select "Update" for a preview until settings are fine.

*Start tracing with "OK".
Now a vectorized image of your original bitmap will be seen on top of the bitmap. We can resize or move this newly created object, delete the original image, or choose to "Object - Ungroup" in case we need to adapt shapes or colour of sub-object created.

*If necessary, reduce size of the vectorized image (hold down CTRL to lock ratio), so that it fits on the page.  Otherwise it may appear "cropped" when viewed.

*Use "File - Save As" to save your file in SVG format.

The advantage of a vector graphic can most rapidly be seen when we increase its size. Shown below was zooming to 2500%. Top is the original bitmap, bottom is the vectorized object:

This image and object was created from your original from chat

A: GIMP is a raster graphics editor application. SVG is a form of vector graphics. If you want to edit SVG files, you should install the inkscape package and use Inkscape instead. Also, beware that SVG is not totally "scalable" in the sense that you will get a good image at every size you scale to, so depending on what you are creating with it, you may need to draw different sizes of the image, with different amounts of detail, so that the images will look good at those sizes. Icons for an application, for example, do need to be drawn at multiple sizes, whether they are drawn as raster or vector images.

A: potrace is the tool for that. You can process them bulk, but first you have to convert the images to monochrome:
ls ./p*.jpg | xargs -L1 -I {}  convert -monochrome {} {}.bmp
ls -1 ./*.bmp | xargs -L1 -I {} potrace {} -r 300 -b svg -o {}.svg

install:
sudo apt install potrace

A: Well, actually, you can save SVGs with GIMP. For instance, you can use this command: (gimp-vectors-export-to-file 1 "new.svg" 0)


Q: Error using Reactive Maps with Google maps Javascript Api I am trying to build and app with ReactiveSearch and ReactiveMaps using some indexed files in Elasticsearch.
The indexed files in Elasticsearch have a field "location", for example:
        "location": {
        "Lat": 56.746423,
        "Lon": 37.189268
      }

And other fields like "Title" or "Authors".
I got a Google maps API key and in my App.js file I have these components:
      <DataSearch
        componentId="mainSearch"
        dataField={["Title", "Title.search", "Abstract", "Abstract.search"]}
        queryFormat="and"
        placeholder="Search for HEP"
        autosuggest={true}
        className="datasearch"
        innerClass={{
          input: "searchbox",
          list: "suggestionlist"
        }}
      />

        <ReactiveMap
        componentId="map"
        dataField="location"
        size={100}
        defaultZoom={13}
        defaultCenter={{ lat: 37.74, lng: -122.45 }}
        showMapStyles={true}
        defaultMapStyle="Standard"
        showMarkerClusters={true}
        showSearchAsMove={true}
        searchAsMove={true}
        react={{
          and: "mainSearch"
        }}
        onData={result => ({
          label: result.Title
        })}
      />

in the same file ("App.js") I have this lines :
  <ReactiveBase
    app="title"
    url=here_the_elasticsearch_cluster
    mapKey="here_my_googlemapsAPI_key"
  >

Also in the file Public/index.html I have
<script
  type="text/javascript"
  src="https://maps.google.com/maps/api/js?v=3.34&key=MY_GOOGLE_MAPS_API_KEY&libraries=places"
></script>

However, When I search for any documents in the mainBar I found it, but, when I click on it it doesnt appear in the map.
What am I doing wrong?

A: Finally I have solved it.
ReactiveMaps does not allow the location field in uppercase, so I had to change the indexed documents in elasticsearch taking in account this.
    "location": {
    "lat": 56.746423,
    "lon": 37.189268
  }


Q: Creating an array from two data-* and one select array codeigniter I have a table with products where i can add rows dynamically and on each row i add it will be a select and an edit button.
If i press this button,it will display a modal where i can modify 2 data-* of the select.The dependence(dep) and the category.
After editing one select, i will have something like this:
<select data-dep="1" data-category="3"></select>

After submitting,in the model,i will get the products like this:
$products = $this->input->post('products[]');

In this way, i will have an array with all the products i wanted to add to database.The question is, can i make an array with the id of the product(what i have now), the value from data-dep and the value from data-category?And if i can,how?Something like this:
[1]--->product_id = 1,dep = 3, category = 2;

[2]--->product_id = 2,dep = 1, category = 3;

My HTML is this:

                        <select class="form-control select-table" name="products[]" id="select-1" data-dep="" data-category="">
                            <?php foreach($products as $product):?>
                                <option value="<?php echo $product['products_id'];?>"><?php echo $product['product_name'];?></option>
                            <?php endforeach;?>
                        </select>

        Pret:
        <input type="number" name="price" class="form-control"/>
        <input type="submit" class="btn btn-primary" name="submit" value="Creaza meniul" style="margin-top: 5px;"/>

Modal title

                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    ×
                </button>

                    <select class="form-control dep-select" id="dep-test" name="dep-select">
                        <option class="form-group" value="1">Fara garnitura&salata</option>
                        <option class="form-group" value="2">Fara salata</option>
                        <option class="form-group" value="3">Fara garnitura</option>
                        <option class="form-group" value="4">Cu de toate</option>
                    </select>
                    <select class="form-control category-select" name="category-select">
                        <option class="form-group" value="1">Fel Principal</option>
                        <option class="form-group" value="2">Garnitura</option>
                        <option class="form-group" value="3">Salata</option>
                        <option class="form-group" value="4">Supa</option>
                        <option class="form-group" value="5">Desert</option>
                    </select>

                    <button type="button" class="btn btn-primary" id="save" data-dismiss="modal">Salveaza</button>
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Inchide</button>


Q: How do I get a Google Admin to Fix my Project Console? Short of paying $150/month so I can actually submit a ticket, what can I do to get Google's attention?  I've seen other people get help for what appears to be the exact same issue.
I uploaded a new (small) app to Google App Engine (GAE), and the Applications Settings page shows an error under Cloud Integration ("An error occurred when creating the project. Please retry").
I've retried over a period of days, but it tries for a while, then reports another failure.  I've asked questions of StackOverflow, and in the GAE issues forum, to no response.

A: Try to get hold of the people from Google Developer relations here, in the relevant Google+ communities or on Google groups.
If it can bring you any comfort: paying the $150 does not help you much - we have the subscription.

A: If you have a second Google Apps domain, replicate the issue by switching domains and recreating the project from scratch. Then if the error occurs again, post that it occurs in 2 or more cloud.google.com accounts with separate domains.  This should help show this is not a one off error and requires investigation.
If it does not occur in the second domain, save your data, delete your project and recreate with a different project name and number.
-ExGenius


Q: Multiply columns of different sheets in power BI I need to multiply the no.of grants into the expected attrition rate based on dates. In image 3 i have the rates and now for image 2, i need to multiply the rates in image based on the date. Im new to power bi and i'm not able to work it out.


Q: React Router: props aren't passed down when directly accessing the URL of child component. Will I need to use the same state in both parent and child? I'm pretty new to React and React Router so apologies if this is a silly question or answered elsewhere - I did a search but couldn't find a similar question.
I'm using React Router v6 and React Hooks. My very basic full-stack app is focused on keeping track of musical artists and their released projects (albums, mixtapes, EPs, etc.). My App component will render the ProjectList component at the '/' route, and the ArtistList component at the '/artists' route.
Relevant portions of App.js:
import React, { useState, useEffect } from 'react';
import { Routes, Route, Link } from 'react-router-dom';
import axios from 'axios';

import ProjectList from './ProjectList';
import ArtistList from './ArtistList';

import { Button } from './styles.js';

const App = () => {
  const [ projects, setProjects ] = useState([]);

  const getProjects = () => axios('projects').then(({ data }) => setProjects(data));
  useEffect(getProjects, []);

  return (<>
    <Link to="/">
      <Button>Projects</Button> // Button is using styled-components
    </Link>
    <Link to="/artists">
      <Button>Artists</Button>
    </Link>
    <Routes>
      <Route path="/" element={<ProjectList projects={projects} />} />
      <Route path="/artists" element={<ArtistList projects={projects} />} />
    </Routes>
  </>);
};

This all works as expected when I click the Projects and Artists buttons. However, when I attempt to access the '/artists' route directly through the URL bar of my browser, nothing renders and I get an error about how the projects prop is undefined. My assumption is that because I'm trying to access the ArtistList component before rendering the App component itself, getProjects doesn't run and so no projects props are passed down to ArtistList.
I need the list of projects to render my ArtistList component. Each element of projects is an object that includes an artist property that I use to create my list of artist names and a dateAdded property that I use to sort the artist list by recency. I also keep track of how many projects each artist has.
Relevant portions of ArtistList.jsx (the return block contains some styled-components - Options, Header, TextWrapper, and Artist):
const ArtistList = ({ projects }) => {
  const [ artists, setArtists ] = useState([]);
  const [ sortBy, setSortBy ] = useState('name');

  const getArtists = () => {
    const artists = [];
    let curArtist = projects[0].artist;
    let projectCount = 0;
    const now = new Date();
    let firstAdded = now;

    for (const { artist, dateAdded } of projects) {
      if (artist !== curArtist) {
        artists.push({ name: curArtist, projectCount, firstAdded });
        curArtist = artist;
        projectCount = 0;
        firstAdded = now;
      }
      projectCount++;
      const projectDate = new Date(dateAdded);
      if (projectDate < firstAdded)
        firstAdded = projectDate;
    }
    setArtists(artists);
  };
  useEffect(getArtists, [ projects, sortBy ]);

  if (sortBy === 'number')
    artists.sort((a, b) => b.projectCount - a.projectCount);
  else if (sortBy === 'recency')
    artists.sort((a, b) => b.firstAdded - a.firstAdded);

  return (<>
    <Options>
      <label htmlFor="sortBy">Sort by: </label>
      <select id="sortBy" value={sortBy} onChange={e => setSortBy(e.target.value)}>
        <option value="artist">Name</option>
        <option value="number"># of Projects</option>
        <option value="recency">Recently Added</option>
      </select>
    </Options>
    <Header>
      <TextWrapper>Name</TextWrapper>
      <TextWrapper># of Projects</TextWrapper>
    </Header>
    {artists.map(({ name, projectCount }, idx) => (
      <Artist key={idx}>
        <TextWrapper>{name}</TextWrapper>
        <TextWrapper>{projectCount}</TextWrapper>
      </Artist>
    ))}
  </>);
};

I currently see 2 solutions to this issue (I'm sure I'm missing more):

*

*Create a projects state and a getProjects in the ArtistList component, pretty much exactly as they are in the parent App component. Whenever I render ArtistList, I will make a request to my back end to retrieve a list of projects and then invoke setProjects. I'd then derive the artists state from projects, as before. Of course, I'd no longer need to pass the projects props from App to ArtistList. However, I would then have the exact same state values/functionality in both parent and child components, and this feels to me like a violation of fundamental React principles.

*Put a collection of Artists into my Mongo database, in addition to the Projects collection I currently have. I would have to implement something similar to the getArtists function, but in the back end this time, then put the list of artist data into my database. Then, every time I try to render ArtistList, I will make a request to my back end to retrieve the list of artists and go from there.
The third option is doing nothing, but then I'm unable to access the '/artists' page directly through the URL.
What would be best practice and the best approach in this instance? Any help is appreciated!

A: The projects state is actually defined on the initial render cycle:
const [ projects, setProjects ] = useState([]);

So it's a defined prop when passed to ArtistList:
<Route path="/artists" element={<ArtistList projects={projects} />} />

The issue starts when in ArtistList in the useEffect hook calling getArtists where it is incorrectly attempting to access a property of the first element of the projects array which is currently an undefined object.
const getArtists = () => {
  const artists = [];
  let curArtist = projects[0].artist; // <-- error, access artist of undefined!
  let projectCount = 0;
  const now = new Date();
  let firstAdded = now;

  for (const { artist, dateAdded } of projects) {
    if (artist !== curArtist) {
      artists.push({ name: curArtist, projectCount, firstAdded });
      curArtist = artist;
      projectCount = 0;
      firstAdded = now;
    }
    projectCount++;
    const projectDate = new Date(dateAdded);
    if (projectDate < firstAdded)
      firstAdded = projectDate;
  }
  setArtists(artists);
};

useEffect(getArtists, [projects, sortBy]);

What you can do is to only run the logic in getArtists is the array is populated.
const getArtists = () => {
  const artists = [];
  let curArtist = projects[0].artist;
  let projectCount = 0;
  const now = new Date();
  let firstAdded = now;

  for (const { artist, dateAdded } of projects) {
    if (artist !== curArtist) {
      artists.push({ name: curArtist, projectCount, firstAdded });
      curArtist = artist;
      projectCount = 0;
      firstAdded = now;
    }
    projectCount++;
    const projectDate = new Date(dateAdded);
    if (projectDate < firstAdded)
      firstAdded = projectDate;
  }
  setArtists(artists);
};

useEffect(() => {
  if (projects.length) {
    getArtists();
  }
}, [projects, sortBy]);

And to ensure that projects is at least always a defined value, provide an initial value when destructuring the prop.
const ArtistList = ({ projects = [] }) => { ... }


Q: How to find largest count using table in a matrix in R Suppose I had the following matrix
    m = matrix(c(1, 0, 0, 0, 0, 0, 1, 1, 0), ncol = 3)
    > m
         [,1] [,2] [,3]
    [1,]    1    0    1
    [2,]    0    0    1
    [3,]    0    0    0

I want to have a count of the values for each of the columns, so
    table(m[,1])
    table(m[,2])
    table(m[,3])

And I want to figure out what's the value (either 0, or 1) that has the largest counts (appears more than the other). So for column 1 I would want R to return 0 (because there are more 0's than 1's), for column 2, R should return 0, and for column 3 return 1.
I've tried which.max() but that only gives me the index. Not the value with the largest count.

A: If you are working with a binary matrix, you can use colMeans
as.numeric(colMeans(m) > 0.5)
# [1] 0 0 1

since colMeans(m) gives you the percentage of 1's in each column

A: A simple solution is to use indexation and which.max, as you had proposed. To make things simpler, it can be done using apply and a function indexing which.max Thus, following your example matrix:
apply(m,2,function (X) as.numeric(names(table(X)[which.max(table(X))])))


Q: Why can't CDs/DVDs be partitioned? Nearly everywhere it's written that it's not possible.. But why?
Why can't I dump a GPT/MBR partition table in the first sector? Basically dump a disk layout with sector size 2048...
Now I'm sure something of this type is possible, but of course no OS will recognise it.. So the question is, why not? What's so hard in a partition table? What's the technical reason behind zero support for partitioning an optical disc?

A: There may be two main reasons why partitioning isn't a well supported feature on optical media:

*

*Optical media was at the beginning small (in comparison with HDD's).

*Optical media was read-only. This later evolved due to easier access to consumer-level disk burners and the advent of RW technology.

Nowadays, there are much better solutions such as pen drives or even portable HDD. Not everyone has a Blu-Ray reader and not everyone wants to purchase a RW DVD. As such, in what regards optical media, partitioning was never demanded enough for it to happen.
I do have to point out the answer Rod Smith gave to a similar question, which I'm now quoting:

There are exceptions to this rule, though. Some Mac discs are written with a partition table and HFS or HFS+ instead of or in addition to ISO-9660. Such discs use the Apple Partition Map (APM) partition table. Some Linux distributions' installer discs use ISO-9660 that coexists with a partition table, but the intent here is to support different media in differnt ways -- when the image is burned to a CD-R or DVD, it appears to be a partitionless ISO-9660 disc; but when it's written to a USB flash drive, it appears to be a partitioned hard disk. This trickery works because of gaps in various data structures and the different sector sizes used on optical media (2048 bytes) vs. hard disks and USB flash drives (512 bytes). Both of these examples (Mac discs and Linux installation discs) are hackish extensions to the standards of ISO-9660, MBR partitions, and so on.

As you can see, it isn't technically impossible to do, but where it's done it's to provide additional support that couldn't be done in another way.

A: The iso9660 standard covers the cdrom specs and since partitions are not part of the specs nobody ever wrote a driver to handle them.  No existing driver would support your changes to the file system, and all the programmers I know would not violated the specification.
Changing the driver now would not only mean adding a sector in the being, but changing the whole code base to accommodate the logic behind partitions.  Lets pretend you wrote such a driver and made ISO's like that, they nobody else could read the ISO of the CD since everyone else has drivers that follow the specs.  By the time you submitted your changes to ISO standards committee, got them to look at and go through the whole approval process would take years.  However, they would probably not approve it since all modern hardware is design around the original specs.
The original thinking was probably who would want to partition such a tiny amount of space.  They probably look at how much work it would take to develop,write, and test the code and said too much work to meet what ever deadlines they had.

A: It is quite easy to "partition" a DVD if you are creating the DVD on a Linux system.   If you do "partition" the DVD, it will present itself to the OS as two or more separate DVD drives.
There are numerous ways to do this.  For example, you can use the -eltorito-alt-boot option to mkisofs. This is what I use to create my UEFI Rescue DVD which contains a 32-bit and a 64-bit set of tools along with both the EFI and UEFI shells.
Oh, and the relevant specification is Mount Fuji v8.


Q: WordPress plugin update not showing on wp.org I have been maintaining this plugin since quite some time...
https://wordpress.org/plugins/pootle-page-builder/
But on releasing v5.1.0 update is not showing even after about 20 hours (at the time of writing this)... I don't know what I'm doing wrong...
This is my trunk
readme.txt
https://plugins.trac.wordpress.org/browser/pootle-page-builder/trunk/README.txt
(I have correct Stable tag specified)
This is my tagged version 5.1.0
readme.txt
https://plugins.trac.wordpress.org/browser/pootle-page-builder/tags/5.1.0/README.txt
(again correct Stable tag specified)
Main plugin file
https://plugins.trac.wordpress.org/browser/pootle-page-builder/tags/5.1.0/pootle-page-builder.php
(version correct here too 5.1.0)
I don't see my changelog modifications here either...
https://wordpress.org/plugins/pootle-page-builder/
I just don't understand why it's not grabbing new version even after 20 hours! It generally works within an hour or so...
Can anyone let me know if I'm missing something..?

A: For those having this problem...
It's really rare...
In most cases you will be missing something like Stable Tag: in your readme.txt file (it should be latest production-ready version).
You will also need to make sure, version is correct on your main plugin .php file header.
Also... version should be tagged to tags/{your_version} with svn copy for example, to tag version 5.2.0 from master we would want to do...
svn copy trunk tags/5.2.0

This should match Stable tag:
If al this is done and you have like waited for at least 10 hours... And still version ain't live (which is very rare), you can go ahead and do another commit with maybe just another line break to like ping WordPress again...
Do this only when everything above doesn't work and you have waited like 10 hours and do it only once because this is an expensive operation for wp.org servers...
Hope that helps (somebody).


Q: Does size of a VARCHAR column matter when used in queries
Possible Duplicate:
is there an advantage to varchar(500) over varchar(8000)?

I understand that a VARCHAR(200) column containing 10 characters takes same amount of space as a VARCHAR(20) column containing same data.
I want to know if changing a dozen VARCHAR(200) columns of a specific table to VARCHAR(20) would make the queries run faster, especially when:

*

*These columns will never contain more than 20 characters

*These columns are often used in ORDER BY clause

*These columns are often used in WHERE clause

*

*Some of these columns are indexed so that they can be used in WHERE clause

PS: I am using SQL Server 2000 but will upgrade to later versions of SQL anytime soon.

A: Here's a blog post that explains under what circumstances and why there are performance differences when using different column sizes (with tests and technical details):
Advanced TSQL Tuning: Why Internals Knowledge Matters

A: It does matter for the query optimiser when it will evaluate the best query path to perform your query.  When more than one path will be available, it will calculate an I/O cost and other various parameters based on your query and from these, chose the one that will appears to him as the least costly.
This is not an absolute calculation, it's only an approximation process.  Therefore, it can easily be thrown off if the apparent mean size required to manipulate the records from one table in memory is much bigger then what will be really necessary and the optimiser might chose a less performing path based on what it thinks would have be necessary for the others paths.
Having a realistic max size is also usefull to any other programmer that will come along looking at your code.  If I have a variable that I want to display in a GUI, I might allocate much more space than neededd if I see that is backed by something like nvarchar(200) or nvarchar(2000) instead of nvarchar(20) if its size is never greater than that.

A: Yes, the length of varchar affects estimation of the query, memory that will be allocated for internal operation (for example for sorting) and as consequence resources of CPU. You can reproduce it with the following simple example.
1.Create two tables:
create table varLenTest1
(
    a varchar(100)
)

create table varLenTest2
(
    a varchar(8000)
)

2. Fill both of them with some data:
declare @i int
set @i = 20000

while (@i > 0)
begin
    insert into varLenTest1 (a) values (cast(NEWID() as varchar(36)))
    set @i = @i - 1
end

3. Execute the following queries with "include actual execution plan":
select a from varLenTest1 order by a OPTION (MAXDOP 1) ;
select a from varLenTest2 order by a OPTION (MAXDOP 1) ;

If you inspect execution plans of these queries, you can see that estimated IO cost and estimated CPU cost is very different:

A:
Size matters
Always use the smallest data size that will accommodate the largest
  possible value. If a column is going to store values between 1 and 5,
  use tinyint instead of int.
This rule also applies to character columns. The smaller the data
  size, the less there is to read, so performance, over all, benefits.
  In addition, smaller size reduces network traffic. With newer
  technology, this tip seems less relevant, but don’t dismiss it out of
  hand. You’ll won’t regret being efficient from the get-go.

For more info visit http://www.techrepublic.com/blog/10-things/10-plus-tips-for-getting-the-best-performance-out-of-your-sql-server-data-types/


Q: Unable to change QT_QPA_PLATFORMTHEME environment variable Xubuntu 20.04 LTS
I want to change default XFCE theme for Qt applications. It's set to Fusion style on my app. I read from tutorials that I need kvantum manager and qt5ct
I installed both packages without any problems, both are working fine.
So when it comes to overriding environment variables I placed it in 3 different locations:

*

*.profile
echo "export QT_QPA_PLATFORMTHEME=qt5ct" >> ~/.profile

*/etc/environment
cat /etc/environment

# [...]
QT_QPA_PLATFORMTHEME=qt5ct

*autostart script

# [...]
export QT_QPA_PLATFORMTHEME=qt5ct

*.bashrc
# [...]
export QT_QPA_PLATFORMTHEME=qt5ct

I placed it in every location that I know off, still qt5ct is telling me that, it has wrong configuration and QT_QPA_PLATFORMTHEME=gtk2 is still set, so it has default system value as it had.
Message from qt5ct
Tell me is it so different in Xubuntu? Because I previously had done that on ArchLinux without any of this issues. Does Ubuntu has some own environment variables file?

A: you have to go to session settings go to advance and in environment variable add another one and set the name to be QT_QPA_PLATFORMTHEME and the value to qt5ct and then close session settings (make sure it gets save)
the next time you reboot qt5ct will work
that worked for me at least

A: As outlined in this answer https://askubuntu.com/a/952571, you need to install  qt5-style-plugins
sudo apt-get install qt5-style-plugins

and then set QT_QPA_PLATFORMTHEME=qt5ct in /etc/X11/Xsession.d/56xubuntu-session