for (var key in data) {
alert("User " + data[key] + " is #" + key); // "User john is #234"
}
CodeIgniter 3
Only:
$this->db->where('archived IS NOT NULL');
The generated query is:
WHERE archived IS NOT NULL;
$this->db->where('archived IS NOT NULL',null,false); << Not necessary
Inverse:
$this->db->where('archived');
The generated query is:
WHERE archived IS NULL;
I've a PHP library which helps to insert array into MySQL Database. By using this you can create update and delete. Your array key value should be same as the table column value. Just using a single line code for the create operation
DB::create($db, 'YOUR_TABLE_NAME', $dataArray);
where $db is your Database connection.
Similarly, You can use this for update and delete. Select operation will be available soon. Github link to download : https://github.com/pairavanvvl/crud
I claim that the obvious way to see whether casting a value changed the value would be to cast and check the result. I would, however, remove the unnecessary cast when comparing. I'm also not too keen on one letter variable names (exception x
and y
, but not when they mean row and column (sometimes respectively)).
public static int intValue(long value) {
int valueInt = (int)value;
if (valueInt != value) {
throw new IllegalArgumentException(
"The long value "+value+" is not within range of the int type"
);
}
return valueInt;
}
However, really I would want to avoid this conversion if at all possible. Obviously sometimes it's not possible, but in those cases IllegalArgumentException
is almost certainly the wrong exception to be throwing as far as client code is concerned.
Try this macro to test the overflow bit of 32-bit machines (adapted the solution of Angel Sinigersky)
#define overflowflag(isOverflow){ \
size_t eflags; \
asm ("pushfl ;" \
"pop %%eax" \
: "=a" (eflags)); \
isOverflow = (eflags >> 11) & 1;}
I defined it as a macro because otherwise the overflow bit would have been overwritten.
Subsequent is a little application with the code segement above:
#include <cstddef>
#include <stdio.h>
#include <iostream>
#include <conio.h>
#if defined( _MSC_VER )
#include <intrin.h>
#include <oskit/x86>
#endif
using namespace std;
#define detectOverflow(isOverflow){ \
size_t eflags; \
asm ("pushfl ;" \
"pop %%eax" \
: "=a" (eflags)); \
isOverflow = (eflags >> 11) & 1;}
int main(int argc, char **argv) {
bool endTest = false;
bool isOverflow;
do {
cout << "Enter two intergers" << endl;
int x = 0;
int y = 0;
cin.clear();
cin >> x >> y;
int z = x * y;
detectOverflow(isOverflow)
printf("\nThe result is: %d", z);
if (!isOverflow) {
std::cout << ": no overflow occured\n" << std::endl;
} else {
std::cout << ": overflow occured\n" << std::endl;
}
z = x * x * y;
detectOverflow(isOverflow)
printf("\nThe result is: %d", z);
if (!isOverflow) {
std::cout << ": no overflow ocurred\n" << std::endl;
} else {
std::cout << ": overflow occured\n" << std::endl;
}
cout << "Do you want to stop? (Enter \"y\" or \"Y)" << endl;
char c = 0;
do {
c = getchar();
} while ((c == '\n') && (c != EOF));
if (c == 'y' || c == 'Y') {
endTest = true;
}
do {
c = getchar();
} while ((c != '\n') && (c != EOF));
} while (!endTest);
}
You need to create another migration file - and place it in there:
Run
Laravel 4: php artisan migrate:make rename_stnk_column
Laravel 5: php artisan make:migration rename_stnk_column
Then inside the new migration file place:
class RenameStnkColumn extends Migration
{
public function up()
{
Schema::table('stnk', function(Blueprint $table) {
$table->renameColumn('id', 'id_stnk');
});
}
public function down()
{
Schema::table('stnk', function(Blueprint $table) {
$table->renameColumn('id_stnk', 'id');
});
}
}
In my case, we had several projects in one solution and had selected a different start project than in the package manager console when running the "Update-Database" Command with Code-First Migrations. Make sure to select the proper start project.
In my case, resetting ADB didn't make a difference. I also needed to delete my existing virtual devices, which were pretty old, and create new ones.
If you look at the 'display' property in the CSS spec, you will see that 'list-item' is specifically a display type. When you set an item to "inline", you're replacing the default display type of list-item, and the marker is specifically a part of the list-item type.
The above answer suggests float, but I've tried that and it doesn't work (at least on Chrome). According to the spec, if you set your boxes to float left or right,"The 'display' is ignored, unless it has the value 'none'." I take this to mean that the default display type of 'list-item' is gone (taking the marker with it) as soon as you float the element.
Edit: Yeah, I guess I was wrong. See top entry. :)
According to http://php.net/manual/en/function.error-get-last.php, use:
print_r(error_get_last());
Which will return an array of the last error generated. You can access the [message]
element to display the error.
You need xlutils.copy
. Try something like this:
from xlutils.copy import copy
w = copy('book1.xls')
w.get_sheet(0).write(0,0,"foo")
w.save('book2.xls')
Keep in mind you can't overwrite cells by default as noted in this question.
For myself, I would assume unsigned int is platform specific. Integer could be 8 bits, 16 bits, 32 bits or even 64 bits.
DWORD in the other hand, specifies its own size, which is Double Word. Word are 16 bits so DWORD will be known as 32 bit across all platform
To filter a list of dicts you can use the selectattr filter together with the equalto test:
network.addresses.private_man | selectattr("type", "equalto", "fixed")
The above requires Jinja2 v2.8 or later (regardless of Ansible version).
Ansible also has the tests match
and search
, which take regular expressions:
match
will require a complete match in the string, whilesearch
will require a match inside of the string.
network.addresses.private_man | selectattr("type", "match", "^fixed$")
To reduce the list of dicts to a list of strings, so you only get a list of the addr
fields, you can use the map filter:
... | map(attribute='addr') | list
Or if you want a comma separated string:
... | map(attribute='addr') | join(',')
Combined, it would look like this.
- debug: msg={{ network.addresses.private_man | selectattr("type", "equalto", "fixed") | map(attribute='addr') | join(',') }}
As an illustration
import fs from 'fs';
import http from 'http';
const options = {
host: 'www.stackoverflow.com',
port: 80,
path: '/index.html'
};
describe('deferredExecution', () => {
it('deferredExecution', (done) => {
console.log('Start');
setTimeout(() => console.log('TO1'), 0);
setImmediate(() => console.log('IM1'));
process.nextTick(() => console.log('NT1'));
setImmediate(() => console.log('IM2'));
process.nextTick(() => console.log('NT2'));
http.get(options, () => console.log('IO1'));
fs.readdir(process.cwd(), () => console.log('IO2'));
setImmediate(() => console.log('IM3'));
process.nextTick(() => console.log('NT3'));
setImmediate(() => console.log('IM4'));
fs.readdir(process.cwd(), () => console.log('IO3'));
console.log('Done');
setTimeout(done, 1500);
});
});
will give the following output
Start
Done
NT1
NT2
NT3
TO1
IO2
IO3
IM1
IM2
IM3
IM4
IO1
I hope this can help to understand the difference.
Updated:
Callbacks deferred with
process.nextTick()
run before any other I/O event is fired, while with setImmediate(), the execution is queued behind any I/O event that is already in the queue.Node.js Design Patterns, by Mario Casciaro (probably the best book about node.js/js)
REVISED - please see Andrew_1510's answer below, as IPython has been updated.
...
It was a bit hard figure out how to get there from a dusty bug report, but:
It ships with IPython now!
import ipy_autoreload
%autoreload 2
%aimport your_mod
# %autoreload? for help
... then every time you call your_mod.dwim()
, it'll pick up the latest version.
You can only send 1 object as a parameter in the body via post. I would change your Post method to
public void Post(ICollection<Product> products)
{
}
and in your angular code you would pass up a product array in JSON notation
In the POSIX standard clock
has its return value defined in terms of the CLOCKS_PER_SEC symbol and an implementation is free to define this in any convenient fashion. Under Linux, I have had good luck with the times()
function.
EOF
is a constant in C. You are not checking the actual file for EOF. You need to do something like this
while(!feof(stdin))
Here is the documentation to feof. You can also check the return value of scanf. It returns the number of successfully converted items, or EOF
if it reaches the end of the file.
Use \0
.
color: green\0;
I however do recommend conditional comments since you'd like to exclude IE9 as well and it's yet unpredictable whether this hack will affect IE9 as well or not.
Regardless, I've never had the need for an IE8 specific hack. What is it, the IE8 specific problem which you'd like to solve? Is it rendering in IE8 standards mode anyway? Its renderer is pretty good.
If you have an array, a
of say 210 rows by 8 columns:
a = numpy.empty([210,8])
and want to add a ninth column of zeros you can do this:
b = numpy.append(a,numpy.zeros([len(a),1]),1)
the articles posted by Ricky are very good, but unfortunately they don't answer your question.
To solve your problem you should try this piece of code:
ExeConfigurationFileMap configMap = new ExeConfigurationFileMap();
configMap.ExeConfigFilename = @"d:\test\justAConfigFile.config.whateverYouLikeExtension";
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(configMap, ConfigurationUserLevel.None);
If need to access a value within the config you can use the index operator:
config.AppSettings.Settings["test"].Value;
The string is basically bounded from the place where it is pointed to (char *ptrChar;
), to the null character (\0
).
The char *ptrChar;
actually points to the beginning of the string (char array), and thus that is the pointer to that string,
so when you do like ptrChar[x]
for example, you actually access the memory location x times after the beginning of the char (aka from where ptrChar is pointing to).
You can make cross domain requests using the XMLHttpRequest
object. This is done using something called "Cross Origin Resource Sharing". See:
http://en.wikipedia.org/wiki/Cross-origin_resource_sharing
Very simply put, when the request is made to the server the server can respond with a Access-Control-Allow-Origin
header which will either allow or deny the request. The browser needs to check this header and if it is allowed then it will continue with the request process. If not the browser will cancel the request.
You can find some more information and a working example here: http://www.leggetter.co.uk/2010/03/12/making-cross-domain-javascript-requests-using-xmlhttprequest-or-xdomainrequest.html
JSONP is an alternative solution, but you could argue it's a bit of a hack.
This code should do the trick:
string strFinalPath = string.Empty;
string normalizedFirstPath = Path1.TrimEnd(new char[] { '\\' });
string normalizedSecondPath = Path2.TrimStart(new char[] { '\\' });
strFinalPath = Path.Combine(normalizedFirstPath, normalizedSecondPath);
return strFinalPath;
Number 7 on the list is Jackson, not using Jerkson. It has support for Scala objects, (case classes etc).
Below is an example of how I use it.
object MyJacksonMapper extends JacksonMapper
val jsonString = MyJacksonMapper.serializeJson(myObject)
val myNewObject = MyJacksonMapper.deserializeJson[MyCaseClass](jsonString)
This makes it very simple. In addition is the XmlSerializer and support for JAXB Annotations is very handy.
This blog post describes it's use with JAXB Annotations and the Play Framework.
http://krasserm.blogspot.co.uk/2012/02/using-jaxb-for-xml-and-json-apis-in.html
Here is my current JacksonMapper.
trait JacksonMapper {
def jsonSerializer = {
val m = new ObjectMapper()
m.registerModule(DefaultScalaModule)
m
}
def xmlSerializer = {
val m = new XmlMapper()
m.registerModule(DefaultScalaModule)
m
}
def deserializeJson[T: Manifest](value: String): T = jsonSerializer.readValue(value, typeReference[T])
def serializeJson(value: Any) = jsonSerializer.writerWithDefaultPrettyPrinter().writeValueAsString(value)
def deserializeXml[T: Manifest](value: String): T = xmlSerializer.readValue(value, typeReference[T])
def serializeXml(value: Any) = xmlSerializer.writeValueAsString(value)
private[this] def typeReference[T: Manifest] = new TypeReference[T] {
override def getType = typeFromManifest(manifest[T])
}
private[this] def typeFromManifest(m: Manifest[_]): Type = {
if (m.typeArguments.isEmpty) { m.erasure }
else new ParameterizedType {
def getRawType = m.erasure
def getActualTypeArguments = m.typeArguments.map(typeFromManifest).toArray
def getOwnerType = null
}
}
}
Any of the following will work:
print 'Hello\nWorld'
print 'Hello'
print 'World'
Additionally, if you want to print a blank line (not make a new line), print
or print()
will work.
You can access the namespace's dictionary with vars():
>>> import argparse
>>> args = argparse.Namespace()
>>> args.foo = 1
>>> args.bar = [1,2,3]
>>> d = vars(args)
>>> d
{'foo': 1, 'bar': [1, 2, 3]}
You can modify the dictionary directly if you wish:
>>> d['baz'] = 'store me'
>>> args.baz
'store me'
Yes, it is okay to access the __dict__ attribute. It is a well-defined, tested, and guaranteed behavior.
My personal opinion is to use what makes sense in the context. Personally I almost never use for
for array traversal. I use it for other types of iteration, but foreach
is just too easy... The time difference is going to be minimal in most cases.
The big thing to watch for is:
for ($i = 0; $i < count($array); $i++) {
That's an expensive loop, since it calls count on every single iteration. So long as you're not doing that, I don't think it really matters...
As for the reference making a difference, PHP uses copy-on-write, so if you don't write to the array, there will be relatively little overhead while looping. However, if you start modifying the array within the array, that's where you'll start seeing differences between them (since one will need to copy the entire array, and the reference can just modify inline)...
As for the iterators, foreach
is equivalent to:
$it->rewind();
while ($it->valid()) {
$key = $it->key(); // If using the $key => $value syntax
$value = $it->current();
// Contents of loop in here
$it->next();
}
As far as there being faster ways to iterate, it really depends on the problem. But I really need to ask, why? I understand wanting to make things more efficient, but I think you're wasting your time for a micro-optimization. Remember, Premature Optimization Is The Root Of All Evil
...
Edit: Based upon the comment, I decided to do a quick benchmark run...
$a = array();
for ($i = 0; $i < 10000; $i++) {
$a[] = $i;
}
$start = microtime(true);
foreach ($a as $k => $v) {
$a[$k] = $v + 1;
}
echo "Completed in ", microtime(true) - $start, " Seconds\n";
$start = microtime(true);
foreach ($a as $k => &$v) {
$v = $v + 1;
}
echo "Completed in ", microtime(true) - $start, " Seconds\n";
$start = microtime(true);
foreach ($a as $k => $v) {}
echo "Completed in ", microtime(true) - $start, " Seconds\n";
$start = microtime(true);
foreach ($a as $k => &$v) {}
echo "Completed in ", microtime(true) - $start, " Seconds\n";
And the results:
Completed in 0.0073502063751221 Seconds
Completed in 0.0019769668579102 Seconds
Completed in 0.0011849403381348 Seconds
Completed in 0.00111985206604 Seconds
So if you're modifying the array in the loop, it's several times faster to use references...
And the overhead for just the reference is actually less than copying the array (this is on 5.3.2)... So it appears (on 5.3.2 at least) as if references are significantly faster...
If it's not vb you can use 

(ascii codes for cr,lf)
hi how to delete from datagridview
1.make query delete by id
2.type
tabletableadaptor.delete
query(datagridwiewX1.selectedrows[0].cell[0].value.tostring);
This is the PHP ternary operator (also known as a conditional operator) - if first operand evaluates true, evaluate as second operand, else evaluate as third operand.
Think of it as an "if" statement you can use in expressions. Can be very useful in making concise assignments that depend on some condition, e.g.
$param = isset($_GET['param']) ? $_GET['param'] : 'default';
There's also a shorthand version of this (in PHP 5.3 onwards). You can leave out the middle operand. The operator will evaluate as the first operand if it true, and the third operand otherwise. For example:
$result = $x ?: 'default';
It is worth mentioning that the above code when using i.e. $_GET or $_POST variable will throw undefined index notice and to prevent that we need to use a longer version, with isset
or a null coalescing operator which is introduced in PHP7:
$param = $_GET['param'] ?? 'default';
Well, actually, React is not suitable for calling child methods from the parent. Some frameworks, like Cycle.js, allow easily access data both from parent and child, and react to it.
Also, there is a good chance you don't really need it. Consider calling it into existing component, it is much more independent solution. But sometimes you still need it, and then you have few choices:
UPD: if you need to share some functionality which doesn't involve any state (like static functions in OOP), then there is no need to contain it inside components. Just declare it separately and invoke when need:
let counter = 0;
function handleInstantiate() {
counter++;
}
constructor(props) {
super(props);
handleInstantiate();
}
Use .is(':checked')
to determine whether or not it's checked, and then set your value accordingly.
For my it was the xdebug. I disabled and it worked as it should be !
[XDebug]
zend_extension = C:\xampp\php\ext\php_xdebug-2.3.2-5.6-vc11.dll
<% String s="Hi"; %>
var v ="<%=s%>";
If you don't want add the /s
regex modifier (perhaps you still want .
to retain its original meaning elsewhere in the regex), you may also use a character class. One possibility:
[\S\s]
a character which is not a space or is a space. In other words, any character.
You can also change modifiers locally in a small part of the regex, like so:
(?s:.)
grep -n "YOUR SEARCH STRING" * > output-file
The -n
will print the line number and the >
will redirect grep-results to the output-file.
If you want to "clean" the results you can filter them using pipe |
for example:
grep -n "test" * | grep -v "mytest" > output-file
will match all the lines that have the string "test" except the lines that match the string "mytest" (that's the switch -v
) - and will redirect the result to an output file.
A few good grep-tips can be found on this post
"(SqlConnection)context"
-- This type-casting no longer works. You can do: "SqlConnection context;
".AsSqlServer()"
-- Does not Exist.
"command.ExecuteNonQuery();"
-- Does not return results. reader=command.ExecuteReader()
does work.
With dt.load(reader)... then you have to switch the framework out of 5.0 and back to 4.51, as 5.0 does not support datatables/datasets, yet. Note: This is VS2015 RC.
i am using this code:
select * from tweets where placeID = '$placeID' and id > (
(select count(*) from tweets where placeID = '$placeID')-2)
In case Chrome tells you "This can only be added from the Chrome Web Store", you can try the following:
For me when I run git clone, Git will store the cloned package in the directory that I am running the command from.
- I use windows.
for example :
C:\Users\user>git clone https://github.com/broosaction/aria
will create a folder:
C:\Users\user\aria
Most memory profilers slow my large complex Windows application to the point where the results are useless. There is one tool that works well for finding leaks in my application: UMDH - http://msdn.microsoft.com/en-us/library/ff560206%28VS.85%29.aspx
Setting the src
of a newly created iframe
in javascript does not trigger the HTML parser until the element is inserted into the document. The HTML is then updated and the HTML parser will be invoked and process the attribute as expected.
var iframe = document.createElement('iframe');
var html = '<body>Foo</body>';
iframe.src = 'data:text/html;charset=utf-8,' + encodeURI(html);
document.body.appendChild(iframe);
console.log('iframe.contentWindow =', iframe.contentWindow);
Also this answer your question it's important to note that this approach has compatibility issues with some browsers, please see the answer of @mschr for a cross-browser solution.
:: Sets environment variables for both the current `cmd` window
:: and/or other applications going forward.
:: I call this file keyz.cmd to be able to just type `keyz` at the prompt
:: after changes because the word `keys` is already taken in Windows.
@echo off
:: set for the current window
set APCA_API_KEY_ID=key_id
set APCA_API_SECRET_KEY=secret_key
set APCA_API_BASE_URL=https://paper-api.alpaca.markets
:: setx also for other windows and processes going forward
setx APCA_API_KEY_ID %APCA_API_KEY_ID%
setx APCA_API_SECRET_KEY %APCA_API_SECRET_KEY%
setx APCA_API_BASE_URL %APCA_API_BASE_URL%
:: Displaying what was just set.
set apca
:: Or for copy/paste manually ...
:: setx APCA_API_KEY_ID 'key_id'
:: setx APCA_API_SECRET_KEY 'secret_key'
:: setx APCA_API_BASE_URL 'https://paper-api.alpaca.markets'
I just solved this problem within my project. Turned out my connection string had a typo and differed from the valid database auth. credentials. Dumb mistake on my part, hopefully somebody else saves time by reading this.
I had a similar Problem as @CraigWalker on debian: My database was in a state where a DROP TABLE
failed because it couldn't find the table, but a CREATE TABLE
also failed because MySQL thought the table still existed. So the broken table still existed somewhere although it wasn't there when I looked in phpmyadmin.
I created this state by just copying the whole folder that contained a database with some MyISAM
and some InnoDB
tables
cp -a /var/lib/mysql/sometable /var/lib/mysql/test
(this is not recommended!)
All InnoDB tables where not visible in the new database test
in phpmyadmin.
sudo mysqladmin flush-tables
didn't help either.
My solution: I had to delete the new test database with drop database test
and copy it with mysqldump
instead:
mysqldump somedatabase -u username -p -r export.sql
mysql test -u username -p < export.sql
I ran some other question regarding ARIA. But it's content looks more promising for this question. would like to share them
What is ARIA?
If you put effort into making your website accessible to users with a variety of different browsing habits and physical disabilities, you'll likely recognize the role and aria-* attributes. WAI-ARIA (Accessible Rich Internet Applications) is a method of providing ways to define your dynamic web content and applications so that people with disabilities can identify and successfully interact with it. This is done through roles that define the structure of the document or application, or through aria-* attributes defining a widget-role, relationship, state, or property.
ARIA use is recommended in the specifications to make HTML5 applications more accessible. When using semantic HTML5 elements, you should set their corresponding role.
And see this you tube video for ARIA live.
If you are not sure if local db is installed, or not sure which database name you should use to connect to it - try running 'sqllocaldb info' command - it will show you existing localdb databases.
Now, as far as I know, local db should be installed together with Visual Studio 2015. But probably it is not required feature, and if something goes wrong or it cannot be installed for some reason - Visual Studio installation continues still (note that is just my guess). So to be on the safe side don't rely on it will always be installed together with VS.
This problem was created by a regression in a recent release. You can find the pull request that fixes this problem at https://github.com/facebook/react-native-fbsdk/pull/339
That means /usr/local/mysql/bin/mysql is not in the PATH variable..
Either execute /usr/local/mysql/bin/mysql to get your mysql shell,
or type this in your terminal:
PATH=$PATH:/usr/local/mysql/bin
to add that to your PATH variable so you can just run mysql without specifying the path
var svg = d3.select("body")
.append("svg")
.style("width", 200)
.style("height", 100)
Another use case is when you want to replace the other branch with yours in a pull request, for example, lets say that you have a software with features A, B, C in develop.
You are developing with the next version and you:
Removed feature B
Added feature D
In the process, develop just added hotfixes for feature B.
You can merge develop into next, but that can be messy sometimes, but you can also use git reset --soft origin/develop
and create a commit with your changes and the branch is mergeable without conflicts and keep your changes.
It turns out that git reset --soft
is a handy command. I personally use it a lot to squash commits that dont have "completed work" like "WIP" so when I open the pull request, all my commits are understandable.
If you need to download a folder via a Linux command try this out:
$ scp [email protected]:foobar.txt -r /some/local/directory
Sources:
Related Post: How to download a file from server using SSH?
8)
OK, first of all I'm not sure how it works when you create a div using (document.createElement('div'))
, so I might be wrong now, but wouldn't it be possible to use the :target pseudo class selector for this?
If you look at the code below, you can se I've used a link to target the div, but in your case it might be possible to target #new from the script instead and that way make the div fade in without user interaction, or am I thinking wrong?
Here's the code for my example:
HTML
<a href="#new">Click</a>
<div id="new">
Fade in ...
</div>
CSS
#new {
width: 100px;
height: 100px;
border: 1px solid #000000;
opacity: 0;
}
#new:target {
-webkit-transition: opacity 2.0s ease-in;
-moz-transition: opacity 2.0s ease-in;
-o-transition: opacity 2.0s ease-in;
opacity: 1;
}
... and here's a jsFiddle
You can achieve roughly the same effect by saying:
var displayName = user.name || "Anonymous";
If you get this message in RStudio, clicking the 'broomstick' figure "Clear All Plots" in Plots tab and try plot() again.
Moreover Execute the command
graphics.off()
The comparison needs to be evaluated fully inside EL ${ ... }
, not outside.
<c:if test="${values.type eq 'object'}">
As to the docs, those ${}
things are not JSTL, but EL (Expression Language) which is a whole subject at its own. JSTL (as every other JSP taglib) is just utilizing it. You can find some more EL examples here.
<c:if test="#{bean.booleanValue}" />
<c:if test="#{bean.intValue gt 10}" />
<c:if test="#{bean.objectValue eq null}" />
<c:if test="#{bean.stringValue ne 'someValue'}" />
<c:if test="#{not empty bean.collectionValue}" />
<c:if test="#{not bean.booleanValue and bean.intValue ne 0}" />
<c:if test="#{bean.enumValue eq 'ONE' or bean.enumValue eq 'TWO'}" />
By the way, unrelated to the concrete problem, if I guess your intent right, you could also just call Object#getClass()
and then Class#getSimpleName()
instead of adding a custom getter.
<c:forEach items="${list}" var="value">
<c:if test="${value['class'].simpleName eq 'Object'}">
<!-- code here -->
</c:if>
</c:forEeach>
I think, after the inclusion of 'track by', you can use it in ng-options to get what you wanted, like the following
<select ng-model="somethingHere" ng-options="option.name for option in options track by option.value" ></select>
This way of doing it is better because when you want to replace the list of strings with list of objects you will just change this to
<select ng-model="somethingHere" ng-options="object.name for option in options track by object.id" ></select>
where somethingHere is an object with the properties name and id, of course. Please note, 'as' is not used in this way of expressing the ng-options, because it will only set the value and you will not be able to change it when you are using track by
You can take advantage of the 'npm cache' command which downloads the package tarball and unpacks it into the npm cache directory.
The source can then be copied in.
Using ideas gleaned from https://groups.google.com/forum/?fromgroups=#!topic/npm-/mwLuZZkHkfU I came up with the following node script. No warranties, YMMV, etcetera.
var fs = require('fs'),
path = require('path'),
exec = require('child_process').exec,
util = require('util');
var packageFileName = 'package.json';
var modulesDirName = 'node_modules';
var cacheDirectory = process.cwd();
var npmCacheAddMask = 'npm cache add %s@%s; echo %s';
var sourceDirMask = '%s/%s/%s/package';
var targetDirMask = '%s/node_modules/%s';
function deleteFolder(folder) {
if (fs.existsSync(folder)) {
var files = fs.readdirSync(folder);
files.forEach(function(file) {
file = folder + "/" + file;
if (fs.lstatSync(file).isDirectory()) {
deleteFolder(file);
} else {
fs.unlinkSync(file);
}
});
fs.rmdirSync(folder);
}
}
function downloadSource(folder) {
var packageFile = path.join(folder, packageFileName);
if (fs.existsSync(packageFile)) {
var data = fs.readFileSync(packageFile);
var package = JSON.parse(data);
function getVersion(data) {
var version = data.match(/-([^-]+)\.tgz/);
return version[1];
}
var callback = function(error, stdout, stderr) {
var dependency = stdout.trim();
var version = getVersion(stderr);
var sourceDir = util.format(sourceDirMask, cacheDirectory, dependency, version);
var targetDir = util.format(targetDirMask, folder, dependency);
var modulesDir = folder + '/' + modulesDirName;
if (!fs.existsSync(modulesDir)) {
fs.mkdirSync(modulesDir);
}
fs.renameSync(sourceDir, targetDir);
deleteFolder(cacheDirectory + '/' + dependency);
downloadSource(targetDir);
};
for (dependency in package.dependencies) {
var version = package.dependencies[dependency];
exec(util.format(npmCacheAddMask, dependency, version, dependency), callback);
}
}
}
if (!fs.existsSync(path.join(process.cwd(), packageFileName))) {
console.log(util.format("Unable to find file '%s'.", packageFileName));
process.exit();
}
deleteFolder(path.join(process.cwd(), modulesDirName));
process.env.npm_config_cache = cacheDirectory;
downloadSource(process.cwd());
use this in the command line
c:\Program Files\Java\jdk1.6.25\bin>keytool -list -v -keystore c:\you_key_here.key
Add these 4 functions to your project:
public const long BUFFER_SIZE = 4096;
public static void AddFileToZip(string zipFilename, string fileToAdd)
{
using (Package zip = global::System.IO.Packaging.Package.Open(zipFilename, FileMode.OpenOrCreate))
{
string destFilename = ".\\" + Path.GetFileName(fileToAdd);
Uri uri = PackUriHelper.CreatePartUri(new Uri(destFilename, UriKind.Relative));
if (zip.PartExists(uri))
{
zip.DeletePart(uri);
}
PackagePart part = zip.CreatePart(uri, "", CompressionOption.Normal);
using (FileStream fileStream = new FileStream(fileToAdd, FileMode.Open, FileAccess.Read))
{
using (Stream dest = part.GetStream())
{
CopyStream(fileStream, dest);
}
}
}
}
public static void CopyStream(global::System.IO.FileStream inputStream, global::System.IO.Stream outputStream)
{
long bufferSize = inputStream.Length < BUFFER_SIZE ? inputStream.Length : BUFFER_SIZE;
byte[] buffer = new byte[bufferSize];
int bytesRead = 0;
long bytesWritten = 0;
while ((bytesRead = inputStream.Read(buffer, 0, buffer.Length)) != 0)
{
outputStream.Write(buffer, 0, bytesRead);
bytesWritten += bytesRead;
}
}
public static void RemoveFileFromZip(string zipFilename, string fileToRemove)
{
using (Package zip = global::System.IO.Packaging.Package.Open(zipFilename, FileMode.OpenOrCreate))
{
string destFilename = ".\\" + fileToRemove;
Uri uri = PackUriHelper.CreatePartUri(new Uri(destFilename, UriKind.Relative));
if (zip.PartExists(uri))
{
zip.DeletePart(uri);
}
}
}
public static void Remove_Content_Types_FromZip(string zipFileName)
{
string contents;
using (ZipFile zipFile = new ZipFile(File.Open(zipFileName, FileMode.Open)))
{
/*
ZipEntry startPartEntry = zipFile.GetEntry("[Content_Types].xml");
using (StreamReader reader = new StreamReader(zipFile.GetInputStream(startPartEntry)))
{
contents = reader.ReadToEnd();
}
XElement contentTypes = XElement.Parse(contents);
XNamespace xs = contentTypes.GetDefaultNamespace();
XElement newDefExt = new XElement(xs + "Default", new XAttribute("Extension", "sab"), new XAttribute("ContentType", @"application/binary; modeler=Acis; version=18.0.2application/binary; modeler=Acis; version=18.0.2"));
contentTypes.Add(newDefExt);
contentTypes.Save("[Content_Types].xml");
zipFile.BeginUpdate();
zipFile.Add("[Content_Types].xml");
zipFile.CommitUpdate();
File.Delete("[Content_Types].xml");
*/
zipFile.BeginUpdate();
try
{
zipFile.Delete("[Content_Types].xml");
zipFile.CommitUpdate();
}
catch{}
}
}
And use them like this:
foreach (string f in UnitZipList)
{
AddFileToZip(zipFile, f);
System.IO.File.Delete(f);
}
Remove_Content_Types_FromZip(zipFile);
I agree with Greg that the log is the best place to start. We've experienced something similar and the fix was to ensure that admins have full permissions to the registry location HKLM\System\CurrentControlSet\Control\WMI\Security prior to starting the installation. HTH.
Instala grunt de manera global: sudo npm install -g grunt-cli --unsafe-perm=true --allow-root
Try to run grunt.
If you have this message:
Warning:
You need to have Ruby and Sass installed and in your PATH for this task to work.
More info: https://github.com/gruntjs/grunt-contrib-sass
Used --force, continuing.
3.1. Check that you have ruby installed (mac, you should have it): ruby -v
i fixed the problem by reinstalling pip using get-pip.py
.
python get-pip.py
.And pip is fixed and work perfectly.
I think the best way would be using a SimpleDateFormat
object.
DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String dateString = "2014-02-11";
Date dateObject = sdf.parse(dateString); // Handle the ParseException here
You can add mysql connection using PHP file. Below is the example of PHP file.
<?php
$con = mysql_connect('localhost:3306', 'dbusername', 'dbpsw');
mysql_select_db("(dbname)", $con);
$sql="SELECT * FROM table_name";
$result = mysql_query($sql);
echo " <table border='1'>
<tr>
<th>Header of Table name</th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['(database_column_name)'] . "</td>";
echo "<td>" . $row['database_column_name'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysql_close($con);
?> }
If you don't have a modifiable lvalue of an iterator, or it is desired to get a copy of a given iterator (leaving the original one unchanged), then C++11 comes with new helper functions - std::next
/ std::prev
:
std::next(iter, 2); // returns a copy of iter incremented by 2
std::next(std::begin(v), 2); // returns a copy of begin(v) incremented by 2
std::prev(iter, 2); // returns a copy of iter decremented by 2
Add display: block;
and overflow: auto;
to .my-table
. This will simply cut off anything past the 280px
limit you enforced. There's no way to make it "look pretty" with that requirement due to words like pélagosthrough
which are wider than 280px
.
This works for me. Has a nice delayed action going on.
var $mouseX = 0, $mouseY = 0;
var $xp = 0, $yp =0;
$(document).mousemove(function(e){
$mouseX = e.pageX;
$mouseY = e.pageY;
});
var $loop = setInterval(function(){
// change 12 to alter damping higher is slower
$xp += (($mouseX - $xp)/12);
$yp += (($mouseY - $yp)/12);
$("#moving_div").css({left:$xp +'px', top:$yp +'px'});
}, 30);
Nice and simples
One sub and two functions. The sub builds your path and use the functions to check if the path exists and create if not. If the full path exists already, it will just pass on by. This will work on PC, but you will have to check what needs to be modified to work on Mac as well.
'requires reference to Microsoft Scripting Runtime
Sub MakeFolder()
Dim strComp As String, strPart As String, strPath As String
strComp = Range("A1") ' assumes company name in A1
strPart = CleanName(Range("C1")) ' assumes part in C1
strPath = "C:\Images\"
If Not FolderExists(strPath & strComp) Then
'company doesn't exist, so create full path
FolderCreate strPath & strComp & "\" & strPart
Else
'company does exist, but does part folder
If Not FolderExists(strPath & strComp & "\" & strPart) Then
FolderCreate strPath & strComp & "\" & strPart
End If
End If
End Sub
Function FolderCreate(ByVal path As String) As Boolean
FolderCreate = True
Dim fso As New FileSystemObject
If Functions.FolderExists(path) Then
Exit Function
Else
On Error GoTo DeadInTheWater
fso.CreateFolder path ' could there be any error with this, like if the path is really screwed up?
Exit Function
End If
DeadInTheWater:
MsgBox "A folder could not be created for the following path: " & path & ". Check the path name and try again."
FolderCreate = False
Exit Function
End Function
Function FolderExists(ByVal path As String) As Boolean
FolderExists = False
Dim fso As New FileSystemObject
If fso.FolderExists(path) Then FolderExists = True
End Function
Function CleanName(strName as String) as String
'will clean part # name so it can be made into valid folder name
'may need to add more lines to get rid of other characters
CleanName = Replace(strName, "/","")
CleanName = Replace(CleanName, "*","")
etc...
End Function
In my case, I've created a wrapper JS file in which I have the logic to select the correct variables according to my environment, dynamically.
I have these two functions, one it's a wrapper of a simple dotenv functionality, and the other discriminate between environments and set the result to the process.env object.
setEnvVariablesByEnvironment : ()=>{_x000D_
return new Promise((resolve)=>{_x000D_
_x000D_
if (process.env.NODE_ENV === undefined || process.env.NODE_ENV ==='development'){_x000D_
logger.info('Lower / Development environment was detected');_x000D_
_x000D_
environmentManager.getEnvironmentFromEnvFile()_x000D_
.then(envFile => {_x000D_
resolve(envFile);_x000D_
});_x000D_
_x000D_
}else{_x000D_
logger.warn('Production or Stage environment was detected.');_x000D_
resolve({_x000D_
payload: process.env,_x000D_
flag: true,_x000D_
status: 0,_x000D_
log: 'Returned environment variables placed in .env file.'_x000D_
});_x000D_
}_x000D_
_x000D_
_x000D_
});_x000D_
} ,_x000D_
_x000D_
/*_x000D_
Get environment variables from .env file, using dotEnv npm module._x000D_
*/_x000D_
getEnvironmentFromEnvFile: () => {_x000D_
return new Promise((resolve)=>{_x000D_
logger.info('Trying to get configuration of environment variables from .env file');_x000D_
_x000D_
env.config({_x000D_
debug: (process.env.NODE_ENV === undefined || process.env.NODE_ENV === 'development')_x000D_
});_x000D_
_x000D_
resolve({_x000D_
payload: process.env,_x000D_
flag: true,_x000D_
status: 0,_x000D_
log: 'Returned environment variables placed in .env file.'_x000D_
});_x000D_
});_x000D_
},
_x000D_
So, in my server.js file i only added the reference:
const envManager = require('./lib/application/config/environment/environment-manager');
And in my entry-point (server.js), it's just simple as use it.
envManager.setEnvVariablesByEnvironment()
.then(envVariables=>{
process.env= envVariables.payload;
const port = process.env.PORT_EXPOSE;
microService.listen(port, '0.0.0.0' , () =>{
let welcomeMessage = `Micro Service started at ${Date.now()}`;
logger.info(welcomeMessage);
logger.info(`${configuration.about.name} port configured -> : ${port}`);
logger.info(`App Author: ${configuration.about.owner}`);
logger.info(`App Version: ${configuration.about.version}`);
logger.info(`Created by: ${configuration.about.author}`);
});
});
I was getting this Swagger error when I created Version 2 of my api using version headers instead of url versioning. The workaround was to add [Obsolete]
attributes to the Version 1 methods then use SwaggerGeneratorOptions
to ignore the obsolete api methods in Startup
-> ConfigureServices
method.
services.AddSwaggerGen(c =>
{
c.SwaggerGeneratorOptions.IgnoreObsoleteActions = true;
c.SwaggerDoc("v2", new Info { Title = "My API", Version = "v2" });
});
Sort of already answered this in the comments, but just so this question has an answer, the problem was resolved through running:
sudo apt-get install python3-pymysql
Swift 4
var refreshControl: UIRefreshControl!
override func viewDidLoad() {
super.viewDidLoad()
refreshControl = UIRefreshControl()
refreshControl.attributedTitle = NSAttributedString(string: "Pull to refresh")
refreshControl.addTarget(self, action: #selector(refresh), for: .valueChanged)
tableView.addSubview(refreshControl)
}
@objc func refresh(_ sender: Any) {
// your code to reload tableView
}
And you could stop refreshing with:
refreshControl.endRefreshing()
It seems to me that you might be better off with a list rather than using orca1
, orca2
, etc, ... then it would be orca[1]
, orca[2]
, ...
Usually you're making a list of variables differentiated by nothing but a number because that number would be a convenient way to access them later.
orca <- list()
orca[1] <- "Hi"
orca[2] <- 59
Otherwise, assign
is just what you want.
If I understand correct you will have something like this:
<input value="default" id="sth" name="sth" type="hidden">
And to get it you have to write:
@Html.HiddenFor(m => m.sth, new { Value = "default" })
for Strongly-typed view.
There is an OFFSET as well that should do the trick:
SELECT column FROM table
LIMIT 10 OFFSET 10
For a simple semi-transparent background color, the above solutions (CSS3 or bg images) are the best options. However, if you want to do something fancier (e.g. animation, multiple backgrounds, etc.), or if you don't want to rely on CSS3, you can try the “pane technique”:
.pane, .pane > .back, .pane > .cont { display: block; }
.pane {
position: relative;
}
.pane > .back {
position: absolute;
width: 100%; height: 100%;
top: auto; bottom: auto; left: auto; right: auto;
}
.pane > .cont {
position: relative;
z-index: 10;
}
<p class="pane">
<span class="back" style="background-color: green; opacity: 0.6;"></span>
<span class="cont" style="color: white;">Hello world</span>
</p>
The technique works by using two “layers” inside of the outer pane element:
The position: relative
on pane is important; it tells back layer to fit to the pane's size. (If you need the <p>
tag to be absolute, change the pane from a <p>
to a <span>
and wrap all that in a absolutely-position <p>
tag.)
The main advantage this technique has over similar ones listed above is that the pane doesn't have to be a specified size; as coded above, it will fit full-width (normal block-element layout) and only as high as the content. The outer pane element can be sized any way you please, as long as it's rectangular (i.e. inline-block will work; plain-old inline will not).
Also, it gives you a lot of freedom for the background; you're free to put really anything in the back element and have it not affect the flow of content (if you want multiple full-size sub-layers, just make sure they also have position: absolute, width/height: 100%, and top/bottom/left/right: auto).
One variation to allow background inset adjustment (via top/bottom/left/right) and/or background pinning (via removing one of the left/right or top/bottom pairs) is to use the following CSS instead:
.pane > .back {
position: absolute;
width: auto; height: auto;
top: 0px; bottom: 0px; left: 0px; right: 0px;
}
As written, this works in Firefox, Safari, Chrome, IE8+, and Opera, although IE7 and IE6 require extra CSS and expressions, IIRC, and last time I checked, the second CSS variation does not work in Opera.
Things to watch out for:
<div>
s instead of <span>
s to simplify your CSS.A fuller demo, showing off the flexiblity of this technique by using it in tandem with display: inline-block
, and with both auto
& specific width
s/min-height
s:
.pane, .pane > .back, .pane > .cont { display: block; }_x000D_
.pane {_x000D_
position: relative;_x000D_
width: 175px; min-height: 100px;_x000D_
margin: 8px;_x000D_
}_x000D_
_x000D_
.pane > .back {_x000D_
position: absolute; z-index: 1;_x000D_
width: auto; height: auto;_x000D_
top: 8px; bottom: 8px; left: 8px; right: 8px;_x000D_
}_x000D_
_x000D_
.pane > .cont {_x000D_
position: relative; z-index: 10;_x000D_
}_x000D_
_x000D_
.debug_red { background: rgba(255, 0, 0, 0.5); border: 1px solid rgba(255, 0, 0, 0.75); }_x000D_
.debug_green { background: rgba(0, 255, 0, 0.5); border: 1px solid rgba(0, 255, 0, 0.75); }_x000D_
.debug_blue { background: rgba(0, 0, 255, 0.5); border: 1px solid rgba(0, 0, 255, 0.75); }
_x000D_
<p class="pane debug_blue" style="float: left;">_x000D_
<span class="back debug_green"></span>_x000D_
<span class="cont debug_red">_x000D_
Pane content.<br/>_x000D_
Pane content._x000D_
</span>_x000D_
</p>_x000D_
<p class="pane debug_blue" style="float: left;">_x000D_
<span class="back debug_green"></span>_x000D_
<span class="cont debug_red">_x000D_
Pane content.<br/>_x000D_
Pane content.<br/>_x000D_
Pane content.<br/>_x000D_
Pane content.<br/>_x000D_
Pane content.<br/>_x000D_
Pane content.<br/>_x000D_
Pane content.<br/>_x000D_
Pane content.<br/>_x000D_
Pane content._x000D_
</span>_x000D_
</p>_x000D_
<p class="pane debug_blue" style="float: left; display: inline-block; width: auto;">_x000D_
<span class="back debug_green"></span>_x000D_
<span class="cont debug_red">_x000D_
Pane content.<br/>_x000D_
Pane content._x000D_
</span>_x000D_
</p>_x000D_
<p class="pane debug_blue" style="float: left; display: inline-block; width: auto; min-height: auto;">_x000D_
<span class="back debug_green"></span>_x000D_
<span class="cont debug_red">_x000D_
Pane content.<br/>_x000D_
Pane content._x000D_
</span>_x000D_
</p>
_x000D_
And here's a live demo of the technique being used extensively:
Using this,
String s = "03/24/2013 21:54";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm");
try
{
Date date = simpleDateFormat.parse(s);
System.out.println("date : "+simpleDateFormat.format(date));
}
catch (ParseException ex)
{
System.out.println("Exception "+ex);
}
if (typeof(opts.query) !== "function") {
throw "query function not defined for Select2 " + opts.element.attr("id");
}
This is thrown becase query does not exist in options. Internally there is a check maintained which requires either of the following for parameters
So you just need to provide one of these 4 options to select2 and it should work as expected.
In practice, I have found that you need to be a bit careful, especially if you are using a bit of xml repeatedly. Suppose, for example, that you have a table that you wish to create a table row for each entry in a list. You've set up some xml:
In my_table_row.xml
:
<?xml version="1.0" encoding="utf-8"?>
<TableRow xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent" android:id="@+id/myTableRow">
<ImageButton android:src="@android:drawable/ic_menu_delete" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/rowButton"/>
<TextView android:layout_height="wrap_content" android:layout_width="wrap_content" android:textAppearance="?android:attr/textAppearanceMedium" android:text="TextView" android:id="@+id/rowText"></TextView>
</TableRow>
Then you want to create it once per row with some code. It assume that you have defined a parent TableLayout myTable to attach the Rows to.
for (int i=0; i<numRows; i++) {
/*
* 1. Make the row and attach it to myTable. For some reason this doesn't seem
* to return the TableRow as you might expect from the xml, so you need to
* receive the View it returns and then find the TableRow and other items, as
* per step 2.
*/
LayoutInflater inflater = (LayoutInflater)getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflater.inflate(R.layout.my_table_row, myTable, true);
// 2. Get all the things that we need to refer to to alter in any way.
TableRow tr = (TableRow) v.findViewById(R.id.profileTableRow);
ImageButton rowButton = (ImageButton) v.findViewById(R.id.rowButton);
TextView rowText = (TextView) v.findViewById(R.id.rowText);
// 3. Configure them out as you need to
rowText.setText("Text for this row");
rowButton.setId(i); // So that when it is clicked we know which one has been clicked!
rowButton.setOnClickListener(this); // See note below ...
/*
* To ensure that when finding views by id on the next time round this
* loop (or later) gie lots of spurious, unique, ids.
*/
rowText.setId(1000+i);
tr.setId(3000+i);
}
For a clear simple example on handling rowButton.setOnClickListener(this), see Onclicklistener for a programatically created button.
I recommend using Prettier as it's very extensible but still works perfectly out of the box:
1. CMD + Shift + P -> Format Document
or
1. Select the text you want to Prettify
2. CMD + Shift + P -> Format Selection
Properties have values only in objects, not classes.
If you need to store something for all objects of a class, you have to use a global variable. You can hide it by declaring it static
in the implementation file.
You may also consider using specific relations between your objects: you attribute a role of master to a specific object of your class and link others objects to this master. The master will hold the dictionary as a simple property. I think of a tree like the one used for the view hierarchy in Cocoa applications.
Another option is to create an object of a dedicated class that is composed of both your 'class' dictionary and a set of all the objects related to this dictionary. This is something like NSAutoreleasePool
in Cocoa.
char is a primitive type, and it can hold a single character. String is instead a reference type, thus a full-blown object.
Following code truncates a string and will not split words up, and instead discard the word where the truncation occurred. Totally based on Sugar.js source.
function truncateOnWord(str, limit) {
var trimmable = '\u0009\u000A\u000B\u000C\u000D\u0020\u00A0\u1680\u180E\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u2028\u2029\u3000\uFEFF';
var reg = new RegExp('(?=[' + trimmable + '])');
var words = str.split(reg);
var count = 0;
return words.filter(function(word) {
count += word.length;
return count <= limit;
}).join('');
}
I've gotten that error twice:
1) When I wrote:
var app = module('flapperNews', []);
instead of:
var app = angular.module('flapperNews', []);
2) When I copy and pasted some html, and the controller name in the html did not exactly match the controller name in my app.js file, for instance:
index.html:
<script src="app.js"></script>
...
...
<body ng-app="flapperNews" ng-controller="MainCtrl">
app.js:
var app = angular.module('flapperNews', []);
app.controller('MyCtrl', ....
In the html, the controller name is "MainCtrl", and in the js I used the name "MyCtrl".
There is actually an error message embedded in the error url:
Error: [ng:areq] http://errors.angularjs.org/1.3.2/ng/areq?p0=MainCtrl&p1=not%20a%20function%2C%20got%20undefined
Here it is without the hieroglyphics:
MainCtrl not a function got undefined
In other words, "There is no function named MainCtrl. Check your spelling."
Imagine you have a numpy array of integers (it works with other types but you need some slight modification). You can do this:
a = np.array([0, 3, 5])
a_str = ','.join(str(x) for x in a) # '0,3,5'
a2 = np.array([int(x) for x in a_str.split(',')]) # np.array([0, 3, 5])
If you have an array of float, be sure to replace int
by float
in the last line.
You can also use the __repr__()
method, which will have the advantage to work for multi-dimensional arrays:
from numpy import array
numpy.set_printoptions(threshold=numpy.nan)
a = array([[0,3,5],[2,3,4]])
a_str = a.__repr__() # 'array([[0, 3, 5],\n [2, 3, 4]])'
a2 = eval(a_str) # array([[0, 3, 5],
# [2, 3, 4]])
try
$this->load->view('home/home_view',$data);
(and note the " ' " not the " ‘ " that you used)
On Windows you can query the precise state of any port on any network-adapter using: GetExtendedTcpTable
You can filter it to only those related to your process, etc and do as you wish periodically monitoring as needed. This is "an alternative" approach.
You could also duplicate the socket handle and set up an IOCP/Overlapped i/o wait on the socket and monitor it that way as well.
Assuming that your docker container is up and running, you can run commands as:
docker exec mycontainer /bin/sh -c "cmd1;cmd2;...;cmdn"
String path = "C:\\Documents and Settings\\someDir";
path = path.replaceAll("\\\\", "/");
In Windows you should use four backslash but not two.
With a \
before a Class declaration you are calling the root namespace:
$now = \Carbon\Carbon::now()->timestamp;
otherwise it looks for it at the current namespace declared at the beginning of the class. other solution is to use it:
use Carbon\Carbon
$now = Carbon::now()->timestamp;
you can even assign it an alias:
use Carbon\Carbon as Time;
$now = Time::now()->timestamp;
hope it helps.
If there is nothing to lose you could also just delete your fork just go to settings... go to danger zone section below and click delete repository. It will ask you to input the repository name and your password after. After that you just fork the original again.
You must know the source encoding.
string someText = "The quick brown fox jumps over the lazy dog.";
byte[] bytes = Encoding.Unicode.GetBytes(someText);
char[] chars = Encoding.Unicode.GetChars(bytes);
I like Zarembisty's answer. Although, if you want to be more explicit, you can always do:
if len(my_list) == 0:
print "my_list is empty"
Probably unrelated, but consider using Path.Combine
instead of destination_dir + dir.Substring(...)
. From the look of it, your .Substring() will leave a backlash at the beginning, but the helper classes like Path are there for a reason.
It is Widget.ProgressBar.Horizontal
on my phone, if I set android:indeterminate="true"
'''
w write mode
r read mode
a append mode
w+ create file if it doesn't exist and open it in write mode
r+ open for reading and writing. Does not create file.
a+ create file if it doesn't exist and open it in append mode
'''
example:
file_name = 'my_file.txt'
f = open(file_name, 'w+') # open file in write mode
f.write('python rules')
f.close()
I hope this helps. [FYI am using python version 3.6.2]
Check to make sure it is "connected" to a network:
public boolean isNetworkAvailable(Context context) {
ConnectivityManager connectivityManager = ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE));
return connectivityManager.getActiveNetworkInfo() != null && connectivityManager.getActiveNetworkInfo().isConnected();
}
Check to make sure it is "connected" to a internet:
public boolean isInternetAvailable() {
try {
InetAddress address = InetAddress.getByName("www.google.com");
return !address.equals("");
} catch (UnknownHostException e) {
// Log error
}
return false;
}
Permission needed:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
You can rename/remove master on remote, but this will be an issue if lots of people have based their work on the remote master branch and have pulled that branch in their local repo.
That might not be the case here since everyone seems to be working on branch 'seotweaks
'.
In that case you can:
git remote --show may not work.
(Make a git remote show
to check how your remote is declared within your local repo. I will assume 'origin
')
(Regarding GitHub, house9 comments: "I had to do one additional step, click the 'Admin
' button on GitHub and set the 'Default Branch
' to something other than 'master
', then put it back afterwards")
git branch -m master master-old # rename master on local
git push origin :master # delete master on remote
git push origin master-old # create master-old on remote
git checkout -b master seotweaks # create a new local master on top of seotweaks
git push origin master # create master on remote
But again:
reset --hard
their local master to the remote/master branch they will fetch, and forget about their current master.Solution: In order to increase your buffer history on iterm bash terminal you've got two options:
Go to iterm -> Preferences -> Profiles -> Terminal Tab -> Scrollback Buffer (section)
Option 1. select the checkbox Unlimited scrollback
Option 2. type the selected Scrollback lines
numbers you'd like your terminal buffer to cache (See image below)
If the buckets get too full, then we have to look through
a very long linked list.
And that's kind of defeating the point.
So here's an example where I have four buckets.
I have elephant and badger in my HashSet so far.
This is a pretty good situation, right?
Each element has zero or one elements.
Now we put two more elements into our HashSet.
buckets elements
------- -------
0 elephant
1 otter
2 badger
3 cat
This isn't too bad either.
Every bucket only has one element . So if I wanna know, does this contain panda?
I can very quickly look at bucket number 1 and it's not
there and
I known it's not in our collection.
If I wanna know if it contains cat, I look at bucket
number 3,
I find cat, I very quickly know if it's in our
collection.
What if I add koala, well that's not so bad.
buckets elements
------- -------
0 elephant
1 otter -> koala
2 badger
3 cat
Maybe now instead of in bucket number 1 only looking at
one element,
I need to look at two.
But at least I don't have to look at elephant, badger and
cat.
If I'm again looking for panda, it can only be in bucket
number 1 and
I don't have to look at anything other then otter and
koala.
But now I put alligator in bucket number 1 and you can
see maybe where this is going.
That if bucket number 1 keeps getting bigger and bigger and
bigger, then I'm basically having to look through all of
those elements to find
something that should be in bucket number 1.
buckets elements
------- -------
0 elephant
1 otter -> koala ->alligator
2 badger
3 cat
If I start adding strings to other buckets,
right, the problem just gets bigger and bigger in every
single bucket.
How do we stop our buckets from getting too full?
The solution here is that
"the HashSet can automatically
resize the number of buckets."
There's the HashSet realizes that the buckets are getting
too full.
It's losing this advantage of this all of one lookup for
elements.
And it'll just create more buckets(generally twice as before) and
then place the elements into the correct bucket.
So here's our basic HashSet implementation with separate
chaining. Now I'm going to create a "self-resizing HashSet".
This HashSet is going to realize that the buckets are
getting too full and
it needs more buckets.
loadFactor is another field in our HashSet class.
loadFactor represents the average number of elements per
bucket,
above which we want to resize.
loadFactor is a balance between space and time.
If the buckets get too full then we'll resize.
That takes time, of course, but
it may save us time down the road if the buckets are a
little more empty.
Let's see an example.
Here's a HashSet, we've added four elements so far.
Elephant, dog, cat and fish.
buckets elements
------- -------
0
1 elephant
2 cat ->dog
3 fish
4
5
At this point, I've decided that the loadFactor, the
threshold,
the average number of elements per bucket that I'm okay
with, is 0.75.
The number of buckets is buckets.length, which is 6, and
at this point our HashSet has four elements, so the
current size is 4.
We'll resize our HashSet, that is we'll add more buckets,
when the average number of elements per bucket exceeds
the loadFactor.
That is when current size divided by buckets.length is
greater than loadFactor.
At this point, the average number of elements per bucket
is 4 divided by 6.
4 elements, 6 buckets, that's 0.67.
That's less than the threshold I set of 0.75 so we're
okay.
We don't need to resize.
But now let's say we add woodchuck.
buckets elements
------- -------
0
1 elephant
2 woodchuck-> cat ->dog
3 fish
4
5
Woodchuck would end up in bucket number 3.
At this point, the currentSize is 5.
And now the average number of elements per bucket
is the currentSize divided by buckets.length.
That's 5 elements divided by 6 buckets is 0.83.
And this exceeds the loadFactor which was 0.75.
In order to address this problem, in order to make the
buckets perhaps a little
more empty so that operations like determining whether a
bucket contains
an element will be a little less complex, I wanna resize
my HashSet.
Resizing the HashSet takes two steps.
First I'll double the number of buckets, I had 6 buckets,
now I'm going to have 12 buckets.
Note here that the loadFactor which I set to 0.75 stays the same.
But the number of buckets changed is 12,
the number of elements stayed the same, is 5.
5 divided by 12 is around 0.42, that's well under our
loadFactor,
so we're okay now.
But we're not done because some of these elements are in
the wrong bucket now.
For instance, elephant.
Elephant was in bucket number 2 because the number of
characters in elephant
was 8.
We have 6 buckets, 8 minus 6 is 2.
That's why it ended up in number 2.
But now that we have 12 buckets, 8 mod 12 is 8, so
elephant does not belong in bucket number 2 anymore.
Elephant belongs in bucket number 8.
What about woodchuck?
Woodchuck was the one that started this whole problem.
Woodchuck ended up in bucket number 3.
Because 9 mod 6 is 3.
But now we do 9 mod 12.
9 mod 12 is 9, woodchuck goes to bucket number 9.
And you see the advantage of all this.
Now bucket number 3 only has two elements whereas before it had 3.
So here's our code,
where we had our HashSet with separate chaining that
didn't do any resizing.
Now, here's a new implementation where we use resizing.
Most of this code is the same,
we're still going to determine whether it contains the
value already.
If it doesn't, then we'll figure it out which bucket it
should go into and
then add it to that bucket, add it to that LinkedList.
But now we increment the currentSize field.
currentSize was the field that kept track of the number
of elements in our HashSet.
We're going to increment it and then we're going to look
at the average load,
the average number of elements per bucket.
We'll do that division down here.
We have to do a little bit of casting here to make sure
that we get a double.
And then, we'll compare that average load to the field
that I've set as
0.75 when I created this HashSet, for instance, which was
the loadFactor.
If the average load is greater than the loadFactor,
that means there's too many elements per bucket on
average, and I need to reinsert.
So here's our implementation of the method to reinsert
all the elements.
First, I'll create a local variable called oldBuckets.
Which is referring to the buckets as they currently stand
before I start resizing everything.
Note I'm not creating a new array of linked lists just yet.
I'm just renaming buckets as oldBuckets.
Now remember buckets was a field in our class, I'm going
to now create a new array
of linked lists but this will have twice as many elements
as it did the first time.
Now I need to actually do the reinserting,
I'm going to iterate through all of the old buckets.
Each element in oldBuckets is a LinkedList of strings
that is a bucket.
I'll go through that bucket and get each element in that
bucket.
And now I'm gonna reinsert it into the newBuckets.
I will get its hashCode.
I will figure out which index it is.
And now I get the new bucket, the new LinkedList of
strings and
I'll add it to that new bucket.
So to recap, HashSets as we've seen are arrays of Linked
Lists, or buckets.
A self resizing HashSet can realize using some ratio or
I tried find similiar as topic first post.
For my needs I find this
http://answers.oreilly.com/topic/217-how-to-match-whole-words-with-a-regular-expression/
"\b[a-zA-Z0-9]{3}\b"
3 char words only "iokldöajf asd alkjwnkmd asd kja wwda da aij ednm <.jkakla "
As of BS3 there's a .center-block
helper class. From the docs:
// Classes
.center-block {
display: block;
margin-left: auto;
margin-right: auto;
}
// Usage as mixins
.element {
.center-block();
}
There is hidden complexity in this seemingly simple problem. All the answers given have some issues.
Create .col-centred
class, but there is a major gotcha.
.col-centred {
float: none !important;
margin: 0 auto;
}
<!-- Bootstrap 3 -->
<div class="col-lg-6 col-centred">
Centred content.
</div>
<!-- Bootstrap 2 -->
<div class="span-6 col-centred">
Centred content.
</div>
The Gotcha
Bootstrap requires columns add up to 12. If they do not they will overlap, which is a problem. In this case the centred column will overlap the column above it. Visually the page may look the same, but mouse events will not work on the column being overlapped (you can't hover or click links, for example). This is because mouse events are registering on the centred column that's overlapping the elements you try to click.
The Fixes
You can resolve this issue by using a clearfix
element. Using z-index
to bring the centred column to the bottom will not work because it will be overlapped itself, and consequently mouse events will work on it.
<div class="row">
<div class="col-lg-12">
I get overlapped by `col-lg-7 centered` unless there's a clearfix.
</div>
<div class="clearfix"></div>
<div class="col-lg-7 centred">
</div>
</div>
Or you can isolate the centred column in its own row.
<div class="row">
<div class="col-lg-12">
</div>
</div>
<div class="row">
<div class="col-lg-7 centred">
Look I am in my own row.
</div>
</div>
<!-- Bootstrap 3 -->
<div class="col-lg-6 col-lg-offset-3">
Centred content.
</div>
<!-- Bootstrap 2 -->
<div class="span-6 span-offset-3">
Centred content.
</div>
The first problem is that your centred column must be an even number because the offset value must divide evenly by 2 for the layout to be centered (left/right).
Secondly, as some have commented, using offsets is a bad idea. This is because when the browser resizes the offset will turn into blank space, pushing the actual content down the page.
This is the best solution in my opinion. No hacking required and you don't mess around with the grid, which could cause unintended consequences, as per solutions 1 and 2.
.col-centred {
margin: 0 auto;
}
<div class="row">
<div class="col-lg-12">
<div class="centred">
Look I am in my own row.
</div>
</div>
</div>
Since, nobody seem to mention this apart myself. My own solution to the above problem is most often to make sure to disable the cached copy by using: pip install <package> --no-cache-dir
.
To execute your command directly from within C#, you would use the SqlCommand class.
Quick sample code using paramaterized SQL (to avoid injection attacks) might look like this:
string queryString = "SELECT tPatCulIntPatIDPk, tPatSFirstname, tPatSName, tPatDBirthday FROM [dbo].[TPatientRaw] WHERE tPatSName = @tPatSName";
string connectionString = "Server=.\PDATA_SQLEXPRESS;Database=;User Id=sa;Password=2BeChanged!;";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(queryString, connection);
command.Parameters.AddWithValue("@tPatSName", "Your-Parm-Value");
connection.Open();
SqlDataReader reader = command.ExecuteReader();
try
{
while (reader.Read())
{
Console.WriteLine(String.Format("{0}, {1}",
reader["tPatCulIntPatIDPk"], reader["tPatSFirstname"]));// etc
}
}
finally
{
// Always call Close when done reading.
reader.Close();
}
}
This code snippet will auto size all the columns that contain data in all the sheets. There is no need to use the activeSheet getter and setter.
// In my case this line didn't make much of a difference
PHPExcel_Shared_Font::setAutoSizeMethod(PHPExcel_Shared_Font::AUTOSIZE_METHOD_EXACT);
// Iterating all the sheets
/** @var PHPExcel_Worksheet $sheet */
foreach ($objPHPExcel->getAllSheets() as $sheet) {
// Iterating through all the columns
// The after Z column problem is solved by using numeric columns; thanks to the columnIndexFromString method
for ($col = 0; $col <= PHPExcel_Cell::columnIndexFromString($sheet->getHighestDataColumn()); $col++) {
$sheet->getColumnDimensionByColumn($col)->setAutoSize(true);
}
}
Just create a new branch with git checkout -b ABC_1
; your uncommitted changes will be kept, and you then commit them to that branch.
See this answer: there is in Ruby 1.9.2, but not in earlier versions. Personally I think rand(8) + 3 is fine, but if you're interested check out the Random class described in the link.
You'll need to do a matrix transform as follows:
filter: progid:DXImageTransform.Microsoft.Matrix(
M11 = COS_THETA,
M12 = -SIN_THETA,
M21 = SIN_THETA,
M22 = COS_THETA,
sizingMethod = 'auto expand'
);
-ms-filter: "progid:DXImageTransform.Microsoft.Matrix(
M11 = COS_THETA,
M12 = -SIN_THETA,
M21 = SIN_THETA,
M22 = COS_THETA,
SizingMethod = 'auto expand'
)";
Where COS_THETA and SIN_THETA are the cosine and sine values of the angle (i.e. 0.70710678
for 45°).
A leading slash indicates that the ignore entry is only to be valid with respect to the directory in which the .gitignore file resides. Specifying *.o
would ignore all .o files in this directory and all subdirs, while /*.o
would just ignore them in that dir, while again, /foo/*.o
would only ignore them in /foo/*.o.
Tried many method above and adding forward slash /
to the end of key name, to create directory didn't work for me:
client.put_object(Bucket="foo-bucket", Key="test-folder/")
You have to supply Body
parameter in order to create directory:
client.put_object(Bucket='foo-bucket',Body='', Key='test-folder/')
Source: ryantuck in boto3 issue
You can switch to shell mode temporarily by:
:! <command>
such as
:! ls
All the above-mentioned code did not work for me. When I dig into the problem I realize that it was not working because I'd placed the style after the href. When I placed the style before the href it was working as expected.
<a style="text-decoration:none" href="http://yoursite.com/">yoursite</a>
I find this library helpful. 3.128 kb of pure convenience.
add script
<script src="/path/to/jquery.cookie.js"></script>
set cookie
$.cookie('name', 'value');
read cookie
$.cookie('name');
I just put the content in the question in a file called test.php
and ran php test.php
.
(In the folder where the test.php
is.)
$ php foo.php
15
What is the difference?
From the documentation:
- - (Boolean)
instance_of?(class)
- Returns
true
ifobj
is an instance of the given class.
and:
- - (Boolean)
is_a?(class)
- (Boolean)kind_of?(class)
- Returns
true
ifclass
is the class ofobj
, or ifclass
is one of the superclasses ofobj
or modules included inobj
.
If that is unclear, it would be nice to know what exactly is unclear, so that the documentation can be improved.
When should I use which?
Never. Use polymorphism instead.
Why are there so many of them?
I wouldn't call two "many". There are two of them, because they do two different things.
From the answer here, spark.sql.shuffle.partitions
configures the number of partitions that are used when shuffling data for joins or aggregations.
spark.default.parallelism
is the default number of partitions in RDD
s returned by transformations like join
, reduceByKey
, and parallelize
when not set explicitly by the user. Note that spark.default.parallelism
seems to only be working for raw RDD
and is ignored when working with dataframes.
If the task you are performing is not a join or aggregation and you are working with dataframes then setting these will not have any effect. You could, however, set the number of partitions yourself by calling df.repartition(numOfPartitions)
(don't forget to assign it to a new val
) in your code.
To change the settings in your code you can simply do:
sqlContext.setConf("spark.sql.shuffle.partitions", "300")
sqlContext.setConf("spark.default.parallelism", "300")
Alternatively, you can make the change when submitting the job to a cluster with spark-submit
:
./bin/spark-submit --conf spark.sql.shuffle.partitions=300 --conf spark.default.parallelism=300
When you say "copy the contents of a variable", does that variable contain a file name, or does it contain a name of a file?
I'm assuming by your question that $var
contains the contents you want to copy into the file:
$ echo "$var" > "$destdir"
This will echo the value of $var into a file called $destdir. Note the quotes. Very important to have "$var" enclosed in quotes. Also for "$destdir" if there's a space in the name. To append it:
$ echo "$var" >> "$destdir"
TF2.0
I see great answers for saving models using TF1.x. I want to provide couple of more pointers in saving tensorflow.keras
models which is a little complicated as there are many ways to save a model.
Here I am providing an example of saving a tensorflow.keras
model to model_path
folder under current directory. This works well with most recent tensorflow (TF2.0). I will update this description if there is any change in near future.
import tensorflow as tf
from tensorflow import keras
mnist = tf.keras.datasets.mnist
#import data
(x_train, y_train),(x_test, y_test) = mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0
# create a model
def create_model():
model = tf.keras.models.Sequential([
tf.keras.layers.Flatten(input_shape=(28, 28)),
tf.keras.layers.Dense(512, activation=tf.nn.relu),
tf.keras.layers.Dropout(0.2),
tf.keras.layers.Dense(10, activation=tf.nn.softmax)
])
# compile the model
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
return model
# Create a basic model instance
model=create_model()
model.fit(x_train, y_train, epochs=1)
loss, acc = model.evaluate(x_test, y_test,verbose=1)
print("Original model, accuracy: {:5.2f}%".format(100*acc))
# Save entire model to a HDF5 file
model.save('./model_path/my_model.h5')
# Recreate the exact same model, including weights and optimizer.
new_model = keras.models.load_model('./model_path/my_model.h5')
loss, acc = new_model.evaluate(x_test, y_test)
print("Restored model, accuracy: {:5.2f}%".format(100*acc))
If you are interested in saving model weights only and then load weights to restore the model, then
model.fit(x_train, y_train, epochs=5)
loss, acc = model.evaluate(x_test, y_test,verbose=1)
print("Original model, accuracy: {:5.2f}%".format(100*acc))
# Save the weights
model.save_weights('./checkpoints/my_checkpoint')
# Restore the weights
model = create_model()
model.load_weights('./checkpoints/my_checkpoint')
loss,acc = model.evaluate(x_test, y_test)
print("Restored model, accuracy: {:5.2f}%".format(100*acc))
# include the epoch in the file name. (uses `str.format`)
checkpoint_path = "training_2/cp-{epoch:04d}.ckpt"
checkpoint_dir = os.path.dirname(checkpoint_path)
cp_callback = tf.keras.callbacks.ModelCheckpoint(
checkpoint_path, verbose=1, save_weights_only=True,
# Save weights, every 5-epochs.
period=5)
model = create_model()
model.save_weights(checkpoint_path.format(epoch=0))
model.fit(train_images, train_labels,
epochs = 50, callbacks = [cp_callback],
validation_data = (test_images,test_labels),
verbose=0)
latest = tf.train.latest_checkpoint(checkpoint_dir)
new_model = create_model()
new_model.load_weights(latest)
loss, acc = new_model.evaluate(test_images, test_labels)
print("Restored model, accuracy: {:5.2f}%".format(100*acc))
import tensorflow as tf
from tensorflow import keras
mnist = tf.keras.datasets.mnist
(x_train, y_train),(x_test, y_test) = mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0
# Custom Loss1 (for example)
@tf.function()
def customLoss1(yTrue,yPred):
return tf.reduce_mean(yTrue-yPred)
# Custom Loss2 (for example)
@tf.function()
def customLoss2(yTrue, yPred):
return tf.reduce_mean(tf.square(tf.subtract(yTrue,yPred)))
def create_model():
model = tf.keras.models.Sequential([
tf.keras.layers.Flatten(input_shape=(28, 28)),
tf.keras.layers.Dense(512, activation=tf.nn.relu),
tf.keras.layers.Dropout(0.2),
tf.keras.layers.Dense(10, activation=tf.nn.softmax)
])
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy', customLoss1, customLoss2])
return model
# Create a basic model instance
model=create_model()
# Fit and evaluate model
model.fit(x_train, y_train, epochs=1)
loss, acc,loss1, loss2 = model.evaluate(x_test, y_test,verbose=1)
print("Original model, accuracy: {:5.2f}%".format(100*acc))
model.save("./model.h5")
new_model=tf.keras.models.load_model("./model.h5",custom_objects={'customLoss1':customLoss1,'customLoss2':customLoss2})
When we have custom ops as in the following case (tf.tile
), we need to create a function and wrap with a Lambda layer. Otherwise, model cannot be saved.
import numpy as np
import tensorflow as tf
from tensorflow.keras.layers import Input, Lambda
from tensorflow.keras import Model
def my_fun(a):
out = tf.tile(a, (1, tf.shape(a)[0]))
return out
a = Input(shape=(10,))
#out = tf.tile(a, (1, tf.shape(a)[0]))
out = Lambda(lambda x : my_fun(x))(a)
model = Model(a, out)
x = np.zeros((50,10), dtype=np.float32)
print(model(x).numpy())
model.save('my_model.h5')
#load the model
new_model=tf.keras.models.load_model("my_model.h5")
I think I have covered a few of the many ways of saving tf.keras model. However, there are many other ways. Please comment below if you see your use case is not covered above. Thanks!
Use count(d.ertek)
or count(d.id)
instead of count(d)
. This can be happen when you have composite primary key at your entity.
Value of %TEMP%
environment variable is often user-specific and Windows sets it up with regard to currently logged in user account. Some user accounts may have no user profile, for example when your process runs as a service on SYSTEM
, LOCALSYSTEM
or other built-in account, or is invoked by IIS application with AppPool identity with Create user profile option disabled. So even when you do not overwrite %TEMP%
variable explicitly, Windows may use c:\temp
or even c:\windows\temp
folders for, lets say, non-usual user accounts. And what's more important, process might have no access rights to this directory!
I think the NOBR tag might be overkill, and as you said, unreliable.
There are 2 options available depending on how you are displaying the text.
If you are displaying text in a table cell you would do Long Text Here. If you are using a div or a span, you can use the style="white-space: nowrap;"
Easy way:
Open the file bootstrap-datepicker.js
Go to line 1399 and find format: 'mm/dd/yyyy'
.
Now you can change the date format here.
Here is the code I've been using for programatically importing .cer files into a new KeyStore.
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
//VERY IMPORTANT. SOME OF THESE EXIST IN MORE THAN ONE PACKAGE!
import java.security.GeneralSecurityException;
import java.security.KeyStore;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
//Put everything after here in your function.
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
trustStore.load(null);//Make an empty store
InputStream fis = /* insert your file path here */;
BufferedInputStream bis = new BufferedInputStream(fis);
CertificateFactory cf = CertificateFactory.getInstance("X.509");
while (bis.available() > 0) {
Certificate cert = cf.generateCertificate(bis);
trustStore.setCertificateEntry("fiddler"+bis.available(), cert);
}
console.log('Hello, \n' +
'Text under your Header\n' +
'-------------------------\n' +
'More Text\n' +
'Moree Text\n' +
'Moooooer Text\n' );
This works great for me for text only, and easy on the eye.
I found this to be a lot easier
from dateutil import relativedelta
relativedelta.relativedelta(end_time,start_time).seconds
I just edited my iPhone's 'hosts' file successfully (on Jailbroken iOS 4.0).
simophone.local
]root
alpine
/etc/hosts
fileThe phone does cache some webpages and DNS queries, so a reboot or clearing the cache may help. Hope that helps someone.
Simon.
git tag --sort=committerdate | tail -1
Sets pattern validation error key if the ngModel $viewValue does not match a RegExp found by evaluating the Angular expression given in the attribute value. If the expression evaluates to a RegExp object, then this is used directly. If the expression evaluates to a string, then it will be converted to a RegExp after wrapping it in ^ and $ characters.
It seems that a most voted answer in this question should be updated, because when i try it, it does not apply test
function and validation not working.
Example from Angular docs works good for me:
Modifying built-in validators
html
<form name="form" class="css-form" novalidate>
<div>
Overwritten Email:
<input type="email" ng-model="myEmail" overwrite-email name="overwrittenEmail" />
<span ng-show="form.overwrittenEmail.$error.email">This email format is invalid!</span><br>
Model: {{myEmail}}
</div>
</form>
js
var app = angular.module('form-example-modify-validators', []);
app.directive('overwriteEmail', function() {
var EMAIL_REGEXP = /^[a-z0-9!#$%&'*+/=?^_`{|}~.-]+@example\.com$/i;
return {
require: 'ngModel',
restrict: '',
link: function(scope, elm, attrs, ctrl) {
// only apply the validator if ngModel is present and Angular has added the email validator
if (ctrl && ctrl.$validators.email) {
// this will overwrite the default Angular email validator
ctrl.$validators.email = function(modelValue) {
return ctrl.$isEmpty(modelValue) || EMAIL_REGEXP.test(modelValue);
};
}
}
};
});
The servlet container loads the servlet during startup or when the first request is made. The loading of the servlet depends on the attribute "load-on-startup" in "web.xml" file. If the attribute has a positive integer(0 to 128) then the servlet is load with the loading of the container otherwise it loads when the first request comes for service.
When the servlet is loaded once it gets request then it is called "Lazy loading".
For selecting within single quotes use vi'
.
For selecting within parenthesis use vi(
.
If you spawn threads in Application_Start
, they will still be executing in the application pool's AppDomain
.
If an application is idle for some time (meaning that no requests are coming in), or certain other conditions are met, ASP.NET
will recycle the entire AppDomain
.
When that happens, any threads that you started from that AppDomain
, including those from Application_Start
, will be aborted.
Lots more on application pools and recycling in this question: What exactly is Appdomain recycling
If you are trying to run a long-running process within IIS/ASP.NET
, the short answer is usually "Don't". That's what Windows Services are for.
From Microsoft documentation:
PAGEIOLATCH_SH
Occurs when a task is waiting on a latch for a buffer that is in an
I/O
request. The latch request is in Shared mode. Long waits may indicate problems with the disk subsystem.
In practice, this almost always happens due to large scans over big tables. It almost never happens in queries that use indexes efficiently.
If your query is like this:
Select * from <table> where <col1> = <value> order by <PrimaryKey>
, check that you have a composite index on (col1, col_primary_key)
.
If you don't have one, then you'll need either a full INDEX SCAN
if the PRIMARY KEY
is chosen, or a SORT
if an index on col1
is chosen.
Both of them are very disk I/O
consuming operations on large tables.
Line magics are only supported by the IPython command line. They cannot simply be used inside a script, because %something
is not correct Python syntax.
If you want to do this from a script you have to get access to the IPython API and then call the run_line_magic
function.
Instead of %matplotlib inline
, you will have to do something like this in your script:
from IPython import get_ipython
get_ipython().run_line_magic('matplotlib', 'inline')
A similar approach is described in this answer, but it uses the deprecated magic
function.
Note that the script still needs to run in IPython. Under vanilla Python the get_ipython
function returns None
and get_ipython().run_line_magic
will raise an AttributeError
.
While I myself would be waiting here for an answer, I wonder if it can be done via CSS:
@media only screen and (orientation:portrait){
#wrapper {width:1024px}
}
@media only screen and (orientation:landscape){
#wrapper {width:1024px}
}
You need to use a raw string, double your slashes or use forward slashes instead:
r'C:\Users\expoperialed\Desktop\Python'
'C:\\Users\\expoperialed\\Desktop\\Python'
'C:/Users/expoperialed/Desktop/Python'
In regular python strings, the \U
character combination signals a extended Unicode codepoint escape.
You can hit any number of other issues, for any of the recognised escape sequences, such as \a
or \t
or \x
, etc.
You can use the from
and size
parameters to page through all your data. This could be very slow depending on your data and how much is in the index.
http://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-from-size.html
you can achieve vertical aligning with display:table-cell
:
#section1 {
height: 90%;
text-align:center;
display:table;
width:100%;
}
#section1 h1 {display:table-cell; vertical-align:middle}
Update - CSS3
For an alternate way to vertical align, you can use the following css 3 which should be supported in all the latest browsers:
#section1 {
height: 90%;
width:100%;
display:flex;
align-items: center;
justify-content: center;
}
I was trying to use Web Api 2 attribute routing to allow for multiple Get methods, and I had incorporated the helpful suggestions from previous answers, but in the Controller I had only decorated the "special" method (example):
[Route( "special/{id}" )]
public IHttpActionResult GetSomethingSpecial( string id ) {
...without also also placing a [RoutePrefix] at the top of the Controller:
[RoutePrefix("api/values")]
public class ValuesController : ApiController
I was getting errors stating that no Route was found matching the submitted URI. Once I had both the [Route] decorating the method as well as [RoutePrefix] decorating the Controller as a whole, it worked.
<script language="javascript">_x000D_
_x000D_
// Set values to variable_x000D_
var sectionName = "TestSection";_x000D_
var fileMap = "fileMapData";_x000D_
var fileId = "foobar";_x000D_
var fileValue= "foobar.png";_x000D_
var fileId2 = "barfoo";_x000D_
var fileValue2= "barfoo.jpg";_x000D_
_x000D_
// Create top-level image object_x000D_
var images = {};_x000D_
_x000D_
// Create second-level object in images object with_x000D_
// the name of sectionName value_x000D_
images[sectionName] = {};_x000D_
_x000D_
// Create a third level object_x000D_
var fileMapObj = {};_x000D_
_x000D_
// Add the third level object to the second level object_x000D_
images[sectionName][fileMap] = fileMapObj;_x000D_
_x000D_
// Add forth level associate array key and value data_x000D_
images[sectionName][fileMap][fileId] = fileValue;_x000D_
images[sectionName][fileMap][fileId2] = fileValue2;_x000D_
_x000D_
_x000D_
// All variables_x000D_
alert ("Example 1 Value: " + images[sectionName][fileMap][fileId]);_x000D_
_x000D_
// All keys with dots_x000D_
alert ("Example 2 Value: " + images.TestSection.fileMapData.foobar);_x000D_
_x000D_
// Mixed with a different final key_x000D_
alert ("Example 3 Value: " + images[sectionName]['fileMapData'][fileId2]);_x000D_
_x000D_
// Mixed brackets and dots..._x000D_
alert ("Example 4 Value: " + images[sectionName]['fileMapData'].barfoo);_x000D_
_x000D_
// This will FAIL! variable names must be in brackets!_x000D_
alert ("Example 5 Value: " + images[sectionName]['fileMapData'].fileId2);_x000D_
// Produces: "Example 5 Value: undefined"._x000D_
_x000D_
// This will NOT work either. Values must be quoted in brackets._x000D_
alert ("Example 6 Value: " + images[sectionName][fileMapData].barfoo);_x000D_
// Throws and exception and stops execution with error: fileMapData is not defined_x000D_
_x000D_
// We never get here because of the uncaught exception above..._x000D_
alert ("The End!");_x000D_
</script>
_x000D_
Simple solution of how to store login value in by SharedPreferences
.
You can extend the MainActivity
class or other class where you will store the "value of something you want to keep". Put this into writer and reader classes:
public static final String GAME_PREFERENCES_LOGIN = "Login";
Here InputClass
is input and OutputClass
is output class, respectively.
// This is a storage, put this in a class which you can extend or in both classes:
//(input and output)
public static final String GAME_PREFERENCES_LOGIN = "Login";
// String from the text input (can be from anywhere)
String login = inputLogin.getText().toString();
// then to add a value in InputCalss "SAVE",
SharedPreferences example = getSharedPreferences(GAME_PREFERENCES_LOGIN, 0);
Editor editor = example.edit();
editor.putString("value", login);
editor.commit();
Now you can use it somewhere else, like other class. The following is OutputClass
.
SharedPreferences example = getSharedPreferences(GAME_PREFERENCES_LOGIN, 0);
String userString = example.getString("value", "defValue");
// the following will print it out in console
Logger.getLogger("Name of a OutputClass".class.getName()).log(Level.INFO, userString);
Note: there is no guarantee this code will work in future versions of the .Net framework. Using private .Net framework internals as done here through reflection is probably not good overall. Use the interop solution mentioned at the bottom, as the Windows API is less likely to change.
If you are looking for a Folder picker that looks more like the Windows 7 dialog, with the ability to copy and paste from a textbox at the bottom and the navigation pane on the left with favorites and common locations, then you can get access to that in a very lightweight way.
The FolderBrowserDialog UI is very minimal:
But you can have this instead:
Here's a class that opens a Vista-style folder picker using the .Net private IFileDialog
interface, without directly using interop in the code (.Net takes care of that for you). It falls back to the pre-Vista dialog if not in a high enough Windows version. Should work in Windows 7, 8, 9, 10 and higher (theoretically).
using System;
using System.Reflection;
using System.Windows.Forms;
namespace MyCoolCompany.Shuriken {
/// <summary>
/// Present the Windows Vista-style open file dialog to select a folder. Fall back for older Windows Versions
/// </summary>
public class FolderSelectDialog {
private string _initialDirectory;
private string _title;
private string _fileName = "";
public string InitialDirectory {
get { return string.IsNullOrEmpty(_initialDirectory) ? Environment.CurrentDirectory : _initialDirectory; }
set { _initialDirectory = value; }
}
public string Title {
get { return _title ?? "Select a folder"; }
set { _title = value; }
}
public string FileName { get { return _fileName; } }
public bool Show() { return Show(IntPtr.Zero); }
/// <param name="hWndOwner">Handle of the control or window to be the parent of the file dialog</param>
/// <returns>true if the user clicks OK</returns>
public bool Show(IntPtr hWndOwner) {
var result = Environment.OSVersion.Version.Major >= 6
? VistaDialog.Show(hWndOwner, InitialDirectory, Title)
: ShowXpDialog(hWndOwner, InitialDirectory, Title);
_fileName = result.FileName;
return result.Result;
}
private struct ShowDialogResult {
public bool Result { get; set; }
public string FileName { get; set; }
}
private static ShowDialogResult ShowXpDialog(IntPtr ownerHandle, string initialDirectory, string title) {
var folderBrowserDialog = new FolderBrowserDialog {
Description = title,
SelectedPath = initialDirectory,
ShowNewFolderButton = false
};
var dialogResult = new ShowDialogResult();
if (folderBrowserDialog.ShowDialog(new WindowWrapper(ownerHandle)) == DialogResult.OK) {
dialogResult.Result = true;
dialogResult.FileName = folderBrowserDialog.SelectedPath;
}
return dialogResult;
}
private static class VistaDialog {
private const string c_foldersFilter = "Folders|\n";
private const BindingFlags c_flags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
private readonly static Assembly s_windowsFormsAssembly = typeof(FileDialog).Assembly;
private readonly static Type s_iFileDialogType = s_windowsFormsAssembly.GetType("System.Windows.Forms.FileDialogNative+IFileDialog");
private readonly static MethodInfo s_createVistaDialogMethodInfo = typeof(OpenFileDialog).GetMethod("CreateVistaDialog", c_flags);
private readonly static MethodInfo s_onBeforeVistaDialogMethodInfo = typeof(OpenFileDialog).GetMethod("OnBeforeVistaDialog", c_flags);
private readonly static MethodInfo s_getOptionsMethodInfo = typeof(FileDialog).GetMethod("GetOptions", c_flags);
private readonly static MethodInfo s_setOptionsMethodInfo = s_iFileDialogType.GetMethod("SetOptions", c_flags);
private readonly static uint s_fosPickFoldersBitFlag = (uint) s_windowsFormsAssembly
.GetType("System.Windows.Forms.FileDialogNative+FOS")
.GetField("FOS_PICKFOLDERS")
.GetValue(null);
private readonly static ConstructorInfo s_vistaDialogEventsConstructorInfo = s_windowsFormsAssembly
.GetType("System.Windows.Forms.FileDialog+VistaDialogEvents")
.GetConstructor(c_flags, null, new[] { typeof(FileDialog) }, null);
private readonly static MethodInfo s_adviseMethodInfo = s_iFileDialogType.GetMethod("Advise");
private readonly static MethodInfo s_unAdviseMethodInfo = s_iFileDialogType.GetMethod("Unadvise");
private readonly static MethodInfo s_showMethodInfo = s_iFileDialogType.GetMethod("Show");
public static ShowDialogResult Show(IntPtr ownerHandle, string initialDirectory, string title) {
var openFileDialog = new OpenFileDialog {
AddExtension = false,
CheckFileExists = false,
DereferenceLinks = true,
Filter = c_foldersFilter,
InitialDirectory = initialDirectory,
Multiselect = false,
Title = title
};
var iFileDialog = s_createVistaDialogMethodInfo.Invoke(openFileDialog, new object[] { });
s_onBeforeVistaDialogMethodInfo.Invoke(openFileDialog, new[] { iFileDialog });
s_setOptionsMethodInfo.Invoke(iFileDialog, new object[] { (uint) s_getOptionsMethodInfo.Invoke(openFileDialog, new object[] { }) | s_fosPickFoldersBitFlag });
var adviseParametersWithOutputConnectionToken = new[] { s_vistaDialogEventsConstructorInfo.Invoke(new object[] { openFileDialog }), 0U };
s_adviseMethodInfo.Invoke(iFileDialog, adviseParametersWithOutputConnectionToken);
try {
int retVal = (int) s_showMethodInfo.Invoke(iFileDialog, new object[] { ownerHandle });
return new ShowDialogResult {
Result = retVal == 0,
FileName = openFileDialog.FileName
};
}
finally {
s_unAdviseMethodInfo.Invoke(iFileDialog, new[] { adviseParametersWithOutputConnectionToken[1] });
}
}
}
// Wrap an IWin32Window around an IntPtr
private class WindowWrapper : IWin32Window {
private readonly IntPtr _handle;
public WindowWrapper(IntPtr handle) { _handle = handle; }
public IntPtr Handle { get { return _handle; } }
}
}
}
I developed this as a cleaned up version of .NET Win 7-style folder select dialog by Bill Seddon of lyquidity.com (I have no affiliation). I wrote my own because his solution requires an additional Reflection class that isn't needed for this focused purpose, uses exception-based flow control, doesn't cache the results of its reflection calls. Note that the nested static VistaDialog
class is so that its static reflection variables don't try to get populated if the Show
method is never called.
It is used like so in a Windows Form:
var dialog = new FolderSelectDialog {
InitialDirectory = musicFolderTextBox.Text,
Title = "Select a folder to import music from"
};
if (dialog.Show(Handle)) {
musicFolderTextBox.Text = dialog.FileName;
}
You can of course play around with its options and what properties it exposes. For example, it allows multiselect in the Vista-style dialog.
Also, please note that Simon Mourier gave an answer that shows how to do the exact same job using interop against the Windows API directly, though his version would have to be supplemented to use the older style dialog if in an older version of Windows. Unfortunately, I hadn't found his post yet when I worked up my solution. Name your poison!
For me, it was just an error in the .env file. I deleted the comma at the end of each line and it was solved.
Before:
HOST=127.0.0.1,
After:
HOST=127.0.0.1
Just Do it.....
( It will create same table structure as from table as to table with same data )
create table toDatabaseName.toTableName as select * from fromDatabaseName.fromTableName;
Within the dplyr world, try:
select(iris,contains("Sepal"))
See the Selection section in ?select
for numerous other helpers like starts_with
, ends_with
, etc.
I found most of the presented answers work for local unused variable only, and will cause compile error for unused static global variable.
Another macro needed to suppress the warning of unused static global variable.
template <typename T>
const T* UNUSED_VARIABLE(const T& dummy) {
return &dummy;
}
#define UNUSED_GLOBAL_VARIABLE(x) namespace {\
const auto dummy = UNUSED_VARIABLE(x);\
}
static int a = 0;
UNUSED_GLOBAL_VARIABLE(a);
int main ()
{
int b = 3;
UNUSED_VARIABLE(b);
return 0;
}
This works because no warning will be reported for non-static global variable in anonymous namespace.
C++ 11 is required though
g++ -Wall -O3 -std=c++11 test.cpp
There is no annotation to set default value.
You can set default value only on java class level:
public class JavaObject
{
public String notNullMember;
public String optionalMember = "Value";
}
Using class members to give default values works very well just so long as you are careful only to do it with immutable values. If you try to do it with a list or a dict that would be pretty deadly. It also works where the instance attribute is a reference to a class just so long as the default value is None.
I've seen this technique used very successfully in repoze which is a framework that runs on top of Zope. The advantage here is not just that when your class is persisted to the database only the non-default attributes need to be saved, but also when you need to add a new field into the schema all the existing objects see the new field with its default value without any need to actually change the stored data.
I find it also works well in more general coding, but it's a style thing. Use whatever you are happiest with.
inspect.trace will let you get local variables after an exception has been thrown. You can then wrap the unit tests with a decorator like the following one to save off those local variables for examination during the post mortem.
import random
import unittest
import inspect
def store_result(f):
"""
Store the results of a test
On success, store the return value.
On failure, store the local variables where the exception was thrown.
"""
def wrapped(self):
if 'results' not in self.__dict__:
self.results = {}
# If a test throws an exception, store local variables in results:
try:
result = f(self)
except Exception as e:
self.results[f.__name__] = {'success':False, 'locals':inspect.trace()[-1][0].f_locals}
raise e
self.results[f.__name__] = {'success':True, 'result':result}
return result
return wrapped
def suite_results(suite):
"""
Get all the results from a test suite
"""
ans = {}
for test in suite:
if 'results' in test.__dict__:
ans.update(test.results)
return ans
# Example:
class TestSequenceFunctions(unittest.TestCase):
def setUp(self):
self.seq = range(10)
@store_result
def test_shuffle(self):
# make sure the shuffled sequence does not lose any elements
random.shuffle(self.seq)
self.seq.sort()
self.assertEqual(self.seq, range(10))
# should raise an exception for an immutable sequence
self.assertRaises(TypeError, random.shuffle, (1,2,3))
return {1:2}
@store_result
def test_choice(self):
element = random.choice(self.seq)
self.assertTrue(element in self.seq)
return {7:2}
@store_result
def test_sample(self):
x = 799
with self.assertRaises(ValueError):
random.sample(self.seq, 20)
for element in random.sample(self.seq, 5):
self.assertTrue(element in self.seq)
return {1:99999}
suite = unittest.TestLoader().loadTestsFromTestCase(TestSequenceFunctions)
unittest.TextTestRunner(verbosity=2).run(suite)
from pprint import pprint
pprint(suite_results(suite))
The last line will print the returned values where the test succeeded and the local variables, in this case x, when it fails:
{'test_choice': {'result': {7: 2}, 'success': True},
'test_sample': {'locals': {'self': <__main__.TestSequenceFunctions testMethod=test_sample>,
'x': 799},
'success': False},
'test_shuffle': {'result': {1: 2}, 'success': True}}
Har det gøy :-)
$no_of_digit = 10;
$number = 123;
$length = strlen((string)$number);
for($i = $length;$i<$no_of_digit;$i++)
{
$number = '0'.$number;
}
echo $number; /////// result 0000000123
Download the latest CMake Mac binary distribution here: https://cmake.org/download/ (current latest is: https://cmake.org/files/v3.17/cmake-3.17.1-Darwin-x86_64.dmg)
Double click the downloaded .dmg file to install it. In the window that pops up, drag the CMake icon into the Application folder.
Add this line to your .bashrc file: PATH="/Applications/CMake.app/Contents/bin":"$PATH"
Reload your .bashrc file: source ~/.bashrc
Verify the latest cmake version is installed: cmake --version
You can launch the CMake GUI by clicking on LaunchPad and typing cmake. Click on the CMake icon that appears.
Recently I had this same problem on windows 10 - after installing Hyper-V & other windows features like:
Windows Projected File System, Windows Sandbox, Windows Subsystem for Linux, Work Folders Client,
And it stopped working for me;(
You should \usepackage{longtable}
.
If you're only looking for one:
import re
match = re.search(r'href=[\'"]?([^\'" >]+)', s)
if match:
print(match.group(1))
If you have a long string, and want every instance of the pattern in it:
import re
urls = re.findall(r'href=[\'"]?([^\'" >]+)', s)
print(', '.join(urls))
Where s
is the string that you're looking for matches in.
Quick explanation of the regexp bits:
r'...'
is a "raw" string. It stops you having to worry about escaping characters quite as much as you normally would. (\
especially -- in a raw string a\
is just a\
. In a regular string you'd have to do\\
every time, and that gets old in regexps.)"
href=[\'"]?
" says to match "href=", possibly followed by a'
or"
. "Possibly" because it's hard to say how horrible the HTML you're looking at is, and the quotes aren't strictly required.Enclosing the next bit in "
()
" says to make it a "group", which means to split it out and return it separately to us. It's just a way to say "this is the part of the pattern I'm interested in.""
[^\'" >]+
" says to match any characters that aren't'
,"
,>
, or a space. Essentially this is a list of characters that are an end to the URL. It lets us avoid trying to write a regexp that reliably matches a full URL, which can be a bit complicated.
The suggestion in another answer to use BeautifulSoup isn't bad, but it does introduce a higher level of external requirements. Plus it doesn't help you in your stated goal of learning regexps, which I'd assume this specific html-parsing project is just a part of.
It's pretty easy to do:
from BeautifulSoup import BeautifulSoup
soup = BeautifulSoup(html_to_parse)
for tag in soup.findAll('a', href=True):
print(tag['href'])
Once you've installed BeautifulSoup, anyway.
This:
ORDER BY 1
...is known as an "Ordinal" - the number stands for the column based on the number of columns defined in the SELECT clause. In the query you provided, it means:
ORDER BY A.PAYMENT_DATE
It's not a recommended practice, because:
I suppose this would help:
<%!
String someOutput() {
return "Some Output";
}
%>
...
<%= someOutput() %>
Anyway, it isn't a good idea to have code in a view.
The thing you are asking is not popup but lightbox. For this, the trick is to display a semitransparent layer behind (called overlay) and that required div above it.
Hope you are familiar basic javascript. Use the following code. With javascript, change display:block to/from display:none to show/hide popup.
<div style="background-color: rgba(150, 150, 150, 0.5); overflow: hidden; position: fixed; left: 0px; top: 0px; bottom: 0px; right: 0px; z-index: 1000; display:block;">
<div style="background-color: rgb(255, 255, 255); width: 600px; position: static; margin: 20px auto; padding: 20px 30px 0px; top: 110px; overflow: hidden; z-index: 1001; box-shadow: 0px 3px 8px rgba(34, 25, 25, 0.4);">
<iframe src="otherpage.html" width="400px"></iframe>
</div>
</div>
Go to Excel Options > Save > Save Files in this format > Select "Excel Workbook(*.xlsx)". This problem occurs if you are using an older version of excel file (.xls) instead of .xlsx. The older version does not allow more than 65k rows in the excel sheet.
Once you have saved as .xslx, try executing your code again.
edit ----
Looking more into your problem, it seems that the problem might be locale specific. Does the code work on another machine? What value does the cell have? Is it datetime format? Have a look here:
http://support.microsoft.com/kb/320369
http://blogs.msdn.com/b/eric_carter/archive/2005/06/15/429515.aspx
In general, one doesn't expand out log(a + b)
; you just deal with it as is. That said, there are occasionally circumstances where it makes sense to use the following identity:
log(a + b) = log(a * (1 + b/a)) = log a + log(1 + b/a)
(In fact, this identity is often used when implementing log
in math libraries).
This is a slight modification to Edens answer - which for me in chrome didn't catch the error. Although you'll still get an error in the console: "Refused to display 'https://www.google.ca/' in a frame because it set 'X-Frame-Options' to 'sameorigin'." At least this will catch the error message and then you can deal with it.
<iframe id="myframe" src="https://google.ca"></iframe>
<script>
myframe.onload = function(){
var that = document.getElementById('myframe');
try{
(that.contentWindow||that.contentDocument).location.href;
}
catch(err){
//err:SecurityError: Blocked a frame with origin "http://*********" from accessing a cross-origin frame.
console.log('err:'+err);
}
}
</script>
I had a similar issue, but the reason that %ANT_HOME% wasn't resolving is that I had added it as a USER variable, not a SYSTEM one. Sorted now, thanks to this post.
I have made a package for that purpose.
You can use it like this:
from pybeep.pybeep import PyVibrate, PyBeep
PyVibrate().beep()
PyVibrate().beepn(3)
PyBeep().beep()
PyBeep().beepn(3)
It depends on sox and only supports python3.
yu have to install the correct version for your computer 32 or 63 bits thats all
Put your wait() function in a loop and wait for all the child processes. The wait function will return -1 and errno will be equal to ECHILD if no more child processes are available.
<Grid >
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Button Command="{Binding ClickCommand}" Width="100" Height="100" Content="wefwfwef"/>
</Grid>
the code behind for the window:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = new ViewModelBase();
}
}
The ViewModel:
public class ViewModelBase
{
private ICommand _clickCommand;
public ICommand ClickCommand
{
get
{
return _clickCommand ?? (_clickCommand = new CommandHandler(() => MyAction(), ()=> CanExecute));
}
}
public bool CanExecute
{
get
{
// check if executing is allowed, i.e., validate, check if a process is running, etc.
return true/false;
}
}
public void MyAction()
{
}
}
Command Handler:
public class CommandHandler : ICommand
{
private Action _action;
private Func<bool> _canExecute;
/// <summary>
/// Creates instance of the command handler
/// </summary>
/// <param name="action">Action to be executed by the command</param>
/// <param name="canExecute">A bolean property to containing current permissions to execute the command</param>
public CommandHandler(Action action, Func<bool> canExecute)
{
_action = action;
_canExecute = canExecute;
}
/// <summary>
/// Wires CanExecuteChanged event
/// </summary>
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
/// <summary>
/// Forcess checking if execute is allowed
/// </summary>
/// <param name="parameter"></param>
/// <returns></returns>
public bool CanExecute(object parameter)
{
return _canExecute.Invoke();
}
public void Execute(object parameter)
{
_action();
}
}
I hope this will give you the idea.
In my case I solved the problem by establishing a valid column number when applying the order
property inside the script where you configure the data table.
var table = $('#mytable').DataTable({
.
.
.
order: [[ 1, "desc" ]],
Rather than set the length, set the max and min values for the number input.
The input box then resizes to fit the longest valid value.
If you want to allow a 3-digit number then set 999 as the max
<input type="number" name="quantity" min="0" max="999">
The Why
java.util.logging has a root logger that defaults to Level.INFO
, and a ConsoleHandler attached to it that also defaults to Level.INFO
.
FINE
is lower than INFO
, so fine messages are not displayed by default.
Solution 1
Create a logger for your whole application, e.g. from your package name or use Logger.getGlobal()
, and hook your own ConsoleLogger to it.
Then either ask root logger to shut up (to avoid duplicate output of higher level messages), or ask your logger to not forward logs to root.
public static final Logger applog = Logger.getGlobal();
...
// Create and set handler
Handler systemOut = new ConsoleHandler();
systemOut.setLevel( Level.ALL );
applog.addHandler( systemOut );
applog.setLevel( Level.ALL );
// Prevent logs from processed by default Console handler.
applog.setUseParentHandlers( false ); // Solution 1
Logger.getLogger("").setLevel( Level.OFF ); // Solution 2
Solution 2
Alternatively, you may lower the root logger's bar.
You can set them by code:
Logger rootLog = Logger.getLogger("");
rootLog.setLevel( Level.FINE );
rootLog.getHandlers()[0].setLevel( Level.FINE ); // Default console handler
Or with logging configuration file, if you are using it:
.level = FINE
java.util.logging.ConsoleHandler.level = FINE
By lowering the global level, you may start seeing messages from core libraries, such as from some Swing or JavaFX components. In this case you may set a Filter on the root logger to filter out messages not from your program.
The best option is prepared statements. Messing around with quotes and escapes is harder work to begin with, and difficult to maintain. Sooner or later you will end up accidentally forgetting to quote something or end up escaping the same string twice, or mess up something like that. Might be years before you find those type of bugs.
Using linq:
prods.Remove( prods.Single( s => s.ID == 1 ) );
Maybe you even want to use SingleOrDefault()
and check if the element exists at all ...
EDIT:
Since stuff
is a struct, SingleOrDefault()
will not return null. But it will return default( stuff ), which will have an ID of 0. When you don't have an ID of 0 for your normal stuff-objects you can query for this ID:
var stuffToRemove = prods.SingleOrDefault( s => s.ID == 1 )
if( stuffToRemove.ID != 0 )
{
prods.Remove( stuffToRemove );
}
I used this function to detect if the element is visible in view port
Code:
const vh = Math.max(document.documentElement.clientHeight || 0, window.innerHeight || 0);
$(window).scroll(function(){
var scrollTop = $(window).scrollTop(),
elementOffset = $('.for-scroll').offset().top,
distance = (elementOffset - scrollTop);
if(distance < vh){
console.log('in view');
}
else{
console.log('not in view');
}
});
There is two ways to make/create object in c++.
First one is :
MyClass myclass; // if you don;t need to call rather than default constructor
MyClass myclass(12); // if you need to call constructor with parameters
Second one is :
MyClass *myclass = new MyClass();// if you don;t need to call rather than default constructor
MyClass *myclass = new MyClass(12);// if you need to call constructor with parameters
In c++ if you use new keyword, object will be stored in heap. it;s very useful if you are using this object long time of period and if you use first method, it will be stored in stack. it can be used only short time period. Notice : if you use new keyword, remember it will return pointer value. you should declare name with *. If you use second method, it doesn;t delete object in the heap. you must delete by yourself using delete keyword;
delete myclass;
You can use long
type or Int64
Security Warning: This class is not secure. It's using Rijndael256-ECB, which is not semantically secure. Just because "it works" doesn't mean "it's secure". Also, it strips tailing spaces afterwards due to not using proper padding.
Found this class recently, it works like a dream!
class Encryption {
var $skey = "yourSecretKey"; // you can change it
public function safe_b64encode($string) {
$data = base64_encode($string);
$data = str_replace(array('+','/','='),array('-','_',''),$data);
return $data;
}
public function safe_b64decode($string) {
$data = str_replace(array('-','_'),array('+','/'),$string);
$mod4 = strlen($data) % 4;
if ($mod4) {
$data .= substr('====', $mod4);
}
return base64_decode($data);
}
public function encode($value){
if(!$value){return false;}
$text = $value;
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
$crypttext = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $this->skey, $text, MCRYPT_MODE_ECB, $iv);
return trim($this->safe_b64encode($crypttext));
}
public function decode($value){
if(!$value){return false;}
$crypttext = $this->safe_b64decode($value);
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
$decrypttext = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $this->skey, $crypttext, MCRYPT_MODE_ECB, $iv);
return trim($decrypttext);
}
}
And to call it:
$str = "My secret String";
$converter = new Encryption;
$encoded = $converter->encode($str );
$decoded = $converter->decode($encoded);
echo "$encoded<p>$decoded";
In my case, I got the error when I had my Web Application in 4.5.2 and the referenced class libaries in 4.6.1. When I updated the Web Application to 4.5.2 version the error went away.
This is an old question, but is still regularly viewed/needed. I want to post to caution readers like me that whitespace as mentioned in the OP's question is not the same as Regex's definition, to include newlines, tabs, and space characters -- Git asks you to be explicit. See some options here: https://git-scm.com/book/en/v2/Customizing-Git-Git-Configuration
As stated, git diff -b
or git diff --ignore-space-change
will ignore spaces at line ends. If you desire that setting to be your default behavior, the following line adds that intent to your .gitconfig file, so it will always ignore the space at line ends:
git config --global core.whitespace trailing-space
In my case, I found this question because I was interested in ignoring "carriage return whitespace differences", so I needed this:
git diff --ignore-cr-at-eol
or
git config --global core.whitespace cr-at-eol
from here.
You can also make it the default only for that repo by omitting the --global parameter, and checking in the settings file for that repo. For the CR problem I faced, it goes away after check-in if warncrlf or autocrlf = true in the [core] section of the .gitconfig file.
There are several issues in your code :
You are handling the click
event of a submit button, whose default behavior is to post a request to the server and reload the page. You have to inhibit this behavior by returning false
from your handler:
onclick="SubmitFrm(); return false;"
value
cannot be called because it is a property, not a method:
var Searchtxt = document.getElementById("txtSearch").value;
The search query you are sending in the query string has to be encoded:
window.location = "http://www.mysite.com/search/?Query="
+ encodeURIComponent(Searchtxt);
The order of the calls is important:
first -
pack();
second -
setLocationRelativeTo(null);
List[] listArr = new ArrayList[4];
Above line gives warning , but it works (i.e it creates Array of ArrayList)
function bindAllEvents (el) {
for (const key in el) {
if (key.slice(0, 2) === 'on') {
el.addEventListener(key.slice(2), e => console.log(e.type));
}
}
}
bindAllEvents($('.yourElement'))
This uses a bit of ES6 for prettiness, but can easily be translated for legacy browsers as well. In the function attached to the event listeners, it's currently just logging out what kind of event occurred but this is where you could print out additional information, or using a switch case on the e.type
, you could only print information on specific events
The issue solved after renaming the xml file name to log4j2.xml
In case you do not want to use a full-fledged framework for cross-platform development, take a look at C++ as an option. iOS fully supports using C++ for your application logic via Objective-C++. I don't know how well Android's support for C++ via the NDK is suited for doing your business logic in C++ rather than just some performance-critical code snippets, but in case that use case is well supported, you could give it a try.
This approach of course only makes sense if your application logic constitutes the greatest part of your project, as the user interfaces will have to be written individually for each platform.
As a matter of fact, C++ is the single most widely supported programming language (with the exception of C), and is therefore the core language of most large cross-platform applications.
Note to under
connetionString =@"server=XXX;Trusted_Connection=yes;database=yourDB;";
Note: XXX = . OR .\SQLEXPRESS OR .\MSSQLSERVER OR (local)\SQLEXPRESS OR (localdb)\v11.0 &...
you can replace 'server' with 'Data Source'
too you can replace 'database' with 'Initial Catalog'
Sample:
connetionString =@"server=.\SQLEXPRESS;Trusted_Connection=yes;Initial Catalog=books;";
Just add a question mark ?
to the optional field.
interface Employee{
id: number;
name: string;
salary?: number;
}
You can use the --prefix
option:
mkdir -p ./install/here/node_modules
npm install --prefix ./install/here <package>
The package(s) will then be installed in ./install/here/node_modules
. The mkdir
is needed since npm might otherwise choose an already existing node_modules
directory higher up in the hierarchy. (See npm documentation on folders.)
It looks like you are trying to set elements 0 through 11 of PriceList to new values. The syntax would usually look like this:
prompt = "What would you like the new price for all standard pizzas to be? "
PizzaChange = float(input(prompt))
for i in [0, 1, 2, 3, 4, 5, 6]: PriceList[i] = PizzaChange
for i in [7, 8, 9, 10, 11]: PriceList[i] = PizzaChange + 3
If they are always consecutive ranges, then it's even simpler to write:
prompt = "What would you like the new price for all standard pizzas to be? "
PizzaChange = float(input(prompt))
for i in range(0, 7): PriceList[i] = PizzaChange
for i in range(7, 12): PriceList[i] = PizzaChange + 3
For reference, PriceList[0][1][2][3][4][5][6]
refers to "Element 6 of element 5 of element 4 of element 3 of element 2 of element 1 of element 0 of PriceList
. Put another way, it's the same as ((((((PriceList[0])[1])[2])[3])[4])[5])[6]
.
You don't need to replace it with anything. The setting magic_quotes_runtime
is removed in PHP6 so the function call is unneeded. If you want to maintain backwards compatibility it may be wise to wrap it in a if statement checking phpversion using version_compare
No need functions
For example to give color to a container using colorcode
Container (
color:Color(0xff000000)
)
Here the 0xff is the format followed by color code
Try something like this:
df.select([c for c in df.columns if c in ['_2','_4','_5']]).show()
If you run into this problem and are working with a non-Windows/Mac OS (Ubuntu in my case), try starting the emulator by itself in Android SDK and AVD Manager then running your application.
You could use ForEach
, but you have to convert the IEnumerable<T>
to a List<T>
first.
list.Where(w => w.Name == "height").ToList().ForEach(s => s.Value = 30);
You can also plot to a png file using gnuplot (which is free):
terminal commands
gnuplot> set title '<title>'
gnuplot> set ylabel '<yLabel>'
gnuplot> set xlabel '<xLabel>'
gnuplot> set grid
gnuplot> set term png
gnuplot> set output '<Output file name>.png'
gnuplot> plot '<fromfile.csv>'
note: you always need to give the right extension (.png here) at set output
Then it is also possible that the ouput is not lines, because your data is not continues. To fix this simply change the 'plot' line to:
plot '<Fromfile.csv>' with line lt -1 lw 2
More line editing options (dashes and line color ect.) at: http://gnuplot.sourceforge.net/demo_canvas/dashcolor.html
apt-get install gnuplot
)brew install gnuplot
)Consider removing the .gitignore file if you want to remove any trace of Git in your project.
** Consider leaving the .gitignore file if you would ever want reincorporate Git into the project.
Some frameworks may automatically produce the .gitignore file so you may want to leave it.
Open a terminal and navigate to the directory of your project, i.e. - cd path_to_your_project
.
Run this command:
rm -rf .git*
This will remove the Git tracking and metadata from your project. If you want to keep the metadata (such as .gitignore and .gitkeep), you can delete only the tracking by running rm -rf .git
.
The rmdir
or rd
command will not delete/remove any hidden files or folders within the directory you specify, so you should use the del
command to be sure that all files are removed from the .git
folder.
Open the command prompt
Either click Start
then Run
or hit the key and r at the same time.
Type cmd
and hit enter
Navigate to the project directory, i.e. - cd path_to_your_project
Run these commands
del /F /S /Q /A .git
rmdir .git
The first command removes all files and folder within the .git
folder. The second removes the .git
folder itself.
Open the file explorer and navigate to your project
Show hidden files and folders - refer to this article for a visual guide
In the view menu on the toolbar, select Options
In the Advanced Settings
section, find Hidden files and Folders
under the Files and Folders
list and select Show hidden files and folders
Close the options menu and you should see all hidden folders and files including the .git
folder.
Delete the
.git
folder Delete the.gitignore
file ** (see note at the top of this answer)
Like this. Make sure you drop the temp table (at the end of the code block, after you're done with it) or it will error on subsequent runs.
SELECT
tblMEP_Sites.Name AS SiteName,
convert(varchar(10),BillingMonth ,101) AS BillingMonth,
SUM(Consumption) AS Consumption
INTO
#MyTempTable
FROM
tblMEP_Projects
JOIN tblMEP_Sites
ON tblMEP_Projects.ID = tblMEP_Sites.ProjectID
JOIN tblMEP_Meters
ON tblMEP_Meters.SiteID = tblMEP_Sites.ID
JOIN tblMEP_MonthlyData
ON tblMEP_MonthlyData.MeterID = tblMEP_Meters.ID
JOIN tblMEP_CustomerAccounts
ON tblMEP_CustomerAccounts.ID = tblMEP_Meters.CustomerAccountID
JOIN tblMEP_UtilityCompanies
ON tblMEP_UtilityCompanies.ID = tblMEP_CustomerAccounts.UtilityCompanyID
JOIN tblMEP_MeterTypes
ON tblMEP_UtilityCompanies.UtilityTypeID = tblMEP_MeterTypes.ID
WHERE
tblMEP_Projects.ID = @ProjectID
AND tblMEP_MonthlyData.BillingMonth Between @StartDate AND @EndDate
AND tbLMEP_MeterTypes.ID = @MeterTypeID
GROUP BY
BillingMonth, tblMEP_Sites.Name
DROP TABLE #MyTempTable
assign is what you are looking for.
assign("x", 5)
x
[1] 5
but buyer beware.
See R FAQ 7.21 http://cran.r-project.org/doc/FAQ/R-FAQ.html#How-can-I-turn-a-string-into-a-variable_003f
Start by reading the fork man page as well as the getppid / getpid man pages.
From fork's
On success, the PID of the child process is returned in the parent's thread of execution, and a 0 is returned in the child's thread of execution. On failure, a -1 will be returned in the parent's context, no child process will be created, and errno will be set appropriately.
So this should be something down the lines of
if ((pid=fork())==0){
printf("yada yada %u and yada yada %u",getpid(),getppid());
}
else{ /* avoids error checking*/
printf("Dont yada yada me, im your parent with pid %u ", getpid());
}
As to your question:
This is the child process. My pid is 22163 and my parent's id is 0.
This is the child process. My pid is 22162 and my parent's id is 22163.
fork()
executes before the printf
. So when its done, you have two processes with the same instructions to execute. Therefore, printf will execute twice. The call to fork()
will return 0
to the child process, and the pid
of the child process to the parent process.
You get two running processes, each one will execute this instruction statement:
printf ("... My pid is %d and my parent's id is %d",getpid(),0);
and
printf ("... My pid is %d and my parent's id is %d",getpid(),22163);
~
To wrap it up, the above line is the child, specifying its pid
. The second line is the parent process, specifying its id (22162) and its child's (22163).