text:
Q: How to use customized clustering function and metrics for pheatmap I have the following function
library(pheatmap)
plot_kmeans_heatmap <- function (dat=NULL, k=3, nstart=20) {
  # Data wrangling ----------------------------------------------------------
  set.seed(1)

  dat_m         <- kmeans(dat, k, nstart = nstart)
  m.kmeans      <- cbind(dat, dat_m$cluster)
  clusterid_col <- dim(m.kmeans)[2]

  # Ordering matrix ----------------------------------------------------------------

  # order the data row index according the last column (i.e. cluster ID)
  ordered_idx   <- order(m.kmeans[,clusterid_col])
  # order the matrix according to the order of the last column
  m.kmeans<- m.kmeans[ordered_idx,]

  # Plot it -----------------------------------------------------------------

  # Annotate row with class
  annot_row <- m.kmeans %>%
               transmute(gene_class=paste0("C", `dat_m$cluster`), rn=row.names(.))
  rownames(annot_row) <- annot_row$rn
  annot_row$rn <- NULL

  pheatmap(m.kmeans[,1:clusterid_col-1],
           scale="row",
           cluster_rows=F,
           cluster_cols=F,
           legend=T,
           annotation_row = annot_row,
           border_color = F,
           show_rownames=F,
           show_colnames=T)

}

With the following code:
irisn  <- iris[sample(nrow(iris), 30), ]
dat    <- irisn[,1:4]
plot_kmeans_heatmap(dat=dat, k=6, nstart=1)

It produces this plot:

My question is instead of using K-means,  I'd like to use my own customized function:
  hclustfun = function(x) hclust(x, method='ward.D2')
  distfun = function(x) as.dist(1-cor(x, method='pearson'))

How can I include that in pheatmap?


text:
Q: Python: Adding list items to a dictionary if conditions are met I'm trying to add the difference between numbers and, until the total difference > 20, append the number to a list that becomes a dictionary value where the key is the number_set. I'm getting a list out of range error right now.
The output should be multiple dictionary entries whose list differences add up to the closest number < 20.
number_set = 1
number_dict = {}

num_list = [1, 3, 5, 9, 18, 20, 22, 25, 27, 31]

incl_num_list = []
total = 0

for x in range(1, len(num_list)):

    if total < 20:
        total = total + (num_list[x+1] - num_list[x])
        incl_num_list.append(num_list[x])
    else:
        number_dict.update({km: num_list})
        km += 1
        incl_num_list = []
        total = 0

for k, v in number_dict.items():
    print k
    print v

The output should be
1
[1, 3, 5, 9, 18, 20]
2
[22, 25, 27, 31]

A: num_list = [1, 3, 5, 9, 18, 20, 22, 25, 27, 31]

overflow = 20
total = 0
key = 1
number_dict = {1: [1]}

for left, right in zip(num_list[:-1], num_list[1:]):
    total += right - left
    if total >= overflow:
        key += 1
        number_dict[key] = [right]
        total = 0
    else:
        number_dict[key].append(right)

for k, v in sorted(number_dict.items()):
    print k
    print v

Outputs:
1
[1, 3, 5, 9, 18, 20]
2
[22, 25, 27, 31]

A: For one thing, you're using km before it's been assigned to anything.
Traceback (most recent call last):
  File "<pyshell#29>", line 15, in <module>
    number_dict.update({km: num_list})
NameError: name 'km' is not defined

As ndpu points out, your last x will be out of range on your num_list.

redpajama_set_name: RedPajamaStackExchange


