Programs & Examples On #Ecos

A small-footprint real-time operating system intended for use in embedded systems across multiple architectures.

Understanding esModuleInterop in tsconfig file

in your tsconfig you have to add: "esModuleInterop": true - it should help.

Specifying onClick event type with Typescript and React.Konva

As posted in my update above, a potential solution would be to use Declaration Merging as suggested by @Tyler-sebastion. I was able to define two additional interfaces and add the index property on the EventTarget in this way.

interface KonvaTextEventTarget extends EventTarget {
  index: number
}

interface KonvaMouseEvent extends React.MouseEvent<HTMLElement> {
  target: KonvaTextEventTarget
}

I then can declare the event as KonvaMouseEvent in my onclick MouseEventHandler function.

onClick={(event: KonvaMouseEvent) => {
          makeMove(ownMark, event.target.index)
}}

I'm still not 100% if this is the best approach as it feels a bit Kludgy and overly verbose just to get past the tslint error.

Download and save PDF file with Python requests module

In Python 3, I find pathlib is the easiest way to do this. Request's response.content marries up nicely with pathlib's write_bytes.

from pathlib import Path
import requests
filename = Path('metadata.pdf')
url = 'http://www.hrecos.org//images/Data/forweb/HRTVBSH.Metadata.pdf'
response = requests.get(url)
filename.write_bytes(response.content)

Xcode Project vs. Xcode Workspace - Differences

I think there are three key items you need to understand regarding project structure: Targets, projects, and workspaces. Targets specify in detail how a product/binary (i.e., an application or library) is built. They include build settings, such as compiler and linker flags, and they define which files (source code and resources) actually belong to a product. When you build/run, you always select one specific target.

It is likely that you have a few targets that share code and resources. These different targets can be slightly different versions of an app (iPad/iPhone, different brandings,…) or test cases that naturally need to access the same source files as the app. All these related targets can be grouped in a project. While the project contains the files from all its targets, each target picks its own subset of relevant files. The same goes for build settings: You can define default project-wide settings in the project, but if one of your targets needs different settings, you can always override them there:

Shared project settings that all targets inherit, unless they overwrite it

Shared project settings that all targets inherit, unless they override it

Concrete target settings: PSE iPhone overwrites the project’s Base SDK setting

Concrete target settings: PSE iPhone overrides the project’s Base SDK setting

In Xcode, you always open projects (or workspaces, but not targets), and all the targets it contains can be built/run, but there’s no way/definition of building a project, so every project needs at least one target in order to be more than just a collection of files and settings.

Select one of the project’s targets to run

Select one of the project’s targets to run

In a lot of cases, projects are all you need. If you have a dependency that you build from source, you can embed it as a subproject. Subprojects can be opened separately or within their super project.

demoLib is a subprojec

demoLib is a subproject

If you add one of the subproject’s targets to the super project’s dependencies, the subproject will be automatically built unless it has remained unchanged. The advantage here is that you can edit files from both your project and your dependencies in the same Xcode window, and when you build/run, you can select from the project’s and its subprojects’ targets:

Running targets from a subproject

If, however, your library (the subproject) is used by a variety of other projects (or their targets, to be precise), it makes sense to put it on the same hierarchy level – that’s what workspaces are for. Workspaces contain and manage projects, and all the projects it includes directly (i.e., not their subprojects) are on the same level and their targets can depend on each other (projects’ targets can depend on subprojects’ targets, but not vice versa).

Workspace structure

Workspace structure

In this example, both apps (AnotherApplication / ProjectStructureExample) can reference the demoLib project’s targets. This would also be possible by including the demoLib project in both other projects as a subproject (which is a reference only, so no duplication necessary), but if you have lots of cross-dependencies, workspaces make more sense. If you open a workspace, you can choose from all projects’ targets when building/running.

Running targets from a workspace

You can still open your project files separately, but it is likely their targets won’t build because Xcode cannot resolve the dependencies unless you open the workspace file. Workspaces give you the same benefit as subprojects: Once a dependency changes, Xcode will rebuild it to make sure it’s up-to-date (although I have had some issues with that, it doesn’t seem to work reliably).

Your questions in a nutshell:

1) Projects contain files (code/resouces), settings, and targets that build products from those files and settings. Workspaces contain projects which can reference each other.

2) Both are responsible for structuring your overall project, but on different levels.

3) I think projects are sufficient in most cases. Don’t use workspaces unless there’s a specific reason. Plus, you can always embed your project in a workspace later.

4) I think that’s what the above text is for…

There’s one remark for 3): CocoaPods, which automatically handles 3rd party libraries for you, uses workspaces. Therefore, you have to use them, too, when you use CocoaPods (which a lot of people do).

How to enter a formula into a cell using VBA?

I would do it like this:

Worksheets("EmployeeCosts").Range("B" & var1a).Formula = _
Replace("=SUM(H5:H{SOME_VAR})","{SOME_VAR}",var1a)

In case you have some more complex formula it will be handy

What is best way to start and stop hadoop ecosystem, with command line?

From Hadoop page,

start-all.sh 

This will startup a Namenode, Datanode, Jobtracker and a Tasktracker on your machine.

start-dfs.sh

This will bring up HDFS with the Namenode running on the machine you ran the command on. On such a machine you would need start-mapred.sh to separately start the job tracker

start-all.sh/stop-all.sh has to be run on the master node

You would use start-all.sh on a single node cluster (i.e. where you would have all the services on the same node.The namenode is also the datanode and is the master node).

In multi-node setup,

You will use start-all.sh on the master node and would start what is necessary on the slaves as well.

Alternatively,

Use start-dfs.sh on the node you want the Namenode to run on. This will bring up HDFS with the Namenode running on the machine you ran the command on and Datanodes on the machines listed in the slaves file.

Use start-mapred.sh on the machine you plan to run the Jobtracker on. This will bring up the Map/Reduce cluster with Jobtracker running on the machine you ran the command on and Tasktrackers running on machines listed in the slaves file.

hadoop-daemon.sh as stated by Tariq is used on each individual node. The master node will not start the services on the slaves.In a single node setup this will act same as start-all.sh.In a multi-node setup you will have to access each node (master as well as slaves) and execute on each of them.

Have a look at this start-all.sh it call config followed by dfs and mapred

How to rollback or commit a transaction in SQL Server

The good news is a transaction in SQL Server can span multiple batches (each exec is treated as a separate batch.)

You can wrap your EXEC statements in a BEGIN TRANSACTION and COMMIT but you'll need to go a step further and rollback if any errors occur.

Ideally you'd want something like this:

BEGIN TRY
    BEGIN TRANSACTION 
        exec( @sqlHeader)
        exec(@sqlTotals)
        exec(@sqlLine)
    COMMIT
END TRY
BEGIN CATCH

    IF @@TRANCOUNT > 0
        ROLLBACK
END CATCH

The BEGIN TRANSACTION and COMMIT I believe you are already familiar with. The BEGIN TRY and BEGIN CATCH blocks are basically there to catch and handle any errors that occur. If any of your EXEC statements raise an error, the code execution will jump to the CATCH block.

Your existing SQL building code should be outside the transaction (above) as you always want to keep your transactions as short as possible.

How to multiply a BigDecimal by an integer in Java

You have a lot of type-mismatches in your code such as trying to put an int value where BigDecimal is required. The corrected version of your code:

public class Payment
{
    BigDecimal itemCost  = BigDecimal.ZERO;
    BigDecimal totalCost = BigDecimal.ZERO;

    public BigDecimal calculateCost(int itemQuantity, BigDecimal itemPrice)
    {
        itemCost  = itemPrice.multiply(new BigDecimal(itemQuantity));
        totalCost = totalCost.add(itemCost);
        return totalCost;
    }
}

Dealing with "Xerces hell" in Java/Maven?

You should debug first, to help identify your level of XML hell. In my opinion, the first step is to add

-Djavax.xml.parsers.SAXParserFactory=com.sun.org.apache.xerces.internal.jaxp.SAXParserFactoryImpl
-Djavax.xml.transform.TransformerFactory=com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl
-Djavax.xml.parsers.DocumentBuilderFactory=com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl

to the command line. If that works, then start excluding libraries. If not, then add

-Djaxp.debug=1

to the command-line.

What is Node.js' Connect, Express and "middleware"?

[Update: As of its 4.0 release, Express no longer uses Connect. However, Express is still compatible with middleware written for Connect. My original answer is below.]

I'm glad you asked about this, because it's definitely a common point of confusion for folks looking at Node.js. Here's my best shot at explaining it:

  • Node.js itself offers an http module, whose createServer method returns an object that you can use to respond to HTTP requests. That object inherits the http.Server prototype.

  • Connect also offers a createServer method, which returns an object that inherits an extended version of http.Server. Connect's extensions are mainly there to make it easy to plug in middleware. That's why Connect describes itself as a "middleware framework," and is often analogized to Ruby's Rack.

  • Express does to Connect what Connect does to the http module: It offers a createServer method that extends Connect's Server prototype. So all of the functionality of Connect is there, plus view rendering and a handy DSL for describing routes. Ruby's Sinatra is a good analogy.

  • Then there are other frameworks that go even further and extend Express! Zappa, for instance, which integrates support for CoffeeScript, server-side jQuery, and testing.

Here's a concrete example of what's meant by "middleware": Out of the box, none of the above serves static files for you. But just throw in connect.static (a middleware that comes with Connect), configured to point to a directory, and your server will provide access to the files in that directory. Note that Express provides Connect's middlewares also; express.static is the same as connect.static. (Both were known as staticProvider until recently.)

My impression is that most "real" Node.js apps are being developed with Express these days; the features it adds are extremely useful, and all of the lower-level functionality is still there if you want it.

"java.lang.OutOfMemoryError: PermGen space" in Maven build

When I encountered this exception, I solved this by using Run Configurations... panel as picture shows below.Especially, at JRE tab, the VM Arguments are the critical
( "-Xmx1024m -Xms512m -XX:MaxPermSize=1024m -XX:PermSize=512m" ).

enter image description here

Kotlin Android start new Activity

another simple way of navigating to another activity is

Intent(this, CodeActivity::class.java).apply {
                    startActivity(this)
                }

How to append a newline to StringBuilder

You can also use the line separator character in String.format (See java.util.Formatter), which is also platform agnostic.

i.e.:

result.append(String.format("%n", ""));

If you need to add more line spaces, just use:

result.append(String.format("%n%n", ""));

You can also use StringFormat to format your entire string, with a newline(s) at the end.

result.append(String.format("%10s%n%n", "This is my string."));

change cursor to finger pointer

You can do this in CSS:

a.menu_links {
    cursor: pointer;
}

This is actually the default behavior for links. You must have either somehow overridden it elsewhere in your CSS, or there's no href attribute in there (it's missing from your example).

Boxplot show the value of mean

The Magrittr way

I know there is an accepted answer already, but I wanted to show one cool way to do it in single command with the help of magrittr package.

PlantGrowth %$% # open dataset and make colnames accessible with '$'
split(weight,group) %T>% # split by group and side-pipe it into boxplot
boxplot %>% # plot
lapply(mean) %>% # data from split can still be used thanks to side-pipe '%T>%'
unlist %T>% # convert to atomic and side-pipe it to points
points(pch=18)  %>% # add points for means to the boxplot
text(x=.+0.06,labels=.) # use the values to print text

This code will produce a boxplot with means printed as points and values: boxplot with means

I split the command on multiple lines so I can comment on what each part does, but it can also be entered as a oneliner. You can learn more about this in my gist.

Resource interpreted as Document but transferred with MIME type application/json warning in Chrome Developer Tools

I was facing the same error. The solution that worked for me is:

From the server end, while returning JSON response, change the content-type: text/html

Now the browsers (Chrome, Firefox and IE8) do not give an error.

What's a "static method" in C#?

Core of the static keyword that you will have only one copy at RAM of this (method /variable /class ) that's shared for all calling

How to check task status in Celery?

You can also create custom states and update it's value duting task execution. This example is from docs:

@app.task(bind=True)
def upload_files(self, filenames):
    for i, file in enumerate(filenames):
        if not self.request.called_directly:
            self.update_state(state='PROGRESS',
                meta={'current': i, 'total': len(filenames)})

http://celery.readthedocs.org/en/latest/userguide/tasks.html#custom-states

Find nearest latitude/longitude with an SQL query

Mysql query for search coordinates with distance limit and where condition

SELECT , ( 3959 acos( cos( radians('28.5850154') ) cos( radians(lat) ) cos( radians( lng ) - radians('77.07207489999999') ) + sin( radians('28.5850154') ) * sin( radians( lat ) ) ) ) AS distance FROM `Wo_Products` WHERE `active` = '1' HAVING distance < 5

Copying sets Java

With Java 8 you can use stream and collect to copy the items:

Set<Item> newSet = oldSet.stream().collect(Collectors.toSet());

Or you can collect to an ImmutableSet (if you know that the set should not change):

Set<Item> newSet = oldSet.stream().collect(ImmutableSet.toImmutableSet());

Objective-C : BOOL vs bool

The Objective-C type you should use is BOOL. There is nothing like a native boolean datatype, therefore to be sure that the code compiles on all compilers use BOOL. (It's defined in the Apple-Frameworks.

MySQL Creating tables with Foreign Keys giving errno: 150

I've found another reason this fails... case sensitive table names.

For this table definition

CREATE TABLE user (
  userId int PRIMARY KEY AUTO_INCREMENT,
  username varchar(30) NOT NULL
) ENGINE=InnoDB;

This table definition works

CREATE TABLE product (
  id int PRIMARY KEY AUTO_INCREMENT,
  userId int,
  FOREIGN KEY fkProductUser1(userId) REFERENCES **u**ser(userId)
) ENGINE=InnoDB;

whereas this one fails

CREATE TABLE product (
  id int PRIMARY KEY AUTO_INCREMENT,
  userId int,
  FOREIGN KEY fkProductUser1(userId) REFERENCES User(userId)
) ENGINE=InnoDB;

The fact that it worked on Windows and failed on Unix took me a couple of hours to figure out. Hope that helps someone else.

Java: notify() vs. notifyAll() all over again

Take a look at the code posted by @xagyg.

Suppose two different threads are waiting for two different conditions:
The first thread is waiting for buf.size() != MAX_SIZE, and the second thread is waiting for buf.size() != 0.

Suppose at some point buf.size() is not equal to 0. JVM calls notify() instead of notifyAll(), and the first thread is notified (not the second one).

The first thread is woken up, checks for buf.size() which might return MAX_SIZE, and goes back to waiting. The second thread is not woken up, continues to wait and does not call get().

How can I give the Intellij compiler more heap space?

In my case the error was caused by the insufficient memory allocated to the "test" lifecycle of maven. It was fixed by adding <argLine>-Xms3512m -Xmx3512m</argLine> to:

<pluginManagement>
  <plugins>
    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-plugin</artifactId>
        <version>2.16</version>
        <configuration>
            <argLine>-Xms3512m -Xmx3512m</argLine>

Thanks @crazycoder for pointing this out (and also that it is not related to IntelliJ; in this case).

If your tests are forked, they run in a new JVM that doesn't inherit Maven JVM options. Custom memory options must be provided via the test runner in pom.xml, refer to Maven documentation for details, it has very little to do with the IDE.

Passing variables to the next middleware using next() in Express.js

As mentioned above, res.locals is a good (recommended) way to do this. See here for a quick tutorial on how to do this in Express.

Error: unexpected symbol/input/string constant/numeric constant/SPECIAL in my code

These errors mean that the R code you are trying to run or source is not syntactically correct. That is, you have a typo.

To fix the problem, read the error message carefully. The code provided in the error message shows where R thinks that the problem is. Find that line in your original code, and look for the typo.


Prophylactic measures to prevent you getting the error again

The best way to avoid syntactic errors is to write stylish code. That way, when you mistype things, the problem will be easier to spot. There are many R style guides linked from the SO R tag info page. You can also use the formatR package to automatically format your code into something more readable. In RStudio, the keyboard shortcut CTRL + SHIFT + A will reformat your code.

Consider using an IDE or text editor that highlights matching parentheses and braces, and shows strings and numbers in different colours.


Common syntactic mistakes that generate these errors

Mismatched parentheses, braces or brackets

If you have nested parentheses, braces or brackets it is very easy to close them one too many or too few times.

{}}
## Error: unexpected '}' in "{}}"
{{}} # OK

