In case if you are using CentOS:
Try:
sudo yum -y install libcurl libcurl-devel
Small refinement to the previous answers: To make longer lines more readable if they spill over to additional screen lines:
ul, li {list-style-type: none;}
li {padding-left: 2em; text-indent: -2em;}
Use the raw_input()
function to get input from users (2.x):
print "Enter a file name:",
filename = raw_input()
or just:
filename = raw_input('Enter a file name: ')
or if in Python 3.x:
filename = input('Enter a file name: ')
It is possible to create the foreign key using ALTER TABLE tablename WITH NOCHECK ..., which will allow data that violates the foreign key.
"ALTER TABLE tablename WITH NOCHECK ..." option to add the FK -- This solution worked for me.
Python has names which are mapped to objects in a hashmap called a namespace. At any instant in time, a name always refers to exactly one object, but a single object can be referred to by any arbitrary number of names. Given a name, it is very efficient for the hashmap to look up the single object which that name refers to. However given an object, which as mentioned can be referred to by multiple names, there is no efficient way to look up the names which refer to it. What you have to do is iterate through all the names in the namespace and check each one individually and see if it maps to your given object. This can easily be done with a list comprehension:
[k for k,v in locals().items() if v is myobj]
This will evaluate to a list of strings containting the names of all local "variables" which are currently mapped to the object myobj
.
>>> a = 1
>>> this_is_also_a = a
>>> this_is_a = a
>>> b = "ligma"
>>> c = [2,3, 534]
>>> [k for k,v in locals().items() if v is a]
['a', 'this_is_also_a', 'this_is_a']
Of course locals()
can be substituted with any dict
that you want to search for names that point to a given object. Obviously this search can be slow for very large namespaces because they must be traversed in their entirety.
My dirty solution is:
public class TestCaseExtended extends TestCase {
private boolean isInitialized = false;
private int serId;
@Override
public void setUp() throws Exception {
super.setUp();
if(!isInitialized) {
loadSaveNewSerId();
emptyTestResultsDirectory();
isInitialized = true;
}
}
...
}
I use it as a base base to all my testCases.
You're correct that this is really painful to hand out to others, but if you have to, this is how you do it.
References
i want to discuss this question more theoretically (since it has already enough practical answers)
.net has a very nice abstraction model for groups of data (a.k.a. collections)
IEnumerable
it's just a group of data that you can enumerate. It doesn't matter HOW you enumerate, it's just that you can enumerate some data. And that enumeration is done by a completely different object, an IEnumerator
these interfaces are defined is as follows:
//
// Summary:
// Exposes an enumerator, which supports a simple iteration over a non-generic collection.
public interface IEnumerable
{
//
// Summary:
// Returns an enumerator that iterates through a collection.
//
// Returns:
// An System.Collections.IEnumerator object that can be used to iterate through
// the collection.
IEnumerator GetEnumerator();
}
//
// Summary:
// Supports a simple iteration over a non-generic collection.
public interface IEnumerator
{
//
// Summary:
// Gets the element in the collection at the current position of the enumerator.
//
// Returns:
// The element in the collection at the current position of the enumerator.
object Current { get; }
//
// Summary:
// Advances the enumerator to the next element of the collection.
//
// Returns:
// true if the enumerator was successfully advanced to the next element; false if
// the enumerator has passed the end of the collection.
//
// Exceptions:
// T:System.InvalidOperationException:
// The collection was modified after the enumerator was created.
bool MoveNext();
//
// Summary:
// Sets the enumerator to its initial position, which is before the first element
// in the collection.
//
// Exceptions:
// T:System.InvalidOperationException:
// The collection was modified after the enumerator was created.
void Reset();
}
as you might have noticed, the IEnumerator
interface doesn't "know" what an index is, it just knows what element it's currently pointing to, and how to move to the next one.
now here is the trick: foreach
considers every input collection an IEnumerable
, even if it is a more concrete implementation like an IList<T>
(which inherits from IEnumerable
), it will only see the abstract interface IEnumerable
.
what foreach
is actually doing, is calling GetEnumerator
on the collection, and calling MoveNext
until it returns false.
so here is the problem, you want to define a concrete concept "Indices" on an abstract concept "Enumerables", the built in foreach
construct doesn't give you that option, so your only way is to define it yourself, either by what you are doing originally (creating a counter manually) or just use an implementation of IEnumerator
that recognizes indices AND implement a foreach
construct that recognizes that custom implementation.
personally i would create an extension method like this
public static class Ext
{
public static void FE<T>(this IEnumerable<T> l, Action<int, T> act)
{
int counter = 0;
foreach (var item in l)
{
act(counter, item);
counter++;
}
}
}
and use it like this
var x = new List<string>() { "hello", "world" };
x.FE((ind, ele) =>
{
Console.WriteLine($"{ind}: {ele}");
});
this also avoids any unnecessary allocations seen in other answers.
As the existing answers mentioned, LEA
has the advantages of performing memory addressing arithmetic without accessing memory, saving the arithmetic result to a different register instead of the simple form of add instruction. The real underlying performance benefit is that modern processor has a separate LEA ALU unit and port for effective address generation (including LEA
and other memory reference address), this means the arithmetic operation in LEA
and other normal arithmetic operation in ALU could be done in parallel in one core.
Check this article of Haswell architecture for some details about LEA unit: http://www.realworldtech.com/haswell-cpu/4/
Another important point which is not mentioned in other answers is LEA REG, [MemoryAddress]
instruction is PIC (position independent code) which encodes the PC relative address in this instruction to reference MemoryAddress
. This is different from MOV REG, MemoryAddress
which encodes relative virtual address and requires relocating/patching in modern operating systems (like ASLR is common feature). So LEA
can be used to convert such non PIC to PIC.
Another way of setting the default to the HTML web forms editor is:
File
> New
> File
HTML Page
Open
button there is a down arrowOpen With
HTML (Web Forms) Editor
Set as Default
OK
WORDPRESS is having this error mostly:
SOLUTION:
Locate your PHP installed directory on Remote live hosting SERVER or "Local Server"
In case of Windows os
for example if you using xampp or wamp webserver. it will be in xammp directory
'c:\xammp\php'
Note: For Unix/Linux OS, locate your PHP directory in Webserver
Find & Edit PHP.INI file
Find 'allow_url_include'
replace it with value 'on'
allow_url_include=On
Save you php.ini & RESTART you web-server.
According to the documentation
x += y
is equivalent tox = operator.iadd(x, y)
. Another way to put it is to say thatz = operator.iadd(x, y)
is equivalent to the compound statementz = x; z += y
.
So x += 3
is the same as x = x + 3
.
x = 2
x += 3
print(x)
will output 5.
Notice that there's also
Found in one of the Chrome sample applications, although this is meant for larger blocks of data where you're okay with an asynchronous conversion.
/**
* Converts an array buffer to a string
*
* @private
* @param {ArrayBuffer} buf The buffer to convert
* @param {Function} callback The function to call when conversion is complete
*/
function _arrayBufferToString(buf, callback) {
var bb = new Blob([new Uint8Array(buf)]);
var f = new FileReader();
f.onload = function(e) {
callback(e.target.result);
};
f.readAsText(bb);
}
cannot be accessed with an instance reference
It means you're calling a STATIC method and passing it an instance. The easiest solution is to remove Static, eg:
public static void ExportToExcel(IEnumerable data, string sheetName)
{
If you're okay with ES2017, await
is good:
const DEF_DELAY = 1000;
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms || DEF_DELAY));
}
await sleep(100);
Note that the await
part needs to be in an async function:
//IIAFE (immediately invoked async function expression)
(async()=>{
//Do some stuff
await sleep(100);
//Do some more stuff
})()
You need to run your script after the element exists. Move the <input type="hidden" name="checkyear" id="checkyear" value="">
to the beginning.
please try below command : kubectl patch pod -p '{"metadata":{"finalizers":null}}'
What Chad says, except its better to use .keyup in this case because with .keydown and .keypress the value of the input is still the older value i.e. the newest key pressed would not be reflected if .val() is called.
This should probably be a comment on Chad's answer but I dont have privileges to comment yet.
You will need to do:
$boot2docker init
$boot2docker start
The following settings fixed the issue:
$export DOCKER_HOST=tcp://192.168.59.103:2376
$export DOCKER_CERT_PATH=/Users/{profileName}/.boot2docker/certs/boot2docker-vm
$export DOCKER_TLS_VERIFY=1
the _T convention is used to indicate the program should use the character set defined for the application (Unicode, ASCII, MBCS, etc.). You can surround your strings with _T( ) to have them stored in the correct format.
cout << _T( "There are " ) << argc << _T( " arguments:" ) << endl;
I'll add yet another random answer just because this question came up in response to my several searches. I have jQuery objects that have public and private methods. The pattern is:
myObject = (function($){
function publicFunction() {}
function privateFunction() {}
return {
theOnlyMethod: publicFunction
}
})(jQuery);
If I put a breakpoint on a line inside a private function, Chrome will not debug it, the line moves down to the return statement! So to debug, I have to expose the private functions! This is new to me this morning (8/20/2020, Version 84.0.4147.125 (Official Build) (64-bit)), I can't believe I've not run into this in 3 years.
The .css()
function doesn't queue behind running animations, it's instantaneous.
To match the behaviour that you're after, you'd need to do the following:
$(document).ready(function() {
$("button").mouseover(function() {
var p = $("p#44.test").css("background-color", "yellow");
p.hide(1500).show(1500);
p.queue(function() {
p.css("background-color", "red");
});
});
});
The .queue()
function waits for running animations to run out and then fires whatever's in the supplied function.
$this->db->where('`id` IN (SELECT `someId` FROM `anotherTable` WHERE `someCondition`='condition')', NULL, FALSE);
You need to use a pointer to a member function, not just a pointer to a function.
class A {
int f() { return 1; }
public:
int (A::*x)();
A() : x(&A::f) {}
};
int main() {
A a;
std::cout << (a.*a.x)();
return 0;
}
Here is my script to do the process described by sje397:
#!/bin/sh
# Needed if running on Windows
FIND="/usr/bin/find"
DIFF="diff -r"
# Extract the jar (war or ear)
JAR_FILE1=$1
JAR_FILE2=$2
JAR_DIR=${PWD} # to assign to a variable
TEMP_DIR=$(mktemp -d)
echo "Extracting jars in $TEMP_DIR"
EXT_DIR1="${TEMP_DIR}/${JAR_FILE1%.*}"
EXT_DIR2="${TEMP_DIR}/${JAR_FILE2%.*}"
mkdir ${EXT_DIR1}
cd ${EXT_DIR1}
jar xf ${JAR_DIR}/${JAR_FILE1}
jad -d . -o -t2 -safe -space -b -ff -s java -r **/*.class
cd ..
mkdir ${EXT_DIR2}
cd ${EXT_DIR2}
jar xf ${JAR_DIR}/${JAR_FILE2}
jad -d . -o -t2 -safe -space -b -ff -s java -r **/*.class
cd ..
# remove class files so the diff is clean
${FIND} ${TEMP_DIR} -name '*.class' | xargs rm
# diff recursively
${DIFF} ${EXT_DIR1} ${EXT_DIR2}
I can run it on Windows using GIT for Windows. Just open a command prompt. Run bash and then execute the script from there.
String.prototype.match
returns an array, we can then check the length,
I find this method to be most descriptive
var str = 'one two three four five';
str.match(/\w+/g).length;
I will do something like this:
List<String> order = List.of("Red", "Green", "Magenta", "Silver");
Comparator.comparing(Car::getColor(), Comparator.comparingInt(c -> order.indexOf(c)))
All credits go to @Sean Patrick Floyd :)
That method can't return true
. That's the point of Long.MAX_VALUE
. It would be really confusing if its name were... false. Then it should be just called Long.SOME_FAIRLY_LARGE_VALUE
and have literally zero reasonable uses. Just use Android's isUserAGoat
, or you may roll your own function that always returns false
.
Note that a long
in memory takes a fixed number of bytes. From Oracle:
long: The long data type is a 64-bit signed two's complement integer. It has a minimum value of -9,223,372,036,854,775,808 and a maximum value of 9,223,372,036,854,775,807 (inclusive). Use this data type when you need a range of values wider than those provided by int.
As you may know from basic computer science or discrete math, there are 2^64 possible values for a long, since it is 64 bits. And as you know from discrete math or number theory or common sense, if there's only finitely many possibilities, one of them has to be the largest. That would be Long.MAX_VALUE
. So you are asking something similar to "is there an integer that's >0 and < 1?" Mathematically nonsensical.
If you actually need this for something for real then use BigInteger
class.
After having spent over an hour going in rounds swearing at Samsung (mostly), Google, and who not, here are my findings, that finally helped me get the device recognized:
adb kill-server
(precede with .\
in ps)adb start-server
(while device connected) > watch for prompt on deviceadb devices
gets the following output:List of devices attached
278c250cce217ece device
if protobuf is installed then import it like this
pip install protobuf
import google.protobuf
as per docs:
"json"
: Evaluates the response as JSON and returns a JavaScript object. In jQuery 1.4 the JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown. (See json.org for more information on proper JSON formatting.)"text"
: A plain text string.The maximal length of the target column is shorter than the value you try to insert.
Rightclick the table in SQL manager and go to 'Design' to visualize your table structure and column definitions.
Edit:
Try to set a length on your nvarchar inserts thats the same or shorter than whats defined in your table.
My solution would be after converting data to numerical type:
Top15[['Citable docs per Capita','Energy Supply per Capita']].corr()
Make sure you use the right doctype.
eg.
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
or just
<!doctype html>
and also read and understand how compatibility modes and developer toolbar for IE work and set modes for IE:
You can use alert(arrayObj.toSource());
Python includes a function called itemgetter to return the item at a specific index in a list:
from operator import itemgetter
Pass the itemgetter() function the index of the item you want to retrieve. To retrieve the first item, you would use itemgetter(0). The important thing to understand is that itemgetter(0) itself returns a function. If you pass a list to that function, you get the specific item:
itemgetter(0)([10, 20, 30]) # Returns 10
This is useful when you combine it with map(), which takes a function as its first argument, and a list (or any other iterable) as the second argument. It returns the result of calling the function on each object in the iterable:
my_list = [['a', 'b', 'c'], [1, 2, 3], ['x', 'y', 'z']]
list(map(itemgetter(0), my_list)) # Returns ['a', 1, 'x']
Note that map() returns a generator, so the result is passed to list() to get an actual list. In summary, your task could be done like this:
lst2.append(list(map(itemgetter(0), lst)))
This is an alternative method to using a list comprehension, and which method to choose highly depends on context, readability, and preference.
More info: https://docs.python.org/3/library/operator.html#operator.itemgetter
An old thread, sure, but a popular one apparently. It's 2020 now and none of these answers have addressed the issue of unreadable code. @pimvdb's answer takes up less lines, but it's also pretty complicated to follow. For easier debugging and better readability, I should suggest refactoring the OP's code to something like this, and adopting an early return pattern, as this is likely the main reason you were unsure of why the were getting undefined:
function validatePassword() {
const password = document.getElementById("password");
const confirm_password = document.getElementById("password_confirm");
if (password.value.length === 0) {
return false;
}
if (password.value !== confirm_password.value) {
return false;
}
return true;
}
Simple javascript document navigation to "#" will do it.
window.onload = function()
{
document.location.href = "#";
}
This will force the navigation bar to remove itself on load.
On a first hand, a web server serves web content (HTML and static content) over the HTTP protocol. On the other hand, an application server is a container upon which you can build and expose business logic and processes to client applications through various protocols including HTTP in a n-tier architecture.
An application server thus offers much more services than an web server which typically include:
AFAIK, ATG Dynamo was one of the very first application server in late 90's (according to the definition above). In early 2000, it was the reign of some proprietary application servers like ColdFusion (CFML AS), BroadVision (Server-side JavaScript AS), etc. But none really survived the Java application server era.
For limited set of values matplotlib is fine. But when you have lots of values the tooltip starts to overlap over other data points. But with limited space you can't ignore the values. Hence it's better to zoom out or zoom in.
Using plotly
import plotly.express as px
df = px.data.tips()
df = px.data.gapminder().query("year==2007 and continent=='Americas'")
fig = px.scatter(df, x="gdpPercap", y="lifeExp", text="country", log_x=True, size_max=100, color="lifeExp")
fig.update_traces(textposition='top center')
fig.update_layout(title_text='Life Expectency', title_x=0.5)
fig.show()
What about data binding?
@JvmStatic
@BindingAdapter("textHtml")
fun setHtml(textView: TextView, resource: String) {
val html: Spanned = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
Html.fromHtml(resource, Html.FROM_HTML_MODE_COMPACT)
} else {
Html.fromHtml(resource)
}
textView.movementMethod = LinkMovementMethod.getInstance()
textView.text = html
}
strings.xml
<string name="text_with_link"><a href=%2$s>%1$s</a> </string>
in your layout.xml
<TextView
android:id="@+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:textHtml="@{@string/text_with_link(model.title, model.url)}"
tools:text="Some text" />
Where title and link in xml is a simple String
Also you can pass multiple arguments to data binding adapter
@JvmStatic
@BindingAdapter(value = ["textLink", "link"], requireAll = true)
fun setHtml(textView: TextView, textLink: String?, link: String?) {
val resource = String.format(textView.context.getString(R.string.text_with_link, textLink, link))
val html: Spanned = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
Html.fromHtml(resource, Html.FROM_HTML_MODE_COMPACT)
} else {
Html.fromHtml(resource)
}
textView.movementMethod = LinkMovementMethod.getInstance()
textView.text = html
}
and in .xml pass arguments separately
<TextView
android:id="@+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:link="@{model.url}"
app:textLink="@{model.title}"
tools:text="Some text" />
If eclipse (none of them) doesn't launch at all and there's not even an error message, uninstall Java 8 Updater and reinstall Java 8 from scratch, this should work. Have luck!
Try just getting the underlying PDO instance. If that fails, then Laravel was unable to connect to the database!
// Test database connection
try {
DB::connection()->getPdo();
} catch (\Exception $e) {
die("Could not connect to the database. Please check your configuration. error:" . $e );
}
Use regular expression is best way to doing this as already mentioned by ashish sahu
public int getInt(String s){
return Integer.parseInt(s.replaceAll("[\\D]", ""));
}
As far as I'm aware this is the only answer here that works correctly with spaces:
space:=
space+=
CURRENT_PATH := $(subst $(lastword $(notdir $(MAKEFILE_LIST))),,$(subst $(space),\$(space),$(shell realpath '$(strip $(MAKEFILE_LIST))')))
It essentially works by escaping space characters by substituting ' '
for '\ '
which allows Make to parse it correctly, and then it removes the filename of the makefile in MAKEFILE_LIST
by doing another substitution so you're left with the directory that makefile is in. Not exactly the most compact thing in the world but it does work.
You'll end up with something like this where all the spaces are escaped:
$(info CURRENT_PATH = $(CURRENT_PATH))
CURRENT_PATH = /mnt/c/Users/foobar/gDrive/P\ roje\ cts/we\ b/sitecompiler/
For others who are experiencing with the same problem, here is the description of the bug in php + patch https://bugs.php.net/bug.php?id=44522
You should declare Environment Variable for PHP in path, so you could use like this:
C:\Path\to\somewhere>php cli.php
You can do it like this
Open an elevated Command Prompt (run cmd as administrator). query your registry for available TT fonts to the console by:
REG query "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Console\TrueTypeFont"
You'll see an output like :
0 REG_SZ Lucida Console
00 REG_SZ Consolas
936 REG_SZ *???
932 REG_SZ *MS ????
Now we need to add a TT font that supports the characters you need like Courier New, we do this by adding zeros to the string name, so in this case the next one would be "000" :
REG ADD "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Console\TrueTypeFont" /v 000 /t REG_SZ /d "Courier New"
Now we implement UTF-8 support:
REG ADD HKCU\Console /v CodePage /t REG_DWORD /d 65001 /f
Set default font to "Courier New":
REG ADD HKCU\Console /v FaceName /t REG_SZ /d "Courier New" /f
Set font size to 20 :
REG ADD HKCU\Console /v FontSize /t REG_DWORD /d 20 /f
Enable quick edit if you like :
REG ADD HKCU\Console /v QuickEdit /t REG_DWORD /d 1 /f
As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers. Users of older versions of jQuery should use .delegate() in preference to .live(). Refer: http://api.jquery.com/on/
$('#imageFile').on("change", function(){ uploadFile(); });
As others have suggested, this might be a use case for loops and iterables. In my opinion, this is the simplest approach. If you want to modify the list in-place, it cannot be considered "real" functional programming anyway. But you could use Collectors.partitioningBy()
in order to get a new list with elements which satisfy your condition, and a new list of those which don't. Of course with this approach, if you have multiple elements satisfying the condition, all of those will be in that list and not only the first.
It can also be caused by piping out of a pair of curly braces on a line.
This fails:
{ /usr/local/bin/mycommand ; outputstatus=$? } >> /var/log/mycommand.log 2>&1h
do_something
#Get NOW that saved output status for the following $? invocation
sh -c "exit $outputstatus"
do_something_more
while this is allowed:
{
/usr/local/bin/mycommand
outputstatus=$?
} >> /var/log/mycommand.log 2>&1h
do_something
#Get NOW that saved output status for the following $? invocation
sh -c "exit $outputstatus"
do_something_more
Manifest.MF contains information about the files contained in the JAR file.
Whenever a JAR file is created a default manifest.mf file is created inside META-INF folder and it contains the default entries like this:
Manifest-Version: 1.0
Created-By: 1.7.0_06 (Oracle Corporation)
These are entries as “header:value” pairs. The first one specifies the manifest version and second one specifies the JDK version with which the JAR file is created.
Main-Class header: When a JAR file is used to bundle an application in a package, we need to specify the class serving an entry point of the application. We provide this information using ‘Main-Class’ header of the manifest file,
Main-Class: {fully qualified classname}
The ‘Main-Class’ value here is the class having main method. After specifying this entry we can execute the JAR file to run the application.
Class-Path header: Most of the times we need to access the other JAR files from the classes packaged inside application’s JAR file. This can be done by providing their fully qualified paths in the manifest file using ‘Class-Path’ header,
Class-Path: {jar1-name jar2-name directory-name/jar3-name}
This header can be used to specify the external JAR files on the same local network and not inside the current JAR.
Package version related headers: When the JAR file is used for package versioning the following headers are used as specified by the Java language specification:
Headers in a manifest
Header | Definition
-------------------------------------------------------------------
Name | The name of the specification.
Specification-Title | The title of the specification.
Specification-Version | The version of the specification.
Specification-Vendor | The vendor of the specification.
Implementation-Title | The title of the implementation.
Implementation-Version | The build number of the implementation.
Implementation-Vendor | The vendor of the implementation.
Package sealing related headers:
We can also specify if any particular packages inside a JAR file should be sealed meaning all the classes defined in that package must be archived in the same JAR file. This can be specified with the help of ‘Sealed’ header,
Name: {package/some-package/} Sealed:true
Here, the package name must end with ‘/’.
Enhancing security with manifest files:
We can use manifest files entries to ensure the security of the web application or applet it packages with the different attributes as ‘Permissions’, ‘Codebae’, ‘Application-Name’, ‘Trusted-Only’ and many more.
META-INF folder:
This folder is where the manifest file resides. Also, it can contain more files containing meta data about the application. For example, in an EJB module JAR file, this folder contains the EJB deployment descriptor for the EJB module along with the manifest file for the JAR. Also, it contains the xml file containing mapping of an abstract EJB references to concrete container resources of the application server on which it will be run.
Reference:
https://docs.oracle.com/javase/tutorial/deployment/jar/manifestindex.html
Description of the possible values:
left
: No floating elements allowed on the left sideright
: No floating elements allowed on the right sideboth
: No floating elements allowed on either the left or the right sidenone
: Default. Allows floating elements on both sidesinherit
: Specifies that the value of the clear property should be inherited from the parent element
Source: w3schools.com
You'd better create some class for each item instead of using anonymous objects. And in object you're serializing you should have array of those items. E.g.:
public class Item
{
public string name { get; set; }
public string index { get; set; }
public string optional { get; set; }
}
public class RootObject
{
public List<Item> items { get; set; }
}
Usage:
var objectToSerialize = new RootObject();
objectToSerialize.items = new List<Item>
{
new Item { name = "test1", index = "index1" },
new Item { name = "test2", index = "index2" }
};
And in the result you won't have to change things several times if you need to change data-structure.
p.s. Here's very nice tool for complex json
s
you forgot to add this in your function : change to this :
<input type="button" value="ahaha" onclick="$(this).MessageBox('msg');" />
To revert a migration:
python manage.py migrate <APP_NAME> <MIGRATION_NUMBER_PREFIX>
MIGRATION_NUMBER_PREFIX
is the number prefix of the migration you want to revert to, for instance 0001
to go to 0001_initial.py
migration. then you can delete that migration.
You can use
zero
as your migration number to revert all migrations of an app.
Well one solution could be:
list.get(list.size()-1)
Edit: You have to convert the collection to a list before maybe like this: new ArrayList(coll)
When the above solution doesn’t work try this:
<IfModule mod_security.c>
SecRuleEngine Off
SecFilterInheritance Off
SecFilterEngine Off
SecFilterScanPOST Off
SecRuleRemoveById 300015 3000016 3000017
</IfModule>
SELECT * FROM table
where Date(col) = 'date'
Symfony 3 and newer
I recently made a function which creates a tree of form errors. This will be helpful for returning list of errors back to front-end. This is based on form types having:
'error_bubbling' => false
Code:
public static function getFormErrorsTree(FormInterface $form): array
{
$errors = [];
if (count($form->getErrors()) > 0) {
foreach ($form->getErrors() as $error) {
$errors[] = $error->getMessage();
}
} else {
foreach ($form->all() as $child) {
$childTree = self::getFormErrorsTree($child);
if (count($childTree) > 0) {
$errors[$child->getName()] = $childTree;
}
}
}
return $errors;
}
Output:
Array
(
[name] => Array
(
[0] => This value is not valid.
)
[emails] => Array
(
[0] => Array
(
[0] => Given e-mail is not valid.
[1] => Given e-mail is not valid #2.
)
[1] => Array
(
[0] => Given e-mail is not valid.
[1] => Given e-mail is not valid #2.
)
)
)
Notice: I know that errors from deeper level fields can be overwritten if higher level has errors, but this is on purpose for my usage.
I figured out what's going on.
When I load a page through a server side action (a url visit), and view the html returned from that action inside a Webview, that first action/page runs inside that Webview. However, when you click on any link that are action commands in your web app, these actions start a new browser. That is why cookie info gets lost because the first cookie information you set for Webview is gone, we have a seperate program here.
You have to intercept clicks on Webview so that browsing never leaves the app, everything stays inside the same Webview.
WebView webview = new WebView(this);
webview.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
view.loadUrl(url); //this is controversial - see comments and other answers
return true;
}
});
setContentView(webview);
webview.loadUrl([MY URL]);
This fixes the problem.
Spring Data JPA by default looks for an EntityManagerFactory named entityManagerFactory
. Check out this part of the Javadoc of EnableJpaRepositories
or Table 2.1
of the Spring Data JPA documentation.
That means that you either have to rename your emf
bean to entityManagerFactory
or change your Spring configuration to:
<jpa:repositories base-package="your.package" entity-manager-factory-ref="emf" />
(if you are using XML)
or
@EnableJpaRepositories(basePackages="your.package", entityManagerFactoryRef="emf")
(if you are using Java Config)
I won't be explaining how the floats work here (in detail), as this question generally focuses on Why use clear: both;
OR what does clear: both;
exactly do...
I'll keep this answer simple, and to the point, and will explain to you graphically why clear: both;
is required or what it does...
Generally designers float the elements, left or to the right, which creates an empty space on the other side which allows other elements to take up the remaining space.
Elements are floated when the designer needs 2 block level elements side by side. For example say we want to design a basic website which has a layout like below...
Live Example of the demo image.
Code For Demo
/* CSS: */_x000D_
_x000D_
* { /* Not related to floats / clear both, used it for demo purpose only */_x000D_
box-sizing: border-box;_x000D_
-moz-box-sizing: border-box;_x000D_
-webkit-box-sizing: border-box;_x000D_
}_x000D_
_x000D_
header, footer {_x000D_
border: 5px solid #000;_x000D_
height: 100px;_x000D_
}_x000D_
_x000D_
aside {_x000D_
float: left;_x000D_
width: 30%;_x000D_
border: 5px solid #000;_x000D_
height: 300px;_x000D_
}_x000D_
_x000D_
section {_x000D_
float: left;_x000D_
width: 70%;_x000D_
border: 5px solid #000;_x000D_
height: 300px;_x000D_
}_x000D_
_x000D_
.clear {_x000D_
clear: both;_x000D_
}
_x000D_
<!-- HTML -->_x000D_
<header>_x000D_
Header_x000D_
</header>_x000D_
<aside>_x000D_
Aside (Floated Left)_x000D_
</aside>_x000D_
<section>_x000D_
Content (Floated Left, Can Be Floated To Right As Well)_x000D_
</section>_x000D_
<!-- Clearing Floating Elements-->_x000D_
<div class="clear"></div>_x000D_
<footer>_x000D_
Footer_x000D_
</footer>
_x000D_
Note: You might have to add header
, footer
, aside
, section
(and other HTML5 elements) as display: block;
in your stylesheet for explicitly mentioning that the elements are block level elements.
I have a basic layout, 1 header, 1 side bar, 1 content area and 1 footer.
No floats for header
, next comes the aside
tag which I'll be using for my website sidebar, so I'll be floating the element to left.
Note: By default, block level element takes up document 100% width, but when floated left or right, it will resize according to the content it holds.
So as you note, the left floated div
leaves the space to its right unused, which will allow the div
after it to shift in the remaining space.
div
's will render one after the other if they are NOT floateddiv
will shift beside each other if floated left or rightOk, so this is how block level elements behave when floated left or right, so now why is clear: both;
required and why?
So if you note in the layout demo - in case you forgot, here it is..
I am using a class called .clear
and it holds a property called clear
with a value of both
. So lets see why it needs both
.
I've floated aside
and section
elements to the left, so assume a scenario, where we have a pool, where header
is solid land, aside
and section
are floating in the pool and footer is solid land again, something like this..
So the blue water has no idea what the area of the floated elements are, they can be bigger than the pool or smaller, so here comes a common issue which troubles 90% of CSS beginners: why the background of a container element is not stretched when it holds floated elements. It's because the container element is a POOL here and the POOL has no idea how many objects are floating, or what the length or breadth of the floated elements are, so it simply won't stretch.
(Refer [Clearfix] section of this answer for neat way to do this. I am using an empty div
example intentionally for explanation purpose)
I've provided 3 examples above, 1st is the normal document flow where red
background will just render as expected since the container doesn't hold any floated objects.
In the second example, when the object is floated to left, the container element (POOL) won't know the dimensions of the floated elements and hence it won't stretch to the floated elements height.
After using clear: both;
, the container element will be stretched to its floated element dimensions.
Another reason the clear: both;
is used is to prevent the element to shift up in the remaining space.
Say you want 2 elements side by side and another element below them... So you will float 2 elements to left and you want the other below them.
div
Floated left resulting in section
moving into remaining spacediv
cleared so that the section
tag will render below the floated div
s Last but not the least, the footer
tag will be rendered after floated elements as I've used the clear
class before declaring my footer
tags, which ensures that all the floated elements (left/right) are cleared up to that point.
Coming to clearfix which is related to floats. As already specified by @Elky, the way we are clearing these floats is not a clean way to do it as we are using an empty div
element which is not a div
element is meant for. Hence here comes the clearfix.
Think of it as a virtual element which will create an empty element for you before your parent element ends. This will self clear your wrapper element holding floated elements. This element won't exist in your DOM literally but will do the job.
To self clear any wrapper element having floated elements, we can use
.wrapper_having_floated_elements:after { /* Imaginary class name */
content: "";
clear: both;
display: table;
}
Note the :after
pseudo element used by me for that class
. That will create a virtual element for the wrapper element just before it closes itself. If we look in the dom you can see how it shows up in the Document tree.
So if you see, it is rendered after the floated child div
where we clear the floats which is nothing but equivalent to have an empty div
element with clear: both;
property which we are using for this too. Now why display: table;
and content
is out of this answers scope but you can learn more about pseudo element here.
Note that this will also work in IE8 as IE8 supports :after
pseudo.
Most of the developers float their content left or right on their pages, probably divs holding logo, sidebar, content etc., these divs are floated left or right, leaving the rest of the space unused and hence if you place other containers, it will float too in the remaining space, so in order to prevent that clear: both;
is used, it clears all the elements floated left or right.
------------------ ----------------------------------
div1(Floated Left) Other div takes up the space here
------------------ ----------------------------------
Now what if you want to make the other div render below div1
, so you'll use clear: both;
so it will ensure you clear all floats, left or right
------------------
div1(Floated Left)
------------------
<div style="clear: both;"><!--This <div> acts as a separator--></div>
----------------------------------
Other div renders here now
----------------------------------
Just use
Request::fullUrl()
It will return the full url
You can extract the Querystring with str_replace
str_replace(Request::url(), '', Request::fullUrl())
Or you can get a array of all the queries with
Request::query()
Just use
$request->fullUrl()
It will return the full url
You can extract the Querystring with str_replace
str_replace($request->url(), '',$request->fullUrl())
Or you can get a array of all the queries with
$request->query()
Try this way, almost same.. but that's what I did, and working.
<configuration>
<system.web>
<customErrors mode="On" defaultRedirect="apperror.aspx">
<error statusCode="404" redirect="404.aspx" />
<error statusCode="500" redirect="500.aspx" />
</customErrors>
</system.web>
</configuration>
or try to change the 404 error page from IIS settings, if required urgently.
I'm not sure if you want to find duplicate files or just compare two single files. If the latter, the above approach (filecmp) is better, if the former, the following approach is better.
There are lots of duplicate files detection questions here. Assuming they are not very small and that performance is important, you can
Here's is an answer with Python implementations (I prefer the one by nosklo, BTW)
Here is how you do it with some simple Excel formulae, and no fancy VBA needed. The trick is to use the OFFSET formula. Please see this example spreadsheet:
You only need to clear your list on OnPostExecute()
and not while doing Pull to Refresh
// Setup refresh listener which triggers new data loading
swipeContainer.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
AsyncTask<String,Void,String> task = new get_listings();
task.execute(); // clear listing inside onPostExecute
}
});
I discovered that this happens when you scroll during a pull to refresh, since I was clearing the list before the async task
, resulting to java.lang.IndexOutOfBoundsException: Inconsistency detected.
swipeContainer.setRefreshing(false);
//TODO : This is very crucial , You need to clear before populating new items
listings.clear();
That way you won't end with an inconsistency
You could store this into a temporary table.
So instead of doing the CTE/sub query you would use a temp table.
Good article on these here http://codingsight.com/introduction-to-temporary-tables-in-sql-server/
If you need an empty folder you can loop until you get an empty folder
QString folder= QString ("%1").arg(QDateTime::currentMSecsSinceEpoch());
while(QDir(folder).exists())
{
folder= QString ("%1").arg(QDateTime::currentMSecsSinceEpoch());
}
QDir().mkdir(folder);
This case you will get a folder name with a number .
Define your database name like :
private static final String DATABASE_NAME = "/mnt/sdcard/hri_database.db";
And you can see your database in :
storage/sdcard0/yourdatabasename.db
The documentation for focusout says (emphasis mine):
The
focusout
event is sent to an element when it, or any element inside of it, loses focus. This is distinct from theblur
event in that it supports detecting the loss of focus on descendant elements (in other words, it supports event bubbling).
The same distinction exists between the focusin and focus events.
Standard freeze function of built-in Object can be used to freeze an object containing constants.
var obj = {
constant_1 : 'value_1'
};
Object.freeze(obj);
obj.constant_1 = 'value_2'; //Silently does nothing
obj.constant_2 = 'value_3'; //Silently does nothing
In strict mode, setting values on immutable object throws TypeError. For more details, see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze
I realise this answer is late, but I found a rather simple, elegant, and effective solution to this problem and felt it necessary to post it here.
However one thing I feel I need to make clear is that this doesn't start gif animation on mouseover, pause it on mouseout, and continue it when you mouseover it again. That, unfortunately, is impossible to do with gifs. (It is possible to do with a string of images displayed one after another to look like a gif, but taking apart every frame of your gifs and copying all those urls into a script would be time consuming)
What my solution does is make an image looks like it starts moving on mouseover. You make the first frame of your gif an image and put that image on the webpage then replace the image with the gif on mouseover and it looks like it starts moving. It resets on mouseout.
Just insert this script in the head section of your HTML:
$(document).ready(function()
{
$("#imgAnimate").hover(
function()
{
$(this).attr("src", "GIF URL HERE");
},
function()
{
$(this).attr("src", "STATIC IMAGE URL HERE");
});
});
And put this code in the img tag of the image you want to animate.
id="imgAnimate"
This will load the gif on mouseover, so it will seem like your image starts moving. (This is better than loading the gif onload because then the transition from static image to gif is choppy because the gif will start on a random frame)
for more than one image just recreate the script create a function:
<script type="text/javascript">
var staticGifSuffix = "-static.gif";
var gifSuffix = ".gif";
$(document).ready(function() {
$(".img-animate").each(function () {
$(this).hover(
function()
{
var originalSrc = $(this).attr("src");
$(this).attr("src", originalSrc.replace(staticGifSuffix, gifSuffix));
},
function()
{
var originalSrc = $(this).attr("src");
$(this).attr("src", originalSrc.replace(gifSuffix, staticGifSuffix));
}
);
});
});
</script>
</head>
<body>
<img class="img-animate" src="example-static.gif" >
<img class="img-animate" src="example-static.gif" >
<img class="img-animate" src="example-static.gif" >
<img class="img-animate" src="example-static.gif" >
<img class="img-animate" src="example-static.gif" >
</body>
That code block is a functioning web page (based on the information you have given me) that will display the static images and on hover, load and display the gif's. All you have to do is insert the url's for the static images.
CharSequence
is a contract (interface), and String
is an implementation of this contract.
public final class String extends Object
implements Serializable, Comparable<String>, CharSequence
The documentation for CharSequence
is:
A CharSequence is a readable sequence of char values. This interface provides uniform, read-only access to many different kinds of char sequences. A char value represents a character in the Basic Multilingual Plane (BMP) or a surrogate. Refer to Unicode Character Representation for details.
Combining some of the previous answers, this is the seedable random function you are looking for:
Math.seed = function(s) {
var mask = 0xffffffff;
var m_w = (123456789 + s) & mask;
var m_z = (987654321 - s) & mask;
return function() {
m_z = (36969 * (m_z & 65535) + (m_z >>> 16)) & mask;
m_w = (18000 * (m_w & 65535) + (m_w >>> 16)) & mask;
var result = ((m_z << 16) + (m_w & 65535)) >>> 0;
result /= 4294967296;
return result;
}
}
var myRandomFunction = Math.seed(1234);
var randomNumber = myRandomFunction();
Iterations
Method 1: forEach
method
messages.forEach(function(message) {
console.log(message);
}
Method 2: for..of
method
for(let message of messages){
console.log(message);
}
Note: This method might not work with objects, such as:
let obj = { a: 'foo', b: { c: 'bar', d: 'daz' }, e: 'qux' }
Method 2: for..in
method
for(let key in messages){
console.log(messages[key]);
}
Not only can you, but you have to make a special effort not to if you don't want to. :-)
When the browser encounters a classic script
tag when parsing the HTML, it stops parsing and hands over to the JavaScript interpreter, which runs the script. The parser doesn't continue until the script execution is complete (because the script might do document.write
calls to output markup that the parser should handle).
That's the default behavior, but you have a few options for delaying script execution:
Use JavaScript modules. A type="module"
script is deferred until the HTML has been fully parsed and the initial DOM created. This isn't the primary reason to use modules, but it's one of the reasons:
<script type="module" src="./my-code.js"></script>
<!-- Or -->
<script type="module">
// Your code here
</script>
The code will be fetched (if it's separate) and parsed in parallel with the HTML parsing, but won't be run until the HTML parsing is done. (If your module code is inline rather than in its own file, it is also deferred until HTML parsing is complete.)
This wasn't available when I first wrote this answer in 2010, but here in 2020, all major modern browsers support modules natively, and if you need to support older browsers, you can use bundlers like Webpack and Rollup.js.
Use the defer
attribute on a classic script tag:
<script defer src="./my-code.js"></script>
As with the module, the code in my-code.js
will be fetched and parsed in parallel with the HTML parsing, but won't be run until the HTML parsing is done. But, defer
doesn't work with inline script content, only with external files referenced via src
.
I don't think it's what you want, but you can use the async
attribute to tell the browser to fetch the JavaScript code in parallel with the HTML parsing, but then run it as soon as possible, even if the HTML parsing isn't complete. You can put it on a type="module"
tag, or use it instead of defer
on a classic script
tag.
Put the script
tag at the end of the document, just prior to the closing </body>
tag:
<!doctype html>
<html>
<!-- ... -->
<body>
<!-- The document's HTML goes here -->
<script type="module" src="./my-code.js"></script><!-- Or inline script -->
</body>
</html>
That way, even though the code is run as soon as its encountered, all of the elements defined by the HTML above it exist and are ready to be used.
It used to be that this caused an additional delay on some browsers because they wouldn't start fetching the code until the script
tag was encountered, but modern browsers scan ahead and start prefetching. Still, this is very much the third choice at this point, both modules and defer
are better options.
The spec has a useful diagram showing a raw script
tag, defer
, async
, type="module"
, and type="module" async
and the timing of when the JavaScript code is fetched and run:
Here's an example of the default behavior, a raw script
tag:
.found {_x000D_
color: green;_x000D_
}
_x000D_
<p>Paragraph 1</p>_x000D_
<script>_x000D_
if (typeof NodeList !== "undefined" && !NodeList.prototype.forEach) {_x000D_
NodeList.prototype.forEach = Array.prototype.forEach;_x000D_
}_x000D_
document.querySelectorAll("p").forEach(p => {_x000D_
p.classList.add("found");_x000D_
});_x000D_
</script>_x000D_
<p>Paragraph 2</p>
_x000D_
(See my answer here for details around that NodeList
code.)
When you run that, you see "Paragraph 1" in green but "Paragraph 2" is black, because the script ran synchronously with the HTML parsing, and so it only found the first paragraph, not the second.
In contrast, here's a type="module"
script:
.found {_x000D_
color: green;_x000D_
}
_x000D_
<p>Paragraph 1</p>_x000D_
<script type="module">_x000D_
document.querySelectorAll("p").forEach(p => {_x000D_
p.classList.add("found");_x000D_
});_x000D_
</script>_x000D_
<p>Paragraph 2</p>
_x000D_
Notice how they're both green now; the code didn't run until HTML parsing was complete. That would also be true with a defer
script
with external content (but not inline content).
(There was no need for the NodeList
check there because any modern browser supporting modules already has forEach
on NodeList
.)
In this modern world, there's no real value to the DOMContentLoaded
event of the "ready" feature that PrototypeJS, jQuery, ExtJS, Dojo, and most others provided back in the day (and still provide); just use modules or defer
. Even back in the day, there wasn't much reason for using them (and they were often used incorrectly, holding up page presentation while the entire jQuery library was loaded because the script
was in the head
instead of after the document), something some developers at Google flagged up early on. This was also part of the reason for the YUI recommendation to put scripts at the end of the body
, again back in the day.
I would recommend a combination of PatIndex and Left. Carefully constructed, you can write a query that always works, no matter what your data looks like.
Ex:
Declare @Temp Table(Data VarChar(20))
Insert Into @Temp Values('BTA200')
Insert Into @Temp Values('BTA50')
Insert Into @Temp Values('BTA030')
Insert Into @Temp Values('BTA')
Insert Into @Temp Values('123')
Insert Into @Temp Values('X999')
Select Data, Left(Data, PatIndex('%[0-9]%', Data + '1') - 1)
From @Temp
PatIndex will look for the first character that falls in the range of 0-9, and return it's character position, which you can use with the LEFT function to extract the correct data. Note that PatIndex is actually using Data + '1'. This protects us from data where there are no numbers found. If there are no numbers, PatIndex would return 0. In this case, the LEFT function would error because we are using Left(Data, PatIndex - 1). When PatIndex returns 0, we would end up with Left(Data, -1) which returns an error.
There are still ways this can fail. For a full explanation, I encourage you to read:
Extracting numbers with SQL Server
That article shows how to get numbers out of a string. In your case, you want to get alpha characters instead. However, the process is similar enough that you can probably learn something useful out of it.
You can import a csv file to this website(https://www.tablesgenerator.com/latex_tables) and click copy to clipboard.
its working with this code
text-align: justify; text-align-last: center;
This can be done with CSS3:
<input type="text" />
input
{
-moz-border-radius: 15px;
border-radius: 15px;
border:solid 1px black;
padding:5px;
}
However, an alternative would be to put the input
inside a div
with a rounded background, and no border on the input
Go to [Tool Window\Project] by Alt+1, and change the level on the top-left corner of this window to Project (the other two are Packages and Android), then you can rename the Project name by Shift+F6. Type in the new name and press OK.
If you just want to change the app name which appears in the system, you can modify the android:title
in the manifest.xml.
Tested for PHP 5.3
As i see here, Anonymous Function could help you: http://php.net/manual/en/functions.anonymous.php
What you'll probably need and it's not said before it's how to pass a function without wrapping it inside a on-the-fly-created function. As you'll see later, you'll need to pass the function's name written in a string as a parameter, check its "callability" and then call it.
The function to do check:
if( is_callable( $string_function_name ) ){
/*perform the call*/
}
Then, to call it, use this piece of code (if you need parameters also, put them on an array), seen at : http://php.net/manual/en/function.call-user-func.php
call_user_func_array( "string_holding_the_name_of_your_function", $arrayOfParameters );
as it follows (in a similar, parameterless, way):
function funToBeCalled(){
print("----------------------i'm here");
}
function wrapCaller($fun){
if( is_callable($fun)){
print("called");
call_user_func($fun);
}else{
print($fun." not called");
}
}
wrapCaller("funToBeCalled");
wrapCaller("cannot call me");
Here's a class explaining how to do something similar :
<?php
class HolderValuesOrFunctionsAsString{
private $functions = array();
private $vars = array();
function __set($name,$data){
if(is_callable($data))
$this->functions[$name] = $data;
else
$this->vars[$name] = $data;
}
function __get($name){
$t = $this->vars[$name];
if(isset($t))
return $t;
else{
$t = $this->$functions[$name];
if( isset($t))
return $t;
}
}
function __call($method,$args=null){
$fun = $this->functions[$method];
if(isset($fun)){
call_user_func_array($fun,$args);
} else {
// error out
print("ERROR: Funciton not found: ". $method);
}
}
}
?>
and an example of usage
<?php
/*create a sample function*/
function sayHello($some = "all"){
?>
<br>hello to <?=$some?><br>
<?php
}
$obj = new HolderValuesOrFunctionsAsString;
/*do the assignement*/
$obj->justPrintSomething = 'sayHello'; /*note that the given
"sayHello" it's a string ! */
/*now call it*/
$obj->justPrintSomething(); /*will print: "hello to all" and
a break-line, for html purpose*/
/*if the string assigned is not denoting a defined method
, it's treat as a simple value*/
$obj->justPrintSomething = 'thisFunctionJustNotExistsLOL';
echo $obj->justPrintSomething; /*what do you expect to print?
just that string*/
/*N.B.: "justPrintSomething" is treated as a variable now!
as the __set 's override specify"*/
/*after the assignement, the what is the function's destiny assigned before ? It still works, because it's held on a different array*/
$obj->justPrintSomething("Jack Sparrow");
/*You can use that "variable", ie "justPrintSomething", in both ways !! so you can call "justPrintSomething" passing itself as a parameter*/
$obj->justPrintSomething( $obj->justPrintSomething );
/*prints: "hello to thisFunctionJustNotExistsLOL" and a break-line*/
/*in fact, "justPrintSomething" it's a name used to identify both
a value (into the dictionary of values) or a function-name
(into the dictionary of functions)*/
?>
A TINYINT is an 8-bit integer value, a BIT field can store between 1 bit, BIT(1), and 64 bits, BIT(64). For a boolean values, BIT(1) is pretty common.
You can do this:
cat("File not supplied.\nUsage: ./program F=filename\n")
Notice that cat
has a return
value of NULL
.
To answer the title of your question directly because this comes up in Google first:
YES, TypeScript can export a function!
Here is a direct quote from the TS Documentation:
"Any declaration (such as a variable, function, class, type alias, or interface) can be exported by adding the export keyword."
Yacoby's answer inspires me to write an adaptor for encapsulating the functor boilerplate.
template< class T, bool (*comp)( T const &, T const & ) >
class set_funcomp {
struct ftor {
bool operator()( T const &l, T const &r )
{ return comp( l, r ); }
};
public:
typedef std::set< T, ftor > t;
};
// usage
bool my_comparison( foo const &l, foo const &r );
set_funcomp< foo, my_comparison >::t boo; // just the way you want it!
Wow, I think that was worth the trouble!
If they are two integers you can try a quick and dirty trick: Map<String, ?>
using the key as i+"#"+j
.
If the key i+"#"+j
is the same as j+"#"+i
try min(i,j)+"#"+max(i,j)
.
This will work for any field you pass to it. (IMPORTANT: It will only order alphabetically so if you pass a date it will order it as alphabet not as date)
/*
* Example use
* Basic Array of single type: *ngFor="let todo of todoService.todos | orderBy : '-'"
* Multidimensional Array Sort on single column: *ngFor="let todo of todoService.todos | orderBy : ['-status']"
* Multidimensional Array Sort on multiple columns: *ngFor="let todo of todoService.todos | orderBy : ['status', '-title']"
*/
import {Pipe, PipeTransform} from "@angular/core";
@Pipe({name: "orderBy", pure: false})
export class OrderByPipe implements PipeTransform {
value: string[] = [];
static _orderByComparator(a: any, b: any): number {
if (a === null || typeof a === "undefined") { a = 0; }
if (b === null || typeof b === "undefined") { b = 0; }
if (
(isNaN(parseFloat(a)) ||
!isFinite(a)) ||
(isNaN(parseFloat(b)) || !isFinite(b))
) {
// Isn"t a number so lowercase the string to properly compare
a = a.toString();
b = b.toString();
if (a.toLowerCase() < b.toLowerCase()) { return -1; }
if (a.toLowerCase() > b.toLowerCase()) { return 1; }
} else {
// Parse strings as numbers to compare properly
if (parseFloat(a) < parseFloat(b)) { return -1; }
if (parseFloat(a) > parseFloat(b)) { return 1; }
}
return 0; // equal each other
}
public transform(input: any, config = "+"): any {
if (!input) { return input; }
// make a copy of the input"s reference
this.value = [...input];
let value = this.value;
if (!Array.isArray(value)) { return value; }
if (!Array.isArray(config) || (Array.isArray(config) && config.length === 1)) {
let propertyToCheck: string = !Array.isArray(config) ? config : config[0];
let desc = propertyToCheck.substr(0, 1) === "-";
// Basic array
if (!propertyToCheck || propertyToCheck === "-" || propertyToCheck === "+") {
return !desc ? value.sort() : value.sort().reverse();
} else {
let property: string = propertyToCheck.substr(0, 1) === "+" || propertyToCheck.substr(0, 1) === "-"
? propertyToCheck.substr(1)
: propertyToCheck;
return value.sort(function(a: any, b: any) {
let aValue = a[property];
let bValue = b[property];
let propertySplit = property.split(".");
if (typeof aValue === "undefined" && typeof bValue === "undefined" && propertySplit.length > 1) {
aValue = a;
bValue = b;
for (let j = 0; j < propertySplit.length; j++) {
aValue = aValue[propertySplit[j]];
bValue = bValue[propertySplit[j]];
}
}
return !desc
? OrderByPipe._orderByComparator(aValue, bValue)
: -OrderByPipe._orderByComparator(aValue, bValue);
});
}
} else {
// Loop over property of the array in order and sort
return value.sort(function(a: any, b: any) {
for (let i = 0; i < config.length; i++) {
let desc = config[i].substr(0, 1) === "-";
let property = config[i].substr(0, 1) === "+" || config[i].substr(0, 1) === "-"
? config[i].substr(1)
: config[i];
let aValue = a[property];
let bValue = b[property];
let propertySplit = property.split(".");
if (typeof aValue === "undefined" && typeof bValue === "undefined" && propertySplit.length > 1) {
aValue = a;
bValue = b;
for (let j = 0; j < propertySplit.length; j++) {
aValue = aValue[propertySplit[j]];
bValue = bValue[propertySplit[j]];
}
}
let comparison = !desc
? OrderByPipe._orderByComparator(aValue, bValue)
: -OrderByPipe._orderByComparator(aValue, bValue);
// Don"t return 0 yet in case of needing to sort by next property
if (comparison !== 0) { return comparison; }
}
return 0; // equal each other
});
}
}
}
Try using the Worksheet.Protect
method, like so:
Sub ProtectActiveSheet()
Dim ws As Worksheet
Set ws = ActiveSheet
ws.Protect DrawingObjects:=True, Contents:=True, _
Scenarios:=True, Password="SamplePassword"
End Sub
You should, however, be concerned about including the password in your VBA code. You don't necessarily need a password if you're only trying to put up a simple barrier that keeps a user from making small mistakes like deleting formulas, etc.
Also, if you want to see how to do certain things in VBA in Excel, try recording a Macro and looking at the code it generates. That's a good way to get started in VBA.
You can use directly replace function on javascript with regex or define a help function as in php ltrim(left) and rtrim(right):
1) With replace:
var myArray = ",'first string','more','even more'".replace(/^\s+/, '').split(/'?,?'/);
2) Help functions:
if (!String.prototype.ltrim) String.prototype.ltrim = function() {
return this.replace(/^\s+/, '');
};
if (!String.prototype.rtrim) String.prototype.rtrim = function() {
return this.replace(/\s+$/, '');
};
var myArray = ",'first string','more','even more'".ltrim().split(/'?,?'/).filter(function(el) {return el.length != 0});;
You can do and other things to add parameter to the help function with what you want to replace the char, etc.
date +%H:%M
Would be easier, I think :). If you really wanted to chop off the seconds, you could have done
date | sed 's/.* \([0-9]*:[0-9]*\):[0-9]*.*/\1/'
In my view, dates and times should be handled as two separate input boxes for it to be most usable and efficient for the user to input. Let the user input one thing at a time is a good principle, imho.
I use the core UI DatePicker, and the following time picker.
This one is inspired by the one Google Calendar uses:
jQuery timePicker:
examples: http://labs.perifer.se/timedatepicker/
project on github: https://github.com/perifer/timePicker
I found it to be the best among all of the alternatives. User can input fast, it looks clean, is simple, and allows user to input specific times down to the minute.
PS: In my view: sliders (used by some alternative time pickers) take too many clicks and require mouse precision from the user (which makes input slower).
adb kill-server
and adb start-server
only control the adb
daemon on the PC side. You need to restart adbd
daemon on the device itself after reverting the service.adb.root
property change done by adb root
:
~$ adb shell id
uid=2000(shell) gid=2000(shell)
~$ adb root
restarting adbd as root
~$ adb shell id
uid=0(root) gid=0(root)
~$ adb shell 'setprop service.adb.root 0; setprop ctl.restart adbd'
~$ adb shell id
uid=2000(shell) gid=2000(shell)
<script src="jquery.min.js"></script>
<table border="1" id="ReportTable" class="myClass">
<tr bgcolor="#CCC">
<td width="100">xxxxx</td>
<td width="700">xxxxxx</td>
<td width="170">xxxxxx</td>
<td width="30">xxxxxx</td>
</tr>
<tr bgcolor="#FFFFFF">
<td><?php
$date = date_create($row_Recordset3['fecha']);
echo date_format($date, 'd-m-Y');
?></td>
<td><?php echo $row_Recordset3['descripcion']; ?></td>
<td><?php echo $row_Recordset3['producto']; ?></td>
<td><img src="borrar.png" width="14" height="14" class="clickable" onClick="eliminarSeguimiento(<?php echo $row_Recordset3['idSeguimiento']; ?>)" title="borrar"></td>
</tr>
</table>
<input type="hidden" id="datatodisplay" name="datatodisplay">
<input type="submit" value="Export to Excel">
exporttable.php
<?php
header('Content-Type: application/force-download');
header('Content-disposition: attachment; filename=export.xls');
// Fix for crappy IE bug in download.
header("Pragma: ");
header("Cache-Control: ");
echo $_REQUEST['datatodisplay'];
?>
Simple bar graph:
set boxwidth 0.5
set style fill solid
plot "data.dat" using 1:3:xtic(2) with boxes
data.dat:
0 label 100
1 label2 450
2 "bar label" 75
If you want to style your bars differently, you can do something like:
set style line 1 lc rgb "red"
set style line 2 lc rgb "blue"
set style fill solid
set boxwidth 0.5
plot "data.dat" every ::0::0 using 1:3:xtic(2) with boxes ls 1, \
"data.dat" every ::1::2 using 1:3:xtic(2) with boxes ls 2
If you want to do multiple bars for each entry:
data.dat:
0 5
0.5 6
1.5 3
2 7
3 8
3.5 1
gnuplot:
set xtics ("label" 0.25, "label2" 1.75, "bar label" 3.25,)
set boxwidth 0.5
set style fill solid
plot 'data.dat' every 2 using 1:2 with boxes ls 1,\
'data.dat' every 2::1 using 1:2 with boxes ls 2
If you want to be tricky and use some neat gnuplot tricks:
Gnuplot has psuedo-columns that can be used as the index to color:
plot 'data.dat' using 1:2:0 with boxes lc variable
Further you can use a function to pick the colors you want:
mycolor(x) = ((x*11244898) + 2851770)
plot 'data.dat' using 1:2:(mycolor($0)) with boxes lc rgb variable
Note: you will have to add a couple other basic commands to get the same effect as the sample images.
This may be your websocket URL you are using in device are not same(You are hitting different websocket URL from android/iphonedevice )
You can use this for direct find value via params name.
const urlParams = new URLSearchParams(window.location.search);
const myParam = urlParams.get('myParam');
Use setDate
.datepicker( "setDate" , date )
Sets the current date for the datepicker. The new date may be a Date object or a string in the current date format (e.g. '01/26/2009'), a number of days from today (e.g. +7) or a string of values and periods ('y' for years, 'm' for months, 'w' for weeks, 'd' for days, e.g. '+1m +7d'), or null to clear the selected date.
You don't need --header "Content-Length: $LENGTH".
curl --request POST --data-binary "@template_entry.xml" $URL
Note that GET request does not support content body widely.
Also remember that POST request have 2 different coding schema. This is first form:
$ nc -l -p 6666 & $ curl --request POST --data-binary "@README" http://localhost:6666 POST / HTTP/1.1 User-Agent: curl/7.21.0 (x86_64-pc-linux-gnu) libcurl/7.21.0 OpenSSL/0.9.8o zlib/1.2.3.4 libidn/1.15 libssh2/1.2.6 Host: localhost:6666 Accept: */* Content-Length: 9309 Content-Type: application/x-www-form-urlencoded Expect: 100-continue .. -*- mode: rst; coding: cp1251; fill-column: 80 -*- .. rst2html.py README README.html .. contents::
You probably request this:
-F/--form name=content (HTTP) This lets curl emulate a filled-in form in which a user has pressed the submit button. This causes curl to POST data using the Content- Type multipart/form-data according to RFC2388. This enables uploading of binary files etc. To force the 'content' part to be a file, prefix the file name with an @ sign. To just get the content part from a file, prefix the file name with the symbol <. The difference between @ and < is then that @ makes a file get attached in the post as a file upload, while the < makes a text field and just get the contents for that text field from a file.
Update: In an effort to answer my own question, here is what I've been able to uncover so far. If anyone else out there has something, I'd still be interested to find out more.
Based on JSON Schema
Commercial (No endorsement intended or implied, may or may not meet requirement)
jQuery
YAML
See Also
You could wrap all your checkboxes in a parent class and check the length of .checked
..
if( $('.your-parent-class').find('.checked').length ){
$(".hide").toggle();
}
Right click project solution
Properties -> Configuration Properties -> C/C++ -> Precompiled Headers
Click on "Precompiled Headers" change to "Not Using Precompiled Headers".
Erase the "pch.h"/"stdafx.h" field in "Precompiled Header File" for the EOF error at the end of the build for the project.
Then you can feel free to delete the pch./stdafx. files in your project
The plugin vim-autoformat lets you format your buffer (or buffer selections) with a single command: https://github.com/Chiel92/vim-autoformat. It uses external format programs for that, with a fallback to vim's indentation functionality.
If I remember correctly, you'll need to set the netbeans_jdkhome
property in your netbeans config file. Should be in your etc/netbeans.conf
file.
For Java 8 and above, it's easy:
when(mock.process(Matchers.anyList()));
For Java 7 and below, the compiler needs a bit of help. Use anyListOf(Class<T> clazz)
:
when(mock.process(Matchers.anyListOf(Bar.class)));
window.onload will work like this:
function codeAddress() {_x000D_
document.getElementById("test").innerHTML=Date();_x000D_
}_x000D_
window.onload = codeAddress;
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<title>learning java script</title>_x000D_
<script src="custom.js"></script>_x000D_
</head>_x000D_
<body>_x000D_
<p id="test"></p>_x000D_
<li>abcd</li>_x000D_
</body>_x000D_
</html>
_x000D_
Try runiing this Program for better understanding
public class FinalizeTest
{
static {
System.out.println(Runtime.getRuntime().freeMemory());
}
public void run() {
System.out.println("run");
System.out.println(Runtime.getRuntime().freeMemory());
}
protected void finalize() throws Throwable {
System.out.println("finalize");
while(true)
break;
}
public static void main(String[] args) {
for (int i = 0 ; i < 500000 ; i++ ) {
new FinalizeTest().run();
}
}
}
Most of the answers are from the Xcode 4-5 era. I recommend an ignore file in a modern style.
# Xcode Project
**/*.xcodeproj/xcuserdata/
**/*.xcworkspace/xcuserdata/
**/*.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist
**/*.xcworkspace/xcshareddata/*.xccheckout
**/*.xcworkspace/xcshareddata/*.xcscmblueprint
**/*.playground/**/timeline.xctimeline
.idea/
# Build
build/
DerivedData/
*.ipa
# CocoaPods
Pods/
# fastlane
fastlane/report.xml
fastlane/Preview.html
fastlane/screenshots
fastlane/test_output
fastlane/sign&cert
# CSV
*.orig
.svn
# Other
*~
.DS_Store
*.swp
*.save
._*
*.bak
Keep it updated from: https://github.com/BB9z/iOS-Project-Template/blob/master/.gitignore
Please note that Arrays.stream(arr) create a LongStream (or IntStream, ...) instead of Stream so the map function cannot be used to modify the type. This is why .mapToLong, mapToObject, ... functions are provided.
Take a look at why-cant-i-map-integers-to-strings-when-streaming-from-an-array
os.path.basename(os.path.normpath('/folderA/folderB/folderC/folderD/'))
>>> folderD
In case someone is using python and linux and looking for full path to file:
>>> path=os.popen("readlink -f file").read()
>>> print path
abs/path/to/file
class myFileReaderThatStarts with arguments
{
class MissingArgumentException extends Exception{
MissingArgumentException(String s)
{
super(s);
}
}
public static void main(String[] args) throws MissingArgumentException
{
//You can test args array for value
if(args.length>0)
{
// do something with args[0]
}
else
{
// default in a path
// or
throw new MissingArgumentException("You need to start this program with a path");
}
}
Besides the other answers. You should notice these args can give you the file path that was dragged and dropped on the .exe
file.
i.e if you drag and drop any file on your .exe
file then the application will be launched and the arg[0]
will contain the file path that was dropped onto it.
static void Main(string[] args)
{
Console.WriteLine(args[0]);
}
this will print the path of the file dropped on the .exe
file. e.g
C:\Users\ABCXYZ\source\repos\ConsoleTest\ConsoleTest\bin\Debug\ConsoleTest.pdb
Hence, looping through the args
array will give you the path of all the files that were selected and dragged and dropped onto the .exe
file of your console app. See:
static void Main(string[] args)
{
foreach (var arg in args)
{
Console.WriteLine(arg);
}
Console.ReadLine();
}
The code sample above will print all the file names that were dragged and dropped onto it, See I am dragging 5 files onto my ConsoleTest.exe
app.
This worked for me for MAC https://flipdazed.github.io/blog/osx%20maintenance/set-up-mysql-osx
Start mysql by running
brew services start mysql
Run the installation script
mysql_secure_installation
You will be asked to set up a setup VALIDATE PASSWORD plugin. Enter y to do this.
Select the required password validation (Doesn’t really matter if it is just you using the database)
Now select y for all the remaining options: Remove anon. users; disallow remote root logins; remove test database; reload privileges tables. Now you should receive a message of
All done!
You don't need the into statements:
var query =
from customer in dc.Customers
from order in dc.Orders
.Where(o => customer.CustomerId == o.CustomerId)
.DefaultIfEmpty()
select new { Customer = customer, Order = order }
//Order will be null if the left join is null
And yes, the query above does indeed create a LEFT OUTER join.
Link to a similar question that handles multiple left joins: Linq to Sql: Multiple left outer joins
df[df$aged <= df$laclen, ]
Should do the trick. The square brackets allow you to index based on a logical expression.
>>> m = max(a)
>>> [i for i, j in enumerate(a) if j == m]
[9, 12]
when you make a COUNT(*) in your mysql statement like in
$q = $db->query("SELECT COUNT(*) FROM ...");
your mysql query is already counting the number of result why counting again in php? to get the result of your mysql
$q = $db->query("SELECT COUNT(*) as counted FROM ...");
$nb = $q->fetch(PDO::FETCH_OBJ);
$nb = $nb->counted;
and $nb
will contain the integer you have counted with your mysql statement
a bit long to write but fast to execute
Edit: sorry for the wrong post but as some example show query with count in, I was suggesting using the mysql result, but if you don't use the count in sql fetchAll() is efficient, if you save the result in a variable you won't loose a line.
$data = $dbh->query("SELECT * FROM ...");
$table = $data->fetchAll(PDO::FETCH_OBJ);
count($table)
will return the number of row and you can still use the result after like $row = $table[0]
or using a foreach
foreach($table as $row){
print $row->id;
}
This would be easier to do with flexbox. Using flexbox will let you not to specify the height of your content and can adjust automatically on the height it contains.
here's the gist of the demo
.container{
display: flex;
height: 100%;
justify-content: center;
align-items: center;
}
html
<div class="container">
<div class='content'> //you can size this anyway you want
put anything you want here,
</div>
</div>
Answer based on JQuery < 3
$('#iframeid').load(function(){
alert('frame has (re)loaded');
});
As mentioned by subharb, as from JQuery 3.0 this needs to be changed to:
$('#iframe').on('load', function() {
alert('frame has (re)loaded ');
});
https://jquery.com/upgrade-guide/3.0/#breaking-change-load-unload-and-error-removed
System.out.print("Enter a Value: ");
val = s.nextInt();
This line is placed in last.The whole code is as follows:-
public static void main(String[] args){
int min, max;
Scanner s = new Scanner(System.in);
System.out.print("Enter a Value: ");
int val = s.nextInt();
min = max = val;
while (val != 0) {
if (val < min) {
min = val;
}
if (val > max) {
max = val;
}
System.out.print("Enter a Value: ");
val = s.nextInt();
}
System.out.println("Min: " + min);
System.out.println("Max: " + max);
}
Below are some notes which i pulled from this codeproject article on C# Out Vs Ref
If you are a visual person then please see this yourtube video which demonstrates the difference practically https://www.youtube.com/watch?v=lYdcY5zulXA
Below image shows the differences more visually
You also can try this:
Step 1: adb shell Step 2: ip -f inet addr show wlan0
l = [1,2,2,3,3,...]
n = []
n.extend(ele for ele in l if ele not in set(n))
A generator expression that uses the O(1) look up of a set to determine whether or not to include an element in the new list.
Currently from MySQL 8
you can set the following to a DATE
column:
In MySQL Workbench
, in the Default
field next to the column, write: (curdate())
If you put just curdate()
it will fail. You need the extra (
and )
at the beginning and end.
**
Using following SQL we can get the distinct column value count in Oracle 11g.
**
Select count(distinct(Column_Name)) from TableName
std::queue<myclass*> my_queue;
will do the job.
See here for more information on this container.
.class {
font-size: clamp(minimum-size, prefered-size, maximum-size)
}
using this you could set it up so prefered and max values are 5vw but the minimum is 15px or something so it won't go over 5vw but if 5vw < 15px it will stick to 15px
You just missed an extra pair of brackets for the "OR" symbol. The following should do the trick:
([0-9]+)\s+((\bseconds\b)|(\bminutes\b))
Without those you were either matching a number followed by seconds OR just the word minutes
You could use the alternative syntax alternative syntax for control structures and break out of PHP:
<?php if ($something): ?>
<some /> <tags /> <etc />
<?=$shortButControversialWayOfPrintingAVariable ?>
<?php /* A comment not visible in the HTML, but it is a bit of a pain to write */ ?>
<?php else: ?>
<!-- else -->
<?php endif; ?>
Try this below code,
SELECT DISTINCT CITY
FROM STATIOn
WHERE city RLIKE '^[aeiouAEIOU].*.[aeiouAEIOU]$'
Rene's answer about the relationship between exports
and module.exports
is quite clear, it's all about javascript references. Just want to add that:
We see this in many node modules:
var app = exports = module.exports = {};
This will make sure that even if we changed module.exports, we can still use exports by making those two variables point to the same object.
You can use HTML5 Fullscreen API for this (which is the most suitable way i think).
The fullscreen has to be triggered via a user event (click, keypress) otherwise it won't work.
Here is a button which makes the div fullscreen on click. And in fullscreen mode, the button click will exit fullscreen mode.
$('#toggle_fullscreen').on('click', function(){_x000D_
// if already full screen; exit_x000D_
// else go fullscreen_x000D_
if (_x000D_
document.fullscreenElement ||_x000D_
document.webkitFullscreenElement ||_x000D_
document.mozFullScreenElement ||_x000D_
document.msFullscreenElement_x000D_
) {_x000D_
if (document.exitFullscreen) {_x000D_
document.exitFullscreen();_x000D_
} else if (document.mozCancelFullScreen) {_x000D_
document.mozCancelFullScreen();_x000D_
} else if (document.webkitExitFullscreen) {_x000D_
document.webkitExitFullscreen();_x000D_
} else if (document.msExitFullscreen) {_x000D_
document.msExitFullscreen();_x000D_
}_x000D_
} else {_x000D_
element = $('#container').get(0);_x000D_
if (element.requestFullscreen) {_x000D_
element.requestFullscreen();_x000D_
} else if (element.mozRequestFullScreen) {_x000D_
element.mozRequestFullScreen();_x000D_
} else if (element.webkitRequestFullscreen) {_x000D_
element.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT);_x000D_
} else if (element.msRequestFullscreen) {_x000D_
element.msRequestFullscreen();_x000D_
}_x000D_
}_x000D_
});
_x000D_
#container{_x000D_
border:1px solid red;_x000D_
border-radius: .5em;_x000D_
padding:10px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="container">_x000D_
<p>_x000D_
<a href="#" id="toggle_fullscreen">Toggle Fullscreen</a>_x000D_
</p>_x000D_
I will be fullscreen, yay!_x000D_
</div>
_x000D_
Please also note that Fullscreen API for Chrome does not work in non-secure pages. See https://sites.google.com/a/chromium.org/dev/Home/chromium-security/deprecating-powerful-features-on-insecure-origins for more details.
Another thing to note is the :fullscreen CSS selector. You can append this to any css selector so the that the rules will be applied when that element is fullscreen:
#container:-webkit-full-screen,
#container:-moz-full-screen,
#container:-ms-fullscreen,
#container:fullscreen {
width: 100vw;
height: 100vh;
}
You can use plt.grid
to draw a horizontal line.
import numpy as np
from matplotlib import pyplot as plt
from scipy.interpolate import UnivariateSpline
from matplotlib.ticker import LinearLocator
# your data here
annual = np.arange(1,21,1)
l = np.random.random(20)
spl = UnivariateSpline(annual,l)
xs = np.linspace(1,21,200)
# plot your data
plt.plot(xs,spl(xs),'b')
# horizental line?
ax = plt.axes()
# three ticks:
ax.yaxis.set_major_locator(LinearLocator(3))
# plot grids only on y axis on major locations
plt.grid(True, which='major', axis='y')
# show
plt.show()
In Laravel 3, call path('storage')
.
In Laravel 4, use the storage_path()
helper function.
One solution would be to divide your table into 20 columns of 5% width each, then use colspan on each real column to get the desired width, like this:
<html>_x000D_
<body bgcolor="#14B3D9">_x000D_
<table width="100%" border="1" bgcolor="#ffffff">_x000D_
<colgroup>_x000D_
<col width="5%"><col width="5%">_x000D_
<col width="5%"><col width="5%">_x000D_
<col width="5%"><col width="5%">_x000D_
<col width="5%"><col width="5%">_x000D_
<col width="5%"><col width="5%">_x000D_
<col width="5%"><col width="5%">_x000D_
<col width="5%"><col width="5%">_x000D_
<col width="5%"><col width="5%">_x000D_
<col width="5%"><col width="5%">_x000D_
<col width="5%"><col width="5%">_x000D_
</colgroup>_x000D_
<tr>_x000D_
<td colspan=5>25</td>_x000D_
<td colspan=10>50</td>_x000D_
<td colspan=5>25</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td colspan=10>50</td>_x000D_
<td colspan=6>30</td>_x000D_
<td colspan=4>20</td>_x000D_
</tr>_x000D_
</table>_x000D_
</body>_x000D_
</html>
_x000D_
try "configuration properties -> debugging -> environment" and set the PATH variable in run-time
DateTime tomorrow = DateTime.Today.AddDays(1);
DateTime yesterday = DateTime.Today.AddDays(-1);
I have a Samsung Galaxy S4. Although visible from Devices, my phone was not listed as connected from Android Studio. I tried a few things independently, and then together, and found that only a combination of steps fixed the issue, so this is for you if measures listed above or on another site did not work on their own.
I repeat, only all 3 of these together fixed the issue, so if some fixes you have tried haven't worked, use these 3 and it could fix the problem for you. Best of luck.
Change:
struct timeval, tvalBefore, tvalAfter; /* Looks like an attempt to
delcare a variable with
no name. */
to:
struct timeval tvalBefore, tvalAfter;
It is less likely (IMO) to make this mistake if there is a single declaration per line:
struct timeval tvalBefore;
struct timeval tvalAfter;
It becomes more error prone when declaring pointers to types on a single line:
struct timeval* tvalBefore, tvalAfter;
tvalBefore
is a struct timeval*
but tvalAfter
is a struct timeval
.
The problem is the indexing subplot
is using. Subplots are counted starting with 1!
Your code thus needs to read
fig=plt.figure(figsize=(15, 6),facecolor='w', edgecolor='k')
for i in range(10):
#this part is just arranging the data for contourf
ind2 = py.find(zz==i+1)
sfr_mass_mat = np.reshape(sfr_mass[ind2],(pixmax_x,pixmax_y))
sfr_mass_sub = sfr_mass[ind2]
zi = griddata(massloclist, sfrloclist, sfr_mass_sub,xi,yi,interp='nn')
temp = 251+i # this is to index the position of the subplot
ax=plt.subplot(temp)
ax.contourf(xi,yi,zi,5,cmap=plt.cm.Oranges)
plt.subplots_adjust(hspace = .5,wspace=.001)
#just annotating where each contour plot is being placed
ax.set_title(str(temp))
Note the change in the line where you calculate temp
Another solution would be the usage of std::make_move_iterator to build a new vector (C++11 )
int main(){
std::map<std::string, int> map;
//Populate map
std::vector<std::pair<std::string, int>> v {std::make_move_iterator(begin(map)),
std::make_move_iterator(end(map))};
// Create a vector with the map parameters
sort(begin(v), end(v),
[](auto p1, auto p2){return p1.second > p2.second;});
// Using sort + lambda function to return an ordered vector
// in respect to the int value that is now the 2nd parameter
// of our newly created vector v
}
I'm going out on a limb here , since your question was not very detailed, that a) your receipt printer is a thermal printer that needs raw data, b) that "from javascript" you are talking about printing from the web browser and c) that you do not have access to send raw data from browser
Here is a Java Applet that solves all that for you , if I'm correct about those assumptions then you need either Java, Flash, or Silverlight http://code.google.com/p/jzebra/
Here's what worked for me.
Html using the directive
<tr orderitemdirective remove="vm.removeOrderItem(orderItem)" order-item="orderitem"></tr>
Html of the directive: orderitem.directive.html
<md-button type="submit" ng-click="remove({orderItem:orderItem})">
(...)
</md-button>
Directive's scope:
scope: {
orderItem: '=',
remove: "&",
//defines an array of 280 pointers (1120 or 2240 bytes)
int *pointer1 [280];
//defines a pointer (4 or 8 bytes depending on 32/64 bits platform)
int (*pointer2)[280]; //pointer to an array of 280 integers
int (*pointer3)[100][280]; //pointer to an 2D array of 100*280 integers
Using pointer2
or pointer3
produce the same binary except manipulations as ++pointer2
as pointed out by WhozCraig.
I recommend using typedef
(producing same binary code as above pointer3
)
typedef int myType[100][280];
myType *pointer3;
Note: Since C++11, you can also use keyword using
instead of typedef
using myType = int[100][280];
myType *pointer3;
in your example:
myType *pointer; // pointer creation
pointer = &tab1; // assignation
(*pointer)[5][12] = 517; // set (write)
int myint = (*pointer)[5][12]; // get (read)
Note: If the array tab1
is used within a function body => this array will be placed within the call stack memory. But the stack size is limited. Using arrays bigger than the free memory stack produces a stack overflow crash.
The full snippet is online-compilable at gcc.godbolt.org
int main()
{
//defines an array of 280 pointers (1120 or 2240 bytes)
int *pointer1 [280];
static_assert( sizeof(pointer1) == 2240, "" );
//defines a pointer (4 or 8 bytes depending on 32/64 bits platform)
int (*pointer2)[280]; //pointer to an array of 280 integers
int (*pointer3)[100][280]; //pointer to an 2D array of 100*280 integers
static_assert( sizeof(pointer2) == 8, "" );
static_assert( sizeof(pointer3) == 8, "" );
// Use 'typedef' (or 'using' if you use a modern C++ compiler)
typedef int myType[100][280];
//using myType = int[100][280];
int tab1[100][280];
myType *pointer; // pointer creation
pointer = &tab1; // assignation
(*pointer)[5][12] = 517; // set (write)
int myint = (*pointer)[5][12]; // get (read)
return myint;
}
I know this is an old question, but we were faced with the same problem when trying to inject Strings. So we invented a JUnit5/Mockito extension that does exactly what you want: https://github.com/exabrial/mockito-object-injection
EDIT:
@InjectionMap
private Map<String, Object> injectionMap = new HashMap<>();
@BeforeEach
public void beforeEach() throws Exception {
injectionMap.put("securityEnabled", Boolean.TRUE);
}
@AfterEach
public void afterEach() throws Exception {
injectionMap.clear();
}
They are related values, and kept consistent by the property setter/getter methods (and using the fact that frame is a purely synthesized value, not backed by an actual instance variable).
The main equations are:
frame.origin = center - bounds.size / 2
(which is the same as)
center = frame.origin + bounds.size / 2
(and there’s also)
frame.size = bounds.size
That's not code, just equations to express the invariant between the three properties. These equations also assume your view's transform is the identity, which it is by default. If it's not, then bounds and center keep the same meaning, but frame can change. Unless you're doing non-right-angle rotations, the frame will always be the transformed view in terms of the superview's coordinates.
This stuff is all explained in more detail with a useful mini-library here:
Logical OR is ||
, logical AND is &&
.
If you need the negation NOT, prefix your expression with !
.
Example:
X = (A && B) || C || !D;
Then X will be true when either A and B are true or if C is true or if D is not true (i.e. false).
If you wanted bit-wise AND/OR/NOT, you would use &
, |
and ~
. But if you are dealing with boolean/truth values, you do not want to use those. They do not provide short-circuit evaluation for example due to the way a bitwise operation works.
PHP 7.0:
apt-get install php7.0-xml
yum install php70w-xml
PHP 7.1:
apt-get install php7.1-xml
yum install php71w-xml
PHP 7.2:
apt-get install php7.2-xml
yum install php72w-xml
PHP 7.3:
apt-get install php7.3-xml
yum install php73w-xml
PHP 7.4:
apt-get install php7.4-xml
yum install php74w-xml
PHP 8.0
apt-get install php8.0-xml
php:remi-8.0
enabled]: dnf install php-xml
Add z-index:-9999;
to this method, or it will cover your top bar if you have 1
.
Use .net inbuilt class JavaScriptSerializer
JavaScriptSerializer js = new JavaScriptSerializer();
string json = js.Serialize(obj);
Because if you create a reference to a variable, all names for that variable (including the original) BECOME REFERENCES.
if you're looking for a simple column hide you can use the :nth-child selector as well.
#tableid tr td:nth-child(3),
#tableid tr th:nth-child(3) {
display: none;
}
I use this with the @media tag sometimes to condense wider tables when the screen is too narrow.
I think what you are looking for is string.count
"Allowed Hello Hollow".count('ll')
>>> 3
Hope this helps
NOTE: this only captures non-overlapping occurences
If you can't change server media-type response, you can extend GsonHttpMessageConverter to process additional support types
public class MyGsonHttpMessageConverter extends GsonHttpMessageConverter {
public MyGsonHttpMessageConverter() {
List<MediaType> types = Arrays.asList(
new MediaType("text", "html", DEFAULT_CHARSET),
new MediaType("application", "json", DEFAULT_CHARSET),
new MediaType("application", "*+json", DEFAULT_CHARSET)
);
super.setSupportedMediaTypes(types);
}
}
I recommend reading through this page: http://developer.android.com/reference/android/app/Activity.html
In short, your activity is no longer visible after onStop()
has been called.
CountRows = ThisWorkbook.Worksheets(1).Range("A:A").Cells.SpecialCells(xlCellTypeConstants).Count
To make an example of Clairton Luz work, you need to run in the FXApplicationThread
and insert into Platform.runLater
method your code snippet:
Platform.runLater(() -> {
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setTitle("Error Dialog");
alert.setHeaderText("No information.");
alert.showAndWait();
}
);
Otherwise, you'll get: java.lang.IllegalStateException: Not on FX application thread
Thank you Hero Editor example, where I found the correct definition:
When I generate app routing module:
ng generate module app-routing --flat --module=app
and update the app-routing.ts file to add:
@NgModule({
imports: [ RouterModule.forRoot(routes) ],
exports: [ RouterModule ]
})
Here are the full example:
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { DashboardComponent } from './dashboard/dashboard.component';
import { HeroesComponent } from './heroes/heroes.component';
import { HeroDetailComponent } from './hero-detail/hero-detail.component';
const routes: Routes = [
{ path: '', redirectTo: '/dashboard', pathMatch: 'full' },
{ path: 'dashboard', component: DashboardComponent },
{ path: 'detail/:id', component: HeroDetailComponent },
{ path: 'heroes', component: HeroesComponent }
];
@NgModule({
imports: [ RouterModule.forRoot(routes) ],
exports: [ RouterModule ]
})
export class AppRoutingModule {}
and add AppRoutingModule into app.module.ts imports:
@NgModule({
declarations: [
AppComponent,
...
],
imports: [
BrowserModule,
FormsModule,
AppRoutingModule
],
providers: [...],
bootstrap: [AppComponent]
})
The simplest way to log to stdout:
import logging
import sys
logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)
The following query can be used to detemine tablespace and other params:
select df.tablespace_name "Tablespace",
totalusedspace "Used MB",
(df.totalspace - tu.totalusedspace) "Free MB",
df.totalspace "Total MB",
round(100 * ( (df.totalspace - tu.totalusedspace)/ df.totalspace)) "Pct. Free"
from (select tablespace_name,
round(sum(bytes) / 1048576) TotalSpace
from dba_data_files
group by tablespace_name) df,
(select round(sum(bytes)/(1024*1024)) totalusedspace,
tablespace_name
from dba_segments
group by tablespace_name) tu
where df.tablespace_name = tu.tablespace_name
and df.totalspace <> 0;
Source: https://community.oracle.com/message/1832920
For your case if you want to know the partition name and it's size just run this query:
select owner,
segment_name,
partition_name,
segment_type,
bytes / 1024/1024 "MB"
from dba_segments
where owner = <owner_name>;
I just renamed the package and it worked for me.
Or if you are using Ionic, you could delete the application and try again, this happens when ionic detects that the app you are deploying is not coming from the same build. It often happen when you change from pc.
In JavaScript? Just instantiate a new Date object
var now = new Date();
That will create a new Date object with the client's local time.
Native API doesn't have such "addHeader" feature, but has the concept of "addItem".
I was able to include this specific feature of headers and extends for footers as well in my FlexibleAdapter project. I called it Scrollable Headers and Footers.
Here how they work:
Scrollable Headers and Footers are special items that scroll along with all others, but they don't belongs to main items (business items) and they are always handled by the adapter beside the main items. Those items are persistently located at the first and last positions.
There's a lot to say about them, better to read the detailed wiki page.
Moreover the FlexibleAdapter allows you to create headers/sections, also you can have them sticky and tens of others features like expandable items, endless scroll, UI extensions etc... all in one library!
import sys
try:
import feedparser
except:
print "Error: Cannot import feedparser.\n"
sys.exit(1)
Here we're exiting with a status code of 1. It is usually also helpful to output an error message, write to a log, and clean up.
Yes, the result is always truncated towards zero. It will round towards the smallest absolute value.
-5 / 2 = -2
5 / 2 = 2
For unsigned and non-negative signed values, this is the same as floor (rounding towards -Infinity).
Try redirecting the output to Out-Null. Like so,
$key = & 'gpg' --decrypt "secret.gpg" --quiet --no-verbose | out-null
I assume your questions is with regards to Java code. If that's the case, you don't actually need any extra plugins to accomplish 1). You can just go to Preferences -> Java -> Editor -> Save Actions and configure it to remove trailing whitespace.
By the sounds of it you also want to make this a team-wide setting, right? To make life easier and avoid having to remember setting it up every time you have a new workspace you can set the save action as a project specific preference that gets stored into your SCM along with the code.
In order to do that right-click on your project and go to Properties -> Java Editor -> Save Actions. From there you can enable project specific settings and configure it to remove trailing whitespace (among other useful things).
NB: This option has been removed in Eclipse Kepler (4.3) and following releases.
NB #2: The option seems to be back in Eclipse Luna - Luna Service Release 1a (4.4.1)
One easy way to select random items is to shuffle then slice.
import random
a = [1,2,3,4,5,6,7,8,9]
random.shuffle(a)
print a[:4] # prints 4 random variables
Use Where-Object
, like:
Get-ChildItem 'PATH' -recurse -include @("*.tif*","*.jp2","*.pdf") |
Where-Object { $_.CreationTime -gt "03/01/2013" -and $_.CreationTime -lt "03/31/2013" }
Select-Object FullName, CreationTime, @{Name="Mbytes";Expression={$_.Length/1Kb}}, @{Name="Age";Expression={(((Get-Date) - $_.CreationTime).Days)}} |
Export-Csv 'PATH\scans.csv'
Disclaimer: work for product I am recommending
Atalasoft has a .NET library that can convert PDF to TIFF -- we are a partner of FOXIT, so the PDF rendering is very good.
What you also can do, if it's something you installed on your system, is to add the directory that contains the shared libraries to your /etc/ld.so.conf file, or make a new file in /etc/ld.so.conf.d/
(I've both checked RHEL5 and Ubuntu distribution so I think it's generic for linux)
The ldconfig program will make sure they are system-wide included.
See the following link for more information: www.dwheeler.com/secure-programs/Secure-Programs-HOWTO/dlls.html
On API >= 11, you can use:
wv.getSettings().setBuiltInZoomControls(true);
wv.getSettings().setDisplayZoomControls(false);
As per the SDK:
public void setDisplayZoomControls (boolean enabled)
Since: API Level 11
Sets whether the on screen zoom buttons are used. A combination of built in zoom controls enabled and on screen zoom controls disabled allows for pinch to zoom to work without the on screen controls
Each line of a batch file will get executed; but only after the previous line has completed. In your case, as soon as it hits the ftp line the ftp program will start and take over user input. When it is closed then the remaining lines will execute. Meaning the username/password are never sent to the FTP program and instead will be fed to the command prompt itself once the ftp program is closed.
Instead you need to pass everything you need on the ftp command line. Something like:
@echo off
echo user MyUserName> ftpcmd.dat
echo MyPassword>> ftpcmd.dat
echo bin>> ftpcmd.dat
echo put %1>> ftpcmd.dat
echo quit>> ftpcmd.dat
ftp -n -s:ftpcmd.dat SERVERNAME.COM
del ftpcmd.dat
it is completely transparent Edittext with transparent background.
<item>
<shape android:shape="rectangle" >
<solid android:color="@color/transparent" />
</shape>
</item>
<item android:top="-3dp" android:right="-3dp" android:left="-3dp">
<shape>
<solid android:color="@android:color/transparent" />
<stroke
android:width="2dp"
android:color="@color/bottomline" />
</shape>
</item>
This should be set directly in the CSS.
.forum {background-color: #123456}
.forum:hover {background-color: #380606}
If you are worried about the fact the IE6 will not accept hover over elements which are not links, you can use the hover event of jQuery for compatibility.
Within Apache Commons, commons-codec-1.7.jar contains a Base64 class which can be used to encode.
Via Maven:
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>20041127.091804</version>
</dependency>
Other replies have nailed it; BigInteger is immutable. Here's the minor change to make that code work.
BigInteger sum = BigInteger.valueOf(0);
for(int i = 2; i < 5000; i++) {
if (isPrim(i)) {
sum = sum.add(BigInteger.valueOf(i));
}
}
I'm surprised no one yet has suggested using the forEach
function to better avoid (re)using local variables. In fact, I'm not using for(var i ...)
at all anymore for this reason.
[0,2,3].forEach(function(i){ console.log('My value:', i); });
// My value: 0
// My value: 2
// My value: 3
// edited to use forEach
instead of map.
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
LocalDate dateBefore = LocalDate.of(2020, 05, 20);
LocalDate dateAfter = LocalDate.now();
long daysBetween = ChronoUnit.DAYS.between(dateBefore, dateAfter);
long monthsBetween= ChronoUnit.MONTHS.between(dateBefore, dateAfter);
long yearsBetween= ChronoUnit.YEARS.between(dateBefore, dateAfter);
System.out.println(daysBetween);
Abdullah's answer is great. But i want to add some more details to it with my answer.
Implementing a Splash Screen
Implementing a splash screen the right way is a little different than you might imagine. The splash view that you see has to be ready immediately, even before you can inflate a layout file in your splash activity.
So you will not use a layout file. Instead, specify your splash screen’s background as the activity’s theme background. To do this, first create an XML drawable in res/drawable.
background_splash.xml
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:drawable="@color/gray"/>
<item>
<bitmap
android:gravity="center"
android:src="@mipmap/ic_launcher"/>
</item>
</layer-list>
It just a layerlist with logo in center background color with it.
Now open styles.xml and add this style
<style name="SplashTheme" parent="Theme.AppCompat.NoActionBar">
<item name="android:windowBackground">@drawable/background_splash</item>
</style>
This theme will have to actionbar and with background that we just created above.
And in manifest you need to set SplashTheme to activity that you want to use as splash.
<activity
android:name=".SplashActivity"
android:theme="@style/SplashTheme">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
Then inside your activity code navigate user to the specific screen after splash using intent.
public class SplashActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
finish();
}
}
That's the right way to do. I used these references for answer.
There are some quirks to be aware of here.
HTMLIFrameElement.contentWindow
is probably the easier way, but it's not quite a standard property and some browsers don't support it, mostly older ones. This is because the DOM Level 1 HTML standard has nothing to say about the window
object.
You can also try HTMLIFrameElement.contentDocument.defaultView
, which a couple of older browsers allow but IE doesn't. Even so, the standard doesn't explicitly say that you get the window
object back, for the same reason as (1), but you can pick up a few extra browser versions here if you care.
window.frames['name']
returning the window is the oldest and hence most reliable interface. But you then have to use a name="..."
attribute to be able to get a frame by name, which is slightly ugly/deprecated/transitional. (id="..."
would be better but IE doesn't like that.)
window.frames[number]
is also very reliable, but knowing the right index is the trick. You can get away with this eg. if you know you only have the one iframe on the page.
It is entirely possible the child iframe hasn't loaded yet, or something else went wrong to make it inaccessible. You may find it easier to reverse the flow of communications: that is, have the child iframe notify its window.parent
script when it has finished loaded and is ready to be called back. By passing one of its own objects (eg. a callback function) to the parent script, that parent can then communicate directly with the script in the iframe without having to worry about what HTMLIFrameElement it is associated with.
struct Connectivity {
static let sharedInstance = NetworkReachabilityManager()!
static var isConnectedToInternet:Bool {
return self.sharedInstance.isReachable
}
}
Now call it
if Connectivity.isConnectedToInternet{
call_your_methods_here()
} else{
show_alert_for_noInternet()
}
In Rails 5+ you can simply use the function as demonstrated below with simple example:
module ApplicationHelper
# format datetime in the format #2018-12-01 12:12 PM
def datetime_format(datetime = nil)
if datetime
datetime.strftime('%Y-%m-%d %H:%M %p')
else
'NA'
end
end
end
class ExamplesController < ApplicationController
def index
current_datetime = helpers.datetime_format DateTime.now
raise current_datetime.inspect
end
end
OUTPUT
"2018-12-10 01:01 AM"
In the "Window" menu, open "Open Perspective" -> "Debug".
click On the plus image icon(you see the below image at status bar), and then select "Logcat"....
f = open("test.py", "a") Will be created in whatever directory the python file is run from.
I'm not sure about the other error...I don't work in windows.
To adjust the length of the samples:
set key samplen X
(default is 4)
To adjust the vertical spacing of the samples:
set key spacing X
(default is 1.25)
and (for completeness), to adjust the fontsize:
set key font "<face>,<size>"
(default depends on the terminal)
And of course, all these can be combined into one line:
set key samplen 2 spacing .5 font ",8"
Note that you can also change the position of the key using set key at <position>
or any one of the pre-defined positions (which I'll just defer to help key
at this point)
public void setHoursWorked(){
hoursWorked = hours;
}
You haven't defined hours
inside that method. hours is not passed in as a parameter, it's not declared as a variable, and it's not being used as a class member, so you get that error.
Inspired by christutty's answer, here is a solution that modifies the source but has not been tested thoroughly. I haven't had any issues yet though.
In the defaults section, add this line around line 71:
// Boolean - Omit x-axis labels
omitXLabels: true,
Then around line 2215, add this in the buildScale method:
//if omitting x labels, replace labels with empty strings
if(Chart.defaults.global.omitXLabels){
var newLabels=[];
for(var i=0;i<labels.length;i++){
newLabels.push('');
}
labels=newLabels;
}
This preserves the tool tips also.
The Chrome Browser versión should matches with the chromeDriver versión. Go to : chrome://settings/help
How do I confirm I'm using the right chromedriver?
Best way to copy all files from one folder to another using PHP
<?php
$src = "/home/www/example.com/source/folders/123456"; // source folder or file
$dest = "/home/www/example.com/test/123456"; // destination folder or file
shell_exec("cp -r $src $dest");
echo "<H2>Copy files completed!</H2>"; //output when done
?>
<table>
<tr><td><img ...><td><img ...>
<tr><td>caption1<td>caption2
</table>
Style as desired.
I think you missed a equal sign at:
Cursor c = ourDatabase.query(DATABASE_TABLE, column, KEY_ROWID + "" + l, null, null, null, null);
Change to:
Cursor c = ourDatabase.query(DATABASE_TABLE, column, KEY_ROWID + " = " + l, null, null, null, null);
Instead of removeClass and addClass, you can also do it like this:
$('.IsBestAnswer').toggleClass('IsBestAnswer bestanswer');
if you are using mongoose try this,after mongoose connection
async ()=> await Mongoose.model("collectionName").updateMany({}, {$set: {newField: value}})
Try using cURL instead. cURL implements a cookie jar, while file_get_contents doesn't.