text:
Q: What is placing name with something called? Recently, I'm watching the Chinese port version of The Voice (not sure if I can call it that since they differ greatly at least in my opinion), 中國好聲音 (The Voice of China).
Every time the name of the show is said, it's referred to as 「加多寶 中國好聲音」. 「加多寶」 is the name of a drink. They sponsored it so the company name is placed every time with the show's title shows up. In Chinese, we call this 冠名贊助. Direct translation would be "name-placing sponsorship". 「冠名」 means literally placing a name on top somthing.
I know in America, there are lines like "<company>'s <show>", "<company> presents, <show>", or "<show>, brought to you by <company>". What is this called in English? What is this action of putting the company's name with the show's title called?
Upon further research, I also don't think this is an example of eponym, so I'm not looking for eponymize.(now whether or not that's a legit word is debatable)
Edit: I edited the title to avoid confusion since, per some dictionary, the meaning of eponymous is exactly bearing name of something or someone.

A: The 冠名赞助 sponsor itself is normally called a title sponsor in English (or sometimes a presenting sponsor if used in the "<event>, presented by <sponsor>" manner):

A title sponsor is a patron of an event that provides money, goods, or services in exchange for the exclusive right to have the patron's name appear prominently before the title of the event. […]
A title sponsor is often the highest level opportunity and provides a company with the exclusive right to have its name featured in conjunction with the title of the event.
The name of the title sponsor should be listed before the name of the event. For example, a title sponsorship might appear as "XYZ's Battle of the Stars." A title sponsor is sometimes also known as a presenting sponsor, and in that case the title of the event might appear as "XYZ Presents the Battle of the Stars."

As far as I am aware, however, there is no commonly used verb in English that corresponds to 冠名 itself. You would probably be understood just fine if you use title-sponsor as a verb ("Jiāduōbǎo title-sponsor The Voice of China"), but I don't recall seeing or hearing it used as such, so I don't think it's a common construction. More likely, as in Chinese1, you would simply say that "Jiāduōbǎo is the title sponsor for The Voice of China".

1 My intuitive feeling is that you would say "加多宝是中国好声音的冠名赞助" more commonly than "加多宝冠名了中国好声音", but my Chinese is not native enough to know if that's accurate.

A: I asked my wife who speaks Chinese and she said it is a kind of sponsorship.  I agree with her choice of word.  Sponsor is the name of the person providing money, so you might say, "The constant and awkward placement of sponsor names upsets me."

A: Technically, this marketing strategy is called "product placement."

Product placement means any form of audiovisual commercial communication consisting of the inclusion of or reference to a product, a service or the trade mark thereof so that it is featured within a programme, in return for payment or for similar consideration.
per http://ec.europa.eu/archives/information_society/avpolicy/reg/tvwf/advertising/product/index_en.htm


text:
Q: Session-only cookie for Express.js http://www.javascriptkit.com/javatutors/cookie.shtml

Session-only cookies, on the other
  hand, stores information in the
  browser memory, and is available for
  the duration of the browser session.
  In other words, the data stored inside
  a session cookie is available from the
  time of storage until the browser is
  closed. Moving from page to page
  during this time does not erase the
  data.

How can I achieve this using Express.js?

A: app.use(express.session({cookie: { path: '/', httpOnly: true, maxAge: null }, secret:'eeuqram'}));

The above works on IE8, Firefox and Chrome.
The important piece is maxAge:null

A: First off, that website is a horrible place to go.
Now on to the question.
What sessions actually are:

*

*Data is stored on the server side.

*A cookie is issued which contains an ID.

*This ID gets send back to the server on every request, due to the fact that the browser sends the cookies.

*Now the server can re-associate the ID in the cookie - commonly called Session ID or short SID - with the session data stored on the server.

Express.js has support for sessions built in.
What the example shows:

*

*Setting up the Express.js middleware

*Using a third-party store for saving the session data, in this case Redis (which IMO is overkill for your problem atm)

Installing Redis requires quite some work, but it's also possible to use Express.js's built-in memory store:
var express = require('express');
var app = express.createServer();

var MemoryStore = require('connect/middleware/session/memory');
app.use(express.bodyDecoder());
app.use(express.cookieDecoder());
app.use(express.session({ store: new MemoryStore({ reapInterval: 60000 * 10 }) }));

app.get('/', function(req, res){
    req.session.visitCount = req.session.visitCount ? req.session.visitCount + 1 : 1;
    res.send('You have visited this page ' + req.session.visitCount + ' times');
});

app.listen(4000);

This will simply keep track of how many times you visited the page, closed your browser and re-opend. The counts will still be there.
You can find more on the options of the MemoryStore, like maximum life time of a session, etc. here.

A: app.get('/remember', function(req, res) {
   res.cookie('rememberme', 'yes', { expires: 0, httpOnly: true });
 });

This will set session cookie. On browser close it will be erased!

A: The following is what I wanted (sort of). When I close browser the information is gone.
var express = require('express');
var app = express.createServer();

var MemoryStore = require('connect/middleware/session/memory');
app.use(express.bodyDecoder());
app.use(express.cookieDecoder());

app.get('/remember', function(req, res) {
    res.cookie('rememberme', 'yes', { expires: new Date() - 1, httpOnly: true });
});

app.get('/', function(req, res){
    res.send('remember: ' + req.cookies.rememberme);
});

app.listen(4000, '127.0.0.1');

A: Below is the updated code for Alfred's answer (session using Express.js).
    var express = require('express');
    var app = express.createServer();

    var MemoryStore = require('/home/node/node_modules/connect/lib/middleware/session/memory');
    app.use(express.bodyParser());
    app.use(express.cookieParser());
    app.use(express.session({
        key: 'some-key',
        secret: 'some-We1rD sEEEEEcret!',
        store: new MemoryStore({ reapInterval: 60000 * 10 })
    }));

   app.get('/', function(req, res) {
       req.session.visitCount = req.session.visitCount ? req.session.visitCount + 1 : 1;
       res.send('You have visited this page ' + req.session.visitCount + ' times');
   });

   app.listen(4000);

A: I know this is an old question but I'm adding an answer since all answers here seem to be either outdated, have security flaws or are just plain wrong.
As of now, express uses the MemoryStore by default, you don't need to explicitly handle that.
Also, as of now, the express-session's official readme page has a stark warning at the beginning to not use MemoryStore as the session store for production, quoting:

Warning The default server-side session storage, MemoryStore, is purposely not designed for a production environment. It will leak memory under most conditions, does not scale past a single process, and is meant for debugging and developing.
For a list of stores, see compatible session stores.

Here's a simple solution with connect-mongodb-session if you want to use MongoDBStore for session storage:
import express from 'express';
import session from 'express-session';
import ConnectMongoDbSession from 'connect-mongodb-session';

const app = express();
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.use(session({
  secret: < COOKIE_SECRET >,
  name: 'sessionId', // Don't use the default name, see http://expressjs.com/en/advanced/best-practice-security.html
  cookie: {
    httpOnly: true,
    secure: true, // Remove this if you're not using HTTPS, but it will be a massive security flaw
    sameSite: 'strict',
  },
  store: getStore(),

  // Boilerplate options, see:
  // * https://www.npmjs.com/package/express-session#resave
  // * https://www.npmjs.com/package/express-session#saveuninitialized
  resave: true,
  saveUninitialized: true,
}));

function getStore() {
  const MongoDBStore = ConnectMongoDbSession(session);

  const store = new MongoDBStore({
    uri: < DATABASE_URI >,
    collection: < SESSION_COLLECTION_NAME >,
    connectionOptions: {
      useNewUrlParser: true,
      useUnifiedTopology: true,
    },
  });

  store.on('error', (error: any) => {
    console.error(error);
  });

  return store;
}


text:
Q: Clickonce messagebox on install: Strong name signature not valid for assembly microsoft.mshtml.dll I've just started to get the following error in my clickonce application. I have just installed visual studio 2013 on my machine prior to this "Application validation did not succeed. Unable to continue.
when i click into details I get
Activation of C:\Temp\ClickOnce\myApp\myApp.application resulted in exception.
Following failure messages were detected:
Strong name signature not valid for this assembly Microsoft.mshtml.dll.

I also get two warnings but I do not believe they are the cause of the problem

*

*The manifest for this application does not have a signature. Signature validation will be ignored.

*The manifest for this application does not have a signature. Signature validation will be ignored.

Error Details are listed as
ERROR DETAILS
    Following errors were detected during this operation.
    * [02/12/2013 15:54:31] System.Deployment.Application.InvalidDeploymentException (SignatureValidation)
        - Strong name signature not valid for this assembly Microsoft.mshtml.dll.
        - Source: System.Deployment
        - Stack trace:
            at System.Deployment.Application.ComponentVerifier.VerifyStrongNameAssembly(String filePath, AssemblyManifest assemblyManifest)
            at System.Deployment.Application.ComponentVerifier.VerifyComponents()
            at System.Deployment.Application.DownloadManager.DownloadDependencies(SubscriptionState subState, AssemblyManifest deployManifest, AssemblyManifest appManifest, Uri sourceUriBase, String targetDirectory, String group, IDownloadNotification notification, DownloadOptions options)
            at System.Deployment.Application.ApplicationActivator.DownloadApplication(SubscriptionState subState, ActivationDescription actDesc, Int64 transactionId, TempDirectory& downloadTemp)
            at System.Deployment.Application.ApplicationActivator.InstallApplication(SubscriptionState& subState, ActivationDescription actDesc)
            at System.Deployment.Application.ApplicationActivator.PerformDeploymentActivation(Uri activationUri, Boolean isShortcut, String textualSubId, String deploymentProviderUrlFromExtension, BrowserSettings browserSettings, String& errorPageUrl)
            at System.Deployment.Application.ApplicationActivator.ActivateDeploymentWorker(Object state)

I am not signing the clickonce manifests. "Enable clickonce security settings" is checked. "This is a full trust application" is selected

A: I got this sorted. what I had to do was go into my project right click, add reference to go assemblies - extensions and there were two dll files listed under Microsoft.mshtml. I hovered over each of them and seen that the path of one was
c:/program files/Microsoft.NET/Primary Interop Assemblies/Microsoft.html.dll

and
c:/program files/Microsoft Visual Studio 12.0/Visual Studio Tools For Office/PIA/Common/Microsoft.mshtml.dll.

The refernce my project had was the second one in visual studio - I changed the reference to the one in Primary Interop Assemblies under project properties I went to the publish tab and clicked on the application files I set publish status to include. Then I went to project properties/references and double clicked on microsoft.mshtml to open its properties, I set 'embed interop types' to false and 'copy local' to true (as copy local was grayed out to false).
after this I uploaded it to my clickonce server and was able to download and install it.


text:
Q: nginx: how to serve /index.php of subfolders? I have a legacy php websiste that has been migrated to a new server with nginx (and php 7.4)
My nginx has near only this
server {
    listen 80;

    server_name domain.tld;

    root /var/www/domain.tld;

    error_log   /var/log/nginx/domain.tld-error.log  warn;
    access_log  /var/log/nginx/domain.tldt-access.log combined;

    client_body_buffer_size     10M;
    client_max_body_size        10M;

    location / {
        try_files $uri /index.php?$args;
    }

    location ~ \.php$ {
        try_files $uri =404;
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_pass unix:/run/php/php7.4-fpm.sock;
        fastcgi_index index.php;
        include fastcgi_params;
        fastcgi_param   SCRIPT_FILENAME    $document_root$fastcgi_script_name;
        fastcgi_param   SCRIPT_NAME        $fastcgi_script_name;
    }
}

If I access to mydomain.tld it works, it serves correctly mydomain.tld/index.php
but If I access mydomain.tld/subfolder or  mydomain.tld/subfolder/ it doesn't serve mydomain.tld/subfolder/index.php as I expect
What am I doing wrong?

A: I resolved modifiying the suggestion of Daniel W
I moved the location / block under location ~ \.php$
But instead of remove the initial / I prepended also $uri
location ~ \.php$ {
    try_files $uri =404;
    fastcgi_split_path_info ^(.+\.php)(/.+)$;
    fastcgi_pass unix:/run/php/php7.4-fpm.sock;
    fastcgi_index index.php;
    include fastcgi_params;
    fastcgi_param   SCRIPT_FILENAME    $document_root$fastcgi_script_name;
    fastcgi_param   SCRIPT_NAME        $fastcgi_script_name;
}

location / {
    index index.php;
    try_files $uri $uri/index.php?$args;
}

If I will find some pitfalls I will update my answer


text:
Q: Domain of a function 5 I was solving this domain:
$$ f(x)= \sqrt\frac{(e^x-2)^x + \arccos(e^x -2)}{x- \sqrt {x^2 -1}}$$
My solution is: $x^2 \geq 1$ and the argument of the first sqrt $\geq 0$ (can't solve this one) and $0 \leq x \leq \log3$ and $x \geq 2$ and the denominator $\neq 0$
Could you help me to reach the right solution?
note1: Missing the x- factor

A: You need that
$$\sqrt {x^2 -1}\neq 0 \quad \land\quad x-\sqrt {x^2 -1} \neq0$$
$$-1 \leq e^x -2 \leq 1 \quad \land\quad  e^x -2>0 \implies 0 < e^x -2 \leq 1$$
$$\frac{(e^x-2)^x + \arccos(e^x -2)}{x-\sqrt {x^2 -1}}\ge0$$

A: The necesaary conditions are :
$x^2>1$ as the denominator of the function cant be 0 ,
$e^x -2 >0$ as the function $a^x$ is defined for all real x iff a>0.
and $-1\leq e^x -2\leq 1$ for $ arccos(e^x-2)$.
and $x- \sqrt{x^2-1}>0$
Solving these conditions you will get the domain, as we can clearly see that $ arccos(e^x-2)$ and $(e^x -2)^x$ are non negative functions.


text:
Q: Cannot connect to imap server on python I'm a networking student who has little programming experience and I have simple project on my hands where I need to make a simple notification that notifies the user when an email arrives in gmail. I have been trying to get this to work for the last few weeks and I am honestly stuck and struggling. I'm using the code below and I think the problem is the authentication bit, where I can't connect to the server. All help is appreciated.
import imaplib
import re
import time
import subprocess

## enter your account details bellow!
imapServer = "imap.gmail.com"
port = "993"
username = "example@gmail.com"
password = "password"

##how often to check ? give interval in seconds! Checking too often might performance and stability.
checkInterval = 120

Mailbox = imaplib.IMAP4_SSL(imapServer, port)
rc,resp = Mailbox.login(username,password)
if rc == 'OK':
    print("Connected to mail-server " + imapServer)
rc, message = Mailbox.status('INBOX', "(UNSEEN)")
unreadCount = int(re.search("UNSEEN (\d+)",str( message[0])).group(1))
oldValue = 0
file = open("%sytemdrive%\Windows\Temp\mailnotify.tmp", "w+")
file.write(str(unreadCount))
file.close
while(1):
    rc, message = Mailbox.status('INBOX', "(UNSEEN)")
unreadCount = int(re.search("UNSEEN (\d+)",str( message[0])).group(1))
file = open("%sytemdrive%\Windows\Temp\mailnotify.tmp", "w+")
oldValue = int(file.readline())
file.close()
if (unreadCount>oldValue):
    subprocess.call(["notify-send", "-u", "low", "low", "t", "5000", "New email!", "New email!",
                     "You have " + str(unreadCount) + " unread " + "emails!" if unreadCount > 1 else "email!",
                     "--icon=email"])
    if oldValue != unreadCount:
        file = open("%sytemdrive%\Windows\Temp\mailnotify.tmp", "w+")
    file.write(str(unreadCount))
    file.close()
    time.sleep(checkInterval)
else :
    print('Fail to connect')
    Mailbox.logout()
    file.remove()


text:
Q: es6 deconstructing an object using a constant I was playing with es6 deconstruct feature and I did the following
const state = { a: 1 };
const ID = 'b';
const newState = { ...state, [ID]: 2 }

As you can see I use the value of the constant as the identifier, generating this new object.
//newStateValue ==> { a:1, b:2 }

I was wondering how the [ID] works?
Thanks

A: It's called Computed Property Names and its not related to deconstructing.

property names. That allows you to put an expression in brackets [],
  that will be computed and used as the property name. This is
  reminiscent of the bracket notation of the property accessor syntax,
  which you might have used to read and set properties already. Now you
  can use a similar syntax in object literals too

A: You can using strings in javascript objects as a key like this
   let obj = {
     ['name']: 'Your Name',
  };

now the key here s name to access its value we use obj.name and the same way if you use a variable that represent a string as a key it will be replaced by its value , and that's it look at this example below

let obj = {
    ['name']: 'Your Name',
};
let myName = 'name';
let anotherObj = {
    [myName]: 'Your Name ',
};
console.log(obj.name); // Your Name
console.log(anotherObj.name); // Your Name

A:  const id = "b":
 const obj = { [id]: 1};

equals:
 const id = "b";
 const obj = {};
 obj[id] = 1;

As always, the syntax can be found In the Ecma Spec, inside of the Expressions > Primary Expressions > Object Initializer part:
Objects are written like this:
 {[id]:2}

ObjectLiteral:
      {}
      {PropertyDefinitionList}

The property definition list is just some comma seperated Property Definitions:
 [id]:2

PropertyDefinitionList:
      PropertyDefinition
      PropertyDefinitionList,PropertyDefinition

A propertyDefinition might be one of the following:

PropertyDefinition:
      IdentifierReference
      CoverInitializedName
      PropertyName:AssignmentExpression
      MethodDefinition

And ours is a PropertyName:AssignmentExpression , so
 [id]

is a PropertyName, which is a ComputedPropertyName.
So the next time, justlook it ip in the docs ;)


text:
Q: MySqlDataReader must be closed MySqlCommand status =
    new MySqlCommand("select name_ru from request_status where id = '50'", conn);
MySqlDataReader dr_status = status.ExecuteReader();
dr_status.Read();
MySqlCommand cmd = new MySqlCommand(query, conn);
dt.Load(cmd.ExecuteReader());
MySqlDataReader dr = cmd.ExecuteReader();

error:

MySqlDataReader must be closed first

Please, help...

A: You need to use only one reader at the same time. You are using three. Wrap all readers in a using-block to ensure that they get disposed in all cases.
ExecuteReader is what executes your SQL. In your sample code you execute the same SQL three times which might not be what you intended.


text:
Q: How do I search for a string and return that string from an email in google apps script? I can extract the body of an email but I can not find a way to search that body. findText only works on documents and I haven't found a way to put an email into a document. The search in email only returns the whole email, which I already have. Am I looking at this the wrong way or have I missed something?

A: Assuming you can get the body of the email as a string, here is something you could try:
var doc = DocumentApp.getActiveDocument();

// Use editAsText to obtain a single text element containing
// all the characters in the document.
var text = doc.editAsText();

// Insert text at the beginning of the document.
text.insertText(0, 'Your Text To Insert.\n');

//Find search for your results
text.findText(searchPattern)

I am not familiar with Google-Script but I hope this could possibly point you in the right direction.
https://developers.google.com/apps-script/class_text


text:
Q: Windows not showing in grub Short Story:
I deleted the first partition and then created a new fat32 partition from it. Then installed manjaro. Now, I cant access Windows 10.
Question: How do I fix this, and get the windows 10 in my grub running?
Long story:
I had dual boot( windows and manjaro) on a HDD, i migrated to SSD using clonezilla. However, after plugging my SSD into the laptop i couldnt start windows, but i could start manjaro easily. So, I decided to install windows 10, after installation I couldnt access grub. I tried to fix this through manjaro live usb, but I couldnt install manjaro, so I deleted the first partition, then used installed manjaro. But that caused the windows to disappear from grub.

A: I was able to fix this problem by creating a windows installer disk by burning the iso to a drive using WoeUSB, i used NTFS.
After doing recovery through windows installer, I did sudo os-prober && sudo update-grub, and that solved the issue.


text:
Q: С++ ругается на массив ошибка: expression must have a constant value the value of variable (declared at line 19) cannot be used as a constant

Не совсем понимаю, что у меня не так, переменная "sh" объявлена как константа.

A: Можно попробовать
constexpr int sh = n;

и массиву станет хорошо... А вот этому присваиванию - вряд ли.


text:
Q: Translating C# to PowerShell in InterIMAP I'm having a problem with using C# in my PowerShell script. The library I'm trying to use is InterIMAP
Specifically, I am trying to convert this constructor:
using InterIMAP;

IMAPConfig config = new IMAPConfig("server","username","password", true, false, "INBOX");

The PowerShell script I have so far:
$loadLib =[Reflection.Assembly]::LoadFile('C:\Users\......\InterIMAP.dll);

$config= [InterIMAP.IMAP.IMAPConfig]::IMAPConfig("imap.gmail.com", $user, $password, $true, $true, "INBOX");

I think the issue I'm having is because the IMAP class has a pointer to the IMAPConfig class: http://interimap.codeplex.com/SourceControl/latest#InterIMAP/InterIMAP/Client/IMAP.cs
I must be doing something wrong. Any help appreciated

A: In your PowerShell code, you're accessing IMAPConfig() as a static method of the IMAPConfig class, which I'm guessing is not valid. In order to use an object constructor in PowerShell, you need to use the New-Object cmdlet.
The -TypeName parameter specifies the .NET class that you want to instantiate. The -ArgumentList parameter accepts an array of arbitrary System.Object objects that represent the constructor parameters.
$config = New-Object -TypeName InterIMAP.IMAP.IMAPConfig -ArgumentList @('imap.gmail.com', $User, $Password, $true, $true, 'INBOX');


text:
Q: SQL Execution plan in ColdFusion I wonder if ColdFusion can get the execution plan from Microsoft SQL Server?
Or even the Estimated execution plan.
It would be nice to get a query back of all the costs.

A: As mentioned in the link @James posted, there are several methods you can use to retrieve the information about the execution plan using a simple cfquery. A couple things to keep in mind:

*

*SET SHOWPLAN options are usually applied to the session connection meaning they may persist beyond the current request if you are using connection pooling (which is undesirable). Be sure to always disable the setting at the end of the query - even if an error occurs.

*Some SET SHOWPLAN options return multiple resultsets. CFQuery only returns a single resultset. So it may not capture all of the data returned.

*Most of the system views and procedures (sys.dm_exec_sql_text, etcetera ...) require elevated permissions. The datasource user must be granted special access to use these objects. So keep in mind the security implications.

...To execute sys.dm_exec_query_plan, a user must be a member of the
  sysadmin fixed server role or have the VIEW SERVER STATE permission on
  the server.

UPDATE:
As @Travis mentioned in the comments, SET SHOWPLAN options must be run separately. So you need separate cfquery's to toggle the setting ON|OFF before and after the main query. Here is a quick and dirty example. Note, the transaction is to ensure the same connection is used throughout. It may be overkill, but should not hurt anything.
<cftransaction>
    <cftry>
        <!--- note, SHOWPLAN_ALL does NOT execute the SQL --->
        <cfquery name="toggleStats" datasource="someDSN">
            SET SHOWPLAN_ALL ON
        </cfquery>
        <cfquery name="getQueryStats" datasource="someDSN">
            --- some sql query here
        </cfquery>
        <cfcatch>
            <!--- rethrow and rollback automatically --->
            <cfrethrow>
        </cfcatch>
        <cffinally>
            <!--- always disable the setting --->
            <cfquery name="toggleStats" datasource="someDSN">
                SET SHOWPLAN_ALL OFF
            </cfquery>
        </cffinally>
    </cftry>
</cftransaction>

<cfif structKeyExists(variables, "getQueryStats")>
    <cfdump var="#getQueryStats#" label="Query Statistics">
</cfif>

A: This seems to cover what you are looking for
How do I obtain a Query Execution Plan?
Then just wrap it in <cfquery>


text:
Q: Running an aws ecs task in a region based on the cost of spot instances I am recently experimenting with AWS and in particular the ECS service.
I have an application that runs tasks in a cluster and these tasks are launched via a lambda using boto3.
Wanting to reduce the cost of running the containers I was thinking of creating multiple clusters in different regions by setting FARGATE_SPOT as the capacity provider and then choosing the cluster in which to run the containers based on the lowest cost of the spot instances.
To control that cost and select the region accordingly I was thinking about the existence of an API that would allow me to do this in the lambda but I couldn't find anything in the documentation.
Would it be possible to do something like this ? If yes, is there an API to check the trend of the spot market in the various regions ?

A: Fargate spot pricing is not variable like EC2 spot pricing. There is no Fargate spot market like there is with EC2. There is no trending Fargate spot price like EC2. It is a set price, with the cheapest Fargate spot pricing always being in the US-EAST-2 Ohio region, followed by Oregon, then Virginia.


text:
Q: C# How to catch alphabetical characters I'm currently working on a height conversion calculator, converting feet and inches to centimetres and want to create a "catch" that will produce an error message when the user inputs alphabetical characters rather than numerical characters, even potentially a catch that will address is the user input is invalid (e.g. entering 5' 111' rather than 5' 11').
The current catch doesn't work:
    Console.Clear();
    Console.WriteLine("Convert your height into Centimeters!");
    Console.WriteLine("Please give your height in the form of Feet and Inches, for example: 5'10\"");
    //user enters 5'10"
    heightString = Console.ReadLine();
    //heightString = "5'10""
    heightString = heightString.Remove(heightString.Length - 1);
    //heightString = "5'10"
    posOfInch = heightString.IndexOf("'");
    //posOfInch = 1

            try
            {
            }

            catch ()
            {
                throw new ("Generic Error Message");
            }

// this catch is invalid within the application
    feet = Convert.ToInt16(heightString.Remove(posOfInch));
    //feet = 5
    inches = Convert.ToInt16(heightString.Substring(posOfInch + 1));
    //inches = 10

    inches = (feet * 12) + inches;
    centimetres = (inches * 2.54);

    Console.WriteLine("Your height is " + centimetres + "cm");
    //Console.WriteLine("Please give your height measurement in inches : ");
    //calculating = int.Parse(Console.ReadLine());
    //inches(calculating);
    Console.ReadKey();
    return true;

Any advice on how I can challenge this catch issue?

A: No need to catch any exceptions, use TryParse:
string heightString = "5'10";

short feet, inches;
bool validFormat = false;
int index = heightString.IndexOf("'", StringComparison.Ordinal);

if (index >= 0)
    validFormat = short.TryParse(heightString.Remove(index), out feet)
               && short.TryParse(heightString.Substring(index + 1), out inches);

By the way, since you don't cast anywhere, catching an InvalidCastException is pointless.

A: Because you also need to do input validation (not just the conversion) I recommend using a regular expression. For instance:
\d+'\d{2}'

will only accept inputs with 1 or more digit, followed by a quote, in turn followed by other 2 digits and a final quote (just an example, you may find a more selective one).
Moreover if you want to extract the values to the convert them and store them as integers, you can use grouping and extract the values, just by putting parentheses around the input you want to capture.
For reference check this out: https://www.codeproject.com/articles/93804/using-regular-expressions-in-c-net


text:
Q: How to upgrade my arangodb docker container from 2.3.4 to 2.4.0 I am new to these docker concepts, can any one help me on this.
I have installed arangodb docker container from below steps,
First I cloned the Repository(https://github.com/arangodb/arangodb-docker) and then did below steps

*

*docker build -t arangodb

*docker create -p 8529:8529 --name arangodb arangodb:latest
Currently arangodb version I have is 2.3.4
How can I upgrade 2.3.4 to 2.4.0 version ?
Do I need to build the image with latest changes(pulling from repository) and then create the container ? If I do like this , I think it will create new container with latest version . But I want to upgrade the existing container so that I can remain have all my previous data(collections and what not).
Thanks in advance....

A: ArangoDB use the volume /data as database directory to store the collection data and the volume /apps as apps directory to store any extensions. These directory are marked as docker volumes.
You have two possibilities to upgrade your arangodb docker container to the next version:

*

*Using host directories

*Using a data container
(see: https://github.com/arangodb/arangodb-docker#persistent-data)

If you use one of the two possibilities you can easily upgrade without losing data


text:
Q: poor search performance for certain wildcard queries I am having performance issues when using wildcard searching for certain letter combinations, and I am not sure what else I need to to to possibly improve it.  All of my documents are following an envelope pattern that look something like the following.
<pdbe:person-envelope>
    <person xmlns="http://schemas.abbvienet.com/people-db/model">
        <account>
            <domain/>
            <username/>
        </account>
        <upi/>
        <title/>
        <firstName>
            <preferred/>
            <given/>
        </firstName>
        <middleName/>
        <lastName>
            <preferred/>
            <given/>
        </lastName>
    </person>
    <pdbe:raw/>
</pdbe:person-envelope>

I have a field defined called name, which includes the firstName and lastName paths:
{
  "field-name": "name",
  "field-path": [
    {
      "path": "/pdbe:person-envelope/pdbm:person/pdbm:firstName",
      "weight": 1
    },
    {
      "path": "/pdbe:person-envelope/pdbm:person/pdbm:lastName",
      "weight": 1
    }
  ],
  "trailing-wildcard-searches": true,
  "trailing-wildcard-word-positions": true,
  "three-character-searches": true
}

When I do some queries using search:search, some come back fast, whereas others come back slow.  This is with the filtered queries.
search:search("name:ha*",
  <options xmlns="http://marklogic.com/appservices/search">
    <constraint name="name">
      <word>
        <field name="name"/>
      </word>
    </constraint>
    <return-plan>true</return-plan>
  </options>
  )

I can see from the query plan that it is going to filter over all 136547 fragments in the db. But this query works fast.
<search:query-resolution-time>PT0.013205S</search:query-resolution-time>
<search:snippet-resolution-time>PT0.008933S</search:snippet-resolution-time>
<search:total-time>PT0.036542S</search:total-time>

However a search for name:tj* takes a long time, and also filters over all of the 136547 fragments.
<search:query-resolution-time>PT6.168373S</search:query-resolution-time>
<search:snippet-resolution-time>PT0.004935S</search:snippet-resolution-time>
<search:total-time>PT12.327275S</search:total-time>

I have the same indexes on both.  Are there any other indexes I should be enabling when I am specifically just doing a search via the field constraint? I have these other indexes enabled on the database itself, in general.
"collection-lexicon": true,
  "triple-index": true,
  "word-searches": true,
  "word-positions": true

I tried doing an unfiltered query, but that did not help as I got a bunch of matches on the whole document, and not the the fields I wanted.  I even tried to set the root-fragment to just my person element, but that did not seem to help things.
 "fragment-root": [
    {
      "namespace-uri": "http://schemas.abbvienet.com/people-db/model",
      "localname": "person"
    }
  ]

Thanks for any ideas.

A: Fragment roots are helpful if you want to use a searchable expression for that person element, and mostly if it occurs multiple times in one document. It won't make your current search constrain on that element.
In your case you enabled a number of relevant options, but the wildcard option only works for 4 characters of more. If you want to search on wildcards with less characters, you need to enable the three, two and one character search options.
The search phrases mentioned above both contained two characters with a wildcard. Since you only enabled the three character option, it had to rely on filtering. The fact some run fast, some slow is probably because of caching. If you repeat the same query, MarkLogic will return the result from cache.
For performance testing you would either have to restart MarkLogic regularly to flush caches, or search on (semi) random strings to avoid MarkLogic being able to cache. Or maybe both..
HTH!


text:
Q: Mroonga on Mariadb Primary Key Insert error I keep on getting duplicate primary key error when trying to insert into my Mroonga table on MariaDB 10.0.19. Does anyone know what might be the cause?
SQL:
    insert into tbl_mroonga select pk_id, keyword from tbl_inno;

Create table:
    create table tbl_mroonga (
    'PK_ID' int(11) not null default 0,
    'Keyword' varchar(191) null default null,
    primary key (`pk_id`),
    fulltext index ('keyword')) Engine=MROONGA;

    create table tbl_inno (
    'PK_ID' int(11) not null default 0,
    'Keyword' varchar(191) null default null,
    primary key (`pk_id`),
    fulltext index ('keyword')) Engine=INNODB;

I'm inserting about 3.5million rows from tbl_inno to tbl_mroonga and it fails at around 400K rows. I've tried it with "select distinct" and "group by pk_id" and still it fails.
Any help would be greatly appreciated!
Thank you.

A: Write a loop that copies over 10K rows at a time.  Use something like (example of the 13th chunk):
INSERT INTO tbl_mroonga
SELECT pk_id, keyword
    FROM tbl_inno
    WHERE pk_id >  120000
      AND pk_id <= 130000

and COMMIT after each chunk.


text: Q: Yii 2 и Angular 2 Пишу небольшое приложение на Yii 2 basic - админка и фронт. Так вот, как прикрутить правильно только для админки Angular 2 ? Первое что пришло в голову - кинуть его в папку web и делать запросы к админке отдавая к примеру json(ну вроде псевдо rest api). Второе - использовать стандартные возможности Yii 2, т.е. впихнуть напрямую код Angular 2 в базовый layout, ну и остальной код ангулара писать в файлах представлений Yii 2, также отдавая его в json. Но оба эти подхода мне не очень нравятся. Как поступить правильно в данной ситуации ?


text:
Q: C# Exception, file being use by another process I encountered an issue when trying to log the content into the .txt file.
Below is my code.
It will keep hit the exception as the process happen too fast.
Is there anyway to write a queue to wait or a locker to lock the current thread first?
DateTime time = DateTime.Now;

time = time.Minute > 30 ? time.Date.AddHours(time.Hour).AddMinutes(30) : time.Date.AddHours(time.Hour).AddMinutes(0);

var FilePath = "C:/temp/DebugLog/"+ webService + "/" + time.ToString("yyyyMMddHHmss") + "_Logs/";

if (!Directory.Exists(FilePath)) { Directory.CreateDirectory(FilePath); }

try
{
    using (StreamWriter w = File.AppendText(FilePath + time.ToString("yyyyMMddHHmss") + ".txt"))
    {
        w.WriteLine(
            Guid.NewGuid().ToString("N") + "; " + DateTime.Now.ToString("yyyyMMddHHmssms") + "; " +
            webService + "; " + eventName + "; " + DateTime.Now.ToString()  + "; " + transactionId + "; " + debuglog);
        w.Close();
    }
}
catch (Exception ex)
{

}
}


text:
Q: Rock papers scissors I was trying to make  a program of rock papers scissors. But the for the output that I am getting is bot satisfactory.
def rpc():
  import random
  moveset=["Rock","Paper","Scissors"]
  a=random.choice(moveset)
  "Rock">"Scissors","Scissors">"Paper","Paper">"Rock"
  playermove=input ("What will you play? please keep the first letter capital")
  print (a)
  if playermove == a:
    print ("draw")
  elif playermove>a:
    print("you win")
  elif playermove<a:
    print("you lose")
  else:
    print("no valid choice")
rpc()
rpc()

How should the code be modified?

A: as noted: your problem line is here:
  "Rock">"Scissors","Scissors">"Paper","Paper">"Rock". This line doesn't actually do anything.
The other problem is here:
elif playermove>a: you are comparing two strings and your line from above is getting ignored.  To understand string comparison, try playing around with some strings and comparing them.  The comparison works like sorting by alphabetical order and capital letters are less than lowercase.
>>> "a" > "b"
False
>>> "ac" > "ab"
True
>>> "A" > "a"
False
>>> "A" > "z"
False

So you need to create a different test to check for winning an losing plays.  there are many ways to do this.  a simple test might be creating a list of winner_to_loser and seeing if your combination is in the list
winner_loser = [('rock', 'scissors'), ('scissors', 'paper'), ('paper', 'rock')]
if (player_move, computer_move) in winner_loser:
    print("you win!")
elif (computer_move, player_move) in winner_loser:
   print("computer wins!")


text:
Q: Embedded linux PPC32 dynamic memory checking tool? The system has only 128 MB ram and I couldn't successfully run valgrind, it will just run out of memory and too slow to be usable. The processor is also very slow.
Is there a simpler tool on PPC32 to check for heap corruption/leaks for PPC 32 with very limited resource?
I am thinking maybe something small like libsegfault.so that can be used with LD_PRELOAD , but to check for malloc/free problems?

A: Electric Fence is ideal for this use case (and does leverage LD_PRELOAD, can be combined with libsegfault.so).
In addition to efence, you can use other features, some of which will end up costing cycles and/or additional memory overhead (though still likely significantly less than valgrind):

*

*gcc's mudflaps

*gcc's fortify-source

*glibc's mcheck(), MALLOC_CHECK_

*clang's address sanitizer


text:
Q: Bootstrap 3 collapse with 2 cols I have to cols (col-md-6) and want a collapse in each of this cols, but when I click on a panel each others won't close.
Here's an example code:

                        TITLE

TEXT

                        TITLE

TEXT

Can someone help me please?
Thanks

A: http://www.bootply.com/7M5lUWZK6e
Here's a working example. I think the reason yours isn't working is because the column is not a part of the panel-default div. You will need to clear the padding on the panel.

          Collapsible Group Item #1

        Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.

          Collapsible Group Item #2

        Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.


text:
Q: Angular 5 invalid Date IE 11 I am using Angular 5 and i try to convert a string to Date. In Chrome is perfectly working but in Internet Explorer 11 i am getting the error of Invalid Date. I tried multiple ways but i haven't succeed. I have also follow the solution provided here Solution provided The string that i have as input is '2018-04-23 15:21:15 +0300' (value) and i am using the following code:
var a = new Date(value);

I also tried the following :
var a = new Date (new Date(value));

A: The problem lies in the format that you pass the required date to the Date() object. IE do not support the date format "yyyy-mm-dd" and therefore fail. Following formats are definitely supported across all browsers and would advise sticking to one of these to avoid errors:
var d = new Date(2011, 01, 07); // yyyy, mm-1, dd
var d = new Date(2011, 01, 07, 11, 05, 00); // yyyy, mm-1, dd, hh, mm, ss
var d = new Date("02/07/2011"); // "mm/dd/yyyy"
var d = new Date("02/07/2011 11:05:00"); // "mm/dd/yyyy hh:mm:ss"
var d = new Date(1297076700000); // milliseconds
var d = new Date("Mon Feb 07 2011 11:05:00 GMT"); // ""Day Mon dd yyyy hh:mm:ss GMT/UTC

So in your case, you can use below code to solve the issue
var result = "2018-04-23 15:21:15 +0300'".split(" ");
var date=result[0].trim().split("-");
var time=result[1].trim().split(":");

var mydate = new Date(parseInt(date [2], 10),
                  parseInt(date [1], 10) - 1,
                  parseInt(date [0], 10),
                  parseInt(time [0], 10),
                  parseInt(time [1], 10),
                  parseInt(time [2], 10));


text:
Q: Extending section heading underline into margin I'm using Koma and have got my section heading numbers set in the margin of the page. I have also got a coloured underline for the section headings. I want, if possible, the underline for the section headings to extend to include the number, i.e. to extend into the margin enough to start where the section number itself starts.
As a bonus, at the moment my section numbers appear at varying distances into the margin - they are in the margin just enough to fit that number. I would prefer to set them at a constant amount left of the margin, so that the left-hand side of each number lines up.
MWE:
\PassOptionsToPackage{svgnames,table,dvipsnames}{xcolor}
\documentclass[a4paper,10pt,oneside,DIV=9]{scrartcl}

% Packages
\usepackage{scrlayer-scrpage}
\usepackage{xcolor} % showframe loads this
\usepackage[normalem]{ulem}
\usepackage{hyperref}

% demo only
\usepackage{lipsum}
\usepackage{mwe}

% theme colours
\definecolor{MyThemeColour}{cmyk}{0.10,0.10,1.00,0} % personal yellow

% KOMA and general setup
\renewcommand*{\sectionformat}{%
  \llap{\thesection\autodot\enskip}%
}
\renewcommand*{\subsectionformat}{%
  \llap{\thesubsection\autodot\enskip}%
}
\renewcommand*{\subsubsectionformat}{%
  \llap{\thesubsubsection\autodot\enskip}%
}

% underline section headings
\makeatletter
\renewcommand{\sectionlinesformat}[4]{%
    \@hangfrom{\hskip #2\expandafter\headuline\expandafter{#3}}%
    {#4}%
}
\makeatother
\newcommand\headuline{%
    \bgroup\markoverwith{\textcolor{MyThemeColour}{\rule[-0.75ex]{1pt}{1pt}}}\ULon% 2pt 2pt
}
\AtBeginDocument{\renewcommand\Sectionformat[2]{\headuline{#1}}}

% recalc the text block after all the font loading
\KOMAoptions{DIV=last}

\begin{document}
\section{Lipsum}
\blinddocument
\end{document}

A: The following draws the line under the number and heading in one go.  We put the numbers in a box of fixed width, governed by a new length \mysecnumhang.  Then we define the section line format to (1) back up this width, (2) print the box with the section number and then the title, and (3) underline everything.

\PassOptionsToPackage{svgnames,table,dvipsnames}{xcolor}
\documentclass[a4paper,10pt,oneside,DIV=9]{scrartcl}

% Packages
\usepackage{scrlayer-scrpage}
\usepackage{xcolor} % showframe loads this
\usepackage[normalem]{ulem}
\usepackage{hyperref}

% demo only
\usepackage{lipsum}
\usepackage{mwe}

% theme colours
\definecolor{MyThemeColour}{cmyk}{0.10,0.10,1.00,0} % personal yellow

\newlength{\mysecnumhang}
\setlength{\mysecnumhang}{30pt}
% KOMA and general setup
\renewcommand*{\sectionformat}{%
  \makebox[\mysecnumhang][l]{\thesection\autodot\enskip}%
}
\renewcommand*{\subsectionformat}{%
  \makebox[\mysecnumhang][l]{\thesubsection\autodot\enskip}%
}
\renewcommand*{\subsubsectionformat}{%
  \makebox[\mysecnumhang][l]{\thesubsubsection\autodot\enskip}%
}

\renewcommand{\sectionlinesformat}[4]{%
    \hspace{-\mysecnumhang}\expandafter\headuline{#3#4}%
}

\newcommand\headuline{%
    \bgroup\markoverwith{\textcolor{MyThemeColour}{\rule[-0.75ex]{1pt}{1pt}}}\ULon% 2pt 2pt
    }

% recalc the text block after all the font loading
\KOMAoptions{DIV=last}

\begin{document}
\section{Lipsum}
\blinddocument
\end{document}

For the extra request to deal with \section* reasonably, one can use the following:
\PassOptionsToPackage{svgnames,table,dvipsnames}{xcolor}
\documentclass[a4paper,10pt,oneside,DIV=9]{scrartcl}

% Packages
\usepackage{scrlayer-scrpage}
\usepackage{xcolor} % showframe loads this
\usepackage[normalem]{ulem}
\usepackage{hyperref}

% demo only
\usepackage{lipsum}
\usepackage{mwe}

% theme colours
\definecolor{MyThemeColour}{cmyk}{0.10,0.10,1.00,0} % personal yellow

\newlength{\mysecnumhang}
\setlength{\mysecnumhang}{30pt}
% KOMA and general setup
\renewcommand*{\sectionformat}{%
  \makebox[\mysecnumhang][l]{\thesection\autodot\enskip}%
}
\renewcommand*{\subsectionformat}{%
  \makebox[\mysecnumhang][l]{\thesubsection\autodot\enskip}%
}
\renewcommand*{\subsubsectionformat}{%
  \makebox[\mysecnumhang][l]{\thesubsubsection\autodot\enskip}%
}

\newbox\tmpseclinenobox
\renewcommand{\sectionlinesformat}[4]{%
  \sbox\tmpseclinenobox{#3}%
  \ifdim\wd\tmpseclinenobox>0pt\hspace{-\mysecnumhang}\fi
  \expandafter\headuline{#3#4}%
}

\newcommand\headuline{%
    \bgroup\markoverwith{\textcolor{MyThemeColour}{\rule[-0.75ex]{1pt}{1pt}}}\ULon% 2pt 2pt
    }

% recalc the text block after all the font loading
\KOMAoptions{DIV=last}

\begin{document}
\section*{Lipsum}
Some text.
\section{Lipsum}
\blinddocument
\end{document}

A: It's not really a clean solution, but you can draw zero-width rules under the left-overlapped section numbers that blend into the actual underlines. Note that the box of the rule is zero-width (using \makebox[0pt]) while the rule itself has the width specified in the \rule command - LaTeX just ignores the width for calculating the position of the following content.
MWE:
\PassOptionsToPackage{svgnames,table,dvipsnames}{xcolor}
\documentclass[a4paper,10pt,oneside,DIV=9]{scrartcl}

% Packages
\usepackage{scrlayer-scrpage}
\usepackage{xcolor} % showframe loads this
\usepackage[normalem]{ulem}
\usepackage{hyperref}

% demo only
\usepackage{lipsum}
\usepackage{mwe}

% theme colours
\definecolor{MyThemeColour}{cmyk}{0.10,0.10,1.00,0} % personal yellow

% KOMA and general setup
\renewcommand*{\sectionformat}{%
  \makebox[0pt]{\color{MyThemeColour}\rule[-0.75ex]{33pt}{1pt}}\llap{\thesection\autodot\enskip}%
}
\renewcommand*{\subsectionformat}{%
  \makebox[0pt]{\color{MyThemeColour}\rule[-0.75ex]{48pt}{1pt}}\llap{\thesubsection\autodot\enskip}%
}
\renewcommand*{\subsubsectionformat}{%
  \makebox[0pt]{\color{MyThemeColour}\rule[-0.75ex]{58pt}{1pt}}\llap{\thesubsubsection\autodot\enskip}%
}

% underline section headings
\makeatletter
\renewcommand{\sectionlinesformat}[4]{%
    \@hangfrom{\hskip #2\expandafter\headuline\expandafter{#3}}%
    {#4}%
}
\makeatother
\newcommand\headuline{%
    \bgroup\markoverwith{\textcolor{MyThemeColour}{\rule[-0.75ex]{1pt}{1pt}}}\ULon% 2pt 2pt
}
\AtBeginDocument{\renewcommand\Sectionformat[2]{\headuline{#1}}}

% recalc the text block after all the font loading
\KOMAoptions{DIV=last}

\begin{document}
\section{Lipsum}
\blinddocument
\end{document}

Result:


text:
Q: C# CRC implementation I am trying to integrate a Serial-port device into my application, which needs CRC-CCTT validation for the bytes that I send to it.
I'm kinda new into managing byte packets, and need help for this.
It uses this formula for making the CRC calculus:
[CRC-CCITT P(X)= X16 + C12 + C8 + 1]

So for example for the packet: 0xFC 0x05 0x11, the CRC is 0x5627.
Then I send this packet to the device: 0xFC 0x05 0x11 0x27 0x56
Also, packet lenghts will vary from 5 to 255 (including CRC checks bytes)
I don't know how to implement this, so any idea/suggestions will be welcome.
Hope I made myself clear,
Thanks in Advance.
EDIT:
here is the specification of what I need to do:

A: Have you tried Googling for an example? There are many of them.
Example 1: http://tomkaminski.com/crc32-hashalgorithm-c-net
Example 2: http://www.sanity-free.com/12/crc32_implementation_in_csharp.html
You also have native MD5 support in .Net through System.Security.Cryptography.MD5CryptoServiceProvider.
EDIT:
If you are looking for an 8-bit algorithm: http://www.codeproject.com/KB/cs/csRedundancyChckAlgorithm.aspx
And 16-bit: http://www.sanity-free.com/133/crc_16_ccitt_in_csharp.html

A: LOL, I've encountered exactly the same STATUS REQUEST sequense, i'm currently developing software to use with CashCode Bill Validator:). Here's the code worked for me, it's CRC16-CCITT with reversed polynomial equals 0x8408 (BDPConstants.Polynomial in the code). That's the code worked for me:
    // TableCRC16Size is 256 of course, don't forget to set in somewhere
    protected ushort[] TableCRC16 = new ushort[BDPConstants.TableCRC16Size];
    protected void InitCRC16Table()
    {
        for (ushort i = 0; i < BDPConstants.TableCRC16Size; ++i)
        {
            ushort CRC = 0;
            ushort c = i;
            for (int j = 0; j < 8; ++j)
            {
                if (((CRC ^ c) & 0x0001) > 0)
                    CRC = (ushort)((CRC >> 1) ^ BDPConstants.Polynominal);
                else
                    CRC = (ushort)(CRC >> 1);
                c = (ushort)(c >> 1);
            }
            TableCRC16[i] = CRC;
        }
    }

    protected ushort CalcCRC16(byte[] aData)
    {
        ushort CRC = 0;
        for (int i = 0; i < aData.Length; ++i)
            CRC = (ushort)(TableCRC16[(CRC ^ aData[i]) & 0xFF] ^ (CRC >> 8));
        return CRC;
    }

Initialize the table somewhere (e.g. Form constructor):
InitCRC16Table();

then use it in your code just like that,
You can use List of bytes instead of array, more convinient to pack byte data in the 'packet' for sending
uint CRC = CalcCRC16(byte[] aByte)
// You need to split your CRC in two bytes of course
byte CRCHW = (byte)((CRC) / 256); // that's your 0x56
byte CRCLW = (byte)(CRC);         // that's your 0x27

A: standard crc-ccitt is x16 + x12 + x5 + 1  I wrote the one @ http://www.sanity-free.com/133/crc_16_ccitt_in_csharp.html  If I have time I'll see if I can't modify it to run with the x16 + x12 + x8 + 1 poly.
EDIT:
here you go:
public class Crc16CcittKermit {
    private static ushort[] table = {
      0x0000, 0x1189, 0x2312, 0x329B, 0x4624, 0x57AD, 0x6536, 0x74BF,
      0x8C48, 0x9DC1, 0xAF5A, 0xBED3, 0xCA6C, 0xDBE5, 0xE97E, 0xF8F7,
      0x1081, 0x0108, 0x3393, 0x221A, 0x56A5, 0x472C, 0x75B7, 0x643E,
      0x9CC9, 0x8D40, 0xBFDB, 0xAE52, 0xDAED, 0xCB64, 0xF9FF, 0xE876,
      0x2102, 0x308B, 0x0210, 0x1399, 0x6726, 0x76AF, 0x4434, 0x55BD,
      0xAD4A, 0xBCC3, 0x8E58, 0x9FD1, 0xEB6E, 0xFAE7, 0xC87C, 0xD9F5,
      0x3183, 0x200A, 0x1291, 0x0318, 0x77A7, 0x662E, 0x54B5, 0x453C,
      0xBDCB, 0xAC42, 0x9ED9, 0x8F50, 0xFBEF, 0xEA66, 0xD8FD, 0xC974,
      0x4204, 0x538D, 0x6116, 0x709F, 0x0420, 0x15A9, 0x2732, 0x36BB,
      0xCE4C, 0xDFC5, 0xED5E, 0xFCD7, 0x8868, 0x99E1, 0xAB7A, 0xBAF3,
      0x5285, 0x430C, 0x7197, 0x601E, 0x14A1, 0x0528, 0x37B3, 0x263A,
      0xDECD, 0xCF44, 0xFDDF, 0xEC56, 0x98E9, 0x8960, 0xBBFB, 0xAA72,
      0x6306, 0x728F, 0x4014, 0x519D, 0x2522, 0x34AB, 0x0630, 0x17B9,
      0xEF4E, 0xFEC7, 0xCC5C, 0xDDD5, 0xA96A, 0xB8E3, 0x8A78, 0x9BF1,
      0x7387, 0x620E, 0x5095, 0x411C, 0x35A3, 0x242A, 0x16B1, 0x0738,
      0xFFCF, 0xEE46, 0xDCDD, 0xCD54, 0xB9EB, 0xA862, 0x9AF9, 0x8B70,
      0x8408, 0x9581, 0xA71A, 0xB693, 0xC22C, 0xD3A5, 0xE13E, 0xF0B7,
      0x0840, 0x19C9, 0x2B52, 0x3ADB, 0x4E64, 0x5FED, 0x6D76, 0x7CFF,
      0x9489, 0x8500, 0xB79B, 0xA612, 0xD2AD, 0xC324, 0xF1BF, 0xE036,
      0x18C1, 0x0948, 0x3BD3, 0x2A5A, 0x5EE5, 0x4F6C, 0x7DF7, 0x6C7E,
      0xA50A, 0xB483, 0x8618, 0x9791, 0xE32E, 0xF2A7, 0xC03C, 0xD1B5,
      0x2942, 0x38CB, 0x0A50, 0x1BD9, 0x6F66, 0x7EEF, 0x4C74, 0x5DFD,
      0xB58B, 0xA402, 0x9699, 0x8710, 0xF3AF, 0xE226, 0xD0BD, 0xC134,
      0x39C3, 0x284A, 0x1AD1, 0x0B58, 0x7FE7, 0x6E6E, 0x5CF5, 0x4D7C,
      0xC60C, 0xD785, 0xE51E, 0xF497, 0x8028, 0x91A1, 0xA33A, 0xB2B3,
      0x4A44, 0x5BCD, 0x6956, 0x78DF, 0x0C60, 0x1DE9, 0x2F72, 0x3EFB,
      0xD68D, 0xC704, 0xF59F, 0xE416, 0x90A9, 0x8120, 0xB3BB, 0xA232,
      0x5AC5, 0x4B4C, 0x79D7, 0x685E, 0x1CE1, 0x0D68, 0x3FF3, 0x2E7A,
      0xE70E, 0xF687, 0xC41C, 0xD595, 0xA12A, 0xB0A3, 0x8238, 0x93B1,
      0x6B46, 0x7ACF, 0x4854, 0x59DD, 0x2D62, 0x3CEB, 0x0E70, 0x1FF9,
      0xF78F, 0xE606, 0xD49D, 0xC514, 0xB1AB, 0xA022, 0x92B9, 0x8330,
      0x7BC7, 0x6A4E, 0x58D5, 0x495C, 0x3DE3, 0x2C6A, 0x1EF1, 0x0F78
    };

    public static ushort ComputeChecksum( params byte[] buffer ) {
        if ( buffer == null ) throw new ArgumentNullException( );
        ushort crc = 0;
        for ( int i = 0; i < buffer.Length; ++i ) {
            crc = (ushort)( ( crc >> 8 ) ^ table[( crc ^ buffer[i] ) & 0xff] );
        }
        return crc;
    }

    public static byte[] ComputeChecksumBytes( params byte[] buffer ) {
        return BitConverter.GetBytes( ComputeChecksum( buffer ) );
    }
}

sample:
ushort crc = Crc16CcittKermit.ComputeChecksum( 0xFC, 0x05, 0x11 );
byte[] crcBuffer = Crc16CcittKermit.ComputeChecksumBytes( 0xFC, 0x05, 0x11 )
// crc = 0x5627
// crcBuffer = { 0x27, 0x56 }

A: it works and dose not need table:
    /// <summary>
    /// Gens the CRC16.
    /// CRC-1021 = X(16)+x(12)+x(5)+1
    /// </summary>
    /// <param name="c">The c.</param>
    /// <param name="nByte">The n byte.</param>
    /// <returns>System.Byte[][].</returns>
    public ushort GenCrc16(byte[] c, int nByte)
    {
        ushort Polynominal = 0x1021;
        ushort InitValue = 0x0;

        ushort i, j, index = 0;
        ushort CRC = InitValue;
        ushort Remainder, tmp, short_c;
        for (i = 0; i < nByte; i++)
        {
            short_c = (ushort)(0x00ff & (ushort) c[index]);
            tmp = (ushort)((CRC >> 8) ^ short_c);
            Remainder = (ushort)(tmp << 8);
            for (j = 0; j < 8; j++)
            {

                if ((Remainder & 0x8000) != 0)
                {
                    Remainder = (ushort)((Remainder << 1) ^ Polynominal);
                }
                else
                {
                    Remainder = (ushort)(Remainder << 1);
                }
            }
            CRC = (ushort)((CRC << 8) ^ Remainder);
            index++;
        }
        return CRC;
    }

A: You are actually using CRC-XMODEM LSB-reverse (with 0x8408 coefficient). C# code for this calculus is:
public void crc_bytes(int[] int_input)
{
   int_array = int_input;
   int int_crc = 0x0; // or 0xFFFF;

   int int_lsb;
   for (int int_i = 0; int_i < int_array.Length; int_i++)
   {
      int_crc = int_crc ^ int_array[int_i];
      for (int int_j = 0; int_j < 8; int_j ++ )
      {
         int_lsb = int_crc & 0x0001; // Mask of LSB
         int_crc = int_crc >> 1;
         int_crc = int_crc & 0x7FFF;
         if (int_lsb == 1)
            int_crc = int_crc ^ 0x8408;
      }
   }

   int_crc_byte_a = int_crc & 0x00FF;
   int_crc_byte_b = (int_crc >> 8) & 0x00FF;
}

Read more (or download project):
http://www.cirvirlab.com/index.php/c-sharp-code-examples/141-c-sharp-crc-computation.html


text:
Q: Javascript/TypeScript : asynchronicity problem with attribute of class with Socket.io? I am developing a WebSocket server with NodeJS and SocketIO. The code was originally in ES6 and I try to switch to TypeScript because I got a problem. I don't have the same result when I try to use attribute from the class or when I use a variable (const or let). It seems like it is asynchronous when I use an attribute from the class.
I think the easiest way to explain is to show you the two pieces of code and their output results. The problem occurs in a fake client I have created to build functional test of the WebSocket server:
1st Case:
import {io, Socket, ManagerOptions} from "socket.io-client";

export default class Admin {
   private user: number;
   private data: Partial<ManagerOptions & SocketOptions>;
   private chatSocket: Socket;

   constructor(userId: number) {
     this.user = userId;
   }

   initQueryAndAuth() {
        this.data = {
            query: {
                user: this.user,
                room: "-1",
                role: 'administrator',
            },
            auth: {
                apiKey: process.env.SERVER_CHAT_API_KEY,
            }
        };
    }

   connectChat() {
        this.initQueryAndAuth();

        this.chatSocket = io("http://localhost:" + process.env.SERVER_PORT + "/chat", this.data);
        console.log(['From client', "0", this.chatSocket.connected]);
        setTimeout(() => {
            console.log(['From client', "3", this.chatSocket.connected]);
        },10);
        return Promise.all([this.joinChat(), this.onEventsChat()]);
    }

    joinChat() {
        return new Promise<void>(resolve => {
            console.log(['From client', "1", this.chatSocket.connected]);
            this.chatSocket.on("connect", () => {
                console.log(['From client', "4", this.chatSocket.connected]);
            });
            console.log(['From client', "2", this.chatSocket.connected]);
        })
    }
}

The console output :

2nd case (When I replace the attribute of class by a variable. I just write the code which changed) :
   connectChat() {
        this.initQueryAndAuth();

        const test = io("http://localhost:" + process.env.SERVER_PORT + "/chat", this.data);
        console.log(['From client', "0", test.connected]);
        setTimeout(() => {
            console.log(['From client', "3", test.connected]);
        }, 10);
        return Promise.all([this.joinChat(test), this.onEventsChat()]);
    }

    joinChat(test) {
        return new Promise<void>(resolve => {
            console.log(['From client', "1", test.connected]);
            test.on("connect", () => {
                console.log(['From client', "4", test.connected]);
            });
            console.log(['From client', "2", test.connected]);
        })
    }

The output of the console :

If someone can explain to me why in the first case the output from the client n°4 is false and true in the second case, it would help me a lot.
Thank you for reading my post.
Have a nice day.


text:
Q: MySQL JOIN not filtering on WHERE clause with < > operators, since moving from MySQL 5.6 -> 5.7 We're upgrading our DB systems to MySQL 5.7 coming from MySQL 5.6 and since the upgrade a few queries have been running really slow.
After some investigating we narrowed it down to a few JOIN queries which suddenly don't listen to the 'WHERE' clause anymore when using a 'larger than' > or 'smaller than' < operator. When using a '=' operator it does work as expected. When querying a large table this caused a constant 100% CPU usage.
The queries have been simplified to explain the issue at hand; when using explain we get the following outputs:
explain
        select * from TableA as A
                left join
                (
                    select
                        DATE_FORMAT(created_at,'%H:%i:00') as `time`
                    FROM
                        TableB
                    WHERE
                        created_at < DATE_ADD(CURDATE(), INTERVAL -3 HOUR)
                )
                as V ON V.time = A.time

Output
id  select_type table   partitions  type    possible_keys   key key_len ref rows    filtered    Extra
1   SIMPLE  A   NULL    ALL NULL    NULL    NULL    NULL    10080   100.00  NULL
1   SIMPLE  TableB  NULL    index   created_at  created_at  4   NULL    488389  100.00  Using where; Using index; Using join buffer (Block Nested Loop)

As you can see, it's querying/matching 488389 rows and not using the where clause since this is the total records in that table.
And now running the same query but with a LIMIT 99999999 command or using the '=' operator:
explain
        select * from TableA as A
                left join
                (
                    select
                        DATE_FORMAT(created_at,'%H:%i:00') as `time`
                    FROM
                        TableB
                    WHERE
                        created_at < DATE_ADD(CURDATE(), INTERVAL -3 HOUR) LIMIT 999999999
                )
                as V ON V.time = A.time

Output
id  select_type table   partitions  type    possible_keys   key key_len ref rows    filtered    Extra
1   PRIMARY A   NULL    ALL NULL    NULL    NULL    NULL    10080   100.00  NULL
1   PRIMARY <derived2>  NULL    ALL NULL    NULL    NULL    NULL    244194  100.00  Using where; Using join buffer (Block Nested Loop)
2   DERIVED TableB  NULL    range   created_at  created_at  4   NULL    244194  100.00  Using where; Using index

You can see it's suddenly only matching '244194' rows which is a part of the table, or with the '=' operator:
id  select_type table   partitions  type    possible_keys   key key_len ref rows    filtered    Extra
1   SIMPLE  A   NULL    ALL NULL    NULL    NULL    NULL    10080   100.00  NULL
1   SIMPLE  TableB  NULL    ref created_at  created_at  4   const   1   100.00  Using where; Using index

Just 1 row, as expected.
So the question now is, have we been querying in a wrong way and
   just now finding out while upgrading or have things changed since
   MySQL 5.6? It seems odd that the = operator works, but the <
   and > are ignored for some reason, unless when using a LIMIT?..
We've searched around and couldn't find the cause of this issue, and we'd rather not use the limit 9999999 solution in our code for obvious reasons.
Note When running just the query inside the join, it works as expected as well.
Note We've also ran the same test on MariaDB 10.1, same issue.

A: The explain row-output is merely a guess on how many rows it will hit. It is based upon statistical data, that has been resettet with your update. And if I had to guess how many rows of all your existing rows are older than yesterday 9pm, I would too guess its closer to "all rows" than to "just some rows". The reason why 'limit 99999999' is displaying another rowcount is the same: it just guesses the limit will have an effect; in this case, mysql guesses it will be exactly half of the rows (what would be, if true, a strange coincidence), and of course, it doesn't actually look at the limit-value, since 999999999 will not limit anything when you only have 500k rows; and even the "1" in case of "=" is just a guess (and might more often be 0 than 1, and maybe sometimes more).
This estimate will help choose the correct execution plan, and being wrong in this guess is just a problem if it would choose the wrong one; your execution plan looks fine though, and there are not many option to do it otherwise. It does exactly as expected: Scan the index for all dates using the index on created_at. Since you do a left join, you cannot skip values from tableA even if you would start with the inner query, so there is really no alternative execution plan available. (The optimizer actually have been changed in 5.7., but here is doesn't have an effect.)
If that is your actual query, there is no real reason why it should be slower than before (only regarding this query; there are of course a lot of general performance options that might have an indirect effect, like caching strategies, buffersizes, ..., but with standard options, it should not have an effect here).
If not, and you e.g. actually use additional columns from TableB in the subquery (it is often hard to guess which maybe important things have gotten "simplified away" in questions), and thus need access to the actual table, it might depends on how your data is structured (or better: in what order you added it). And you might try Optimize table TableB to make your table and indexes fresh and new, it can't hurt (but will lock your table for a little while).
With mysql 5.7., you now can add generated columns, so it might be worth a try to generate a cleaned up column time as DATE_FORMAT(created_at,'%H:%i:00'), so you don't have to calculate it anymore. And maybe add it to your index, so you don't have to sort it anymore to improve the block nested join, but that may depend on your actual query and how often you use it (spamming indexes increases overhead and uses space).

A: Use JOIN instead of LEFT JOIN unless you need the 'right' table to be optional.
Avoid JOIN ( SELECT ... ).  Although 5.6 and 5.7 added some features to handle it, it is usually better to turn the subquery into a simpler JOIN.
Your time expression leads to 9pm yesterday; did you mean "3 hours ago" instead?
See if this gives the desired results and runs faster:
select  A.*, DATE_FORMAT(B.created_at,'%H:%i:00') as `time`
    from  TableA as A
    JOIN  TableB as B  ON B.time = A.time
    WHERE  B.created_at < NOW() - INTERVAL 3 HOUR   -- (assuming "3 hours ago")

As for 5.6 vs 5.7...  5.7 has a new, 'better', optimizer, based on a "cost model".  However your particular query makes it virtually impossible for the optimizer to come up with good costs.  I guess that 5.6 happened on the better EXPLAIN, and 5.7 happened on a worse one.  By simplifying the query, I think both optimizers will have a better chance at performing the query faster.
You do need these indexes:
B:  INDEX(time, created_at) -- in that order
A:  INDEX(time)

A: In MySQL 5.7, derived tables (sub-queries in FROM clause) will be merged into the outer query if possible.  This is usually an advantage since one avoids that the result of the sub-query is stored in a temporary table.  However, for your query, MySQL 5.6 will create an index on this temporary table that could be used for the join execution.
The problem with the merged query is that the index on TableB.created_at can not be used when the column is a parameter to a function.  If you can change the query so that the transformation is made to the column on the left side of the join, an index can be used to access the table on the right side.  Something like:
   select * from TableA as A
            left join
            (
                select created_at as time
                FROM TableB
                WHERE created_at < DATE_ADD(CURDATE(), INTERVAL -3 HOUR)
            )
            as V ON V.time = func(A.time)

Alternatively, if you can use inner join instead of left join, MySQL can reverse the join order, so that the index on tableA.time can be used for the join.
If the subquery use LIMIT, it can not be merged.  Hence, by using LIMIT you will get the same query plan as was used in MySQL 5.6.


text:
Q: Maxsize of array I keep getting segfalut while trying to create a array, which size is 10000000.
unsigned char anal1[10000000];

do I have to malloc for such huge variables?

A: Option #1 - a local variable - the stack must be large enough to accommodate it:
void func(...)
{
    unsigned char anal1[10000000];
    ...
}

Option #2 - a static local variable - the data-section must be large enough to accommodate it:
void func(...)
{
    static unsigned char anal1[10000000];
    ...
}

Option #3 - a global variable - the data-section must be large enough to accommodate it:
unsigned char anal1[10000000];

Option #4 - a static global variable - the data-section must be large enough to accommodate it:
static unsigned char anal1[10000000];

Option #5 - if you allocate it during run-time, then the heap must be large enough to accommodate it:
unsigned char* anal1 = malloc(10000000);

Whichever option you choose, you will probably need to assert the corresponding requirement within your project settings (not sure what IDE you're using, so cannot tell you exactly how to configure that).


text:
Q: The difference between strategy and state design patterm, How a state is aware of its predecessor? I read about state and strategy design patterns in refactoring.guru web site in pages State and Strategy. The author says

This structure may look similar to the Strategy pattern, but there's one key difference. In the State pattern, the particular states may be aware of each other and initiate transitions from one state to another, whereas strategies almost never know about each other.

The author also says, the ConcereteState classes, store a variable context which is an object to Context class and by this variable, states may aware of each other.
There are two things I can't understand:

*

*How a state is aware of its predecessor?

*Where should I implement the logic of transition between states? For example state1 by input a moves to state2 and by b moves to state4, where exactly this logic must be implemented?

This is a simple implementation of strategy I implemented in php language
<?php
class Algorithms{
    public $algorithm;
    function __construct(AlgorithmsInterface $algorithm){
        $this->algorithm = $algorithm;
    }

    public function run(){
        $this->algorithm->run();
    }
}

interface AlgorithmsInterface{
    public function run();
}

class Algorithm1 implements AlgorithmsInterface{
    public function run(){
        print "Algorithm1";
    }
}

class Algorithm2 implements AlgorithmsInterface{
    public function run(){
        print "Algorithm2";
    }
}

$payment = new Algorithms(new Algorithm2());
$payment->run();

and this is a simple implementation of State design pattern I implemented
<?php
    interface State{
        public function execute();
    }

    class Context{

        public $state;

        public function __construct(State $initialState){
            $this->state = $initialState;
        }

        public function changeState(State $state){
            $this->state = $state;
        }

        public function execute(){
            $this->state->execute();
        }
    }

    class State1 implements State{
        public function execute(){
            print "This is State1";
        }
    }

    class State2 implements State{
        public function execute(){
            print "This is State2";
        }
    }

    $initialState = new State1();
    $state2 = new State2();
    $context = new Context($initialState);
    $context->execute();
    $context->changeState($state2);
    $context->execute();

?>

I can't see much difference between state and strategy while I know exactly what the intents of these strategies are. Besides that, the logic of movement between states and the way a state should be aware of its parent are missed from the code.

A: From your examples the two patterns look very similar. But your example of State design pattern is not really state design pattern, because you are setting the state from outside.
Typical state design pattern changes state internally and very often delegates the change to the state itself.
Let's look at simple toggle button. It has a state, and method to press it, and method to describe current state (toString()):
class ToggleButton {
    enum State {
        ON {
            public State press() {
                return OFF;
            }
         },
         OFF {
             public State press() {
                 return ON;
             }
         };
         abstract public State press();
    }

    State state = State.OFF;
    public void press() {
        state = state.press();
    }
    public String toString() {
        return "Device is " + state;
    }
}

So from outside you're not setting the state, so you don't know in which state it is and how it will react. You use:
button.press();
System.out.println(button);

So the key difference is, that for strategy, you pass the strategy from outside, and let your object perform some operation (which doesn't change the strategy), so it's sticky delegation.
But purpose of State design pattern is, that the state is supposed to change, very often intrrnally, and with change of the state also the behavior changes. So even if we set some state before computation of some task, it may change (typically does) internally during the task to complete it.
It's a way to achieve state polymorphism. Also notice, that it's often related to state automata.


text:
Q: Wireless is not working on my lenovo E4430 having ubuntu 12.04 LTS (Realtek 8723BE802.11n PCI wireless). There is no icon to enable wireless Initially wireless was working in my lenovo E4430 having Ubuntu 12.04 LTS. When I updated Ubuntu 12.04 in root, wireless stopped working. Now Realtek 8723BE 802.11n PCI wireless driver is not activated while earlier it was activated and was in use. I installed Ubuntu 12.04 LTS again and again but no use. I tried but could not find Realtek 8723BE 802.11n PCI wireless driver for Ubuntu 12.04 on the Internet. Please suggest me what should I do?

A: Yes, I know this problem at another Lenovo. The small radio-card under a cover at the backside was "dead". It was cheaper to use a Wifi-dongle on a USB-port than to buy a new Wifi-card. Ubuntu works fine with it.


text:
Q: Is there a ``Ladner's Theorem" for the PH-vs-PSPACE scenario? Like a statement of the kind, ``If the Polynomial Hierarchy (PH) $\neq$ PSPACE then there exists $L \in PSPACE \backslash PH$ which is not PSPACE-complete"?
Or is there something else that states that this is impossible?


text:
Q: Android ViewPager doesn't remove old views from screen I'm trying to add a pageviewer to my app that simply show some images that explaing how the app work but I'm encountering a lot of problem...
The first page it's correctly showed but when I drag to next pages all pages that I've just seen stay in background and it's cause weird visualization.
Here my code...
import android.app.Activity;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.ImageView;

public class ViewPagerActivity extends Activity {
private static int NUM_VIEWS = 5;

private MyPagerAdapter adapter;
private ViewPager pager;
private int[] pics = { R.drawable.bookmarks, R.drawable.bookmarks_click, R.drawable.help,
        R.drawable.help_click, R.drawable.logo_wil };

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_view_pager);

    adapter = new MyPagerAdapter();
    pager = (ViewPager) findViewById(R.id.mypager);
    pager.setAdapter(adapter);
}

private class MyPagerAdapter extends PagerAdapter {

    @Override
    public int getCount() {
        return NUM_VIEWS;
    }

    /**
     * Create the page for the given position. The adapter is responsible
     * for adding the view to the container given here, although it only
     * must ensure this is done by the time it returns from
     * {@link #finishUpdate()}.
     *
     * @param container
     *            The containing View in which the page will be shown.
     * @param position
     *            The page position to be instantiated.
     * @return Returns an Object representing the new page. This does not
     *         need to be a View, but can be some other container of the
     *         page.
     */
    @Override
    public Object instantiateItem(View collection, int position) {
        ImageView view = new ImageView(ViewPagerActivity.this);
        view.setImageResource(pics[position]);

        ((ViewPager) collection).addView(view, 0);

        return view;
    }

    /**
     * Remove a page for the given position. The adapter is responsible for
     * removing the view from its container, although it only must ensure
     * this is done by the time it returns from {@link #finishUpdate()}.
     *
     * @param container
     *            The containing View from which the page will be removed.
     * @param position
     *            The page position to be removed.
     * @param object
     *            The same object that was returned by
     *            {@link #instantiateItem(View, int)}.
     */

    @Override
    public void destroyItem(View collection, int position, Object view) {
        ((ViewPager) collection).removeView((ImageView) view);
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == ((ImageView) object);
    }

    /**
     * Called when the a change in the shown pages has been completed. At
     * this point you must ensure that all of the pages have actually been
     * added or removed from the container as appropriate.
     *
     * @param container
     *            The containing View which is displaying this adapter's
     *            page views.
     */
    @Override
    public void finishUpdate(View arg0) {
    }

    @Override
    public void restoreState(Parcelable arg0, ClassLoader arg1) {
    }

    @Override
    public Parcelable saveState() {
        return null;
    }

    @Override
    public void startUpdate(View arg0) {
    }

}

}