Missing * when doing multiplication

This is a common mistake by mathematicians.

5x
Error: unexpected symbol in "5x"
5*x # OK

Not wrapping if, for, or return values in parentheses

This is a common mistake by MATLAB users. In R, if, for, return, etc., are functions, so you need to wrap their contents in parentheses.

if x > 0 {}
## Error: unexpected symbol in "if x"
if(x > 0) {} # OK

Not using multiple lines for code

Trying to write multiple expressions on a single line, without separating them by semicolons causes R to fail, as well as making your code harder to read.

x + 2 y * 3
## Error: unexpected symbol in "x + 2 y"
x + 2; y * 3 # OK

else starting on a new line

In an if-else statement, the keyword else must appear on the same line as the end of the if block.

if(TRUE) 1
else 2
## Error: unexpected 'else' in "else"    
if(TRUE) 1 else 2 # OK
if(TRUE) 
{
  1
} else            # also OK
{
  2
}

= instead of ==

= is used for assignment and giving values to function arguments. == tests two values for equality.

if(x = 0) {}
## Error: unexpected '=' in "if(x ="    
if(x == 0) {} # OK

Missing commas between arguments

When calling a function, each argument must be separated by a comma.

c(1 2)
## Error: unexpected numeric constant in "c(1 2"
c(1, 2) # OK

Not quoting file paths

File paths are just strings. They need to be wrapped in double or single quotes.

path.expand(~)
## Error: unexpected ')' in "path.expand(~)"
path.expand("~") # OK

Quotes inside strings

This is a common problem when trying to pass quoted values to the shell via system, or creating quoted xPath or sql queries.

Double quotes inside a double quoted string need to be escaped. Likewise, single quotes inside a single quoted string need to be escaped. Alternatively, you can use single quotes inside a double quoted string without escaping, and vice versa.

"x"y"
## Error: unexpected symbol in ""x"y"   
"x\"y" # OK
'x"y'  # OK  

Using curly quotes

So-called "smart" quotes are not so smart for R programming.

path.expand(“~”)
## Error: unexpected input in "path.expand(“"    
path.expand("~") # OK

Using non-standard variable names without backquotes

?make.names describes what constitutes a valid variable name. If you create a non-valid variable name (using assign, perhaps), then you need to access it with backquotes,

assign("x y", 0)
x y
## Error: unexpected symbol in "x y"
`x y` # OK

This also applies to column names in data frames created with check.names = FALSE.

dfr <- data.frame("x y" = 1:5, check.names = FALSE)
dfr$x y
## Error: unexpected symbol in "dfr$x y"
dfr[,"x y"] # OK
dfr$`x y`   # also OK

It also applies when passing operators and other special values to functions. For example, looking up help on %in%.

?%in%
## Error: unexpected SPECIAL in "?%in%"
?`%in%` # OK

Sourcing non-R code

The source function runs R code from a file. It will break if you try to use it to read in your data. Probably you want read.table.

source(textConnection("x y"))
## Error in source(textConnection("x y")) : 
##   textConnection("x y"):1:3: unexpected symbol
## 1: x y
##       ^

Corrupted RStudio desktop file

RStudio users have reported erroneous source errors due to a corrupted .rstudio-desktop file. These reports only occurred around March 2014, so it is possibly an issue with a specific version of the IDE. RStudio can be reset using the instructions on the support page.


Using expression without paste in mathematical plot annotations

When trying to create mathematical labels or titles in plots, the expression created must be a syntactically valid mathematical expression as described on the ?plotmath page. Otherwise the contents should be contained inside a call to paste.

plot(rnorm(10), ylab = expression(alpha ^ *)))
## Error: unexpected '*' in "plot(rnorm(10), ylab = expression(alpha ^ *"
plot(rnorm(10), ylab = expression(paste(alpha ^ phantom(0), "*"))) # OK

C++ performance vs. Java/C#

Whenever I talk managed vs. unmanaged performance, I like to point to the series Rico (and Raymond) did comparing C++ and C# versions of a Chinese/English dictionary. This google search will let you read for yourself, but I like Rico's summary.

So am I ashamed by my crushing defeat? Hardly. The managed code got a very good result for hardly any effort. To defeat the managed Raymond had to:

  • Write his own file I/O stuff
  • Write his own string class
  • Write his own allocator
  • Write his own international mapping

Of course he used available lower level libraries to do this, but that's still a lot of work. Can you call what's left an STL program? I don't think so, I think he kept the std::vector class which ultimately was never a problem and he kept the find function. Pretty much everything else is gone.

So, yup, you can definately beat the CLR. Raymond can make his program go even faster I think.

Interestingly, the time to parse the file as reported by both programs internal timers is about the same -- 30ms for each. The difference is in the overhead.

For me the bottom line is that it took 6 revisions for the unmanaged version to beat the managed version that was a simple port of the original unmanaged code. If you need every last bit of performance (and have the time and expertise to get it), you'll have to go unmanaged, but for me, I'll take the order of magnitude advantage I have on the first versions over the 33% I gain if I try 6 times.

What is the Swift equivalent of isEqualToString in Objective-C?

One important point is that Swift's == on strings might not be equivalent to Objective-C's -isEqualToString:. The peculiarity lies in differences in how strings are represented between Swift and Objective-C.

Just look on this example:

let composed = "Ö" // U+00D6 LATIN CAPITAL LETTER O WITH DIAERESIS
let decomposed = composed.decomposedStringWithCanonicalMapping // (U+004F LATIN CAPITAL LETTER O) + (U+0308 COMBINING DIAERESIS)

composed.utf16.count // 1
decomposed.utf16.count // 2

let composedNSString = composed as NSString
let decomposedNSString = decomposed as NSString

decomposed == composed // true, Strings are equal
decomposedNSString == composedNSString // false, NSStrings are not

NSString's are represented as a sequence of UTF–16 code units (roughly read as an array of UTF-16 (fixed-width) code units). Whereas Swift Strings are conceptually sequences of "Characters", where "Character" is something that abstracts extended grapheme cluster (read Character = any amount of Unicode code points, usually something that the user sees as a character and text input cursor jumps around).

The next thing to mention is Unicode. There is a lot to write about it, but here we are interested in something called "canonical equivalence". Using Unicode code points, visually the same "character" can be encoded in more than one way. For example, "Á" can be represented as a precomposed "Á" or as decomposed A + ?´ (that's why in example composed.utf16 and decomposed.utf16 had different lengths). A good thing to read on that is this great article.

-[NSString isEqualToString:], according to the documentation, compares NSStrings code unit by code unit, so:

[Á] != [A, ?´]

Swift's String == compares characters by canonical equivalence.

[ [Á] ] == [ [A, ?´] ]

In swift the above example will return true for Strings. That's why -[NSString isEqualToString:] is not equivalent to Swift's String ==. Equivalent pure Swift comparison could be done by comparing String's UTF-16 Views:

decomposed.utf16.elementsEqual(composed.utf16) // false, UTF-16 code units are not the same
decomposedNSString == composedNSString // false, UTF-16 code units are not the same
decomposedNSString.isEqual(to: composedNSString as String) // false, UTF-16 code units are not the same

Also, there is a difference between NSString == NSString and String == String in Swift. The NSString == will cause isEqual and UTF-16 code unit by code unit comparison, where as String == will use canonical equivalence:

decomposed == composed // true, Strings are equal
decomposed as NSString == composed as NSString // false, UTF-16 code units are not the same

And the whole example:

let composed = "Ö" // U+00D6 LATIN CAPITAL LETTER O WITH DIAERESIS
let decomposed = composed.decomposedStringWithCanonicalMapping // (U+004F LATIN CAPITAL LETTER O) + (U+0308 COMBINING DIAERESIS)

composed.utf16.count // 1
decomposed.utf16.count // 2

let composedNSString = composed as NSString
let decomposedNSString = decomposed as NSString

decomposed == composed // true, Strings are equal
decomposedNSString == composedNSString // false, NSStrings are not

decomposed.utf16.elementsEqual(composed.utf16) // false, UTF-16 code units are not the same
decomposedNSString == composedNSString // false, UTF-16 code units are not the same
decomposedNSString.isEqual(to: composedNSString as String) // false, UTF-16 code units are not the same

Best way to find os name and version in Unix/Linux platform

I prepared following commands to find concise information about a Linux system:

clear
echo "\n----------OS Information------------"
hostnamectl | grep "Static hostname:"
hostnamectl | tail -n 3
echo "\n----------Memory Information------------"
cat /proc/meminfo | grep MemTotal
echo "\n----------CPU Information------------"
echo -n "Number of core(s): "
cat /proc/cpuinfo | grep "processor" | wc -l
cat /proc/cpuinfo | grep "model name" | head -n 1
echo "\n----------Disk Information------------"
echo -n "Total Size: "
df -h --total | tail -n 1| awk '{print $2}'
echo -n "Used: "
df -h --total | tail -n 1| awk '{print $3}'
echo -n "Available: "
df -h --total | tail -n 1| awk '{print $4}'
echo "\n-------------------------------------\n"

Copy and paste in an sh file like info.sh and then run it using command sh info.sh

How do you change text to bold in Android?

You can use this for font

create a Class Name TypefaceTextView and extend the TextView

private static Map mTypefaces;

public TypefaceTextView(final Context context) {
    this(context, null);
}

public TypefaceTextView(final Context context, final AttributeSet attrs) {
    this(context, attrs, 0);
}

public TypefaceTextView(final Context context, final AttributeSet attrs, final int defStyle) {
    super(context, attrs, defStyle);
    if (mTypefaces == null) {
        mTypefaces = new HashMap<String, Typeface>();
    }

    if (this.isInEditMode()) {
        return;
    }

    final TypedArray array = context.obtainStyledAttributes(attrs, styleable.TypefaceTextView);
    if (array != null) {
        final String typefaceAssetPath = array.getString(
                R.styleable.TypefaceTextView_customTypeface);

        if (typefaceAssetPath != null) {
            Typeface typeface = null;

            if (mTypefaces.containsKey(typefaceAssetPath)) {
                typeface = mTypefaces.get(typefaceAssetPath);
            } else {
                AssetManager assets = context.getAssets();
                typeface = Typeface.createFromAsset(assets, typefaceAssetPath);
                mTypefaces.put(typefaceAssetPath, typeface);
            }

            setTypeface(typeface);
        }
        array.recycle();
    }
}

paste the font in the fonts folder created in the asset folder

<packagename.TypefaceTextView
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1.5"
        android:gravity="center"
        android:text="TRENDING TURFS"
        android:textColor="#000"
        android:textSize="20sp"
        app:customTypeface="fonts/pompiere.ttf" />**here pompiere.ttf is the font name**

Place the lines in the parent layout in the xml

 xmlns:app="http://schemas.android.com/apk/res/com.mediasters.wheresmyturf"
xmlns:custom="http://schemas.android.com/apk/res-auto"

How to include vars file in a vars file with ansible?

You can put your servers in the default_step group and those vars will apply to it:

# inventory file
[default_step]
prod2
web_v2

Then just move your default_step.yml file to group_vars/default_step.yml.

How do you run a .bat file from PHP?

on my windows machine 8 machine running IIS 8 I can run the batch file just by putting the bats name and forgettig the path to it. Or by putting the bat in c:\windows\system32 don't ask me how it works but it does. LOL

$test=shell_exec("C:\windows\system32\cmd.exe /c $streamnumX.bat");

Populate nested array in mongoose

That works for me:

 Project.find(query)
  .lean()
  .populate({ path: 'pages' })
  .exec(function(err, docs) {

    var options = {
      path: 'pages.components',
      model: 'Component'
    };

    if (err) return res.json(500);
    Project.populate(docs, options, function (err, projects) {
      res.json(projects);
    });
  });

Documentation: Model.populate

Pass props in Link react-router

See this post for reference

The simple is that:

<Link to={{
     pathname: `your/location`,
     state: {send anything from here}
}}

Now you want to access it:

this.props.location.state

How do I change a single value in a data.frame?

Suppose your dataframe is df and you want to change gender from 2 to 1 in participant id 5 then you should determine the row by writing "==" as you can see

 df["rowName", "columnName"] <- value
 df[df$serial.id==5, "gender"] <- 1

Routing HTTP Error 404.0 0x80070002

Having this in Global.asax.cs solved it for me.

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();
    RouteConfig.RegisterRoutes(RouteTable.Routes);
}

Basic Apache commands for a local Windows machine

For frequent uses of this command I found it easy to add the location of C:\xampp\apache\bin to the PATH. Use whatever directory you have this installed in.

Then you can run from any directory in command line:

httpd -k restart

The answer above that suggests httpd -k -restart is actually a typo. You can see the commands by running httpd /?

SQL Statement with multiple SETs and WHEREs

No, you would need to create a seperate query for each update.

Setting format and value in input type="date"

It's ugly, but it works. :/

var today = new Date().toLocaleString('en-GB').split(' ')[0].split('/').reverse().join('-');

Counting unique / distinct values by group in a data frame

This is a simple solution with the function aggregate:

aggregate(order_no ~ name, myvec, function(x) length(unique(x)))

Using event.target with React components

First argument in update method is SyntheticEvent object that contains common properties and methods to any event, it is not reference to React component where there is property props.

if you need pass argument to update method you can do it like this

onClick={ (e) => this.props.onClick(e, 'home', 'Home') }

and get these arguments inside update method

update(e, space, txt){
   console.log(e.target, space, txt);
}

Example


event.target gives you the native DOMNode, then you need to use the regular DOM APIs to access attributes. For instance getAttribute or dataset

<button 
  data-space="home" 
  className="home" 
  data-txt="Home" 
  onClick={ this.props.onClick } 
/> 
  Button
</button>

onClick(e) {
   console.log(e.target.dataset.txt, e.target.dataset.space);
}

Example

How to append elements into a dictionary in Swift?

Given two dictionaries as below:

var dic1 = ["a": 1, "c": 2]
var dic2 = ["e": 3, "f": 4]

Here is how you can add all the items from dic2 to dic1:

dic2.forEach {
   dic1[$0.key] = $0.value
}

Best way to use Google's hosted jQuery, but fall back to my hosted library on Google fail

Conditionally load latest/legacy jQuery version and fallback:

<!--[if lt IE 9]>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
    <script>window.jQuery || document.write('<script src="/public/vendor/jquery-legacy/dist/jquery.min.js">\x3C/script>')</script>
<![endif]-->
<!--[if gte IE 9]><!-->
    <script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
    <script>window.jQuery || document.write('<script src="/public/vendor/jquery/dist/jquery.min.js">\x3C/script>')</script>
<!--<![endif]-->

How to do a simple file search in cmd

dir *.txt /s /p will give more detailed information.

SQL Server: How to use UNION with two queries that BOTH have a WHERE clause?

