Specifying the path to the DLL file in your project's settings does not ensure that your application will find the DLL at run-time. You only told Visual Studio how to find the files it needs. That has nothing to do with how the program finds what it needs, once built.
Placing the DLL file into the same folder as the executable is by far the simplest solution. That's the default search path for dependencies, so you won't need to do anything special if you go that route.
To avoid having to do this manually each time, you can create a Post-Build Event for your project that will automatically copy the DLL into the appropriate directory after a build completes.
Alternatively, you could deploy the DLL to the Windows side-by-side cache, and add a manifest to your application that specifies the location.
In the generated constructor code it should call OnContextCreated()
I added this partial class to solve the problem:
partial class MyContext: ObjectContext
{
partial void OnContextCreated()
{
this.CommandTimeout = 300;
}
}
To keep all objects whose names match a pattern, you could use grep
, like so:
to.remove <- ls()
to.remove <- c(to.remove[!grepl("^obj", to.remove)], "to.remove")
rm(list=to.remove)
I don't know if Eclipse is THE BEST Java IDE, but it is definitely very decent and my favorite IDE. I tried IntelliJ briefly before, and found that it's pretty similar to Eclipse (IntelliJ might offer some nicer features, but Eclipse is free and open source). I never really tried NetBean because I know Eclipse before I know NetBean.
Eclipse is my favorite because:
If you are used to using conventional Java IDE like JCreator you might need some time to get used to Eclipse. I remember when I first learned Eclipse, I didn't know how to compile Java source...
I would suggest that in order to find the best IDE FOR YOU, try what people recommended (NetBean, Eclipse, and IntelliJ), and see which one you like the most, then stick with it and become an expert of it. Having the right IDE will boost up your productivity a lot in my opinion.
As mentioned here: Re: BUG #4243: Idle in transaction it is probably best to check your pg_locks table to see what is being locked and that might give you a better clue where the problem lies.
'Create Excel
Set objExcel = Wscript.CreateObject("Excel.Application")
objExcel.visible = True
Set objWb = objExcel.Workbooks.Add
objWb.Saveas("D:\Example.xlsx")
objExcel.Quit
Use a hashtag followed by a white-space(!) for this:
# comment here
Do not forget the whitespace here! Otherwise it can interfere with internal commands.
E.g. this is NOT a comment:
#requires -runasadmin
function isset(key){
ret = false;
array_example.forEach(function(entry) {
if( entry == key ){
ret = true;
}
});
return ret;
}
alert( isset("key_search") );
It's just a function. Import it and call it:
import myModule
myModule.main()
If you need to parse arguments, you have two options:
Parse them in main()
, but pass in sys.argv
as a parameter (all code below in the same module myModule
):
def main(args):
# parse arguments using optparse or argparse or what have you
if __name__ == '__main__':
import sys
main(sys.argv[1:])
Now you can import and call myModule.main(['arg1', 'arg2', 'arg3'])
from other another module.
Have main()
accept parameters that are already parsed (again all code in the myModule
module):
def main(foo, bar, baz='spam'):
# run with already parsed arguments
if __name__ == '__main__':
import sys
# parse sys.argv[1:] using optparse or argparse or what have you
main(foovalue, barvalue, **dictofoptions)
and import and call myModule.main(foovalue, barvalue, baz='ham')
elsewhere and passing in python arguments as needed.
The trick here is to detect when your module is being used as a script; when you run a python file as the main script (python filename.py
) no import
statement is being used, so python calls that module "__main__"
. But if that same filename.py
code is treated as a module (import filename
), then python uses that as the module name instead. In both cases the variable __name__
is set, and testing against that tells you how your code was run.
I suggest you do:
<input type="button" value="button text" onclick="click()">
Hope this helps you!
You cannot insert data because you have a quota of 0 on the tablespace. To fix this, run
ALTER USER <user> quota unlimited on <tablespace name>;
or
ALTER USER <user> quota 100M on <tablespace name>;
as a DBA user (depending on how much space you need / want to grant).
Pseudo code, something like:
CASE
When CHARINDEX('lactulose', dbo.Table.Column) > 0 Then 'BP Medication'
ELSE ''
END AS 'Medication Type'
This does not care where the keyword is found in the list and avoids depending on formatting of spaces and commas.
I've also faced the problem of ordering of loaded scripts, which was solved through sequential loading of scripts. The loading is based on Rob W's answer.
function scriptFromFile(file) {
var script = document.createElement("script");
script.src = chrome.extension.getURL(file);
return script;
}
function scriptFromSource(source) {
var script = document.createElement("script");
script.textContent = source;
return script;
}
function inject(scripts) {
if (scripts.length === 0)
return;
var otherScripts = scripts.slice(1);
var script = scripts[0];
var onload = function() {
script.parentNode.removeChild(script);
inject(otherScripts);
};
if (script.src != "") {
script.onload = onload;
document.head.appendChild(script);
} else {
document.head.appendChild(script);
onload();
}
}
The example of usage would be:
var formulaImageUrl = chrome.extension.getURL("formula.png");
var codeImageUrl = chrome.extension.getURL("code.png");
inject([
scriptFromSource("var formulaImageUrl = '" + formulaImageUrl + "';"),
scriptFromSource("var codeImageUrl = '" + codeImageUrl + "';"),
scriptFromFile("EqEditor/eq_editor-lite-17.js"),
scriptFromFile("EqEditor/eq_config.js"),
scriptFromFile("highlight/highlight.pack.js"),
scriptFromFile("injected.js")
]);
Actually, I'm kinda new to JS, so feel free to ping me to the better ways.
Some times due to some code you get HTML tags in a text filed, like I was replacing some characters with new line BR tag of HTML and by mistake I also replaced it in the text that was supposed to be displayed in a Multiline text box so my multiline text box had a new line HTML tag BR in it coming dynamically due to my string replace function and I started getting this JavaScript error and as this HTML code was displayed in a text box that was in an update panel I start getting this error so I made the correction and all was fine. So before copying pasting anything please look at your code and see that all tag are closed proper and no irrelevant code data is coming to text boxes or Drop down lists. This error always come due to ill formed tags and irrelevant data.
If you cannot use RowCounter
for whatever reason, then a combination of these two filters should be an optimal way to get a count:
FirstKeyOnlyFilter() AND KeyOnlyFilter()
The FirstKeyOnlyFilter
will result in the scanner only returning the first column qualifier it finds, as opposed to the scanner returning all of the column qualifiers in the table, which will minimize the network bandwith. What about simply picking one column qualifier to return? This would work if you could guarentee that column qualifier exists for every row, but if that is not true then you would get an inaccurate count.
The KeyOnlyFilter
will result in the scanner only returning the column family, and will not return any value for the column qualifier. This further reduces the network bandwidth, which in the general case wouldn't account for much of a reduction, but there can be an edge case where the first column picked by the previous filter just happens to be an extremely large value.
I tried playing around with scan.setCaching
but the results were all over the place. Perhaps it could help.
I had 16 million rows in between a start and stop that I did the following pseudo-empirical testing:
With FirstKeyOnlyFilter and KeyOnlyFilter activated: With caching not set (i.e., the default value), it took 188 seconds. With caching set to 1, it took 188 seconds With caching set to 10, it took 200 seconds With caching set to 100, it took 187 seconds With caching set to 1000, it took 183 seconds. With caching set to 10000, it took 199 seconds. With caching set to 100000, it took 199 seconds. With FirstKeyOnlyFilter and KeyOnlyFilter disabled: With caching not set, (i.e., the default value), it took 309 seconds
I didn't bother to do proper testing on this, but it seems clear that the FirstKeyOnlyFilter
and KeyOnlyFilter
are good.
Moreover, the cells in this particular table are very small - so I think the filters would have been even better on a different table.
Here is a Java code sample:
import java.io.IOException; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.HBaseConfiguration; import org.apache.hadoop.hbase.client.HTable; import org.apache.hadoop.hbase.client.Result; import org.apache.hadoop.hbase.client.ResultScanner; import org.apache.hadoop.hbase.client.Scan; import org.apache.hadoop.hbase.util.Bytes; import org.apache.hadoop.hbase.filter.RowFilter; import org.apache.hadoop.hbase.filter.KeyOnlyFilter; import org.apache.hadoop.hbase.filter.FirstKeyOnlyFilter; import org.apache.hadoop.hbase.filter.FilterList; import org.apache.hadoop.hbase.filter.CompareFilter.CompareOp; import org.apache.hadoop.hbase.filter.RegexStringComparator; public class HBaseCount { public static void main(String[] args) throws IOException { Configuration config = HBaseConfiguration.create(); HTable table = new HTable(config, "my_table"); Scan scan = new Scan( Bytes.toBytes("foo"), Bytes.toBytes("foo~") ); if (args.length == 1) { scan.setCaching(Integer.valueOf(args[0])); } System.out.println("scan's caching is " + scan.getCaching()); FilterList allFilters = new FilterList(); allFilters.addFilter(new FirstKeyOnlyFilter()); allFilters.addFilter(new KeyOnlyFilter()); scan.setFilter(allFilters); ResultScanner scanner = table.getScanner(scan); int count = 0; long start = System.currentTimeMillis(); try { for (Result rr = scanner.next(); rr != null; rr = scanner.next()) { count += 1; if (count % 100000 == 0) System.out.println(count); } } finally { scanner.close(); } long end = System.currentTimeMillis(); long elapsedTime = end - start; System.out.println("Elapsed time was " + (elapsedTime/1000F)); } }
Here is a pychbase code sample:
from pychbase import Connection c = Connection() t = c.table('my_table') # Under the hood this applies the FirstKeyOnlyFilter and KeyOnlyFilter # similar to the happybase example below print t.count(row_prefix="foo")
Here is a Happybase code sample:
from happybase import Connection c = Connection(...) t = c.table('my_table') count = 0 for _ in t.scan(filter='FirstKeyOnlyFilter() AND KeyOnlyFilter()'): count += 1 print count
Thanks to @Tuckr and @KennyCason for the tip.
System.out.print("Enter a Value: ");
val = s.nextInt();
This line is placed in last.The whole code is as follows:-
public static void main(String[] args){
int min, max;
Scanner s = new Scanner(System.in);
System.out.print("Enter a Value: ");
int val = s.nextInt();
min = max = val;
while (val != 0) {
if (val < min) {
min = val;
}
if (val > max) {
max = val;
}
System.out.print("Enter a Value: ");
val = s.nextInt();
}
System.out.println("Min: " + min);
System.out.println("Max: " + max);
}
To be able to use std::unordered_map
(or one of the other unordered associative containers) with a user-defined key-type, you need to define two things:
A hash function; this must be a class that overrides operator()
and calculates the hash value given an object of the key-type. One particularly straight-forward way of doing this is to specialize the std::hash
template for your key-type.
A comparison function for equality; this is required because the hash cannot rely on the fact that the hash function will always provide a unique hash value for every distinct key (i.e., it needs to be able to deal with collisions), so it needs a way to compare two given keys for an exact match. You can implement this either as a class that overrides operator()
, or as a specialization of std::equal
, or – easiest of all – by overloading operator==()
for your key type (as you did already).
The difficulty with the hash function is that if your key type consists of several members, you will usually have the hash function calculate hash values for the individual members, and then somehow combine them into one hash value for the entire object. For good performance (i.e., few collisions) you should think carefully about how to combine the individual hash values to ensure you avoid getting the same output for different objects too often.
A fairly good starting point for a hash function is one that uses bit shifting and bitwise XOR to combine the individual hash values. For example, assuming a key-type like this:
struct Key
{
std::string first;
std::string second;
int third;
bool operator==(const Key &other) const
{ return (first == other.first
&& second == other.second
&& third == other.third);
}
};
Here is a simple hash function (adapted from the one used in the cppreference example for user-defined hash functions):
namespace std {
template <>
struct hash<Key>
{
std::size_t operator()(const Key& k) const
{
using std::size_t;
using std::hash;
using std::string;
// Compute individual hash values for first,
// second and third and combine them using XOR
// and bit shifting:
return ((hash<string>()(k.first)
^ (hash<string>()(k.second) << 1)) >> 1)
^ (hash<int>()(k.third) << 1);
}
};
}
With this in place, you can instantiate a std::unordered_map
for the key-type:
int main()
{
std::unordered_map<Key,std::string> m6 = {
{ {"John", "Doe", 12}, "example"},
{ {"Mary", "Sue", 21}, "another"}
};
}
It will automatically use std::hash<Key>
as defined above for the hash value calculations, and the operator==
defined as member function of Key
for equality checks.
If you don't want to specialize template inside the std
namespace (although it's perfectly legal in this case), you can define the hash function as a separate class and add it to the template argument list for the map:
struct KeyHasher
{
std::size_t operator()(const Key& k) const
{
using std::size_t;
using std::hash;
using std::string;
return ((hash<string>()(k.first)
^ (hash<string>()(k.second) << 1)) >> 1)
^ (hash<int>()(k.third) << 1);
}
};
int main()
{
std::unordered_map<Key,std::string,KeyHasher> m6 = {
{ {"John", "Doe", 12}, "example"},
{ {"Mary", "Sue", 21}, "another"}
};
}
How to define a better hash function? As said above, defining a good hash function is important to avoid collisions and get good performance. For a real good one you need to take into account the distribution of possible values of all fields and define a hash function that projects that distribution to a space of possible results as wide and evenly distributed as possible.
This can be difficult; the XOR/bit-shifting method above is probably not a bad start. For a slightly better start, you may use the hash_value
and hash_combine
function template from the Boost library. The former acts in a similar way as std::hash
for standard types (recently also including tuples and other useful standard types); the latter helps you combine individual hash values into one. Here is a rewrite of the hash function that uses the Boost helper functions:
#include <boost/functional/hash.hpp>
struct KeyHasher
{
std::size_t operator()(const Key& k) const
{
using boost::hash_value;
using boost::hash_combine;
// Start with a hash value of 0 .
std::size_t seed = 0;
// Modify 'seed' by XORing and bit-shifting in
// one member of 'Key' after the other:
hash_combine(seed,hash_value(k.first));
hash_combine(seed,hash_value(k.second));
hash_combine(seed,hash_value(k.third));
// Return the result.
return seed;
}
};
And here’s a rewrite that doesn’t use boost, yet uses good method of combining the hashes:
namespace std
{
template <>
struct hash<Key>
{
size_t operator()( const Key& k ) const
{
// Compute individual hash values for first, second and third
// http://stackoverflow.com/a/1646913/126995
size_t res = 17;
res = res * 31 + hash<string>()( k.first );
res = res * 31 + hash<string>()( k.second );
res = res * 31 + hash<int>()( k.third );
return res;
}
};
}
Thanks @Joey. It's what I am looking for.
I just bring some improvements:
function Stop-Processes {
param(
[parameter(Mandatory=$true)] $processName,
$timeout = 5
)
$processList = Get-Process $processName -ErrorAction SilentlyContinue
if ($processList) {
# Try gracefully first
$processList.CloseMainWindow() | Out-Null
# Wait until all processes have terminated or until timeout
for ($i = 0 ; $i -le $timeout; $i ++){
$AllHaveExited = $True
$processList | % {
$process = $_
If (!$process.HasExited){
$AllHaveExited = $False
}
}
If ($AllHaveExited){
Return
}
sleep 1
}
# Else: kill
$processList | Stop-Process -Force
}
}
I was only interested for a trigger when a width of an element was changed (I don' care about height), so I created a jquery event that does exactly that, using an invisible iframe element.
$.event.special.widthChanged = {
remove: function() {
$(this).children('iframe.width-changed').remove();
},
add: function () {
var elm = $(this);
var iframe = elm.children('iframe.width-changed');
if (!iframe.length) {
iframe = $('<iframe/>').addClass('width-changed').prependTo(this);
}
var oldWidth = elm.width();
function elmResized() {
var width = elm.width();
if (oldWidth != width) {
elm.trigger('widthChanged', [width, oldWidth]);
oldWidth = width;
}
}
var timer = 0;
var ielm = iframe[0];
(ielm.contentWindow || ielm).onresize = function() {
clearTimeout(timer);
timer = setTimeout(elmResized, 20);
};
}
}
It requires the following css :
iframe.width-changed {
width: 100%;
display: block;
border: 0;
height: 0;
margin: 0;
}
You can see it in action here widthChanged fiddle
Building on Darren's answer, to use Notepad++ you can simply do this (all on one line):
git config --global core.editor "'C:/Program Files/Notepad++/notepad++.exe' -multiInst -notabbar -nosession -noPlugin"
Obviously, the C:/Program Files/Notepad++/notepad++.exe
part should be the path to the Notepad++ executable on your system. For example, it might be C:/Program Files (x86)/Notepad++/notepad++.exe
.
It works like a charm for me.
Your best bet is to create a new List<Customer>
, iterate through the List<Object>
, add each item to the new list, and return that.
If you want your script to return values, just do return [1,2,3]
from a function wrapping your code but then you'd have to import your script from another script to even have any use for that information:
(again, this would have to be run by a separate Python script and be imported in order to even do any good):
import ...
def main():
# calculate stuff
return [1,2,3]
(This is generally just good for when you want to indicate to a governor what went wrong or simply the number of bugs/rows counted or w/e. Normally 0 is a good exit and >=1 is a bad exit but you could inter-prate them in any way you want to get data out of it)
import sys
# calculate and stuff
sys.exit(100)
And exit with a specific exit code depending on what you want that to tell your governor. I used exit codes when running script by a scheduling and monitoring environment to indicate what has happened.
(os._exit(100)
also works, and is a bit more forceful)
If not you'd have to use stdout to communicate with the outside world (like you've described). But that's generally a bad idea unless it's a parser executing your script and can catch whatever it is you're reporting to.
import sys
# calculate stuff
sys.stdout.write('Bugs: 5|Other: 10\n')
sys.stdout.flush()
sys.exit(0)
Are you running your script in a controlled scheduling environment then exit codes are the best way to go.
There's also the option to simply write information to a file, and store the result there.
# calculate
with open('finish.txt', 'wb') as fh:
fh.write(str(5)+'\n')
And pick up the value/result from there. You could even do it in a CSV format for others to read simplistically.
If none of the above work, you can also use network sockets locally *(unix sockets is a great way on nix systems). These are a bit more intricate and deserve their own post/answer. But editing to add it here as it's a good option to communicate between processes. Especially if they should run multiple tasks and return values.
import java.util.*;
public class ScannerExample {
public static void main(String args[]) {
int a;
String s;
Scanner scan = new Scanner(System.in);
System.out.println("enter a no");
a = scan.nextInt();
System.out.println("no is =" + a);
System.out.println("enter a string");
s = scan.next();
System.out.println("string is=" + s);
}
}
As of 10. July 2017, the issue of Bootstrap 4 support with bootstrap-select
is still open. In the open issue, there are some ad-hoc solutions which you could try with your project.
Or you could use a library like Select2 and add a theme to match Bootstrap 4. Here is an example: Select 2 with Bootstrap 4 (disclaimer: I'm not the author of this blog post and I haven't verified if this still works with the all versions of Bootstrap 4).
@DSM's answer is perfectly fine in almost any normal scenario. But if you're the type of programmer who wants to go a little deeper than the surface level, you might be interested to know that it is a little faster to call numpy functions on the underlying .to_numpy()
(or .values
for <0.24) array instead of directly calling the (cythonized) functions defined on the DataFrame/Series objects.
For example, you can use ndarray.max()
along the first axis.
# Data borrowed from @DSM's post.
df = pd.DataFrame({"A": [1,2,3], "B": [-2, 8, 1]})
df
A B
0 1 -2
1 2 8
2 3 1
df['C'] = df[['A', 'B']].values.max(1)
# Or, assuming "A" and "B" are the only columns,
# df['C'] = df.values.max(1)
df
A B C
0 1 -2 1
1 2 8 8
2 3 1 3
If your data has NaN
s, you will need numpy.nanmax
:
df['C'] = np.nanmax(df.values, axis=1)
df
A B C
0 1 -2 1
1 2 8 8
2 3 1 3
You can also use numpy.maximum.reduce
. numpy.maximum
is a ufunc (Universal Function), and every ufunc has a reduce
:
df['C'] = np.maximum.reduce(df['A', 'B']].values, axis=1)
# df['C'] = np.maximum.reduce(df[['A', 'B']], axis=1)
# df['C'] = np.maximum.reduce(df, axis=1)
df
A B C
0 1 -2 1
1 2 8 8
2 3 1 3
np.maximum.reduce
and np.max
appear to be more or less the same (for most normal sized DataFrames)—and happen to be a shade faster than DataFrame.max
. I imagine this difference roughly remains constant, and is due to internal overhead (indexing alignment, handling NaNs, etc).
The graph was generated using perfplot. Benchmarking code, for reference:
import pandas as pd
import perfplot
np.random.seed(0)
df_ = pd.DataFrame(np.random.randn(5, 1000))
perfplot.show(
setup=lambda n: pd.concat([df_] * n, ignore_index=True),
kernels=[
lambda df: df.assign(new=df.max(axis=1)),
lambda df: df.assign(new=df.values.max(1)),
lambda df: df.assign(new=np.nanmax(df.values, axis=1)),
lambda df: df.assign(new=np.maximum.reduce(df.values, axis=1)),
],
labels=['df.max', 'np.max', 'np.maximum.reduce', 'np.nanmax'],
n_range=[2**k for k in range(0, 15)],
xlabel='N (* len(df))',
logx=True,
logy=True)
If you want an efficient search that is often repeated, first sort the array (Array.Sort
) and then use Array.BinarySearch
.
I created a little javascript tool to style elements on screen size without using media queries or recompiling bootstrap css:
https://github.com/Heras/Responsive-Breakpoints
Just add class responsive-breakpoints
to any element, and it will automagically add xs sm md lg xl
classes to those elements.
Save your sorting order in a ViewState.
private const string ASCENDING = " ASC";
private const string DESCENDING = " DESC";
public SortDirection GridViewSortDirection
{
get
{
if (ViewState["sortDirection"] == null)
ViewState["sortDirection"] = SortDirection.Ascending;
return (SortDirection) ViewState["sortDirection"];
}
set { ViewState["sortDirection"] = value; }
}
protected void GridView_Sorting(object sender, GridViewSortEventArgs e)
{
string sortExpression = e.SortExpression;
if (GridViewSortDirection == SortDirection.Ascending)
{
GridViewSortDirection = SortDirection.Descending;
SortGridView(sortExpression, DESCENDING);
}
else
{
GridViewSortDirection = SortDirection.Ascending;
SortGridView(sortExpression, ASCENDING);
}
}
private void SortGridView(string sortExpression,string direction)
{
// You can cache the DataTable for improving performance
DataTable dt = GetData().Tables[0];
DataView dv = new DataView(dt);
dv.Sort = sortExpression + direction;
GridView1.DataSource = dv;
GridView1.DataBind();
}
Why you don't want to use existing sorting functionality? You can always customize it.
Sorting Data in a GridView Web Server Control at MSDN
Here is an example with customization:
Please set your form action attribute as below it will solve your problem.
<form name="addProductForm" id="addProductForm" action="javascript:;" enctype="multipart/form-data" method="post" accept-charset="utf-8">
jQuery code:
$(document).ready(function () {
$("#addProductForm").submit(function (event) {
//disable the default form submission
event.preventDefault();
//grab all form data
var formData = $(this).serialize();
$.ajax({
url: 'addProduct.php',
type: 'POST',
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
success: function () {
alert('Form Submitted!');
},
error: function(){
alert("error in ajax form submission");
}
});
return false;
});
});
In your example, you can't: the 5px margin
is added to the bounding box of div#two
and div#three
effectively making their width and height 100% of parent + 5px, which will overflow.
You can use padding
on the parent Element to ensure there's 5px
of space inside its border:
<style>
html, body {width:100%;height:100%;margin:0;padding:0;}
.border {border:1px solid black;}
#one {padding:5px;width:500px;height:300px;}
#two {width:100%;height:50px;}
#three {width:100px;height:100%;}
</style>
EDIT: In testing, removing the width:100%
from div#two
will actually let it work properly as div
s are block-level and will always fill their parents' widths by default. That should clear your first case if you'd like to use margin.
Instead of adding readonly you can also use onkeypress="return false;"
I did a very straightforward solution by manipulating the output of the .gitignore statement with sed:
cat .gitignore | sed '/^#.*/ d' | sed '/^\s*$/ d' | sed 's/^/git rm -r /' | bash
Explanation:
If you wanted to keep it with just HTML and CSS you can use CSS Variables. Keep in mind, css variables aren't supported in IE.
<div class="thumb" style="--background: url('images/img.jpg')"></div>
.thumb {
background-image: var(--background);
}
As of AngularJS v1.4.0, there is a built-in $httpParamSerializer
service that converts any object to a part of a HTTP request according to the rules that are listed on the docs page.
It can be used like this:
$http.post('http://example.com', $httpParamSerializer(formDataObj)).
success(function(data){/* response status 200-299 */}).
error(function(data){/* response status 400-999 */});
Remember that for a correct form post, the Content-Type
header must be changed. To do this globally for all POST requests, this code (taken from Albireo's half-answer) can be used:
$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";
To do this only for the current post, the headers
property of the request-object needs to be modified:
var req = {
method: 'POST',
url: 'http://example.com',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
data: $httpParamSerializer(formDataObj)
};
$http(req);
Java has Reflection (java.reflection.*), but I would suggest looking into a library like Apache Beanutils, it will make the process much less hairy than using reflection directly.
import subprocess as sbp
import pip
pkgs = eval(str(sbp.run("pip3 list -o --format=json", shell=True,
stdout=sbp.PIPE).stdout, encoding='utf-8'))
for pkg in pkgs:
sbp.run("pip3 install --upgrade " + pkg['name'], shell=True)
Save as xx.py
Then run Python3 xx.py
Environment: python3.5+ pip10.0+
Set the style on the textbox as text-transform: uppercase?
UPDATE mytable SET column=LEFT(column, LEN(column)-5)
Removes the last 5 characters from the column (every row in mytable)
Many of the answers here do not work with the latest Swift (Xcode 7.1.1 at time of writing).
The current way of getting the information is to create a Mirror
and interrogate that. For the classname it is as simple as:
let mirror = Mirror(reflecting: instanceToInspect)
let classname:String = mirror.description
Additional information about the object can also be retrieved from the Mirror
. See http://swiftdoc.org/v2.1/type/Mirror/ for details.
Library Seaborn has this built in with function .despine()
.
Just add:
import seaborn as sns
Now create your graph. And add at the end:
sns.despine()
If you look at some of the default parameter values of the function it removes the top and right spine and keeps the bottom and left spine:
sns.despine(top=True, right=True, left=False, bottom=False)
Check out further documentation here: https://seaborn.pydata.org/generated/seaborn.despine.html
Easy.
Intent myIntent = new Intent(CurrentActivity.this, NextActivity.class);
myIntent.putExtra("key", value); //Optional parameters
CurrentActivity.this.startActivity(myIntent);
Extras are retrieved on the other side via:
@Override
protected void onCreate(Bundle savedInstanceState) {
Intent intent = getIntent();
String value = intent.getStringExtra("key"); //if it's a string you stored.
}
Don't forget to add your new activity in the AndroidManifest.xml:
<activity android:label="@string/app_name" android:name="NextActivity"/>
You can .split()
to get an array of strings, then loop through to convert them to numbers, like this:
var myArray = "14 2".split(" ");
for(var i=0; i<myArray.length; i++) { myArray[i] = +myArray[i]; }
//use myArray, it's an array of numbers
The +myArray[i]
is just a quick way to do the number conversion, if you're sure they're integers you can just do:
for(var i=0; i<myArray.length; i++) { myArray[i] = parseInt(myArray[i], 10); }
If you want the sum of all bars to be equal unity, weight each bin by the total number of values:
weights = np.ones_like(myarray) / len(myarray)
plt.hist(myarray, weights=weights)
Hope that helps, although the thread is quite old...
Note for Python 2.x: add casting to float()
for one of the operators of the division as otherwise you would end up with zeros due to integer division
You can get the raw data by calling ReadAsStringAsAsync
on the Request.Content
property.
string result = await Request.Content.ReadAsStringAsync();
There are various overloads if you want it in a byte or in a stream. Since these are async-methods you need to make sure your controller is async:
public async Task<IHttpActionResult> GetSomething()
{
var rawMessage = await Request.Content.ReadAsStringAsync();
// ...
return Ok();
}
EDIT: if you're receiving an empty string from this method, it means something else has already read it. When it does that, it leaves the pointer at the end. An alternative method of doing this is as follows:
public IHttpActionResult GetSomething()
{
var reader = new StreamReader(Request.Body);
reader.BaseStream.Seek(0, SeekOrigin.Begin);
var rawMessage = reader.ReadToEnd();
return Ok();
}
In this case, your endpoint doesn't need to be async (unless you have other async-methods)
To begin with, it would be best to understand the measure of information
.
measure
the information?When something unlikely happens, we say it's a big news. Also, when we say something predictable, it's not really interesting. So to quantify this interesting-ness
, the function should satisfy
one bit
of information.One natural measure that satisfy the constraints is
I(X) = -log_2(p)
where p is the probability of the event X
. And the unit is in bit
, the same bit computer uses. 0 or 1.
Fair coin flip :
How much information can we get from one coin flip?
Answer : -log(p) = -log(1/2) = 1 (bit)
If a meteor strikes the Earth tomorrow, p=2^{-22}
then we can get 22 bits of information.
If the Sun rises tomorrow, p ~ 1
then it is 0 bit of information.
So if we take expectation on the interesting-ness
of an event Y
, then it is the entropy.
i.e. entropy is an expected value of the interesting-ness of an event.
H(Y) = E[ I(Y)]
More formally, the entropy is the expected number of bits of an event.
Y = 1 : an event X occurs with probability p
Y = 0 : an event X does not occur with probability 1-p
H(Y) = E[I(Y)] = p I(Y==1) + (1-p) I(Y==0)
= - p log p - (1-p) log (1-p)
Log base 2 for all log.
You can have two different versions of XAMPP.
Java does not truely support multidimensional arrays. In Java, a two-dimensional array is simply an array of arrays, a three-dimensional array is an array of arrays of arrays, a four-dimensional array is an array of arrays of arrays of arrays, and so on...
We can define a two-dimensional array as:
int[ ] num[ ] = {{1,2}, {1,2}, {1,2}, {1,2}}
int[ ][ ] num = new int[4][2]
num[0][0] = 1;
num[0][1] = 2;
num[1][0] = 1;
num[1][1] = 2;
num[2][0] = 1;
num[2][1] = 2;
num[3][0] = 1;
num[3][1] = 2;
If you don't allocate, let's say num[2][1]
, it is not initialized and then it is automatically allocated 0, that is, automatically num[2][1] = 0
;
Below, num1.length
gives you rows.
While num1[0].length
gives you the number of elements related to num1[0]
. Here num1[0]
has related arrays num1[0][0]
and num[0][1]
only.
Here we used a for
loop which helps us to calculate num1[i].length
. Here i
is incremented through a loop.
class array
{
static int[][] add(int[][] num1,int[][] num2)
{
int[][] temp = new int[num1.length][num1[0].length];
for(int i = 0; i<temp.length; i++)
{
for(int j = 0; j<temp[i].length; j++)
{
temp[i][j] = num1[i][j]+num2[i][j];
}
}
return temp;
}
public static void main(String args[])
{
/* We can define a two-dimensional array as
1. int[] num[] = {{1,2},{1,2},{1,2},{1,2}}
2. int[][] num = new int[4][2]
num[0][0] = 1;
num[0][1] = 2;
num[1][0] = 1;
num[1][1] = 2;
num[2][0] = 1;
num[2][1] = 2;
num[3][0] = 1;
num[3][1] = 2;
If you don't allocate let's say num[2][1] is
not initialized, and then it is automatically
allocated 0, that is, automatically num[2][1] = 0;
3. Below num1.length gives you rows
4. While num1[0].length gives you number of elements
related to num1[0]. Here num1[0] has related arrays
num1[0][0] and num[0][1] only.
5. Here we used a 'for' loop which helps us to calculate
num1[i].length, and here i is incremented through a loop.
*/
int num1[][] = {{1,2},{1,2},{1,2},{1,2}};
int num2[][] = {{1,2},{1,2},{1,2},{1,2}};
int num3[][] = add(num1,num2);
for(int i = 0; i<num1.length; i++)
{
for(int j = 0; j<num1[j].length; j++)
System.out.println("num3[" + i + "][" + j + "]=" + num3[i][j]);
}
}
}
You can try something like:
var str = "a,d,k";
str.replace(/,/g, "");
Since Java 8, using the streams API:
int[][] copy = Arrays.stream(matrix).map(int[]::clone).toArray(int[][]::new);
Ok for my case it was really simple.
I set to a local IP address at my Ethernet port.
Then having this error. Turns out I did not connect the cable to it, so the IP does not resolve to the IP set in Apache.
Solution was to connect the cable to a switch or router. Then able to start Apache.
Keystore is used by a server to store private keys, and Truststore is used by third party client to store public keys provided by server to access. I have done that in my production application. Below are the steps for generating java certificates for SSL communication:
keytool -genkey -keystore server.keystore -alias mycert -keyalg RSA -keysize 2048 -validity 3950
keytool -selfcert -alias mycert -keystore server.keystore -validity 3950
keytool -export -alias mycert -keystore server.keystore -rfc -file mycert.cer
keytool -importcert -alias mycert -file mycert.cer -keystore truststore
I don't know why you would need this but to do this, you could edit your css file:-
<style type="text/css">
body{
...;
...;
}
</style>
You have just added here and saved it as main.php. You can continue with main.css but it is better as .php since it does not remain a css file after you do that edit
Then edit your HTML file like this. NOTE: Make the include statement inside the tag
<html>
<head>
<title>Sample</title>
<?php inculde('css/main.css');>
</head>
<body>
...
...
</body>
</html>
As @Vlad from Moscow says,
Take into account that value_type
for std::map
is defined the following way:
typedef pair<const Key, T> value_type
This then means that if you wish to replace the keyword auto
with a more explicit type specifier, then you could this;
for ( const pair<const string, int> &p : table ) {
std::cout << p.first << '\t' << p.second << std::endl;
}
Just for understanding what auto
will translate to in this case.
Take a look at Multimap
from the guava-libraries and its implementation - HashMultimap
A collection similar to a Map, but which may associate multiple values with a single key. If you call put(K, V) twice, with the same key but different values, the multimap contains mappings from the key to both values.
Use spread operator and some ES6 here
this.setState({
jasper: {
...this.state.jasper,
name: 'something'
}
})
If you want to append
text or html to span
then you can do it as below.
$('p span#add_here').append('text goes here');
append will add text to span tag at the end.
to replace entire text or html inside of span you can use .text()
or .html()
I had to open Android studio and go through the wizard. Android studio will install the SDK for you.
You can try using max() in subquery, something like this :
SELECT model, date
FROM doc
WHERE date in (SELECT MAX(date) from doc GROUP BY model);
You can do:
var buf = Buffer.from(bufStr, 'utf8');
But this is a bit silly, so another suggestion would be to copy the minimal amount of code out of the called function to allow yourself access to the original buffer. This might be quite easy or fairly difficult depending on the details of that library.
If you haven't already, choose a Jekyll theme in your GitHub Pages settings tab. Apparently this is required even if you're not using Jekyll for your Pages site.
JPG and JPEG stand both for an image format proposed and supported by the Joint Photographic Experts Group. The two terms have the same meaning and are interchangeable.
To read on, check out Difference between JPG and JPEG.
The reason for the different file extensions dates back to the early versions of Windows. The original file extension for the Joint Photographic Expert Group File Format was ‘.jpeg’; however in Windows all files required a three letter file extension. So, the file extension was shortened to ‘.jpg’. However, Macintosh was not limited to three letter file extensions, so Mac users used ‘.jpeg’. Eventually, with upgrades Windows also began to accept ‘.jpeg’. However, many users were already used to ‘.jpg’, so both the three letter file extension and the four letter extension began to be commonly used, and still is.
Today, the most commonly accepted and used form is the ‘.jpg’, as many users were Windows users. Imaging applications, such as Adobe Photoshop, save all JPEG files with a ".jpg" extension on both Mac and Windows, in an attempt to avoid confusion. The Joint Photographic Expert Group File Format can also be saved with the upper-case ‘.JPEG’ and ‘.JPG’ file extensions, which are less common, but also accepted.
If you have removed package using Uninstall-Package utility and deleted the desired package from package directory under solution (and you are still getting error), just open up the *.csproj file in code editor and remove the tag manually. Like for instance, I wanted to get rid of Nuget package Xamarin.Forms.Alias and I removed these lines from *.csproj file.
And finally, don't forget to reload your project once prompted in Visual Studio (after changing project file). I tried it on Visual Studio 2015, but it should work on Visual Studio 2010 and onward too.
Hope this helps.
The existing answers are good but don't cover what to do when a smart pointer is not the (complete) answer to the problem you are trying to solve.
Among other things (explained well in other answers) using a smart pointer is a possible solution to How do we use a abstract class as a function return type? which has been marked as a duplicate of this question. However, the first question to ask if tempted to specify an abstract (or in fact, any) base class as a return type in C++ is "what do you really mean?". There is a good discussion (with further references) of idiomatic object oriented programming in C++ (and how this is different to other languages) in the documentation of the boost pointer container library. In summary, in C++ you have to think about ownership. Which smart pointers help you with, but are not the only solution, or always a complete solution (they don't give you polymorphic copy) and are not always a solution you want to expose in your interface (and a function return sounds an awful lot like an interface). It might be sufficient to return a reference, for example. But in all of these cases (smart pointer, pointer container or simply returning a reference) you have changed the return from a value to some form of reference. If you really needed copy you may need to add more boilerplate "idiom" or move beyond idiomatic (or otherwise) OOP in C++ to more generic polymorphism using libraries like Adobe Poly or Boost.TypeErasure.
I've built systems before that use the following:
In the systems I've built admins were under instruction to react to ERRORs. On the other hand we would watch for WARNINGS and determine for each case whether any system changes, reconfigurations etc. were required.
New Operator for lambda expression added in java 8
Lambda expression is the short way of method writing.
It is indirectly used to implement functional interface
Primary Syntax : (parameters) -> { statements; }
There are some basic rules for effective lambda expressions writting which you should konw.
API is specifications on how to do something, an interface, such as "The railroad tracks are four feet apart, and the metal bar is 1 inch wide" Now that you have the API you can now build a train that will fit on those railroad tracks if you want to go anywhere. API is just information on how to build your code, it doesn't do anything.
SDK is some package of actual tools that already worried about the specifications. "Here's a train, some coal, and a maintenance man. Use it to go from place to place" With the SDK you don't worry about specifics. An SDK is actual code, it can be used by itself to do something, but of course, the train won't start up spontaneously, you still have to get a conductor to control the train.
SDKs also have their own APIs. "If you want to power the train put coal in it", "Pull the blue lever to move the train.", "If the train starts acting funny, call the maintenance man" etc.
What you do here is called a JOIN
(although you do it implicitly because you select from multiple tables). This means, if you didn't put any conditions in your WHERE clause, you had all combinations of those tables. Only with your condition you restrict your join to those rows where the drink id matches.
But there are still X multiple rows in the result for every drink, if there are X photos with this particular drinks_id. Your statement doesn't restrict which photo(s) you want to have!
If you only want one row per drink, you have to tell SQL what you want to do if there are multiple rows with a particular drinks_id. For this you need grouping and an aggregate function. You tell SQL which entries you want to group together (for example all equal drinks_ids) and in the SELECT, you have to tell which of the distinct entries for each grouped result row should be taken. For numbers, this can be average, minimum, maximum (to name some).
In your case, I can't see the sense to query the photos for drinks if you only want one row. You probably thought you could have an array of photos in your result for each drink, but SQL can't do this. If you only want any photo and you don't care which you'll get, just group by the drinks_id (in order to get only one row per drink):
SELECT name, price, photo
FROM drinks, drinks_photos
WHERE drinks.id = drinks_id
GROUP BY drinks_id
name price photo
fanta 5 ./images/fanta-1.jpg
dew 4 ./images/dew-1.jpg
In MySQL, we also have GROUP_CONCAT, if you want the file names to be concatenated to one single string:
SELECT name, price, GROUP_CONCAT(photo, ',')
FROM drinks, drinks_photos
WHERE drinks.id = drinks_id
GROUP BY drinks_id
name price photo
fanta 5 ./images/fanta-1.jpg,./images/fanta-2.jpg,./images/fanta-3.jpg
dew 4 ./images/dew-1.jpg,./images/dew-2.jpg
However, this can get dangerous if you have ,
within the field values, since most likely you want to split this again on the client side. It is also not a standard SQL aggregate function.
Can anyone give me a brief explanation...
Sure.
ORM stands for "Object to Relational Mapping" where
The Object part is the one you use with your programming language ( python in this case )
The Relational part is a Relational Database Manager System ( A database that is ) there are other types of databases but the most popular is relational ( you know tables, columns, pk fk etc eg Oracle MySQL, MS-SQL )
And finally the Mapping part is where you do a bridge between your objects and your tables.
In applications where you don't use a ORM framework you do this by hand. Using an ORM framework would allow you do reduce the boilerplate needed to create the solution.
So let's say you have this object.
class Employee:
def __init__( self, name ):
self.__name = name
def getName( self ):
return self.__name
#etc.
and the table
create table employee(
name varcar(10),
-- etc
)
Using an ORM framework would allow you to map that object with a db record automagically and write something like:
emp = Employee("Ryan")
orm.save( emp )
And have the employee inserted into the DB.
Oops it was not that brief but I hope it is simple enough to catch other articles you read.
The value you have passed as the file descriptor is not valid. It is either negative or does not represent a currently open file or socket.
So you have either closed the socket before calling write()
or you have corrupted the value of 'sockfd' somewhere in your code.
It would be useful to trace all calls to close()
, and the value of 'sockfd' prior to the write()
calls.
Your technique of only printing error messages in debug mode seems to me complete madness, and in any case calling another function between a system call and perror()
is invalid, as it may disturb the value of errno
. Indeed it may have done so in this case, and the real underlying error may be different.
In case someone is looking for a universal event handler the following code can be used more or less (assuming that name property is set for every input):
this.handleInputChange = (e) => {
item[e.target.name] = e.target.type === "checkbox" ? e.target.checked : e.target.value;
}
and then go to control panel > system and security > windows firewall and turn windows firewall off
now you can access your wamp server from another computer over local network by the network IP of computer which have wamp server installed like http://192.168.2.34/mysite
Your project is mostly likely targetting .NET Framework 4 Client Profile. Check the application tab in your project properties.
This question has a good answer on the different versions: Target framework, what does ".NET Framework ... Client Profile" mean?
You can find every content type here: http://www.iana.org/assignments/media-types/media-types.xhtml
The most common type are:
Type application
application/java-archive
application/EDI-X12
application/EDIFACT
application/javascript
application/octet-stream
application/ogg
application/pdf
application/xhtml+xml
application/x-shockwave-flash
application/json
application/ld+json
application/xml
application/zip
application/x-www-form-urlencoded
Type audio
audio/mpeg
audio/x-ms-wma
audio/vnd.rn-realaudio
audio/x-wav
Type image
image/gif
image/jpeg
image/png
image/tiff
image/vnd.microsoft.icon
image/x-icon
image/vnd.djvu
image/svg+xml
Type multipart
multipart/mixed
multipart/alternative
multipart/related (using by MHTML (HTML mail).)
multipart/form-data
Type text
text/css
text/csv
text/html
text/javascript (obsolete)
text/plain
text/xml
Type video
video/mpeg
video/mp4
video/quicktime
video/x-ms-wmv
video/x-msvideo
video/x-flv
video/webm
Type vnd :
application/vnd.android.package-archive
application/vnd.oasis.opendocument.text
application/vnd.oasis.opendocument.spreadsheet
application/vnd.oasis.opendocument.presentation
application/vnd.oasis.opendocument.graphics
application/vnd.ms-excel
application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
application/vnd.ms-powerpoint
application/vnd.openxmlformats-officedocument.presentationml.presentation
application/msword
application/vnd.openxmlformats-officedocument.wordprocessingml.document
application/vnd.mozilla.xul+xml
$( 'input[name="testGroup"]:radio' ).on('change', function(e) {_x000D_
console.log(e.type);_x000D_
return false;_x000D_
});
_x000D_
This syntax is a little more flexible to handle events. Not only can you observe "changes", but also other types of events can be controlled here too by using one single event handler. You can do this by passing the list of events as arguments to the first parameter. See jQuery On
Secondly, .change() is a shortcut for .on( "change", handler ). See here. I prefer using .on() rather than .change because I have more control over the events.
Lastly, I'm simply showing an alternative syntax to attach the event to the element.
ES6:
let after = 'something after';
let text = `before text ${after}`;
You're mixing notations. It should be:
<img src="folder/file.jpg" width="200" height="200">
(note, no px). Or:
<img src="folder/file.jpg" style="width: 200px; height: 200px;">
(using the style attribute) The style attribute could be replaced with the following CSS:
#mydiv img {
width: 200px;
height: 200px;
}
or
#mydiv img {
width: 100%;
height: 100%;
}
select count(*) from(select count(SID) from Test where Date = '2012-12-10' group by SID)
select count(*) from(select count(SID) from Test where Date = '2012-12-10' group by SID)
should works
you can also use blank columns to give spaces on left
like
<div class="row">
<div class="col-md-8"></div> <!-- blank space increase or decrease it by column # -->
<div class="col-md-4">
<button id="saveedit" name="saveedit" class="btn btn-success">Save</button>
</div>
</div>
Demo :: Jsfiddle demo
Private constructor means a user cannot directly instantiate a class. Instead, you can create objects using something like the Named Constructor Idiom, where you have static
class functions that can create and return instances of a class.
The Named Constructor Idiom is for more intuitive usage of a class. The example provided at the C++ FAQ is for a class that can be used to represent multiple coordinate systems.
This is pulled directly from the link. It is a class representing points in different coordinate systems, but it can used to represent both Rectangular and Polar coordinate points, so to make it more intuitive for the user, different functions are used to represent what coordinate system the returned Point
represents.
#include <cmath> // To get std::sin() and std::cos()
class Point {
public:
static Point rectangular(float x, float y); // Rectangular coord's
static Point polar(float radius, float angle); // Polar coordinates
// These static methods are the so-called "named constructors"
...
private:
Point(float x, float y); // Rectangular coordinates
float x_, y_;
};
inline Point::Point(float x, float y)
: x_(x), y_(y) { }
inline Point Point::rectangular(float x, float y)
{ return Point(x, y); }
inline Point Point::polar(float radius, float angle)
{ return Point(radius*std::cos(angle), radius*std::sin(angle)); }
There have been a lot of other responses that also fit the spirit of why private constructors are ever used in C++ (Singleton pattern among them).
Another thing you can do with it is to prevent inheritance of your class, since derived classes won't be able to access your class' constructor. Of course, in this situation, you still need a function that creates instances of the class.
x ~= 0 or 1
is the same as ((x ~= 0) or 1)
x ~=(0 or 1)
is the same as (x ~= 0)
.
try something like this instead.
function isNot0Or1(x)
return (x ~= 0 and x ~= 1)
end
print( isNot0Or1(-1) == true )
print( isNot0Or1(0) == false )
print( isNot0Or1(1) == false )
As of Bootstrap 3, you can use Panel classes:
<div class="panel panel-default">Surrounded by border</div>
In Bootstrap 4, you can use Border classes:
<div class="border border-secondary">Surrounded by border</div>
To add to tacaswell's answer, the colorbar()
function has an optional cax
input you can use to pass an axis on which the colorbar should be drawn. If you are using that input, you can directly set a label using that axis.
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
fig, ax = plt.subplots()
heatmap = ax.imshow(data)
divider = make_axes_locatable(ax)
cax = divider.append_axes('bottom', size='10%', pad=0.6)
cb = fig.colorbar(heatmap, cax=cax, orientation='horizontal')
cax.set_xlabel('data label') # cax == cb.ax
For SQL Server 2012 and up , with leading zeroes:
SELECT FORMAT(GETDATE(),'MM')
without:
SELECT MONTH(GETDATE())
As another answer already said, call select myfunc(:y) from dual;
, but you might find declaring and setting a variable in sqlplus a little tricky:
sql> var y number
sql> begin
2 select 7 into :y from dual;
3 end;
4 /
PL/SQL procedure successfully completed.
sql> print :y
Y
----------
7
sql> select myfunc(:y) from dual;
It might be late but I want to add few things.
In Android Studio Version 4.0.1, and Gradle Version 6.1.1, the windowSoftInputMode
will not work as expected if you are adding the following flags in your Activity :
getWindow().setFlags(
WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,
WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS
);
After wasting lot of time, I have found that hack. In order for adjustResize
or AdjustPan
or any attribute of windowSoftInputMode
to work properly, you need to remove that from your activity.
I think the accepted answer is great, but it seems many people have failed to grasp some fundamental points.
First, Scala's for
comprehensions are equivalent to Haskell's do
notation, and it is nothing more than a syntactic sugar for composition of multiple monadic operations. As this statement will most likely not help anyone who needs help, let's try again… :-)
Scala's for
comprehensions is syntactic sugar for composition of multiple operations with map, flatMap
and filter
. Or foreach
. Scala actually translates a for
-expression into calls to those methods, so any class providing them, or a subset of them, can be used with for comprehensions.
First, let's talk about the translations. There are very simple rules:
This
for(x <- c1; y <- c2; z <-c3) {...}
is translated into
c1.foreach(x => c2.foreach(y => c3.foreach(z => {...})))
This
for(x <- c1; y <- c2; z <- c3) yield {...}
is translated into
c1.flatMap(x => c2.flatMap(y => c3.map(z => {...})))
This
for(x <- c; if cond) yield {...}
is translated on Scala 2.7 into
c.filter(x => cond).map(x => {...})
or, on Scala 2.8, into
c.withFilter(x => cond).map(x => {...})
with a fallback into the former if method withFilter
is not available but filter
is. Please see the section below for more information on this.
This
for(x <- c; y = ...) yield {...}
is translated into
c.map(x => (x, ...)).map((x,y) => {...})
When you look at very simple for
comprehensions, the map
/foreach
alternatives look, indeed, better. Once you start composing them, though, you can easily get lost in parenthesis and nesting levels. When that happens, for
comprehensions are usually much clearer.
I'll show one simple example, and intentionally omit any explanation. You can decide which syntax was easier to understand.
l.flatMap(sl => sl.filter(el => el > 0).map(el => el.toString.length))
or
for {
sl <- l
el <- sl
if el > 0
} yield el.toString.length
withFilter
Scala 2.8 introduced a method called withFilter
, whose main difference is that, instead of returning a new, filtered, collection, it filters on-demand. The filter
method has its behavior defined based on the strictness of the collection. To understand this better, let's take a look at some Scala 2.7 with List
(strict) and Stream
(non-strict):
scala> var found = false
found: Boolean = false
scala> List.range(1,10).filter(_ % 2 == 1 && !found).foreach(x => if (x == 5) found = true else println(x))
1
3
7
9
scala> found = false
found: Boolean = false
scala> Stream.range(1,10).filter(_ % 2 == 1 && !found).foreach(x => if (x == 5) found = true else println(x))
1
3
The difference happens because filter
is immediately applied with List
, returning a list of odds -- since found
is false
. Only then foreach
is executed, but, by this time, changing found
is meaningless, as filter
has already executed.
In the case of Stream
, the condition is not immediatelly applied. Instead, as each element is requested by foreach
, filter
tests the condition, which enables foreach
to influence it through found
. Just to make it clear, here is the equivalent for-comprehension code:
for (x <- List.range(1, 10); if x % 2 == 1 && !found)
if (x == 5) found = true else println(x)
for (x <- Stream.range(1, 10); if x % 2 == 1 && !found)
if (x == 5) found = true else println(x)
This caused many problems, because people expected the if
to be considered on-demand, instead of being applied to the whole collection beforehand.
Scala 2.8 introduced withFilter
, which is always non-strict, no matter the strictness of the collection. The following example shows List
with both methods on Scala 2.8:
scala> var found = false
found: Boolean = false
scala> List.range(1,10).filter(_ % 2 == 1 && !found).foreach(x => if (x == 5) found = true else println(x))
1
3
7
9
scala> found = false
found: Boolean = false
scala> List.range(1,10).withFilter(_ % 2 == 1 && !found).foreach(x => if (x == 5) found = true else println(x))
1
3
This produces the result most people expect, without changing how filter
behaves. As a side note, Range
was changed from non-strict to strict between Scala 2.7 and Scala 2.8.
In general,
variable=$(command)
or
variable=`command`
The latter one is the old syntax, prefer $(command)
.
Note: variable = ....
means execute the command variable
with the first argument =
, the second ....
With Jenkins CLI you do not have to reload everything - you just can load the job (update-job command). You can't use tokens with CLI, AFAIK - you have to use password or password file.
Token name for user can be obtained via http://<jenkins-server>/user/<username>/configure
- push on 'Show API token' button.
Here's a link on how to use API tokens (it uses wget
, but curl
is very similar).
My stringdata
is coming from PHP file but still, I indicate here in var
. When i directly take my json into obj
it will nothing show thats why i put my json file as
var obj=JSON.parse(stringdata);
so after that i get message
obj and show in alert box then I get data
which is json array and store in one varible ArrObj
then i read first object of that array with key value like this ArrObj[0].id
var stringdata={
"success": true,
"message": "working",
"data": [{
"id": 1,
"name": "foo"
}]
};
var obj=JSON.parse(stringdata);
var key = "message";
alert(obj[key]);
var keyobj = "data";
var ArrObj =obj[keyobj];
alert(ArrObj[0].id);
You may want to use:
SELECT Name, 'Unpaid' AS Status FROM table;
The SELECT
clause syntax, as defined in MSDN: SELECT Clause (Transact-SQL), is as follows:
SELECT [ ALL | DISTINCT ]
[ TOP ( expression ) [ PERCENT ] [ WITH TIES ] ]
<select_list>
Where the expression
can be a constant, function, any combination of column names, constants, and functions connected by an operator or operators, or a subquery.
When you add floating point numbers together, there's often a little bit of error. Would a range(0.0, 2.2, 1.1)
return [0.0, 1.1]
or [0.0, 1.1, 2.199999999]
? There's no way to be certain without rigorous analysis.
The code you posted is an OK work-around if you really need this. Just be aware of the possible shortcomings.
(This answer might seem needlessly complicated, but it’s easily extensible and robust regarding whitespace and special characters, as far as I know.)
You can feed data right through the standard input of the ssh
command and read
that from the remote location.
In the following example,
ssh
a null-terminated line giving the name and value of the variable.shh
command itself, we loop through these lines to initialise the required variables.# Initialize examples of variables.
# The first one even contains whitespace and a newline.
readonly FOO=$'apjlljs ailsi \n ajlls\t éjij'
readonly BAR=ygnàgyààynygbjrbjrb
# Make a list of what you want to pass through SSH.
# (The “unset” is just in case someone exported
# an associative array with this name.)
unset -v VAR_NAMES
readonly VAR_NAMES=(
FOO
BAR
)
for name in "${VAR_NAMES[@]}"
do
printf '%s %s\0' "$name" "${!name}"
done | ssh [email protected] '
while read -rd '"''"' name value
do
export "$name"="$value"
done
# Check
printf "FOO = [%q]; BAR = [%q]\n" "$FOO" "$BAR"
'
Output:
FOO = [$'apjlljs ailsi \n ajlls\t éjij']; BAR = [ygnàgyààynygbjrbjrb]
If you don’t need to export
those, you should be able to use declare
instead of export
.
A really simplified version (if you don’t need the extensibility, have a single variable to process, etc.) would look like:
$ ssh [email protected] 'read foo' <<< "$foo"
A browser will only open a tab/popup without the popup blocker warning if the command to open the tab/popup comes from a trusted event. That means the user has to actively click somewhere to open a popup.
In your case, the user performs a click so you have the trusted event. You do lose that trusted context, however, by performing the Ajax request. Your success handler does not have that event anymore. The only way to circumvent this is to perform a synchronous Ajax request which will block your browser while it runs, but will preserve the event context.
In jQuery this should do the trick:
$.ajax({
url: 'http://yourserver/',
data: 'your image',
success: function(){window.open(someUrl);},
async: false
});
Here is your answer: Open new tab without popup blocker after ajax call on user click
In my case, I have Eclipse Maven project. I had the same issue and I posted detailed explanation of the issue and answer here Eclipse Maven - Code Completion fails "This compilation unit is not on the build path of a Java project" and "Failed to Download Index" Error
The rest of the sentence is:
where only structure (e.g., elements, comments, processing instructions, CDATA sections, and entity references) separates Text nodes, i.e., there are neither adjacent Text nodes nor empty Text nodes.
This basically means that the following XML element
<foo>hello
wor
ld</foo>
could be represented like this in a denormalized node:
Element foo
Text node: ""
Text node: "Hello "
Text node: "wor"
Text node: "ld"
When normalized, the node will look like this
Element foo
Text node: "Hello world"
And the same goes for attributes: <foo bar="Hello world"/>
, comments, etc.
Requests to /** are evaluated to static locations configured in resourceProperties.
adding the following on application.properties, might be the only thing you need to do...
spring.resources.static-locations=classpath:/myresources/
this will overwrite default static locations, wich is:
ResourceProperties.CLASSPATH_RESOURCE_LOCATIONS = { "classpath:/META-INF/resources/",
"classpath:/resources/", "classpath:/static/", "classpath:/public/" };
You might not want to do that and just make sure your resources end up in one of those default folders.
Performing a request: If I would have example.html stored on /public/example.html Then I can acces it like this:
<host>/<context-path?if you have one>/example.html
If I would want another uri like <host>/<context-path>/magico/*
for files in classpath:/magicofiles/* you need a bit more config
@Configuration
class MyConfigClass implements WebMvcConfigurer
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/magico/**").addResourceLocations("/magicofiles/");
}
adb reboot
should not reboot your linux box.
But in any case, you can redirect the command to a specific adb device using adb -s <device_id> command
, where
Device ID can be obtained from the command adb devices
command in this case is reboot
float: right
to.. float the second column to the.. right.overflow: hidden
to clear the floats so that the background color I just put in will be visible.#wrapper{
background:#000;
overflow: hidden
}
#c1 {
float:left;
background:red;
}
#c2 {
background:green;
float: right
}
With the fs-extra package you can do this with a one-liner:
const fs = require('fs-extra');
const dir = '/tmp/this/path/does/not/exist';
fs.ensureDirSync(dir);
Adding to what @Shog9 posted, you can also restrict dates individually in the beforeShowDay: callback function.
You supply a function that takes a date and returns a boolean array:
"$(".selector").datepicker({ beforeShowDay: nationalDays})
natDays = [[1, 26, 'au'], [2, 6, 'nz'], [3, 17, 'ie'], [4, 27, 'za'],
[5, 25, 'ar'], [6, 6, 'se'], [7, 4, 'us'], [8, 17, 'id'], [9, 7,
'br'], [10, 1, 'cn'], [11, 22, 'lb'], [12, 12, 'ke']];
function nationalDays(date) {
for (i = 0; i < natDays.length; i++) {
if (date.getMonth() == natDays[i][0] - 1 && date.getDate() ==
natDays[i][1]) {
return [false, natDays[i][2] + '_day'];
}
}
return [true, ''];
}
Oftentimes in Ruby, you don't actually care what the object's class is, per se, you just care that it responds to a certain method. This is known as Duck Typing and you'll see it in all sorts of Ruby codebases.
So in many (if not most) cases, its best to use Duck Typing using #respond_to?(method)
:
object.respond_to?(:to_i)
I get this exception often while running on my development machine, especially after I make a code change, rebuild the code, then execute an associated web page(s). However, the problem goes away for me if I bump up the CommandTimeout parameter to 120 seconds or more (e.g., set context.Database.CommandTimeout = 120 before the LINQ statement). While this was originally asked 3 years ago, it may help someone looking for an answer. My theory is VisualStudio takes time to convert the built binary libraries to machine code, and times out when attempting to connect to SQL Server following that just-in-time compile.
If you tried all the other answers in this question and you:
...you may have separate versions of the NuGet packages DLL in your projects' References, as the reference created by Intellisense/ReSharper will be a "normal" reference, and not a NuGet reference as expected, so the NuGet update process won't find or update it!
To fix this, remove the reference in Project A, then use NuGet to install it, and make sure the NuGet packages in all projects are the same version. (as explain in this answer)
This issue can come up whenever ReSharper/Intellisense suggests to add a reference to your project. It can be much more deeply convoluted than the example above, with multiple interweaving projects and dependencies making it hard to track down. If the reference being suggested by ReSharper/Intellisense is actually from a NuGet package, use NuGet to install it.
One option of compiling for Windows in Linux is via mingw. I found a very helpful tutorial here.
To install mingw32 on Debian based systems, run the following command:
sudo apt-get install mingw32
To compile your code, you can use something like:
i586-mingw32msvc-g++ -o myApp.exe myApp.cpp
You'll sometimes want to test the new Windows application directly in Linux. You can use wine for that, although you should always keep in mind that wine could have bugs. This means that you might not be sure that a bug is in wine, your program, or both, so only use wine for general testing.
To install wine, run:
sudo apt-get install wine
For Apps converted from older versions (Angular v2 - v5): HttpModule is now deprecated and you need to replace it with HttpClientModule or else you will get the error too.
import { HttpModule } from '@angular/http';
with the new HttpClientModule import { HttpClientModule} from "@angular/common/http";
Note: Be sure to then update the modules imports[]
array by removing the old HttpModule
and replacing it with the new HttpClientModule
.import { Http } from '@angular/http';
with the new HttpClient import { HttpClient } from '@angular/common/http';
Update how you handle your Http response. For example - If you have code that looks like this
http.get('people.json').subscribe((res:Response) => this.people = res.json());
The above code example will result in an error. We no longer need to parse the response, because it already comes back as JSON in the config object.
The subscription callback copies the data fields into the component's config object, which is data-bound in the component template for display.
For more information please see the - Angular HttpClientModule - Official Documentation
I still prefer the method in one line
new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Calendar.getInstance().getTime())
// Get a notification builder that's compatible with platform versions
// >= 4
NotificationCompat.Builder builder = new NotificationCompat.Builder(
this);
builder.setSound(soundUri);
builder.setAutoCancel(true);
this works if you are using a notification builder...
Java 6 has a default embedded http server.
By the way, if you plan to have a rest web service, here is a simple example using jersey.
You should use the OpenFileDialog class like this
Dim fd As OpenFileDialog = New OpenFileDialog()
Dim strFileName As String
fd.Title = "Open File Dialog"
fd.InitialDirectory = "C:\"
fd.Filter = "All files (*.*)|*.*|All files (*.*)|*.*"
fd.FilterIndex = 2
fd.RestoreDirectory = True
If fd.ShowDialog() = DialogResult.OK Then
strFileName = fd.FileName
End If
Then you can use the File class.
This should work
<option *ngFor="let title of titleArray"
[value]="title.Value"
[attr.selected]="passenger.Title==title.Text ? true : null">
{{title.Text}}
</option>
I'm not sure the attr.
part is necessary.
While editing the code (because mild OCD), I noticed that weather is also a list. You should probably consider something like
echo $data[0]->weather[0]->weatherIconUrl[0]->value;
to make sure you are using the weatherIconUrl for the correct date instance.
Fill
is command always return how many records inserted into dataset.
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(sqlString, sqlConn);
var count = da.Fill(ds);
if(count > 0)
{
Console.Write("It is not Empty");
}
Yes, let's use Select
as an example
sample code: Columns("A").select
How to loop through Columns:
Method 1: (You can use index to replace the Excel Address)
For i = 1 to 100
Columns(i).Select
next i
Method 2: (Using the address)
For i = 1 To 100
Columns(Columns(i).Address).Select
Next i
EDIT: Strip the Column for OP
columnString = Replace(Split(Columns(27).Address, ":")(0), "$", "")
e.g. you want to get the 27th Column --> AA, you can get it this way
I had exactly the same issue, after moving from old go version (installed from old PPA) to newer (1.2.1) default packages in ubuntu 14.04.
The first step was to purge existing go:
sudo apt-get purge golang*
Which outputs following warnings:
dpkg: warning: while removing golang-go, directory '/usr/lib/go/src' not empty so not removed
dpkg: warning: while removing golang-go.tools, directory '/usr/lib/go' not empty so not removed
It looks like removing go leaves some files behind, which in turn can confuse newer install. More precisely, installation itself will complete fine, but afterwards any go command, like "go get something" gives those "unrecognized import path" errors.
All I had to do was to remove those dirs first, reinstall golang, and all works like a charm (assuming you also set GOPATH)
# careful!
sudo rm -rf /usr/lib/go /usr/lib/go/src
sudo apt-get install golang-go golang-go.tools
Recursive traverse object or array with array or objects elements:
function traverse(&$objOrArray)
{
foreach ($objOrArray as $key => &$value)
{
if (is_array($value) || is_object($value))
{
traverse($value);
}
else
{
// DO SOMETHING
}
}
}
.hide()
stores the previous display
property just before setting it to none
, so if it wasn't the standard display
property for the element you're a bit safer, .show()
will use that stored property as what to go back to. So...it does some extra work, but unless you're doing tons of elements, the speed difference should be negligible.
I want to point out that in PHP there is no such thing like empty object in sense:
$obj = new stdClass();
var_dump(empty($obj)); // bool(false)
but of course $obj will be empty.
On other hand empty array mean empty in both cases
$arr = array();
var_dump(empty($arr));
Quote from changelog function empty
Objects with no properties are no longer considered empty.
Try using below code:
<button title="button title" class="action primary tocart" onclick=" window.open('http://www.google.com', '_blank'); return false;">Google</button>
Here, the window.open
with _blank
as second argument of window.open
function will open the link in new tab.
And by the use of return false
we can remove/cancel the default behavior of the button like submit.
For more detail and live example, click here
We also had this problem when upgrading our system to Revive. After turning of GZIP we found the problem still persisted. Upon further investigation we found the file permissions where not correct after the upgrade. A simple recursive chmod did the trick.
I shared two solutions depending on your needs:
<style type="text/css" ref="stylesheet">
.border-inside-box {
border: 1px solid black;
}
.border-inside-box-v1 {
outline: 1px solid black; /* 'border-radius' not available */
}
.border-outside-box-v2 {
box-shadow: 0 0 0 1px black; /* 'border-style' not available (dashed, solid, etc) */
}
</style>
As a variation of @tangens answer: if you can't wait for the garbage collector to clean up your thread, cancel the timer at the end of your run method.
Timer t = new java.util.Timer();
t.schedule(
new java.util.TimerTask() {
@Override
public void run() {
// your code here
// close the thread
t.cancel();
}
},
5000
);
The current documentation has a good explanation of what .NET Core is, areas to use and so on. The following characteristics best define .NET Core:
Flexible deployment: Can be included in your app or installed side-by-side user- or machine-wide.
Cross-platform: Runs on Windows, macOS and Linux; can be ported to other OSes. The supported operating systems (OSes), CPUs and application scenarios will grow over time, provided by Microsoft, other companies, and individuals.
Command-line tools: All product scenarios can be exercised at the command-line.
Compatible: .NET Core is compatible with .NET Framework, Xamarin and Mono, via the .NET Standard Library.
Open source: The .NET Core platform is open source, using MIT and Apache 2 licenses. Documentation is licensed under CC-BY. .NET Core is a .NET Foundation project.
Supported by Microsoft: .NET Core is supported by Microsoft, per .NET Core Support
And here is what .NET Core includes:
A .NET runtime, which provides a type system, assembly loading, a garbage collector, native interoperability and other basic services.
A set of framework libraries, which provide primitive data types, application composition types and fundamental utilities.
A set of SDK tools and language compilers that enable the base developer experience, available in the .NET Core SDK.
The 'dotnet' application host, which is used to launch .NET Core applications. It selects the runtime and hosts the runtime, provides an assembly loading policy and launches the app. The same host is also used to launch SDK tools in much the same way.
Old question but it kind of pointed me in the right direction. The method I went for was to add the disabled class to the li and then added the following code to my Javascript file.
$('.nav-tabs li.disabled > a[data-toggle=tab]').on('click', function(e) {
e.stopImmediatePropagation();
});
This will disable any link where the li has a class of disabled. Kind of similar to totas's answer but it won't run the if every time a user clicks any tab link and it doesn't use return false.
Hopefully it'll be useful to someone!
The biggest problem that i have after enabling the Push Notification
from Capabilities
and remaking all the certificates is that the Target name and the folder name where was stored the project was composed from 2 strings separated by space. After removing the space all worked just fine!
Try this, to make sure you configured CORS correctly:
[EnableCors(origins: "*", headers: "*", methods: "*")]
Still not working? Check HTTP headers presence.
If I have open a package in BIDS ("Business Intelligence Development Studio", the tool you use to design the packages), and do not select any item in it, I have a "Properties" pane in the bottom right containing - among others, the MaximumErrorCount
property. If you do not see it, maybe it is minimized and you have to open it (have a look at tabs in the right).
If you cannot find it this way, try the menu: View/Properties Window.
Or try the F4 key.
This is the exact answer. Try this code:
If String.IsNullOrEmpty(editTransactionRow.pay_id.ToString()) = False Then
stTransactionPaymentID = editTransactionRow.pay_id 'Check for null value
End If
Just call mkdir C:\VTS
no matter what. It will simply report that the subdirectory already exists.
Edit: As others have noted, this does set the %ERRORLEVEL% if the folder already exists. If your batch (or any processes calling it) doesn't care about the error level, this method works nicely. Since the question made no mention of avoiding the error level, this answer is perfectly valid. It fulfills the needs of creating the folder if it doesn't exist, and it doesn't overwrite the contents of an existing folder. Otherwise follow Martin Schapendonk's answer.
This also happens when you use development docker compose like the below, in production. You don't want to be building images in production as that breaks the ideology of containers. We should be deploying images:
web:
build: .
command: python manage.py runserver 0.0.0.0:8000
volumes:
- .:/code
ports:
- "8000:8000"
Change that to use the built image:
web:
command: /bin/bash run.sh
image: registry.voxcloud.co.za:9000/dyndns_api_web:0.1
ports:
- "8000:8000"
Yes, 4,2 means "4 digits total, 2 of which are after the decimal place". That translates to a number in the format of 00.00
. Beyond that, you'll have to show us your SQL query. PHP won't translate 3.80 into 99.99 without good reason. Perhaps you've misaligned your fields/values in the query and are trying to insert a larger number that belongs in another field.
First, we are going to create a Windows Service that runs under the System account. This service will be responsible for spawning an interactive process within the currently active User’s Session. This newly created process will display a UI and run with full admin rights. When the first User logs on to the computer, this service will be started and will be running in Session0; however the process that this service spawns will be running on the desktop of the currently logged on User. We will refer to this service as the LoaderService.
Next, the winlogon.exe process is responsible for managing User login and logout procedures. We know that every User who logs on to the computer will have a unique Session ID and a corresponding winlogon.exe process associated with their Session. Now, we mentioned above, the LoaderService runs under the System account. We also confirmed that each winlogon.exe process on the computer runs under the System account. Because the System account is the owner of both the LoaderService and the winlogon.exe processes, our LoaderService can copy the access token (and Session ID) of the winlogon.exe process and then call the Win32 API function CreateProcessAsUser to launch a process into the currently active Session of the logged on User. Since the Session ID located within the access token of the copied winlogon.exe process is greater than 0, we can launch an interactive process using that token.
Try this one. Subverting Vista UAC in Both 32 and 64 bit Architectures
From the C99 standard, 6.7(5):
A declaration specifies the interpretation and attributes of a set of identifiers. A definition of an identifier is a declaration for that identifier that:
From the C++ standard, 3.1(2):
A declaration is a definition unless it declares a function without specifying the function's body, it contains the extern specifier or a linkage-specification and neither an initializer nor a function-body, it declares a static data member in a class declaration, it is a class name declaration, or it is a typedef declaration, a using-declaration, or a using-directive.
Then there are some examples.
So interestingly (or not, but I'm slightly surprised by it), typedef int myint;
is a definition in C99, but only a declaration in C++.
In Android Studio resolved it by
ISO-8859-1
UTF-8
and the same case to Default encoding for properties files.my quick answer with basic java arithmetic calculation is this:
First consider the following values:
1 Minute = 60 Seconds
1 Hour = 3600 Seconds ( 60 * 60 )
1 Day = 86400 Second ( 24 * 3600 )
the code snippet is as follows:
int input=500000;
int numberOfDays;
int numberOfHours;
int numberOfMinutes;
int numberOfSeconds;
numberOfDays = input / 86400;
numberOfHours = (input % 86400 ) / 3600 ;
numberOfMinutes = ((input % 86400 ) % 3600 ) / 60
numberOfSeconds = ((input % 86400 ) % 3600 ) % 60 ;
I hope to be helpful to you.
Here is how I transitioned from UIWebView to WKWebView.
Note: There is no property like UIWebView that you can drag onto your storyboard, you have to do it programatically.
Make sure you import WebKit/WebKit.h into your header file.
This is my header file:
#import <WebKit/WebKit.h>
@interface ViewController : UIViewController
@property(strong,nonatomic) WKWebView *webView;
@property (strong, nonatomic) NSString *productURL;
@end
Here is my implementation file:
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.productURL = @"http://www.URL YOU WANT TO VIEW GOES HERE";
NSURL *url = [NSURL URLWithString:self.productURL];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
_webView = [[WKWebView alloc] initWithFrame:self.view.frame];
[_webView loadRequest:request];
_webView.frame = CGRectMake(self.view.frame.origin.x,self.view.frame.origin.y, self.view.frame.size.width, self.view.frame.size.height);
[self.view addSubview:_webView];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
Same error occurs in localhost, i'm just changing the mysql port (8080 into localhost mysql port 5506). it works for me.
Basically you want to join two tables together where their QID columns are both not null, correct? However, you aren't enforcing any other conditions, such as that the two QID values (which seems strange to me, but ok). Something as simple as the following (tested in MySQL) seems to do what you want:
SELECT * FROM `Y` INNER JOIN `X` ON (`Y`.`QID` IS NOT NULL AND `X`.`QID` IS NOT NULL);
This gives you every non-null row in Y joined to every non-null row in X.
Update: Rico says he also wants the rows with NULL values, why not just:
SELECT * FROM `Y` INNER JOIN `X`;
What is wrong with List.Find ??
I think we need more information on what you've done, and why it fails, before we can provide truly helpful answers.
Other useful registers:
"*
or "+
- the contents of the system clipboard
"/
- last search command
":
- last command-line command.
Note with vim macros, you can edit them, since they are just a list of the keystrokes used when recording the macro. So you can write to a text file the macro (using "ap
to write macro a) and edit them, and load them into a register with "ay$
. Nice way of storing useful macros.
Focusing on one of the accepted answer's jQuery solutions, $.getScript()
is an .ajax()
request in disguise. It allows to execute other function on success by adding a second parameter:
$.getScript(url, function() {console.log('loaded script!')})
Or on the request's handlers themselves, i.e. success (.done()
- script was loaded) or failure (.fail()
):
$.getScript(_x000D_
"https://code.jquery.com/color/jquery.color.js",_x000D_
() => console.log('loaded script!')_x000D_
).done((script,textStatus ) => {_x000D_
console.log( textStatus );_x000D_
$(".block").animate({backgroundColor: "green"}, 1000);_x000D_
}).fail(( jqxhr, settings, exception ) => {_x000D_
console.log(exception + ': ' + jqxhr.status);_x000D_
}_x000D_
);
_x000D_
.block {background-color: blue;width: 50vw;height: 50vh;margin: 1rem;}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div class="block"></div>
_x000D_
I had the same error because of character '@' in my resources/application.properties. All I did was replacing the '@' for its unicode value:
eureka.client.serviceUrl.defaultZone=http://discUser:discPassword\u0040localhost:8082/eureka/
and it worked like charm. I know the '@' is a perfectly valid character in .properties files and the file was in UTF-8 encoding and it makes me question my career till today but it's worth a shot if you delete content of your resource files to see if you can get pass this error.
You could use the ngSwitch directive:
<div ng-switch on="selection" >
<div ng-switch-when="settings">Settings Div</div>
<span ng-switch-when="home">Home Span</span>
<span ng-switch-default>default</span>
</div>
If you don't want the DOM to be loaded with empty divs, you need to create your custom directive using $http to load the (sub)templates and $compile to inject it in the DOM when a certain condition has reached.
This is just an (untested) example. It can and should be optimized:
HTML:
<conditional-template ng-model="element" template-url1="path/to/partial1" template-url2="path/to/partial2"></div>
Directive:
app.directive('conditionalTemplate', function($http, $compile) {
return {
restrict: 'E',
require: '^ngModel',
link: function(sope, element, attrs, ctrl) {
// get template with $http
// check model via ctrl.$viewValue
// compile with $compile
// replace element with element.replaceWith()
}
};
});
If you are using PHP's password_hash()
with the PASSWORD_DEFAULT
algorithm to generate the bcrypt hash (which I would assume is a large percentage of people reading this question) be sure to keep in mind that in the future password_hash()
might use a different algorithm as the default and this could therefore affect the length of the hash (but it may not necessarily be longer).
From the manual page:
Note that this constant is designed to change over time as new and stronger algorithms are added to PHP. For that reason, the length of the result from using this identifier can change over time. Therefore, it is recommended to store the result in a database column that can expand beyond 60 characters (255 characters would be a good choice).
Using bcrypt, even if you have 1 billion users (i.e. you're currently competing with facebook) to store 255 byte password hashes it would only ~255 GB of data - about the size of a smallish SSD hard drive. It is extremely unlikely that storing the password hash is going to be the bottleneck in your application. However in the off chance that storage space really is an issue for some reason, you can use PASSWORD_BCRYPT
to force password_hash()
to use bcrypt, even if that's not the default. Just be sure to stay informed about any vulnerabilities found in bcrypt and review the release notes every time a new PHP version is released. If the default algorithm is ever changed it would be good to review why and make an informed decision whether to use the new algorithm or not.
You can use sudo gem install -n /usr/local/bin cocoapods
This works for me.
In one script
#! /bin/sh
# Save git data
cp -r .git gitold
# Remove all empty git object files
find .git -type f -empty -delete -print
# Get current branch name
branchname=$(git branch --show-current)
# Get latest commit hash
commit=$(tail -2 .git/logs/refs/heads/jwt | awk '{ print $2 }' | tr -d '[:space:]')
# Set HEAD to this latest commit
git update-ref HEAD $commit
# Pull latest changes on the current branch (consifering remote is origin)
git pull origin $branchname
echo "If everything looks fine you remove the git backup running :\n\
$ rm -rf gitold\n\
Otherwise restore it with:\n\
$ rm -rf .git; mv gitold .git"
This will safely remove only if token is at end of string.
StringUtils.removeEnd(string, ".xml");
Apache StringUtils functions are null-, empty-, and no match- safe
http://realfavicongenerator.net/favicon_checker?site=http://stackoverflow.com gives you favicon analysis stating which favicons are present in what size. You can process the page information to see which is the best quality favicon, and append it's filename to the URL to get it.
The previous posts about forming POST
requests are largely correct (add the parameters to the body, not the URL). But if there is any chance of the input data containing any reserved characters (e.g. spaces, ampersand, plus sign), then you will want to handle these reserved characters. Namely, you should percent-escape the input.
//create body of the request
NSString *userid = ...
NSString *encodedUserid = [self percentEscapeString:userid];
NSString *postString = [NSString stringWithFormat:@"userid=%@", encodedUserid];
NSData *postBody = [postString dataUsingEncoding:NSUTF8StringEncoding];
//initialize a request from url
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPBody:postBody];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
//initialize a connection from request, any way you want to, e.g.
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
Where the precentEscapeString
method is defined as follows:
- (NSString *)percentEscapeString:(NSString *)string
{
NSString *result = CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
(CFStringRef)string,
(CFStringRef)@" ",
(CFStringRef)@":/?@!$&'()*+,;=",
kCFStringEncodingUTF8));
return [result stringByReplacingOccurrencesOfString:@" " withString:@"+"];
}
Note, there was a promising NSString
method, stringByAddingPercentEscapesUsingEncoding
(now deprecated), that does something very similar, but resist the temptation to use that. It handles some characters (e.g. the space character), but not some of the others (e.g. the +
or &
characters).
The contemporary equivalent is stringByAddingPercentEncodingWithAllowedCharacters
, but, again, don't be tempted to use URLQueryAllowedCharacterSet
, as that also allows +
and &
pass unescaped. Those two characters are permitted within the broader "query", but if those characters appear within a value within a query, they must escaped. Technically, you can either use URLQueryAllowedCharacterSet
to build a mutable character set and remove a few of the characters that they've included in there, or build your own character set from scratch.
For example, if you look at Alamofire's parameter encoding, they take URLQueryAllowedCharacterSet
and then remove generalDelimitersToEncode
(which includes the characters #
, [
, ]
, and @
, but because of a historical bug in some old web servers, neither ?
nor /
) and subDelimitersToEncode
(i.e. !
, $
, &
, '
, (
, )
, *
, +
, ,
, ;
, and =
). This is correct implementation (though you could debate the removal of ?
and /
), though pretty convoluted. Perhaps CFURLCreateStringByAddingPercentEscapes
is more direct/efficient.
const char* text_char = "example of mbstowcs";
size_t length = strlen(text_char );
Example of usage "mbstowcs"
std::wstring text_wchar(length, L'#');
//#pragma warning (disable : 4996)
// Or add to the preprocessor: _CRT_SECURE_NO_WARNINGS
mbstowcs(&text_wchar[0], text_char , length);
Example of usage "mbstowcs_s"
Microsoft suggest to use "mbstowcs_s" instead of "mbstowcs".
Links:
wchar_t text_wchar[30];
mbstowcs_s(&length, text_wchar, text_char, length);
Using method set and remove attribute
function radioButton(o) {_x000D_
_x000D_
var text = document.querySelector("textarea");_x000D_
_x000D_
if (o.value == "on") {_x000D_
text.removeAttribute("disabled", "");_x000D_
text.setAttribute("enabled", "");_x000D_
} else {_x000D_
text.removeAttribute("enabled", "");_x000D_
text.setAttribute("disabled", "");_x000D_
}_x000D_
_x000D_
}
_x000D_
<input type="radio" name="radioButton" value="on" onclick = "radioButton(this)" />Enable_x000D_
<input type="radio" name="radioButton" value="off" onclick = "radioButton(this)" />Disabled<hr/>_x000D_
_x000D_
<textarea disabled ></textarea>
_x000D_
The below code doesn't return the correct screen size sometimes:
MediaQuery.of(context).size
I tested on SAMSUNG SM-T580, which returns {width: 685.7, height: 1097.1}
instead of the real resolution 1920x1080
.
Please use:
import 'dart:ui';
window.physicalSize;
Since the OP was asking for using a custom compare function (and this is what led me to this question as well), I want to give a solid answer here:
Generally, you want to use the built-in sorted()
function which takes a custom comparator as its parameter. We need to pay attention to the fact that in Python 3 the parameter name and semantics have changed.
When providing a custom comparator, it should generally return an integer/float value that follows the following pattern (as with most other programming languages and frameworks):
< 0
) when the left item should be sorted before the right item> 0
) when the left item should be sorted after the right item0
when both the left and the right item have the same weight and should be ordered "equally" without precedenceIn the particular case of the OP's question, the following custom compare function can be used:
def compare(item1, item2):
return fitness(item1) - fitness(item2)
Using the minus operation is a nifty trick because it yields to positive values when the weight of left item1
is bigger than the weight of the right item2
. Hence item1
will be sorted after item2
.
If you want to reverse the sort order, simply reverse the subtraction: return fitness(item2) - fitness(item1)
sorted(mylist, cmp=compare)
or:
sorted(mylist, cmp=lambda item1, item2: fitness(item1) - fitness(item2))
from functools import cmp_to_key
sorted(mylist, key=cmp_to_key(compare))
or:
from functools import cmp_to_key
sorted(mylist, key=cmp_to_key(lambda item1, item2: fitness(item1) - fitness(item2)))
Use an ordered broadcast. See http://android-developers.blogspot.nl/2011/01/processing-ordered-broadcasts.html
In your activity, register a receiver in onStart, unregister in onStop. Now when for example a service needs to handle something that the activity might be able to do better, send an ordered broadcast from the service (with a default handler in the service itself). You can now respond in the activity when it is running. The service can check the result data to see if the broadcast was handled, and if not take appropriate action.
The other answers and comments covered table renaming, file renaming, and grepping through your code.
I'd like to add a few more caveats:
Let's use a real-world example I faced today: renaming a model from 'Merchant' to 'Business.'
I suggest you add separate overloaded method and add them to your projects Utility/Utilities class.
To check for Collection be empty or null
public static boolean isEmpty(Collection obj) {
return obj == null || obj.isEmpty();
}
or use Apache Commons CollectionUtils.isEmpty()
To check if Map is empty or null
public static boolean isEmpty(Map<?, ?> value) {
return value == null || value.isEmpty();
}
or use Apache Commons MapUtils.isEmpty()
To check for String empty or null
public static boolean isEmpty(String string) {
return string == null || string.trim().isEmpty();
}
or use Apache Commons StringUtils.isBlank()
To check an object is null is easy but to verify if it's empty is tricky as object can have many private or inherited variables and nested objects which should all be empty. For that All need to be verified or some isEmpty() method be in all objects which would verify the objects emptiness.
This is my personal understanding about the topic.
For a project, we can do the version control by different repositories. And for a repository, it can manage a whole project or part of projects.
Regarding on your project (several prototype applications which are independent of each them). You can manage the project by one repository or by several repositories, the difference:
Manage by one repository. If one of the applications is changed, the whole project (all the applications) will be committed to a new version.
Manage by several repositories. If one application is changed, it will only affect the repository which manages the application. Version for other repositories was not changed.
Accordily http://javascript.about.com/library/blweekyear.htm
Date.prototype.getWeek = function() {
var onejan = new Date(this.getFullYear(),0,1);
var millisecsInDay = 86400000;
return Math.ceil((((this - onejan) /millisecsInDay) + onejan.getDay()+1)/7);
};
The char already has an IsDigit(char c) which does this:
public static bool IsDigit(char c)
{
if (!char.IsLatin1(c))
return CharUnicodeInfo.GetUnicodeCategory(c) == UnicodeCategory.DecimalDigitNumber;
if ((int) c >= 48)
return (int) c <= 57;
else
return false;
}
You can simply do this:
var theString = "839278";
bool digitsOnly = theString.All(char.IsDigit);
If you're doing the check inside the View, put the value in the ViewBag
.
In your controller:
ViewBag["parameterName"] = Request["parameterName"];
It's worth noting that the Request
and Response
properties are exposed by the Controller
class. They have the same semantics as HttpRequest
and HttpResponse
.
Use the XML Tools plugin for Notepad++ and then you can Auto-Indent the code with Ctrl+Alt+Shift+B .For the more point-and-click inclined, you could also go to Plugins --> XML Tools --> Pretty Print.
I was getting this error in PyroCMS.
You can improve the error message in the Loader.php file that is in the code of the library.
Open the Loader.php file and find any calls to show_error
. I replaced mine with the following:
show_error(sprintf("Unable to load the requested file: \"%s\" with instance title of \"%s\"", $_ci_file, $_ci_data['_ci_vars']['options']['instance_title']));
I was then able to see which file was causing the issues for me.
len(each) == max(len(x) for x in myList)
or just each == max(myList, key=len)
add the following to the "floating" view
position: 'absolute'
you may also need to add a top and left value for positioning
see this example: https://rnplay.org/apps/OjzcxQ/edit
Of course you can, but why do this? You have to include a <script></script>
pair of tags that link to the jQuery web page, i.e.:
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
. Then you will load the whole jQuery object just to use one single function, and because jQuery is a JavaScript library which will take time for the computer to upload, it will execute slower than just JavaScript.
THIS IS A QUICK FIX; 1. GO TO C:\Users(YOUR USER NAME)\AppData\Local\Android\sdk\build-tools 2. DELETE THE PREEXISTING FOLDER OF THE VERSION THAT HAS NO LICENSE. 3. GO TO ANDROID STUDIO AND MANUALLY INSTALL THE TOOL AGAIN(this will give you an opportunity to accept the license ) ........ (problem solved)
Javascript can be executed against the current page just by putting it in the URL address, e.g.
javascript:;alert(window.document.body.innerHTML);
javascript:;alert(window.document.body.childNodes[0].innerHTML);
As commented by David Thomas, descendants of those child elements will (likely) inherit most of the styles assigned to those child elements.
You need to wrap your .myTestClass
inside an element and apply the styles to descendants by adding .wrapper *
descendant selector. Then, add .myTestClass > *
child selector to apply the style to the elements children, not its grand children. For example like this:
JSFiddle - DEMO
.wrapper * {_x000D_
color: blue;_x000D_
margin: 0 100px; /* Only for demo */_x000D_
}_x000D_
.myTestClass > * {_x000D_
color:red;_x000D_
margin: 0 20px;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
<div class="myTestClass">Text 0_x000D_
<div>Text 1</div>_x000D_
<span>Text 1</span>_x000D_
<div>Text 1_x000D_
<p>Text 2</p>_x000D_
<div>Text 2</div>_x000D_
</div>_x000D_
<p>Text 1</p>_x000D_
</div>_x000D_
<div>Text 0</div>_x000D_
</div>
_x000D_
If using Postgres or SQLite, you can use the Filter clause to improve readability:
SELECT
COUNT(1) FILTER (WHERE POSITION = 'Manager') AS ManagerCount,
COUNT(1) FILTER (WHERE POSITION = 'Other') AS OtherCount
FROM ...
BigQuery also has Countif
- see the support across different SQL dialects for these features here:
https://modern-sql.com/feature/filter
I have tried but above not working after research found below the solution.
SELECT * FROM my_table where DATE(start_date) > '2011-01-01';
In a nutshell, three easy rules to remember PECS:
<? extends T>
wildcard if you need to retrieve object of
type T
from a collection.<? super T>
wildcard if you need to put objects of type T
in
a collection.If your data is in wide format matplot
is made for this and often forgotten about:
dat <- matrix(runif(40,1,20),ncol=4) # make data
matplot(dat, type = c("b"),pch=1,col = 1:4) #plot
legend("topleft", legend = 1:4, col=1:4, pch=1) # optional legend
There is also the added bonus for those unfamiliar with things like ggplot
that most of the plotting paramters such as pch
etc. are the same using matplot()
as plot()
.
The short answer is no (or should be no). EDIT: yeah, it's possible (see assylias' answer below), but keep reading. EDIT2: but see Stuart Marks' answer for yet another reason why you still shouldn't do it!
The longer answer:
The purpose of these constructs in Java 8 is to introduce some concepts of Functional Programming to the language; in Functional Programming, data structures are not typically modified, instead, new ones are created out of old ones by means of transformations such as map, filter, fold/reduce and many others.
If you must modify the old list, simply collect the mapped items into a fresh list:
final List<Integer> newList = list.stream()
.filter(n -> n % 2 == 0)
.collect(Collectors.toList());
and then do list.addAll(newList)
— again: if you really must.
(or construct a new list concatenating the old one and the new one, and assign it back to the list
variable—this is a little bit more in the spirit of FP than addAll
)
As to the API: even though the API allows it (again, see assylias' answer) you should try to avoid doing that regardless, at least in general. It's best not to fight the paradigm (FP) and try to learn it rather than fight it (even though Java generally isn't a FP language), and only resort to "dirtier" tactics if absolutely needed.
The really long answer: (i.e. if you include the effort of actually finding and reading an FP intro/book as suggested)
To find out why modifying existing lists is in general a bad idea and leads to less maintainable code—unless you're modifying a local variable and your algorithm is short and/or trivial, which is out of the scope of the question of code maintainability—find a good introduction to Functional Programming (there are hundreds) and start reading. A "preview" explanation would be something like: it's more mathematically sound and easier to reason about to not modify data (in most parts of your program) and leads to higher level and less technical (as well as more human friendly, once your brain transitions away from the old-style imperative thinking) definitions of program logic.
I could find this solution and is working fine:
cd /Applications/Python\ 3.7/
./Install\ Certificates.command
I used:
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
to disable the screen timeout and
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
to re-enable it.
I've spent the entire day testing these solutions and the only thing that worked for me is the above approaches for getting the image and manually calling the GC, which I know is not supposed to be necessary, but it is the only thing that worked when I put my app under heavy load testing switching between activities. My app has a list of thumbnail images in a listview in (lets say activity A) and when you click on one of those images it takes you to another activity (lets say activity B) that shows a main image for that item. When I would switch back and forth between the two activities, I would eventually get the OOM error and the app would force close.
When I would get half way down the listview it would crash.
Now when I implement the following in activity B, I can go through the entire listview with no issue and keep going and going and going...and its plenty fast.
@Override
public void onDestroy()
{
Cleanup();
super.onDestroy();
}
private void Cleanup()
{
bitmap.recycle();
System.gc();
Runtime.getRuntime().gc();
}
Use following statement for error
be careful about your data take backup if data have in table.
ALTER TABLE your_table_name CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci;
dplyr package could be nice alternative to this problem:
library(dplyr)
df %>%
group_by(group) %>%
summarize(mean = mean(dt),
sum = sum(dt))
To get 1st quadrant and 3rd quadrant
df %>%
group_by(group) %>%
summarize(q1 = quantile(dt, 0.25),
q3 = quantile(dt, 0.75))
I had the same issue, I resolved it using some javascript.
<script type="text/javascript">
var theHeight = $("#PrimaryContent").height() + 100;
$('#SecondaryContent').height(theHeight);
</script>
_counter = 0 def foo(): global _counter _counter += 1 print 'counter is', _counter
Python customarily uses underscores to indicate private variables. The only reason in C to declare the static variable inside the function is to hide it outside the function, which is not really idiomatic Python.
I use
SAVEIFS=$IFS
IFS=$(echo -en "\n\b")
for f in $( find "$1" -type d ! -path "$1" )
do
echo $f
done
IFS=$SAVEIFS
Wouldn't that be enough?
Idea taken from http://www.cyberciti.biz/tips/handling-filenames-with-spaces-in-bash.html
Please make sure that all properties are both the getter and setter. In case, any property is getter only, it will cause the reverting the List to original data as the JSON string is typed.
Please refer to the following code snippet for the same: Model:
public class Person
{
public int ID { get; set; }
// following 2 lines are cause of error
//public string Name { get { return string.Format("{0} {1}", First, Last); } }
//public string Country { get { return Countries[CountryID]; } }
public int CountryID { get; set; }
public bool Active { get; set; }
public string First { get; set; }
public string Last { get; set; }
public DateTime Hired { get; set; }
}
public class ModelObj
{
public string Str { get; set; }
public List<Person> Persons { get; set; }
}
Controller:
[HttpPost]
public ActionResult Index(FormCollection collection)
{
var data = new ModelObj();
data.Str = (string)collection.GetValue("Str").ConvertTo(typeof(string));
var personsString = (string)collection.GetValue("Persons").ConvertTo(typeof(string));
using (var textReader = new StringReader(personsString))
{
using (var reader = new JsonTextReader(textReader))
{
data.Persons = new JsonSerializer().Deserialize(reader, typeof(List<Person>)) as List<Person>;
}
}
return View(data);
}
I don't like that much solutions based on multiplying text-shadows, it's not really flexible, it may work for a 2 pixels stroke where directions to add are 8, but with just 3 pixels stroke directions became 16, and so on... Not really confortable to manage.
The right tool exists, it's SVG <text>
The browsers' support problem worth nothing in this case, 'cause the usage of text-shadow has its own support problem too,
filter: progid:DXImageTransform
can be used or IE < 10 but often doesn't work as expected.
To me the best solution remains SVG with a fallback in not-stroked text for older browser:
This kind of approuch works on pratically all versions of Chrome and Firefox, Safari since version 3.04, Opera 8, IE 9
Compared to text-shadow
whose supports are:
Chrome 4.0,
FF 3.5,
IE 10,
Safari 4.0,
Opera 9, it results even more compatible.
.stroke {_x000D_
margin: 0;_x000D_
font-family: arial;_x000D_
font-size:70px;_x000D_
font-weight: bold;_x000D_
}_x000D_
_x000D_
svg {_x000D_
display: block;_x000D_
}_x000D_
_x000D_
text {_x000D_
fill: black;_x000D_
stroke: red;_x000D_
stroke-width: 3;_x000D_
}
_x000D_
<p class="stroke">_x000D_
<svg xmlns="http://www.w3.org/2000/svg" width="700" height="72" viewBox="0 0 700 72">_x000D_
<text x="0" y="70">Stroked text</text>_x000D_
</svg>_x000D_
</p>
_x000D_
I'm using Android Studio Beta version 0.8.1 and I have the same problem. I now I sold my problem by changing the AVD (I'm using Genymotion) to API 19. and here is my build.gradle file
apply plugin: 'com.android.application'
android {
compileSdkVersion 19
buildToolsVersion "19.1.0"
defaultConfig {
applicationId "com.example.daroath.actionbar"
minSdkVersion 14
targetSdkVersion 19
versionCode 1
versionName "1.0"
}
buildTypes {
release {
runProguard false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
}
Hope this help!
I have gone through the same problem when I was using
myApp.controller('mainController', ['$scope', function($scope,) {
//$http was not working in this
}]);
I have changed the above code to given below. Remember to include $http(2 times) as given below.
myApp.controller('mainController', ['$scope','$http', function($scope,$http) {
//$http is working in this
}]);
and It has worked well.
Hi I hope this will help:
private PowerManager mPowerManager;
private PowerManager.WakeLock mWakeLock;
public void turnOnScreen(){
// turn on screen
Log.v("ProximityActivity", "ON!");
mWakeLock = mPowerManager.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "tag");
mWakeLock.acquire();
}
@TargetApi(21) //Suppress lint error for PROXIMITY_SCREEN_OFF_WAKE_LOCK
public void turnOffScreen(){
// turn off screen
Log.v("ProximityActivity", "OFF!");
mWakeLock = mPowerManager.newWakeLock(PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK, "tag");
mWakeLock.acquire();
}
From R..'s answer:
However, this is probably a very bad idea, because the resulting type is an array type, but users of it won't see that it's an array type. If used as a function argument, it will be passed by reference, not by value, and the sizeof for it will then be wrong.
Users who don't see that it's an array will most likely write something like this (which fails):
#include <stdio.h>
typedef int twoInts[2];
void print(twoInts *twoIntsPtr);
void intermediate (twoInts twoIntsAppearsByValue);
int main () {
twoInts a;
a[0] = 0;
a[1] = 1;
print(&a);
intermediate(a);
return 0;
}
void intermediate(twoInts b) {
print(&b);
}
void print(twoInts *c){
printf("%d\n%d\n", (*c)[0], (*c)[1]);
}
It will compile with the following warnings:
In function ‘intermediate’:
warning: passing argument 1 of ‘print’ from incompatible pointer type [enabled by default]
print(&b);
^
note: expected ‘int (*)[2]’ but argument is of type ‘int **’
void print(twoInts *twoIntsPtr);
^
And produces the following output:
0
1
-453308976
32767
This can be achieved purely with JavaScript.
I see the answer I wanted to write has been answered by lynx in comments to the question.
But I'm going to write answer anyway because just like me, people sometimes forget to read the comments.
So, if you just want to get an element's distance (in Pixels) from the top of your screen window, here is what you need to do:
// Fetch the element
var el = document.getElementById("someElement");
// Use the 'top' property of 'getBoundingClientRect()' to get the distance from top
var distanceFromTop = el.getBoundingClientRect().top;
Thats it!
Hope this helps someone :)
if my_list is the list that you want to store your objects in it and my_object is your object wanted to be stored, use this structure:
my_list.append(my_object)
One note for people who might not have the set password for sysdba or sys and regularly use a third party client. Here's some info about logging into command line sqlplus without a password that helped me. I am using fedora 21 by the way.
locate sqlplus
In my case, sqlplus is located here:
/u01/app/oracle/product/11.2.0/xe/config/scripts/sqlplus.sh
Now run
cd /u01/app/oracle/product/11.2.0/xe/config/scripts
./sqlplus.sh / as sysdba
Now you need to connect to database with your old credentials. You can find Oracle provided template in your output:
Use "connect username/password@XE" to connect to the database.
In my case I have user "oracle" with password "oracle" so my input looks like
connect oracle/oracle@XE
Done. Now type your new password twice. Then if you don't want your password to expire anymore you could run
ALTER PROFILE DEFAULT LIMIT PASSWORD_LIFE_TIME UNLIMITED;
It is very simple.
don't make a csv file by "create new excel" or save as ".csv" from window.
simply import csv module, write a dummy csv file, and then paste your data in that.
csv made by python csv module itself will no longer show you encoding or blank line error.
This code:
from scipy.stats import linregress
linregress(x,y) #x and y are arrays or lists.
gives out a list with the following:
slope : float
slope of the regression line
intercept : float
intercept of the regression line
r-value : float
correlation coefficient
p-value : float
two-sided p-value for a hypothesis test whose null hypothesis is that the slope is zero
stderr : float
Standard error of the estimate
the easiest way in python 3.x
text = "hi , I'm text"
text.encode('utf-8')
I prefer using pip in case you are using virtualenv:
apt install libpython2.7 libpython2.7-dev
pip install psycopg2
The CSS standard enables some advanced formatting. There is a @page directive in CSS that enables some formatting that applies only to paged media (like paper). See http://www.w3.org/TR/1998/REC-CSS2-19980512/page.html.
<html xmlns="http://www.w3.org/1999/xhtml">_x000D_
<head>_x000D_
<title>Print Test</title>_x000D_
<style type="text/css" media="print">_x000D_
@page _x000D_
{_x000D_
size: auto; /* auto is the current printer page size */_x000D_
margin: 0mm; /* this affects the margin in the printer settings */_x000D_
}_x000D_
_x000D_
body _x000D_
{_x000D_
background-color:#FFFFFF; _x000D_
border: solid 1px black ;_x000D_
margin: 0px; /* the margin on the content before printing */_x000D_
}_x000D_
</style>_x000D_
</head>_x000D_
<body>_x000D_
<div>Top line</div>_x000D_
<div>Line 2</div>_x000D_
</body>_x000D_
</html>
_x000D_
and for firefox use it
In Firefox, https://bug743252.bugzilla.mozilla.org/attachment.cgi?id=714383 (view page source :: tag HTML).
In your code, replace <html>
with <html moznomarginboxes mozdisallowselectionprint>.
In my case i have to concatenate all the account number of a person who's mobile number is unique. So i have used the following query to achieve that.
SELECT GROUP_CONCAT(AccountsNo) as Accounts FROM `tblaccounts` GROUP BY MobileNumber
Query Result is below:
Accounts
93348001,97530801,93348001,97530801
89663501
62630701
6227895144840002
60070021
60070020
60070019
60070018
60070017
60070016
60070015
Arrays are not changeable after initialization. You have to give it a value, and that value is what that array length stays. You can create multiple arrays to contain certain parts of player information like their hand and such, and then create an arrayList to sort of shepherd those arrays.
Another point of contention I see, and I may be wrong about this, is the fact that your private Player[] InitializePlayers() is static where the class is now non-static. So:
private Player[] InitializePlayers(int playerCount)
{
...
}
My last point would be that you should probably have playerCount declared outside of the method that is going to change it so that the value that is set to it becomes the new value as well and it is not just tossed away at the end of the method's "scope."
Hope this helps
with open('target.txt','w') as out:
line1 = raw_input("line 1: ")
line2 = raw_input("line 2: ")
line3 = raw_input("line 3: ")
print("I'm going to write these to the file.")
out.write('{}\n{}\n{}\n'.format(line1,line2,line3))
Here is how I made monthly page in similar manner as Fernando:
I made five weeks on every page and on fifth week I made function
=IF(C12=5,DATE(YEAR(B48),MONTH(B48),DAY(B48)+7),"")
that empties fifth week if this month has only four weeks. C12 holds the number of weeks.
Insert following function on the first day field starting sheet #2:
=INDIRECT(CONCATENATE("'Month (",ThisMonth-1,")'!B15"))+INDIRECT(CONCATENATE("'Month (",ThisMonth-1,")'!C12"))*7
So in another word, if you fill four or five weeks on the previous sheet, this calculates date correctly and continues from correct date.