According to RFC 4329 the correct MIME type for JavaScript should be application/javascript
. Howerver, older IE versions choke on this since they expect text/javascript
.
You can create a helper method that accept a one object parameter base on error arguments
error(message: string, title?: string, autoHideAfter?: number){}
getError(args: { message: string, title?: string, autoHideAfter?: number }) {
return error(args.message, args.title, args.autoHideAfter);
}
I found the best solution if you have nested numpy arrays in a dictionary:
import json
import numpy as np
class NumpyEncoder(json.JSONEncoder):
""" Special json encoder for numpy types """
def default(self, obj):
if isinstance(obj, np.integer):
return int(obj)
elif isinstance(obj, np.floating):
return float(obj)
elif isinstance(obj, np.ndarray):
return obj.tolist()
return json.JSONEncoder.default(self, obj)
dumped = json.dumps(data, cls=NumpyEncoder)
with open(path, 'w') as f:
json.dump(dumped, f)
Thanks to this guy.
This will give you the date in 24 hour format.
Date date = new Date();
date.setHours(date.getHours() + 8);
System.out.println(date);
SimpleDateFormat simpDate;
simpDate = new SimpleDateFormat("kk:mm:ss");
System.out.println(simpDate.format(date));
you could also change from the .get()
method to the .getJSON()
method, jQuery will then parse the string returned as data
to a javascript object and/or array that you can then reference like any other javascript object/array.
using your code above, if you changed .get
to .getJSON
, you should get an alert of [object Object]
for each element in the array. If you changed the alert to alert(item.name)
you will get the names.
If you want the month year unique pair, using apply is pretty sleek.
df['mnth_yr'] = df['date_column'].apply(lambda x: x.strftime('%B-%Y'))
Outputs month-year in one column.
Don't forget to first change the format to date-time before, I generally forget.
df['date_column'] = pd.to_datetime(df['date_column'])
This worked for me :
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),R.layout.simple_spinner_item,areas);
Spinner areasSpinner = (Spinner) view.findViewById(R.id.area_spinner);
areasSpinner.setAdapter(adapter);
and in my layout folder I created simple_spinner_item
:
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/text1"
android:layout_width="match_parent"
// add custom fields here
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceListItemSmall"
android:gravity="center_vertical"
android:paddingStart="?android:attr/listPreferredItemPaddingStart"
android:paddingEnd="?android:attr/listPreferredItemPaddingEnd"
android:minHeight="?android:attr/listPreferredItemHeightSmall"
android:paddingLeft="?android:attr/listPreferredItemPaddingLeft"
android:paddingRight="?android:attr/listPreferredItemPaddingRight" />
When it comes to Linux
I suggest an Update Node Using a Package Manager:
Node comes with npm pre-installed, but the manager is updated more frequently than Node. Run npm -v to see which version you have, then npm install npm@latest -g
to install the newest npm update. Run npm -v
again if you want to make sure npm updated correctly.
To update NodeJS
, you’ll need npm’s handy n module. Run this code to clear npm’s cache, install n, and install the latest stable version of Node
:
sudo npm cache clean -f
sudo npm install -g n
sudo n stable
To install the latest release, use n latest
. Alternatively, you can run n #.#.# to get a specific Node
version.
When it comes to Windows/ macOS
I suggest using Installers on Nodejs.org
The Node.js downloads page includes binary packages for Windows and macOS — but why make your life more difficult? The pre-made installers — .msi for Windows and .pkg for macOS — make the installation process unbelievably efficient and understandable. Download and run the file, and let the installation wizard take care of the rest. With each downloaded update, the newer versions of Node and npm will replace the older version.
Alternatively, macOS users can use the npm and n instructions above.
When it comes to updating your node_modules
dependencies folder, I suggest skipping all the things that could cause you a headache and just go to your specific project and re-run npm install
again.
Before anyone does that, I suggest first checking your package.json
file for the following:
As a user of NodeJS packages, you can specify which kinds of updates your app can accept in the package.json file. For example, if you were starting with a package version 1.0.4, this is how you could specify the allowed update version ranges in three basic ways:
To Allow Patch Releases: 1.0 or 1.0.x or ~1.0.4
To Allow Minor Releases: 1 or 1.x or ^1.0.4
To Allow Major Releases: * or x
Explanation:
MAJOR version for when there are incompatible API changes. --> ~
MINOR version for when functionality is added in a backwards compatible manner. --> ^
PATCH version for when backward compatible bug fixes are done. --> *
I was having this problem using Eclipse Neon on Kubuntu with a 16.04 kernel, I had to change my #include <stdlib.h>
to #include <cstdlib>
this made the std namespace "visible" to Eclipse and removed the error.
This is with reference to @Ladislav Mrnka's answer on using fluent api for configuring one-to-one relationship.
Had a situation where having FK of dependent must be it's PK
was not feasible.
E.g., Foo
already has one-to-many relationship with Bar
.
public class Foo {
public Guid FooId;
public virtual ICollection<> Bars;
}
public class Bar {
//PK
public Guid BarId;
//FK to Foo
public Guid FooId;
public virtual Foo Foo;
}
Now, we had to add another one-to-one relationship between Foo and Bar.
public class Foo {
public Guid FooId;
public Guid PrimaryBarId;// needs to be removed(from entity),as we specify it in fluent api
public virtual Bar PrimaryBar;
public virtual ICollection<> Bars;
}
public class Bar {
public Guid BarId;
public Guid FooId;
public virtual Foo PrimaryBarOfFoo;
public virtual Foo Foo;
}
Here is how to specify one-to-one relationship using fluent api:
modelBuilder.Entity<Bar>()
.HasOptional(p => p.PrimaryBarOfFoo)
.WithOptionalPrincipal(o => o.PrimaryBar)
.Map(x => x.MapKey("PrimaryBarId"));
Note that while adding PrimaryBarId
needs to be removed, as we specifying it through fluent api.
Also note that method name [WithOptionalPrincipal()][1]
is kind of ironic. In this case, Principal is Bar. WithOptionalDependent() description on msdn makes it more clear.
There's no need for LINQ here, just call Sort:
list.Sort();
Example code:
List<int> list = new List<int> { 5, 7, 3 };
list.Sort();
foreach (int x in list)
{
Console.WriteLine(x);
}
Result:
3
5
7
The solution to this question is:
<?xml version="1.0" encoding="utf-8"?>
<?xml-stylesheet type="text/xsl" href="dummy.xsl"?>
<item>
<summary>
<![CDATA[Tootsie roll tiramisu macaroon wafer carrot cake. <br />
Danish topping sugar plum tart bonbon caramels cake.]]>
</summary>
</item>
by adding the <br />
inside the the <![CDATA]]>
this allows the line to break, thus creating a new line!
I know its too late but this solution is working perfect for both .net framework and .net core:
@System.Web.HttpUtility.JavaScriptStringEncode()
You can use the forEach
method to execute a provided function once for each element in the array. In this provided function you can add the Active
property to the element.
Results.forEach(function (element) {
element.Active = "false";
});
Use sql
from sql
:
spool output of this to a file:
select 'alter index '||owner||'.'||index_name||' rebuild tablespace TO_TABLESPACE_NAME;' from all_indexes where owner='OWNERNAME';
spoolfile will have something like this:
alter index OWNER.PK_INDEX rebuild tablespace CORRECT_TS_NAME;
The LINEST function described in a previous answer is the way to go, but an easier way to show the 3 coefficients of the output is to additionally use the INDEX function. In one cell, type: =INDEX(LINEST(B2:B21,A2:A21^{1,2},TRUE,FALSE),1) (by the way, the B2:B21 and A2:A21 I used are just the same values the first poster who answered this used... of course you'd change these ranges appropriately to match your data). This gives the X^2 coefficient. In an adjacent cell, type the same formula again but change the final 1 to a 2... this gives the X^1 coefficient. Lastly, in the next cell over, again type the same formula but change the last number to a 3... this gives the constant. I did notice that the three coefficients are very close but not quite identical to those derived by using the graphical trendline feature under the charts tab. Also, I discovered that LINEST only seems to work if the X and Y data are in columns (not rows), with no empty cells within the range, so be aware of that if you get a #VALUE error.
To list mongodb database on shell
show databases //Print a list of all available databases.
show dbs // Print a list of all databases on the server.
Few more basic commands
use <db> // Switch current database to <db>. The mongo shell variable db is set to the current database.
show collections //Print a list of all collections for current database.
show users //Print a list of users for current database.
show roles //Print a list of all roles, both user-defined and built-in, for the current database.
This can occur if you are trying to use the splat operator(...
) in an unsupported version of PHP.
...
first became available in PHP 5.6 to capture a variable number of arguments to a function:
function concatenate($transform, ...$strings) {
$string = '';
foreach($strings as $piece) {
$string .= $piece;
}
return($transform($string));
}
echo concatenate("strtoupper", "I'd ", "like ", 4 + 2, " apples");
// This would print:
// I'D LIKE 6 APPLES
In PHP 7.4, you could use it for Array expressions.
$parts = ['apple', 'pear'];
$fruits = ['banana', 'orange', ...$parts, 'watermelon'];
// ['banana', 'orange', 'apple', 'pear', 'watermelon'];
The BeautifulSoup documentation provides an example about removing objects from a document using the extract method. In the following example the aim is to remove all comments from the document:
Removing Elements
Once you have a reference to an element, you can rip it out of the tree with the extract method. This code removes all the comments from a document:
from BeautifulSoup import BeautifulSoup, Comment
soup = BeautifulSoup("""1<!--The loneliest number-->
<a>2<!--Can be as bad as one--><b>3""")
comments = soup.findAll(text=lambda text:isinstance(text, Comment))
[comment.extract() for comment in comments]
print soup
# 1
# <a>2<b>3</b></a>
Set password that satisfies 7 MySql validation rules
eg:- d_VX>N("xn_BrD2y
Making validation criteria bit more simple will solve the issue
SET GLOBAL validate_password_length = 6;
SET GLOBAL validate_password_number_count = 0;
But recommended a Strong password is a correct solution
int result = 0;
bool isValidInt = int.TryParse("1234", out result);
//isValidInt should be true
//result is the integer 1234
Of course, you can check against other number types, like decimal
or double
.
I was looking for a way to play VMDK files without the vmx file in VMware Player 5 and didn't find any explicit tutorial to do it. So after some time messing around with VMware PLayer 5, it turned out to be pretty simple, but not so intuitive. Here it is:
Create a new virtual machine from VMware Player 5; There's no need to install an OS, since you already have the VMDK (Virtual Machine Disk); Set the Virtual Machine to the OS you'll be playing (the one from the VMDK); After creating the VM with the remaining creation wizard options, go to your VM settings; There you can remove the existing hard drive and add a new one; Upon addition of the new hard drive, point it to your existing VMDK file.
And that's it.
If you have problems starting the VM because VMware Player can't lock the VMDK file, rename/delete the dir/files with extension *.lck from the directory where the *.vmdk file is located.
Hope this is helpful.
This rule is intended to avoid conflicts in legacy code that still uses raw types.
Here's an illustration of why this was not allowed, drawn from the JLS. Suppose, before generics were introduced to Java, I wrote some code like this:
class CollectionConverter {
List toList(Collection c) {...}
}
You extend my class, like this:
class Overrider extends CollectionConverter{
List toList(Collection c) {...}
}
After the introduction of generics, I decided to update my library.
class CollectionConverter {
<T> List<T> toList(Collection<T> c) {...}
}
You aren't ready to make any updates, so you leave your Overrider
class alone. In order to correctly override the toList()
method, the language designers decided that a raw type was "override-equivalent" to any generified type. This means that although your method signature is no longer formally equal to my superclass' signature, your method still overrides.
Now, time passes and you decide you are ready to update your class. But you screw up a little, and instead of editing the existing, raw toList()
method, you add a new method like this:
class Overrider extends CollectionConverter {
@Override
List toList(Collection c) {...}
@Override
<T> List<T> toList(Collection<T> c) {...}
}
Because of the override equivalence of raw types, both methods are in a valid form to override the toList(Collection<T>)
method. But of course, the compiler needs to resolve a single method. To eliminate this ambiguity, classes are not allowed to have multiple methods that are override-equivalent—that is, multiple methods with the same parameter types after erasure.
The key is that this is a language rule designed to maintain compatibility with old code using raw types. It is not a limitation required by the erasure of type parameters; because method resolution occurs at compile-time, adding generic types to the method identifier would have been sufficient.
I think your problem is that it's closing the document that calls the macro before sending the command to quit the application.
Your solution in that case is to not send a command to close the workbook. Instead, you could set the "Saved" state of the workbook to true, which would circumvent any messages about closing an unsaved book. Note: this does not save the workbook; it just makes it look like it's saved.
ThisWorkbook.Saved = True
and then, right after
Application.Quit
M2_HOME
(and the like) is not to be used as of Maven 3.5.0. See MNG-5607 and Release Notes for details.
Inner join matches tables on keys, but outer join matches keys just for one side. For example when you use left outer join the query brings the whole left side table and matches the right side to the left table primary key and where there is not matched places null.
There is another (somewhat easier) solution, without the size problems. I used this approach today (on a 2003 XLS file, using Excel 2007) and was successful.
DPB=...
partDPB=...
string to DPx=...
*NOTE: Be sure that you have changed the password to a new value, otherwise the next time you open the spreadsheet Excel will report errors (Unexpected Error), then when you access the list of VBA modules you will now see the names of the source modules but receive another error when trying to open forms/code/etc. To remedy this, go back to the VBA Project Properties and set the password to a new value. Save and re-open the Excel document and you should be good to go!
With C++11 you can now do
struct std::tm tm;
std::istringstream ss("16:35:12");
ss >> std::get_time(&tm, "%H:%M:%S"); // or just %T in this case
std::time_t time = mktime(&tm);
see std::get_time and strftime for reference
I would suggest you to use fseek-ftell functions.
FILE *stream = fopen("example.txt", "r");
if(!stream) {
puts("I/O error.\n");
return;
}
fseek(stream, 0, SEEK_END);
long size = ftell(stream);
fseek(stream, 0, SEEK_SET);
while(1) {
if(ftell(stream) == size) {
break;
}
/* INSERT ROUTINE */
}
fclose(stream);
Because it is not portable.
pause
is a windows / dos only program, so this your code won't run on linux. Moreover, system
is not generally regarded as a very good way to call another program - it is usually better to use CreateProcess
or fork
or something similar.
Does the screenshot contain only the icon? If so, the L2 distance of the two images might suffice. If the L2 distance doesn't work, the next step is to try something simple and well established, like: Lucas-Kanade. Which I'm sure is available in OpenCV.
I don't know which version of Jquery you are using, but this works for me in jquery 1.3:
$.ajax({
type: 'POST',
url: your url,
data: $('#'+form_id).serialize(),
success: function(data) {
$('#debug').html(data);
}
});
Then you can access POST array keys as you would normally do in php.
Just try with a print_r()
.
I think you're wrapping serialized form value in an object's property, which is useless as far as i know.
Hope this helps!
Due to the way Python works, it is necessary for it to run your modules when it imports them.
To prevent code in the module from being executed when imported, but only when run directly, you can guard it with this if
:
if __name__ == "__main__":
# this won't be run when imported
You may want to put this code in a main()
method, so that you can either execute the file directly, or import the module and call the main()
. For example, assume this is in the file foo.py
.
def main():
print "Hello World"
if __name__ == "__main__":
main()
This program can be run either by going python foo.py
, or from another Python script:
import foo
...
foo.main()
The solution proposed by Jens is correct. However, it turns out that if you initialize your ModelForm with an instance (example below) django will not populate the data:
def your_view(request):
if request.method == 'POST':
form = UserDetailsForm(request.POST)
if form.is_valid():
# some code here
else:
form = UserDetailsForm(instance=request.user)
So, I made my own ModelForm base class that populates the initial data:
from django import forms
class BaseModelForm(forms.ModelForm):
"""
Subclass of `forms.ModelForm` that makes sure the initial values
are present in the form data, so you don't have to send all old values
for the form to actually validate.
"""
def merge_from_initial(self):
filt = lambda v: v not in self.data.keys()
for field in filter(filt, getattr(self.Meta, 'fields', ())):
self.data[field] = self.initial.get(field, None)
Then, the simple view example looks like this:
def your_view(request): if request.method == 'POST':
form = UserDetailsForm(request.POST)
if form.is_valid():
# some code here
else:
form = UserDetailsForm(instance=request.user)
form.merge_from_initial()
Using Eclipse Mars.1 CTRL + / on Linux in Java will comment out multiple lines of code. When trying to un-comment those multiple lines, Eclipse was commenting the comments. I found that if there is a blank line in the comments it will do this. If you have 10 lines of code, a blank line, and 10 more lines of code, CTRL + / will comment it all. You'll have to remove the line or un-comment them in blocks of 10.
I have an idea that I don't have time to try to implement immediately.
But what if you do something like the following:
$ MY_HISTORY_FILE = `get_temp_filename`
$ MY_HISTORY_FILE=$MY_HISTORY_FILE bash -i 2>&1 | tee $MY_HISTORY_FILE
$ some_command
$ cat $MY_HISTORY_FILE
$ # ^You'll want to filter that down in practice!
There might be issues with IO buffering. Also the file might get too huge. One would have to come up with a solution to these problems.
Due to updates and changes overtime, version compatibility start causing issues with configuration.
Your webpack.config.js should be like this you can also configure how ever you dim fit.
var path = require('path');
var webpack = require("webpack");
module.exports = {
entry: './src/js/app.js',
devtool: 'source-map',
mode: 'development',
module: {
rules: [{
test: /\.js$/,
exclude: /node_modules/,
use: ["babel-loader"]
},{
test: /\.css$/,
use: ['style-loader', 'css-loader']
}]
},
output: {
path: path.resolve(__dirname, './src/vendor'),
filename: 'bundle.min.js'
}
};
Another Thing to notice it's the change of args, you should read babel documentation https://babeljs.io/docs/en/presets
.babelrc
{
"presets": ["@babel/preset-env", "@babel/preset-react"]
}
NB: you have to make sure you have the above @babel/preset-env & @babel/preset-react installed in your package.json dependencies
What makes jQuery easy to use is that you don't have to apply attributes to each element. The jQuery object contains an array of elements, and the methods of the jQuery object applies the same attributes to all the elements in the array.
There is also a shorter form for $(document).ready(function(){...})
in $(function(){...})
.
So, this is all you need:
$(function(){
$('div.easy_editor').css('border','9px solid red');
});
If you want the code to work for any element with that class, you can just specify the class in the selector without the tag name:
$(function(){
$('.easy_editor').css('border','9px solid red');
});
You don't set PYTHONPATH
, you add entries to sys.path
. It's a list of directories that should be searched for Python packages, so you can just append your directories to that list.
sys.path.append('/path/to/whatever')
In fact, sys.path
is initialized by splitting the value of PYTHONPATH
on the path separator character (:
on Linux-like systems, ;
on Windows).
You can also add directories using site.addsitedir
, and that method will also take into account .pth
files existing within the directories you pass. (That would not be the case with directories you specify in PYTHONPATH
.)
Just close the visual studio and reopen and execute. It worked for me.
sudo apt-get update
sudo apt purge python2.7-minimal
I was using this way:
worksheet.get_Range(11, 1, 11, 41)
.SetHeadFontStyle()
.SetHeadFillStyle(45)
.SetBorders(
XlBorderWeight.xlMedium
, XlBorderWeight.xlThick
, XlBorderWeight.xlMedium
, XlBorderWeight.xlThick)
;
SetHeadFontStyle / SetHeadFillStyle is ExtMethod of Range like below:
public static Range SetHeadFillStyle(this Range rng, int colorIndex)
{
//do some operation
return rng;
}
do some operation and return the Range for next operation
it's look like Linq :)
but now still can't fully look like it -- propery set value
with cell.Border(xlEdgeTop)
.LineStyle = xlContinuous
.Weight = xlMedium
.ColorIndex = xlAutomatic
You could create a JsonConverter
. See here for an example thats similar to your question.
I made a javascript function to create dots with an svg. You can adjust dot spacing and size in the javascript code.
var make_dotted_borders = function() {_x000D_
// EDIT THESE SETTINGS:_x000D_
_x000D_
var spacing = 8;_x000D_
var dot_width = 2;_x000D_
var dot_height = 2;_x000D_
_x000D_
//---------------------_x000D_
_x000D_
var dotteds = document.getElementsByClassName("dotted");_x000D_
for (var i = 0; i < dotteds.length; i++) {_x000D_
var width = dotteds[i].clientWidth + 1.5;_x000D_
var height = dotteds[i].clientHeight;_x000D_
_x000D_
var horizontal_count = Math.floor(width / spacing);_x000D_
var h_spacing_percent = 100 / horizontal_count;_x000D_
var h_subtraction_percent = ((dot_width / 2) / width) * 100;_x000D_
_x000D_
var vertical_count = Math.floor(height / spacing);_x000D_
var v_spacing_percent = 100 / vertical_count;_x000D_
var v_subtraction_percent = ((dot_height / 2) / height) * 100;_x000D_
_x000D_
var dot_container = document.createElement("div");_x000D_
dot_container.classList.add("dot_container");_x000D_
dot_container.style.display = getComputedStyle(dotteds[i], null).display;_x000D_
_x000D_
var clone = dotteds[i].cloneNode(true);_x000D_
_x000D_
dotteds[i].parentElement.replaceChild(dot_container, dotteds[i]);_x000D_
dot_container.appendChild(clone);_x000D_
_x000D_
for (var x = 0; x < horizontal_count; x++) {_x000D_
// The Top Dots_x000D_
var dot = document.createElement("div");_x000D_
dot.classList.add("dot");_x000D_
dot.style.width = dot_width + "px";_x000D_
dot.style.height = dot_height + "px";_x000D_
_x000D_
var left_percent = (h_spacing_percent * x) - h_subtraction_percent;_x000D_
dot.style.left = left_percent + "%";_x000D_
dot.style.top = (-dot_height / 2) + "px";_x000D_
dot_container.appendChild(dot);_x000D_
_x000D_
// The Bottom Dots_x000D_
var dot = document.createElement("div");_x000D_
dot.classList.add("dot");_x000D_
dot.style.width = dot_width + "px";_x000D_
dot.style.height = dot_height + "px";_x000D_
_x000D_
dot.style.left = (h_spacing_percent * x) - h_subtraction_percent + "%";_x000D_
dot.style.top = height - (dot_height / 2) + "px";_x000D_
dot_container.appendChild(dot);_x000D_
}_x000D_
_x000D_
for (var y = 1; y < vertical_count; y++) {_x000D_
// The Left Dots:_x000D_
var dot = document.createElement("div");_x000D_
dot.classList.add("dot");_x000D_
dot.style.width = dot_width + "px";_x000D_
dot.style.height = dot_height + "px";_x000D_
_x000D_
dot.style.left = (-dot_width / 2) + "px";_x000D_
dot.style.top = (v_spacing_percent * y) - v_subtraction_percent + "%";_x000D_
dot_container.appendChild(dot);_x000D_
}_x000D_
for (var y = 0; y < vertical_count + 1; y++) {_x000D_
// The Right Dots:_x000D_
var dot = document.createElement("div");_x000D_
dot.classList.add("dot");_x000D_
dot.style.width = dot_width + "px";_x000D_
dot.style.height = dot_height + "px";_x000D_
_x000D_
dot.style.left = width - (dot_width / 2) + "px";_x000D_
if (y < vertical_count) {_x000D_
dot.style.top = (v_spacing_percent * y) - v_subtraction_percent + "%";_x000D_
}_x000D_
else {_x000D_
dot.style.top = height - (dot_height / 2) + "px";_x000D_
}_x000D_
_x000D_
dot_container.appendChild(dot);_x000D_
}_x000D_
}_x000D_
}_x000D_
_x000D_
make_dotted_borders();
_x000D_
div.dotted {_x000D_
display: inline-block;_x000D_
padding: 0.5em;_x000D_
}_x000D_
_x000D_
div.dot_container {_x000D_
position: relative;_x000D_
margin-left: 0.25em;_x000D_
margin-right: 0.25em;_x000D_
}_x000D_
_x000D_
div.dot {_x000D_
position: absolute;_x000D_
content: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" height="100" width="100"><circle cx="50" cy="50" r="50" fill="black" /></svg>');_x000D_
}
_x000D_
<div class="dotted">Lorem Ipsum</div>
_x000D_
Here is the codepen demo showing the solution:
Important highlights:
html
, body
, ... .container
, should have the height set to 100%flex
to ANY of the flex items will trigger calculation of the items sizes based on flex distribution:
flex
, for example: flex: 1
then this flex item will occupy the remaining of the spaceflex
property, the calculation will be more complicated. For example, if the item 1 is set to flex: 1
and the item 2 is se to flex: 2
then the item 2 will take twice more of the remaining space
flex-direction
propertyflex
property: https://www.w3.org/TR/css-flexbox-1/#propdef-flex
min-*
and max-*
will be respectedConsidering that both strings may be very large, there are 2 main approaches bitwise search
and localeCompare
I recommed this function
function compareLargeStrings(a,b){
if (a.length !== b.length) {
return false;
}
return a.localeCompare(b) === 0;
}
I was getting the same exact error as well. Here is the fix. When you are specifying where to write to, Android will automatically resolve your path into either /data/
or /mnt/sdcard/
. Let me explain.
If you execute the following statement:
File resolveMe = new File("/data/myPackage/files/media/qmhUZU.jpg");
resolveMe.createNewFile();
It will resolve the path to the root /data/
somewhere higher up in Android.
I figured this out, because after I executed the following code, it was placed automatically in the root /mnt/
without me translating anything on my own.
File resolveMeSDCard = new File("/sdcard/myPackage/files/media/qmhUZU.jpg");
resolveMeSDCard.createNewFile();
A quick fix would be to change your following code:
File f = new File(getLocalPath().replace("/data/data/", "/"));
Hope this helps
via https://speakerdeck.com/anguscroll/es6-uncensored by Angus Croll
It turns out, we can use spread
operator:
var myArr = [...mySet];
Or, alternatively, use Array.from
:
var myArr = Array.from(mySet);
I recently needed to do a System Restore and it caused several of my files to change/disappear that I had been working on since the restore. Some of those were DLL files. I used Source Control to retrieve the entire project but I still had a similar issue as above. I found this answer that described you may need to remove a DLL and readd it to get your errors fixed. This was the case in my scenario.
Removing WebMatrix.WebData
and readding it as well as adding in WebMatrix.Data
fixed my error of The type or namespace name 'Data' does not exist in the namespace 'WebMatrix' ...
.
Here you can find some useful info about cURL & cookies http://docstore.mik.ua/orelly/webprog/pcook/ch11_04.htm .
You can also use this well done method https://github.com/alixaxel/phunction/blob/master/phunction/Net.php#L89 like a function:
function CURL($url, $data = null, $method = 'GET', $cookie = null, $options = null, $retries = 3)
{
$result = false;
if ((extension_loaded('curl') === true) && (is_resource($curl = curl_init()) === true))
{
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_FAILONERROR, true);
curl_setopt($curl, CURLOPT_AUTOREFERER, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
if (preg_match('~^(?:DELETE|GET|HEAD|OPTIONS|POST|PUT)$~i', $method) > 0)
{
if (preg_match('~^(?:HEAD|OPTIONS)$~i', $method) > 0)
{
curl_setopt_array($curl, array(CURLOPT_HEADER => true, CURLOPT_NOBODY => true));
}
else if (preg_match('~^(?:POST|PUT)$~i', $method) > 0)
{
if (is_array($data) === true)
{
foreach (preg_grep('~^@~', $data) as $key => $value)
{
$data[$key] = sprintf('@%s', rtrim(str_replace('\\', '/', realpath(ltrim($value, '@'))), '/') . (is_dir(ltrim($value, '@')) ? '/' : ''));
}
if (count($data) != count($data, COUNT_RECURSIVE))
{
$data = http_build_query($data, '', '&');
}
}
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
}
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, strtoupper($method));
if (isset($cookie) === true)
{
curl_setopt_array($curl, array_fill_keys(array(CURLOPT_COOKIEJAR, CURLOPT_COOKIEFILE), strval($cookie)));
}
if ((intval(ini_get('safe_mode')) == 0) && (ini_set('open_basedir', null) !== false))
{
curl_setopt_array($curl, array(CURLOPT_MAXREDIRS => 5, CURLOPT_FOLLOWLOCATION => true));
}
if (is_array($options) === true)
{
curl_setopt_array($curl, $options);
}
for ($i = 1; $i <= $retries; ++$i)
{
$result = curl_exec($curl);
if (($i == $retries) || ($result !== false))
{
break;
}
usleep(pow(2, $i - 2) * 1000000);
}
}
curl_close($curl);
}
return $result;
}
And pass this as $cookie
parameter:
$cookie_jar = tempnam('/tmp','cookie');
Assuming one has installed a JDK in /opt/java/jdk1.8.0_144
then:
Install the alternative for javac
$ sudo update-alternatives --install /usr/bin/javac javac /opt/java/jdk1.8.0_144/bin/javac 1
Check / update the alternatives config:
$ sudo update-alternatives --config javac
If there is only a single alternative for javac
you will get a message saying so, otherwise select the option for the new JDK.
To check everything is setup correctly then:
$ which javac
/usr/bin/javac
$ ls -l /usr/bin/javac
lrwxrwxrwx 1 root root 23 Sep 4 17:10 /usr/bin/javac -> /etc/alternatives/javac
$ ls -l /etc/alternatives/javac
lrwxrwxrwx 1 root root 32 Sep 4 17:10 /etc/alternatives/javac -> /opt/java/jdk1.8.0_144/bin/javac
And finally
$ javac -version
javac 1.8.0_144
Repeat for java, keytool, jar, etc as needed.
According to PEP8, long lines should be placed in parentheses. When using parentheses, the lines can be broken up without using backslashes. You should also try to put the line break after boolean operators.
Further to this, if you're using a code style check such as pycodestyle, the next logical line needs to have different indentation to your code block.
For example:
if (abcdefghijklmnopqrstuvwxyz > some_other_long_identifier and
here_is_another_long_identifier != and_finally_another_long_name):
# ... your code here ...
pass
I'm sure you know that a std::vector<X>
stores a whole bunch of X
objects, right? But if you have a std::map<X, Y>
, what it actually stores is a whole bunch of std::pair<const X, Y>
s. That's exactly what a map is - it pairs together the keys and the associated values.
When you iterate over a std::map
, you're iterating over all of these std::pair
s. When you dereference one of these iterators, you get a std::pair
containing the key and its associated value.
std::map<std::string, int> m = /* fill it */;
auto it = m.begin();
Here, if you now do *it
, you will get the the std::pair
for the first element in the map.
Now the type std::pair
gives you access to its elements through two members: first
and second
. So if you have a std::pair<X, Y>
called p
, p.first
is an X
object and p.second
is a Y
object.
So now you know that dereferencing a std::map
iterator gives you a std::pair
, you can then access its elements with first
and second
. For example, (*it).first
will give you the key and (*it).second
will give you the value. These are equivalent to it->first
and it->second
.
You can also perform Implicit Type Conversions with template literals. Example:
let fruits = ["mango","orange","pineapple","papaya"];
console.log(`My favourite fruits are ${fruits}`);
// My favourite fruits are mango,orange,pineapple,papaya
I have a test application set up using JPA/Hibernate & Spring, and my configuration mirrors yours with the exception that I create a datasource and inject it into the EntityManagerFactory, and moved the datasource specific properties out of the persistenceUnit and into the datasource. With these two small changes, my EM gets injected properly.
It can be done simply by using the following codes inside onCreate. By using android's default layout
Snackbar.make(findViewById(android.R.id.content),"Your Message",Snackbar.LENGTH_LONG).show();
As ping
works, but telnet
to port 80
does not, the HTTP port 80
is closed on your machine. I assume that your browser's HTTP connection goes through a proxy (as browsing works, how else would you read stackoverflow?).
You need to add some code to your python program, that handles the proxy, like described here:
Just had similar problem in Eclipse fixed with:
rightclick on project->Properties->Deployment Assembly->add Maven Dependencies
something kicked it out before, while I was editing my pom.xml
I had all needed jar files, taglib uri and web.xml was ok
Yes, you can install IPA in iPad, first you have to import that IPA to your itunes. Connect your iPad to iTunes then install application just by click on install and then sync.
Here's an example that only uses a Left join and I believe is more efficient than any group by method out there: ExchangeCore Blog
SELECT t1.*
FROM TrainTable t1 LEFT JOIN TrainTable t2
ON (t1.Train = t2.Train AND t1.Time < t2.Time)
WHERE t2.Time IS NULL;
If you are helpless like me, try this:
List all Sub-Modules of "Serial" (or whatever package you are having trouble with) with the method described here: List all the modules that are part of a python package
In my case, the problems solved one after the other.
...looks like a bug to me...
isinstance()
In your case, isinstance("this is a string", str)
will return True
.
You may also want to read this: http://www.canonical.org/~kragen/isinstance/
The difference is substantial for many applications. If you are currently constrained by storage throughput, particularly when reading data, BitLocker will slow you down.
It would be useful to compare with other software based whole disk or whole partition encryption like TrueCrypt (which has the advantage if you dual boot with Linux since it works for both Windows and Linux).
A much better option is to use hardware encryption, which is available in many SSDs as well as in Hitachi 7200 RPM HDD. The performance of encrypted v. not is undetectable, and the encryption is invisible to operating systems. If you have a decent laptop, you can use the built-in security functions to generate and store the key, which your password unlocks from the encrypted key storage of the laptop.
$order = new WC_Order( $post_id );
If you
echo $order->id;
then you'll be returned the id of the post from which the order is made. As you've already got that, it's probably not what you want.
echo $order->get_order_number();
will return the id of the order (with a # in front of it). To get rid of the #,
echo trim( str_replace( '#', '', $order->get_order_number() ) );
as per the accepted answer.
This may be late but hope this may help.. Try this....
public void writefile()
{
File externalStorageDir = Environment.getExternalStorageDirectory();
File myFile = new File(externalStorageDir , "yourfilename.txt");
if(myFile.exists())
{
try
{
FileOutputStream fostream = new FileOutputStream(myFile);
OutputStreamWriter oswriter = new OutputStreamWriter(fostream);
BufferedWriter bwriter = new BufferedWriter(oswriter);
bwriter.write("Hi welcome ");
bwriter.newLine();
bwriter.close();
oswriter.close();
fostream.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
else
{
try {
myFile.createNewFile();
}
catch (IOException e)
{
e.printStackTrace();
}
}
here bfwritter.newline
writes your text into the file. And add the permission
<uses-permission android:name = "android.permission.WRITE_EXTERNAL_STORAGE"/>
in your manifest file without fail.
As pointed out by Brani, vector() is a solution, e.g.
newVector <- vector(mode = "numeric", length = 50)
will return a vector named "newVector" with 50 "0"'s as initial values. It is also fairly common to just add the new scalar to an existing vector to arrive at an expanded vector, e.g.
aVector <- c(aVector, newScalar)
Hello guys i am using this technique to get the values from the selected dropdown list and it is working like charm.
var methodvalue = $("#method option:selected").val();
Its easy, just wrap it in a relative box like so:
<div class="relative">
<div class="absolute">LOGO</div>
</div>
The relative box has a margin: 0 Auto; and, important, a width...
You can't use the ID while inserting, neither do you need it. MySQL does not even know the ID when you are inserting that record. You could just save "sahf4d2fdd45"
in the payment_code
table and use id
and payment_code
later on.
If you really need your payment_code to have the ID in it then UPDATE the row after the insert to add the ID.
The include path is set against the server configuration (PHP.ini) but the include path you specify is relative to that path so in your case the include path is (actual path in windows):
C:\xampp\php\PEAR\initcontrols\header_myworks.php
providing the path you pasted in the subject is correct. Make sure your file is located there.
For more info you can get and set the include path programmatically.
I know it was asked over 6 years ago, but knowledge is still knowledge. This is different solution than all above, as I had to run it under SQL Server 2000:
DECLARE @TestData TABLE([ID] int, [SKU] char(6), [Product] varchar(15))
INSERT INTO @TestData values (1 ,'FOO-23', 'Orange')
INSERT INTO @TestData values (2 ,'BAR-23', 'Orange')
INSERT INTO @TestData values (3 ,'FOO-24', 'Apple')
INSERT INTO @TestData values (4 ,'FOO-25', 'Orange')
SELECT DISTINCT [ID] = ( SELECT TOP 1 [ID] FROM @TestData Y WHERE Y.[Product] = X.[Product])
,[SKU]= ( SELECT TOP 1 [SKU] FROM @TestData Y WHERE Y.[Product] = X.[Product])
,[PRODUCT]
FROM @TestData X
the position:fixed; property should do the work, I used it on my Website and it worked fine. http://www.w3schools.com/css/css_positioning.asp
This works as you suggest - you just have to specify the class name as well:
python testMyCase.py MyCase.testItIsHot
An example, available for POSIX compliant systems :
/*
* This program displays the names of all files in the current directory.
*/
#include <dirent.h>
#include <stdio.h>
int main(void) {
DIR *d;
struct dirent *dir;
d = opendir(".");
if (d) {
while ((dir = readdir(d)) != NULL) {
printf("%s\n", dir->d_name);
}
closedir(d);
}
return(0);
}
Beware that such an operation is platform dependant in C.
Source : http://faq.cprogramming.com/cgi-bin/smartfaq.cgi?answer=1046380353&id=1044780608
The PostgreSQL manual indicates that this means the transaction is open (inside BEGIN) and idle. It's most likely a user connected using the monitor who is thinking or typing. I have plenty of those on my system, too.
If you're using Slony for replication, however, the Slony-I FAQ suggests idle in transaction
may mean that the network connection was terminated abruptly. Check out the discussion in that FAQ for more details.
http://guides.rubyonrails.org should be a good site if you're trying to get through the basic stuff in Ruby on Rails.
Here is a link to associate models while you generate them: http://guides.rubyonrails.org/getting_started.html#associating-models
As Matt said, the curly braces are for concatenation. The extra curly braces around 16{a[15]}
are the replication operator. They are described in the IEEE Standard for Verilog document (Std 1364-2005), section "5.1.14 Concatenations".
{16{a[15]}}
is the same as
{
a[15], a[15], a[15], a[15], a[15], a[15], a[15], a[15],
a[15], a[15], a[15], a[15], a[15], a[15], a[15], a[15]
}
In bit-blasted form,
assign result = {{16{a[15]}}, {a[15:0]}};
is the same as:
assign result[ 0] = a[ 0];
assign result[ 1] = a[ 1];
assign result[ 2] = a[ 2];
assign result[ 3] = a[ 3];
assign result[ 4] = a[ 4];
assign result[ 5] = a[ 5];
assign result[ 6] = a[ 6];
assign result[ 7] = a[ 7];
assign result[ 8] = a[ 8];
assign result[ 9] = a[ 9];
assign result[10] = a[10];
assign result[11] = a[11];
assign result[12] = a[12];
assign result[13] = a[13];
assign result[14] = a[14];
assign result[15] = a[15];
assign result[16] = a[15];
assign result[17] = a[15];
assign result[18] = a[15];
assign result[19] = a[15];
assign result[20] = a[15];
assign result[21] = a[15];
assign result[22] = a[15];
assign result[23] = a[15];
assign result[24] = a[15];
assign result[25] = a[15];
assign result[26] = a[15];
assign result[27] = a[15];
assign result[28] = a[15];
assign result[29] = a[15];
assign result[30] = a[15];
assign result[31] = a[15];
Simply use RelativeLayout
or FrameLayout
. The last child view will overlay everything else.
Android supports a pattern which Cocoa Touch SDK doesn't: Layout management.
Layout for iPhone means to position everything absolute (besides some strech factors). Layout in android means that children will be placed in relation to eachother.
Example (second EditText will completely cover the first one):
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/root_view">
<EditText
android:layout_width="fill_parent"
android:id="@+id/editText1"
android:layout_height="fill_parent">
</EditText>
<EditText
android:layout_width="fill_parent"
android:id="@+id/editText2"
android:layout_height="fill_parent">
<requestFocus></requestFocus>
</EditText>
</FrameLayout>
FrameLayout
is some kind of view stack. Made for special cases.
RelativeLayout
is pretty powerful. You can define rules like View A has to align parent layout bottom, View B has to align A bottom to top, etc
Update based on comment
Usually you set the content with setContentView(R.layout.your_layout)
in onCreate
(it will inflate the layout for you). You can do that manually and call setContentView(inflatedView)
, there's no difference.
The view itself might be a single view (like TextView
) or a complex layout hierarchy (nested layouts, since all layouts are views themselves).
After calling setContentView
your activity knows what its content looks like and you can use (FrameLayout) findViewById(R.id.root_view)
to retrieve any view int this hierarchy (General pattern (ClassOfTheViewWithThisId) findViewById(R.id.declared_id_of_view)
).
Promises are an abstraction over statements that allow us to express ourselves synchronously with asynchronous code. They represent a execution of a one time task.
They also provide exception handling, just like normal code, you can return from a promise or you can throw.
What you'd want in synchronous code is:
try{
try{
var res = $http.getSync("url");
res = someProcessingOf(res);
} catch (e) {
console.log("Got an error!",e);
throw e; // rethrow to not marked as handled
}
// do more stuff with res
} catch (e){
// handle errors in processing or in error.
}
The promisified version is very similar:
$http.get("url").
then(someProcessingOf).
catch(function(e){
console.log("got an error in initial processing",e);
throw e; // rethrow to not marked as handled,
// in $q it's better to `return $q.reject(e)` here
}).then(function(res){
// do more stuff
}).catch(function(e){
// handle errors in processing or in error.
});
From Increase MySQL connection limit:-
MySQL’s default configuration sets the maximum simultaneous connections to 100. If you need to increase it, you can do it fairly easily:
For MySQL 3.x:
# vi /etc/my.cnf
set-variable = max_connections = 250
For MySQL 4.x and 5.x:
# vi /etc/my.cnf
max_connections = 250
Restart MySQL once you’ve made the changes and verify with:
echo "show variables like 'max_connections';" | mysql
EDIT:-(From comments)
The maximum concurrent connection can be maximum range: 4,294,967,295. Check MYSQL docs
As already stated, you have too many methods (more than 65k) in your project and libs.
Since often the Google Play services is one of the main suspects in "wasting" methods with its 20k+ methods. Google Play services version 6.5 or later, it is possible for you to include Google Play services in your application using a number of smaller client libraries. For example, if you only need GCM and maps you can choose to use these dependencies only:
dependencies {
compile 'com.google.android.gms:play-services-base:6.5.+'
compile 'com.google.android.gms:play-services-maps:6.5.+'
}
The full list of sub libraries and it's responsibilities can be found in the official google doc.
Update: Since Support Library v4 v24.2.0 it was split up into the following modules:
support-compat
,support-core-utils
,support-core-ui
,support-media-compat
andsupport-fragment
dependencies {
compile 'com.android.support:support-fragment:24.2.+'
}
Do note however, if you use support-fragment
, it will have dependencies to all the other modules (ie. if you use android.support.v4.app.Fragment
there is no benefit)
See here the official release notes for support-v4 lib
Since Lollipop (aka build tools 21+) it is very easy to handle. The approach is to work around the 65k methods per dex file problem to create multiple dex files for your app. Add the following to your gradle build file (this is taken from the official google doc on applications with more than 65k methods):
android {
compileSdkVersion 21
buildToolsVersion "21.1.0"
defaultConfig {
...
// Enabling multidex support.
multiDexEnabled true
}
...
}
dependencies {
compile 'com.android.support:multidex:1.0.1'
}
The second step is to either prepare your Application class or if you don't extend Application use the MultiDexApplication
in your Android Manifest:
Either add this to your Application.java
@Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(base);
MultiDex.install(this);
}
or use the provided application from the mutlidex lib
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.android.myapplication">
<application
...
android:name="android.support.multidex.MultiDexApplication">
...
</application>
</manifest>
As further tip, if you run into OutOfMemory
exceptions during the build phase you could enlarge the heap with
android {
...
dexOptions {
javaMaxHeapSize "4g"
}
}
which would set the heap to 4 gigabytes.
See this question for more detail on the dex heap memory issue.
To analyze the source of the methods the gradle plugin https://github.com/KeepSafe/dexcount-gradle-plugin can help in combination with the dependency tree provided by gradle with e.g.
.\gradlew app:dependencies
See this answer and question for more information on method count in android
For python bindings it will be :
element.get_attribute('value')
I had this issue and tried both, but had to settle for removing crap like "pageEditState", but not removing user info lest I have to look it up again.
public static void RemoveEverythingButUserInfo()
{
foreach (String o in HttpContext.Current.Session.Keys)
{
if (o != "UserInfoIDontWantToAskForAgain")
keys.Add(o);
}
}
Say, for an user, there is revision for each date. The following will pick up record for the max revision of each date for each employee.
select job, adate, rev, usr, typ
from tbl
where exists ( select 1 from ( select usr, adate, max(rev) as max_rev
from tbl
group by usr, adate
) as cond
where tbl.usr=cond.usr
and tbl.adate =cond.adate
and tbl.rev =cond.max_rev
)
order by adate, job, usr
For me sure some of the high rated answers "work" when I put them into jsfiddle, but when I have a dynamically generated amount of array list a lot of this code in the answers just doesn't work for ME.
This is what IS working for me.
var from = [];
if(typeof from[0] !== undefined) {
//...
}
Notice, NO quotes around undefined and I'm not bothering with the length.
What's wrong with using 'key_name'
instead, even if it is a variable?
>>> a=["a","b","c","d","e"]
>>> a[0],a[3] = a[3],a[0]
>>> a
['d', 'b', 'c', 'a', 'e']
An algorithm is the description of an automated solution to a problem. What the algorithm does is precisely defined. The solution could or could not be the best possible one but you know from the start what kind of result you will get. You implement the algorithm using some programming language to get (a part of) a program.
Now, some problems are hard and you may not be able to get an acceptable solution in an acceptable time. In such cases you often can get a not too bad solution much faster, by applying some arbitrary choices (educated guesses): that's a heuristic.
A heuristic is still a kind of an algorithm, but one that will not explore all possible states of the problem, or will begin by exploring the most likely ones.
Typical examples are from games. When writing a chess game program you could imagine trying every possible move at some depth level and applying some evaluation function to the board. A heuristic would exclude full branches that begin with obviously bad moves.
In some cases you're not searching for the best solution, but for any solution fitting some constraint. A good heuristic would help to find a solution in a short time, but may also fail to find any if the only solutions are in the states it chose not to try.
Referencing the connection string should be done as such:
MySQLHelper.ExecuteNonQuery(
ConfigurationManager.ConnectionStrings["MyDB"].ConnectionString,
CommandType.Text,
sqlQuery,
sqlParams);
ConfigurationManager.AppSettings["ConnectionString"]
would be looking in the AppSettings
for something named ConnectionString
, which it would not find. This is why your error message indicated the "ConnectionString" property has not been initialized
, because it is looking for an initialized property of AppSettings
named ConnectionString
.
ConfigurationManager.ConnectionStrings["MyDB"].ConnectionString
instructs to look for the connection string named "MyDB".
Here is someone talking about using web.config connection strings
I researched successfully and it is working fine for me. My requirement is to sent an email using vbscript which needs to be call from a batch file in windows. Here is the exact command I am using with no errors.
START C:\Windows\System32\cscript.exe "C:\Documents and Settings\akapoor\Desktop\Mail.vbs"
First of all, why would you need to output to console in a release mode build? Nobody will think to look there when there's a gui...
Second, qDebug is fancy :)
Third, you can try adding console
to your .pro
's CONFIG
, it might work.
teteArg, thank you so much. Just an added information so, everyone bumping into this question will be able to understand why.
What teteArg said is indicated on the Spring Boot Common Properties: http://docs.spring.io/spring-boot/docs/current/reference/html/common-application-properties.html
Apparently, spring.jpa.hibernate.naming.strategy is not a supported property for Spring JPA implementation using Hibernate 5.
I had this issue when inserting date data into a database, you can simply use the struct members separately: In my case it's useful since the sql sentence needs to have the right values and you just need to add the slash or dash to complete the format, no conversions needed.
DateTimePicker dtp = new DateTimePicker();
String sql = "insert into table values(" + dtp.Value.Date.Year + "/" +
dtp.Value.Date.Month + "/" + dtp.Value.Date.Day + ");";
That way you get just the date members without time...
Saish's answer using REGEXP_LIKE
is the right idea but does not support floating numbers. This one will ...
Return values that are numeric
SELECT foo
FROM bar
WHERE REGEXP_LIKE (foo,'^-?\d+(\.\d+)?$');
Return values not numeric
SELECT foo
FROM bar
WHERE NOT REGEXP_LIKE (foo,'^-?\d+(\.\d+)?$');
You can test your regular expressions themselves till your heart is content at http://regexpal.com/ (but make sure you select the checkbox match at line breaks for this one).
Are they the home directories of users in /etc/passwd
? Services like postgres, sendmail, apache, etc., create system users that have home directories just like normal users.
It is possible to turn the string into a stream by using the std::stringstream
class (its constructor takes a string as parameter). Once it's built, you can use the >>
operator on it (like on regular file based streams), which will extract, or tokenize word from it:
#include <iostream>
#include <sstream>
using namespace std;
int main(){
string line = "test one two three.";
string arr[4];
int i = 0;
stringstream ssin(line);
while (ssin.good() && i < 4){
ssin >> arr[i];
++i;
}
for(i = 0; i < 4; i++){
cout << arr[i] << endl;
}
}
I had to do this myself in a context of a web-extension. This web-extension injects some piece of UI into each page, and this UI lives inside an iframe
. The content inside the iframe
is dynamic, so I had to readjust the width and height of the iframe
itself.
I use React but the concept applies to every library.
Inside the iframe
I changed body
styles to have really big dimensions. This will allow the elements inside to lay out using all the necessary space. Making width
and height
100% didn't work for me (I guess because the iframe has a default width = 300px
and height = 150px
)
/* something like this */
body {
width: 99999px;
height: 99999px;
}
Then I injected all the iframe UI inside a div and gave it some styles
#ui-root {
display: 'inline-block';
}
After rendering my app inside this #ui-root
(in React I do this inside componentDidMount
) I compute the dimensions of this div like and sync them to the parent page using window.postMessage
:
let elRect = el.getBoundingClientRect()
window.parent.postMessage({
type: 'resize-iframe',
payload: {
width: elRect.width,
height: elRect.height
}
}, '*')
In the parent frame I do something like this:
window.addEventListener('message', (ev) => {
if(ev.data.type && ev.data.type === 'resize-iframe') {
iframe.style.width = ev.data.payload.width + 'px'
iframe.style.height = ev.data.payload.height + 'px'
}
}, false)
According to the documentation, the static method UUID.randomUUID()
generates a type 4 UUID.
This means that six bits are used for some type information and the remaining 122 bits are assigned randomly.
The six non-random bits are distributed with four in the most significant half of the UUID and two in the least significant half. So the most significant half of your UUID contains 60 bits of randomness, which means you on average need to generate 2^30 UUIDs to get a collision (compared to 2^61 for the full UUID).
So I would say that you are rather safe. Note, however that this is absolutely not true for other types of UUIDs, as Carl Seleborg mentions.
Incidentally, you would be slightly better off by using the least significant half of the UUID (or just generating a random long using SecureRandom).
you must changes in $watch ....
function MyController($scope) {_x000D_
$scope.form = {_x000D_
name: 'my name',_x000D_
}_x000D_
_x000D_
$scope.$watch('form.name', function(newVal, oldVal){_x000D_
console.log('changed');_x000D_
_x000D_
});_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>_x000D_
<div ng-app>_x000D_
<div ng-controller="MyController">_x000D_
<label>Name:</label> <input type="text" ng-model="form.name"/>_x000D_
_x000D_
<pre>_x000D_
{{ form }}_x000D_
</pre>_x000D_
</div>_x000D_
</div>
_x000D_
You can add your attribute on callback function ({key} , speed.callback, like is
$('.usercontent').animate( {
backgroundColor:'#ddd',
},1000,function () {
$(this).css("backgroundColor","red")
});
bar
is deprecated. Please check ogp.me for the current docs.
Other way could be this one:
driver.FindElement(By.XPath(".//*[@id='examp']/form/select[1]/option[3]")).Click();
and you can change the index in option[x] changing x by the number of element that you want to select.
I don't know if it is the best way but I hope that help you.
The answer depends on what do you need a loop for.
of course you can have a loop similar to Java:
for i in xrange(len(my_list)):
but I never actually used loops like this,
because usually you want to iterate
for obj in my_list
or if you need an index as well
for index, obj in enumerate(my_list)
or you want to produce another collection from a list
map(some_func, my_list)
[somefunc[x] for x in my_list]
also there are itertools
module that covers most of iteration related cases
also please take a look at the builtins like any
, max
, min
, all
, enumerate
I would say - do not try to write Java-like code in python. There is always a pythonic way to do it.
This solution works if you're using chrome (can't verify other browsers) and if the text is located in the same DOM Element:
window.getSelection().anchorNode.textContent.substring(
window.getSelection().extentOffset,
window.getSelection().anchorOffset)
Modules Preconditions:
The IIS core engine uses preconditions to determine when to enable a particular module. Performance reasons, for example, might determine that you only want to execute managed modules for requests that also go to a managed handler. The precondition in the following example (
precondition="managedHandler"
) only enables the forms authentication module for requests that are also handled by a managed handler, such as requests to .aspx or .asmx files:<add name="FormsAuthentication" type="System.Web.Security.FormsAuthenticationModule" preCondition="managedHandler" />
If you remove the attribute
precondition="managedHandler"
, Forms Authentication also applies to content that is not served by managed handlers, such as .html, .jpg, .doc, but also for classic ASP (.asp) or PHP (.php) extensions. See "How to Take Advantage of IIS Integrated Pipeline" for an example of enabling ASP.NET modules to run for all content.You can also use a shortcut to enable all managed (ASP.NET) modules to run for all requests in your application, regardless of the "
managedHandler
" precondition.To enable all managed modules to run for all requests without configuring each module entry to remove the "
managedHandler
" precondition, use therunAllManagedModulesForAllRequests
property in the<modules>
section:<modules runAllManagedModulesForAllRequests="true" />
When you use this property, the "
managedHandler
" precondition has no effect and all managed modules run for all requests.
Copied from IIS Modules Overview: Preconditions
While binding a databound control, you can evaluate a field of the row in your data source with eval() function.
For example you can add a column to your gridview like that :
<asp:BoundField DataField="YourFieldName" />
And alternatively, this is the way with eval :
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lbl" runat="server" Text='<%# Eval("YourFieldName") %>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
It seems a little bit complex, but it's flexible, because you can set any property of the control with the eval() function :
<asp:TemplateField>
<ItemTemplate>
<asp:HyperLink ID="HyperLink1" runat="server"
NavigateUrl='<%# "ShowDetails.aspx?id="+Eval("Id") %>'
Text='<%# Eval("Text", "{0}") %>'></asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>
If the types of your items are all different, here is a class I made to get them more intuitively.
The usage of this class:
var t = TypedTuple.Create("hello", 1, new MyClass());
var s = t.Get<string>();
var i = t.Get<int>();
var c = t.Get<MyClass>();
Source code:
public static class TypedTuple
{
public static TypedTuple<T1> Create<T1>(T1 t1)
{
return new TypedTuple<T1>(t1);
}
public static TypedTuple<T1, T2> Create<T1, T2>(T1 t1, T2 t2)
{
return new TypedTuple<T1, T2>(t1, t2);
}
public static TypedTuple<T1, T2, T3> Create<T1, T2, T3>(T1 t1, T2 t2, T3 t3)
{
return new TypedTuple<T1, T2, T3>(t1, t2, t3);
}
public static TypedTuple<T1, T2, T3, T4> Create<T1, T2, T3, T4>(T1 t1, T2 t2, T3 t3, T4 t4)
{
return new TypedTuple<T1, T2, T3, T4>(t1, t2, t3, t4);
}
public static TypedTuple<T1, T2, T3, T4, T5> Create<T1, T2, T3, T4, T5>(T1 t1, T2 t2, T3 t3, T4 t4, T5 t5)
{
return new TypedTuple<T1, T2, T3, T4, T5>(t1, t2, t3, t4, t5);
}
public static TypedTuple<T1, T2, T3, T4, T5, T6> Create<T1, T2, T3, T4, T5, T6>(T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6)
{
return new TypedTuple<T1, T2, T3, T4, T5, T6>(t1, t2, t3, t4, t5, t6);
}
public static TypedTuple<T1, T2, T3, T4, T5, T6, T7> Create<T1, T2, T3, T4, T5, T6, T7>(T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6, T7 t7)
{
return new TypedTuple<T1, T2, T3, T4, T5, T6, T7>(t1, t2, t3, t4, t5, t6, t7);
}
public static TypedTuple<T1, T2, T3, T4, T5, T6, T7, T8> Create<T1, T2, T3, T4, T5, T6, T7, T8>(T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6, T7 t7, T8 t8)
{
return new TypedTuple<T1, T2, T3, T4, T5, T6, T7, T8>(t1, t2, t3, t4, t5, t6, t7, t8);
}
}
public class TypedTuple<T>
{
protected Dictionary<Type, object> items = new Dictionary<Type, object>();
public TypedTuple(T item1)
{
Item1 = item1;
}
public TSource Get<TSource>()
{
object value;
if (this.items.TryGetValue(typeof(TSource), out value))
{
return (TSource)value;
}
else
return default(TSource);
}
private T item1;
public T Item1 { get { return this.item1; } set { this.item1 = value; this.items[typeof(T)] = value; } }
}
public class TypedTuple<T1, T2> : TypedTuple<T1>
{
public TypedTuple(T1 item1, T2 item2)
: base(item1)
{
Item2 = item2;
}
private T2 item2;
public T2 Item2 { get { return this.item2; } set { this.item2 = value; this.items[typeof(T2)] = value; } }
}
public class TypedTuple<T1, T2, T3> : TypedTuple<T1, T2>
{
public TypedTuple(T1 item1, T2 item2, T3 item3)
: base(item1, item2)
{
Item3 = item3;
}
private T3 item3;
public T3 Item3 { get { return this.item3; } set { this.item3 = value; this.items[typeof(T3)] = value; } }
}
public class TypedTuple<T1, T2, T3, T4> : TypedTuple<T1, T2, T3>
{
public TypedTuple(T1 item1, T2 item2, T3 item3, T4 item4)
: base(item1, item2, item3)
{
Item4 = item4;
}
private T4 item4;
public T4 Item4 { get { return this.item4; } set { this.item4 = value; this.items[typeof(T4)] = value; } }
}
public class TypedTuple<T1, T2, T3, T4, T5> : TypedTuple<T1, T2, T3, T4>
{
public TypedTuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5)
: base(item1, item2, item3, item4)
{
Item5 = item5;
}
private T5 item5;
public T5 Item5 { get { return this.item5; } set { this.item5 = value; this.items[typeof(T5)] = value; } }
}
public class TypedTuple<T1, T2, T3, T4, T5, T6> : TypedTuple<T1, T2, T3, T4, T5>
{
public TypedTuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6)
: base(item1, item2, item3, item4, item5)
{
Item6 = item6;
}
private T6 item6;
public T6 Item6 { get { return this.item6; } set { this.item6 = value; this.items[typeof(T6)] = value; } }
}
public class TypedTuple<T1, T2, T3, T4, T5, T6, T7> : TypedTuple<T1, T2, T3, T4, T5, T6>
{
public TypedTuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7)
: base(item1, item2, item3, item4, item5, item6)
{
Item7 = item7;
}
private T7 item7;
public T7 Item7 { get { return this.item7; } set { this.item7 = value; this.items[typeof(T7)] = value; } }
}
public class TypedTuple<T1, T2, T3, T4, T5, T6, T7, T8> : TypedTuple<T1, T2, T3, T4, T5, T6, T7>
{
public TypedTuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7, T8 item8)
: base(item1, item2, item3, item4, item5, item6, item7)
{
Item8 = item8;
}
private T8 item8;
public T8 Item8 { get { return this.item8; } set { this.item8 = value; this.items[typeof(T8)] = value; } }
}
The above answers provided are perfect. The LF(\n
), CR(\r
) and CRLF(\r\n
) characters are platform dependent. However, the interpretation for these characters is not only defined by the platforms but also the console that you are using. In Intellij console (Windows), this \r
character in this statement System.out.print("Happ\ry");
produces the output y
. But, if you use the terminal (Windows), you will get yapp
as the output.
You can create with javascript some css-rules
, which you can later use in your styles: http://jsfiddle.net/ARTsinn/vKbda/
var addRule = (function (sheet) {
if(!sheet) return;
return function (selector, styles) {
if (sheet.insertRule) return sheet.insertRule(selector + " {" + styles + "}", sheet.cssRules.length);
if (sheet.addRule) return sheet.addRule(selector, styles);
}
}(document.styleSheets[document.styleSheets.length - 1]));
var i = 101;
while (i--) {
addRule("[data-width='" + i + "%']", "width:" + i + "%");
}
This creates 100 pseudo-selectors like this:
[data-width='1%'] { width: 1%; }
[data-width='2%'] { width: 2%; }
[data-width='3%'] { width: 3%; }
...
[data-width='100%'] { width: 100%; }
Note: This is a bit offtopic, and not really what you (or someone) wants, but maybe helpful.
Have you set up a python interpreter facet?
Open Project Structure CTRL+ALT+SHIFT+S
Project settings -> Facets -> expand Python click on child -> Python Interpreter
Then:
Project settings -> Modules -> Expand module -> Python -> Dependencies -> select Python module SDK
If you can't rename the original file, you could also use a symlink:
ln -s foo-bar.py foo_bar.py
Then you can just:
from foo_bar import *
You could use grep. doesn't wget tell you where it's redirecting too? Just grep that out.
It's not a good practice to use document.write
. You can learn more about document.write by pressing here. Don't use document.write unless if you have to. Here's a somewhat friendly javascript/html solution. And yes, there is studies on how InnerHTML is bad, working on a more friendly soultion.
document.getElementById("year").innerHTML=(new Date).getFullYear();
? javascript
? html
<span id="year"></span>
You can place the javascript code in your html, but it would look best in a javascript file. Very clean answer. Personally, I recommend writing the current year with PHP. Probably the safest answer.
If you want to write the current year with PHP, you can do so with this small code.
<?php echo date("Y"); ?>
Remember in order to apply this PHP code, your webpage file has to be PHP.
Calling ifconfig is very platform-dependent, and the networking layer does know what IP addresses a socket is on, so best is to ask it.
Node.js doesn't expose a direct method of doing this, but you can open any socket, and ask what local IP address is in use. For example, opening a socket to www.google.com:
var net = require('net');
function getNetworkIP(callback) {
var socket = net.createConnection(80, 'www.google.com');
socket.on('connect', function() {
callback(undefined, socket.address().address);
socket.end();
});
socket.on('error', function(e) {
callback(e, 'error');
});
}
Usage case:
getNetworkIP(function (error, ip) {
console.log(ip);
if (error) {
console.log('error:', error);
}
});
Not exactly the issue you had but the same error for people searching.
This happened to me when I spent too much time on JavaScript.
Coming back to PHP I concatenated two strings with +
instead of .
and got that error.
Here is sample code for LocalNotification that worked for my project.
Objective-C:
This code block in AppDelegate
file :
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[launchOptions valueForKey:UIApplicationLaunchOptionsLocalNotificationKey];
// Override point for customization after application launch.
return YES;
}
// This code block is invoked when application is in foreground (active-mode)
-(void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
UIAlertView *notificationAlert = [[UIAlertView alloc] initWithTitle:@"Notification" message:@"This local notification"
delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
[notificationAlert show];
// NSLog(@"didReceiveLocalNotification");
}
This code block in .m file of any ViewController
:
-(IBAction)startLocalNotification { // Bind this method to UIButton action
NSLog(@"startLocalNotification");
UILocalNotification *notification = [[UILocalNotification alloc] init];
notification.fireDate = [NSDate dateWithTimeIntervalSinceNow:7];
notification.alertBody = @"This is local notification!";
notification.timeZone = [NSTimeZone defaultTimeZone];
notification.soundName = UILocalNotificationDefaultSoundName;
notification.applicationIconBadgeNumber = 10;
[[UIApplication sharedApplication] scheduleLocalNotification:notification];
}
The above code display an AlertView after time interval of 7 seconds when pressed on button that binds startLocalNotification
If application is in background then it displays BadgeNumber
as 10 and with default notification sound.
This code works fine for iOS 7.x and below but for iOS 8 it will prompt following error on console:
Attempting to schedule a local notification with an alert but haven't received permission from the user to display alerts
This means you need register for local notification. This can be achieved using:
if ([UIApplication instancesRespondToSelector:@selector(registerUserNotificationSettings:)]){
[application registerUserNotificationSettings [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert|UIUserNotificationTypeBadge|UIUserNotificationTypeSound categories:nil]];
}
You can also refer blog for local notification.
Swift:
You AppDelegate.swift
file should look like this:
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: UIUserNotificationType.Sound | UIUserNotificationType.Badge | UIUserNotificationType.Alert, categories: nil))
return true
}
The swift file (say ViewController.swift
) in which you want to create local notification should contain below code:
//MARK: - Button functions
func buttonIsPressed(sender: UIButton) {
println("buttonIsPressed function called \(UIButton.description())")
var localNotification = UILocalNotification()
localNotification.fireDate = NSDate(timeIntervalSinceNow: 3)
localNotification.alertBody = "This is local notification from Swift 2.0"
localNotification.timeZone = NSTimeZone.localTimeZone()
localNotification.repeatInterval = NSCalendarUnit.CalendarUnitMinute
localNotification.userInfo = ["Important":"Data"];
localNotification.soundName = UILocalNotificationDefaultSoundName
localNotification.applicationIconBadgeNumber = 5
localNotification.category = "Message"
UIApplication.sharedApplication().scheduleLocalNotification(localNotification)
}
//MARK: - viewDidLoad
class ViewController: UIViewController {
var objButton : UIButton!
. . .
override func viewDidLoad() {
super.viewDidLoad()
. . .
objButton = UIButton.buttonWithType(.Custom) as? UIButton
objButton.frame = CGRectMake(30, 100, 150, 40)
objButton.setTitle("Click Me", forState: .Normal)
objButton.setTitle("Button pressed", forState: .Highlighted)
objButton.addTarget(self, action: "buttonIsPressed:", forControlEvents: .TouchDown)
. . .
}
. . .
}
The way you use to work with Local Notification in iOS 9 and below is completely different in iOS 10.
Below screen grab from Apple release notes depicts this.
You can refer apple reference document for UserNotification.
Below is code for local notification:
Objective-C:
In App-delegate.h
file use @import UserNotifications;
App-delegate should conform to UNUserNotificationCenterDelegate
protocol
In didFinishLaunchingOptions
use below code:
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
[center requestAuthorizationWithOptions:(UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert)
completionHandler:^(BOOL granted, NSError * _Nullable error) {
if (!error) {
NSLog(@"request authorization succeeded!");
[self showAlert];
}
}];
-(void)showAlert {
UIAlertController *objAlertController = [UIAlertController alertControllerWithTitle:@"Alert" message:@"show an alert!" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"OK"
style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
NSLog(@"Ok clicked!");
}];
[objAlertController addAction:cancelAction];
[[[[[UIApplication sharedApplication] windows] objectAtIndex:0] rootViewController] presentViewController:objAlertController animated:YES completion:^{
}];
}
Now create a button in any view controller and in IBAction use below code :
UNMutableNotificationContent *objNotificationContent = [[UNMutableNotificationContent alloc] init];
objNotificationContent.title = [NSString localizedUserNotificationStringForKey:@“Notification!” arguments:nil];
objNotificationContent.body = [NSString localizedUserNotificationStringForKey:@“This is local notification message!“arguments:nil];
objNotificationContent.sound = [UNNotificationSound defaultSound];
// 4. update application icon badge number
objNotificationContent.badge = @([[UIApplication sharedApplication] applicationIconBadgeNumber] + 1);
// Deliver the notification in five seconds.
UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:10.f repeats:NO];
UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:@“ten” content:objNotificationContent trigger:trigger];
// 3. schedule localNotification
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
[center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
if (!error) {
NSLog(@“Local Notification succeeded“);
} else {
NSLog(@“Local Notification failed“);
}
}];
Swift 3:
AppDelegate.swift
file use import UserNotifications
UNUserNotificationCenterDelegate
protocolIn didFinishLaunchingWithOptions
use below code
// Override point for customization after application launch.
let center = UNUserNotificationCenter.current()
center.requestAuthorization(options: [.alert, .sound]) { (granted, error) in
// Enable or disable features based on authorization.
if error != nil {
print("Request authorization failed!")
} else {
print("Request authorization succeeded!")
self.showAlert()
}
}
func showAlert() {
let objAlert = UIAlertController(title: "Alert", message: "Request authorization succeeded", preferredStyle: UIAlertControllerStyle.alert)
objAlert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
//self.presentViewController(objAlert, animated: true, completion: nil)
UIApplication.shared().keyWindow?.rootViewController?.present(objAlert, animated: true, completion: nil)
}
Now create a button in any view controller and in IBAction use below code :
let content = UNMutableNotificationContent()
content.title = NSString.localizedUserNotificationString(forKey: "Hello!", arguments: nil)
content.body = NSString.localizedUserNotificationString(forKey: "Hello_message_body", arguments: nil)
content.sound = UNNotificationSound.default()
content.categoryIdentifier = "notify-test"
let trigger = UNTimeIntervalNotificationTrigger.init(timeInterval: 5, repeats: false)
let request = UNNotificationRequest.init(identifier: "notify-test", content: content, trigger: trigger)
let center = UNUserNotificationCenter.current()
center.add(request)
Google provides a start to finish PHP/MySQL solution for an example "Store Locator" application with Google Maps. In this example, they store the lat/lng values as "Float" with a length of "10,6"
Here JQuery plugin version of Maryan solution with handle optimization. Only with JQuery 1.7+!
(function ($) {
$.fn.heartbeat = function (options) {
var settings = $.extend({
// These are the defaults.
events: 'mousemove keydown'
, url: '/Home/KeepSessionAlive'
, every: 5*60*1000
}, options);
var keepSessionAlive = false
, $container = $(this)
, handler = function () {
keepSessionAlive = true;
$container.off(settings.events, handler)
}, reset = function () {
keepSessionAlive = false;
$container.on(settings.events, handler);
setTimeout(sessionAlive, settings.every);
}, sessionAlive = function () {
keepSessionAlive && $.ajax({
type: "POST"
, url: settings.url
,success: reset
});
};
reset();
return this;
}
})(jQuery)
and how it does import in your *.cshtml
$('body').heartbeat(); // Simple
$('body').heartbeat({url:'@Url.Action("Home", "heartbeat")'}); // different url
$('body').heartbeat({every:6*60*1000}); // different timeout
When using lombok on a fresh installation of Eclipse or STS, you have to:
Install the lombok jar which you can get at https://projectlombok.org/download. Run the jar (as Administrator if using windows) and specify the path to your Eclipse/STS installation.
Restart your IDE (Eclipse or STS)
Give some time for eclipse to generate the class files for lombok (Might take a up to 4 mins in some cases)
I found some trick for your problem! Here you can see it: Habrahabr -- Redesigning Qt Creator by your hands (russian lang.)
According to that article, that trick is kind of not so dirty, but "hack" (probably it wouldn't harm your system, but it can leave some artifacts on your interface).
You don't need to patch something (there is possibility, but I don't recommend).
Main idea is to use stylesheet like this stylesheet.css:
// on Linux
qtcreator -stylesheet='.qt-stylesheet.css'
// on Windows
[pathToQt]\QtCreator\bin\qtcreator.exe -stylesheet [pathToStyleSheet]
To get such effect:
To customize by your needs, you may need to read documentation: Qt Style Sheets Reference, Qt Style Sheets Examples and so on.
This wiki page is dedicated to custom Qt Creator styling.
P.S. If you'll got better stylesheet, share it, I'll be happy! :)
UPD (10.12.2014): Hopefully, now we can close this topic. Thanks, Simon G., Things have changed once again. Users may use custom themes since QtCreator 3.3. So hacky stylesheets are no longer needed.
Everyone can take a look at todays update: Qt 5.4 released. There you can find information that Qt 5.4, also comes with a brand new version of Qt Creator 3.3. Just take a look at official video at Youtube.
So, to apply dark theme you need go to "Tools" -> "Options" -> "Environment" -> "General" tab, and there you need to change "Theme".
See more information about its configuring here: Configuring Qt Creator.
I'd recommend NPOI. NPOI is FREE and works exclusively with .XLS files. It has helped me a lot.
Detail: you don't need to have Microsoft Office installed on your machine to work with .XLS files if you use NPOI.
Check these blog posts:
Creating Excel spreadsheets .XLS and .XLSX in C#
NPOI with Excel Table and dynamic Chart
[UPDATE]
NPOI 2.0 added support for XLSX and DOCX.
You can read more about it here:
In a comment to one of the answers you mention that to_date with a format doesn't help. In another comment you explain that the table is accessed via DBLINK.
So obviously the other system contains an invalid date that Oracle cannot accept. Fix this in the other dbms (or whatever you dblink to) and your query will work.
Having said this, I agree with the others: always use to_date with a format to convert a string literal to a date. Also never use only two digits for a year. For example '23/04/49' means 2049 in your system (format RR), but it confuses the reader (as you see from the answers suggesting a format with YY).
That's my favorite way prior to Java 8:
Date date = new GregorianCalendar(year, month - 1, day).getTime();
I'd say this is a cleaner approach than:
calendar.set(year, month - 1, day, 0, 0);
cp -r ./SourceFolder ./DestFolder
Using Altair.
from altair import *
import pandas as pd
df = datasets.load_dataset('iris')
Chart(df).mark_point().encode(x='petalLength',y='sepalLength', color='species')
I've also had this problem from a service reference that was out of date, even with the server & client on the same machine. Running 'Update Service Reference' will generally fix it if this is the issue.
Either call cancel()
on the Timer
if that's all it's doing, or cancel()
on the TimerTask
if the timer itself has other tasks which you wish to continue.
You'll want to use a udf as below
from pyspark.sql.types import IntegerType
from pyspark.sql.functions import udf
def func(fruit1, fruit2):
if fruit1 == None or fruit2 == None:
return 3
if fruit1 == fruit2:
return 1
return 0
func_udf = udf(func, IntegerType())
df = df.withColumn('new_column',func_udf(df['fruit1'], df['fruit2']))
You can use System.Diagnostics.Process.Start
.
Or use the WinApi directly with something like the following, which will launch explorer.exe. You can use the fourth parameter to ShellExecute to give it a starting directory.
public partial class Window1 : Window
{
public Window1()
{
ShellExecute(IntPtr.Zero, "open", "explorer.exe", "", "", ShowCommands.SW_NORMAL);
InitializeComponent();
}
public enum ShowCommands : int
{
SW_HIDE = 0,
SW_SHOWNORMAL = 1,
SW_NORMAL = 1,
SW_SHOWMINIMIZED = 2,
SW_SHOWMAXIMIZED = 3,
SW_MAXIMIZE = 3,
SW_SHOWNOACTIVATE = 4,
SW_SHOW = 5,
SW_MINIMIZE = 6,
SW_SHOWMINNOACTIVE = 7,
SW_SHOWNA = 8,
SW_RESTORE = 9,
SW_SHOWDEFAULT = 10,
SW_FORCEMINIMIZE = 11,
SW_MAX = 11
}
[DllImport("shell32.dll")]
static extern IntPtr ShellExecute(
IntPtr hwnd,
string lpOperation,
string lpFile,
string lpParameters,
string lpDirectory,
ShowCommands nShowCmd);
}
The declarations come from the pinvoke.net website.
we can use createNativeQuery("Here Nagitive SQL Query ");
for Example :
Query q = em.createNativeQuery("SELECT a.firstname, a.lastname FROM Author a");
List<Object[]> authors = q.getResultList();
To follow up on Theo's suggestion with my findings (apologies - I don't currently have enough reputation to post this as a comment)
First, this is how to use several named parameters:
String commandString = "INSERT INTO Users (Name, Desk, UpdateTime) VALUES (:Name, :Desk, :UpdateTime)";
using (OracleCommand command = new OracleCommand(commandString, _connection, _transaction))
{
command.Parameters.Add("Name", OracleType.VarChar, 50).Value = strategy;
command.Parameters.Add("Desk", OracleType.VarChar, 50).Value = deskName ?? OracleString.Null;
command.Parameters.Add("UpdateTime", OracleType.DateTime).Value = updated;
command.ExecuteNonQuery();
}
However, I saw no variation in speed between:
I'm using System.Data.OracleClient, deleting and inserting 2500 rows inside a transaction
The CSS uses only the data in the DOM tree, which has little to do with how the renderer decides what to do with elements with missing attributes.
So either let the CSS reflect the HTML
input:not([type]), input[type="text"]
{
background:red;
}
or make the HTML explicit.
<input name='t1' type='text'/> /* Is Not Red */
If it didn't do that, you'd never be able to distinguish between
element { ...properties... }
and
element[attr] { ...properties... }
because all attributes would always be defined on all elements. (For example, table
always has a border
attribute, with 0
for a default.)
To match pattern
or an empty string, use
^$|pattern
^
and $
are the beginning and end of the string anchors respectively.|
is used to denote alternates, e.g. this|that
.\b
\b
in most flavor is a "word boundary" anchor. It is a zero-width match, i.e. an empty string, but it only matches those strings at very specific places, namely at the boundaries of a word.
That is, \b
is located:
\w
and \W
(either order):
^
and \w
\w
\w
and $
\w
This is not trivial depending on specification.
Rename column name in mysql
alter table categories change type category_type varchar(255);
While this is one of the most voted feature requests, there is one plugin available, by Victor Kropp, that adds support to makefiles:
Makefile support plugin for IntelliJ IDEA
You can install directly from the official repository:
Settings > Plugins > search for makefile
> Search in repositories > Install > Restart
There are at least three different ways to run:
It opens a pane named Run target with the output.
HTML:
<button type="submit" name="submit" class="button">
<img src="images/free.png" />
</button>
CSS:
.button { }
In my case, it took some digging, but found it.
My Context
I'm looking at exception/error logs from the website using Elmah. Elmah returns the state of the server at the of time the exception, in the form of a large XML document. For our reporting engine I pretty-print the XML with XmlWriter.
During a website attack, I noticed that some xmls weren't parsing and was receiving this '.', hexadecimal value 0x00, is an invalid character.
exception.
NON-RESOLUTION: I converted the document to a byte[]
and sanitized it of 0x00, but it found none.
When I scanned the xml document, I found the following:
...
<form>
...
<item name="SomeField">
<value
string="C:\boot.ini�.htm" />
</item>
...
There was the nul byte encoded as an html entity �
!!!
RESOLUTION: To fix the encoding, I replaced the �
value before loading it into my XmlDocument
, because loading it will create the nul byte and it will be difficult to sanitize it from the object. Here's my entire process:
XmlDocument xml = new XmlDocument();
details.Xml = details.Xml.Replace("�", "[0x00]"); // in my case I want to see it, otherwise just replace with ""
xml.LoadXml(details.Xml);
string formattedXml = null;
// I have this in a helper function, but for this example I have put it in-line
StringBuilder sb = new StringBuilder();
XmlWriterSettings settings = new XmlWriterSettings {
OmitXmlDeclaration = true,
Indent = true,
IndentChars = "\t",
NewLineHandling = NewLineHandling.None,
};
using (XmlWriter writer = XmlWriter.Create(sb, settings)) {
xml.Save(writer);
formattedXml = sb.ToString();
}
LESSON LEARNED: sanitize for illegal bytes using the associated html entity, if your incoming data is html encoded on entry.
PS> I posted this answer on a related question. Here's how I got round the issue of my async ajax request losing the trusted context:
I opened the popup directly on the users click, directed the url to about:blank
and got a handle on that window. You could probably direct the popup to a 'loading' url while your ajax request is made
var myWindow = window.open("about:blank",'name','height=500,width=550');
Then, when my request is successful, I open my callback url in the window
function showWindow(win, url) {
win.open(url,'name','height=500,width=550');
}
The closest thing in C# 3.0, is that you can use a constructor to initialize properties:
Stuff.Elements.Foo foo = new Stuff.Elements.Foo() {Name = "Bob Dylan", Age = 68, Location = "On Tour", IsCool = true}
Following code is working for me.
Usings:
using System.IO;
using System.Net;
using Newtonsoft.Json.Linq;
Code:
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (Stream responseStream = response.GetResponseStream())
{
using (StreamReader responseReader = new StreamReader(responseStream))
{
string json = responseReader.ReadToEnd();
string data = JObject.Parse(json)["id"].ToString();
}
}
}
//json = {"kind": "ALL", "id": "1221455", "longUrl": "NewURL"}
Apps can’t be deleted if they are part of a Game Center group, in an app bundle, or currently displayed on a store. You’ll want to remove the app from sale or from the group if you want to delete it.
Source: iTunes Connect Developer Guide - Transferring and Deleting Apps
tsc
requires a config file or .ts(x) files to compile.
To solve both of your issues, create a file called tsconfig.json
with the following contents:
{
"compilerOptions": {
"outFile": "../../built/local/tsc.js"
},
"exclude": [
"node_modules"
]
}
Also, modify your npm run with this
tsc --config /path/to/a/tsconfig.json
(tl;dr: The exact answer to your question is numpy.empty
or numpy.empty_like
, but you likely don't care and can get away with using myList = [None]*10000
.)
You can initialize your list to all the same element. Whether it semantically makes sense to use a non-numeric value (that will give an error later if you use it, which is a good thing) or something like 0 (unusual? maybe useful if you're writing a sparse matrix or the 'default' value should be 0 and you're not worried about bugs) is up to you:
>>> [None for _ in range(10)]
[None, None, None, None, None, None, None, None, None, None]
(Here _
is just a variable name, you could have used i
.)
You can also do so like this:
>>> [None]*10
[None, None, None, None, None, None, None, None, None, None]
You probably don't need to optimize this. You can also append to the array every time you need to:
>>> x = []
>>> for i in range(10):
>>> x.append(i)
Which is best?
>>> def initAndWrite_test():
... x = [None]*10000
... for i in range(10000):
... x[i] = i
...
>>> def initAndWrite2_test():
... x = [None for _ in range(10000)]
... for i in range(10000):
... x[i] = i
...
>>> def appendWrite_test():
... x = []
... for i in range(10000):
... x.append(i)
Results in python2.7:
>>> import timeit
>>> for f in [initAndWrite_test, initAndWrite2_test, appendWrite_test]:
... print('{} takes {} usec/loop'.format(f.__name__, timeit.timeit(f, number=1000)*1000))
...
initAndWrite_test takes 714.596033096 usec/loop
initAndWrite2_test takes 981.526136398 usec/loop
appendWrite_test takes 908.597946167 usec/loop
Results in python 3.2:
initAndWrite_test takes 641.3581371307373 usec/loop
initAndWrite2_test takes 1033.6499214172363 usec/loop
appendWrite_test takes 895.9040641784668 usec/loop
As we can see, it is likely better to do the idiom [None]*10000
in both python2 and python3. However, if one is doing anything more complicated than assignment (such as anything complicated to generate or process every element in the list), then the overhead becomes a meaninglessly small fraction of the cost. That is, such optimization is premature to worry about if you're doing anything reasonable with the elements of your list.
These are all however inefficient because they go through memory, writing something in the process. In C this is different: an uninitialized array is filled with random garbage memory (sidenote: that has been reallocated from the system, and can be a security risk when you allocate or fail to mlock and/or fail to delete memory when closing the program). This is a design choice, designed for speedup: the makers of the C language thought that it was better not to automatically initialize memory, and that was the correct choice.
This is not an asymptotic speedup (because it's O(N)
), but for example you wouldn't need to first initialize your entire memory block before you overwrite with stuff you actually care about. This, if it were possible, is equivalent to something like (pseudo-code) x = list(size=10000)
.
If you want something similar in python, you can use the numpy
numerical matrix/N-dimensional-array manipulation package. Specifically, numpy.empty
or numpy.empty_like
That is the real answer to your question.
Since JSF 2.3 all the bean scopes defined in package javax.faces.bean
package have been deprecated to align the scopes with CDI. Moreover they're only applicable if your bean is using @ManagedBean
annotation. If you are using JSF versions below 2.3 refer to the legacy answer at the end.
From JSF 2.3 here are scopes that can be used on JSF Backing Beans:
1. @javax.enterprise.context.ApplicationScoped
: The application scope persists for the entire duration of the web application. That scope is shared among all requests and all sessions. This is useful when you have data for whole application.
2. @javax.enterprise.context.SessionScoped
: The session scope persists from the time that a session is established until session termination. The session context is shared between all requests that occur in the same HTTP session. This is useful when you wont to save data for a specific client for a particular session.
3. @javax.enterprise.context.ConversationScoped
: The conversation scope persists as log as the bean lives. The scope provides 2 methods: Conversation.begin()
and Conversation.end()
. These methods should called explicitly, either to start or end the life of a bean.
4. @javax.enterprise.context.RequestScoped
: The request scope is short-lived. It starts when an HTTP request is submitted and ends after the response is sent back to the client. If you place a managed bean into request scope, a new instance is created with each request. It is worth considering request scope if you are concerned about the cost of session scope storage.
5. @javax.faces.flow.FlowScoped
: The Flow scope persists as long as the Flow lives. A flow may be defined as a contained set of pages (or views) that define a unit of work. Flow scoped been is active as long as user navigates with in the Flow.
6. @javax.faces.view.ViewScoped
: A bean in view scope persists while the same JSF page is redisplayed. As soon as the user navigates to a different page, the bean goes out of scope.
The following legacy answer applies JSF version before 2.3
As of JSF 2.x there are 4 Bean Scopes:
- @SessionScoped
- @RequestScoped
- @ApplicationScoped
- @ViewScoped
Session Scope: The session scope persists from the time that a session is established until session termination. A session terminates if the web application invokes the invalidate method on the HttpSession object, or if it times out.
RequestScope: The request scope is short-lived. It starts when an HTTP request is submitted and ends after the response is sent back to the client. If you place a managed bean into request scope, a new instance is created with each request. It is worth considering request scope if you are concerned about the cost of session scope storage.
ApplicationScope: The application scope persists for the entire duration of the web application. That scope is shared among all requests and all sessions. You place managed beans into the application scope if a single bean should be shared among all instances of a web application. The bean is constructed when it is first requested by any user of the application, and it stays alive until the web application is removed from the application server.
ViewScope: View scope was added in JSF 2.0. A bean in view scope persists while the same JSF page is redisplayed. (The JSF specification uses the term view for a JSF page.) As soon as the user navigates to a different page, the bean goes out of scope.
Choose the scope you based on your requirement.
Source: Core Java Server Faces 3rd Edition by David Geary & Cay Horstmann [Page no. 51 - 54]
there is dual method for fcm
fcm messaging notification and app notification
in first your app reciever only message notification with body ,title and you can add color ,vibration not working,sound default.
in 2nd you can full control what happen when you recieve message example
onMessageReciever(RemoteMessage rMessage){ notification.setContentTitle(rMessage.getData().get("yourKey")); }
you will recieve data with(yourKey)
but that not from fcm message
that from fcm cloud functions
reguard
Thread-safe code is code that will work even if many Threads are executing it simultaneously.
One line Swift 5.2
let date = String(DateFormatter.localizedString(from: NSDate() as Date, dateStyle: .medium, timeStyle: .short))
If you are in a browser environment you can also use btoa.
btoa
is a function which takes a string as argument and produces a Base64 encoded ASCII string. Its supported by 97% of browsers.
Example:
> "Basic " + btoa("billy"+":"+"secretpassword")
< "Basic YmlsbHk6c2VjcmV0cGFzc3dvcmQ="
You can then add Basic YmlsbHk6c2VjcmV0cGFzc3dvcmQ=
to the authorization
header.
Note that the usual caveats about HTTP BASIC auth apply, most importantly if you do not send your traffic over https an eavesdropped can simply decode the Base64 encoded string thus obtaining your password.
This security.stackexchange.com answer gives a good overview of some of the downsides.
use javascript inbuild functions escape and unescape
for example
var escapedData = escape("hel'lo");
output = "%27hel%27lo%27" which can be used in the attribute.
again to read the value from the attr
var unescapedData = unescape("%27hel%27lo%27")
output = "'hel'lo'"
This will be helpful if you have huge json stringify data to be used in the attribute
You can do it without setlocal
, because of the setlocal
command the variable won't survive an endlocal
because it was created in setlocal
. In this way the variable will be defined the right way.
To do that use this code:
set var1=A
set var2=B
set AB=hi
call set newvar=%%%var1%%var2%%%
echo %newvar%
Note: You MUST use call
before you set the variable or it won't work.
You can use it like this: http://plnkr.co/edit/vtNjEgmpItqxX5fdwtPi?p=preview
Like you found, filter
accepts predicate function which accepts item
by item from the array.
So, you just have to create an predicate function based on the given criteria
.
In this example, criteriaMatch
is a function which returns a predicate
function which matches the given criteria
.
template:
<div ng-repeat="item in items | filter:criteriaMatch(criteria)">
{{ item }}
</div>
scope:
$scope.criteriaMatch = function( criteria ) {
return function( item ) {
return item.name === criteria.name;
};
};
You can use sort of Maybe monad (though I'd prefer Jay's answer)
public class Maybe<T>
{
private readonly T _value;
public Maybe(T value)
{
_value = value;
IsNothing = false;
}
public Maybe()
{
IsNothing = true;
}
public bool IsNothing { get; private set; }
public T Value
{
get
{
if (IsNothing)
{
throw new InvalidOperationException("Value doesn't exist");
}
return _value;
}
}
public override bool Equals(object other)
{
if (IsNothing)
{
return (other == null);
}
if (other == null)
{
return false;
}
return _value.Equals(other);
}
public override int GetHashCode()
{
if (IsNothing)
{
return 0;
}
return _value.GetHashCode();
}
public override string ToString()
{
if (IsNothing)
{
return "";
}
return _value.ToString();
}
public static implicit operator Maybe<T>(T value)
{
return new Maybe<T>(value);
}
public static explicit operator T(Maybe<T> value)
{
return value.Value;
}
}
Your method would look like:
public static Maybe<T> GetQueryString<T>(string key) where T : IConvertible
{
if (String.IsNullOrEmpty(HttpContext.Current.Request.QueryString[key]) == false)
{
string value = HttpContext.Current.Request.QueryString[key];
try
{
return (T)Convert.ChangeType(value, typeof(T));
}
catch
{
//Could not convert. Pass back default value...
return new Maybe<T>();
}
}
return new Maybe<T>();
}
I too faced the same problem. Despite of following every Answer it didnt work. Then I changed the "Inherits=namespace.class" to "Inherits=fully qualified assemble name" i.e "Inherits=namespace.class,assemblyname, Version=, Culture=, PublicKeyToken=" Hope it helps.
Simply add a class (on any element) and check inside the interval if it's there. This is more reliable, customisable and cross-language than any other way, I believe.
var i = 0;_x000D_
this.setInterval(function() {_x000D_
if(!$('#counter').hasClass('pauseInterval')) { //only run if it hasn't got this class 'pauseInterval'_x000D_
console.log('Counting...');_x000D_
$('#counter').html(i++); //just for explaining and showing_x000D_
} else {_x000D_
console.log('Stopped counting');_x000D_
}_x000D_
}, 500);_x000D_
_x000D_
/* In this example, I'm adding a class on mouseover and remove it again on mouseleave. You can of course do pretty much whatever you like */_x000D_
$('#counter').hover(function() { //mouse enter_x000D_
$(this).addClass('pauseInterval');_x000D_
},function() { //mouse leave_x000D_
$(this).removeClass('pauseInterval');_x000D_
}_x000D_
);_x000D_
_x000D_
/* Other example */_x000D_
$('#pauseInterval').click(function() {_x000D_
$('#counter').toggleClass('pauseInterval');_x000D_
});
_x000D_
body {_x000D_
background-color: #eee;_x000D_
font-family: Calibri, Arial, sans-serif;_x000D_
}_x000D_
#counter {_x000D_
width: 50%;_x000D_
background: #ddd;_x000D_
border: 2px solid #009afd;_x000D_
border-radius: 5px;_x000D_
padding: 5px;_x000D_
text-align: center;_x000D_
transition: .3s;_x000D_
margin: 0 auto;_x000D_
}_x000D_
#counter.pauseInterval {_x000D_
border-color: red; _x000D_
}
_x000D_
<!-- you'll need jQuery for this. If you really want a vanilla version, ask -->_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
_x000D_
<p id="counter"> </p>_x000D_
<button id="pauseInterval">Pause/unpause</button></p>
_x000D_
I assume you want to link to a library called foo, its filename is usually something link foo.dll
or libfoo.so
.
1. Find the library
You have to find the library. This is a good idea, even if you know the path to your library. CMake will error out if the library vanished or got a new name. This helps to spot error early and to make it clear to the user (may yourself) what causes a problem.
To find a library foo and store the path in FOO_LIB
use
find_library(FOO_LIB foo)
CMake will figure out itself how the actual file name is. It checks the usual places like /usr/lib
, /usr/lib64
and the paths in PATH
.
You already know the location of your library. Add it to the CMAKE_PREFIX_PATH
when you call CMake, then CMake will look for your library in the passed paths, too.
Sometimes you need to add hints or path suffixes, see the documentation for details: https://cmake.org/cmake/help/latest/command/find_library.html
2. Link the library
From 1. you have the full library name in FOO_LIB
. You use this to link the library to your target GLBall
as in
target_link_libraries(GLBall PRIVATE "${FOO_LIB}")
You should add PRIVATE
, PUBLIC
, or INTERFACE
after the target, cf. the documentation:
https://cmake.org/cmake/help/latest/command/target_link_libraries.html
If you don't add one of these visibility specifiers, it will either behave like PRIVATE
or PUBLIC
, depending on the CMake version and the policies set.
3. Add includes (This step might be not mandatory.)
If you also want to include header files, use find_path
similar to find_library
and search for a header file. Then add the include directory with target_include_directories
similar to target_link_libraries
.
Documentation: https://cmake.org/cmake/help/latest/command/find_path.html and https://cmake.org/cmake/help/latest/command/target_include_directories.html
If available for the external software, you can replace find_library
and find_path
by find_package
.
Indeed a one-hot encoder will work just fine here, convert any string and numerical categorical variables you want into 1's and 0's this way and random forest should not complain.
Sorry for "answering my own question", but I figured out a workaround... If we remove the newlines in the comment / commit message, it seems to work fine.
Your groups_main
table has a key column named id
. I believe you can only use the USING
syntax for the join if the groups_fans
table has a key column with the same name, which it probably does not. So instead, try this:
LEFT JOIN groups_fans AS m ON m.group_id = g.id
Or replace group_id
with whatever the appropriate column name is in the groups_fans
table.
You could do something like this:
//outside of main
namespace A
{
enum A
{
a = 0,
b = 69,
c = 666
};
};
//in main:
A::A a = A::c;
std::cout << a << std::endl;
The for-each loop was introduced in Java 1.5 and is used with collections (and to be pedantic, arrays, and anything implementing the Iterable<E>
interface ... which the article notes):
http://download.oracle.com/javase/1,5.0/docs/guide/language/foreach.html
If you are using windows, then take a look at this link. Otherwise, you may look for your OS specific version api. I don't think C++ comes with a cross-platform way to do it. At the end, it's NOT C++'s work, it's the OS's work.
I ran a benchmarking analysis and list(mvv_count_df.select('mvv').toPandas()['mvv'])
is the fastest method. I'm very surprised.
I ran the different approaches on 100 thousand / 100 million row datasets using a 5 node i3.xlarge cluster (each node has 30.5 GBs of RAM and 4 cores) with Spark 2.4.5. Data was evenly distributed on 20 snappy compressed Parquet files with a single column.
Here's the benchmarking results (runtimes in seconds):
+-------------------------------------------------------------+---------+-------------+
| Code | 100,000 | 100,000,000 |
+-------------------------------------------------------------+---------+-------------+
| df.select("col_name").rdd.flatMap(lambda x: x).collect() | 0.4 | 55.3 |
| list(df.select('col_name').toPandas()['col_name']) | 0.4 | 17.5 |
| df.select('col_name').rdd.map(lambda row : row[0]).collect()| 0.9 | 69 |
| [row[0] for row in df.select('col_name').collect()] | 1.0 | OOM |
| [r[0] for r in mid_df.select('col_name').toLocalIterator()] | 1.2 | * |
+-------------------------------------------------------------+---------+-------------+
* cancelled after 800 seconds
Golden rules to follow when collecting data on the driver node:
toPandas
was significantly improved in Spark 2.3. It's probably not the best approach if you're using a Spark version earlier than 2.3.
See here for more details / benchmarking results.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TRIAL
{
public class Class1
{
static void Main(string[] args)
{
string[] fileArray = Directory.GetDirectories("YOUR PATH");
for (int i = 0; i < fileArray.Length; i++)
{
Console.WriteLine(fileArray[i]);
}
Console.ReadLine();
}
}
}
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
in your PrimaryKey column and make sure its set to a data type int. If the column is the primary key and is set to IsIDentity to true in SQL there is no need for this line of code [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
Considering unit test is the domain of this question, highly recommend you to use monkey. This Package make you to mock test without changing your original source code. Compare to other answer, it's more "non-intrusive".
main
type AA struct {
//...
}
func (a *AA) OriginalFunc() {
//...
}
mock test
var a *AA
func NewFunc(a *AA) {
//...
}
monkey.PatchMethod(reflect.TypeOf(a), "OriginalFunc", NewFunc)
Bad side is:
Good side is:
I have written a small routine which copies formula from a cell to clipboard which one can easily paste in Visual Basic Editor.
Public Sub CopyExcelFormulaInVBAFormat()
Dim strFormula As String
Dim objDataObj As Object
'\Check that single cell is selected!
If Selection.Cells.Count > 1 Then
MsgBox "Select single cell only!", vbCritical
Exit Sub
End If
'Check if we are not on a blank cell!
If Len(ActiveCell.Formula) = 0 Then
MsgBox "No Formula To Copy!", vbCritical
Exit Sub
End If
'Add quotes as required in VBE
strFormula = Chr(34) & Replace(ActiveCell.Formula, Chr(34), Chr(34) & Chr(34)) & Chr(34)
'This is ClsID of MSFORMS Data Object
Set objDataObj = CreateObject("New:{1C3B4210-F441-11CE-B9EA-00AA006B1A69}")
objDataObj.SetText strFormula, 1
objDataObj.PutInClipboard
MsgBox "VBA Format formula copied to Clipboard!", vbInformation
Set objDataObj = Nothing
End Sub
It is originally posted on Chandoo.org forums' Vault Section.
Thanks all. I took bits of each of your solutions and made my own.
The final working solution is:
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
url: '<?php bloginfo('template_url'); ?>/functions/twitter.php',
data: "tweets=<?php echo $ct_tweets; ?>&account=<?php echo $ct_twitter; ?>",
success: function(data) {
$('#twitter-loader').remove();
$('#twitter-container').html(data);
}
});
});
</script>
Just a note: I have experienced different behaviours on different versions of bash:
for the former (3.1) for nn in (00..99) ; do ...
works but for nn in (000..999) ; do ...
does not work
both will work on version 4.1 ; haven't tested printf behaviour
(bash --version
gave the version info)
Cheers, Jan
Looks like you are using python 2.x. Python 2.x defaults to ascii and it doesn’t know about Unicode. Hence the exception.
Just paste the below line after shebang, it will work
# -*- coding: utf-8 -*-
There's also SSH Key - Still asking for password and passphrase
Using ssh-add ~/.ssh/id_rsa
without a local keychain.
This avoids having to mess with tokens.
Reading a CSV file in very simple and common in Java. You actually don't require to load any extra third party library to do this for you. CSV (comma separated value) file is just a normal plain-text file, store data in column by column, and split it by a separator (e.g comma ",").
In order to read specific columns from the CSV file, there are several ways. Simplest of all is as below:
Code to read CSV without any 3rd party library
BufferedReader br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
// use comma as separator
String[] cols = line.split(cvsSplitBy);
System.out.println("Coulmn 4= " + cols[4] + " , Column 5=" + cols[5]);
}
If you notice, nothing special is performed here. It is just reading a text file, and spitting it by a separator – ",".
Consider an extract from legacy country CSV data at GeoLite Free Downloadable Databases
"1.0.0.0","1.0.0.255","16777216","16777471","AU","Australia"
"1.0.1.0","1.0.3.255","16777472","16778239","CN","China"
"1.0.4.0","1.0.7.255","16778240","16779263","AU","Australia"
"1.0.8.0","1.0.15.255","16779264","16781311","CN","China"
"1.0.16.0","1.0.31.255","16781312","16785407","JP","Japan"
"1.0.32.0","1.0.63.255","16785408","16793599","CN","China"
"1.0.64.0","1.0.127.255","16793600","16809983","JP","Japan"
"1.0.128.0","1.0.255.255","16809984","16842751","TH","Thailand"
Above code will output as below:
Column 4= "AU" , Column 5="Australia"
Column 4= "CN" , Column 5="China"
Column 4= "AU" , Column 5="Australia"
Column 4= "CN" , Column 5="China"
Column 4= "JP" , Column 5="Japan"
Column 4= "CN" , Column 5="China"
Column 4= "JP" , Column 5="Japan"
Column 4= "TH" , Column 5="Thailand"
You can, in fact, put
the columns in a Map
and then get the values simply by using the key
.
Shishir
To eliminate the need for the cmd variable, you can do this:
eval 'mysql AMORE -u root --password="password" -h localhost -e "select host from amoreconfig"'
I had a similar issue. Killing an existing instance of the ADB process from Task Manager did not work for me.
Just few days back, I had tried to install MIPS SDK and ADT-17 earlier and Eclipse gave me the error, and I did not fix that issue.
So, now, when I got this ADB server didn't ACK, failed to start daemon... issue, I executed 'Check for Updates' in the Eclipse Help menu item. There were no updates available, but at least 'ADB server did not ACK' error disappeared.
I hope this might help in a few cases.
The Mozilla Developer Network provides the following explanation:
event = document.createEvent("KeyboardEvent")
using:
event.initKeyEvent (type, bubbles, cancelable, viewArg,
ctrlKeyArg, altKeyArg, shiftKeyArg, metaKeyArg,
keyCodeArg, charCodeArg)
yourElement.dispatchEvent(event)
I don't see the last one in your code, maybe that's what you're missing. I hope this works in IE as well...
et.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
et.setHint(temp +" Characters");
}
});
Use 0 for true and 1 for false.
Sample:
#!/bin/bash
isdirectory() {
if [ -d "$1" ]
then
# 0 = true
return 0
else
# 1 = false
return 1
fi
}
if isdirectory $1; then echo "is directory"; else echo "nopes"; fi
Edit
From @amichair's comment, these are also possible
isdirectory() {
if [ -d "$1" ]
then
true
else
false
fi
}
isdirectory() {
[ -d "$1" ]
}
Do you mean you want to execute code in function1 regardless of whether function2 threw an exception or not? Have you looked at the finally-block? http://msdn.microsoft.com/en-us/library/zwc8s4fz.aspx
For me, ant apparently refuses to listen to any configuration for eclipse default, project JDK, and the suggestion of "Ant Home Entries" just didn't have traction - there was nothing there referring to JDK.
However, this works:
Menu "Run" -> "External Tools" -> "External Tools Configuration".
Goto the node "Ant build", choose the ant buildfile in question.
Choose tab "JRE".
Select e.g. "Run in same JRE as workspace", or whatever you want.
You might try using my mailer module.
from mailer import Mailer
from mailer import Message
message = Message(From="[email protected]",
To="[email protected]")
message.Subject = "An HTML Email"
message.Html = """<p>Hi!<br>
How are you?<br>
Here is the <a href="http://www.python.org">link</a> you wanted.</p>"""
sender = Mailer('smtp.example.com')
sender.send(message)
Execute in a terminal:
mongo // To go to shell
show databases // To show all existing databases.
use <DATA_BASE> // To switch to the wanted database.
db.dropDatabase() // To remove the current database.
You can't declare multiple types in the initialization, but you can assign to multiple types E.G.
{
int i;
char x;
for(i = 0, x = 'p'; ...){
...
}
}
Just declare them in their own scope.
Quoting this article https://docs.microsoft.com/en-us/windows/desktop/FileIO/naming-a-file#maximum-path-length-limitation
Maximum Path Length Limitation
In the Windows API (with some exceptions discussed in the following paragraphs), the maximum length for a path is MAX_PATH, which is defined as 260 characters. A local path is structured in the following order: drive letter, colon, backslash, name components separated by backslashes, and a terminating null character. For example, the maximum path on drive D is "D:\some 256-character path string<NUL>" where "<NUL>" represents the invisible terminating null character for the current system codepage. (The characters < > are used here for visual clarity and cannot be part of a valid path string.)
Now we see that it is 1+2+256+1 or [drive][:\][path][null] = 260. One could assume that 256 is a reasonable fixed string length from the DOS days. And going back to the DOS APIs we realize that the system tracked the current path per drive, and we have 26 (32 with symbols) maximum drives (and current directories).
The INT 0x21 AH=0x47 says “This function returns the path description without the drive letter and the initial backslash.” So we see that the system stores the CWD as a pair (drive, path) and you ask for the path by specifying the drive (1=A, 2=B, …), if you specify a 0 then it assumes the path for the drive returned by INT 0x21 AH=0x15 AL=0x19. So now we know why it is 260 and not 256, because those 4 bytes are not stored in the path string.
Why a 256 byte path string, because 640K is enough RAM.
UPDATE `MySQL_Table`
SET `MySQL_Table_Column` = REPLACE(`MySQL_Table_Column`, 'oldString', 'newString')
WHERE `MySQL_Table_Column` LIKE 'oldString%';
SWIFT 3
To clear, nowadays there is a default method:
public init?(_ text: String)` of `Double` class.
It can be used for all classes.
let c = Double("-1.0")
let f = Double("0x1c.6")
let i = Double("inf")
, etc.
Solutions above don't work with websites with cloudflare protection, example: https://paxful.com/fr/buy-bitcoin
.
Modify agent as follows: options.add_argument("user-agent=Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.125 Safari/537.36")
Fix found here: What is the difference in accessing Cloudflare website using ChromeDriver/Chrome in normal/headless mode through Selenium Python
You must use the Invoke-Command cmdlet to launch this external program. Normally it works without an effort.
If you need more than one command you should use the Invoke-Expression cmdlet with the -scriptblock
option.
Gluing several answers together fit my need for existing json:
Code:
echo "<pre>";
echo json_encode(json_decode($json_response), JSON_PRETTY_PRINT);
echo "</pre>";
Output:
{
"data": {
"token_type": "bearer",
"expires_in": 3628799,
"scopes": "full_access",
"created_at": 1540504324
},
"errors": [],
"pagination": {},
"token_type": "bearer",
"expires_in": 3628799,
"scopes": "full_access",
"created_at": 1540504324
}
If you know which column to search against, you can use array_search() and array_column():
$userdb = Array
(
(0) => Array
(
('uid') => '100',
('name') => 'Sandra Shush',
('url') => 'urlof100'
),
(1) => Array
(
('uid') => '5465',
('name') => 'Stefanie Mcmohn',
('url') => 'urlof5465'
),
(2) => Array
(
('uid') => '40489',
('name') => 'Michael',
('url') => 'urlof40489'
)
);
if(array_search('urlof5465', array_column($userdb, 'url')) !== false) {
echo 'value is in multidim array';
}
else {
echo 'value is not in multidim array';
}
This idea is in the comments section for array_search() on the PHP manual;
To drop last n rows:
df.drop(df.tail(n).index,inplace=True) # drop last n rows
By the same vein, you can drop first n rows:
df.drop(df.head(n).index,inplace=True) # drop first n rows
In case anybody is here and the other two solutions do not make the trick, check that what you are using to filter is what you expect:
user = UniversityDetails.objects.get(email=email)
is email a str
, or a None
? or an int
?
You almost always use HashMap
, you should only use TreeMap
if you need your keys to be in a specific order.
I found it easiest to just read the entire line into one column then parse out the data using XML.
IF (OBJECT_ID('tempdb..#data') IS NOT NULL) DROP TABLE #data
CREATE TABLE #data (data VARCHAR(MAX))
BULK INSERT #data FROM 'E:\filefromabove.txt' WITH (FIRSTROW = 2, ROWTERMINATOR = '\n')
IF (OBJECT_ID('tempdb..#dataXml') IS NOT NULL) DROP TABLE #dataXml
CREATE TABLE #dataXml (ID INT NOT NULL IDENTITY(1,1) PRIMARY KEY CLUSTERED, data XML)
INSERT #dataXml (data)
SELECT CAST('<r><d>' + REPLACE(data, '|', '</d><d>') + '</d></r>' AS XML)
FROM #data
SELECT d.data.value('(/r//d)[1]', 'varchar(max)') AS col1,
d.data.value('(/r//d)[2]', 'varchar(max)') AS col2,
d.data.value('(/r//d)[3]', 'varchar(max)') AS col3
FROM #dataXml d
Starting from iOS 6 you can set an attributed string to the UILabel. Check the following :
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:label.text];
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.lineSpacing = spacing;
[attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, label.text.length)];
label.attributedText = attributedString;
Just cast it as a const char *. print((const char *)"Yo!") will work fine.
var color = Enum.Parse<Colors>("Green");
If you whant only one first string, you can use simple for-loop.
var lines = File.ReadAllLines(pathToTextFile);
var firstFound = false;
for(int index = 0; index < lines.Count; index++)
{
if(!firstFound && lines[index].Contains("CustomerEN"))
{
firstFound = true;
}
if(firstFound && lines[index].Contains("CustomerCh"))
{
//do, what you want, and exit the loop
// return lines[index];
}
}
There is a space missing between --
and >
. x
is post decremented, that is, decremented after checking the condition x>0 ?
.
Since there is no way to determine the lenght of all lines without reading them, you have no choice but to iterate over all lines before your starting line. All you can do is to make it look nice. If the file is really huge then you might want to use a generator based approach:
from itertools import dropwhile
def iterate_from_line(f, start_from_line):
return (l for i, l in dropwhile(lambda x: x[0] < start_from_line, enumerate(f)))
for line in iterate_from_line(open(filename, "r", 0), 141978):
DoSomethingWithThisLine(line)
Note: the index is zero based in this approach.