select * from 
(
    select top 2 t1.ID, t1.ReceivedDate
    from Table t1
    where t1.Type = 'TYPE_1'
    order by t1.ReceivedDate de
) t1
union
select * from 
(
    select top 2 t2.ID
    from Table t2
    where t2.Type = 'TYPE_2'
    order by t2.ReceivedDate desc
) t2

or using CTE (SQL Server 2005+)

;with One as
(
    select top 2 t1.ID, t1.ReceivedDate
    from Table t1
    where t1.Type = 'TYPE_1'
    order by t1.ReceivedDate de
)
,Two as
(
    select top 2 t2.ID
    from Table t2
    where t2.Type = 'TYPE_2'
    order by t2.ReceivedDate desc
)
select * from One
union
select * from Two

How to convert DateTime? to DateTime

Consider using the following which its far better than the accepted answer

DateTime UpdatedTime = _objHotelPackageOrder.UpdatedDate == null 
    ? DateTime.Now : (DateTime)_objHotelPackageOrder.UpdatedDate;

Creating an empty bitmap and drawing though canvas in Android

This is probably simpler than you're thinking:

int w = WIDTH_PX, h = HEIGHT_PX;

Bitmap.Config conf = Bitmap.Config.ARGB_8888; // see other conf types
Bitmap bmp = Bitmap.createBitmap(w, h, conf); // this creates a MUTABLE bitmap
Canvas canvas = new Canvas(bmp);

// ready to draw on that bitmap through that canvas

Here's a series of tutorials I've found on the topic: Drawing with Canvas Series

Copy files to network computers on windows command line

check Robocopy:

ROBOCOPY \\server-source\c$\VMExports\ C:\VMExports\ /E /COPY:DAT

make sure you check what robocopy parameter you want. this is just an example. type robocopy /? in a comandline/powershell on your windows system.

Get css top value as number not as string?

You can use the parseInt() function to convert the string to a number, e.g:

parseInt($('#elem').css('top'));

Update: (as suggested by Ben): You should give the radix too:

parseInt($('#elem').css('top'), 10);

Forces it to be parsed as a decimal number, otherwise strings beginning with '0' might be parsed as an octal number (might depend on the browser used).

How to remove all debug logging calls before building the release version of an Android app?

You can try use this simple conventional method:

Ctrl+Shift+R

replace

Log.e(

With

// Log.e(

Sorted collection in Java

You want the SortedSet implementations, namely TreeSet.

How to align center the text in html table row?

The following worked for me to vertically align content (multi-line) in a list-table

.. list-table::
   :class: longtable
   :header-rows: 1
   :stub-columns: 1
   :align: left
   :widths: 20, 20, 20, 20, 20

   * - Classification
     - Restricted
     - Company |br| Confidential
     - Internal Use Only
     - Public
   * - Row1 col1
     - Row1 col2
     - Row1 col3 
     - Row1 col4
     - Row1 col5

Using theme overrides .css option I defined:

.stub {
       text-align: left;
       vertical-align: top;
}

In the theme that I use 'python-docs-theme', the cell entry is defined as 'stub' class. Use your browser development menu to inspect what your theme class is for cell content and update that accordingly.

cast class into another class or convert class to another

I tried to use the Cast Extension (see https://stackoverflow.com/users/247402/stacker) in a situation where the Target Type contains a Property that is not present in the Source Type. It did not work, I'm not sure why. I refactored to the following extension that did work for my situation:

public static T Casting<T>(this Object source)
{
    Type sourceType = source.GetType();
    Type targetType = typeof(T);
    var target =  Activator.CreateInstance(targetType, false);
    var sourceMembers = sourceType.GetMembers()
        .Where(x => x.MemberType  == MemberTypes.Property)
        .ToList();
    var targetMembers = targetType.GetMembers()
        .Where(x => x.MemberType == MemberTypes.Property)
        .ToList();
    var members = targetMembers
        .Where(x => sourceMembers
            .Select(y => y.Name)
                .Contains(x.Name));
    PropertyInfo propertyInfo;
    object value;
    foreach (var memberInfo in members)
    {
        propertyInfo = typeof(T).GetProperty(memberInfo.Name);
        value = source.GetType().GetProperty(memberInfo.Name).GetValue(source, null);
        propertyInfo.SetValue(target, value, null);
    }
    return (T)target;
}

Note that I changed the name of the extension as the Name Cast conflicts with results from Linq. Hat tip https://stackoverflow.com/users/2093880/usefulbee

Htaccess: add/remove trailing slash from URL

Right below the RewriteEngine On line, add:

RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ /$1 [L,R] # <- for test, for prod use [L,R=301]

to enforce a no-trailing-slash policy.

To enforce a trailing-slash policy:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*[^/])$ /$1/ [L,R] # <- for test, for prod use [L,R=301]

EDIT: commented the R=301 parts because, as explained in a comment:

Be careful with that R=301! Having it there makes many browsers cache the .htaccess-file indefinitely: It somehow becomes irreversible if you can't clear the browser-cache on all machines that opened it. When testing, better go with simple R or R=302

After you've completed your tests, you can use R=301.

Create a date time with month and day only, no year

Well, you can create your own type - but a DateTime always has a full date and time. You can't even have "just a date" using DateTime - the closest you can come is to have a DateTime at midnight.

You could always ignore the year though - or take the current year:

// Consider whether you want DateTime.UtcNow.Year instead
DateTime value = new DateTime(DateTime.Now.Year, month, day);

To create your own type, you could always just embed a DateTime within a struct, and proxy on calls like AddDays etc:

public struct MonthDay : IEquatable<MonthDay>
{
    private readonly DateTime dateTime;

    public MonthDay(int month, int day)
    {
        dateTime = new DateTime(2000, month, day);
    }

    public MonthDay AddDays(int days)
    {
        DateTime added = dateTime.AddDays(days);
        return new MonthDay(added.Month, added.Day);
    }

    // TODO: Implement interfaces, equality etc
}

Note that the year you choose affects the behaviour of the type - should Feb 29th be a valid month/day value or not? It depends on the year...

Personally I don't think I would create a type for this - instead I'd have a method to return "the next time the program should be run".

What is the difference between hg forget and hg remove?

'hg forget' is just shorthand for 'hg remove -Af'. From the 'hg remove' help:

...and -Af can be used to remove files from the next revision without deleting them from the working directory.

Bottom line: 'remove' deletes the file from your working copy on disk (unless you uses -Af) and 'forget' doesn't.

How do I use the includes method in lodash to check if an object is in the collection?

The includes (formerly called contains and include) method compares objects by reference (or more precisely, with ===). Because the two object literals of {"b": 2} in your example represent different instances, they are not equal. Notice:

({"b": 2} === {"b": 2})
> false

However, this will work because there is only one instance of {"b": 2}:

var a = {"a": 1}, b = {"b": 2};
_.includes([a, b], b);
> true

On the other hand, the where(deprecated in v4) and find methods compare objects by their properties, so they don't require reference equality. As an alternative to includes, you might want to try some (also aliased as any):

_.some([{"a": 1}, {"b": 2}], {"b": 2})
> true

Getting session value in javascript

protected void Page_Load(object sender, EventArgs e)
    {
        Session["MyTest"] = "abcd";

        String csname = "OnSubmitScript";
        Type cstype = this.GetType();

        // Get a ClientScriptManager reference from the Page class.
        ClientScriptManager cs = Page.ClientScript;

        // Check to see if the OnSubmit statement is already registered.
        if (!cs.IsOnSubmitStatementRegistered(cstype, csname))
        {
            string cstext = " document.getElementById(\"TextBox1\").value = getMyvalSession()  ; ";
            cs.RegisterOnSubmitStatement(cstype, csname, cstext);
        }

        if (TextBox1.Text.Equals("")) { }
        else {
              Session["MyTest"] = TextBox1.Text;
        }

    }


<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">

    <script language=javascript type="text/javascript">
        function getMyvalSession() {

             var txt = "efgh";
             var ff = '<%=Session["MyTest"] %>' + txt;
             return ff ;
        }
    </script>

</head>
<body>

    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="TextBox1" runat="server"  AutoPostBack=true ></asp:TextBox>
     <input type="submit"  value="Submit" />
    </div>
    </form>
</body>
</html>

Room persistance library. Delete all

If want to delete an entry from the the table in Room simply call this function,

@Dao
public interface myDao{
    @Delete
    void delete(MyModel model);
}

Update: And if you want to delete complete table, call below function,

  @Query("DELETE FROM MyModel")
  void delete();

Note: Here MyModel is a Table Name.

XAMPP installation on Win 8.1 with UAC Warning

There are two things you need to check:

  1. Ensure that your user account has administrator privilege.
  2. Disable UAC (User Account Control) as it restricts certain administrative function needed to run a web server.

To ensure that your user account has administrator privilege, run lusrmgr.msc from the Windows Start > Run menu to bring up the Local Users and Groups Windows. Double-click on your user account that appears under Users, and verifies that it is a member of Administrators.

To disable UAC (as an administrator), from Control Panel:

  1. Type UAC in the search field in the upper right corner.
  2. Click Change User Account Control settings in the search results.
  3. Drag the slider down to Never notifyand click OK.

open up the User Accounts window from Control Panel. Click on the Turn User Account Control on or off option, and un-check the checkbox.

Alternately, if you don't want to disable UAC, you will have to install XAMPP in a different folder, outside of C:\Program Files (x86), such as C:\xampp.

Hope this helps.

WebSockets vs. Server-Sent events/EventSource

One thing to note:
I have had issues with websockets and corporate firewalls. (Using HTTPS helps but not always.)

See https://github.com/LearnBoost/socket.io/wiki/Socket.IO-and-firewall-software https://github.com/sockjs/sockjs-client/issues/94

I assume there aren't as many issues with Server-Sent Events. But I don't know.

That said, WebSockets are tons of fun. I have a little web game that uses websockets (via Socket.IO) (http://minibman.com)

Conversion failed when converting from a character string to uniqueidentifier - Two GUIDs

You have to check unique identifier column and you have to give a diff value to that particular field if you give the same value it will not work. It enforces uniqueness of the key.

Here is the code:

Insert into production.product 
(Name,ProductNumber,MakeFlag,FinishedGoodsFlag,Color,SafetyStockLevel,ReorderPoint,StandardCost,ListPrice,Size
,SizeUnitMeasureCode,WeightUnitMeasureCode,Weight,DaysToManufacture,
    ProductLine, 
    Class, 
    Style ,
    ProductSubcategoryID 
    ,ProductModelID 
    ,SellStartDate 
,SellEndDate 
    ,DiscontinuedDate 
    ,rowguid
    ,ModifiedDate 
  )
  values ('LL lemon' ,'BC-1234',0,0,'blue',400,960,0.00,100.00,Null,Null,Null,null,1,null,null,null,null,null,'1998-06-01 00:00:00.000',null,null,'C4244F0C-ABCE-451B-A895-83C0E6D1F468','2004-03-11 10:01:36.827')

The application has stopped unexpectedly: How to Debug?

If you use the Logcat display inside the 'debug' perspective in Eclipse the lines are colour-coded. It's pretty easy to find what made your app crash because it's usually in red.

The Java (or Dalvik) virtual machine should never crash, but if your program throws an exception and does not catch it the VM will terminate your program, which is the 'crash' you are seeing.

How do you round UP a number in Python?

I am surprised nobody suggested

(numerator + denominator - 1) // denominator

for integer division with rounding up. Used to be the common way for C/C++/CUDA (cf. divup)

Python: fastest way to create a list of n lists

The list comprehensions actually are implemented more efficiently than explicit looping (see the dis output for example functions) and the map way has to invoke an ophaque callable object on every iteration, which incurs considerable overhead overhead.

Regardless, [[] for _dummy in xrange(n)] is the right way to do it and none of the tiny (if existent at all) speed differences between various other ways should matter. Unless of course you spend most of your time doing this - but in that case, you should work on your algorithms instead. How often do you create these lists?

Could not install packages due to an EnvironmentError: [Errno 13]

I was making the same mistakes then I realized that I have created my virtual environment as root user. It was write protected, so please check whether your virtual environment is write protected. make a new venv and try again

How do I update a Tomcat webapp without restarting the entire service?

In conf directory of apache tomcat you can find context.xml file. In that edit tag as <Context reloadable="true">. this should solve the issue and you need not restart the server

Assign output of a program to a variable using a MS batch file

I wrote the script that pings google.com every 5 seconds and logging results with current time. Here you can find output to variables "commandLineStr" (with indices)

@echo off

:LOOPSTART

echo %DATE:~0% %TIME:~0,8% >> Pingtest.log

SETLOCAL ENABLEDELAYEDEXPANSION
SET scriptCount=1
FOR /F "tokens=* USEBACKQ" %%F IN (`ping google.com -n 1`) DO (
  SET commandLineStr!scriptCount!=%%F
  SET /a scriptCount=!scriptCount!+1
)
@ECHO %commandLineStr1% >> PingTest.log
@ECHO %commandLineStr2% >> PingTest.log
ENDLOCAL

timeout 5 > nul

GOTO LOOPSTART

Inserting a tab character into text using C#

When using literal strings (start with @") this might be easier

char tab = '\u0009';
string A = "Apple";
string B = "Bob";
string myStr = String.Format(@"{0}:{1}{2}", A, tab, B);

Would result in Apple:<tab>Bob

How to install mechanize for Python 2.7?

sudo pip-2.7 install mechanize

How to create a WPF Window without a border that can be resized via a grip only?

I was having difficulty getting the answer by @fernando-aguirre using WindowChrome to work. It was not working in my case because I was overriding OnSourceInitialized in the MainWindow and not calling the base class method.

protected override void OnSourceInitialized(EventArgs e)
{
    ViewModel.Initialize(this);
    base.OnSourceInitialized(e); // <== Need to call this!
}

This stumped me for a very long time.

How to check all checkboxes using jQuery?

You Can use below Simple Code:

function checkDelBoxes(pForm, boxName, parent)
{
    for (i = 0; i < pForm.elements.length; i++)
        if (pForm.elements[i].name == boxName)
            pForm.elements[i].checked = parent;
}

Example for Using:

<a href="javascript:;" onclick="javascript:checkDelBoxes($(this).closest('form').get(0), 'CheckBox[]', true);return false;"> Select All
</a>
<a href="javascript:;" onclick="javascript:checkDelBoxes($(this).closest('form').get(0), 'CheckBox[]', false);return false;"> Unselect All
</a>

How do I prompt a user for confirmation in bash script?

This way you get 'y' 'yes' or 'Enter'

 read -r -p "Are you sure? [Y/n]" response
 response=${response,,} # tolower
 if [[ $response =~ ^(yes|y| ) ]] || [[ -z $response ]]; then
    your-action-here
 fi

If you are using zsh try this:

read "response?Are you sure ? [Y/n] "
response=${response:l} #tolower
if [[ $response =~ ^(yes|y| ) ]] || [[ -z $response ]]; then
    your-action-here
fi

json_encode function: special characters

To me, it works this way:

# Creating the ARRAY from Result.
$array=array();

while($row = $result->fetch_array(MYSQL_ASSOC))
{
    # Converting each column to UTF8
    $row = array_map('utf8_encode', $row);
    array_push($array,$row);
}

json_encode($array);

Image change every 30 seconds - loop

setInterval function is the one that has to be used. Here is an example for the same without any fancy fading option. Simple Javascript that does an image change every 30 seconds. I have assumed that the images were kept in a separate images folder and hence _images/ is present at the beginning of every image. You can have your own path as required to be set.

CODE:

var im = document.getElementById("img");

var images = ["_images/image1.jpg","_images/image2.jpg","_images/image3.jpg"];
var index=0;

function changeImage()
{
  im.setAttribute("src", images[index]);
  index++;
  if(index >= images.length)
  {
    index=0;
  }
}

setInterval(changeImage, 30000);

How to do SVN Update on my project using the command line

I think I got it. It's:

"SVN Client Path"  /command:update / path:"My folder path"

Excel: last character/string match in a string

A simple way to do that in VBA is:

YourText = "c:\excel\text.txt"
xString = Mid(YourText, 2 + Len(YourText) - InStr(StrReverse(YourText), "\" ))

Add vertical scroll bar to panel

Try this instead for 'only' scrolling vertical.
(auto scroll needs to be false before it will accept changes)

mypanel.AutoScroll = false;
mypanel.HorizontalScroll.Enabled = false;
mypanel.HorizontalScroll.Visible = false;
mypanel.HorizontalScroll.Maximum = 0;
mypanel.AutoScroll = true;

How to style a clicked button in CSS

button:hover is just when you move the cursor over the button.
Try button:active instead...will work for other elements as well

_x000D_
_x000D_
button:active{_x000D_
  color: red;_x000D_
}
_x000D_
_x000D_
_x000D_

PHP/MySQL: How to create a comment section in your website

You can create a 'comment' table, with an id as primary key, then you add a text field to capture the text inserted by the user and you need another field to link the comment table to the article table (foreign key). Plus you need a field to store the user that has entered a comment, this field can be the user's email. Then you capture via GET or POST the user's email and comment and you insert everything in the DB:

"INSERT INTO comment (comment, email, approved) VALUES ('$comment', '$email', '$approved')"

This is a first hint. Of course adding a comment feature it takes a little bit. Then you should think about a form to let the admin to approve the comments and how to publish the comments in the end of articles.

Reference - What does this regex mean?

The Stack Overflow Regular Expressions FAQ

See also a lot of general hints and useful links at the tag details page.


Online tutorials

Quantifiers

Character Classes

Escape Sequences

Anchors

(Also see "Flavor-Specific Information ? Java ? The functions in Matcher")

Groups

Lookarounds

Modifiers

Other:

Common Tasks

Advanced Regex-Fu

Flavor-Specific Information

(Except for those marked with *, this section contains non-Stack Overflow links.)

General information

(Links marked with * are non-Stack Overflow links.)

Examples of regex that can cause regex engine to fail

Tools: Testers and Explainers

(This section contains non-Stack Overflow links.)

Create a Dropdown List for MVC3 using Entity Framework (.edmx Model) & Razor Views && Insert A Database Record to Multiple Tables

Well, actually I'll have to say David is right with his solution, but there are some topics disturbing me:

  1. You should never send your model to the view => This is correct
  2. If you create a ViewModel, and include the Model as member in the ViewModel, then you effectively sent your model to the View => this is BAD
  3. Using dictionaries to send the options to the view => this not good style

So how can you create a better coupling?

I would use a tool like AutoMapper or ValueInjecter to map between ViewModel and Model. AutoMapper does seem to have the better syntax and feel to it, but the current version lacks a very severe topic: It is not able to perform the mapping from ViewModel to Model (under certain circumstances like flattening, etc., but this is off topic) So at present I prefer to use ValueInjecter.

So you create a ViewModel with the fields you need in the view. You add the SelectList items you need as lookups. And you add them as SelectLists already. So you can query from a LINQ enabled sourc, select the ID and text field and store it as a selectlist: You gain that you do not have to create a new type (dictionary) as lookup and you just move the new SelectList from the view to the controller.

  // StaffTypes is an IEnumerable<StaffType> from dbContext
  // viewModel is the viewModel initialized to copy content of Model Employee  
  // viewModel.StaffTypes is of type SelectList

  viewModel.StaffTypes =
    new SelectList(
        StaffTypes.OrderBy( item => item.Name )
        "StaffTypeID",
        "Type",
        viewModel.StaffTypeID
    );

In the view you just have to call

@Html.DropDownListFor( model => mode.StaffTypeID, model.StaffTypes )

Back in the post element of your method in the controller you have to take a parameter of the type of your ViewModel. You then check for validation. If the validation fails, you have to remember to re-populate the viewModel.StaffTypes SelectList, because this item will be null on entering the post function. So I tend to have those population things separated into a function. You just call back return new View(viewModel) if anything is wrong. Validation errors found by MVC3 will automatically be shown in the view.

If you have your own validation code you can add validation errors by specifying which field they belong to. Check documentation on ModelState to get info on that.

If the viewModel is valid you have to perform the next step:

If it is a create of a new item, you have to populate a model from the viewModel (best suited is ValueInjecter). Then you can add it to the EF collection of that type and commit changes.

If you have an update, you get the current db item first into a model. Then you can copy the values from the viewModel back to the model (again using ValueInjecter gets you do that very quick). After that you can SaveChanges and are done.

Feel free to ask if anything is unclear.

Python : How to parse the Body from a raw email , given that raw email does not have a "Body" tag or anything

If emails is the pandas dataframe and emails.message the column for email text

## Helper functions
def get_text_from_email(msg):
    '''To get the content from email objects'''
    parts = []
    for part in msg.walk():
        if part.get_content_type() == 'text/plain':
            parts.append( part.get_payload() )
    return ''.join(parts)

def split_email_addresses(line):
    '''To separate multiple email addresses'''
    if line:
        addrs = line.split(',')
        addrs = frozenset(map(lambda x: x.strip(), addrs))
    else:
        addrs = None
    return addrs 

import email
# Parse the emails into a list email objects
messages = list(map(email.message_from_string, emails['message']))
emails.drop('message', axis=1, inplace=True)
# Get fields from parsed email objects
keys = messages[0].keys()
for key in keys:
    emails[key] = [doc[key] for doc in messages]
# Parse content from emails
emails['content'] = list(map(get_text_from_email, messages))
# Split multiple email addresses
emails['From'] = emails['From'].map(split_email_addresses)
emails['To'] = emails['To'].map(split_email_addresses)

# Extract the root of 'file' as 'user'
emails['user'] = emails['file'].map(lambda x:x.split('/')[0])
del messages

emails.head()

convert string to date in sql server

I think style no. 111 (Japan) should work:

SELECT CONVERT(DATETIME, '2012-08-17', 111)

And if that doesn't work for some reason - you could always just strip out the dashes and then you have the totally reliable ISO-8601 format (YYYYMMDD) which works for any language and date format setting in SQL Server:

SELECT CAST(REPLACE('2012-08-17', '-', '') AS DATETIME)

installing python packages without internet and using source code as .tar.gz and .whl

We have a similar situation at work, where the production machines have no access to the Internet; therefore everything has to be managed offline and off-host.

Here is what I tried with varied amounts of success:

  1. basket which is a small utility that you run on your internet-connected host. Instead of trying to install a package, it will instead download it, and everything else it requires to be installed into a directory. You then move this directory onto your target machine. Pros: very easy and simple to use, no server headaches; no ports to configure. Cons: there aren't any real showstoppers, but the biggest one is that it doesn't respect any version pinning you may have; it will always download the latest version of a package.

  2. Run a local pypi server. Used pypiserver and devpi. pypiserver is super simple to install and setup; devpi takes a bit more finagling. They both do the same thing - act as a proxy/cache for the real pypi and as a local pypi server for any home-grown packages. localshop is a new one that wasn't around when I was looking, it also has the same idea. So how it works is your internet-restricted machine will connect to these servers, they are then connected to the Internet so that they can cache and proxy the actual repository.

The problem with the second approach is that although you get maximum compatibility and access to the entire repository of Python packages, you still need to make sure any/all dependencies are installed on your target machines (for example, any headers for database drivers and a build toolchain). Further, these solutions do not cater for non-pypi repositories (for example, packages that are hosted on github).

We got very far with the second option though, so I would definitely recommend it.

Eventually, getting tired of having to deal with compatibility issues and libraries, we migrated the entire circus of servers to commercially supported docker containers.

This means that we ship everything pre-configured, nothing actually needs to be installed on the production machines and it has been the most headache-free solution for us.

We replaced the pypi repositories with a local docker image server.

Logcat not displaying my log calls

I've noticed that Eclipse will sometimes throw an exception upon starting an Android app, then LogCat stops updating. I've corrected that by simply restarting Eclipse. I'm not sure if you've tried that and I know it's far from an optimal solution, but I suspect that the Eclipse plugin still has a few bugs to iron out.

Is there a way to access an iteration-counter in Java's for-each loop?

I'm afraid this isn't possible with foreach. But I can suggest you a simple old-styled for-loops:

    List<String> l = new ArrayList<String>();

    l.add("a");
    l.add("b");
    l.add("c");
    l.add("d");

    // the array
    String[] array = new String[l.size()];

    for(ListIterator<String> it =l.listIterator(); it.hasNext() ;)
    {
        array[it.nextIndex()] = it.next();
    }

Notice that, the List interface gives you access to it.nextIndex().

(edit)

To your changed example:

    for(ListIterator<String> it =l.listIterator(); it.hasNext() ;)
    {
        int i = it.nextIndex();
        doSomethingWith(it.next(), i);
    }

How to get the entire document HTML as a string?

I tried the various answers to see what is returned. I'm using the latest version of Chrome.

The suggestion document.documentElement.innerHTML; returned <head> ... </body>

Gaby's suggestion document.getElementsByTagName('html')[0].innerHTML; returned the same.

The suggestion document.documentElement.outerHTML; returned <html><head> ... </body></html> which is everything apart from the 'doctype'.

You can retrieve the doctype object with document.doctype; This returns an object, not a string, so if you need to extract the details as strings for all doctypes up to and including HTML5 it is described here: Get DocType of an HTML as string with Javascript

I only wanted HTML5, so the following was enough for me to create the whole document:

alert('<!DOCTYPE HTML>' + '\n' + document.documentElement.outerHTML);

Ruby combining an array into one string

Use the Array#join method (the argument to join is what to insert between the strings - in this case a space):

@arr.join(" ")

How to develop or migrate apps for iPhone 5 screen resolution?

To determine if your app can support iPhone 5 Retina use this: (This could be more robust to return the type of display, 4S Retina, etc., but as it is written below, it just returns if the iPhone supports iOS5 Retina as a YES or NO)

In a common ".h" file add:

BOOL IS_IPHONE5_RETINA(void);

In a common ".m" file add:

BOOL IS_IPHONE5_RETINA(void) {
    BOOL isiPhone5Retina = NO;
    if(UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
        if ([UIScreen mainScreen].scale == 2.0f) {
            CGSize result = [[UIScreen mainScreen] bounds].size;
            CGFloat scale = [UIScreen mainScreen].scale;
            result = CGSizeMake(result.width * scale, result.height * scale);

            if(result.height == 960){
                //NSLog(@"iPhone 4, 4s Retina Resolution");
            }
            if(result.height == 1136){
                //NSLog(@"iPhone 5 Resolution");
                isiPhone5Retina = YES;
            }
        } else {
            //NSLog(@"iPhone Standard Resolution");
        }
    }
    return isiPhone5Retina;
}

What's the difference between Thread start() and Runnable run()

The points, that the members made are all right so I just want to add something. The thing is that JAVA supports no Multi-inheritance. But What is if you want to derive a class B from another class A, but you can only derive from one Class. The problem now is how to "derive" from both classes: A and Thread. Therefore you can use the Runnable Interface.

public class ThreadTest{
   public void method(){
      Thread myThread = new Thread(new B());
      myThread.start;
   }
}

public class B extends A implements Runnable{...

Invalid self signed SSL cert - "Subject Alternative Name Missing"

  • Make a copy of your OpenSSL config in your home directory:

    cp /System/Library/OpenSSL/openssl.cnf ~/openssl-temp.cnf
    

    or on Linux:

    cp /etc/ssl/openssl.cnf ~/openssl-temp.cnf
    
  • Add Subject Alternative Name to openssl-temp.cnf, under [v3_ca]:

    [ v3_ca ]
    subjectAltName = DNS:localhost
    

    Replace localhost by the domain for which you want to generate that certificate.

  • Generate certificate:

    sudo openssl req -x509 -nodes -days 365 -newkey rsa:2048 \
        -config ~/openssl-temp.cnf
        -keyout /path/to/your.key -out /path/to/your.crt
    

You can then delete openssl-temp.cnf

What are the different types of indexes, what are the benefits of each?

I'll add a couple of index types

BITMAP - when you have very low number of different possible values, very fast and doesn't take up much space

PARTITIONED - allows the index to be partitioned based on some property usually advantageous on very large database objects for storage or performance reasons.

FUNCTION/EXPRESSION indexes - used to pre-calculate some value based on the table and store it in the index, a very simple example might be an index based on lower() or a substring function.

Visual Studio C# IntelliSense not automatically displaying

At the bottommost right look at the blue line where Ln, Col, Spaces, UTF, CRLF,..... here the language is specified. Check that your language and the language specified there are the same. In my case, it was Django Python while I was trying to use HTML.

node.js string.replace doesn't work?

If you just want to clobber all of the instances of a substring out of a string without using regex you can using:

    var replacestring = "A B B C D"
    const oldstring = "B";
    const newstring = "E";
    while (replacestring.indexOf(oldstring) > -1) {
        replacestring = replacestring.replace(oldstring, newstring);
    }        
    //result: "A E E C D"

Can I set an unlimited length for maxJsonLength in web.config?

In MVC 4 you can do:

protected override JsonResult Json(object data, string contentType, System.Text.Encoding contentEncoding, JsonRequestBehavior behavior)
{
    return new JsonResult()
    {
        Data = data,
        ContentType = contentType,
        ContentEncoding = contentEncoding,
        JsonRequestBehavior = behavior,
        MaxJsonLength = Int32.MaxValue
    };
}

in your controller.

Addition:

For anyone puzzled by the parameters you need to specify, a call could look like this:

Json(
    new {
        field1 = true,
        field2 = "value"
        },
    "application/json",
    Encoding.UTF8,
    JsonRequestBehavior.AllowGet
);

"Cannot allocate an object of abstract type" error

You must have some virtual function declared in one of the parent classes and never implemented in any of the child classes. Make sure that all virtual functions are implemented somewhere in the inheritence chain. If a class's definition includes a pure virtual function that is never implemented, an instance of that class cannot ever be constructed.

How to scroll to specific item using jQuery?

Contrary to what most people here are suggesting, I'd recommend you do use a plugin if you want to animate the move. Just animating scrollTop is not enough for a smooth user experience. See my answer here for the reasoning.

I have tried a number of plugins over the years, but eventually written one myself. You might want to give it a spin: jQuery.scrollable. Using that, the scroll action becomes

$container.scrollTo( targetPosition );

But that's not all. We need to fix the target position, too. The calculation you see in other answers,

$target.offset().top - $container.offset().top + $container.scrollTop()

mostly works but is not entirely correct. It doesn't handle the border of the scroll container properly. The target element is scrolled upwards too far, by the size of the border. Here is a demo.

Hence, a better way to calculate the target position is

var target = $target[0], 
    container = $container[0];

targetPosition = $container.scrollTop() + target.getBoundingClientRect().top - container.getBoundingClientRect().top - container.clientTop;

Again, have a look at the demo to see it in action.

For a function which returns the target position and works for both window and non-window scroll containers, feel free to use this gist. The comments in there explain how the position is calculated.

In the beginning, I have said it would be best to use a plugin for animated scrolling. You don't need a plugin, however, if you want to jump to the target without a transition. See the answer by @James for that, but make sure you calculate the target position correctly if there is a border around the container.

Difference between DOMContentLoaded and load events

The DOMContentLoaded event will fire as soon as the DOM hierarchy has been fully constructed, the load event will do it when all the images and sub-frames have finished loading.

DOMContentLoaded will work on most modern browsers, but not on IE including IE9 and above. There are some workarounds to mimic this event on older versions of IE, like the used on the jQuery library, they attach the IE specific onreadystatechange event.

Is it possible to declare a public variable in vba and assign a default value?

This is what I do when I need Initialized Global Constants:
1. Add a module called Globals
2. Add Properties like this into the Globals module:

Property Get PSIStartRow() As Integer  
    PSIStartRow = Sheets("FOB Prices").Range("F1").Value  
End Property  
Property Get PSIStartCell() As String  
    PSIStartCell = "B" & PSIStartRow  
End Property

Send file using POST from a Python script

You may also want to have a look at httplib2, with examples. I find using httplib2 is more concise than using the built-in HTTP modules.

How to Inspect Element using Safari Browser

in menu bar click on Edit->preference->advance at bottom click the check box true that is for Show develop menu in menu bar now a develop menu is display at menu bar where you can see all develop option and inspect.

How to view files in binary from bash?

You can use hexdump binary file

sudo apt-get install hexdump

hexdump -C yourfile.bin

Aligning label and textbox on same line (left and right)

you can use style

   <td  colspan="2">
     <div style="float:left; width:80px"><asp:Label ID="Label6" runat="server" Text="Label"></asp:Label></div>

    <div style="float: right; width:100px">    
            <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
    </div>

     <div style="clear:both"></div>

    </td>

What are the Differences Between "php artisan dump-autoload" and "composer dump-autoload"?

composer dump-autoload

PATH vendor/composer/autoload_classmap.php
  • Composer dump-autoload won’t download a thing.
  • It just regenerates the list of all classes that need to be included in the project (autoload_classmap.php).
  • Ideal for when you have a new class inside your project.
  • autoload_classmap.php also includes the providers in config/app.php

php artisan dump-autoload

  • It will call Composer with the optimize flag
  • It will 'recompile' loads of files creating the huge bootstrap/compiled.php

Hiding axis text in matplotlib plots

I was not actually able to render an image without borders or axis data based on any of the code snippets here (even the one accepted at the answer). After digging through some API documentation, I landed on this code to render my image

plt.axis('off')
plt.tick_params(axis='both', left='off', top='off', right='off', bottom='off', labelleft='off', labeltop='off', labelright='off', labelbottom='off')
plt.savefig('foo.png', dpi=100, bbox_inches='tight', pad_inches=0.0)

I used the tick_params call to basically shut down any extra information that might be rendered and I have a perfect graph in my output file.

Why are primes important in cryptography?

One more resource for you. Security Now! episode 30(~30 minute podcast, link is to the transcript) talks about cryptography issues, and explains why primes are important.

What is the C# Using block and why should I use it?

The using statement is used to work with an object in C# that implements the IDisposable interface.

The IDisposable interface has one public method called Dispose that is used to dispose of the object. When we use the using statement, we don't need to explicitly dispose of the object in the code, the using statement takes care of it.

using (SqlConnection conn = new SqlConnection())
{

}

When we use the above block, internally the code is generated like this:

SqlConnection conn = new SqlConnection() 
try
{

}
finally
{
    // calls the dispose method of the conn object
}

For more details read: Understanding the 'using' statement in C#.

How do I push a new local branch to a remote Git repository and track it too?

edit Outdated, just use git push -u origin $BRANCHNAME


Use git publish-branch from William's miscellaneous Git tools.

OK, no Ruby, so - ignoring the safeguards! - take the last three lines of the script and create a bash script, git-publish-branch:

#!/bin/bash
REMOTE=$1 # Rewrite this to make it optional...
BRANCH=$2
# Uncomment the following line to create BRANCH locally first
#git checkout -b ${BRANCH}
git push ${ORIGIN} ${BRANCH}:refs/heads/${BRANCH} &&
git config branch.${BRANCH}.remote ${REMOTE} &&
git config branch.${BRANCH}.merge refs/heads/${BRANCH}

Then run git-publish-branch REMOTENAME BRANCHNAME, where REMOTENAME is usually origin (you may modify the script to take origin as default, etc...)

SQL : BETWEEN vs <= and >=

Although BETWEEN is easy to read and maintain, I rarely recommend its use because it is a closed interval and as mentioned previously this can be a problem with dates - even without time components.

For example, when dealing with monthly data it is often common to compare dates BETWEEN first AND last, but in practice this is usually easier to write dt >= first AND dt < next-first (which also solves the time part issue) - since determining last usually is one step longer than determining next-first (by subtracting a day).

In addition, another gotcha is that lower and upper bounds do need to be specified in the correct order (i.e. BETWEEN low AND high).

Program does not contain a static 'Main' method suitable for an entry point

Just in case anyone is having the same problem... I was getting this error, and it turned out to be my <Application.Resources> in my App.xaml file. I had a resource outside my resource dictionary tags, and that caused this error.

round up to 2 decimal places in java?

This is long one but a full proof solution, never fails

Just pass your number to this function as a double, it will return you rounding the decimal value up to the nearest value of 5;

if 4.25, Output 4.25

if 4.20, Output 4.20

if 4.24, Output 4.20

if 4.26, Output 4.30

if you want to round upto 2 decimal places,then use

DecimalFormat df = new DecimalFormat("#.##");
roundToMultipleOfFive(Double.valueOf(df.format(number)));

if up to 3 places, new DecimalFormat("#.###")

if up to n places, new DecimalFormat("#.nTimes #")

 public double roundToMultipleOfFive(double x)
            {

                x=input.nextDouble();
                String str=String.valueOf(x);
                int pos=0;
                for(int i=0;i<str.length();i++)
                {
                    if(str.charAt(i)=='.')
                    {
                        pos=i;
                        break;
                    }
                }

                int after=Integer.parseInt(str.substring(pos+1,str.length()));
                int Q=after/5;
                int R =after%5;

                if((Q%2)==0)
                {
                    after=after-R;
                }
                else
                {
                   if(5-R==5)
                   {
                     after=after;
                   }
                   else after=after+(5-R);
                }

                       return Double.parseDouble(str.substring(0,pos+1).concat(String.valueOf(after))));

            }

How do I catch an Ajax query post error?

You have to log the responseText:

$.ajax({
    type: 'POST',
    url: 'status.ajax.php',
    data: {
    deviceId: id
  }
})
.done(
 function (data) {
  //your code
 }
)
.fail(function (data) {
      console.log( "Ajax failed: " + data['responseText'] );
})

Finding repeated words on a string and counting the repetitions

As mentioned by others use String::split(), followed by some map (hashmap or linkedhashmap) and then merge your result. For completeness sake putting the code.

import java.util.*;

public class Genric<E>
{
    public static void main(String[] args) 
    {
        Map<String, Integer> unique = new LinkedHashMap<String, Integer>();
        for (String string : "House, House, House, Dog, Dog, Dog, Dog".split(", ")) {
            if(unique.get(string) == null)
                unique.put(string, 1);
            else
                unique.put(string, unique.get(string) + 1);
        }
        String uniqueString = join(unique.keySet(), ", ");
        List<Integer> value = new ArrayList<Integer>(unique.values());

        System.out.println("Output = " + uniqueString);
        System.out.println("Values = " + value);

    }

    public static String join(Collection<String> s, String delimiter) {
        StringBuffer buffer = new StringBuffer();
        Iterator<String> iter = s.iterator();
        while (iter.hasNext()) {
            buffer.append(iter.next());
            if (iter.hasNext()) {
                buffer.append(delimiter);
            }
        }
        return buffer.toString();
    }
}

New String is Output = House, Dog

Int array (or rather list) Values = [3, 4] (you can use List::toArray) for getting an array.

Query to list number of records in each table in a database

This approaches uses string concatenation to produce a statement with all tables and their counts dynamically, like the example(s) given in the original question:

          SELECT COUNT(*) AS Count,'[dbo].[tbl1]' AS TableName FROM [dbo].[tbl1]
UNION ALL SELECT COUNT(*) AS Count,'[dbo].[tbl2]' AS TableName FROM [dbo].[tbl2]
UNION ALL SELECT...

Finally this is executed with EXEC:

DECLARE @cmd VARCHAR(MAX)=STUFF(
                    (
                        SELECT 'UNION ALL SELECT COUNT(*) AS Count,''' 
                              + QUOTENAME(t.TABLE_SCHEMA) + '.' + QUOTENAME(t.TABLE_NAME) 
                              + ''' AS TableName FROM ' + QUOTENAME(t.TABLE_SCHEMA) + '.' + QUOTENAME(t.TABLE_NAME)
                        FROM INFORMATION_SCHEMA.TABLES AS t
                        WHERE TABLE_TYPE='BASE TABLE'
                        FOR XML PATH('')
                    ),1,10,'');
EXEC(@cmd);

How do I tar a directory of files and folders without including the directory itself?

tar -czvf mydir.tgz -C my_dir/ `ls -A mydir`

Run it one level above mydir. This won't include any [.] or stuff.

How do I check if string contains substring?

you can define an extension method and use it later.

String.prototype.contains = function(it) 
{ 
   return this.indexOf(it) != -1; 
};

so that you can use in your page anywhere like:

var str="hello how are you";
str.contains("are");

which returns true.

Refer below post for more extension helper methods. Javascript helper methods

Android emulator doesn't take keyboard input - SDK tools rev 20

Confirmed. I had the same problem after upgrading to Tools version 20. I had to Edit the AVD to add an option as follows:

  1. From Eclipse, Go to AVD Mananger.
  2. Select the particular AVD and click on Edit
  3. Go to the Hardware section, click on New.
  4. Select the Property Name : Keyboard Support
  5. By default, it is added with a value of 'no'. Just click on the value column and change it to 'yes'.
  6. Click on Edit AVD again.

This will add a property hw.keyboard=yes in config.ini file for the AVD.

You also have to set hw.mainKeys = yes

How to grep a text file which contains some binary data?

Here's what I used in a system that didn't have "strings" command installed

cat yourfilename | tr -cd "[:print:]"

This prints the text and removes unprintable characters in one fell swoop, unlike "cat -v filename" which requires some postprocessing to remove unwanted stuff. Note that some of the binary data may be printable so you'll still get some gibberish between the good stuff. I think strings removes this gibberish too if you can use that.

How to wait for 2 seconds?

As mentioned in other answers, all of the following will work for the standard string-based syntax.

WAITFOR DELAY '02:00' --Two hours
WAITFOR DELAY '00:02' --Two minutes
WAITFOR DELAY '00:00:02' --Two seconds
WAITFOR DELAY '00:00:00.200' --Two tenths of a seconds

There is also an alternative method of passing it a DATETIME value. You might think I'm confusing this with WAITFOR TIME, but it also works for WAITFOR DELAY.

Considerations for passing DATETIME:

  • It must be passed as a variable, so it isn't a nice one-liner anymore.
  • The delay is measured as the time since the Epoch ('1900-01-01').
  • For situations that require a variable amount of delay, it is much easier to manipulate a DATETIME than to properly format a VARCHAR.

How to wait for 2 seconds:

--Example 1
DECLARE @Delay1 DATETIME
SELECT @Delay1 = '1900-01-01 00:00:02.000'
WAITFOR DELAY @Delay1

--Example 2
DECLARE @Delay2 DATETIME
SELECT @Delay2 = dateadd(SECOND, 2, convert(DATETIME, 0))
WAITFOR DELAY @Delay2

A note on waiting for TIME vs DELAY:

Have you ever noticed that if you accidentally pass WAITFOR TIME a date that already passed, even by just a second, it will never return? Check it out:

--Example 3
DECLARE @Time1 DATETIME
SELECT @Time1 = getdate()
WAITFOR DELAY '00:00:01'
WAITFOR TIME @Time1 --WILL HANG FOREVER

Unfortunately, WAITFOR DELAY will do the same thing if you pass it a negative DATETIME value (yes, that's a thing).

--Example 4
DECLARE @Delay3 DATETIME
SELECT @Delay3 = dateadd(SECOND, -1, convert(DATETIME, 0))
WAITFOR DELAY @Delay3 --WILL HANG FOREVER

However, I would still recommend using WAITFOR DELAY over a static time because you can always confirm your delay is positive and it will stay that way for however long it takes your code to reach the WAITFOR statement.

Moving all files from one directory to another using Python

Please, take a look at implementation of the copytree function which:

  • List directory files with:

    names = os.listdir(src)

  • Copy files with:

for name in names:
  srcname = os.path.join(src, name)
  dstname = os.path.join(dst, name)
  copy2(srcname, dstname)

Getting dstname is not necessary, because if destination parameter specifies a directory, the file will be copied into dst using the base filename from srcname.

Replace copy2 by move.

Is there more to an interface than having the correct methods

Don't forget that at a later date you can take an existing class, and make it implement IBox, and it will then become available to all your box-aware code.

This becomes a bit clearer if interfaces are named -able. e.g.

public interface Saveable {
....

public interface Printable {
....

etc. (Naming schemes don't always work e.g. I'm not sure Boxable is appropriate here)

Increment a value in Postgres

UPDATE totals 
   SET total = total + 1
WHERE name = 'bill';

If you want to make sure the current value is indeed 203 (and not accidently increase it again) you can also add another condition:

UPDATE totals 
   SET total = total + 1
WHERE name = 'bill'
  AND total = 203;

Postgres: How to convert a json string to text?

In 9.4.4 using the #>> operator works for me:

select to_json('test'::text) #>> '{}';

To use with a table column:

select jsoncol #>> '{}' from mytable;

Installing OpenCV on Windows 7 for Python 2.7

I have posted a very simple method to install OpenCV 2.4 for Python in Windows here : Install OpenCV in Windows for Python

It is just as simple as copy and paste. Hope it will be useful for future viewers.

  1. Download Python, Numpy, OpenCV from their official sites.

  2. Extract OpenCV (will be extracted to a folder opencv)

  3. Copy ..\opencv\build\python\x86\2.7\cv2.pyd

  4. Paste it in C:\Python27\Lib\site-packages

  5. Open Python IDLE or terminal, and type

    >>> import cv2
    

If no errors shown, it is OK.

UPDATE (Thanks to dana for this info):

If you are using the VideoCapture feature, you must copy opencv_ffmpeg.dll into your path as well. See: https://stackoverflow.com/a/11703998/1134940

java.io.FileNotFoundException: the system cannot find the file specified

I have the same problem, but you know why? because I didn't put .txt in the end of my File and so it was File not a textFile, you shoud do just two things:

  1. Put your Text File in the Root Directory (e.x if you have a project called HelloWorld, just right-click on the HelloWorld file in the package Directory and create File
  2. Save as that File with any name that you want but with a .txt in the end of that I guess your problem is solved, but I write it to other peoples know that. Thanks.

C++ floating point to integer type conversions

One thing I want to add. Sometimes, there can be precision loss. You may want to add some epsilon value first before converting. Not sure why that works... but it work.

int someint = (somedouble+epsilon);

How to adjust gutter in Bootstrap 3 grid system?

You could create a CSS class for this and apply it to your columns. Since the gutter (spacing between columns) is controlled by padding in Bootstrap 3, adjust the padding accordingly:

.col {
  padding-right:7px;
  padding-left:7px;
}

Demo: http://bootply.com/93473

EDIT If you only want the spacing between columns you can select all cols except first and last like this..

.col:not(:first-child,:last-child) {
  padding-right:7px;
  padding-left:7px;
}

Updated Bootply

For Bootstrap 4 see: Remove gutter space for a specific div only

How to update and order by using ms sql

You can do a subquery where you first get the IDs of the top 10 ordered by priority and then update the ones that are on that sub query:

UPDATE  messages 
SET status=10 
WHERE ID in (SELECT TOP (10) Id 
             FROM Table 
             WHERE status=0 
             ORDER BY priority DESC);

Heap space out of memory

Are you keeping references to variables that you no longer need (e.g. data from the previous simulations)? If so, you have a memory leak. You just need to find where that is happening and make sure that you remove the references to the variables when they are no longer needed (this would automatically happen if they go out of scope).

If you actually need all that data from previous simulations in memory, you need to increase the heap size or change your algorithm.

What is the best way to get the first letter from a string in Java, returned as a string of length 1?

String whole = "something";
String first = whole.substring(0, 1);
System.out.println(first);

Stretch and scale a CSS image in the background - with CSS only

Thanks!

But then it was not working for the Google Chrome and Safari browsers (stretching worked, but the hight of the pictures was only 2 mm!), until someone told me what lacks:

Try to set height:auto;min-height:100%;

So change that for your height:100%; line, gives:

#### #background {
    width: 100%; 
    height: 100%; 
    position: fixed; 
    left: 0px; 
    top: 0px; 
    z-index: -1;
}

.stretch {
    width:100%;
    height:auto;
    min-height:100%;
}

Just before that newly added code I have this in my Drupal Tendu themes style.css:

html, body{height:100%;}

#page{background:#ffffff; height:auto !important;height:100%;min-height:100%;position:relative;}

Then I have to make a new block within Drupal with the picture while adding class=stretch:

< img alt="" class="stretch" src="pic.url" />

Just copying a picture with the editor in that Drupal block doesn't work; one has to change the editor to non-formatted text.

Symfony2 Setting a default choice field selection

If you want to pass in an array of Doctrine entities, try something like this (Symfony 3.0+):

protected $entities;
protected $selectedEntities;

public function __construct($entities = null, $selectedEntities = null)
{
    $this->entities = $entities;
    $this->selectedEntities = $selectedEntities;
}

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder->add('entities', 'entity', [
        'class' => 'MyBundle:MyEntity',
        'choices' => $this->entities,
        'property' => 'id',
        'multiple' => true,
        'expanded' => true,
        'data' => $this->selectedEntities,
    ]);
}

Running Node.Js on Android

I just had a jaw-drop moment - Termux allows you to install NodeJS on an Android device!

It seems to work for a basic Websocket Speed Test I had on hand. The http served by it can be accessed both locally and on the network.

There is a medium post that explains the installation process

Basically: 1. Install termux 2. apt install nodejs 3. node it up!

One restriction I've run into - it seems the shared folders don't have the necessary permissions to install modules. It might just be a file permission thing. The private app storage works just fine.

Java - Writing strings to a CSV file

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;

public class CsvFile {

    public static void main(String[]args){
        PrintWriter pw = null;
        try {
            pw = new PrintWriter(new File("NewData.csv"));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        StringBuilder builder = new StringBuilder();
        String columnNamesList = "Id,Name";
        // No need give the headers Like: id, Name on builder.append
        builder.append(columnNamesList +"\n");
        builder.append("1"+",");
        builder.append("Chola");
        builder.append('\n');
        pw.write(builder.toString());
        pw.close();
        System.out.println("done!");
    }
}

How to create a vector of user defined size but with no predefined values?

With the constructor:

// create a vector with 20 integer elements
std::vector<int> arr(20);

for(int x = 0; x < 20; ++x)
   arr[x] = x;

Which way is best for creating an object in JavaScript? Is `var` necessary before an object property?

There are a many ways to create your objects in JavaScript. Using a constructer function to create an object or object literal notation is using alot in JavaScript. Also creating an instance of Object and then adding properties and methods to it, there are three common ways to do create objects in JavaScript.

Constructer functions

There are built-in constructer functions that we all may use them time to time, like Date(), Number(), Boolean() etc, all constructer functions start with Capital letter, in the meantime we can create custom constructor function in JavaScript like this:

function Box (Width, Height, fill) {  
  this.width = Width;  // The width of the box 
  this.height = Height;  // The height of the box 
  this.fill = true;  // Is it filled or not?
}  

and you can invoke it, simply using new(), to create a new instance of the constructor, create something like below and call the constructor function with filled parameters:

var newBox = new Box(8, 12, true);  

Object literals

Using object literals are very used case creating object in JavaScript, this an example of creating a simple object, you can assign anything to your object properties as long as they are defined:

var person = { 
    name: "Alireza",
    surname: "Dezfoolian"
    nose: 1,  
    feet: 2,  
    hands: 2,
    cash: null
};  

Prototyping

After creating an Object, you can prototype more members to that, for example adding colour to our Box, we can do this:

Box.prototype.colour = 'red';

JavaScript: How do I print a message to the error console?

This does not print to the Console, but will open you an alert Popup with your message which might be useful for some debugging:

just do:

alert("message");

Decorators with parameters?

Here is a slightly modified version of t.dubrownik's answer. Why?

  1. As a general template, you should return the return value from the original function.
  2. This changes the name of the function, which could affect other decorators / code.

So use @functools.wraps():

from functools import wraps

def decorator(argument):
    def real_decorator(function):
        @wraps(function)
        def wrapper(*args, **kwargs):
            funny_stuff()
            something_with_argument(argument)
            retval = function(*args, **kwargs)
            more_funny_stuff()
            return retval
        return wrapper
    return real_decorator

Changing EditText bottom line color with appcompat v7

The accepted answer is a bit more per style basis thing, but the most efficient thing to do is to add the colorAccent attribute in your AppTheme style like this:

<style name="AppTheme.Base" parent="Theme.AppCompat.Light.NoActionBar">
        <item name="colorAccent">@color/colorAccent</item>
        <item name="android:editTextStyle">@style/EditTextStyle</item>
</style>

<style name="EditTextStyle" parent="Widget.AppCompat.EditText"/>

The colorAccent attribute is used for widget tinting throughout the app and thus should be used for consistency

Using gdb to single-step assembly code outside specified executable causes error "cannot find bounds of current function"

Instead of gdb, run gdbtui. Or run gdb with the -tui switch. Or press C-x C-a after entering gdb. Now you're in GDB's TUI mode.

Enter layout asm to make the upper window display assembly -- this will automatically follow your instruction pointer, although you can also change frames or scroll around while debugging. Press C-x s to enter SingleKey mode, where run continue up down finish etc. are abbreviated to a single key, allowing you to walk through your program very quickly.

   +---------------------------------------------------------------------------+
B+>|0x402670 <main>         push   %r15                                        |
   |0x402672 <main+2>       mov    %edi,%r15d                                  |
   |0x402675 <main+5>       push   %r14                                        |
   |0x402677 <main+7>       push   %r13                                        |
   |0x402679 <main+9>       mov    %rsi,%r13                                   |
   |0x40267c <main+12>      push   %r12                                        |
   |0x40267e <main+14>      push   %rbp                                        |
   |0x40267f <main+15>      push   %rbx                                        |
   |0x402680 <main+16>      sub    $0x438,%rsp                                 |
   |0x402687 <main+23>      mov    (%rsi),%rdi                                 |
   |0x40268a <main+26>      movq   $0x402a10,0x400(%rsp)                       |
   |0x402696 <main+38>      movq   $0x0,0x408(%rsp)                            |
   |0x4026a2 <main+50>      movq   $0x402510,0x410(%rsp)                       |
   +---------------------------------------------------------------------------+
child process 21518 In: main                            Line: ??   PC: 0x402670
(gdb) file /opt/j64-602/bin/jconsole
Reading symbols from /opt/j64-602/bin/jconsole...done.
(no debugging symbols found)...done.
(gdb) layout asm
(gdb) start
(gdb)

How to break out of a loop from inside a switch?

You could potentially use goto, but I would prefer to set a flag that stops the loop. Then break out of the switch.

How do I make JavaScript beep?

function Sound(url, vol, autoplay, loop)
{
    var that = this;

    that.url = (url === undefined) ? "" : url;
    that.vol = (vol === undefined) ? 1.0 : vol;
    that.autoplay = (autoplay === undefined) ? true : autoplay;
    that.loop = (loop === undefined) ? false : loop;
    that.sample = null;

    if(that.url !== "")
    {
        that.sync = function(){
            that.sample.volume = that.vol;
            that.sample.loop = that.loop;
            that.sample.autoplay = that.autoplay;
            setTimeout(function(){ that.sync(); }, 60);
        };

        that.sample = document.createElement("audio");
        that.sample.src = that.url;
        that.sync();

        that.play = function(){
            if(that.sample)
            {
                that.sample.play();
            }
        };

        that.pause = function(){
            if(that.sample)
            {
                that.sample.pause();
            }
        };
    }
}

var test = new Sound("http://mad-hatter.fr/Assets/projects/FreedomWings/Assets/musiques/freedomwings.mp3");
test.play();

http://jsfiddle.net/sv9j638j/

Load HTML page dynamically into div with jQuery

JQuery load works, but it will strip out javascript and other elements from the source page. This makes sense because you might not want to introduce bad script on your page. I think this is a limitation and since you are doing a whole page and not just a div on the source page, you might not want to use it. (I am not sure about css, but I think it would also get stripped)

In this example, if you put a tag around the body of your source page, it will grab anything in between the tags and won't strip anything out. I wrap my source page with and .

This solution will grab everything between the above delimiters. I feel it is a much more robust solution than a simple load.

  var content = $('.contentDiv');
    content.load(urlAddress, function (response, status, xhr) {
        var fullPageTextAsString = response;
        var pageTextBetweenDelimiters = fullPageTextAsString.substring(fullPageTextAsString.indexOf("<jqueryloadmarkerstart />"), fullPageTextAsString.indexOf("<jqueryloadmarkerend />"));
        content.html(pageTextBetweenDelimiters);
    });

How can I send an email by Java application using GMail, Yahoo, or Hotmail?

This is what I do when i want to send email with attachment, work fine. :)

 public class NewClass {

    public static void main(String[] args) {
        try {
            Properties props = System.getProperties();
            props.put("mail.smtp.starttls.enable", "true");
            props.put("mail.smtp.host", "smtp.gmail.com");
            props.put("mail.smtp.auth", "true");
            props.put("mail.smtp.port", "465"); // smtp port
            Authenticator auth = new Authenticator() {

                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication("username-gmail", "password-gmail");
                }
            };
            Session session = Session.getDefaultInstance(props, auth);
            MimeMessage msg = new MimeMessage(session);
            msg.setFrom(new InternetAddress("[email protected]"));
            msg.setSubject("Try attachment gmail");
            msg.setRecipient(RecipientType.TO, new InternetAddress("[email protected]"));
            //add atleast simple body
            MimeBodyPart body = new MimeBodyPart();
            body.setText("Try attachment");
            //do attachment
            MimeBodyPart attachMent = new MimeBodyPart();
            FileDataSource dataSource = new FileDataSource(new File("file-sent.txt"));
            attachMent.setDataHandler(new DataHandler(dataSource));
            attachMent.setFileName("file-sent.txt");
            attachMent.setDisposition(MimeBodyPart.ATTACHMENT);
            Multipart multipart = new MimeMultipart();
            multipart.addBodyPart(body);
            multipart.addBodyPart(attachMent);
            msg.setContent(multipart);
            Transport.send(msg);
        } catch (AddressException ex) {
            Logger.getLogger(NewClass.class.getName()).log(Level.SEVERE, null, ex);
        } catch (MessagingException ex) {
            Logger.getLogger(NewClass.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

}

Convert to/from DateTime and Time in Ruby

While making such conversions one should take into consideration the behavior of timezones while converting from one object to the other. I found some good notes and examples in this stackoverflow post.

html5 input for money/currency

More easy and beautiful if you has vue.js v-money-spinner :)

enter image description here

How to escape apostrophe (') in MySql?

What I believe user2087510 meant was:

name = 'something'
name = name.replace("'", "\\'")

I have also used this with success.

Insert multiple lines into a file after specified pattern using shell script

You can use awk for inserting output of some command in the middle of input.txt.
The lines to be inserted can be the output of a cat otherfile, ls -l or 4 lines with a number generated by printf.

awk 'NR==FNR {a[NR]=$0;next}
    {print}
    /cdef/ {for (i=1; i <= length(a); i++) { print a[i] }}'
    <(printf "%s\n" line{1..4}) input.txt

fork and exec in bash

How about:

(sleep 5; echo "Hello World") &

Compiling an application for use in highly radioactive environments

If your hardware fails then you can use mechanical storage to recover it. If your code base is small and have some physical space then you can use a mechanical data store.

Enter image description here

There will be a surface of material which will not be affected by radiation. Multiple gears will be there. A mechanical reader will run on all the gears and will be flexible to move up and down. Down means it is 0 and up means it is 1. From 0 and 1 you can generate your code base.

What is the (function() { } )() construct in JavaScript?

Start here:

var b = 'bee';
console.log(b);  // global

Put it in a function and it is no longer global -- your primary goal.

function a() {
  var b = 'bee';
  console.log(b);
}
a();
console.log(b);  // ReferenceError: b is not defined -- *as desired*

Call the function immediately -- oops:

function a() {
  var b = 'bee';
  console.log(b);
}();             // SyntaxError: Expected () to start arrow function, but got ';' instead of '=>'

Use the parentheses to avoid a syntax error:

(function a() {
  var b = 'bee';
  console.log(b);
})(); // OK now

You can leave off the function name:

(function () {    // no name required
  var b = 'bee';
  console.log(b);
})();

It doesn't need to be any more complicated than that.

How to stop execution after a certain time in Java?

long start = System.currentTimeMillis();
long end = start + 60*1000; // 60 seconds * 1000 ms/sec
while (System.currentTimeMillis() < end)
{
    // run
}

password for postgres

Set the default password in the .pgpass file. If the server does not save the password, it is because it is not set in the .pgpass file, or the permissions are open and the file is therefore ignored.

Read more about the password file here.

Also, be sure to check the permissions: on *nix systems the permissions on .pgpass must disallow any access to world or group; achieve this by the command chmod 0600 ~/.pgpass. If the permissions are less strict than this, the file will be ignored.

Have you tried logging-in using PGAdmin? You can save the password there, and modify the pgpass file.

Redirect stdout to a file in Python?

Quoted from PEP 343 -- The "with" Statement (added import statement):

Redirect stdout temporarily:

import sys
from contextlib import contextmanager
@contextmanager
def stdout_redirected(new_stdout):
    save_stdout = sys.stdout
    sys.stdout = new_stdout
    try:
        yield None
    finally:
        sys.stdout = save_stdout

Used as follows:

with open(filename, "w") as f:
    with stdout_redirected(f):
        print "Hello world"

This isn't thread-safe, of course, but neither is doing this same dance manually. In single-threaded programs (for example in scripts) it is a popular way of doing things.

How do you change the value inside of a textfield flutter?

The problem with just setting

_controller.text = "New value";

is that the cursor will be repositioned to the beginning (in material's TextField). Using

_controller.text = "Hello";
_controller.selection = TextSelection.fromPosition(
    TextPosition(offset: _controller.text.length),
);
setState(() {});

is not efficient since it rebuilds the widget more than it's necessary (when setting the text property and when calling setState).

--

I believe the best way is to combine everything into one simple command:

final _newValue = "New value";
_controller.value = TextEditingValue(
      text: _newValue,
      selection: TextSelection.fromPosition(
        TextPosition(offset: _newValue.length),
      ),
    );

It works properly for both Material and Cupertino Textfields.

Slide right to left?

GreenSock Animation Platform (GSAP) with TweenLite / TweenMax provides much smoother transitions with far greater customization than jQuery or CSS3 transitions. In order to animate CSS properties with TweenLite / TweenMax, you'll also need their plugin called "CSSPlugin". TweenMax includes this automatically.

First, load the TweenMax library:

<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/1.18.0/TweenMax.min.js"></script>

Or the lightweight version, TweenLite:

<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/1.18.0/plugins/CSSPlugin.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/1.18.0/easing/EasePack.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/1.18.0/TweenLite.min.js"></script>

Then, call your animation:

 var myObj= document.getElementById("myDiv");

// Syntax: (target, speed, {distance, ease})
 TweenLite.to(myObj, .7, { x: 500, ease: Power3.easeOut});

You can also call it with an ID selector:

 TweenLite.to("#myID", .7, { x: 500, ease: Power3.easeOut});

If you have jQuery loaded, you can use more advanced broad selectors, like all elements containing a specific class:

 // This will parse the selectors using jQuery's engine.
TweenLite.to(".myClass", .7, { x: 500, ease: Power3.easeOut});

For full details, see: TweenLite Documentation

According to their website: "TweenLite is an extremely fast, lightweight, and flexible animation tool that serves as the foundation of the GreenSock Animation Platform (GSAP)."

How to split (chunk) a Ruby array into parts of X elements?

Take a look at Enumerable#each_slice:

foo.each_slice(3).to_a
#=> [["1", "2", "3"], ["4", "5", "6"], ["7", "8", "9"], ["10"]]

Regex for checking if a string is strictly alphanumeric

Considering you want to check for ASCII Alphanumeric characters, Try this: "^[a-zA-Z0-9]*$". Use this RegEx in String.matches(Regex), it will return true if the string is alphanumeric, else it will return false.

public boolean isAlphaNumeric(String s){
    String pattern= "^[a-zA-Z0-9]*$";
    return s.matches(pattern);
}

If it will help, read this for more details about regex: http://www.vogella.com/articles/JavaRegularExpressions/article.html

height style property doesn't work in div elements

Also, make sure you add ";" to each style. Your excluding them from width and height and while it might not be causing your specific problem, it's important to close it.

<div style="height:20px; width: 70px;">My Text Here</div>

How do Python functions handle the types of the parameters that you pass in?

There's one notorious exception from the duck-typing worth mentioning on this page.

When str function calls __str__ class method it subtly ?hecks its type:

>>> class A(object):
...     def __str__(self):
...         return 'a','b'
...
>>> a = A()
>>> print a.__str__()
('a', 'b')
>>> print str(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: __str__ returned non-string (type tuple)

As if Guido hints us which exception should a program raise if it encounters an unexpected type.

Converting user input string to regular expression

You can ask for flags using checkboxes then do something like this:

var userInput = formInput;
var flags = '';
if(formGlobalCheckboxChecked) flags += 'g';
if(formCaseICheckboxChecked) flags += 'i';
var reg = new RegExp(userInput, flags);

Can Mockito capture arguments of a method called multiple times?

I think it should be

verify(mockBar, times(2)).doSomething(...)

Sample from mockito javadoc:

ArgumentCaptor<Person> peopleCaptor = ArgumentCaptor.forClass(Person.class);
verify(mock, times(2)).doSomething(peopleCaptor.capture());

List<Person> capturedPeople = peopleCaptor.getAllValues();
assertEquals("John", capturedPeople.get(0).getName());
assertEquals("Jane", capturedPeople.get(1).getName());

Returning JSON from PHP to JavaScript?

$msg="You Enter Wrong Username OR Password"; $responso=json_encode($msg);

echo "{\"status\" : \"400\", \"responce\" : \"603\", \"message\" : \"You Enter Wrong Username OR Password\", \"feed\":".str_replace("<p>","",$responso). "}";

Difference between "this" and"super" keywords in Java

super() & this()

  • super() - to call parent class constructor.
  • this() - to call same class constructor.

NOTE:

  • We can use super() and this() only in constructor not anywhere else, any attempt to do so will lead to compile-time error.

  • We have to keep either super() or this() as the first line of the constructor but NOT both simultaneously.

super & this keyword

  • super - to call parent class members(variables and methods).
  • this - to call same class members(variables and methods).

NOTE: We can use both of them anywhere in a class except static areas(static block or method), any attempt to do so will lead to compile-time error.

Notify ObservableCollection when Item changes

A simple solution is to use BindingList<T> instead of ObservableCollection<T> . Indeed the BindingList relay item change notifications. So with a binding list, if the item implements the interface INotifyPropertyChanged then you can simply get notifications using the ListChanged event.

See also this SO answer.

How to get primary key of table?

If you have spatial tables in your database, use:

SHOW KEYS FROM table WHERE Key_name = 'PRIMARY' OR Key_name = 'OGR_FID'

Does Python SciPy need BLAS?

On Fedora, this works:

 yum install lapack lapack-devel blas blas-devel
 pip install numpy
 pip install scipy

Remember to install 'lapack-devel' and 'blas-devel' in addition to 'blas' and 'lapack' otherwise you'll get the error you mentioned or the "numpy.distutils.system_info.LapackNotFoundError" error.

Restart android machine

adb reboot should not reboot your linux box.

But in any case, you can redirect the command to a specific adb device using adb -s <device_id> command , where

Device ID can be obtained from the command adb devices
command in this case is reboot

Using scp to copy a file to Amazon EC2 instance?

I would use:

scp -i "path to .pem file" "file to be copeide from local machine" username@amazoninstance: 'destination folder to copy file on remote machine'

Calling a function within a Class method?

In order to have a "function within a function", if I understand what you're asking, you need PHP 5.3, where you can take advantage of the new Closure feature.

So you could have:

public function newTest() {
   $bigTest = function() {
        //Big Test Here
   }
}

How to uncommit my last commit in Git

If you aren't totally sure what you mean by "uncommit" and don't know if you want to use git reset, please see "Revert to a previous Git commit".

If you're trying to understand git reset better, please see "Can you explain what "git reset" does in plain English?".


If you know you want to use git reset, it still depends what you mean by "uncommit". If all you want to do is undo the act of committing, leaving everything else intact, use:

git reset --soft HEAD^

If you want to undo the act of committing and everything you'd staged, but leave the work tree (your files intact):

git reset HEAD^

And if you actually want to completely undo it, throwing away all uncommitted changes, resetting everything to the previous commit (as the original question asked):

git reset --hard HEAD^

The original question also asked it's HEAD^ not HEAD. HEAD refers to the current commit - generally, the tip of the currently checked-out branch. The ^ is a notation which can be attached to any commit specifier, and means "the commit before". So, HEAD^ is the commit before the current one, just as master^ is the commit before the tip of the master branch.

Here's the portion of the git-rev-parse documentation describing all of the ways to specify commits (^ is just a basic one among many).

StringUtils.isBlank() vs String.isEmpty()

StringUtils.isBlank() checks that each character of the string is a whitespace character (or that the string is empty or that it's null). This is totally different than just checking if the string is empty.

From the linked documentation:

Checks if a String is whitespace, empty ("") or null.

 StringUtils.isBlank(null)      = true
 StringUtils.isBlank("")        = true  
 StringUtils.isBlank(" ")       = true  
 StringUtils.isBlank("bob")     = false  
 StringUtils.isBlank("  bob  ") = false

For comparison StringUtils.isEmpty:

 StringUtils.isEmpty(null)      = true
 StringUtils.isEmpty("")        = true  
 StringUtils.isEmpty(" ")       = false  
 StringUtils.isEmpty("bob")     = false  
 StringUtils.isEmpty("  bob  ") = false

Warning: In java.lang.String.isBlank() and java.lang.String.isEmpty() work the same except they don't return true for null.

java.lang.String.isBlank() (since Java 11)

java.lang.String.isEmpty()

how to count the total number of lines in a text file using python

One liner:

total_line_count = sum(1 for line in open("filename.txt"))

print(total_line_count)

jQuery Selector: Id Ends With?

It's safer to add the underscore or $ to the term you're searching for so it's less likely to match other elements which end in the same ID:

$("element[id$=_txtTitle]")

(where element is the type of element you're trying to find - eg div, input etc.

(Note, you're suggesting your IDs tend to have $ signs in them, but I think .NET 2 now tends to use underscores in the ID instead, so my example uses an underscore).

Visual Studio : short cut Key : Duplicate Line

I don't know if this exists in Visual Studio 2008 but in Visual Studio 2010+ you can easily do this by:

Don't select anything, then press Ctrl + C And then (without doing anything else) Ctrl + V

php error: Class 'Imagick' not found

On an EC2 at AWS, I did this:

 yum list | grep imagick

Then found a list of ones I could install...

 php -v

told me which version of php I had and thus which version of imagick

yum install php56-pecl-imagick.x86_64

Did the trick. Enjoy!

Get the last 4 characters of a string

Like this:

>>>mystr = "abcdefghijkl"
>>>mystr[-4:]
'ijkl'

This slices the string's last 4 characters. The -4 starts the range from the string's end. A modified expression with [:-4] removes the same 4 characters from the end of the string:

>>>mystr[:-4]
'abcdefgh'

For more information on slicing see this Stack Overflow answer.

Return multiple values to a method caller

In C# 7 and above, see this answer.

In previous versions, you can use .NET 4.0+'s Tuple:

For Example:

public Tuple<int, int> GetMultipleValue()
{
     return Tuple.Create(1,2);
}

Tuples with two values have Item1 and Item2 as properties.

How can I fetch all items from a DynamoDB table without specifying the primary key?

A simple code to list all the Items from DynamoDB Table by specifying the region of AWS Service.

import boto3

dynamodb = boto3.resource('dynamodb', region_name='ap-south-1')
table = dynamodb.Table('puppy_store')
response = table.scan()
items = response['Items']

# Prints All the Items at once
print(items)

# Prints Items line by line
for i, j in enumerate(items):
    print(f"Num: {i} --> {j}")

Where are logs located?

You should be checking the root directory and not the app directory.

Look in $ROOT/storage/laravel.log not app/storage/laravel.log, where root is the top directory of the project.

How to add a delay for a 2 or 3 seconds

For 2.3 seconds you should do:

System.Threading.Thread.Sleep(2300);

Javascript: how to validate dates in format MM-DD-YYYY?

<!DOCTYPE html>  
<html>  
<head>  

<title></title>  
 <script>
     function dateCheck(inputText) {
         debugger;

         var dateFormat = /^(0?[1-9]|[12][0-9]|3[01])[\/\-](0?[1-9]|1[012])[\/\-]\d{4}$/;

         var flag = 1;

         if (inputText.value.match(dateFormat)) {
             document.myForm.dateInput.focus();

             var inputFormat1 = inputText.value.split('/');
             var inputFormat2 = inputText.value.split('-');
             linputFormat1 = inputFormat1.length;
             linputFormat2 = inputFormat2.length;

             if (linputFormat1 > 1) {
                 var pdate = inputText.value.split('/');
             }
             else if (linputFormat2 > 1) {
                 var pdate = inputText.value.split('-');
             }
             var date = parseInt(pdate[0]);
             var month = parseInt(pdate[1]);
             var year = parseInt(pdate[2]);

             var ListofDays = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
             if (month == 1 || month > 2) {
                 if (date > ListofDays[month - 1]) {
                     alert("Invalid date format!");
                     return false;
                 }
             }

             if (month == 2) {
                 var leapYear = false;

                 if ((!(year % 4) && year % 100) || !(year % 400)) {
                     leapYear = true;

                 }
                 if ((leapYear == false) && (date >= 29)) {
                     alert("Invalid date format!");
                     return false;
                 }
                 if ((leapYear == true) && (date > 29)) {
                     alert("Invalid date format!");
                     return false;
                 }
             }
             if (flag == 1) {
                 alert("Valid Date");
             }
         }
         else {
             alert("Invalid date format!");
             document.myForm.dateInput.focus();
             return false;
         }
     }
     function restrictCharacters(evt) {

         evt = (evt) ? evt : window.event;
         var charCode = (evt.which) ? evt.which : evt.keyCode;
         if (((charCode >= '48') && (charCode <= '57')) || (charCode == '47')) {
             return true;
         }
         else {
             return false;
         }
     }


 </script>   
</head>



<body>  
    <div>  
        <form name="myForm" action="#">   
            <table>
                <tr>
                    <td>Enter Date</td>
                    <td><input type="text" onkeypress="return restrictCharacters(event);" name="dateInput"/></td>
                    <td></td>
                    <td><span id="span2"></span></td>
                </tr>

                <tr>
                    <td></td>
                    <td><input type="button" name="submit" value="Submit" onclick="dateCheck(document.myForm.dateInput)"  /></td>
                </tr>
            </table>
        </form>  
    </div>   
</body>  
</html> 

Why is &#65279; appearing in my HTML?

If you have a lot of files to review, you can use this tool: https://www.mannaz.at/codebase/utf-byte-order-mark-bom-remover/

Credits to Maurice

It help me to clean a system, with MVC in CakePhp, as i work in Linux, Windows, with different tools.. in some files my design was break.. so after checkin in Chrome with debug tool find the &#65279 error

Java: How to convert a File object to a String object in java?

With Java 7, it's as simple as:

final String EoL = System.getProperty("line.separator");
List<String> lines = Files.readAllLines(Paths.get(fileName),
        Charset.defaultCharset());

StringBuilder sb = new StringBuilder();
for (String line : lines) {
    sb.append(line).append(EoL);
}
final String content = sb.toString();

However, it does havea few minor caveats (like handling files that does not fit into the memory).

I would suggest taking a look on corresponding section in the official Java tutorial (that's also the case if you have a prior Java).

As others pointed out, you might find sime 3rd party libraries useful (like Apache commons I/O or Guava).

Access denied for root user in MySQL command-line

Gain access to a MariaDB 10 database server

After stopping the database server, the next step is to gain access to the server through a backdoor by starting the database server and skipping networking and permission tables. This can be done by running the commands below.

sudo mysqld_safe --skip-grant-tables --skip-networking &

Reset MariaDB root Password

Now that the database server is started in safe mode, run the commands below to logon as root without password prompt. To do that, run the commands below

sudo mysql -u root

Then run the commands below to use the mysql database.

use mysql;

Finally, run the commands below to reset the root password.

update user set password=PASSWORD("new_password_here") where User='root';

Replace new_password _here with the new password you want to create for the root account, then press Enter.

After that, run the commands below to update the permissions and save your changes to disk.

flush privileges;

Exit (CTRL + D) and you’re done.

Next start MariaDB normally and test the new password you just created.

sudo systemctl stop mariadb.service
sudo systemctl start mariadb.service

Logon to the database by running the commands below.

sudo mysql -u root -p

source: https://websiteforstudents.com/reset-mariadb-root-password-ubuntu-17-04-17-10/

How can multiple rows be concatenated into one in Oracle without creating a stored procedure?

Easy:

SELECT question_id, wm_concat(element_id) as elements
FROM   questions
GROUP BY question_id;

Pesonally tested on 10g ;-)

From http://www.oracle-base.com/articles/10g/StringAggregationTechniques.php

Copying a rsa public key to clipboard

Another alternative solution, that is recommended in the github help pages:

pbcopy < ~/.ssh/id_rsa.pub

Should this fail, I recommend using their docs to trouble shoot or generate a new key - if not already done.

Github docs

What is an IIS application pool?

An application pool is a group of one or more URLs that are served by a worker process or set of worker processes. Any Web directory or virtual directory can be assigned to an application pool.

Every application within an application pool shares the same worker process.

How do I pipe a subprocess call to a text file?

You could also just call the script from the terminal, outputting everything to a file, if that helps. This way:

$ /path/to/the/script.py > output.txt

This will overwrite the file. You can use >> to append to it.

If you want errors to be logged in the file as well, use &>> or &>.

Android Starting Service at Boot Time , How to restart service class after device Reboot?

Most the solutions posted here are missing an important piece: doing it without a wake lock runs the risk of your Service getting killed before it is finished processing. Saw this solution in another thread, answering here as well.

Since WakefulBroadcastReceiver is deprecated in api 26 it is recommended for API Levels below 26

You need to obtain a wake lock . Luckily, the Support library gives us a class to do this:

public class SimpleWakefulReceiver extends WakefulBroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        // This is the Intent to deliver to our service.
        Intent service = new Intent(context, SimpleWakefulService.class);

        // Start the service, keeping the device awake while it is launching.
        Log.i("SimpleWakefulReceiver", "Starting service @ " + SystemClock.elapsedRealtime());
        startWakefulService(context, service);
    }
}

then, in your Service, make sure to release the wake lock:

    @Override
    protected void onHandleIntent(Intent intent) {
        // At this point SimpleWakefulReceiver is still holding a wake lock
        // for us.  We can do whatever we need to here and then tell it that
        // it can release the wakelock.

...
        Log.i("SimpleWakefulReceiver", "Completed service @ " + SystemClock.elapsedRealtime());
        SimpleWakefulReceiver.completeWakefulIntent(intent);
    }

Don't forget to add the WAKE_LOCK permission and register your receiver in the manifest:

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.WAKE_LOCK" />

...

<service android:name=".SimpleWakefulReceiver">
    <intent-filter>
        <action android:name="com.example.SimpleWakefulReceiver"/>
    </intent-filter>
</service>

PreparedStatement with Statement.RETURN_GENERATED_KEYS

You mean something like this?

long key = -1L;

PreparedStatement preparedStatement = connection.prepareStatement(YOUR_SQL_HERE, PreparedStatement.RETURN_GENERATED_KEYS);
preparedStatement.setXXX(index, VALUE);
preparedStatement.executeUpdate();

ResultSet rs = preparedStatement.getGeneratedKeys();

if (rs.next()) {
    key = rs.getLong(1);
}

What is the most efficient way to store a list in the Django models?

If you are using Django >= 1.9 with Postgres you can make use of ArrayField advantages

A field for storing lists of data. Most field types can be used, you simply pass another field instance as the base_field. You may also specify a size. ArrayField can be nested to store multi-dimensional arrays.

It is also possible to nest array fields:

from django.contrib.postgres.fields import ArrayField
from django.db import models

class ChessBoard(models.Model):
    board = ArrayField(
        ArrayField(
            models.CharField(max_length=10, blank=True),
            size=8,
        ),
        size=8,
    )

As @thane-brimhall mentioned it is also possible to query elements directly. Documentation reference

Difference between JSONObject and JSONArray

The difference is the same as a (Hash)Map vs List.

JSONObject:

  • Contains named values (key->value pairs, tuples or whatever you want to call them)
    • like {ID : 1}
  • Order of elements is not important
    • a JSONObject of {id: 1, name: 'B'} is equal to {name: 'B', id: 1}.

JSONArray:

  • Contains only series values
    • like [1, 'value']
  • Order of values is important
    • array of [1,'value'] is not the same as ['value',1]

Example

JSON Object --> { "":""}

JSON Array --> [ , , , ]

{"employees":[
    {"firstName":"John", "lastName":"Doe"},
    {"firstName":"Anna", "lastName":"Smith"},
    {"firstName":"Peter", "lastName":"Jones"}
]}

How do you properly use namespaces in C++?

I did not see any mention of it in the other answers, so here are my 2 Canadian cents:

On the "using namespace" topic, a useful statement is the namespace alias, allowing you to "rename" a namespace, normally to give it a shorter name. For example, instead of:

Some::Impossibly::Annoyingly::Long:Name::For::Namespace::Finally::TheClassName foo;
Some::Impossibly::Annoyingly::Long:Name::For::Namespace::Finally::AnotherClassName bar;

you can write:

namespace Shorter = Some::Impossibly::Annoyingly::Long:Name::For::Namespace::Finally;
Shorter::TheClassName foo;
Shorter::AnotherClassName bar;

Hide keyboard in react-native

Keyboard module is used to control keyboard events.

  • import { Keyboard } from 'react-native'
  • Add below code in render method.

    render() { return <TextInput onSubmitEditing={Keyboard.dismiss} />; }

You can use -

Keyboard.dismiss()

static dismiss() Dismisses the active keyboard and removes focus as per react native documents.

How to implement the factory method pattern in C++ correctly

Factory Pattern

class Point
{
public:
  static Point Cartesian(double x, double y);
private:
};

And if you compiler does not support Return Value Optimization, ditch it, it probably does not contain much optimization at all...

MySQL pivot table query with dynamic columns

Here's stored procedure, which will generate the table based on data from one table and column and data from other table and column.

The function 'sum(if(col = value, 1,0)) as value ' is used. You can choose from different functions like MAX(if()) etc.

delimiter //

  create procedure myPivot(
    in tableA varchar(255),
    in columnA varchar(255),
    in tableB varchar(255),
    in columnB varchar(255)
)
begin
  set @sql = NULL;
    set @sql = CONCAT('select group_concat(distinct concat(
            \'SUM(IF(', 
        columnA, 
        ' = \'\'\',',
        columnA,
        ',\'\'\', 1, 0)) AS \'\'\',',
        columnA, 
            ',\'\'\'\') separator \', \') from ',
        tableA, ' into @sql');
    -- select @sql;

    PREPARE stmt FROM @sql;
    EXECUTE stmt;

    DEALLOCATE PREPARE stmt;
    -- select @sql;

    SET @sql = CONCAT('SELECT p.', 
        columnB, 
        ', ', 
        @sql, 
        ' FROM ', tableB, ' p GROUP BY p.',
        columnB,'');

    -- select @sql;

    /* */
    PREPARE stmt FROM @sql;
    EXECUTE stmt;
    /* */
    DEALLOCATE PREPARE stmt;
end//

delimiter ;

How to use @Nullable and @Nonnull annotations more effectively?

Other than your IDE giving you hints when you pass null to methods that expect the argument to not be null, there are further advantages:

This can help your code be more maintainable (since you do not need null checks) and less error-prone.

How to validate GUID is a GUID

Will return the Guid if it is valid Guid, else it will return Guid.Empty

if (!Guid.TryParse(yourGuidString, out yourGuid)){
          yourGuid= Guid.Empty;
}

What is the best (idiomatic) way to check the type of a Python variable?

built-in types in Python have built in names:

>>> s = "hallo"
>>> type(s) is str
True
>>> s = {}
>>> type(s) is dict
True

btw note the is operator. However, type checking (if you want to call it that) is usually done by wrapping a type-specific test in a try-except clause, as it's not so much the type of the variable that's important, but whether you can do a certain something with it or not.

How to check if a database exists in SQL Server?

Actually it's best to use:

IF DB_ID('dms') IS NOT NULL
   --code mine :)
   print 'db exists'

See https://docs.microsoft.com/en-us/sql/t-sql/functions/db-id-transact-sql and note that this does not make sense with the Azure SQL Database.

Android Studio gradle takes too long to build

1) My build time severely increased after i added some new library dependencies to my gradle file, what turned out that i need to use multidex after that. And when i set up multidex correctly then my build times went up to 2-3 minutes. So if you want faster build times, avoid using multidex, and as far as possible, reduce the number of library dependencies.

2) Also you can try enabling "offline work" in android studio, like suggested here, that makes sense. This will not refetch libraries every time you make a build. Perhaps slow connection or proxy/vpn usage with "offline work" disabled may lead to slow build times.

3) google services - as mentioned here, dont use the whole bundle, use only the needed parts of it.

if checkbox is checked, do this

Probably you can go with this code to take actions as the checkbox is checked or unchecked.

$('#chk').on('click',function(){
    if(this.checked==true){
      alert('yes');
    }else{
      alert('no');
    }
});

Android Completely transparent Status Bar?

Just add this line of code to your main java file:

getWindow().setFlags(
    WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,
    WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS
);

HttpServletRequest to complete URL

Combining the results of getRequestURL() and getQueryString() should get you the desired result.

How to add background-image using ngStyle (angular2)?

Looks like your style has been sanitized, to bypass it try using bypassSecurityTrustStyle method from DomSanitizer.

_x000D_
_x000D_
import { Component, OnInit, Input } from '@angular/core';_x000D_
import { DomSanitizer, SafeStyle } from '@angular/platform-browser';_x000D_
_x000D_
@Component({_x000D_
  selector: 'my-component',_x000D_
  templateUrl: './my-component.component.html',_x000D_
  styleUrls: ['./my-component.component.scss']_x000D_
})_x000D_
_x000D_
export class MyComponent implements OnInit {_x000D_
_x000D_
  public backgroundImg: SafeStyle;_x000D_
  @Input() myObject: any;_x000D_
_x000D_
  constructor(private sanitizer: DomSanitizer) {}_x000D_
_x000D_
  ngOnInit() {_x000D_
     this.backgroundImg = this.sanitizer.bypassSecurityTrustStyle('url(' + this.myObject.ImageUrl + ')');_x000D_
  }_x000D_
_x000D_
}
_x000D_
<div *ngIf="backgroundImg.length > 0" [style.background-image]="backgroundImg"></div>
_x000D_
_x000D_
_x000D_

Angular get object from array by Id

CASE - 1

Using array.filter() We can get an array of objects which will match with our condition.
see the working example.

_x000D_
_x000D_
var questions = [
      {id: 1, question: "Do you feel a connection to a higher source and have a sense of comfort knowing that you are part of something greater than yourself?", category: "Spiritual", subs: []},
      {id: 2, question: "Do you feel you are free of unhealthy behavior that impacts your overall well-being?", category: "Habits", subs: []},
      {id: 3, question: "1 Do you feel you have healthy and fulfilling relationships?", category: "Relationships", subs: []},
      {id: 3, question: "2 Do you feel you have healthy and fulfilling relationships?", category: "Relationships", subs: []},
      {id: 3, question: "3 Do you feel you have healthy and fulfilling relationships?", category: "Relationships", subs: []},
      {id: 4, question: "Do you feel you have a sense of purpose and that you have a positive outlook about yourself and life?", category: "Emotional Well-being", subs: []},
      {id: 5, question: "Do you feel you have a healthy diet and that you are fueling your body for optimal health? ", category: "Eating Habits ", subs: []},
      {id: 6, question: "Do you feel that you get enough rest and that your stress level is healthy?", category: "Relaxation ", subs: []},
      {id: 7, question: "Do you feel you get enough physical activity for optimal health?", category: "Exercise ", subs: []},
      {id: 8, question: "Do you feel you practice self-care and go to the doctor regularly?", category: "Medical Maintenance", subs: []},
      {id: 9, question: "Do you feel satisfied with your income and economic stability?", category: "Financial", subs: []},
      {id: 10, question: "1 Do you feel you do fun things and laugh enough in your life?", category: "Play", subs: []},
      {id: 10, question: "2 Do you feel you do fun things and laugh enough in your life?", category: "Play", subs: []},
      {id: 11, question: "Do you feel you have a healthy sense of balance in this area of your life?", category: "Work-life Balance", subs: []},
      {id: 12, question: "Do you feel a sense of peace and contentment  in your home? ", category: "Home Environment", subs: []},
      {id: 13, question: "Do you feel that you are challenged and growing as a person?", category: "Intellectual Wellbeing", subs: []},
      {id: 14, question: "Do you feel content with what you see when you look in the mirror?", category: "Self-image", subs: []},
      {id: 15, question: "Do you feel engaged at work and a sense of fulfillment with your job?", category: "Work Satisfaction", subs: []}
];

function filter(){
  console.clear();
  var filter_id = document.getElementById("filter").value;
  var filter_array = questions.filter(x => x.id == filter_id);
  console.log(filter_array);
}
_x000D_
button {
  background: #0095ff;
  color: white;
  border: none;
  border-radius: 3px;
  padding: 8px;
  cursor: pointer;
}

input {
  padding: 8px;
}
_x000D_
<div>
  <label for="filter"></label>
  <input id="filter" type="number" name="filter" placeholder="Enter id which you want to filter">
  <button onclick="filter()">Filter</button>
</div>
_x000D_
_x000D_
_x000D_

CASE - 2

Using array.find() we can get first matched item and break the iteration.

_x000D_
_x000D_
var questions = [
      {id: 1, question: "Do you feel a connection to a higher source and have a sense of comfort knowing that you are part of something greater than yourself?", category: "Spiritual", subs: []},
      {id: 2, question: "Do you feel you are free of unhealthy behavior that impacts your overall well-being?", category: "Habits", subs: []},
      {id: 3, question: "1 Do you feel you have healthy and fulfilling relationships?", category: "Relationships", subs: []},
      {id: 3, question: "2 Do you feel you have healthy and fulfilling relationships?", category: "Relationships", subs: []},
      {id: 3, question: "3 Do you feel you have healthy and fulfilling relationships?", category: "Relationships", subs: []},
      {id: 4, question: "Do you feel you have a sense of purpose and that you have a positive outlook about yourself and life?", category: "Emotional Well-being", subs: []},
      {id: 5, question: "Do you feel you have a healthy diet and that you are fueling your body for optimal health? ", category: "Eating Habits ", subs: []},
      {id: 6, question: "Do you feel that you get enough rest and that your stress level is healthy?", category: "Relaxation ", subs: []},
      {id: 7, question: "Do you feel you get enough physical activity for optimal health?", category: "Exercise ", subs: []},
      {id: 8, question: "Do you feel you practice self-care and go to the doctor regularly?", category: "Medical Maintenance", subs: []},
      {id: 9, question: "Do you feel satisfied with your income and economic stability?", category: "Financial", subs: []},
      {id: 10, question: "1 Do you feel you do fun things and laugh enough in your life?", category: "Play", subs: []},
      {id: 10, question: "2 Do you feel you do fun things and laugh enough in your life?", category: "Play", subs: []},
      {id: 11, question: "Do you feel you have a healthy sense of balance in this area of your life?", category: "Work-life Balance", subs: []},
      {id: 12, question: "Do you feel a sense of peace and contentment  in your home? ", category: "Home Environment", subs: []},
      {id: 13, question: "Do you feel that you are challenged and growing as a person?", category: "Intellectual Wellbeing", subs: []},
      {id: 14, question: "Do you feel content with what you see when you look in the mirror?", category: "Self-image", subs: []},
      {id: 15, question: "Do you feel engaged at work and a sense of fulfillment with your job?", category: "Work Satisfaction", subs: []}
];

function find(){
  console.clear();
  var find_id = document.getElementById("find").value;
  var find_object = questions.find(x => x.id == find_id);
  console.log(find_object);
}
_x000D_
button {
  background: #0095ff;
  color: white;
  border: none;
  border-radius: 3px;
  padding: 8px;
  cursor: pointer;
}

input {
  padding: 8px;
  width: 200px;
}
_x000D_
<div>
  <label for="find"></label>
  <input id="find" type="number" name="find" placeholder="Enter id which you want to find">
  <button onclick="find()">Find</button>
</div>
_x000D_
_x000D_
_x000D_

plot is not defined

Change that import to

from matplotlib.pyplot import *

Note that this style of imports (from X import *) is generally discouraged. I would recommend using the following instead:

import matplotlib.pyplot as plt
plt.plot([1,2,3,4])